Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Move to My Cloud: move the rest when some things never arrive, say why in the open, and stop freezing every hour
milind-soni15242586e373
diff --git a/electron/cloud-send-move.node-test.mjs b/electron/cloud-send-move.node-test.mjsindex daf6899e49..e45c83c571 100644--- a/electron/cloud-send-move.node-test.mjs+++ b/electron/cloud-send-move.node-test.mjs@@ -437,3 +437,29 @@ test("while the chats go, the move's progress counts chats only: the automationsassert.ok(counted.every((progress) => progress.total === 2 && progress.done <= 2), `every count is of the 2 chats: ${JSON.stringify(counted)}`);assert.deepEqual(counted.at(-1), { done: 2, total: 2 });});++test("a check that finds things missing names, for what may stay behind, each short chat's bot and every bot and room by name", async () => {+ // Seen on a customer's PC: the check found things missing pass after pass, and only this computer's log said what.+ const manifest = (side) => ({ v: 1, appVersion: "0.1.140", items: [bot("b1", { soul: "s" }), bot("b2", { soul: "s" })], memory: [], journal: [], learned: [], forgotten: [], teams: [],+ rooms: [{ id: "r1", name: "Launch room", members: ["b1"], threads: ["t-r1"] }], connections: [],+ conversations: [{ 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 === "/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 } }] });+ }+ 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: {} });+ return null;+ } });+ const local = s.deps.local;+ s.deps.local = async (route, init) => (route === "/api/cloud-send/manifest" ? json(manifest("here")) : local(route, init));+ s.deps.handoff = async (what) => (what.kind === "verify-secrets" ? { secrets: {} } : {});+ const report = await createCloudSend(s.deps).check();+ assert.equal(report.ok, false);+ assert.deepEqual(report.attachments, ["0b6c9f2e-1d4a.mp3"], "one this computer no longer has is missing pass after pass");+ assert.deepEqual(report.names, { b1: "b1", b2: "b2", "room:r1": "Launch room" });+ assert.deepEqual(report.owners, { "t-b1": "b1" }, "only the chats found short");+});diff --git a/electron/cloud-send.mjs b/electron/cloud-send.mjsindex e6cc6e5b97..4481306d4c 100644--- a/electron/cloud-send.mjs+++ b/electron/cloud-send.mjs@@ -896,7 +896,14 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>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]) });- return { ok: checkPassed({ gaps, chats, attachments, secrets }), gaps, chats, attachments, secrets };+ 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 };} finally {try { await session.close(); } catch {}}diff --git a/electron/move-gaps.mjs b/electron/move-gaps.mjsnew file mode 100644index 0000000000..1f0b2f625b--- /dev/null+++ b/electron/move-gaps.mjs@@ -0,0 +1,94 @@+// What a move's check (cloud-send.mjs `check`, cloud-send-check.mjs) still found missing on My Cloud, three ways:+// `gapKey`, the same answer however often it is asked while nothing changes, so one-home.mjs can tell a gap that sending+// again carries from one it never will; `gapSummary`, kinds and counts only, for the Admin's move report+// (move-status.mjs); and `stayedBehind`, what the person reads on the done line for what stayed on this computer.+import { createHash } from "node:crypto";++const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);+const list = (value) => (Array.isArray(value) ? value : []);+const text = (value) => (typeof value === "string" ? value : "");++/** The chats the check found short on My Cloud: rows it lacks, the owner's lines not yet theirs, or a path that breaks. */+const shortChats = (report) => list(report?.chats).filter((entry) => record(entry) && (entry.missing || entry.unstamped || entry.path === "broken"));+const secretsOf = (report) => [...list(report?.secrets?.differs), ...list(report?.secrets?.missing)];++/** Each gap by its ids only, sorted, so two checks that found the same things missing give the same key. */+export function gapKey(report) {+ const gaps = record(report?.gaps) ? report.gaps : {};+ const ids = (kind, entry) => {+ if (!record(entry)) return text(entry);+ if (kind === "items") return text(entry.key);+ if (kind === "parts") return `${text(entry.key)}:${list(entry.parts).join(",")}`;+ if (kind === "memory") return `${text(entry.bot)}/${text(entry.path)}`;+ if (kind === "rooms") return text(entry.id);+ return JSON.stringify(entry);+ };+ const shape = {+ gaps: Object.fromEntries(Object.keys(gaps).sort().map((kind) => [kind, list(gaps[kind]).map((entry) => ids(kind, entry)).sort()]).filter(([, entries]) => entries.length)),+ chats: shortChats(report).map((entry) => `${entry.threadId}:${entry.missing ?? 0}:${entry.unstamped ?? 0}:${entry.path}`).sort(),+ attachments: list(report?.attachments).map(text).sort(),+ secrets: { differs: list(report?.secrets?.differs).map(text).sort(), missing: list(report?.secrets?.missing).map(text).sort() },+ };+ return createHash("sha256").update(JSON.stringify(shape)).digest("hex").slice(0, 24);+}++/** "2 chats (1 broken path, 3 rows), 4 attachments, 1 memory": what is missing by kind and count, never a name or an id. */+export function gapSummary(report) {+ const gaps = record(report?.gaps) ? report.gaps : {};+ const parts = Object.entries(gaps).flatMap(([kind, entries]) => (list(entries).length ? [`${list(entries).length} ${kind}`] : []));+ const chats = shortChats(report);+ if (chats.length) {+ const rows = chats.reduce((sum, entry) => sum + (Number.isSafeInteger(entry.missing) ? entry.missing : 0), 0);+ const unstamped = chats.reduce((sum, entry) => sum + (Number.isSafeInteger(entry.unstamped) ? entry.unstamped : 0), 0);+ const broken = chats.filter((entry) => entry.path === "broken").length;+ const detail = [...(rows ? [`${rows} rows`] : []), ...(unstamped ? [`${unstamped} unstamped`] : []), ...(broken ? [`${broken} broken paths`] : [])];+ parts.push(`${chats.length} chats (${detail.join(", ")})`);+ }+ if (list(report?.attachments).length) parts.push(`${report.attachments.length} attachments`);+ if (list(report?.secrets?.differs).length) parts.push(`${report.secrets.differs.length} credentials differ`);+ if (list(report?.secrets?.missing).length) parts.push(`${report.secrets.missing.length} credentials missing`);+ return parts.join(", ") || "something";+}++/** At most this many lines say what stayed behind; the rest are counted in the last. */+export const STAYED_MAX = 8;++/**+ * What stayed on this computer, in the person's words, one line per thing they know: a bot's name for its memory, chats+ * and files, a room's name, an app or a key. `report.names`: bot ids and `room:<id>` to their names; `report.owners`: each+ * short chat's bot id or `room:<id>`. Never a path, a secret or anything written in a chat.+ */+export function stayedBehind(report) {+ const gaps = record(report?.gaps) ? report.gaps : {};+ const names = record(report?.names) ? report.names : {};+ const owners = record(report?.owners) ? report.owners : {};+ const nameOf = (id) => (typeof names[id] === "string" && names[id].trim() ? names[id].trim() : null);+ const out = [];+ const add = (label, error) => { if (label && !out.some((entry) => entry.label === label && entry.error === error)) out.push({ label, error }); };+ const plural = (count, one, many) => (count === 1 ? one : many.replace("{n}", String(count)));+ const byBot = (entries, botOf) => {+ const counts = new Map();+ for (const entry of entries) { const bot = botOf(entry); counts.set(bot, (counts.get(bot) ?? 0) + 1); }+ return counts;+ };++ for (const item of list(gaps.items)) add(text(item?.label) || "Something", "It didn't reach My Cloud.");+ for (const item of list(gaps.parts)) add(text(item?.label) || "Something", "Some of its settings didn't reach My Cloud.");+ for (const room of list(gaps.rooms)) add(text(room?.name) || "A room", "This room didn't reach My Cloud.");+ for (const [bot, count] of byBot(list(gaps.memory), (entry) => entry?.bot)) add(nameOf(bot) ?? "A bot", plural(count, "One of its memory notes didn't reach My Cloud.", "{n} of its memory notes didn't reach My Cloud."));+ for (const bot of new Set(list(gaps.journal))) add(nameOf(bot) ?? "A bot", "Some of its memory history didn't reach My Cloud.");+ const files = byBot(list(gaps.files), (path) => /^(?:workspaces|task-workspaces)\/([\w-]{1,128})\//u.exec(text(path))?.[1]);+ for (const [bot, count] of files) add(nameOf(bot) ?? "A bot", plural(count, "One of its files didn't reach My Cloud.", "{n} of its files didn't reach My Cloud."));+ const chats = byBot([...list(gaps.conversations), ...list(gaps.settings), ...shortChats(report).map((entry) => entry.threadId)], (threadId) => owners[threadId]);+ for (const [owner, count] of chats) add(nameOf(owner) ?? "Chats", plural(count, "Part of one chat didn't reach My Cloud.", "Parts of {n} chats didn't reach My Cloud."));+ if (list(gaps.runs).length) add("Routine history", plural(gaps.runs.length, "One past run didn't reach My Cloud.", "{n} past runs didn't reach My Cloud."));+ if (list(gaps.learned).length) add("What your bots learned about you", "Some of it didn't reach My Cloud.");+ if (list(gaps.teams).length) add("Team notes", "Some of them didn't reach My Cloud.");+ for (const id of list(gaps.connections)) add(text(id).replace(/^(?:mcp|key):/u, "") || "An app", "It didn't reach My Cloud. Add it there again if a bot needs it.");+ const attachments = list(report?.attachments).length;+ if (attachments) add(plural(attachments, "An attachment", "{n} attachments"), plural(attachments, "It didn't reach My Cloud.", "They didn't reach My Cloud."));+ const secrets = secretsOf(report).length;+ if (secrets) add(plural(secrets, "A sign-in or key", "{n} sign-ins and keys"), plural(secrets, "It didn't reach My Cloud. Add it there again if a bot needs it.", "They didn't reach My Cloud. Add them there again if a bot needs them."));+ if (out.length <= STAYED_MAX) return out;+ return [...out.slice(0, STAYED_MAX - 1), { label: `${out.length - STAYED_MAX + 1} more`, error: "They didn't reach My Cloud." }];+}diff --git a/electron/move-gaps.node-test.mjs b/electron/move-gaps.node-test.mjsnew file mode 100644index 0000000000..09c910e58c--- /dev/null+++ b/electron/move-gaps.node-test.mjs@@ -0,0 +1,61 @@+import assert from "node:assert/strict";+import test from "node:test";++import { gapKey, gapSummary, STAYED_MAX, stayedBehind } from "./move-gaps.mjs";++const report = (extra = {}) => ({+ ok: false,+ gaps: { items: [{ key: "bot:b9", kind: "bot", label: "Archie" }], parts: [], memory: [{ bot: "b1", path: "memory/notes.md" }, { bot: "b1", path: "memory/log/2026-10-03.md" }],+ rooms: [], connections: ["mcp:linear"], conversations: ["t2"], files: ["workspaces/b1/drafts/report.docx"], runs: [], journal: [], learned: [], teams: [], settings: [] },+ chats: [{ threadId: "t1", missing: 3, unstamped: 0, path: "equal" }, { threadId: "t3", missing: 0, unstamped: 0, path: "broken" }, { threadId: "t4", missing: 0, unstamped: 0, path: "inside" }],+ attachments: ["0b6c9f2e-1d4a-4b6e-9f1a-2c3d4e5f6a7b.mp3"],+ secrets: { equal: ["key:openrouter"], differs: [], missing: ["login:example.test|alice"] },+ names: { b1: "Scout", b9: "Archie", "room:r1": "Launch room" },+ owners: { t1: "b1", t2: "b1", t3: "room:r1" },+ ...extra,+});++test("the same gaps give the same key in any order, and anything else missing gives another", () => {+ const one = report();+ const shuffled = report({ gaps: { ...one.gaps, memory: [...one.gaps.memory].reverse() }, chats: [...one.chats].reverse(), names: {}, owners: {} });+ assert.equal(gapKey(one), gapKey(shuffled), "order, names and owners never change the key");+ assert.equal(gapKey(report({ chats: one.chats.filter((entry) => entry.threadId !== "t4") })), gapKey(one), "a chat whose path holds inside a longer one is no gap");+ assert.notEqual(gapKey(report({ attachments: [] })), gapKey(one));+ assert.notEqual(gapKey(report({ chats: [{ threadId: "t1", missing: 2, unstamped: 0, path: "equal" }] })), gapKey(report({ chats: [{ threadId: "t1", missing: 3, unstamped: 0, path: "equal" }] })),+ "a chat that got some of its rows is progress");+ assert.match(gapKey(one), /^[a-f0-9]{24}$/u);+});++test("the Admin hears kinds and counts only: never a name, an id, a path or a credential", () => {+ const said = gapSummary(report());+ assert.equal(said, "1 items, 2 memory, 1 connections, 1 conversations, 1 files, 2 chats (3 rows, 1 broken paths), 1 attachments, 1 credentials missing");+ assert.doesNotMatch(said, /Archie|Scout|linear|report\.docx|alice|example|t1|t3|b1|0b6c9f2e/u);+ assert.equal(gapSummary({}), "something");+});++test("what stayed behind is said in the person's words, one line for each thing they know, by its bot or room", () => {+ assert.deepEqual(stayedBehind(report()), [+ { label: "Archie", error: "It didn't reach My Cloud." },+ { label: "Scout", error: "2 of its memory notes didn't reach My Cloud." },+ { label: "Scout", error: "One of its files didn't reach My Cloud." },+ { label: "Scout", error: "Parts of 2 chats didn't reach My Cloud." },+ { label: "Launch room", error: "Part of one chat didn't reach My Cloud." },+ { label: "linear", error: "It didn't reach My Cloud. Add it there again if a bot needs it." },+ { label: "An attachment", error: "It didn't reach My Cloud." },+ { label: "A sign-in or key", error: "It didn't reach My Cloud. Add it there again if a bot needs it." },+ ]);+ const said = JSON.stringify(stayedBehind(report()));+ assert.doesNotMatch(said, /report\.docx|memory\/|alice|example\.test|0b6c9f2e|"t1"|"b1"/u, "never a path, a file name, an id or an account");+ assert.deepEqual(stayedBehind(report({ names: {}, owners: {} })).slice(1, 3), [+ { label: "A bot", error: "2 of its memory notes didn't reach My Cloud." },+ { label: "A bot", error: "One of its files didn't reach My Cloud." },+ ], "a bot it can't name is still said");+ assert.deepEqual(stayedBehind({ ok: false }), [], "nothing named, nothing left behind");+});++test("at most a handful of lines, the rest counted", () => {+ const items = Array.from({ length: 20 }, (_, at) => ({ key: `bot:b${at}`, kind: "bot", label: `Bot ${at}` }));+ const said = stayedBehind({ ok: false, gaps: { items } });+ assert.equal(said.length, STAYED_MAX);+ assert.deepEqual(said.at(-1), { label: "13 more", error: "They didn't reach My Cloud." });+});diff --git a/electron/move-status.mjs b/electron/move-status.mjsindex 3f8919b3f4..df86c068b6 100644--- a/electron/move-status.mjs+++ b/electron/move-status.mjs@@ -62,10 +62,12 @@ function reasonOf({ journal, phase, state, cloud, kept, facts, now }) {return null;}-/** The journal's last failure, its sentence made safe to send; a journal from before failures had codes reads as `error`. */+/** The journal's last failure, its sentence made safe to send; a journal from before failures had codes reads as `error`.+ * A check's failure leads with what it found missing, by kind and count (move-gaps.mjs), which the Admin keeps whole. */function failureIn(journal) {const failure = record(journal?.failure) ? journal.failure : null;- const message = safeSentence(journal?.error);+ const gaps = typeof journal?.gaps === "string" && journal.gaps ? journal.gaps : null;+ const message = safeSentence(gaps ? `Missing: ${gaps}. ${journal?.error ?? ""}` : journal?.error);if (!failure && !message) return null;const count = Number.isSafeInteger(failure?.count) && failure.count > 0 ? failure.count : Number.isSafeInteger(journal?.tries) && journal.tries > 0 ? journal.tries : 1;return {diff --git a/electron/move-status.node-test.mjs b/electron/move-status.node-test.mjsindex a28d8e19af..349cf13f24 100644--- a/electron/move-status.node-test.mjs+++ b/electron/move-status.node-test.mjs@@ -4,7 +4,7 @@ import test from "node:test";import { CloudSendError } from "./cloud-send.mjs";import { failureCode, safeSentence, SENTENCE_MAX } from "./move-failure.mjs";import { createMoveStatusReport, MOVE_STATUS_GAP_MS, MOVE_STATUS_HEARTBEAT_MS, MOVE_STATUS_OFF_MS, MOVE_STATUS_SETTLE_MS, moveStatus } from "./move-status.mjs";-import { CHECK_PASSES, createOneHome, parseJournal, QUIET_MS } from "./one-home.mjs";+import { CHECK_PASSES, createOneHome, INCOMPLETE, parseJournal, QUIET_MS } from "./one-home.mjs";import { installOneHome, oneHomeCloud } from "./one-home-main.mjs";const CLOUD = "https://omb-t-1.fly.dev";@@ -39,7 +39,7 @@ function world({ state = signedIn(), moves = [], checks = [], busy = [] } = {})cloud: () => oneHomeCloud(w.state),send: {async move() { const failure = moves.shift(); if (failure) throw failure; },- async check() { return { ok: checks.shift() ?? true }; },+ async check() { const next = checks.shift(); return next && typeof next === "object" ? next : { ok: next ?? true }; },switches: () => ({ "routine:r1": true }),snapshot: () => ({}),},@@ -155,7 +155,7 @@ test("every phase's failure has its own code", async () => {{ name: "My Cloud answering nothing usable", moves: [new CloudSendError("unreachable", "My Cloud said: Bot \"Sales team\" can't be read")], expect: { phase: "copy", code: "unreachable", message: "My Cloud said: …" } },{ name: "My Cloud refusing the final pass", moves: [undefined, new CloudSendError("refused", "My Cloud could not add the chats.")], expect: { phase: "final", code: "refused" } },{ name: "something unforeseen", moves: [new Error("Cannot read properties of undefined (reading 'items')")], expect: { phase: "copy", code: "error" } },- { name: "the check still missing things after three passes", checks: [false, false, false], expect: { phase: "check", code: "incomplete", message: "Some of this computer's things did not reach My Cloud." } },+ { name: "the check still missing things after three passes", checks: [false, false, false], expect: { phase: "check", code: "incomplete", message: "Missing: something. " + INCOMPLETE } },{ name: "this computer's server refusing to pause", freezeError: Object.assign(new Error("OpenMausBot on this computer could not pause."), { status: 500 }), expect: { phase: "freeze", code: "freeze" } },{ name: "My Cloud refusing to switch an automation on", cloudAnswer: (method) => (method === "PATCH" ? reply(500, { error: "Routines are busy." }) : null), expect: { phase: "switch", code: "switch_refused", message: "Routines are busy." } },];@@ -174,6 +174,18 @@ test("every phase's failure has its own code", async () => {}});+test("a check's failure tells the Admin what it found missing first, by kind and count, so it is never cut off", async () => {+ // Seen on a customer's PC: 94 failures in a week, and all the Admin knew was that "some things" did not arrive.+ const missing = { ok: false, gaps: { memory: [{ bot: "b1", path: "memory/notes.md" }] }, chats: [{ threadId: "t-1", missing: 0, unstamped: 0, path: "broken" }],+ attachments: ["a1.mp3", "a2.png"], secrets: { equal: [], differs: [], missing: [] }, names: { b1: "Scout" }, owners: { "t-1": "b1" } };+ const w = world({ checks: [missing, missing, missing] });+ await w.home.kick();+ const { message } = w.report().failure;+ assert.ok(message.startsWith("Missing: 1 memory, 1 chats (1 broken paths), 2 attachments. "), message);+ assert.ok(message.length <= 200);+ assert.doesNotMatch(message, /Scout|notes\.md|a1\.mp3|t-1/u);+});+test("a frozen move whose Cloud stops being ready, or whose account changes, says so", async () => {const w = world();// Stopped just as the final pass would go: frozen, then the Cloud is no longer ready.diff --git a/electron/one-home.mjs b/electron/one-home.mjsindex 2bf8b609c1..a89a2dcb52 100644--- a/electron/one-home.mjs+++ b/electron/one-home.mjs@@ -28,6 +28,7 @@// computer no longer counts as moved. Choosing otherwise again moves it again, as anyone's first move.import { failureOf, rateLimited } from "./move-failure.mjs";+import { gapKey, gapSummary, stayedBehind } from "./move-gaps.mjs";export { rateLimited };@@ -40,8 +41,12 @@ const BUSY_POLL_MS = 5_000;/** The longest a timer waits before it looks again: longer ones overflow Node's timers. */const LONGEST_WAIT_MS = 6 * HOUR;export const CHECK_PASSES = 3;-/** A failure while this computer's server is frozen: lifted, and tried again in an hour. */+/** A failure while this computer's server is frozen: lifted, and tried again in an hour, then twice as long after each+ * one that follows, up to FROZEN_RETRY_MAX_MS, so a move that keeps failing does not stop this computer every hour. */export const FROZEN_RETRY_MS = HOUR;+export const FROZEN_RETRY_MAX_MS = 12 * HOUR;+/** What the line and the Admin say when the check still found things missing after its passes. */+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];export const FAILING_LINE_MS = DAY;@@ -255,8 +260,12 @@ export function createOneHome(deps) {log(`one home: ${journal.phase} failed (${said})`);const tries = (journal.tries ?? 0) + 1;const hourly = frozen && !rateLimited(error);- const next = write({ ...journal, phase: "copy", passes: 0, tries, error: said, failingSince: journal.failingSince ?? now(), failure: failureOf(error, journal.phase, journal.failure, now()),- retryAt: now() + (hourly ? FROZEN_RETRY_MS : COPY_RETRY_MS[Math.min(tries - 1, COPY_RETRY_MS.length - 1)]), hourly: hourly || undefined, ...(frozen ? { thaw: true } : {}) });+ 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)];+ // 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, 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,+ retryAt: now() + wait, hourly: hourly || undefined, ...(frozen ? { thaw: true } : {}) });if (frozen) await thaw(next);return null;}@@ -307,12 +316,22 @@ export function createOneHome(deps) {return write({ ...journal, phase: "check", passes: 1 });}+ /** What arrived, against what is here. What sending again three times carried none of, which the try before this one+ * also ended without (by the same gaps, or by any for a journal from before gaps were kept), never will go: it stays on+ * this computer, the rest moves, and the done line says what stayed (`stuck`). Anything else fails, and goes again. */async function check(journal) {- let passes = journal.passes ?? 1;+ let passes = journal.passes ?? 1, first = null, stuck = null;try {for (let report = await deps.send.check(); report?.ok !== true; report = await deps.send.check()) {log(`one home: the check found ${missingOf(report)} missing`);- if (passes >= CHECK_PASSES) throw tagged("Some of this computer's things did not reach My Cloud.", "incomplete");+ const key = gapKey(report);+ first ??= key;+ if (passes >= CHECK_PASSES) {+ const again = journal.failure?.code === "incomplete" && (journal.gapKey === undefined || journal.gapKey === key);+ // Only what can be named stays behind: a check that can't say what it misses fails as before.+ if (key === first && again && (stuck = stayedBehind(report)).length) { log(`one home: moving on without what never arrived (${gapSummary(report)})`); break; }+ throw tagged(INCOMPLETE, "incomplete", { gapKey: key, gaps: gapSummary(report) });+ }await deps.send.move({ final: true });passes += 1;write({ ...journal, passes });@@ -324,7 +343,7 @@ export function createOneHome(deps) {try { counts = arrivedCounts(await deps.local.json("/api/cloud-send/manifest"), (await session.call("GET", "/api/cloud-send/manifest")).body); }finally { await session.close().catch(() => {}); }} catch {}- return write({ ...journal, phase: "switch", passes, checkedAt: now(), ...(counts ? { counts } : {}) });+ return write({ ...journal, phase: "switch", passes, checkedAt: now(), ...(counts ? { counts } : {}), ...(stuck?.length ? { stuck } : {}) });}/** The point of no return: My Cloud switches on what was on here, and keeps which computer its bots came from. What was@@ -357,9 +376,9 @@ export function createOneHome(deps) {} finally { await session?.close().catch(() => {}); }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);+ const left = [...notCarried(sent, true), ...(Array.isArray(journal.stuck) ? journal.stuck : [])];const done = write({ ...journal, phase: "done", switched, doneAt: now(), version: deps.version ?? null, phone: deps.phone?.paired() === true, held, ...(left.length ? { left } : {}),- error: undefined, failingSince: undefined, retryAt: undefined, tries: undefined, failure: undefined });+ error: undefined, failingSince: undefined, retryAt: undefined, tries: undefined, failure: undefined, frozenTries: undefined, gapKey: undefined, gaps: undefined, stuck: undefined });await settle(done);deps.openHome?.();return null;diff --git a/electron/one-home.node-test.mjs b/electron/one-home.node-test.mjsindex 7069dac39c..bc785ee7f4 100644--- a/electron/one-home.node-test.mjs+++ b/electron/one-home.node-test.mjs@@ -1,7 +1,7 @@import assert from "node:assert/strict";import test from "node:test";-import { arrivedCounts, CHECK_PASSES, COPY_RETRY_MS, createOneHome, FAILING_LINE_MS, FROZEN_RETRY_MS, KEPT_MS, missingOf, QUIET_MS, switchOn } from "./one-home.mjs";+import { arrivedCounts, CHECK_PASSES, COPY_RETRY_MS, createOneHome, FAILING_LINE_MS, FROZEN_RETRY_MAX_MS, FROZEN_RETRY_MS, INCOMPLETE, KEPT_MS, missingOf, QUIET_MS, switchOn } from "./one-home.mjs";import { oneHomeCloud } from "./one-home-main.mjs";const CLOUD = "https://omb-t-1.fly.dev";@@ -42,7 +42,8 @@ function world({ cloud = {}, switches = { "routine:r1": true, "routine:r2": falsconst failure = moves.shift();if (failure) throw failure;},- async check() { w.checked++; return { ok: checks.shift() ?? true }; },+ // A check answers `true`/`false`, or a whole report (cloud-send.mjs `check`).+ async check() { w.checked++; const next = checks.shift(); return next && typeof next === "object" ? next : { ok: next ?? true }; },switches: () => switches,snapshot: () => ({ running: w.running ?? null, whole: { result: { notes: [{ kind: "held", connection: "OpenRouter" }], failed: w.failed ?? [] } } }),},@@ -198,11 +199,85 @@ test("a check that still finds things missing after three passes says so at onceawait w.home.kick();assert.equal(w.journal.failure.code, "incomplete");assert.ok(w.now() - w.journal.failingSince < FAILING_LINE_MS, "not a day later");- assert.deepEqual(w.home.view(), { phase: "copy", failing: { error: "Some of this computer's things did not reach My Cloud.", items: [+ assert.deepEqual(w.home.view(), { phase: "copy", failing: { error: INCOMPLETE, items: [{ label: "tidy", error: "OpenMausBot on this computer did not answer. Try again in a moment." },{ label: "Reply to email", error: "This app automation stays on the computer it came from." }] } });});+/** A check that finds the same things missing on every pass: one attachment and one bot's memory note that sending again+ * never carries (a file gone from this computer, a note My Cloud can't keep). */+const stuckReport = (extra = {}) => ({ ok: false, gaps: { items: [], memory: [{ bot: "b1", path: "memory/notes.md" }], conversations: [] },+ chats: [{ threadId: "t1", missing: 2, unstamped: 0, path: "equal" }], attachments: ["a1.mp3"], secrets: { equal: [], differs: [], missing: [] },+ names: { b1: "Scout" }, owners: { t1: "b1" }, ...extra });++test("what sending again never carries stays on this computer once two tries ended the same way, and the rest moves", async () => {+ // Seen on a customer's PC (0.1.140): the check found the same things missing on every pass, so the move failed 94 times+ // in a week, freezing the computer each hour, and the line only said "Some of this computer's things did not reach My Cloud".+ const w = world({ checks: [stuckReport(), stuckReport(), stuckReport(), stuckReport(), stuckReport(), stuckReport()] });+ await w.home.kick();+ assert.equal(w.journal.phase, "copy", "the first try that ends this way still goes again: My Cloud may have been busy");+ assert.equal(w.journal.failure.code, "incomplete");+ assert.equal(w.journal.gaps, "1 memory, 1 chats (2 rows), 1 attachments");+ assert.equal(w.home.view().failing.error, INCOMPLETE, "the line says what happens next, not only that it failed");+ assert.equal(w.server.frozen, false);++ w.advance(FROZEN_RETRY_MS);+ await w.tick();+ assert.equal(w.journal.phase, "done", "the next try ending the same way moves the rest");+ assert.equal(w.server.frozen, true);+ assert.deepEqual(w.journal.left, [+ { label: "Scout", error: "One of its memory notes didn't reach My Cloud." },+ { label: "Scout", error: "Part of one chat didn't reach My Cloud." },+ { label: "An attachment", error: "It didn't reach My Cloud." },+ ]);+ assert.deepEqual(w.home.view().left, w.journal.left, "the done line says what stayed here");+ for (const key of ["gapKey", "gaps", "stuck", "frozenTries", "failure"]) assert.equal(w.journal[key], undefined, `${key} is cleared once done`);+});++test("a move keeps trying while sending again carries something, or something new goes missing", async () => {+ // Pass by pass the gaps shrink: sending again is working, so this is no reason to leave anything behind.+ const shrinking = world({ checks: [stuckReport(), stuckReport({ attachments: [] }), stuckReport({ attachments: [] }),+ stuckReport(), stuckReport({ attachments: [] }), stuckReport({ attachments: [] })] });+ shrinking.journal = { v: 1, phase: "copy", cloud: { origin: CLOUD, account: "acct-1", machine: CLOUD }, failure: { phase: "check", code: "incomplete", count: 3, since: 1, at: 1 } };+ await shrinking.relaunch().kick();+ assert.equal(shrinking.journal.phase, "copy");+ assert.equal(shrinking.journal.failure.code, "incomplete");++ // The try before found other things missing than this one: both go again.+ const other = world({ checks: [stuckReport(), stuckReport(), stuckReport()] });+ other.journal = { v: 1, phase: "copy", cloud: { origin: CLOUD, account: "acct-1", machine: CLOUD }, failure: { phase: "check", code: "incomplete", count: 1, since: 1, at: 1 }, gapKey: "not-these" };+ await other.relaunch().kick();+ assert.equal(other.journal.phase, "copy");+ assert.notEqual(other.journal.gapKey, "not-these");++ // A journal an older app wrote, failing this way with no gaps kept: the first try that ends the same way moves the rest.+ const older = world({ checks: [stuckReport(), stuckReport(), stuckReport()] });+ older.journal = { v: 1, phase: "copy", cloud: { origin: CLOUD, account: "acct-1", machine: CLOUD }, failure: { phase: "check", code: "incomplete", count: 94, since: 1, at: 1 }, tries: 94 };+ await older.relaunch().kick();+ assert.equal(older.journal.phase, "done");+ assert.equal(older.journal.left.length, 3);+});++test("a move that keeps failing frozen waits twice as long each time, up to half a day, so this computer is not stopped every hour", async () => {+ const w = world({ moves: Array.from({ length: 12 }, (_, at) => (at % 2 ? new Error("My Cloud could not add the chats.") : undefined)) });+ const waits = [];+ for (let attempt = 0; attempt < 6; attempt++) {+ await w.tick();+ waits.push((w.journal.retryAt - w.now()) / FROZEN_RETRY_MS);+ w.advance(w.journal.retryAt - w.now());+ }+ assert.deepEqual(waits, [1, 2, 4, 8, 12, 12]);+ assert.equal(FROZEN_RETRY_MAX_MS, 12 * FROZEN_RETRY_MS);+ assert.equal(w.server.freezes, 6, "one freeze a try, never more");+ await w.home.retry();+ assert.equal(w.server.freezes, 7, "Try again still goes at once");++ const unnamed = world({ checks: [false, false, false, false, false, false] });+ unnamed.journal = { v: 1, phase: "copy", cloud: { origin: CLOUD, account: "acct-1", machine: CLOUD }, failure: { phase: "check", code: "incomplete", count: 2, since: 1, at: 1 } };+ await unnamed.relaunch().kick();+ assert.equal(unnamed.journal.phase, "copy", "a check that can't say what it misses never leaves anything behind");+});+test("a move done without what My Cloud refused for good names it on the done line", async () => {const w = world();w.failed = [{ key: "app-event:e1", kind: "app-event", label: "Reply to email", error: "This app automation stays on the computer it came from.", final: true }];diff --git a/src/components/AccountMove.test.ts b/src/components/AccountMove.test.tsindex 4d17245302..c465223af7 100644--- a/src/components/AccountMove.test.ts+++ b/src/components/AccountMove.test.ts@@ -73,11 +73,21 @@ describe("the move's words on the account", () => {// The words shorten before Try again does.expect(html).toContain('<span class="truncate">My Cloud move needs you</span>');expect(tag).toMatch(/class="[^"]*\bshrink-0\b/);- const tryAgain = (status.props as { children: ReturnType<typeof createElement>[] }).children[1]!;+ const row = (status.props as { children: ReturnType<typeof createElement>[] }).children[0]!;+ const tryAgain = (row.props as { children: ReturnType<typeof createElement>[] }).children[1]!;(tryAgain.props as { onClick: () => void }).onClick();expect(onRetry).toHaveBeenCalledOnce();});+ it("says why it failed in the open, under its words, and never while it goes", () => {+ const why = "Some of this computer's things didn't reach My Cloud yet. It tries again by itself.";+ const html = markup(AccountMoveStatus({ kind: "failed", onOpen: noop, retry: { onRetry: noop, retrying: false, why } }));+ expect(html).toMatch(new RegExp(`<p data-move-why[^>]*>${why.replaceAll(".", "\\.")}</p>`));+ expect(html.indexOf(">Try again<")).toBeLessThan(html.indexOf("data-move-why"));+ expect(markup(AccountMoveStatus({ kind: "sending", onOpen: noop, retry: { onRetry: noop, retrying: false, why } }))).not.toContain("data-move-why");+ expect(markup(AccountMoveStatus({ kind: "failed", onOpen: noop, retry: { onRetry: noop, retrying: false, why: "" } }))).not.toContain("data-move-why");+ });+it("while Try again runs: disabled and busy, with a spinner", () => {const html = markup(AccountMoveStatus({ kind: "failed", onOpen: noop, retry: { onRetry: noop, retrying: true, why: "My Cloud did not answer." } }));const tag = tryAgainTag(html);@@ -98,13 +108,12 @@ describe("the move's row in the account menu", () => {const rows = (value: AccountMoveLine | null, patch: Partial<Parameters<typeof moveMenuItems>[1]> = {}) =>moveMenuItems(value, { onOpen: noop, onRetry: noop, onClose: noop, ...patch });- it("failing: one row the size of the others that tries again, with why in its tooltip", () => {+ it("failing: one row that tries again, with why written under it and in its tooltip", () => {const onOpen = vi.fn(), onRetry = vi.fn();const items = rows(line({ phase: "copy", failing: { error: "Some of this computer's things did not reach My Cloud." } }), { onOpen, onRetry });expect(items).toHaveLength(1);expect(items[0]).toMatchObject({ key: "cloud-move", label: "Try My Cloud move again", title: "Some of this computer's things did not reach My Cloud.", disabled: false, keepOpen: true });- expect(items[0]).not.toHaveProperty("note");- expect(items[0]).not.toHaveProperty("wrap");+ expect(items[0]).toMatchObject({ note: "Some of this computer's things did not reach My Cloud.", wrap: true });expect(markup(items[0]!.icon)).not.toContain("animate-spin");items[0]!.onSelect();expect(onRetry).toHaveBeenCalledOnce();diff --git a/src/components/AccountMove.tsx b/src/components/AccountMove.tsxindex e73b6520a5..f8fa6e07c7 100644--- a/src/components/AccountMove.tsx+++ b/src/components/AccountMove.tsx@@ -32,8 +32,8 @@ function failingWhy(line: AccountMoveLine, unanswered: string | null): string {return [unanswered && unanswered !== plain ? unanswered : line.reason, ...line.extra].filter(Boolean).join(" ") || plain;}-/** The move's rows at the top of the account menu, each the size of every other row there. Failed: Try again, with why- * in its tooltip and a spinner while it runs. On its way: one row, the progress in its tooltip. Done: what arrived, the+/** The move's rows at the top of the account menu. Failed: Try again, with why written under it (and in its tooltip),+ * and a spinner while it runs. On its way: one row, the progress in its tooltip. Done: what arrived, the* phone to pair, and Got it, which closes it for good. A row that does not retry opens My Cloud in Settings. */export function moveMenuItems(line: AccountMoveLine | null, { retrying = false, unanswered = null, onOpen, onRetry, onPairPhone, onClose }: {retrying?: boolean;@@ -46,11 +46,13 @@ export function moveMenuItems(line: AccountMoveLine | null, { retrying = false,if (!line) return [];if (line.kind === "failed") {const title = failingWhy(line, unanswered);- if (!line.retry) return [{ key: "cloud-move", label: accountMoveWords("failed", line.place)!, title, icon: <CloudAlert size={16} className="text-warning" />, onSelect: onOpen }];+ if (!line.retry) return [{ key: "cloud-move", label: accountMoveWords("failed", line.place)!, title, note: title, wrap: true, icon: <CloudAlert size={16} className="text-warning" />, onSelect: onOpen }];return [{key: "cloud-move",label: line.place ? t("sidebar.account.moveRetryNamed", { place: line.place }) : t("sidebar.account.moveRetry"),title,+ note: title,+ wrap: true,icon: retrying ? <Loader2 size={16} className="animate-spin" /> : <RefreshCw size={16} className="text-warning" />,disabled: retrying,keepOpen: true,@@ -135,8 +137,8 @@ export function useAccountMoveLine(cloudHome: boolean): { kind: AccountMoveKind}/** The account's line for the move: amber while it needs the person, quiet while it goes, nothing otherwise. With- * `onOpen` its words are a button that opens the account menu, followed by Try again when `retry` allows one; without,- * words inside a trigger. The words shorten before Try again does. */+ * `onOpen` its words are a button that opens the account menu, followed by Try again when `retry` allows one, and why it+ * failed written out under them; without, words inside a trigger. The words shorten before Try again does. */export function AccountMoveStatus({ kind, place, retry = null, onOpen, className }: { kind: AccountMoveKind | null; place?: string; retry?: AccountMoveRetry | null; onOpen?: () => void; className?: string }) {const words = accountMoveWords(kind, place);if (!words) return null;@@ -148,23 +150,26 @@ export function AccountMoveStatus({ kind, place, retry = null, onOpen, className</>;if (!onOpen) return <span data-account-move={kind} className={cn(look, className)}>{body}</span>;return (- <div role="status" data-account-move={kind} className={cn("flex min-w-0 items-center gap-1.5", className)}>- <button type="button" onClick={onOpen} className={cn(look, kind === "failed" ? "hover:underline" : "hover:text-ink")}>{body}</button>- {kind === "failed" && retry && (- <button- type="button"- data-move-retry- aria-label={place ? t("sidebar.account.moveRetryNameNamed", { place }) : t("sidebar.account.moveRetryName")}- aria-busy={retry.retrying || undefined}- aria-disabled={retry.retrying || undefined}- title={retry.why}- onClick={retry.retrying ? undefined : retry.onRetry}- className={cn("ui-button ui-button-sm shrink-0", retry.retrying && "cursor-progress")}- >- {retry.retrying && <Loader2 aria-hidden="true" className="size-3.5 shrink-0 animate-spin motion-reduce:animate-none" />}- {t("cloudSend.strip.retry")}- </button>- )}+ <div role="status" data-account-move={kind} className={cn("flex min-w-0 flex-col gap-0.5", className)}>+ <div className="flex min-w-0 items-center gap-1.5">+ <button type="button" onClick={onOpen} className={cn(look, kind === "failed" ? "hover:underline" : "hover:text-ink")}>{body}</button>+ {kind === "failed" && retry && (+ <button+ type="button"+ data-move-retry+ aria-label={place ? t("sidebar.account.moveRetryNameNamed", { place }) : t("sidebar.account.moveRetryName")}+ aria-busy={retry.retrying || undefined}+ aria-disabled={retry.retrying || undefined}+ title={retry.why}+ onClick={retry.retrying ? undefined : retry.onRetry}+ className={cn("ui-button ui-button-sm shrink-0", retry.retrying && "cursor-progress")}+ >+ {retry.retrying && <Loader2 aria-hidden="true" className="size-3.5 shrink-0 animate-spin motion-reduce:animate-none" />}+ {t("cloudSend.strip.retry")}+ </button>+ )}+ </div>+ {kind === "failed" && retry?.why && <p data-move-why className="line-clamp-4 text-[12px] leading-4 text-ink-secondary">{retry.why}</p>}</div>);}diff --git a/src/components/SidebarProfileMenu.test.ts b/src/components/SidebarProfileMenu.test.tsindex cc477eb4a0..1f45ff47b6 100644--- a/src/components/SidebarProfileMenu.test.ts+++ b/src/components/SidebarProfileMenu.test.ts@@ -530,16 +530,17 @@ describe("Simple mode's account menu", () => {expect(groups(build({ move: [] }))[0]).toEqual(["usage", "phone-app", "support", "settings"]);});- it("gives a failing or moving move one row shaped like Usage and Settings: a label and an icon, no second line", () => {+ it("gives a moving move one row shaped like Usage and Settings, and a failing one the reason written under its Try again", () => {const shape = (item: SidebarMenuItem) => ({ lines: [item.subtitle, item.note].filter(Boolean).length, wrap: item.wrap === true, icon: Boolean(item.icon) });const failing = moveMenuItems(moveLine({ phase: "copy", failing: { error: "Some of this computer's things did not reach My Cloud." } }, "local"), { onOpen: noop, onRetry: noop, onClose: noop });const moving = moveMenuItems(moveLine({ phase: "copy", chats: { done: 34, total: 120 } }, "local"), { onOpen: noop, onRetry: noop, onClose: noop });- for (const move of [failing, moving]) {- const items = build({ move });- expect(groups(items)[0]).toEqual(["cloud-move"]);- const settings = items.find((item) => item.key === "settings")!;- expect(shape(items[0]!)).toEqual(shape(settings));- }+ const items = build({ move: moving });+ expect(groups(items)[0]).toEqual(["cloud-move"]);+ expect(shape(items[0]!)).toEqual(shape(items.find((item) => item.key === "settings")!));+ const failed = build({ move: failing });+ expect(groups(failed)[0]).toEqual(["cloud-move"]);+ expect(shape(failed[0]!)).toEqual({ lines: 1, wrap: true, icon: true });+ expect(failed[0]!.note).toBe("Some of this computer's things did not reach My Cloud.");});it("puts the move's row first in Advanced's account menu too, under its own divider", () => {diff --git a/src/one-home-preview.tsx b/src/one-home-preview.tsxindex 756fc1e82c..1ee1ec7e49 100644--- a/src/one-home-preview.tsx+++ b/src/one-home-preview.tsx@@ -1,6 +1,6 @@// Dev-only gallery of bringing the bots together on a server of the person's own, served at /one-home-preview.html; not in// the packaged app. It mounts the real rail and account line over fake bridges, with no server behind them.-// ?state=menu|moving|failing|suggest&skin=midnight|daylight&lang=de+// ?state=menu|moving|failing|cloud-failing|suggest&skin=midnight|daylight&lang=deimport { StrictMode, useEffect } from "react";import { createRoot } from "react-dom/client";import type { CloudSendNotice } from "../electron/cloud-send.mjs";@@ -23,7 +23,9 @@ const rail: RailState = { places: [{ id: "local", name: "This computer", color: null, kind: "computer", opens: true, active: true, paint: { swatch: null } },{ id: "garage", name: "Garage server", color: "teal", kind: "server", opens: true, makeHome: true, paint: { swatch: "green" } },], add: { cloud: true, link: true, address: false } };-const move = stateName === "failing"+// cloud-failing: the move to My Cloud whose check keeps finding things missing, as main says it (one-home.mjs INCOMPLETE).+const cloudFailing = { phase: "copy" as const, failing: { error: "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." } };+const move = stateName === "cloud-failing" ? cloudFailing : stateName === "failing"? { phase: "copy" as const, place: "Garage server", failing: { error: "This app isn't signed in to Garage server. Open Garage server in this app, then try again." } }: stateName === "moving" ? { phase: "copy" as const, place: "Garage server", chats: { done: 14, total: 31 } } : null;const notice = { ready: true, bots: [], updatedBots: [], skills: 0, logins: 0, onePassword: false, settings: 0, signature: "", dismissed: false, running: false, last: null, whole: null,