Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Delete leftovers: one sliced pass for which uploads stay, not a full scan per upload
milind-soniccd37f116346
diff --git a/server/attachment-references.test.ts b/server/attachment-references.test.tsnew file mode 100644index 0000000000..b7c7413881--- /dev/null+++ b/server/attachment-references.test.ts@@ -0,0 +1,117 @@+import { describe, expect, it } from "vitest";++import { createAttachmentReferences, type MessageRow, type MessageRows } from "./attachment-references.ts";+import { messageWritten, watchMessageWrites } from "./message-writes.ts";++const rowsOf = (texts: readonly string[]) => (): MessageRows => (after, limit) =>+ texts.map((json, index): MessageRow => ({ rowid: index + 1, json })).filter((row) => row.rowid > after).slice(0, limit);++/** What the old per-name check answered: the name anywhere in any remaining row (SQLite instr). */+const oldRule = (texts: readonly string[], name: string) => texts.some((text) => text.includes(name));++async function unreferenced(texts: readonly string[], names: readonly string[], over: Parameters<typeof createAttachmentReferences>[0] = {}) {+ const going: string[] = [];+ const references = createAttachmentReferences({ rows: rowsOf(texts), ...over });+ await references.removeUnreferenced(names, (batch) => { going.push(...batch); return batch.length; });+ return going.sort();+}++describe("which uploads no remaining message names", () => {+ it("agrees with the old per-name check on names inside longer words, prefixes, suffixes and odd characters", async () => {+ const names = ["a.png", "ba.png", "a.png.bak", "x", "photo-1.jpg", "photo-12.jpg", "été.pdf", "😀.gif", "q\"uote.txt", "none.png", "9f86d081-0000.png"];+ const texts = [+ JSON.stringify({ text: "see /api/attachments/ba.png and copy-photo-12.jpg.old" }),+ JSON.stringify({ path: "C:\\data\\attachments\\été.pdf" }),+ JSON.stringify({ text: "😀.gif" }),+ JSON.stringify({ text: "q\"uote.txt" }),+ JSON.stringify({ text: "nothing here", id: "9f86d081-0000.pn" }),+ ];+ const expected = names.filter((name) => !oldRule(texts, name)).sort();+ expect(await unreferenced(texts, names)).toEqual(expected);+ expect(expected).toEqual(["9f86d081-0000.png", "a.png.bak", "none.png", "photo-1.jpg", "q\"uote.txt"].sort());+ });++ it("agrees with the old per-name check on a random corpus", async () => {+ let seed = 7;+ const random = () => (seed = (seed * 1_103_515_245 + 12_345) % 2_147_483_648) / 2_147_483_648;+ const alphabet = "ab.-_1";+ const word = (max: number) => Array.from({ length: 1 + Math.floor(random() * max) }, () => alphabet[Math.floor(random() * alphabet.length)]).join("");+ const names = [...new Set(Array.from({ length: 300 }, () => word(6)))];+ const texts = Array.from({ length: 400 }, () => JSON.stringify({ text: Array.from({ length: 6 }, () => word(9)).join(" / ") }));+ const expected = names.filter((name) => !oldRule(texts, name)).sort();+ expect(expected.length).toBeGreaterThan(0);+ expect(expected.length).toBeLessThan(names.length);+ expect(await unreferenced(texts, names)).toEqual(expected);+ });++ it("splits a long list of names into several matchers and still reads each row once", async () => {+ const names = Array.from({ length: 3_000 }, (_, i) => `${String(i).padStart(4, "0")}-${"f".repeat(60)}.png`);+ const texts = names.filter((_, i) => i % 3 === 0).map((name) => JSON.stringify({ text: `/api/attachments/${name}` }));+ let read = 0;+ const rows = rowsOf(texts);+ const going = await unreferenced(texts, names, { rows: () => { const inner = rows(); return (after, limit) => { const slice = inner(after, limit); read += slice.length; return slice; }; } });+ expect(going).toEqual(names.filter((_, i) => i % 3 !== 0).sort());+ expect(read).toBe(texts.length);+ });++ it("keeps a name a message written during the pass names", async () => {+ const texts = Array.from({ length: 50 }, (_, i) => JSON.stringify({ text: `row ${i}` }));+ let pauses = 0;+ const going = await unreferenced(texts, ["late.png", "gone.png"], {+ rowsPerRead: 5,+ sliceMs: 0,+ pause: async () => { if (++pauses === 3) messageWritten(JSON.stringify({ text: "/api/attachments/late.png" })); },+ });+ expect(going).toEqual(["gone.png"]);+ });++ it("keeps a name a message written between removal batches names", async () => {+ let pauses = 0;+ const references = createAttachmentReferences({ rows: rowsOf([]), batch: 1, sliceMs: 0, pause: async () => { pauses++; } });+ const going: string[] = [];+ await references.removeUnreferenced(["a.png", "b.png"], (batch) => {+ going.push(...batch);+ messageWritten(JSON.stringify({ text: "b.png" }));+ return batch.length;+ });+ expect(going).toEqual(["a.png"]);+ expect(pauses).toBeGreaterThan(1);+ });++ it("removes nothing when the pass cannot finish", async () => {+ const references = createAttachmentReferences({ rows: () => () => { throw new Error("messages.db was reopened during the check"); } });+ const going: string[] = [];+ await expect(references.removeUnreferenced(["a.png"], (batch) => { going.push(...batch); return batch.length; })).rejects.toThrow("reopened");+ expect(going).toEqual([]);+ });++ it("runs one pass at a time, and names asked for meanwhile share the next pass", async () => {+ const texts = Array.from({ length: 200 }, (_, i) => JSON.stringify({ text: i === 150 ? "c.png" : `row ${i}` }));+ let reading = 0, overlapped = false, passesStarted = 0;+ const rows = rowsOf(texts);+ const references = createAttachmentReferences({+ rowsPerRead: 10,+ sliceMs: 0,+ rows: () => { passesStarted++; const inner = rows(); return (after, limit) => { reading++; if (reading > 1) overlapped = true; const slice = inner(after, limit); reading--; return slice; }; },+ });+ const going: string[] = [];+ // As a real remover: a file another request's batch already took is not there to take again.+ const remove = (batch: readonly string[]) => { const fresh = batch.filter((name) => !going.includes(name)); going.push(...fresh); return fresh.length; };+ const first = references.removeUnreferenced(["a.png"], remove);+ await new Promise((done) => setImmediate(done));+ await new Promise((done) => setImmediate(done));+ expect(references.passes).toBe(1);+ const second = references.removeUnreferenced(["b.png", "c.png"], remove);+ const third = references.removeUnreferenced(["b.png", "d.png"], remove);+ expect(await Promise.all([first, second, third])).toEqual([1, 1, 1]);+ expect([references.passes, passesStarted, overlapped]).toEqual([2, 2, false]);+ expect(going).toEqual(["a.png", "b.png", "d.png"]);+ });++ it("stops watching writes once its pass and removals are done", async () => {+ let watching = 0;+ const references = createAttachmentReferences({ rows: rowsOf([]), watchWrites: (listener) => { watching++; const stop = watchMessageWrites(listener); return () => { watching--; stop(); }; } });+ await references.removeUnreferenced(["a.png"], (batch) => batch.length);+ expect(watching).toBe(0);+ });+});diff --git a/server/attachment-references.ts b/server/attachment-references.tsnew file mode 100644index 0000000000..cb16e0a4fe--- /dev/null+++ b/server/attachment-references.ts@@ -0,0 +1,245 @@+// Which stored uploads no remaining message names, for the clean-ups that remove uploads after a delete+// (host/delete-leftovers.ts, host/team-member-left.ts). Asking SQLite once per name (instr over every row's JSON) is a+// full read of the transcripts per name: thousands of them, on the main thread, held a large Cloud's server for minutes.+// Here one pass over the rows checks every name at once, with the same rule as instr (the name anywhere in the row's+// JSON), in short slices that give the event loop back between them; the files then go a batch at a time.+//+// One pass runs at a time: names asked for while one runs wait, together, for the next. Nothing is kept on disk, so a+// restart replays nothing (an upload a restart cut off stays, as any upload a message still names does).+//+// Safety: unsure means kept. A pass that fails, or finds messages.db reopened under it, removes nothing; a message+// written while the pass or its removals run is checked too (message-writes.ts); a name found once stays found.+import type { StatementSync } from "node:sqlite";+import { setImmediate as nextTurn } from "node:timers/promises";++import { prepared } from "./message-db.ts";+import { watchMessageWrites } from "./message-writes.ts";++export interface MessageRow { rowid: number; json: string }+/** At most `limit` message rows with a rowid above `after`, in rowid order. */+export type MessageRows = (after: number, limit: number) => readonly MessageRow[];++export interface AttachmentReferencesDeps {+ /** A reader for one pass. The default reads messages.db, and throws when the database was reopened during the pass. */+ rows?: () => MessageRows;+ watchWrites?: (listener: (json: string) => void) => () => void;+ now?: () => number;+ /** Gives the event loop back between slices. */+ pause?: () => Promise<void>;+ /** How long one slice of the pass may hold the event loop. */+ sliceMs?: number;+ rowsPerRead?: number;+ /** Names handed to one removal call. */+ batch?: number;+}++/** Removes the names given (none a remaining message names, as of the call); answers how many went. Must not throw. */+export type RemoveBatch = (names: readonly string[]) => number;++export interface AttachmentReferences {+ /** Hands `remove` every one of `names` no message names, a batch at a time, after one pass over the rows. Resolves with+ * how many went; rejects, having removed nothing, when the pass could not finish. */+ removeUnreferenced(names: Iterable<string>, remove: RemoveBatch): Promise<number>;+ /** Passes run so far. */+ readonly passes: number;+}++const ROWS_SQL = "SELECT rowid, json FROM messages WHERE rowid > ? ORDER BY rowid LIMIT ?";+/** Matcher tables above this many entries are split, so a long list of names never takes much memory at once. */+const MAX_TABLE_ENTRIES = 8_000_000;++/** messages.db read a slice at a time; throws when the database was reopened since this reader's first read. */+export function messageDbRows(): MessageRows {+ let first: StatementSync | undefined;+ return (after, limit) => {+ const statement = prepared(ROWS_SQL);+ if ((first ??= statement) !== statement) throw new Error("messages.db was reopened during the check");+ return statement.all(after, limit) as unknown as MessageRow[];+ };+}++/** Every name of a list found anywhere in a text, in one read of the text (Aho-Corasick, as one table per character). */+class NameMatcher {+ private readonly symbols = new Uint16Array(65_536);+ private readonly width: number;+ private readonly next: Int32Array;+ /** The name ending at each state, or -1; and the nearest shorter state that ends a name, or 0. */+ private readonly ends: Int32Array;+ private readonly shorter: Int32Array;+ private readonly names: readonly string[];++ constructor(names: readonly string[]) {+ this.names = names;+ let width = 1;+ let states = 1;+ for (const name of names) {+ states += name.length;+ for (let i = 0; i < name.length; i++) {+ const code = name.charCodeAt(i);+ if (!this.symbols[code]) this.symbols[code] = width++;+ }+ }+ this.width = width;+ const next = this.next = new Int32Array(states * width).fill(-1);+ const ends = this.ends = new Int32Array(states).fill(-1);+ const shorter = this.shorter = new Int32Array(states);+ let made = 1;+ names.forEach((name, index) => {+ let state = 0;+ for (let i = 0; i < name.length; i++) {+ const at = state * width + this.symbols[name.charCodeAt(i)]!;+ if (next[at] === -1) next[at] = made++;+ state = next[at]!;+ }+ ends[state] = index;+ });+ // Breadth first: a state's fallback (its longest proper suffix that is also a prefix) is settled before its children.+ const fallback = new Int32Array(made);+ const queue = new Int32Array(made);+ let head = 0, tail = 0;+ for (let symbol = 0; symbol < width; symbol++) {+ const child = next[symbol]!;+ if (child === -1) next[symbol] = 0;+ else if (child !== 0) queue[tail++] = child;+ }+ while (head < tail) {+ const state = queue[head++]!;+ const back = fallback[state]!;+ shorter[state] = ends[back]! >= 0 ? back : shorter[back]!;+ for (let symbol = 0; symbol < width; symbol++) {+ const at = state * width + symbol;+ const child = next[at]!;+ if (child === -1) { next[at] = next[back * width + symbol]!; continue; }+ fallback[child] = next[back * width + symbol]!;+ queue[tail++] = child;+ }+ }+ // A character no name has leads back to the start.+ for (let state = 0; state < made; state++) next[state * width] = 0;+ }++ /** Adds to `found` each name `text` holds. */+ read(text: string, found: Set<string>): void {+ const { next, width, symbols, ends, shorter, names } = this;+ let state = 0;+ for (let i = 0; i < text.length; i++) {+ state = next[state * width + symbols[text.charCodeAt(i)]!]!;+ for (let at = state; at !== 0; at = shorter[at]!) if (ends[at]! >= 0) found.add(names[ends[at]!]!);+ }+ }+}++/** One matcher per part of the list that fits MAX_TABLE_ENTRIES. */+function matchers(names: readonly string[]): NameMatcher[] {+ const characters = new Set<number>();+ for (const name of names) for (let i = 0; i < name.length; i++) characters.add(name.charCodeAt(i));+ const width = characters.size + 1;+ const parts: string[][] = [];+ let part: string[] = [];+ let entries = 0;+ for (const name of names) {+ const cost = name.length * width;+ if (part.length && entries + cost > MAX_TABLE_ENTRIES) { parts.push(part); part = []; entries = 0; }+ part.push(name);+ entries += cost;+ }+ if (part.length) parts.push(part);+ return parts.map((list) => new NameMatcher(list));+}++interface Request { names: string[]; remove: RemoveBatch; resolve: (removed: number) => void; reject: (error: unknown) => void }++export function createAttachmentReferences(deps: AttachmentReferencesDeps = {}): AttachmentReferences {+ const rowsFor = deps.rows ?? messageDbRows;+ const watchWrites = deps.watchWrites ?? watchMessageWrites;+ const now = deps.now ?? (() => performance.now());+ const pause = deps.pause ?? (() => nextTurn());+ const sliceMs = deps.sliceMs ?? 15;+ const rowsPerRead = deps.rowsPerRead ?? 64;+ const batch = deps.batch ?? 25;+ let waiting: Request[] = [];+ let running = false;+ let passes = 0;++ /** Reads every row once, a slice at a time, until each name is found or the rows run out. */+ async function scan(all: readonly string[], read: (text: string) => void, found: ReadonlySet<string>): Promise<void> {+ const rows = rowsFor();+ let after = 0;+ // Rows read but not yet checked when a slice ran out of time; a row changed meanwhile is checked again as written.+ let slice: readonly MessageRow[] = [];+ let at = 0;+ for (;;) {+ await pause();+ const started = now();+ do {+ if (at === slice.length) {+ slice = rows(after, rowsPerRead);+ at = 0;+ if (!slice.length) return;+ }+ const row = slice[at++]!;+ read(row.json);+ after = row.rowid;+ if (found.size === all.length) return;+ } while (now() - started < sliceMs);+ }+ }++ async function pass(requests: readonly Request[]): Promise<void> {+ passes++;+ const all = [...new Set(requests.flatMap((request) => request.names))];+ const found = new Set<string>();+ const readers = matchers(all);+ const read = (text: string) => { for (const reader of readers) reader.read(text, found); };+ const stop = watchWrites(read);+ try {+ try {+ await scan(all, read, found);+ } catch (error) {+ for (const request of requests) request.reject(error);+ return;+ }+ let started = now();+ for (const request of requests) {+ const left = request.names.filter((name) => !found.has(name));+ let removed = 0;+ for (let at = 0; at < left.length; at += batch) {+ if (now() - started >= sliceMs) { await pause(); started = now(); }+ const going = left.slice(at, at + batch).filter((name) => !found.has(name));+ try { if (going.length) removed += request.remove(going); } catch { /* the remover warns for itself */ }+ }+ request.resolve(removed);+ }+ } finally {+ stop();+ }+ }++ async function drain(): Promise<void> {+ running = true;+ try {+ while (waiting.length) {+ const requests = waiting;+ waiting = [];+ await pass(requests).catch((error: unknown) => { for (const request of requests) request.reject(error); });+ }+ } finally {+ running = false;+ }+ }++ return {+ removeUnreferenced(names, remove) {+ const list = [...new Set(names)].filter((name) => name !== "");+ if (!list.length) return Promise.resolve(0);+ return new Promise<number>((resolve, reject) => {+ waiting.push({ names: list, remove, resolve, reject });+ if (!running) void drain();+ });+ },+ get passes() { return passes; },+ };+}++/** The server's one: every clean-up shares it, so only one pass over messages.db runs at a time. */+export const attachmentReferences = createAttachmentReferences();diff --git a/server/attachments.ts b/server/attachments.tsindex 32f57c67af..89c579737f 100644--- a/server/attachments.ts+++ b/server/attachments.ts@@ -193,17 +193,22 @@ function dropBoxUploadCopies(names: readonly string[], dataDir = DATA_DIR): voidif (!names.length) return;const root = join(dataDir, "box-uploads");const dirs = (path: string) => { try { return readdirSync(path); } catch { return []; } };+ // One listing of each folder for every name at once: a folder per conversation times a name each was minutes of work+ // when a delete took thousands of uploads.+ const going = new Set(names);for (const bot of dirs(root)) {for (const thread of dirs(join(root, bot))) {- for (const name of names) {- try { rmSync(join(boxUploadsDir(dataDir, bot, thread), name), { force: true }); } catch { /* best effort: a file still in use stays */ }+ const folder = boxUploadsDir(dataDir, bot, thread);+ for (const name of dirs(folder)) {+ if (!going.has(name)) continue;+ try { rmSync(join(folder, name), { force: true }); } catch { /* best effort: a file still in use stays */ }}}}}-/** Every removal of a file saveImage/saveFile created must come through here, or the cache overcounts and rejects uploads. */-export function deleteAttachment(path: string): void {+/** True when the upload is gone (removed now or already); an upload still on disk (a busy file on Windows) stays. */+function unlinkAttachment(path: string): boolean {try {const size = committedAttachmentBytes !== null ? statSync(path).size : 0;unlinkSync(path);@@ -211,13 +216,21 @@ export function deleteAttachment(path: string): void {committedAttachmentBytes = Math.max(0, committedAttachmentBytes - size);}} catch (error) {- // 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)]);- dropKeptOriginals([basename(path)]);+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") return false;}+ return true;+}++/** Every removal of a file saveImage/saveFile created must come through here, or the cache overcounts and rejects uploads. */+export function deleteAttachment(path: string): void {+ deleteAttachments([path]);+}++/** deleteAttachment for many files at once. An upload still on disk keeps its box copies; one gone loses them. */+export function deleteAttachments(paths: readonly string[]): void {+ const gone = paths.filter((path) => unlinkAttachment(path) && resolve(dirname(path)) === resolve(ATTACHMENTS_DIR)).map((path) => basename(path));+ dropBoxUploadCopies(gone);+ dropKeptOriginals(gone);}/** Settings → General: what the store holds against its ceiling, rescanned so files removed outside the app count. */diff --git a/server/host/delete-leftovers.many-uploads.test.ts b/server/host/delete-leftovers.many-uploads.test.tsnew file mode 100644index 0000000000..9c0af795ac--- /dev/null+++ b/server/host/delete-leftovers.many-uploads.test.ts@@ -0,0 +1,133 @@+// A delete of conversations holding thousands of uploads, against a transcript store of tens of thousands of rows: the+// check of which uploads a remaining message still names is one pass over the rows in short slices, so the server keeps+// answering while it runs, and it keeps and removes exactly the files the old per-name check did.+import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { monitorEventLoopDelay } from "node:perf_hooks";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { createAttachmentReferences, messageDbRows } from "../attachment-references.ts";+import { deleteAttachments } from "../attachments.ts";+import { DATA_DIR } from "../config.ts";+import * as mdb from "../message-db.ts";+import type { Message } from "../store.ts";+import { createDeleteLeftovers, type DeleteLeftoversDeps } from "./delete-leftovers.ts";++const NAMES = 2_000;+const DELETED_THREADS = 20;+const REMAINING_THREADS = 100;+const ROWS_PER_THREAD = 500;+const FILLER = "lorem ipsum dolor sit amet, ".repeat(45);+const MEMBER = "p_bobbobbobbobbobbobbobb";++const name = (i: number) => `${String(i).padStart(8, "0")}-0000-4000-8000-000000000000.png`;+const names = Array.from({ length: NAMES }, (_, i) => name(i));+/** Every third name stays named by a remaining conversation, in one of the ways a message names a file. */+const referenced = new Set(names.filter((_, i) => i % 3 === 0));+const kept = new Set(names.filter((_, i) => i % 3 !== 0 && i % 40 === 1));+const pictured = new Set(names.filter((_, i) => i % 3 !== 0 && i % 40 === 2));+const ways = [+ (file: string) => ``,+ (file: string) => `the file ${file} from before`,+ (file: string) => `copy-of-${file}.bak`,+ (file: string) => `<attached-file path="C:\\data\\attachments\\${file}" />`,+];++let rowCount = 0;+const message = (thread: string, row: number, text: string): Message =>+ ({ id: `${thread}-m${row}`, at: 1_700_000_000_000 + row, role: row % 2 ? "bot" : "user", kind: "text", text, detail: FILLER }) as unknown as Message;++beforeAll(() => {+ mkdirSync(join(DATA_DIR, "attachments"), { recursive: true });+ for (const file of names) writeFileSync(join(DATA_DIR, "attachments", file), "x");+ mkdirSync(join(DATA_DIR, "people", MEMBER), { recursive: true });+ writeFileSync(join(DATA_DIR, "people", MEMBER, "profile.json"), JSON.stringify({ name: "Bob", avatarUrl: `/api/attachments/${[...pictured][0]}`, more: [...pictured].map((file) => `/api/attachments/${file}`) }));+ const naming = [...referenced];+ for (let t = 0; t < REMAINING_THREADS; t++) {+ const thread = `keep${t}`;+ mdb.importThread(thread, Array.from({ length: ROWS_PER_THREAD }, (_, row) => {+ const at = t * ROWS_PER_THREAD + row;+ const file = at % 75 === 0 ? naming[(at / 75) % naming.length] : undefined;+ return message(thread, row, file ? ways[at % ways.length]!(file) : `line ${at}`);+ }), null);+ }+ rowCount = REMAINING_THREADS * ROWS_PER_THREAD;+ // A box uploads folder for many conversations, each with a copy of some uploads and a file of its own.+ for (let t = 0; t < 300; t++) {+ const folder = join(DATA_DIR, "box-uploads", "scout", `other${t}`);+ mkdirSync(folder, { recursive: true });+ writeFileSync(join(folder, "own.txt"), "x");+ for (let i = t; i < NAMES; i += 150) writeFileSync(join(folder, name(i)), "x");+ }+}, 120_000);++afterAll(() => {+ mdb.closeMessageDb();+ rmSync(DATA_DIR, { recursive: true, force: true });+});++describe("deleting conversations that hold thousands of uploads", () => {+ it("never holds the event loop for long, reads each remaining row once, and removes exactly what the old check removed", async () => {+ expect(referenced.size).toBe(Math.ceil(NAMES / 3));+ // Every name planted in the remaining rows is there; the old check would keep it.+ expect(rowCount).toBe(50_000);+ const conversations = new Map<string, unknown[]>();+ for (let t = 0; t < DELETED_THREADS; t++) {+ const thread = `gone${t}`;+ const held = names.filter((_, i) => i % DELETED_THREADS === t);+ const rows = held.map((file, row) => message(thread, row, ``));+ mdb.importThread(thread, rows, null);+ conversations.set(thread, rows);+ }+ let reads = 0, read = 0, pauses = 0;+ const references = createAttachmentReferences({+ rows: () => { const inner = messageDbRows(); return (after, limit) => { reads++; const slice = inner(after, limit); read += slice.length; return slice; }; },+ pause: () => new Promise((done) => { pauses++; setImmediate(done); }),+ });+ let listener: (change: { type: string; threadId?: string }) => void = () => {};+ const store: DeleteLeftoversDeps["store"] = { bots: [], messagesFor: (threadId) => conversations.get(threadId) ?? [], onChange: (added) => { listener = added; }, threadsGoing: () => {} };+ const warnings: string[] = [];+ const leftovers = createDeleteLeftovers({+ dataDir: DATA_DIR,+ store,+ references,+ keptAttachments: () => kept,+ deleteAttachments: (files) => deleteAttachments(files.map((file) => join(DATA_DIR, "attachments", file))),+ engineFolders: () => ({ claude: [], codex: [], pi: [] }),+ layers: { journalFile: (layer) => join(DATA_DIR, "memory-journal", `${layer}.ndjson`), forget: () => {} },+ defer: () => {},+ warn: (line) => { warnings.push(line); },+ });+ const gone = [...conversations.keys()];+ store.threadsGoing(gone);+ mdb.deleteThreads(gone);+ for (const thread of gone) listener({ type: "thread.deleted", threadId: thread });++ const delay = monitorEventLoopDelay({ resolution: 10 });+ delay.enable();+ await leftovers.flush();+ delay.disable();+ const longestMs = delay.max / 1e6;++ expect(warnings).toEqual([]);+ // One pass: every remaining row read once, in many short reads with the event loop given back between slices.+ expect(references.passes).toBe(1);+ expect(read).toBe(rowCount);+ expect(reads).toBeGreaterThan(rowCount / 64);+ expect(pauses).toBeGreaterThan(10);+ expect(longestMs).toBeLessThan(1_000);++ const stored = (file: string) => existsSync(join(DATA_DIR, "attachments", file));+ const expected = (file: string) => referenced.has(file) || kept.has(file) || pictured.has(file);+ expect(names.filter((file) => stored(file) !== expected(file))).toEqual([]);+ expect(names.filter((file) => !stored(file)).length).toBe(NAMES - referenced.size - kept.size - pictured.size);+ // The old per-name check agrees, on a sample of both kinds.+ for (const file of [...names.filter((f) => referenced.has(f)).slice(0, 20), ...names.filter((f) => !expected(f)).slice(0, 20)]) {+ expect(mdb.threadsReferencing(file).length > 0, file).toBe(referenced.has(file));+ }+ // A removed upload's copies go from every box uploads folder; a kept one's and the folders' own files stay.+ const copies = (i: number) => existsSync(join(DATA_DIR, "box-uploads", "scout", `other${i % 150}`, name(i)));+ expect(names.map((_, i) => i).filter((i) => copies(i) !== expected(name(i)))).toEqual([]);+ expect(existsSync(join(DATA_DIR, "box-uploads", "scout", "other7", "own.txt"))).toBe(true);+ }, 300_000);+});diff --git a/server/host/delete-leftovers.store.test.ts b/server/host/delete-leftovers.store.test.tsindex d9facdda73..89169acdfe 100644--- a/server/host/delete-leftovers.store.test.ts+++ b/server/host/delete-leftovers.store.test.ts@@ -7,6 +7,7 @@ import type { ModelSelection } from "../contracts.ts";import { journalFile } from "../memory-journal.ts";import * as mdb from "../message-db.ts";import { Store } from "../store.ts";+import { createAttachmentReferences } from "../attachment-references.ts";import { createConversationFolderCleanup, deleteTimeCleanup } from "./conversation-folder-cleanup.ts";import { createDeleteLeftovers, engineSessionFolders, type DeleteLeftoversDeps } from "./delete-leftovers.ts";import { memoryLayerRecords } from "./team-member-left.ts";@@ -27,9 +28,9 @@ function fixture(over: Partial<Omit<DeleteLeftoversDeps, "store">> & { store?: Sconst warnings: string[] = [];const leftovers = createDeleteLeftovers({dataDir: DATA_DIR,- threadsReferencing: mdb.threadsReferencing,+ references: createAttachmentReferences(),keptAttachments: () => new Set(),- deleteAttachment: (name) => rmSync(join(DATA_DIR, "attachments", name)),+ deleteAttachments: (names) => { for (const name of names) rmSync(join(DATA_DIR, "attachments", name)); },engineFolders: () => engineSessionFolders(DATA_DIR, [{ HOME }]),layers: memoryLayerRecords,defer: () => {},@@ -52,49 +53,50 @@ function fixture(over: Partial<Omit<DeleteLeftoversDeps, "store">> & { store?: Sdescribe("deleting through the store", () => {beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));- it("removes a deleted conversation's upload, engine session and box uploads, and keeps the files it made", () => {+ it("removes a deleted conversation's upload, engine session and box uploads, and keeps the files it made", async () => {const { store, bot, task, files, leftovers } = fixture();const made = put(join(DATA_DIR, "task-workspaces", bot.id, task.threadId, "result.txt"));expect(store.deleteTask(bot.id, task.threadId)).not.toBeNull();- leftovers.flush();+ await leftovers.flush();expect(Object.values(files).filter(existsSync)).toEqual([]);expect(existsSync(made)).toBe(true);});- it("keeps an upload a conversation that stays also shows", () => {+ it("keeps an upload a conversation that stays also shows", async () => {const { store, bot, task, files, leftovers } = fixture();store.appendMessage(bot.threadId, { role: "user", kind: "text", text: `` });store.deleteTask(bot.id, task.threadId);- leftovers.flush();+ await leftovers.flush();expect([existsSync(files.upload), existsSync(files.session)]).toEqual([true, false]);});- it("removes nothing when the delete itself fails", () => {+ it("removes nothing when the delete itself fails", async () => {const { store, bot, task, files, leftovers } = fixture();vi.spyOn(store as unknown as { commitBotChange: () => void }, "commitBotChange").mockImplementationOnce(() => { throw new Error("fixture write failure"); });expect(() => store.deleteTask(bot.id, task.threadId)).toThrow("fixture write failure");- leftovers.flush();+ await leftovers.flush();expect(store.messagesFor(task.threadId)).toHaveLength(1);expect(Object.values(files).filter((path) => !existsSync(path))).toEqual([]);});- it("deletes the conversation even when the cleanup fails", () => {+ it("deletes the conversation even when the cleanup fails", async () => {const { store, bot, task, files, warnings, leftovers } = fixture({- deleteAttachment: () => { throw new Error("disk is read-only"); },+ deleteAttachments: () => { throw new Error("disk is read-only"); },engineFolders: () => { throw new Error("no engine folders"); },});expect(store.deleteTask(bot.id, task.threadId)).not.toBeNull();- expect(() => leftovers.flush()).not.toThrow();+ await expect(leftovers.flush()).resolves.toBeUndefined();expect(store.taskByThread(bot.id, task.threadId)).toBeFalsy();expect(mdb.threadsReferencing(UPLOAD)).toEqual([]);expect(existsSync(files.upload)).toBe(true);+ // The uploads go last, after the pass over the transcripts.expect(warnings).toEqual([- `delete leftovers: the upload ${UPLOAD} stayed behind: disk is read-only`,"delete leftovers: engine sessions stayed behind: no engine folders",+ `delete leftovers: the upload ${UPLOAD} stayed behind: disk is read-only`,]);});- it("removes a deleted bot's uploads, sessions, checkpoints, memory layers and memory journal, and keeps the files it made", () => {+ it("removes a deleted bot's uploads, sessions, checkpoints, memory layers and memory journal, and keeps the files it made", async () => {const { store, bot, files, leftovers } = fixture();const layer = `${bot.id}--member-p_bobbobbobbobbobbobbobb`;const mine = [@@ -107,12 +109,12 @@ describe("deleting through the store", () => {const other = store.createBot({ name: "Ledger" });const others = [put(join(DATA_DIR, "checkpoints", other.id, "0123456789abcdef", ".git", "HEAD")), put(journalFile(other.id)), put(join(DATA_DIR, "task-workspaces", bot.id, bot.threadId, "result.txt"))];expect(store.deleteBot(bot.id)).toBe(true);- leftovers.flush();+ await leftovers.flush();expect(mine.filter(existsSync)).toEqual([]);expect(others.filter((path) => !existsSync(path))).toEqual([]);});- it("removes a deleted group chat's uploads", () => {+ it("removes a deleted group chat's uploads", async () => {const { store, bot, leftovers } = fixture();const other = store.createBot({ name: "Ledger" });const room = store.createGroup("Launch team", [bot.id, other.id], false);@@ -120,7 +122,7 @@ describe("deleting through the store", () => {const upload = put(join(DATA_DIR, "attachments", name));store.appendMessage(room.threadId, { role: "user", kind: "text", text: `` });expect(store.deleteGroup(room.id)).toBe(true);- leftovers.flush();+ await leftovers.flush();expect(existsSync(upload)).toBe(false);});@@ -135,7 +137,7 @@ describe("deleting through the store", () => {put(join(own, "site", "package.json"));const results = put(join(DATA_DIR, "tool-results", task.threadId, "r.txt"));expect(store.deleteTask(bot.id, task.threadId)).not.toBeNull();- leftovers.flush();+ await leftovers.flush();await new Promise((done) => setTimeout(done, 0));expect([existsSync(deps), existsSync(results)]).toEqual([true, true]);expect(existsSync(join(DATA_DIR, ".removing"))).toBe(false);@@ -155,12 +157,12 @@ describe("deleting through the store", () => {put(join(own, "site", "package.json"));const results = put(join(DATA_DIR, "tool-results", task.threadId, "r.txt"));expect(store.deleteTask(bot.id, task.threadId)).not.toBeNull();- leftovers.flush();+ await leftovers.flush();await folders.idle();expect(existsSync(results)).toBe(false);expect(existsSync(deps)).toBe(true);expect(store.deleteTask(bot.id, fork.threadId)).not.toBeNull();- leftovers.flush();+ await leftovers.flush();await folders.idle();expect(existsSync(deps)).toBe(false);expect(existsSync(made)).toBe(true);@@ -175,7 +177,7 @@ describe("deleting through the store", () => {put(join(DATA_DIR, "task-workspaces", bot.id, "deleted-earlier", "node_modules", ".modules.yaml"));put(join(DATA_DIR, "task-workspaces", bot.id, "deleted-earlier", "package.json"));expect(store.deleteBot(bot.id)).toBe(true);- leftovers.flush();+ await leftovers.flush();await folders.idle();expect(existsSync(deps)).toBe(false);expect(existsSync(made)).toBe(true);diff --git a/server/host/delete-leftovers.test.ts b/server/host/delete-leftovers.test.tsindex 778c3f5373..31d5c9493c 100644--- a/server/host/delete-leftovers.test.ts+++ b/server/host/delete-leftovers.test.ts@@ -3,6 +3,8 @@ import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";+import { createAttachmentReferences } from "../attachment-references.ts";+import { rowsOfConversations } from "../testing/message-rows-fixture.ts";import { createDeleteLeftovers, engineSessionFolders, instanceEnvironment, plainlyUnder, removeMemoryLayer, removeUnder, type DeleteLeftoversDeps } from "./delete-leftovers.ts";const SESSION = "11111111-1111-4111-8111-111111111111";@@ -42,9 +44,9 @@ function fixture(over: Partial<DeleteLeftoversDeps> = {}) {const leftovers = createDeleteLeftovers({dataDir,store,- threadsReferencing: (fragment) => [...messages].filter(([, list]) => JSON.stringify(list).includes(fragment)).map(([threadId]) => threadId),+ references: createAttachmentReferences({ rows: rowsOfConversations(messages) }),keptAttachments: () => kept,- deleteAttachment: (name) => rmSync(join(dataDir, "attachments", name)),+ deleteAttachments: (names) => { for (const name of names) rmSync(join(dataDir, "attachments", name)); },engineFolders: () => engineSessionFolders(dataDir, [{ HOME: home }]),layers: { journalFile: (layer) => join(dataDir, "memory-journal", `${layer}.ndjson`), forget: (layer) => { forgotten.push(layer); } },defer: () => {},@@ -63,7 +65,7 @@ function fixture(over: Partial<DeleteLeftoversDeps> = {}) {for (const bot of bots) bot.tasks = bot.tasks?.filter((task) => task.threadId !== threadId);listener({ type: "thread.deleted", threadId });}- leftovers.flush();+ return leftovers.flush();};const deleteBot = (botId: string) => {const bot = bots.find((one) => one.id === botId)!;@@ -75,7 +77,7 @@ function fixture(over: Partial<DeleteLeftoversDeps> = {}) {listener({ type: "thread.deleted", threadId });}listener({ type: "bot.deleted", botId });- leftovers.flush();+ return leftovers.flush();};const stored = (name: string) => existsSync(join(dataDir, "attachments", name));const logSession = (threadId: string, sessionId: string) =>@@ -84,84 +86,84 @@ function fixture(over: Partial<DeleteLeftoversDeps> = {}) {}describe("a deleted conversation's uploads", () => {- it("go with it", () => {+ it("go with it", async () => {const { bots, say, deleteThreads, stored } = fixture();bots.push({ id: "scout", tasks: [{ threadId: "t1" }, { threadId: "t2" }] });say("t1", upload(1));- deleteThreads("t1");+ await deleteThreads("t1");expect(stored(upload(1))).toBe(false);});- it("stay while another conversation, a picture, a member's picture or a routine still names them", () => {+ it("stay while another conversation, a picture, a member's picture or a routine still names them", async () => {const { dataDir, bots, kept, say, deleteThreads, stored } = fixture();bots.push({ id: "scout", tasks: [{ threadId: "t1" }, { threadId: "t2" }] });say("t2", upload(1));say("t1", upload(1), upload(2), upload(3), upload(4));kept.add(upload(2));put(join(dataDir, "people", MEMBER, "profile.json"), JSON.stringify({ name: "Bob", avatarUrl: `/api/attachments/${upload(4)}` }));- deleteThreads("t1");+ await deleteThreads("t1");expect([stored(upload(1)), stored(upload(2)), stored(upload(3)), stored(upload(4))]).toEqual([true, true, false, true]);});- it("go once every conversation that named them is deleted together", () => {+ it("go once every conversation that named them is deleted together", async () => {const { bots, say, deleteThreads, stored } = fixture();bots.push({ id: "scout", tasks: [{ threadId: "t1" }, { threadId: "t2" }, { threadId: "t3" }] });say("t1", upload(1));say("t2", upload(1));- deleteThreads("t1", "t2");+ await deleteThreads("t1", "t2");expect(stored(upload(1))).toBe(false);});- it("stay when the delete did not happen", () => {+ it("stay when the delete did not happen", async () => {const { bots, say, store, leftovers, stored } = fixture();bots.push({ id: "scout", tasks: [{ threadId: "t1" }] });say("t1", upload(1));store.threadsGoing(["t1"]);- leftovers.flush();+ await leftovers.flush();expect(stored(upload(1))).toBe(true);});- it("stay, with a warning, while what still uses uploads cannot be read", () => {+ it("stay, with a warning, while what still uses uploads cannot be read", async () => {const { bots, say, deleteThreads, stored, warnings } = fixture({ keptAttachments: () => null });bots.push({ id: "scout", tasks: [{ threadId: "t1" }] });say("t1", upload(1));- deleteThreads("t1");+ await deleteThreads("t1");expect(stored(upload(1))).toBe(true);expect(warnings.join("\n")).toContain("uploads stayed behind");});- it("never reach a file outside attachments/ a message names", () => {+ it("never reach a file outside attachments/ a message names", async () => {const { dataDir, bots, messages, deleteThreads } = fixture();bots.push({ id: "scout", tasks: [{ threadId: "t1" }] });const config = put(join(dataDir, "config.json"));messages.set("t1", [{ text: "attachments/../config.json and attachments/..\\config.json" }]);- deleteThreads("t1");+ await deleteThreads("t1");expect(existsSync(config)).toBe(true);});- it("take the conversation's box uploads folder too", () => {+ it("take the conversation's box uploads folder too", async () => {const { dataDir, bots, deleteThreads } = fixture();bots.push({ id: "scout", tasks: [{ threadId: "t1" }, { threadId: "t2" }] });const mine = put(join(dataDir, "box-uploads", "scout", "t1", upload(1)));const others = put(join(dataDir, "box-uploads", "scout", "t2", upload(2)));- deleteThreads("t1");+ await deleteThreads("t1");expect([existsSync(dirname(mine)), existsSync(others)]).toEqual([false, true]);});- it("take the conversation's own notes, and leave the bot's memory and its other conversations' notes", () => {+ it("take the conversation's own notes, and leave the bot's memory and its other conversations' notes", async () => {const { dataDir, bots, deleteThreads } = fixture();bots.push({ id: "counsel", tasks: [{ threadId: "t1" }, { threadId: "t2" }] });const memory = join(dataDir, "workspaces", "counsel");const mine = put(join(memory, "memory", "threads", "t1.md"));const others = put(join(memory, "memory", "threads", "t2.md"));const index = put(join(memory, "MEMORY.md"));- deleteThreads("t1");+ await deleteThreads("t1");expect([existsSync(mine), existsSync(others), existsSync(index)]).toEqual([false, true, true]);});});describe("a deleted conversation's engine sessions", () => {- it("go from Claude's and Codex's folders, by the session it resumes and the ones its log says it started", () => {+ it("go from Claude's and Codex's folders, by the session it resumes and the ones its log says it started", async () => {const { home, bots, deleteThreads, logSession } = fixture();bots.push({ id: "scout", tasks: [{ threadId: "t1", resumeCursors: { claude: SESSION } }, { threadId: "t2", resumeCursors: { claude: SHARED } }] });logSession("t1", LOGGED);@@ -184,23 +186,23 @@ describe("a deleted conversation's engine sessions", () => {put(join(home, ".codex", "sessions", "2026", "11", "10", `rollout-2026-11-10T11-00-00-${SHARED}.jsonl`)),put(join(home, ".codex", "auth.json")),];- deleteThreads("t1");+ await deleteThreads("t1");expect(mine.filter(existsSync)).toEqual([]);expect(others.filter((path) => !existsSync(path))).toEqual([]);});- it("stay while a remaining conversation resumes the same session", () => {+ it("stay while a remaining conversation resumes the same session", async () => {const { home, bots, deleteThreads, logSession } = fixture();bots.push({ id: "scout", tasks: [{ threadId: "t1", resumeCursors: { claude: SHARED } }, { threadId: "fork", resumeCursors: { claude: SHARED } }] });logSession("t1", SHARED);const session = put(join(home, ".claude", "projects", "-work", `${SHARED}.jsonl`));- deleteThreads("t1");+ await deleteThreads("t1");expect(existsSync(session)).toBe(true);- deleteThreads("fork");+ await deleteThreads("fork");expect(existsSync(session)).toBe(false);});- it("go from every audience's engine home on a Team Cloud", () => {+ it("go from every audience's engine home on a Team Cloud", async () => {const sessions = (dataDir: string) => engineSessionFolders(dataDir, ["team", "member-0123456789abcdef"].map((key) => ({ HOME: join(dataDir, "engine-homes", key) })));let dataDirOf = "";const { dataDir, bots, deleteThreads } = fixture({ engineFolders: () => sessions(dataDirOf) });@@ -208,20 +210,20 @@ describe("a deleted conversation's engine sessions", () => {bots.push({ id: "scout", tasks: [{ threadId: "t1", resumeCursors: { claude: SESSION, codex: LOGGED } }, { threadId: "t2" }] });const team = put(join(dataDir, "engine-homes", "team", ".claude", "projects", "-work", `${SESSION}.jsonl`));const member = put(join(dataDir, "engine-homes", "member-0123456789abcdef", ".codex", "sessions", "2026", "11", "10", `rollout-x-${LOGGED}.jsonl`));- deleteThreads("t1");+ await deleteThreads("t1");expect([existsSync(team), existsSync(member)]).toEqual([false, false]);});- it("removes a Pi session, which is named by its file, only inside Pi's own folder", () => {+ it("removes a Pi session, which is named by its file, only inside Pi's own folder", async () => {const { home, outside, bots, deleteThreads } = fixture();const mine = put(join(home, ".pi", "agent", "sessions", "--work--", "2026-11-10_a.jsonl"));const elsewhere = put(join(outside, "notes.jsonl"));bots.push({ id: "scout", tasks: [{ threadId: "t1", resumeCursors: { pi: mine } }, { threadId: "t2", resumeCursors: { pi: elsewhere } }, { threadId: "t3" }] });- deleteThreads("t1", "t2");+ await deleteThreads("t1", "t2");expect([existsSync(mine), existsSync(elsewhere)]).toEqual([false, true]);});- it("never follows a link out of an engine's folder", () => {+ it("never follows a link out of an engine's folder", async () => {const { home, outside, bots, deleteThreads } = fixture();bots.push({ id: "scout", tasks: [{ threadId: "t1", resumeCursors: { claude: SESSION } }, { threadId: "t2" }] });const elsewhere = put(join(outside, "projects", "-work", `${SESSION}.jsonl`));@@ -232,12 +234,12 @@ describe("a deleted conversation's engine sessions", () => {symlinkSync(join(outside, "history", SESSION), join(home, ".claude", "file-history", SESSION));mkdirSync(join(home, ".codex"), { recursive: true });symlinkSync(join(outside, "projects"), join(home, ".codex", "sessions"));- deleteThreads("t1");+ await deleteThreads("t1");expect([existsSync(elsewhere), existsSync(history)]).toEqual([true, true]);expect(existsSync(join(home, ".claude", "file-history", SESSION))).toBe(false);});- it("never follows a link out of the data folder to an engine home", () => {+ it("never follows a link out of the data folder to an engine home", async () => {const sessions = (dataDir: string) => engineSessionFolders(dataDir, [{ HOME: join(dataDir, "engine-homes", "team") }]);let dataDirOf = "";const { dataDir, outside, bots, deleteThreads } = fixture({ engineFolders: () => sessions(dataDirOf) });@@ -246,13 +248,13 @@ describe("a deleted conversation's engine sessions", () => {const elsewhere = put(join(outside, "claude", "projects", "-work", `${SESSION}.jsonl`));mkdirSync(join(dataDir, "engine-homes", "team"), { recursive: true });symlinkSync(join(outside, "claude"), join(dataDir, "engine-homes", "team", ".claude"));- deleteThreads("t1");+ await deleteThreads("t1");expect(existsSync(elsewhere)).toBe(true);});});describe("a deleted bot", () => {- it("takes its checkpoints, its box uploads and the memory layers kept beside its own folder, and keeps the files its conversations made", () => {+ it("takes its checkpoints, its box uploads and the memory layers kept beside its own folder, and keeps the files its conversations made", async () => {const { dataDir, bots, deleteBot, forgotten } = fixture();bots.push({ id: "scout", tasks: [{ threadId: "t1" }] }, { id: "scout-two", tasks: [{ threadId: "t9" }] });const layers = [`scout--member-${MEMBER}`, "scout--room-r1"];@@ -268,7 +270,7 @@ describe("a deleted bot", () => {put(join(dataDir, "workspaces", "scout-two", "memory", "notes.md")),put(join(dataDir, "memory-journal", "scout-two.ndjson")),];- deleteBot("scout");+ await deleteBot("scout");expect(mine.filter(existsSync)).toEqual([]);expect(others.filter((path) => !existsSync(path))).toEqual([]);expect(forgotten.sort()).toEqual([...layers].sort());@@ -281,7 +283,7 @@ describe("a deleted bot", () => {bots.push({ id: "scout", tasks: [{ threadId: "t1" }] });const checkpoint = put(join(dataDir, "checkpoints", "scout", "0123456789abcdef", ".git", "HEAD"));const uploaded = put(join(dataDir, "box-uploads", "scout", "t1", upload(1)));- deleteBot("scout");+ await deleteBot("scout");await Promise.resolve();expect(asked).toEqual(["scout"]);expect([existsSync(checkpoint), existsSync(uploaded)]).toEqual([true, false]);@@ -289,7 +291,7 @@ describe("a deleted bot", () => {await vi.waitFor(() => expect(existsSync(checkpoint)).toBe(false));});- it("never follows a link out of the data folder", () => {+ it("never follows a link out of the data folder", async () => {const { dataDir, outside, bots, deleteBot } = fixture();bots.push({ id: "scout", tasks: [{ threadId: "t1" }] });const checkpoint = put(join(outside, "checkpoints", "scout", "repo", "HEAD"));@@ -297,14 +299,14 @@ describe("a deleted bot", () => {symlinkSync(join(outside, "checkpoints"), join(dataDir, "checkpoints"));mkdirSync(join(dataDir, "workspaces"), { recursive: true });symlinkSync(join(outside, "layer"), join(dataDir, "workspaces", `scout--member-${MEMBER}`));- deleteBot("scout");+ await deleteBot("scout");expect([existsSync(checkpoint), existsSync(layer)]).toEqual([true, true]);expect(existsSync(join(dataDir, "workspaces", `scout--member-${MEMBER}`))).toBe(false);});});describe("the conversation folders' cleanup", () => {- it("is handed the deleted conversations, the folders they worked in and the deleted bots, and a failure there stays inside it", () => {+ it("is handed the deleted conversations, the folders they worked in and the deleted bots, and a failure there stays inside it", async () => {const calls: unknown[] = [];const { bots, deleteThreads, deleteBot, warnings, say } = fixture({ folders: {conversationsGone: (ids, workedIn) => { calls.push(["threads", [...ids], [...(workedIn ?? [])]]); throw new Error("busy disk"); },@@ -312,21 +314,21 @@ describe("the conversation folders' cleanup", () => {} });bots.push({ id: "scout", tasks: [{ threadId: "t1", cwd: "/data/task-workspaces/scout/t0" }, { threadId: "t2" }] });say("t1", upload(1));- deleteThreads("t1");- deleteBot("scout");+ await deleteThreads("t1");+ await deleteBot("scout");expect(calls).toEqual([["threads", ["t1"], ["/data/task-workspaces/scout/t0"]], ["threads", ["t2"], []], ["bot", "scout"]]);expect(warnings.filter((line) => line.includes("busy disk"))).toHaveLength(2);});});describe("a cleanup that fails", () => {- it("is logged, never thrown into the delete, and the rest still goes", () => {- const { dataDir, home, bots, say, deleteThreads, warnings } = fixture({ deleteAttachment: () => { throw new Error("disk is read-only"); } });+ it("is logged, never thrown into the delete, and the rest still goes", async () => {+ const { dataDir, home, bots, say, deleteThreads, warnings } = fixture({ deleteAttachments: () => { throw new Error("disk is read-only"); } });bots.push({ id: "scout", tasks: [{ threadId: "t1", resumeCursors: { claude: SESSION } }, { threadId: "t2" }] });say("t1", upload(1));const session = put(join(home, ".claude", "projects", "-work", `${SESSION}.jsonl`));const box = put(join(dataDir, "box-uploads", "scout", "t1", upload(1)));- expect(() => deleteThreads("t1")).not.toThrow();+ await expect(deleteThreads("t1")).resolves.toBeUndefined();expect(warnings).toEqual([`delete leftovers: the upload ${upload(1)} stayed behind: disk is read-only`]);expect([existsSync(session), existsSync(box)]).toEqual([false, false]);});diff --git a/server/host/delete-leftovers.ts b/server/host/delete-leftovers.tsindex 54ff281162..30408e968c 100644--- a/server/host/delete-leftovers.ts+++ b/server/host/delete-leftovers.ts@@ -11,6 +11,7 @@import { lstatSync, readFileSync, readdirSync, rmSync } from "node:fs";import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";+import type { AttachmentReferences } from "../attachment-references.ts";import { baseBotId, isLayerId } from "../audience.ts";/** A file in attachments/, by its URL or by its path (as JSON escapes it) a sent document's tag carries. */@@ -49,12 +50,13 @@ export interface DeleteLeftoversDeps {/** Set here: the store calls it before it tries to delete these conversations. */threadsGoing: (threadIds: readonly string[]) => void;};- /** Conversations whose messages still name this text (message-db.ts threadsReferencing). */- threadsReferencing(fragment: string): readonly string[];+ /** Which uploads no remaining message names: one pass over the transcripts for them all (attachment-references.ts). */+ references: Pick<AttachmentReferences, "removeUnreferenced">;/** Stored names something other than a transcript uses (pictures, routines' files, files on their way into a turn);* null while that cannot be read, and then no upload is removed. */keptAttachments(): ReadonlySet<string> | null;- deleteAttachment(name: string): void;+ /** Removes these stored uploads, by name (attachments.ts deleteAttachments). */+ deleteAttachments(names: readonly string[]): void;engineFolders(): EngineSessionFolders;layers: MemoryLayerRecords;/** Resolves once no git is running on the bot's checkpoints: Windows cannot remove a folder a process still has open. */@@ -258,19 +260,42 @@ export function createDeleteLeftovers(deps: DeleteLeftoversDeps) {}).join("\n");}- function removeAttachments(names: ReadonlySet<string>): void {- if (!names.size) return;+ /** Of these names, the stored uploads nothing but a transcript may use: not a picture, a member's picture or a kept file.+ * Null, with a warning, while what still uses uploads cannot be read. */+ function removable(names: Iterable<string>): string[] | null {const kept = deps.keptAttachments();- if (!kept) return warn("delete leftovers: uploads stayed behind: what still uses them cannot be read right now");+ if (!kept) { warn("delete leftovers: uploads stayed behind: what still uses them cannot be read right now"); return null; }const pictures = memberPictures();+ const found: string[] = [];for (const name of names) {const path = join(attachments, name);if (name.includes("..") || basename(name) !== name || kept.has(name) || pictures.includes(name) || !plainlyUnder(dataDir, path)) continue;- attempt(`the upload ${name}`, () => {- if (!lstatSync(path, { throwIfNoEntry: false })?.isFile() || deps.threadsReferencing(name).length) return;- deps.deleteAttachment(name);- });+ attempt(`the upload ${name}`, () => { if (lstatSync(path, { throwIfNoEntry: false })?.isFile()) found.push(name); });}+ return found;+ }++ /** Asked again just before they go, since the pass gives the event loop back: a name something started using meanwhile stays. */+ function removeNow(names: readonly string[]): number {+ const going = removable(names) ?? [];+ if (!going.length) return 0;+ try {+ deps.deleteAttachments(going);+ } catch (error) {+ for (const name of going) warn(`delete leftovers: the upload ${name} stayed behind: ${error instanceof Error ? error.message : String(error)}`);+ return 0;+ }+ return going.length;+ }++ /** Resolves once every upload no remaining message names has gone; never rejects. */+ function removeAttachments(names: ReadonlySet<string>): Promise<void> {+ if (!names.size) return Promise.resolve();+ const candidates = removable(names);+ if (!candidates?.length) return Promise.resolve();+ return deps.references.removeUnreferenced(candidates, removeNow).then(() => {}, (error: unknown) => {+ for (const name of candidates) warn(`delete leftovers: the upload ${name} stayed behind: ${error instanceof Error ? error.message : String(error)}`);+ });}function removeSessions(sessions: ReadonlySet<string>): void {@@ -313,13 +338,15 @@ export function createDeleteLeftovers(deps: DeleteLeftoversDeps) {}}- function flush(): void {+ /** The uploads go after the rest, off this call: the promise resolves once they have. */+ function flush(): Promise<void> {scheduled = false;const threads = new Map(gone);const bots = [...goneBots];gone.clear();goneBots.clear();- attempt("uploads", () => removeAttachments(new Set([...threads.values()].flatMap((found) => [...found.attachments]))));+ let uploads = Promise.resolve();+ attempt("uploads", () => { uploads = removeAttachments(new Set([...threads.values()].flatMap((found) => [...found.attachments]))); });attempt("engine sessions", () => removeSessions(new Set([...threads.values()].flatMap((found) => [...found.sessions]))));for (const threadId of threads.keys()) attempt(`box uploads of ${threadId}`, () => removeBoxUploads(threadId));for (const threadId of threads.keys()) attempt(`notes of ${threadId}`, () => removeThreadNotes(threadId));@@ -329,12 +356,13 @@ export function createDeleteLeftovers(deps: DeleteLeftoversDeps) {attempt("conversation folders", () => folders.conversationsGone(threads.keys(), [...threads.values()].flatMap((found) => [...found.folders])));for (const botId of bots) if (!isLayerId(botId)) attempt(`conversation folders of ${botId}`, () => folders.botGone(botId));}+ return uploads;}function schedule(): void {if (scheduled) return;scheduled = true;- defer(() => attempt("leftovers", flush));+ defer(() => attempt("leftovers", () => void flush()));}deps.store.threadsGoing = (threadIds) => {diff --git a/server/host/team-member-left.test.ts b/server/host/team-member-left.test.tsindex 9e62417b79..5e86fb1aa4 100644--- a/server/host/team-member-left.test.ts+++ b/server/host/team-member-left.test.ts@@ -3,7 +3,9 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, it } from "vitest";+import { createAttachmentReferences } from "../attachment-references.ts";import { personKey } from "../person-key.ts";+import { rowsOfConversations } from "../testing/message-rows-fixture.ts";import { TEAM_READER, VaultStore } from "../vault-store.ts";import { createUploadOwners } from "./member-uploads.ts";import { createTeamMemberLeft, type TeamMemberLeftDeps } from "./team-member-left.ts";@@ -49,8 +51,8 @@ function fixture() {deletedBots.push(botId);return true;},- threadsReferencing: (fragment) => [...messages].filter(([, list]) => JSON.stringify(list).includes(fragment)).map(([threadId]) => threadId),- deleteAttachment: (file) => deleted.push(file),+ references: createAttachmentReferences({ rows: rowsOfConversations(messages) }),+ deleteAttachments: (files) => { deleted.push(...files); },eraseBrowsers: async () => true,forgetConnections: () => {},forgetSecrets: (person) => { vault.forgetPerson(person); },diff --git a/server/host/team-member-left.ts b/server/host/team-member-left.tsindex 30fcd51ff7..3c6a98dc8f 100644--- a/server/host/team-member-left.ts+++ b/server/host/team-member-left.ts@@ -18,6 +18,7 @@ import { basename, join } from "node:path";import { defaultBotPerson, type DefaultBotFields } from "../../shared/default-bot.ts";import type { AdminActionRow } from "../admin-activity.ts";+import type { AttachmentReferences } from "../attachment-references.ts";import { memberAudience, type Audience } from "../audience.ts";import { forgetDefaultBot } from "../default-bot.ts";import { audienceHome } from "../engine-homes/layout.ts";@@ -61,9 +62,10 @@ export interface TeamMemberLeftDeps {deleteTasks(botId: string, threadIds: string[]): { deleted: string[] } | null;/** The app's own deletion of a bot (its chats, notes and folder), MausBot included; false when it could not. */deleteBot(botId: string): Promise<boolean>;- /** Conversations whose messages still name this text (message-db.ts threadsReferencing). */- threadsReferencing(fragment: string): readonly string[];- deleteAttachment(name: string): void;+ /** Which uploads no remaining message names: one pass over the transcripts for them all (attachment-references.ts). */+ references: Pick<AttachmentReferences, "removeUnreferenced">;+ /** Removes these stored uploads, by name (attachments.ts deleteAttachments). */+ deleteAttachments(names: readonly string[]): void;eraseBrowsers(audience: Audience): Promise<boolean>;/** Their own connections, keys and MCP sign-ins (team-connections.ts). */forgetConnections(person: string): void | Promise<void>;@@ -139,14 +141,19 @@ export function createTeamMemberLeft(deps: TeamMemberLeftDeps): (email: string)}// A file only their chats or private routines used, or that they never sent, goes too; one a bot's picture, another// conversation or a routine that stays uses stays.- const routineFiles = new Set(deps.routines().flatMap((routine) => routine.files));- let removed = 0;- for (const name of files) {- const url = `/api/attachments/${name}`;- if (name.includes("..") || !existsSync(join(attachments, name)) || routineFiles.has(name) || deps.threadsReferencing(name).length || deps.store.bots.some((bot) => bot.avatarUrl === url)) continue;- deps.deleteAttachment(basename(name));- removed++;- }+ // Asked again for each batch just before it goes, since the pass over the transcripts gives the event loop back.+ const removable = (names: Iterable<string>) => {+ const routineFiles = new Set(deps.routines().flatMap((routine) => routine.files));+ return [...names].filter((name) => !name.includes("..") && existsSync(join(attachments, name)) && !routineFiles.has(name) && !deps.store.bots.some((bot) => bot.avatarUrl === `/api/attachments/${name}`));+ };+ const removed = await deps.references.removeUnreferenced(removable(files), (names) => {+ const going = removable(names);+ deps.deleteAttachments(going.map((name) => basename(name)));+ return going.length;+ }).catch((error: unknown) => {+ console.warn(`[team] a leaving member's files stayed: ${error instanceof Error ? error.message : String(error)}`);+ return 0;+ });let layers = 0;let entries: string[] = [];try { entries = readdirSync(workspaces); } catch {}diff --git a/server/index.ts b/server/index.tsindex 0695438091..cfec213724 100644--- a/server/index.ts+++ b/server/index.ts@@ -65,7 +65,7 @@ import { commandReceipt } from "./commands.ts"; import { moveSavedGrants } fromimport { buildTurnDigest, coverageForDriver, digestCompletedLate, digestPromptLine, renderDigest, toolEvidence } from "./digest.ts";import { appendDecision, bindDecisionRetention, decisionRetentionDays, flushDecisionLog, pruneDecisions, withDecisionActor, type DecisionActor, type DecisionVia } from "./decision-log.ts";import { folderToFollow, inMyFolderCwd, validateBotCwd } from "./bot-cwd.ts";-import { ATTACHMENTS_DIR, attachmentExists, deleteAttachment, keptAttachmentNames, offerAttachmentClear, saveAudio, saveImage } from "./attachments.ts";+import { ATTACHMENTS_DIR, attachmentExists, deleteAttachment, deleteAttachments, keptAttachmentNames, offerAttachmentClear, saveAudio, saveImage } from "./attachments.ts"; import { attachmentReferences } from "./attachment-references.ts";import {messageAttachmentName,messageFileRoots,@@ -11945,7 +11945,7 @@ const roomReactionNotes = createRoomReactionNotes({ store }), { react } = create});const publishedPages = createPublishedPages({ dataDir: DATA_DIR, cloudHome: CLOUD_HOME, selfHosted: !CLOUD_HOME && !HOSTED_WORKSPACE && utilityParentPort === undefined, patch: (threadId, messageId, text, publishedPage) => void store.patchMessage(threadId, messageId, { text, publishedPage }), liveRoots: (botId, threadId) => liveRoots(threadId, botId), paused: () => workspaceMaintenance.active || moveFreeze.frozen(), apps: { chat: chatApps, store } }); ROUTES.push(createReactionRoutes({ react, reactorFor, cloudGuestSendRefusal }), publishedPages.routes, createBotLibraryRoutes({ bot: (id) => store.bot(id), visibleFor: (auth) => visibleTo(viewerFor(auth)), pages: () => publishedPages.store.list() }), savedSteps.routes, createPlacesElsewhereRoutes({ elsewhere: placesElsewhere, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (auth.kind === "loopback" || ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }));// `let` slots are read per request.-const engineEnvironments = () => [process.env, ...Object.values(providerConfigs()).map((instance) => instanceEnvironment(process.env, instance))].flatMap((env) => engineHomes.everyHome(env)); const folderCleanup = CLOUD_HOME && (deleteTimeCleanup(process.env, true, () => true) || orphanSweepMode() !== "off" || idleReclaimMode() !== "off") ? createConversationFolderCleanup({ dataDir: DATA_DIR, records: () => store, heldText: () => routines ? JSON.stringify([cfg, routines.listRoutines()]) : null, mentions: (words) => threadsMentioning(join(DATA_DIR, "messages.db"), words), paused: () => (moveFreeze.frozen() ? "frozen after a move" : workspaceMaintenance.active ? "a backup is being made or restored" : null), processFolders: linuxProcessPaths, processPaths: linuxProcessPaths }) : undefined; const keptAttachments = () => { const routineFiles = routines?.attachmentPaths(); return routineFiles && calendarCalls ? keptAttachmentNames([...store.bots.map((bot) => bot.avatarUrl), cfg.profile?.avatarUrl], [workspaceBannerStore.current()?.name, ...routineFiles, ...calendarCalls.list().flatMap((call) => call.attachments?.map((file) => file.path) ?? []), ...[...turnAttachmentsByTurn.values()].flat().map((file) => file.path)]) : null; }; createDeleteLeftovers({ dataDir: DATA_DIR, store, checkpointsQuiet: checkpoints.quiet, threadsReferencing, keptAttachments, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), engineFolders: () => engineSessionFolders(DATA_DIR, engineEnvironments()), layers: memoryLayerRecords, folders: deleteTimeCleanup(process.env, Boolean(folderCleanup), () => folderCleanup!) }); startEngineSessionSweep({ cloudHome: CLOUD_HOME !== null, env: process.env, dataDir: DATA_DIR, bots: () => store.bots, folders: () => engineSessionFolders(DATA_DIR, engineEnvironments()), environments: engineEnvironments, paused: () => moveFreeze.frozen() || workspaceMaintenance.active, turnsRunning: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking) || Boolean(routines?.hasActiveRuns()) });+const engineEnvironments = () => [process.env, ...Object.values(providerConfigs()).map((instance) => instanceEnvironment(process.env, instance))].flatMap((env) => engineHomes.everyHome(env)); const folderCleanup = CLOUD_HOME && (deleteTimeCleanup(process.env, true, () => true) || orphanSweepMode() !== "off" || idleReclaimMode() !== "off") ? createConversationFolderCleanup({ dataDir: DATA_DIR, records: () => store, heldText: () => routines ? JSON.stringify([cfg, routines.listRoutines()]) : null, mentions: (words) => threadsMentioning(join(DATA_DIR, "messages.db"), words), paused: () => (moveFreeze.frozen() ? "frozen after a move" : workspaceMaintenance.active ? "a backup is being made or restored" : null), processFolders: linuxProcessPaths, processPaths: linuxProcessPaths }) : undefined; const keptAttachments = () => { const routineFiles = routines?.attachmentPaths(); return routineFiles && calendarCalls ? keptAttachmentNames([...store.bots.map((bot) => bot.avatarUrl), cfg.profile?.avatarUrl], [workspaceBannerStore.current()?.name, ...routineFiles, ...calendarCalls.list().flatMap((call) => call.attachments?.map((file) => file.path) ?? []), ...[...turnAttachmentsByTurn.values()].flat().map((file) => file.path)]) : null; }; createDeleteLeftovers({ dataDir: DATA_DIR, store, checkpointsQuiet: checkpoints.quiet, references: attachmentReferences, keptAttachments, deleteAttachments: (names) => deleteAttachments(names.map((name) => join(ATTACHMENTS_DIR, name))), engineFolders: () => engineSessionFolders(DATA_DIR, engineEnvironments()), layers: memoryLayerRecords, folders: deleteTimeCleanup(process.env, Boolean(folderCleanup), () => folderCleanup!) }); startEngineSessionSweep({ cloudHome: CLOUD_HOME !== null, env: process.env, dataDir: DATA_DIR, bots: () => store.bots, folders: () => engineSessionFolders(DATA_DIR, engineEnvironments()), environments: engineEnvironments, paused: () => moveFreeze.frozen() || workspaceMaintenance.active, turnsRunning: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking) || Boolean(routines?.hasActiveRuns()) });ROUTES.push(createThreadRoutes({groupFor: personRooms.groupForAuth, ...(botOrders ? { botOrderFor: (auth: RequestAuth, bots: readonly BotRecord[]) => { const person = botOrders.personOf(auth); return person ? botOrders.ordered(person, bots) : bots; } } : {}),store, userName: userNameFor, sessions, groupUsageReader, lendingEnabled,@@ -12127,7 +12127,7 @@ const taskRoutes = createTaskRoutes({revokeInternalCapabilitiesForThread,stagedSkillCleanupsForThread,rejectDeletedThreadSkillStages,-}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, sharesLeft: conversationSharing.personLeft, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, stopBot: (botId) => memberOwnBot.stopWork(botId, "The person left the team"), deleteBot: memberOwnBot.remove, threadsReferencing, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => { connectionHealth.forgetPerson(person); personRooms.reads?.forgetPerson(person); return teamConnections.forgetPerson(person); }, forgetSecrets: (person) => { logins.forgetPerson(person); githubSignIn.forgetPerson(person); }, ...teamRoutines.leaving, forgetOnBots: (email) => forgetMember(store, email, (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access)).length, ownerOf: (botId) => { const bot = store.bot(botId); return bot ? botOwner(bot) : null; }, record: (row) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: "MausBot Cloud" } }) }) : null; const teamSlack = createTeamSlackHost({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, ...(personalSlackMessages ? { messages: personalSlackMessages } : {}), owner: (auth) => (cloudOwnerSession(auth) ? CLOUD_OWNER_KEY : null), store, visibleFor: (auth) => visibleTo(viewerFor(auth)), sender: messageSender, trigger: usageTriggerFor, actor: runActor, audienceOf: teamHost.audienceOf, starters: threadStarters, shareFromSlack: (threadId, person) => void conversationShares.share(threadId, person, "team", Date.now(), "slack"), discard: (botId, threadId) => void taskRoutes.deleteTasks(botId, [threadId]), send: (input) => acceptDirectSend(input), busy: threadBusy, handedOn: directRootPending, request: (threadId) => directRequestOwners.get(threadId), stopRefusal: (threadId, by) => runOwners.stopRefusal(threadId, by), removeRefusal: (threadId, sender, by) => runOwners.removeRefusal(threadId, sender, by), stopThread: stopThreadForPerson, language: personLanguages.forLine }); ROUTES.push(createTeamSlackRoutes({ host: teamSlack }));+}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, sharesLeft: conversationSharing.personLeft, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, stopBot: (botId) => memberOwnBot.stopWork(botId, "The person left the team"), deleteBot: memberOwnBot.remove, references: attachmentReferences, deleteAttachments: (names) => deleteAttachments(names.map((name) => join(ATTACHMENTS_DIR, name))), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => { connectionHealth.forgetPerson(person); personRooms.reads?.forgetPerson(person); return teamConnections.forgetPerson(person); }, forgetSecrets: (person) => { logins.forgetPerson(person); githubSignIn.forgetPerson(person); }, ...teamRoutines.leaving, forgetOnBots: (email) => forgetMember(store, email, (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access)).length, ownerOf: (botId) => { const bot = store.bot(botId); return bot ? botOwner(bot) : null; }, record: (row) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: "MausBot Cloud" } }) }) : null; const teamSlack = createTeamSlackHost({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, ...(personalSlackMessages ? { messages: personalSlackMessages } : {}), owner: (auth) => (cloudOwnerSession(auth) ? CLOUD_OWNER_KEY : null), store, visibleFor: (auth) => visibleTo(viewerFor(auth)), sender: messageSender, trigger: usageTriggerFor, actor: runActor, audienceOf: teamHost.audienceOf, starters: threadStarters, shareFromSlack: (threadId, person) => void conversationShares.share(threadId, person, "team", Date.now(), "slack"), discard: (botId, threadId) => void taskRoutes.deleteTasks(botId, [threadId]), send: (input) => acceptDirectSend(input), busy: threadBusy, handedOn: directRootPending, request: (threadId) => directRequestOwners.get(threadId), stopRefusal: (threadId, by) => runOwners.stopRefusal(threadId, by), removeRefusal: (threadId, sender, by) => runOwners.removeRefusal(threadId, sender, by), stopThread: stopThreadForPerson, language: personLanguages.forLine }); ROUTES.push(createTeamSlackRoutes({ host: teamSlack }));ROUTES.push(createTeamRoutes({store,authorName: (auth) => CLOUD_TEAM ? (auth.kind === "session" ? teamHost.memberProfile(auth.session).name || undefined : undefined) : cfg.profile?.name?.trim(),diff --git a/server/message-db.ts b/server/message-db.tsindex d46d8ec643..266c49e8de 100644--- a/server/message-db.ts+++ b/server/message-db.ts@@ -12,7 +12,7 @@ import { BOT_TEXT_MESSAGE_INDEXES_SQL } from "./message-db-bot-text-indexes.ts";import { ensureMemoryIndex } from "./message-db-memory-index.ts";import { cjkSearchText, cjkTokenParts, ensureSearchIndex, ftsPhrase, hasCjk, withoutSearchMarks } from "./cjk-search.ts";import { attentionSelect } from "./message-db-attention.ts";-import { MessageSearchWorker } from "./message-search-worker.ts";+import { MessageSearchWorker } from "./message-search-worker.ts"; import { messageWritten } from "./message-writes.ts";import { searchMessagesInDatabase, type SearchHit } from "./message-search-query.ts";import type { Notification, NotificationLogEntry } from "../shared/notification.ts";export type { SearchHit } from "./message-search-query.ts";@@ -437,7 +437,7 @@ function importLegacy(threadId: string, legacyFile: string): ThreadRows {}export function insertMessage(threadId: string, message: Message): void {- prepared(UPSERT_MESSAGE).run(...messageRow(threadId, message));+ const row = messageRow(threadId, message); prepared(UPSERT_MESSAGE).run(...row); messageWritten(row[6]);}/** `relinked`: adds `messages` to a conversation that has rows; each row it names changes only its parentId, and an id it already has fails the whole import. */@@ -449,11 +449,11 @@ export function importThread(threadId: string, messages: Message[], activeLeafId}const insert = relinked && database.prepare("INSERT INTO messages (thread_id, id, at, role, kind, text, json, search_text) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");for (const message of messages) {- if (insert) insert.run(...messageRow(threadId, message));+ if (insert) { const row = messageRow(threadId, message); insert.run(...row); messageWritten(row[6]); }else insertMessage(threadId, message);}const link = database.prepare("UPDATE messages SET json = json_set(json, '$.parentId', ?) WHERE thread_id = ? AND id = ?");- for (const row of relinked ?? []) link.run(row.parentId, threadId, row.id);+ for (const row of relinked ?? []) { link.run(row.parentId, threadId, row.id); messageWritten(JSON.stringify(row.parentId)); }setActiveLeaf(threadId, activeLeafId);});}@@ -466,7 +466,7 @@ export function appendMessage(threadId: string, message: Message): void {}export function updateMessage(threadId: string, message: Message): void {- prepared("UPDATE messages SET at = ?, role = ?, kind = ?, text = ?, json = ?, search_text = ? WHERE thread_id = ? AND id = ?").run(message.at, message.role, message.kind, message.text ?? null, JSON.stringify(message), cjkSearchText(message.text), threadId, message.id);+ const json = JSON.stringify(message); prepared("UPDATE messages SET at = ?, role = ?, kind = ?, text = ?, json = ?, search_text = ? WHERE thread_id = ? AND id = ?").run(message.at, message.role, message.kind, message.text ?? null, json, cjkSearchText(message.text), threadId, message.id); messageWritten(json);}export function workingGoalRunMessages(): Array<{ threadId: string; message: Message }> {diff --git a/server/message-writes.ts b/server/message-writes.tsnew file mode 100644index 0000000000..d2da32f4c5--- /dev/null+++ b/server/message-writes.ts@@ -0,0 +1,18 @@+// Each message row's JSON as message-db.ts writes it, for a reader that must not miss a row written while it reads the+// table in slices (attachment-references.ts). Listeners run inside the write and must be quick; one that throws is ignored.+type Listener = (json: string) => void;++const listeners = new Set<Listener>();++/** Calls `listener` with the JSON of every message row written from now until the returned stop is called. */+export function watchMessageWrites(listener: Listener): () => void {+ const own: Listener = (json) => listener(json);+ listeners.add(own);+ return () => { listeners.delete(own); };+}++export function messageWritten(json: string): void {+ for (const listener of listeners) {+ try { listener(json); } catch { /* a watcher's failure never fails the write */ }+ }+}diff --git a/server/testing/message-rows-fixture.ts b/server/testing/message-rows-fixture.tsnew file mode 100644index 0000000000..3c83be5a56--- /dev/null+++ b/server/testing/message-rows-fixture.ts@@ -0,0 +1,5 @@+import type { MessageRows } from "../attachment-references.ts";++/** In-memory conversations as message rows, one per message numbered in order: a reader for createAttachmentReferences. */+export const rowsOfConversations = (conversations: ReadonlyMap<string, readonly unknown[]>) => (): MessageRows => (after, limit) =>+ [...conversations.values()].flat().map((message, index) => ({ rowid: index + 1, json: JSON.stringify(message) })).filter((row) => row.rowid > after).slice(0, limit);