Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,16 @@ on first message); `GET /project/:id/threads` returns every thread keyed by id
the server fills author/ts. Read comments back by merging a doc's `ranges.comments` (anchors:
`op.{p,c,t}`) with the threads API (messages). Note the ranges `c`/change text is the realtime
**byte-view** (decode with `ot.decodeWireText`), but REST message `content` is already real
UTF-8 (do not decode). The resolve/reopen/delete thread routes return 404 on overleaf.com, so
Claudeleaf ships only create + list. Exposed as `addComment`/`listComments` (SDK) and
`overleaf_add_comment`/`overleaf_list_comments` (MCP).
UTF-8 (do not decode). **Resolving/reopening** is HTTP and doc-scoped (verified live):
`POST /project/:id/doc/:docId/thread/:threadId/resolve` or `.../reopen` (cookie + CSRF, empty
body) → 204, and `GET /threads` then reports `resolved: true/false`. The older project-level
`/project/:id/thread/:threadId/resolve` 404s on overleaf.com. `resolveComments`/`reopenComments`
read the doc's comments first and change nothing if any id is not anchored there; threads
already in the wanted state are skipped; one request per thread, so a failure part-way names
the threads already changed. Deleting a thread is not implemented. Exposed as
`addComment`/`listComments`/`resolveComments`/`reopenComments` (SDK),
`overleaf_add_comment`/`overleaf_list_comments`/`overleaf_resolve_comments`/
`overleaf_reopen_comments` (MCP) and `comment`/`comments`/`resolve`/`reopen` (CLI).

**Reading tracked changes and the overwrite guard.** `ranges.changes` entries are
`{id, op:{p,i}|{p,d}, metadata:{user_id,ts}}`: a tracked insertion is snapshot text at
Expand Down Expand Up @@ -284,7 +291,7 @@ state; instead:
— an accepted suggestion can no longer be rejected — and `upload_file`, which replaces a
same-named file), `false` for the purely additive ones (`insert_text`,
`append_text`, `create_document`, `add_comment` — which only annotates, leaving the text
unchanged — and `rename_document`, which changes a name, losing no content). The seven write
unchanged — `resolve_comments`/`reopen_comments` (reversible, also `idempotentHint: true`) and `rename_document`, which changes a name, losing no content). The seven write
tools that change document text also take an optional `trackChanges` to submit as a
review-mode suggestion.

