diff --git a/CHANGELOG.md b/CHANGELOG.md index 36aae68..3faae96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,19 @@ All notable changes to this project will be documented in this file. ## [Unreleased] ### Added -- **Turn pushed edits into tracked changes** - `suggestChanges(projectId, path, edits)` makes edits that reached Overleaf as plain text, through git, `olcli push` or a sync, show up as tracked changes, as if they had been typed in Reviewing mode. Each edit is given as the old and new text with some text around it; olcli finds the new text, undoes the edit without tracking and redoes it with tracking (`meta.tc` on the update, as the editor sends it). The text ends up as it was, so a git clone that pushed the edit has nothing new to pull. An edit whose new text is not on Overleaf yet is reported as `not-pushed` and left alone. sharejs-text-ot docs only; history-ot docs are refused +- **Turn pushed edits into tracked changes** ([#66](https://github.com/aloth/olcli/pull/66)) - `suggestChanges(projectId, path, edits)` makes edits that reached Overleaf as plain text, through git, `olcli push` or a sync, show up as tracked changes, as if they had been typed in Reviewing mode. Each edit is given as the old and new text with some text around it; olcli finds the new text, undoes the edit without tracking and redoes it with tracking (`meta.tc` on the update, as the editor sends it). The text ends up as it was, so a git clone that pushed the edit has nothing new to pull. An edit whose new text is not on Overleaf yet is reported as `not-pushed` and left alone. sharejs-text-ot docs only; history-ot docs are refused. Thanks to @fredericosantos +- **MCP tool `suggest_changes` (experimental)** - turns edits that are already on Overleaf as plain text into suggestions collaborators can accept or reject, for projects with track changes, by calling `suggestChanges`. Like the other write tools it asks the user first: the dialog lists each edit with its location and the suggested deletion and insertion, or why it is left alone. If no edit can become a suggestion it asks nothing and writes nothing, and it refuses to write when the document changed after the preview. Clients without elicitation get the preview only, since there is no olcli command for this yet. sharejs-text-ot documents only; returns one result per edit + +### Fixed +- **`suggestChanges` no longer hangs on an edit with nothing to search for** - an edit whose `before`, `inserted` and `after` were all empty, such as a pure deletion given without surrounding text, made the search loop forever. Such an edit is now reported as `invalid` and nothing is sent +- **`suggestChanges` no longer tracks the same edit twice** - running it again for an edit that is already a tracked change added a second tracked change, and the tracked deletion held the old text twice. An edit whose new or old text is already tracked at that place is now reported as `already-tracked` and nothing is sent, also when the same edit appears twice in one call +- **`suggestChanges` checks its result** - after writing, the document is read again, and an edit without a tracked change at the expected place is reported as `not-tracked` instead of `done` +- **`suggestChanges` names the missing permission** - with review-only access the untracked undo is refused, and the call failed with "applyOtUpdate did not return an acknowledgement". It now throws `SuggestionPermissionError`, which says that the account needs edit access to the project, and nothing is written. When Overleaf reports the access level up front, the check happens before anything is sent +- **`suggestChanges` sends a tracked-change id seed in Overleaf's format** - the seed in `meta.tc` was 18 random hex digits; it now starts with the current time in seconds like the seeds the Overleaf editor generates, so the ids of the new tracked changes carry a meaningful timestamp + +### Changed +- **`suggestChanges` reports `unchanged`** for an edit whose `inserted` equals `deleted`, instead of `not-pushed`. `SuggestionResult` gains `already-tracked`, `unchanged`, `invalid` and `not-tracked`; existing values keep their meaning. `hint` is now optional +- **`suggestChanges` is marked experimental** - sharejs-text-ot documents only (history-ot documents are refused), and collaborators who have the document open see the old text for about 0.2 seconds while an edit is undone and redone. `planSuggestions` reports what it would do without writing, and an `expectedVersion` option refuses to write when the document changed since. Documented in docs/LIBRARY.md ## [0.17.0] - 2026-11-15 diff --git a/SKILL.md b/SKILL.md index 487d7f7..02b9639 100644 --- a/SKILL.md +++ b/SKILL.md @@ -119,7 +119,7 @@ olcli-mcp npx -y --package @aloth/olcli olcli-mcp ``` -Available MCP tools: `list_projects`, `get_project_info`, `pull_project`, `push_file`, `compile`, `download_pdf`, `list_comments`, `get_entities`, `download_file`, `add_comment`, `reply_to_comment`, `resolve_comment`, `delete_entity`, `rename_entity`, `rename_project`, `plan_project_renames`, `compile_with_outputs`, `diff_project`, `create_project`, `accept_tracked_changes`, `reject_tracked_changes`. +Available MCP tools: `list_projects`, `get_project_info`, `pull_project`, `push_file`, `compile`, `download_pdf`, `list_comments`, `get_entities`, `download_file`, `add_comment`, `reply_to_comment`, `resolve_comment`, `delete_entity`, `rename_entity`, `rename_project`, `plan_project_renames`, `compile_with_outputs`, `diff_project`, `create_project`, `accept_tracked_changes`, `reject_tracked_changes`, `suggest_changes` (experimental). `compile`, `download_pdf` and `compile_with_outputs` accept an optional `resource_path` to compile a specific root document. diff --git a/docs/LIBRARY.md b/docs/LIBRARY.md index 08828fc..f7c7aac 100644 --- a/docs/LIBRARY.md +++ b/docs/LIBRARY.md @@ -37,6 +37,9 @@ import { FolderEntry, DocEntry, FileEntry, CommentMessage, ProjectComment, CommentContext, CommentStatus, ListCommentsOptions, AddCommentOptions, Credentials, SessionCookiePair, + // Tracked changes and suggestions + TrackedChange, ListTrackedChangesOptions, ProjectReview, RejectConflictError, + SuggestionEdit, SuggestionResult, SuggestionOutcome, SuggestionPlan, SuggestionPermissionError, // Config utilities getBaseUrl, setBaseUrl, getSessionCookie, setSessionCookie, getSessionCookieName, setSessionCookieName, getCsrf, setCsrf, @@ -48,3 +51,32 @@ import { IgnoreContext, LoadIgnoreOptions, } from '@aloth/olcli'; ``` + +## Turning pushed edits into suggestions (experimental) + +`client.suggestChanges(projectId, path, edits)` turns edits that are already on Overleaf as plain text, for example pushed through git, `olcli push` or a sync, into tracked changes that collaborators can accept or reject. Each edit is `{ before, deleted, inserted, after, hint? }`: the old and the new text with some unchanged text around it, and optionally the approximate offset of the edit; the nearest match wins. `client.planSuggestions(projectId, path, edits)` reports what would happen without writing. + +```ts +const results = await client.suggestChanges(projectId, 'main.tex', [ + { before: 'The ', deleted: 'quick', inserted: 'slow', after: ' fox', hint: 120 }, +]); +// ['done'] +``` + +This method is experimental: + +- Only documents in the `sharejs-text-ot` format are supported; `history-ot` documents are refused with an error. +- Each edit is undone without tracking and redone with tracking. The text ends up the same, but collaborators who have the document open see the old text for a short moment, about 0.2 seconds. +- The account needs edit access to the project. Review-only access cannot send the untracked undo, so the call throws `SuggestionPermissionError` before writing anything. + +One result per edit, in order: + +| Result | Meaning | +|--------|---------| +| `done` | Now a tracked change, checked by reading the document again | +| `already-tracked` | The edit is already a tracked change, for example from an earlier call; nothing was sent | +| `not-pushed` | Overleaf still has the old text; nothing was sent | +| `not-found` | Neither the old nor the new text is there; nothing was sent | +| `unchanged` | `inserted` equals `deleted`; nothing was sent | +| `invalid` | `before`, `inserted` and `after` are all empty, so the edit cannot be found; nothing was sent | +| `not-tracked` | The edit was sent, but no tracked change showed up when the document was read again. The text is as before the call | diff --git a/docs/MCP.md b/docs/MCP.md index c74bafb..fe157e7 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -22,6 +22,7 @@ Tools marked "asks first" change the Overleaf project. Before writing, the serve | `resolve_comment` | Mark a comment thread as resolved; asks first | | `accept_tracked_changes` | Accept tracked changes by id; sends nothing if any id is unknown; asks first | | `reject_tracked_changes` | Reject tracked changes by id; returns a diff preview and writes only with `apply: true`, after asking | +| `suggest_changes` | Experimental. Turn edits that are already on Overleaf as plain text (pushed through git, `push_file` or a sync) into tracked changes collaborators can accept or reject, for projects with track changes; sharejs-text-ot documents only; returns one result per edit; asks first | | `delete_entity` | Delete a file or document by path; asks first | | `rename_entity` | Rename a file, document, or folder, or move it into another folder (`new_name` as a path, see below); asks first | | `rename_project` | Rename the project itself (not a file inside it); asks first | @@ -32,6 +33,8 @@ Tools marked "asks first" change the Overleaf project. Before writing, the serve > **Tracked changes need a premium project.** Track changes is an Overleaf premium feature: it is only available in projects whose owner has a premium plan, and invited collaborators can then use it regardless of their own plan. In other projects `list_comments` with `include_changes` returns no changes and `accept_tracked_changes`/`reject_tracked_changes` report the ids as not found. See the [Overleaf documentation](https://docs.overleaf.com/collaborating/track-changes). +> **`suggest_changes` is experimental.** Each edit is undone without tracking and redone with tracking, so the text ends up the same, but collaborators who have the document open see the old text for a short moment (about 0.2 seconds). It needs edit access to the project: review-only access cannot send the untracked undo, and the tool then fails with an error that says so before writing anything. Only documents in the `sharejs-text-ot` format are supported; `history-ot` documents are refused. Results per edit: `done` (checked by reading the document again), `already-tracked`, `not-pushed`, `not-found`, `unchanged`, `invalid`, and `not-tracked` (sent, but no tracked change showed up afterwards). + > **What `diff_project` compares.** The remote side is fetched fresh on every call, so the result describes the project as it is right now, which is what a later push would overwrite. It is not a comparison against the last pull: the manifest records remote paths, never remote contents, so there is no stored snapshot. Every response carries `remote_fetched_at` for that reason — a collaborator editing between the call and a push can still change the outcome. Patches are oriented `a/` = remote, `b/` = local, so a `+` line is content a push would upload. Pass `name_only` to get statuses without patch text. > **What `new_name` of `rename_entity` accepts.** The same destinations as `olcli mv`: a bare name renames in place and the entity keeps its folder; `chapters/intro.tex` moves the entity into `chapters/` (created if missing) and renames it; `chapters/` moves it and keeps the name; `/` is the project root. The result returns `old_path`, `new_path` and `created_folders`. @@ -58,12 +61,13 @@ The server also tells the client, in its MCP `instructions` and in the descripti | `resolve_comment` | The thread | | `accept_tracked_changes` | Each change as `path:line:column`, kind, author, and text, plus a diff of what becomes final: the text without the selected suggestions against the text after accepting them. Other tracked changes in the same document stay pending and are shown as not applied on both sides | | `reject_tracked_changes` with `apply: true` | Each change and the rejection diff. With `apply: false` (the default) it returns the preview and asks nothing | +| `suggest_changes` | Per edit its location as `path:line:column` and the suggested deletion and insertion with the text around them, or why the edit is left alone (already tracked, not pushed, not found, unchanged, invalid). If no edit can become a suggestion, nothing is asked and nothing is written. Clients without elicitation get the preview only, since there is no olcli command for this yet | The dialog has one checkbox, "Confirm", which starts unchecked. Only accepting with the box checked writes. Declining, dismissing the dialog, submitting it unchecked, no answer within 10 minutes (or the client canceling the call sooner), or an error all write nothing, and the tool result tells the assistant that the change was not made and why. Long content is cut with an explicit note such as `... 12 more lines not shown`. Control characters, zero-width characters, and bidirectional formatting characters are shown as `\u{...}`, so text cannot look different from what it is. -What you confirm is what gets written: `delete_entity` and `rename_entity` act on the entity shown in the dialog, `reject_tracked_changes` refuses to write if a document changed after the preview, and `accept_tracked_changes` refuses if a selected change no longer has the text shown. +What you confirm is what gets written: `delete_entity` and `rename_entity` act on the entity shown in the dialog, `reject_tracked_changes` and `suggest_changes` refuse to write if a document changed after the preview, and `accept_tracked_changes` refuses if a selected change no longer has the text shown. Tools that only read never ask. `pull_project`, `download_file`, and `download_pdf` write local files but do not change the Overleaf project, and do not ask either. `plan_project_renames` never applies anything. diff --git a/src/client.ts b/src/client.ts index a71f0ed..167f865 100644 --- a/src/client.ts +++ b/src/client.ts @@ -28,6 +28,11 @@ import { describeAuthor, parseHistoryOtChanges, parseShareJsChanges, + matchSuggestionEdit, + trackedParts, + generateIdSeed, + type SuggestionEdit, + type SuggestionOutcome, type DocTrackedChange, type ShareJsTextOp, type TrackedChangeAuthor, @@ -58,20 +63,6 @@ export function retryDelayMs(retryAfter: string | string[] | undefined, attempt: return 1000 * 2 ** attempt * (0.75 + random() * 0.5); } -/** Offset of the occurrence of `needle` nearest to `hint`, or -1. */ -function nearestIndex(text: string, needle: string, hint: number): number { - let best = -1; - for (let i = text.indexOf(needle); i !== -1; i = text.indexOf(needle, i + 1)) { - if (best === -1 || Math.abs(i - hint) < Math.abs(best - hint)) best = i; - } - return best; -} - -/** The editor names tracked changes by an 18-hex-digit seed plus a counter, and sends the seed as `meta.tc`. */ -function trackChangesSeed(): string { - return Array.from({ length: 18 }, () => Math.floor(Math.random() * 16).toString(16)).join(''); -} - const DEFAULT_BASE_URL = 'https://www.overleaf.com'; const RESOURCE_PATH_FAILURE_HINT = ' (Perhaps the resource file you specified does not exist in the project?)'; @@ -274,23 +265,39 @@ export interface AcceptancePlan { export { RejectConflictError }; +export type { SuggestionEdit }; + /** - * An edit that was made outside Overleaf and pushed as plain text (through - * git, `olcli push` or a sync): `deleted` was replaced by `inserted` between - * `before` and `after`. `suggestChanges` turns it into a tracked change. + * What `suggestChanges` did with one edit. + * - `done`: now a tracked change, checked by reading the doc again. + * - `not-pushed`: Overleaf still has the old text; nothing was sent. + * - `not-found`: neither text is there; nothing was sent. + * - `already-tracked`: the edit is already a tracked change, for example from an earlier call; nothing was sent. + * - `unchanged`: `inserted` equals `deleted`, so there is no edit; nothing was sent. + * - `invalid`: `before`, `inserted` and `after` are all empty, so the edit cannot be found; nothing was sent. + * - `not-tracked`: the edit was sent, but reading the doc again shows no tracked change for it. The text is as before the call. */ -export interface SuggestionEdit { - before: string; - after: string; - deleted: string; - inserted: string; - /** About where the edit is in the doc; the match nearest to it wins. */ - hint: number; -} +export type SuggestionResult = 'done' | 'not-pushed' | 'not-found' | 'already-tracked' | 'unchanged' | 'invalid' | 'not-tracked'; -/** done: now a tracked change. not-pushed: Overleaf still has the old text. not-found: neither text is there. */ -export type SuggestionResult = 'done' | 'not-pushed' | 'not-found'; +export type { SuggestionOutcome }; +/** What `planSuggestions` found for each edit, before anything is written. */ +export interface SuggestionPlan { + docId: string; + path: string; + version: number; + /** The account's access level in the project, when Overleaf sent it. */ + permissionsLevel?: string; + edits: Array<{ edit: SuggestionEdit; outcome: SuggestionOutcome; line?: number; column?: number }>; +} + +/** Thrown when the account may review but not edit: turning an edit into a suggestion first writes untracked. */ +export class SuggestionPermissionError extends Error { + constructor(path: string, detail?: string) { + super(`${path}: this account needs edit access to the project to turn edits into suggestions; review-only access cannot do it, because the edit is first undone without tracking. Nothing was changed${detail ? ` (${detail})` : ''}`); + this.name = 'SuggestionPermissionError'; + } +} export interface AddCommentOptions { filePath: string; @@ -327,6 +334,8 @@ interface ProjectSocketSession { sid: string; projectId: string; pollUrl: () => string; + /** From joinProjectResponse: `owner`, `readAndWrite`, `review` or `readOnly`, when Overleaf sent it. */ + permissionsLevel?: string; } export interface SessionCookiePair { @@ -1419,7 +1428,11 @@ export class OverleafClient { if (packets.some(packet => { if (!packet.startsWith('5:::')) return false; try { - return JSON.parse(packet.slice(4))?.name === 'joinProjectResponse'; + const payload = JSON.parse(packet.slice(4)); + if (payload?.name !== 'joinProjectResponse') return false; + const level = payload?.args?.[0]?.permissionsLevel; + if (typeof level === 'string') session.permissionsLevel = level; + return true; } catch { return false; } @@ -2836,14 +2849,69 @@ export class OverleafClient { } /** - * Turn edits that already reached Overleaf as plain text into tracked - * changes, as if they had been typed in Reviewing mode: each edit is undone - * without tracking and then redone with tracking (the update's `meta.tc`). - * The text ends up as it was, so a git clone that pushed the edit has - * nothing new to pull. An edit whose new text is not in the doc is left - * alone and reported. One socket, one join; sharejs-text-ot docs only. + * Work out what `suggestChanges` would do with `edits`, without writing: + * per edit the outcome and, for an edit that would become a suggestion or + * is already tracked, its line and column. Refuses history-ot docs, like + * `suggestChanges`. + */ + async planSuggestions(projectId: string, filePath: string, edits: SuggestionEdit[]): Promise { + const docs = this.collectProjectDocs(await this.getProjectInfo(projectId)); + const wanted = filePath.replace(/^\/+/, ''); + const doc = docs.find(item => item.path.replace(/^\/+/, '') === wanted); + if (!doc) { + throw new Error(`Doc not found: ${filePath}`); + } + const session = await this.openProjectSocket(projectId); + try { + const joinedDoc = await this.joinDocument(session, doc.id); + if (joinedDoc.type !== 'sharejs-text-ot') { + throw new Error(`${doc.path}: turning edits into tracked changes is not supported for history-ot docs yet`); + } + const changes = parseShareJsChanges(joinedDoc.ranges); + const planned = edits.map(edit => { + const match = matchSuggestionEdit(joinedDoc.content, changes, edit); + const location = match.position === undefined ? undefined : this.positionToLineColumn(joinedDoc.content, match.position); + if (match.outcome === 'suggest') { + // A repeated edit later in the list must see this one as tracked. + if (edit.deleted) changes.push({ id: '', kind: 'delete', position: match.position! + edit.inserted.length, text: edit.deleted, userId: null }); + if (edit.inserted) changes.push({ id: '', kind: 'insert', position: match.position!, text: edit.inserted, userId: null }); + } + return { edit, outcome: match.outcome, ...(location ?? {}) }; + }); + return { docId: doc.id, path: doc.path, version: joinedDoc.version, permissionsLevel: session.permissionsLevel, edits: planned }; + } finally { + await this.closeProjectSocket(session); + } + } + + /** + * Delays before each read-back of a doc after `suggestChanges` wrote to it. + * The real-time service acknowledges an update when it is queued, so the + * new ranges can take a moment to show up. */ - async suggestChanges(projectId: string, filePath: string, edits: SuggestionEdit[]): Promise { + private suggestionVerifyDelaysMs: number[] = [0, 300, 700, 1500]; + + /** + * Experimental. Turn edits that already reached Overleaf as plain text + * (through git, `olcli push` or a sync) into tracked changes, as if they + * had been typed in Reviewing mode: each edit is undone without tracking + * and then redone with tracking (the update's `meta.tc`). The text ends up + * as it was, so a git clone that pushed the edit has nothing new to pull. + * + * Limits: sharejs-text-ot docs only; history-ot docs are refused. Between + * the undo and the redo, collaborators who have the doc open see the old + * text for a short moment (about 0.2 s on overleaf.com). The account needs + * edit access: the undo is an untracked edit, which review-only access + * cannot send. + * + * One result per edit, in order (see `SuggestionResult`). Edits that are + * invalid, unchanged, not pushed, not found or already tracked are left + * alone. After writing, the doc is read again and an edit without a + * tracked change is reported as `not-tracked` instead of `done`. With + * `expectedVersion` (from `planSuggestions`), a doc that changed since is + * refused with `RejectConflictError` and nothing is written. + */ + async suggestChanges(projectId: string, filePath: string, edits: SuggestionEdit[], options: { expectedVersion?: number } = {}): Promise { const docs = this.collectProjectDocs(await this.getProjectInfo(projectId)); const wanted = filePath.replace(/^\/+/, ''); const doc = docs.find(item => item.path.replace(/^\/+/, '') === wanted); @@ -2851,39 +2919,101 @@ export class OverleafClient { throw new Error(`Doc not found: ${filePath}`); } + const results: SuggestionResult[] = []; + const written: Array<{ index: number; seed: string; position: number; edit: SuggestionEdit }> = []; const session = await this.openProjectSocket(projectId); try { const joinedDoc = await this.joinDocument(session, doc.id); if (joinedDoc.type !== 'sharejs-text-ot') { throw new Error(`${doc.path}: turning edits into tracked changes is not supported for history-ot docs yet`); } + if (options.expectedVersion !== undefined && joinedDoc.version !== options.expectedVersion) { + throw new RejectConflictError(`${doc.path} changed since the preview (version ${options.expectedVersion} -> ${joinedDoc.version}); nothing was written, run it again`); + } const content = joinedDoc.content; + const changes = parseShareJsChanges(joinedDoc.ranges); + const level = session.permissionsLevel; + const canEdit = level === undefined || level === 'owner' || level === 'readAndWrite'; let version = joinedDoc.version; const send = async (op: ShareJsTextOp[], tc?: string) => { await this.socketRpc(session, 'applyOtUpdate', [doc.id, { doc: doc.id, op, v: version, ...(tc ? { meta: { tc } } : {}) }]); version++; }; - const results: SuggestionResult[] = []; for (const edit of edits) { - const from = edit.hint - edit.before.length; - const at = edit.inserted === edit.deleted ? -1 : nearestIndex(content, edit.before + edit.inserted + edit.after, from); - if (at === -1) { - results.push(nearestIndex(content, edit.before + edit.deleted + edit.after, from) === -1 ? 'not-found' : 'not-pushed'); + const match = matchSuggestionEdit(content, changes, edit); + if (match.outcome !== 'suggest') { + results.push(match.outcome === 'invalid' || match.outcome === 'unchanged' || match.outcome === 'not-pushed' + || match.outcome === 'not-found' || match.outcome === 'already-tracked' ? match.outcome : 'not-found'); continue; } - const p = at + edit.before.length; + // Refuse before the first write: a review-only account can send the tracked redo but not the untracked undo. + if (!canEdit) throw new SuggestionPermissionError(doc.path, `access level ${level}`); + const p = match.position!; // Each edit leaves the text as it found it, so the offsets of the next edits stay valid. const undo: ShareJsTextOp[] = [...(edit.inserted ? [{ p, d: edit.inserted }] : []), ...(edit.deleted ? [{ p, i: edit.deleted }] : [])]; const redo: ShareJsTextOp[] = [...(edit.deleted ? [{ p, d: edit.deleted }] : []), ...(edit.inserted ? [{ p, i: edit.inserted }] : [])]; - await send(undo); - await send(redo, trackChangesSeed()); + try { + await send(undo); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (/not authorized/.test(message)) { + throw new SuggestionPermissionError(doc.path, message); + } + if (/did not return an acknowledgement/.test(message)) { + // What a review-only account gets live: the server refuses the untracked undo and drops the socket. + throw new SuggestionPermissionError(doc.path, `${message}; if the account does have edit access, check ${doc.path} on Overleaf, since the undo may have arrived without the redo`); + } + throw error; + } + const seed = generateIdSeed(); + await send(redo, seed); + written.push({ index: results.length, seed, position: p, edit }); results.push('done'); + // A repeated edit in the same call must see this one as tracked. + if (edit.deleted) changes.push({ id: `${seed}-d`, kind: 'delete', position: p + edit.inserted.length, text: edit.deleted, userId: null }); + if (edit.inserted) changes.push({ id: `${seed}-i`, kind: 'insert', position: p, text: edit.inserted, userId: null }); } - return results; } finally { await this.closeProjectSocket(session); } + + if (written.length > 0) { + const unverified = await this.unverifiedSuggestions(projectId, doc.id, written); + for (const index of unverified) results[index] = 'not-tracked'; + } + return results; + } + + /** + * Read a doc again until every written suggestion shows up as a tracked + * change, or the read-back delays run out. Returns the result indexes that + * never showed up. A change counts when its id starts with the seed sent + * with the redo, or, since the ranges tracker merges an insert into an + * adjacent one by the same user, when a tracked change covers the edit. + */ + private async unverifiedSuggestions(projectId: string, docId: string, written: Array<{ index: number; seed: string; position: number; edit: SuggestionEdit }>): Promise { + let missing = written; + for (const delay of this.suggestionVerifyDelaysMs) { + if (delay > 0) await new Promise(resolve => setTimeout(resolve, delay)); + const session = await this.openProjectSocket(projectId); + let changes: DocTrackedChange[]; + try { + changes = parseShareJsChanges((await this.joinDocument(session, docId)).ranges); + } finally { + await this.closeProjectSocket(session); + } + missing = missing.filter(item => { + const { deleted, inserted } = item.edit; + const bySeed = (kind: 'insert' | 'delete') => changes.some(change => change.kind === kind && change.id.startsWith(item.seed)); + const parts = trackedParts(changes, item.position, deleted, inserted); + const insertOk = inserted === '' || bySeed('insert') || parts.insert; + const deleteOk = deleted === '' || bySeed('delete') || parts.delete; + return !(insertOk && deleteOk); + }); + if (missing.length === 0) break; + } + return missing.map(item => item.index); } async resolveComment(projectId: string, threadId: string): Promise { diff --git a/src/index.ts b/src/index.ts index 6b10a19..73a738f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -35,6 +35,9 @@ export { type AddCommentOptions, type SuggestionEdit, type SuggestionResult, + SuggestionPermissionError, + type SuggestionPlan, + type SuggestionOutcome, type TrackedChange, type ListTrackedChangesOptions, type ProjectReview, diff --git a/src/mcp-confirm.ts b/src/mcp-confirm.ts index 6130b29..4e34e92 100644 --- a/src/mcp-confirm.ts +++ b/src/mcp-confirm.ts @@ -290,7 +290,8 @@ export type ConfirmationOutcome = | 'timeout' | 'aborted' | 'error' - | 'unsupported'; + | 'unsupported' + | 'unsupported_no_cli'; /** What the agent is told when nothing was written, by outcome. */ export function outcomeMessage(outcome: ConfirmationOutcome, detail?: string): string { @@ -307,6 +308,8 @@ export function outcomeMessage(outcome: ConfirmationOutcome, detail?: string): s return 'The request was canceled while waiting for the user. Nothing was written to Overleaf.'; case 'error': return `The confirmation could not be shown or read${detail ? `: ${detail}` : ''}. Nothing was written to Overleaf.`; + case 'unsupported_no_cli': + return `This MCP client did not declare the elicitation capability, so olcli cannot ask the user to confirm this change. Nothing was written to Overleaf. There is no olcli command for this change yet, so show the preview to the user. To let this server write without asking, relying on the MCP client's own tool approval, the user can set ${UNCONFIRMED_WRITES_ENV}=1 in the server's environment.`; case 'unsupported': return `This MCP client did not declare the elicitation capability, so olcli cannot ask the user to confirm this change. Nothing was written to Overleaf. Show the preview and cli_command to the user: they can review it and apply it by running cli_command in a terminal where olcli is signed in. Run it yourself only if the user explicitly asks you to. To let this server write without asking, relying on the MCP client's own tool approval as olcli 0.15.0 did, the user can set ${UNCONFIRMED_WRITES_ENV}=1 in the server's environment.`; } diff --git a/src/mcp-server.ts b/src/mcp-server.ts index badebe2..737c95a 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -70,6 +70,7 @@ export const WRITE_TOOLS = [ 'resolve_comment', 'accept_tracked_changes', 'reject_tracked_changes', + 'suggest_changes', ] as const; /** MCP `instructions`: sent to the client once, at initialization. */ @@ -102,8 +103,8 @@ interface CallContext { interface WritePreview { /** Dialog text: what will happen, in terms the user can check. */ message: string; - /** The olcli command that performs the same write from a terminal. */ - cliCommand: string; + /** The olcli command that performs the same write from a terminal; undefined when there is none. */ + cliCommand?: string; /** Structured parts of the preview, returned to the agent when nothing is written. */ data?: Record; /** Performs the write. Called only after the user confirmed. */ @@ -257,8 +258,8 @@ export function createOlcliMcpServer(options: OlcliMcpServerOptions): McpServer return jsonResult({ applied: false, confirmation: 'unsupported', - message: outcomeMessage('unsupported'), - cli_command: prepared.cliCommand, + message: prepared.cliCommand === undefined ? outcomeMessage('unsupported_no_cli') : outcomeMessage('unsupported'), + ...(prepared.cliCommand === undefined ? {} : { cli_command: prepared.cliCommand }), opt_out_env: `${UNCONFIRMED_WRITES_ENV}=1`, preview: prepared.message, ...prepared.data, @@ -689,6 +690,92 @@ export function createOlcliMcpServer(options: OlcliMcpServerOptions): McpServer } ); + // ------------------------------------------------------------------------- + // Tool: suggest_changes (experimental) + // ------------------------------------------------------------------------- + + const SUGGESTION_NOTES: Record = { + suggest: 'becomes a suggestion', + 'already-tracked': 'already a tracked change, left alone', + 'not-pushed': 'Overleaf still has the old text, left alone', + 'not-found': 'neither the old nor the new text is in the document, left alone', + unchanged: 'old and new text are the same, left alone', + invalid: 'before, inserted and after are all empty, so it cannot be found, left alone', + }; + + server.registerTool( + 'suggest_changes', + { + description: `Experimental. Turn edits that are already on Overleaf as plain text (pushed through git, push_file or a sync) into tracked changes (suggestions) that collaborators can accept or reject, for projects with track changes. Each edit gives the old text (deleted), the new text (inserted) and some unchanged text right before and after it, so the new text can be found; hint is the approximate character offset of the edit and picks the nearest match. Olcli undoes each edit without tracking and redoes it with tracking, so the text ends up the same; collaborators with the document open see the old text for about 0.2 seconds. Only documents in the sharejs-text-ot format; history-ot documents are refused. Needs edit access to the project. Returns one result per edit: done, already-tracked, not-pushed, not-found, unchanged, invalid, or not-tracked (sent, but no tracked change showed up).${askNote}${CONTENT_NOTE}`, + inputSchema: { + project_id: z.string().describe('The Overleaf project ID'), + path: z.string().describe('Path of the document within the project (e.g. main.tex)'), + edits: z.array(z.object({ + before: z.string().describe('Unchanged text right before the edit'), + deleted: z.string().describe('The old text that the edit replaced (empty for a pure insertion)'), + inserted: z.string().describe('The new text, as it is on Overleaf now (empty for a pure deletion)'), + after: z.string().describe('Unchanged text right after the edit'), + hint: z.number().int().min(0).optional().describe('Approximate character offset of the edit in the document; the nearest match wins'), + })).min(1).max(100).describe('The edits to turn into suggestions'), + }, + annotations: WRITE(false, true), + }, + async ({ project_id, path, edits }, extra) => + gatedWrite( + extra, + async () => { + const client = await getClient(); + const results = await client.suggestChanges(project_id, path, edits); + return { path, results: edits.map((edit, index) => ({ ...edit, result: results[index] })) }; + }, + async () => { + const client = await getClient(); + const plan = await client.planSuggestions(project_id, path, edits); + const items = plan.edits.map((item, index) => ({ index: index + 1, outcome: item.outcome, line: item.line, column: item.column })); + const toSuggest = plan.edits.filter(item => item.outcome === 'suggest').length; + if (toSuggest === 0) { + return { + noWrite: { + applied: false, + message: 'None of the edits can become a suggestion, so nothing was asked and nothing was written.', + path: plan.path, + results: edits.map((edit, index) => ({ ...edit, result: plan.edits[index].outcome })), + }, + }; + } + const name = await projectName(client, project_id); + const lines = plan.edits.map((item, index) => { + const where = item.line !== undefined ? ` at ${inlineText(plan.path)}:${item.line}:${item.column}` : ''; + const head = `${index + 1}.${where}: ${SUGGESTION_NOTES[item.outcome] ?? item.outcome}`; + if (item.outcome !== 'suggest') return head; + const parts = [head]; + if (item.edit.deleted) parts.push(` suggested deletion: ${quoteInline(item.edit.deleted)}`); + if (item.edit.inserted) parts.push(` suggested insertion: ${quoteInline(item.edit.inserted)}`); + parts.push(` between ${quoteInline(item.edit.before)} and ${quoteInline(item.edit.after)}`); + return parts.join('\n'); + }); + const message = [ + `Turn ${countOf(toSuggest, 'edit')} in ${inlineText(plan.path)} into suggestions in Overleaf project ${projectLabel(project_id, name)} (experimental)`, + '', + 'The text stays the same. Each edit is briefly undone and redone as a tracked change, so collaborators with the document open see the old text for about 0.2 seconds. Afterwards anyone can accept or reject the suggestions.', + '', + 'Edits:', + lines.join('\n'), + ].join('\n'); + return { + message, + // No CLI command does this yet, so a client without elicitation gets the preview only. + data: { path: plan.path, edits: items }, + apply: async () => { + // Refuses to write if the doc moved since this preview. + const results = await client.suggestChanges(project_id, path, edits, { expectedVersion: plan.version }); + return { path: plan.path, results: edits.map((edit, index) => ({ ...edit, result: results[index] })) }; + }, + }; + }, + ) + ); + // ------------------------------------------------------------------------- // Tool: get_entities // ------------------------------------------------------------------------- diff --git a/src/tracked-changes.ts b/src/tracked-changes.ts index a95228b..de2ead3 100644 --- a/src/tracked-changes.ts +++ b/src/tracked-changes.ts @@ -300,3 +300,105 @@ export function formatAuthor(author: TrackedChangeAuthor): string { export function renderRejectionDiff(path: string, before: string, after: string): string { return createTwoFilesPatch(`a/${path}`, `b/${path}`, before, after, undefined, undefined, { context: 2 }); } + +/** + * An edit that was made outside Overleaf and pushed as plain text (through + * git, `olcli push` or a sync): `deleted` was replaced by `inserted` between + * `before` and `after`. `suggestChanges` turns it into a tracked change. + */ +export interface SuggestionEdit { + before: string; + after: string; + deleted: string; + inserted: string; + /** + * About where the edit is in the doc (offset of the edited text); the + * match nearest to it wins. Without it the first match wins. + */ + hint?: number; +} + +/** + * What `suggestChanges` does with one edit, decided from the doc alone: + * - `suggest`: the new text is there and not tracked yet; it becomes a suggestion. + * - `invalid`: `before`, `inserted` and `after` are all empty (or not strings), so there is nothing to find. + * - `unchanged`: `inserted` equals `deleted`; there is no edit. + * - `not-pushed`: Overleaf still has the old text. + * - `not-found`: neither the old nor the new text is there. + * - `already-tracked`: the new text is there and the edit, or part of it, is already a tracked change. + */ +export type SuggestionOutcome = 'suggest' | 'invalid' | 'unchanged' | 'not-pushed' | 'not-found' | 'already-tracked'; + +export interface SuggestionMatch { + outcome: SuggestionOutcome; + /** Offset of the edit in the visible text, for `suggest` and `already-tracked`. */ + position?: number; +} + +/** + * Offset of the occurrence of `needle` nearest to `hint`, or -1. An empty + * needle matches nowhere: it would match at every offset, which tells + * nothing about where an edit is. + */ +export function nearestIndex(text: string, needle: string, hint: number): number { + if (needle === '') return -1; + let best = -1; + for (let i = text.indexOf(needle); i !== -1; i = text.indexOf(needle, i + 1)) { + if (best === -1 || Math.abs(i - hint) < Math.abs(best - hint)) best = i; + } + return best; +} + +/** + * Which parts of an edit at `position` are tracked changes in `changes` + * (sharejs-text-ot, visible offsets): a tracked insert that covers the new + * text, and a tracked delete holding the old text right after it or at its + * start, where the ranges tracker puts the delete of a tracked replacement. + * With `anywhere`, position is ignored and any change with the text counts, + * for a doc that collaborators edited in the meantime. + */ +export function trackedParts(changes: DocTrackedChange[], position: number, deleted: string, inserted: string, anywhere = false): { insert: boolean; delete: boolean } { + const end = position + inserted.length; + return { + insert: inserted !== '' && changes.some(change => change.kind === 'insert' + && change.text.includes(inserted) + && (anywhere || (change.position <= position && change.position + change.text.length >= end))), + delete: deleted !== '' && changes.some(change => change.kind === 'delete' + && change.text.includes(deleted) + && (anywhere || change.position === end || change.position === position)) + }; +} + +/** Find one edit in a doc's visible text and decide what to do with it. */ +export function matchSuggestionEdit(content: string, changes: DocTrackedChange[], edit: SuggestionEdit): SuggestionMatch { + const { before, after, deleted, inserted } = edit ?? ({} as SuggestionEdit); + if (![before, after, deleted, inserted].every(part => typeof part === 'string')) return { outcome: 'invalid' }; + // The new text is searched as before + inserted + after; empty, it would match anywhere. + if (before === '' && after === '' && inserted === '') return { outcome: 'invalid' }; + if (inserted === deleted) return { outcome: 'unchanged' }; + const hint = typeof edit.hint === 'number' && Number.isFinite(edit.hint) ? edit.hint : 0; + const from = hint - before.length; + const at = nearestIndex(content, before + inserted + after, from); + if (at === -1) { + return { outcome: nearestIndex(content, before + deleted + after, from) === -1 ? 'not-found' : 'not-pushed' }; + } + const position = at + before.length; + const tracked = trackedParts(changes, position, deleted, inserted); + // Redoing an edit that is already (partly) tracked would track it twice: + // the old text would end up in the tracked delete two times. + if (tracked.insert || tracked.delete) return { outcome: 'already-tracked', position }; + return { outcome: 'suggest', position }; +} + +/** + * An 18-hex-digit id seed in the format of `RangesTracker.generateIdSeed` in + * Overleaf: 8 digits of seconds since the epoch, then 10 random digits. The + * server takes it as `meta.tc` and names the new tracked changes by it plus + * a 6-digit counter, the same shape as a Mongo ObjectId. + */ +export function generateIdSeed(now: number = Date.now(), random: () => number = Math.random): string { + const timestamp = Math.floor(now / 1000).toString(16).padStart(8, '0'); + const machine = Math.floor(random() * 16777216).toString(16).padStart(6, '0'); + const pid = Math.floor(random() * 32767).toString(16).padStart(4, '0'); + return `${timestamp}${machine}${pid}`; +} diff --git a/test/mcp.test.ts b/test/mcp.test.ts index af07b6e..b2a1dc7 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -202,7 +202,7 @@ test('every tool has annotations; write tools are not read-only and read tools a const fake = fakeClient(); const h = await connect(async () => fake); const { tools } = await h.client.listTools(); - assert.equal(tools.length, 21); + assert.equal(tools.length, 22); for (const tool of tools) { assert.ok(tool.annotations, `${tool.name} has annotations`); assert.equal(tool.annotations.openWorldHint, true, `${tool.name} openWorldHint`); @@ -399,6 +399,128 @@ test('reject_tracked_changes: apply true without elicitation -> CLI command with await h.close(); }); +/** + * A real OverleafClient with a stubbed socket holding "alpha beta delta." + * where "gamma" was replaced by "beta" as plain text. A tracked update adds + * the tracked delete and insert, as the ranges tracker would. + */ +function suggestClient() { + const client: any = new OverleafClient({ cookies: { session: 's' }, csrf: 'c' }); + const state = { content: 'alpha beta delta.\n', version: 3, changes: [] as any[], sent: [] as any[] }; + client.suggestionVerifyDelaysMs = [0]; + client.getProjectInfo = async () => ({ rootFolder: [{ docs: [{ _id: 'd1', name: 'main.tex' }], folders: [] }] }); + client.getProjectById = async (id: string) => ({ id, name: 'Paper' }); + client.openProjectSocket = async () => ({ permissionsLevel: 'owner' }); + client.closeProjectSocket = async () => {}; + client.joinDocument = async (_s: object, docId: string) => ({ + docId, content: state.content, lines: [], version: state.version, type: 'sharejs-text-ot', ranges: { changes: JSON.parse(JSON.stringify(state.changes)) }, + }); + client.socketRpc = async (_s: object, name: string, args: any[]) => { + const update = args[1]; + state.sent.push({ name, update }); + state.content = applyTextOps(state.content, update.op); + if (update.meta?.tc) { + state.changes.push({ id: `${update.meta.tc}000001`, op: { d: 'gamma', p: 10 }, metadata: { user_id: 'u1' } }); + state.changes.push({ id: `${update.meta.tc}000002`, op: { i: 'beta', p: 6 }, metadata: { user_id: 'u1' } }); + } + state.version++; + return []; + }; + return { client, state }; +} + +const SUGGEST_EDIT = { before: 'alpha ', deleted: 'gamma', inserted: 'beta', after: ' delta', hint: 6 }; + +test('suggest_changes: confirmed -> done; the dialog shows each edit and what is left alone', async () => { + const { client, state } = suggestClient(); + const h = await connect(async () => client); + const result = await h.call('suggest_changes', { project_id: PROJECT, path: 'main.tex', edits: [SUGGEST_EDIT, { before: 'zz', deleted: 'a', inserted: 'b', after: 'zz' }] }); + assert.equal(result.isError, false, result.text[0]); + assert.equal(h.dialogs.length, 1); + const message = h.dialogs[0].message; + assert.match(message, /Turn 1 edit in main\.tex into suggestions in Overleaf project "Paper" \(6ad7a5fe455ae390791ca9ef\) \(experimental\)/); + assert.match(message, /1\. at main\.tex:1:7: becomes a suggestion\n {3}suggested deletion: "gamma"\n {3}suggested insertion: "beta"\n {3}between "alpha " and " delta"/); + assert.match(message, /2\.: neither the old nor the new text is in the document, left alone/); + assert.match(message, /about 0\.2 seconds/); + assert.deepEqual(result.json.results.map((r: any) => r.result), ['done', 'not-found']); + assert.equal(state.sent.length, 2); + assert.equal(state.sent[0].update.meta, undefined); + assert.match(state.sent[1].update.meta.tc, /^[0-9a-f]{18}$/); + await h.close(); +}); + +test('suggest_changes: declined -> nothing sent', async () => { + const { client, state } = suggestClient(); + const h = await connect(async () => client, { answer: { action: 'decline' } }); + const result = await h.call('suggest_changes', { project_id: PROJECT, path: 'main.tex', edits: [SUGGEST_EDIT] }); + assert.equal(result.json.confirmation, 'declined'); + assert.equal(state.sent.length, 0); + await h.close(); +}); + +test('suggest_changes: an edit that is already tracked asks nothing and sends nothing', async () => { + const { client, state } = suggestClient(); + const h = await connect(async () => client); + await h.call('suggest_changes', { project_id: PROJECT, path: 'main.tex', edits: [SUGGEST_EDIT] }); + const again = await h.call('suggest_changes', { project_id: PROJECT, path: 'main.tex', edits: [SUGGEST_EDIT] }); + assert.equal(h.dialogs.length, 1, 'only the first call asks'); + assert.equal(again.json.applied, false); + assert.deepEqual(again.json.results.map((r: any) => r.result), ['already-tracked']); + assert.equal(state.sent.length, 2); + await h.close(); +}); + +test('suggest_changes: a doc that changed after the preview is not written', async () => { + const { client, state } = suggestClient(); + const h = await connect(async () => client); + const plan = client.planSuggestions.bind(client); + client.planSuggestions = async (...args: any[]) => { + const result = await plan(...args); + state.version++; + return result; + }; + const result = await h.call('suggest_changes', { project_id: PROJECT, path: 'main.tex', edits: [SUGGEST_EDIT] }); + assert.equal(result.isError, true); + assert.match(result.text[0], /changed since the preview/); + assert.equal(state.sent.length, 0); + await h.close(); +}); + +test('suggest_changes: client without elicitation -> nothing sent, preview without a CLI command', async () => { + const { client, state } = suggestClient(); + const h = await connect(async () => client, { elicitation: false }); + const result = await h.call('suggest_changes', { project_id: PROJECT, path: 'main.tex', edits: [SUGGEST_EDIT] }); + assert.equal(result.json.confirmation, 'unsupported'); + assert.equal(result.json.cli_command, undefined); + assert.match(result.json.message, /no olcli command for this change/); + assert.match(result.json.preview, /becomes a suggestion/); + assert.equal(state.sent.length, 0); + await h.close(); +}); + +test('suggest_changes: env opt-out writes without a dialog', async () => { + const { client, state } = suggestClient(); + const h = await connect(async () => client, { env: { [UNCONFIRMED_WRITES_ENV]: '1' } }); + const result = await h.call('suggest_changes', { project_id: PROJECT, path: 'main.tex', edits: [SUGGEST_EDIT] }); + assert.equal(h.dialogs.length, 0); + assert.deepEqual(result.json.results.map((r: any) => r.result), ['done']); + assert.equal(state.sent.length, 2); + await h.close(); +}); + +test('suggest_changes: the schema requires project_id, path and edits; the description says experimental', async () => { + const h = await connect(async () => fakeClient()); + const { tools } = await h.client.listTools(); + await h.close(); + const tool = tools.find(item => item.name === 'suggest_changes')!; + assert.deepEqual(tool.inputSchema.required, ['project_id', 'path', 'edits']); + assert.match(tool.description ?? '', /^Experimental\./); + assert.match(tool.description ?? '', /for projects with track changes/); + assert.match(tool.description ?? '', /history-ot documents are refused/); + assert.doesNotMatch(tool.description ?? '', /premium/); + assert.equal(tool.annotations?.readOnlyHint, false); +}); + test('push_file: dialog shows path, size and the diff against the remote file', async () => { const fake = fakeClient(); const local = tempFile('main.tex', '\\section{Intro}\nnew line\n'); diff --git a/test/tracked-changes.test.ts b/test/tracked-changes.test.ts index 34a1a8e..dd9ba32 100644 --- a/test/tracked-changes.test.ts +++ b/test/tracked-changes.test.ts @@ -8,9 +8,11 @@ import { parseHistoryOtChanges, parseShareJsChanges, planRejection, - RejectConflictError + RejectConflictError, + nearestIndex, + generateIdSeed } from '../src/tracked-changes.js'; -import { OverleafClient } from '../src/client.js'; +import { OverleafClient, SuggestionPermissionError } from '../src/client.js'; test('parseShareJsChanges reads inserts and deletes and skips malformed entries', () => { const changes = parseShareJsChanges({ @@ -235,14 +237,46 @@ test('not found error explains premium only when the project has no tracked chan await assert.rejects(some.client.acceptTrackedChanges('p', ['x']), (err: Error) => /not found: x$/.test(err.message)); }); -test('suggestChanges undoes a pushed edit untracked, redoes it tracked, and leaves unpushed edits alone', async () => { +/** + * A client whose socket is a small stand-in for Overleaf: it applies the ops + * to the text and, for an update with `meta.tc`, records a tracked delete + * and insert the way the ranges tracker names them (seed plus counter). + * `track: false` drops the tracking, like a server that ignored `meta.tc`. + */ +function suggestionClient(content: string, options: { ranges?: any; track?: boolean; permissionsLevel?: string; rejectUntracked?: 'error' | 'no-ack' } = {}) { const client: any = new OverleafClient({ cookies: {}, csrf: 'c' }); + const state = { content, version: 7, ranges: options.ranges ?? { changes: [] as any[] }, sent: [] as any[], joins: 0 }; + client.suggestionVerifyDelaysMs = [0, 0]; client.getProjectInfo = async () => ({ rootFolder: [{ docs: [{ _id: 'd1', name: 'main.tex' }], folders: [] }] }); - client.openProjectSocket = async () => ({}); + client.openProjectSocket = async () => (options.permissionsLevel ? { permissionsLevel: options.permissionsLevel } : {}); client.closeProjectSocket = async () => {}; - client.joinDocument = async () => ({ docId: 'd1', content: 'The new cat sat. The new dog.', lines: [], version: 7, type: 'sharejs-text-ot', ranges: {} }); - const sent: any[] = []; - client.socketRpc = async (_s: object, name: string, args: any[]) => { sent.push([name, args[1]]); return []; }; + client.joinDocument = async () => { + state.joins++; + return { docId: 'd1', content: state.content, lines: [], version: state.version, type: 'sharejs-text-ot', ranges: JSON.parse(JSON.stringify(state.ranges)) }; + }; + client.socketRpc = async (_s: object, name: string, args: any[]) => { + const update = args[1]; + if (!update.meta?.tc && options.rejectUntracked === 'error') throw new Error(`${name} failed: not authorized`); + if (!update.meta?.tc && options.rejectUntracked === 'no-ack') throw new Error(`${name} did not return an acknowledgement`); + state.sent.push([name, update]); + state.content = applyTextOps(state.content, update.op); + if (update.meta?.tc && options.track !== false) { + let counter = 0; + const id = () => `${update.meta.tc}${(++counter).toString(16).padStart(6, '0')}`; + const del = update.op.find((op: any) => typeof op.d === 'string'); + const ins = update.op.find((op: any) => typeof op.i === 'string'); + if (del) state.ranges.changes.push({ id: id(), op: { d: del.d, p: del.p + (ins ? ins.i.length : 0) }, metadata: { user_id: 'u1' } }); + if (ins) state.ranges.changes.push({ id: id(), op: { i: ins.i, p: ins.p }, metadata: { user_id: 'u1' } }); + } + state.version++; + return []; + }; + return { client, state }; +} + +test('suggestChanges undoes a pushed edit untracked, redoes it tracked, and leaves unpushed edits alone', async () => { + const { client, state } = suggestionClient('The new cat sat. The new dog.'); + const sent = state.sent; const res = await client.suggestChanges('p', '/main.tex', [ { before: 'The ', deleted: 'old', inserted: 'new', after: ' dog', hint: 21 }, @@ -257,6 +291,96 @@ test('suggestChanges undoes a pushed edit untracked, redoes it tracked, and leav assert.deepEqual(sent[1][1].op, [{ p: 21, d: 'old' }, { p: 21, i: 'new' }]); assert.match(sent[1][1].meta.tc, /^[0-9a-f]{18}$/); assert.deepEqual([sent[0][1].v, sent[1][1].v], [7, 8]); + assert.equal(state.content, 'The new cat sat. The new dog.'); +}); + +test('suggestChanges: an edit with nothing to search for returns invalid instead of hanging', async () => { + const { client, state } = suggestionClient('alpha gamma delta'); + const res = await Promise.race([ + client.suggestChanges('p', 'main.tex', [ + { before: '', deleted: 'gamma ', inserted: '', after: '', hint: 6 }, + { before: '', deleted: '', inserted: '', after: '', hint: 0 } + ]), + new Promise((_, reject) => setTimeout(() => reject(new Error('suggestChanges hung')), 2000)) + ]); + assert.deepEqual(res, ['invalid', 'invalid']); + assert.equal(state.sent.length, 0); +}); + +test('nearestIndex returns -1 for an empty needle instead of looping', () => { + assert.equal(nearestIndex('abc', '', 3), -1); + assert.equal(nearestIndex('abcabc', 'bc', 4), 4); + assert.equal(nearestIndex('abc', 'x', 0), -1); +}); + +test('suggestChanges: the same edit twice is done, then already-tracked, and sent once', async () => { + const { client, state } = suggestionClient('alpha beta delta.'); + const edit = { before: 'alpha ', deleted: 'gamma', inserted: 'beta', after: ' delta', hint: 6 }; + assert.deepEqual(await client.suggestChanges('p', 'main.tex', [edit]), ['done']); + assert.deepEqual(await client.suggestChanges('p', 'main.tex', [edit]), ['already-tracked']); + assert.equal(state.sent.length, 2, 'one undo and one redo in total'); + assert.deepEqual(state.ranges.changes.map((c: any) => c.op), [{ d: 'gamma', p: 10 }, { i: 'beta', p: 6 }], 'the delete is not doubled'); + // In one call, a repeated edit is caught too. + const again = suggestionClient('alpha beta delta.'); + assert.deepEqual(await again.client.suggestChanges('p', 'main.tex', [edit, edit]), ['done', 'already-tracked']); + assert.equal(again.state.sent.length, 2); +}); + +test('suggestChanges: a pure insert or delete that is already tracked is not sent again', async () => { + const ins = suggestionClient('a new b', { ranges: { changes: [{ id: 'x1', op: { i: 'new ', p: 2 }, metadata: {} }] } }); + assert.deepEqual(await ins.client.suggestChanges('p', 'main.tex', [{ before: 'a ', deleted: '', inserted: 'new ', after: 'b', hint: 2 }]), ['already-tracked']); + const del = suggestionClient('a b', { ranges: { changes: [{ id: 'x2', op: { d: 'old ', p: 2 }, metadata: {} }] } }); + assert.deepEqual(await del.client.suggestChanges('p', 'main.tex', [{ before: 'a ', deleted: 'old ', inserted: '', after: 'b', hint: 2 }]), ['already-tracked']); + assert.equal(ins.state.sent.length + del.state.sent.length, 0); +}); + +test('suggestChanges: reports not-tracked when the doc has no tracked change after writing', async () => { + const { client, state } = suggestionClient('alpha beta delta.', { track: false }); + const res = await client.suggestChanges('p', 'main.tex', [{ before: 'alpha ', deleted: 'gamma', inserted: 'beta', after: ' delta', hint: 6 }]); + assert.deepEqual(res, ['not-tracked']); + assert.equal(state.sent.length, 2); + assert.equal(state.joins, 3, 'one join to plan, then one read-back per delay'); + assert.equal(state.content, 'alpha beta delta.', 'the text is as before'); +}); + +test('suggestChanges: review-only access is refused with a permission error before anything is sent', async () => { + const known = suggestionClient('alpha beta delta.', { permissionsLevel: 'review' }); + await assert.rejects( + known.client.suggestChanges('p', 'main.tex', [{ before: 'alpha ', deleted: 'gamma', inserted: 'beta', after: ' delta', hint: 6 }]), + (err: Error) => err.name === 'SuggestionPermissionError' && /needs edit access/.test(err.message) && /review-only access cannot/.test(err.message) + ); + assert.equal(known.state.sent.length, 0); + for (const mode of ['error', 'no-ack'] as const) { + const live = suggestionClient('alpha beta delta.', { rejectUntracked: mode }); + await assert.rejects( + live.client.suggestChanges('p', 'main.tex', [{ before: 'alpha ', deleted: 'gamma', inserted: 'beta', after: ' delta', hint: 6 }]), + (err: Error) => err instanceof SuggestionPermissionError && /needs edit access/.test(err.message), + mode + ); + assert.equal(live.state.sent.length, 0, `${mode}: no tracked redo after a refused undo`); + } +}); + +test('generateIdSeed: 18 hex digits, the first 8 are the current time in seconds', () => { + const seed = generateIdSeed(); + assert.match(seed, /^[0-9a-f]{18}$/); + const seconds = parseInt(seed.slice(0, 8), 16); + assert.ok(Math.abs(seconds - Date.now() / 1000) < 5, `timestamp part ${seconds}`); + assert.equal(generateIdSeed(0x6a000000 * 1000, () => 0), '6a0000000000000000'); + assert.equal(generateIdSeed(1000, () => 0.999999999), '00000001ffffff7ffe'); +}); + +test('suggestChanges sends meta.tc with a timestamp seed', async () => { + const { client, state } = suggestionClient('alpha beta delta.'); + await client.suggestChanges('p', 'main.tex', [{ before: 'alpha ', deleted: 'gamma', inserted: 'beta', after: ' delta', hint: 6 }]); + const tc = state.sent[1][1].meta.tc; + assert.ok(Math.abs(parseInt(tc.slice(0, 8), 16) - Date.now() / 1000) < 5); +}); + +test('suggestChanges: inserted equal to deleted is unchanged, not not-pushed', async () => { + const { client, state } = suggestionClient('alpha beta delta.'); + assert.deepEqual(await client.suggestChanges('p', 'main.tex', [{ before: 'alpha ', deleted: 'beta', inserted: 'beta', after: ' delta', hint: 6 }]), ['unchanged']); + assert.equal(state.sent.length, 0); }); test('suggestChanges refuses history-ot docs', async () => {