Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Harden the move's check after review
Milind Soni22bbfddeb75c
diff --git a/electron/cloud-send-big.node-test.mjs b/electron/cloud-send-big.node-test.mjsindex e9673832a9..eed84ac30a 100644--- a/electron/cloud-send-big.node-test.mjs+++ b/electron/cloud-send-big.node-test.mjs@@ -317,3 +317,37 @@ test("the whole move of 100 bots and 3,000 conversations, copy to switch, finishconst hours = (cloud.now() - started) / 3_600_000;assert.ok(hours < 4, `${hours.toFixed(1)} h on the slow Cloud`);});++test("a gateway error on My Cloud's own description is waited out, never read as a Cloud too old to take a move", async () => {+ const workspace = bigWorkspace();+ const cloud = slowCloud(workspace);+ const call = cloud.session.call;+ let bad = 2;+ cloud.session.call = async (method, route, body, options) => (route === "/.well-known/openmausbot/environment" && bad-- > 0 ? reply(503, {}) : call(method, route, body, options));+ assert.equal((await mover(workspace, cloud).send.check()).ok, true);+ assert.equal(bad, -1);+});++test("a conversation whose visible path changed on either side is checked again, though its rows did not", async () => {+ const leafed = (workspace, leaf) => { const copy = structuredClone(workspace); copy.manifest.conversations = copy.manifest.conversations.map((head) => ({ ...head, leaf: head.threadId === "t-b1-1" ? leaf : head.newest })); return copy; };+ const workspace = leafed(bigWorkspace(), "first");+ const store = stored();+ await mover(workspace, slowCloud(workspace), store).send.check();+ const same = slowCloud(workspace);+ await mover(workspace, same, store).send.check();+ assert.deepEqual(same.conversationsAsked, []);+ const here = leafed(workspace, "another-branch");+ const again = slowCloud(workspace);+ await mover(here, again, store).send.check();+ assert.deepEqual([...new Set(again.conversationsAsked)], ["t-b1-1"]);+});++test("the person stopping the move ends a check that waits for My Cloud at once, not when My Cloud stands still long enough", async () => {+ const workspace = bigWorkspace();+ const cloud = slowCloud(workspace, { down: () => true });+ const started = cloud.now();+ let stop = false;+ const { send } = mover(workspace, cloud);+ await assert.rejects(send.check({ stopped: () => { if (cloud.now() - started > 150_000) stop = true; return stop; } }), { message: "The move stopped." });+ assert.ok(cloud.now() - started < 5 * 60_000, `over in ${Math.round((cloud.now() - started) / 1000)} s`);+});diff --git a/electron/cloud-send-check.mjs b/electron/cloud-send-check.mjsindex 6f7564591a..237f09f1b8 100644--- a/electron/cloud-send-check.mjs+++ b/electron/cloud-send-check.mjs@@ -20,6 +20,8 @@ const THREAD = /^[\w-]{1,200}$/u;* answer: a slow Cloud that keeps answering is waited for however long its work takes. */export const PATIENCE_MS = Object.freeze([15_000, 30_000, 60_000, 120_000, 300_000]);export const STALL_MS = 10 * 60_000;+/** How often a check that waits for My Cloud looks whether the person stopped the move. */+const STOP_LOOK_MS = 5_000;/** The waits before a move's pass gives up on a request it can safely ask again: as long as a Cloud takes to start again. */export const BLIP_MS = Object.freeze([5_000, 15_000, 30_000, 60_000]);@@ -47,12 +49,13 @@ const nap = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });* request got an answer in the last STALL_MS (`moved`). Then it gives up with an error that still reads as unanswered and* says whether any of the work got done (`progressed`), which the next check does not do again; an answer that only* opens the work (`run(work, { counts: false })`) keeps it waiting without counting as work done. `onWait(until)` while it- * waits, `onWait(null)` once it asks again.+ * waits, `onWait(null)` once it asks again. `stopped()`: the person stopped the move, so it ends at the next answer or look.*/-export function createPatience({ now = Date.now, sleep = nap, onWait = () => {}, stallMs = STALL_MS, waits = PATIENCE_MS } = {}) {+export function createPatience({ now = Date.now, sleep = nap, onWait = () => {}, stallMs = STALL_MS, waits = PATIENCE_MS, stopped = () => false } = {}) {let movedAt = now(), progressed = false, tries = 0;+ const stop = () => { if (stopped()) throw Object.assign(new Error("The move stopped."), { code: "stopped" }); };const patience = {- moved({ counts = true } = {}) { movedAt = now(); tries = 0; if (counts) progressed = true; },+ moved({ counts = true } = {}) { movedAt = now(); tries = 0; if (counts) progressed = true; stop(); },get progressed() { return progressed; },/** Waits before asking again after `error`, or throws once the check has stood still too long. */async wait(error) {@@ -62,7 +65,8 @@ export function createPatience({ now = Date.now, sleep = nap, onWait = () => {},throw Object.assign(new Error(`My Cloud did not answer for ${Math.round((now() - movedAt) / 60_000)} min (${error?.message ?? "no answer"}).`), { cause: error, code: "slow", progressed });}onWait(now() + ms);- await sleep(ms);+ for (let left = ms; left > 0; left -= STOP_LOOK_MS) { stop(); await sleep(Math.min(left, STOP_LOOK_MS)); }+ stop();onWait(null);},/** `work()` until it is answered. */@@ -314,8 +318,9 @@ export async function missingAttachments(session, names, { patience = IMPATIENT,for (let i = 0; i < names.length; i += ATTACHMENT_NAMES) {const asked = names.slice(i, i + ATTACHMENT_NAMES);const answer = await patience.run(async () => answered(await session.call("POST", "/api/cloud-send/chats/attachments", { names: asked }), "My Cloud did not check the attachments."));+ if (!Array.isArray(answer.body?.missing)) throw new Error("My Cloud did not check the attachments.");const named = new Set(asked);- missing.push(...list(answer.body?.missing).filter((name) => named.has(name)));+ missing.push(...answer.body.missing.filter((name) => named.has(name)));onProgress(Math.min(names.length, i + ATTACHMENT_NAMES), names.length);}return missing;@@ -352,15 +357,15 @@ const BOT_FILE = /^(?:workspaces|task-workspaces)\/([\w-]{1,128})\//u;** Every request is a bounded piece of the work, so a Cloud with thousands of conversations answers each in time: My* Cloud's manifest without the attachments and files it never needs to list for this, its files a bot at a time, the- * chats many conversations to a request. A conversation found whole before (`kept.verified`) and unchanged on both sides- * since is not asked about again, so a check cut short goes on where it was. A slow Cloud is waited for while it keeps+ * chats many conversations to a request. A conversation found whole before (`kept.verified`), with its rows and the path+ * it shows unchanged on both sides since, is not asked about again, so a check cut short goes on where it was. A slow Cloud is waited for while it keeps* answering (createPatience). `onStep({ step, done, total, bots, until? })`: which step it is at, how far, and until when* it waits for My Cloud. `refuse(answer, message)`: the error a refusal of My Cloud's is.*/-export async function moveCheck({ session, kept, persist, localJson, handoff, scoped = (route) => route, now = Date.now, sleep, patience: pace = {}, takesMove, refuse = null, onStep = () => {} }) {+export async function moveCheck({ session, kept, persist, localJson, handoff, scoped = (route) => route, now = Date.now, sleep, patience: pace = {}, stopped, takesMove, refuse = null, onStep = () => {} }) {let bots = 0, at = null;const step = (name, done = 0, total = 0) => { at = { step: name, done, total, bots }; onStep(at); };- const patience = createPatience({ now, ...(sleep ? { sleep } : {}), ...(pace.stallMs !== undefined ? { stallMs: pace.stallMs } : {}), ...(pace.waits ? { waits: pace.waits } : {}), onWait: (until) => {+ const patience = createPatience({ now, ...(sleep ? { sleep } : {}), ...(pace.stallMs !== undefined ? { stallMs: pace.stallMs } : {}), ...(pace.waits ? { waits: pace.waits } : {}), ...(stopped ? { stopped } : {}), onWait: (until) => {if (!at) return;const { until: _, ...rest } = at;at = until ? { ...rest, until } : rest;@@ -372,7 +377,7 @@ export async function moveCheck({ session, kept, persist, localJson, handoff, scawait patience.run(takesMove, { counts: false });const here = await localJson(scoped("/api/cloud-send/manifest"), { timeoutMs: LOCAL_LISTING_MS });const heads = new Map(list(here?.conversations).filter(record).map((head) => [head.threadId, head]));- const there = (await ask("GET", scoped("/api/cloud-send/manifest?attachments=0&files=0"), listingMs(heads.size * 20), undefined, false)).body;+ const there = (await ask("GET", scoped("/api/cloud-send/manifest?attachments=0&files=0"), listingMs(heads.size * 20 + list(here?.items).length * 300), undefined, false)).body;if (!record(here) || !record(there)) throw new Error("My Cloud did not say what it has. Try again.");const removed = new Set([...Object.entries(kept.off).filter(([, why]) => why === "removed").map(([key]) => key),...Object.entries(kept.chats).filter(([, cursor]) => cursor === "removed").map(([threadId]) => threadId),@@ -385,16 +390,19 @@ export async function moveCheck({ session, kept, persist, localJson, handoff, scconst rooms = roomsThatGo(here, going);const threads = list(here.conversations).filter((head) => !removed.has(head.threadId)&& (head.room ? rooms.has(head.room) && !removed.has(`room:${head.room}`) : going.has(head.bot))).map((head) => head.threadId);- const theirRows = new Map(list(there.conversations).filter(record).map((head) => [head.threadId, Number.isSafeInteger(head.rows) ? head.rows : 0]));+ const theirs = new Map(list(there.conversations).filter(record).map((head) => [head.threadId, head]));+ const theirRows = (threadId) => (Number.isSafeInteger(theirs.get(threadId)?.rows) ? theirs.get(threadId).rows : 0);const whole = (threadId) => {const seen = kept.verified?.[threadId], head = heads.get(threadId);- return Boolean(seen && head && seen.newest === head.newest && seen.rows === head.rows && (theirRows.get(threadId) ?? -1) >= seen.there);+ return Boolean(seen && head && seen.newest === head.newest && seen.rows === head.rows && seen.leaf === head.leaf && theirs.has(threadId) && theirRows(threadId) >= seen.there && seen.theirLeaf === theirs.get(threadId).leaf);};step("chats", 0, threads.length);const chats = await checkChats({ localJson, session, threads, patience, timeoutMs: LISTING_MS, skip: whole,checked: (threadId) => {const head = heads.get(threadId);- if (kept.verified && head && typeof head.newest === "string" && Number.isSafeInteger(head.rows)) kept.verified[threadId] = { newest: head.newest, rows: head.rows, there: theirRows.get(threadId) ?? 0 };+ if (kept.verified && head && typeof head.newest === "string" && Number.isSafeInteger(head.rows)) {+ kept.verified[threadId] = { newest: head.newest, rows: head.rows, there: theirRows(threadId), ...(head.leaf ? { leaf: head.leaf } : {}), ...(theirs.get(threadId)?.leaf ? { theirLeaf: theirs.get(threadId).leaf } : {}) };+ }},onProgress: (done, total) => { if (done % 50 === 0) persist(); step("chats", done, total); } });for (const entry of chats) if (entry.unstamped && kept.stamped) delete kept.stamped[entry.threadId];diff --git a/electron/cloud-send-check.node-test.mjs b/electron/cloud-send-check.node-test.mjsindex b1339c500a..3fdbbbaee7 100644--- a/electron/cloud-send-check.node-test.mjs+++ b/electron/cloud-send-check.node-test.mjs@@ -197,3 +197,8 @@ test("a move's check finds what only a move carries: memory pieces, journal rowsconst full = { bot: "ember", ids: Array.from({ length: 500 }, (_, i) => `mine-${i}`) };assert.deepEqual(manifestGaps(here, { ...there, journal: [full] }, { removed }).journal, [], "a journal showing its latest 500 rows of My Cloud's own may no longer show older ones");});++test("an answer about the attachments that names no list is never read as nothing missing", async () => {+ const session = { call: async () => ({ ok: true, status: 200, body: {} }) };+ await assert.rejects(missingAttachments(session, ["00000001.png"]), /did not check the attachments/u);+});diff --git a/electron/cloud-send-main.d.mts b/electron/cloud-send-main.d.mtsindex 29e8a9469a..85cfb85b95 100644--- a/electron/cloud-send-main.d.mts+++ b/electron/cloud-send-main.d.mts@@ -29,7 +29,7 @@ export function installCloudSend(deps: {/** This computer's server's private port, asked as a send asks it: another move's sends share it. */handoff(what: { kind: string; [key: string]: unknown }): Promise<any>;move(options?: { final?: boolean }): Promise<CloudSendOutcome>;- check(): Promise<CloudMoveCheck>;+ check(options?: { stopped?(): boolean }): Promise<CloudMoveCheck>;switches(): Record<string, boolean>;snapshot(): CloudSendSnapshot;publish(): void;diff --git a/electron/cloud-send-main.mjs b/electron/cloud-send-main.mjsindex c681ffdf80..ee2d792a83 100644--- a/electron/cloud-send-main.mjs+++ b/electron/cloud-send-main.mjs@@ -158,7 +158,7 @@ export function installCloudSend({ ipcMain, cloudPage, server, local, home, cook/** The one-time move to My Cloud (cloud-send.mjs): a pass that carries everything, `final` the one after this computer* stops, and the check of what arrived. */move: (options) => send.send({ reason: "move", final: options?.final === true }),- check: () => send.check(),+ check: (options) => send.check(options),/** Each automation the move carried, and whether it was on here when it went. */switches: () => send.switches(),snapshot: () => send.snapshot(),diff --git a/electron/cloud-send.d.mts b/electron/cloud-send.d.mtsindex c10671cfb8..9ccc31fbbb 100644--- a/electron/cloud-send.d.mts+++ b/electron/cloud-send.d.mts@@ -212,7 +212,8 @@ export function createCloudSend(deps: {/** `reason: "move"`: everything this computer has, apps and keys first; `final`: the pass after this computer stopped,* which carries the sign-ins that refresh themselves and lets go of this computer's copies. */send(options?: { keys?: string[] | null; force?: string[]; reason?: string; final?: boolean }): Promise<CloudSendOutcome>;- check(): Promise<CloudMoveCheck>;+ /** `stopped`: the person stopped the move, so a check waiting for My Cloud ends now. */+ check(options?: { stopped?(): boolean }): Promise<CloudMoveCheck>;/** Each automation a move carried ("routine:<id>", "call:<id>", "webhook:<id>", "app-event:<id>") and whether it was* on here when it went. */switches(): Record<string, boolean>;diff --git a/electron/cloud-send.mjs b/electron/cloud-send.mjsindex b34a53ca88..afc106a338 100644--- a/electron/cloud-send.mjs+++ b/electron/cloud-send.mjs@@ -374,6 +374,7 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>/** A move goes only to a Cloud that says it takes one: an older one would lose the owner's lines and the checks. */async function assertTakesMove(session) {const described = await session.call("GET", "/.well-known/openmausbot/environment");+ if (described.status >= 500) throw Object.assign(new CloudSendError("unreachable", "My Cloud did not answer. Try again."), { status: described.status });if (!(Number(described.body?.capabilities?.move) >= 1)) throw new CloudSendError("outdated", OUTDATED_FOR_MOVE);}@@ -893,12 +894,12 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>/** What did not arrive of what a move carried (cloud-send-check.mjs `moveCheck`), over one owner session that counts* as someone using My Cloud; `snapshot().checking` says how far it is. A check that stood still too long fails as* unanswered, saying whether it got anywhere (`progressed`). */- async function check() {+ async function check({ stopped } = {}) {const origin = cloud.origin();if (!origin) throw new CloudSendError("no_cloud", "This computer has no My Cloud yet.");const session = await cloud.open({ move: true }).catch((error) => { throw new CloudSendError("session", sentence(error?.message) ?? "This app could not sign in to My Cloud. Try again.", { cause: error }); });try {- return await moveCheck({ session, kept: entry(origin), persist, localJson, handoff: team ? null : handoff, scoped, now, sleep, patience, takesMove: () => assertTakesMove(session),+ return await moveCheck({ session, kept: entry(origin), persist, localJson, handoff: team ? null : handoff, scoped, now, sleep, patience, stopped, takesMove: () => assertTakesMove(session),refuse: (answer, message) => refusedError("unreachable", answer, message), onStep: (value) => { checking = value; publish(); } });} catch (error) {if (error?.code === "slow") throw Object.assign(new CloudSendError("unreachable", sentence(error.message) ?? "My Cloud did not answer.", { cause: error.cause }), { progressed: error.progressed === true });diff --git a/electron/move-lease.mjs b/electron/move-lease.mjsindex 2e247f4df1..4b49c24089 100644--- a/electron/move-lease.mjs+++ b/electron/move-lease.mjs@@ -18,7 +18,7 @@ const sentence = (value) => (typeof value === "string" && value.trim() ? value.t* known, and then nothing waits. `label`: its name, which the other computer's line says while it waits.*/export function createMoveLease({ session, holder, label, timers = { set: (work, ms) => { const timer = setInterval(work, ms); timer.unref?.(); return timer; }, clear: (timer) => clearInterval(timer) }, log = () => {} }) {- let held = null, name = "", timer = null;+ let held = null, name = "", timer = null, renewing = null;const ask = async (body) => (await session()).call("POST", "/api/cloud-send/lease", { v: 1, ...body });const stop = () => { if (timer) timers.clear(timer); timer = null; };@@ -36,7 +36,7 @@ export function createMoveLease({ session, holder, label, timers = { set: (work,if (!timer) {timer = timers.set(() => {if (!held) return;- ask({ holder: held, label: name }).then((again) => { if (again.status === 409) log("one home: another computer took My Cloud's move lease"); }, () => {});+ renewing = ask({ holder: held, label: name }).then((again) => { if (again.status === 409) log("one home: another computer took My Cloud's move lease"); }, () => {});}, LEASE_RENEW_MS);}return null;@@ -46,6 +46,8 @@ export function createMoveLease({ session, holder, label, timers = { set: (work,stop();const id = held;held = null;+ // Letting go after any renewal still on its way, or that renewal would take the lease back.+ await renewing;if (id) await ask({ holder: id, release: true }).catch(() => {});},held: () => held !== null,diff --git a/electron/one-home-check.node-test.mjs b/electron/one-home-check.node-test.mjsindex 799c7c04ee..bcd9dd211c 100644--- a/electron/one-home-check.node-test.mjs+++ b/electron/one-home-check.node-test.mjs@@ -56,7 +56,8 @@ function computer({ clock, checks = [], lease = null, name = "Mac", id = "computcloud: () => ({ origin: CLOUD, account: "acct-1", machine: CLOUD, ready: true, moves: true, ended: false, paid: false }),send: {async move(options) { c.passes.push(options?.final ? "final" : "copy"); if (!options?.final && copy) await copy(); },- async check() {+ async check(options) {+ c.checkOptions = options;const next = checks.shift();const answer = typeof next === "function" ? await next(c) : next;if (answer instanceof Error) throw answer;@@ -175,3 +176,16 @@ test("a move that waits for another computer after an earlier failure asks againassert.deepEqual(nuc.passes, []);assert.deepEqual(nuc.timers.map((timer) => timer.ms), [QUEUE_POLL_MS]);});++test("a check is told when the person stops the move, and a failed one lifts the freeze before it lets go of My Cloud", async () => {+ const clock = newClock();+ const order = [];+ const lease = cloudLease(() => clock.now);+ const answer = lease.answer;+ lease.answer = (body) => { if (body.release) order.push(c.server.frozen ? "released frozen" : "released thawed"); return answer(body); };+ const c = computer({ clock, lease, checks: [Object.assign(new Error("My Cloud did not answer."), { cause: timeout() })] });+ await c.home.kick();+ assert.equal(typeof c.checkOptions.stopped, "function");+ assert.equal(c.checkOptions.stopped(), false);+ assert.ok(order.includes("released thawed") && !order.includes("released frozen"), order.join());+});diff --git a/electron/one-home.d.mts b/electron/one-home.d.mtsindex 217b99ecf3..c787aeb571 100644--- a/electron/one-home.d.mts+++ b/electron/one-home.d.mts@@ -80,7 +80,7 @@ export function missingOf(report: unknown): string;export function createOneHome(deps: {journal: { read(): unknown; write(value: unknown): void };cloud(): OneHomeCloud | null;- send: { move(options?: { final?: boolean }): Promise<unknown>; check(): Promise<{ ok: boolean }>; switches(): Record<string, boolean>; snapshot(): any };+ send: { move(options?: { final?: boolean }): Promise<unknown>; check(options?: { stopped?(): boolean }): Promise<{ ok: boolean }>; switches(): Record<string, boolean>; snapshot(): any };local: {freeze(origin: string): Promise<{ frozen: true } | { busy: string; what?: string }>;unfreeze(options?: { automations?: "off" }): Promise<void>;diff --git a/electron/one-home.mjs b/electron/one-home.mjsindex 4f002e3cf8..c374d27bb2 100644--- a/electron/one-home.mjs+++ b/electron/one-home.mjs@@ -309,7 +309,6 @@ export function createOneHome(deps) {async function failed(journal, error, frozen) {const said = sentence(error?.message) ?? "My Cloud did not answer.";log(`one home: ${journal.phase} failed (${said})`);- await letGo();const tries = (journal.tries ?? 0) + 1;// A check that got somewhere before My Cloud stopped answering goes on from there soon, as a pass that carried things does.const resumes = frozen && error?.progressed === true;@@ -321,6 +320,7 @@ export function createOneHome(deps) {gapKey: typeof error?.gapKey === "string" ? error.gapKey : undefined, gaps: typeof error?.gaps === "string" ? error.gaps : undefined,retryAt: now() + wait, hourly: hourly || undefined, ...(frozen ? { thaw: true } : {}) });if (frozen) await thaw(next);+ await letGo();return null;}@@ -383,7 +383,8 @@ export function createOneHome(deps) {async function check(journal) {let passes = journal.passes ?? 1, first = null, stuck = null;try {- for (let report = await deps.send.check(); report?.ok !== true; report = await deps.send.check()) {+ const stopped = () => closed || kept();+ for (let report = await deps.send.check({ stopped }); report?.ok !== true; report = await deps.send.check({ stopped })) {log(`one home: the check found ${missingOf(report)} missing`);const key = gapKey(report);first ??= key;diff --git a/electron/team-move-main.mjs b/electron/team-move-main.mjsindex 33aa317658..0f15792e73 100644--- a/electron/team-move-main.mjs+++ b/electron/team-move-main.mjs@@ -81,13 +81,13 @@ function lazy(open) {/** The move-in sign-in the team handed out, as a session the send uses. */function bearerSession(origin, token, fetchImpl) {- const request = (method, route, init) => fetchImpl(`${origin}${route}`, {- method, redirect: "error", credentials: "omit", cache: "no-store", signal: AbortSignal.timeout(120_000), ...init,+ const request = (method, route, { timeoutMs = 120_000, ...init }) => fetchImpl(`${origin}${route}`, {+ method, redirect: "error", credentials: "omit", cache: "no-store", signal: AbortSignal.timeout(timeoutMs), ...init,headers: { accept: "application/json", authorization: `Bearer ${token}`, ...init.headers },});return {- call: async (method, route, body) => answer(await request(method, route, body === undefined ? { headers: {} }- : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) })),+ call: async (method, route, body, options) => answer(await request(method, route, { ...(options?.timeoutMs ? { timeoutMs: options.timeoutMs } : {}), ...(body === undefined ? { headers: {} }+ : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }) })),upload: async (route, bytes, type) => answer(await request("POST", route, { headers: { "content-type": type }, body: bytes })),close: async () => { await request("POST", "/api/auth/logout", { headers: { "content-type": "application/json" }, body: "{}" }).then((response) => response.body?.cancel()); },};diff --git a/server/cloud-send-big.test.ts b/server/cloud-send-big.test.tsindex 6da1adad69..95055c938e 100644--- a/server/cloud-send-big.test.ts+++ b/server/cloud-send-big.test.ts@@ -77,6 +77,7 @@ describe("a move's check of a big workspace", () => {expect(manifest.conversations).toHaveLength(BOTS * TASKS);expect(manifest.attachments).toBeUndefined();expect(manifest.files).toBeUndefined();+ expect(manifest.conversations[0]!.leaf, "where the conversation stands, read without its rows").toBe(base.activeLeaf(manifest.conversations[0]!.threadId));const whole = await cloudSendManifest({ summary: () => ({ v: 1, appVersion: "0", items: [] }), store, dataDir: DATA_DIR, connections: async () => [], heads: threadHeads });expect(whole.attachments).toHaveLength(BOTS * TASKS * (ROWS / 4));expect(reads.messagesFor, "not one conversation parsed and kept by the store").toBe(0);diff --git a/server/cloud-send-manifest.ts b/server/cloud-send-manifest.tsindex adc98f8943..b861a9be0e 100644--- a/server/cloud-send-manifest.ts+++ b/server/cloud-send-manifest.ts@@ -4,7 +4,7 @@import type { ChatStore } from "./cloud-chat-merge.ts";import { listBotFiles, type BotFile } from "./cloud-send-files.ts";import { chatHeads, conversationSettings } from "./cloud-send-chats.ts";-import { attachmentNamesOf } from "./cloud-send-rows.ts";+import { activeLeaves, attachmentNamesOf } from "./cloud-send-rows.ts";import { automationSwitches, routineRunIds, type MoveKindsDeps } from "./cloud-send-kinds.ts";import { journalIds, memoryFiles, memoryLines, teamsHere } from "./cloud-send-memory.ts";import type { CloudSendSummary } from "./cloud-send.ts";@@ -14,7 +14,7 @@ import { learnedState } from "./profile-learned.ts";import type { BotRecord } from "./store.ts";import type { TeamMemory } from "./team-memory.ts";-export interface ManifestConversation { threadId: string; bot?: string; room?: string; rows: number; newest: string; settings: Record<string, unknown> }+export interface ManifestConversation { threadId: string; bot?: string; room?: string; rows: number; newest: string; leaf: string; settings: Record<string, unknown> }export interface CloudSendManifest {v: 1;@@ -70,8 +70,9 @@ export async function cloudSendManifest(sources: ManifestSources): Promise<Cloudconst only = sources.bot;const rooms = only === undefined ? store.groups.filter((room) => !room.dm) : [];const counts = sources.heads();+ const leaves = activeLeaves();const conversations: ManifestConversation[] = chatHeads(only === undefined ? store.bots : store.bots.filter((bot) => bot.id === only), rooms).map((head) => ({- threadId: head.threadId, ...(head.bot ? { bot: head.bot } : { room: head.room }), rows: counts.get(head.threadId)?.rows ?? 0, newest: head.lastId,+ threadId: head.threadId, ...(head.bot ? { bot: head.bot } : { room: head.room }), rows: counts.get(head.threadId)?.rows ?? 0, newest: head.lastId, leaf: leaves.get(head.threadId) ?? head.lastId,settings: conversationSettings(store, head),}));const attachments = sources.attachments === false ? {} : { attachments: [...attachmentNamesOf(new Set(conversations.map((head) => head.threadId)), sources.dataDir)].sort() };diff --git a/server/cloud-send-rows.ts b/server/cloud-send-rows.tsindex e02ff27521..07c7ce1bfc 100644--- a/server/cloud-send-rows.ts+++ b/server/cloud-send-rows.ts@@ -27,6 +27,12 @@ export function threadLinks(threadId: string): ThreadLinks | null {return { ids, parent, leaf: state?.active_leaf_id || ids.at(-1) || null };}+/** Each conversation's kept active leaf, without reading any of its rows. */+export function activeLeaves(): Map<string, string> {+ const rows = prepared("SELECT thread_id AS threadId, active_leaf_id AS leaf FROM thread_state WHERE active_leaf_id IS NOT NULL").all() as Array<{ threadId: string; leaf: string }>;+ return new Map(rows.map((row) => [row.threadId, row.leaf]));+}+/** The links of rows the store already holds parsed. */export function linksOf(rows: readonly Message[], leaf: string | null): ThreadLinks {return { ids: rows.map((row) => row.id), parent: new Map(rows.map((row) => [row.id, row.parentId ?? null])), leaf };