Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Ride out a blip in a move's passes, and prove the whole move at scale
Milind Sonica5c5b311217
diff --git a/electron/cloud-send-big.node-test.mjs b/electron/cloud-send-big.node-test.mjsindex ec8579f420..e9673832a9 100644--- a/electron/cloud-send-big.node-test.mjs+++ b/electron/cloud-send-big.node-test.mjs@@ -3,6 +3,7 @@ import test from "node:test";import { createCloudSend } from "./cloud-send.mjs";import { STALL_MS } from "./cloud-send-check.mjs";+import { createOneHome } from "./one-home.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;@@ -189,3 +190,130 @@ test("a check My Cloud stops answering for longer fails as unanswered, says it gawait mover(changed, later, store).send.check();assert.deepEqual([...new Set(later.conversationsAsked)], ["t-b0-0"]);});++/** The whole workspace as this computer's server answers a move, and an empty My Cloud that keeps what it is sent, each+ * request taking the time its work takes there. Rows and files are small here: what they cost is the model's. */+function wholeMove() {+ const { bots, conversations, manifest: full } = bigWorkspace();+ const data = new TextEncoder().encode("data");+ const sha = "a".repeat(64);+ const manifest = { ...full, files: full.files.map((file) => ({ ...file, size: data.length, sha256: sha })) };+ const rowsOf = new Map(conversations.map((head) => [head.threadId, head.rows]));+ const attachmentsOf = new Map(conversations.map((head) => [head.threadId, []]));+ manifest.attachments.forEach((name, i) => attachmentsOf.get(conversations[i % conversations.length].threadId).push(name));+ const local = async (route) => {+ if (route === "/api/cloud-send?move=1" || route === "/api/cloud-send") return json({ v: 1, appVersion: "0.1.151", items: manifest.items, chats: 1 });+ if (route === "/api/cloud-send/manifest") return json(manifest);+ if (route === "/api/cloud-connections") return json({ computer: { environmentId: "env-desk", label: "Desk" }, connections: [], engines: [], commands: [] });+ if (route === "/api/bots?messages=0") return json({ bots: bots.map((id) => ({ id, threadId: `t-${id}-0`, name: `Bot ${id}`, soul: "s" })) });+ if (/^\/api\/bots\/[\w-]+\/skills$/u.test(route)) return json({ skills: [] });+ if (route.startsWith("/api/cloud-send/kind?key=")) return json({ v: 1, dataDir: "/desk", record: {} });+ if (route.startsWith("/api/cloud-send/memory?bot=")) return json({ v: 1, files: [], journal: [] });+ if (route === "/api/cloud-send/memory") return json({ v: 1, about: { learned: [], removed: [] }, teams: [] });+ if (route === "/api/cloud-send/files") return json({ v: 1, files: manifest.files });+ if (route.startsWith("/api/cloud-send/files?path=")) return new Response(data);+ if (route.startsWith("/api/cloud-send/chats/attachment/")) return new Response(data);+ if (route === "/api/cloud-send/chats?attachments=1") return json({ v: 1, attachments: manifest.attachments.map((name) => ({ name, size: data.length })) });+ if (route === "/api/cloud-send/chats") return json({ v: 1, dataDir: "/desk", rooms: [], conversations: conversations.map((head) => ({ bot: head.bot, threadId: head.threadId, last: head.rows, lastId: head.newest, busy: false, settings: {} })) });+ const rows = /^\/api\/cloud-send\/chats\/rows\?thread=([\w-]+)&after=(\d+)/u.exec(route);+ if (rows) {+ const after = Number(rows[2]), end = Math.min(rowsOf.get(rows[1]), after + 300);+ return json({ rows: Array.from({ length: end - after }, (_, i) => ({ id: `${rows[1]}-${after + i}`, at: after + i })), leaf: `${rows[1]}-${end - 1}`, task: null, last: end, lastId: `${rows[1]}-${end - 1}`,+ more: end < rowsOf.get(rows[1]), restarted: false, attachments: after === 0 ? attachmentsOf.get(rows[1]) : [] });+ }+ const ids = /^\/api\/cloud-send\/chats\/ids\?thread=([\w-]+)&from=(\d+)$/u.exec(route);+ if (ids) {+ const count = rowsOf.get(ids[1]) ?? 0, from = Number(ids[2]);+ const listed = Array.from({ length: Math.max(0, Math.min(5_000, count - from)) }, (_, i) => `${ids[1]}-${from + i}`);+ return json({ v: 1, ids: listed, path: listed, leaf: `${ids[1]}-${count - 1}`, more: from + 5_000 < count });+ }+ return json({}, 404);+ };++ let clock = 1_000_000;+ const asked = [], items = new Map(), chats = new Map(), attachments = new Set(), files = new Set();+ const summaryMs = () => 400 + 30 * BOTS;+ const cost = (method, route, body) => {+ if (route.startsWith("/api/cloud-send/manifest") || route.startsWith("/api/cloud-send?")) return summaryMs();+ if (route === "/api/cloud-send/chats" && method === "POST") return body.conversations.reduce((sum, page) => sum + 2 + 0.25 * page.rows.length, 0);+ if (route === "/api/cloud-send/chats/owner" || route === "/api/cloud-send/chats/verify") return body.conversations.reduce((sum, entry) => sum + 1 + 0.25 * (entry.ids?.length ?? 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 === "/api/cloud-send?move=1") return reply(200, { v: 1, appVersion: "0.1.151", items: [...items.values()], chats: 1 });+ const item = /^\/api\/cloud-send\?item=([^&]+)/u.exec(route);+ if (item) return reply(200, { v: 1, appVersion: "0.1.151", items: [...items.values()].filter((entry) => entry.key === decodeURIComponent(item[1])), chats: 1 });+ if (route === "/api/cloud-connections") return reply(200, { computer: { environmentId: "env-cloud", label: "My Cloud" }, connections: [], engines: ["claude"], commands: ["node"] });+ if (method === "POST" && route === "/api/bots") { items.set(`bot:${body.id}`, manifest.items.find((entry) => entry.id === body.id)); return reply(201, { bot: { id: body.id } }); }+ const listed = /^\/api\/cloud-send\/files\?bot=([\w-]+)$/u.exec(route);+ if (listed) return reply(200, { v: 1, files: manifest.files.filter((file) => files.has(file.path) && file.path.startsWith(`workspaces/${listed[1]}/`)), space: { freeBytes: 1e12, volumeBytes: 1e12 } });+ if (route === "/api/cloud-send/chats/attachments") return reply(200, { missing: body.names.filter((name) => !attachments.has(name)) });+ if (route === "/api/cloud-send/chats" && method === "POST") {+ for (const page of body.conversations) chats.set(page.threadId, (chats.get(page.threadId) ?? 0) + page.rows.length);+ return reply(200, { conversations: body.conversations.length, messages: 0, accepted: body.conversations.map((page) => page.threadId), waiting: [], removed: [] });+ }+ if (route === "/api/cloud-send/chats" && method === "GET") return reply(200, { v: 1, conversations: conversations.filter((head) => chats.has(head.threadId)).map((head) => ({ threadId: head.threadId, settings: {} })) });+ if (route.startsWith("/api/cloud-send/manifest")) {+ const { attachments: _a, files: _f, ...rest } = manifest;+ return reply(200, { ...rest, items: [...items.values()], conversations: conversations.filter((head) => chats.get(head.threadId) === head.rows) });+ }+ if (route === "/api/cloud-send/chats/verify") {+ return reply(200, { v: 1, conversations: body.conversations.map(({ threadId, ids = [], path }) => ({ threadId, missing: ids.filter((id) => Number(id.slice(id.lastIndexOf("-") + 1)) >= (chats.get(threadId) ?? 0)), 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/verify-secrets") return reply(200, { v: 1, secrets: {} });+ return reply(200, { v: 1 });+ };+ const session = {+ async call(method, route, body, options) {+ const limit = options?.timeoutMs ?? 120_000, takes = 400 + cost(method, route, body);+ asked.push({ method, route, takes, limit });+ if (takes > limit) { clock += limit; throw timeout(); }+ clock += takes;+ return answer(method, route, body);+ },+ async upload(route) {+ clock += 400;+ asked.push({ method: "POST", route, takes: 400, limit: 120_000 });+ const file = /^\/api\/cloud-send\/files\?(.*)$/u.exec(route);+ if (file) files.add(new URLSearchParams(file[1]).get("path"));+ else attachments.add(route.slice(route.lastIndexOf("/") + 1));+ return reply(201, { stored: true });+ },+ close: async () => {},+ };+ return { local, session, asked, conversations, manifest, now: () => clock, sleep: async (ms) => { clock += ms; } };+}++test("the whole move of 100 bots and 3,000 conversations, copy to switch, finishes by itself on a slow Cloud, says how far it is, and never starts over", async () => {+ const cloud = wholeMove();+ const store = stored(), lines = [];+ let journal = null, frozen = false, freezes = 0;+ const send = createCloudSend({ local: cloud.local, 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, engineWaitMs: 0, onChange: () => { const seen = home?.view(); if (seen) lines.push(seen); } });+ const timers = [];+ const 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: { move: (options) => send.send({ reason: "move", final: options?.final === true }), check: () => send.check(), switches: () => send.switches(), snapshot: () => send.snapshot() },+ local: {+ freeze: async () => { frozen = true; freezes++; return { frozen: true }; }, unfreeze: async () => { frozen = false; }, frozen: async () => frozen,+ json: async (route) => (await cloud.local(route)).json(), call: async () => reply(200),+ },+ session: async () => cloud.session,+ lastInput: () => 0, now: cloud.now,+ timers: { set: (work, ms) => { timers.push({ work, ms }); return timers.at(-1); }, clear: () => {} },+ });+ const started = cloud.now();+ await home.kick();+ assert.equal(journal.phase, "done", JSON.stringify({ phase: journal.phase, error: journal.error }));+ assert.equal(journal.failure, undefined, "no pass failed");+ assert.equal(freezes, 1, "one freeze, and nothing started over");+ assert.deepEqual(cloud.asked.filter((entry) => entry.takes > entry.limit), [], "no request took longer than it may");+ assert.ok(lines.some((line) => line.phase === "copy" && line.chats?.total === BOTS * CHATS_PER_BOT && line.chats.done > 0), "the copy counts the chats");+ assert.ok(lines.some((line) => line.phase === "finishing" && line.checking?.step === "chats" && line.checking.done > 0 && line.checking.bots === BOTS), "the check counts them too");+ const hours = (cloud.now() - started) / 3_600_000;+ assert.ok(hours < 4, `${hours.toFixed(1)} h on the slow Cloud`);+});diff --git a/electron/cloud-send-check.mjs b/electron/cloud-send-check.mjsindex 999f76cd7e..6f7564591a 100644--- a/electron/cloud-send-check.mjs+++ b/electron/cloud-send-check.mjs@@ -19,7 +19,9 @@ 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;+export const STALL_MS = 10 * 60_000;+/** The waits before a move's pass gives up on a request it can safely ask again: as long as a Cloud takes to start again. */+export const BLIP_MS = Object.freeze([5_000, 15_000, 30_000, 60_000]);/** 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. */@@ -38,16 +40,19 @@ export function answered(answer, message, refuse = null) {throw Object.assign(new Error(message), { status: answer.status });}+const nap = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });+/*** 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.+ * says whether any of the work got done (`progressed`), which the next check does not do again; an answer that only+ * opens the work (`run(work, { counts: false })`) keeps it waiting without counting as work done. `onWait(until)` while it+ * waits, `onWait(null)` once it asks again.*/-export function createPatience({ now = Date.now, sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); }), onWait = () => {}, stallMs = STALL_MS, waits = PATIENCE_MS } = {}) {+export function createPatience({ now = Date.now, sleep = nap, onWait = () => {}, stallMs = STALL_MS, waits = PATIENCE_MS } = {}) {let movedAt = now(), progressed = false, tries = 0;const patience = {- moved() { movedAt = now(); progressed = true; tries = 0; },+ moved({ counts = true } = {}) { movedAt = now(); tries = 0; if (counts) progressed = true; },get progressed() { return progressed; },/** Waits before asking again after `error`, or throws once the check has stood still too long. */async wait(error) {@@ -61,9 +66,9 @@ export function createPatience({ now = Date.now, sleep = (ms) => new Promise((reonWait(null);},/** `work()` until it is answered. */- async run(work) {+ async run(work, { counts = true } = {}) {for (;;) {- try { const value = await work(); patience.moved(); return value; }+ try { const value = await work(); patience.moved({ counts }); return value; }catch (error) { await patience.wait(error); }}},@@ -71,6 +76,36 @@ export function createPatience({ now = Date.now, sleep = (ms) => new Promise((rereturn patience;}+const GATEWAY = new Set([502, 503, 504]);+const REPEATABLE = /^\/api\/cloud-send\/chats(?:[/?]|$)/u;++/**+ * A move's session for its passes: a read, or a chats request My Cloud adds by id, is asked again through a blip (BLIP_MS)+ * instead of ending the pass. What still has no answer after that throws as it did, or comes back as the gateway answered,+ * and says whether anything was answered before it (`progressed`).+ */+export function patientSession(session, { sleep = nap, blips = BLIP_MS } = {}) {+ let answeredOnce = false;+ return {+ ...session,+ async call(method, route, body, options) {+ if (method !== "GET" && !REPEATABLE.test(route)) return session.call(method, route, body, options);+ for (let waited = 0; ; waited++) {+ try {+ const answer = await session.call(method, route, body, options);+ if (!GATEWAY.has(answer.status) || waited >= blips.length) {+ if (!GATEWAY.has(answer.status)) answeredOnce = true;+ return answer;+ }+ } catch (error) {+ if (!unanswered(error) || waited >= blips.length) throw Object.assign(error, { progressed: answeredOnce });+ }+ await sleep(blips[waited]);+ }+ },+ };+}+/** Asks once: what a check without patience does. */const IMPATIENT = { moved() {}, progressed: false, wait: async (error) => { throw error; }, run: (work) => work() };@@ -322,22 +357,22 @@ const BOT_FILE = /^(?:workspaces|task-workspaces)\/([\w-]{1,128})\//u;* 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 = () => {} }) {+export async function moveCheck({ session, kept, persist, localJson, handoff, scoped = (route) => route, now = Date.now, sleep, patience: pace = {}, 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) => {+ const patience = createPatience({ now, ...(sleep ? { sleep } : {}), ...(pace.stallMs !== undefined ? { stallMs: pace.stallMs } : {}), ...(pace.waits ? { waits: pace.waits } : {}), 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));+ const ask = (method, route, timeoutMs, message = "My Cloud did not answer. Try again.", counts = true) =>+ patience.run(async () => answered(await session.call(method, route, undefined, { timeoutMs }), message, refuse), { counts });step("manifest");- await patience.run(takesMove);+ await patience.run(takesMove, { counts: false });const here = await localJson(scoped("/api/cloud-send/manifest"), { timeoutMs: LOCAL_LISTING_MS });const heads = new Map(list(here?.conversations).filter(record).map((head) => [head.threadId, head]));- const there = (await ask("GET", scoped("/api/cloud-send/manifest?attachments=0&files=0"), listingMs(heads.size * 20))).body;+ const there = (await ask("GET", scoped("/api/cloud-send/manifest?attachments=0&files=0"), listingMs(heads.size * 20), undefined, false)).body;if (!record(here) || !record(there)) throw new Error("My Cloud did not say what it has. Try again.");const removed = new Set([...Object.entries(kept.off).filter(([, why]) => why === "removed").map(([key]) => key),...Object.entries(kept.chats).filter(([, cursor]) => cursor === "removed").map(([threadId]) => threadId),@@ -368,7 +403,7 @@ export async function moveCheck({ session, kept, persist, localJson, handoff, scstep("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 secrets = handoff ? await patience.run(() => checkSecrets({ handoff, session, skip: new Set([...removed, ...refused]) }), { counts: false }) : { 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.diff --git a/electron/cloud-send-main.d.mts b/electron/cloud-send-main.d.mtsindex 64b4044468..29e8a9469a 100644--- a/electron/cloud-send-main.d.mts+++ b/electron/cloud-send-main.d.mts@@ -19,6 +19,7 @@ export function installCloudSend(deps: {fetch?: typeof fetch;t?(key: string, params?: Record<string, string | number>): string;engineWaitMs?: number;+ patience?: { stallMs?: number; waits?: number[]; blips?: number[] };space?: { disk(): unknown; grow(sizeGb: number): Promise<unknown> };move?: () => { view(): unknown; seen(): unknown; retry(): Promise<unknown> } | null;/** The one session every pass of the move uses (move-session.mjs). */diff --git a/electron/cloud-send-main.mjs b/electron/cloud-send-main.mjsindex f74afab8b6..c681ffdf80 100644--- a/electron/cloud-send-main.mjs+++ b/electron/cloud-send-main.mjs@@ -79,7 +79,7 @@ export async function openOwnerSession(target, fetchImpl, { label = SESSION_LABE* `moveSession`: the one session every pass of the move uses (move-session.mjs); without it each pass opens its own.*/export function installCloudSend({ ipcMain, cloudPage, server, local, home, cookieFetch, reconnect, power, file, window, localOrigin,- fetch: fetchImpl = globalThis.fetch, engineWaitMs, space, move = () => null, teamMove = () => null, moveSession = null, t }) {+ fetch: fetchImpl = globalThis.fetch, engineWaitMs, patience, space, move = () => null, teamMove = () => null, moveSession = null, t }) {const handoff = createLoginHandoffClient();const pageOf = () => {const win = window();@@ -127,6 +127,7 @@ export function installCloudSend({ ipcMain, cloudPage, server, local, home, cook},onChange: deliver,engineWaitMs,+ ...(patience ? { patience } : {}),space,t,});diff --git a/electron/cloud-send-move.node-test.mjs b/electron/cloud-send-move.node-test.mjsindex 99d993dfae..97ca176d53 100644--- a/electron/cloud-send-move.node-test.mjs+++ b/electron/cloud-send-move.node-test.mjs@@ -88,6 +88,7 @@ function sides({ here = [], bots = {}, there = [], connections = [], secrets = {},store: stored(),engineWaitMs: 0,+ patience: { stallMs: 0, waits: [0], blips: [] },};return { calls, cloud, deps, opened, asked };}diff --git a/electron/cloud-send-parts.mjs b/electron/cloud-send-parts.mjsindex c1b3e26a7e..aa9e308b46 100644--- a/electron/cloud-send-parts.mjs+++ b/electron/cloud-send-parts.mjs@@ -65,7 +65,7 @@ const HASH = /^[\w:.-]{1,80}$/u;export function parseSendSummary(value) {if (!record(value) || value.v !== 1 || !Array.isArray(value.items)) return null;const items = [];- for (const item of value.items.slice(0, 20_000)) {+ for (const item of value.items.slice(0, 200_000)) {if (!record(item) || typeof item.key !== "string" || !KEY.test(item.key) || !KINDS.includes(item.kind) || !record(item.parts)) continue;const parts = Object.fromEntries(Object.entries(item.parts).filter(([part, hash]) => PART.test(part) && typeof hash === "string" && HASH.test(hash)));items.push({diff --git a/electron/cloud-send.d.mts b/electron/cloud-send.d.mtsindex c44bf39b80..c10671cfb8 100644--- a/electron/cloud-send.d.mts+++ b/electron/cloud-send.d.mts@@ -197,6 +197,8 @@ export function createCloudSend(deps: {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 a Cloud that does not answer: `stallMs` and `waits` in a check, `blips` in a pass. */+ patience?: { stallMs?: number; waits?: number[]; blips?: number[] };/** 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 05a172193a..b34a53ca88 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 { moveCheck, rowIdChunks, unanswered } from "./cloud-send-check.mjs";+import { moveCheck, patientSession, 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;@@ -202,14 +202,15 @@ const movedResult = () => ({ moved: 0, memory: 0, files: { sent: 0, kept: 0 }, c* engineWaitMs?: number,* space?: { disk(): unknown, grow(sizeGb: number): Promise<unknown> },* team?: { bot: string, name: string, label: string },- * }} deps `open({ move: true })`: the move's session, which counts as someone using My Cloud. `engineWaitMs`: how long a+ * patience?: { stallMs?: number, waits?: number[], blips?: number[] },+ * }} deps `patience`: how long a move waits for a Cloud that does not answer (cloud-send-check.mjs). `open({ move: true })`: the move's session, which counts as someone using My Cloud. `engineWaitMs`: how long a* move waits for My Cloud to run the engines whose keys it just took. `local(route, { method })`: a change on this* computer's server (an app event My Cloud now collects). `space`: My Cloud's plan disk and the Admin's grow. `team`: a* move of this one bot into a team (team-move.mjs): only the bot, its skills, files, chats and routines go, under the* 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, sleep, engineWaitMs, space, team = null, t = nativeText.englishText.t }) {+export function createCloudSend({ local, cloud, handoff, store, onChange = () => {}, now = Date.now, sleep, patience = {}, 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, checking = null;@@ -383,7 +384,8 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>async function sendItems(origin, mine, result, { keys, force, job, withChats }) {const move = job.reason === "move";const summaryRoute = move ? scoped("/api/cloud-send?move=1") : "/api/cloud-send";- const session = await cloud.open(move ? { move: true } : undefined).catch((error) => { throw new CloudSendError("session", sentence(error?.message) ?? "This app could not sign in to My Cloud. Try again.", { cause: error }); });+ const opened = await cloud.open(move ? { move: true } : undefined).catch((error) => { throw new CloudSendError("session", sentence(error?.message) ?? "This app could not sign in to My Cloud. Try again.", { cause: error }); });+ const session = move && !team ? patientSession(opened, { ...(sleep ? { sleep } : {}), ...(patience.blips ? { blips: patience.blips } : {}) }) : opened;try {const before = await session.call("GET", summaryRoute);if (before.status === 404) throw new CloudSendError("outdated", move ? OUTDATED_FOR_MOVE : "My Cloud needs an update before it can receive bots from this computer. It updates by itself; try again later.");@@ -896,7 +898,7 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>if (!origin) throw new CloudSendError("no_cloud", "This computer has no My Cloud yet.");const session = await cloud.open({ move: true }).catch((error) => { throw new CloudSendError("session", sentence(error?.message) ?? "This app could not sign in to My Cloud. Try again.", { cause: error }); });try {- return await moveCheck({ session, kept: entry(origin), persist, localJson, handoff: team ? null : handoff, scoped, now, sleep, takesMove: () => assertTakesMove(session),+ return await moveCheck({ session, kept: entry(origin), persist, localJson, handoff: team ? null : handoff, scoped, now, sleep, patience, takesMove: () => assertTakesMove(session),refuse: (answer, message) => refusedError("unreachable", answer, message), onStep: (value) => { checking = value; publish(); } });} catch (error) {if (error?.code === "slow") throw Object.assign(new CloudSendError("unreachable", sentence(error.message) ?? "My Cloud did not answer.", { cause: error.cause }), { progressed: error.progressed === true });diff --git a/scripts/testing/cloud-send-fixture.ts b/scripts/testing/cloud-send-fixture.tsindex 371fc463b0..ee86c1045d 100644--- a/scripts/testing/cloud-send-fixture.ts+++ b/scripts/testing/cloud-send-fixture.ts@@ -407,6 +407,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cllocalOrigin: () => desktopBase,fetch: throughEdge(null) as typeof fetch,engineWaitMs: 2_000,+ patience: { stallMs: 0, waits: [0], blips: [] },...(space ? { space } : {}),account: () => ({ state: () => account.state, pairHome: async () => ({ origin: cloudBase, code: await mintCode("OpenMausBot app (Cloud)"), expiresAt: Date.now() + 300_000 }), exportHome: (options) => account.exportHome(options),reportMove: async (options) => (account.reportMove ? account.reportMove(options) : false), reportKept: async (options) => (account.reportKept ? account.reportKept(options) : false),@@ -485,6 +486,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cllocalOrigin: () => base,fetch: throughEdge(null) as typeof fetch,engineWaitMs: 2_000,+ patience: { stallMs: 0, waits: [0], blips: [] },account: () => ({ state: () => deskAccount.state, pairHome: async () => ({ origin: cloudBase, code: await mintCode("OpenMausBot app (Cloud)"), expiresAt: Date.now() + 300_000 }), exportHome: (options) => deskAccount.exportHome(options),reportMove: async (options) => (deskAccount.reportMove ? deskAccount.reportMove(options) : false), reportKept: async (options) => (deskAccount.reportKept ? deskAccount.reportKept(options) : false),pairTeam: (teamId: string) => deskAccount.pairTeam(teamId) }),