Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

What changed: compare a bot's edit with the person's document; what_changed tool; keep uploads as sent (#6867)

Milind Soni9f500468416d
diff --git a/scripts/bundle-server.mjs b/scripts/bundle-server.mjs
index 3a3f2ca5b5..a7e7c3a72d 100644
--- a/scripts/bundle-server.mjs
+++ b/scripts/bundle-server.mjs
@@ -32,6 +32,7 @@ const NODE_REQUIRE = {
const ENTRY_POINTS = [
"index.ts",
"message-search.worker.ts",
+ "text-changes.worker.ts",
// the `openmausbot` command
"openmausbot.ts",
"pair-cli.ts",
diff --git a/server/activity.ts b/server/activity.ts
index 0bc48f2afc..70a4b852dd 100644
--- a/server/activity.ts
+++ b/server/activity.ts
@@ -94,6 +94,7 @@ const TEAM_ACTION_KEYS: Record<string, string> = {
decide: "activity.tool.team.decide",
delegate_bot: "activity.tool.team.delegateBot",
extract: "activity.tool.team.extract",
+ what_changed: "activity.tool.team.whatChanged",
fill_login: "activity.tool.team.fillLogin",
find_tool: "activity.tool.team.findTool",
generate_image: "activity.tool.team.generateImage",
diff --git a/server/agent-tool-policy.test.ts b/server/agent-tool-policy.test.ts
index 07478dee50..be4fef3e8c 100644
--- a/server/agent-tool-policy.test.ts
+++ b/server/agent-tool-policy.test.ts
@@ -18,6 +18,7 @@ describe("built-in agent tool read policy", () => {
"skills_list",
"list_unread_notifications",
"usage_limits",
+ "what_changed",
]);
for (const name of READ_ONLY_AGENT_TOOL_NAMES) {
expect(isReadOnlyAgentTool(name)).toBe(true);
diff --git a/server/agent-tool-policy.ts b/server/agent-tool-policy.ts
index f70cba2cd6..78a5d3a3e0 100644
--- a/server/agent-tool-policy.ts
+++ b/server/agent-tool-policy.ts
@@ -15,6 +15,7 @@ export const READ_ONLY_AGENT_TOOL_NAMES: ReadonlySet<string> = new Set([
"skills_list",
"list_unread_notifications",
"usage_limits",
+ "what_changed",
]);
export const READ_ONLY_ANNOTATIONS = Object.freeze({
diff --git a/server/attachment-originals.test.ts b/server/attachment-originals.test.ts
new file mode 100644
index 0000000000..414a5be716
--- /dev/null
+++ b/server/attachment-originals.test.ts
@@ -0,0 +1,78 @@
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { dropKeptOriginals, dropOrphanKeptOriginals, KEEP_MAX_BYTES, keepUploadedOriginal, keptOriginal, keptOriginalsBytes, keptOriginalsDir } from "./attachment-originals.ts";
+
+const name = (n: number, ext = "md") => `${n.toString(16).padStart(8, "0")}-1a2b-4c3d-8e4f-0a1b2c3d4e5f.${ext}`;
+
+describe("kept originals", () => {
+ let root: string, store: string, kept: string;
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "kept-originals-"));
+ store = join(root, "data", "attachments");
+ kept = keptOriginalsDir(join(root, "data"));
+ mkdirSync(store, { recursive: true });
+ });
+ afterEach(() => rmSync(root, { recursive: true, force: true }));
+
+ it("keeps what the person sent as it arrives, through an in-place write and a rename over it", async () => {
+ const upload = join(store, name(1));
+ writeFileSync(upload, "as sent");
+ await keepUploadedOriginal(upload, kept);
+ expect(keptOriginal(upload, store, kept)).toBe(join(kept, name(1)));
+
+ writeFileSync(upload, "edited in place");
+ expect(readFileSync(keptOriginal(upload, store, kept)!, "utf8")).toBe("as sent");
+ writeFileSync(`${upload}.tmp`, "saved by rename");
+ renameSync(`${upload}.tmp`, upload);
+ expect(readFileSync(keptOriginal(upload, store, kept)!, "utf8")).toBe("as sent");
+
+ // Sending the same upload again never replaces the kept copy with an edit.
+ await keepUploadedOriginal(upload, kept);
+ expect(readFileSync(join(kept, name(1)), "utf8")).toBe("as sent");
+ });
+
+ it("keeps only documents from the store, within the size limit", async () => {
+ const video = join(store, name(2, "mp4")), big = join(store, name(3, "txt"));
+ writeFileSync(video, "video");
+ writeFileSync(big, Buffer.alloc(KEEP_MAX_BYTES + 1));
+ await keepUploadedOriginal(video, kept);
+ await keepUploadedOriginal(big, kept);
+ await keepUploadedOriginal(join(root, "someone's own.md"), kept);
+ expect(existsSync(kept) ? readdirSync(kept) : []).toEqual([]);
+ expect(keptOriginal(join(root, name(1)), store, kept)).toBeNull();
+ });
+
+ it("makes room by dropping the oldest copies when the folder is full, never by keeping nothing", async () => {
+ mkdirSync(kept, { recursive: true });
+ const old = join(kept, name(4)), newer = join(kept, name(5));
+ writeFileSync(old, Buffer.alloc(50));
+ writeFileSync(newer, Buffer.alloc(40));
+ utimesSync(old, new Date(1_000_000), new Date(1_000_000));
+ const upload = join(store, name(6));
+ writeFileSync(upload, "the newest upload");
+ await keepUploadedOriginal(upload, kept, 100);
+ expect(readdirSync(kept).sort()).toEqual([name(5), name(6)].sort());
+ });
+
+ it("is counted in the storage figure and goes with its upload, or at a clear once its upload is gone", async () => {
+ const upload = join(store, name(7)), orphan = join(store, name(8));
+ writeFileSync(upload, "as sent");
+ writeFileSync(orphan, "removed outside the app");
+ await keepUploadedOriginal(upload, kept);
+ await keepUploadedOriginal(orphan, kept);
+ expect(keptOriginalsBytes(kept)).toBe("as sent".length + "removed outside the app".length);
+ rmSync(orphan);
+ expect(dropOrphanKeptOriginals(store, kept)).toBe(1);
+ dropKeptOriginals([name(7), "../escape.md"], kept);
+ expect(keptOriginal(upload, store, kept)).toBeNull();
+ expect(keptOriginalsBytes(kept)).toBe(0);
+ });
+
+ it("never fails the upload when the copy cannot be made", async () => {
+ writeFileSync(join(root, "not-a-folder"), "");
+ await expect(keepUploadedOriginal(join(store, name(9)), join(root, "not-a-folder", "kept"))).resolves.toBeUndefined();
+ });
+});
diff --git a/server/attachment-originals.ts b/server/attachment-originals.ts
new file mode 100644
index 0000000000..415562dac5
--- /dev/null
+++ b/server/attachment-originals.ts
@@ -0,0 +1,104 @@
+import { constants, existsSync, readdirSync, rmSync, statSync } from "node:fs";
+import { copyFile, mkdir, readdir, rename, rm, stat } from "node:fs/promises";
+import { basename, dirname, join, resolve } from "node:path";
+import { DATA_DIR } from "./config.ts";
+
+/**
+ * Without the bot box (or outside a conversation's own folder) a turn names the person's upload by its place in the
+ * attachment store, and an engine with file tools can save its edit over it, in place or by renaming a new file over
+ * it. So each document the person uploads is copied once, as it arrives and before any turn can see it, into this
+ * private folder that no turn is told about. The person's own message and the original side of a comparison read the
+ * copy, which is exactly what they sent. Only documents a bot might edit, up to KEEP_MAX_BYTES each; when the folder
+ * reaches KEPT_TOTAL_MAX_BYTES the oldest copies make room. A copy goes when its upload does.
+ */
+export const keptOriginalsDir = (dataDir: string) => join(dataDir, "attachment-originals");
+export const KEPT_ORIGINALS_DIR = keptOriginalsDir(DATA_DIR);
+export const KEEP_MAX_BYTES = 4 * 1024 * 1024;
+export const KEPT_TOTAL_MAX_BYTES = 256 * 1024 * 1024;
+
+const STORED_NAME = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.([a-z0-9]+)$/i;
+const DOCUMENT = new Set(["md", "txt", "csv", "tsv", "json", "rtf", "doc", "docx", "odt", "xls", "xlsx", "ods", "ppt", "pptx", "odp"]);
+
+export function isKeptDocumentName(name: string): boolean {
+ const match = STORED_NAME.exec(name);
+ return Boolean(match && DOCUMENT.has(match[1]!.toLowerCase()));
+}
+
+/** What the folder holds, for Settings › General's storage figure. */
+export function keptOriginalsBytes(keptDir = KEPT_ORIGINALS_DIR): number {
+ let total = 0;
+ let names: string[] = [];
+ try { names = readdirSync(keptDir); } catch { return 0; }
+ for (const name of names) {
+ try { total += statSync(join(keptDir, name)).size; } catch { /* gone meanwhile */ }
+ }
+ return total;
+}
+
+/** Oldest copies first, until `size` more bytes fit under the total. */
+async function makeRoom(keptDir: string, size: number, total: number): Promise<void> {
+ const files = (await Promise.all((await readdir(keptDir).catch(() => [] as string[])).map(async (name) => {
+ const info = await stat(join(keptDir, name)).catch(() => null);
+ return info?.isFile() ? { name, size: info.size, at: info.mtimeMs } : null;
+ }))).filter((file): file is { name: string; size: number; at: number } => file !== null);
+ let used = files.reduce((sum, file) => sum + file.size, 0);
+ for (const file of files.sort((a, b) => a.at - b.at)) {
+ if (used + size <= total) return;
+ await rm(join(keptDir, file.name), { force: true }).catch(() => undefined);
+ used -= file.size;
+ }
+}
+
+/** Keeps a copy of an upload the person just sent, before any turn names it. Never throws into the upload. */
+export async function keepUploadedOriginal(path: string, keptDir = KEPT_ORIGINALS_DIR, total = KEPT_TOTAL_MAX_BYTES): Promise<void> {
+ const name = basename(path);
+ if (!isKeptDocumentName(name)) return;
+ const target = join(keptDir, name);
+ const partial = `${target}.${process.pid}.partial`;
+ try {
+ if (existsSync(target)) return;
+ const { size } = await stat(path);
+ if (size > KEEP_MAX_BYTES) return;
+ await mkdir(keptDir, { recursive: true, mode: 0o700 });
+ await makeRoom(keptDir, size, total);
+ // A clone where the file system has them (APFS, Btrfs): no bytes are copied until one side changes.
+ await copyFile(path, partial, constants.COPYFILE_FICLONE | constants.COPYFILE_EXCL);
+ await rename(partial, target);
+ } catch {
+ // The upload stands; it simply has no kept copy, and a comparison says so.
+ } finally {
+ await rm(partial, { force: true }).catch(() => undefined);
+ }
+}
+
+/** The kept copy of a stored upload, or null when there is none. */
+export function keptOriginal(path: string, attachmentsDir: string, keptDir = KEPT_ORIGINALS_DIR): string | null {
+ const name = basename(path);
+ if (resolve(dirname(path)) !== resolve(attachmentsDir) || !isKeptDocumentName(name)) return null;
+ const target = join(keptDir, name);
+ return existsSync(target) ? target : null;
+}
+
+export function dropKeptOriginals(names: readonly string[], keptDir = KEPT_ORIGINALS_DIR): void {
+ for (const name of names) {
+ if (!isKeptDocumentName(name)) continue;
+ try {
+ rmSync(join(keptDir, name), { force: true });
+ } catch { /* a busy file on Windows stays until the next removal */ }
+ }
+}
+
+/** Copies whose upload is gone (removed outside the app, or while a copy was busy): Settings' Clear removes them. */
+export function dropOrphanKeptOriginals(attachmentsDir: string, keptDir = KEPT_ORIGINALS_DIR): number {
+ let names: string[] = [];
+ try { names = readdirSync(keptDir); } catch { return 0; }
+ let removed = 0;
+ for (const name of names) {
+ if (name.endsWith(".partial") || existsSync(join(attachmentsDir, name))) continue;
+ try {
+ rmSync(join(keptDir, name), { force: true });
+ removed += 1;
+ } catch { /* tried again at the next clear */ }
+ }
+ return removed;
+}
diff --git a/server/attachments.ts b/server/attachments.ts
index d65b7b8dd5..a4adf65e0f 100644
--- a/server/attachments.ts
+++ b/server/attachments.ts
@@ -14,6 +14,7 @@ import { link, open, unlink } from "node:fs/promises";
import { basename, dirname, extname, join, resolve } from "node:path";
import { FILE_MAX_BYTES, PREVIEW_MAX_BYTES } from "../shared/upload-limits.ts";
import { DATA_DIR } from "./config.ts";
+import { dropKeptOriginals, dropOrphanKeptOriginals, keepUploadedOriginal, keptOriginalsBytes } from "./attachment-originals.ts";
import { boxUploadsDir } from "./bot-box/plan.ts";
export { FILE_MAX_BYTES, PREVIEW_MAX_BYTES } from "../shared/upload-limits.ts";
@@ -213,13 +214,16 @@ export function deleteAttachment(path: string): void {
// An upload still on disk (a busy file on Windows) keeps its box copies; one already gone loses them.
if ((error as NodeJS.ErrnoException).code !== "ENOENT") return;
}
- if (resolve(dirname(path)) === resolve(ATTACHMENTS_DIR)) dropBoxUploadCopies([basename(path)]);
+ if (resolve(dirname(path)) === resolve(ATTACHMENTS_DIR)) {
+ dropBoxUploadCopies([basename(path)]);
+ dropKeptOriginals([basename(path)]);
+ }
}
/** Settings → General: what the store holds against its ceiling, rescanned so files removed outside the app count. */
export function attachmentStorageUsage(): { usedBytes: number; maxBytes: number } {
invalidateAttachmentAccounting();
- return { usedBytes: committedBytes(), maxBytes: ATTACHMENTS_MAX_BYTES };
+ return { usedBytes: committedBytes() + keptOriginalsBytes(), maxBytes: ATTACHMENTS_MAX_BYTES };
}
/** What a Settings clear leaves, as stored names: pictures given by their /api/attachments/ url (bot and profile
@@ -267,6 +271,8 @@ export function clearAttachments(kept: ReadonlySet<string>, now = Date.now()): {
}
}
dropBoxUploadCopies(gone);
+ dropKeptOriginals(gone);
+ dropOrphanKeptOriginals(ATTACHMENTS_DIR);
invalidateAttachmentAccounting();
return { removed, freedBytes, failed };
}
@@ -447,7 +453,8 @@ export async function saveFile(
chunks: AsyncIterable<Uint8Array>,
originalName: string,
mime: string,
- options: { uploadId?: string; expectedBytes?: number } = {},
+ /** keepOriginal: the person's own upload, kept as sent (attachment-originals.ts). */
+ options: { uploadId?: string; expectedBytes?: number; keepOriginal?: boolean } = {},
): Promise<SavedFile> {
const known = extensionForFileMime(mime);
const normalized = known ? normalizedMime(mime)! : GENERIC_FILE_MIME;
@@ -532,6 +539,7 @@ export async function saveFile(
}
await unlink(partialPath);
}
+ if (options.keepOriginal) await keepUploadedOriginal(path);
return { path, name, mime: normalized, bytes };
} catch (error) {
if (file && !closed) await file.close().catch(() => undefined);
diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.ts
index 3d21fce1b5..01b164ac69 100644
--- a/server/drivers/agents-call.ts
+++ b/server/drivers/agents-call.ts
@@ -19,6 +19,7 @@ import { argumentNames, outOfBounds } from "./agents-schema.ts";
import { dropBlankArguments } from "./agents-blank-arguments.ts";
import { callResearchTool, RESEARCH_TOOL_NAMES } from "./agents-research-tools.ts";
import { callHelperTool, HELPER_TOOL_NAMES } from "./agents-helper-tools.ts";
+import { callWhatChangedTool, WHAT_CHANGED_TOOL } from "./agents-what-changed-tool.ts";
import { callUsageLimitsTool, USAGE_LIMITS_TOOL } from "./agents-usage-tool.ts";
import { callThreadPostTool, THREAD_POST_TOOL } from "./agents-thread-post-tool.ts"; import { callListThreadsTool, LIST_THREADS_TOOL } from "./agents-list-threads-tool.ts"; import { callRenameThreadTool, RENAME_THREAD_TOOL } from "./agents-thread-title-tool.ts";
import { callWaitTool, WAIT_TOOL_NAMES } from "./agents-wait-tools.ts"; import { callCheckBackTool, CHECK_BACK_TOOL_NAMES } from "./agents-check-back-tool.ts";
@@ -246,6 +247,7 @@ export async function callTool(called: string, input: Json, context: ToolCallCon
if (CARD_TOOL_NAMES.has(name)) return callCardTool(name, args, context);
if (RESEARCH_TOOL_NAMES.has(name)) return callResearchTool(name, args, context);
if (HELPER_TOOL_NAMES.has(name)) return callHelperTool(name, args, context);
+ if (name === WHAT_CHANGED_TOOL) return callWhatChangedTool(args, context);
if (IMAGE_TOOL_NAMES.has(name)) return callImageTool(name, args, context);
if (HOSTING_TOOL_NAMES.has(name)) return callHostingTool(name, args, context);
if (MEETING_TOOL_NAMES.has(name)) return callMeetingTool(name, args, context);
diff --git a/server/drivers/agents-catalog-goldens/bridged.profiles.json b/server/drivers/agents-catalog-goldens/bridged.profiles.json
index a4c452519e..f9ba78d9fe 100644
--- a/server/drivers/agents-catalog-goldens/bridged.profiles.json
+++ b/server/drivers/agents-catalog-goldens/bridged.profiles.json
@@ -1,7 +1,7 @@
{
"default": {
- "bytes": 18042,
- "sha256": "77e381efdb38f4f5baf0d7713b97b3d5fdbf59771ef282e137b14c11d84337e9",
+ "bytes": 18056,
+ "sha256": "4b60038ce6c1ba27fa969c87a7d14ef560b88544b746b795af879f97372eec35",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -24,8 +24,8 @@
]
},
"voice": {
- "bytes": 18823,
- "sha256": "6b3b080f386cdbe41c1610f8e3df99a5eedb7bfbbc96a5fd568d2ac6dd75bfc3",
+ "bytes": 18837,
+ "sha256": "26335c62d9f44729e9bf491ad6e4fc700c036f04be411e38bed47345a81c72ba",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -49,8 +49,8 @@
]
},
"shared": {
- "bytes": 18082,
- "sha256": "9f0e8423c761a226315886aa3d322814ab7ebf34b45a6518de27bc809529f3fd",
+ "bytes": 18096,
+ "sha256": "1a9fcae125368565cc1aed4d348ea9b9620ede93ac3f53e802cae159ab1da138",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -73,8 +73,8 @@
]
},
"shared+voice": {
- "bytes": 18863,
- "sha256": "4a04a23df21bc6ac943e83f23ea790cf494d8e91547d01bfd7e65a41d5c21897",
+ "bytes": 18877,
+ "sha256": "0bff84f8c38c6d0b64277e2551134b5d21a85aeb897542c8cdcb72179929c450",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -98,8 +98,8 @@
]
},
"skills": {
- "bytes": 18069,
- "sha256": "58fe1016e6600ffc8945aa5f8484e8fb20c085f8f333e6633e775746159a9a8c",
+ "bytes": 18083,
+ "sha256": "335f10e32366bca4c89056c389d1a4e202e449fa188ea218f05be521037e5a52",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -122,8 +122,8 @@
]
},
"skills+voice": {
- "bytes": 18850,
- "sha256": "c93615e5f8b24d1359d8ec16373fd0c4b236516c0cdae3c093b0dd7748549216",
+ "bytes": 18864,
+ "sha256": "8305458a652c356191980056232e9bfb19d3254cf345cc474c59bfdb8672c254",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -147,8 +147,8 @@
]
},
"skills+shared": {
- "bytes": 18109,
- "sha256": "4730af33348dbca434989e4e61d8559fb6e517cdee592bf7423b7155c09c86e7",
+ "bytes": 18123,
+ "sha256": "6b3ab40e56c15cdac65edafed42fed53260b3f3457d70890d8893ee1dfa19c2c",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -171,8 +171,8 @@
]
},
"skills+shared+voice": {
- "bytes": 18890,
- "sha256": "5e0e33bea0b9e1a962d2f9baae672be8696847697ff46f28feb6800f5fdf26a5",
+ "bytes": 18904,
+ "sha256": "d46eacc48eff53855e29f3debef61d39f559fce07ebc648c273ea1520dc94834",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -196,8 +196,8 @@
]
},
"non-chief": {
- "bytes": 17925,
- "sha256": "7f9f776f07f7050b4a93f6178abbac20816dc94a17335e49cbe5b9e587140211",
+ "bytes": 17939,
+ "sha256": "66e31d3cec92184d81bc71dbf6795445797cd14a462b00e9f6c8688b32b0043f",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -220,8 +220,8 @@
]
},
"voice+non-chief": {
- "bytes": 18706,
- "sha256": "b75e27bd99e8628ee42c290e33741366209351a4bdd9a0bb5de4e5dfff1e2e30",
+ "bytes": 18720,
+ "sha256": "61964ddf6ce1558bb388f20c5974449feef8f1234f65b3d70eed2424ffda859b",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -245,8 +245,8 @@
]
},
"shared+non-chief": {
- "bytes": 17965,
- "sha256": "52cdb6533b6a75ffb8cb7ffd24b4214232f59bfaec3e19768a3d724ea534f815",
+ "bytes": 17979,
+ "sha256": "6846bbed057b642dfe934273ac7fefe9a40228b0ab745afd5623f2d8de7b77ad",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -269,8 +269,8 @@
]
},
"shared+voice+non-chief": {
- "bytes": 18746,
- "sha256": "33b2cad8dc7c81b66fec3e043dcff16d16512e43912dc95cfea37acd5e727b39",
+ "bytes": 18760,
+ "sha256": "a8889dd0a9f000a3f993f6443a757280d181af700b808075e30925a565b6fd09",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -294,8 +294,8 @@
]
},
"skills+non-chief": {
- "bytes": 17952,
- "sha256": "8f936477369bdc53234def6a3734287d0ceda4a502e106781693adf5012031e2",
+ "bytes": 17966,
+ "sha256": "7394d63dfe62a014fa3c47d68fc6fe599dbfd06fceb8138afd21733f8a6ac1f6",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -318,8 +318,8 @@
]
},
"skills+voice+non-chief": {
- "bytes": 18733,
- "sha256": "7a13fd4becb2b77128ff1f3167342f2c67f4c57fa3953fc21371360c37ad4e2c",
+ "bytes": 18747,
+ "sha256": "5ac076bf2866eb11445c7c5af25c613a0416c056599cf3da8ed7d480cf84bdcc",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -343,8 +343,8 @@
]
},
"skills+shared+non-chief": {
- "bytes": 17992,
- "sha256": "a87836c170782e3785c0ac2a302af4226d9145608628929a522e45ff0bb643d8",
+ "bytes": 18006,
+ "sha256": "ad00faa91ac3a2a6eadaf337cc1a88b6462953d709dfd54e4003e03758dcfbf7",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -367,8 +367,8 @@
]
},
"skills+shared+voice+non-chief": {
- "bytes": 18773,
- "sha256": "5a358456b45a2d3880bf192d435d39245cd45f12a3a110745a18ab4aafd378a2",
+ "bytes": 18787,
+ "sha256": "54d897f52188f542e03a3fed31337d5394851088138a7a42ff8b089d9fc38e53",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -392,8 +392,8 @@
]
},
"skills+shared+voice+cloud-home": {
- "bytes": 18906,
- "sha256": "19fa09a0f90d988eeaa94e4621611b2e7729824aac235835f1fcd63f868031a5",
+ "bytes": 18920,
+ "sha256": "e37a0236ac88e083e35bc2dde8fd4a02dac09d7f57c3c77ce35124b2c223f359",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -417,8 +417,8 @@
]
},
"skills+shared+voice+non-chief+cloud-home": {
- "bytes": 18789,
- "sha256": "76a9cda3121e556222b2c189004728ebaaaf407fae5d1a22c1ce28b985483a64",
+ "bytes": 18803,
+ "sha256": "11d2adc1abc3cd2af217bb088374b6272d558511668998fd2bbc183e0a92adb2",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -442,8 +442,8 @@
]
},
"skills+shared+voice+x": {
- "bytes": 18951,
- "sha256": "13745dea473a78c3ed15502554dbe864347b46593fbe75453697da0d441d0502",
+ "bytes": 18965,
+ "sha256": "47b3bd6cf7100e6872d52f48b248c89e2f109b3de7915034c8d2bd2df032ae6a",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -467,8 +467,8 @@
]
},
"skills+shared+voice+x+team": {
- "bytes": 18951,
- "sha256": "13745dea473a78c3ed15502554dbe864347b46593fbe75453697da0d441d0502",
+ "bytes": 18965,
+ "sha256": "47b3bd6cf7100e6872d52f48b248c89e2f109b3de7915034c8d2bd2df032ae6a",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -492,8 +492,8 @@
]
},
"skills+shared+voice+x+team+images": {
- "bytes": 18979,
- "sha256": "dd48e03197d0c7b2c303053098ed737a01f53837d0c60d101b07fd23142d224b",
+ "bytes": 18993,
+ "sha256": "da2170b7ec0e2aefa14c9ff78601f3e1b81a2c83f13a3a51a26fc306ee400f0e",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -517,8 +517,8 @@
]
},
"default+legacy-switches": {
- "bytes": 18042,
- "sha256": "77e381efdb38f4f5baf0d7713b97b3d5fdbf59771ef282e137b14c11d84337e9",
+ "bytes": 18056,
+ "sha256": "4b60038ce6c1ba27fa969c87a7d14ef560b88544b746b795af879f97372eec35",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -541,8 +541,8 @@
]
},
"default+mausbot": {
- "bytes": 18094,
- "sha256": "9bc2fbba9e038c8418fa2da8942304db5234b9f75432e2691d45fef42d96d3ed",
+ "bytes": 18108,
+ "sha256": "453bc803e95c2551a8d23eaaee4268cc8f008fb98289e1832af1171d56ddd952",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -565,8 +565,8 @@
]
},
"skills+shared+voice+mausbot": {
- "bytes": 18942,
- "sha256": "91a5c99105c63d8b9c9296a8b2b274e51c8c9f099fe8ca4ded78e08b8f660c78",
+ "bytes": 18956,
+ "sha256": "5b849de52c59e54032e81c58e76b7dcea4a35e60a7d7e03ed12b683e4928a8a9",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -590,8 +590,8 @@
]
},
"default+no-computer-pick": {
- "bytes": 16830,
- "sha256": "1ef5bed20d164393ab479bdad845341228530d399cdee57b3ec218c0880e62c0",
+ "bytes": 16844,
+ "sha256": "1ccaa17415e93c4bf24a21d631eef925c493236dfa17f6228a292290064e04dc",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -613,8 +613,8 @@
]
},
"default+room": {
- "bytes": 16759,
- "sha256": "6db6d1fb2fa77f0dea6ae414a2818e9aa6c77bd5810484456fcf29fb1f765d9c",
+ "bytes": 16773,
+ "sha256": "4340d20691aa941294200072ac04ef9075fe057ddcab5dfa163e7c8c22c06ae0",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -636,8 +636,8 @@
]
},
"non-chief+room": {
- "bytes": 16642,
- "sha256": "fbcac5dd1f001703405dd9cbeefc625165be2a52fa6421fe4a8d54dadaad1612",
+ "bytes": 16656,
+ "sha256": "6f4a3d05f6cae1efbd22acc78d836190dc93778ade7bb3c3b37d9e26e0101734",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -659,8 +659,8 @@
]
},
"default+images": {
- "bytes": 18070,
- "sha256": "b9ff9c4af83c6f0f1dad2f4c08f9820ab9de19b06708937c604b3488b6190431",
+ "bytes": 18084,
+ "sha256": "562e39ed76c1bc1a653b19f37f023e454f8589fd94a9ba7067eff090bca57328",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -683,8 +683,8 @@
]
},
"skills+shared+voice+x+team+images+hosting": {
- "bytes": 20181,
- "sha256": "5caa8816b73fa9ba571d5626425b43dba8e67a854d388a12a7e36ab0e35da1cf",
+ "bytes": 20195,
+ "sha256": "45f7f773878e7c9e92e54565da77e022c96099a84638d5d3e1c39481921422dc",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -709,8 +709,8 @@
]
},
"default+hosting": {
- "bytes": 19244,
- "sha256": "2371919f9588a0cc6f9aa638958c5bd5e412ab1f580d1e3bc5c4757c612db64c",
+ "bytes": 19258,
+ "sha256": "42d6c6fc65efeb729cf1f722ff13575a181b2e6a874051fb4ee28cfc32cabbd5",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -734,8 +734,8 @@
]
},
"default+tools-off": {
- "bytes": 16385,
- "sha256": "796a8cf642248fc4ad6ae216efe5835f52e375058e787528c115d83d43a8fa3e",
+ "bytes": 16399,
+ "sha256": "507ef4f21acba4d56331961f10f33af07ecd82779ee7639920f011535207c7f2",
"tools": [
"tool_result_read",
"list_room_targets",
diff --git a/server/drivers/agents-catalog-goldens/bridged.tools-list.json b/server/drivers/agents-catalog-goldens/bridged.tools-list.json
index 4b362007f5..d30b6ee4ff 100644
--- a/server/drivers/agents-catalog-goldens/bridged.tools-list.json
+++ b/server/drivers/agents-catalog-goldens/bridged.tools-list.json
@@ -537,7 +537,7 @@
},
{
"name": "find_tool",
- "description": "Find an OpenMausBot tool that is not in your tool list. Say what you want to do in a few words, or give the tool's name. Each match comes back with its description and exact input schema; run one with use_tool. Tools reached this way: list_shared_computers, shared_computer, assignment_status, usage_limits, list_threads, close_thread, rename_thread, start_thread, burst, list_models, vm_exec, show_widget, show_html, unpublish_page, create_bot, list_team_setup, list_team_library, propose_team_setup, propose_bot_deletion, manage_room, x_search, research_search, research_endpoint, research_call, decide, extract, edit_image, generate_image, report_bug, check_app_hosting, retry_thread, memory_log, session_search, trigger_info, trigger, delete_trigger, wait_until, list_waits, cancel_wait, check_back, propose_profile, propose_model, propose_team_memory, skills_list, skill_manage, mcp_server, app_settings.",
+ "description": "Find an OpenMausBot tool that is not in your tool list. Say what you want to do in a few words, or give the tool's name. Each match comes back with its description and exact input schema; run one with use_tool. Tools reached this way: list_shared_computers, shared_computer, assignment_status, usage_limits, list_threads, close_thread, rename_thread, start_thread, burst, list_models, vm_exec, show_widget, show_html, unpublish_page, create_bot, list_team_setup, list_team_library, propose_team_setup, propose_bot_deletion, manage_room, x_search, research_search, research_endpoint, research_call, decide, extract, what_changed, edit_image, generate_image, report_bug, check_app_hosting, retry_thread, memory_log, session_search, trigger_info, trigger, delete_trigger, wait_until, list_waits, cancel_wait, check_back, propose_profile, propose_model, propose_team_memory, skills_list, skill_manage, mcp_server, app_settings.",
"inputSchema": {
"type": "object",
"additionalProperties": false,
diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.json
index 873f13c9f4..a0a6e7663d 100644
--- a/server/drivers/agents-catalog-goldens/full.tools-list.json
+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json
@@ -1223,6 +1223,38 @@
]
}
},
+ {
+ "name": "what_changed",
+ "description": "What differs between a text and its edit: sentences changed ([-old-]{+new+}), added, removed, moved. Use before saying what you changed.",
+ "inputSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "original_file": {
+ "type": "string",
+ "description": "A .md/.txt you can read or attached here."
+ },
+ "edited_file": {
+ "type": "string"
+ },
+ "original_text": {
+ "type": "string"
+ },
+ "edited_text": {
+ "type": "string"
+ },
+ "start": {
+ "type": "integer"
+ }
+ }
+ },
+ "annotations": {
+ "readOnlyHint": true,
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": false
+ }
+ },
{
"name": "edit_image",
"description": "Change an existing image from a text instruction, optionally guided by a markup PNG: marks (circles, arrows, scribbles) drawn on a transparent background at the image's exact size, which point at where to change. Both files are paths in your working folder. The result is attached to your reply when the turn ends. Needs a GPT-Image-2.6 model on OpenAI.",
diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.json
index 0b44988f08..76fd3daf21 100644
--- a/server/drivers/agents-catalog-goldens/profiles.json
+++ b/server/drivers/agents-catalog-goldens/profiles.json
@@ -1,7 +1,7 @@
{
"default": {
- "bytes": 58828,
- "sha256": "0bc510317f6c20f8a6f99d3c523657344603486fa41285717358c37316e186af",
+ "bytes": 59402,
+ "sha256": "31a259fcdf0ca79a6c4b5b1b5f4584916261c0c71455a9dd54ee4046dfad6c0d",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -36,6 +36,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -58,8 +59,8 @@
]
},
"voice": {
- "bytes": 59609,
- "sha256": "84c74fc165fa7788490f88532d8fac7766879c6f215328a26fdfad5aaddb1cec",
+ "bytes": 60183,
+ "sha256": "6420e055d2e7a4afc7011c7d960144467ded607ee1ed4fd8a12669d5fa0ea548",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -95,6 +96,7 @@
"send_voice_note",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -117,8 +119,8 @@
]
},
"shared": {
- "bytes": 61093,
- "sha256": "8efe0d27e4adf6249d19c047a929bcf1c389d10403fd6399da9e1e9f1428edde",
+ "bytes": 61667,
+ "sha256": "166bbf1ea5e0f1c479e81ce8dfa0c93c7deb4cc909c7a00dac8b232dbcb1763f",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -155,6 +157,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -177,8 +180,8 @@
]
},
"shared+voice": {
- "bytes": 61874,
- "sha256": "ef67c1e35a2219d9e1b132a12d425e390327b3d12b3deee713565d5107a40dfe",
+ "bytes": 62448,
+ "sha256": "20fd5d970444c6e61319b0283ba12fe3b471d77f13959e546970bd5659451998",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -216,6 +219,7 @@
"send_voice_note",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -238,8 +242,8 @@
]
},
"skills": {
- "bytes": 61149,
- "sha256": "2b9c046537f8c3bf02d291061963d3e093a8f76906980f472f548694695e1b43",
+ "bytes": 61723,
+ "sha256": "f30fa68bc9594c2731a96ca1de14da412fc24514ebab056bec9ee5397d078f54",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -274,6 +278,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -298,8 +303,8 @@
]
},
"skills+voice": {
- "bytes": 61930,
- "sha256": "6790c26bf2db33fe4a05a28e3c8be24361fc0177da1860fdc6f085a015185dd5",
+ "bytes": 62504,
+ "sha256": "126cda6b417c7d34596cd63b9c765bb70007a5ef84ee411e176dc28857b382ca",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -335,6 +340,7 @@
"send_voice_note",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -359,8 +365,8 @@
]
},
"skills+shared": {
- "bytes": 63414,
- "sha256": "7e4b83b4bd72690866e9ac5fdb04a797618e0c2084d3037d303c2a858651d8d4",
+ "bytes": 63988,
+ "sha256": "f19ef58676021b6681220f774d6d0f84a44bf046586db2068da3be9220377843",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -397,6 +403,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -421,8 +428,8 @@
]
},
"skills+shared+voice": {
- "bytes": 64195,
- "sha256": "3baddbc0c2fb5eae43372a7ec7975dde4bad9777672e170645df5fa174d6bbcb",
+ "bytes": 64769,
+ "sha256": "8fc830a4ab0823ff7d302ebbe3427246f2a47a078b292a73109a115b7a2096fa",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -460,6 +467,7 @@
"send_voice_note",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -484,8 +492,8 @@
]
},
"non-chief": {
- "bytes": 50280,
- "sha256": "2f36a30278c390b6e75b5ef9b13d8969b41d37dbcd03046857c515d8a8949885",
+ "bytes": 50854,
+ "sha256": "b0eb050397bff3d64375ffaecd51bc13b349ab7afe3bf95b0b74ca1504341061",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -514,6 +522,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -535,8 +544,8 @@
]
},
"voice+non-chief": {
- "bytes": 51061,
- "sha256": "9c2327276275e3c59daeb928ba6ef8cc7d0113050bfb6db068383f9b51345778",
+ "bytes": 51635,
+ "sha256": "b6336aaf559651e0a17e3a760e459bd2581202af4679fa2bcbff237441a9c262",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -566,6 +575,7 @@
"send_voice_note",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -587,8 +597,8 @@
]
},
"shared+non-chief": {
- "bytes": 52545,
- "sha256": "7b88c750cfc76292aefafbaad6c338aa57581a7634b4594c20174df59eacdb27",
+ "bytes": 53119,
+ "sha256": "54c8eb1321b4a1718d9c99569d71915f35105b9849288565a6a8de0ce946d4ea",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -619,6 +629,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -640,8 +651,8 @@
]
},
"shared+voice+non-chief": {
- "bytes": 53326,
- "sha256": "344fae24fb4ca181f9535d8491d63f4b3730733852e556f29a5e0e5afdf33070",
+ "bytes": 53900,
+ "sha256": "755591f72d300a859e93cf508f36115482ed90bf1fa1b5263c9deea9727b73c9",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -673,6 +684,7 @@
"send_voice_note",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -694,8 +706,8 @@
]
},
"skills+non-chief": {
- "bytes": 52601,
- "sha256": "f58b8554a43b1221632d881269372885edf7fc9d560d6ddabf7e51d9d42b945c",
+ "bytes": 53175,
+ "sha256": "6d74638a2756cd1314268df3a2b996da9ae185cbf1c2a9f77718c513f91dc074",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -724,6 +736,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -747,8 +760,8 @@
]
},
"skills+voice+non-chief": {
- "bytes": 53382,
- "sha256": "45cc5db670f9c0ad6c487df9a881db5d58802813b0d7237f853b2599cd79dcc0",
+ "bytes": 53956,
+ "sha256": "a06f28da7d4b144df1df84138599ea62098cadbfc1634a13353da52b796c0a85",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -778,6 +791,7 @@
"send_voice_note",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -801,8 +815,8 @@
]
},
"skills+shared+non-chief": {
- "bytes": 54866,
- "sha256": "3d70000599f350cbbbd41fbe67d26c5e3fa0ecff3ba5ed707ab389c621e79f28",
+ "bytes": 55440,
+ "sha256": "c968a3eac55a9542e33e74d8ae76d38b416c4bca1cc6329844c18ab2ff55cc4b",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -833,6 +847,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -856,8 +871,8 @@
]
},
"skills+shared+voice+non-chief": {
- "bytes": 55647,
- "sha256": "618f91f99861d9b84922da174fa7cb4fac6b8b6269c48e2bed7802d4d259c1d1",
+ "bytes": 56221,
+ "sha256": "2aee88fd3a1c8d7ab4ff53a33cee8a9ce657c9b4bcb996cd0abd6a1fc3c5bb0b",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -889,6 +904,7 @@
"send_voice_note",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -912,8 +928,8 @@
]
},
"skills+shared+voice+cloud-home": {
- "bytes": 63961,
- "sha256": "12b61b8135e45ed1d8d5cc1b3d486ed8b1dc2754f7207d13ef797ada1b94adaa",
+ "bytes": 64535,
+ "sha256": "08abae7472cb3a90b2414769bfbc1666bde8a82cfcddfaa5be0314e051eca2b1",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -950,6 +966,7 @@
"send_voice_note",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -975,8 +992,8 @@
]
},
"skills+shared+voice+non-chief+cloud-home": {
- "bytes": 55413,
- "sha256": "2b1058789d6de069e611534026b85b4fe6e01cf6d4c3d927e584010b9c7422ad",
+ "bytes": 55987,
+ "sha256": "8bcc95d36e92284d616454b8664b5edb201838c9320eb1e6a14cbdc09be2dab6",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1007,6 +1024,7 @@
"send_voice_note",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -1031,8 +1049,8 @@
]
},
"skills+shared+voice+x": {
- "bytes": 68034,
- "sha256": "07704e3ea47b374017b1673993709c4c3295af93c1093fb978f79ee9c93cc119",
+ "bytes": 68608,
+ "sha256": "cc72ea19d6c60e4a708e8529babaed67de47b332a3ae0a1da52b793387962f00",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1074,6 +1092,7 @@
"research_call",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -1098,8 +1117,8 @@
]
},
"skills+shared+voice+x+team": {
- "bytes": 68034,
- "sha256": "07704e3ea47b374017b1673993709c4c3295af93c1093fb978f79ee9c93cc119",
+ "bytes": 68608,
+ "sha256": "cc72ea19d6c60e4a708e8529babaed67de47b332a3ae0a1da52b793387962f00",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1141,6 +1160,7 @@
"research_call",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -1165,8 +1185,8 @@
]
},
"skills+shared+voice+x+team+images": {
- "bytes": 69981,
- "sha256": "cdce42a3892f3425c82f94695e9f06760c57071751fbc5ba77dcc09bf6deac20",
+ "bytes": 70555,
+ "sha256": "d6fbf9822350063b8ed2fc1381fa1461c83d9b30043dbea81fd73a02f0e7aab8",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1208,6 +1228,7 @@
"research_call",
"decide",
"extract",
+ "what_changed",
"edit_image",
"generate_image",
"message_person",
@@ -1234,8 +1255,8 @@
]
},
"default+legacy-switches": {
- "bytes": 58828,
- "sha256": "0bc510317f6c20f8a6f99d3c523657344603486fa41285717358c37316e186af",
+ "bytes": 59402,
+ "sha256": "31a259fcdf0ca79a6c4b5b1b5f4584916261c0c71455a9dd54ee4046dfad6c0d",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1270,6 +1291,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -1292,8 +1314,8 @@
]
},
"default+mausbot": {
- "bytes": 59479,
- "sha256": "648fe0697b962ab200977b51d8438abaeede5ed122a3330ae88cff2ededb054f",
+ "bytes": 60053,
+ "sha256": "6bc64c6ffed74c16e7bb9ef5839ae77fc7b1822194248eef5d68d9ea5ffddfa7",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1328,6 +1350,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -1352,8 +1375,8 @@
]
},
"skills+shared+voice+mausbot": {
- "bytes": 64846,
- "sha256": "3e38f4adecea9c5fe026ab7dbd15da8c4f1d8ed45c68a97c4fe923de7c389e75",
+ "bytes": 65420,
+ "sha256": "75152033f295e58cbc909aed960027ac8b3bc9a635ce27e0f8c083a9c956251c",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1391,6 +1414,7 @@
"send_voice_note",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -1417,8 +1441,8 @@
]
},
"default+no-computer-pick": {
- "bytes": 57616,
- "sha256": "0d4c7eb2d214eb47ca111a1d2f0cc8cf990a730f65e4be9829821be5b97b06dd",
+ "bytes": 58190,
+ "sha256": "7d987f9cfceb635bc99e945c6e1de1510c42616d538c19b1d26e867dc17ba8ff",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1452,6 +1476,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -1474,8 +1499,8 @@
]
},
"default+room": {
- "bytes": 54176,
- "sha256": "5712832949edbc37c2d3f0141d292b6ae2910e0e91f73a900a32e5da17dab9b2",
+ "bytes": 54750,
+ "sha256": "c503d968f149d935cb101b06f5f143320392fc6081199c20c216c8b1aac9871e",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1507,6 +1532,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -1525,8 +1551,8 @@
]
},
"non-chief+room": {
- "bytes": 45628,
- "sha256": "05c64d2fe12e3fa0cd6cc913cda686ee507123b956313f5c5893337e301f16c2",
+ "bytes": 46202,
+ "sha256": "a9ff32051a0e9bab6b1c41b082a897dab26260a2a6ef33a51a88dfab05167707",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1552,6 +1578,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -1569,8 +1596,8 @@
]
},
"default+images": {
- "bytes": 60775,
- "sha256": "0843c41a1e3a7d891dbb8d0c767c614581f9123570d1bfd19286813d4c94c604",
+ "bytes": 61349,
+ "sha256": "9bea71600a63eae6874a69525ca22f3ee89bbaa5d2f121de40911fee9749e769",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1605,6 +1632,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"edit_image",
"generate_image",
"message_person",
@@ -1629,8 +1657,8 @@
]
},
"skills+shared+voice+x+team+images+hosting": {
- "bytes": 71844,
- "sha256": "cdab3567ed19c7d4bd0a97614ddfe0421521913d19e63f9065ced6e4f73328cf",
+ "bytes": 72418,
+ "sha256": "0fefd78b2e4d2a41f1952fade925a28692f23879178de5b0aac945253c6efa8f",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1672,6 +1700,7 @@
"research_call",
"decide",
"extract",
+ "what_changed",
"edit_image",
"generate_image",
"message_person",
@@ -1700,8 +1729,8 @@
]
},
"default+hosting": {
- "bytes": 60691,
- "sha256": "ddfd0a210f66b3872a37eceff61fa185deeb866a5cca123bd54a50e9dfa4e3cb",
+ "bytes": 61265,
+ "sha256": "b25e91eb515c8113567430421f4e953af7c0089bbc9e9a8ba68d20748f32ff28",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1736,6 +1765,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"publish_app",
@@ -1760,8 +1790,8 @@
]
},
"default+tools-off": {
- "bytes": 54510,
- "sha256": "4bc1783522425f2423926b2f68a7bdcd2959a2a592af06c454e7cf19db7aaf7d",
+ "bytes": 55084,
+ "sha256": "841bdb8105ea88b4a664445fbeff79925642ca58fe1c5f0594d19ade3cbd3fa8",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1793,6 +1823,7 @@
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"memory_update",
diff --git a/server/drivers/agents-catalog-wire.test.ts b/server/drivers/agents-catalog-wire.test.ts
index c737fbea73..0c60bd8448 100644
--- a/server/drivers/agents-catalog-wire.test.ts
+++ b/server/drivers/agents-catalog-wire.test.ts
@@ -87,37 +87,37 @@ const FULL = "skills+shared+voice+x+team+images+hosting";
/** Bytes when the budget was last set; a profile may move at most 2% either way (lower it to lock in a win). */
const BUDGET_BASELINE: Record<string, number> = {
- "default": 57945,
- "voice": 58726,
- "shared": 60210,
- "shared+voice": 60991,
- "skills": 60031,
- "skills+voice": 60812,
- "skills+shared": 62296,
- "skills+shared+voice": 63077,
- "non-chief": 49528,
- "voice+non-chief": 50309,
- "shared+non-chief": 51793,
- "shared+voice+non-chief": 52574,
- "skills+non-chief": 51614,
- "skills+voice+non-chief": 52395,
- "skills+shared+non-chief": 53879,
- "skills+shared+voice+non-chief": 54660,
- "skills+shared+voice+cloud-home": 62843,
- "skills+shared+voice+non-chief+cloud-home": 54426,
- "default+legacy-switches": 57945,
- "default+mausbot": 58596,
- "skills+shared+voice+mausbot": 63728,
- "skills+shared+voice+x": 67179,
- "skills+shared+voice+x+team": 67179,
- "default+no-computer-pick": 56733,
- "default+room": 53729,
- "non-chief+room": 45312,
- "skills+shared+voice+x+team+images": 69244,
- "default+images": 60010,
- "skills+shared+voice+x+team+images+hosting": 71107,
- "default+hosting": 59808,
- "default+tools-off": 54421,
+ "default": 58519,
+ "voice": 59300,
+ "shared": 60784,
+ "shared+voice": 61565,
+ "skills": 60605,
+ "skills+voice": 61386,
+ "skills+shared": 62870,
+ "skills+shared+voice": 63651,
+ "non-chief": 50102,
+ "voice+non-chief": 50883,
+ "shared+non-chief": 52367,
+ "shared+voice+non-chief": 53148,
+ "skills+non-chief": 52188,
+ "skills+voice+non-chief": 52969,
+ "skills+shared+non-chief": 54453,
+ "skills+shared+voice+non-chief": 55234,
+ "skills+shared+voice+cloud-home": 63417,
+ "skills+shared+voice+non-chief+cloud-home": 55000,
+ "default+legacy-switches": 58519,
+ "default+mausbot": 59170,
+ "skills+shared+voice+mausbot": 64302,
+ "skills+shared+voice+x": 67753,
+ "skills+shared+voice+x+team": 67753,
+ "default+no-computer-pick": 57307,
+ "default+room": 54303,
+ "non-chief+room": 45886,
+ "skills+shared+voice+x+team+images": 69818,
+ "default+images": 60584,
+ "skills+shared+voice+x+team+images+hosting": 71681,
+ "default+hosting": 60382,
+ "default+tools-off": 54995,
};
const RPC_PREFIX = '{"jsonrpc":"2.0","id":1,"result":';
diff --git a/server/drivers/agents-catalog.ts b/server/drivers/agents-catalog.ts
index 1286cc1e2c..bfee3f5283 100644
--- a/server/drivers/agents-catalog.ts
+++ b/server/drivers/agents-catalog.ts
@@ -7,6 +7,7 @@ import { agentToolAnnotations } from "../agent-tool-policy.ts";
import { CHAT_CARD_TOOL_DEFINITIONS } from "./agents-chat-card-tools.ts";
import { DEVS_TOOL_DEFINITIONS } from "./agents-devs-tools.ts";
import { HELPER_TOOL_DEFINITIONS } from "./agents-helper-tools.ts";
+import { WHAT_CHANGED_TOOL_DEFINITION } from "./agents-what-changed-tool.ts";
import { USAGE_LIMITS_TOOL_DEFINITION } from "./agents-usage-tool.ts";
import { APP_SETTINGS_TOOL_DEFINITION } from "./agents-app-settings-tool.ts";
import { THREAD_POST_TOOL_DEFINITION } from "./agents-thread-post-tool.ts";
@@ -516,7 +517,7 @@ const TOOL_DEFINITIONS = [
required: ["text"],
},
},
- ...RESEARCH_TOOL_DEFINITIONS, ...HELPER_TOOL_DEFINITIONS, ...IMAGE_TOOL_DEFINITIONS, ...MEETING_TOOL_DEFINITIONS, ...PERSON_TOOL_DEFINITIONS, ...DEVS_TOOL_DEFINITIONS, ...HOSTING_TOOL_DEFINITIONS, ...SHARE_TOOL_DEFINITIONS,
+ ...RESEARCH_TOOL_DEFINITIONS, ...HELPER_TOOL_DEFINITIONS, WHAT_CHANGED_TOOL_DEFINITION, ...IMAGE_TOOL_DEFINITIONS, ...MEETING_TOOL_DEFINITIONS, ...PERSON_TOOL_DEFINITIONS, ...DEVS_TOOL_DEFINITIONS, ...HOSTING_TOOL_DEFINITIONS, ...SHARE_TOOL_DEFINITIONS,
{
name: "memory_update",
description:
diff --git a/server/drivers/agents-claude-defer.test.ts b/server/drivers/agents-claude-defer.test.ts
index c5deb06a6f..71e748498d 100644
--- a/server/drivers/agents-claude-defer.test.ts
+++ b/server/drivers/agents-claude-defer.test.ts
@@ -23,9 +23,9 @@ const DEFER = { [DEFER_TOOLS_ENV]: "1" };
/** Bytes Claude Code sends up front for the agents server when the budget was last set; each may move at most 2%. */
const UP_FRONT_BASELINE: Record<string, { whole: number; deferred: number }> = {
- default: { whole: 3855, deferred: 1252 },
- specialist: { whole: 1495, deferred: 1080 },
- fullest: { whole: 3855, deferred: 1589 },
+ default: { whole: 3855, deferred: 1278 },
+ specialist: { whole: 1495, deferred: 1106 },
+ fullest: { whole: 3855, deferred: 1615 },
};
const listed = (env: Record<string, string>) => agentsToolList(env).listed as Array<{ name: string; description: string; inputSchema: unknown; _meta?: Record<string, unknown> }>;
diff --git a/server/drivers/agents-proxy.test.ts b/server/drivers/agents-proxy.test.ts
index e3196b6196..8ae2990559 100644
--- a/server/drivers/agents-proxy.test.ts
+++ b/server/drivers/agents-proxy.test.ts
@@ -670,6 +670,7 @@ describe("agents-proxy MCP surface", () => {
"fill_login",
"decide",
"extract",
+ "what_changed",
"message_person",
"report_bug",
"share",
@@ -775,7 +776,7 @@ describe("agents-proxy MCP surface", () => {
"list_shared_computers",
"assignment_status", "list_bots", "usage_limits", "list_rooms", "list_threads",
"list_models", "list_team_setup",
- "session_search", "trigger_info", "list_waits", "skills_list",
+ "what_changed", "session_search", "trigger_info", "list_waits", "skills_list",
];
expect(list.result.tools.filter((tool: any) => tool.annotations?.readOnlyHint)
.map((tool: any) => tool.name)).toEqual(readNames);
diff --git a/server/drivers/agents-tool-groups.ts b/server/drivers/agents-tool-groups.ts
index b8b2d6a48e..18c603de1f 100644
--- a/server/drivers/agents-tool-groups.ts
+++ b/server/drivers/agents-tool-groups.ts
@@ -31,7 +31,7 @@ export const CORE_TOOLS: ReadonlySet<string> = new Set([
"close_thread", "rename_thread", "start_thread", "burst", "list_models", "vm_exec", "attach_file", "show_widget", "create_options_card",
"post_to_room", "post_to_thread", "create_bot", "list_team_setup", "list_team_library", "propose_team_setup",
"propose_bot_deletion", "manage_room", "request_credential", "request_sign_in", "fill_login", "send_voice_note", "decide",
- "extract", "message_person", "report_bug", "retry_thread", "session_search", "trigger_info", "trigger", "delete_trigger",
+ "extract", "what_changed", "message_person", "report_bug", "retry_thread", "session_search", "trigger_info", "trigger", "delete_trigger",
"wait_until", "list_waits", "cancel_wait", "check_back", "propose_profile", "propose_model", "propose_team_memory", "skills_list",
"skill_manage", "mcp_server", "app_settings", "list_unread_notifications", "mark_notifications_read",
]);
diff --git a/server/drivers/agents-what-changed-tool.ts b/server/drivers/agents-what-changed-tool.ts
new file mode 100644
index 0000000000..64fc0cb1de
--- /dev/null
+++ b/server/drivers/agents-what-changed-tool.ts
@@ -0,0 +1,35 @@
+// The agents catalog's what_changed tool: the differences between a document and its edited version, sentence by
+// sentence, from the same comparison the chat's "What changed" view uses, so a bot reports what it changed from the
+// files rather than from memory. Every bot on every engine has it; the internal route (server/routes/what-changed.ts)
+// reads the files and runs the comparison off the server's event loop.
+import type { ToolCallContext, ToolCallResult } from "./agents-call.ts";
+import type { Json } from "./agents-client.ts";
+
+export const WHAT_CHANGED_TOOL = "what_changed";
+
+/** The internal request carries at most 1 MB (harness/http.ts readBody), so text passed inline must fit under it. */
+export const WHAT_CHANGED_INLINE_MAX = 900_000;
+export const WHAT_CHANGED_INLINE_REFUSAL = "Text passed directly may be about 900 KB in all. Save it to a file in your working folder (up to 2 MB each) and pass original_file / edited_file.";
+
+export async function callWhatChangedTool(args: Json, context: ToolCallContext): Promise<ToolCallResult> {
+ const body = JSON.stringify(args);
+ if (body.length > WHAT_CHANGED_INLINE_MAX) return { text: WHAT_CHANGED_INLINE_REFUSAL, isError: true };
+ const { ok, body: answer } = await context.client.apiResponse("/api/internal/what-changed", { method: "POST", body });
+ return ok ? { text: String(answer.text ?? "") } : { text: String(answer.error ?? "The comparison could not finish. Try again."), isError: true };
+}
+
+export const WHAT_CHANGED_TOOL_DEFINITION = {
+ name: WHAT_CHANGED_TOOL,
+ description: "What differs between a text and its edit: sentences changed ([-old-]{+new+}), added, removed, moved. Use before saying what you changed.",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ original_file: { type: "string", description: "A .md/.txt you can read or attached here." },
+ edited_file: { type: "string" },
+ original_text: { type: "string" },
+ edited_text: { type: "string" },
+ start: { type: "integer" },
+ },
+ },
+};
diff --git a/server/index.ts b/server/index.ts
index 9cd6f8e983..26cecfb5c4 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12329,7 +12329,7 @@ ROUTES.push(createBrowserViewerRoutes({
restartRefusal: (session) => browserRestartRefusal(browserRuntime.interrupted(session), store.bots.filter((candidate) => candidate.busy
&& browserSessionsOf(candidate.id, candidate.browserProfile).includes(session)).map((candidate) => ({ waitingOnBrowser: computerControl.snapshot(candidate.id).help?.place === "browser" }))),
}));
-const internalToolRoutes = createInternalToolRoutes({ engineLimits: { instances: () => registry.instances(), configs: () => instanceConfigs(cfg), status: (instanceId) => registry.knownSnapshot(instanceId), load: (accounts) => loadPlanUsage({ accounts }), audienceOf: (threadId) => teamHost.audienceOf(threadId), guestDriven: cloudGuestDriven, dataDir: DATA_DIR }, helpers: { decider, extractor }, notifications: { bot: (id) => store.bot(id), team: sharedMembership, broadcast }, xResearch: { credential: () => researchCredential(cfg.treg?.key), botEnabled: (botId) => store.bot(botId)?.xResearch !== false, cloudHome: CLOUD_HOME !== null, researchOff: () => researchAvailability.refused() }, appPublisher }); const waitRoutes = createWaitRoutes({ waits: botWaits, cloudHome: Boolean(CLOUD_HOME), sleeps: Boolean(CLOUD_HOME) && CLOUD_TEAM === null }); ROUTES.push(createXConnectorRoutes({ credential: () => researchCredential(cfg.treg?.key), included: () => xCredential(), unavailable: () => xResearchStatus().unavailable === true }));
+const internalToolRoutes = createInternalToolRoutes({ engineLimits: { instances: () => registry.instances(), configs: () => instanceConfigs(cfg), status: (instanceId) => registry.knownSnapshot(instanceId), load: (accounts) => loadPlanUsage({ accounts }), audienceOf: (threadId) => teamHost.audienceOf(threadId), guestDriven: cloudGuestDriven, dataDir: DATA_DIR }, helpers: { decider, extractor }, whatChanged: { dataDir: DATA_DIR, attachmentsDir: ATTACHMENTS_DIR, messages: (threadId) => store.messagesFor(threadId) }, notifications: { bot: (id) => store.bot(id), team: sharedMembership, broadcast }, xResearch: { credential: () => researchCredential(cfg.treg?.key), botEnabled: (botId) => store.bot(botId)?.xResearch !== false, cloudHome: CLOUD_HOME !== null, researchOff: () => researchAvailability.refused() }, appPublisher }); const waitRoutes = createWaitRoutes({ waits: botWaits, cloudHome: Boolean(CLOUD_HOME), sleeps: Boolean(CLOUD_HOME) && CLOUD_TEAM === null }); ROUTES.push(createXConnectorRoutes({ credential: () => researchCredential(cfg.treg?.key), included: () => xCredential(), unavailable: () => xResearchStatus().unavailable === true }));
// Live calls: the client holds the WebRTC audio; the key never leaves the harness, which creates the session.
function liveBotFor(botId: string): LiveBot {
diff --git a/server/routes/internal-tools.ts b/server/routes/internal-tools.ts
index 38172bfc9d..4d37e8836f 100644
--- a/server/routes/internal-tools.ts
+++ b/server/routes/internal-tools.ts
@@ -1,16 +1,18 @@
// The agents tools' internal calls that need only the capability's bot and conversation, its body and its folders: research,
-// the helper models' decide and extract, MausBot's notifications, the usage limits and publishing an app. Runs inside index.ts's /api/internal/ block, after the
-// capability bearer is checked; each route answers its own paths and passes the rest on.
+// the helper models' decide and extract, what_changed, MausBot's notifications, the usage limits and publishing an app.
+// Runs inside index.ts's /api/internal/ block, after the capability bearer is checked; each route answers its own paths
+// and passes the rest on.
import type { AppPublisher } from "../host/app-publisher.ts";
import { createAppHostingInternalRoutes } from "./app-hosting.ts";
import { createEngineLimitsRoutes, type EngineLimitsDeps } from "./engine-limits.ts";
import { createHelperToolRoutes, type HelperToolContext, type HelperToolDeps } from "./helper-tools.ts";
import { createMausBotNotificationRoutes, type LiveNotificationsDeps } from "./mausbot-notifications.ts";
import { PASS } from "./table.ts";
+import { createWhatChangedRoutes, type WhatChangedDeps } from "./what-changed.ts";
import { createXResearchInternalRoutes, type XResearchDeps } from "./x-research.ts";
-export function createInternalToolRoutes(deps: { helpers: HelperToolDeps; xResearch: XResearchDeps; notifications: LiveNotificationsDeps; engineLimits: EngineLimitsDeps; appPublisher: AppPublisher }) {
- const routes = [createXResearchInternalRoutes(deps.xResearch), createHelperToolRoutes(deps.helpers), createMausBotNotificationRoutes(deps.notifications), createEngineLimitsRoutes(deps.engineLimits), createAppHostingInternalRoutes(deps.appPublisher)];
+export function createInternalToolRoutes(deps: { helpers: HelperToolDeps; xResearch: XResearchDeps; notifications: LiveNotificationsDeps; engineLimits: EngineLimitsDeps; appPublisher: AppPublisher; whatChanged: WhatChangedDeps }) {
+ const routes = [createXResearchInternalRoutes(deps.xResearch), createHelperToolRoutes(deps.helpers), createWhatChangedRoutes(deps.whatChanged), createMausBotNotificationRoutes(deps.notifications), createEngineLimitsRoutes(deps.engineLimits), createAppHostingInternalRoutes(deps.appPublisher)];
return async (ctx: HelperToolContext & { threadId: string }): Promise<typeof PASS | void> => {
for (const route of routes) if (await route(ctx) !== PASS) return;
return PASS;
diff --git a/server/routes/threads.ts b/server/routes/threads.ts
index d33cf4df64..3e01b6da39 100644
--- a/server/routes/threads.ts
+++ b/server/routes/threads.ts
@@ -3,6 +3,7 @@ import { basename, join } from "node:path";
import type { BotsResponse, SearchResponse, WireBot, WireGroup } from "../../shared/wire.ts";
import { NO_SUCH_BOT } from "../../shared/bot-read.ts";
+import { KEPT_ORIGINALS_DIR, keptOriginal } from "../attachment-originals.ts";
import {
ATTACHMENTS_DIR, attachmentStorageUsage, clearAttachments, deleteAttachment, extensionForMime, FILE_MAX_BYTES, IMAGE_MAX_BYTES,
parseAudioRange, readAttachment, saveFile, saveImageUpload, validateAttachmentUploadId, type SavedAttachment,
@@ -277,9 +278,13 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
const maxBytes = streamsMessageImage ? MESSAGE_FILE_MAX_BYTES : MESSAGE_FILE_DOWNLOAD_MAX_BYTES;
let file: Awaited<ReturnType<typeof openMessageFile>>;
try {
+ // What the person sent, even when a bot has since saved over the stored file.
+ const kept = message.role === "user" && !folderEntry ? keptOriginal(href, ATTACHMENTS_DIR) : null;
file = folderEntry
? await openMessageFolderEntry(href, folderEntry, roots, maxBytes)
- : await openMessageFile(href, roots, maxBytes);
+ : kept ? await openMessageFile(kept, [KEPT_ORIGINALS_DIR], maxBytes) : await openMessageFile(href, roots, maxBytes);
+ // Says the bytes are exactly what the person sent, so a comparison may call them that.
+ if (kept) res.setHeader("x-openmausbot-kept-original", "1");
} catch (error) {
const code = (error as { code?: unknown } | null)?.code;
const status = (error as { status?: unknown } | null)?.status;
@@ -446,7 +451,7 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
const chunks = req.iterator({ destroyOnReturn: false }) as AsyncIterable<Buffer>;
const saved = rawType?.split(";")[0]!.trim().toLowerCase() === XMIND_MIME
? await saveXmindUpload(chunks, name, { uploadId })
- : await saveFile(chunks, name, rawType ?? "", { uploadId, expectedBytes: declaredLength });
+ : await saveFile(chunks, name, rawType ?? "", { uploadId, expectedBytes: declaredLength, keepOriginal: true });
deps.uploads.note(auth, basename(saved.path));
return json(res, 201, saved);
} catch (error) {
diff --git a/server/routes/what-changed.test.ts b/server/routes/what-changed.test.ts
new file mode 100644
index 0000000000..1494b4df8a
--- /dev/null
+++ b/server/routes/what-changed.test.ts
@@ -0,0 +1,120 @@
+// The what_changed tool's internal route: files from the bot's own folders or this conversation's attachments (the
+// original side of the person's upload as it was sent, the edited side as it is now), text in place of a file, plain
+// refusals, and the comparison run in a worker thread, one at a time, with the last answer kept for paging.
+import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+import { keepUploadedOriginal, keptOriginalsDir } from "../attachment-originals.ts";
+import { boxUploadsDir } from "../bot-box/plan.ts";
+import { __forgetLastComparisonForTests, compareInWorker } from "../text-changes-worker.ts";
+import { PASS } from "./table.ts";
+import { conversationFileNames, createWhatChangedRoutes, WHAT_CHANGED_MESSAGES, WHAT_CHANGED_PATH, type WhatChangedDeps } from "./what-changed.ts";
+
+const home = mkdtempSync(join(tmpdir(), "omb-what-changed-"));
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+const dataDir = join(home, "data"), store = join(dataDir, "attachments"), work = join(home, "work");
+mkdirSync(store, { recursive: true });
+mkdirSync(work);
+const UPLOAD = "6f1d2c3b-1a2b-4c3d-8e4f-0a1b2c3d4e5f.md", STRANGER = "7f1d2c3b-1a2b-4c3d-8e4f-0a1b2c3d4e5f.md";
+const ORIGINAL = "Mara walked into the bar at noon. The rain had not stopped.\n\nTom said nothing.";
+const EDITED = "Mara ran into the bar at midnight. The rain had not stopped.\n\nTom said nothing. A stranger watched.";
+const COUNTS = JSON.stringify({ changed: 1, added: 1, removed: 0, moved: 0, unchanged: 2 });
+writeFileSync(join(store, UPLOAD), ORIGINAL);
+writeFileSync(join(store, STRANGER), "not this conversation's");
+writeFileSync(join(work, "chapter-edited.md"), EDITED);
+writeFileSync(join(work, "chapter.docx"), "PK\u0003\u0004");
+writeFileSync(join(work, "huge.txt"), "x".repeat(2 * 1024 * 1024 + 1));
+writeFileSync(join(home, "elsewhere.md"), "not in the working folder");
+const attachedText = (name: string) => `Improve the dialogue\n\n<attached-file path="${join(store, name)}" name="chapter.md" />`;
+
+async function call(body: unknown, deps: Partial<WhatChangedDeps> = {}) {
+ const route = createWhatChangedRoutes({ dataDir, attachmentsDir: store, messages: () => [{ text: attachedText(UPLOAD) }], compare: compareInWorker, ...deps });
+ const json = vi.fn();
+ const outcome = await route({ method: "POST", path: WHAT_CHANGED_PATH, res: {} as never, json, botId: "bot", threadId: "thread", readBody: async () => body, folders: async () => ({ roots: [work], vmWorkspace: null }) });
+ const [, status, payload] = json.mock.calls[0] ?? [];
+ return { outcome, status: status as number | undefined, payload: payload as { text?: string; error?: string } | undefined };
+}
+
+describe("what_changed route", () => {
+ it("passes other paths on", async () => {
+ const route = createWhatChangedRoutes({ dataDir, attachmentsDir: store, messages: () => [] });
+ expect(await route({ method: "POST", path: "/api/internal/helpers/decide", res: {} as never, json: vi.fn(), botId: "b", threadId: "t", readBody: async () => ({}), folders: async () => ({ roots: [], vmWorkspace: null }) })).toBe(PASS);
+ });
+
+ it("compares the person's attachment with the bot's edit in its working folder, in a worker thread", async () => {
+ const { status, payload } = await call({ original_file: join(store, UPLOAD), edited_file: join(work, "chapter-edited.md") });
+ expect(status).toBe(200);
+ expect(payload!.text!.split("\n")).toEqual([
+ COUNTS,
+ "1. changed, paragraph 1: Mara [-walked-]{+ran+} into the bar at [-noon-]{+midnight+}.",
+ "2. added, paragraph 2: {+A stranger watched.+}",
+ WHAT_CHANGED_MESSAGES.notKept,
+ ]);
+ });
+
+ it("reads the attachment by the path a boxed turn was given", async () => {
+ const boxed = join(boxUploadsDir(dataDir, "bot", "thread"), UPLOAD);
+ const { status, payload } = await call({ original_file: boxed, edited_text: EDITED });
+ expect(status).toBe(200);
+ expect(payload!.text!.split("\n")[0]).toBe(COUNTS);
+ });
+
+ it("finds the bot's edit when it saved over the person's upload and passes that one path as both sides", async () => {
+ const name = "8f1d2c3b-1a2b-4c3d-8e4f-0a1b2c3d4e5f.md", path = join(store, name);
+ writeFileSync(path, ORIGINAL);
+ await keepUploadedOriginal(path, keptOriginalsDir(dataDir));
+ // The way an engine's atomic save replaces a file: a new file renamed over the old name.
+ writeFileSync(`${path}.tmp`, EDITED);
+ renameSync(`${path}.tmp`, path);
+ const { status, payload } = await call({ original_file: path, edited_file: path }, { messages: () => [{ text: attachedText(name) }] });
+ expect(status).toBe(200);
+ expect(payload!.text!.split("\n")[0]).toBe(COUNTS);
+ expect(payload!.text).not.toContain(WHAT_CHANGED_MESSAGES.notKept);
+ });
+
+ it("refuses a stored file this conversation does not carry, and files outside the bot's folders", async () => {
+ expect(await call({ original_file: join(store, STRANGER), edited_text: "x" })).toMatchObject({ status: 403, payload: { error: WHAT_CHANGED_MESSAGES.outside } });
+ expect(await call({ original_file: join(home, "elsewhere.md"), edited_text: "x" })).toMatchObject({ status: 403 });
+ });
+
+ it("says what is missing, what is not text and what is too large, in words a bot can act on", async () => {
+ expect(await call({ original_text: "a" })).toMatchObject({ status: 400, payload: { error: WHAT_CHANGED_MESSAGES.sides } });
+ expect(await call({ original_text: "a", original_file: join(work, "chapter-edited.md"), edited_text: "b" })).toMatchObject({ status: 400 });
+ expect(await call({ original_file: join(work, "chapter.docx"), edited_text: "b" })).toMatchObject({ status: 415, payload: { error: WHAT_CHANGED_MESSAGES.notText } });
+ expect(await call({ original_file: join(work, "huge.txt"), edited_text: "b" })).toMatchObject({ status: 413, payload: { error: WHAT_CHANGED_MESSAGES.tooLarge } });
+ expect(await call({ original_text: "a", edited_text: "b" }, { compare: async () => ({ reason: "busy" }) })).toMatchObject({ status: 429, payload: { error: WHAT_CHANGED_MESSAGES.busy } });
+ expect(await call({ original_text: "A. ".repeat(20_001), edited_text: "b" })).toMatchObject({ status: 413, payload: { error: WHAT_CHANGED_MESSAGES.tooManySentences } });
+ });
+
+ it("pages a long list from the last answer", async () => {
+ const lines = Array.from({ length: 200 }, (_, i) => `${i + 1}. added, paragraph ${i + 1}: {+x+}`);
+ const compare = vi.fn(async () => ({ list: { head: "{}", lines, coarse: false } }));
+ const page = (await call({ original_text: "a", edited_text: "b", start: 151 }, { compare })).payload!.text!.split("\n");
+ expect(page[1]).toBe("151. added, paragraph 151: {+x+}");
+ expect(page).toHaveLength(51);
+ });
+});
+
+describe("compareInWorker", () => {
+ it("runs one comparison at a time and answers a repeated one from the last answer", async () => {
+ __forgetLastComparisonForTests();
+ const first = compareInWorker(ORIGINAL, EDITED);
+ expect(await compareInWorker("other", "texts")).toEqual({ reason: "busy" });
+ const answer = await first;
+ expect("list" in answer && answer.list.head).toBe(COUNTS);
+ // A second page of the same pair, asked while another pair would be busy: no new comparison is started.
+ const again = await Promise.all([compareInWorker(ORIGINAL, EDITED), compareInWorker(ORIGINAL, EDITED)]);
+ expect(again).toEqual([answer, answer]);
+ });
+});
+
+describe("conversationFileNames", () => {
+ it("names the person's attachments and the bots' attached files, by stored name", () => {
+ expect([...conversationFileNames([
+ { text: `<attached-file path="/d/attachments/${UPLOAD}" name="a.md" />` },
+ { text: "", attachments: [{ kind: "file", path: `/d/attachments/${STRANGER}` }, { kind: "image", path: "/d/attachments/x.png" }] },
+ ])]).toEqual([UPLOAD, STRANGER]);
+ });
+});
diff --git a/server/routes/what-changed.ts b/server/routes/what-changed.ts
new file mode 100644
index 0000000000..a723880325
--- /dev/null
+++ b/server/routes/what-changed.ts
@@ -0,0 +1,133 @@
+// The internal call behind the agents server's what_changed tool. Runs inside index.ts's /api/internal/ block, after the
+// capability bearer is checked; the bot and conversation are the capability's. A file is read from the bot's own folders
+// (by the extract tool's rules) or is a file this conversation's messages carry. The original side of a person's upload
+// is the copy kept when it was sent; the edited side is always the file as it is now. The comparison runs in a worker
+// thread. Nothing read is logged.
+import { realpath, stat } from "node:fs/promises";
+import { basename, dirname, extname, join, resolve } from "node:path";
+
+import { formatChangePage, TEXT_CHANGES_MAX_SENTENCES } from "../../shared/text-changes.ts";
+import { decodeAttachmentAttribute } from "../../src/lib/composer-attachments.ts";
+import { keptOriginal, keptOriginalsDir } from "../attachment-originals.ts";
+import { boxUploadsDir } from "../bot-box/plan.ts";
+import { botFileSource, canonicalRoots, containedBy, PageBundleError, readContained } from "../pages/bundle.ts";
+import { compareInWorker, type WorkerComparison } from "../text-changes-worker.ts";
+import type { HelperToolContext } from "./helper-tools.ts";
+import { PASS } from "./table.ts";
+
+export const WHAT_CHANGED_PATH = "/api/internal/what-changed";
+export const WHAT_CHANGED_FILE_MAX_BYTES = 2 * 1024 * 1024;
+
+type Line = { text?: string; attachments?: ReadonlyArray<{ kind: string; path: string }> };
+export interface WhatChangedDeps {
+ dataDir: string;
+ attachmentsDir: string;
+ messages: (threadId: string) => readonly Line[];
+ compare?: (original: string, edited: string) => Promise<WorkerComparison>;
+}
+
+const TAG = /<attached-file[\t ]+path="([^"\r\n]*)"/g;
+const NOT_TEXT = new Set([".docx", ".doc", ".odt", ".rtf", ".pdf", ".pages", ".xlsx", ".pptx"]);
+
+export const WHAT_CHANGED_MESSAGES = {
+ sides: "Give the original as original_file or original_text, and the edited version as edited_file or edited_text.",
+ outside: "Only files in your working folder, or files attached in this conversation, can be read. Save it there first.",
+ notText: "That is not a plain text file. Word, PDF and other document files aren't read here yet: compare their text instead (save it as .txt or .md, or pass original_text / edited_text).",
+ tooLarge: "Each file may be up to 2 MB. Compare a part at a time.",
+ tooManySentences: `Each side may have up to ${TEXT_CHANGES_MAX_SENTENCES.toLocaleString("en-US")} sentences (about 300 pages). Compare a part at a time.`,
+ busy: "Another comparison is running. Try again in a moment.",
+ failed: "The comparison could not finish. Try again, or compare a smaller part.",
+ notKept: "Note: no copy of the original was kept when it was sent, so the original here is that file as it is now.",
+} as const;
+
+/** Every stored file this conversation's messages carry, by stored name: the person's attachments and the bots'. */
+export function conversationFileNames(lines: readonly Line[]): Set<string> {
+ const names = new Set<string>();
+ for (const line of lines) {
+ for (const match of (line.text ?? "").matchAll(TAG)) names.add(basename(decodeAttachmentAttribute(match[1]!)));
+ for (const attachment of line.attachments ?? []) if (attachment.kind === "file") names.add(basename(attachment.path));
+ }
+ return names;
+}
+
+type Side = { text: string; notKept?: true } | { error: string; status: number };
+type Context = HelperToolContext & { threadId: string };
+
+const missing = (file: string): Side => ({ error: `Nothing was found at ${file.slice(0, 200)}.`, status: 404 });
+
+/** The file `file` names and the folder that must hold it: a stored file this conversation carries (its kept copy for the
+ * original side), else one in the bot's own folders. */
+async function locate(ctx: Context, deps: WhatChangedDeps, file: string, original: boolean): Promise<{ target: string; root: string; notKept?: true } | Side> {
+ const name = basename(file.replaceAll("\\", "/"));
+ const folder = resolve(dirname(file));
+ const stored = folder === resolve(deps.attachmentsDir) || folder === resolve(boxUploadsDir(deps.dataDir, ctx.botId, ctx.threadId));
+ if (stored && conversationFileNames(deps.messages(ctx.threadId)).has(name)) {
+ const inStore = join(deps.attachmentsDir, name);
+ const kept = original ? keptOriginal(inStore, deps.attachmentsDir, keptOriginalsDir(deps.dataDir)) : null;
+ const target = kept ?? inStore;
+ const sentByPerson = deps.messages(ctx.threadId).some((line) => [...(line.text ?? "").matchAll(TAG)].some((match) => basename(decodeAttachmentAttribute(match[1]!)) === name));
+ const [real, root] = await Promise.all([realpath(target).catch(() => null), realpath(dirname(target)).catch(() => null)]);
+ if (!real || !root) return missing(file);
+ return { target: real, root, ...(original && !kept && sentByPerson ? { notKept: true as const } : {}) };
+ }
+ try {
+ const target = await botFileSource(file, ctx.folders);
+ const { roots, vmWorkspace } = await ctx.folders();
+ const root = (await canonicalRoots(vmWorkspace ? [vmWorkspace, ...roots] : roots)).find((each) => containedBy(each, target));
+ return root ? { target, root } : { error: WHAT_CHANGED_MESSAGES.outside, status: 403 };
+ } catch (error) {
+ if (!(error instanceof PageBundleError)) throw error;
+ return error.status === 403 ? { error: WHAT_CHANGED_MESSAGES.outside, status: 403 } : missing(file);
+ }
+}
+
+async function readSide(ctx: Context, deps: WhatChangedDeps, file: string, original: boolean): Promise<Side> {
+ const found = await locate(ctx, deps, file, original);
+ if (!("target" in found)) return found;
+ if (NOT_TEXT.has(extname(found.target).toLowerCase())) return { error: WHAT_CHANGED_MESSAGES.notText, status: 415 };
+ const info = await stat(found.target).catch(() => null);
+ if (!info?.isFile()) return missing(file);
+ if (info.size > WHAT_CHANGED_FILE_MAX_BYTES) return { error: WHAT_CHANGED_MESSAGES.tooLarge, status: 413 };
+ const bytes = await readContained(found.target, found.root).catch(() => null);
+ if (!bytes) return missing(file);
+ if (bytes.includes(0)) return { error: WHAT_CHANGED_MESSAGES.notText, status: 415 };
+ let text: string;
+ try {
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
+ } catch {
+ // Notes saved by Windows apps are often Windows-1252, not UTF-8.
+ text = new TextDecoder("windows-1252").decode(bytes);
+ }
+ return { text, ...(found.notKept ? { notKept: true as const } : {}) };
+}
+
+async function side(ctx: Context, deps: WhatChangedDeps, file: unknown, text: unknown, original: boolean): Promise<Side | null> {
+ if (typeof text === "string" && (typeof file !== "string" || !file.trim())) return { text };
+ if (typeof file === "string" && file.trim() && text === undefined) return readSide(ctx, deps, file.trim(), original);
+ return null;
+}
+
+export function createWhatChangedRoutes(deps: WhatChangedDeps) {
+ const compare = deps.compare ?? compareInWorker;
+ return async (ctx: Context): Promise<typeof PASS | void> => {
+ if (ctx.method !== "POST" || ctx.path !== WHAT_CHANGED_PATH) return PASS;
+ const body = await ctx.readBody();
+ if (!body || typeof body !== "object" || Array.isArray(body)) return void ctx.json(ctx.res, 400, { error: "Send a JSON object." });
+ const args = body as Record<string, unknown>;
+ const original = await side(ctx, deps, args.original_file, args.original_text, true);
+ const edited = await side(ctx, deps, args.edited_file, args.edited_text, false);
+ if (!original || !edited) return void ctx.json(ctx.res, 400, { error: WHAT_CHANGED_MESSAGES.sides });
+ for (const one of [original, edited]) if ("error" in one) return void ctx.json(ctx.res, one.status, { error: one.error });
+ const start = typeof args.start === "number" && Number.isSafeInteger(args.start) && args.start > 1 ? args.start : undefined;
+ const before = original as { text: string; notKept?: true };
+ const answer = await compare(before.text, (edited as { text: string }).text);
+ if ("list" in answer) {
+ const page = formatChangePage(answer.list, start ? { start } : {});
+ return void ctx.json(ctx.res, 200, { text: before.notKept ? `${page}\n${WHAT_CHANGED_MESSAGES.notKept}` : page });
+ }
+ const [status, error] = answer.reason === "too_large" ? [413, WHAT_CHANGED_MESSAGES.tooLarge]
+ : answer.reason === "too_many_sentences" ? [413, WHAT_CHANGED_MESSAGES.tooManySentences]
+ : answer.reason === "busy" ? [429, WHAT_CHANGED_MESSAGES.busy] : [500, WHAT_CHANGED_MESSAGES.failed];
+ return void ctx.json(ctx.res, status, { error });
+ };
+}
diff --git a/server/text-changes-worker.ts b/server/text-changes-worker.ts
new file mode 100644
index 0000000000..fb32462068
--- /dev/null
+++ b/server/text-changes-worker.ts
@@ -0,0 +1,52 @@
+import { createHash } from "node:crypto";
+import { existsSync } from "node:fs";
+import { Worker } from "node:worker_threads";
+import type { ChangeList } from "../shared/text-changes.ts";
+
+export type WorkerComparison = { list: ChangeList } | { reason: "too_large" | "too_many_sentences" | "failed" | "timeout" | "busy" };
+
+const TIMEOUT_MS = 30_000;
+/** The last answer, so asking for the next page of a long list never compares again. */
+const KEEP_LAST_MS = 5 * 60_000;
+let running = false;
+let last: { key: string; list: ChangeList; until: number } | null = null;
+
+/** compareTexts in a worker thread of its own, so a long document never holds the server's event loop: one at a time
+ * (a Cloud home may have 2 GB and a shared core), stopped after 30 seconds, and held to a small heap. With the
+ * sentence limit in text-changes.ts its worst case stays well under 200 MB. */
+export function compareInWorker(original: string, edited: string): Promise<WorkerComparison> {
+ const key = createHash("sha256").update(original).update("\0").update(edited).digest("hex");
+ if (last && last.key === key && last.until > Date.now()) return Promise.resolve({ list: last.list });
+ if (running) return Promise.resolve({ reason: "busy" });
+ running = true;
+ last = null;
+ const source = new URL("./text-changes.worker.ts", import.meta.url);
+ return new Promise<WorkerComparison>((resolve) => {
+ let worker: Worker;
+ try {
+ worker = new Worker(existsSync(source) ? source : new URL("./text-changes.worker.js", import.meta.url), {
+ execArgv: [], resourceLimits: { maxOldGenerationSizeMb: 128, maxYoungGenerationSizeMb: 8 },
+ });
+ } catch {
+ return resolve({ reason: "failed" });
+ }
+ let settled = false;
+ const finish = (answer: WorkerComparison) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ void worker.terminate();
+ if ("list" in answer) last = { key, list: answer.list, until: Date.now() + KEEP_LAST_MS };
+ resolve(answer);
+ };
+ const timer = setTimeout(() => finish({ reason: "timeout" }), TIMEOUT_MS);
+ worker.once("message", (reply: WorkerComparison) => finish(reply));
+ worker.once("error", () => finish({ reason: "failed" }));
+ worker.once("exit", () => finish({ reason: "failed" }));
+ worker.postMessage({ original, edited });
+ }).finally(() => { running = false; });
+}
+
+export function __forgetLastComparisonForTests(): void {
+ last = null;
+}
diff --git a/server/text-changes.worker.ts b/server/text-changes.worker.ts
new file mode 100644
index 0000000000..7e93c26e15
--- /dev/null
+++ b/server/text-changes.worker.ts
@@ -0,0 +1,12 @@
+import { parentPort } from "node:worker_threads";
+import { changeList, compareTexts } from "../shared/text-changes.ts";
+
+parentPort!.once("message", (request: { original: string; edited: string }) => {
+ try {
+ const result = compareTexts(request.original, request.edited);
+ parentPort!.postMessage(result.ok ? { list: changeList(result) } : { reason: result.reason });
+ } catch {
+ // An error message could quote the documents.
+ parentPort!.postMessage({ reason: "failed" });
+ }
+});
diff --git a/server/workspace-backup-team-private.test.ts b/server/workspace-backup-team-private.test.ts
index a19b1a0847..afbd1e7748 100644
--- a/server/workspace-backup-team-private.test.ts
+++ b/server/workspace-backup-team-private.test.ts
@@ -98,6 +98,8 @@ describe("what a Team Cloud's export leaves out (the private sentence: not the O
expect([...attachments].sort()).toEqual(["bobs.png", "unsent.png"]);
expect(omittedAsTeamPrivate("attachments/bobs.png", { ...privacy, attachments })).toBe(true);
expect(omittedAsTeamPrivate("attachments/both.png", { ...privacy, attachments })).toBe(false);
+ expect(omittedAsTeamPrivate("attachment-originals/bobs.png", { ...privacy, attachments })).toBe(true);
+ expect(omittedAsTeamPrivate("attachment-originals/both.png", { ...privacy, attachments })).toBe(false);
expect(omittedAsTeamPrivate(`workspaces/bot--member-${BOB}/MEMORY.md`, privacy)).toBe(true);
expect(omittedAsTeamPrivate("workspaces/bot--room-room/MEMORY.md", privacy)).toBe(false);
expect(omittedAsTeamPrivate("workspaces/bot/MEMORY.md", privacy)).toBe(false);
diff --git a/server/workspace-backup-team-private.ts b/server/workspace-backup-team-private.ts
index 91d74d7b0b..f53093da45 100644
--- a/server/workspace-backup-team-private.ts
+++ b/server/workspace-backup-team-private.ts
@@ -60,7 +60,8 @@ const memberLayer = (id: string): boolean => isLayerId(id) && layerAudience(id).
export function omittedAsTeamPrivate(path: string, privacy: TeamPrivacy): boolean {
if (/^(?:people(?:\/|$)|person-inbox\.json)/.test(path)) return true;
if (/^bots\/[^/]+\/data\.duckdb(?:\.wal)?$/.test(path)) return true;
- const attachment = /^attachments\/([^/]+)$/.exec(path)?.[1];
+ // A kept copy of an upload (attachment-originals.ts) is as private as the upload.
+ const attachment = /^(?:attachments|attachment-originals)\/([^/]+)$/.exec(path)?.[1];
if (attachment && privacy.attachments.has(attachment)) return true;
return path.split("/").some((part) => {
const name = part.replace(/\.[^-]*$/, "");
diff --git a/shared/text-changes.test.ts b/shared/text-changes.test.ts
new file mode 100644
index 0000000000..e701354ba2
--- /dev/null
+++ b/shared/text-changes.test.ts
@@ -0,0 +1,169 @@
+import { describe, expect, it } from "vitest";
+
+import { compareTexts, formatTextChanges, splitSentences, TEXT_CHANGES_MAX_CHARS, TEXT_CHANGES_MAX_SENTENCES, wordParts, type TextChanges } from "./text-changes";
+
+function changes(before: string, after: string): TextChanges {
+ const result = compareTexts(before, after);
+ if (!result.ok) throw new Error(result.reason);
+ return result;
+}
+
+const CHAPTER = [
+ "Mara walked into the bar at noon. The rain had not stopped for three days.",
+ "\"You're late,\" said Tom. He did not look up from the glass he was drying.",
+ "She sat down without a word. Tom poured her a drink, and she drank it slowly.",
+ "Outside, a car alarm went off.",
+].join("\n\n");
+
+describe("compareTexts on prose", () => {
+ it("reports nothing for the same text, whatever its line endings, byte order mark or Unicode composition", () => {
+ const crlf = `${CHAPTER.replace(/\n/g, "\r\n")}`;
+ expect(changes(CHAPTER, crlf).counts).toEqual({ changed: 0, added: 0, removed: 0, moved: 0, unchanged: 7 });
+ const composed = "Zoë said café.", decomposed = "Zoë said café.";
+ expect(changes(composed, decomposed).counts.changed).toBe(0);
+ });
+
+ it("finds a changed event and an added detail, word by word", () => {
+ const edited = CHAPTER
+ .replace("walked into the bar at noon", "ran into the bar at midnight")
+ .replace("drank it slowly.", "drank it slowly. A stranger watched from the corner.");
+ const result = changes(CHAPTER, edited);
+ expect(result.counts).toEqual({ changed: 1, added: 1, removed: 0, moved: 0, unchanged: 6 });
+ const changed = result.segments.find((segment) => segment.kind === "changed");
+ expect(changed).toMatchObject({ para: 1, beforePara: 1, minor: false });
+ expect(changed?.kind === "changed" && changed.parts.filter((part) => part.op !== "same")).toEqual([
+ { op: "del", text: "walked" }, { op: "add", text: "ran" }, { op: "del", text: "noon" }, { op: "add", text: "midnight" },
+ ]);
+ expect(result.segments.find((segment) => segment.kind === "added")).toMatchObject({ para: 3, text: "A stranger watched from the corner." });
+ });
+
+ it("counts a removed sentence once and keeps where it was", () => {
+ const result = changes(CHAPTER, CHAPTER.replace(" He did not look up from the glass he was drying.", ""));
+ expect(result.counts).toMatchObject({ removed: 1, changed: 0, added: 0 });
+ expect(result.segments.find((segment) => segment.kind === "removed")).toMatchObject({ beforePara: 2, text: "He did not look up from the glass he was drying." });
+ });
+
+ it("calls a paragraph moved elsewhere moved, not removed and added", () => {
+ const paragraphs = CHAPTER.split("\n\n");
+ const moved = [paragraphs[0], paragraphs[2], paragraphs[3], paragraphs[1]].join("\n\n");
+ const result = changes(CHAPTER, moved);
+ expect(result.counts).toMatchObject({ added: 0, removed: 0, changed: 0, moved: 2 });
+ expect(result.segments.filter((segment) => segment.kind === "moved").map((segment) => segment.kind === "moved" && [segment.beforePara, segment.para])).toEqual([[2, 4], [2, 4]]);
+ });
+
+ it("marks a change of punctuation or case only as minor, also when the sentence moved", () => {
+ const result = changes("She sat down without a word. Then she left.", "She sat down without a word! Then she left.");
+ expect(result.counts).toMatchObject({ changed: 1, unchanged: 1 });
+ expect(result.segments[0]).toMatchObject({ kind: "changed", minor: true });
+ const moved = changes("One here.\n\nShe sat down without a word.\n\nTwo here.", "One here.\n\nTwo here.\n\nshe sat down without a word!");
+ expect(moved.counts).toMatchObject({ changed: 1, removed: 0, added: 0, moved: 0 });
+ expect(moved.segments.find((segment) => segment.kind === "changed")).toMatchObject({ minor: true, beforePara: 2, para: 3 });
+ });
+
+ it("re-wrapping a paragraph changes nothing, while dialogue on its own line stays its own sentence", () => {
+ const wrapped = "Mara walked into the bar at noon. The rain had\nnot stopped for three days.";
+ expect(changes("Mara walked into the bar at noon. The rain had not stopped for three days.", wrapped).counts.changed).toBe(0);
+ expect(splitSentences("\"Late again,\" he said\n\"Sorry\"").map((unit) => unit.key)).toEqual(["\"Late again,\" he said", "\"Sorry\""]);
+ });
+
+ it("handles scripts without spaces and characters outside the basic plane", () => {
+ const result = changes("我走进了酒吧。外面在下雨。🙂 Done.", "我跑进了酒吧。外面在下雨。🙃 Done.");
+ expect(result.counts.unchanged).toBeGreaterThanOrEqual(1);
+ expect(result.counts.changed + result.counts.added + result.counts.removed).toBeGreaterThanOrEqual(1);
+ const rejoined = result.segments.map((segment) => segment.kind === "changed" ? segment.after : segment.kind === "removed" ? "" : segment.text).join("");
+ expect(rejoined).toBe("我跑进了酒吧。外面在下雨。🙃 Done.");
+ });
+
+ it("splits a very long line into bounded pieces, so one changed word costs little", () => {
+ const line = Array.from({ length: 30_000 }, (_, i) => `word${i % 97}`).join(" ");
+ const edited = line.replace("word50 word51", "word50 CHANGED");
+ const result = changes(line, edited);
+ expect(result.counts.changed).toBe(1);
+ expect(result.counts.unchanged).toBeGreaterThan(200);
+ for (const unit of splitSentences(line)) expect(unit.text.length).toBeLessThanOrEqual(800);
+ expect(result.work).toBeLessThan(2_000_000);
+ });
+
+ it("keeps the edited text whole: unchanged, changed, added and moved pieces give it back", () => {
+ const edited = CHAPTER.replace("noon", "dusk").replace("Outside, a car alarm went off.", "Outside, a car alarm went off. Nobody moved.");
+ const result = changes(CHAPTER, edited);
+ const byPara = new Map<number, string>();
+ for (const segment of result.segments) {
+ const text = segment.kind === "changed" ? segment.after : segment.kind === "removed" ? "" : segment.text;
+ byPara.set(segment.para, (byPara.get(segment.para) ?? "") + text);
+ }
+ expect([...byPara.values()].map((text) => text.trim()).join("\n\n")).toBe(edited);
+ });
+});
+
+describe("compareTexts bounds", () => {
+ it("refuses more than the limit on either side", () => {
+ expect(compareTexts("x".repeat(TEXT_CHANGES_MAX_CHARS + 1), "y")).toEqual({ ok: false, reason: "too_large" });
+ });
+
+ it("compares two wholly different long texts coarsely, within the work budget, and still lists every sentence", () => {
+ const one = Array.from({ length: 6_000 }, (_, i) => `Alpha ${i} went home.`).join(" ");
+ const two = Array.from({ length: 6_000 }, (_, i) => `Beta ${i} stayed out.`).join(" ");
+ const result = changes(one, two);
+ expect(result.coarse).toBe(true);
+ expect(result.work).toBeLessThan(60_000_000);
+ expect(result.counts.changed + result.counts.removed).toBe(6_000);
+ expect(result.counts.changed + result.counts.added).toBe(6_000);
+ });
+
+ it("never calls a sentence moved in a stretch it could only align roughly", () => {
+ const short = ["The cat sat.", "He left.", "She smiled.", "It rained."];
+ const lines = Array.from({ length: 3_000 }, (_, i) => short[i % short.length]!);
+ const edited = [...lines];
+ edited[200] = "The dog sat.";
+ edited[2_802] = "She frowned.";
+ const result = changes(lines.join(" "), edited.join(" "));
+ expect(result.coarse).toBe(true);
+ expect(result.counts).toMatchObject({ moved: 0, changed: 2, added: 0, removed: 0, unchanged: 2_998 });
+ });
+
+ it("refuses more sentences than it can hold in bounded memory, before aligning anything", () => {
+ expect(compareTexts("A. ".repeat(TEXT_CHANGES_MAX_SENTENCES + 1), "A.")).toEqual({ ok: false, reason: "too_many_sentences" });
+ });
+
+ it("keeps a near-identical long text exact through unique anchors", () => {
+ const sentences = Array.from({ length: 19_000 }, (_, i) => `Sentence number ${i} is here.`);
+ const edited = [...sentences];
+ edited[10_000] = "Sentence number 10000 is not here.";
+ const result = changes(sentences.join(" "), edited.join(" "));
+ expect(result.coarse).toBe(false);
+ expect(result.counts).toMatchObject({ changed: 1, unchanged: 18_999 });
+ expect(result.work).toBeLessThan(500_000);
+ });
+
+ it("gives up word detail, never the change, when one sentence pair is too long to align", () => {
+ const parts = wordParts("a ".repeat(400), "b ".repeat(400));
+ expect(parts.length).toBeGreaterThan(0);
+ expect(parts.filter((part) => part.op === "add").map((part) => part.text).join("").replace(/\s/g, "")).toBe("b".repeat(400));
+ });
+});
+
+describe("formatTextChanges", () => {
+ it("starts with the counts as JSON and marks words the wdiff way", () => {
+ const text = formatTextChanges(changes(CHAPTER, CHAPTER.replace("noon", "dusk").replace("drank it slowly.", "drank it slowly. Later.")));
+ const [head, ...lines] = text.split("\n");
+ expect(JSON.parse(head!)).toEqual({ changed: 1, added: 1, removed: 0, moved: 0, unchanged: 6 });
+ expect(lines[0]).toBe("1. changed, paragraph 1: Mara walked into the bar at [-noon-]{+dusk+}.");
+ });
+
+ it("says so when nothing changed", () => {
+ expect(formatTextChanges(changes("Same.", "Same."))).toBe(`${JSON.stringify({ changed: 0, added: 0, removed: 0, moved: 0, unchanged: 1 })}\nNo changes: the two texts say the same thing, sentence for sentence.`);
+ });
+
+ it("pages a long list and tells the caller where to start next", () => {
+ const before = Array.from({ length: 40 }, (_, i) => `Line ${i} stays as written here.`).join("\n\n");
+ const after = Array.from({ length: 40 }, (_, i) => `Line ${i} stays as rewritten here.`).join("\n\n");
+ const result = changes(before, after);
+ const first = formatTextChanges(result, { limit: 25 }).split("\n");
+ expect(first).toHaveLength(27);
+ expect(first.at(-1)).toBe("15 more not listed here; the counts above are complete. Call again with start: 26 for the rest.");
+ const second = formatTextChanges(result, { start: 26, limit: 25 }).split("\n");
+ expect(second[1]!.startsWith("26. changed, paragraph 26:")).toBe(true);
+ expect(second).toHaveLength(16);
+ });
+});
diff --git a/shared/text-changes.ts b/shared/text-changes.ts
new file mode 100644
index 0000000000..142863c9ec
--- /dev/null
+++ b/shared/text-changes.ts
@@ -0,0 +1,456 @@
+/** What changed between a document and its edited version, sentence by sentence, with the words inside each changed
+ * sentence. One implementation for the chat's "What changed" view and the bots' `what_changed` tool, so the two always
+ * report the same counts. Pure and synchronous: callers run it in a worker, never on a server's event loop or the UI
+ * thread. Every step has a work bound; a part too costly to align closely is still reported in full, sentence by
+ * sentence (`coarse`), never left out. */
+
+export const TEXT_CHANGES_MAX_CHARS = 4 * 1024 * 1024;
+/** Sentences per side: past this a comparison is refused, which keeps its memory bounded (20,000 sentences is about
+ * 1.4 MB of ordinary prose, some 300 pages). */
+export const TEXT_CHANGES_MAX_SENTENCES = 20_000;
+const UNIT_MAX_CHARS = 800;
+const GAP_CELLS = 1_000_000;
+const WORK_BUDGET = 60_000_000;
+const PAIR_CELLS = 40_000;
+const WORD_CELLS = 250_000;
+const MAX_DEPTH = 64;
+const SIMILAR = 0.4;
+
+export interface TextChangeCounts { changed: number; added: number; removed: number; moved: number; unchanged: number }
+export type WordPart = { op: "same" | "add" | "del"; text: string };
+/** `para`: the paragraph (1-based) of the edited text it sits in; `beforePara`: the original's. */
+export type ChangeSegment =
+ | { kind: "same"; para: number; text: string }
+ | { kind: "changed"; para: number; beforePara: number; before: string; after: string; parts: WordPart[]; minor: boolean }
+ | { kind: "added"; para: number; text: string }
+ | { kind: "removed"; para: number; beforePara: number; text: string }
+ | { kind: "moved"; para: number; beforePara: number; text: string };
+export interface TextChanges {
+ counts: TextChangeCounts;
+ segments: ChangeSegment[];
+ /** Some stretch was too different to align closely: its sentences are reported as removed and added. */
+ coarse: boolean;
+ /** Work units spent, for the bounds tests. */
+ work: number;
+}
+export type TextComparison = ({ ok: true } & TextChanges) | { ok: false; reason: "too_large" | "too_many_sentences" };
+
+interface Unit { text: string; key: string; loose: string; para: number; words?: Uint32Array }
+/** `rough`: from a stretch too costly to align, where a sentence's place says nothing. */
+type Op = { op: "eq"; a: number; b: number } | { op: "del"; a: number; rough?: true } | { op: "ins"; b: number; rough?: true };
+
+let sentences: Intl.Segmenter | undefined;
+let words: Intl.Segmenter | undefined;
+const sentenceSegmenter = () => (sentences ??= new Intl.Segmenter("en", { granularity: "sentence" }));
+const wordSegmenter = () => (words ??= new Intl.Segmenter("en", { granularity: "word" }));
+
+/** Byte order mark, CRLF and Unicode composition never count as changes. */
+export function normalizeText(text: string): string {
+ return text.replace(/^/, "").replace(/\r\n?/g, "\n").normalize("NFC");
+}
+
+const keyOf = (text: string) => text.replace(/\s+/g, " ").trim();
+const looseOf = (key: string) => key.toLowerCase().replace(/[\p{P}\p{S}]+/gu, "").replace(/\s+/g, " ").trim();
+
+function pushUnit(units: Unit[], text: string, para: number): void {
+ while (text.length > UNIT_MAX_CHARS) {
+ let cut = text.lastIndexOf(" ", UNIT_MAX_CHARS - 1) + 1;
+ if (cut < UNIT_MAX_CHARS / 2) cut = UNIT_MAX_CHARS;
+ if (/[\uD800-\uDBFF]/.test(text[cut - 1] ?? "")) cut -= 1;
+ pushPiece(units, text.slice(0, cut), para);
+ text = text.slice(cut);
+ }
+ pushPiece(units, text, para);
+}
+
+function pushPiece(units: Unit[], text: string, para: number): void {
+ const key = keyOf(text);
+ if (!key) {
+ if (units.length && units[units.length - 1]!.para === para) units[units.length - 1]!.text += text;
+ return;
+ }
+ units.push({ text, key, loose: looseOf(key), para });
+}
+
+/** Paragraphs are blocks between blank lines. A line break followed by a lower-case letter is a wrapped sentence, so
+ * re-wrapping a paragraph changes nothing; any other line (dialogue, a list item) starts a new sentence. */
+export function splitSentences(text: string, max = Infinity): Unit[] | null {
+ const units: Unit[] = [];
+ let para = 0;
+ for (const block of text.split(/\n[\t ]*\n\s*/)) {
+ if (!block.trim()) continue;
+ para += 1;
+ const prepared = block.replace(/\n(?=[\t ]*\p{Ll})/gu, " ");
+ for (const { index, segment } of sentenceSegmenter().segment(prepared)) {
+ pushUnit(units, block.slice(index, index + segment.length), para);
+ if (units.length > max) return null;
+ }
+ }
+ return units;
+}
+
+/** A sentence's distinct words as sorted 32-bit hashes: a few bytes a word, where a Set of strings costs hundreds. */
+function wordSet(unit: Unit): Uint32Array {
+ if (!unit.words) {
+ const hashes: number[] = [];
+ for (const part of wordSegmenter().segment(unit.loose)) {
+ if (!part.isWordLike) continue;
+ let hash = 2166136261;
+ for (let i = 0; i < part.segment.length; i++) hash = Math.imul(hash ^ part.segment.charCodeAt(i), 16777619);
+ hashes.push(hash >>> 0);
+ }
+ const sorted = Uint32Array.from(hashes).sort();
+ let size = 0;
+ for (let i = 0; i < sorted.length; i++) if (!i || sorted[i] !== sorted[i - 1]) sorted[size++] = sorted[i]!;
+ unit.words = sorted.slice(0, size);
+ }
+ return unit.words;
+}
+
+function similarity(a: Unit, b: Unit): number {
+ const left = wordSet(a), right = wordSet(b);
+ if (!left.length || !right.length) return a.loose === b.loose ? 1 : 0;
+ let shared = 0;
+ for (let i = 0, j = 0; i < left.length && j < right.length;) {
+ if (left[i] === right[j]) { shared += 1; i++; j++; }
+ else if (left[i]! < right[j]!) i++;
+ else j++;
+ }
+ return (2 * shared) / (left.length + right.length);
+}
+
+class Aligner {
+ work = 0;
+ coarse = false;
+ readonly out: Op[] = [];
+ private readonly a: readonly string[];
+ private readonly b: readonly string[];
+ constructor(a: readonly string[], b: readonly string[]) {
+ this.a = a;
+ this.b = b;
+ }
+
+ run(a0: number, a1: number, b0: number, b1: number, depth: number): void {
+ const { a, b, out } = this;
+ while (a0 < a1 && b0 < b1 && a[a0] === b[b0]) out.push({ op: "eq", a: a0++, b: b0++ });
+ let tail = 0;
+ while (a1 - tail > a0 && b1 - tail > b0 && a[a1 - 1 - tail] === b[b1 - 1 - tail]) tail += 1;
+ this.middle(a0, a1 - tail, b0, b1 - tail, depth);
+ for (let i = tail; i > 0; i--) out.push({ op: "eq", a: a1 - i, b: b1 - i });
+ }
+
+ private middle(a0: number, a1: number, b0: number, b1: number, depth: number): void {
+ const { out } = this;
+ this.work += a1 - a0 + b1 - b0;
+ if (a0 === a1 || b0 === b1) {
+ for (let i = a0; i < a1; i++) out.push({ op: "del", a: i });
+ for (let j = b0; j < b1; j++) out.push({ op: "ins", b: j });
+ return;
+ }
+ const anchors = depth < MAX_DEPTH ? this.anchors(a0, a1, b0, b1) : [];
+ if (anchors.length) {
+ let ai = a0, bj = b0;
+ for (const [i, j] of anchors) {
+ this.run(ai, i, bj, j, depth + 1);
+ out.push({ op: "eq", a: i, b: j });
+ ai = i + 1;
+ bj = j + 1;
+ }
+ this.run(ai, a1, bj, b1, depth + 1);
+ return;
+ }
+ const cells = (a1 - a0) * (b1 - b0);
+ if (cells <= GAP_CELLS && this.work + cells <= WORK_BUDGET) return this.lcs(a0, a1, b0, b1);
+ this.coarse = true;
+ for (let i = a0; i < a1; i++) out.push({ op: "del", a: i, rough: true });
+ for (let j = b0; j < b1; j++) out.push({ op: "ins", b: j, rough: true });
+ }
+
+ /** Sentences that occur exactly once on each side, kept in an order both sides agree on (patience diff). */
+ private anchors(a0: number, a1: number, b0: number, b1: number): Array<[number, number]> {
+ const seen = new Map<string, { a: number; na: number; b: number; nb: number }>();
+ for (let i = a0; i < a1; i++) {
+ const entry = seen.get(this.a[i]!);
+ if (entry) entry.na += 1;
+ else seen.set(this.a[i]!, { a: i, na: 1, b: -1, nb: 0 });
+ }
+ for (let j = b0; j < b1; j++) {
+ const entry = seen.get(this.b[j]!);
+ if (entry) { entry.nb += 1; entry.b = j; }
+ }
+ const pairs: Array<[number, number]> = [];
+ for (const entry of seen.values()) if (entry.na === 1 && entry.nb === 1) pairs.push([entry.a, entry.b]);
+ pairs.sort((x, y) => x[0] - y[0]);
+ this.work += pairs.length * 2;
+ const tops: number[] = [], back = new Int32Array(pairs.length).fill(-1);
+ for (let k = 0; k < pairs.length; k++) {
+ let lo = 0, hi = tops.length;
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1;
+ if (pairs[tops[mid]!]![1] < pairs[k]![1]) lo = mid + 1;
+ else hi = mid;
+ }
+ if (lo > 0) back[k] = tops[lo - 1]!;
+ tops[lo] = k;
+ }
+ const chain: Array<[number, number]> = [];
+ for (let k = tops.length ? tops[tops.length - 1]! : -1; k >= 0; k = back[k]!) chain.push(pairs[k]!);
+ return chain.reverse();
+ }
+
+ private lcs(a0: number, a1: number, b0: number, b1: number): void {
+ const { a, b, out } = this;
+ const n = a1 - a0, m = b1 - b0, width = m + 1;
+ this.work += n * m;
+ const table = new Uint32Array((n + 1) * width);
+ for (let i = n - 1; i >= 0; i--) {
+ for (let j = m - 1; j >= 0; j--) {
+ table[i * width + j] = a[a0 + i] === b[b0 + j] ? table[(i + 1) * width + j + 1]! + 1 : Math.max(table[(i + 1) * width + j]!, table[i * width + j + 1]!);
+ }
+ }
+ let i = 0, j = 0;
+ while (i < n && j < m) {
+ if (a[a0 + i] === b[b0 + j]) out.push({ op: "eq", a: a0 + i++, b: b0 + j++ });
+ else if (table[(i + 1) * width + j]! >= table[i * width + j + 1]!) out.push({ op: "del", a: a0 + i++ });
+ else out.push({ op: "ins", b: b0 + j++ });
+ }
+ while (i < n) out.push({ op: "del", a: a0 + i++ });
+ while (j < m) out.push({ op: "ins", b: b0 + j++ });
+ }
+}
+
+/** The words inside one changed sentence: spaces and punctuation are their own tokens, so a changed comma shows alone. */
+export function wordParts(before: string, after: string): WordPart[] {
+ const split = (text: string) => Array.from(wordSegmenter().segment(text), (part) => part.segment);
+ const x = split(before), y = split(after);
+ const same = (p: string, q: string) => p === q || (!p.trim() && !q.trim());
+ const parts: WordPart[] = [];
+ const push = (op: WordPart["op"], text: string) => {
+ const last = parts[parts.length - 1];
+ if (last?.op === op) last.text += text;
+ else parts.push({ op, text });
+ };
+ const n = x.length, m = y.length;
+ if (n * m > WORD_CELLS) return [{ op: "del", text: before }, { op: "add", text: after }];
+ const width = m + 1, table = new Uint32Array((n + 1) * width);
+ for (let i = n - 1; i >= 0; i--) {
+ for (let j = m - 1; j >= 0; j--) {
+ table[i * width + j] = same(x[i]!, y[j]!) ? table[(i + 1) * width + j + 1]! + 1 : Math.max(table[(i + 1) * width + j]!, table[i * width + j + 1]!);
+ }
+ }
+ let i = 0, j = 0;
+ while (i < n && j < m) {
+ if (same(x[i]!, y[j]!)) { push("same", y[j]!); i++; j++; }
+ else if (table[(i + 1) * width + j]! >= table[i * width + j + 1]!) push("del", x[i++]!);
+ else push("add", y[j++]!);
+ }
+ while (i < n) push("del", x[i++]!);
+ while (j < m) push("add", y[j++]!);
+ return joinedRuns(parts);
+}
+
+/** Changes separated only by spaces read as one: "[-The train was late-]{+Blame the train+}", not word by word. */
+function joinedRuns(parts: WordPart[]): WordPart[] {
+ const out: WordPart[] = [];
+ for (let k = 0; k < parts.length;) {
+ if (parts[k]!.op === "same") { out.push(parts[k++]!); continue; }
+ let before = "", after = "", end = k;
+ for (let at = k; at < parts.length; at++) {
+ const part = parts[at]!;
+ if (part.op === "same" && (part.text.trim() || parts[at + 1]?.op === "same" || at + 1 === parts.length)) break;
+ if (part.op !== "add") before += part.text;
+ if (part.op !== "del") after += part.text;
+ end = at + 1;
+ }
+ if (before) out.push({ op: "del", text: before });
+ if (after) out.push({ op: "add", text: after });
+ k = end;
+ }
+ return out;
+}
+
+type Step = { kind: "removed"; a: number } | { kind: "added"; b: number } | { kind: "changed"; a: number; b: number };
+
+/** Pairs a hunk's removed and added sentences into changed ones where they share enough words, in order. */
+function pairHunk(dels: number[], inss: number[], A: Unit[], B: Unit[], tally: { work: number }): Step[] {
+ const n = dels.length, m = inss.length, steps: Step[] = [];
+ if (!n || !m) return [...dels.map((a) => ({ kind: "removed" as const, a })), ...inss.map((b) => ({ kind: "added" as const, b }))];
+ const sim = (i: number, j: number) => similarity(A[dels[i]!]!, B[inss[j]!]!);
+ if (n * m <= PAIR_CELLS) {
+ tally.work += n * m;
+ const width = m + 1, score = new Float64Array((n + 1) * width);
+ const scores = new Float64Array(n * m);
+ for (let i = 0; i < n; i++) for (let j = 0; j < m; j++) scores[i * m + j] = sim(i, j);
+ for (let i = n - 1; i >= 0; i--) {
+ for (let j = m - 1; j >= 0; j--) {
+ const s = scores[i * m + j]!;
+ score[i * width + j] = Math.max(s >= SIMILAR ? s + score[(i + 1) * width + j + 1]! : 0, score[(i + 1) * width + j]!, score[i * width + j + 1]!);
+ }
+ }
+ let i = 0, j = 0;
+ while (i < n && j < m) {
+ const s = scores[i * m + j]!;
+ if (s >= SIMILAR && score[i * width + j] === s + score[(i + 1) * width + j + 1]!) steps.push({ kind: "changed", a: dels[i++]!, b: inss[j++]! });
+ else if (score[(i + 1) * width + j]! >= score[i * width + j + 1]!) steps.push({ kind: "removed", a: dels[i++]! });
+ else steps.push({ kind: "added", b: inss[j++]! });
+ }
+ while (i < n) steps.push({ kind: "removed", a: dels[i++]! });
+ while (j < m) steps.push({ kind: "added", b: inss[j++]! });
+ return steps;
+ }
+ let i = 0, j = 0;
+ while (i < n && j < m) {
+ tally.work += 2;
+ if (sim(i, j) >= SIMILAR) steps.push({ kind: "changed", a: dels[i++]!, b: inss[j++]! });
+ else if (j + 1 < m && sim(i, j + 1) >= SIMILAR) steps.push({ kind: "added", b: inss[j++]! });
+ else steps.push({ kind: "removed", a: dels[i++]! });
+ }
+ while (i < n) steps.push({ kind: "removed", a: dels[i++]! });
+ while (j < m) steps.push({ kind: "added", b: inss[j++]! });
+ return steps;
+}
+
+export function compareTexts(original: string, edited: string): TextComparison {
+ if (original.length > TEXT_CHANGES_MAX_CHARS || edited.length > TEXT_CHANGES_MAX_CHARS) return { ok: false, reason: "too_large" };
+ const A = splitSentences(normalizeText(original), TEXT_CHANGES_MAX_SENTENCES);
+ const B = A && splitSentences(normalizeText(edited), TEXT_CHANGES_MAX_SENTENCES);
+ if (!A || !B) return { ok: false, reason: "too_many_sentences" };
+ const aligner = new Aligner(A.map((unit) => unit.key), B.map((unit) => unit.key));
+ aligner.run(0, A.length, 0, B.length, 0);
+ const ops = aligner.out;
+ const tally = { work: aligner.work + A.length + B.length };
+
+ // A sentence removed in one place and added in another moved: word for word, or with only punctuation or case changed.
+ // A stretch aligned only roughly is left out: its sentences' places were never matched, so nothing there moved.
+ const movedFrom = new Map<number, { a: number; exact: boolean }>(), movedAway = new Set<number>();
+ for (const field of ["key", "loose"] as const) {
+ const removed = new Map<string, { at: number; list: number[] }>();
+ for (const op of ops) {
+ if (op.op !== "del" || op.rough || movedAway.has(op.a)) continue;
+ const entry = removed.get(A[op.a]![field]);
+ if (entry) entry.list.push(op.a);
+ else removed.set(A[op.a]![field], { at: 0, list: [op.a] });
+ }
+ for (const op of ops) {
+ if (op.op !== "ins" || op.rough || movedFrom.has(op.b)) continue;
+ const entry = removed.get(B[op.b]![field]);
+ const from = entry && entry.at < entry.list.length ? entry.list[entry.at++] : undefined;
+ if (from === undefined) continue;
+ movedFrom.set(op.b, { a: from, exact: field === "key" });
+ movedAway.add(from);
+ }
+ }
+
+ const counts: TextChangeCounts = { changed: 0, added: 0, removed: 0, moved: 0, unchanged: 0 };
+ const segments: ChangeSegment[] = [];
+ const changedSegment = (before: Unit, after: Unit): ChangeSegment => {
+ tally.work += before.text.length + after.text.length;
+ return { kind: "changed", para: after.para, beforePara: before.para, before: before.text, after: after.text, parts: wordParts(before.text, after.text), minor: before.loose === after.loose };
+ };
+ const paraAt = (b: number) => B[Math.min(b, B.length - 1)]?.para ?? 1;
+ let k = 0;
+ while (k < ops.length) {
+ const op = ops[k]!;
+ if (op.op === "eq") {
+ counts.unchanged += 1;
+ segments.push({ kind: "same", para: B[op.b]!.para, text: B[op.b]!.text });
+ k += 1;
+ continue;
+ }
+ const dels: number[] = [], inss: number[] = [], moved: number[] = [];
+ let nextB = B.length;
+ for (; k < ops.length && ops[k]!.op !== "eq"; k++) {
+ const step = ops[k]!;
+ if (step.op === "del") { if (!movedAway.has(step.a)) dels.push(step.a); }
+ else if (step.op === "ins") (movedFrom.has(step.b) ? moved : inss).push(step.b);
+ }
+ if (k < ops.length) nextB = (ops[k] as { b: number }).b;
+ const queue = [...moved];
+ const flush = (until: number) => {
+ while (queue.length && queue[0]! < until) {
+ const b = queue.shift()!, from = movedFrom.get(b)!;
+ if (from.exact) {
+ counts.moved += 1;
+ segments.push({ kind: "moved", para: B[b]!.para, beforePara: A[from.a]!.para, text: B[b]!.text });
+ } else {
+ counts.changed += 1;
+ segments.push(changedSegment(A[from.a]!, B[b]!));
+ }
+ }
+ };
+ for (const step of pairHunk(dels, inss, A, B, tally)) {
+ if (step.kind === "removed") {
+ counts.removed += 1;
+ const at = inss.find((b) => b >= 0) ?? nextB;
+ segments.push({ kind: "removed", para: paraAt(at), beforePara: A[step.a]!.para, text: A[step.a]!.text });
+ continue;
+ }
+ flush(step.b);
+ if (step.kind === "added") {
+ counts.added += 1;
+ segments.push({ kind: "added", para: B[step.b]!.para, text: B[step.b]!.text });
+ } else if (A[step.a]!.key === B[step.b]!.key) {
+ // Paired in a stretch aligned only roughly, and word for word the same: not a change.
+ counts.unchanged += 1;
+ segments.push({ kind: "same", para: B[step.b]!.para, text: B[step.b]!.text });
+ } else {
+ counts.changed += 1;
+ segments.push(changedSegment(A[step.a]!, B[step.b]!));
+ }
+ }
+ flush(Infinity);
+ }
+ return { ok: true, counts, segments, coarse: aligner.coarse, work: tally.work };
+}
+
+export const changeCount = (counts: TextChangeCounts) => counts.changed + counts.added + counts.removed + counts.moved;
+
+const clip = (text: string, max: number) => {
+ const flat = text.replace(/\s+/g, " ").trim();
+ return flat.length > max ? `${flat.slice(0, max)}…` : flat;
+};
+
+/** The `what_changed` tool's lines: one per change in reading order, words marked `[-removed-]{+added+}`. */
+export function changeLines(result: TextChanges): string[] {
+ const lines: string[] = [];
+ let index = 0;
+ for (const change of result.segments) {
+ if (change.kind === "same") continue;
+ index += 1;
+ lines.push(change.kind === "changed"
+ ? `${index}. ${change.minor ? "changed (punctuation or case only)" : "changed"}, paragraph ${change.para}: ${clip(change.parts.map((part) => part.op === "same" ? part.text : part.op === "del" ? `[-${part.text}-]` : `{+${part.text}+}`).join(""), 600)}`
+ : change.kind === "added" ? `${index}. added, paragraph ${change.para}: {+${clip(change.text, 500)}+}`
+ : change.kind === "removed" ? `${index}. removed, was paragraph ${change.beforePara} of the original: [-${clip(change.text, 500)}-]`
+ : `${index}. moved, from paragraph ${change.beforePara} to paragraph ${change.para}: ${clip(change.text, 500)}`);
+ }
+ return lines;
+}
+
+export interface ChangeList { head: string; lines: readonly string[]; coarse: boolean }
+
+export function changeList(result: TextChanges): ChangeList {
+ return { head: JSON.stringify({ ...result.counts, ...(result.coarse ? { coarse: true } : {}) }), lines: changeLines(result), coarse: result.coarse };
+}
+
+/** The `what_changed` tool's answer: a JSON line of counts, then one numbered line per change in reading order. A page
+ * never drops a change silently: its last line says how to list the rest. */
+export function formatChangePage(list: ChangeList, options: { start?: number; limit?: number; maxChars?: number } = {}): string {
+ const start = Math.max(1, Math.floor(options.start ?? 1)), limit = Math.max(1, options.limit ?? 150), maxChars = options.maxChars ?? 20_000;
+ const { head, lines: all } = list;
+ if (!all.length) return `${head}\nNo changes: the two texts say the same thing, sentence for sentence.`;
+ const lines = [head];
+ let used = head.length, shown = 0;
+ for (let index = start - 1; index < all.length && shown < limit; index++) {
+ const line = all[index]!;
+ if (shown && used + line.length > maxChars) break;
+ lines.push(line);
+ used += line.length + 1;
+ shown += 1;
+ }
+ const next = start + shown;
+ if (next <= all.length) lines.push(`${all.length - next + 1} more not listed here; the counts above are complete. Call again with start: ${next} for the rest.`);
+ if (list.coarse) lines.push("Some long stretches differed too much to match sentence by sentence; their sentences are listed as removed and added.");
+ return lines.join("\n");
+}
+
+export const formatTextChanges = (result: TextChanges, options: { start?: number; limit?: number; maxChars?: number } = {}) => formatChangePage(changeList(result), options);
diff --git a/src/components/AttachmentGallery.tsx b/src/components/AttachmentGallery.tsx
index c5b71b4efc..f6f453a544 100644
--- a/src/components/AttachmentGallery.tsx
+++ b/src/components/AttachmentGallery.tsx
@@ -19,6 +19,8 @@ import {
type PreviewImage,
} from "./AttachmentPreview";
import { useRevealOriginalMenu } from "./RevealOriginalMenu";
+import { WhatChangedButton } from "./WhatChangedButton";
+import { useEditSources } from "@/lib/use-edit-sources";
export interface GalleryFile extends TranscriptFileAttachment {
linked?: boolean;
@@ -477,6 +479,7 @@ export function AttachmentGallery({ images = [], files = [], originals, message,
return result;
}, [images, files, originals, message]);
const reveal = useRevealOriginalMenu();
+ const edits = useEditSources(message, files);
if (!items.length) return null;
const limit = beneath ? BENEATH_LIMIT : 4;
const shown = expanded ? items : items.slice(0, limit);
@@ -514,7 +517,7 @@ export function AttachmentGallery({ images = [], files = [], originals, message,
<div className="flex max-w-full flex-wrap items-start gap-1.5">
{rest.map((item) => item.kind === "audio" && message
? <span key={`${message.threadId}:${message.messageId}:${item.key}`} className="contents" {...reveal.targetProps(item.source)}><AudioAttachment file={item.file} message={message} /></span>
- : item.kind === "file" && <span key={item.key} className="contents" {...reveal.targetProps(item.source)}><AttachedFileChip file={item.file} linked={item.file.linked} message={message} compact /></span>)}
+ : item.kind === "file" && <span key={item.key} className="contents" {...reveal.targetProps(item.source)}><AttachedFileChip file={item.file} linked={item.file.linked} message={message} compact />{message && edits.has(item.file.path) && <WhatChangedButton path={item.file.path} name={item.file.name} message={message} source={edits.get(item.file.path)!} compact />}</span>)}
{items.length > limit && (
<button type="button" onClick={() => setExpanded(!expanded)} aria-expanded={expanded} className="inline-flex h-7 items-center rounded-full px-2.5 text-[13px] leading-none text-ink-secondary transition-colors hover:bg-ink/[0.06] hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus">
{expanded ? t("attach.showLess") : t("attach.moreCount", { count: items.length - limit })}
@@ -544,7 +547,7 @@ export function AttachmentGallery({ images = [], files = [], originals, message,
<div className="flex flex-col items-start gap-1.5">
{documents.map((item) => item.kind === "audio" && message
? <span key={`${message.threadId}:${message.messageId}:${item.key}`} className="contents" {...reveal.targetProps(item.source)}><AudioAttachment file={item.file} message={message} /></span>
- : item.kind === "file" && <span key={item.key} className="contents" {...reveal.targetProps(item.source)}><AttachedFileChip file={item.file} linked={item.file.linked} message={message} className="max-w-none rounded-xl border-hairline/25 bg-transparent" /></span>)}
+ : item.kind === "file" && <span key={item.key} className={message && edits.has(item.file.path) ? "flex max-w-full items-center gap-1" : "contents"} {...reveal.targetProps(item.source)}><AttachedFileChip file={item.file} linked={item.file.linked} message={message} className="max-w-none rounded-xl border-hairline/25 bg-transparent" />{message && edits.has(item.file.path) && <WhatChangedButton path={item.file.path} name={item.file.name} message={message} source={edits.get(item.file.path)!} />}</span>)}
</div>
)}
{items.length > limit && (
diff --git a/src/components/FilePreviewPanel.tsx b/src/components/FilePreviewPanel.tsx
index 16ac215138..361593b768 100644
--- a/src/components/FilePreviewPanel.tsx
+++ b/src/components/FilePreviewPanel.tsx
@@ -65,12 +65,12 @@ function FilePane({ preview }: { preview: FilePreview }) {
className="absolute inset-y-0 start-0 z-10 w-1.5 cursor-col-resize hover:bg-accent/40 focus-visible:bg-accent/60 max-md:hidden"
/>
<header {...dragProps} className="ms-1.5 flex items-center gap-1 py-2.5 ps-2.5 pe-3">
- <h2 dir="auto" title={preview.name} className="min-w-0 flex-1 truncate text-[17px] font-semibold text-ink">{preview.name}</h2>
+ <h2 dir="auto" title={preview.name} className="min-w-0 flex-1 truncate text-[17px] font-semibold text-ink">{preview.kind === "changes" ? t("changes.title", { name: preview.name }) : preview.name}</h2>
<button ref={closeButton} type="button" className="ui-icon-button shrink-0" aria-label={t("attach.besideClose")} title={t("attach.besideClose")} onClick={dismiss}><X size={16} /></button>
</header>
{/* An HTML file's frame swallows the pointer, so the resize drag would stop the moment it crossed the page. */}
<div className={cn("ms-1.5 flex min-h-0 flex-1 flex-col overflow-auto px-3 pb-3", dragging && "pointer-events-none")}>
- <FilePreviewContent kind={preview.kind} path={preview.path} name={preview.name} message={preview.message} fill />
+ <FilePreviewContent kind={preview.kind} path={preview.path} name={preview.name} message={preview.message} original={preview.original} fill />
</div>
</aside>
);
diff --git a/src/components/HtmlFilePreview.tsx b/src/components/HtmlFilePreview.tsx
index 18378bc08d..ab168ec131 100644
--- a/src/components/HtmlFilePreview.tsx
+++ b/src/components/HtmlFilePreview.tsx
@@ -23,6 +23,7 @@ export function isMarkdownFile(name: string): boolean {
// Lazy, so the chat's Markdown renderer (which uses this file's chips) is not imported back into it.
const MarkdownFileContent = lazy(() => import("./MarkdownFilePreview"));
+const WhatChangedContent = lazy(() => import("./WhatChangedView"));
// React 19 caches a rejected lazy import until the page reloads; without a boundary it would replace the whole message.
class MarkdownPreviewBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
@@ -76,8 +77,9 @@ export function useHtmlPreview(path: string, name: string, message?: MessageAtta
}
/** A file's preview, in the dialog or in the pane beside the chat, which it fills. */
-export function FilePreviewContent({ kind, path, name, message, fill = false }: Pick<FilePreview, "kind" | "path" | "name" | "message"> & { fill?: boolean }) {
+export function FilePreviewContent({ kind, path, name, message, original, fill = false }: Pick<FilePreview, "kind" | "path" | "name" | "message" | "original"> & { fill?: boolean }) {
const key = `${message.threadId}:${message.messageId}:${path}`;
+ if (kind === "changes") return original ? <MarkdownPreviewBoundary><Suspense fallback={<div role="status" className="flex items-center justify-center gap-2 p-12 text-sm text-ink-secondary"><LoaderCircle size={16} className="animate-spin" />{t("changes.loading")}</div>}><WhatChangedContent key={`${key}:${original.path}`} edited={{ path, name, message }} original={{ path: original.path, name: original.name, message: { threadId: message.threadId, messageId: original.messageId } }} fill={fill} /></Suspense></MarkdownPreviewBoundary> : null;
if (kind === "html") return <HtmlFileContent key={key} path={path} name={name} message={message} fill={fill} />;
if (kind === "table") {
const delimiter = tableDelimiter(name) ?? tableDelimiter(path);
diff --git a/src/components/WhatChangedButton.tsx b/src/components/WhatChangedButton.tsx
new file mode 100644
index 0000000000..0fcdb0d799
--- /dev/null
+++ b/src/components/WhatChangedButton.tsx
@@ -0,0 +1,33 @@
+import { lazy, Suspense, useRef, useState } from "react";
+import { LoaderCircle } from "lucide-react";
+
+import type { MessageAttachmentContext } from "./AttachmentPreview";
+import { TableDialog } from "./RichTable";
+import { cn } from "@/lib/cn";
+import type { EditSource } from "@/lib/edit-source";
+import { useFileBesideChat } from "@/lib/file-preview";
+import { t } from "@/lib/i18n";
+
+const WhatChangedContent = lazy(() => import("./WhatChangedView"));
+
+/** "What changed" beside a file a bot returned as an edit of the person's file: opens the comparison beside the chat
+ * when the window has room, else in a dialog. Nothing loads until it is pressed. */
+export function WhatChangedButton({ path, name, message, source, compact = false }: { path: string; name: string; message: MessageAttachmentContext; source: EditSource; compact?: boolean }) {
+ const [open, setOpen] = useState(false);
+ const trigger = useRef<HTMLButtonElement>(null);
+ const beside = useFileBesideChat();
+ const show = () => {
+ if (!beside({ kind: "changes", path, name, message, original: source, opener: trigger.current })) setOpen(true);
+ };
+ return <>
+ <button ref={trigger} type="button" onClick={show} aria-label={t("changes.openAria", { name })} title={t("changes.openAria", { name })}
+ className={cn("inline-flex shrink-0 items-center rounded-full px-2.5 leading-none text-ink-secondary transition-colors hover:bg-ink/[0.06] hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus", compact ? "h-7 text-[13px]" : "h-8 text-[12px]")}>
+ {t("changes.open")}
+ </button>
+ {open && <TableDialog title={t("changes.title", { name })} returnFocus={trigger.current} onClose={() => setOpen(false)}>
+ <Suspense fallback={<div role="status" className="flex items-center justify-center gap-2 p-12 text-sm text-ink-secondary"><LoaderCircle size={16} className="animate-spin" />{t("changes.loading")}</div>}>
+ <WhatChangedContent edited={{ path, name, message }} original={{ path: source.path, name: source.name, message: { threadId: message.threadId, messageId: source.messageId } }} />
+ </Suspense>
+ </TableDialog>}
+ </>;
+}
diff --git a/src/components/WhatChangedView.dom.test.ts b/src/components/WhatChangedView.dom.test.ts
new file mode 100644
index 0000000000..c6db45b15c
--- /dev/null
+++ b/src/components/WhatChangedView.dom.test.ts
@@ -0,0 +1,115 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { compareTexts } from "../../shared/text-changes";
+import { StoreContext } from "@/state/store-context";
+import { AttachmentGallery } from "./AttachmentGallery";
+import WhatChangedContent, { changeBlocks } from "./WhatChangedView";
+
+const ORIGINAL = ["Mara walked into the bar at noon.", "Tom said nothing.", "One.", "Two.", "Three.", "Four.", "She left before dawn."].join("\n\n");
+const EDITED = ORIGINAL.replace("walked", "ran").replace("She left before dawn.", "She left before dawn. A stranger watched.");
+const STORE = "/data/attachments";
+const SOURCE = `${STORE}/1f1d2c3b-1a2b-4c3d-8e4f-0a1b2c3d4e5f.md`, RESULT = `${STORE}/2f1d2c3b-1a2b-4c3d-8e4f-0a1b2c3d4e5f.md`;
+
+class InlineWorker {
+ onmessage: ((event: MessageEvent) => void) | null = null;
+ onerror: (() => void) | null = null;
+ postMessage(data: { original: string; edited: string }) {
+ queueMicrotask(() => this.onmessage?.({ data: compareTexts(data.original, data.edited) } as MessageEvent));
+ }
+ terminate() {}
+}
+
+let host: HTMLDivElement, root: Root;
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ vi.stubGlobal("Worker", InlineWorker);
+ host = document.createElement("div"); document.body.append(host); root = createRoot(host);
+});
+afterEach(async () => { await act(async () => root.unmount()); host.remove(); vi.unstubAllGlobals(); });
+
+/** Polls until the page shows what the test waits for, letting React and the fake worker run in between. */
+const until = (check: () => void) => vi.waitFor(async () => { await act(async () => {}); check(); }, { timeout: 5_000, interval: 5 });
+
+describe("What changed view", () => {
+ it("loads both files through their messages, counts the changes and marks them word by word", async () => {
+ const asked: Array<{ url: string; path: string }> = [];
+ vi.stubGlobal("fetch", vi.fn(async (url: string, init: RequestInit) => {
+ const { path } = JSON.parse(String(init.body)) as { path: string };
+ asked.push({ url, path });
+ return new Response(path === SOURCE ? ORIGINAL : EDITED, path === SOURCE ? { headers: { "x-openmausbot-kept-original": "1" } } : {});
+ }));
+ await act(async () => root.render(createElement(WhatChangedContent, {
+ original: { path: SOURCE, name: "chapter.md", message: { threadId: "t", messageId: "u1" } },
+ edited: { path: RESULT, name: "chapter-edited.md", message: { threadId: "t", messageId: "b1" } },
+ })));
+ await until(() => expect(host.querySelector("[role=status]")?.textContent).toBe("Changed 1 · Added 1"));
+ expect(asked).toEqual([
+ { url: "/api/threads/t/messages/u1/file", path: SOURCE },
+ { url: "/api/threads/t/messages/b1/file", path: RESULT },
+ ]);
+ expect(host.textContent).toContain("Compared with chapter.md, as you sent it");
+ expect([...host.querySelectorAll("del")].map((node) => node.textContent)).toEqual(["walked"]);
+ expect([...host.querySelectorAll("ins")].map((node) => node.textContent)).toEqual(["ran", "A stranger watched."]);
+ // The unchanged middle is folded away beyond one paragraph of context on each side.
+ expect(host.textContent).toContain("3 unchanged paragraphs");
+ expect(host.textContent).not.toContain("Two.");
+
+ await act(async () => (host.querySelector("[aria-label='Next change']") as HTMLButtonElement).click());
+ expect(host.textContent).toContain("1 of 2");
+ await act(async () => (host.querySelector("[aria-label='Previous change']") as HTMLButtonElement).click());
+ expect(host.textContent).toContain("2 of 2");
+ });
+
+ it("says so when nothing changed, and when a file is too large", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(ORIGINAL)));
+ await act(async () => root.render(createElement(WhatChangedContent, {
+ original: { path: SOURCE, name: "a.md", message: { threadId: "t", messageId: "u1" } },
+ edited: { path: RESULT, name: "b.md", message: { threadId: "t", messageId: "b1" } },
+ })));
+ await until(() => expect(host.textContent).toContain("No changes: the two versions say the same thing"));
+ // Served from the store, not from a copy kept when it was sent: the view says so.
+ expect(host.textContent).toContain("Your original a.md wasn't kept when you sent it");
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("x", { headers: { "content-length": String(3 * 1024 * 1024) } })));
+ await act(async () => root.render(createElement(WhatChangedContent, {
+ key: "again",
+ original: { path: SOURCE, name: "a.md", message: { threadId: "t", messageId: "u1" } },
+ edited: { path: RESULT, name: "b.md", message: { threadId: "t", messageId: "b2" } },
+ })));
+ await until(() => expect(host.querySelector("[role=alert]")?.textContent).toBe("These files are too large to compare here (each up to 2 MB and 20,000 sentences)."));
+ });
+});
+
+describe("the What changed control", () => {
+ const state = (messages: unknown[]) => ({ state: { bots: [{ id: "bot", threadId: "t", messages }], groups: [], forkPanel: null } }) as never;
+ const person = { id: "u1", role: "user", text: `Improve the dialogue\n\n<attached-file path="${SOURCE}" name="chapter.md" />`, parentId: null };
+ const returned = { id: "b1", role: "bot", text: "", parentId: "u1", attachments: [{ kind: "file", path: RESULT, name: "chapter-edited.md", mime: "text/markdown" }] };
+ const gallery = () => createElement(AttachmentGallery, { files: [{ path: RESULT, name: "chapter-edited.md", private: true }], message: { threadId: "t", messageId: "b1" } });
+ const labels = () => [...host.querySelectorAll("button")].map((button) => button.textContent);
+
+ it("sits beside a returned edit of the person's file, and nowhere else", async () => {
+ await act(async () => root.render(createElement(StoreContext.Provider, { value: state([person, returned]) }, gallery())));
+ expect(labels()).toContain("What changed");
+ vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => new Response(JSON.parse(String(init.body)).path === SOURCE ? ORIGINAL : EDITED)));
+ await act(async () => [...host.querySelectorAll("button")].find((button) => button.textContent === "What changed")!.click());
+ await until(() => expect(document.querySelector("dialog h2")?.textContent).toBe("What changed in chapter-edited.md"));
+ await until(() => expect(document.querySelector("dialog [role=status]")?.textContent).toBe("Changed 1 · Added 1"));
+ expect(document.querySelector("dialog [role=status]")?.textContent).toBe("Changed 1 · Added 1");
+ await act(async () => root.render(createElement(StoreContext.Provider, { value: state([{ ...person, text: "Improve the dialogue" }, returned]) }, gallery())));
+ expect(labels()).not.toContain("What changed");
+ await act(async () => root.render(gallery()));
+ expect(labels()).not.toContain("What changed");
+ });
+});
+
+describe("changeBlocks", () => {
+ it("numbers changes in reading order and keeps changed paragraphs whole", () => {
+ const result = compareTexts(ORIGINAL, EDITED);
+ if (!result.ok) throw new Error("compare");
+ const { blocks, changes } = changeBlocks(result.segments);
+ expect(changes).toBe(2);
+ expect(blocks.map((block) => block.kind === "paragraph" ? block.paragraph.para : `folded ${block.paragraphs.length}`)).toEqual([1, 2, "folded 3", 6, 7]);
+ });
+});
diff --git a/src/components/WhatChangedView.tsx b/src/components/WhatChangedView.tsx
new file mode 100644
index 0000000000..1e9c4989ef
--- /dev/null
+++ b/src/components/WhatChangedView.tsx
@@ -0,0 +1,175 @@
+import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { ChevronDown, ChevronUp, LoaderCircle } from "lucide-react";
+
+import { requestMessageFile, type MessageAttachmentContext } from "./AttachmentPreview";
+import { previewHeight } from "./HtmlFilePreview";
+import { readTableResponse } from "./TableFilePreview";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import { changeCount, type ChangeSegment, type TextComparison } from "../../shared/text-changes";
+
+/** What the view reads of each side: a preview limit, as for a Markdown file. */
+export const WHAT_CHANGED_MAX_BYTES = 2 * 1024 * 1024;
+const CONTEXT_PARAGRAPHS = 1;
+/** Blocks drawn per frame: a heavily edited 100-page document never lands in one long commit. */
+const BLOCKS_PER_FRAME = 120;
+
+export interface ComparedFile { path: string; name: string; message: MessageAttachmentContext }
+
+type Failure = "size" | "load" | "encoding" | "failed";
+type Paragraph = { para: number; segments: Array<{ segment: ChangeSegment; change: number | null }>; changed: boolean };
+/** `first` and `last`: the change numbers inside the block, -1 for none. */
+export type Block = ({ kind: "paragraph"; paragraph: Paragraph } | { kind: "unchanged"; paragraphs: Paragraph[] }) & { first: number; last: number };
+
+/** The edited text paragraph by paragraph, each change numbered in reading order, and stretches of unchanged paragraphs
+ * folded away beyond one paragraph of context on each side of a change. */
+export function changeBlocks(segments: readonly ChangeSegment[]): { blocks: Block[]; changes: number } {
+ const paragraphs: Paragraph[] = [];
+ let changes = 0;
+ for (const segment of segments) {
+ let last = paragraphs[paragraphs.length - 1];
+ if (!last || last.para !== segment.para) paragraphs.push(last = { para: segment.para, segments: [], changed: false });
+ const change = segment.kind === "same" ? null : changes++;
+ last.segments.push({ segment, change });
+ if (change !== null) last.changed = true;
+ }
+ const near = paragraphs.map((_, index) => paragraphs.slice(Math.max(0, index - CONTEXT_PARAGRAPHS), index + CONTEXT_PARAGRAPHS + 1).some((paragraph) => paragraph.changed));
+ const blocks: Block[] = [];
+ paragraphs.forEach((paragraph, index) => {
+ if (near[index]) {
+ const numbers = paragraph.segments.flatMap(({ change }) => change === null ? [] : [change]);
+ return void blocks.push({ kind: "paragraph", paragraph, first: numbers.length ? numbers[0]! : -1, last: numbers.length ? numbers[numbers.length - 1]! : -1 });
+ }
+ const last = blocks[blocks.length - 1];
+ if (last?.kind === "unchanged") last.paragraphs.push(paragraph);
+ else blocks.push({ kind: "unchanged", paragraphs: [paragraph], first: -1, last: -1 });
+ });
+ return { blocks, changes };
+}
+
+/** `kept`: the server served the copy kept when the person sent the file, so it is exactly their original. */
+async function readSide(file: ComparedFile, signal: AbortSignal): Promise<{ text: string; kept: boolean }> {
+ const response = await requestMessageFile(file.path, file.message, signal);
+ const kept = response.headers.get("x-openmausbot-kept-original") === "1";
+ return { text: await readTableResponse(response, signal, WHAT_CHANGED_MAX_BYTES, "windows-1252"), kept };
+}
+
+const INS = "rounded-[3px] bg-success/15 text-ink no-underline";
+const DEL = "rounded-[3px] text-ink-secondary line-through decoration-ink-secondary";
+const MOVED = "rounded-[3px] bg-ink/[0.06] underline decoration-ink-tertiary decoration-dotted underline-offset-4";
+
+function Segment({ segment, current }: { segment: ChangeSegment; current: boolean }): ReactNode {
+ const mark = current ? "outline-2 outline-offset-2 outline-focus" : undefined;
+ switch (segment.kind) {
+ case "same": return segment.text;
+ case "added": return <ins className={cn(INS, mark)}>{segment.text}</ins>;
+ case "removed": return <del className={cn(DEL, mark)}>{segment.text}</del>;
+ case "moved": return <span className={cn(MOVED, mark)} title={t("changes.movedFrom", { para: segment.beforePara })}>{segment.text}</span>;
+ case "changed": return <span className={cn("rounded-[3px]", mark)} title={segment.minor ? t("changes.minor") : undefined}>
+ {segment.parts.map((part, index) => part.op === "same" ? part.text : part.op === "add" ? <ins key={index} className={INS}>{part.text}</ins> : <del key={index} className={DEL}>{part.text}</del>)}
+ </span>;
+ }
+}
+
+/** One block, drawn again only when it opens or the current change enters or leaves it. */
+const BlockView = memo(function BlockView({ block, index, open, current, onOpen }: { block: Block; index: number; open: boolean; current: number; onOpen: (index: number) => void }) {
+ if (block.kind === "unchanged" && !open) {
+ return <button type="button" className="mb-3 inline-flex h-7 items-center rounded-full px-2.5 text-[13px] leading-none text-ink-secondary transition-colors hover:bg-ink/[0.06] hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus" onClick={() => onOpen(index)}>
+ {t(block.paragraphs.length === 1 ? "changes.unchangedOne" : "changes.unchanged", { count: block.paragraphs.length })}
+ </button>;
+ }
+ return (block.kind === "paragraph" ? [block.paragraph] : block.paragraphs).map((paragraph) => <p key={paragraph.para} dir="auto" className="mb-3 whitespace-pre-wrap break-words">
+ {paragraph.segments.map(({ segment, change }, at) => change === null ? <span key={at}>{segment.kind === "same" ? segment.text : null}</span> : <span key={at} data-change={change}><Segment segment={segment} current={change === current} /></span>)}
+ </p>);
+});
+
+/** An edited file beside the person's original: every change in the edited text, word by word inside a changed
+ * sentence, with counts and next and previous. Both files come through the message file route; the comparison runs in
+ * a worker, never on the page's thread. */
+export default function WhatChangedContent({ original, edited, fill = false }: { original: ComparedFile; edited: ComparedFile; fill?: boolean }) {
+ const [attempt, setAttempt] = useState(0);
+ const [result, setResult] = useState<TextComparison | { ok: false; reason: "failed" } | null>(null);
+ const [kept, setKept] = useState(false);
+ const [error, setError] = useState<Failure | { reason: string } | null>(null);
+ const [current, setCurrent] = useState(-1);
+ const [opened, setOpened] = useState<ReadonlySet<number>>(new Set());
+ const [drawn, setDrawn] = useState(BLOCKS_PER_FRAME);
+ const body = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ const controller = new AbortController();
+ let worker: Worker | undefined;
+ setResult(null);
+ setError(null);
+ setCurrent(-1);
+ void (async () => {
+ let answered = false;
+ try {
+ const [before, after] = await Promise.all([readSide(original, controller.signal), readSide(edited, controller.signal)]);
+ answered = true;
+ controller.signal.throwIfAborted();
+ worker = new Worker(new URL("../lib/text-changes.worker.ts", import.meta.url), { type: "module" });
+ worker.onmessage = (event: MessageEvent<TextComparison | { ok: false; reason: "failed" }>) => {
+ if (!controller.signal.aborted) setResult(event.data);
+ worker?.terminate();
+ };
+ worker.onerror = () => { if (!controller.signal.aborted) setError("failed"); worker?.terminate(); };
+ setKept(before.kept);
+ worker.postMessage({ original: before.text, edited: after.text });
+ } catch (reason) {
+ if (controller.signal.aborted) return;
+ if (reason instanceof Error && (reason.message === "size" || reason.message === "encoding")) setError(reason.message);
+ else if (!answered && reason instanceof Error && !(reason instanceof TypeError)) setError({ reason: reason.message });
+ else setError("load");
+ }
+ })();
+ return () => { controller.abort(); worker?.terminate(); };
+ }, [original.path, original.message.messageId, edited.path, edited.message.messageId, edited.message.threadId, attempt]);
+ const view = useMemo(() => result?.ok ? changeBlocks(result.segments) : null, [result]);
+ useEffect(() => {
+ if (!view || drawn >= view.blocks.length) return;
+ const frame = requestAnimationFrame(() => setDrawn((count) => count + BLOCKS_PER_FRAME));
+ return () => cancelAnimationFrame(frame);
+ }, [view, drawn]);
+ const scrollTo = useRef(-1);
+ const openBlock = useCallback((index: number) => setOpened((was) => new Set([...was, index])), []);
+ useEffect(() => {
+ if (scrollTo.current < 0) return;
+ const target = body.current?.querySelector(`[data-change="${scrollTo.current}"]`);
+ if (!target) return;
+ scrollTo.current = -1;
+ target.scrollIntoView({ block: "center", behavior: "smooth" });
+ }, [current, drawn]);
+
+ const retry = <button type="button" className="mt-3 rounded-lg border border-hairline px-3 py-2 hover:bg-raised" onClick={() => setAttempt(attempt + 1)}>{t("chat.retry")}</button>;
+ if (error || (result && !result.ok)) {
+ const why = typeof error === "object" && error ? t("changes.refused", { reason: error.reason })
+ : t(error === "size" || (result && !result.ok && result.reason !== "failed") ? "changes.tooLarge" : error === "encoding" ? "changes.notText" : "changes.failed");
+ return <div className="p-8 text-center text-sm"><p role="alert" className="text-ink-secondary">{why}</p>{retry}</div>;
+ }
+ if (!result?.ok || !view) return <div role="status" className="flex items-center justify-center gap-2 p-12 text-sm text-ink-secondary"><LoaderCircle size={16} className="animate-spin" />{t("changes.loading")}</div>;
+
+ const { counts } = result;
+ const total = changeCount(counts);
+ const go = (step: 1 | -1) => {
+ const next = current < 0 ? (step > 0 ? 0 : total - 1) : (current + step + total) % total;
+ scrollTo.current = next;
+ setCurrent(next);
+ };
+ return <div className={cn("flex flex-col gap-2", fill && "min-h-0 flex-1")}>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ <div className="min-w-0 flex-1 text-[13px] text-ink-secondary">
+ <p role="status" className="text-ink">{total ? (["changed", "added", "removed", "moved"] as const).filter((kind) => counts[kind]).map((kind) => t(`changes.${kind}`, { count: counts[kind] })).join(" · ") : t("changes.none")}</p>
+ <p dir="auto" className={kept ? "truncate" : undefined}>{t(kept ? "changes.against" : "changes.notKept", { name: original.name })}</p>
+ </div>
+ {total > 0 && <div className="flex items-center gap-1">
+ <span className="text-[12px] text-ink-secondary tabular-nums">{current >= 0 ? t("changes.position", { index: current + 1, count: total }) : null}</span>
+ <button type="button" className="table-action" aria-label={t("changes.previous")} title={t("changes.previous")} onClick={() => go(-1)}><ChevronUp size={14} /></button>
+ <button type="button" className="table-action" aria-label={t("changes.next")} title={t("changes.next")} onClick={() => go(1)}><ChevronDown size={14} /></button>
+ </div>}
+ </div>
+ {result.coarse && <p className="text-[12px] text-ink-secondary">{t("changes.coarse")}</p>}
+ <div ref={body} data-what-changed className={cn(previewHeight(fill), "overflow-auto rounded-lg border border-hairline/40 bg-panel px-5 py-4 text-[14px] leading-6 text-ink")}>
+ {view.blocks.slice(0, drawn).map((block, index) => <BlockView key={index} block={block} index={index} open={opened.has(index)} current={block.first <= current && current <= block.last ? current : -1} onOpen={openBlock} />)}
+ </div>
+ </div>;
+}
diff --git a/src/lib/edit-source.test.ts b/src/lib/edit-source.test.ts
new file mode 100644
index 0000000000..14dfec811c
--- /dev/null
+++ b/src/lib/edit-source.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from "vitest";
+
+import { editStem, findEditSource } from "./edit-source";
+
+const STORE = "/data/attachments";
+const id = (n: number, ext = "md") => `${STORE}/${n}f1d2c3b-1a2b-4c3d-8e4f-0a1b2c3d4e5f.${ext}`;
+const attached = (path: string, name: string) => `<attached-file path="${path}" name="${name}" />`;
+const file = (path: string, name: string) => ({ path, name, private: true });
+
+const person = (text: string, parentId: string | null = null) => ({ id: "u1", role: "user", text, parentId });
+const reply = (parentId = "u1") => ({ id: "b1", role: "bot", text: "", parentId });
+
+describe("findEditSource: when What changed is offered", () => {
+ it("pairs a returned file with the person's file of the same name, edit words set aside", () => {
+ const messages = [person(`Improve the dialogue\n\n${attached(id(1), "Chapter 3.md")}\n${attached(id(2), "Notes.md")}`), reply()];
+ for (const name of ["Chapter 3 (edited).md", "chapter_3_revised.md", "Chapter-3-v2.md", "Chapter 3.md"]) {
+ expect(findEditSource(messages, "b1", [file(id(5), name)]).get(id(5))).toEqual({ messageId: "u1", path: id(1), name: "Chapter 3.md" });
+ }
+ });
+
+ it("does not pair files of other names, which may be different documents", () => {
+ const messages = [person(`Tighten this\n\n${attached(id(1), "draft.txt")}`), reply()];
+ expect(findEditSource(messages, "b1", [file(id(5), "polished.md")]).size).toBe(0);
+ });
+
+ it("offers nothing when it is unsure: two candidates, two returned files with other names, other kinds of file", () => {
+ const two = [person(`${attached(id(1), "a.md")}\n${attached(id(2), "b.md")}`), reply()];
+ expect(findEditSource(two, "b1", [file(id(5), "c.md")]).size).toBe(0);
+ const one = [person(attached(id(1), "draft.md")), reply()];
+ expect(findEditSource(one, "b1", [file(id(5), "x.md"), file(id(6), "y.md")]).size).toBe(0);
+ expect(findEditSource(one, "b1", [file(id(5, "docx"), "draft.docx")]).size).toBe(0);
+ const word = [person(attached(id(1, "docx"), "draft.docx")), reply()];
+ expect(findEditSource(word, "b1", [file(id(5), "draft.md")]).size).toBe(0);
+ expect(findEditSource(one, "b1", [{ path: "/home/me/draft.md", name: "draft.md" }]).size).toBe(0);
+ });
+
+ it("never offers it on the person's own message, nor compares a file with itself", () => {
+ const messages = [person(`${attached(id(1), "chapter.md")}\n${attached(id(2), "chapter-edited.md")}`)];
+ expect(findEditSource(messages, "u1", [file(id(2), "chapter-edited.md")]).size).toBe(0);
+ const echoed = [person(attached(id(1), "chapter.md")), reply()];
+ expect(findEditSource(echoed, "b1", [file(id(1), "chapter.md")]).size).toBe(0);
+ });
+
+ it("goes back to the nearest message of the person's that attached text, and needs it loaded", () => {
+ const messages = [
+ { id: "u0", role: "user", text: attached(id(1), "chapter.md"), parentId: null },
+ { id: "b0", role: "bot", text: "Read it.", parentId: "u0" },
+ { id: "u1", role: "user", text: "Now improve the dialogue", parentId: "b0" },
+ reply(),
+ ];
+ expect(findEditSource(messages, "b1", [file(id(5), "chapter-edited.md")]).get(id(5))?.messageId).toBe("u0");
+ expect(findEditSource(messages.slice(2), "b1", [file(id(5), "chapter-edited.md")]).size).toBe(0);
+ });
+
+ it("follows the branch the reply is on, not messages on another branch", () => {
+ const messages = [
+ { id: "u0", role: "user", text: attached(id(1), "chapter.md"), parentId: null },
+ { id: "u9", role: "user", text: attached(id(9), "chapter.md"), parentId: null },
+ { id: "b1", role: "bot", text: "", parentId: "u0" },
+ ];
+ expect(findEditSource(messages, "b1", [file(id(5), "chapter-edited.md")]).get(id(5))?.path).toBe(id(1));
+ });
+
+ it("does not mistake another chapter for an edit", () => {
+ expect(editStem("Chapter 3.md")).not.toBe(editStem("Chapter 4.md"));
+ expect(editStem("credit.md")).toBe("credit");
+ expect(editStem("Chapter 3 (1).md")).toBe("chapter 3");
+ });
+});
diff --git a/src/lib/edit-source.ts b/src/lib/edit-source.ts
new file mode 100644
index 0000000000..6c2c233a1b
--- /dev/null
+++ b/src/lib/edit-source.ts
@@ -0,0 +1,76 @@
+import { attachmentBasename, splitTranscriptAttachments, type TranscriptFileAttachment } from "./composer-attachments";
+
+/** The person's attached file a bot's returned file is an edit of: the "What changed" view compares the two. */
+export interface EditSource { messageId: string; path: string; name: string }
+
+type Line = { id: string; role: string; text?: string; parentId?: string | null };
+
+const TEXT_FILE = /\.(?:md|markdown|txt)$/i;
+const MAX_STEPS = 200;
+// Words people and bots add to an edited copy's name: "chapter-3 (edited).md", "chapter_3_v2.md", "Chapter 3 revised.md".
+const EDIT_WORDS = /(?:[\s._-]*(?:\([^)]*\)|\[[^\]]*\])|[\s._-]+(?:edited|edit|revised|revision|rewrite|rewritten|updated|update|final|new|copy|clean|improved|changes|tracked|v\d+))+$/i;
+
+export const isComparableTextName = (name: string) => TEXT_FILE.test(name);
+
+export function editStem(name: string): string {
+ const stem = name.replace(/\.[^.]+$/, "").normalize("NFC").toLowerCase();
+ return stem.replace(EDIT_WORDS, "").replace(/[\s._-]+/g, " ").trim() || stem;
+}
+
+const parsed = new WeakMap<object, TranscriptFileAttachment[]>();
+const positionsOf = new WeakMap<readonly Line[], Map<string, number>>();
+/** Where each message is, built once for each loaded conversation the store hands out. */
+function positions(messages: readonly Line[]): Map<string, number> {
+ let index = positionsOf.get(messages);
+ if (!index) {
+ index = new Map();
+ messages.forEach((line, at) => index!.set(line.id, at));
+ positionsOf.set(messages, index);
+ }
+ return index;
+}
+function attachedTextFiles(line: Line): TranscriptFileAttachment[] {
+ let files = parsed.get(line);
+ if (!files) {
+ files = line.text?.includes("<attached-file") ? splitTranscriptAttachments(line.text, false).files.filter((file) => file.private && isComparableTextName(file.name || attachmentBasename(file.path))) : [];
+ parsed.set(line, files);
+ }
+ return files;
+}
+
+/**
+ * The rule for offering "What changed" on a file a bot returned, from the conversation's structure alone (no file is
+ * read to decide): the returned file is a stored .md, .markdown or .txt on a bot's message; going back from that
+ * message, the nearest message of the person's that attached text files is found within the loaded conversation; and
+ * exactly one of those files has the same name once edit words are set aside ("chapter-3 (edited).md" is an edit of
+ * "chapter-3.md"). Anything less certain offers nothing: two files of other names may be different documents.
+ */
+export function findEditSource(messages: readonly Line[], replyId: string, returned: readonly TranscriptFileAttachment[]): Map<string, EditSource> {
+ const found = new Map<string, EditSource>();
+ const texts = returned.filter((file) => file.private && isComparableTextName(file.name || attachmentBasename(file.path)));
+ if (!texts.length) return found;
+ const index = positions(messages);
+ let at = index.get(replyId);
+ if (at === undefined || messages[at]!.role !== "bot") return found;
+ let source: { line: Line; files: TranscriptFileAttachment[] } | null = null;
+ for (let steps = 0; at !== undefined && steps < MAX_STEPS; steps++) {
+ const line: Line = messages[at]!;
+ if (line.role === "user") {
+ const files = attachedTextFiles(line);
+ if (files.length) {
+ source = { line, files };
+ break;
+ }
+ }
+ at = line.parentId ? index.get(line.parentId) : line.parentId === null ? undefined : at > 0 ? at - 1 : undefined;
+ }
+ if (!source) return found;
+ const { line, files } = source;
+ for (const file of texts) {
+ const stem = editStem(file.name || attachmentBasename(file.path));
+ const named = files.filter((candidate) => editStem(candidate.name || attachmentBasename(candidate.path)) === stem);
+ const match = named.length === 1 ? named[0]! : null;
+ if (match && match.path !== file.path) found.set(file.path, { messageId: line.id, path: match.path, name: match.name });
+ }
+ return found;
+}
diff --git a/src/lib/file-preview.ts b/src/lib/file-preview.ts
index 34a7e302d2..b1f28aacac 100644
--- a/src/lib/file-preview.ts
+++ b/src/lib/file-preview.ts
@@ -8,10 +8,12 @@ import { SIDEBAR_AND_PANEL_FIT } from "./use-media-query";
/** A file from a message, shown beside the chat. Renderer-only: nothing about it is stored or sent anywhere. */
export interface FilePreview {
- kind: "html" | "markdown" | "table";
+ kind: "html" | "markdown" | "table" | "changes";
path: string;
name: string;
message: { threadId: string; messageId: string };
+ /** For "changes": the person's file this one is an edit of, in the message that attached it. */
+ original?: { path: string; name: string; messageId: string };
/** What opened it, to take focus back when the person closes the pane. */
opener: HTMLElement | null;
}
diff --git a/src/lib/text-changes.worker.ts b/src/lib/text-changes.worker.ts
new file mode 100644
index 0000000000..10cdb090a0
--- /dev/null
+++ b/src/lib/text-changes.worker.ts
@@ -0,0 +1,6 @@
+import { compareTexts } from "../../shared/text-changes";
+
+self.onmessage = (event: MessageEvent<{ original: string; edited: string }>) => {
+ try { self.postMessage(compareTexts(event.data.original, event.data.edited)); }
+ catch { self.postMessage({ ok: false, reason: "failed" }); }
+};
diff --git a/src/lib/use-edit-sources.ts b/src/lib/use-edit-sources.ts
new file mode 100644
index 0000000000..6c21d25ba1
--- /dev/null
+++ b/src/lib/use-edit-sources.ts
@@ -0,0 +1,46 @@
+import { use, useContext, useMemo, useSyncExternalStore } from "react";
+
+import type { AppState, Message } from "@/state/store";
+import { StoreContext, StoreSourceContext } from "@/state/store-context";
+import { findEditSource, isComparableTextName, type EditSource } from "./edit-source";
+import type { TranscriptFileAttachment } from "./composer-attachments";
+
+const noSubscription = () => () => {};
+const NONE: ReadonlyMap<string, EditSource> = new Map();
+
+function threadMessages(state: AppState, threadId: string): readonly Message[] | null {
+ if (state.forkPanel?.threadId === threadId) return state.forkPanel.messages;
+ return state.bots.find((bot) => bot.threadId === threadId)?.messages ?? state.groups.find((group) => group.threadId === threadId)?.messages ?? null;
+}
+
+const answers = new WeakMap<readonly Message[], Map<string, string>>();
+const encode = (found: Map<string, EditSource>) => [...found].map(([path, source]) => [path, source.messageId, source.path, source.name].join("\u0000")).join("\n");
+
+/** The person's attached file each of a reply's returned text files is an edit of (edit-source.ts), followed in the
+ * store as one string so a gallery renders again only when the answer changes. Outside a store there is none. */
+export function useEditSources(message: { threadId: string; messageId: string } | undefined, files: readonly TranscriptFileAttachment[]): ReadonlyMap<string, EditSource> {
+ const source = useContext(StoreSourceContext);
+ const scoped = use(StoreContext);
+ const eligible = message ? files.filter((file) => file.private && isComparableTextName(file.name)) : [];
+ const read = () => {
+ if (!message || !eligible.length) return "";
+ const state = source ? source.getState() : scoped?.state;
+ const messages = state && threadMessages(state, message.threadId);
+ if (!messages) return "";
+ // Asked again on every store change: answered once for each loaded conversation, reply and set of files.
+ const asked = `${message.messageId}\n${eligible.map((file) => file.path).join("\n")}`;
+ let known = answers.get(messages);
+ if (!known) answers.set(messages, known = new Map());
+ let answer = known.get(asked);
+ if (answer === undefined) known.set(asked, answer = encode(findEditSource(messages, message.messageId, eligible)));
+ return answer;
+ };
+ const key = useSyncExternalStore(source?.subscribe ?? noSubscription, read, read);
+ return useMemo(() => {
+ if (!key) return NONE;
+ return new Map(key.split("\n").map((row) => {
+ const [path, messageId, original, name] = row.split("\u0000") as [string, string, string, string];
+ return [path, { messageId, path: original, name }];
+ }));
+ }, [key]);
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index 0d60fe3e37..e18b46d990 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -9948,6 +9948,7 @@
"chat.notice.exportedGoal.failed": "{before}[Goal: failed]{content}",
"activity.tool.team.decide": "Decide",
"activity.tool.team.extract": "Extract",
+ "activity.tool.team.whatChanged": "What changed",
"serverError.voice.utteranceTooLong": "voice utterances are limited to 500 characters",
"browser.panel.restore": "Restore size",
"browser.panel.maximize": "Maximize",
@@ -11319,5 +11320,28 @@
"insights.other": "Other",
"insights.breakdown": "Breakdown",
"insights.byHour": "By hour",
- "insights.share": "Share"
+ "insights.share": "Share",
+ "changes.open": "What changed",
+ "changes.openAria": "What changed in {name}",
+ "changes.title": "What changed in {name}",
+ "changes.changed": "Changed {count}",
+ "changes.added": "Added {count}",
+ "changes.removed": "Removed {count}",
+ "changes.moved": "Moved {count}",
+ "changes.against": "Compared with {name}, as you sent it",
+ "changes.notKept": "Your original {name} wasn't kept when you sent it, so this compares with that file as it is now.",
+ "changes.none": "No changes: the two versions say the same thing, sentence for sentence.",
+ "changes.previous": "Previous change",
+ "changes.next": "Next change",
+ "changes.position": "{index} of {count}",
+ "changes.unchanged": "{count} unchanged paragraphs",
+ "changes.unchangedOne": "1 unchanged paragraph",
+ "changes.movedFrom": "Moved here from paragraph {para}",
+ "changes.minor": "Punctuation or capitals only",
+ "changes.loading": "Comparing…",
+ "changes.failed": "Couldn't compare these files.",
+ "changes.tooLarge": "These files are too large to compare here (each up to 2 MB and 20,000 sentences).",
+ "changes.notText": "One of these files isn't plain text.",
+ "changes.refused": "Couldn't open a file to compare: {reason}",
+ "changes.coarse": "Some long stretches differ too much to match sentence by sentence; they show as removed and added."
}
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 221bc9c971..4d7274656b 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -9862,6 +9862,7 @@
"chat.notice.exportedGoal.failed": "{before}[Objetivo: falhou]{content}",
"activity.tool.team.decide": "Decidir",
"activity.tool.team.extract": "Extrair",
+ "activity.tool.team.whatChanged": "O que mudou",
"serverError.voice.utteranceTooLong": "Cada trecho de fala pode ter no máximo 500 caracteres",
"browser.panel.restore": "Restaurar tamanho",
"browser.panel.maximize": "Maximizar",
@@ -11319,5 +11320,28 @@
"insights.other": "Outros",
"insights.breakdown": "Detalhamento",
"insights.byHour": "Por hora",
- "insights.share": "Participação"
+ "insights.share": "Participação",
+ "changes.open": "O que mudou",
+ "changes.openAria": "O que mudou em {name}",
+ "changes.title": "O que mudou em {name}",
+ "changes.changed": "Alteradas {count}",
+ "changes.added": "Adicionadas {count}",
+ "changes.removed": "Removidas {count}",
+ "changes.moved": "Movidas {count}",
+ "changes.against": "Comparado com {name}, como você enviou",
+ "changes.notKept": "O seu {name} original não foi guardado quando você o enviou, então esta comparação usa o arquivo como está agora.",
+ "changes.none": "Sem mudanças: as duas versões dizem a mesma coisa, frase por frase.",
+ "changes.previous": "Mudança anterior",
+ "changes.next": "Próxima mudança",
+ "changes.position": "{index} de {count}",
+ "changes.unchanged": "{count} parágrafos sem mudança",
+ "changes.unchangedOne": "1 parágrafo sem mudança",
+ "changes.movedFrom": "Movido para cá do parágrafo {para}",
+ "changes.minor": "Só pontuação ou maiúsculas",
+ "changes.loading": "Comparando…",
+ "changes.failed": "Não foi possível comparar estes arquivos.",
+ "changes.tooLarge": "Estes arquivos são grandes demais para comparar aqui (até 2 MB e 20.000 frases cada).",
+ "changes.notText": "Um destes arquivos não é texto simples.",
+ "changes.refused": "Não foi possível abrir um arquivo para comparar: {reason}",
+ "changes.coarse": "Alguns trechos longos diferem demais para alinhar frase por frase; aparecem como removidos e adicionados."
}