Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Finish the move to My Cloud on big workspaces and slow Clouds
Milind Soni687ecb548a6c
diff --git a/docs/verification/cloud-send.md b/docs/verification/cloud-send.mdindex 2c3620d1b7..b71c2c246d 100644--- a/docs/verification/cloud-send.md+++ b/docs/verification/cloud-send.md@@ -98,6 +98,32 @@ the reason in its tooltip. Both run the one retry, and both wait with a spinnerwhile it runs. On My Cloud's page the menu says once what arrived, with the phoneto pair and Got it.+## A big workspace on a slow Cloud++```sh+node --test electron/cloud-send-big.node-test.mjs electron/one-home-check.node-test.mjs+pnpm exec vitest run server/cloud-send-big.test.ts server/cloud-send-lease.test.ts+```++`electron/cloud-send-big.node-test.mjs` runs the real check (`createCloudSend`'s+`check`) against a fake Cloud that takes, on a clock, the time a Fly Starter+machine takes for each request's work, and cuts off a request that takes longer+than its caller waits, as fetch does: 100 bots, 3,000 conversations (five of+12,000 rows), 6,000 attachments and 2,000 bot files. The whole manifest in one+answer, as the check asked for it before, takes about 19 minutes there; the+check asks My Cloud's manifest without attachments and files, its files a bot at+a time, and the chats 200 conversations to a request, and finishes with no+request cut off. A Cloud that stops answering for minutes is waited for; one+that stops for longer fails the check as unanswered with what it got done kept,+and the next check asks only about the conversations not found whole yet.+`electron/one-home-check.node-test.mjs` covers the move around it: such a check+goes on in five minutes, not an hour, the line says how far the check is or that+My Cloud is slow until when, and two computers moving into one Cloud take turns+at the heavy part, the second saying which computer it waits for.+`server/cloud-send-big.test.ts` builds 100 bots with 2,000 conversations in a+real store and shows the server's answers read messages.db directly and never+parse a conversation through the store.+## The real utility port```shdiff --git a/electron/cloud-send-big.node-test.mjs b/electron/cloud-send-big.node-test.mjsnew file mode 100644index 0000000000..ec8579f420--- /dev/null+++ b/electron/cloud-send-big.node-test.mjs@@ -0,0 +1,191 @@+import assert from "node:assert/strict";+import test from "node:test";++import { createCloudSend } from "./cloud-send.mjs";+import { STALL_MS } from "./cloud-send-check.mjs";++const CLOUD = "https://omb-u-1.fly.dev";+const BOTS = 100, CHATS_PER_BOT = 30, ROWS = 40, LONG = 12_000, ATTACHMENTS = 6_000, FILES_PER_BOT = 20, FILE_BYTES = 5 * 1024 ** 2;+const json = (value, status = 200) => new Response(JSON.stringify(value), { status });+const reply = (status, body) => ({ status, ok: status < 400, body });+const stored = (value = null) => ({ read: () => value, write(next) { value = structuredClone(next); }, get value() { return value; } });+const timeout = () => new DOMException("The operation was aborted due to timeout", "TimeoutError");++/**+ * A big workspace: 100 bots with 30 conversations each, 40 rows to a conversation and five of 12,000, 6,000 stored+ * attachments and 20 files of 5 MB to a bot. Both computers that move into My Cloud are this size, so My Cloud holds+ * twice its rows.+ */+function bigWorkspace() {+ const bots = Array.from({ length: BOTS }, (_, i) => `b${i}`);+ const conversations = bots.flatMap((bot, b) => Array.from({ length: CHATS_PER_BOT }, (_, c) => {+ const rows = b < 5 && c === 0 ? LONG : ROWS;+ return { threadId: `t-${bot}-${c}`, bot, rows, newest: `t-${bot}-${c}-${rows - 1}`, settings: {} };+ }));+ const manifest = {+ v: 1, appVersion: "0.1.151", memory: [], journal: [], learned: [], forgotten: [], teams: [], rooms: [], connections: [], automations: [], runs: [],+ items: bots.map((id) => ({ key: `bot:${id}`, kind: "bot", label: `Bot ${id}`, id, parts: { soul: "s" } })),+ conversations,+ attachments: Array.from({ length: ATTACHMENTS }, (_, i) => `${String(i).padStart(8, "0")}-a.png`),+ files: bots.flatMap((bot) => Array.from({ length: FILES_PER_BOT }, (_, f) => ({ path: `workspaces/${bot}/data-${f}.bin`, size: FILE_BYTES, sha256: "a".repeat(64) }))),+ };+ return { bots, conversations, manifest };+}++/**+ * My Cloud on a Fly Starter machine (2 shared CPUs, throttled) as the clock sees it: each request takes the time its work+ * takes there, and one that takes longer than its caller waits is cut off as fetch cuts it off. A stored row parsed costs+ * 0.25 ms, a byte hashed 1/20,000 ms (20 MB/s, the hash cache cold after a restart), and any request 400 ms. `down`: when+ * nothing answers at all.+ */+function slowCloud({ manifest }, { down = () => false } = {}) {+ let clock = 0;+ const asked = [], conversationsAsked = [];+ const rowsThere = manifest.conversations.reduce((sum, head) => sum + head.rows, 0) * 2;+ const rowsOf = new Map(manifest.conversations.map((head) => [head.threadId, head.rows]));+ const filesOf = (bot) => manifest.files.filter((file) => file.path.startsWith(`workspaces/${bot}/`));+ const cost = (method, route, body) => {+ if (route.startsWith("/api/cloud-send/manifest")) {+ const query = new URLSearchParams(route.split("?")[1] ?? "");+ const listsAll = query.get("attachments") !== "0", hashesAll = query.get("files") !== "0";+ return 30 * BOTS + 0.05 * manifest.conversations.length + (listsAll ? 0.25 * rowsThere : 0) + (hashesAll ? (2 * manifest.files.length * FILE_BYTES) / 20_000 : 0);+ }+ const files = /^\/api\/cloud-send\/files\?bot=([\w-]+)$/u.exec(route);+ if (files) return filesOf(files[1]).reduce((sum, file) => sum + file.size, 0) / 20_000;+ if (route === "/api/cloud-send/chats/verify") return body.conversations.reduce((sum, entry) => sum + 1 + 0.25 * (rowsOf.get(entry.threadId) ?? 0), 0);+ if (route === "/api/cloud-send/chats/attachments") return 0.05 * body.names.length;+ return 0;+ };+ const answer = (method, route, body) => {+ if (route === "/.well-known/openmausbot/environment") return reply(200, { capabilities: { cloudHome: true, move: 1 } });+ if (route.startsWith("/api/cloud-send/manifest")) {+ const query = new URLSearchParams(route.split("?")[1] ?? "");+ const { attachments: _a, files: _f, ...rest } = manifest;+ return reply(200, { ...rest, ...(query.get("attachments") === "0" ? {} : { attachments: [] }), ...(query.get("files") === "0" ? {} : { files: manifest.files }) });+ }+ const files = /^\/api\/cloud-send\/files\?bot=([\w-]+)$/u.exec(route);+ if (files) return reply(200, { v: 1, files: filesOf(files[1]), space: { freeBytes: 1e12, volumeBytes: 1e12 } });+ if (route === "/api/cloud-send/chats/verify") {+ conversationsAsked.push(...body.conversations.map((entry) => entry.threadId));+ return reply(200, { v: 1, conversations: body.conversations.map(({ threadId, path }) => ({ threadId, missing: [], unstamped: 0,+ ...(path ? { path: { holds: true, at: path.ids.at(-1) ?? path.after, ...(path.last ? { leaf: `${threadId}-${rowsOf.get(threadId) - 1}`, length: rowsOf.get(threadId) } : {}) } } : {}) })) });+ }+ if (route === "/api/cloud-send/chats/attachments") return reply(200, { missing: [] });+ if (route === "/api/cloud-send/verify-secrets") return reply(200, { v: 1, secrets: {} });+ return reply(200, {});+ };+ const session = {+ async call(method, route, body, options) {+ const limit = options?.timeoutMs ?? 120_000;+ const takes = 400 + cost(method, route, body);+ asked.push({ route, takes, limit });+ if (down(clock) || takes > limit) { clock += limit; throw timeout(); }+ clock += takes;+ return answer(method, route, body);+ },+ upload: async () => reply(201, {}),+ close: async () => {},+ };+ return { session, asked, conversationsAsked, now: () => clock, sleep: async (ms) => { clock += ms; }, advance: (ms) => { clock += ms; } };+}++/** This computer's own server: its manifest, and each conversation's row ids, 5,000 at a time. */+function thisComputer({ manifest }) {+ const rowsOf = new Map(manifest.conversations.map((head) => [head.threadId, head.rows]));+ return async (route) => {+ if (route === "/api/cloud-send/manifest") return json(manifest);+ const listed = /^\/api\/cloud-send\/chats\/ids\?thread=([\w-]+)&from=(\d+)$/u.exec(route);+ if (listed) {+ const count = rowsOf.get(listed[1]) ?? 0, from = Number(listed[2]);+ const ids = Array.from({ length: Math.max(0, Math.min(5_000, count - from)) }, (_, i) => `${listed[1]}-${from + i}`);+ return json({ v: 1, ids, path: ids, leaf: `${listed[1]}-${count - 1}`, more: from + 5_000 < count });+ }+ return json({}, 404);+ };+}++function mover(workspace, cloud, store = stored()) {+ const seen = [];+ const send = createCloudSend({+ local: thisComputer(workspace),+ cloud: { origin: () => CLOUD, asleep: () => false, read: async () => json({}), open: async () => cloud.session },+ handoff: async (what) => (what.kind === "verify-secrets" ? { secrets: {} } : {}),+ store,+ now: cloud.now,+ sleep: cloud.sleep,+ onChange: (snapshot) => { if (snapshot.checking) seen.push(snapshot.checking); },+ });+ return { send, seen, store };+}++test("on a slow Cloud, the whole manifest the check asked for in one request takes longer than any request may; the check of a big workspace now finishes", async () => {+ const workspace = bigWorkspace();+ const cloud = slowCloud(workspace);+ // What the check asked My Cloud for first: every attachment its rows name and every bot file's hash, in one answer.+ await assert.rejects(cloud.session.call("GET", "/api/cloud-send/manifest"), { name: "TimeoutError", message: "The operation was aborted due to timeout" });+ assert.ok(cloud.asked[0].takes > 5 * cloud.asked[0].limit, `the whole manifest takes ${Math.round(cloud.asked[0].takes / 60_000)} min there`);+ cloud.asked.length = 0;++ const { send, seen } = mover(workspace, cloud);+ const started = cloud.now();+ const report = await send.check();+ assert.equal(report.ok, true);+ assert.deepEqual(cloud.asked.filter((entry) => entry.takes > entry.limit), [], "no request takes longer than it may");+ const verifies = cloud.asked.filter((entry) => entry.route === "/api/cloud-send/chats/verify").length;+ assert.ok(verifies < 50, `3,000 conversations in ${verifies} requests, not one each`);+ assert.equal(cloud.asked.filter((entry) => entry.route.startsWith("/api/cloud-send/files?bot=")).length, BOTS, "My Cloud's files, a bot at a time");+ assert.ok(cloud.now() - started < 30 * 60_000, `done in ${Math.round((cloud.now() - started) / 60_000)} min`);+ const chats = seen.filter((step) => step.step === "chats");+ assert.equal(chats.at(-1).done, BOTS * CHATS_PER_BOT, "the line counts every conversation checked");+ assert.equal(chats.at(-1).bots, BOTS);+ assert.ok(chats.some((step) => step.done > 0 && step.done < step.total), "and how far it is on the way");+ assert.deepEqual([...new Set(seen.map((step) => step.step))], ["manifest", "files", "chats", "attachments", "credentials"]);+ assert.equal(send.snapshot().checking, null, "nothing is said of a check once it is over");+});++test("a Cloud that stops answering for minutes mid-check is waited for, and the line says until when", async () => {+ const workspace = bigWorkspace();+ let stalledAt = null;+ const cloud = slowCloud(workspace, { down: (clock) => stalledAt !== null && clock < stalledAt + 6 * 60_000 });+ const { send, seen } = mover(workspace, cloud);+ const call = cloud.session.call;+ let verifies = 0;+ cloud.session.call = async (method, route, body, options) => {+ if (route === "/api/cloud-send/chats/verify" && ++verifies === 5) stalledAt ??= cloud.now();+ return call(method, route, body, options);+ };+ const report = await send.check();+ assert.equal(report.ok, true);+ assert.ok(seen.some((step) => step.step === "chats" && step.until > cloud.now() - 60 * 60_000), "while it waits, the line says until when");+});++test("a check My Cloud stops answering for longer fails as unanswered, says it got somewhere, and the next check goes on from there", async () => {+ const workspace = bigWorkspace();+ let verifies = 0, stalledAt = null;+ const cloud = slowCloud(workspace, { down: (clock) => stalledAt !== null && clock < stalledAt + 2 * STALL_MS });+ const store = stored();+ const first = mover(workspace, cloud, store);+ const call = cloud.session.call;+ cloud.session.call = async (method, route, body, options) => {+ if (route === "/api/cloud-send/chats/verify" && ++verifies === 8) stalledAt ??= cloud.now();+ return call(method, route, body, options);+ };+ await assert.rejects(first.send.check(), (error) => error.progressed === true && /did not answer/u.test(error.message) && error.cause?.name === "TimeoutError");+ const checkedBefore = new Set(cloud.conversationsAsked).size;+ assert.ok(checkedBefore > 0 && checkedBefore < BOTS * CHATS_PER_BOT);++ cloud.advance(2 * STALL_MS);+ cloud.conversationsAsked.length = 0;+ const again = mover(workspace, cloud, store);+ const report = await again.send.check();+ assert.equal(report.ok, true);+ assert.ok(cloud.conversationsAsked.length <= BOTS * CHATS_PER_BOT - checkedBefore + 400,+ `the second check asked about ${cloud.conversationsAsked.length} conversations, not all ${BOTS * CHATS_PER_BOT} again`);++ // A conversation that changed here since is checked again, and only it.+ const changed = structuredClone(workspace);+ changed.manifest.conversations[0] = { ...changed.manifest.conversations[0], rows: LONG + 1, newest: `t-b0-0-${LONG}` };+ const later = slowCloud(changed);+ await mover(changed, later, store).send.check();+ assert.deepEqual([...new Set(later.conversationsAsked)], ["t-b0-0"]);+});diff --git a/electron/cloud-send-check.mjs b/electron/cloud-send-check.mjsindex 19de2e603a..999f76cd7e 100644--- a/electron/cloud-send-check.mjs+++ b/electron/cloud-send-check.mjs@@ -10,9 +10,70 @@ const record = (value) => value !== null && typeof value === "object" && !Array.const list = (value) => (Array.isArray(value) ? value : []);/** As many of a conversation's row ids, and of its path, as My Cloud checks at once. */const IDS = 5_000;+/** My Cloud checks at most this many conversations, and row and path ids together, a request. */+const VERIFY_CONVERSATIONS = 200;+const VERIFY_IDS = 2 * IDS;const ATTACHMENT_NAMES = 2_000;const THREAD = /^[\w-]{1,200}$/u;+/** The waits between tries of a request nothing answered, and how long a check goes on while none of its requests gets an+ * 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 = 15 * 60_000;++/** Nothing answered on the way to My Cloud (no network, a timeout, a gateway error, the Admin's or My Cloud's), as+ * against a refusal: trying again soon may well work. */+export function unanswered(error, depth = 0) {+ if (!error || depth > 4) return false;+ if ((error.name === "TypeError" && /fetch/iu.test(error.message ?? "")) || error.name === "TimeoutError" || error.name === "AbortError") return true;+ if (Number.isInteger(error.status) && error.status >= 500) return true;+ return unanswered(error.cause, depth + 1);+}++/** An answer of My Cloud's, or the error it is: a gateway error (5xx) stays one that trying again may get past, and any+ * other is what `refuse(answer, message)` makes of it. */+export function answered(answer, message, refuse = null) {+ if (answer.ok) return answer;+ if (refuse && !(answer.status >= 500)) throw refuse(answer, message);+ throw Object.assign(new Error(message), { status: answer.status });+}++/**+ * A check's patience with a slow Cloud: a request nothing answered is asked again after PATIENCE_MS, for as long as some+ * 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 anything got done (`progressed`), which the next check does not do again. `onWait(until)` while it waits,+ * `onWait(null)` once it asks again.+ */+export function createPatience({ now = Date.now, sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); }), onWait = () => {}, stallMs = STALL_MS, waits = PATIENCE_MS } = {}) {+ let movedAt = now(), progressed = false, tries = 0;+ const patience = {+ moved() { movedAt = now(); progressed = true; tries = 0; },+ get progressed() { return progressed; },+ /** Waits before asking again after `error`, or throws once the check has stood still too long. */+ async wait(error) {+ if (!unanswered(error)) throw error;+ const ms = waits[Math.min(tries++, waits.length - 1)];+ if (now() + ms - movedAt > stallMs) {+ 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);+ onWait(null);+ },+ /** `work()` until it is answered. */+ async run(work) {+ for (;;) {+ try { const value = await work(); patience.moved(); return value; }+ catch (error) { await patience.wait(error); }+ }+ },+ };+ return patience;+}++/** Asks once: what a check without patience does. */+const IMPATIENT = { moved() {}, progressed: false, wait: async (error) => { throw error; }, run: (work) => work() };+/** My Cloud's journal shows at most this many of a bot's latest changes. */const JOURNAL_ROWS = 500;@@ -119,34 +180,91 @@ export async function* rowIdChunks(localJson, threadId) {}/**- * Each conversation's rows and visible path checked on My Cloud, a chunk at a time, ids only: `missing`, the rows My- * Cloud lacks; `unstamped`, the lines of its owner's it holds that do not carry the owner yet; `path`: "equal" when My- * Cloud shows exactly this computer's path, "inside" when this computer's path appears in order inside a longer one of- * My Cloud's (both sides added to it), "broken" otherwise.+ * Each conversation's rows and visible path checked on My Cloud, ids only: `missing`, the rows My Cloud lacks;+ * `unstamped`, the lines of its owner's it holds that do not carry the owner yet; `path`: "equal" when My Cloud shows+ * exactly this computer's path, "inside" when this computer's path appears in order inside a longer one of My Cloud's+ * (both sides added to it), "broken" otherwise. Conversations of up to IDS rows go many to a request; a longer one goes a+ * chunk at a time, each after the one before it, as its path is checked in order. A request nothing answered is split in+ * two, and the rest of the check asks for less at a time, until one conversation's chunk waits for My Cloud (`patience`).+ * `skip(threadId)`: checked before and unchanged since, left out; `checked(threadId)`: nothing missing; `onProgress(done,+ * total)` as conversations are checked.*/-export async function checkChats({ localJson, session, threads }) {+export async function checkChats({ localJson, session, threads, skip = () => false, checked = () => {}, onProgress = () => {}, patience = IMPATIENT, timeoutMs }) {const out = [];- for (const threadId of threads.filter((id) => THREAD.test(id))) {+ const todo = threads.filter((id) => THREAD.test(id));+ const total = todo.length;+ let done = 0, most = VERIFY_CONVERSATIONS, budget = VERIFY_IDS, batch = [], ids = 0;+ const verify = async (conversations) => {+ const answer = answered(await session.call("POST", "/api/cloud-send/chats/verify", { v: 1, conversations }, timeoutMs ? { timeoutMs } : undefined), "My Cloud did not check the chats.");+ const byThread = new Map(list(answer.body?.conversations).filter(record).map((entry) => [entry.threadId, entry]));+ if (conversations.some((entry) => !byThread.has(entry.threadId))) throw Object.assign(new Error("My Cloud did not check the chats."), { status: answer.status });+ return byThread;+ };+ const finish = (result) => {+ out.push(result);+ if (!result.missing && !result.unstamped && result.path !== "broken") checked(result.threadId);+ onProgress(++done, total);+ };+ const flush = async () => {+ const queue = batch.length ? [batch] : [];+ batch = []; ids = 0;+ while (queue.length) {+ const part = queue.shift();+ let answers;+ try { answers = await verify(part.map(({ asked }) => asked)); }+ catch (error) {+ if (!unanswered(error)) throw error;+ if (part.length > 1) {+ const half = Math.ceil(part.length / 2);+ most = Math.max(1, Math.min(most, half));+ budget = Math.max(IDS, Math.floor(budget / 2));+ queue.unshift(part.slice(0, half), part.slice(half));+ } else {+ await patience.wait(error);+ queue.unshift(part);+ }+ continue;+ }+ patience.moved();+ for (const { asked, leaf } of part) {+ const answer = answers.get(asked.threadId);+ const holds = answer.path?.holds === true;+ finish({ threadId: asked.threadId, missing: list(answer.missing).length, unstamped: Number.isSafeInteger(answer.unstamped) ? answer.unstamped : 0,+ path: !holds ? "broken" : answer.path.leaf === leaf && answer.path.length === asked.path.ids.length ? "equal" : "inside" });+ }+ }+ };+ for (const threadId of todo) {+ if (skip(threadId)) { onProgress(++done, total); continue; }+ const first = await localJson(`/api/cloud-send/chats/ids?thread=${threadId}&from=0`);+ if (!record(first)) throw new Error("OpenMausBot on this computer did not list a conversation's rows.");+ if (first.more === true) { finish(await checkLong(threadId)); continue; }+ const asked = { threadId, ids: list(first.ids), path: { after: null, ids: list(first.path), last: true } };+ const size = asked.ids.length + asked.path.ids.length;+ if (batch.length && (batch.length >= most || ids + size > budget)) await flush();+ batch.push({ asked, leaf: first.leaf ?? null });+ ids += size;+ }+ await flush();+ return out;++ async function checkLong(threadId) {let missing = 0, unstamped = 0, after = null, holds = true, cloud = null, localLeaf = null, length = 0;for await (const chunk of rowIdChunks(localJson, threadId)) {localLeaf = chunk.leaf ?? localLeaf;length += chunk.path.length;const asked = { threadId, ids: chunk.ids, ...(holds ? { path: { after, ids: chunk.path, last: !chunk.more } } : {}) };- const answer = await session.call("POST", "/api/cloud-send/chats/verify", { v: 1, conversations: [asked] });- const checked = answer.ok ? list(answer.body?.conversations).find((entry) => entry?.threadId === threadId) : null;- if (!checked) throw Object.assign(new Error("My Cloud did not check the chats."), { status: answer.status });- missing += list(checked.missing).length;- unstamped += Number.isSafeInteger(checked.unstamped) ? checked.unstamped : 0;+ const answer = await patience.run(() => verify([asked])).then((answers) => answers.get(threadId));+ missing += list(answer.missing).length;+ unstamped += Number.isSafeInteger(answer.unstamped) ? answer.unstamped : 0;if (asked.path) {- holds = checked.path?.holds === true;- after = checked.path?.at ?? null;- if (!chunk.more) cloud = checked.path;+ holds = answer.path?.holds === true;+ after = answer.path?.at ?? null;+ if (!chunk.more) cloud = answer.path;}}- const path = !holds ? "broken" : cloud && cloud.leaf === localLeaf && cloud.length === length ? "equal" : "inside";- out.push({ threadId, missing, unstamped, path });+ return { threadId, missing, unstamped, path: !holds ? "broken" : cloud && cloud.leaf === localLeaf && cloud.length === length ? "equal" : "inside" };}- return out;}/** A move's check passes when nothing is missing: no gap, every conversation's rows there on a path that holds with@@ -155,14 +273,15 @@ export const checkPassed = ({ gaps, chats, attachments, secrets }) => noGaps(gap&& chats.every((thread) => !thread.missing && !thread.unstamped && thread.path !== "broken")&& !attachments.length && !secrets.differs.length && !secrets.missing.length;-/** The attachments of `names` My Cloud lacks. */-export async function missingAttachments(session, names) {+/** The attachments of `names` My Cloud lacks; `onProgress(done, total)` as they are checked. */+export async function missingAttachments(session, names, { patience = IMPATIENT, onProgress = () => {} } = {}) {const missing = [];for (let i = 0; i < names.length; i += ATTACHMENT_NAMES) {const asked = names.slice(i, i + ATTACHMENT_NAMES);- const answer = await session.call("POST", "/api/cloud-send/chats/attachments", { names: asked });- if (!answer.ok) throw Object.assign(new Error("My Cloud did not check the attachments."), { status: answer.status });- missing.push(...list(answer.body?.missing).filter((name) => asked.includes(name)));+ 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."));+ const named = new Set(asked);+ missing.push(...list(answer.body?.missing).filter((name) => named.has(name)));+ onProgress(Math.min(names.length, i + ATTACHMENT_NAMES), names.length);}return missing;}@@ -181,3 +300,101 @@ export async function checkSecrets({ handoff, session, skip = new Set(), nonce =}return out;}++/** How long a request that lists much may take: My Cloud's, a little longer for each conversation it heads or byte of a+ * bot's files it may hash; this computer's own, frozen while the check reads it. */+const LISTING_MS = 2 * 60_000;+const LISTING_MAX_MS = 30 * 60_000;+export const LOCAL_LISTING_MS = 10 * 60_000;+const listingMs = (work) => Math.min(LISTING_MAX_MS, LISTING_MS + Math.round(work));+const BOT_FILE = /^(?:workspaces|task-workspaces)\/([\w-]{1,128})\//u;++/**+ * What did not arrive of what a move carried, from both sides' own answers: `gaps`, the manifests compared; `chats`, each+ * conversation's rows, its owner's lines and its visible path; `attachments`, the stored ones My Cloud lacks; `secrets`,+ * each credential by its fingerprint (none without `handoff`, as for a bot moving into a team). Left out: what was removed+ * on My Cloud, and a 1Password token 1Password itself refused. `ok` when nothing is missing.+ *+ * 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+ * 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, 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 } : {}), onWait: (until) => {+ if (!at) return;+ const { until: _, ...rest } = at;+ at = until ? { ...rest, until } : rest;+ onStep(at);+ } });+ const ask = (method, route, timeoutMs, message = "My Cloud did not answer. Try again.") =>+ patience.run(async () => answered(await session.call(method, route, undefined, { timeoutMs }), message, refuse));+ step("manifest");+ await patience.run(takesMove);+ 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))).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),+ ...roomsRemovedThere(here, there, kept.chats)]);+ const refused = new Set(list(kept.whole?.result.failed).filter((failure) => failure.final === true).map((failure) => failure.key));+ const going = new Set(list(here.items).filter((item) => item.kind === "bot" && !removed.has(item.key) && !refused.has(item.key)).map((item) => item.id));+ bots = going.size;+ if (!Array.isArray(there.files)) there.files = await cloudFiles(list(here.files), going, ask, step, scoped);+ const gaps = manifestGaps(here, there, { sent: kept.sent, removed, skip: refused });+ const 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 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);+ };+ 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 };+ },+ 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];+ persist();+ const names = list(here.attachments);+ step("attachments", 0, names.length);+ const attachments = await missingAttachments(session, names, { patience, onProgress: (done, total) => step("attachments", done, total) });+ step("credentials");+ const secrets = handoff ? await patience.run(() => checkSecrets({ handoff, session, skip: new Set([...removed, ...refused]) })) : { equal: [], differs: [], missing: [] };+ const ok = checkPassed({ gaps, chats, attachments, secrets });+ // What the person knows things by, for what stayed behind (move-gaps.mjs): bots and rooms by name, and the bot or room+ // each conversation the check found short belongs to.+ const short = new Set([...gaps.conversations, ...gaps.settings, ...chats.filter((entry) => entry.missing || entry.unstamped || entry.path === "broken").map((entry) => entry.threadId)]);+ const named = ok ? {} : Object.fromEntries([...list(here.items).filter((item) => item.kind === "bot" && item.id).map((item) => [item.id, item.label]),+ ...list(here.rooms).map((room) => [`room:${room.id}`, room.name])]);+ const owners = ok ? {} : Object.fromEntries(list(here.conversations).filter((head) => short.has(head.threadId)).map((head) => [head.threadId, head.bot ?? `room:${head.room}`]));+ return { ok, gaps, chats, attachments, secrets, names: named, owners };+}++/** My Cloud's files of the bots that go, a bot at a time, each given as long as hashing that bot's files here could take+ * there; only bots with files here are asked about. */+async function cloudFiles(here, going, ask, step, scoped) {+ const bytes = new Map();+ for (const file of here) {+ const bot = BOT_FILE.exec(typeof file?.path === "string" ? file.path : "")?.[1];+ if (bot && going.has(bot)) bytes.set(bot, (bytes.get(bot) ?? 0) + (Number.isSafeInteger(file.size) ? file.size : 0));+ }+ const out = [];+ let done = 0;+ for (const [bot, size] of bytes) {+ step("files", done, bytes.size);+ const route = scoped("/api/cloud-send/files").includes("bot=") ? scoped("/api/cloud-send/files") : `/api/cloud-send/files?bot=${bot}`;+ const listed = await ask("GET", route, listingMs(size / 20_000), "My Cloud did not list its files.");+ out.push(...list(listed.body?.files));+ step("files", ++done, bytes.size);+ }+ return out;+}diff --git a/electron/cloud-send-kinds.mjs b/electron/cloud-send-kinds.mjsindex 4715be7bff..384eb5374e 100644--- a/electron/cloud-send-kinds.mjs+++ b/electron/cloud-send-kinds.mjs@@ -13,6 +13,12 @@ const FILE_PATH = /^(?:workspaces\/[\w-]{1,128}|task-workspaces\/[\w-]{1,128}\/[/** A part of a file, as My Cloud takes one (server/cloud-send-files.ts). */const FILE_PART_BYTES = 8 * 1024 * 1024;const SETTINGS_BATCH = 500;+/** How long My Cloud may take to list a bot's files: longer the more bytes it may have to hash. */+const LISTING_MS = 2 * 60_000;+const LISTING_MAX_MS = 30 * 60_000;+/** How long this computer's own server may take to list what it holds. */+const LOCAL_LISTING_MS = 10 * 60_000;+const ownerOf = (path) => /^(?:workspaces|task-workspaces)\/([\w-]{1,128})\//u.exec(path)?.[1];const AUTOMATIONS = new Set(AUTOMATION_KINDS);const ATTACHMENT_NAMES = 2000;@@ -167,7 +173,7 @@ export function createMoveKinds({ localJson, localBytes, localSend, entry, persi/** The attachments My Cloud lacks of those this computer's chats name, in bytes. */async function missingAttachmentBytes(session) {- const listed = list((await localJson(scoped("/api/cloud-send/chats?attachments=1")))?.attachments).filter((item) => record(item) && typeof item.name === "string" && Number.isSafeInteger(item.size));+ const listed = list((await localJson(scoped("/api/cloud-send/chats?attachments=1"), { timeoutMs: LOCAL_LISTING_MS }))?.attachments).filter((item) => record(item) && typeof item.name === "string" && Number.isSafeInteger(item.size));let bytes = 0;for (let i = 0; i < listed.length; i += ATTACHMENT_NAMES) {const asked = listed.slice(i, i + ATTACHMENT_NAMES);@@ -209,19 +215,35 @@ export function createMoveKinds({ localJson, localBytes, localSend, entry, persithrow new Error("My Cloud could not take this file.");}+ /** My Cloud's files of these bots, a bot at a time (one answer for every bot of a big workspace is more than a slow+ * Cloud hashes in time), each given as long as hashing that bot's files here could take there; and its free space. */+ async function cloudFiles(ctx, here, carried) {+ const bytes = new Map();+ for (const file of here) bytes.set(ownerOf(file.path), (bytes.get(ownerOf(file.path)) ?? 0) + file.size);+ const scopedRoute = scoped("/api/cloud-send/files");+ const asks = scopedRoute.includes("bot=") ? [[scopedRoute, here.reduce((sum, file) => sum + file.size, 0)]]+ : [...bytes].map(([bot, size]) => [`/api/cloud-send/files?bot=${bot}`, size]);+ if (!asks.length) asks.push([carried.size && !scopedRoute.includes("bot=") ? `/api/cloud-send/files?bot=${[...carried][0]}` : scopedRoute, 0]);+ const files = [];+ let space = null;+ for (const [route, size] of asks) {+ const listed = await ctx.session.call("GET", route, undefined, { timeoutMs: Math.min(LISTING_MAX_MS, LISTING_MS + Math.round(size / 20_000)) });+ if (!listed.ok) throw new Error(refusal(listed, "My Cloud did not list its files."));+ files.push(...parseFiles(listed.body));+ if (record(listed.body?.space)) space = listed.body.space;+ }+ return { there: new Map(files.map((file) => [file.path, file])), space };+ }+/** The bots' files My Cloud lacks, once it has room for them and for the attachments still to go. */async function moveFiles(ctx, bots, label) {const carried = new Set(bots.map((bot) => bot.id));- const owner = (path) => /^(?:workspaces|task-workspaces)\/([\w-]{1,128})\//u.exec(path)?.[1];- const here = parseFiles(await localJson(scoped("/api/cloud-send/files"))).filter((file) => carried.has(owner(file.path)));- const listed = await ctx.session.call("GET", scoped("/api/cloud-send/files"));- if (!listed.ok) throw new Error(refusal(listed, "My Cloud did not list its files."));- const there = new Map(parseFiles(listed.body).map((file) => [file.path, file]));+ const here = parseFiles(await localJson(scoped("/api/cloud-send/files"), { timeoutMs: LOCAL_LISTING_MS })).filter((file) => carried.has(ownerOf(file.path)));+ const { there, space: measured } = await cloudFiles(ctx, here, carried);const kept = entry(ctx.origin);const plan = planFiles(here, there, kept.files, label);ctx.result.files = { sent: 0, kept: 0 };const bytes = plan.reduce((sum, file) => sum + file.size, 0) + await missingAttachmentBytes(ctx.session);- const measured = record(listed.body?.space) ? listed.body.space : null;if (measured && bytes) {const short = await makeRoom(ctx.session, bytes, measured);if (short) return void failed(ctx, "files", "files", "Files", short);diff --git a/electron/cloud-send-kinds.node-test.mjs b/electron/cloud-send-kinds.node-test.mjsindex d30c94b6f8..801defc4a1 100644--- a/electron/cloud-send-kinds.node-test.mjs+++ b/electron/cloud-send-kinds.node-test.mjs@@ -56,9 +56,15 @@ function filesSides({ here, there = [], free = 1e12, volume = 1e12, disk = null,const stored = new Map(there.map((entry) => [entry.path, { ...entry }]));const uploads = [], failed = [];const parts = new Map();+ const listings = [];const session = {call: async (method, route, body) => {- if (method === "GET" && route === "/api/cloud-send/files") return { ok: true, status: 200, body: { files: [...stored.values()], space: { freeBytes: typeof free === "function" ? free() : free, volumeBytes: volume } } };+ const listing = /^\/api\/cloud-send\/files(?:\?bot=([\w-]+))?$/u.exec(route);+ if (method === "GET" && listing) {+ listings.push(route);+ const files = [...stored.values()].filter((entry) => !listing[1] || entry.path.split("/")[1] === listing[1]);+ return { ok: true, status: 200, body: { files, space: { freeBytes: typeof free === "function" ? free() : free, volumeBytes: volume } } };+ }if (method === "POST" && route === "/api/cloud-send/chats/attachments") return { ok: true, status: 200, body: { missing: body.names } };throw new Error(`unexpected ${method} ${route}`);},@@ -94,7 +100,7 @@ function filesSides({ here, there = [], free = 1e12, volume = 1e12, disk = null,...(disk || grow ? { space: { disk: () => disk, grow } } : {}),});const ctx = { origin: "https://omb-u-1.fly.dev", session, result: { failed } };- return { kinds, ctx, stored, uploads, failed, state };+ return { kinds, ctx, stored, uploads, failed, state, listings };}test("the bots' files go once My Cloud has room for them and the attachments still to go; on a conflict, beside My Cloud's own", async () => {@@ -106,6 +112,7 @@ test("the bots' files go once My Cloud has room for them and the attachments stiassert.equal(sides.stored.get("workspaces/b1/notes.md").sha256, sha("their own"), "My Cloud's own file is never written over");assert.deepEqual(sides.ctx.result.files, { sent: 1, kept: 1 });assert.deepEqual(sides.state.files, { "workspaces/b1/notes (Mac).md": sha("mine") });+ assert.deepEqual(sides.listings, ["/api/cloud-send/files?bot=b1"], "My Cloud lists the files of the bots that go, a bot at a time, never every bot's at once");});test("a file the move put there that conflicts only when it lands goes beside, and a part My Cloud holds already is not sent again", async () => {diff --git a/electron/cloud-send-main.d.mts b/electron/cloud-send-main.d.mtsindex 912005d742..64b4044468 100644--- a/electron/cloud-send-main.d.mts+++ b/electron/cloud-send-main.d.mts@@ -8,7 +8,7 @@ export function installCloudSend(deps: {ipcMain: { handle(channel: string, handler: (...args: any[]) => unknown): void };cloudPage(event: unknown): "local" | "cloud" | null;server(): { postMessage(message: unknown): void } | null | undefined;- local(route: string, init?: { method?: string }): Promise<Response>;+ local(route: string, init?: { method?: string; timeoutMs?: number }): Promise<Response>;home(): CloudTarget | null;cookieFetch: typeof fetch;reconnect(origin: string): Promise<boolean>;diff --git a/electron/cloud-send-main.mjs b/electron/cloud-send-main.mjsindex 71f836c476..f74afab8b6 100644--- a/electron/cloud-send-main.mjs+++ b/electron/cloud-send-main.mjs@@ -11,9 +11,15 @@ const MOVE_LABEL = "Move to My Cloud";const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);const sentence = (value) => (typeof value === "string" && value.trim() ? value.trim().slice(0, 300) : null);+/** The most of an answer main reads: a big workspace's manifest of a Cloud, which holds every computer's bots that moved+ * there, runs to tens of megabytes. */+const ANSWER_MAX = 64 * 1024 * 1024;+/** How long a request to My Cloud may take unless its caller sized it to its work. */+const REQUEST_MS = 120_000;+async function answer(response) {const text = await response.text();- if (text.length > 8 * 1024 * 1024) return { status: response.status, ok: false, body: null };+ if (text.length > ANSWER_MAX) return { status: response.status, ok: false, body: null };try { return { status: response.status, ok: response.ok, body: text ? JSON.parse(text) : null }; }catch { return { status: response.status, ok: response.ok, body: null }; }}@@ -32,13 +38,14 @@ export async function openOwnerSession(target, fetchImpl, { label = SESSION_LABE}));if (!paired.ok || typeof paired.body?.token !== "string" || !paired.body.token.startsWith("omb_sess_")) throw Object.assign(new Error("This app could not sign in to My Cloud. Try again."), { status: paired.status });const token = paired.body.token;- const request = (method, route, init) => fetchImpl(`${target.origin}${route}`, {- method, redirect: "error", credentials: "omit", cache: "no-store", signal: AbortSignal.timeout(120_000), ...init,+ const request = (method, route, { timeoutMs = REQUEST_MS, ...init }) => fetchImpl(`${target.origin}${route}`, {+ method, redirect: "error", credentials: "omit", cache: "no-store", signal: AbortSignal.timeout(timeoutMs), ...init,headers: { accept: "application/json", authorization: `Bearer ${token}`, ...quiet, ...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) })),+ /** `timeoutMs`: how long this request may take, sized to the work it asks for; REQUEST_MS otherwise. */+ 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 })),/** The answer as it came, for a download. */fetch: (route, init = {}) => request(init.method ?? "GET", route, { ...init, headers: init.headers ?? {} }),diff --git a/electron/cloud-send-move.node-test.mjs b/electron/cloud-send-move.node-test.mjsindex e45c83c571..99d993dfae 100644--- a/electron/cloud-send-move.node-test.mjs+++ b/electron/cloud-send-move.node-test.mjs@@ -445,10 +445,10 @@ test("a check that finds things missing names, for what may stay behind, each shconversations: [{ threadId: "t-b1", bot: "b1", rows: 1, newest: "t-b1-1", settings: {} }, { threadId: "t-b2", bot: "b2", rows: 1, newest: "t-b2-1", settings: {} }],attachments: side === "here" ? ["0b6c9f2e-1d4a.mp3"] : [], files: [], automations: [], runs: [] });const s = sides({ here: [bot("b1", { soul: "s" }), bot("b2", { soul: "s" })], there: [bot("b1", { soul: "s" }), bot("b2", { soul: "s" })], onCall: (method, route, body) => {- if (route === "/api/cloud-send/manifest") return reply(200, { ...manifest("there"), rooms: [{ id: "r1", name: "Launch room", members: ["b1"], threads: ["t-r1"] }] });+ if (route.startsWith("/api/cloud-send/manifest")) return reply(200, { ...manifest("there"), rooms: [{ id: "r1", name: "Launch room", members: ["b1"], threads: ["t-r1"] }] });if (route === "/api/cloud-send/chats/verify") {- const threadId = body.conversations[0].threadId;- return reply(200, { v: 1, conversations: [{ threadId, missing: threadId === "t-b1" ? body.conversations[0].ids : [], unstamped: 0, path: { holds: true, at: null, leaf: `${threadId}-1`, length: 1 } }] });+ return reply(200, { v: 1, conversations: body.conversations.map(({ threadId, ids }) => ({ threadId, missing: threadId === "t-b1" ? ids : [], unstamped: 0,+ path: { holds: true, at: null, leaf: `${threadId}-1`, length: 1 } })) });}if (route === "/api/cloud-send/chats/attachments") return reply(200, { missing: body.names });if (route === "/api/cloud-send/verify-secrets") return reply(200, { v: 1, secrets: {} });diff --git a/electron/cloud-send-team.node-test.mjs b/electron/cloud-send-team.node-test.mjsindex 993593c555..0770c0831f 100644--- a/electron/cloud-send-team.node-test.mjs+++ b/electron/cloud-send-team.node-test.mjs@@ -75,5 +75,5 @@ test("a bot moving into a team carries its own things only: no apps, keys, loginassert.equal(sent.owner, OWNER, "the team learns whose lines become the mover's");const report = await send.check();assert.deepEqual(report.secrets, { equal: [], differs: [], missing: [] });- assert.ok(calls.some(([method, route]) => method === "GET" && route === "/api/cloud-send/manifest?bot=scout"));+ assert.ok(calls.some(([method, route]) => method === "GET" && /^\/api\/cloud-send\/manifest\?(?:[\w=&]+&)?bot=scout$/u.test(route)));});diff --git a/electron/cloud-send.d.mts b/electron/cloud-send.d.mtsindex e69fc07541..c44bf39b80 100644--- a/electron/cloud-send.d.mts+++ b/electron/cloud-send.d.mts@@ -55,6 +55,9 @@ export interface CloudSendSnapshot {arrived: CloudSendArrived;cloudVersion: string | null;localVersion: string | null;+ /** A move's check under way: its step, `done` of `total` there, the bots it checks, and until when it waits for a My+ * Cloud that did not answer. */+ checking?: { step: string; done: number; total: number; bots: number; until?: number } | null;}/** What My Cloud's own page is told: names of this computer's bots that wait, and counts, never logins' sites. */@@ -126,7 +129,8 @@ export interface CloudSendPageBridge {export interface KeepHereState { shown: boolean; on: boolean; moved: boolean; coming: boolean }export interface CloudSendSession {- call(method: string, route: string, body?: unknown): Promise<{ status: number; ok: boolean; body: any }>;+ /** `timeoutMs`: how long this request may take, sized to the work it asks for. */+ call(method: string, route: string, body?: unknown, options?: { timeoutMs?: number }): Promise<{ status: number; ok: boolean; body: any }>;upload(route: string, bytes: Uint8Array, type: string): Promise<{ status: number; ok: boolean; body: any }>;/** The answer as it came, for a download; only the owner sessions main opens have it. */fetch?(route: string, init?: RequestInit): Promise<Response>;@@ -176,7 +180,8 @@ export interface CloudMoveCheck {}export function createCloudSend(deps: {- local(route: string, init?: { method?: string }): Promise<Response>;+ /** `timeoutMs`: how long a request that lists much may take on this computer's own server. */+ local(route: string, init?: { method?: string; timeoutMs?: number }): Promise<Response>;cloud: {origin(): string | null;asleep(): boolean;@@ -190,6 +195,8 @@ export function createCloudSend(deps: {onChange?(snapshot: CloudSendSnapshot): void;t?(key: string, params?: Record<string, string | number>): string;now?(): number;+ /** How a check waits before it asks a slow Cloud again; setTimeout's by default. */+ sleep?(ms: number): Promise<void>;/** How long a move waits for My Cloud to run the engines whose keys it just took. */engineWaitMs?: number;/** My Cloud's plan disk and the Admin's grow, so a move makes room for the files it carries. */diff --git a/electron/cloud-send.mjs b/electron/cloud-send.mjsindex 5453c8c853..05a172193a 100644--- a/electron/cloud-send.mjs+++ b/electron/cloud-send.mjs@@ -19,7 +19,7 @@ import { AUTOMATION_KINDS, BOT_PARTS, EMPTY, MOVE_BOT_PARTS, MOVE_KINDS, PICTUREimport { collectConnections, releaseConnections, sendConnections } from "./cloud-connections.mjs";import { createMoveKinds, mergeRoutines } from "./cloud-send-kinds.mjs";import { botsOnCloud } from "./cloud-logins.mjs";-import { checkChats, checkPassed, checkSecrets, manifestGaps, missingAttachments, roomsRemovedThere, roomsThatGo, rowIdChunks } from "./cloud-send-check.mjs";+import { moveCheck, rowIdChunks, unanswered } from "./cloud-send-check.mjs";import nativeText from "./native-text.cjs";const LOCAL_ROUTE = /^\/api\/(?:cloud-send|cloud-send\?move=1|cloud-send\/manifest|cloud-send\/chats|cloud-send\/chats\?attachments=1|cloud-send\/kind\?key=[\w%.-]{1,300}|cloud-send\/memory|cloud-send\/memory\?bot=[\w-]{1,128}|cloud-send\/files|cloud-send\/files\?path=[\w%.()~!*'-]{1,12000}&offset=\d{1,16}&length=\d{1,9}|cloud-send\/chats\/rows\?thread=[\w-]{1,200}&after=\d{1,16}&id=[\w%.-]{0,600}|cloud-send\/chats\/ids\?thread=[\w-]{1,200}&from=\d{1,9}|cloud-send\/chats\/attachment\/[A-Za-z0-9-]{1,80}\.[A-Za-z0-9]{1,10}|cloud-connections|connectors\/connected|config|bots\?messages=0|bots\/[\w-]{1,128}\/(?:skills|skills\/[a-z0-9-]{1,64}|memory|memory\/file\?path=[\w%.-]{1,200})|attachments\/[A-Za-z0-9-]{1,80}\.(?:png|jpg|gif|webp))$/u;@@ -47,14 +47,7 @@ export class CloudSendError extends Error {constructor(code, message, options) { super(message, options); this.name = "CloudSendError"; this.code = code; }}-/** Nothing answered on the way to My Cloud (no network, a timeout, a gateway error, the Admin's or My Cloud's), as- * against a refusal: trying again soon may well work. */-export function unanswered(error, depth = 0) {- if (!error || depth > 4) return false;- if ((error.name === "TypeError" && /fetch/iu.test(error.message ?? "")) || error.name === "TimeoutError" || error.name === "AbortError") return true;- if (Number.isInteger(error.status) && error.status >= 500) return true;- return unanswered(error.cause, depth + 1);-}+export { unanswered };/** Security: only a `serverError.*` key passes, so a server cannot make the page show any other catalog string. */export function namedRefusal(answer) {@@ -119,8 +112,10 @@ const addCounts = (total, sent) => countsOf({ ...Object.fromEntries(COUNTED.map(/** The state main keeps in its own folder: per Cloud what was sent, what the person kept here, the bots a send made* there whose fields still wait to be recorded (`created`), the bots a send asked My Cloud to make and has not heard back* about (`creating`), the sign-ins My Cloud took that this computer still holds- * (`release`), the bot files a move put there (`files`, path to sha256), and whether each automation a move carried was- * on here (`on`). */+ * (`release`), the bot files a move put there (`files`, path to sha256), whether each automation a move carried was+ * on here (`on`), the conversations a move's check found whole (`verified`: this computer's newest row and row count+ * then, and how many rows My Cloud's manifest said it had), and those whose earlier rows My Cloud made its owner's+ * (`stamped`). */export function parseSendState(value) {const clouds = {};if (record(value?.clouds)) {@@ -140,6 +135,9 @@ export function parseSendState(value) {release: Array.isArray(entry.release) ? entry.release.filter((held) => record(held) && typeof held.id === "string" && typeof held.digest === "string").slice(0, 200) : [],files: record(entry.files) ? Object.fromEntries(Object.entries(entry.files).filter(([path, sha]) => typeof sha === "string" && /^[a-f0-9]{64}$/u.test(sha) && path.length <= 4096)) : {},on: record(entry.on) ? Object.fromEntries(Object.entries(entry.on).filter(([key, on]) => /^(?:routine|call|webhook|app-event):[\w-]{1,128}$/u.test(key) && typeof on === "boolean")) : {},+ verified: record(entry.verified) ? Object.fromEntries(Object.entries(entry.verified).filter(([threadId, seen]) => /^[\w-]{1,200}$/u.test(threadId) && record(seen)+ && typeof seen.newest === "string" && Number.isSafeInteger(seen.rows) && Number.isSafeInteger(seen.there))) : {},+ stamped: record(entry.stamped) ? Object.fromEntries(Object.entries(entry.stamped).filter(([threadId, on]) => /^[\w-]{1,200}$/u.test(threadId) && on === true)) : {},};}}@@ -211,17 +209,18 @@ const movedResult = () => ({ moved: 0, memory: 0, files: { sent: 0, kept: 0 }, c* name the team gave it; never apps, keys, logins, settings or its notes about the person. `local` is then the bot's* own Cloud, and `label` names the person beside a file or bot of the same name.*/-export function createCloudSend({ local, cloud, handoff, store, onChange = () => {}, now = Date.now, engineWaitMs, space, team = null, t = nativeText.englishText.t }) {+export function createCloudSend({ local, cloud, handoff, store, onChange = () => {}, now = Date.now, sleep, engineWaitMs, space, team = null, t = nativeText.englishText.t }) {let saved = parseSendState(safeRead(store));let view = { cloud: "none", plan: null, local: null, theirs: null, chats: null };- let running = null, progress = null;+ let running = null, progress = null, checking = null;const only = team?.bot ?? null;/** A route as a move of one bot asks it of either side: kept to that bot. */const scoped = (route) => (only ? `${route}${route.includes("?") ? "&" : "?"}bot=${only}` : route);function safeRead(source) { try { return source.read(); } catch { return null; } }function persist() { try { store.write(saved); } catch {} }- const entry = (origin) => (saved.clouds[origin] ??= { sent: {}, off: {}, dismissed: "", last: null, whole: null, arrived: countsOf(null), chats: {}, created: {}, creating: {}, release: [], files: {}, on: {} });+ const entry = (origin) => (saved.clouds[origin] ??= { sent: {}, off: {}, dismissed: "", last: null, whole: null, arrived: countsOf(null), chats: {}, created: {}, creating: {}, release: [], files: {}, on: {},+ verified: {}, stamped: {} });/** What a move ignores of what the person kept here: everything goes but what was removed on My Cloud. */const removedOnly = (off) => Object.fromEntries(Object.entries(off).filter(([, why]) => why === "removed"));const connectionLocal = { json: (route) => localJson(route), handoff: (what) => handoff(what) };@@ -244,14 +243,15 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>arrived: mine?.arrived ?? countsOf(null),cloudVersion: view.theirs?.appVersion ?? null,localVersion: view.local?.appVersion ?? null,+ checking,};}const publish = () => { const value = snapshot(); try { onChange(value); } catch {} return value; };const allowed = (route) => LOCAL_ROUTE.test(route.replace(/[?&]bot=[\w-]{1,128}$/u, ""));- async function localJson(route) {+ async function localJson(route, options) {if (!allowed(route)) throw new CloudSendError("invalid", "Unsupported local request.");- const response = await local(route);+ const response = await local(route, options);if (!response.ok) throw new CloudSendError("local", "OpenMausBot on this computer did not answer. Try again in a moment.");return response.json();}@@ -589,25 +589,31 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>}/** A move has My Cloud make its owner's lines and answers its owner's among the rows it already held of this computer's- * bots and rooms, which an earlier send or a Bring left naming nobody: this computer's row ids go, never a row. */+ * bots and rooms, which an earlier send or a Bring left naming nobody: this computer's row ids go, never a row. Once per+ * conversation (`stamped`): every row that arrives over the owner's session after it carries the owner already, and a+ * check that finds one that does not names its conversation again. */async function stampHeld(origin, session, theirs) {const listed = await localJson(scoped("/api/cloud-send/chats"));const kept = entry(origin);const cloudBots = new Set(theirs.items.filter((item) => item.kind === "bot" && item.id).map((item) => item.id));const threads = (Array.isArray(listed?.conversations) ? listed.conversations : []).filter((head) => record(head) && (cloudBots.has(head.bot) || typeof head.room === "string")- && typeof head.threadId === "string" && /^[\w-]{1,200}$/u.test(head.threadId) && kept.chats[head.threadId] !== "removed").map((head) => head.threadId);- let batch = [], ids = 0;+ && typeof head.threadId === "string" && /^[\w-]{1,200}$/u.test(head.threadId) && kept.chats[head.threadId] !== "removed" && !kept.stamped[head.threadId]).map((head) => head.threadId);+ let batch = [], ids = 0, whole = [];const flush = async () => {- if (!batch.length) return;- const answer = await session.call("POST", "/api/cloud-send/chats/owner", { v: 1, conversations: batch });- if (!answer.ok) throw refusedError("refused", answer, "My Cloud could not keep the chats' lines as yours.");- batch = []; ids = 0;+ if (batch.length) {+ const answer = await session.call("POST", "/api/cloud-send/chats/owner", { v: 1, conversations: batch });+ if (!answer.ok) throw refusedError("refused", answer, "My Cloud could not keep the chats' lines as yours.");+ }+ for (const threadId of whole) kept.stamped[threadId] = true;+ if (whole.length) persist();+ batch = []; ids = 0; whole = [];};for (const threadId of threads) {for await (const chunk of rowIdChunks(localJson, threadId)) {if (ids + chunk.ids.length > ROW_IDS || batch.length >= ROW_ID_CONVERSATIONS) await flush();batch.push({ threadId, ids: chunk.ids });ids += chunk.ids.length;+ if (!chunk.more) whole.push(threadId);}}await flush();@@ -882,45 +888,22 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>ctx.result.onePassword = true;}- /**- * What did not arrive of what a move carried, from both sides' own answers, over one owner session that counts as- * someone using My Cloud: `gaps`, the manifests compared (cloud-send-check.mjs); `chats`, each conversation's rows, its- * owner's lines and its visible path; `attachments`, the stored ones My Cloud lacks; `secrets`, each credential by its- * fingerprint. Left out: what was removed on My Cloud, and a 1Password token 1Password itself refused. `ok` when- * nothing is missing.- */+ /** 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() {const origin = cloud.origin();if (!origin) throw new CloudSendError("no_cloud", "This computer has no My Cloud yet.");- const kept = entry(origin);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 {- await assertTakesMove(session);- const here = await localJson(scoped("/api/cloud-send/manifest"));- const answer = await session.call("GET", scoped("/api/cloud-send/manifest"));- if (!answer.ok) throw refusedError("unreachable", answer, "My Cloud did not answer. 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),- ...roomsRemovedThere(here, answer.body, kept.chats)]);- const refused = new Set((kept.whole?.result.failed ?? []).filter((failure) => failure.final === true).map((failure) => failure.key));- const gaps = manifestGaps(here, answer.body, { sent: kept.sent, removed, skip: refused });- if (!gaps) throw new CloudSendError("unreachable", "My Cloud did not say what it has. Try again.");- const bots = new Set((here.items ?? []).filter((item) => item.kind === "bot" && !removed.has(item.key) && !refused.has(item.key)).map((item) => item.id));- const going = roomsThatGo(here, bots);- const threads = (here.conversations ?? []).filter((head) => !removed.has(head.threadId)- && (head.room ? going.has(head.room) && !removed.has(`room:${head.room}`) : bots.has(head.bot))).map((head) => head.threadId);- const chats = await checkChats({ localJson, session, threads });- const attachments = await missingAttachments(session, Array.isArray(here.attachments) ? here.attachments : []);- const secrets = team ? { equal: [], differs: [], missing: [] } : await checkSecrets({ handoff, session, skip: new Set([...removed, ...refused]) });- const ok = checkPassed({ gaps, chats, attachments, secrets });- // What the person knows things by, for what stayed behind (move-gaps.mjs): bots and rooms by name, and the bot or room- // each conversation the check found short belongs to.- const short = new Set([...gaps.conversations, ...gaps.settings, ...chats.filter((entry) => entry.missing || entry.unstamped || entry.path === "broken").map((entry) => entry.threadId)]);- const names = ok ? {} : Object.fromEntries([...(here.items ?? []).filter((item) => item.kind === "bot" && item.id).map((item) => [item.id, item.label]),- ...(here.rooms ?? []).map((room) => [`room:${room.id}`, room.name])]);- const owners = ok ? {} : Object.fromEntries((here.conversations ?? []).filter((head) => short.has(head.threadId)).map((head) => [head.threadId, head.bot ?? `room:${head.room}`]));- return { ok, gaps, chats, attachments, secrets, names, owners };+ return await moveCheck({ session, kept: entry(origin), persist, localJson, handoff: team ? null : handoff, scoped, now, sleep, 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 });+ throw error;} finally {+ checking = null;+ publish();try { await session.close(); } catch {}}}diff --git a/electron/cloud-send.node-test.mjs b/electron/cloud-send.node-test.mjsindex b77ddf7b4d..eb08c1c2d4 100644--- a/electron/cloud-send.node-test.mjs+++ b/electron/cloud-send.node-test.mjs@@ -76,9 +76,11 @@ test("a bot's fields reach My Cloud without Custom approval and without naming bconst body = botPatch(ember, ["soul", "access", "team", "model"], new Set(["juno"]));assert.deepEqual(body, { soul: "Be brief.", alwaysAllow: ["Bash(ls)"], peers: ["juno"], modelSelection: { instanceId: "claude", model: "m" }, requireAvailableModel: true });assert.ok(!Object.values(BOT_PARTS).flat().includes("cwd"), "a working folder is this computer's");- assert.deepEqual(parseSendState({ auto: false, clouds: { "javascript:alert(1)": {}, [CLOUD]: { off: { a: "you", b: "nonsense" }, created: { "bot:x": true, "login:y": true }, creating: { "bot:z": true, "skill:q": true }, release: [{ id: "mcp:a", digest: "d" }, { id: 3 }] } } }),+ assert.deepEqual(parseSendState({ auto: false, clouds: { "javascript:alert(1)": {}, [CLOUD]: { off: { a: "you", b: "nonsense" }, created: { "bot:x": true, "login:y": true }, creating: { "bot:z": true, "skill:q": true }, release: [{ id: "mcp:a", digest: "d" }, { id: 3 }],+ verified: { "t-1": { newest: "m9", rows: 9, there: 9 }, "t-2": { newest: 3 }, "bad id": { newest: "m", rows: 1, there: 1 } }, stamped: { "t-1": true, "t-2": "yes" } } } }),{ v: 1, clouds: { [CLOUD]: { sent: {}, off: { a: "you" }, dismissed: "", last: null, whole: null, arrived: { bots: 0, updatedBots: 0, skills: 0, logins: 0, settings: 0, onePassword: false, chats: { conversations: 0, messages: 0 } },- chats: {}, created: { "bot:x": true }, creating: { "bot:z": true }, release: [{ id: "mcp:a", digest: "d" }], files: {}, on: {} } } }, "nothing is kept of the switch that once sent by itself");+ chats: {}, created: { "bot:x": true }, creating: { "bot:z": true }, release: [{ id: "mcp:a", digest: "d" }], files: {}, on: {}, verified: { "t-1": { newest: "m9", rows: 9, there: 9 } }, stamped: { "t-1": true } } } },+ "nothing is kept of the switch that once sent by itself");});function fakeSides({ cloudItems = [], localItems = [], refuse = {} } = {}) {diff --git a/electron/move-lease.mjs b/electron/move-lease.mjsnew file mode 100644index 0000000000..2e247f4df1--- /dev/null+++ b/electron/move-lease.mjs@@ -0,0 +1,53 @@+// The lease that lets one computer at a time run the heavy part of its move into a Cloud (server/cloud-send-lease.ts):+// asked for before a pass that copies and before the freeze, held through the switch, asked again every few minutes while+// held, and let go of at the end. A Cloud too old to keep one (404) lets every computer go on, as before.++/** How often a held lease is asked for again: well inside the Cloud's 10 minutes. */+export const LEASE_RENEW_MS = 3 * 60_000;++const sentence = (value) => (typeof value === "string" && value.trim() ? value.trim().slice(0, 120) : "");++/**+ * @param {{+ * session(): Promise<{ call(method: string, route: string, body?: unknown): Promise<{ ok: boolean, status: number, body: any }> }>,+ * holder(): Promise<string | null>,+ * label(): Promise<string>,+ * timers?: { set(work: () => void, ms: number): unknown, clear(timer: unknown): void },+ * log?(line: string): void,+ * }} deps `holder`: this computer, as the Cloud tells computers apart (one-home-main.mjs `installationOf`); null until it is+ * 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;+ const ask = async (body) => (await session()).call("POST", "/api/cloud-send/lease", { v: 1, ...body });+ const stop = () => { if (timer) timers.clear(timer); timer = null; };++ return {+ /** Null once this computer holds the lease, or when the Cloud keeps none; otherwise the other computer, by its name. */+ async take() {+ const id = await holder();+ if (!id) return null;+ name = sentence(await label().catch(() => "")) || name;+ const answer = await ask({ holder: id, label: name });+ if (answer.status === 409) { stop(); held = null; return { name: sentence(answer.body?.label) }; }+ // An older Cloud keeps no lease, and one that fails to answer fails the request the move makes next anyway.+ if (!answer.ok) return null;+ held = id;+ 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"); }, () => {});+ }, LEASE_RENEW_MS);+ }+ return null;+ },+ /** Lets go of a held lease, so another computer's move goes on at once. */+ async release() {+ stop();+ const id = held;+ held = null;+ if (id) await ask({ holder: id, release: true }).catch(() => {});+ },+ held: () => held !== null,+ };+}diff --git a/electron/move-session.mjs b/electron/move-session.mjsindex 7d08ecb47d..9ef1dd967b 100644--- a/electron/move-session.mjs+++ b/electron/move-session.mjs@@ -4,7 +4,7 @@// interrupted or two computers moved together./**- * @typedef {{ call(method: string, route: string, body?: unknown): Promise<{ ok: boolean, status: number, body: any }>,+ * @typedef {{ call(method: string, route: string, body?: unknown, options?: { timeoutMs?: number }): Promise<{ ok: boolean, status: number, body: any }>,* upload(route: string, bytes: Uint8Array, type: string): Promise<{ ok: boolean, status: number, body: any }>,* fetch(route: string, init?: RequestInit): Promise<Response>, close(): Promise<void> }} OwnerSession* @typedef {{ origin: string }} Target@@ -54,7 +54,7 @@ export function createMoveSession({ open }) {async open(target) {await current(target).session;return {- call: (method, route, body) => using(target, (session) => session.call(method, route, body)),+ call: (method, route, body, options) => using(target, (session) => session.call(method, route, body, options)),upload: (route, bytes, type) => using(target, (session) => session.upload(route, bytes, type)),fetch: (route, init) => using(target, async (session) => {const response = await session.fetch(route, init);diff --git a/electron/one-home-check.node-test.mjs b/electron/one-home-check.node-test.mjsnew file mode 100644index 0000000000..799c7c04ee--- /dev/null+++ b/electron/one-home-check.node-test.mjs@@ -0,0 +1,177 @@+import assert from "node:assert/strict";+import test from "node:test";++import { createMoveLease } from "./move-lease.mjs";+import { CHECK_RESUME_MS, createOneHome, FROZEN_RETRY_MS, QUEUE_POLL_MS, QUIET_MS } from "./one-home.mjs";++const CLOUD = "https://omb-t-1.fly.dev";+const reply = (status, body = {}) => ({ ok: status < 400, status, body });+const timeout = () => new DOMException("The operation was aborted due to timeout", "TimeoutError");++/** My Cloud's lease (server/cloud-send-lease.ts), as the clock `now` sees it. */+function cloudLease(now) {+ let held = null;+ return {+ get held() { return held && held.until > now() ? held : null; },+ answer(body) {+ if (body.release) { if (held?.holder === body.holder) held = null; return reply(200, { v: 1, held: false }); }+ if (held && held.holder !== body.holder && held.until > now()) return reply(409, { v: 1, held: false, label: held.label, until: held.until });+ held = { holder: body.holder, label: body.label || held?.label || "", until: now() + 10 * 60_000 };+ return reply(200, { v: 1, held: true, until: held.until });+ },+ };+}++/**+ * One computer moving into My Cloud, with fakes on every side: its journal, its server (frozen or not), the send (each+ * pass and check, `checks` answering in turn: true, false, an error, or a function of the moment), My Cloud's session,+ * the clock and its timers, and My Cloud's lease when `lease` is given (`name` and `id`: this computer as it asks).+ */+function computer({ clock, checks = [], lease = null, name = "Mac", id = "computer-mac", copy = null }) {+ let journal = null;+ const timers = [];+ const c = {+ passes: [], server: { frozen: false, freezes: 0, unfreezes: 0 }, checking: null, timers,+ get journal() { return journal; },+ set journal(value) { journal = structuredClone(value); },+ async tick() { for (const timer of timers.splice(0)) timer.work(); await c.home.kick(); },+ };+ const session = async () => ({+ async call(method, route, body) {+ if (route === "/api/cloud-send/lease") return lease ? lease.answer(body) : reply(404, { error: "not found" });+ if (route === "/api/cloud-send/manifest") return reply(200, { items: [], conversations: [], automations: [] });+ return reply(200, { v: 1 });+ },+ async close() {},+ });+ const local = {+ async freeze() { if (!c.server.frozen) c.server.freezes++; c.server.frozen = true; return { frozen: true }; },+ async unfreeze() { if (c.server.frozen) c.server.unfreezes++; c.server.frozen = false; },+ frozen: async () => c.server.frozen,+ json: async (route) => (route === "/api/cloud-connections" ? { computer: { label: name } } : route.startsWith("/api/bots") ? { bots: [] } : { items: [], conversations: [], automations: [] }),+ call: async () => reply(200),+ };+ c.home = createOneHome({+ journal: { read: () => structuredClone(journal), write: (value) => { journal = structuredClone(value); } },+ cloud: () => ({ 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() {+ const next = checks.shift();+ const answer = typeof next === "function" ? await next(c) : next;+ if (answer instanceof Error) throw answer;+ return { ok: answer ?? true };+ },+ switches: () => ({}),+ snapshot: () => ({ running: null, checking: c.checking, whole: { result: { notes: [], failed: [] } } }),+ },+ local,+ session,+ ...(lease ? { lease: createMoveLease({ session, holder: async () => id, label: async () => name, timers: { set: () => null, clear: () => {} } }) } : {}),+ lastInput: () => 0,+ now: () => clock.now,+ timers: { set: (work, ms) => { const timer = { work, ms }; timers.push(timer); return timer; }, clear: (timer) => { const at = timers.indexOf(timer); if (at >= 0) timers.splice(at, 1); } },+ });+ return c;+}++const newClock = () => ({ now: 1_000_000 + QUIET_MS + 1 });++test("a check My Cloud stopped answering after it got somewhere goes on from there in minutes, and the line says My Cloud is slow until then", async () => {+ const clock = newClock();+ const slow = Object.assign(new Error("My Cloud did not answer for 15 min (The operation was aborted due to timeout)."), { cause: timeout(), progressed: true });+ const c = computer({ clock, checks: [slow, true] });+ await c.home.kick();+ assert.equal(c.journal.phase, "copy");+ assert.equal(c.server.frozen, false, "this computer is never left frozen while My Cloud is slow");+ assert.equal(c.journal.retryAt, clock.now + CHECK_RESUME_MS, "minutes, not the hour a check that got nowhere waits");+ assert.equal(c.journal.frozenTries, undefined, "nor does it count toward waiting longer next time");+ assert.deepEqual({ phase: c.journal.failure.phase, code: c.journal.failure.code }, { phase: "check", code: "unanswered" }, "the Admin hears it as it did");+ assert.deepEqual(c.home.view(), { phase: "copy", slow: { until: clock.now + CHECK_RESUME_MS } });++ clock.now += CHECK_RESUME_MS;+ await c.tick();+ assert.equal(c.journal.phase, "done");++ const nowhere = computer({ clock, checks: [Object.assign(new Error("My Cloud did not answer."), { cause: timeout(), progressed: false })] });+ await nowhere.home.kick();+ assert.equal(nowhere.journal.retryAt, clock.now + FROZEN_RETRY_MS, "a check that got nowhere still waits its hour");+});++test("while the check runs, the line says which step it is at, how far, and how many bots it checks", async () => {+ const clock = newClock();+ const views = [];+ const c = computer({ clock, checks: [async (self) => {+ self.checking = { step: "chats", done: 400, total: 1_000, bots: 25 };+ views.push(self.home.view());+ self.checking = { step: "chats", done: 400, total: 1_000, bots: 25, until: clock.now + 60_000 };+ views.push(self.home.view());+ self.checking = null;+ return true;+ }] });+ await c.home.kick();+ assert.deepEqual(views, [+ { phase: "finishing", checking: { step: "chats", done: 400, total: 1_000, bots: 25 } },+ { phase: "finishing", checking: { step: "chats", done: 400, total: 1_000, bots: 25 }, slow: { until: clock.now + 60_000 } },+ ]);+ assert.equal(c.journal.phase, "done");+});++test("two computers moving into one Cloud take turns: the second waits for the first, says for which, and goes on once it is done", async () => {+ const clock = newClock();+ const lease = cloudLease(() => clock.now);+ let letCopyEnd;+ const copying = new Promise((resolve) => { letCopyEnd = resolve; });+ let seenFromNuc = null;+ const nuc = computer({ clock, lease, name: "NUC", id: "computer-nuc" });+ const mac = computer({ clock, lease, name: "Mac", id: "computer-mac", copy: () => copying, checks: [async () => {+ // While the Mac finishes, the NUC asks: it waits, unfrozen, and copies nothing.+ await nuc.tick();+ seenFromNuc = nuc.home.view();+ return true;+ }] });++ const macRun = mac.home.kick();+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(lease.held?.label, "Mac", "the Mac's copy holds the lease");+ await nuc.home.kick();+ assert.deepEqual(nuc.passes, [], "nothing of the NUC's goes while the Mac's copy runs");+ assert.deepEqual(nuc.home.view(), { phase: "copy", queued: { name: "Mac" } });+ assert.deepEqual(nuc.timers.map((timer) => timer.ms), [QUEUE_POLL_MS], "it asks again in a minute");++ letCopyEnd();+ await macRun;+ assert.equal(mac.journal.phase, "done");+ assert.deepEqual(mac.passes, ["copy", "final"]);+ assert.deepEqual(seenFromNuc, { phase: "copy", queued: { name: "Mac" } }, "the Mac held the lease from its freeze to its switch");+ assert.deepEqual(nuc.passes, []);+ assert.equal(lease.held, null, "the Mac let go once it was done");++ clock.now += QUEUE_POLL_MS;+ await nuc.tick();+ assert.equal(nuc.journal.phase, "done");+ assert.deepEqual(nuc.passes, ["copy", "final"]);+ assert.equal(nuc.server.frozen, true);+ assert.equal(lease.held, null);+});++test("a Cloud too old to keep a lease lets every computer move as before", async () => {+ const clock = newClock();+ const c = computer({ clock });+ await c.home.kick();+ assert.equal(c.journal.phase, "done");+ const old = createMoveLease({ session: async () => ({ call: async () => reply(404, { error: "not found" }) }), holder: async () => "computer-x", label: async () => "X", timers: { set: () => null, clear: () => {} } });+ assert.equal(await old.take(), null);+ assert.equal(old.held(), false);+});++test("a move that waits for another computer after an earlier failure asks again in a minute, not in a tight loop", async () => {+ const clock = newClock();+ const lease = cloudLease(() => clock.now);+ lease.answer({ holder: "computer-mac", label: "Mac" });+ const nuc = computer({ clock, lease, name: "NUC", id: "computer-nuc" });+ nuc.journal = { v: 1, phase: "copy", cloud: { origin: CLOUD, account: "acct-1", machine: CLOUD }, retryAt: clock.now - 1, failure: { phase: "check", code: "unanswered", count: 1, since: 1, at: 1 } };+ await nuc.home.kick();+ assert.deepEqual(nuc.passes, []);+ assert.deepEqual(nuc.timers.map((timer) => timer.ms), [QUEUE_POLL_MS]);+});diff --git a/electron/one-home-main.mjs b/electron/one-home-main.mjsindex 815714756a..b295a05ec3 100644--- a/electron/one-home-main.mjs+++ b/electron/one-home-main.mjs@@ -10,6 +10,7 @@ import { dirname, join } from "node:path";import { Readable } from "node:stream";import { installCloudSend, openOwnerSession } from "./cloud-send-main.mjs";+import { createMoveLease } from "./move-lease.mjs";import { createMoveSession } from "./move-session.mjs";import { createMoveStatusReport, moveStatus } from "./move-status.mjs";import { createHomeAgain } from "./one-home-again.mjs";@@ -145,7 +146,7 @@ export function installOneHome({ localRequest: anyServer, clean = null, account,let teamMove = null;// One owner session for the whole move, every pass and check and the switch: each new one is one of the Admin's codes.const moveSession = createMoveSession({ open: (target) => openOwnerSession(target, fetchImpl, { label: MOVE_LABEL, background: false }) });- const send = installCloudSend({ ...sendDeps, t, local: (route, init) => localRequest(route, { method: init?.method ?? "GET", signal: AbortSignal.timeout(30_000) }),+ const send = installCloudSend({ ...sendDeps, t, local: (route, init) => localRequest(route, { method: init?.method ?? "GET", signal: AbortSignal.timeout(init?.timeoutMs ?? 30_000) }),move: () => (home?.view() === null && other()?.view() ? other() : home), teamMove: () => teamMove, moveSession });teamMove = installTeamMove({ t, ipcMain: sendDeps.ipcMain, cloudPage: sendDeps.cloudPage, pageOrigin: sendDeps.pageOrigin, confirmMove: sendDeps.confirmMove, home: sendDeps.home, account: () => account(), fetch: fetchImpl, openTeam,file: () => join(dirname(journalFile()), "team-move-send.json"), journalFile: () => join(dirname(journalFile()), "team-moves.json"), ...(teamJournal ? { journal: teamJournal } : {}),@@ -226,9 +227,13 @@ export function installOneHome({ localRequest: anyServer, clean = null, account,tempRoot: tempRoot(),});+ // Two computers moving into one Cloud take turns at the heavy part (server/cloud-send-lease.ts).+ const lease = createMoveLease({ session: () => moveSession.open(target()), holder: installation, log,+ label: async () => String((await local.json("/api/cloud-connections").catch(() => null))?.computer?.label ?? "") });home = createOneHome({journal,t,+ lease,// Every run starts here: the key watch is set up before any wait asks, so a key pressed since then counts.cloud: () => {typed();diff --git a/electron/one-home.d.mts b/electron/one-home.d.mtsindex 125d233587..217b99ecf3 100644--- a/electron/one-home.d.mts+++ b/electron/one-home.d.mts@@ -5,17 +5,25 @@ export type OneHomeView = OneHomePhase & { place?: string };export type OneHomeNotCarried = { label: string; error: string };/** Why the move fails, including the server's error code and parameters when provided. */export type OneHomeFailing = { error: string | null; errorKey?: string; errorParams?: Record<string, string | number>; items?: OneHomeNotCarried[] };+/** How far the check of what arrived is. */+export type OneHomeChecking = { step: "manifest" | "files" | "chats" | "attachments" | "credentials" | (string & {}); done: number; total: number; bots: number };+/** My Cloud did not answer, and is asked again at `until`. */+export type OneHomeSlow = { until: number };+/** Another computer moves into the same Cloud now, by its name ("" when it gave none): this one waits for it. */+export type OneHomeQueued = { name: string };/** A connector that stayed on this computer. */export type OneHomeStayed = { name: string; needs?: string };type OneHomePhase =/** `chats`: conversations gone of those to go; `failing`: it has failed for a day, or its check found things missing pass* after pass, with why and what did not go; `updating`: My Cloud is too old* to take a move and updates first. */- | { phase: "copy"; chats?: { done: number; total: number }; failing?: OneHomeFailing; updating?: true }+ | { phase: "copy"; chats?: { done: number; total: number }; failing?: OneHomeFailing; updating?: true; slow?: OneHomeSlow; queued?: OneHomeQueued }/** `waitingFor`: the bot or room whose work holds the move ("" when it has no name), and `waitingWhat` what it is;* neither while it waits for a quiet moment or has not asked yet. */- | { phase: "wait"; waitingFor?: string; waitingWhat?: "bot" | "room" | "sign-in"; failing?: OneHomeFailing }- | { phase: "finishing"; failing?: OneHomeFailing }+ | { phase: "wait"; waitingFor?: string; waitingWhat?: "bot" | "room" | "sign-in"; failing?: OneHomeFailing; queued?: OneHomeQueued }+ /** `checking`: the check of what arrived, at its step (`manifest`, `files`, `chats`, `attachments`, `credentials`), with+ * `done` of `total` there and how many bots it checks. */+ | { phase: "finishing"; checking?: OneHomeChecking; slow?: OneHomeSlow; failing?: OneHomeFailing }/** What arrived, checked on both sides; `at`: when the move was done; `phone`: a phone was paired with this computer; `held`: keys a trial's Cloud keeps unused while its Claude credit lasts; `left`: what My Cloud refused for good, which stayed where it was; `stayed`: connectors that work only on this computer (`needs`: a program My Cloud lacks). */| { phase: "done"; at?: number; counts?: OneHomeCounts; phone: boolean; held: string[]; left?: OneHomeNotCarried[]; stayed?: OneHomeStayed[] }/** This computer's bots are on their way home from a My Cloud that goes on, because the person keeps them here;@@ -50,6 +58,8 @@ export declare const QUIET_MS: number;export declare const CHECK_PASSES: number;export declare const FROZEN_RETRY_MS: number;export declare const COPY_RETRY_MS: number[];+export declare const CHECK_RESUME_MS: number;+export declare const QUEUE_POLL_MS: number;export declare const FAILING_LINE_MS: number;export declare const KEPT_MS: number;export function parseJournal(value: unknown): Record<string, any> | null;@@ -87,6 +97,8 @@ export function createOneHome(deps: {session(): Promise<{ call(method: string, route: string, body?: unknown): Promise<Answer>; close(): Promise<void> }>;/** My Cloud's session is no longer needed: the move is done, paused, or not this account's. */release?(): Promise<void>;+ /** One computer at a time runs the heavy part of a move into My Cloud: `take()` is null once this one does, else who does. */+ lease?: { take(): Promise<null | { name: string }>; release(): Promise<void> };lend?(projects: string[]): Promise<unknown>;phone?: { paired(): boolean; stop(): Promise<void>; start(): Promise<void> };openHome?(): void;diff --git a/electron/one-home.mjs b/electron/one-home.mjsindex de0d794283..4f002e3cf8 100644--- a/electron/one-home.mjs+++ b/electron/one-home.mjs@@ -50,6 +50,10 @@ export const FROZEN_RETRY_MAX_MS = 12 * HOUR;export const INCOMPLETE = "Some things didn't reach My Cloud yet. It tries again by itself, and if they still can't go, the rest moves without them and you'll see what stayed here.";/** A failure before the freeze (no network, My Cloud asleep or updating): tried again sooner at first, then hourly. */export const COPY_RETRY_MS = [2 * MINUTE, 5 * MINUTE, 15 * MINUTE, 30 * MINUTE, HOUR];+/** A check My Cloud stopped answering after it got somewhere goes on from there this soon: nothing it did is done again. */+export const CHECK_RESUME_MS = 5 * MINUTE;+/** How often a move that waits for another computer's move into the same Cloud asks again. */+export const QUEUE_POLL_MS = MINUTE;export const FAILING_LINE_MS = DAY;/** At most this many of the things a move could not carry are named on its line. */const NAMED_MAX = 5;@@ -171,6 +175,7 @@ export function arrivedCounts(here, there) {* gone?(origin: string): Promise<"deleted" | "ended" | null>,* session(): Promise<{ call(method: string, route: string, body?: unknown): Promise<{ ok: boolean, status: number, body: any }>, close(): Promise<void> }>,* release?(): Promise<void>,+ * lease?: { take(): Promise<null | { name: string }>, release(): Promise<void> },* lend?(projects: string[]): Promise<unknown>,* phone?: { paired(): boolean, start(): Promise<void> },* openHome?(): void,@@ -192,7 +197,8 @@ export function arrivedCounts(here, there) {* t?(key: string, params?: Record<string, string | number>): string,* }} deps `gone(origin)`: the Admin's word that this account's Cloud at `origin` is gone ("deleted", or "ended": stopped* and kept only until it is deleted); null for anything else, and while it can't be asked. `cloud().verified`: the Admin- * answered this sign-in just now (connected). `local.marker()`: this computer's freeze marker.+ * answered this sign-in just now (connected). `local.marker()`: this computer's freeze marker. `lease`: one computer at a+ * time runs the heavy part of a move into My Cloud (move-lease.mjs); `take()` is null once this one does, else who does.*/export function createOneHome(deps) {const now = deps.now ?? Date.now;@@ -203,6 +209,8 @@ export function createOneHome(deps) {/** What the last run found holding the move that only a run can find out; `heldOff`, a first move waits for this* computer's own copy, said once in the log. */let noted = null, heldOff = false;+ /** The other computer whose move into the same Cloud this one waits for (`deps.lease`), by its name ("" without one). */+ let queuedFor = null;const read = () => parseJournal(deps.journal.read());const kept = () => { try { return parseKeep(deps.keep?.read()).on; } catch { return false; } };@@ -250,7 +258,12 @@ export function createOneHome(deps) {const items = failing ? notCarried(sent, false) : [];const phase = FROZEN.has(journal.phase) || journal.phase === "switch" ? "finishing" : journal.phase;const waits = phase === "wait" && waitingFor !== null ? { waitingFor, ...(waitingWhat ? { waitingWhat } : {}) } : {};- return { phase, ...(chats ? { chats } : {}), ...waits, ...(failing ? { failing: { ...failing, ...(items.length ? { items } : {}) } } : {}) };+ const checking = journal.phase === "check" ? checkingOf(sent?.checking) : null;+ // My Cloud did not answer: when it is asked again, said at once rather than after a day of failing.+ const slowUntil = checking?.until ?? (journal.phase === "copy" && journal.failure?.code === "unanswered" && journal.retryAt > now() ? journal.retryAt : null);+ return { phase, ...(chats ? { chats } : {}), ...waits, ...(checking ? { checking: { step: checking.step, done: checking.done, total: checking.total, bots: checking.bots } } : {}),+ ...(slowUntil && !failing ? { slow: { until: slowUntil } } : {}), ...(queuedFor !== null && (phase === "copy" || phase === "wait") ? { queued: { name: queuedFor } } : {}),+ ...(failing ? { failing: { ...failing, ...(items.length ? { items } : {}) } } : {}) };}/** What the last whole pass could not carry, each with why: all of it while the move is failing, only what My Cloud@@ -261,6 +274,28 @@ export function createOneHome(deps) {.slice(0, NAMED_MAX).map((entry) => ({ label: entry.label, error: sentence(entry.error) ?? t("native.home.itemDidNotMove") }));}+ /** How far the check is (cloud-send-check.mjs `moveCheck`), kept to its known shape. */+ function checkingOf(value) {+ if (!record(value) || typeof value.step !== "string") return null;+ const count = (number) => (Number.isSafeInteger(number) && number >= 0 ? number : 0);+ return { step: value.step, done: count(value.done), total: count(value.total), bots: count(value.bots), ...(Number.isSafeInteger(value.until) && value.until > now() ? { until: value.until } : {}) };+ }++ /** True when another computer's move into the same Cloud runs its heavy part now: this one asks again in a minute.+ * Without a lease (an older Cloud, or none given), nothing waits. */+ async function queued() {+ let other = null;+ try { other = await deps.lease?.take() ?? null; } catch (error) { log(`one home: could not ask My Cloud which computer moves now (${error?.message ?? error})`); }+ if (!other) { if (queuedFor !== null) { queuedFor = null; publish(); } return false; }+ if (queuedFor === null) log("one home: another computer is moving into My Cloud; this one waits for it");+ queuedFor = typeof other.name === "string" ? other.name : "";+ publish();+ later(QUEUE_POLL_MS);+ return true;+ }++ const letGo = () => deps.lease?.release().catch(() => {});+/** Lifts this computer's freeze; true once it is lifted. */async function thaw(journal) {try { await deps.local.unfreeze(); } catch (error) { noted = "thaw_failed"; log(`one home: could not lift the freeze yet (${error?.message ?? error})`); later(MINUTE); return false; }@@ -274,10 +309,13 @@ 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;- const hourly = frozen && !rateLimited(error);+ // 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;+ const hourly = frozen && !rateLimited(error) && !resumes;const frozenTries = hourly ? (journal.frozenTries ?? 0) + 1 : journal.frozenTries;- const wait = hourly ? Math.min(FROZEN_RETRY_MAX_MS, FROZEN_RETRY_MS * 2 ** Math.min(frozenTries - 1, 8)) : COPY_RETRY_MS[Math.min(tries - 1, COPY_RETRY_MS.length - 1)];+ const wait = resumes ? CHECK_RESUME_MS : hourly ? Math.min(FROZEN_RETRY_MAX_MS, FROZEN_RETRY_MS * 2 ** Math.min(frozenTries - 1, 8)) : COPY_RETRY_MS[Math.min(tries - 1, COPY_RETRY_MS.length - 1)];// A check's gaps are kept by key, so the next check can tell whether sending again carried any of them.const next = write({ ...journal, phase: "copy", passes: 0, tries, frozenTries, error: said, ...errorText(error), failingSince: journal.failingSince ?? now(), failure: failureOf(error, journal.phase, journal.failure, now()),gapKey: typeof error?.gapKey === "string" ? error.gapKey : undefined, gaps: typeof error?.gaps === "string" ? error.gaps : undefined,@@ -288,8 +326,10 @@ export function createOneHome(deps) {async function copy(journal) {waitingFor = waitingWhat = null;+ if (await queued()) return null;try { await deps.send.move(); }- catch (error) { return error?.code === "outdated" ? updating(journal, error) : failed({ ...journal, updating: undefined }, error, false); }+ catch (error) { return error?.code === "outdated" ? (await letGo(), updating(journal, error)) : failed({ ...journal, updating: undefined }, error, false); }+ await letGo();return write({ ...journal, phase: "wait", retryAt: undefined, hourly: undefined, updating: undefined });}@@ -305,6 +345,8 @@ export function createOneHome(deps) {async function wait(journal) {const quietFor = now() - (deps.lastInput?.() ?? 0);if (quietFor < QUIET_MS) { noted = "waiting_quiet"; later(QUIET_MS - quietFor); return null; }+ // The finish, from the freeze to the switch, is one heavy part: asked for before anything stops here, and held to the end.+ if (await queued()) return null;// The journal says "freeze" before the server is frozen: a crash in between resumes frozen, never forgotten.return freeze(write({ ...journal, phase: "freeze" }));}@@ -318,6 +360,7 @@ export function createOneHome(deps) {// hour (server/move-waits.ts), so this poll ends by itself.waitingFor = answer.busy;waitingWhat = typeof answer.what === "string" ? answer.what : null;+ await letGo();write({ ...journal, phase: "wait" });later(BUSY_POLL_MS);return null;@@ -327,6 +370,8 @@ export function createOneHome(deps) {}async function final(journal) {+ // Held since the freeze; asked again only for an app that started again frozen, which never waits for it here.+ await deps.lease?.take().catch(() => null);try { await deps.send.move({ final: true }); }catch (error) { return failed(journal, error, true); }return write({ ...journal, phase: "check", passes: 1 });@@ -389,7 +434,7 @@ export function createOneHome(deps) {const next = write({ ...journal, switched, error: sentence(error?.message) ?? undefined, ...errorText(error), retryAt: now() + 2 * MINUTE, failure: failureOf(error, "switch", journal.failure, now()) });later(next.retryAt - now());return null;- } finally { await session?.close().catch(() => {}); }+ } finally { await session?.close().catch(() => {}); await letGo(); }const sent = deps.send.snapshot?.();const held = (sent?.whole?.result?.notes ?? []).filter((note) => note?.kind === "held" && typeof note.connection === "string").map((note) => note.connection);const left = [...notCarried(sent, true), ...(Array.isArray(journal.stuck) ? journal.stuck : [])];@@ -718,7 +763,8 @@ export function createOneHome(deps) {else break;}const after = read();- if (after?.phase === "copy" && after.retryAt) later(after.retryAt - now());+ // Not one already past: a copy that waits for another computer asks again on its own clock (queued).+ if (after?.phase === "copy" && after.retryAt > now()) later(after.retryAt - now());}/** Goes on from where the journal is: at launch, on account changes and when a wait is over. One run at a time. */@@ -731,7 +777,7 @@ export function createOneHome(deps) {try { await run(); } catch (error) { log(`one home: ${error?.message ?? error}`); later(MINUTE); }} while (again && !closed);const journal = read();- if (!journal || journal.paused || !MOVING.has(journal.phase)) await deps.release?.();+ if (!journal || journal.paused || !MOVING.has(journal.phase)) { await letGo(); await deps.release?.(); }})().finally(() => { running = null; publish(); });return running;}diff --git a/electron/own-home-main.mjs b/electron/own-home-main.mjsindex 25281f3ede..90c8d540d2 100644--- a/electron/own-home-main.mjs+++ b/electron/own-home-main.mjs@@ -46,13 +46,15 @@ export const handSaved = (entry) => record(entry) && entry.kind === "remote" &&* @param {typeof fetch} fetchImpl*/export function serverRequests(place, fetchImpl) {- const request = (method, route, init = {}) => fetchImpl(`${place.origin}${route}`, {- method, redirect: "error", credentials: "include", cache: "no-store", signal: AbortSignal.timeout(120_000), ...init,+ const request = (method, route, { timeoutMs = 120_000, ...init } = {}) => fetchImpl(`${place.origin}${route}`, {+ method, redirect: "error", credentials: "include", cache: "no-store", signal: AbortSignal.timeout(timeoutMs), ...init,headers: { accept: "application/json", origin: place.origin, ...init.headers },});return {request,- call: async (method, route, body) => answer(await request(method, route, body === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) })),+ /** `timeoutMs`: how long this request may take, sized to the work it asks for. */+ call: async (method, route, body, options) => answer(await request(method, route, { ...(options?.timeoutMs ? { timeoutMs: options.timeoutMs } : {}),+ ...(body === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }) })),async who() {const [session, described] = await Promise.all([request("GET", "/api/auth/session").then(answer), request("GET", "/.well-known/openmausbot/environment").then(answer)]);const signedIn = session.ok && session.body?.kind === "session";@@ -120,7 +122,7 @@ export function installOwnHome({ localRequest, fetch: fetchImpl, environments, h},};const send = createCloudSend({- local: (route, init) => localRequest(route, { method: init?.method ?? "GET", signal: AbortSignal.timeout(30_000) }),+ local: (route, init) => localRequest(route, { method: init?.method ?? "GET", signal: AbortSignal.timeout(init?.timeoutMs ?? 30_000) }),cloud: {origin: () => chosen()?.origin ?? null,asleep: () => false,diff --git a/server/cloud-send-big.test.ts b/server/cloud-send-big.test.tsnew file mode 100644index 0000000000..6da1adad69--- /dev/null+++ b/server/cloud-send-big.test.ts@@ -0,0 +1,113 @@+// What a move asks of a big workspace's server: 100 bots and thousands of conversations with attachments. Its check reads+// conversations straight from messages.db, never parsing one through the store (which keeps every conversation it parsed+// in memory for ten minutes, more than a 2 GB Cloud holds), and its answers are the ones a full read gives.+import { beforeAll, describe, expect, it } from "vitest";++import { activePath, attachmentNames } from "./cloud-chat-merge.ts";+import { chatIds, stampHeld, verifyChats } from "./cloud-send-chats.ts";+import { cloudSendManifest } from "./cloud-send-manifest.ts";+import { attachmentNamesOf, linkedPath, threadLinks } from "./cloud-send-rows.ts";+import { DATA_DIR } from "./config.ts";+import { deleteThread, threadHeads } from "./message-db.ts";+import { Store, type Message } from "./store.ts";++const BOTS = 100, TASKS = 20, ROWS = 12;++/** The store, with every read of a whole conversation through it counted. */+function counted(store: Store) {+ const reads = { messagesFor: 0 };+ const wrapped = new Proxy(store, {+ get(target, key, receiver) {+ if (key === "messagesFor") return (threadId: string) => { reads.messagesFor++; return target.messagesFor(threadId); };+ const value = Reflect.get(target, key, receiver);+ return typeof value === "function" ? value.bind(target) : value;+ },+ });+ return { store: wrapped, reads };+}++/** 100 bots with 20 conversations each, 12 rows to a conversation, every fourth line with a stored attachment; a few rows+ * stored without a parent, as an old app stored them. */+function bigWorkspace() {+ const store = new Store(() => ({ instanceId: "fixture", model: "fixture-model" }));+ const threads: string[] = [];+ let at = 1_000, attachment = 0;+ for (let b = 0; b < BOTS; b++) {+ const bot = store.createBot({ name: `Bot ${b}` }, { seedMessages: false });+ const conversations = [bot.threadId, ...Array.from({ length: TASKS - 1 }, (_, i) => store.createTask(bot.id, `Task ${i}`, false)!.threadId)];+ for (const threadId of conversations) {+ const rows: Message[] = [];+ for (let r = 0; r < ROWS; r++) {+ const id = `${threadId}-m${r}`;+ const named = r % 4 === 0 ? { attachments: [{ path: `${DATA_DIR}/attachments/${String(attachment++).padStart(8, "0")}-big.png`, name: "shot.png", mimeType: "image/png" }] } : {};+ const legacy = b === 7 && r > 0;+ rows.push({ id, at: at++, role: r % 2 ? "bot" : "user", kind: "text", text: `line ${r}`, ...(legacy ? {} : { parentId: r ? `${threadId}-m${r - 1}` : null }), ...named } as Message);+ }+ store.importTranscript(threadId, rows, rows.at(-1)!.id);+ threads.push(threadId);+ }+ }+ return { store, threads };+}++describe("a move's check of a big workspace", () => {+ let base: Store, threads: string[];+ beforeAll(() => { ({ store: base, threads } = bigWorkspace()); }, 120_000);++ it("lists the attachments only from rows that name one, as reading every row does", () => {+ const full = new Set<string>();+ for (const threadId of threads) for (const row of base.messagesFor(threadId)) for (const name of attachmentNames(row, DATA_DIR)) full.add(name);+ expect(full.size).toBe(BOTS * TASKS * (ROWS / 4));+ expect(attachmentNamesOf(new Set(threads), DATA_DIR)).toEqual(full);+ expect(attachmentNamesOf(new Set(threads.slice(0, 1)), DATA_DIR).size).toBe(ROWS / 4);+ });++ it("reads a conversation's ids and path as the store does, rows stored without a parent included", () => {+ for (const threadId of [threads[0]!, threads[7 * TASKS]!, threads[7 * TASKS + 3]!]) {+ const links = threadLinks(threadId)!;+ expect(links.ids).toEqual(base.messagesFor(threadId).map((row) => row.id));+ expect(linkedPath(links)).toEqual(activePath(base.messagesFor(threadId), base.activeLeaf(threadId)).map((row) => row.id));+ }+ });++ it("answers My Cloud's manifest without the attachments and files the check never needs, and reads no conversation through the store", async () => {+ const { store, reads } = counted(base);+ const manifest = await cloudSendManifest({ summary: () => ({ v: 1, appVersion: "0", items: [] }), store, dataDir: DATA_DIR, connections: async () => [], heads: threadHeads,+ attachments: false, files: false });+ expect(manifest.conversations).toHaveLength(BOTS * TASKS);+ expect(manifest.attachments).toBeUndefined();+ expect(manifest.files).toBeUndefined();+ 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);+ });++ it("checks 200 conversations in one request without parsing any through the store, and finds what is missing", () => {+ const { store, reads } = counted(base);+ const asked = threads.slice(0, 200).map((threadId) => {+ const ids = chatIds({ store, dataDir: DATA_DIR }, threadId, 0)!;+ return { threadId, ids: threadId === threads[5] ? [...ids.ids, "gone-1"] : ids.ids, path: { after: null, ids: ids.path, last: true } };+ });+ const answers = verifyChats(store, asked);+ expect(reads.messagesFor).toBe(0);+ expect(answers.filter((entry) => entry.missing.length)).toEqual([expect.objectContaining({ threadId: threads[5], missing: ["gone-1"] })]);+ expect(answers.every((entry) => entry.path?.holds === true && entry.path.length === ROWS)).toBe(true);+ expect(answers[0]!.unstamped, "the owner's own lines that do not carry the owner yet").toBe(ROWS / 2);+ });++ it("stamps the owner's lines it holds reading only those rows, and a conversation it lacks is skipped", () => {+ const { store, reads } = counted(base);+ const threadId = threads[1]!;+ const { stamped } = stampHeld(store, [{ threadId, ids: threadLinks(threadId)!.ids }, { threadId: "t-nobody", ids: ["x"] }], { person: "p_owner", name: "Ada" });+ expect(stamped).toBe(ROWS / 2);+ expect(verifyChats(store, [{ threadId, ids: threadLinks(threadId)!.ids }])[0]!.unstamped).toBe(0);+ expect(reads.messagesFor, "only to patch the rows it stamped").toBeLessThanOrEqual(ROWS / 2);+ });++ it("a conversation messages.db has no row of reads as the store holds it", () => {+ const threadId = threads.at(-1)!;+ deleteThread(threadId);+ expect(threadLinks(threadId)).toBeNull();+ expect(verifyChats(base, [{ threadId, ids: ["a"] }])[0]!.missing).toEqual(["a"]);+ });+});diff --git a/server/cloud-send-chats.ts b/server/cloud-send-chats.tsindex 3ca7f5b862..c6fbf1ca5c 100644--- a/server/cloud-send-chats.ts+++ b/server/cloud-send-chats.ts@@ -13,9 +13,10 @@ import type { ApprovalMode } from "../shared/approval-mode.ts";import type { BotVisibility, ModelSelection } from "../shared/wire.ts";import { ATTACHMENTS_DIR, FILE_MAX_BYTES, saveNamedAttachment } from "./attachments.ts";import { audienceEquals, narrowestAudience } from "./bot-visibility.ts";-import { activePath, addSentChats, attachmentNames, ATTACHMENT_NAME, type ChatStore, type SentConversation, type SentRoom } from "./cloud-chat-merge.ts";+import { addSentChats, attachmentNames, ATTACHMENT_NAME, type ChatStore, type SentConversation, type SentRoom } from "./cloud-chat-merge.ts";import { threadHeads, threadRowNumbers, threadRowsFrom } from "./message-db.ts";import { ownerStamp, unstamped, type CloudOwner } from "./cloud-owner-lines.ts";+import { attachmentNamesOf, linkedPath, linksOf, storedRows, threadLinks, type ThreadLinks } from "./cloud-send-rows.ts";import type { RequestAuth } from "./request-auth.ts";import type { RouteContext } from "./routes/table.ts";import type { BotRecord, GroupRecord, GroupTaskRecord, Message, Store, TaskPatch, TaskRecord } from "./store.ts";@@ -149,9 +150,8 @@ export function conversationSettings(store: Pick<ChatStore, "bot" | "group">, he}/** Each stored attachment the conversations' rows name, with its size. */-async function attachmentSizes(store: ChatStore, dataDir: string, heads: readonly ChatHead[]): Promise<Array<{ name: string; size: number }>> {- const names = new Set<string>();- for (const head of heads) for (const row of store.messagesFor(head.threadId)) for (const name of attachmentNames(row, dataDir)) names.add(name);+async function attachmentSizes(dataDir: string, heads: readonly ChatHead[]): Promise<Array<{ name: string; size: number }>> {+ const names = attachmentNamesOf(new Set(heads.map((head) => head.threadId)), dataDir);const out: Array<{ name: string; size: number }> = [];for (const name of names) {const info = await lstat(join(ATTACHMENTS_DIR, name)).catch(() => null);@@ -246,11 +246,22 @@ const ownerOf = (store: Pick<ChatStore, "bots" | "groups">, threadId: string) =>return { bot, room: bot ? undefined : store.groups.find((candidate) => roomThreads(candidate).includes(threadId)) };};+/** ownerOf for every conversation at once, for a request about many of them. */+function ownerIndex(store: Pick<ChatStore, "bots" | "groups">): Map<string, { bot?: BotRecord; room?: Room }> {+ const index = new Map<string, { bot?: BotRecord; room?: Room }>();+ for (const bot of store.bots) for (const threadId of [bot.threadId, ...(bot.tasks ?? []).map((task) => task.threadId)]) if (!index.has(threadId)) index.set(threadId, { bot });+ for (const room of store.groups) for (const threadId of roomThreads(room)) if (!index.has(threadId)) index.set(threadId, { room });+ return index;+}++/** A conversation's links as messages.db holds them, or as the store holds a conversation messages.db has no row of. */+const linksFor = (store: Pick<ChatStore, "messagesFor" | "activeLeaf">, threadId: string): ThreadLinks => threadLinks(threadId) ?? linksOf(store.messagesFor(threadId), store.activeLeaf(threadId));+/** A conversation's rows after a point, a page at a time, as main sends them on; null when no bot or room here has it. */export function chatPage({ store, dataDir }: CloudSendChatsDeps, threadId: string, after: number, afterId: string | null) {const { bot, room } = ownerOf(store, threadId);if ((!bot && !room) || !Number.isSafeInteger(after) || after < 0) return null;- const path = activePath(store.messagesFor(threadId), store.activeLeaf(threadId)).map((row) => row.id);+ const path = linkedPath(linksFor(store, threadId));const page = threadRowsAfter(threadId, after, afterId, CHAT_ROWS_PAGE, CHAT_PAGE_BYTES, path);const task = bot ? taskOf(bot, threadId) : room!.tasks?.find((candidate) => candidate.threadId === threadId) ?? null;const owner = bot ? { bot: bot.id, task: task ? sentTask(task as TaskRecord) : null }@@ -264,10 +275,10 @@ export function chatPage({ store, dataDir }: CloudSendChatsDeps, threadId: strinexport function chatIds({ store }: CloudSendChatsDeps, threadId: string, from: number) {const { bot, room } = ownerOf(store, threadId);if ((!bot && !room) || !Number.isSafeInteger(from) || from < 0) return null;- const rows = store.messagesFor(threadId);- const path = activePath(rows, store.activeLeaf(threadId)).map((row) => row.id);- return { v: 1, ids: rows.slice(from, from + VERIFY_IDS).map((row) => row.id), path: path.slice(from, from + VERIFY_IDS), leaf: path.at(-1) ?? null,- more: from + VERIFY_IDS < Math.max(rows.length, path.length) };+ const links = linksFor(store, threadId);+ const path = linkedPath(links);+ return { v: 1, ids: links.ids.slice(from, from + VERIFY_IDS), path: path.slice(from, from + VERIFY_IDS), leaf: path.at(-1) ?? null,+ more: from + VERIFY_IDS < Math.max(links.ids.length, path.length) };}/** Whether `ids` appear in this order on `path` after the row `after` (from its start when null), and the last of them@@ -296,12 +307,13 @@ const idsSchema = z.object({export function stampHeld(store: CloudSendChatsDeps["store"], conversations: ReadonlyArray<{ threadId: string; ids: readonly string[] }>, owner: CloudOwner): { stamped: number; threads: string[] } {let stamped = 0;const threads = new Set<string>();+ const owners = ownerIndex(store);for (const { threadId, ids } of conversations) {- const where = ownerOf(store, threadId);- if (!where.bot && !where.room) continue;+ if (!owners.has(threadId)) continue;const named = new Set(ids);- for (const row of store.messagesFor(threadId)) {- const stamp = named.has(row.id) ? ownerStamp(row, owner) : null;+ const rows = threadLinks(threadId) ? storedRows(threadId, [...named], { owners: true }) : store.messagesFor(threadId).filter((row) => named.has(row.id));+ for (const row of rows) {+ const stamp = ownerStamp(row, owner);if (!stamp || !store.patchMessage(threadId, row.id, stamp)) continue;stamped++;threads.add(threadId);@@ -324,13 +336,15 @@ const verifySchema = z.object({* (a conversation both sides added to weaves the two together). The last chunk of a path also gets My Cloud's leaf and* path length, so the sender can tell an equal path from one that holds inside a longer one. Ids only, never a row. */export function verifyChats(store: ChatStore, conversations: z.infer<typeof verifySchema>["conversations"]) {- return conversations.map(({ threadId, ids, path }) => {- const rows = store.messagesFor(threadId);- const byId = new Map(rows.map((row) => [row.id, row]));- const bot = Boolean(ownerOf(store, threadId).bot);- const visible = path ? activePath(rows, store.activeLeaf(threadId)).map((row) => row.id) : [];- return { threadId, missing: (ids ?? []).filter((id) => !byId.has(id)),- unstamped: bot ? (ids ?? []).filter((id) => { const row = byId.get(id); return row !== undefined && unstamped(row); }).length : 0,+ const owners = ownerIndex(store);+ return conversations.map(({ threadId, ids = [], path }) => {+ const stored = threadLinks(threadId);+ const links = stored ?? linksOf(store.messagesFor(threadId), store.activeLeaf(threadId));+ const held = new Set(ids.filter((id) => links.parent.has(id)));+ const rows = !owners.get(threadId)?.bot || !held.size ? [] : stored ? storedRows(threadId, [...held], { owners: true })+ : store.messagesFor(threadId).filter((row) => held.has(row.id));+ const visible = path ? linkedPath(links) : [];+ return { threadId, missing: ids.filter((id) => !links.parent.has(id)), unstamped: rows.filter((row) => unstamped(row)).length,...(path ? { path: { ...inOrder(visible, path.after, path.ids), ...(path.last ? { leaf: visible.at(-1) ?? null, length: visible.length } : {}) } } : {}) };});}@@ -345,7 +359,7 @@ export async function cloudSendChatsRoute(deps: CloudSendChatsDeps, { req, res,const heads = deps.bot ? chatHeads(store.bots.filter((bot) => bot.id === deps.bot), []) : chatHeads(store.bots, store.groups);json(res, 200, { v: 1, dataDir: deps.dataDir, ...(deps.bot && deps.ownerKey ? { owner: deps.ownerKey } : {}), conversations: heads.map((head) => ({ ...head, settings: conversationSettings(store, head) })),rooms: deps.bot ? [] : emptyRooms(store.groups, heads),- ...(url.searchParams.get("attachments") === "1" ? { attachments: await attachmentSizes(store, deps.dataDir, heads) } : {}) });+ ...(url.searchParams.get("attachments") === "1" ? { attachments: await attachmentSizes(deps.dataDir, heads) } : {}) });return true;}if (path === `${PREFIX}/settings` && method === "POST") {diff --git a/server/cloud-send-files.ts b/server/cloud-send-files.tsindex f1c6983ff7..0a55ef69fa 100644--- a/server/cloud-send-files.ts+++ b/server/cloud-send-files.ts@@ -48,7 +48,8 @@ async function fileSha256(full: string, size: number, mtimeMs: number): Promise<const hash = createHash("sha256");for await (const chunk of createReadStream(full)) hash.update(chunk as Buffer);const digest = hash.digest("hex");- if (hashes.size > 50_000) hashes.clear();+ // As many as one listing holds, oldest out first: a listing never pushes out what it hashed itself.+ if (hashes.size >= MAX_FILES) hashes.delete(hashes.keys().next().value!);hashes.set(key, digest);return digest;}diff --git a/server/cloud-send-lease.test.ts b/server/cloud-send-lease.test.tsnew file mode 100644index 0000000000..aa68d336ef--- /dev/null+++ b/server/cloud-send-lease.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from "vitest";++import { createMoveLeases, LEASE_MS, moveLeaseRoute } from "./cloud-send-lease.ts";++function cloud(owner = true) {+ let clock = 1_000;+ const leases = createMoveLeases(() => clock);+ const ask = async (body: unknown, method = "POST") => {+ let answered: { status: number; body: any } | undefined;+ const handled = await moveLeaseRoute({ leases, owner: () => (owner ? { person: "p_owner", name: "Owner" } : null) }, {+ path: "/api/cloud-send/lease", method, req: { resume() {} } as never, res: { setHeader() {} } as never, auth: {} as never, url: new URL("http://x/"),+ json: (_res: unknown, status: number, value: unknown) => { answered = { status, body: value }; }, readBody: async () => body } as never);+ expect(handled).toBe(true);+ return answered!;+ };+ return { ask, leases, advance: (ms: number) => { clock += ms; }, now: () => clock };+}++describe("POST /api/cloud-send/lease", () => {+ it("lets one computer at a time move in: the other hears who moves now, and goes once that one lets go", async () => {+ const { ask } = cloud();+ expect(await ask({ v: 1, holder: "computer-mac", label: "Mac" })).toEqual({ status: 200, body: { v: 1, held: true, until: 1_000 + LEASE_MS } });+ expect(await ask({ v: 1, holder: "computer-nuc", label: "NUC" })).toEqual({ status: 409, body: { v: 1, held: false, label: "Mac", until: 1_000 + LEASE_MS } });+ expect((await ask({ v: 1, holder: "computer-mac", label: "" })).status, "the holder asks again as it goes on").toBe(200);+ expect((await ask({ v: 1, holder: "computer-nuc", label: "NUC" })).body.label, "and keeps its name").toBe("Mac");+ expect(await ask({ v: 1, holder: "computer-nuc", release: true })).toEqual({ status: 200, body: { v: 1, held: false } });+ expect((await ask({ v: 1, holder: "computer-nuc", label: "NUC" })).status, "only the holder lets go").toBe(409);+ await ask({ v: 1, holder: "computer-mac", release: true });+ expect((await ask({ v: 1, holder: "computer-nuc", label: "NUC" })).status).toBe(200);+ });++ it("runs out when its computer stops asking, as an app that quit does", async () => {+ const { ask, advance } = cloud();+ await ask({ v: 1, holder: "computer-mac", label: "Mac" });+ advance(LEASE_MS - 1);+ expect((await ask({ v: 1, holder: "computer-nuc", label: "NUC" })).status).toBe(409);+ advance(1);+ expect((await ask({ v: 1, holder: "computer-nuc", label: "NUC" })).status).toBe(200);+ });++ it("answers only My Cloud's owner, and only a well-formed ask", async () => {+ expect((await cloud(false).ask({ v: 1, holder: "computer-mac" })).status).toBe(403);+ const { ask } = cloud();+ expect((await ask({ v: 1, holder: "x" })).status).toBe(400);+ expect((await ask({ v: 1, holder: "computer-mac" }, "GET")).status).toBe(405);+ });+});diff --git a/server/cloud-send-lease.ts b/server/cloud-send-lease.tsnew file mode 100644index 0000000000..a8008358cb--- /dev/null+++ b/server/cloud-send-lease.ts@@ -0,0 +1,53 @@+// POST /api/cloud-send/lease, on the person's own Cloud over the owner's own session: one computer at a time runs the heavy+// part of its move here (a pass that copies, or the finish from its freeze to its switch), so two computers moving into one+// Cloud never load it together and never check while the other writes. A computer asks before each such part, again+// every few minutes while it runs, and lets go at its end; one that quits lets go by the lease running out. Kept in memory:+// a Cloud that starts again holds none, and the next to ask gets it.+import { z } from "zod";++import type { CloudOwner } from "./cloud-owner-lines.ts";+import type { RequestAuth } from "./request-auth.ts";+import type { RouteContext } from "./routes/table.ts";++export const LEASE_MS = 10 * 60_000;++export interface MoveLease { holder: string; label: string; until: number }++const askSchema = z.object({+ v: z.literal(1),+ holder: z.string().regex(/^[\w-]{8,128}$/u),+ label: z.string().max(120).optional(),+ release: z.literal(true).optional(),+});++/** One Cloud's lease. `ask`: held by `holder` from now on (null), or who holds it. */+export function createMoveLeases(now: () => number = Date.now) {+ let held: MoveLease | null = null;+ return {+ ask(holder: string, label: string): MoveLease | null {+ if (held && held.holder !== holder && held.until > now()) return held;+ held = { holder, label: label || (held?.holder === holder ? held.label : ""), until: now() + LEASE_MS };+ return null;+ },+ release(holder: string): void { if (held?.holder === holder) held = null; },+ held: (): MoveLease | null => (held && held.until > now() ? held : null),+ };+}++export type MoveLeases = ReturnType<typeof createMoveLeases>;++/** False when the path is not this route. */+export async function moveLeaseRoute(deps: { leases: MoveLeases; owner(auth: RequestAuth): CloudOwner | null }, { req, res, path, method, auth, json, readBody }: RouteContext): Promise<boolean> {+ if (path !== "/api/cloud-send/lease") return false;+ res.setHeader("cache-control", "no-store");+ if (method !== "POST") { json(res, 405, { error: "method not allowed" }); return true; }+ if (!deps.owner(auth)) { req.resume(); json(res, 403, { error: "Only My Cloud's owner can move into it." }); return true; }+ const asked = askSchema.safeParse(await readBody(req, 4096));+ if (!asked.success) { json(res, 400, { error: "send { v: 1, holder, label }" }); return true; }+ const { holder, label = "", release } = asked.data;+ if (release) { deps.leases.release(holder); json(res, 200, { v: 1, held: false }); return true; }+ const other = deps.leases.ask(holder, label.trim());+ if (other) { json(res, 409, { v: 1, held: false, label: other.label, until: other.until }); return true; }+ json(res, 200, { v: 1, held: true, until: deps.leases.held()?.until ?? null });+ return true;+}diff --git a/server/cloud-send-manifest.ts b/server/cloud-send-manifest.tsindex 643999afc0..adc98f8943 100644--- a/server/cloud-send-manifest.ts+++ b/server/cloud-send-manifest.ts@@ -1,9 +1,10 @@// GET /api/cloud-send/manifest: everything of the person's this server holds that a move carries, by id with a// fingerprint per kind, on this computer and on their Cloud alike, so the desktop can check that a move carried it all.// Read only, never a secret: credentials are named here and checked by fingerprint (cloud-send-verify.ts).-import { attachmentNames, type ChatStore } from "./cloud-chat-merge.ts";+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 { 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";@@ -32,9 +33,10 @@ export interface CloudSendManifest {/** "mcp:<name>", "key:<provider>", "composio" or "email". */connections: string[];conversations: ManifestConversation[];- /** The stored attachments the conversations' rows name. */- attachments: string[];- files: BotFile[];+ /** The stored attachments the conversations' rows name; left out when not asked for. */+ attachments?: string[];+ /** Left out when not asked for: GET /api/cloud-send/files?bot= lists them a bot at a time. */+ files?: BotFile[];/** Each automation and whether it is on: the switch turns on there what was on here. */automations: Array<{ key: string; on: boolean }>;/** The routines' finished runs, by id with their routine's. */@@ -52,6 +54,9 @@ export interface ManifestSources {teamMemory?: Pick<TeamMemory, "list">;/** A move of this one bot into a team: what it carries only (its summary is already kept to it). */bot?: string;+ /** False: the attachments, or the bot files, are not listed (the desktop's check never reads My Cloud's attachments). */+ attachments?: boolean;+ files?: boolean;}function memoryOf(botId: string): CloudSendManifest["memory"] {@@ -69,11 +74,11 @@ export async function cloudSendManifest(sources: ManifestSources): Promise<CloudthreadId: head.threadId, ...(head.bot ? { bot: head.bot } : { room: head.room }), rows: counts.get(head.threadId)?.rows ?? 0, newest: head.lastId,settings: conversationSettings(store, head),}));- const attachments = new Set<string>();- for (const { threadId } of conversations) for (const row of store.messagesFor(threadId)) for (const name of attachmentNames(row, sources.dataDir)) attachments.add(name);+ const attachments = sources.attachments === false ? {} : { attachments: [...attachmentNamesOf(new Set(conversations.map((head) => head.threadId)), sources.dataDir)].sort() };+ const files = sources.files === false ? {} : { files: await listBotFiles(sources.dataDir, sent) };if (only !== undefined) {return { v: 1, appVersion: summary.appVersion, items: summary.items, memory: [], journal: [], learned: [], forgotten: [], teams: [], rooms: [], connections: [],- conversations, attachments: [...attachments].sort(), files: await listBotFiles(sources.dataDir, sent),+ conversations, ...attachments, ...files,automations: sources.kinds ? automationSwitches(sources.kinds, only) : [], runs: sources.kinds ? routineRunIds(sources.kinds, only) : [] };}return {@@ -90,8 +95,8 @@ export async function cloudSendManifest(sources: ManifestSources): Promise<Cloudthreads: room.tasks?.length ? room.tasks.map((task) => task.threadId) : [room.threadId] })),connections: (await sources.connections()).map((item) => item.id).sort(),conversations,- attachments: [...attachments].sort(),- files: await listBotFiles(sources.dataDir, sent),+ ...attachments,+ ...files,automations: sources.kinds ? automationSwitches(sources.kinds) : [],runs: sources.kinds ? routineRunIds(sources.kinds) : [],};diff --git a/server/cloud-send-rows.ts b/server/cloud-send-rows.tsnew file mode 100644index 0000000000..e02ff27521--- /dev/null+++ b/server/cloud-send-rows.ts@@ -0,0 +1,67 @@+// What a move reads of conversations without parsing every stored row or keeping it parsed in memory: a conversation's+// row ids and parents straight from messages.db, only the rows that can name an attachment, and only the rows asked for+// by id. A Cloud with thousands of conversations answers a move's check in bounded time and memory this way.+import { attachmentNames } from "./cloud-chat-merge.ts";+import { prepared } from "./message-db.ts";+import type { Message } from "./store.ts";++/** A conversation's rows, oldest first, each with its parent, and its active leaf. */+export interface ThreadLinks { ids: string[]; parent: Map<string, string | null>; leaf: string | null }++const BY_ID_CHUNK = 200;++/** As the store reads a conversation: a row stored without a parent follows the row before it, and the active leaf is+ * the newest row when none was kept. Null when messages.db holds no row of it. */+export function threadLinks(threadId: string): ThreadLinks | null {+ const rows = prepared("SELECT id, json_type(json, '$.parentId') AS type, json_extract(json, '$.parentId') AS parent FROM messages WHERE thread_id = ? ORDER BY rowid")+ .all(threadId) as Array<{ id: string; type: string | null; parent: unknown }>;+ if (!rows.length) return null;+ const ids: string[] = [], parent = new Map<string, string | null>();+ let previous: string | null = null;+ for (const row of rows) {+ ids.push(row.id);+ parent.set(row.id, row.type === null ? previous : typeof row.parent === "string" ? row.parent : null);+ previous = row.id;+ }+ const state = prepared("SELECT active_leaf_id FROM thread_state WHERE thread_id = ?").get(threadId) as { active_leaf_id: string | null } | undefined;+ return { ids, parent, leaf: state?.active_leaf_id || ids.at(-1) || null };+}++/** 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 };+}++/** The ids on the path from the root to the leaf. */+export function linkedPath(links: ThreadLinks): string[] {+ const path: string[] = [], seen = new Set<string>();+ for (let id = links.leaf; id !== null && links.parent.has(id) && !seen.has(id); id = links.parent.get(id) ?? null) {+ seen.add(id);+ path.push(id);+ }+ return path.reverse();+}++/** The stored rows of a conversation with these ids; `owners`: only those a person wrote or that carry a card. */+export function storedRows(threadId: string, ids: readonly string[], { owners = false } = {}): Message[] {+ const out: Message[] = [];+ const sql = `SELECT json FROM messages WHERE thread_id = ? AND id IN (${Array(BY_ID_CHUNK).fill("?").join(",")})${owners ? " AND (role = 'user' OR instr(json, '\"card\"') > 0)" : ""}`;+ for (let at = 0; at < ids.length; at += BY_ID_CHUNK) {+ const chunk = ids.slice(at, at + BY_ID_CHUNK);+ const padded = chunk.length < BY_ID_CHUNK ? [...chunk, ...Array<string>(BY_ID_CHUNK - chunk.length).fill("")] : chunk;+ for (const row of prepared(sql).all(threadId, ...padded) as Array<{ json: string }>) out.push(JSON.parse(row.json) as Message);+ }+ return out;+}++/** Each stored attachment the rows of these conversations name. Only a row whose stored JSON mentions an attachment is+ * parsed, one at a time. */+export function attachmentNamesOf(threadIds: ReadonlySet<string>, dataDir: string): Set<string> {+ const names = new Set<string>();+ const rows = prepared("SELECT thread_id AS threadId, json FROM messages WHERE instr(json, 'attachments') > 0 OR instr(json, '<attached-') > 0").iterate();+ for (const row of rows as Iterable<{ threadId: string; json: string }>) {+ if (!threadIds.has(row.threadId)) continue;+ for (const name of attachmentNames(JSON.parse(row.json) as Message, dataDir)) names.add(name);+ }+ return names;+}diff --git a/server/message-db.ts b/server/message-db.tsindex 8c74d95d38..eafea245cc 100644--- a/server/message-db.ts+++ b/server/message-db.ts@@ -167,7 +167,7 @@ function db(): DatabaseSync {}/** One prepared statement per SQL text for the life of the open database. */-function prepared(sql: string): StatementSync {+export function prepared(sql: string): StatementSync {const database = db();let statement = statements.get(sql);if (!statement) statements.set(sql, statement = database.prepare(sql));diff --git a/server/routes/cloud-send.ts b/server/routes/cloud-send.tsindex 02236da9ec..fcfb2ec35a 100644--- a/server/routes/cloud-send.ts+++ b/server/routes/cloud-send.ts@@ -3,7 +3,8 @@// carries, to check it by (server/cloud-send-manifest.ts); on a Cloud home, POST /api/cloud-send/verify-secrets: the// credentials' fingerprints (server/cloud-send-verify.ts); a move's own kinds, memory and bot files// (server/cloud-send-kinds.ts, cloud-send-memory.ts, cloud-send-files.ts), and what My Cloud keeps once a move is done and-// what this computer says once the bots came home (server/cloud-send-arrived.ts). Admin scope (request-auth's default):+// what this computer says once the bots came home (server/cloud-send-arrived.ts), and the lease that lets one computer at a+// time move in (server/cloud-send-lease.ts). Admin scope (request-auth's default):// the owner's app reads them on this computer and on their own Cloud.import { z } from "zod";@@ -11,6 +12,7 @@ import { botAvatarUrlSchema } from "../../shared/bot-avatar.ts";import { readAttachment } from "../attachments.ts";import { arrivedRoute, automationsOffRoute, homeRoute } from "../cloud-send-arrived.ts";import { moveFilesRoute } from "../cloud-send-files.ts";+import { createMoveLeases, moveLeaseRoute } from "../cloud-send-lease.ts";import { automatedBot, moveBotParts, moveItems, moveKindsRoute, type MoveKindsDeps } from "../cloud-send-kinds.ts";import { cloudSendManifest } from "../cloud-send-manifest.ts";import { moveMemoryRoute, type MoveMemoryDeps } from "../cloud-send-memory.ts";@@ -74,6 +76,7 @@ export function createCloudSendRoutes(deps: CloudSendRouteDeps): RouteHandler {...(deps.move ? { move: { items: (bots: ReadonlySet<string>, only?: BotRecord) => moveItems(deps.move!, bots, only), botParts: (bot: BotRecord) => moveBotParts(bot, partHash) } } : {}),};const move = deps.move;+ const leases = createMoveLeases();return async (ctx) => {const { req, res, path, method, url, json, readBody } = ctx;if (path !== "/api/cloud-send" && !path.startsWith("/api/cloud-send/")) return PASS;@@ -86,6 +89,7 @@ export function createCloudSendRoutes(deps: CloudSendRouteDeps): RouteHandler {if (move && await moveKindsRoute(move, ctx)) return;if (move && await moveMemoryRoute({ ...move, bot: (id) => move.store.bot(id) ?? undefined }, ctx)) return;if (move && await moveFilesRoute({ dataDir: move.dataDir, bots: () => (bot ? move.store.bots.filter((entry) => entry.id === bot) : move.store.bots), owner: move.owner }, ctx)) return;+ if (move && home && await moveLeaseRoute({ leases, owner: move.owner }, ctx)) return;if (move && home && await arrivedRoute({ dataDir: move.dataDir, store: move.store, webhooks: move.webhooks, owner: move.owner, lineLanguage: deps.lineLanguage ?? (() => deps.config().language), ...(deps.connectionsMoved ? { stayed: deps.connectionsMoved } : {}) }, ctx)) return;if (move && deps.cloudHome && deps.automations && await automationsOffRoute({ automations: deps.automations, owner: move.owner }, ctx)) return;if (move && !deps.cloudHome && await homeRoute({ dataDir: move.dataDir, store: move.store, webhooks: move.webhooks }, ctx)) return;@@ -94,7 +98,8 @@ export function createCloudSendRoutes(deps: CloudSendRouteDeps): RouteHandler {if (!deps.chats) return json(res, 404, { error: "not found" });res.setHeader("cache-control", "no-store");return json(res, 200, await cloudSendManifest({ summary: () => cloudSendSummary(sources, { move: true, ...(bot ? { bot } : {}) }), store: deps.chats.store, dataDir: deps.chats.dataDir,- connections: deps.connections ?? (async () => []), heads: threadHeads, ...(move ? { kinds: move, teamMemory: move.teamMemory } : {}), ...(bot ? { bot } : {}) }));+ connections: deps.connections ?? (async () => []), heads: threadHeads, ...(move ? { kinds: move, teamMemory: move.teamMemory } : {}), ...(bot ? { bot } : {}),+ attachments: url.searchParams.get("attachments") !== "0", files: url.searchParams.get("files") !== "0" }));}if (path === "/api/cloud-send/verify-secrets") {if (!home || !deps.connectionFingerprints) return json(res, 404, { error: "not found" });diff --git a/src/lib/cloud-send.test.ts b/src/lib/cloud-send.test.tsindex 158b7c64b3..ebcbb3265c 100644--- a/src/lib/cloud-send.test.ts+++ b/src/lib/cloud-send.test.ts@@ -21,6 +21,23 @@ describe("the one-time move's line", () => {expect(moveLine({ ...done, place: "Garage server", stayed: [{ name: "easy" }] }, "cloud")?.extra).toEqual(["easy: it only works on that computer, so bots here can't use it."]);});+ it("says how far the check of what arrived is, that My Cloud is slow and when it goes on, and which computer it waits for", () => {+ expect(moveLine({ phase: "finishing", checking: { step: "chats", done: 400, total: 1000, bots: 25 } }, "local")?.text).toBe("Moving to My Cloud… checking 25 bots' chats there, 40%");+ expect(moveLine({ phase: "finishing", checking: { step: "chats", done: 1, total: 3, bots: 1 } }, "local")?.text).toBe("Moving to My Cloud… checking your bot's chats there, 33%");+ expect(moveLine({ phase: "finishing", checking: { step: "files", done: 10, total: 100, bots: 25 } }, "local")?.text).toBe("Moving to My Cloud… checking your bots' files there, 10%");+ expect(moveLine({ phase: "finishing", checking: { step: "manifest", done: 0, total: 0, bots: 0 } }, "local")?.text).toBe("Moving to My Cloud… checking that everything arrived");+ const until = new Date(2026, 10, 9, 14, 5).getTime();+ const time = new Intl.DateTimeFormat("en", { timeStyle: "short" }).format(until);+ expect(moveLine({ phase: "copy", slow: { until } }, "local")).toMatchObject({ kind: "sending", text: `My Cloud is slow to answer. Your move goes on from where it was at ${time}.` });+ expect(moveLine({ phase: "finishing", checking: { step: "chats", done: 5, total: 9, bots: 2 }, slow: { until } }, "local")?.text).toContain("My Cloud is slow to answer");+ expect(moveLine({ phase: "copy", slow: { until }, failing: { error: "My Cloud did not answer." } }, "local")?.kind, "a day of failing still says so, with Try again").toBe("failed");+ expect(moveLine({ phase: "copy", queued: { name: "Milind's Mac" } }, "local")?.text).toBe("Waiting for Milind's Mac to finish moving to My Cloud. Your bots move right after.");+ expect(moveLine({ phase: "wait", queued: { name: "" } }, "local")?.text).toBe("Waiting for your other computer to finish moving to My Cloud. Your bots move right after.");+ expect(moveLine({ phase: "finishing", checking: { step: "chats", done: 1, total: 2, bots: 3 }, place: "Garage server" }, "local")?.text).toBe("Moving to Garage server… checking 3 bots' chats there, 50%");+ setLocale("pt-br");+ expect(moveLine({ phase: "finishing", checking: { step: "chats", done: 400, total: 1000, bots: 25 } }, "local")?.text).toBe("Indo para o Cloud… conferindo as conversas de 25 bots lá, 40%");+ });+it("says where the move is on whichever page is open, and who it waits for", () => {expect(moveLine({ phase: "copy" }, "local")).toMatchObject({ kind: "sending", text: "Moving your bots to My Cloud…" });expect(moveLine({ phase: "copy", chats: { done: 34, total: 120 } }, "local")?.text).toBe("Moving your bots to My Cloud… 34 of 120 chats");diff --git a/src/lib/cloud-send.ts b/src/lib/cloud-send.tsindex 6bff0b8664..df3314dc8f 100644--- a/src/lib/cloud-send.ts+++ b/src/lib/cloud-send.ts@@ -68,6 +68,26 @@ const stayedHere = (items: OneHomeStayed[] | undefined) => (items ?? []).map((it? t("cloudSend.move.stayedNeeds", { name: item.name, program: item.needs }): t("cloudSend.move.stayedHere", { name: item.name })));+const atTime = (at: number) => new Intl.DateTimeFormat(activeLocale(), { timeStyle: "short" }).format(at);+const percent = (done: number, total: number) => Math.min(100, Math.floor((done / Math.max(1, total)) * 100));++/** What a move that is under way waits for or checks now, when it says: My Cloud slow to answer, another computer moving+ * into it first, or how far the check of what arrived is; null when it says none of that. */+function underWayLine(move: OneHomeView, place?: string): string | null {+ const slow = "slow" in move ? move.slow : undefined;+ if (slow) return place ? t("cloudSend.move.slowNamed", { place, time: atTime(slow.until) }) : t("cloudSend.move.slow", { time: atTime(slow.until) });+ const queued = "queued" in move ? move.queued : undefined;+ if (queued && !place) return queued.name ? t("cloudSend.move.queued", { name: queued.name }) : t("cloudSend.move.queuedAny");+ const checking = move.phase === "finishing" ? move.checking : undefined;+ if (!checking) return null;+ const share = percent(checking.done, checking.total);+ if (place) return checking.step === "chats" && checking.total ? t("cloudSend.move.checkingChatsNamed", { place, bots: checking.bots, percent: share }) : t("cloudSend.move.checkingNamed", { place });+ if (checking.step === "chats" && checking.total) return checking.bots === 1 ? t("cloudSend.move.checkingChatsOne", { percent: share }) : t("cloudSend.move.checkingChats", { bots: checking.bots, percent: share });+ if (checking.step === "files" && checking.total) return t("cloudSend.move.checkingFiles", { percent: share });+ if (checking.step === "attachments" && checking.total) return t("cloudSend.move.checkingAttachments", { percent: share });+ return t("cloudSend.move.checking");+}+/** The one-time move's line on either page: on its way (with progress, or who it waits for), almost done, failing for a* day (with Try again), what arrived (on My Cloud's page, once), coming home, where the bots came home instead, or this* computer's bots on their way home and home because the person keeps them here.@@ -100,6 +120,8 @@ export function moveLine(move: OneHomeView, page: "local" | "cloud"): { kind: "sreturn failing.error ? { kind: "failed", text: t("cloudSend.move.failing", { error: serverErrorText(failing, failing.error) }), extra, retry: true, reason: serverErrorText(failing, failing.error) }: { kind: "failed", text: t("cloudSend.move.failingPlain"), extra, retry: true };}+ const underWay = underWayLine(move);+ if (underWay) return { kind: "sending", text: underWay, extra: [] };if (move.phase === "finishing") return { kind: "sending", text: t("cloudSend.move.finishing"), extra: [] };// Who holds the move, by name, or what it is; nothing is claimed while it only waits for a quiet moment.if (move.phase === "wait" && move.waitingFor !== undefined) {@@ -127,6 +149,8 @@ function ownMoveLine(move: OneHomeView, place: string, page: "local" | "cloud"):: line("failed", t("cloudSend.move.failingPlainNamed", { place }), { retry: true, extra });}if (move.phase === "copy" && move.updating) return line("sending", t("cloudSend.move.updatingNamed", { place }));+ const underWay = underWayLine(move, place);+ if (underWay) return line("sending", underWay);if (move.phase === "finishing") return line("sending", t("cloudSend.move.finishingNamed", { place }));if (move.phase === "wait" && move.waitingFor !== undefined) {return line("sending", move.waitingFor ? t("cloudSend.move.waitingNamed", { place, name: move.waitingFor })diff --git a/src/locales/en.json b/src/locales/en.jsonindex 1354da1a07..f1ae9598b6 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -1357,6 +1357,14 @@"cloudSend.move.waitingAny": "Moving your bots to My Cloud… waiting for your bots to finish","cloudSend.move.waitingSignIn": "Moving your bots to My Cloud… waiting for a sign-in to finish","cloudSend.move.finishing": "Moving to My Cloud… almost done",+ "cloudSend.move.checking": "Moving to My Cloud… checking that everything arrived",+ "cloudSend.move.checkingChats": "Moving to My Cloud… checking {bots} bots' chats there, {percent}%",+ "cloudSend.move.checkingChatsOne": "Moving to My Cloud… checking your bot's chats there, {percent}%",+ "cloudSend.move.checkingFiles": "Moving to My Cloud… checking your bots' files there, {percent}%",+ "cloudSend.move.checkingAttachments": "Moving to My Cloud… checking your chats' attachments there, {percent}%",+ "cloudSend.move.slow": "My Cloud is slow to answer. Your move goes on from where it was at {time}.",+ "cloudSend.move.queued": "Waiting for {name} to finish moving to My Cloud. Your bots move right after.",+ "cloudSend.move.queuedAny": "Waiting for your other computer to finish moving to My Cloud. Your bots move right after.","cloudSend.move.updating": "My Cloud is updating. Your move starts when it's done.","cloudSend.move.failing": "Your bots couldn't move to My Cloud yet: {error}","cloudSend.move.failingPlain": "Your bots couldn't move to My Cloud yet.",@@ -1366,6 +1374,9 @@"cloudSend.move.waitingAnyNamed": "Moving your bots to {place}… waiting for your bots to finish","cloudSend.move.waitingSignInNamed": "Moving your bots to {place}… waiting for a sign-in to finish","cloudSend.move.finishingNamed": "Moving to {place}… almost done",+ "cloudSend.move.checkingNamed": "Moving to {place}… checking that everything arrived",+ "cloudSend.move.checkingChatsNamed": "Moving to {place}… checking {bots} bots' chats there, {percent}%",+ "cloudSend.move.slowNamed": "{place} is slow to answer. Your move goes on from where it was at {time}.","cloudSend.move.updatingNamed": "Update OpenMausBot on {place}. Your bots move there once it's updated.","cloudSend.move.failingNamed": "Your bots couldn't move to {place} yet: {error}","cloudSend.move.failingPlainNamed": "Your bots couldn't move to {place} yet.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 3cc07ce43b..5d6cdc352e 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -7164,6 +7164,14 @@"cloudSend.move.waitingAny": "Levando seus bots para o Cloud… esperando seus bots terminarem","cloudSend.move.waitingSignIn": "Movendo seus bots para o Cloud… aguardando um login terminar","cloudSend.move.finishing": "Indo para o Cloud… quase pronto",+ "cloudSend.move.checking": "Indo para o Cloud… conferindo se tudo chegou",+ "cloudSend.move.checkingChats": "Indo para o Cloud… conferindo as conversas de {bots} bots lá, {percent}%",+ "cloudSend.move.checkingChatsOne": "Indo para o Cloud… conferindo as conversas do seu bot lá, {percent}%",+ "cloudSend.move.checkingFiles": "Indo para o Cloud… conferindo os arquivos dos seus bots lá, {percent}%",+ "cloudSend.move.checkingAttachments": "Indo para o Cloud… conferindo os anexos das suas conversas lá, {percent}%",+ "cloudSend.move.slow": "O Cloud está demorando para responder. A mudança continua de onde parou às {time}.",+ "cloudSend.move.queued": "Esperando {name} terminar de ir para o Cloud. Seus bots vão logo depois.",+ "cloudSend.move.queuedAny": "Esperando seu outro computador terminar de ir para o Cloud. Seus bots vão logo depois.","cloudSend.move.updating": "O Cloud está sendo atualizado. A mudança começa assim que a atualização terminar.","cloudSend.move.failing": "Seus bots ainda não conseguiram ir para o Cloud: {error}","cloudSend.move.failingPlain": "Seus bots ainda não conseguiram ir para o Cloud.",@@ -7173,6 +7181,9 @@"cloudSend.move.waitingAnyNamed": "Levando seus bots para {place}… esperando seus bots terminarem","cloudSend.move.waitingSignInNamed": "Levando seus bots para {place}… esperando um login terminar","cloudSend.move.finishingNamed": "Indo para {place}… quase pronto",+ "cloudSend.move.checkingNamed": "Indo para {place}… conferindo se tudo chegou",+ "cloudSend.move.checkingChatsNamed": "Indo para {place}… conferindo as conversas de {bots} bots lá, {percent}%",+ "cloudSend.move.slowNamed": "{place} está demorando para responder. A mudança continua de onde parou às {time}.","cloudSend.move.updatingNamed": "Atualize o OpenMausBot em {place}. Seus bots vão para lá assim que a atualização terminar.","cloudSend.move.failingNamed": "Seus bots ainda não conseguiram ir para {place}: {error}","cloudSend.move.failingPlainNamed": "Seus bots ainda não conseguiram ir para {place}.",