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
15 changes: 11 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <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.
- **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 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 <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.
- **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.
Expand Down
4 changes: 2 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number> {
const command = argv[0];
Expand Down
59 changes: 36 additions & 23 deletions src/mcpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 });
},
);
Expand All @@ -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 });
},
);
Expand All @@ -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 });
},
);
Expand All @@ -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 });
},
);
Expand All @@ -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 });
},
);
Expand All @@ -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 });
},
);
Expand All @@ -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 });
},
);
Expand Down
16 changes: 15 additions & 1 deletion src/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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). */
Expand Down Expand Up @@ -81,6 +83,7 @@ interface RawProject {

export class RestClient {
private csrf: string | null = null;
private userId: string | null = null;

constructor(
private readonly config: Config,
Expand All @@ -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)");
Expand All @@ -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<string | null> {
if (!this.userId) await this.ensureCsrf(this.csrf !== null);
return this.userId;
}

private async request(
method: "GET" | "POST" | "DELETE",
path: string,
Expand Down
28 changes: 21 additions & 7 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand All @@ -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;
}
Expand Down Expand Up @@ -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<string | null> {
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<string, any> | undefined {
const owner = this.project.owner as Record<string, any> | undefined;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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)."
);
}

Expand Down
Loading
Loading