From a9b5f3ed8a66bbf832dbaf67d4e97b149f84cf43 Mon Sep 17 00:00:00 2001 From: JohannKaspar <63501587+JohannKaspar@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:55:07 +0100 Subject: [PATCH] Resolve and reopen comment threads Overleaf's resolve/reopen routes are doc-scoped (POST /project/:id/doc/:docId/thread/:threadId/resolve|reopen); the older project-level route 404s, which is why only create + list shipped so far. - SDK: resolveComments / reopenComments. They read the doc's comments first and change nothing if any id is not anchored there, skip threads already in the wanted state, and name the threads already changed if a later request fails. - CLI: resolve / reopen; comments now prints thread ids. - MCP: overleaf_resolve_comments / overleaf_reopen_comments (reversible, idempotent). - Unit tests and a live integration test (resolve, reopen, resolve). --- CLAUDE.md | 17 +++++++--- README.md | 14 ++++---- src/cli.ts | 21 ++++++++++-- src/client.ts | 8 +++++ src/mcpServer.ts | 35 ++++++++++++++++++++ src/rest.ts | 10 ++++++ src/session.ts | 44 +++++++++++++++++++++++++ test/clientOps.test.ts | 70 ++++++++++++++++++++++++++++++++++++++++ test/integration.test.ts | 11 +++++++ 9 files changed, 217 insertions(+), 13 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 10ea823..a724fbf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 @@ -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. @@ -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 diff --git a/README.md b/README.md index 719ce43..d39db1f 100644 --- a/README.md +++ b/README.md @@ -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 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 ...`; MCP `overleaf_resolve_comments` / `overleaf_reopen_comments`). - **Collaborators' suggestions are protected.** List a document's pending tracked changes with their authors (`claudeleaf changes `, `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 ...`, `--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. @@ -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 # resolve a thread (reopen undoes it) ``` ### Use it with Claude Code (MCP) @@ -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." @@ -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 } @@ -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. diff --git a/src/cli.ts b/src/cli.ts index 5346d24..cfe8e6d 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -79,7 +79,9 @@ Usage: claudeleaf [args] search find text comment [message|-] comment on the [start,end) span - comments list a document's comments + comments list a document's comments (with thread ids) + resolve ... resolve comment threads + reopen ... reopen resolved comment threads changes [path] list pending tracked changes (whole project if no path) accept ... | --all [--before ISO-DATE] accept tracked changes (by id, or all / all before a date) @@ -234,11 +236,26 @@ async function run(argv: string[]): Promise { } 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) { diff --git a/src/client.ts b/src/client.ts index bca2a93..f2b8d0e 100644 --- a/src/client.ts +++ b/src/client.ts @@ -215,6 +215,14 @@ export class OverleafClient { return (await this.project(project)).listComments(path); } + async resolveComments(project: string, path: string, threadIds: string[]): Promise { + return (await this.project(project)).resolveComments(path, threadIds); + } + + async reopenComments(project: string, path: string, threadIds: string[]): Promise { + 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 { diff --git a/src/mcpServer.ts b/src/mcpServer.ts index 7814cb9..2c43c03 100644 --- a/src/mcpServer.ts +++ b/src/mcpServer.ts @@ -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", { diff --git a/src/rest.ts b/src/rest.ts index b21abfa..86672ea 100644 --- a/src/rest.ts +++ b/src/rest.ts @@ -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 { + 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 diff --git a/src/session.ts b/src/session.ts index 7a72e2b..8108cf3 100644 --- a/src/session.ts +++ b/src/session.ts @@ -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 { + return this.setCommentsResolved(path, threadIds, true); + } + + /** Reopen resolved comment threads of a document; the counterpart of {@link resolveComments}. */ + reopenComments(path: string, threadIds: string[]): Promise { + return this.setCommentsResolved(path, threadIds, false); + } + + private async setCommentsResolved(path: string, threadIds: string[], resolved: boolean): Promise { + 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, diff --git a/test/clientOps.test.ts b/test/clientOps.test.ts index 1d276c3..ac49034 100644 --- a/test/clientOps.test.ts +++ b/test/clientOps.test.ts @@ -312,6 +312,76 @@ describe("comments", () => { }, ]); }); + + describe("resolving and reopening", () => { + function withThreads(state: Record) { + 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", () => { diff --git a/test/integration.test.ts b/test/integration.test.ts index 5f3d86a..d0d02f9 100644 --- a/test/integration.test.ts +++ b/test/integration.test.ts @@ -141,6 +141,17 @@ describe.skipIf(!testProject)("integration", () => { expect((await client.readDocument(project, SCRATCH)).startsWith("OWN [more] SUGGESTION Line zero")).toBe(true); }); + it("resolves and reopens a comment", async () => { + const c = await client.addComment(project, SCRATCH, 0, 4, "resolve me"); + const state = async () => (await client.listComments(project, SCRATCH)).find((x) => x.threadId === c.threadId)?.resolved; + expect(await state()).toBe(false); + expect((await client.resolveComments(project, SCRATCH, [c.threadId]))[0].resolved).toBe(true); + expect(await state()).toBe(true); + expect((await client.reopenComments(project, SCRATCH, [c.threadId]))[0].resolved).toBe(false); + expect(await state()).toBe(false); + await client.resolveComments(project, SCRATCH, [c.threadId]); // leave the scratch doc tidy + }); + it("version increments", async () => { const v0 = await client.documentVersion(project, SCRATCH); await client.append(project, SCRATCH, "x");