diff --git a/CLAUDE.md b/CLAUDE.md index c0124b1..10ea823 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -167,10 +167,29 @@ 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`. Without a path, `listTrackedChanges` walks every doc (each +change carries its `path`). + +**Accepting tracked changes** is HTTP, not realtime (verified live): +`POST /project/:id/doc/:docId/changes/accept {change_ids:[...]}` (cookie + CSRF) → 204. The text +and version do not change (an accepted insertion stays, an accepted deletion is already gone); +only the ranges drop the changes, and the server broadcasts `accept-changes [docId, ids]` to +the project, which the mirror can ignore. `acceptTrackedChanges(path, ids)` re-joins first and +accepts nothing if any id is not pending in that doc. MCP: `overleaf_accept_tracked_changes` +(destructive: an accepted suggestion can no longer be rejected; its description limits it to +changes the user explicitly said to accept). CLI: `accept ... | --all +[--before ISO-DATE]`. Rejecting is not implemented (the editor does it client-side by +applying the inverse op). **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 @@ -261,8 +280,9 @@ state; instead: also `idempotentHint: false`, since each call kicks off a fresh build. The writes set `destructiveHint` explicitly (it would otherwise default to `true` whenever `readOnlyHint` is `false`): `true` for overwrite/remove tools (`replace_text`, `replace_range`, - `delete_range`, `delete_lines`, `set_document`, `delete_document`, and `upload_file` — which - replaces a same-named file), `false` for the purely additive ones (`insert_text`, + `delete_range`, `delete_lines`, `set_document`, `delete_document`, `accept_tracked_changes` + — 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 tools that change document text also take an optional `trackChanges` to submit as a @@ -288,7 +308,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`, `createDocument`, +`replaceText`, `setText`, `deleteLines`, `setCursor`, `getConnectedUsers`, `listTrackedChanges`, `acceptTrackedChanges`, `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 9fb4285..719ce43 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,8 @@ 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. +- **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. - **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..5346d24 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -12,7 +12,7 @@ import { OverleafClient } from "./client.js"; import { Config } from "./config.js"; import { ClaudeleafError } from "./errors.js"; -const VALUE_FLAGS = new Set(["count", "folder", "name"]); +const VALUE_FLAGS = new Set(["count", "folder", "name", "before"]); function parseArgs(args: string[]): { positionals: string[]; flags: Record } { const positionals: string[] = []; @@ -80,7 +80,9 @@ Usage: claudeleaf [args] comment [message|-] comment on the [start,end) span comments list a document's comments - changes list a document's pending tracked changes + 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) upload [--folder DIR] [--name NAME] upload an image/PDF for \includegraphics compile [--draft] [--stop-on-first-error] [--log] [--warnings] @@ -91,8 +93,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]; @@ -246,10 +248,35 @@ async function run(argv: string[]): Promise { for (const c of changes) { const who = c.author ?? c.email ?? c.userId ?? "?"; const when = c.timestamp ? ` ${c.timestamp}` : ""; - console.log(`${c.line}:${c.column} ${c.kind.padEnd(6)} ${who}${when} ${JSON.stringify(c.text)}`); + const where = positionals[1] === undefined ? `${c.path} ` : ""; + console.log(`${c.id} ${where}${c.line}:${c.column} ${c.kind.padEnd(6)} ${who}${when} ${JSON.stringify(c.text)}`); } return 0; } + case "accept": { + const path = positionals[1]; + if (!path) { + console.error("error: 'accept' needs a document path"); + return 1; + } + let ids = positionals.slice(2); + const before = typeof flags.before === "string" ? Date.parse(flags.before) : undefined; + if (before !== undefined && Number.isNaN(before)) { + console.error(`error: --before is not a date: ${flags.before}`); + return 1; + } + if (ids.length === 0 && (boolFlag(flags.all) || before !== undefined)) { + ids = (await client.listTrackedChanges(project, path)) + .filter((c) => before === undefined || (c.timestamp !== undefined && Date.parse(c.timestamp) < before)) + .map((c) => c.id); + } else if (ids.length === 0) { + console.error("error: 'accept' needs change ids, --all or --before"); + return 1; + } + const accepted = await client.acceptTrackedChanges(project, path, ids); + console.log(`Accepted ${accepted.length} tracked change(s) in ${path}.`); + return 0; + } case "upload": { const file = positionals[1]; if (!file) { diff --git a/src/client.ts b/src/client.ts index 5c74ead..bca2a93 100644 --- a/src/client.ts +++ b/src/client.ts @@ -216,10 +216,15 @@ export class OverleafClient { } // -- tracked changes -------------------------------------------------- - async listTrackedChanges(project: string, path: string): Promise { + /** A document's pending tracked changes, or the whole project's when `path` is omitted. */ + async listTrackedChanges(project: string, path?: string): Promise { return (await this.project(project)).listTrackedChanges(path); } + async acceptTrackedChanges(project: string, path: string, changeIds: string[]): Promise { + return (await this.project(project)).acceptTrackedChanges(path, changeIds); + } + // -- presence & structure --------------------------------------------- async setCursor(project: string, path: string, line: number, column: number): Promise { await (await this.project(project)).setCursor(path, line, column); diff --git a/src/mcpServer.ts b/src/mcpServer.ts index f8d973b..6d43d8a 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 }); }, ); @@ -291,16 +304,36 @@ export function createServer(): McpServer { "overleaf_list_tracked_changes", { description: - "List a document's pending tracked changes (review-mode suggestions) — each with kind " + - "(insert: text in the document; delete: text removed but kept as a suggestion), the text, " + - "position (offset/line/column), author and time. Edits that would touch one are refused, " + - "so check here before editing text a collaborator may have suggested changes to.", - inputSchema: { project: z.string(), path: z.string() }, + "List pending tracked changes (review-mode suggestions) of a document, or of every " + + "document in the project when `path` is omitted — each with id, path, kind (insert: text " + + "in the document; delete: text removed but kept as a suggestion), the text, position " + + "(offset/line/column), author and time. Edits that would touch a co-author's one are " + + "refused, so check here before editing text a collaborator may have suggested changes to.", + inputSchema: { project: z.string(), path: z.string().optional() }, annotations: { readOnlyHint: true }, }, async ({ project, path }) => result(await getClient().listTrackedChanges(project, path)), ); + server.registerTool( + "overleaf_accept_tracked_changes", + { + description: + "Accept pending tracked changes (suggestions) in a document by id, like Accept in " + + "Overleaf's review panel: an insertion becomes plain text, a deletion becomes final; the " + + "suggestion is gone and cannot be rejected afterwards. Only accept changes the user " + + "explicitly told you to accept (e.g. by author, date or id) — accepting a co-author's " + + "suggestion is a review decision. Take ids from overleaf_list_tracked_changes; if any id " + + "is not pending in the document, nothing is accepted. Returns the accepted changes.", + inputSchema: { project: z.string(), path: z.string(), changeIds: z.array(z.string()).min(1) }, + annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false }, + }, + async ({ project, path, changeIds }) => { + const accepted = await getClient().acceptTrackedChanges(project, path, changeIds); + return result({ accepted: accepted.length, changes: accepted }); + }, + ); + server.registerTool( "overleaf_compile", { diff --git a/src/rest.ts b/src/rest.ts index 866da7c..b21abfa 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, @@ -222,6 +236,15 @@ export class RestClient { await this.request("POST", `/project/${this.projectId}/thread/${threadId}/messages`, { content }); } + /** + * 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 + * ranges lose these changes, and the server broadcasts `accept-changes` to the project. + */ + async acceptChanges(docId: string, changeIds: string[]): Promise { + await this.request("POST", `/project/${this.projectId}/doc/${docId}/changes/accept`, { change_ids: changeIds }); + } + /** Fetch every comment thread in the project, keyed by thread id. */ async getThreads(): Promise> { return (await this.request("GET", `/project/${this.projectId}/threads`)) as Record; diff --git a/src/session.ts b/src/session.ts index 89408cb..7a72e2b 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; } @@ -382,7 +384,13 @@ export class ProjectSession { * List a document's pending tracked changes (review-mode suggestions), in document order, * with their author where the author is a member of the project. Read-only. */ - async listTrackedChanges(path: string): Promise { + async listTrackedChanges(path?: string): Promise { + if (path === undefined) { + // Every document in tree order, one join at a time. + const all: TrackedChange[] = []; + for (const e of this.entities.filter((x) => x.type === "doc")) all.push(...(await this.listTrackedChanges(e.path))); + return all; + } const doc = await this.openDoc(path); // Through joinDoc for the same reasons as listComments: a failed join raises, and the // offsets are mapped against the text of this same join. @@ -392,12 +400,38 @@ export class ProjectSession { .map((c) => this.describeChange(doc, c)); } + /** + * Accept pending tracked changes of a document by id (from {@link listTrackedChanges}), as + * the review panel's Accept does: an insertion becomes plain text, a deletion is final. The + * text does not change. Ids are checked against freshly read ranges first; if any is not + * pending in this document, nothing is accepted. Returns the accepted changes. + */ + async acceptTrackedChanges(path: string, changeIds: string[]): Promise { + const doc = await this.openDoc(path); + const wanted = [...new Set(changeIds)]; + if (wanted.length === 0) return []; + return this.mutex(doc.id).runExclusive(async () => { + const ranges = await this.joinDoc(doc); + const pending = new Map(parseChanges(ranges.changes).map((c) => [c.id, c])); + const missing = wanted.filter((id) => !pending.has(id)); + if (missing.length > 0) { + throw new ClaudeleafError( + `not accepted: ${missing.length} change id(s) are not pending in ${doc.path} ` + + `(${missing.slice(0, 5).join(", ")}${missing.length > 5 ? ", ..." : ""}); nothing was accepted`, + ); + } + await this.rest.acceptChanges(doc.id, wanted); + return wanted.map((id) => this.describeChange(doc, pending.get(id)!)); + }); + } + private describeChange(doc: Document, c: ParsedChange): TrackedChange { const [line, column] = doc.offsetToRowcol(c.offset); const user = c.userId ? this.projectUser(c.userId) : undefined; const name = user ? [user.first_name, user.last_name].filter(Boolean).join(" ") : ""; return { id: c.id, + path: doc.path, kind: c.kind, text: c.text, offset: c.offset, @@ -410,6 +444,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 +767,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 +1004,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/src/types.ts b/src/types.ts index 8fac22e..9cb621f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -76,6 +76,8 @@ export interface Comment { export interface TrackedChange { /** Overleaf's change id. */ id: string; + /** Path of the document the change is in. */ + path: string; kind: "insert" | "delete"; /** The suggested inserted text, or the text suggested for deletion. */ text: string; diff --git a/test/clientOps.test.ts b/test/clientOps.test.ts index f55caad..1d276c3 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 }; } @@ -467,6 +470,7 @@ describe("tracked changes: listing and the overwrite guard", () => { expect(await session.listTrackedChanges("main.tex")).toEqual([ { id: "c1", + path: "main.tex", kind: "insert", text: "brave ", offset: 6, @@ -520,6 +524,104 @@ 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"); + }); + }); + + describe("accepting", () => { + function withAccept() { + const m = withSuggestion(); + const sent: { docId: string; ids: string[] }[] = []; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (m.session as any).rest = { + currentUserId: async () => "u-owner", + acceptChanges: async (docId: string, ids: string[]) => void sent.push({ docId, ids }), + }; + return { ...m, sent }; + } + + it("accepts pending changes by id and returns them", async () => { + const { session, fake, sent } = withAccept(); + const accepted = await session.acceptTrackedChanges("main.tex", ["c1", "c1"]); + expect(sent).toEqual([{ docId: DOC_ID, ids: ["c1"] }]); + expect(accepted.map((c) => [c.id, c.author])).toEqual([["c1", "Kenny S"]]); + expect(fake.text).toBe("hello brave world"); // text unchanged + expect(fake.applies).toBe(0); + }); + + it("accepts nothing if any id is not pending", async () => { + const { session, sent } = withAccept(); + await expect(session.acceptTrackedChanges("main.tex", ["c1", "gone"])).rejects.toThrow(/not pending.*gone/); + expect(sent).toEqual([]); + }); + + it("is a no-op for an empty id list", async () => { + const { session, sent } = withAccept(); + expect(await session.acceptTrackedChanges("main.tex", [])).toEqual([]); + expect(sent).toEqual([]); + }); + + it("lists the whole project's changes when no path is given", async () => { + const { session } = withAccept(); + expect((await session.listTrackedChanges()).map((c) => [c.path, c.id])).toEqual([["main.tex", "c1"]]); + }); + }); + 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/integration.test.ts b/test/integration.test.ts index 6913efd..5f3d86a 100644 --- a/test/integration.test.ts +++ b/test/integration.test.ts @@ -130,6 +130,17 @@ describe.skipIf(!testProject)("integration", () => { expect(hits[0].line).toBe(0); }); + it("edits inside one's own suggestion, then accepts it", async () => { + await client.insertAt(project, SCRATCH, 0, "OWN SUGGESTION ", { trackChanges: true }); + await client.insertAt(project, SCRATCH, 4, "[more] ", { trackChanges: true }); // inside it: allowed + const changes = await client.listTrackedChanges(project, SCRATCH); + expect(changes.map((c) => [c.kind, c.text])).toEqual([["insert", "OWN [more] SUGGESTION "]]); + const accepted = await client.acceptTrackedChanges(project, SCRATCH, changes.map((c) => c.id)); + expect(accepted).toHaveLength(1); + expect(await client.listTrackedChanges(project, SCRATCH)).toEqual([]); + expect((await client.readDocument(project, SCRATCH)).startsWith("OWN [more] SUGGESTION Line zero")).toBe(true); + }); + it("version increments", async () => { const v0 = await client.documentVersion(project, SCRATCH); await client.append(project, SCRATCH, "x"); 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"]); + }); +});