diff --git a/CLAUDE.md b/CLAUDE.md index c0124b1..3caf965 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -167,10 +167,17 @@ pending suggestions, since its break-and-restore would drop them. `submit` re-jo the doc before every attempt unless `EditOptions.overwriteTrackedChanges` is set (the mirror tracks text, not ranges, so earlier ranges may be stale) and throws `TrackedChangeConflictError` (with `.changes`) before sending. Why: an edit inside a co-author's pending suggestion silently -rewrites or removes it, and Overleaf mails its author that the suggestion was rejected. -`listTrackedChanges` names authors from the project's owner/members. The MCP exposes -`overleaf_list_tracked_changes` but deliberately no override, so an agent asks a human instead; -the CLI has `changes` and `--overwrite-tracked-changes`. +rewrites or removes it, and Overleaf mails its author that the suggestion was rejected. Only +**other authors'** changes are protected (`foreignChanges`): the signed-in user's id is scraped +from the project page's `ol-user_id` (`RestClient.currentUserId`, alongside the CSRF token; it is +not in `joinProjectResponse`) and changes with that `user_id` pass. Verified live: a tracked +insert inside one's own tracked insertion extends it (same id), a tracked delete inside it just +shrinks it (no deletion change), an untracked insert splits it in two. A change without an +author, or every change when the user id is unknown, stays protected. `listTrackedChanges` names +authors from the project's owner/members. The MCP exposes `overleaf_list_tracked_changes` and an +`overwriteTrackedChanges` param on the seven text-writing tools, described as only for when the +user explicitly said to override a co-author's suggestion; the CLI has `changes` and +`--overwrite-tracked-changes`. **Hash.** Overleaf's optional ShareJS hash is git-blob SHA-1 (`ot.gitBlobHash`). We **omit it**: the server treats it as optional, and a mismatch is fatal (`otUpdateError "Invalid diff --git a/README.md b/README.md index 9fb4285..fd733a4 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Bring Claude (and any agent) into Overleaf. Claudeleaf is a reliable TypeScript - **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. -- **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 someone's pending suggestion is refused before it is sent, instead of silently rewriting it (which Overleaf reports to the author as a rejected suggestion). Override in the SDK/CLI with `overwriteTrackedChanges` / `--overwrite-tracked-changes`; the MCP server has no override, so an agent asks a human. +- **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. - **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. - **Reliable by design** — automatic reconnect with document re-join, per-document edit serialization, and server-confirmed edits (no silent loss). - **Zero config, easy sign-in.** No credentials stored and nothing to configure: run `claudeleaf login` once, sign in by hand in the browser that opens (handles reCAPTCHA / SSO / 2FA), and the session is cached. diff --git a/src/cli.ts b/src/cli.ts index 8e79d9d..67c4db1 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -91,8 +91,8 @@ project is an id or name. line/column are 0-based; start/end are character offse The editing commands (append, insert, replace, set) accept --track-changes to submit the edit as a review-mode suggestion instead of a direct edit (requires track changes on the project, a premium feature). They refuse, sending nothing, -an edit that would touch a pending tracked change; --overwrite-tracked-changes -skips that check.`; +an edit that would touch another author's pending tracked change (your own +suggestions stay editable); --overwrite-tracked-changes skips that check.`; async function run(argv: string[]): Promise { const command = argv[0]; diff --git a/src/mcpServer.ts b/src/mcpServer.ts index f8d973b..0c0a373 100644 --- a/src/mcpServer.ts +++ b/src/mcpServer.ts @@ -36,8 +36,21 @@ const trackChanges = z "Submit as a tracked change (review-mode suggestion) instead of a direct edit, for a " + "human to accept or reject. Inserts become tracked insertions; deletions keep the removed " + "text struck through. Requires track changes to be available on the project (premium). " + - "Every text edit is refused, with nothing sent, if it would touch a pending suggestion " + - "(see overleaf_list_tracked_changes); then ask the human instead of working around it.", + "Every text edit is refused, with nothing sent, if it would touch a co-author's pending " + + "suggestion (see overleaf_list_tracked_changes); then ask the human instead of working " + + "around it. The signed-in user's own suggestions are not protected: editing inside one " + + "extends or shrinks it, as in the Overleaf editor.", + ); + +/** Shared schema fragment: let the edit touch a co-author's pending suggestion. */ +const overwriteTrackedChanges = z + .boolean() + .optional() + .describe( + "Let this edit change text inside a co-author's pending tracked change (suggestion), which " + + "silently rewrites or removes it (Overleaf tells the author it was rejected). Only set " + + "this when the user explicitly said to override that co-author's suggestion; never to " + + "get past a refused edit on your own. Not needed for the user's own suggestions.", ); export function createServer(): McpServer { @@ -98,11 +111,11 @@ export function createServer(): McpServer { "overleaf_insert_text", { description: "Insert text at a 0-based line and column. Collaborators see the edit live.", - inputSchema: { project: z.string(), path: z.string(), line: z.number().int(), column: z.number().int(), text: z.string(), trackChanges }, + inputSchema: { project: z.string(), path: z.string(), line: z.number().int(), column: z.number().int(), text: z.string(), trackChanges, overwriteTrackedChanges }, annotations: { readOnlyHint: false, destructiveHint: false }, }, - async ({ project, path, line, column, text, trackChanges }) => { - const doc = await getClient().insert(project, path, line, column, text, { trackChanges }); + async ({ project, path, line, column, text, trackChanges, overwriteTrackedChanges }) => { + const doc = await getClient().insert(project, path, line, column, text, { trackChanges, overwriteTrackedChanges }); return result({ ok: true, path: doc.path, version: doc.version, length: doc.length }); }, ); @@ -111,11 +124,11 @@ export function createServer(): McpServer { "overleaf_append_text", { description: "Append text to the end of a document (a newline is added if needed).", - inputSchema: { project: z.string(), path: z.string(), text: z.string(), trackChanges }, + inputSchema: { project: z.string(), path: z.string(), text: z.string(), trackChanges, overwriteTrackedChanges }, annotations: { readOnlyHint: false, destructiveHint: false }, }, - async ({ project, path, text, trackChanges }) => { - const doc = await getClient().append(project, path, text, { trackChanges }); + async ({ project, path, text, trackChanges, overwriteTrackedChanges }) => { + const doc = await getClient().append(project, path, text, { trackChanges, overwriteTrackedChanges }); return result({ ok: true, path: doc.path, version: doc.version, length: doc.length }); }, ); @@ -124,11 +137,11 @@ export function createServer(): McpServer { "overleaf_replace_text", { description: "Replace literal occurrences of `old` with `new`. count=0 replaces all.", - inputSchema: { project: z.string(), path: z.string(), old: z.string(), new: z.string(), count: z.number().int().optional(), trackChanges }, + inputSchema: { project: z.string(), path: z.string(), old: z.string(), new: z.string(), count: z.number().int().optional(), trackChanges, overwriteTrackedChanges }, annotations: { readOnlyHint: false, destructiveHint: true }, }, - async ({ project, path, old, new: newStr, count, trackChanges }) => { - const n = await getClient().replaceText(project, path, old, newStr, count ?? 0, { trackChanges }); + async ({ project, path, old, new: newStr, count, trackChanges, overwriteTrackedChanges }) => { + const n = await getClient().replaceText(project, path, old, newStr, count ?? 0, { trackChanges, overwriteTrackedChanges }); return result({ ok: true, path, replaced: n }); }, ); @@ -137,11 +150,11 @@ export function createServer(): McpServer { "overleaf_replace_range", { description: "Replace the text between character offsets [start, end) with `text`.", - inputSchema: { project: z.string(), path: z.string(), start: z.number().int(), end: z.number().int(), text: z.string(), trackChanges }, + inputSchema: { project: z.string(), path: z.string(), start: z.number().int(), end: z.number().int(), text: z.string(), trackChanges, overwriteTrackedChanges }, annotations: { readOnlyHint: false, destructiveHint: true }, }, - async ({ project, path, start, end, text, trackChanges }) => { - const doc = await getClient().replaceRange(project, path, start, end, text, { trackChanges }); + async ({ project, path, start, end, text, trackChanges, overwriteTrackedChanges }) => { + const doc = await getClient().replaceRange(project, path, start, end, text, { trackChanges, overwriteTrackedChanges }); return result({ ok: true, path: doc.path, version: doc.version, length: doc.length }); }, ); @@ -150,11 +163,11 @@ export function createServer(): McpServer { "overleaf_delete_range", { description: "Delete the text between character offsets [start, end).", - inputSchema: { project: z.string(), path: z.string(), start: z.number().int(), end: z.number().int(), trackChanges }, + inputSchema: { project: z.string(), path: z.string(), start: z.number().int(), end: z.number().int(), trackChanges, overwriteTrackedChanges }, annotations: { readOnlyHint: false, destructiveHint: true }, }, - async ({ project, path, start, end, trackChanges }) => { - const doc = await getClient().deleteRange(project, path, start, end, { trackChanges }); + async ({ project, path, start, end, trackChanges, overwriteTrackedChanges }) => { + const doc = await getClient().deleteRange(project, path, start, end, { trackChanges, overwriteTrackedChanges }); return result({ ok: true, path: doc.path, version: doc.version, length: doc.length }); }, ); @@ -163,11 +176,11 @@ export function createServer(): McpServer { "overleaf_delete_lines", { description: "Delete 0-based lines startLine..endLine (inclusive).", - inputSchema: { project: z.string(), path: z.string(), startLine: z.number().int(), endLine: z.number().int(), trackChanges }, + inputSchema: { project: z.string(), path: z.string(), startLine: z.number().int(), endLine: z.number().int(), trackChanges, overwriteTrackedChanges }, annotations: { readOnlyHint: false, destructiveHint: true }, }, - async ({ project, path, startLine, endLine, trackChanges }) => { - const doc = await getClient().deleteLines(project, path, startLine, endLine, { trackChanges }); + async ({ project, path, startLine, endLine, trackChanges, overwriteTrackedChanges }) => { + const doc = await getClient().deleteLines(project, path, startLine, endLine, { trackChanges, overwriteTrackedChanges }); return result({ ok: true, path: doc.path, version: doc.version, length: doc.length }); }, ); @@ -176,11 +189,11 @@ export function createServer(): McpServer { "overleaf_set_document", { description: "Replace a document's entire contents with `content` (sent as a minimal diff).", - inputSchema: { project: z.string(), path: z.string(), content: z.string(), trackChanges }, + inputSchema: { project: z.string(), path: z.string(), content: z.string(), trackChanges, overwriteTrackedChanges }, annotations: { readOnlyHint: false, destructiveHint: true }, }, - async ({ project, path, content, trackChanges }) => { - const doc = await getClient().setText(project, path, content, { trackChanges }); + async ({ project, path, content, trackChanges, overwriteTrackedChanges }) => { + const doc = await getClient().setText(project, path, content, { trackChanges, overwriteTrackedChanges }); return result({ ok: true, path: doc.path, version: doc.version, length: doc.length }); }, ); diff --git a/src/rest.ts b/src/rest.ts index 866da7c..a7e8156 100644 --- a/src/rest.ts +++ b/src/rest.ts @@ -11,6 +11,7 @@ import type { ProjectSummary } from "./types.js"; import { sleep } from "./util.js"; const CSRF_RE = /name="ol-csrfToken"\s+content="([^"]+)"/; +const USER_ID_RE = /name="ol-user_id"\s+content="([^"]+)"/; /** * Resolve a server-relative `path` against the configured Overleaf instance and refuse any @@ -29,6 +30,7 @@ export function sameOriginUrl(baseUrl: string, path: string): string { } return url.toString(); } + type EntityType = "doc" | "file" | "folder"; /** List every project the signed-in account can access (via the dashboard JSON API). */ @@ -81,6 +83,7 @@ interface RawProject { export class RestClient { private csrf: string | null = null; + private userId: string | null = null; constructor( private readonly config: Config, @@ -100,7 +103,9 @@ export class RestClient { headers: { Cookie: ch, "User-Agent": this.config.userAgent }, signal: AbortSignal.timeout(this.config.requestTimeout * 1000), }); - const m = CSRF_RE.exec(await res.text()); + const html = await res.text(); + const m = CSRF_RE.exec(html); + this.userId = USER_ID_RE.exec(html)?.[1] ?? this.userId; if (!m) { if (!forceRefresh) return this.ensureCsrf(true); throw new ClaudeleafError("could not obtain CSRF token (session may be invalid)"); @@ -109,6 +114,15 @@ export class RestClient { return this.csrf; } + /** + * The signed-in user's id (`ol-user_id`), read from the same project page as the CSRF + * token; null if the page does not carry it. + */ + async currentUserId(): Promise { + if (!this.userId) await this.ensureCsrf(this.csrf !== null); + return this.userId; + } + private async request( method: "GET" | "POST" | "DELETE", path: string, diff --git a/src/session.ts b/src/session.ts index 89408cb..95fc104 100644 --- a/src/session.ts +++ b/src/session.ts @@ -46,7 +46,7 @@ import type { ProjectInfo, TrackedChange, } from "./types.js"; -import { findConflicts, parseChanges, type ParsedChange } from "./trackedChanges.js"; +import { findConflicts, foreignChanges, parseChanges, type ParsedChange } from "./trackedChanges.js"; import { Deferred, Mutex, sleep } from "./util.js"; const TREE_EVENTS = new Set([ @@ -72,11 +72,13 @@ type ConfirmResult = { status: "confirmed"; version?: number } | { status: "drop export interface EditOptions { trackChanges?: boolean; /** - * Allow the edit to change text inside or at the edge of a pending tracked change. By - * default an edit that would touch someone's suggestion is refused with a + * Allow the edit to change text inside a co-author's pending tracked change. By default an + * edit that would touch someone else's suggestion is refused with a * {@link TrackedChangeConflictError} before anything is sent, because it would silently * alter or remove that suggestion (Overleaf reports a removed insertion to its author as - * "rejected"). The check re-joins the document before each edit to read fresh ranges. + * "rejected"). Suggestions by the signed-in user are never protected: editing inside one's + * own suggestion extends or shrinks it, as in the editor. The check re-joins the document + * before each edit to read fresh ranges. */ overwriteTrackedChanges?: boolean; } @@ -410,6 +412,15 @@ export class ProjectSession { }; } + /** The signed-in user's id, or null if it cannot be determined (then nothing counts as own). */ + private async ownUserId(): Promise { + try { + return await this.rest.currentUserId(); + } catch { + return null; + } + } + /** The owner or member with this user id, from the joinProject payload. */ private projectUser(userId: string): Record | undefined { const owner = this.project.owner as Record | undefined; @@ -724,7 +735,10 @@ export class ProjectSession { const { op, cursor } = build(doc); if (op.length === 0) return doc; if (ranges) { - const touched = findConflicts(op, parseChanges(ranges.changes)); + let touched = findConflicts(op, parseChanges(ranges.changes)); + // Only a co-author's suggestion is protected; one's own stays editable. The user id + // is looked up only when something is touched (an unknown id protects everything). + if (touched.length > 0) touched = foreignChanges(touched, await this.ownUserId()); if (touched.length > 0) { const described = touched.map((c) => this.describeChange(doc, c)); throw new TrackedChangeConflictError(conflictMessage(doc.path, described), described); @@ -958,9 +972,9 @@ function conflictMessage(path: string, changes: TrackedChange[]): string { }); const more = changes.length > 3 ? ` and ${changes.length - 3} more` : ""; return ( - `edit to ${path} not sent: it would touch ${changes.length} pending tracked change(s) - ` + + `edit to ${path} not sent: it would touch ${changes.length} pending tracked change(s) by another author - ` + `${shown.join("; ")}${more}. Ask the author to accept or reject the suggestion first ` + - "(or retry with overwriteTrackedChanges)." + "(or, only if the user explicitly said to override it, retry with overwriteTrackedChanges)." ); } diff --git a/src/trackedChanges.ts b/src/trackedChanges.ts index c532a52..0a5fd1b 100644 --- a/src/trackedChanges.ts +++ b/src/trackedChanges.ts @@ -11,7 +11,8 @@ * An edit that changes text inside or at the edge of someone's pending suggestion changes or * removes that suggestion without the author seeing it as a decision of theirs (Overleaf * reports a removed insertion to its author as "rejected"). {@link findConflicts} finds the - * suggestions an op would touch, so the edit can be refused instead. + * suggestions an op would touch, and {@link foreignChanges} keeps those of other authors, so + * an edit into a co-author's suggestion can be refused while one's own stay editable. * * Pure / side-effect free. */ @@ -129,6 +130,17 @@ export function findConflicts(op: ot.Op, changes: ParsedChange[]): ParsedChange[ return changes.filter((c) => hit.has(c.id)); } +/** + * The changes not authored by `selfId` - those an edit by `selfId` may not touch. Editing + * inside one's own pending suggestion is what the Overleaf editor does when you keep typing + * in it (verified live: a tracked insert inside one's own tracked insertion extends it under + * the same id, a tracked delete inside it just shrinks it), so it needs no protection. A + * change without an author, or any change when `selfId` is unknown, counts as foreign. + */ +export function foreignChanges(changes: ParsedChange[], selfId: string | null | undefined): ParsedChange[] { + return changes.filter((c) => !selfId || c.userId !== selfId); +} + function shiftForDelete(pos: number, a: number, b: number): number { if (pos <= a) return pos; if (pos >= b) return pos - (b - a); diff --git a/test/clientOps.test.ts b/test/clientOps.test.ts index f55caad..b09cb79 100644 --- a/test/clientOps.test.ts +++ b/test/clientOps.test.ts @@ -73,6 +73,9 @@ function makeSession(text: string, version = 0, requestTimeout = 1): { session: fake.addHandler((name, args) => (session as unknown as { onEvent(n: string, a: unknown[]): void }).onEvent(name, args)); // eslint-disable-next-line @typescript-eslint/no-explicit-any (session as any).entities = [{ id: DOC_ID, name: "main.tex", path: "main.tex", type: "doc", folderId: "root" }]; + // No network: the signed-in user is unknown unless a test says otherwise. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (session as any).rest = { currentUserId: async () => null }; return { session, fake }; } @@ -520,6 +523,65 @@ describe("tracked changes: listing and the overwrite guard", () => { expect(fake.text).toBe("hello bold world"); }); + describe("own suggestions vs a co-author's", () => { + // "hello brave new world": the signed-in user's insertion "brave " at [6, 12) and Kenny's + // insertion "new " at [12, 16). + function withMine(selfId: string | null = "u-owner") { + const m = makeSession("hello brave new world"); + m.fake.ranges = { + changes: [ + { id: "own", op: { p: 6, i: "brave " }, metadata: { user_id: "u-owner" } }, + { id: "theirs", op: { p: 12, i: "new " }, metadata: { user_id: "u-kenny" } }, + ], + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const s = m.session as any; + s.project = { + owner: { _id: "u-owner", first_name: "Ada" }, + members: [{ _id: "u-kenny", first_name: "Kenny", last_name: "S" }], + }; + s.rest = { currentUserId: async () => selfId }; + return m; + } + + it("allows an edit that touches only one's own suggestion", async () => { + const { session, fake } = withMine(); + await session.insertAt("main.tex", 8, "x", { trackChanges: true }); + expect(fake.text).toBe("hello brxave new world"); + await session.replaceText("main.tex", "brxave", "bold"); + expect(fake.text).toBe("hello bold new world"); + }); + + it("refuses an edit that touches a co-author's suggestion", async () => { + const { session, fake } = withMine(); + const err = await session.insertAt("main.tex", 14, "x", { trackChanges: true }).catch((e) => e); + expect(err).toBeInstanceOf(TrackedChangeConflictError); + expect(err.message).toMatch(/insertion by Kenny S/); + expect(fake.applies).toBe(0); + }); + + it("refuses a mixed edit and names only the co-author's suggestion", async () => { + const { session, fake } = withMine(); + const err = await session.deleteRange("main.tex", 8, 14).catch((e) => e); + expect(err).toBeInstanceOf(TrackedChangeConflictError); + expect(err.changes.map((c: { id: string }) => c.id)).toEqual(["theirs"]); + expect(err.message).not.toMatch(/Ada/); + expect(fake.applies).toBe(0); + }); + + it("protects every suggestion when the signed-in user is unknown", async () => { + const { session, fake } = withMine(null); + await expect(session.insertAt("main.tex", 8, "x")).rejects.toBeInstanceOf(TrackedChangeConflictError); + expect(fake.applies).toBe(0); + }); + + it("overwriteTrackedChanges lets a co-author edit through", async () => { + const { session, fake } = withMine(); + await session.deleteRange("main.tex", 8, 14, { overwriteTrackedChanges: true }); + expect(fake.text).toBe("hello brw world"); + }); + }); + it("does not block comments on suggested text", async () => { const { session, fake } = withSuggestion(); // eslint-disable-next-line @typescript-eslint/no-explicit-any diff --git a/test/trackedChanges.test.ts b/test/trackedChanges.test.ts index 76d4eb5..631d360 100644 --- a/test/trackedChanges.test.ts +++ b/test/trackedChanges.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect } from "vitest"; import * as ot from "../src/ot.js"; -import { findConflicts, parseChanges, type ParsedChange } from "../src/trackedChanges.js"; +import { findConflicts, foreignChanges, parseChanges, type ParsedChange } from "../src/trackedChanges.js"; // "hello brave world": a pending insertion "brave " at [6, 12), a pending deletion anchored at 12. const ins: ParsedChange = { id: "ins", kind: "insert", text: "brave ", offset: 6 }; @@ -64,3 +64,16 @@ describe("findConflicts", () => { expect(ids([ot.del(4, "o brave w")])).toEqual(["ins", "del"]); }); }); + +describe("foreignChanges", () => { + const mk = (id: string, userId?: string): ParsedChange => ({ id, kind: "insert", text: "x", offset: 0, userId }); + const changes = [mk("a", "me"), mk("b", "kenny"), mk("c")]; + + it("drops the signed-in user's own changes", () => { + expect(foreignChanges(changes, "me").map((c) => c.id)).toEqual(["b", "c"]); + }); + + it("keeps everything when the user is unknown", () => { + expect(foreignChanges(changes, null).map((c) => c.id)).toEqual(["a", "b", "c"]); + }); +});