Expand All @@ -308,7 +315,7 @@ No configuration is required. Overrides (mainly for self-hosted / tuning):
`project(idOrName)` → `ProjectSession`. All document methods take a `project` (id or name) as
the first argument and are `async`: `projectInfo`, `listDocuments`, `readDocument`, `getLines`,
`documentVersion`, `search`, `insertAt`, `insert`, `append`, `deleteRange`, `replaceRange`,
`replaceText`, `setText`, `deleteLines`, `setCursor`, `getConnectedUsers`, `listTrackedChanges`, `acceptTrackedChanges`, `createDocument`,
`replaceText`, `setText`, `deleteLines`, `setCursor`, `getConnectedUsers`, `listTrackedChanges`, `acceptTrackedChanges`, `resolveComments`, `reopenComments`, `createDocument`,
`uploadFile`, `createFolder`, `deleteDocument`, `renameDocument`, `resync`, `compile`. `ProjectSession`
exposes the same methods without the leading `project` argument. Every edit method takes an
optional trailing `EditOptions` (`{trackChanges?}`) — set `trackChanges` to submit the edit as
Expand Down
14 changes: 8 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Bring Claude (and any agent) into Overleaf. Claudeleaf is a reliable TypeScript
- **All your projects, one instance.** List every project you can access and edit any of them by id or name — no project configured up front.
- **Full document control** — list documents, read text, insert at a position or line/column, replace ranges or literal text, delete ranges or lines, replace a whole document, create/delete/rename files, and **upload images** (e.g. a local W&B plot PNG) for `\includegraphics`: `claudeleaf upload <project> plot.png --folder figures` or the `overleaf_upload_file` MCP tool.
- **Review mode (track changes).** Submit any edit as a tracked change (a suggestion) with `trackChanges` instead of a direct edit, so a human accepts or rejects it in Overleaf. Requires track changes on the project (a premium feature).
- **Comments.** Anchor a comment to a span of text (like selecting text and commenting in the editor) and list a document's comments with their threads.
- **Comments.** Anchor a comment to a span of text (like selecting text and commenting in the editor), list a document's comments with their threads, and resolve or reopen threads by id (`claudeleaf resolve|reopen <project> <path> <threadId>...`; MCP `overleaf_resolve_comments` / `overleaf_reopen_comments`).
- **Collaborators' suggestions are protected.** List a document's pending tracked changes with their authors (`claudeleaf changes <project> <path>`, `overleaf_list_tracked_changes`). Any edit that would change text inside a co-author's pending suggestion is refused before it is sent, instead of silently rewriting it (which Overleaf reports to the author as a rejected suggestion). Your own suggestions stay editable: editing inside one extends or shrinks it, as in the Overleaf editor. Override with `overwriteTrackedChanges` (SDK, MCP) / `--overwrite-tracked-changes` (CLI); the MCP tools tell an agent to use it only when the user explicitly asked to override a co-author's suggestion.
- **Accept suggestions.** Accept pending tracked changes by id, like the review panel's Accept (`claudeleaf accept <project> <path> <id>...`, `--all`, `--before 2026-10-15`; MCP `overleaf_accept_tracked_changes`). `changes` without a path lists the whole project.
- **Compile & error logs** — trigger a LaTeX recompile and get back the status plus the parsed errors and warnings (with file and line), or the full raw log.
Expand Down Expand Up @@ -63,7 +63,8 @@ npx claudeleaf replace "My Paper" main.tex "foo" "bar" --track-changes
# comment on the [start, end) character span (use `search` to find offsets)
npx claudeleaf search "My Paper" main.tex "Introduction" # -> offset 772
npx claudeleaf comment "My Paper" main.tex 772 784 "Should this be shorter?"
npx claudeleaf comments "My Paper" main.tex # list comments + threads
npx claudeleaf comments "My Paper" main.tex # list comments + threads (with thread ids)
npx claudeleaf resolve "My Paper" main.tex <threadId> # resolve a thread (reopen undoes it)
```

### Use it with Claude Code (MCP)
Expand All @@ -80,7 +81,8 @@ The tools reuse the session from `claudeleaf login` (they won't pop a browser).
It can also work in **review mode** rather than editing directly — the seven tools that write
document text (`insert_text`, `append_text`, `replace_text`, `replace_range`, `delete_range`,
`delete_lines`, `set_document`) take `trackChanges: true` to leave a tracked suggestion — and
comment on the text with `overleaf_add_comment` / `overleaf_list_comments`. For example:
comment on the text with `overleaf_add_comment` / `overleaf_list_comments` (and close threads with
`overleaf_resolve_comments` / `overleaf_reopen_comments`). For example:

> "Read main.tex, then suggest a tighter abstract as tracked changes and leave a comment on
> the title explaining why."
Expand All @@ -105,10 +107,11 @@ await client.replaceText("My Paper", "main.tex", "Your Paper", "Our Paper");
await client.replaceText("My Paper", "main.tex", "utilise", "use", 0, { trackChanges: true });

// comment on a span of text, then read the document's comments back
await client.addComment("My Paper", "main.tex", 772, 784, "Should this be shorter?");
const comment = await client.addComment("My Paper", "main.tex", 772, 784, "Should this be shorter?");
for (const c of await client.listComments("My Paper", "main.tex")) {
console.log(c.line, c.text, c.messages.map((m) => m.content));
}
await client.resolveComments("My Paper", "main.tex", [comment.threadId]); // reopenComments undoes it

const compile = await client.compile("My Paper");
console.log(compile.status, compile.errors); // errors carry { message, file, line }
Expand All @@ -130,6 +133,5 @@ npm run build # compile to dist/
make the edit a suggestion in the first place with `--track-changes` / `trackChanges`.
- Track changes is an Overleaf **premium** feature. On a project without it the edit still
applies, just as a normal edit rather than a suggestion. Comments work on any project.
- Comment threads can be created and listed, but not resolved or deleted — Overleaf does not
expose those routes.
- Comment threads can be created, listed, resolved and reopened, but not deleted.
- The cached session is a credential; it lives under `~/.claudeleaf` with restrictive permissions.
21 changes: 19 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,9 @@ Usage: claudeleaf <command> [args]
search <project> <path> <query> find text
comment <project> <path> <start> <end> [message|-]
comment on the [start,end) span
comments <project> <path> list a document's comments
comments <project> <path> list a document's comments (with thread ids)
resolve <project> <path> <threadId>... resolve comment threads
reopen <project> <path> <threadId>... reopen resolved comment threads
changes <project> [path] list pending tracked changes (whole project if no path)
accept <project> <path> <id>... | --all [--before ISO-DATE]
accept tracked changes (by id, or all / all before a date)
Expand Down Expand Up @@ -234,11 +236,26 @@ async function run(argv: string[]): Promise<number> {
}
for (const c of comments) {
const state = c.resolved ? " [resolved]" : "";
console.log(`${c.line}:${c.column} ${JSON.stringify(c.text)}${state}`);
console.log(`${c.threadId} ${c.line}:${c.column} ${JSON.stringify(c.text)}${state}`);
for (const m of c.messages) console.log(` ${m.author ?? "?"}: ${m.content}`);
}
return 0;
}
case "resolve":
case "reopen": {
const path = positionals[1];
const ids = positionals.slice(2);
if (!path || ids.length === 0) {
console.error(`error: '${command}' needs a document path and at least one thread id`);
return 1;
}
const done =
command === "resolve"
? await client.resolveComments(project, path, ids)
: await client.reopenComments(project, path, ids);
console.log(`${command === "resolve" ? "Resolved" : "Reopened"} ${done.length} comment thread(s) in ${path}.`);
return 0;
}
case "changes": {
const changes = await client.listTrackedChanges(project, positionals[1]);
if (changes.length === 0) {
Expand Down
8 changes: 8 additions & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,14 @@ export class OverleafClient {
return (await this.project(project)).listComments(path);
}

async resolveComments(project: string, path: string, threadIds: string[]): Promise<Comment[]> {
return (await this.project(project)).resolveComments(path, threadIds);
}

async reopenComments(project: string, path: string, threadIds: string[]): Promise<Comment[]> {
return (await this.project(project)).reopenComments(path, threadIds);
}

// -- tracked changes --------------------------------------------------
/** A document's pending tracked changes, or the whole project's when `path` is omitted. */
async listTrackedChanges(project: string, path?: string): Promise<TrackedChange[]> {
Expand Down
35 changes: 35 additions & 0 deletions src/mcpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,41 @@ export function createServer(): McpServer {
async ({ project, path }) => result(await getClient().listComments(project, path)),
);

server.registerTool(
"overleaf_resolve_comments",
{
description:
"Resolve comment threads in a document by thread id, like Resolve in Overleaf's review " +
"panel: the comment leaves the open list but keeps its messages and can be reopened with " +
"overleaf_reopen_comments. Only resolve threads the user asked you to close — resolving a " +
"co-author's open question hides it from them. Take thread ids from " +
"overleaf_list_comments; if any id is not a comment in the document, nothing is changed. " +
"Threads already resolved are left as they are. Returns the affected comments.",
inputSchema: { project: z.string(), path: z.string(), threadIds: z.array(z.string()).min(1) },
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
},
async ({ project, path, threadIds }) => {
const done = await getClient().resolveComments(project, path, threadIds);
return result({ resolved: done.length, comments: done });
},
);

server.registerTool(
"overleaf_reopen_comments",
{
description:
"Reopen resolved comment threads in a document by thread id, undoing " +
"overleaf_resolve_comments. If any id is not a comment in the document, nothing is " +
"changed. Returns the affected comments.",
inputSchema: { project: z.string(), path: z.string(), threadIds: z.array(z.string()).min(1) },
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
},
async ({ project, path, threadIds }) => {
const done = await getClient().reopenComments(project, path, threadIds);
return result({ reopened: done.length, comments: done });
},
);

server.registerTool(
"overleaf_list_tracked_changes",
{
Expand Down
10 changes: 10 additions & 0 deletions src/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,16 @@ export class RestClient {
await this.request("POST", `/project/${this.projectId}/thread/${threadId}/messages`, { content });
}

/**
* Resolve or reopen a comment thread, as the review panel does. The routes are scoped to the
* doc that anchors the comment; the older project-level `/thread/:id/resolve` 404s on
* overleaf.com.
*/
async setThreadResolved(docId: string, threadId: string, resolved: boolean): Promise<void> {
const action = resolved ? "resolve" : "reopen";
await this.request("POST", `/project/${this.projectId}/doc/${docId}/thread/${threadId}/${action}`, {});
}

/**
* Accept pending tracked changes of a doc (what the review panel's Accept does). The text is
* unchanged (an accepted insertion stays, an accepted deletion is already gone); only the
Expand Down
44 changes: 44 additions & 0 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,50 @@ export class ProjectSession {
});
}

/**
* Resolve comment threads of a document by thread id (from {@link listComments}), as the
* review panel's Resolve does: the comment leaves the open list but keeps its messages and
* can be reopened. Ids are checked against the document's anchored comments first; if any is
* not anchored in this document, nothing is changed. Threads already resolved are left alone.
* Returns the affected comments in their new state.
*/
resolveComments(path: string, threadIds: string[]): Promise<Comment[]> {
return this.setCommentsResolved(path, threadIds, true);
}

/** Reopen resolved comment threads of a document; the counterpart of {@link resolveComments}. */
reopenComments(path: string, threadIds: string[]): Promise<Comment[]> {
return this.setCommentsResolved(path, threadIds, false);
}

private async setCommentsResolved(path: string, threadIds: string[], resolved: boolean): Promise<Comment[]> {
const wanted = [...new Set(threadIds)];
if (wanted.length === 0) return [];
const verb = resolved ? "resolved" : "reopened";
const comments = new Map((await this.listComments(path)).map((c) => [c.threadId, c]));
const missing = wanted.filter((id) => !comments.has(id));
if (missing.length > 0) {
throw new ClaudeleafError(
`not ${verb}: ${missing.length} thread id(s) are not comments in ${path} ` +
`(${missing.slice(0, 5).join(", ")}${missing.length > 5 ? ", ..." : ""}); nothing was ${verb}`,
);
}
const doc = await this.openDoc(path);
const done: string[] = [];
for (const id of wanted) {
if (comments.get(id)!.resolved === resolved) continue; // already in that state
try {
await this.rest.setThreadResolved(doc.id, id, resolved);
} catch (e) {
// One request per thread, so a failure part-way leaves the earlier ones changed: say which.
const prefix = done.length ? `${verb} ${done.join(", ")} before failing; ` : "";
throw new ClaudeleafError(`${prefix}thread ${id} was not ${verb}: ${(e as Error).message}`);
}
done.push(id);
}
return wanted.map((id) => ({ ...comments.get(id)!, resolved }));
}

// -- tracked changes --------------------------------------------------
/**
* List a document's pending tracked changes (review-mode suggestions), in document order,
Expand Down
70 changes: 70 additions & 0 deletions test/clientOps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,76 @@ describe("comments", () => {
},
]);
});

describe("resolving and reopening", () => {
function withThreads(state: Record<string, boolean>) {
const { session, fake } = makeSession("hello world again");
fake.ranges = {
comments: [
{ id: "t1", op: { p: 0, c: "hello", t: "t1" } },
{ id: "t2", op: { p: 6, c: "world", t: "t2" } },
],
};
const sent: { docId: string; threadId: string; resolved: boolean }[] = [];
let failOn: string | null = null;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(session as any).rest = {
getThreads: async () =>
Object.fromEntries(Object.entries(state).map(([id, resolved]) => [id, { messages: [], resolved }])),
setThreadResolved: async (docId: string, threadId: string, resolved: boolean) => {
if (threadId === failOn) throw new Error("500 boom");
sent.push({ docId, threadId, resolved });
state[threadId] = resolved;
},
};
return { session, fake, sent, failOn: (id: string) => void (failOn = id) };
}

it("resolves open threads by id and returns them resolved", async () => {
const { session, fake, sent } = withThreads({ t1: false, t2: false });
const done = await session.resolveComments("main.tex", ["t1", "t1"]);
expect(sent).toEqual([{ docId: DOC_ID, threadId: "t1", resolved: true }]);
expect(done.map((c) => [c.threadId, c.text, c.resolved])).toEqual([["t1", "hello", true]]);
expect(fake.applies).toBe(0); // no op on the document
});

it("reopens resolved threads", async () => {
const { session, sent } = withThreads({ t1: true, t2: false });
const done = await session.reopenComments("main.tex", ["t1"]);
expect(sent).toEqual([{ docId: DOC_ID, threadId: "t1", resolved: false }]);
expect(done[0].resolved).toBe(false);
});

it("leaves threads already in the wanted state alone", async () => {
const { session, sent } = withThreads({ t1: true, t2: false });
const done = await session.resolveComments("main.tex", ["t1", "t2"]);
expect(sent.map((s) => s.threadId)).toEqual(["t2"]);
expect(done.map((c) => c.resolved)).toEqual([true, true]);
});

it("changes nothing if any id is not a comment in the document", async () => {
const { session, sent } = withThreads({ t1: false, t2: false });
await expect(session.resolveComments("main.tex", ["t1", "elsewhere"])).rejects.toThrow(
/not resolved: .*elsewhere.*nothing was resolved/,
);
expect(sent).toEqual([]);
});

it("names the threads already resolved when a later one fails", async () => {
const { session, sent, failOn } = withThreads({ t1: false, t2: false });
failOn("t2");
await expect(session.resolveComments("main.tex", ["t1", "t2"])).rejects.toThrow(
/resolved t1 before failing; thread t2 was not resolved: 500 boom/,
);
expect(sent.map((s) => s.threadId)).toEqual(["t1"]);
});

it("is a no-op for an empty id list", async () => {
const { session, sent } = withThreads({ t1: false });
expect(await session.resolveComments("main.tex", [])).toEqual([]);
expect(sent).toEqual([]);
});
});
});

describe("reliability paths", () => {
Expand Down
Loading
Loading