Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
This computer and My Cloud together: on by default with a one-time notice, for My Cloud as home too (#7566)
Milind Soni77d4299e62c4
diff --git a/docs/multi-device.md b/docs/multi-device.mdindex dffc58f9c5..7e48a683d0 100644--- a/docs/multi-device.md+++ b/docs/multi-device.md@@ -15,7 +15,7 @@ to the other by itself. Unless both computers open the same home (below), each hempty Inbox, and a bot created on one computer does not appear in the other's list. Engine sign-ins (Claude, Codex andthe rest) are separate too, because they belong to the machine the bots run on.-Each bot lives in one place, and bots work together within one home. The one exception is a computer and its own My Cloud: with **Settings → MausBot Cloud → This computer and My Cloud together** on (an early feature, off by default), a bot in one can hand work to a bot in the other while both are reachable.+Each bot lives in one place, and bots work together within one home. The one exception is a computer and its own My Cloud: with **Settings → Plan & billing → This computer and My Cloud together** on, a bot in one can hand work to a bot in the other while both are reachable, and this computer's sidebar lists both places' bots. It is on by default: the desktop app turns it on the first time it shows a short notice about it on this computer's page, with a switch right there to turn it off. Someone who chose either way keeps their choice. When My Cloud is home, it joins the workspace of this computer that is running (This Mac or This PC), never the copy the move left behind. The default never lets your Clouds' bots run commands on this computer: that stays its own switch, in the notice and in the OpenMausBot icon's menu, and it asks before it turns on. Only turning the setting on by hand in Settings turns it on too, as that setting says; Show bots together in the rail's menu switches the list alone. With My Cloud as home and the setting on, the app starts This Mac's workspace in the background a little after launch (only if it has bots), so the list and hand-offs work without opening it first.## One set of bots on every devicediff --git a/electron/bot-link-main.mjs b/electron/bot-link-main.mjsindex 1f183d4f5d..949cf4e05d 100644--- a/electron/bot-link-main.mjs+++ b/electron/bot-link-main.mjs@@ -6,9 +6,10 @@// out, or either changes, main ends it on this computer at once, and this computer's server tells that Cloud (now, or// when main next says it is awake).//-// A Cloud that sleeps is never started for the link's sake: pairing is a background request made only while the Admin-// says the Cloud is awake (or the person has just turned the switch on), a refusal is not asked again for hours, and-// main passes the Admin's word on to this computer's server every minute so its end sleeps and wakes with the Cloud.+// A Cloud that sleeps is never started for the link's sake: anything main sends it, and the "awake" main passes on to this+// computer's server (which then asks it), waits until the Admin answered just now that it is awake: main's last word can be+// a minute old, and a Cloud that went to sleep since would be started again by one request. Only the person's own turn on+// pairs at once. Nothing of this in the app's first `quietMs`; a refusal is not asked again for hours.// "Asleep" goes with the time main first heard it, so that end can tell the Admin's lagging word from the Cloud's own// answers since (server/bot-link/dial.ts).//@@ -16,7 +17,7 @@// team's Cloud. The link's sign-in goes from My Cloud to this computer's server and nowhere else; no page sees it.import { linkedAddress } from "./bot-link-address.mjs";import { BACKGROUND_HEADERS } from "./cloud-power.mjs";-import { parseTogether } from "./places-together.mjs";+import { readTogether } from "./places-together.mjs";const STATE = "/api/bot-link";const PAIR = "/api/bot-link/pair";@@ -26,6 +27,10 @@ const WATCH_MS = 60_000;export const RETRY_MS = 6 * 60 * 60_000;/** A Cloud on a version without the link is asked again once a day (or when the app starts, or the switch is turned on again). */export const OUTDATED_RETRY_MS = 24 * 60 * 60_000;+/** The Admin is asked again about the Cloud's sleep for the link at most this often. */+export const ADMIN_EVERY_MS = 60_000;+/** An answer from the Admin that the Cloud is awake still counts as "just now" this long (one look's own steps). */+export const FRESH_AWAKE_MS = 5_000;async function body(response) {try { return await response.json(); } catch { return null; }@@ -34,7 +39,13 @@ async function body(response) {/*** @param {{* wanted(): boolean,- * pref: { read(): unknown },+ * pref?: { read(): unknown },+ * switchedOff?(): boolean,+ * chosen?(): boolean | null,+ * powerChecked?(): Promise<boolean>,+ * napped?(): void,+ * proved?(): void,+ * quietMs?: number,* localRequest(route: string, init?: RequestInit): Promise<Response>,* fetch: typeof fetch,* cloud(): { origin: string | null, account: string | null, asleep: boolean, since?: string | number | null, signedOut?: boolean },@@ -44,12 +55,18 @@ async function body(response) {* watchMs?: number,* now?(): number,* }} deps `wanted()`: the switch is on and both places exist. `pref`: the switch's own file: turning it off ends a- * link (My Cloud not being seen for a moment leaves it alone, and so does a file that cannot be read). `cloud()`: My+ * link (My Cloud not being seen for a moment leaves it alone). `switchedOff()` and `chosen()` (places-together.mjs) stand+ * in for it: off also while the person never chose and has not seen the notice of the default; `chosen()` is the person's+ * own choice, and only their own turn on pairs with a Cloud the Admin says sleeps. `powerChecked()`: asks the Admin again,+ * true once it answered just now (at most every ADMIN_EVERY_MS from here). `napped()`: this computer's end heard My Cloud+ * itself answer that it sleeps; main holds it asleep (cloud-power.mjs `hold`), as Files and lending do, so the Admin's+ * lagging "awake" starts nothing. `proved()`: this computer's end has My Cloud's own answer, since that, to work a person+ * waits on: it is awake, so the hold ends at once (cloud-power.mjs `woke`). `cloud()`: My* Cloud's address and the signed-in account while the person has them, whether the Admin says it sleeps now (and* since when, in its words: a new `since` is a new word), and whether the person signed out. `cloudName()`: what the app calls My Cloud, in the person's language. `changed()`: the* addresses `address` gives changed (the link came, went, or is another Cloud's now).*/-export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImpl, cloud, cloudName, changed = () => {}, log = () => {}, watchMs = WATCH_MS, now = Date.now }) {+export function createBotLinkMain({ wanted, pref = null, switchedOff = null, chosen = null, powerChecked = null, napped = () => {}, proved = () => {}, quietMs = 0, localRequest, fetch: fetchImpl, cloud, cloudName, changed = () => {}, log = () => {}, watchMs = WATCH_MS, now = Date.now }) {const local = async (method, payload) => {const response = await localRequest(STATE, { method, signal: AbortSignal.timeout(15_000),...(payload === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(payload) }) });@@ -57,6 +74,7 @@ export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImplif (!response?.ok) throw Object.assign(new Error(answer?.error ?? `This computer's server answered ${response?.status}`), { status: response?.status });return answer ?? { on: false };};+ /** This computer's server, as the link knows it: read again once another workspace of this computer's runs. */let computer = null;const thisComputer = async () => {if (computer) return computer;@@ -104,8 +122,29 @@ export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImpltry { changed(); } catch {}};- const switchedOff = () => { try { return !parseTogether(pref.read()); } catch (error) { return error?.code === "ENOENT"; } };- let retryAt = -Infinity, switchWasOn = null, looking = null, idle = false;+ const readChoice = () => (chosen ? chosen() : readTogether(() => pref?.read()).choice);+ // A file that can't be read just now leaves a link alone.+ const isOff = () => { if (switchedOff) return switchedOff(); const read = readTogether(() => pref?.read()); return !read.unreadable && !read.foreign && read.choice !== true; };+ let retryAt = -Infinity, choseOn = null, looking = null, idle = false;+ const quietUntil = now() + quietMs;+ let heardNap = -Infinity, heardProof = -Infinity;+ let askedAdminAt = -Infinity, awakeAt = -Infinity;+ /** When the Admin said just now, after `after`, that the Cloud is awake (this computer's clock), else null: what main+ * needs before it sends the Cloud anything, or tells this computer's server it is awake. Never in the quiet start. */+ async function awakeNow(after = -Infinity) {+ if (now() < quietUntil || cloud().asleep) return null;+ // The Admin's answer from a moment ago (the same look) is still its answer just now: not asked again, nor refused.+ if (now() - awakeAt < FRESH_AWAKE_MS) return awakeAt > after ? awakeAt : null;+ if (powerChecked) {+ if (now() - askedAdminAt < ADMIN_EVERY_MS) return null;+ askedAdminAt = now();+ let answered = false;+ try { answered = await powerChecked(); } catch {}+ if (!answered || cloud().asleep) return null;+ }+ const at = awakeAt = now();+ return at > after ? at : null;+ }/** The Admin's "asleep" and when main first heard it, on this computer's clock: heard again when the Admin's `since`* moves on or it said awake in between. */let heard = null;@@ -125,18 +164,28 @@ export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImpl}async function reconcile() {idle = false;- const heardAt = hearing(cloud());const state = await local("GET").catch(() => null);if (!state) return;if (state.on) await thisComputer().catch(() => null);note(state);- const mine = cloud(), off = switchedOff();- const justOn = switchWasOn === false && !off;- switchWasOn = !off;+ // My Cloud's own word that it sleeps, as this computer's end last heard it: held before anything below reads cloud().+ if (Number.isFinite(state.cloudAsleepAt) && state.cloudAsleepAt > heardNap) { heardNap = state.cloudAsleepAt; try { napped(); } catch {} }+ // Its own answer since, to work a person waits on, says it is awake: that ends the hold at once.+ const answered = Number.isFinite(state.answeredAt) ? state.answeredAt : -Infinity;+ if (answered > heardNap && answered > heardProof) { heardProof = answered; try { proved(); } catch {} }+ // When main first heard "asleep", read after the hold above, so every "asleep" goes with it.+ const heardAt = hearing(cloud());+ const mine = cloud(), off = isOff(), own = readChoice() === true;+ // Only the person's own turn on, never the default's start: a Cloud the Admin says sleeps is left asleep for that.+ const justOn = choseOn === false && own && !off;+ choseOn = own;if (!state.on) {// A link that ended while its Cloud slept or could not be reached: this computer's server tells that Cloud now.- if (mine.origin && !mine.asleep && Array.isArray(state.ended) && state.ended.includes(mine.origin)) await local("PUT", { cloud: "awake", origin: mine.origin }).catch(() => {});- if (wanted() && !mine.signedOut && (justOn || !mine.asleep)) await tryPair(justOn);+ if (mine.origin && !mine.asleep && Array.isArray(state.ended) && state.ended.includes(mine.origin)) {+ const at = await awakeNow();+ if (at !== null) await local("PUT", { cloud: "awake", origin: mine.origin, heardAt: at }).catch(() => {});+ }+ if (wanted() && !mine.signedOut && (justOn || !mine.asleep)) { if (justOn || (now() >= retryAt && await awakeNow() !== null)) await tryPair(justOn); }// Off, with nothing linked and nothing left to tell a Cloud: the timer has no more to do until something changes.else idle = off && !(Array.isArray(state.ended) && state.ended.length);return;@@ -152,10 +201,15 @@ export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImplreturn;}if (!mine.origin) return;- if (state.needsPairing) { if (!mine.asleep) await tryPair(false); return; }+ if (state.needsPairing) { if (!mine.asleep && now() >= retryAt && await awakeNow() !== null) await tryPair(false); return; }// The Admin's word, passed on for this link's own Cloud only, for as long as this computer's end disagrees with it.- if (mine.asleep && !state.asleep) await local("PUT", { cloud: "asleep", origin: mine.origin, ...(heardAt === null ? {} : { heardAt }) });- else if (!mine.asleep && state.asleep) await local("PUT", { cloud: "awake", origin: mine.origin });+ // Never for a Cloud that answered work since main heard it: it is awake, whatever the word says.+ if (mine.asleep && !state.asleep) { if (heardAt !== null && answered < heardAt) await local("PUT", { cloud: "asleep", origin: mine.origin, heardAt }); }+ else if (!mine.asleep && state.asleep) {+ // Only an Admin answer from after the link parked: the one main holds may be from before the Cloud went to sleep.+ const at = await awakeNow(Number.isFinite(state.parkedAt) ? state.parkedAt : -Infinity);+ if (at !== null) await local("PUT", { cloud: "awake", origin: mine.origin, heardAt: at });+ }}/** Brings the link in line with the switch, the account and the Cloud: now, when any of them changes, and every minute. */function look() {@@ -168,6 +222,8 @@ export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImplvoid look();return {look,+ /** Another of this computer's own workspaces runs now (or the same one started again): its link is its own. */+ serverChanged() { computer = null; known = null; addressed = ""; retryAt = -Infinity; try { changed(); } catch {} return look(); },/** The address over the link of a bot the sidebar lists for `home`: where the other place's bots know it, and where* this place's stand-in for it is found. Null while no link of this Cloud and account is on, so a row never carries* an address that belongs to another Cloud's or another account's link. */diff --git a/electron/bot-link-main.node-test.mjs b/electron/bot-link-main.node-test.mjsindex 7c71de6697..4ded9f6078 100644--- a/electron/bot-link-main.node-test.mjs+++ b/electron/bot-link-main.node-test.mjs@@ -2,11 +2,11 @@ import assert from "node:assert/strict";import test from "node:test";import { linkedAddress } from "./bot-link-address.mjs";-import { createBotLinkMain, OUTDATED_RETRY_MS, RETRY_MS } from "./bot-link-main.mjs";+import { createBotLinkMain, ADMIN_EVERY_MS, OUTDATED_RETRY_MS, RETRY_MS } from "./bot-link-main.mjs";const CLOUD = "https://omb-u-1.fly.dev";-function harness({ origin = CLOUD, pairStatus = 200, on = false, putFails = false, watchMs = 3_600_000 } = {}) {+function harness({ origin = CLOUD, pairStatus = 200, on = false, putFails = false, watchMs = 3_600_000, deps = {} } = {}) {const cloudCalls = [], localCalls = [];let server = { on: false };const the = { switch: on, asleep: false, origin, account: "account-1", signedOut: false, clock: 1_000_000, unreadable: false, putFails };@@ -15,7 +15,7 @@ function harness({ origin = CLOUD, pairStatus = 200, on = false, putFails = falswanted: () => the.switch && Boolean(the.origin),pref: { read: () => { if (the.unreadable) throw new Error("busy"); return { v: 1, on: the.switch }; } },localRequest: async (route, init = {}) => {- if (route === "/.well-known/openmausbot/environment") return answer(200, { environmentId: "11111111-1111-4111-8111-111111111111", label: "Sam's Mac" });+ if (route === "/.well-known/openmausbot/environment") return answer(200, { environmentId: the.environmentId ?? "11111111-1111-4111-8111-111111111111", label: "Sam's Mac" });const sent = init.body ? JSON.parse(init.body) : undefined;localCalls.push({ method: init.method ?? "GET", ...(sent ? { body: sent } : {}) });if (init.method === "PUT" && sent.on === true) {@@ -35,6 +35,7 @@ function harness({ origin = CLOUD, pairStatus = 200, on = false, putFails = falswatchMs,changed: () => { the.changes = (the.changes ?? 0) + 1; },now: () => the.clock,+ ...(typeof deps === "function" ? deps(the) : deps),});const pairs = () => cloudCalls.filter((call) => call.method === "POST").length;return { cloudCalls, localCalls, link, the, pairs, set server(next) { server = next; }, get server() { return server; } };@@ -205,10 +206,10 @@ test("the Admin's word on sleep goes to this computer's server for its own Cloudassert.equal(h.localCalls.filter((call) => call.method === "PUT").length, puts);h.the.asleep = false;await h.link.look();- assert.deepEqual(h.localCalls.at(-1), { method: "PUT", body: { cloud: "awake", origin: CLOUD } });+ assert.deepEqual(h.localCalls.at(-1), { method: "PUT", body: { cloud: "awake", origin: CLOUD, heardAt: 1_000_000 } });h.server = { ...h.server, asleep: true };await h.link.look();- assert.deepEqual(h.localCalls.at(-1), { method: "PUT", body: { cloud: "awake", origin: CLOUD } });+ assert.deepEqual(h.localCalls.at(-1), { method: "PUT", body: { cloud: "awake", origin: CLOUD, heardAt: 1_000_000 } });const asked = h.cloudCalls.length;h.server = { ...h.server, needsPairing: true };h.the.asleep = true;@@ -223,7 +224,7 @@ test("the Admin's word on sleep goes to this computer's server for its own Cloudassert.equal(ended.localCalls.some((call) => call.method === "PUT"), false);ended.the.asleep = false;await ended.link.look();- assert.deepEqual(ended.localCalls.filter((call) => call.method === "PUT"), [{ method: "PUT", body: { cloud: "awake", origin: CLOUD } }]);+ assert.deepEqual(ended.localCalls.filter((call) => call.method === "PUT"), [{ method: "PUT", body: { cloud: "awake", origin: CLOUD, heardAt: 1_000_000 } }]);});test("\"asleep\" goes with when main first heard it: the same word keeps its time, a new one (a new since, or awake between) gets a new time", async (t) => {@@ -250,3 +251,124 @@ test("\"asleep\" goes with when main first heard it: the same word keeps its timawait h.link.look();assert.deepEqual(sleeps(), [1_000_000, 1_000_000, 1_120_000, 1_180_000]);});++test("on by default (never chosen, notice seen): it links like a switch turned on, but only after a quiet start and the Admin's fresh word that the Cloud is awake", async (t) => {+ const h = harness({ deps: (the) => ({ wanted: () => the.byDefault && Boolean(the.origin), switchedOff: () => !the.byDefault, chosen: () => null, quietMs: 15_000,+ powerChecked: async () => { the.checks = (the.checks ?? 0) + 1; return the.adminAnswers !== false; } }) });+ t.after(() => h.link.close());+ h.the.asleep = true;+ await h.link.look();+ h.the.byDefault = true;+ await h.link.look();+ assert.equal(h.pairs(), 0, "the default turning on is not the person's own turn on: a sleeping Cloud stays asleep");+ h.the.asleep = false;+ await h.link.look();+ assert.deepEqual([h.pairs(), h.the.checks ?? 0], [0, 0], "nothing in the app's first seconds, not even the Admin");+ h.the.clock += 15_000;+ h.the.adminAnswers = false;+ await h.link.look();+ assert.deepEqual([h.pairs(), h.the.checks], [0, 1], "the Admin could not say just now: My Cloud is not asked");+ await h.link.look();+ assert.equal(h.the.checks, 1, "and the Admin is not asked again for a while");+ h.the.clock += ADMIN_EVERY_MS;+ h.the.adminAnswers = true;+ await h.link.look();+ assert.equal(h.pairs(), 1, "paired once the Admin says just now that it is awake");+ assert.equal(h.server.on, true);+ h.the.byDefault = false;+ await h.link.look();+ assert.equal(h.server.on, false, "turned off: the link ends");+});++test("another of this computer's workspaces starts: the link reads its server again and pairs it as itself", async (t) => {+ const h = harness({ on: true });+ t.after(() => h.link.close());+ await h.link.look();+ assert.equal(h.cloudCalls.find((call) => call.method === "POST").body.computer.id, "11111111-1111-4111-8111-111111111111");+ h.the.environmentId = "22222222-2222-4222-8222-222222222222";+ h.server = { on: false };+ await h.link.serverChanged();+ const pairs = h.cloudCalls.filter((call) => call.method === "POST");+ assert.equal(pairs.length, 2);+ assert.equal(pairs[1].body.computer.id, "22222222-2222-4222-8222-222222222222");+ assert.equal(h.link.address("computer", "scout"), linkedAddress("22222222-2222-4222-8222-222222222222", "scout"));+});++test("a link that parked as its Cloud went to sleep is never told awake on the Admin's older word: only on an answer from after the park, asked at most once a minute and never in the app's first seconds", async (t) => {+ const h = harness({ on: true, deps: (the) => ({ quietMs: 15_000, powerChecked: async () => { the.checks = (the.checks ?? 0) + 1; the.clock += 200; return the.adminAnswers !== false; } }) });+ t.after(() => h.link.close());+ // Linked before this launch; this computer's server parked as it started (or as its Cloud went to sleep).+ h.server = { on: true, role: "dialer", online: false, origin: CLOUD, account: "account-1", peer: { id: "cloud-1", name: "My Cloud" }, bots: 0, waiting: 0, asleep: true, parkedAt: h.the.clock, needsPairing: false };+ await h.link.look();+ const awake = () => h.localCalls.filter((call) => call.method === "PUT" && call.body.cloud === "awake");+ assert.deepEqual([awake(), h.the.checks ?? 0], [[], 0], "the app's first seconds: nothing, not even the Admin");+ h.the.clock += 15_000;+ h.the.adminAnswers = false;+ await h.link.look();+ assert.deepEqual([awake(), h.the.checks], [[], 1], "the Admin's last word says awake, but it could not say so just now: the link stays parked");+ await h.link.look();+ assert.equal(h.the.checks, 1, "and the Admin is not asked again within the minute");+ h.the.clock += ADMIN_EVERY_MS;+ h.the.adminAnswers = true;+ await h.link.look();+ assert.equal(awake().length, 1, "an answer from just now, after the park: told once");+ assert.equal(awake()[0].body.heardAt > h.server.parkedAt, true, "with when it was heard, so this computer's end can tell it is newer than its park");+ assert.equal(h.cloudCalls.length, 0, "main itself asked My Cloud nothing");+});++test("My Cloud's own answer that it sleeps is held as asleep, as Files and lending hold theirs: with no lending running, the Admin's lagging awake starts nothing", async (t) => {+ const h = harness({ on: true, deps: (the) => ({ powerChecked: async () => { the.checks = (the.checks ?? 0) + 1; return true; }, napped: () => { the.naps = (the.naps ?? 0) + 1; the.asleep = true; } }) });+ t.after(() => h.link.close());+ await h.link.look();+ h.localCalls.length = 0;+ h.the.checks = 0;+ h.the.clock += ADMIN_EVERY_MS;+ h.server = { on: true, role: "dialer", online: false, origin: CLOUD, account: "account-1", peer: { id: "cloud-1", name: "My Cloud" }, bots: 0, waiting: 0, asleep: true, parkedAt: h.the.clock, cloudAsleepAt: h.the.clock, needsPairing: false };+ await h.link.look();+ const awake = () => h.localCalls.filter((call) => call.method === "PUT" && call.body.cloud === "awake");+ assert.deepEqual([h.the.naps, awake(), h.the.checks ?? 0], [1, [], 0], "held before anything else reads the Cloud's state: no awake, and not even the Admin");+ await h.link.look();+ assert.equal(h.the.naps, 1, "the same answer is held once");+ h.the.asleep = false;+ h.the.clock += 1_000;+ await h.link.look();+ assert.equal(awake().length, 1, "once the hold is over and the Admin says awake just now, the link is told");+});++test("work a person waits on that wakes the Cloud during the hold ends the hold at once, and main never sends asleep for a Cloud that answered since it heard it", async (t) => {+ const h = harness({ on: true, deps: (the) => ({ powerChecked: async () => true, napped: () => { the.held = true; the.asleep = true; }, proved: () => { the.proofs = (the.proofs ?? 0) + 1; the.held = false; the.asleep = false; } }) });+ t.after(() => h.link.close());+ await h.link.look();+ h.the.clock += ADMIN_EVERY_MS;+ const parked = h.the.clock;+ h.server = { on: true, role: "dialer", online: false, origin: CLOUD, account: "account-1", peer: { id: "cloud-1", name: "My Cloud" }, bots: 0, waiting: 0, asleep: true, parkedAt: parked, cloudAsleepAt: parked, needsPairing: false };+ await h.link.look();+ assert.equal(h.the.held, true, "the Cloud's own asleep is held");+ // A person's hand-off wakes it: this computer's end has its answer, and is no longer parked.+ h.the.clock += 5_000;+ h.server = { ...h.server, asleep: false, online: true, answeredAt: h.the.clock };+ h.localCalls.length = 0;+ await h.link.look();+ assert.deepEqual([h.the.proofs, h.the.held], [1, false], "its answer ends the hold at once");+ assert.equal(h.localCalls.some((call) => call.method === "PUT" && call.body.cloud === "asleep"), false, "no asleep for a Cloud that answered");+ // The Admin's lagging word still says asleep, heard before that answer: still nothing is sent.+ h.the.asleep = true; h.the.since = "before-the-answer";+ h.the.clock -= 10_000;+ await h.link.look();+ assert.equal(h.localCalls.some((call) => call.method === "PUT" && call.body.cloud === "asleep"), false);+ assert.equal(h.localCalls.filter((call) => call.method === "PUT").every((call) => typeof call.body.heardAt === "number"), true, "every word main passes on says when it was heard");+});++test("one look that needs the Admin's fresh awake twice (tell an ended link, then pair) asks it once and uses that answer for both", async (t) => {+ const h = harness({ deps: (the) => ({ wanted: () => Boolean(the.origin), switchedOff: () => false, chosen: () => null, powerChecked: async () => { the.checks = (the.checks ?? 0) + 1; return true; } }) });+ t.after(() => h.link.close());+ await h.link.look();+ const pairs = h.pairs(), checks = h.the.checks ?? 0;+ h.localCalls.length = 0;+ h.the.clock += ADMIN_EVERY_MS;+ h.server = { on: false, ended: [CLOUD] };+ await h.link.look();+ assert.equal(h.localCalls.some((call) => call.method === "PUT" && call.body.cloud === "awake"), true, "the ended link is told");+ assert.equal(h.pairs() - pairs, 1, "and the pairing goes in the same look, on the same answer");+ assert.equal(h.the.checks - checks, 1);+});diff --git a/electron/clean-workspace.d.mts b/electron/clean-workspace.d.mtsindex 1beb0ea354..5a36686bce 100644--- a/electron/clean-workspace.d.mts+++ b/electron/clean-workspace.d.mts@@ -12,8 +12,8 @@ export interface CleanWorkspace {ownCopy(): boolean;marker(): { frozen: boolean; cloud?: string; place?: string };enter(): Promise<boolean>;- open(id?: string): Promise<boolean>;- leave(): Promise<boolean>;+ open(id?: string, options?: { background?: boolean }): Promise<boolean>;+ leave(options?: { background?: boolean }): Promise<boolean>;settled(): Promise<unknown>;holding<T>(work: () => Promise<T>): Promise<T>;realCopy(request: (route: string, init?: RequestInit) => Promise<Response>): (route: string, init?: RequestInit) => Promise<Response>;@@ -21,7 +21,7 @@ export interface CleanWorkspace {export function createCleanWorkspace(deps: {dataDir(): string;running(): string | null;- swap(dir: string): Promise<{ ok: boolean }>;+ swap(dir: string, how?: { background: true }): Promise<{ ok: boolean }>;allowed?(): boolean;t?(key: string, params?: Record<string, string | number>): string;changed?(): void;diff --git a/electron/clean-workspace.mjs b/electron/clean-workspace.mjsindex bc7e5abf75..4b6d6beabd 100644--- a/electron/clean-workspace.mjs+++ b/electron/clean-workspace.mjs@@ -47,7 +47,7 @@ export function cleanWorkspaceConfig(language = null, now = new Date()) {* @param {{* dataDir(): string,* running(): string | null,- * swap(dir: string): Promise<{ ok: boolean }>,+ * swap(dir: string, how?: { background: true }): Promise<{ ok: boolean }>,* allowed?(): boolean,* changed?(): void,* log?(line: string): void,@@ -86,15 +86,15 @@ export function createCleanWorkspace({ dataDir, running, swap, allowed = () => ttry { fs.writeFileSync(path.join(dir, "config.json"), JSON.stringify(cleanWorkspaceConfig(language)), { mode: 0o600, flag: "wx" }); }catch (error) { if (error?.code !== "EEXIST") throw error; }}- async function swapTo(dir) {+ async function swapTo(dir, how) {swapping = true;- const done = await swap(dir).catch((error) => ({ ok: false, error })).finally(() => { swapping = false; });+ const done = await (how ? swap(dir, how) : swap(dir)).catch((error) => ({ ok: false, error })).finally(() => { swapping = false; });if (done?.ok !== true) { log(`clean workspace: could not start on ${dir} (${done?.error?.message ?? done?.error ?? "no answer"})`); return false; }changed();return true;}- /** The frozen copy's server again; true once it is the one running. */- const leave = () => inTurn(() => (active() ? swapTo(dataDir()) : true));+ /** The frozen copy's server again; true once it is the one running. `background`: the window stays where it is. */+ const leave = ({ background = false } = {}) => inTurn(() => (active() ? swapTo(dataDir(), background ? { background: true } : undefined) : true));/** This computer's freeze marker, as the frozen copy's own server would say it. */function marker() {const text = readOwn("moved.json");@@ -122,14 +122,16 @@ export function createCleanWorkspace({ dataDir, running, swap, allowed = () => ttry { seed(folder()); } catch (error) { log(`clean workspace: could not set it up (${error?.message ?? error})`); return false; }return swapTo(folder());}),- /** Opens profile `id`, set up fresh the first time; true once it runs. */- open: (id = DEFAULT_PROFILE) => inTurn(async () => {+ /** Opens profile `id`, set up fresh the first time; true once it runs. `background`: its server only, the window stays+ * where it is (this computer and My Cloud together, together-background.mjs), and only one that exists already. */+ open: (id = DEFAULT_PROFILE, { background = false } = {}) => inTurn(async () => {if (!PROFILE_ID.test(id)) return false;if (profile() === id) return true;if (!allowed() || held > 0) return false;const dir = profileDir(dataDir(), id);+ if (background && !fs.existsSync(dir)) return false;try { seed(dir); } catch (error) { log(`profile ${id}: could not set it up (${error?.message ?? error})`); return false; }- return swapTo(dir);+ return swapTo(dir, background ? { background: true } : undefined);}),leave,/** Settles once the swaps asked for so far are done. */diff --git a/electron/clean-workspace.node-test.mjs b/electron/clean-workspace.node-test.mjsindex d096f939cd..77dc86bb90 100644--- a/electron/clean-workspace.node-test.mjs+++ b/electron/clean-workspace.node-test.mjs@@ -24,7 +24,7 @@ function computer(t, { frozen = { v: 1, at: 1, cloud: CLOUD } } = {}) {w.write = (name, text) => { writeFileSync(join(dataDir, name), text); };w.clean = createCleanWorkspace({dataDir: () => dataDir, running: () => w.running,- swap: async (dir) => { w.swaps.push(dir); if (w.swapFails) return { ok: false, error: "switch-failed" }; await new Promise((resolve) => setImmediate(resolve)); w.running = dir; return { ok: true }; },+ swap: async (dir, how) => { w.swaps.push(dir); if (how) w.hows = [...(w.hows ?? []), how]; if (w.swapFails) return { ok: false, error: "switch-failed" }; await new Promise((resolve) => setImmediate(resolve)); w.running = dir; return { ok: true }; },changed: () => { w.changes++; },});w.request = async (route, init) => { w.requests.push([w.running, (init?.method ?? "GET").toUpperCase(), route]); return json({ frozen: w.running === dataDir && Boolean(frozen) }); };@@ -410,3 +410,16 @@ test("a named local environment is never forgotten in place of this computer's cawait w.main.kick();assert.deepEqual(w.requests.filter(([, , route]) => route === "/api/move/forget"), [[w.dataDir, "POST", "/api/move/forget"]]);});++test("a workspace opened in the background (together with My Cloud) starts only if it exists, and tells the swap to leave the window alone", async (t) => {+ const w = computer(t);+ assert.equal(await w.clean.open("default", { background: true }), false, "never made for it");+ assert.equal(existsSync(profileDir(w.dataDir, "default")), false);+ assert.deepEqual(w.swaps, []);+ mkdirSync(profileDir(w.dataDir, "default"), { recursive: true });+ assert.equal(await w.clean.open("default", { background: true }), true);+ assert.deepEqual([w.swaps, w.hows], [[profileDir(w.dataDir, "default")], [{ background: true }]]);+ assert.equal(w.clean.profile(), "default");+ assert.equal(await w.clean.open("default"), true, "a click on This Mac afterwards finds it running");+ assert.equal(w.swaps.length, 1);+});diff --git a/electron/cloud-rail.d.mts b/electron/cloud-rail.d.mtsindex f8bb173ec3..ffaebb433e 100644--- a/electron/cloud-rail.d.mts+++ b/electron/cloud-rail.d.mts@@ -55,6 +55,9 @@ export interface RailPlace {/** A server of the person's own, theirs alone by its own word, that this computer's bots may move to: its menu offers* Make … my home. */makeHome?: true;+ /** This computer (or the workspace of its own that runs now) and My Cloud: its menu offers Show bots together, checked+ * while it is on (places-together.mjs). Absent where it is not offered. */+ together?: boolean;}/** +'s choices here: buying a Cloud, pasting a server's pairing link, typing its address on this computer's Settings, and* a new organization on the Team plan this account pays for (absent from an older app's main). */diff --git a/electron/cloud-rail.mjs b/electron/cloud-rail.mjsindex 69332f2f58..70b9cb6bae 100644--- a/electron/cloud-rail.mjs+++ b/electron/cloud-rail.mjs@@ -68,10 +68,12 @@ const unlisted = (entry, { clouds, home, mine }) => Array.isArray(clouds) && (en* device, each with its places as they were kept: grouped by account after these (withAccounts). `profiles`: the workspaces* of this computer's own it may open (local-profiles.mjs; `active`: the one on screen, `settling`: it opens once that bot* finishes): first once My Cloud is home, as This computer was, else right after This computer. `computerSettling`: This- * computer opens once that bot finishes.- * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any, offers?: (entry: any) => boolean, waiting?: (id: string) => boolean, accounts?: any[], profiles?: Array<{ id: string, name?: string | null, color?: string | null, swatch?: string | null, active?: boolean, settling?: string }>, computerSettling?: string | null }} input+ * computer opens once that bot finishes. `together`: "This computer and My Cloud together" where it is offered (null+ * elsewhere): whether it is on, and the workspace of this computer's own that joins while My Cloud is home (`profile`);+ * This computer's circle (or that workspace's) and My Cloud's then offer Show bots together in their menu.+ * @param {{ saved: { environments: any[], activeId: string }, home?: string | null, mine?: string | null, state?: any, offers?: (entry: any) => boolean, waiting?: (id: string) => boolean, accounts?: any[], profiles?: Array<{ id: string, name?: string | null, color?: string | null, swatch?: string | null, active?: boolean, settling?: string }>, computerSettling?: string | null, together?: { on: boolean, profile?: string | null } | null }} input*/-export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false, waiting = () => false, accounts = [], profiles = [], computerSettling = null }) {+export function railPlaces({ saved, home = null, mine = null, state = null, offers = () => false, waiting = () => false, accounts = [], profiles = [], computerSettling = null, together = null }) {const connected = state?.status === "connected" ? state : null;const clouds = Array.isArray(connected?.clouds) ? connected.clouds : [];const order = entry => { const at = clouds.findIndex(cloud => cloud.origin === entry.origin); return at === -1 ? clouds.length : at; };@@ -79,7 +81,7 @@ export function railPlaces({ saved, home = null, mine = null, state = null, offeconst remote = saved.environments.filter(entry => entry.kind !== "local" && entry.origin && !(connected && unlisted(entry, { clouds: connected.clouds, home, mine }))).map((entry, index) => ({ entry, index })).sort((a, b) => rank(a.entry) - rank(b.entry) || order(a.entry) - order(b.entry) || a.index - b.index)- .map(({ entry }) => circle(entry, { activeId: saved.activeId, mine, state: connected, offers, waiting }));+ .map(({ entry }) => ({ ...circle(entry, { activeId: saved.activeId, mine, state: connected, offers, waiting }), ...(together && mine && entry.origin === mine ? { together: together.on } : {}) }));const making = otherOwnClouds(clouds).filter(cloud => !cloud.origin && ["checkout", "setting_up"].includes(cloud.status)).map(cloud => ({ id: `${PENDING}${cloud.id}`, name: cloud.name, color: swatchColor(cloud.color), kind: "cloud", opens: true, progress: cloudSetupProgress(cloud) ?? 0,...(cloud.status === "checkout" ? { waiting: true } : {}), cloudId: cloud.id }));@@ -91,11 +93,12 @@ export function railPlaces({ saved, home = null, mine = null, state = null, offeconst computer = environments.savedPlace(saved, environments.LOCAL_ID), color = computer.color ?? null;const own = profiles.map(profile => ({ id: `${PROFILE_PLACE}${profile.id}`, name: profile.name || computer.name, color: profile.color ?? null, kind: "computer", profile: profile.id,...(profile.name ? { named: true } : {}), opens: true, paint: { swatch: profile.swatch ?? null }, ...(profile.active ? { active: true } : {}),+ ...(together && home && together.profile === profile.id ? { together: together.on } : {}),...(typeof profile.settling === "string" ? { settling: profile.settling } : {}) }));const profileShown = own.some(place => place.active);const all = home ? [...own, ...places] : [{ id: computer.id, name: computer.name, color, kind: "computer", opens: true, paint: railPaint(placeLook(computer), color),...(saved.activeId === environments.LOCAL_ID && !profileShown ? { active: true } : {}), ...(waiting(computer.id) ? { attention: true } : {}),- ...(typeof computerSettling === "string" ? { settling: computerSettling } : {}) }, ...own, ...places];+ ...(typeof computerSettling === "string" ? { settling: computerSettling } : {}), ...(together ? { together: together.on } : {}) }, ...own, ...places];if (accounts.length) return withAccounts(all, { saved, accounts, email: state?.account?.email ?? null });return all.length < (clouds.some(ownCloud) ? 1 : RAIL_MIN_PLACES) ? [] : all;}diff --git a/electron/cloud-rail.node-test.mjs b/electron/cloud-rail.node-test.mjsindex e1d9cc1e60..a3afa2d511 100644--- a/electron/cloud-rail.node-test.mjs+++ b/electron/cloud-rail.node-test.mjs@@ -365,7 +365,7 @@ function preload(origin, { activation = false } = {}) {test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle, + and checkout open only from the person's click", async () => {const page = preload(HOME);- assert.deepEqual(Object.keys(page.bridge.workspaces), ["state", "menu", "line", "places", "open", "add", "probe", "look", "color", "recolor", "remove", "rename", "makeHome", "homeOffers", "onChanged", "local", "onNewLocal"]);+ assert.deepEqual(Object.keys(page.bridge.workspaces), ["state", "menu", "line", "places", "open", "add", "probe", "look", "color", "recolor", "remove", "rename", "makeHome", "homeOffers", "together", "onChanged", "local", "onNewLocal"]);assert.deepEqual(Object.keys(page.bridge.cloudAdd), ["state", "start", "reopen", "copyLink", "open", "interest", "sheet", "organization"]);await page.bridge.workspaces.places();await page.bridge.cloudAdd.state();@@ -378,6 +378,7 @@ test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle,await assert.rejects(page.bridge.cloudAdd.organization("Client B", "rose"), /Create organization/);await assert.rejects(page.bridge.workspaces.color("rose"), /Choose a color/, "a page changes its place's colour only from the person's click");await assert.rejects(page.bridge.workspaces.recolor("vps", "rose"), /Choose a color/);+ await assert.rejects(page.bridge.workspaces.together(true), /Show bots together/, "a Cloud's page turns Show bots together only from the person's click");await assert.rejects(page.bridge.workspaces.remove("old"), /Choose Remove from list/, "Remove from list only from the person's click");await assert.rejects(page.bridge.workspaces.rename("vps", "Office"), /Choose Rename/, "Rename only from the person's click");await assert.rejects(page.bridge.workspaces.makeHome("vps"), /Choose Make my home/, "a move starts only from the person's click");@@ -523,3 +524,14 @@ test("+'s new workspace and a workspace's menu: only while main offers it, onlcreatable = false; r.w.trusted = true;assert.throws(() => r.call("workspaces:local-new", "Notes", null), /isn't something to add/);});++test("Show bots together: in the menu of This computer and My Cloud while this computer is home; of the workspace that runs and My Cloud once My Cloud is home; nowhere else, and nowhere where it is not offered", () => {+ const marked = (places) => places.filter(place => "together" in place).map(place => [place.id, place.together]);+ const alone = { activeId: "local", environments: [{ id: "home", kind: "remote", name: "My Cloud", origin: HOME }] };+ const clouds = session({ teams: [], clouds: parseCloudList([PRIMARY]) });+ assert.deepEqual(marked(railPlaces({ saved: alone, home: null, mine: HOME, state: clouds, profiles: [{ id: "work", name: "Work" }], together: { on: true, profile: null } })),+ [["local", true], ["home", true]], "a named workspace beside This computer is not the one that joins");+ assert.deepEqual(marked(railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session(), profiles: [{ id: "default" }, { id: "work", name: "Work" }], together: { on: false, profile: "default" } })),+ [["profile:default", false], ["home", false]], "My Cloud as home: This Mac, which runs, and My Cloud; never Client A, a team's Cloud or a server");+ assert.deepEqual(marked(railPlaces({ saved: saved(), home: HOME, mine: HOME, state: session(), profiles: [{ id: "default" }], together: null })), [], "not offered (the frozen copy runs): no row");+});diff --git a/electron/computer-sharing.d.mts b/electron/computer-sharing.d.mtsindex f426b5f0e0..2a853f679a 100644--- a/electron/computer-sharing.d.mts+++ b/electron/computer-sharing.d.mts@@ -190,6 +190,8 @@ export function createComputerSharing(options: {resume(): Promise<void> | undefined;/** Whether every Cloud of the signed-in account's own may run commands here as this user, across restarts too. */lendTerminal(on: boolean): Promise<void> | undefined;+ /** Every Cloud of the signed-in account's own may run commands here now (what lendTerminal last set, for that account). */+ terminalOn(): boolean;screenChanged(): Promise<void>;cloudChanged(): void;start(options?: { maintainer?: boolean }): void;diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjsindex aab379a932..8c7f1f9b48 100644--- a/electron/computer-sharing.mjs+++ b/electron/computer-sharing.mjs@@ -932,7 +932,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lowakeAsking();},resume: () => resumeLending(),- /** Whether every Cloud of the signed-in account's own may run commands here as this user, across restarts too. */+ terminalOn: () => terminalAccount !== null && terminalAccount === signedInAccount(), // lendTerminal(on): whether every Cloud of the signed-in account's own may run commands here as this user, across restarts too.lendTerminal(on) {const account = on === true ? signedInAccount() : null;if (closed || terminalAccount === account) return;diff --git a/electron/main.mjs b/electron/main.mjsindex c1e36bedab..46e4eda285 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -109,7 +109,7 @@ import { cleanWorkspaceDir, createCleanWorkspace, profilesDir } from "./clean-woimport { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";import { createHomeWindow, installHomeWindowIpc, HOME_SCREEN_PATH } from "./home-window.mjs";import { createTeamProfileSeeds } from "./team-profile-seed.mjs";-import { createHomePlaces } from "./home-places.mjs"; import { openStartPlace } from "./start-place.mjs"; import { createDesktopRing, installAccounts } from "./accounts-main.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { createPlaceInboxWatch } from "./place-inbox-watch.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs"; import { openComputerSettings } from "./open-computer-settings.mjs"; import { createPlacesTogether, installPlacesTogether, PLACES_TOGETHER_FILE } from "./places-together.mjs"; import { createBotLinkMain } from "./bot-link-main.mjs";+import { createHomePlaces } from "./home-places.mjs"; import { openStartPlace } from "./start-place.mjs"; import { createDesktopRing, installAccounts } from "./accounts-main.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { createPlaceInboxWatch } from "./place-inbox-watch.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs"; import { openComputerSettings } from "./open-computer-settings.mjs"; import { createPlacesTogether, installPlacesTogether, PLACES_TOGETHER_FILE, START_QUIET_MS, togetherComputer, togetherPrefFile } from "./places-together.mjs"; import { createBotLinkMain } from "./bot-link-main.mjs"; import { createTogetherBackground } from "./together-background.mjs";import { createWindowStateFile } from "./window-state-file.mjs"; import { createSystemProxyCache } from "./system-proxy.mjs"; import { createBootHeadStart } from "./boot-head-start.mjs";import { createEnvironmentsFile, ENVIRONMENTS_SAVE_FAILED } from "./environments-file.mjs";import { createOrgLibrary } from "./org-library.mjs";@@ -304,7 +304,7 @@ const serverSupervisor = createServerSupervisor({serverStartConflictOnly = false;slog(`server ready pid=${proc.pid} port=${SERVER_PORT}`); launchRecord.serverReady();void readCloudOfferBrand();- syncManagedComposioCredentials(); includedX.serverStarted(); includedPages.serverStarted(); phoneLinkFact.serverStarted(); linkCommandsFact.serverStarted(); phonePushAccess.serverStarted(); railChanged(); void systemProxy.refresh();+ syncManagedComposioCredentials(); includedX.serverStarted(); includedPages.serverStarted(); phoneLinkFact.serverStarted(); linkCommandsFact.serverStarted(); phonePushAccess.serverStarted(); try { placesTogether.scopeChanged(); void botLink?.serverChanged(); } catch {} railChanged(); void systemProxy.refresh();reportOwnListeners(proc);orgLibrary?.runtimeReady();if (managedDesktop) void managedDesktop.refresh().catch(() => {});@@ -1423,7 +1423,7 @@ async function refreshSharedComputersAllowed() {return sharedComputersAllowed;}-function sharingController() {+const cloudAwakeNow = async () => { const account = cloudAccount; if (!account) return false; if (Date.now() - (account.state().verifiedAt ?? 0) >= 5_000) await account.refresh(); return Date.now() - (account.state().verifiedAt ?? 0) < 5_000; }; function sharingController() {computerSharing ??= createComputerSharing({file: path.join(app.getPath("userData"), "computer-sharing.json"),// Each holds provider API keys and sessions.json: a broad share must never reach them.@@ -1434,14 +1434,14 @@ function sharingController() {cloud: lendingTarget.cloud, myCloud: lendingTarget.environment, ownClouds: lendingTarget.places, screen: screenControl.now, askForScreen, power: cloudPower, cloudPower: origin => cloudAccount?.powerOf?.(origin) ?? null, reconnect: reconnectCloud,prompt: createAskPrompt({ t: nativeT, dialog, window: () => mainWindow, idleSeconds: () => powerMonitor.getSystemIdleState(1) === "unknown" ? null : powerMonitor.getSystemIdleTime() }), startScreen: screenControl.start, confirmTerminal: () => lendingDialogs.lendTerminal(true, () => sharingController().lendTerminal(true)), log: slog,linkHeaders: async env => ({ cookie: (await session.defaultSession.cookies.get({ url: env.origin })).map(cookie => `${cookie.name}=${cookie.value}`).join("; ") }),- onChange: summary => { lendingIndicator().update(summary); loginItem.follow(summary.lending.length > 0); linkCommandsFact.observe(summary); },+ onChange: summary => { lendingIndicator().update(summary); loginItem.follow(summary.lending.length > 0); linkCommandsFact.observe(summary); try { placesTogether.commandsChanged(summary.terminal === true); } catch {} },cuaConnection: () => cuaReady, screenLocked: () => powerMonitor.getSystemIdleState(1) === "locked", idleSeconds: () => powerMonitor.getSystemIdleState(1) === "unknown" ? null : powerMonitor.getSystemIdleTime(),hostControl: createHostScreenLease({ url: () => `http://127.0.0.1:${SERVER_PORT}/api/desktop/shared-computer-control`, headers: () => desktopServerHeaders({}, { packaged: app.isPackaged, token: desktopMutationToken }) }),});return computerSharing;}-const cleanWorkspace = createCleanWorkspace({ t: nativeT, dataDir: desktopDataDir, running: () => runningDataDir, swap: dir => switchLocalEnvironmentTo(dir, LOCAL_ID, true), allowed: () => app.isPackaged && !desktopRemoteAccess, changed: () => { computerSharing?.cloudChanged(); void oneHome.kick(); }, log: slog }); const lendingTarget = createLendingTarget({ account: () => cloudAccount, clean: cleanWorkspace, environments: () => environmentsState.environments, ownHome: () => ownHome?.home() ?? null });+const cleanWorkspace = createCleanWorkspace({ t: nativeT, dataDir: desktopDataDir, running: () => runningDataDir, swap: (dir, how) => switchLocalEnvironmentTo(dir, LOCAL_ID, true, how?.background === true), allowed: () => app.isPackaged && !desktopRemoteAccess, changed: () => { computerSharing?.cloudChanged(); void oneHome.kick(); try { placesTogether.scopeChanged(); void botLink?.serverChanged(); } catch {} }, log: slog }); const lendingTarget = createLendingTarget({ account: () => cloudAccount, clean: cleanWorkspace, environments: () => environmentsState.environments, ownHome: () => ownHome?.home() ?? null });const screenControl = createScreenControl({ connection: () => cuaReady, remote: () => Boolean(desktopRemoteAccess), request: requestComputerUse, log: slog });let screenAskedAt = -Infinity;/** Computer control starts again, as Settings' Retry does, which asks macOS for what it never asked; at most every 10 minutes. */@@ -1551,11 +1551,11 @@ function acquireDataDirLeaseFor(dir) {}/** Pause the supervisor first, or its recovery forks on the wrong data dir; resume() stays in the finally. */-async function switchLocalEnvironmentTo(targetDir, targetId, quiet = false) {+async function switchLocalEnvironmentTo(targetDir, targetId, quiet = false, background = false) {if (!app.isPackaged) return { ok: false, error: "dev" };// A second switch would be un-paused by the first's finally mid-handoff.if (localSwitchInFlight) return { ok: false, error: "busy" };- const previousDir = runningDataDir ?? startupEnvironmentDir(environmentsState, desktopDataDir()), asked = placeSwitch.turn(), windowFollows = () => placeSwitch.turn() === asked || (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents }));+ const previousDir = runningDataDir ?? startupEnvironmentDir(environmentsState, desktopDataDir()), asked = placeSwitch.turn(), windowFollows = () => !background && (placeSwitch.turn() === asked || (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })));let startedProc = null;let switchSucceeded = false;const failedSwitch = () => {@@ -2041,7 +2041,7 @@ function createWindow({ deferNavigation = false } = {}) {// Not did-finish-load: Electron still reports the main frame as loading then.win.webContents.on("did-stop-loading", () => {deliverPackageInstall(win);- deliverChatLink(win); desktopNotifications.arrived(); placesTogether.arrived();+ deliverChatLink(win); desktopNotifications.arrived(); placesTogether.arrived(); togetherBackground.settled();});win.webContents.on("did-finish-load", () => void serverLending.offer(win));@@ -2578,7 +2578,7 @@ const cloudLook = createCloudLook({ store: lookFile(() => path.join(app.getPath(const cloudBuy = installCloudBuy({ ipcMain, guard: localWorkspaceOnly, client: ensureCloudAccount, offersReady: cloudOffersReady, clipboard, look: cloudLook });const localServerRequest = (route, init = {}) => (serverProc && serverReady ? fetch(`http://127.0.0.1:${SERVER_PORT}${route}`, { ...init, redirect: "error", credentials: "omit", headers: { ...init.headers, [DESKTOP_MUTATION_HEADER]: desktopMutationToken } }) : Promise.reject(new Error("not running"))); launchRecord.deliverWith((part) => localServerRequest("/api/diagnostics/launch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(part), signal: AbortSignal.timeout(5_000) }).then((res) => res.json()));const teamProfileSeeds = createTeamProfileSeeds({ teamFetch: (...args) => session.defaultSession.fetch(...args), localRequest: localServerRequest, log: slog });-const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1, chooses: true, t: nativeT, moveLending: () => ({ state: sharingController().cloudState(lendingTarget.environment()), paused: sharingController().paused() }), allowCommands: () => lendingDialogs.lendTerminal(true, () => sharingController().lendTerminal(true)) }); ownHome = installOwnHome({ t: nativeT, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); botLink = createBotLinkMain({ wanted: () => placesTogether.on(), pref: jsonFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep(), since: cloudAccount?.power()?.since ?? null, signedOut: cloudAccount?.state().status === "signed-out" }), cloudName: () => nativeT("cloudSetup.myCloud"), changed: () => placesTogether.linkChanged(), log: slog }); twoPlaces = installTwoPlacesMain({ t: nativeT, ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), lastRead: jsonFile(path.join(app.getPath("userData"), "two-places-read.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });+const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1, chooses: true, t: nativeT, moveLending: () => ({ state: sharingController().cloudState(lendingTarget.environment()), paused: sharingController().paused() }), allowCommands: () => lendingDialogs.lendTerminal(true, () => sharingController().lendTerminal(true)) }); ownHome = installOwnHome({ t: nativeT, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); botLink = createBotLinkMain({ wanted: () => placesTogether.on(), switchedOff: () => placesTogether.switchedOff(), chosen: () => placesTogether.chosen(), powerChecked: cloudAwakeNow, napped: () => cloudPower.hold(), proved: () => cloudPower.woke(), quietMs: START_QUIET_MS, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep(), since: cloudAccount?.power()?.since ?? null, signedOut: cloudAccount?.state().status === "signed-out" }), cloudName: () => nativeT("cloudSetup.myCloud"), changed: () => placesTogether.linkChanged(), log: slog }); twoPlaces = installTwoPlacesMain({ t: nativeT, ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), lastRead: jsonFile(path.join(app.getPath("userData"), "two-places-read.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), together: () => { try { return placesTogether.on(); } catch { return false; } }, awakeNow: async () => (await cloudAwakeNow()) && !cloudPower.asleep(), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });// Teams from the verified session as places this window shows (home-places.mjs): the one to open next time, and its lines.const homePlaces = createHomePlaces({ store: jsonFile(path.join(app.getPath("userData"), "home-place.json")), environments: () => environmentsState, persist: persistEnvironments, makeId: randomUUID, homeOrigin: myCloud, homeName: name => cloudLook.homeName(name), synced: state => teamLinks.changed(state), log: slog });const homeWindow = createHomeWindow({ clean: cleanWorkspace, journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,@@ -2596,8 +2596,8 @@ function showHome(options) {return homeWindow.show(options).catch(error => slog(`home: ${error?.message ?? error}`));}const showStartPlace = () => openStartPlace({ home: homeWindow, places: homePlaces, profiles: localProfiles, log: slog, server: id => { const entry = environmentsState.environments.find(candidate => candidate.id === id && handSaved(candidate)); return entry ? reopenSavedServer(entry, { saved: () => environmentsState.environments.filter(handSaved), fetch: (...args) => session.defaultSession.fetch(...args), opened: async (found) => { if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: true }); persistEnvironments(withActive(environmentsState, found.id)); return navigateMainWindow(activeOrigin()); } }) : Promise.resolve(false); } }).catch(error => slog(`start: ${error?.message ?? error}`)); const openOwnCloud = id => { homeWindow.cancel(); return showHome({ place: { cloud: id, name: environmentsState.environments.find(entry => entry.cloud?.id === id)?.name } }); };-const placeInbox = createPlaceInboxWatch({ places: () => [{ id: LOCAL_ID, local: true }, ...environmentsState.environments.filter(entry => entry.kind !== "local" && entry.origin)], activeId: () => environmentsState.activeId, local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), shown: () => !desktopRemoteAccess && serverReady && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()), changed: () => railChanged() }); const homeOfUrl = url => { let at = null; try { at = new URL(url); } catch { return "other"; } return at.origin === rendererOrigin() ? (at.pathname === HOME_SCREEN_PATH ? "waking" : "computer") : at.origin === myCloud() ? "cloud" : "other"; }; const placeShown = () => { const page = mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null; return page && !page.isLoadingMainFrame() ? homeOfUrl(page.getURL()) ?? "other" : null; }; const shownHome = () => { const place = placeShown(); return place === "computer" || place === "cloud" ? place : null; }; const placesTogether = installPlacesTogether({ ipcMain, asking: cloudPageAsking, together: createPlacesTogether({ turnedOn: () => { try { void sharingController().lendTerminal(true)?.catch?.(error => slog(`together: commands not lent (${error?.message ?? error})`)); } catch (error) { slog(`together: commands not lent (${error?.message ?? error})`); } }, pref: jsonFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep() }), powerChecked: async () => { const account = cloudAccount; if (!account) return false; await account.refresh(); return Date.now() - (account.state().verifiedAt ?? 0) < 5_000; }, computer: () => !(homeWindow.cloudOrigin() ?? ownHome?.origin()), local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), napped: () => cloudPower.hold(), address: (home, botId) => botLink?.address(home, botId) ?? null, shown: placeShown, focused: () => powerMonitor.getSystemIdleState(60) !== "locked" && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), openPlace: home => { const entry = home === "cloud" ? environmentsState.environments.find(candidate => candidate.origin === myCloud()) : null; return home === "cloud" && (!entry || myCloud() === homeWindow.cloudOrigin()) ? showHome({ place: "cloud" }) : workspaceMenuAction(() => switchEnvironment(entry?.id ?? LOCAL_ID)); }, send: (channel, value) => { if (shownHome()) mainWindow.webContents.send(channel, value); }, changed: () => { botLink?.look(); if (shownHome()) mainWindow.webContents.send("places-together:changed"); } }) });-const localProfiles = createLocalProfiles({ registry: createProfileRegistry({ dataDir: desktopDataDir }), clean: cleanWorkspace, dataDir: desktopDataDir, allowed: () => app.isPackaged && !desktopRemoteAccess, home: () => (homeWindow.cloudOrigin() ? "cloud" : ownHome?.origin() || cleanWorkspace.marker().frozen ? null : "local"), window: { openProfile: id => homeWindow.openProfile(id), profile: () => homeWindow.profile(), showCloud: () => showHome({ place: "cloud" }) }, showLocal: () => { homeWindow.cancel(); persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(rendererOrigin()); }, onLocal: () => Boolean(mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })), busy: async () => { const said = await (await localServerRequest("/api/move/freeze", { signal: AbortSignal.timeout(5_000) })).json(); return typeof said?.busy === "string" ? { name: said.busy, what: said.what } : null; }, trash: dir => shell.trashItem(dir), reserved: () => nativeT(process.platform === "darwin" ? "rail.thisMac" : "rail.thisPc"), remember: homePlaces.remember, changed: () => railChanged(), log: slog }); const railList = () => { ownHome?.refresh(); const settling = localProfiles.settling(); return railPlaces({ saved: environmentsState, waiting: placeInbox.waiting, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true, accounts: accountRing.waiting(), profiles: localProfiles.places({ activeLocal: environmentsState.activeId === LOCAL_ID }), computerSettling: settling && settling.id === null ? settling.name : null }); };+const placeInbox = createPlaceInboxWatch({ places: () => [{ id: LOCAL_ID, local: true }, ...environmentsState.environments.filter(entry => entry.kind !== "local" && entry.origin)], activeId: () => environmentsState.activeId, local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), shown: () => !desktopRemoteAccess && serverReady && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()), changed: () => railChanged() }); const homeOfUrl = url => { let at = null; try { at = new URL(url); } catch { return "other"; } return at.origin === rendererOrigin() ? (at.pathname === HOME_SCREEN_PATH ? "waking" : "computer") : at.origin === myCloud() ? "cloud" : "other"; }; const placeShown = () => { const page = mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null; return page && !page.isLoadingMainFrame() ? homeOfUrl(page.getURL()) ?? "other" : null; }; const shownHome = () => { const place = placeShown(); return place === "computer" || place === "cloud" ? place : null; }; const togetherCommands = () => { try { void sharingController().lendTerminal(true)?.catch?.(error => slog(`together: commands not lent (${error?.message ?? error})`)); } catch (error) { slog(`together: commands not lent (${error?.message ?? error})`); } }; const placesTogether = installPlacesTogether({ ipcMain, asking: cloudPageAsking, rail: event => chromeRail.owns(event), together: createPlacesTogether({ turnedOn: togetherCommands, commands: { on: () => sharingController().terminalOn(), set: on => (on ? lendingDialogs.lendTerminal(true, () => sharingController().lendTerminal(true)) : sharingController().lendTerminal(false)) }, pref: togetherPrefFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep() }), powerChecked: cloudAwakeNow, computer: () => togetherComputer({ cloudHome: Boolean(homeWindow.cloudOrigin()), ownHome: Boolean(ownHome?.origin()), frozen: cleanWorkspace.marker().frozen, profile: cleanWorkspace.profile(), running: runningDataDir }), local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), napped: () => cloudPower.hold(), address: (home, botId) => botLink?.address(home, botId) ?? null, shown: placeShown, focused: () => powerMonitor.getSystemIdleState(60) !== "locked" && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), openPlace: home => { const entry = home === "cloud" ? environmentsState.environments.find(candidate => candidate.origin === myCloud()) : null; return home === "cloud" && (!entry || myCloud() === homeWindow.cloudOrigin()) ? showHome({ place: "cloud" }) : workspaceMenuAction(() => switchEnvironment(entry?.id ?? LOCAL_ID)); }, send: (channel, value) => { if (shownHome()) mainWindow.webContents.send(channel, value); }, changed: () => { botLink?.look(); if (shownHome()) mainWindow.webContents.send("places-together:changed"); try { togetherBackground.changed(); } catch {} const offered = JSON.stringify(placesTogether?.offered() ?? null); if (offered !== togetherOnRail) { togetherOnRail = offered; railChanged(); } } }) }); let togetherOnRail = "null"; const togetherBackground = createTogetherBackground({ cloudHome: () => Boolean(homeWindow.cloudOrigin()), togetherOn: () => placesTogether.switchOn(), shown: placeShown, ownCopyRuns: () => cleanWorkspace.ownCopy(), running: () => cleanWorkspace.profile(), dataDir: desktopDataDir, open: id => cleanWorkspace.open(id, { background: true }), leave: () => cleanWorkspace.leave({ background: true }), busy: async () => { const said = await (await localServerRequest("/api/move/freeze", { signal: AbortSignal.timeout(5_000) })).json(); return typeof said?.busy === "string"; }, linkOff: async () => { await botLink?.look(); await botLink?.look(); }, log: slog });+const localProfiles = createLocalProfiles({ registry: createProfileRegistry({ dataDir: desktopDataDir }), clean: cleanWorkspace, dataDir: desktopDataDir, allowed: () => app.isPackaged && !desktopRemoteAccess, home: () => (homeWindow.cloudOrigin() ? "cloud" : ownHome?.origin() || cleanWorkspace.marker().frozen ? null : "local"), window: { openProfile: id => homeWindow.openProfile(id), profile: () => homeWindow.profile(), showCloud: () => showHome({ place: "cloud" }) }, showLocal: () => { homeWindow.cancel(); persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(rendererOrigin()); }, onLocal: () => Boolean(mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })), busy: async () => { const said = await (await localServerRequest("/api/move/freeze", { signal: AbortSignal.timeout(5_000) })).json(); return typeof said?.busy === "string" ? { name: said.busy, what: said.what } : null; }, trash: dir => shell.trashItem(dir), reserved: () => nativeT(process.platform === "darwin" ? "rail.thisMac" : "rail.thisPc"), remember: homePlaces.remember, changed: () => railChanged(), log: slog }); const railList = () => { ownHome?.refresh(); const settling = localProfiles.settling(); return railPlaces({ saved: environmentsState, waiting: placeInbox.waiting, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true, accounts: accountRing.waiting(), profiles: localProfiles.places({ activeLocal: environmentsState.activeId === LOCAL_ID }), computerSettling: settling && settling.id === null ? settling.name : null, together: placesTogether.offered() && { on: placesTogether.offered().on, profile: cleanWorkspace.profile() } }); };// The rail as the window's own chrome (chrome-rail.mjs): this app's page beside every place's page, the one that lists.const placeSwitch = createPlaceSwitch({ changed: () => railChanged(), stop: () => homeWindow.stopOpening(), kept: () => homePlaces.remembered(), pageSettled: () => { const page = mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null; if (page?.isLoadingMainFrame()) return new Promise(done => { page.once("did-stop-loading", done); page.once("destroyed", done); }); } }); const openPlace = (id, stale) => workspaceMenuAction(async () => { if (id === LOCAL_ID) await cleanWorkspace.settled(); if (!stale()) await switchEnvironment(id, stale); }); const chromeRail = createChromeRail({ createView: options => new WebContentsView(options), preload: path.join(__dirname, "preload.cjs"), log: slog, prefs: () => desktopPrefs, changed: () => rail.changed(), openComputer: (page) => openComputerSettings({ window: () => mainWindow, onLocal: (win) => senderIsLocal({ sender: win.webContents }), showLocal: () => placeSwitch.ask(LOCAL_ID, stale => { localProfiles.cancel(); return openPlace(LOCAL_ID, stale); }) }, page),args: () => [...desktopCompanionRendererArguments(rendererOrigin(), desktopRemoteAccess), ...(app.isPackaged && !desktopRemoteAccess ? ["--omb-company-desktop=1"] : []), `--omb-app-version=${app.getVersion()}`],@@ -3026,7 +3026,7 @@ app.whenReady().then(async () => { launchRecord.mark("ready");// A cold-start action owns its first navigation; a default load started first would be aborted by it.const deliveredOrganizationEntry = await deliverOrganizationEntry();const deliveredCloudEntry = await cloudEntry.ready();- if (!hiddenStart && !restoredOrganizationEntry && !deliveredOrganizationEntry && !deliveredCloudEntry) await showStartPlace(); void cloudAccountRestored().then(() => teamLinks.ready());+ if (!hiddenStart && !restoredOrganizationEntry && !deliveredOrganizationEntry && !deliveredCloudEntry) await showStartPlace(); void cloudAccountRestored().then(() => teamLinks.ready()); togetherBackground.start();// Reconcile incomplete setup and resume interrupted sign-out only once the local app is usable.if (hostedAccount) void hostedAccount.restore().catch(() => {});// Registering from an unreadable store would mint a second installation identity.@@ -3073,7 +3073,7 @@ app.on("before-quit", (e) => {companyBackupSchedule?.close();orgLibrary?.close();managedDesktop?.close();- accountRing.close(); cloudAccount?.close(); oneHome.close(); ownHome?.close(); twoPlaces?.close(); homeWindow.close(); placesTogether.close(); botLink?.close();+ accountRing.close(); cloudAccount?.close(); oneHome.close(); ownHome?.close(); twoPlaces?.close(); homeWindow.close(); placesTogether.close(); togetherBackground.close(); botLink?.close();companyBackupController?.abort();computerSharing?.close();cloudSync.close();diff --git a/electron/places-together-default.node-test.mjs b/electron/places-together-default.node-test.mjsnew file mode 100644index 0000000000..b52669be4d--- /dev/null+++ b/electron/places-together-default.node-test.mjs@@ -0,0 +1,296 @@+// This computer and My Cloud together, on by default (places-together.mjs): the notice, the person's own choices, the+// switch file, and which workspace joins. The rest of the switch is in places-together.node-test.mjs.+import assert from "node:assert/strict";+import { join } from "node:path";+import test from "node:test";++import { CLOUD_EVERY_MS, createPlacesTogether, installPlacesTogether, readTogether, START_QUIET_MS, togetherComputer, togetherPrefFile } from "./places-together.mjs";++const CLOUD = "https://mine.cloud.test";+const answer = (status, body, headers = {}) => ({ ok: status < 400, status, headers: { get: (name) => headers[name] ?? null }, json: async () => body, body: { cancel: async () => {} } });+const bot = (id, name, over = {}) => ({ id, threadId: `t-${id}`, name, title: "", color: "blue", mascotBody: "classic", ...over });+const ai = (displayName, snapshot = {}) => ({ instanceId: displayName.toLowerCase(), driverKind: "claude", displayName, snapshot: { state: "available", ...snapshot } });+const settle = () => new Promise((done) => setImmediate(done));++function setup(over = {}) {+ const f = {+ saved: "saved" in over ? over.saved : { v: 1, on: true }, asked: [], sent: [], opened: [], changes: 0, tick: null, cleared: 0, clock: 1_000,+ cloud: { origin: CLOUD, account: "acct-a", asleep: false }, computer: true, shown: "computer", focused: true, napped: 0, checks: 0, admin: true, timeouts: [], opening: new Promise(() => {}),+ bots: { computer: [bot("scout", "Scout")], cloud: [bot("scout", "Scout"), bot("nova", "Nova", { unread: true })] },+ reply: { computer: null, cloud: null },+ instances: { computer: [ai("Claude"), ai("Codex")], cloud: [ai("Claude"), ai("Included AI")] }, makes: { computer: true, cloud: true },+ };+ f.together = createPlacesTogether({+ pref: { read: () => f.saved, write: (value) => { f.saved = value; } },+ cloud: () => f.cloud, computer: () => f.computer,+ powerChecked: async () => { f.checks += 1; f.asked.push(["admin"]); return typeof f.admin === "function" ? f.admin() : f.admin; },+ local: async (route, init) => { f.asked.push(["computer", route, init]); return f.reply.computer ?? answer(200, route === "/api/instances" ? { instances: f.instances.computer } : { bots: f.bots.computer, ...(f.makes.computer ? { together: { newBot: true } } : {}) }); },+ cloudFetch: async (url, init) => { f.asked.push(["cloud", url, init]); return typeof f.reply.cloud === "function" ? f.reply.cloud() : f.reply.cloud ?? answer(200, url.endsWith("/api/instances") ? { instances: f.instances.cloud } : { bots: f.bots.cloud, ...(f.makes.cloud ? { together: { newBot: true } } : {}) }); },+ napped: () => { f.napped += 1; },+ shown: () => f.shown, focused: () => f.focused, openPlace: (home) => { f.opened.push(home); return f.opening; },+ send: (channel, value) => { f.sent.push([channel, value]); },+ changed: () => { f.changes += 1; },+ now: () => f.clock,+ setTimer: (run, ms) => { f.tick = { run, ms }; return {}; }, clearTimer: () => { f.cleared += 1; },+ later: (run, ms) => { const timer = { run, ms, cancelled: false }; f.timeouts.push(timer); return timer; }, cancelLater: (timer) => { if (timer) timer.cancelled = true; },+ startQuietMs: 0,+ ...over.deps,+ });+ /** The next read of My Cloud is due: a minute has passed. */+ f.later = () => { f.clock += CLOUD_EVERY_MS; };+ f.cloudAsked = (route = "") => f.asked.filter(([side, url]) => side === "cloud" && url.endsWith(route)).length;+ return f;+}+++/** A person signed in, with "Let your Clouds run commands on this computer" as `lent`, and what the notice's switch and the+ * person's own turn on did to it. */+function withCommands(over = {}, lent = false) {+ const c = { lent, set: [], turnedOn: 0 };+ const f = setup({ ...over, deps: { ...over.deps, commands: { on: () => c.lent, set: (on) => { c.set.push(on); c.lent = on; } }, turnedOn: () => { c.turnedOn += 1; c.lent = true; } } });+ return { f, c };+}++test("on by default: a person who never chose has it on from the moment this computer's page showed the notice, and not before", async () => {+ const { f, c } = withCommands({ saved: null });+ assert.equal(f.together.on(), false);+ assert.equal(f.together.switchedOff(), true, "the link stays off too");+ assert.equal(f.together.chosen(), null);+ await f.together.refresh("cloud");+ assert.deepEqual(f.asked, [], "nothing is read before the notice");+ assert.equal(f.together.noticeShown("cloud"), false, "My Cloud's page never turns the default on");+ assert.equal(f.together.on(), false);+ assert.equal(f.together.noticeShown("computer"), true);+ assert.equal(f.together.on(), true);+ assert.equal(f.together.switchedOff(), false);+ assert.equal(f.together.chosen(), null, "still never chosen: the person's own choice stays theirs to make");+ assert.deepEqual(f.saved, { v: 1, noticed: { "acct-a": 1_000 } }, "no `on`: an older app reads the file as off");+ assert.equal(f.together.state("computer").notice, true, "the notice stays due until it is closed");+ await f.together.refresh("cloud");+ assert.equal(f.cloudAsked("/api/bots?messages=3"), 1, "now My Cloud's bots are read, under the list's own rules");+ assert.deepEqual([c.set, c.turnedOn, c.lent], [[], 0, false], "the default never lets My Cloud run commands here");+});++test("the notice shows once: closed, it never shows again, after a restart too, and the default stays on", () => {+ const { f } = withCommands({ saved: null });+ f.together.noticeShown("computer");+ const reopened = withCommands({ saved: f.saved }).f;+ assert.equal(reopened.together.state("computer").notice, true, "shown but never closed (the app quit first): it shows again");+ assert.equal(reopened.together.on(), true);+ f.together.noticeDone("computer");+ assert.equal(f.together.state("computer").notice, undefined);+ const later = withCommands({ saved: f.saved }).f;+ assert.equal(later.together.state("computer").notice, undefined, "closed: never again");+ assert.equal(later.together.on(), true, "and still on");+ assert.equal(later.together.noticeShown("computer"), false, "a stale page cannot show it again");+});++test("a person who chose keeps their choice: off stays off, on stays on, and neither sees the notice", async () => {+ const off = withCommands({ saved: { v: 1, on: false } });+ assert.equal(off.f.together.state("computer").notice, undefined);+ assert.equal(off.f.together.noticeShown("computer"), false);+ assert.equal(off.f.together.on(), false);+ await off.f.together.refresh("cloud");+ assert.deepEqual(off.f.asked, []);+ assert.deepEqual(off.f.saved, { v: 1, on: false });+ const on = withCommands({ saved: { v: 1, on: true } });+ assert.equal(on.f.together.state("computer").notice, undefined);+ assert.equal(on.f.together.on(), true);+ assert.equal(on.f.together.chosen(), true);+ assert.deepEqual(on.c.set, []);+});++test("touching the switch anywhere ends the notice: off in the notice gives back today's two lists at once and lends nothing", async () => {+ const { f, c } = withCommands({ saved: null });+ f.together.noticeShown("computer");+ await f.together.refresh("cloud");+ assert.equal(f.together.state("computer").other.bots.length, 2);+ f.together.noticeDone("computer");+ const state = f.together.set("computer", false);+ assert.deepEqual(state, { v: 1, available: true, on: false, here: "computer", other: null, commands: false }, "the other place's rows are gone and no notice is due");+ assert.equal(f.saved.on, false);+ assert.equal(f.together.switchedOff(), true, "the link ends");+ assert.deepEqual([c.set, c.turnedOn], [[], 0]);+ const restarted = withCommands({ saved: f.saved }).f;+ assert.equal(restarted.together.on(), false, "the person's off is kept");+ assert.equal(restarted.together.state("computer").notice, undefined);+ const settings = withCommands({ saved: null });+ settings.f.together.set("computer", false);+ assert.equal(settings.f.together.state("computer").notice, undefined, "turned off in Settings before the notice ever showed: it never shows");+ assert.equal(settings.f.together.noticeShown("computer"), false);+});++test("running commands: the notice's own switch, read from lending itself and kept live, as the person has it; the person's own turn on in Settings still lends it", async () => {+ const had = withCommands({ saved: null }, true);+ assert.equal(had.f.together.state("computer").commands, true, "a grant the person had shows as on");+ had.f.together.noticeShown("computer");+ assert.equal(had.c.lent, true, "and stays as it was");+ const never = withCommands({ saved: null });+ never.f.together.noticeShown("computer");+ assert.equal(never.f.together.state("computer").commands, false);+ assert.equal(await never.f.together.setCommands("computer", true), true);+ assert.deepEqual(never.c.set, [true]);+ assert.equal(await never.f.together.setCommands("computer", false), false);+ assert.deepEqual(never.c.set, [true, false]);+ await assert.rejects(never.f.together.setCommands("cloud", true), /this computer's page/);+ const gone = withCommands({ saved: null, deps: { computer: () => null } });+ await assert.rejects(gone.f.together.setCommands("computer", true), /this computer's page/, "not offered: not turned here");+ const declined = setup({ saved: null, deps: { commands: { on: () => false, set: async () => false } } });+ assert.equal(await declined.together.setCommands("computer", true), false, "Cancel in the icon's own question: still off, as lending says");+ const live = withCommands({ saved: null });+ live.f.together.noticeShown("computer");+ const changes = live.f.changes;+ live.c.lent = true;+ live.f.together.commandsChanged(true);+ assert.equal(live.f.changes, changes + 1, "turned on from the icon's menu while the notice is up: the page is told");+ assert.equal(live.f.together.state("computer").commands, true, "and reads lending's own word, not a copy");+ live.f.together.commandsChanged(true);+ assert.equal(live.f.changes, changes + 1, "the same word again tells nothing");+ const again = withCommands({ saved: null });+ again.f.together.noticeShown("computer");+ again.f.together.set("computer", false, { listOnly: true });+ again.f.together.set("computer", true, { listOnly: true });+ assert.equal(again.c.turnedOn, 0, "off and on again in the notice: the joining only, never the grant");+ const byHand = withCommands({ saved: null });+ byHand.f.together.set("computer", true);+ assert.equal(byHand.c.turnedOn, 1, "turned on in Settings, whose words say so, it comes with the grant as before");+ assert.equal(byHand.f.together.state("computer").notice, undefined);+});++test("no read of My Cloud at the app's start: the first waits START_QUIET_MS, whatever a page asks", async () => {+ const f = setup({ deps: { startQuietMs: START_QUIET_MS } });+ f.together.state("computer");+ await f.together.refresh("cloud");+ await settle();+ assert.equal(f.asked.filter(([side]) => side !== "computer").length, 0, "neither the Admin nor My Cloud");+ f.clock += START_QUIET_MS;+ await f.together.refresh("cloud");+ assert.deepEqual(f.asked.map(([side]) => side), ["admin", "cloud"]);+ assert.equal(START_QUIET_MS >= 10_000, true);+});++test("on by default, a sleeping Cloud is never asked or woken: its list says asleep, with no error", async () => {+ const { f } = withCommands({ saved: null });+ f.cloud.asleep = true;+ f.together.noticeShown("computer");+ await f.together.refresh("cloud");+ f.later();+ await f.together.refresh("cloud");+ assert.deepEqual(f.asked, [], "not even the Admin is asked while it is known asleep");+ assert.deepEqual(f.together.state("computer").other, { home: "cloud", state: "asleep", bots: [] });+});++test("the default is per account: another account signed in here has not seen the notice, so it is off for them", () => {+ const { f } = withCommands({ saved: null });+ f.together.noticeShown("computer");+ f.cloud = { ...f.cloud, account: "acct-b" };+ assert.equal(f.together.on(), false);+ assert.equal(f.together.state("computer").notice, true);+ f.cloud = { ...f.cloud, account: null };+ assert.equal(f.together.noticeShown("computer"), false, "no account: nothing is noted");+});++test("a switch file that can't be read is off and shows no notice, and leaves a link alone; one that makes no sense is off", () => {+ const busy = setup({ deps: { pref: { read: () => { throw Object.assign(new Error("busy"), { code: "EBUSY" }); }, write: () => {} } } });+ assert.equal(busy.together.on(), false);+ assert.equal(busy.together.state("computer").notice, undefined);+ assert.equal(busy.together.switchedOff(), false);+ const missing = () => { throw Object.assign(new Error("gone"), { code: "ENOENT" }); };+ assert.equal(readTogether(missing).choice, null);+ assert.equal(readTogether(() => ({ v: 2, on: true })).choice, false);+ assert.equal(readTogether(() => ({ v: 1, on: "yes" })).choice, false);+ assert.equal(readTogether(() => ({ v: 1, noticed: {} })).choice, null);+});++test("which of this computer's workspaces joins My Cloud: its own server with this computer home; the workspace that runs with My Cloud home; none for the frozen copy or a server of their own as home", () => {+ assert.equal(togetherComputer({ cloudHome: false, ownHome: false, profile: null, running: "/data/omb" }), "computer:/data/omb");+ assert.equal(togetherComputer({ cloudHome: true, ownHome: false, profile: "default", running: "/data/omb-profiles/default" }), "profile:default");+ assert.equal(togetherComputer({ cloudHome: true, ownHome: false, profile: null, running: "/data/omb" }), null, "the frozen copy a move left admits no turns");+ assert.equal(togetherComputer({ cloudHome: true, ownHome: false, profile: null, running: "/data/omb-clean" }), null, "the clean workspace");+ assert.equal(togetherComputer({ cloudHome: false, ownHome: true, profile: null, running: "/data/omb" }), null);+ assert.equal(togetherComputer({ cloudHome: false, ownHome: false, frozen: true, profile: null, running: "/data/omb" }), null,+ "the freeze marker is there before the home window knows My Cloud is home: the frozen copy still never joins");+ assert.equal(togetherComputer({ cloudHome: false, ownHome: false, frozen: true, profile: null, running: "/data/omb-clean" }), null, "nor the clean workspace (signed in with no way to the moved Cloud)");+ assert.equal(togetherComputer({ cloudHome: false, ownHome: false, frozen: true, profile: "default", running: "/data/omb-profiles/default" }), "profile:default");+});++test("My Cloud as home: offered (and on by default) while a workspace of this computer's own runs; another one has lists of its own; the frozen copy has none", async () => {+ let here = "profile:default";+ const { f } = withCommands({ saved: null, deps: { computer: () => here } });+ assert.equal(f.together.state("computer").available, true);+ assert.equal(f.together.state("computer").notice, true);+ f.together.noticeShown("computer");+ await f.together.refresh("cloud");+ assert.deepEqual(f.together.state("computer").other.bots.map((row) => row.id), ["scout", "nova"]);+ assert.equal(f.together.state("cloud").other.bots.length, 0, "My Cloud's page asks for this computer's rows as before");+ const changes = f.changes;+ here = "profile:work";+ assert.equal(f.together.state("computer").other.state, "loading", "another workspace: the last one's list is dropped");+ assert.equal(f.changes > changes, true);+ here = null;+ assert.deepEqual(f.together.state("computer"), { v: 1, available: false, on: true, here: "computer", other: null }, "the frozen copy runs: nothing is offered or read");+ assert.equal(f.together.on(), false);+ f.asked.length = 0;+ await f.together.refresh("computer");+ assert.deepEqual(f.asked, []);+});++test("the rail turns the same switch from a circle's menu, only from the window's rail, and turning it on there switches the list alone, never lending commands", () => {+ const handlers = new Map();+ const { f, c } = withCommands({ saved: null });+ installPlacesTogether({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, asking: (event) => event.page, rail: (event) => event.rail === true, together: f.together });+ assert.throws(() => handlers.get("places-together:rail-set")({ page: "local" }, true), /Only the window's rail/);+ assert.equal(handlers.get("places-together:rail-set")({ rail: true }, true), true);+ assert.deepEqual([f.together.chosen(), c.turnedOn, c.set], [true, 0, []], "the rail's row never lets My Cloud run commands here");+ assert.equal(handlers.get("places-together:rail-set")({ rail: true }, false), false);+ assert.equal(f.saved.on, false);+ assert.deepEqual(f.together.offered(), { on: false });+ const none = withCommands({ saved: null, deps: { computer: () => null } });+ assert.equal(none.f.together.offered(), null, "where it is not offered the circles show nothing");+});++test("a switch file this app does not understand (another shape, a newer version) is left alone: no default, no notice, the link untouched, never written over", () => {+ for (const odd of [{ v: 2, on: true }, [], "on", { v: 1, on: "yes" }]) {+ const writes = [];+ const f = setup({ saved: odd, deps: { pref: { read: () => odd, write: (value) => { writes.push(value); } } } });+ const state = f.together.state("computer");+ assert.equal(state.on, false, JSON.stringify(odd));+ assert.equal(state.notice, undefined, `no notice for ${JSON.stringify(odd)}`);+ assert.equal(f.together.noticeShown("computer"), false);+ f.together.noticeDone("computer");+ if (!(Array.isArray(odd) || typeof odd === "string" || odd.v !== 1)) continue;+ assert.equal(f.together.switchedOff(), false, "the link is left as it is");+ assert.throws(() => f.together.set("computer", true), /not one this app can change/);+ assert.deepEqual(writes, [], `never written over: ${JSON.stringify(odd)}`);+ }+});++test("the notice says this computer's workspace now starts with the app only to a person whose home is My Cloud", () => {+ const cloudHome = setup({ saved: null, deps: { computer: () => "profile:default" } });+ assert.equal(cloudHome.together.state("computer").profileHome, true);+ const computerHome = setup({ saved: null, deps: { computer: () => "computer:/data" } });+ assert.equal(computerHome.together.state("computer").profileHome, undefined);+});++test("a switch file that is not JSON at all is off and quiet until the person turns the switch in Settings, which keeps the bad file beside it and writes a good one; a newer version's file stays untouched", async (t) => {+ const { mkdtempSync, readdirSync, readFileSync: read, rmSync, writeFileSync } = await import("node:fs");+ const { tmpdir } = await import("node:os");+ const dir = mkdtempSync(join(tmpdir(), "together-pref-"));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const path = join(dir, "places-together.json");+ writeFileSync(path, "{\"v\":1,\"on\":tr");+ const f = setup({ deps: { pref: togetherPrefFile(path, undefined, () => 42) } });+ assert.equal(f.together.state("computer").notice, undefined);+ assert.equal(f.together.on(), false);+ assert.throws(() => f.together.set("computer", true, { listOnly: true }), /not one this app can change/, "the rail and the notice never repair it");+ assert.equal(read(path, "utf8"), "{\"v\":1,\"on\":tr");+ f.together.set("computer", true);+ assert.equal(read(join(dir, "places-together.json.unreadable-42"), "utf8"), "{\"v\":1,\"on\":tr", "the bad file is kept beside it");+ assert.deepEqual(JSON.parse(read(path, "utf8")), { v: 1, on: true, choices: { "acct-a": true } });+ assert.equal(f.together.on(), true);+ writeFileSync(path, JSON.stringify({ v: 3, on: true }));+ const newer = setup({ deps: { pref: togetherPrefFile(path, undefined, () => 43) } });+ assert.throws(() => newer.together.set("computer", false), /not one this app can change/);+ assert.deepEqual(JSON.parse(read(path, "utf8")), { v: 3, on: true }, "a newer version's file is read only");+ assert.equal(readdirSync(dir).filter((name) => name.includes("unreadable")).length, 1);+});diff --git a/electron/places-together.d.mts b/electron/places-together.d.mtsindex 5c5fdf4925..25a37c0b24 100644--- a/electron/places-together.d.mts+++ b/electron/places-together.d.mts@@ -40,13 +40,20 @@ export interface PlacesTogetherState {/** The other place's bots while the switch is on. `state`: how that place is doing: asleep, waking and offline keep the* bots it gave last; "signin" is a My Cloud this window has not signed in to yet, which lists none. */other: { home: BotHome; state: "ready" | "loading" | "asleep" | "waking" | "offline" | "signin"; bots: PlaceBotRow[]; newBot?: boolean } | null;+ /** This computer's page shows the one-time notice that this is on by default: the person never chose, and has not closed it. */+ notice?: true;+ /** With the notice, for a person whose home is My Cloud: this computer's own workspace now starts with the app. */+ profileHome?: true;+ /** This computer's page while the switch is offered: whether the person's Clouds may run commands on this computer now,+ * as lending says it (the notice's second switch). */+ commands?: boolean;}/** `window.ogb.placesTogether`: this computer's page and My Cloud's own page. */export interface PlacesTogetherBridge {state(): Promise<PlacesTogetherState>;/** Turning it on is this computer's page's alone; main refuses it from My Cloud's page. */- set(on: boolean): Promise<PlacesTogetherState>;+ set(on: boolean, from?: "notice"): Promise<PlacesTogetherState>;/** Opens the other place at one of its listed bots. False when main does not list that bot. */open(botId: string): Promise<boolean>;onChanged(callback: () => void): () => void;@@ -57,6 +64,12 @@ export interface PlacesTogetherBridge {newBot(): Promise<boolean>;/** The other place asked this one to make a new bot. */onNewBot(callback: () => void): () => void;+ /** This computer's page drew the notice of the default: from now on it is on. True when it is on now. Older apps lack it. */+ noticeShown?(): Promise<boolean>;+ /** The notice's second switch: whether My Cloud's bots may run commands on this computer. What it is now. */+ setCommands?(on: boolean): Promise<boolean>;+ /** The person closed the notice: it never shows again. */+ noticeDone?(): Promise<void>;}export interface NewBotChoice {@@ -67,6 +80,27 @@ export interface NewBotChoice {}export const PLACES_TOGETHER_FILE: string;+export const START_QUIET_MS: number;+export function togetherComputer(input: { cloudHome: boolean; ownHome: boolean; frozen?: boolean; profile: string | null; running: string | null }): string | null;+export function readTogether(read: () => unknown, account?: string | null): { choice: boolean | null; kept: Record<string, unknown>; unreadable?: true; foreign?: true; corrupt?: true };+export function togetherPrefFile(file: string, fs?: unknown, now?: () => number): { read(): unknown; write(value: unknown): void; backup(): void };export const PREVIEW_MAX: number;export const PREVIEW_LOOK: number;export function otherHome(asking: "local" | "cloud" | BotHome): BotHome;+/** Main's side of the switch (places-together.mjs), as a test drives it: the deps are its own, loosely typed here. */+export interface PlacesTogether {+ on(): boolean;+ switchOn(): boolean;+ offered(): { on: boolean } | null;+ state(asking: BotHome): PlacesTogetherState;+ set(asking: BotHome, value: boolean, options?: { listOnly?: boolean }): PlacesTogetherState;+ noticeShown(asking: BotHome): boolean;+ noticeDone(asking: BotHome): void;+ setCommands(asking: BotHome, value: boolean): Promise<boolean>;+ commandsChanged(on: boolean): void;+ switchedOff(): boolean;+ chosen(): boolean | null;+ close(): void;+}+export function createPlacesTogether(deps: Record<string, unknown>): PlacesTogether;+export function installPlacesTogether(options: { ipcMain: { handle(channel: string, handler: (event: unknown, ...args: unknown[]) => unknown): void }; asking(event: unknown): "local" | "cloud" | null; together: PlacesTogether; rail?(event: unknown): boolean }): PlacesTogether;diff --git a/electron/places-together.mjs b/electron/places-together.mjsindex 51f4c07a1f..705ad89c56 100644--- a/electron/places-together.mjs+++ b/electron/places-together.mjs@@ -1,17 +1,28 @@-// "This computer and My Cloud together" (Settings → MausBot Cloud, an early feature that starts off): the sidebar of this-// computer's page and of My Cloud's page lists the other one's bots too. A page can only talk to its own place, so main-// reads the other place's bots as the signed-in person, keeps the list, and opens that place at a bot when its row is-// clicked. With the switch off nothing here reads, keeps or sends anything.+// "This computer and My Cloud together" (Settings → Plan & billing): the sidebar of this computer's page lists My Cloud's+// bots too. A page can only talk to its own place, so main reads the other place's bots as the signed-in person, keeps the+// list, and opens that place at a bot when its row is clicked. With the switch off nothing here reads, keeps or sends anything.+//+// On by default: a person who never turned the switch either way has it on, but only from the moment this computer's page+// has shown them the one-time notice that says so, with the switch right there. Until then it is off as before: nothing is+// read or linked. The default never lets My Cloud run commands here: the notice has its own switch for that, as the person+// has it now. A choice the person made either way is kept for good, and the notice never shows again once they closed it,+// used one of its switches, or touched the switch in Settings or on the rail.//// Security: the list goes only to this computer's own page and to My Cloud's own page (`asking`, which main works out from// the sender), never to a team's Cloud or a server saved by hand. A row is a name, a look, a state and, as the person's// own two pages show each other, a short preview of the bot's newest line (PREVIEW_MAX characters of plain words; never a// step, a card, a file or another bot's note): no whole message, address or token. A page names a bot by an id main listed itself; main opens only such an id, in a place of its own choosing.// A sleeping Cloud is never asked, since any request would wake it; it keeps the list it gave last.+import nodeFs from "node:fs";+import { asleepAnswer, BACKGROUND_HEADERS } from "./cloud-power.mjs";-/** The switch, kept in `places-together.json` as `{ v: 1, on }`. Everything that joins the two places reads this one key. */+/** The switch, kept in `places-together.json` as `{ v: 1, on }`. Everything that joins the two places reads this one key.+ * Beside it, by signed-in account: `noticed` (when the notice of the default was first shown) and `done` (when the person+ * closed it or used it). `on` is absent while the person never chose: an older app reads that as off. */export const PLACES_TOGETHER_FILE = "places-together.json";+/** No read of My Cloud for this long after the app starts: the default adds nothing to a start. */+export const START_QUIET_MS = 15_000;/** How often the list on screen is looked at again. This computer answers each time; My Cloud at most every CLOUD_EVERY_MS. */export const LOOK_EVERY_MS = 20_000;/** This computer's bots are read again for a page that asks once they are older than this. */@@ -40,11 +51,52 @@ const look = (value) => (typeof value === "string" && COLOR.test(value) ? value/** The other side of a page: This computer's page lists My Cloud's bots, My Cloud's page this computer's. */export const otherHome = (asking) => (asking === "cloud" ? "computer" : "cloud");-/** Whether the switch is on, read back from its file. */+/** Whether the switch is on, read back from its file: the person's own choice only. */export function parseTogether(value) {return record(value) && value.v === 1 && value.on === true;}+/** The switch's file as read for `account`: `choice` is that person's (true, false, or null when they never chose), `kept`+ * what a rewrite keeps. Choices are kept by account (`choices`); a file from before them has one `on` for everyone here,+ * which stands until the first choice made since. `on` stays written too, the last choice made here, for an older app.+ * A file that can't be read (`unreadable`, which may pass), whose words are not JSON at all (`corrupt`), or that this app+ * does not understand (`foreign`: another shape or a newer version) is left alone: off, no default, no notice, and never+ * written over. Only the person's own turn of the switch in Settings repairs a corrupt one, kept beside it first. */+export function readTogether(read, account = null) {+ let value;+ try { value = read(); } catch (error) {+ if (error?.code === "ENOENT") return { choice: null, kept: { v: 1 } };+ return error instanceof SyntaxError ? { choice: false, kept: { v: 1 }, corrupt: true } : { choice: false, kept: { v: 1 }, unreadable: true };+ }+ if (value === null || value === undefined) return { choice: null, kept: { v: 1 } };+ if (!record(value) || value.v !== 1) return { choice: false, kept: { v: 1 }, foreign: true };+ return { choice: choiceIn(value, account), kept: value };+}++/** One person's choice in a readable switch file (readTogether). */+function choiceIn(kept, account) {+ if (record(kept.choices)) return typeof account === "string" && typeof kept.choices[account] === "boolean" ? kept.choices[account] : null;+ return typeof kept.on === "boolean" ? kept.on : kept.on === undefined ? null : false;+}++const stamped = (map, account) => record(map) && typeof account === "string" && Number.isFinite(map[account]) && map[account] > 0;++/** Which of this computer's own workspaces would join My Cloud, as a key that changes whenever another one runs; null when+ * none can. `cloudHome`: My Cloud is the person's home (their bots moved there). `ownHome`: a server of their own is.+ * `frozen`: this computer's data folder holds the move's freeze marker (clean-workspace.mjs `marker()`), known before the+ * home window knows My Cloud is home. `profile`: the workspace of this computer's own that runs now (This Mac is+ * `default`), null for the frozen copy a move left or the clean workspace. `running`: the folder this computer's server+ * runs on.+ *+ * Home = this computer: its own server, as ever. Bots moved away (home = My Cloud, or the marker says so): only while a+ * workspace of this computer's own runs: the frozen copy admits no turns and still lists the bots that moved, and the clean+ * workspace has nothing of the person's, so neither joins. A server of their own as home: none (not offered yet). */+export function togetherComputer({ cloudHome, ownHome, frozen = false, profile, running }) {+ if (ownHome) return null;+ if (cloudHome || frozen) return typeof profile === "string" && profile ? `profile:${profile}` : null;+ return `computer:${typeof running === "string" ? running : ""}`;+}+function rowState(bot) {const tasks = Array.isArray(bot.tasks) ? bot.tasks.filter((task) => record(task) && !task.routineRunId && task.archivedAt === undefined) : [];const waiting = bot.activity === "waiting-on-you" || tasks.some((task) => task.activity === "waiting-on-you");@@ -116,7 +168,8 @@ const needsSignIn = (response) => response?.status === 401 || response?.status =* pref: { read(): unknown, write(value: unknown): void },* cloud(): { origin: string | null, account: string | null, asleep: boolean },* powerChecked(): Promise<boolean>,- * computer(): boolean,+ * computer(): string | boolean | null,+ * commands?: { on(): boolean, set(on: boolean): unknown },* local(route: string, init?: RequestInit): Promise<Response>,* cloudFetch(url: string, init?: RequestInit): Promise<Response>,* napped?(): void,@@ -133,7 +186,10 @@ const needsSignIn = (response) => response?.status === 401 || response?.status =* cancelLater?: typeof clearTimeout,* }} deps `cloud()`: My Cloud's address and the signed-in account while the person has one, and whether the Admin last* said it sleeps. `powerChecked()`: asks the Admin again whether My Cloud sleeps, true once it answered just now.- * `computer()`: this computer is a place of its own (its bots did not move away). `napped()`: My Cloud answered that it+ * `computer()`: the workspace of this computer's own that joins My Cloud (togetherComputer), falsy when none does: a new+ * value is another workspace, whose lists are its own. `commands`: "Let your Clouds run commands on this computer"+ * (computer-sharing.mjs): whether it is on now, read from lending itself, and the notice's own switch for it, which turns it+ * on only through the same question the icon's menu asks (lending-dialogs.mjs). `napped()`: My Cloud answered that it* is going to sleep. `shown()`: the place whose page the window shows; "waking" for this app's own screen while My Cloud* wakes, "other" for any other place or screen, null while a page loads.* `focused()`: the window is the one the person is using: in front, and the screen not locked. `openPlace(home)`: main's@@ -146,8 +202,8 @@ const needsSignIn = (response) => response?.status === 401 || response?.status =* remains is a Cloud that fell asleep in the seconds since the Admin answered; one that only agreed to sleep answers so* itself and is left alone. Rows are kept for the Cloud and account they came from, and dropped the moment either changes.*/-export function createPlacesTogether({ pref, cloud, powerChecked, computer, local, cloudFetch, napped = () => {}, address = () => null, shown, focused, openPlace, send, changed, turnedOn = () => {}, now = Date.now,- setTimer = setInterval, clearTimer = clearInterval, later = setTimeout, cancelLater = clearTimeout }) {+export function createPlacesTogether({ pref, cloud, powerChecked, computer, local, cloudFetch, napped = () => {}, address = () => null, shown, focused, openPlace, send, changed, turnedOn = () => {}, commands = null, now = Date.now,+ setTimer = setInterval, clearTimer = clearInterval, later = setTimeout, cancelLater = clearTimeout, startQuietMs = START_QUIET_MS }) {/** What each place gave last: its rows, when, and how the last read went. */const kept = new Map();const reading = new Map();@@ -155,12 +211,38 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, locaconst aisWanted = new Set();/** Moves whenever the lists are dropped; a read that started before it moved is thrown away. */let epoch = 0;- let on = null, timer = null, pending = null, scope = null, cloudAskedAt = -Infinity, signIn = false, unheard = null;+ // The first read of My Cloud waits until the app has been up START_QUIET_MS: as if it had been asked just before.+ const neverAsked = now() - CLOUD_EVERY_MS + startQuietMs;+ let commandsSeen = null, saved = null, timer = null, pending = null, scope = null, cloudAskedAt = neverAsked, signIn = false, unheard = null;const placeShown = () => { const place = shown(); return place === "computer" || place === "cloud" ? place : null; };- const isOn = () => { if (on === null) { try { on = parseTogether(pref.read()); } catch { on = false; } } return on; };- const available = () => Boolean(cloud().origin) && computer();+ /** The file as last read or written: read once, then kept here. */+ const file = () => {+ if (saved) return saved;+ const read = readTogether(() => pref.read());+ if (!read.unreadable) saved = read;+ return read;+ };+ /** A file this app cannot read or does not understand is left as it is. */+ const untouchable = () => { const read = file(); return Boolean(read.unreadable || read.foreign || read.corrupt); };+ const write = (value) => { if (untouchable()) throw new Error("The switch's file is not one this app can change."); pref.write(value); saved = { kept: value }; };+ const chosen = () => (untouchable() ? false : choiceIn(file().kept, account()));+ const account = () => cloud().account ?? null;+ /** The default's notes for the signed-in account: the notice was shown, and closed or used. */+ const noted = (key) => stamped(file().kept[key], account());+ const note = (key, value) => {+ const { kept } = file(), who = account();+ if (!who || untouchable()) return;+ const map = { ...(record(kept[key]) ? kept[key] : {}) };+ if (value === null) delete map[who]; else map[who] = value;+ write({ ...kept, v: 1, [key]: map });+ };+ /** On: the person's own choice, else the default once the notice has been shown to this account. */+ const isOn = () => { const own = chosen(); return own === null ? noted("noticed") : own; };+ const available = () => Boolean(cloud().origin) && Boolean(computer());const active = () => isOn() && available();+ /** The notice of the default is due on this computer's page: offered, never chosen, and not closed by this account. */+ const noticeDue = () => available() && !untouchable() && chosen() === null && !noted("done");const tell = () => { try { changed(); } catch {} };function forget() {@@ -168,7 +250,7 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, locakept.clear();reading.clear();aisWanted.clear();- cloudAskedAt = -Infinity;+ cloudAskedAt = neverAsked;signIn = false;drop();}@@ -184,7 +266,8 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, loca/** The Cloud and account the lists belong to. Another one, or none, and they are gone at once. */function sameScope() {const { origin, account } = cloud();- const next = origin && isOn() && computer() ? `${origin}\n${account ?? ""}` : null;+ const here = computer();+ const next = origin && isOn() && here ? `${origin}\n${account ?? ""}\n${String(here)}` : null;if (next === scope) return;const had = kept.size > 0 || pending !== null;scope = next;@@ -314,26 +397,79 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, locareturn {/** Whether the switch is on and both places exist: what anything else that joins the two places asks. */on: active,+ /** Whether the switch is on for the signed-in account with My Cloud, whatever runs on this computer now: whether this+ * computer's own workspace should be started to join it (together-background.mjs). */+ switchOn: () => Boolean(cloud().origin) && isOn(),+ /** The switch is offered (the person has My Cloud and a workspace of this computer's own runs), and whether it is on:+ * what the rail's circles show in their menu. Null when it is not offered. */+ offered: () => (available() ? { on: isOn() } : null),/** What `asking`'s page draws: the switch, and the other place's bots while it is on. */state(asking) {sameScope();const here = asking === "cloud" ? "cloud" : "computer";- if (!active()) return { v: 1, available: available(), on: isOn(), here, other: null };+ let notice = {};+ if (here === "computer" && available()) {+ let lent = false;+ try { lent = commands?.on() === true; } catch {}+ // My Cloud as home: this computer's own workspace starts with the app (together-background.mjs), which the notice says.+ notice = { ...(noticeDue() ? { notice: true, ...(String(computer()).startsWith("profile:") ? { profileHome: true } : {}) } : {}), commands: lent };+ }+ if (!active()) return { v: 1, available: available(), on: isOn(), here, other: null, ...notice };watch();void refresh(otherHome(here));- return { v: 1, available: true, on: true, here, other: otherOf(here) };+ return { v: 1, available: true, on: true, here, other: otherOf(here), ...notice };},- /** The switch. Off forgets every list. Turned on from this computer's page, it also lets My Cloud run commands here- * (`turnedOn`), so the two places work as one with one switch; the person turns that alone off from the icon's menu. */- set(asking, value) {- const was = isOn();- on = value === true;- pref.write({ v: 1, on });- if (on && !was && asking === "computer") { try { turnedOn(); } catch {} }+ /** The switch. Off forgets every list. Turned on from Settings on this computer's page, whose words say so, it also+ * lets My Cloud run commands here (`turnedOn`), so the two places work as one with one switch; the person turns that+ * alone off from the icon's menu. The rail's row and the notice (`listOnly`) switch the list alone, and the default+ * never lends anything. */+ set(asking, value, { listOnly = false } = {}) {+ const was = isOn(), next = value === true;+ // The person's own turn in Settings repairs a file that is not JSON at all: the bad one is kept beside it first.+ if (!listOnly && file().corrupt && typeof pref.backup === "function") { pref.backup(); saved = { choice: null, kept: { v: 1 } }; }+ const { kept } = file(), who = account();+ write({ ...kept, v: 1, on: next, choices: { ...(record(kept.choices) ? kept.choices : {}), ...(who ? { [who]: next } : {}) } });+ if (next && !was && asking === "computer" && !listOnly) { try { turnedOn(); } catch {} }sameScope();tell();return this.state(asking);},+ /** This computer's page shows the notice of the default: from now on it is on for this account. Nothing before this: an+ * app closed before the notice was seen has joined and linked nothing. Running commands here is left as it is. True+ * when it is on now. */+ noticeShown(asking) {+ sameScope();+ if (asking !== "computer" || !noticeDue() || !account()) return false;+ if (!noted("noticed")) note("noticed", now());+ sameScope();+ tell();+ return active();+ },+ /** The notice's own switch for "Let My Cloud's bots run commands on this computer", from this computer's page while the+ * joining is offered: the person's own choice, kept as the icon's menu keeps it. What it is now. */+ async setCommands(asking, value) {+ if (asking !== "computer" || !available() || !commands) throw new Error("Turn this from this computer's page.");+ await commands.set(value === true);+ tell();+ return commands.on();+ },+ /** Lending says whether My Cloud may run commands here (it changed, or it says it again): a page showing it asks again. */+ commandsChanged(on) {+ if (on === commandsSeen) return;+ commandsSeen = on;+ if (available()) tell();+ },+ /** The person closed the notice (Got it, its close button or Escape): it never shows again for this account. */+ noticeDone(asking) {+ if (asking !== "computer" || !account()) return;+ try { note("done", now()); } catch {}+ tell();+ },+ /** Off for the link (bot-link-main.mjs): the person turned it off, or never chose and has not seen the notice yet. A+ * file that cannot be read just now leaves the link alone. */+ switchedOff: () => !untouchable() && !isOn(),+ /** The person's own choice: true, false, or null while they never chose. */+ chosen,refresh,/** The signed-in account or My Cloud's address may have changed: lists that belong to another are dropped now. */scopeChanged: sameScope,@@ -378,7 +514,7 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, locaarrived() {sameScope();const place = placeShown();- if (place === "cloud" && signIn) { signIn = false; cloudAskedAt = -Infinity; }+ if (place === "cloud" && signIn) { signIn = false; cloudAskedAt = neverAsked; }if (!pending || place !== pending.home) return;const { channel, value } = pending;drop();@@ -405,21 +541,39 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, loca** Security: only this computer's own page turns the switch on. My Cloud's page is served by the Cloud, so it may turn the* joining off but never start it. */-export function installPlacesTogether({ ipcMain, asking, together }) {+export function installPlacesTogether({ ipcMain, asking, together, rail = () => false }) {const side = (event) => {const page = asking(event);if (!page) throw new Error("Only this computer's page and My Cloud's page list each other's bots.");return page === "cloud" ? "cloud" : "computer";};ipcMain.handle("places-together:state", (event) => together.state(side(event)));- ipcMain.handle("places-together:set", (event, value) => {+ ipcMain.handle("places-together:set", (event, value, from) => {const page = side(event);if (value === true && page !== "computer") throw new Error("Turn this on from this computer's page.");- return together.set(page, value === true);+ return together.set(page, value === true, { listOnly: from === "notice" });});ipcMain.handle("places-together:open", (event, botId) => together.open(side(event), String(botId)));ipcMain.handle("places-together:new-bot-choice", (event) => together.newBotChoice(side(event)));ipcMain.handle("places-together:new-bot", (event) => together.newBot(side(event)));ipcMain.handle("places-together:new-bot-heard", (event) => { side(event); together.newBotHeard(); });+ ipcMain.handle("places-together:notice-shown", (event) => together.noticeShown(side(event)));+ ipcMain.handle("places-together:notice-done", (event) => { together.noticeDone(side(event)); });+ ipcMain.handle("places-together:commands", (event, value) => together.setCommands(side(event), value === true));+ // The rail's own page (this app's, beside whichever place is open): Show bots together in a circle's menu.+ ipcMain.handle("places-together:rail-set", (event, value) => {+ if (!rail(event)) throw new Error("Only the window's rail turns this from a circle's menu.");+ return together.set("computer", value === true, { listOnly: true }).on;+ });return together;}++/** The switch's file in the desktop app's own folder: read, written whole, and, before a corrupt one is repaired, kept beside+ * it as `<name>.unreadable-<time>`. */+export function togetherPrefFile(file, fs = nodeFs, now = Date.now) {+ return {+ read: () => JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, "")),+ write: (value) => { const temporary = `${file}.${process.pid}.tmp`; fs.writeFileSync(temporary, JSON.stringify(value), { mode: 0o600 }); fs.renameSync(temporary, file); },+ backup: () => fs.copyFileSync(file, `${file}.unreadable-${now()}`),+ };+}diff --git a/electron/places-together.node-test.mjs b/electron/places-together.node-test.mjsindex 66ee34db02..59d23dc6e3 100644--- a/electron/places-together.node-test.mjs+++ b/electron/places-together.node-test.mjs@@ -35,6 +35,7 @@ function setup(over = {}) {now: () => f.clock,setTimer: (run, ms) => { f.tick = { run, ms }; return {}; }, clearTimer: () => { f.cleared += 1; },later: (run, ms) => { const timer = { run, ms, cancelled: false }; f.timeouts.push(timer); return timer; }, cancelLater: (timer) => { if (timer) timer.cancelled = true; },+ startQuietMs: 0,...over.deps,});/** The next read of My Cloud is due: a minute has passed. */@@ -48,7 +49,7 @@ test("the switch starts off, and off reads nothing, keeps nothing and starts nof.together.linkChanged();assert.equal(parseTogether(null), false);assert.equal(parseTogether({ v: 1, on: "yes" }), false);- assert.deepEqual(f.together.state("computer"), { v: 1, available: true, on: false, here: "computer", other: null });+ assert.deepEqual(f.together.state("computer"), { v: 1, available: true, on: false, here: "computer", other: null, notice: true, commands: false }, "never chosen: off until its notice is shown");await f.together.refresh("cloud");assert.equal(f.together.open("computer", "nova"), false);f.together.arrived();@@ -399,13 +400,27 @@ test("turning it off forgets every list and stops the timer; the choice is kept"await f.together.refresh("cloud");f.together.open("computer", "nova");const off = f.together.set("computer", false);- assert.deepEqual([off.on, off.other, f.saved, f.cleared], [false, null, { v: 1, on: false }, 1]);+ assert.deepEqual([off.on, off.other, f.saved, f.cleared], [false, null, { v: 1, on: false, choices: { "acct-a": false } }, 1]);f.shown = "cloud";f.together.arrived();assert.deepEqual(f.sent, []);assert.equal(f.together.open("computer", "nova"), false);const on = f.together.set("computer", true);- assert.deepEqual([on.on, on.other.bots, f.saved], [true, [], { v: 1, on: true }]);+ assert.deepEqual([on.on, on.other.bots, f.saved], [true, [], { v: 1, on: true, choices: { "acct-a": true } }]);+});++test("a choice is the account's own: another account signed in on this computer has not chosen, and a file from before choices counts for everyone until the first choice", () => {+ const f = setup({ saved: { v: 1, on: true } });+ assert.equal(f.together.chosen(), true, "a file from before per-account choices: its one choice stands");+ f.together.set("computer", false);+ assert.deepEqual(f.saved, { v: 1, on: false, choices: { "acct-a": false } }, "`on` stays written, the last choice, for an older app");+ f.cloud = { ...f.cloud, account: "acct-b" };+ assert.equal(f.together.chosen(), null, "acct-b never chose: the default and its notice are theirs to see");+ assert.equal(f.together.state("computer").notice, true);+ f.together.set("computer", true);+ f.cloud = { ...f.cloud, account: "acct-a" };+ assert.equal(f.together.chosen(), false, "acct-a's off is kept");+ assert.equal(f.together.on(), false);});test("without a My Cloud, or once this computer's bots moved away, there is nothing to join", async () => {@@ -474,8 +489,9 @@ test("only this computer's page and My Cloud's own page are answered", async ()const handlers = new Map();const f = setup();installPlacesTogether({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, asking: (event) => event.page, together: f.together });- assert.deepEqual([...handlers.keys()], ["places-together:state", "places-together:set", "places-together:open", "places-together:new-bot-choice", "places-together:new-bot", "places-together:new-bot-heard"]);- for (const handler of handlers.values()) assert.throws(() => handler({ page: null }, "nova"), /Only this computer's page and My Cloud's page/);+ assert.deepEqual([...handlers.keys()], ["places-together:state", "places-together:set", "places-together:open", "places-together:new-bot-choice", "places-together:new-bot", "places-together:new-bot-heard",+ "places-together:notice-shown", "places-together:notice-done", "places-together:commands", "places-together:rail-set"]);+ for (const [channel, handler] of handlers) assert.throws(() => handler({ page: null }, "nova"), channel === "places-together:rail-set" ? /Only the window's rail/ : /Only this computer's page and My Cloud's page/);assert.equal(handlers.get("places-together:state")({ page: "local" }).here, "computer");assert.equal(handlers.get("places-together:state")({ page: "cloud" }).here, "cloud");assert.equal(handlers.get("places-together:set")({ page: "local" }, "yes").on, false, "only true turns it on");@@ -491,13 +507,21 @@ test("main wires it to the one rule for this app's own pages, and the preload ofassert.match(main, /desktopNotifications\.arrived\(\); placesTogether\.arrived\(\);/);assert.match(main, /try \{ placesTogether\.scopeChanged\(\); \} catch \{\}/, "an account change or sign-out drops the lists at once");assert.match(main, /placesTogether\.navigated\(homeOfUrl\(url\)\)/);- assert.match(main, /powerChecked: async \(\) => \{ const account = cloudAccount; if \(!account\) return false; await account\.refresh\(\); return Date\.now\(\) - \(account\.state\(\)\.verifiedAt \?\? 0\) < 5_000; \}/);+ assert.match(main, /const cloudAwakeNow = async \(\) => \{ const account = cloudAccount; if \(!account\) return false; if \(Date\.now\(\) - \(account\.state\(\)\.verifiedAt \?\? 0\) >= 5_000\) await account\.refresh\(\); return Date\.now\(\) - \(account\.state\(\)\.verifiedAt \?\? 0\) < 5_000; \};/);+ assert.match(main, /awakeNow: async \(\) => \(await cloudAwakeNow\(\)\) && !cloudPower\.asleep\(\)/, "the Bots in two places card reads My Cloud only on a fresh awake");+ assert.match(main, /powerChecked: cloudAwakeNow, computer:/, "the list asks the Admin just before each read of My Cloud");+ assert.match(main, /commands: \{ on: \(\) => sharingController\(\)\.terminalOn\(\), set: on => \(on \? lendingDialogs\.lendTerminal\(true, \(\) => sharingController\(\)\.lendTerminal\(true\)\) : sharingController\(\)\.lendTerminal\(false\)\) \}/,+ "the notice's commands switch reads lending itself and asks the icon menu's own question before turning it on");+ assert.match(main, /linkCommandsFact\.observe\(summary\); try \{ placesTogether\.commandsChanged\(summary\.terminal === true\); \} catch \{\} \}/, "and stays live while the notice is up");+ assert.match(main, /chosen: \(\) => placesTogether\.chosen\(\), powerChecked: cloudAwakeNow, napped: \(\) => cloudPower\.hold\(\), proved: \(\) => cloudPower\.woke\(\), quietMs: START_QUIET_MS,/, "so does the link's first pairing on by default");+ assert.match(main, /computer: \(\) => togetherComputer\(\{ cloudHome: Boolean\(homeWindow\.cloudOrigin\(\)\), ownHome: Boolean\(ownHome\?\.origin\(\)\), frozen: cleanWorkspace\.marker\(\)\.frozen, profile: cleanWorkspace\.profile\(\), running: runningDataDir \}\)/, "the freeze marker counts before the home window knows My Cloud is home");assert.match(main, /focused: \(\) => powerMonitor\.getSystemIdleState\(60\) !== "locked" && Boolean\(mainWindow && !mainWindow\.isDestroyed\(\) && mainWindow\.isFocused\(\)\)/);assert.equal(main.match(/places-together:/g).length, 1, "main sends only that the list changed, never the list");const preload = readFileSync(join(HERE, "preload.cjs"), "utf8");assert.match(preload.match(/const REMOTE_SAFE = new Set\(\[([^\]]*)\]\)/)[1], /"placesTogether"/);const bridge = preload.slice(preload.indexOf(" placesTogether: "), preload.indexOf(" twoPlaces: {"));- assert.deepEqual(bridge.match(/"places-together:[a-z-]+"/g), ['"places-together:state"', '"places-together:set"', '"places-together:open"', '"places-together:changed"', '"places-together:changed"', '"places-together:new-bot-choice"', '"places-together:new-bot"']);+ assert.deepEqual(bridge.match(/"places-together:[a-z-]+"/g), ['"places-together:state"', '"places-together:set"', '"places-together:open"', '"places-together:changed"', '"places-together:changed"',+ '"places-together:notice-shown"', '"places-together:notice-done"', '"places-together:commands"', '"places-together:new-bot-choice"', '"places-together:new-bot"']);});test("the +'s other place: that place opens and is told to make the bot itself, once its page has loaded", async () => {@@ -730,3 +754,4 @@ test("the preload forgets a new bot nobody listened for: when main says so, andassert.equal(made, 0, "a page that starts listening later, such as after a sign-in, makes no bot");assert.deepEqual(late.invoked, []);});+diff --git a/electron/preload.cjs b/electron/preload.cjsindex b1cad3e6c3..09235d8713 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -193,6 +193,9 @@ const bridge = {? ipcRenderer.invoke("workspaces:make-home", String(id)) : Promise.reject(new Error("Choose Make my home.")),// The ids of the servers main offers Make … my home for now (this computer's own page and the rail's only).homeOffers: () => ipcRenderer.invoke("workspaces:home-offers"),+ // Show bots together (This computer and My Cloud together), from a click in a circle's menu on the rail's own page (main refuses any other page).+ together: (on) => isLocalPage || navigator.userActivation?.isActive === true+ ? ipcRenderer.invoke("places-together:rail-set", on === true) : Promise.reject(new Error("Choose Show bots together.")),onChanged: (cb) => {const handler = () => cb();ipcRenderer.on("workspaces:changed", handler);@@ -622,8 +625,8 @@ const bridge = {// This computer's page and My Cloud's own page (main refuses any other): the other one's bots, listed beside this one's.placesTogether: process.argv.includes("--omb-company-desktop=1") ? {state: () => ipcRenderer.invoke("places-together:state"),- set: on => isLocalPage || navigator.userActivation?.isActive === true- ? ipcRenderer.invoke("places-together:set", on === true) : Promise.reject(new Error("Turn the switch to list both places' bots.")),+ set: (on, from) => isLocalPage || navigator.userActivation?.isActive === true+ ? ipcRenderer.invoke("places-together:set", on === true, ...(from === "notice" ? ["notice"] : [])) : Promise.reject(new Error("Turn the switch to list both places' bots.")),open: botId => isLocalPage || navigator.userActivation?.isActive === true? ipcRenderer.invoke("places-together:open", String(botId)) : Promise.reject(new Error("Choose a bot to open it.")),onChanged: cb => {@@ -631,6 +634,11 @@ const bridge = {ipcRenderer.on("places-together:changed", handler);return () => ipcRenderer.removeListener("places-together:changed", handler);},+ // The notice of the default was drawn on this page, and the person closed it (main answers this computer's page only).+ noticeShown: () => ipcRenderer.invoke("places-together:notice-shown"),+ noticeDone: () => ipcRenderer.invoke("places-together:notice-done"),+ setCommands: on => isLocalPage || navigator.userActivation?.isActive === true+ ? ipcRenderer.invoke("places-together:commands", on === true) : Promise.reject(new Error("Turn the switch to let My Cloud's bots run commands.")),newBotChoice: () => ipcRenderer.invoke("places-together:new-bot-choice"),newBot: () => isLocalPage || navigator.userActivation?.isActive === true? ipcRenderer.invoke("places-together:new-bot") : Promise.reject(new Error("Choose where the new bot lives.")),diff --git a/electron/together-background.d.mts b/electron/together-background.d.mtsnew file mode 100644index 0000000000..c762e33b1f--- /dev/null+++ b/electron/together-background.d.mts@@ -0,0 +1,22 @@+export const TRY_AT_MS: number[];+export const BUSY_RETRY_MS: number;+export const BUSY_TRIES: number;+export function holdsBots(dir: string, fs?: unknown): boolean;+export function createTogetherBackground(deps: {+ cloudHome(): boolean;+ togetherOn(): boolean;+ shown(): string | null;+ ownCopyRuns(): boolean;+ running(): string | null;+ dataDir(): string;+ open(id: string): Promise<boolean>;+ leave(): Promise<boolean>;+ busy(): Promise<boolean>;+ linkOff?(): Promise<unknown>;+ fs?: unknown;+ tryAt?: number[];+ now?(): number;+ later?: typeof setTimeout;+ cancel?: typeof clearTimeout;+ log?(line: string): void;+}): { start(): void; settled(): void; changed(): void; run(): Promise<boolean>; close(): void };diff --git a/electron/together-background.mjs b/electron/together-background.mjsnew file mode 100644index 0000000000..33e2aca5a7--- /dev/null+++ b/electron/together-background.mjs@@ -0,0 +1,111 @@+// "This computer and My Cloud together" for a person whose home is My Cloud: this computer's own bots live in a workspace of+// its own (This Mac or This PC, the `default` profile, clean-workspace.mjs), which runs only once opened, while the folder+// the app starts on is the copy the move froze. With together on, this starts that workspace's server in the background+// after launch, so the one list and the link work without first clicking This Mac; the window stays where it is.+//+// Only when: My Cloud is home; the switch is on for the signed-in account; the window shows My Cloud (not while it loads+// or shows the screen of a Cloud waking up); the frozen copy runs (no other workspace was opened); the workspace exists and+// holds at least one bot. Never the frozen copy, never a new workspace made for it. Tried at TRY_AT_MS after launch and+// when the window settles in between, never inside the launch's quiet start, and started at most once a launch.+//+// Turned off again while the workspace it started runs and the window is not on it: the link is ended first, on that+// workspace's own server (its Cloud is told and forgets it), then the frozen copy runs again, once no turn is under way+// there (asked again every BUSY_RETRY_MS, at most BUSY_TRIES times; past that it stays until relaunch). Turned on again in+// the same session, it is tried again on the same schedule, from then.+import nodeFs from "node:fs";+import path from "node:path";++import { DEFAULT_PROFILE, profileDir } from "./clean-workspace.mjs";+import { START_QUIET_MS } from "./places-together.mjs";++/** When after launch it is tried: past the quiet start, and again while the window may still be loading. */+export const TRY_AT_MS = [START_QUIET_MS, 45_000, 120_000];+export const BUSY_RETRY_MS = 30_000;+export const BUSY_TRIES = 20;++/** Whether the workspace in `dir` holds a bot of its own: its bots.json lists one that is not hidden and did not move. A+ * folder or file that is missing or can't be read holds none. */+export function holdsBots(dir, fs = nodeFs) {+ let bots;+ try { bots = JSON.parse(fs.readFileSync(path.join(dir, "bots.json"), "utf8")); } catch { return false; }+ return Array.isArray(bots) && bots.some((bot) => bot && typeof bot === "object" && typeof bot.id === "string" && !bot.hidden && !bot.movedTo);+}++/**+ * @param {{+ * cloudHome(): boolean,+ * togetherOn(): boolean,+ * shown(): string | null,+ * ownCopyRuns(): boolean,+ * running(): string | null,+ * dataDir(): string,+ * open(id: string): Promise<boolean>,+ * leave(): Promise<boolean>,+ * busy(): Promise<boolean>,+ * linkOff(): Promise<unknown>,+ * fs?: typeof nodeFs,+ * tryAt?: number[],+ * now?(): number,+ * later?: typeof setTimeout,+ * cancel?: typeof clearTimeout,+ * log?(line: string): void,+ * }} deps `togetherOn()`: the switch is on for the signed-in account (places-together.mjs `switchOn`). `shown()`: the place+ * the window shows ("cloud", "computer", "waking", "other", null while a page loads). `ownCopyRuns()`: this computer's+ * server runs on the frozen copy. `running()`: the workspace that runs now (clean-workspace.mjs `profile`). `open(id)` and+ * `leave()`: start that workspace's server, or the frozen copy's again, without moving the window. `busy()`: a turn is+ * under way in the workspace that runs (or it could not say). `linkOff()`: the link is brought in line with the switch+ * (bot-link-main.mjs `look`), ended on the server that runs now, before that server stops.+ */+export function createTogetherBackground({ cloudHome, togetherOn, shown, ownCopyRuns, running, dataDir, open, leave, busy, linkOff = async () => {}, fs = nodeFs, tryAt = TRY_AT_MS,+ now = Date.now, later = setTimeout, cancel = clearTimeout, log = () => {} }) {+ /** When the tries were last scheduled from: the launch, or the switch turned on again. */+ let launchedAt = now(), wasOn = null;+ const timers = new Set();+ let started = false, opening = false, startedHere = false, stopping = null;+ const schedule = (run, ms) => { const timer = later(() => { timers.delete(timer); void run(); }, ms); timer?.unref?.(); timers.add(timer); };++ async function run() {+ if (started || opening || now() - launchedAt < tryAt[0] || now() - launchedAt > tryAt.at(-1) + 1_000) return false;+ if (!cloudHome() || !togetherOn() || shown() !== "cloud" || !ownCopyRuns()) return false;+ if (!holdsBots(profileDir(dataDir(), DEFAULT_PROFILE), fs)) return false;+ opening = true;+ const opened = await open(DEFAULT_PROFILE).catch((error) => { log(`together: this computer's workspace did not start (${error?.message ?? error})`); return false; }).finally(() => { opening = false; });+ if (opened !== true) return false;+ started = startedHere = true;+ log("together: this computer's workspace started in the background");+ return true;+ }++ /** Turned off: the frozen copy again, once the workspace this started is idle, unless the window shows it. */+ async function stopOnce(tries) {+ stopping = null;+ if (!startedHere || togetherOn() || running() !== DEFAULT_PROFILE) { startedHere = startedHere && running() === DEFAULT_PROFILE; return; }+ if (shown() === "computer") return;+ // The link ends on this workspace's own server, and its Cloud is told, before that server stops.+ await linkOff().catch((error) => log(`together: the link did not end before the workspace stopped (${error?.message ?? error})`));+ if (togetherOn() || running() !== DEFAULT_PROFILE) return;+ if (await busy().catch(() => true)) {+ if (tries + 1 < BUSY_TRIES) { stopping = tries + 1; schedule(() => stopOnce(tries + 1), BUSY_RETRY_MS); }+ else log("together: this computer's workspace keeps working; it stops at the next launch");+ return;+ }+ if (await leave().catch(() => false)) { startedHere = false; log("together: off, so this computer's workspace stopped and the frozen copy runs again"); }+ }++ const scheduleTries = () => { for (const ms of tryAt) schedule(run, Math.max(0, ms - (now() - launchedAt))); };+ return {+ /** The launch is under way: tried at each of TRY_AT_MS. */+ start() { wasOn = togetherOn(); scheduleTries(); },+ /** The window finished loading a page: tried now, within the launch's tries. */+ settled() { void run(); },+ /** The switch changed: turned off, the workspace this started stops; turned on again, it is tried again from now. */+ changed() {+ const on = togetherOn();+ if (!on && startedHere && stopping === null) void stopOnce(0);+ if (on && wasOn === false && !startedHere) { started = false; launchedAt = now(); for (const timer of timers) cancel(timer); timers.clear(); scheduleTries(); }+ wasOn = on;+ },+ run,+ close() { for (const timer of timers) cancel(timer); timers.clear(); },+ };+}diff --git a/electron/together-background.node-test.mjs b/electron/together-background.node-test.mjsnew file mode 100644index 0000000000..025fe63f57--- /dev/null+++ b/electron/together-background.node-test.mjs@@ -0,0 +1,157 @@+import assert from "node:assert/strict";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++import { profileDir } from "./clean-workspace.mjs";+import { BUSY_RETRY_MS, BUSY_TRIES, createTogetherBackground, holdsBots, TRY_AT_MS } from "./together-background.mjs";++const HERE = dirname(fileURLToPath(import.meta.url));++function setup(t, { bots = [{ id: "ledger", name: "Ledger" }] } = {}) {+ const root = mkdtempSync(join(tmpdir(), "together-background-"));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ const data = join(root, "omb");+ if (bots) { mkdirSync(profileDir(data, "default"), { recursive: true }); writeFileSync(join(profileDir(data, "default"), "bots.json"), JSON.stringify(bots)); }+ const f = { cloudHome: true, on: true, shown: "cloud", running: null, busy: false, opened: [], left: 0, timers: [], clock: 0, order: [] };+ f.background = createTogetherBackground({+ cloudHome: () => f.cloudHome, togetherOn: () => f.on, shown: () => f.shown, ownCopyRuns: () => f.running === null, running: () => f.running, dataDir: () => data,+ open: async (id) => { f.opened.push(id); f.running = id; return true; }, leave: async () => { f.order.push("leave"); f.left += 1; f.running = null; return true; }, busy: async () => f.busy,+ linkOff: async () => { f.order.push("link off:start"); await new Promise((done) => setImmediate(done)); f.order.push("link off:done"); },+ now: () => f.clock, later: (run, ms) => { const timer = { run, ms }; f.timers.push(timer); return timer; }, cancel: () => {},+ });+ /** Time moves to `at` ms after launch and every try due by then runs. */+ f.at = async (at) => { f.clock = at; for (const timer of f.timers.splice(0).sort((a, b) => a.ms - b.ms)) { if (timer.ms <= at) await timer.run(); else f.timers.push(timer); } await new Promise((done) => setImmediate(done)); };+ return f;+}++test("My Cloud home, together on: this computer's own workspace starts in the background once the launch's quiet start is over, and only once", async (t) => {+ const f = setup(t);+ f.background.start();+ f.background.settled();+ assert.deepEqual(f.opened, [], "nothing during the launch's quiet start, even when the window settles");+ assert.deepEqual(f.timers.map((timer) => timer.ms), TRY_AT_MS);+ await f.at(TRY_AT_MS[0]);+ assert.deepEqual(f.opened, ["default"]);+ await f.at(TRY_AT_MS.at(-1));+ assert.deepEqual(f.opened, ["default"], "once a launch");+});++test("a window still loading, or on the screen of My Cloud waking, is tried again at the next try and when it settles, and then no more", async (t) => {+ const f = setup(t);+ f.shown = null;+ f.background.start();+ await f.at(TRY_AT_MS[0]);+ assert.deepEqual(f.opened, []);+ f.shown = "waking";+ await f.at(TRY_AT_MS[1]);+ assert.deepEqual(f.opened, []);+ f.shown = "cloud";+ f.clock = TRY_AT_MS[1] + 5_000;+ f.background.settled();+ await new Promise((done) => setImmediate(done));+ assert.deepEqual(f.opened, ["default"], "the window settled on My Cloud: started then");+ const late = setup(t);+ late.shown = null;+ late.background.start();+ await late.at(TRY_AT_MS.at(-1));+ late.shown = "cloud";+ late.clock = TRY_AT_MS.at(-1) + 60_000;+ late.background.settled();+ await new Promise((done) => setImmediate(done));+ assert.deepEqual(late.opened, [], "past the last try it is left for the next launch");+});++test("it never starts: together off, home this computer, the window on another place, another workspace running, or a workspace with no bot or none at all", async (t) => {+ for (const [why, change] of [["together off", (f) => { f.on = false; }], ["home is this computer", (f) => { f.cloudHome = false; }],+ ["the window shows another place", (f) => { f.shown = "other"; }], ["a workspace runs already", (f) => { f.running = "work"; }]]) {+ const f = setup(t);+ change(f);+ f.clock = TRY_AT_MS[0];+ assert.equal(await f.background.run(), false, why);+ assert.deepEqual(f.opened, [], why);+ }+ for (const [why, bots] of [["no workspace", null], ["no bot", []], ["only bots that moved or are hidden", [{ id: "a", movedTo: "x" }, { id: "b", hidden: true }]]]) {+ const f = setup(t, { bots });+ f.clock = TRY_AT_MS[0];+ assert.equal(await f.background.run(), false, why);+ assert.deepEqual(f.opened, [], why);+ }+});++test("turned off: the workspace it started stops and the frozen copy runs again, once no turn is under way, never while the window shows it, never one the person opened", async (t) => {+ const f = setup(t);+ f.background.start();+ await f.at(TRY_AT_MS[0]);+ f.on = false;+ f.busy = true;+ f.background.changed();+ await new Promise((done) => setImmediate(done));+ assert.equal(f.left, 0, "a turn is under way: it waits");+ assert.equal(f.timers.some((timer) => timer.ms === BUSY_RETRY_MS), true);+ f.busy = false;+ await f.at(BUSY_RETRY_MS);+ assert.deepEqual([f.left, f.running], [1, null], "idle now: back to the frozen copy");++ const looking = setup(t);+ looking.background.start();+ await looking.at(TRY_AT_MS[0]);+ looking.on = false;+ looking.shown = "computer";+ looking.background.changed();+ await new Promise((done) => setImmediate(done));+ assert.equal(looking.left, 0, "the person is on This Mac: it stays");++ const opened = setup(t);+ opened.running = "default";+ opened.on = false;+ opened.background.changed();+ await new Promise((done) => setImmediate(done));+ assert.equal(opened.left, 0, "a workspace the person opened is theirs");+ assert.equal(BUSY_TRIES > 1, true);+});++test("a workspace counts as holding bots only from a readable bots.json", (t) => {+ const root = mkdtempSync(join(tmpdir(), "together-bots-"));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ assert.equal(holdsBots(join(root, "missing")), false);+ writeFileSync(join(root, "bots.json"), "{not json");+ assert.equal(holdsBots(root), false);+ writeFileSync(join(root, "bots.json"), JSON.stringify([{ id: "scout" }]));+ assert.equal(holdsBots(root), true);+});++test("main starts it after the start place opened, tries it as the window settles, stops it when the switch changes, and opens and leaves without moving the window", () => {+ const main = readFileSync(join(HERE, "main.mjs"), "utf8");+ assert.match(main, /await showStartPlace\(\); void cloudAccountRestored\(\)\.then\(\(\) => teamLinks\.ready\(\)\); togetherBackground\.start\(\);/);+ assert.match(main, /desktopNotifications\.arrived\(\); placesTogether\.arrived\(\); togetherBackground\.settled\(\);/);+ assert.match(main, /try \{ togetherBackground\.changed\(\); \} catch \{\}/);+ assert.match(main, /shown: placeShown, ownCopyRuns: \(\) => cleanWorkspace\.ownCopy\(\), running: \(\) => cleanWorkspace\.profile\(\)/, "it reads which place the window shows and whether the frozen copy runs from main's own state");+ assert.match(main, /linkOff: async \(\) => \{ await botLink\?\.look\(\); await botLink\?\.look\(\); \}/);+ assert.match(main, /open: id => cleanWorkspace\.open\(id, \{ background: true \}\), leave: \(\) => cleanWorkspace\.leave\(\{ background: true \}\)/);+ assert.match(main, /windowFollows = \(\) => !background && \(placeSwitch\.turn\(\) === asked \|\|/, "a background start or stop never moves the window or the remembered place");+ const clean = readFileSync(join(HERE, "clean-workspace.mjs"), "utf8");+ assert.match(clean, /if \(background && !fs\.existsSync\(dir\)\) return false;/);+ assert.match(clean, /const leave = \(\{ background = false \} = \{\}\) => inTurn\(\(\) => \(active\(\) \? swapTo\(dataDir\(\), background \? \{ background: true \} : undefined\) : true\)\);/);+});++test("turned off, the link is ended on the workspace's own server before it stops; turned on again in the same session, it is tried again from then", async (t) => {+ const f = setup(t);+ f.background.start();+ await f.at(TRY_AT_MS[0]);+ f.on = false;+ f.background.changed();+ await new Promise((done) => setTimeout(done, 20));+ assert.deepEqual(f.order, ["link off:start", "link off:done", "leave"], "the link ends (and its Cloud is told) before the frozen copy runs again");+ f.clock = 10 * 60_000;+ f.timers.length = 0;+ f.on = true;+ f.background.changed();+ assert.deepEqual(f.timers.map((timer) => timer.ms), TRY_AT_MS, "the tries start again from the switch turned on");+ const base = f.clock;+ for (const timer of f.timers) timer.ms += base;+ await f.at(base + TRY_AT_MS[0]);+ assert.deepEqual(f.opened, ["default", "default"]);+});diff --git a/electron/two-places-main.d.mts b/electron/two-places-main.d.mtsindex f246ec8efe..4b36be1d7c 100644--- a/electron/two-places-main.d.mts+++ b/electron/two-places-main.d.mts@@ -18,6 +18,10 @@ export function installTwoPlacesMain(deps: {/** The verified account, whose state lists the person's teams; with `teamsRemembered`, each team is a place read for its bots. */account?: () => ({ state(): any } | null);teamsRemembered?: { read(): unknown; write(value: unknown): void };+ /** "This computer and My Cloud together" is on: My Cloud is never suggested. */+ together?(): boolean;+ /** The Admin answered just now that My Cloud is awake: only then is it read or told. */+ awakeNow?(): Promise<boolean>;tell(): void;log?(line: string): void;}): TwoPlaces & { close(): void };diff --git a/electron/two-places-main.mjs b/electron/two-places-main.mjsindex 9bd33cab29..a3eecd422f 100644--- a/electron/two-places-main.mjs+++ b/electron/two-places-main.mjs@@ -42,9 +42,11 @@ async function sent(response, what) {* }} deps `guard`: this computer's own page only. `cloud()`: My Cloud's address while it is ready, and whether it sleeps* now (a sleeping Cloud is never asked). `account()` and `teamsRemembered`: the person's teams, read as places that have* bots. `lastRead`: each own place's bots as last read, kept across restarts. `tell()`: the suggestion changed, so this- * computer's page asks again.+ * computer's page asks again. `together()`: "This computer and My Cloud together" is on (places-together.mjs): their bots+ * already work together, so My Cloud is never suggested. `awakeNow()`: the Admin answered just now that My Cloud is awake+ * (main asks it again when its word is older than a few seconds): My Cloud is read or told only then.*/-export function installTwoPlacesMain({ ipcMain, guard, localRequest, fetch: fetchImpl, environments, cloud, oneHome, ownHome, dismissed, lastRead = null, account = null, teamsRemembered = null, tell, log = () => {}, t = nativeText.englishText.t }) {+export function installTwoPlacesMain({ ipcMain, guard, localRequest, fetch: fetchImpl, environments, cloud, oneHome, ownHome, dismissed, lastRead = null, account = null, teamsRemembered = null, together = () => false, awakeNow = async () => true, tell, log = () => {}, t = nativeText.englishText.t }) {const put = (payload) => ({ method: "PUT", body: JSON.stringify(payload), signal: AbortSignal.timeout(10_000) });const teams = account && teamsRemembered ? teamPlaces({ account, fetch: fetchImpl, remembered: teamsRemembered }) : () => [];const places = () => {@@ -55,13 +57,14 @@ export function installTwoPlacesMain({ ipcMain, guard, localRequest, fetch: fetcconst request = (route, init = {}) => fetchImpl(`${mine.origin}${route}`, { credentials: "include", cache: "no-store", redirect: "error", signal: AbortSignal.timeout(10_000), ...init,headers: { accept: "application/json", origin: mine.origin, ...BACKGROUND_HEADERS, ...init.headers } });out.push({ key: `cloud:${mine.origin}`, name: t("cloudSetup.myCloud"), kind: "cloud",- read: async () => (cloud().asleep ? null : json(await request("/api/cloud-send?move=1"))),+ // Only right after the Admin said just now that it is awake: its last word may be from before it went to sleep.+ read: async () => (cloud().asleep || !(await awakeNow()) || cloud().asleep ? null : json(await request("/api/cloud-send?move=1"))),// Asleep since it was listed: still not told, as it is not read....(mine.asleep ? {} : { tell: async (payload) => {- if (cloud().asleep) throw new Error(`${t("cloudSetup.myCloud")} is asleep`);+ if (cloud().asleep || !(await awakeNow())) throw new Error(`${t("cloudSetup.myCloud")} is asleep`);return sent(await request(ROUTE, { ...put(payload), headers: { "content-type": "application/json" } }), t("cloudSetup.myCloud"));} }),- ...(keep.on && !keep.moved && !mine.asleep ? { bring: () => oneHome.keep.set(false) } : {}) });+ ...(keep.on && !keep.moved && !mine.asleep && !together() ? { bring: () => oneHome.keep.set(false) } : {}) });}for (const place of environments().filter((entry) => handSaved(entry) && ownHome.owns(entry))) {const server = serverRequests(place, fetchImpl);diff --git a/electron/two-places.node-test.mjs b/electron/two-places.node-test.mjsindex 12424f082a..dae5b6204f 100644--- a/electron/two-places.node-test.mjs+++ b/electron/two-places.node-test.mjs@@ -96,9 +96,30 @@ test("each place is read again at most every ten minutes, unless something aboutassert.equal(w.reads, 3);});+test("My Cloud is read for the card only right after the Admin said just now that it is awake: never on its older word", async () => {+ const handlers = new Map(), asked = [];+ let fresh = false;+ const main = installTwoPlacesMain({+ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, guard: (_channel, handler) => handler,+ localRequest: async () => Response.json(summary("Scout")),+ fetch: async (url) => { asked.push(new URL(url).origin); return Response.json(summary("Chief")); },+ environments: () => [], cloud: () => ({ origin: "https://omb-u-1.fly.dev", asleep: false }),+ oneHome: { journal: () => null, keep: { state: () => ({ shown: true, on: true, moved: false }), set: async () => {} } },+ ownHome: { owns: () => false, offers: () => false, start: async () => {}, active: () => false, away: () => false, refresh: () => {} },+ dismissed: memory(), awakeNow: async () => fresh, tell: () => {},+ });+ try {+ await main.refresh({ force: true });+ assert.deepEqual(asked, [], "the cached awake is not enough: nothing is asked");+ fresh = true;+ await main.refresh({ force: true });+ assert.deepEqual([...new Set(asked)], ["https://omb-u-1.fly.dev"]);+ } finally { main.close(); }+});+test("main's places: My Cloud only while the person keeps this computer's bots here, a server only when it says it is theirs alone; never a team's Cloud", async () => {const handlers = new Map(), asked = [];- let keep = { shown: true, on: true, moved: false }, offered = new Set(["garage"]), journal = null, active = false;+ let keep = { shown: true, on: true, moved: false }, offered = new Set(["garage"]), journal = null, active = false, together = false;const environments = [{ id: "garage", kind: "remote", name: "Garage server", origin: "https://garage.example.test" },{ id: "family", kind: "remote", name: "Family server", origin: "https://family.example.test" },@@ -112,9 +133,13 @@ test("main's places: My Cloud only while the person keeps this computer's bots honeHome: { journal: () => journal, keep: { state: () => keep, set: async (on) => { keep = { ...keep, on }; } } },ownHome: { owns: (place) => offered.has(place.id), offers: (place) => offered.has(place.id), start: async (id) => { active = true; asked.push(`start:${id}`); }, active: () => active,away: () => false, refresh: () => {} },- dismissed: memory(), tell: () => {},+ dismissed: memory(), together: () => together, tell: () => {},});try {+ together = true;+ await main.refresh({ force: true });+ assert.equal(main.state().suggest?.key, "server:https://garage.example.test", "with this computer and My Cloud together, their bots already work together: My Cloud is not suggested");+ together = false;await main.refresh({ force: true });assert.deepEqual(await handlers.get("two-places:state")({}), { suggest: { key: "cloud:https://omb-u-1.fly.dev", name: "My Cloud", kind: "cloud" } });assert.deepEqual([...new Set(asked)].sort(), ["https://garage.example.test", "https://omb-u-1.fly.dev"], "never the team's Cloud or a server others use");diff --git a/server/attach-file-hint.test.ts b/server/attach-file-hint.test.tsnew file mode 100644index 0000000000..69de81b9e1--- /dev/null+++ b/server/attach-file-hint.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from "vitest";++import { attachNotFound } from "./attach-file-hint.ts";++describe("attach_file's hint when no file is at the path", () => {+ it("names this turn's own working folder, never the Local VM's on a Mac", () => {+ expect(attachNotFound("/tmp/report.pdf", "/Users/sam/.openmausbot/task-workspaces/bot/thread")).toBe("No file was found at /tmp/report.pdf. Save it under /Users/sam/.openmausbot/task-workspaces/bot/thread (your working folder) and pass its exact path.");+ expect(attachNotFound("C:\\tmp\\a.pdf", "D:\\omb\\task-workspaces\\bot")).toContain("D:\\omb\\task-workspaces\\bot");+ expect(attachNotFound("/x", undefined)).toBe("No file was found at /x. Save it under your working folder and pass its exact path.");+ expect(attachNotFound("/x", "/Users/sam/w")).not.toContain("/home/cua");+ });++ it("the server builds it from the turn's own folders: the VM's workspace only for a turn on the Local VM", async () => {+ const { readFileSync } = await import("node:fs");+ const source = readFileSync(new URL("./index.ts", import.meta.url), "utf8");+ expect(source).not.toContain("Save it under /home/cua/workspace");+ expect(source).toMatch(/attachNotFound\(requestedPath, localVmThreadTargets\.has\(threadId\) \? VM_WORKSPACE_GUEST : messageFileRootsForThread\(from\.id, threadId\)\.find\(\(root\) => root !== ATTACHMENTS_DIR\)\)/u);+ });+});diff --git a/server/attach-file-hint.ts b/server/attach-file-hint.tsnew file mode 100644index 0000000000..14ed12505b--- /dev/null+++ b/server/attach-file-hint.ts@@ -0,0 +1,5 @@+// What attach_file says when the path it was given holds no file: where to save it instead, as this turn's own folders+// are (the Local VM's workspace inside the VM, else the bot's working folder on this machine), never another machine's.+export function attachNotFound(requested: string, folder: string | undefined): string {+ return `No file was found at ${requested}. Save it under ${folder ? `${folder} (your working folder)` : "your working folder"} and pass its exact path.`;+}diff --git a/server/bot-link/away.test.ts b/server/bot-link/away.test.tsnew file mode 100644index 0000000000..b9e9a2ae5a--- /dev/null+++ b/server/bot-link/away.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from "vitest";++import type { HandoffView } from "../coordinator.ts";+import { armBackground, BACKGROUND_WAIT_MS, backgroundWaitNote, cloudUnreachableTooLong, neverSent } from "./away.ts";++const node = (more: Partial<HandoffView> = {}): HandoffView => ({ id: "n", rootId: "r", threadId: "t", botId: "link-cloud-atlas", key: "k", text: "", createdAt: 0, status: "queued",+ result: "", reported: false, executions: 0, kind: "assignment", restarts: 0, mode: "work", reply: "resume", ...more } as HandoffView);++describe("work no person waits on, for a Cloud that cannot be reached", () => {+ it("waits up to the bound while the Cloud has not taken it, and its words hold for any reason the Cloud could not be reached", () => {+ expect(cloudUnreachableTooLong(node(), "My Cloud", true, BACKGROUND_WAIT_MS - 1)).toBeNull();+ expect(cloudUnreachableTooLong(node(), "My Cloud", true, BACKGROUND_WAIT_MS)).toBe("My Cloud could not be reached for 6 hours (asleep, off or not connected), so this was not sent there. Work no person waits on does not wake it.");+ expect(cloudUnreachableTooLong(node(), "My Cloud", false, BACKGROUND_WAIT_MS), "the Cloud took it: it is not given up here").toBeNull();+ expect(cloudUnreachableTooLong(node({ restart: "rerun", restarts: 1 }), "My Cloud", true, BACKGROUND_WAIT_MS)).toBeNull();+ expect(backgroundWaitNote("My Cloud")).not.toContain("delivered when it is back");+ expect(neverSent(node({ executions: 1 }))).toBe(false);+ });+});++describe("after an app restart", () => {+ it("waiting background work is looked at again when its wait is over, not at the next unrelated kick, once per node", async () => {+ const { vi } = await import("vitest");+ vi.useFakeTimers();+ try {+ const kicks: number[] = [];+ armBackground([{ id: "restart-a", createdAt: 1_000 }, { id: "restart-b", createdAt: 5_000 }], 3_000, 10_000, () => kicks.push(Date.now()));+ armBackground([{ id: "restart-a", createdAt: 1_000 }], 3_000, 10_000, () => kicks.push(-1));+ vi.advanceTimersByTime(8_000 + 49);+ expect(kicks).toHaveLength(0);+ vi.advanceTimersByTime(2);+ expect(kicks).toHaveLength(1);+ vi.advanceTimersByTime(4_000);+ expect(kicks).toHaveLength(2);+ expect(kicks).not.toContain(-1);+ } finally { vi.useRealTimers(); }+ const { readFileSync } = await import("node:fs");+ expect(readFileSync(new URL("./link.ts", import.meta.url), "utf8")).toMatch(/tidy\(\): void \{ prune\(\); expire\(\); sweep\(\); if \(state\?\.role === "dialer"\) armBackground\(/u);+ });+});diff --git a/server/bot-link/away.ts b/server/bot-link/away.tsnew file mode 100644index 0000000000..9ad7361a52--- /dev/null+++ b/server/bot-link/away.ts@@ -0,0 +1,35 @@+// How long work for the person's Cloud waits on a computer while that Cloud cannot be reached (server/bot-link/link.ts).+// Work no person waits on (a routine's, a scheduled run's) never wakes a sleeping Cloud (dial.ts): it waits until the+// Cloud is awake for another reason, at most BACKGROUND_WAIT_MS, and is given up then while still unsent. Work a person+// waits on is never given up here: it may wake the Cloud, and otherwise waits until it can.+import type { HandoffView } from "../coordinator.ts";++/** On a computer: work no person waits on waits this long for a Cloud that cannot be reached, then fails. */+export const BACKGROUND_WAIT_MS = 6 * 60 * 60_000;++/** Never sent to the other place: not yet run here, and not a rerun of one that ran before a restart. */+export const neverSent = (node: Pick<HandoffView, "status" | "executions" | "restart" | "restarts">): boolean =>+ node.status === "queued" && node.executions === 0 && node.restart === undefined && node.restarts === 0;++/** What a bot is told when work no person waits on goes to a Cloud that cannot be reached now. */+export const backgroundWaitNote = (place: string, waitMs = BACKGROUND_WAIT_MS): string =>+ `${place} can't be reached now (asleep, off or not connected), and work no person waits on does not wake it, so this waits until it can be reached for another reason, at most ${Math.round(waitMs / 3_600_000)} hours, and is not sent if it can't be by then`;++/** Why work no person waits on, for a Cloud that could not be reached, is given up, or null while it may still wait.+ * `unsent`: the Cloud has not taken it yet. */+export function cloudUnreachableTooLong(node: HandoffView, place: string, unsent: boolean, now: number, waitMs = BACKGROUND_WAIT_MS): string | null {+ if (!unsent || node.restart !== undefined || now - node.createdAt < waitMs) return null;+ return `${place} could not be reached for ${Math.round(waitMs / 3_600_000)} hours (asleep, off or not connected), so this was not sent there. Work no person waits on does not wake it.`;+}++const armed = new Set<string>();+/** After a restart, waiting work's give-up is looked at again when its wait is over, not at the next unrelated kick:+ * `kick` once at each node's deadline (once per node per run). */+export function armBackground(nodes: readonly Pick<HandoffView, "id" | "createdAt">[], now: number, waitMs: number, kick: () => void): void {+ for (const node of nodes) {+ if (armed.has(node.id)) continue;+ armed.add(node.id);+ const timer = setTimeout(kick, Math.max(0, node.createdAt + waitMs - now) + 50);+ timer.unref?.();+ }+}diff --git a/server/bot-link/dial.test.ts b/server/bot-link/dial.test.tsindex 8f44407989..97138302d3 100644--- a/server/bot-link/dial.test.ts+++ b/server/bot-link/dial.test.ts@@ -118,7 +118,7 @@ describe("bot-link exchange lifetime", () => {cleanups.push(() => dialer.close());dialer.start();await requested.promise;- await dialer[action]();+ await (action === "sleep" ? dialer.sleep(Date.now()) : dialer[action]());expect(transport.signals[0]!.aborted).toBe(true);expect(observed.receive).not.toHaveBeenCalled();expect(observed.setOnline).not.toHaveBeenCalledWith("cloud-peer", true);@@ -137,7 +137,7 @@ describe("bot-link exchange lifetime", () => {cleanups.push(() => dialer.close());dialer.start();await transport.reading;- await dialer[action]();+ await (action === "sleep" ? dialer.sleep(Date.now()) : dialer[action]());expect(transport.signals[0]!.aborted).toBe(true);expect(observed.receive).not.toHaveBeenCalled();expect(observed.setOnline).not.toHaveBeenCalledWith("cloud-peer", true);@@ -230,7 +230,7 @@ async function sleepyCloud(answer: (request: { background: boolean; wait: number}/** A computer's link whose Cloud sleeps: work can be wanted, and what the dialer says of waking is kept. */-function sleepyLink(origin: string) {+function sleepyLink(origin: string, { sleeps = true }: { sleeps?: boolean } = {}) {let wanted: (person: boolean) => void = () => {};const waking: boolean[] = [];const link = {@@ -243,7 +243,7 @@ function sleepyLink(origin: string) {setOnline: vi.fn(),setLevel: vi.fn(),setSleeps: vi.fn(),- sleeps: () => true,+ sleeps: () => sleeps,setWaking: (_peer: string, on: boolean) => { waking.push(on); },setTransfer: vi.fn(),onOutgoing: () => () => {},@@ -268,6 +268,37 @@ describe("a Cloud that sleeps", () => {expect(sleepy.seen).toEqual([]);});+ it("this server starting asks nothing of the Cloud, even one the link never saw asleep, until the app says it is awake", async () => {+ const sleepy = await sleepyCloud();+ const { link } = sleepyLink(sleepy.origin, { sleeps: false });+ const dialer = createDialer({ link, holdMs: 200, firstRetryMs: 1 });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ await settle();+ expect(dialer.state()).toMatchObject({ running: true, asleep: true });+ expect(sleepy.seen, "a stopped Cloud is not started by this server starting").toEqual([]);+ });++ it("an awake the app heard before the link parked starts nothing; one heard after it asks the Cloud once", async () => {+ let clock = 50_000;+ const sleepy = await sleepyCloud();+ const { link } = sleepyLink(sleepy.origin);+ const dialer = createDialer({ link, holdMs: 5_000, firstRetryMs: 1, now: () => clock });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ expect(dialer.state()).toMatchObject({ asleep: true, parkedAt: 50_000 });+ clock = 60_000;+ dialer.start({ heardAt: 20_000 });+ dialer.start({ heardAt: 50_000 });+ await settle();+ expect(sleepy.seen, "the Admin's awake from before the Cloud went to sleep is stale").toEqual([]);+ expect(dialer.state()).toMatchObject({ asleep: true });+ dialer.start({ heardAt: 60_000 });+ await sleepy.requests(1);+ expect(sleepy.seen[0], "the first ask since the park, as background work; the held poll that follows is the link's own").toEqual({ background: true, wait: 0 });+ expect(dialer.state()).toMatchObject({ asleep: false });+ });+it("work a person waits on wakes it with an exchange that is not background; the idle polls after it are background again", async () => {const sleepy = await sleepyCloud();const { link, observed, want, waking } = sleepyLink(sleepy.origin);@@ -281,6 +312,21 @@ describe("a Cloud that sleeps", () => {expect(observed.setOnline).toHaveBeenCalledWith("cloud-peer", true);});+ it("the Cloud's own asleep answer is kept for the app to hold, apart from a park the app asked for", async () => {+ let clock = 70_000;+ const sleepy = await sleepyCloud(() => "asleep");+ const { link } = sleepyLink(sleepy.origin);+ const dialer = createDialer({ link, firstRetryMs: 1, now: () => clock });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ expect(dialer.state()).not.toHaveProperty("cloudAsleepAt");+ clock = 80_000;+ dialer.start({ heardAt: 80_000 });+ await sleepy.requests(1);+ await settle();+ expect(dialer.state()).toMatchObject({ asleep: true, cloudAsleepAt: 80_000 });+ });+it("a Cloud that answers even that exchange with asleep parks the link once, with no second ask", async () => {const sleepy = await sleepyCloud(() => "asleep");const { link, want, waking } = sleepyLink(sleepy.origin);@@ -398,10 +444,10 @@ describe("a wake for work is bounded", () => {}await settle();expect(cloudSide.calls).toHaveLength(WAKES_PER_HOUR * WAKE_TRIES);- // A fourth in the same hour is no wake: it asks in the background as before, and the app's asleep parks it.+ // A fourth in the same hour is no wake: the link stays parked and asks nothing.want();- await vi.waitFor(() => expect(cloudSide.calls.length).toBeGreaterThan(WAKES_PER_HOUR * WAKE_TRIES));- dialer.sleep(clock.at);+ await settle();+ expect(cloudSide.calls).toHaveLength(WAKES_PER_HOUR * WAKE_TRIES);expect(dialer.state()).toMatchObject({ asleep: true });expect(foreground()).toBe(WAKES_PER_HOUR * WAKE_TRIES);// An hour on, work may wake it again.@@ -411,6 +457,31 @@ describe("a wake for work is bounded", () => {});}+ it("a person's work past the wakes an hour allows waits, says when it goes, and wakes the Cloud by itself once the hour has passed", async () => {+ const clock = { at: 1_000_000 };+ const cloudSide = unanswering("network", clock, 0);+ const { link, observed, want } = sleepyLink("https://cloud.invalid");+ const later = vi.fn();+ Object.assign(observed, { wakeLater: later, personWaiting: () => true });+ const dialer = createDialer({ link, fetch: cloudSide.fetch, firstRetryMs: 1, now: () => clock.at });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ const foreground = () => cloudSide.calls.filter((call) => call.foreground).length;+ for (let wake = 1; wake <= WAKES_PER_HOUR; wake += 1) {+ want();+ await vi.waitFor(() => expect(foreground()).toBe(wake * WAKE_TRIES), { timeout: 5_000 });+ await vi.waitFor(() => expect(dialer.state().asleep).toBe(true), { timeout: 5_000 });+ }+ clock.at += 60 * 60_000 - 200;+ want();+ await settle();+ expect(foreground(), "past the limit: nothing now").toBe(WAKES_PER_HOUR * WAKE_TRIES);+ expect(later).toHaveBeenLastCalledWith("cloud-peer", 1_200);+ clock.at += 1_000;+ await vi.waitFor(() => expect(foreground()).toBe((WAKES_PER_HOUR + 1) * WAKE_TRIES), { timeout: 5_000 });+ expect(later).toHaveBeenLastCalledWith("cloud-peer", 0);+ });+it("a wake that runs out of time parks, and the app's asleep is no longer put off", async () => {const clock = { at: 1_000_000 };const cloudSide = unanswering("network", clock, 0);@@ -428,18 +499,22 @@ describe("a wake for work is bounded", () => {expect(cloudSide.calls).toHaveLength(1);});- it("work no person waits on (a routine's) unparks with background asks, as before, and the app's asleep parks it", async () => {+ it("work no person waits on (a routine's) never wakes a parked link: nothing is asked until the app says the Cloud is awake", async () => {+ let clock = 5_000;const sleepy = await sleepyCloud(() => "asleep");const { link, want, waking } = sleepyLink(sleepy.origin);- const dialer = createDialer({ link });+ const dialer = createDialer({ link, now: () => clock });cleanups.push(() => dialer.close());dialer.start({ gentle: true });want(false);- await sleepy.requests(1);await settle();- expect(sleepy.seen).toEqual([{ background: true, wait: 0 }]);+ expect(sleepy.seen).toEqual([]);expect(waking).toEqual([]);expect(dialer.state()).toMatchObject({ asleep: true });+ clock = 6_000;+ dialer.start({ heardAt: 6_000 });+ await sleepy.requests(1);+ expect(sleepy.seen[0]).toEqual({ background: true, wait: 0 });});it("asked to sign in again while waking: the wake ends, and after pairing again the first ask is background", async () => {diff --git a/server/bot-link/dial.ts b/server/bot-link/dial.tsindex 6c424bbd2f..476922029a 100644--- a/server/bot-link/dial.ts+++ b/server/bot-link/dial.ts@@ -7,14 +7,21 @@// or the app says the Cloud is awake (`start`), since any request would start a sleeping Cloud; the app looks every// minute and never asks the Cloud itself to find out.//+// This server starting parks the link too, whatever it knew of the Cloud before: it asks nothing until the app says the+// Cloud is awake, and an "awake" the app heard before the link parked (`heardAt`) is stale and starts nothing, since the+// Admin's word lags the Cloud going to sleep and any request would start it again.+//// Work a person waits on (a hand-off or room turn from a person's own line: `onWanted(true)`) may wake a parked Cloud:// the exchanges that follow are not marked background until one is answered, so the Cloud counts them as use and answers// them even if it has not yet noticed it was woken. Such a wake is bounded: WAKE_TRIES exchanges within WAKE_MS, and-// WAKES_PER_HOUR wakes an hour; one that gets no answer parks the link again until new work or the app's "awake".-// Work no person waits on (a routine's, a scheduled run's) unparks the link with background exchanges, as before.-// Everything else (directory news, idle polls) stays background and is never sent while parked, so it never wakes the-// Cloud or keeps it awake. An answer to a foreground exchange is the Cloud's own word that it is awake: the app's-// "asleep" heard before it is stale and parks nothing; only one heard after it does.+// WAKES_PER_HOUR wakes an hour; past those the link stays parked and wakes it by itself once an hour has passed since the+// oldest (the bot is told when), and once a wake gets no answer it stays parked until new work or the app's "awake".+// Work no person waits on (a routine's, a scheduled run's) never wakes it: it waits, parked, until the Cloud is awake for+// another reason (the app's "awake"), and is given up after a while (away.ts). Everything else (directory news, idle+// polls) stays background and is never sent while parked, so it never wakes the Cloud or keeps it awake. An answer to a+// foreground exchange is the Cloud's own word that it is awake (`answeredAt`): the app's "asleep" heard before it is stale+// and parks nothing, and an "asleep" or "awake" that does not say when the app heard it changes nothing. (A background+// answer proves less: a Cloud the Admin is putting to sleep still answers until it stops, and the next poll would start it.)import { createWriteStream, openAsBlob, rmSync } from "node:fs";import { stat } from "node:fs/promises";import { Readable, Transform } from "node:stream";@@ -34,6 +41,7 @@ const FILE_MS = 10 * 60_000;* start), and this many wakes in any hour. */export const WAKE_MS = 150_000, WAKE_TRIES = 6, WAKES_PER_HOUR = 3;const HOUR_MS = 60 * 60_000;+export const WAKE_RECHECK_MS = 60_000;export interface DialerOptions {link: BotLink;@@ -44,15 +52,20 @@ export interface DialerOptions {/** What this computer says its version reads; a test stands in for an older app with it. */level?: number;now?: () => number;+ /** How often a person's work waiting for the hour's wakes to allow another looks again (WAKE_RECHECK_MS). */+ recheckMs?: number;}-export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, holdMs = HOLD_MS, firstRetryMs = FIRST_RETRY_MS, level = PROTOCOL_LEVEL, now = Date.now }: DialerOptions) {+export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, holdMs = HOLD_MS, firstRetryMs = FIRST_RETRY_MS, level = PROTOCOL_LEVEL, now = Date.now, recheckMs = WAKE_RECHECK_MS }: DialerOptions) {let running = false, stopped = true, asleep = false, needsPairing = false;/** `wake`: work a person waits on is waking the Cloud until `wakeUntil` or WAKE_TRIES exchanges (`wakeTries`), so* exchanges are not background until one is answered; `wakes`: when each wake of the last hour began. `provedAt`: when- * the Cloud last answered a foreground exchange (its own word that it is awake); `staleSaid`: the app's last "asleep"- * that was older, so it is logged once. */+ * the Cloud last answered a foreground exchange since the link last parked (its own word that it is awake); `staleSaid`: the+ * app's last "asleep" that was older, so it is logged once. */let wake = false, wakeUntil = 0, wakeTries = 0, provedAt = -Infinity, staleSaid: number | undefined | null = null;+ /** When the link last parked (this computer's clock): an app's "awake" heard before it is stale. `cloudAsleepAt`: when the+ * Cloud itself last answered that it sleeps, which the app holds as asleep (cloud-power.mjs `hold`), as Files and lending do. */+ let parkedAt = -Infinity, cloudAsleepAt = -Infinity;const wakes: number[] = [];let session = "", ack = 0, fresh = true, retryMs = firstRetryMs;let active: AbortController | null = null, held: AbortController | null = null;@@ -116,23 +129,46 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, h/** The wake had its time or its tries without an answer. */const wakeOver = () => wake && (now() >= wakeUntil || wakeTries >= WAKE_TRIES);const endWake = (peer: string | null) => { if (!wake) return; wake = false; if (peer) link.setWaking(peer, false); };- const stopWanted = link.onWanted((person) => {+ /** A person's work that found the wakes of the last hour used up: it is tried again by itself once the oldest is an hour old. */+ let wakeAgain: NodeJS.Timeout | null = null;+ const wanted = (person: boolean): void => {if (stopped) return;if (wake && !wakeOver()) { wakeUp?.(); return; }const peer = link.cloudPeer(), at = now();while (wakes.length && at - wakes[0]! >= HOUR_MS) wakes.shift();- if (person && asleep && peer && !needsPairing && link.dial() && wakes.length < WAKES_PER_HOUR) {- wakes.push(at);- wake = true; wakeUntil = at + WAKE_MS; wakeTries = 0;- link.setWaking(peer, true);+ if (person && asleep && peer && !needsPairing && link.dial()) {+ if (wakes.length < WAKES_PER_HOUR) {+ wakes.push(at);+ wake = true; wakeUntil = at + WAKE_MS; wakeTries = 0;+ link.wakeLater?.(peer, 0);+ link.setWaking(peer, true);+ } else if (!wakeAgain) waitForWake(peer, at);}+ // Background work, or a person's past the wakes an hour allows (tried again as above): a parked link stays parked; it+ // goes with the next "awake".+ if (asleep && !wake) return;asleep = false; retryMs = firstRetryMs;wakeUp?.();- });+ };+ /** The wakes of the last hour are used up: the bot is told when, and it is looked at again (at most every `recheckMs`,+ * so a clock that moves on is noticed) until a wake is allowed, while a person's work for the Cloud still waits. */+ function waitForWake(peer: string, at: number): void {+ const ms = wakes[0]! + HOUR_MS - at + 1_000;+ link.wakeLater?.(peer, ms);+ wakeAgain = setTimeout(() => {+ wakeAgain = null;+ if (stopped || !asleep || !link.personWaiting?.(peer)) { link.wakeLater?.(peer, 0); return; }+ const now2 = now();+ while (wakes.length && now2 - wakes[0]! >= HOUR_MS) wakes.shift();+ if (wakes.length < WAKES_PER_HOUR) wanted(true); else waitForWake(peer, now2);+ }, Math.min(ms, recheckMs));+ wakeAgain.unref?.();+ }+ const stopWanted = link.onWanted(wanted);/** The Cloud answered that it sleeps, the app's word parks the link, or a wake got no answer: nothing asks it until* there is new work for it or the app says it is awake. */const park = (peer: string | null) => {- asleep = true; fresh = true; provedAt = -Infinity;+ asleep = true; fresh = true; provedAt = -Infinity; parkedAt = now();endWake(peer);link.setSleeps(true);if (peer) link.setOnline(peer, false);@@ -162,6 +198,7 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, hif (response.status === 503 && response.headers.get(POWER_HEADER) === "asleep") {await response.body?.cancel();park(peer);+ cloudAsleepAt = parkedAt;return;}if (response.status === 401 || response.status === 403) {@@ -239,10 +276,16 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, hreturn {/** Starts asking, or asks again at once: after turning on, after pairing again, or when the app says the Cloud is- * awake. `gentle`: this server just started, so a Cloud that sleeps is left alone until the app says it is awake or- * there is work for it. */- start({ gentle = false }: { gentle?: boolean } = {}): void {- stopped = false; asleep = gentle && link.sleeps(); needsPairing = false; fresh = true; retryMs = firstRetryMs;+ * awake. `gentle`: this server just started, so the Cloud is left alone until the app says it is awake or there is+ * work for it (it may have gone to sleep, or stopped, since this server last asked). `heardAt`: when the app heard the+ * Admin say it is awake (this computer's clock); a word heard before the link parked starts nothing. */+ start({ gentle = false, heardAt }: { gentle?: boolean; heardAt?: number } = {}): void {+ if (!stopped && asleep && heardAt !== undefined && heardAt <= parkedAt) {+ log("bot link: the app says the Cloud is awake, but heard it before the Cloud went to sleep; the link stays parked");+ return;+ }+ stopped = false; asleep = gentle; needsPairing = false; fresh = true; retryMs = firstRetryMs;+ if (gentle) parkedAt = now();endWake(link.cloudPeer());wakeUp?.();void loop();@@ -252,6 +295,7 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, h* Cloud (within the wake's bounds), or when the Cloud has answered such work since: the Admin's word lags the Cloud's. */sleep(heardAt?: number): void {if (stopped) return;+ if (heardAt === undefined) { log("bot link: the app says the Cloud sleeps without saying when it heard it; the link is left as it is"); return; }if ((wake && !wakeOver()) || (heardAt !== undefined && heardAt <= provedAt)) {if (staleSaid !== heardAt) log(`bot link: the app says the Cloud sleeps, but it has answered since${wake ? " (waking it for work)" : ""}; the link stays up`);staleSaid = heardAt;@@ -275,7 +319,8 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, hfor (const ended of link.ended()) if (ended.origin === origin && await bye(ended)) told.push(ended.token);if (told.length) link.forgetEnded(told);},- state: () => ({ running: !stopped, asleep, needsPairing }),- close(): void { stopped = true; active?.abort(); wakeUp?.(); stopListening(); stopWanted(); link.setTransfer(null); },+ state: () => ({ running: !stopped, asleep, needsPairing, ...(asleep && Number.isFinite(parkedAt) ? { parkedAt } : {}), ...(Number.isFinite(cloudAsleepAt) ? { cloudAsleepAt } : {}),+ ...(Number.isFinite(provedAt) ? { answeredAt: provedAt } : {}) }),+ close(): void { stopped = true; if (wakeAgain) clearTimeout(wakeAgain); active?.abort(); wakeUp?.(); stopListening(); stopWanted(); link.setTransfer(null); },};}diff --git a/server/bot-link/link-state.ts b/server/bot-link/link-state.tsnew file mode 100644index 0000000000..74da4f235d--- /dev/null+++ b/server/bot-link/link-state.ts@@ -0,0 +1,42 @@+// What a link keeps on disk (server/bot-link/link.ts): its record, `bot-link.json`, and the links that ended while their+// Cloud could not be told, `bot-link-ended.json`.+import { z } from "zod";++import { linkedBotSchema, placeSchema } from "./protocol.ts";++export const workSchema = z.object({+ /** The place it came from: its result goes there and nowhere else. */+ peer: z.string(),+ root: z.string(), from: z.string(), person: z.string().optional(), at: z.number(),+ /** The assignment here that does the work; its words are read from the runtime's own row. */+ child: z.string().optional(),+ done: z.object({ ok: z.boolean(), outcome: z.string().optional(), /** Kept only when no assignment here ran. */ text: z.string().optional() }).optional(),+ /** When the requester said it has the result. */+ ackedAt: z.number().optional(),+});+export const peerSchema = z.object({+ place: placeSchema, bots: z.array(linkedBotSchema),+ /** On the Cloud: the one session that may use this computer's link. */+ sessionId: z.string().optional(),+ seenAt: z.number(),+});+export const stateSchema = z.object({+ v: z.literal(2),+ /** `dialer`: a computer, which asks. `acceptor`: the Cloud, which answers. */+ role: z.enum(["dialer", "acceptor"]),+ self: placeSchema,+ /** dialer: the Cloud's address, this link's sign-in there, and the account it was made for. */+ origin: z.string().optional(), token: z.string().optional(), account: z.string().optional(),+ /** dialer: the Cloud is on a plan that sleeps, so it is asked only when it is known awake or there is work for it. */+ sleeps: z.boolean().optional(),+ peers: z.record(z.string(), peerSchema),+ /** Another place's thread names, each with the thread here its work runs in. */+ threads: z.record(z.string(), z.object({ threadId: z.string(), at: z.number() })),+ /** Hand-offs taken from another place, by assignment id. */+ work: z.record(z.string(), workSchema),+});+export type LinkState = z.infer<typeof stateSchema>;+export type Work = z.infer<typeof workSchema>;+export const endedSchema = z.array(z.object({ origin: z.string(), token: z.string(), at: z.number() })).max(10);+/** A link that was turned off while its Cloud could not be told: the Cloud is told when it can next be reached. */+export type EndedLink = z.infer<typeof endedSchema>[number];diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.tsindex 97650df81e..2ce1a216e6 100644--- a/server/bot-link/link.test.ts+++ b/server/bot-link/link.test.ts@@ -15,7 +15,7 @@ import type { SessionRecord } from "../sessions.ts";import type { PassedFile } from "../host/handoff-files.ts";import { readBody } from "../harness/http.ts";import { removeTempDir } from "../testing/cleanup.ts";-import { createDialer } from "./dial.ts";+import { createDialer, WAKES_PER_HOUR } from "./dial.ts";import { createBotLink, SPOOL_KEEP_MS, type BotLink } from "./link.ts";import { createBotLinkRoutes as routesOf, linkSessionRefusal } from "../routes/bot-link.ts";import { createLinkedRooms, type LinkedRooms } from "../host/bot-link-rooms.ts";@@ -101,7 +101,7 @@ function place(label: string, bots: Bot[], version?: number) {const syncs: Array<{ background: boolean }> = [];const sockets = new Set<import("node:net").Socket>();- function boot(options: { limits?: { queueMs?: number; stallMs?: number }; tell?: { afterMs: number; withinMs: number } } = {}) {+ function boot(options: { limits?: { queueMs?: number; stallMs?: number }; tell?: { afterMs: number; withinMs: number }; backgroundWaitMs?: number } = {}) {rooms = createLinkedRooms({ dataDir: dir, store: roomStore as never, coordinator: () => coordinator, on: () => link.on(), linked: (peer) => link.has(peer), online: (peer) => link.online(peer), linkedBots: () => link.linked(), selfName: () => link.selfName(), wanted: (person) => link.wanted(person),window: (threadId, reader) => createRoomTranscript({ store: roomStore as never, teammateReportContext: () => "" }).window(threadId, "Sam", undefined, reader),opener: (botId, threadId) => (routineThreads.has(threadId) ? { requester: { kind: "routine_run", runId: "run-1", botId, threadId }, origin: { kind: "routine", source: "routine", ref: "routine-1" } } : undefined),@@ -109,7 +109,7 @@ function place(label: string, bots: Bot[], version?: number) {link = createBotLink({rooms, directoryChanged: () => { directoryChanges += 1; rooms.sync(); },dataDir: dir, coordinator: () => coordinator, bots: () => bots, bot: (id) => bots.find((bot) => bot.id === id), level: () => "full", paused: (bot) => Boolean((bot as Bot).paused), acceptRefusal: (bot) => (bot as Bot).farWorkRefused ?? null,- ...(options.tell ? { tellAfterMs: options.tell.afterMs, tellWithinMs: options.tell.withinMs } : {}),+ ...(options.tell ? { tellAfterMs: options.tell.afterMs, tellWithinMs: options.tell.withinMs } : {}), ...(options.backgroundWaitMs ? { backgroundWaitMs: options.backgroundWaitMs } : {}),openThread: (bot, title, opener, brief) => { const id = `${bot.id}-work-${++openedCount}`; threads.add(id); opened.push({ threadId: id, title, from: opener.name, brief }); return id; },hasThread: (_botId, threadId) => threads.has(threadId), personName: () => "Sam", handed: (input) => { if (handedFails.on) throw new Error("the line could not be written"); handed.push(input); },sentRow: (input) => { sent.push({ recipient: input.recipient.name, threadId: input.threadId, ...(input.roomId ? { roomId: input.roomId } : {}) }); },@@ -133,7 +133,7 @@ function place(label: string, bots: Bot[], version?: number) {},};coordinator = createCoordinator({ dataDir: dir, host: link.host(inner), log: () => {}, ...(options.limits ? { runtimeLimits: options.limits } : {}) });- dialer = createDialer({ link, holdMs: 400, firstRetryMs: 20, ...(version ? { level: version } : {}) });+ dialer = createDialer({ link, holdMs: 400, firstRetryMs: 20, now: () => Date.now() + skew, recheckMs: 50, ...(version ? { level: version } : {}) });ticker = setInterval(() => coordinator.tick(), 15);return api;}@@ -248,7 +248,7 @@ afterEach(async () => {});/** A computer and a Cloud. The same id, `shared`, is a different bot in each. */-async function two(options: { paired?: boolean; limits?: { queueMs?: number; stallMs?: number }; tell?: { afterMs: number; withinMs: number } } = {}) {+async function two(options: { paired?: boolean; limits?: { queueMs?: number; stallMs?: number }; tell?: { afterMs: number; withinMs: number }; backgroundWaitMs?: number } = {}) {const computer = place("computer", [{ id: "shared", name: "Scout" }, { id: "local-writer", name: "Writer" }]).boot(options);const cloud = place("cloud", [{ id: "shared", name: "Atlas" }, { id: "cloud-analyst", name: "Analyst" }]).boot(options);places.push(computer, cloud);@@ -596,6 +596,21 @@ describe("the link between a computer and its Cloud", () => {expect(cloudOrigin).toContain("127.0.0.1");});+ it("turned off mid-hand-off: the Cloud's work is stopped, and the asker is told so truthfully, with the bot's own name", async () => {+ const { computer, cloud } = await two();+ let stopped = false;+ cloud.engine((_node, _resumed, signal) => new Promise((resolve) => { signal.addEventListener("abort", () => { stopped = true; resolve({ ok: false, text: "stopped" }); }); }));+ await computer.handOff("local-writer", call(["Analyst"], "Count the orders"));+ await until(() => cloud.runs.length === 1, "the work starts on the Cloud");+ await computer.fetch("PUT", STATE_PATH, { on: false });+ await until(() => stopped, "the Cloud's turn is stopped, not left running with nowhere to send its result");+ await until(() => computer.results.length === 1, "the asker hears");+ const [row] = computer.results;+ expect(row!.name).toBe("Analyst (My Cloud)");+ expect(row!.result).not.toMatch(/not (delivered|sent)/);+ expect(row!.result).toContain("turned off");+ });+it("two computers on one Cloud: each has its own link, and work, results and stops go only to the computer they belong to", async () => {const { computer, cloud, cloudOrigin } = await two();const laptop = place("laptop", [{ id: "shared", name: "Scout" }, { id: "laptop-coder", name: "Coder" }]).boot();@@ -689,20 +704,31 @@ describe("the link between a computer and its Cloud", () => {expect(JSON.parse(readFileSync(join(computer.dir, "bot-link-ended.json"), "utf8"))).toHaveLength(1);await cloud.listen(at);expect(cloud.link.on()).toBe(true);- await computer.fetch("PUT", STATE_PATH, { cloud: "awake", origin: "https://another.example" });+ await computer.fetch("PUT", STATE_PATH, { cloud: "awake", origin: "https://another.example", heardAt: Date.now() });expect(cloud.link.on()).toBe(true);- await computer.fetch("PUT", STATE_PATH, { cloud: "awake", origin: cloudOrigin });+ await computer.fetch("PUT", STATE_PATH, { cloud: "awake", origin: cloudOrigin, heardAt: Date.now() });expect(cloud.link.on()).toBe(false);expect(cloud.sessions()).toEqual([]);expect(existsSync(join(computer.dir, "bot-link-ended.json"))).toBe(false);});+ it("an asleep or awake that does not say when the app heard it changes nothing: it neither parks the link nor asks the Cloud", async () => {+ const { computer, cloud, cloudOrigin } = await two();+ expect((await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin })).body).toMatchObject({ asleep: false, online: true });+ expect((await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin, heardAt: Date.now() })).body).toMatchObject({ asleep: true });+ const before = cloud.requests.length;+ await computer.fetch("PUT", STATE_PATH, { cloud: "awake", origin: cloudOrigin });+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(cloud.requests.length, "no request to a Cloud on an undated awake").toBe(before);+ expect((await computer.fetch("GET", STATE_PATH)).body).toMatchObject({ asleep: true });+ });+it("the app's word about one Cloud is not fed to a link to another", async () => {const { computer, cloudOrigin } = await two();- expect((await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: "https://another.example" })).body).toMatchObject({ asleep: false, online: true });- expect((await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin })).body).toMatchObject({ asleep: true, online: false });+ expect((await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: "https://another.example", heardAt: Date.now() })).body).toMatchObject({ asleep: false, online: true });+ expect((await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin, heardAt: Date.now() })).body).toMatchObject({ asleep: true, online: false });expect((await computer.fetch("GET", STATE_PATH)).body).toMatchObject({ origin: cloudOrigin, account: "account-1" });- await computer.fetch("PUT", STATE_PATH, { cloud: "awake", origin: cloudOrigin });+ await computer.fetch("PUT", STATE_PATH, { cloud: "awake", origin: cloudOrigin, heardAt: Date.now() });await until(() => computer.link.online(), "the link is back");});@@ -1393,7 +1419,7 @@ describe("the link between a computer and its Cloud", () => {await cloud.listen(at);expect(cloud.link.linked().length).toBeGreaterThan(0);// The app says that Cloud is awake: it is told, and the computer's bots go there at once.- await computer.fetch("PUT", STATE_PATH, { cloud: "awake", origin: cloudOrigin });+ await computer.fetch("PUT", STATE_PATH, { cloud: "awake", origin: cloudOrigin, heardAt: Date.now() });expect(cloud.link.linked()).toEqual([]);expect(cloud.link.on()).toBe(false);expect(existsSync(join(computer.dir, "bot-link-ended.json"))).toBe(false);@@ -1401,7 +1427,7 @@ describe("the link between a computer and its Cloud", () => {it("turned off while the Cloud sleeps: the sleeping Cloud is not asked, and turning the link on again there ends the earlier one", async () => {const { computer, cloud, cloudOrigin } = await two();- await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin });+ await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin, heardAt: Date.now() });const before = cloud.requests.length;expect((await computer.fetch("PUT", STATE_PATH, { on: false })).body).toEqual({ on: false, ended: [cloudOrigin] });expect(cloud.requests.length).toBe(before);@@ -1499,15 +1525,85 @@ describe("a Cloud that sleeps", () => {const before = cloud.syncs.length;home.jump(12_000);const { receipts } = await computer.handOff("local-writer", call(["Analyst"], "Count the orders"), undefined, undefined, true);- expect(receipts[0]!.detail).toContain("My Cloud is offline now");+ expect(receipts[0]!.detail, "never promised as delivered when it is back: it may be given up").toContain("My Cloud can't be reached now (asleep, off or not connected), and work no person waits on does not wake it, so this waits until it can be reached for another reason, at most 6 hours, and is not sent if it can't be by then");expect(receipts[0]!.detail).not.toContain("waking");- // As before this change: one background exchange, which a Cloud that sleeps answers with asleep, and the link parks again.- await until(() => cloud.syncs.length > before && computer.dialer.state().asleep, "the link asks once and parks again");- expect(cloud.syncs.slice(before).every((one) => one.background)).toBe(true);+ // Work no person waits on never wakes it: not one exchange while it sleeps.+ await new Promise((resolve) => setTimeout(resolve, 500));+ expect(cloud.syncs.length).toBe(before);+ expect(computer.dialer.state().asleep).toBe(true);expect(home.power.sleeping()).toBe(true);expect(computer.results).toEqual([]);});+ it("a person's hand-off while the Cloud was already woken as often as an hour allows is told when it goes by itself", async () => {+ const { computer, cloud } = await two();+ await computer.dialer.stop();+ computer.link.setOnline(CLOUD, false);+ computer.link.wakeLater(CLOUD, 10 * 60_000);+ const { receipts } = await computer.handOff("local-writer", call(["Analyst"], "Count the orders"));+ expect(receipts[0]!.detail).toContain("My Cloud was woken for work several times in the last hour already, so this waits and is sent by itself when it may be woken again, in about 10 minutes");+ computer.link.wakeLater(CLOUD, 0);+ expect(cloud.runs).toEqual([]);+ });++ it("a person's hand-off past the hour's wakes is told the wait, wakes nothing now, and goes by itself once the oldest wake is an hour old, using one wake", async () => {+ const { computer, cloud, cloudOrigin } = await two();+ /** The app's word that the Cloud sleeps, heard after its last answer: the computer's end parks. */+ const park = async () => {+ // Said again until it holds: a word heard before the Cloud's last answer to a person's work parks nothing.+ await until(() => computer.dialer.state().asleep || (void computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin, heardAt: Date.now() + 60 * 60_000 * (parkedLater ? 1 : 0) }), false), "the computer's end parks");+ };+ let parkedLater = false;+ for (let wake = 1; wake <= WAKES_PER_HOUR; wake += 1) {+ await park();+ const { receipts } = await computer.handOff("local-writer", call(["Analyst"], `Job ${wake}`));+ expect(receipts[0]!.detail, `wake ${wake}`).toContain("waking up for this now");+ await until(() => computer.results.length === wake, `the result of job ${wake}`);+ }+ await park();+ const before = cloud.syncs.length;+ const { receipts } = await computer.handOff("local-writer", call(["Analyst"], "Job 4"));+ expect(receipts[0]!.detail).toContain("was woken for work several times in the last hour already, so this waits and is sent by itself");+ await new Promise((resolve) => setTimeout(resolve, 400));+ expect(cloud.syncs.length, "nothing wakes it now").toBe(before);+ computer.later(60 * 60_000);+ parkedLater = true;+ await until(() => computer.results.length === WAKES_PER_HOUR + 1, "it goes by itself once the oldest wake is an hour old");+ expect(cloud.syncs.slice(before).some((one) => !one.background), "as a wake, a person's").toBe(true);+ await park();+ const settled = cloud.syncs.length;+ await new Promise((resolve) => setTimeout(resolve, 400));+ expect(cloud.syncs.length, "nothing waits, so nothing more is sent: no loop").toBe(settled);+ });++ it("the only computer linked to the Cloud expires after thirty days: as before, no work there is cancelled with words of a turn-off", async () => {+ const { computer, cloud } = await two();+ cloud.engine(() => new Promise(() => {}));+ await computer.handOff("local-writer", call(["Analyst"], "Count the orders"));+ await until(() => cloud.runs.length === 1, "the Cloud runs it");+ const reasons: string[] = [];+ const original = cloud.coordinator.cancelDirect.bind(cloud.coordinator);+ cloud.coordinator.cancelDirect = ((root: string, why?: string) => { reasons.push(why ?? ""); return original(root, why); }) as typeof cloud.coordinator.cancelDirect;+ await computer.dialer.stop();+ await until(() => !cloud.link.online(), "the computer goes quiet");+ cloud.later(LINK_EXPIRES_MS + 60_000);+ cloud.link.tidy();+ expect(cloud.link.on()).toBe(false);+ expect(reasons).toEqual([]);+ });++ it("a routine's hand-off to a sleeping Cloud waits for it to be awake for another reason, and is given up with a plain line after the bound, never sent", async () => {+ const { computer, cloud, cloudOrigin } = await two({ backgroundWaitMs: 600 });+ const home = sleepyHome(cloud);+ await asleep(computer, cloudOrigin, home);+ const before = cloud.syncs.length;+ await computer.handOff("local-writer", call(["Analyst"], "Count the orders"), undefined, undefined, true);+ await until(() => computer.results.length === 1, "given up after the bound");+ expect(computer.results[0]!.result).toContain("could not be reached for");+ expect(cloud.syncs.length, "nothing was ever sent to the sleeping Cloud").toBe(before);+ expect(cloud.runs).toEqual([]);+ });+it("background link traffic never wakes a sleeping Cloud or keeps one awake", async () => {const { computer, cloud, cloudOrigin } = await two();const home = sleepyHome(cloud);diff --git a/server/bot-link/link.ts b/server/bot-link/link.tsindex 1e1dd9b2f9..582e38fd48 100644--- a/server/bot-link/link.ts+++ b/server/bot-link/link.ts@@ -23,7 +23,6 @@import { createHash } from "node:crypto";import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";import { basename, join } from "node:path";-import { z } from "zod";import { writeFileAtomic } from "../atomic.ts";import type { CoordinateBotsCall, Coordinator, CoordinatorHost, HandoffView, HostTurnResult } from "../coordinator.ts";@@ -31,7 +30,9 @@ import type { PassedFile } from "../host/handoff-files.ts";import { foldName, withTargetsHere, type CoordinateResult, type PeerDeliveryReceipt } from "../peer-delivery.ts";import { isIdStart } from "../peer-roster.ts";import type { Level } from "../runtime/types.ts";-import { BRIEF_MAX, EXCHANGE_BYTES, FILES_MAX, LINK_EXPIRES_MS, PEERS_MAX, frameSchema, handoffOfRoot, isLinkedId, linkRoot, linkedBotSchema, linkedId, parseLinked, peerKey, placeSchema,+import { armBackground, BACKGROUND_WAIT_MS, backgroundWaitNote, cloudUnreachableTooLong, neverSent } from "./away.ts";+import { endedSchema, stateSchema, type EndedLink, type LinkState, type Work } from "./link-state.ts";+import { BRIEF_MAX, EXCHANGE_BYTES, FILES_MAX, LINK_EXPIRES_MS, PEERS_MAX, frameSchema, handoffOfRoot, isLinkedId, linkRoot, linkedId, parseLinked, peerKey,type FileMeta, type FileWay, type Frame, type HandoffFrame, type LinkedBot, type Numbered, type Place, type ResultFrame } from "./protocol.ts";const FILE = "bot-link.json";@@ -49,6 +50,7 @@ const ALIVE_EVERY_MS = 60_000;/** How often a place's last contact is written down. */const SEEN_WRITE_MS = 60 * 60_000;const STOPPED = "Coordinated work was stopped";+const OFF_STOP = "The link to the person's other place was turned off, so this work was stopped.";const SPOOL = "bot-link-files";/** Bytes that crossed and were never stored (their hand-off was dropped, a side restarted) are removed after this long,* and the oldest go first when all of them together pass the size. */@@ -78,42 +80,7 @@ const said = (error: unknown) => (error instanceof Error ? error.message : Strinconst metaOf = (files: readonly PassedFile[]): FileMeta[] => files.slice(0, FILES_MAX).map(({ name, mime, kind, bytes }) => ({ name: name.slice(0, 255), mime: mime.slice(0, 200), kind, bytes }));const GONE = "The result is no longer kept.";-const workSchema = z.object({- /** The place it came from: its result goes there and nowhere else. */- peer: z.string(),- root: z.string(), from: z.string(), person: z.string().optional(), at: z.number(),- /** The assignment here that does the work; its words are read from the runtime's own row. */- child: z.string().optional(),- done: z.object({ ok: z.boolean(), outcome: z.string().optional(), /** Kept only when no assignment here ran. */ text: z.string().optional() }).optional(),- /** When the requester said it has the result. */- ackedAt: z.number().optional(),-});-const peerSchema = z.object({- place: placeSchema, bots: z.array(linkedBotSchema),- /** On the Cloud: the one session that may use this computer's link. */- sessionId: z.string().optional(),- seenAt: z.number(),-});-const stateSchema = z.object({- v: z.literal(2),- /** `dialer`: a computer, which asks. `acceptor`: the Cloud, which answers. */- role: z.enum(["dialer", "acceptor"]),- self: placeSchema,- /** dialer: the Cloud's address, this link's sign-in there, and the account it was made for. */- origin: z.string().optional(), token: z.string().optional(), account: z.string().optional(),- /** dialer: the Cloud is on a plan that sleeps, so it is asked only when it is known awake or there is work for it. */- sleeps: z.boolean().optional(),- peers: z.record(z.string(), peerSchema),- /** Another place's thread names, each with the thread here its work runs in. */- threads: z.record(z.string(), z.object({ threadId: z.string(), at: z.number() })),- /** Hand-offs taken from another place, by assignment id. */- work: z.record(z.string(), workSchema),-});-export type LinkState = z.infer<typeof stateSchema>;-type Work = z.infer<typeof workSchema>;-const endedSchema = z.array(z.object({ origin: z.string(), token: z.string(), at: z.number() })).max(10);-/** A link that was turned off while its Cloud could not be told: the Cloud is told when it can next be reached. */-export type EndedLink = z.infer<typeof endedSchema>[number];+export type { EndedLink, LinkState } from "./link-state.ts";interface LocalBot { id: string; name: string; color?: string; hidden?: boolean; title?: string; description?: string; movedTo?: unknown;mascotBody?: string | null; mascotFaceColor?: string | null; mascotBodyColor?: string | null; mascotMaterial?: string | null; chiefOfStaff?: boolean; threadId?: string }@@ -172,6 +139,8 @@ export interface BotLinkDeps {/** On the Cloud: ends the session a computer's link used. */revoke?(sessionId: string): void;now?: () => number;+ /** On a computer: how long work no person waits on waits for a Cloud that cannot be reached (away.ts). */+ backgroundWaitMs?: number;log?(line: string): void;/** How long after the last change to this place's bots the other places are told (TELL_AFTER_MS), and the longest a* change waits while more keep coming (TELL_WITHIN_MS). */@@ -201,6 +170,9 @@ export type BotLink = ReturnType<typeof createBotLink>;export function createBotLink(deps: BotLinkDeps) {const now = deps.now ?? Date.now;+ const backgroundWait = deps.backgroundWaitMs ?? BACKGROUND_WAIT_MS;+ /** A computer's own word, from its dialer, that the Cloud was woken too often this hour for work a person waits on: until when. */+ const wakeLater = new Map<string, number>();const log = deps.log ?? (() => {});const file = join(deps.dataDir, FILE), endedFile = join(deps.dataDir, ENDED_FILE);let state: LinkState | null = null;@@ -216,6 +188,9 @@ export function createBotLink(deps: BotLinkDeps) {/** Hand-offs this side sent whose result has not come back. */type Pending = { peer: string; frame: HandoffFrame; files: readonly PassedFile[]; settle(result: HostTurnResult): void; threadId: string; cancelled: boolean; busy?: boolean; tries: number };const pending = new Map<string, Pending>();+ /** What each bot of another place was called when work went to it: kept so a hand-off that ends after the link went+ * still names its bot. */+ const namedHere = new Map<string, string>();/** Hand-offs whose result came: the rest that end here (cut by restarts, refused, stopped) are stopped where they run. */const resulted = new Set<string>();let alive: NodeJS.Timeout | undefined;@@ -350,6 +325,8 @@ export function createBotLink(deps: BotLinkDeps) {deps.kick();}+ /** A far bot's name and place, as the last time it was known (`namedHere`), so work that ends after its link went names it. */+ const farName = (linked: string) => { const remote = remoteOf(linked); if (remote) namedHere.set(linked, `${remote.bot.name} (${placeName(remote.peer)})`); return namedHere.get(linked) ?? "Teammate"; };const remoteOf = (linked: string): Remote | undefined => {const address = parseLinked(linked), bot = address ? state?.peers[address.peer]?.bots.find((one) => one.id === address.botId) : undefined;return address && bot ? { peer: address.peer, bot } : undefined;@@ -385,7 +362,11 @@ export function createBotLink(deps: BotLinkDeps) {return `${matches.length} bots of the person's other places are named "${raw.trim().slice(0, 120)}", so nothing was sent: ${listed}${matches.length > 12 ? `; and ${matches.length - 12} more` : ""}. Send it again with the id of the one you mean.`;}- const offlineNote = (peer: string) => waking.has(peer) ? wakingNote(peer) : `${placeName(peer)} is offline now (off, asleep or not connected), so this waits and is delivered when it is back`;+ /** `person`: work a person waits on (it may wake a sleeping Cloud); other work never wakes it, and may be given up. */+ const offlineNote = (peer: string, person = true) => waking.has(peer) ? wakingNote(peer)+ : state?.role === "dialer" && !person ? backgroundWaitNote(placeName(peer), backgroundWait)+ : state?.role === "dialer" && (wakeLater.get(peer) ?? 0) > now() ? `${placeName(peer)} was woken for work several times in the last hour already, so this waits and is sent by itself when it may be woken again, in about ${Math.max(1, Math.ceil(((wakeLater.get(peer) ?? 0) - now()) / 60_000))} minutes, or sooner if it wakes`+ : `${placeName(peer)} is offline now (off, asleep or not connected), so this waits and is delivered when it is back`;const wakingNote = (peer: string) => `${placeName(peer)} was asleep and is waking up for this now, so this is delivered as soon as it answers`;function keepAlive(): void {@@ -399,6 +380,7 @@ export function createBotLink(deps: BotLinkDeps) {function runRemote(node: HandoffView, signal: AbortSignal): Promise<HostTurnResult> {const coordinator = deps.coordinator();const address = parseLinked(node.botId)!;+ farName(node.botId);const parent = node.parentId ? coordinator.node(node.parentId) : undefined;const sender = parent ? deps.bot(parent.botId) : undefined;const record = coordinator.status(node.id)?.assignment;@@ -603,7 +585,7 @@ export function createBotLink(deps: BotLinkDeps) {deps.coordinator().cancelDirect(work.root, `Stopped by ${work.from || "the requester"}`);return;}- case "bye": return state.role === "acceptor" ? dropPeer(peer, `The link to ${placeName(peer)} was turned off before the work came back.`) : off(true);+ case "bye": return state.role === "acceptor" ? dropPeer(peer, `The link to ${placeName(peer)} was turned off before the work came back.`, `The link to ${placeName(peer)} was turned off, so this work was stopped.`) : off(true, OFF_STOP);}}@@ -636,6 +618,14 @@ export function createBotLink(deps: BotLinkDeps) {}}+ /** Work this place runs for `peer` (or for every place) that has not ended is stopped: its result has nowhere to go. */+ function stopWorkFor(peer: string | null, reason: string): void {+ if (!state) return;+ for (const work of Object.values(state.work)) {+ if (work.done || (peer !== null && work.peer !== peer)) continue;+ try { deps.coordinator().cancelDirect(work.root, reason); } catch (error) { log(`bot link: work for ${work.peer} not stopped (${String(error)})`); }+ }+ }function failPending(peer: string | null, reason: string): void {for (const [id, entry] of pending) {if (peer !== null && entry.peer !== peer) continue;@@ -648,14 +638,16 @@ export function createBotLink(deps: BotLinkDeps) {}/** On the Cloud: one computer's link ends. Its session is revoked and work waiting for it ends with the reason. */- function dropPeer(peer: string, reason: string): void {+ /** `stopped`: the link was turned off, so the work this place runs for that computer stops, with these words. */+ function dropPeer(peer: string, reason: string, stopped?: string): void {const known = state?.peers[peer];if (!state || !known) return;+ if (stopped) stopWorkFor(peer, stopped);delete state.peers[peer];live.delete(peer);if (known.sessionId) deps.revoke?.(known.sessionId);failPending(peer, reason);- if (Object.keys(state.peers).length === 0) { off(true); return; }+ if (Object.keys(state.peers).length === 0) { off(true, stopped); return; }save();deps.directoryChanged?.();for (const listener of outboundListeners) listener(peer);@@ -672,8 +664,10 @@ export function createBotLink(deps: BotLinkDeps) {/** The link is off here: nothing more is sent, and work waiting on another place ends with the reason. `told`: the other* side knows. A computer whose Cloud could not be told keeps what it takes to tell it later. */- function off(told: boolean): void {+ function off(told: boolean, stopped?: string): void {if (!state) return;+ // Only a real turn-off (the person's switch, the other side's goodbye) stops what runs here for the other place.+ if (stopped) stopWorkFor(null, stopped);const was = state;state = null;clearTimeout(telling);@@ -727,10 +721,12 @@ export function createBotLink(deps: BotLinkDeps) {// work a person's own line started may wake it; a routine's or a scheduled run's waits as before.const person = coordinator.status(node.id)?.assignment?.origin?.kind === "person";if (!online) for (const listener of wantedListeners) listener(person);+ // On a computer, work no person waits on is looked at again once its wait is over (host.validate, away.ts).+ if (!online && state?.role === "dialer" && !person) { const later = setTimeout(() => deps.kick(), backgroundWait + 50); later.unref?.(); }const told = !online && waking.has(remote.peer) ? `Finish your turn and tell the person ${place} is waking up for it.` : `Finish your turn and tell the person it waits for ${place}.`;receipts.push(receipt(remote, duplicate && node.status !== "queued" ? "injected" : "queued",duplicate ? `already sent to ${remote.bot.name} on ${place}: it is ${node.status === "queued" ? "queued" : "under way"} and ${returns}`- : online ? `sent to ${remote.bot.name} on ${place}; ${returns}.${files}` : `${offlineNote(remote.peer)}; ${returns} then. ${told}${files}`,+ : online ? `sent to ${remote.bot.name} on ${place}; ${returns}.${files}` : `${offlineNote(remote.peer, person)}; ${returns} then. ${told}${files}`,{ requestId: node.id }));if (!duplicate) {context.handed(node.id);@@ -754,26 +750,43 @@ export function createBotLink(deps: BotLinkDeps) {: call.answers || call.post || call.ownThread ? `That does not reach ${place} yet: send the bot plain work or a question instead`: call.consult && call.reply === "none" ? "consult asks a question whose answer comes back to you; leave reply out" : null;}+ /** On a computer: work no person waits on, for a Cloud that cannot be reached now, that waits no longer (away.ts): why, or+ * undefined. Only work the Cloud never took is given up, so nothing is stopped there for it. On the Cloud nothing is. */+ function givenUp(node: HandoffView, peer: string): string | undefined {+ if (state?.role !== "dialer" || deps.coordinator().status(node.id)?.assignment?.origin?.kind === "person") return undefined;+ const one = live.get(peer), queued = one?.outbox.some((entry) => entry.frame.t === "handoff" && entry.frame.id === node.id) === true;+ const said = cloudUnreachableTooLong(node, placeName(peer), neverSent(node) || queued, now(), backgroundWait);+ if (!said) return undefined;+ if (one && queued) one.outbox = one.outbox.filter((entry) => !(entry.frame.t === "handoff" && entry.frame.id === node.id));+ const entry = pending.get(node.id);+ if (entry) { entry.cancelled = true; pending.delete(node.id); keepAlive(); entry.settle({ ok: false, text: said }); }+ resulted.add(node.id);+ return said;+ }/** The coordinator's host with other places' bots in it: their nodes run there, every other node as before. */function host(inner: CoordinatorHost): CoordinatorHost {const awayNode = (node: HandoffView) => isLinkedId(node.botId);const peerOf = (node: HandoffView) => parseLinked(node.botId)?.peer ?? "";const workOf = (parent: HandoffView | undefined) => (parent && awayNode(parent) ? state?.work[handoffOfRoot(parent.id)] : undefined);- const nameOf = (linked: string) => { const remote = remoteOf(linked); return remote ? `${remote.bot.name} (${placeName(remote.peer)})` : "Teammate"; };+ const nameOf = farName;return {...inner,validate: (node, parent) => {if (!awayNode(node)) return inner.validate(node, parent && awayNode(parent) ? undefined : parent);if (!node.parentId) return undefined;- if (!state) return "The link to the person's other place was turned off, so this was not delivered.";+ // Never "not delivered" for work that went: it was, and the link going stops it there.+ if (!state) return node.status === "queued" ? "The link to the person's other place was turned off, so this was not sent."+ : `The link to the person's other place was turned off while ${nameOf(node.botId)} worked on this, so its result will not come back.`;const left = deps.rooms?.problem(node);if (left) return left;- return remoteOf(node.botId) ? undefined : "That bot's place is no longer linked, or the bot is no longer there.";+ if (!remoteOf(node.botId)) return "That bot's place is no longer linked, or the bot is no longer there.";+ const peer = peerOf(node);+ return isOnline(peer) ? undefined : givenUp(node, peer);},// A node that only stands for who asked (a room, another place's requester) has no parent and runs nothing: it is// never busy, so it ends as soon as the work under it has ended, whether or not any place is connected.busy: (node) => (awayNode(node) ? Boolean(node.parentId) && !isOnline(peerOf(node)) : inner.busy(node)),- holdReason: (node) => (awayNode(node) ? offlineNote(peerOf(node)) : inner.holdReason?.(node) as string),+ holdReason: (node) => (awayNode(node) ? offlineNote(peerOf(node), deps.coordinator().status(node.id)?.assignment?.origin?.kind === "person") : inner.holdReason?.(node) as string),// Work for a place that cannot be reached, waiting to go or already running there, is held by no clock.away: (node) => (awayNode(node) ? Boolean(state) && Boolean(node.parentId) && !isOnline(peerOf(node)) : inner.away?.(node) ?? false),run: (node, resumed, signal, composed) => {@@ -849,6 +862,8 @@ export function createBotLink(deps: BotLinkDeps) {const listed = far.slice(0, 12).map(({ peer, bot }) => `${bot.name} on ${placeName(peer)} (id ${linkedId(peer, bot.id)})`).join(", ");return `Through the link to ${places} you can also reach: ${listed}${far.length > 12 ? `, and ${far.length - 12} more` : ""}.`;},+ /** On a computer: the Cloud was woken for work a person waits on as often as an hour allows; it is woken again by itself in `ms`. */+ wakeLater(peer: string, ms: number): void { if (ms > 0) wakeLater.set(peer, now() + ms); else wakeLater.delete(peer); },/** Other places' bots as list_bots names them. */agents: () => Object.entries(state?.peers ?? {}).flatMap(([peer, known]) => known.bots.map((bot) => ({ id: linkedId(peer, bot.id), name: bot.name, section: "", model: bot.model ?? "", busy: false,status: isOnline(peer) ? "linked" : "offline", statusText: isOnline(peer) ? `on ${known.place.name}` : waking.has(peer) ? `on ${known.place.name}, waking up now: work for it is delivered as soon as it answers` : `on ${known.place.name}, offline now: work for it waits until it is back`,@@ -882,10 +897,10 @@ export function createBotLink(deps: BotLinkDeps) {unpair(computerId?: string): void {if (state?.role !== "acceptor") return;const reason = "The link to that computer was turned off before the work came back.";- for (const peer of computerId === undefined ? Object.keys(state.peers) : [peerKey(computerId)]) dropPeer(peer, reason);+ for (const peer of computerId === undefined ? Object.keys(state.peers) : [peerKey(computerId)]) dropPeer(peer, reason, `The link to ${placeName(peer)} was turned off, so this work was stopped.`);},/** Turned off on a computer. `told`: its Cloud knows; otherwise the Cloud is told when it can next be reached. */- turnOff(told: boolean): void { off(told); },+ turnOff(told: boolean): void { off(told, OFF_STOP); },ended: readEnded,/** These ended links' Clouds know now. */forgetEnded(tokens: readonly string[]): void { writeEnded(readEnded().filter((one) => !tokens.includes(one.token))); },@@ -899,7 +914,7 @@ export function createBotLink(deps: BotLinkDeps) {for (const [id, work] of Object.entries(state.work)) if (work.peer === peer && work.done && work.ackedAt === undefined) dispatchResult(id);},/** Housekeeping, at start and once a day: old records go, and on the Cloud a computer long gone is unlinked. */- tidy(): void { prune(); expire(); sweep(); },+ tidy(): void { prune(); expire(); sweep(); if (state?.role === "dialer") armBackground(deps.coordinator().active().filter((node) => isLinkedId(node.botId) && node.parentId), now(), backgroundWait, deps.kick); },/** This place's bots changed (one was made, renamed, hidden, moved, deleted, paused, its look, model or level changed):* once changes settle (or every TELL_WITHIN_MS while they do not), the other places hear the new list, and nothing when* what they are told did not change. */@@ -966,6 +981,8 @@ export function createBotLink(deps: BotLinkDeps) {return taken;},hasOutgoing: (peer: string, ack = 0) => live.get(peer)?.outbox.some((entry) => entry.seq > ack) === true,+ /** Work a person waits on, for `peer`, that has not ended (held while the link is parked, so not in the outbox). */+ personWaiting: (peer: string) => deps.coordinator().active().some((node) => parseLinked(node.botId)?.peer === peer && Boolean(node.parentId) && deps.coordinator().status(node.id)?.assignment?.origin?.kind === "person"),onOutgoing(listener: (peer: string) => void): () => void { outboundListeners.add(listener); return () => outboundListeners.delete(listener); },/** Work was handed to a place that is not connected: a computer asks its Cloud for it now. *//** There is work for a place that is not connected, handed over outside `coordinate` (a room turn). */diff --git a/server/host/linked-roster.test.ts b/server/host/linked-roster.test.tsindex 40e1f311fa..756ed7f1a0 100644--- a/server/host/linked-roster.test.ts+++ b/server/host/linked-roster.test.ts@@ -137,6 +137,26 @@ describe("the other place's bots in a bot's team prompts", () => {}});+ it("past the cap, the Cloud Chief's roster keeps the bots of the computer in use over those of one that never came back, as list_bots lists both", () => {+ const gone = Array.from({ length: 13 }, (_, index) => ({ ...mac({ id: `old${index}`, name: `Old ${index}`, title: "Helper" }, MAC, "Sam's Mac"), online: false }));+ const inUse = [mac({ id: "writer", name: "Writer", title: "Writer" }, MAC2, "Sam's Mac"), mac({ id: "waiter", name: "Waiter", title: "Helper" }, MAC2, "Sam's Mac")];+ const roster = createLinkedRoster({ link: onCloud([...gone, ...inUse]), bots: () => local });+ const text = roster.forChief(chief, true)!.roster;+ expect(text).toContain("- Writer — Writer");+ expect(text).toContain("- Waiter — Helper");+ expect(text).toMatch(/- …and \d+ more there: list_bots shows them\./u);+ });++ it("the Chief's roster is the same text whatever order a place lists its bots in, and changes only when the reachable places do", () => {+ const listed = [mac({ id: "w", name: "Writer" }), mac({ id: "a", name: "Atlas" }), mac({ id: "m", name: "Mover" })];+ const text = (rows: LinkedRow[]) => createLinkedRoster({ link: onCloud(rows), bots: () => local }).forChief(chief, true)!.roster;+ const once = text(listed);+ expect(text([...listed].reverse())).toBe(once);+ expect(once.indexOf("- Atlas")).toBeLessThan(once.indexOf("- Mover"));+ const quiet = [{ ...listed[0]!, online: false }, listed[1]!, listed[2]!];+ expect(text(quiet).indexOf("- Writer"), "a place that went quiet moves after the reachable ones").toBeGreaterThan(text(quiet).indexOf("- Mover"));+ });+it("a bot shared with only some people is told of no far bot, as it is told of no local bot everyone shares", () => {const roster = createLinkedRoster({ link: directory(farBots(2)), bots: () => local });const narrow = { ...writer, visibility: { people: ["[email protected]"] } };diff --git a/server/host/linked-roster.ts b/server/host/linked-roster.tsindex 0ac1075e1f..6fdadb3e74 100644--- a/server/host/linked-roster.ts+++ b/server/host/linked-roster.ts@@ -101,15 +101,19 @@ export function createLinkedRoster(deps: LinkedRosterDeps) {/** Only when it matters: the place cannot be reached now. */const state = (row: LinkedRow): string => row.online ? "" : row.kind === "cloud" && deps.link.role() === "dialer" && deps.link.sleeps() ? "asleep: work sent there waits" : "offline: work sent there waits";- /** The far bots in their place's order, the person's Chief first. `busy`: past the cap, the ones this place has work- * out with now come next; only a hand-off's [LIVE TEAMMATES] uses it, so a system prompt never changes with work. */+ /** The far bots, the person's Chief first and any other Chief next, then those of places that can be reached now (a computer that never came+ * back would otherwise crowd out the one in use), each group by name: so a system prompt's roster changes only when a+ * bot or the reachable places change, never with the order a place lists its bots in. `busy`: past the cap, the ones+ * this place has work out with now are kept first; only a hand-off's [LIVE TEAMMATES] uses that, so a system prompt+ * never changes with work. */function ordered(rows: readonly LinkedRow[], chief: LinkedRow | null, busy: boolean): LinkedRow[] {- const first = (a: LinkedRow) => Number(a.id === chief?.id);- const order = new Map(rows.map((row, index) => [row, index]));+ const first = (a: LinkedRow) => (a.id === chief?.id ? 2 : a.bot.chief ? 1 : 0);+ const byName = (a: LinkedRow, b: LinkedRow) => farLabel(a.bot.name, NAME_MAX).localeCompare(farLabel(b.bot.name, NAME_MAX), "en", { numeric: true, sensitivity: "base" }) || a.id.localeCompare(b.id);+ const settled = (a: LinkedRow, b: LinkedRow) => first(b) - first(a) || Number(b.online) - Number(a.online) || byName(a, b);const used = new Map<string, number>();if (busy && rows.length > FAR_ROSTER_MAX) for (const node of deps.active?.() ?? []) used.set(node.botId, Math.max(used.get(node.botId) ?? 0, node.createdAt));- const kept = new Set([...rows].sort((a, b) => first(b) - first(a) || (used.get(b.id) ?? 0) - (used.get(a.id) ?? 0) || order.get(a)! - order.get(b)!).slice(0, FAR_ROSTER_MAX));- return rows.filter((row) => kept.has(row)).sort((a, b) => first(b) - first(a) || order.get(a)! - order.get(b)!);+ const kept = new Set([...rows].sort((a, b) => first(b) - first(a) || (used.get(b.id) ?? 0) - (used.get(a.id) ?? 0) || settled(a, b)).slice(0, FAR_ROSTER_MAX));+ return rows.filter((row) => kept.has(row)).sort(settled);}/** The far bots, fenced, within FAR_BLOCK_MAX characters. `about`: a Chief's lines, with each bot's role anddiff --git a/server/index.ts b/server/index.tsindex fa77714ebb..c1fd0a1414 100644--- a/server/index.ts+++ b/server/index.ts@@ -145,7 +145,7 @@ import {type Runtime,} from "./container-computer.ts";import { containerComputerMcp } from "./local-vm-box.ts";-import { attachedFileLine, attachForTurn, saveBotAttachment } from "./bot-attachment.ts";+import { attachedFileLine, attachForTurn, saveBotAttachment } from "./bot-attachment.ts"; import { attachNotFound } from "./attach-file-hint.ts";import {cacheUntilConfigChanges,ensureDirs,@@ -13050,7 +13050,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {} catch (error) {const status = typeof (error as { status?: unknown }).status === "number" ? (error as { status: number }).status : 500;const message = status === 404- ? `No file was found at ${requestedPath}. Save it under /home/cua/workspace (or your working folder) and pass its exact path.`+ ? attachNotFound(requestedPath, localVmThreadTargets.has(threadId) ? VM_WORKSPACE_GUEST : messageFileRootsForThread(from.id, threadId).find((root) => root !== ATTACHMENTS_DIR)): error instanceof Error ? error.message : "could not attach that file";return json(res, status, { error: message });}diff --git a/server/routes/bot-link.ts b/server/routes/bot-link.tsindex 83ad216655..85a17d5762 100644--- a/server/routes/bot-link.ts+++ b/server/routes/bot-link.ts@@ -29,7 +29,8 @@ const origin = z.string().max(300).regex(/^https?:\/\/[^/\s]+$/u);const switchBody = z.union([z.object({ on: z.literal(true), origin, token: z.string().min(16).max(512), name, cloud: placeSchema, account: z.string().max(200).optional() }).strict(),z.object({ on: z.literal(false) }).strict(),- /** `heardAt`: when the app first heard "asleep" (this computer's clock), so a word older than the Cloud's own answers parks nothing. */+ /** `heardAt`: when the app heard the word (this computer's clock): an "asleep" older than the Cloud's own answers parks+ * nothing, and an "awake" older than the link's last park starts nothing. */z.object({ cloud: z.enum(["asleep", "awake"]), origin, heardAt: z.number().int().nonnegative().optional() }).strict(),]);const pairBody = z.object({ computer: placeSchema, name }).strict();@@ -124,8 +125,9 @@ export function createBotLinkRoutes(deps: BotLinkRouteDeps): RouteHandler {if (!body.success) return json(res, 400, { error: "send { on: true, origin, token, name, cloud: { id, name } }, { on: false } or { cloud: \"asleep\" | \"awake\", origin }" });if (!("on" in body.data)) {// The word is one Cloud's: a link to another Cloud is not told it.- if (body.data.cloud === "awake") await dialer.tellEnded(body.data.origin);- if (link.role() === "dialer" && link.dial()?.origin === body.data.origin) { if (body.data.cloud === "asleep") dialer.sleep(body.data.heardAt); else dialer.start(); }+ // A word that does not say when the app heard it is too old to act on: nothing is sent or parked for it.+ if (body.data.cloud === "awake" && body.data.heardAt !== undefined) await dialer.tellEnded(body.data.origin);+ if (link.role() === "dialer" && link.dial()?.origin === body.data.origin) { if (body.data.cloud === "asleep") dialer.sleep(body.data.heardAt); else if (body.data.heardAt !== undefined) dialer.start({ heardAt: body.data.heardAt }); }return json(res, 200, state());}if (!body.data.on) {diff --git a/src/components/AppNotices.test.ts b/src/components/AppNotices.test.tsindex d817eb7572..dd7b55a5b7 100644--- a/src/components/AppNotices.test.ts+++ b/src/components/AppNotices.test.ts@@ -47,6 +47,8 @@ import { ADVANCED_BACK_KEY } from "@/lib/new-look";import { api } from "@/state/store";import { forgetAnnouncementCards, seenKey } from "@/lib/announcements";import { CLOUD_WELCOME_DONE } from "../../shared/cloud-hints";+import { createPlacesTogether, installPlacesTogether } from "../../electron/places-together.mjs";+import { resetPlacesTogetherForTest } from "@/lib/places-together";const DAY = 86_400_000, NOW = new Date(2026, 9, 9, 12).getTime();const plans = [@@ -1896,3 +1898,78 @@ describe("the Teams What's new", () => {expect(await relaunch(), "the next launch").toContain(TITLE);});});++describe("bots together by default", () => {+ let saved: unknown, reads: string[], lent: boolean, lends: boolean[];+ const install = () => {+ const together = createPlacesTogether({+ pref: { read: () => { if (saved === undefined) throw Object.assign(new Error("none"), { code: "ENOENT" }); return saved; }, write: (value: unknown) => { saved = JSON.parse(JSON.stringify(value)); } },+ cloud: () => ({ origin: MY_CLOUD, account: "a", asleep: false }), computer: () => "computer:/data",+ powerChecked: async () => { reads.push("admin"); return true; },+ local: async (route: string) => { reads.push(`computer ${route}`); return new Response(JSON.stringify({ bots: [] })); },+ cloudFetch: async (url: string) => { reads.push(`cloud ${url}`); return new Response(JSON.stringify({ bots: [] })); },+ shown: () => "computer", focused: () => true, openPlace: () => undefined, send: () => {}, changed: () => {}, now: () => now,+ commands: { on: () => lent, set: (on: boolean) => { lends.push(on); lent = on; } }, turnedOn: () => { lends.push(true); lent = true; },+ setTimer: () => ({}) as never, clearTimer: () => {},+ });+ installPlacesTogether({ ipcMain: { handle: (channel: string, handler: Handler) => void desk.handlers.set(channel, handler) } as never,+ asking: (event: unknown) => { const page = (event as { page: Page }).page; return page === "server" ? null : page; }, together });+ return together;+ };+ beforeEach(() => { saved = undefined; reads = []; lent = false; lends = []; resetPlacesTogetherForTest(); });+ afterEach(() => resetPlacesTogetherForTest());++ it("once, on this computer's page, for a person who never chose: drawing it turns the list on, lends nothing and reads nothing of My Cloud yet", async () => {+ returning(); storage.set(CLOUD_INTRO, "1");+ const together = install();+ expect(together.on()).toBe(false);+ const html = await launch();+ expect(html).toContain('data-notice="together-default"');+ expect(html).toContain("Your bots are in one list now");+ expect(html).toContain("Let your Clouds' bots run commands on this computer");+ expect(html).not.toContain(STAR);+ expect(together.on()).toBe(true);+ expect(lends, "the default never lends commands").toEqual([]);+ expect(reads.filter(read => !read.startsWith("computer")), "no read of My Cloud at the start").toEqual([]);+ press("Got it");+ expect(await settle()).not.toContain('data-notice="together-default"');+ resetPlacesTogetherForTest();+ expect(await launch(), "closed: never again").not.toContain('data-notice="together-default"');+ expect(together.on(), "and it stays on").toBe(true);+ });++ it("never in the launch What's new or the Cloud card takes: it waits for a later launch", async () => {+ returning();+ install();+ const html = await launch();+ expect(html).not.toContain('data-notice="together-default"');+ });++ it("no suggestion to move bots to My Cloud goes ahead of it: not while it is due, nor while main has not said whether it is", async () => {+ returning(); storage.set(CLOUD_INTRO, "1"); storage.set(PRODUCT_HUNT_NOTICE, "1");+ desk.handlers.set("two-places:state", async () => ({ suggest: { key: "cloud:mine", name: "My Cloud", kind: "cloud" } }));+ desk.handlers.set("places-together:state", () => new Promise(() => {}));+ expect(await launch(), "main has not said yet").not.toContain('data-notice="two-places"');+ resetPlacesTogetherForTest();+ install();+ const due = await launch();+ expect(due).not.toContain('data-notice="two-places"');+ expect(due).toContain('data-notice="together-default"');+ });++ it("never for a person who chose either way, nor on My Cloud's page", async () => {+ returning();+ saved = { v: 1, on: false };+ install();+ expect(await launch()).not.toContain('data-notice="together-default"');+ saved = { v: 1, on: true };+ resetPlacesTogetherForTest();+ install();+ expect(await launch()).not.toContain('data-notice="together-default"');+ saved = undefined;+ resetPlacesTogetherForTest();+ install();+ showWindow(MY_CLOUD);+ expect(await launch()).not.toContain('data-notice="together-default"');+ });+});diff --git a/src/components/AppNotices.tsx b/src/components/AppNotices.tsxindex 52e752d635..7e9fbfda7c 100644--- a/src/components/AppNotices.tsx+++ b/src/components/AppNotices.tsx@@ -15,10 +15,11 @@ import { buyOfferAllowed, cloudNoticeKind, cloudPlanView, cloudTrialNotice, clouimport { jobRoutine, useCloudIntent } from "@/lib/cloud-intent";import { CLOUD_INTENT_GIVEN, cloudSetupStage } from "@/lib/cloud-setup";import { cornerPopupWaits, firstChatQuiet, firstReplyPending } from "@/lib/corner-popup";-import { ANNOUNCEMENT_NOTICE, BOAT_OFFER_NOTICE, CLOUD_INTRO, CLOUD_NOTICE, CLOUD_TRIAL_NOTICE, dismissNotice, dismissNotices, EARLIER_WHATS_NEW_NOTICE, GROK_MOVE_NOTICE, introShown, introStage, launchNotice, markLaunchNotice, MODELGO_OFFER_NOTICE, nextNotice, noticeSeen, PHONE_UPDATE_NOTICE, phoneUpdateHint, PRODUCT_HUNT_NOTICE, PRODUCT_HUNT_UNTIL, PRODUCT_HUNT_URL, SIMPLE_MODE_NOTICE, STAR_NOTICE, TEAMS_NOTICE, TWO_PLACES_NOTICE, UPDATES_CONSENT_NOTICE, usedBefore, WHATS_NEW_NOTICE } from "@/lib/notices";+import { ANNOUNCEMENT_NOTICE, BOAT_OFFER_NOTICE, CLOUD_INTRO, CLOUD_NOTICE, CLOUD_TRIAL_NOTICE, dismissNotice, dismissNotices, EARLIER_WHATS_NEW_NOTICE, GROK_MOVE_NOTICE, introShown, introStage, launchNotice, markLaunchNotice, MODELGO_OFFER_NOTICE, nextNotice, noticeSeen, PHONE_UPDATE_NOTICE, phoneUpdateHint, PRODUCT_HUNT_NOTICE, TOGETHER_NOTICE, PRODUCT_HUNT_UNTIL, PRODUCT_HUNT_URL, SIMPLE_MODE_NOTICE, STAR_NOTICE, TEAMS_NOTICE, TWO_PLACES_NOTICE, UPDATES_CONSENT_NOTICE, usedBefore, WHATS_NEW_NOTICE } from "@/lib/notices";import { rememberNoticeSeen } from "@/lib/announcement-history";import { reportTeams, teamsAction } from "@/lib/teams-whats-new";import { useTwoPlaces } from "@/lib/two-places";+import { useTogetherNoticeDue } from "@/lib/places-together";import { SIMPLE_ONLY } from "@/lib/simple-only";import { useAdvancedBackDue, useNewLookDue } from "@/lib/new-look";import { useAdvancedMode } from "@/lib/interface-mode";@@ -48,6 +49,7 @@ import { NewLookNotice, reportNewLook } from "./NewLookNotice";import { PhoneUpdateCard, phonesToTell, useRetiredLinkPhones } from "./PhoneUpdateNotice";import { reportSimpleModePrompt, SimpleModePrompt } from "./SimpleModePrompt";import { TwoPlacesCard } from "./TwoPlacesCard";+import { TogetherNotice } from "./TogetherNotice";import { TeamsPopup } from "./whats-new/TeamsPopup";import { WhatsNewPopup } from "./whats-new/WhatsNewPopup";@@ -110,7 +112,15 @@ export function AppNotices({ quiet = false, viewer = null, now = Date.now }: { qconst mausBot = useMausBotWelcomeDue(viewer);// Bots in two places: this computer's page only, where main knows what lives here.const two = useTwoPlaces();- const twoFact = !local || two.suggest === null ? false : two.suggest === undefined ? null : true;+ // Together by default: this computer's page only, where the one list is; never during a live call.+ const togetherDue = useTogetherNoticeDue();+ // While the notice of the default is due, or main has not said yet whether it is, the bots of this computer and My+ // Cloud are about to work together: no suggestion to move them to My Cloud goes ahead of it.+ const cloudHeld = two.suggest?.kind === "cloud" && togetherDue !== false;+ const twoFact = !local || two.suggest === null || (cloudHeld && togetherDue === true) ? false : two.suggest === undefined || cloudHeld ? null : true;+ // Once drawn it stays until closed, though main stops calling it due as soon as one of its switches is used.+ const [togetherOpen, setTogetherOpen] = useState(false);+ const togetherFact = togetherOpen ? true : remote || !local || togetherDue === false ? false : togetherDue === null || (state.liveCall && state.liveCall.status !== "ended") ? null : true;// Phones whose older app lost its way in: this computer's own page only, never a Cloud, a server's page or client mode.const linkPhones = useRetiredLinkPhones(!remote && local);useEffect(() => {@@ -257,7 +267,7 @@ export function AppNotices({ quiet = false, viewer = null, now = Date.now }: { q// FOLLOWERS); nothing else does.const notice = waits ? null: firstChatQuiet(state) ? (grokNow === true && (launch === null || launch === GROK_MOVE_NOTICE) ? GROK_MOVE_NOTICE : null)- : teamsHere || cards || whatsNewOwed || consentHere || simpleDue || boatHere || announcementNow !== false || twoFact !== false || grokNow !== false || phoneNow !== false ? nextNotice({+ : teamsHere || cards || whatsNewOwed || consentHere || simpleDue || boatHere || announcementNow !== false || twoFact !== false || togetherFact !== false || grokNow !== false || phoneNow !== false ? nextNotice({[TEAMS_NOTICE]: teamsNow,[GROK_MOVE_NOTICE]: grokNow,[PHONE_UPDATE_NOTICE]: phoneNow,@@ -272,6 +282,7 @@ export function AppNotices({ quiet = false, viewer = null, now = Date.now }: { q[CLOUD_TRIAL_NOTICE]: planBridge && plan === null ? null : Boolean(key && (trialDue || trialOpen === key)),[CLOUD_NOTICE]: !view ? false : view.kind === "unknown" ? null: Boolean(kind && !noticeSeen(record, CLOUD_NOTICE_CARD[kind].dismissed)),+ [TOGETHER_NOTICE]: togetherFact,[BOAT_OFFER_NOTICE]: !boatHere || moving || afterWelcome === true || !usedBefore(state.bots) || desktopState?.seen.includes(BOAT_OFFER_NOTICE) ? false: organization === null || moving === null || afterWelcome === null || mausBotFirst || (desktop && !desktopState) ? null : !organization,[ANNOUNCEMENT_NOTICE]: announcementNow,@@ -305,6 +316,8 @@ export function AppNotices({ quiet = false, viewer = null, now = Date.now }: { qmarkLaunchAnnouncement(announcement.id);reportAnnouncement(announcement, "shown");if (announcement.kind === "sponsor") rememberSponsorDay(seenRecord, now(), remembering);+ } else if (shownKey === TOGETHER_NOTICE) {+ setTogetherOpen(true);} else if (shownKey === GROK_MOVE_NOTICE && !grokShown) {setGrokShown(true);reportGrokMovePopup("shown");@@ -342,6 +355,8 @@ export function AppNotices({ quiet = false, viewer = null, now = Date.now }: { qreturn <PhoneUpdateCard phones={retiredPhones} onOpen={() => { done(); dispatch(phonePairingSettingsAction()); }} onDismiss={done} />;}+ if (notice === TOGETHER_NOTICE) return <TogetherNotice onClose={() => { setTogetherOpen(false); close(); }} />;+if (notice === SIMPLE_MODE_NOTICE) {return SIMPLE_ONLY || advancedBack ? <NewLookNotice onClose={close} back={advancedBack} /> : <SimpleModePrompt onClose={close} />;}diff --git a/src/components/OtherPlaceBots.dom.test.ts b/src/components/OtherPlaceBots.dom.test.tsindex 7d43bf44d3..3cd1a8f6a7 100644--- a/src/components/OtherPlaceBots.dom.test.ts+++ b/src/components/OtherPlaceBots.dom.test.ts@@ -113,12 +113,14 @@ it("a line is no search result: hidden while the sidebar is searched", async ()expect(q("[data-other-place]")).toBeNull();});-it("the switch: marked Early, off until turned on, and hidden where main does not offer it", async () => {+it("the switch: no longer marked Early, says it is on by default, and is hidden where main does not offer it", async () => {said = state({ on: false, other: null });await render(createElement(SettingsLook.Provider, { key: "switch", value: true }, createElement(PlacesTogetherSwitch)));expect(q("[data-places-together]")!.getAttribute("data-places-together")).toBe("off");expect(q("[data-places-together]")!.textContent).toContain("This computer and My Cloud together");- expect(q("[data-places-together] [data-settings-tag]")!.textContent).toBe("Early");+ expect(q("[data-places-together]")!.textContent).toContain("On by default.");+ expect(q("[data-places-together]")!.textContent, "the grant covers every Cloud of the account").toContain("your Clouds' bots run commands on this computer");+ expect(q("[data-places-together] [data-settings-tag]")).toBeNull();await act(async () => q("[data-places-together] [role=switch]")!.click());expect(page.set.mock.calls).toEqual([[true]]);expect(q("[data-places-together]")!.getAttribute("data-places-together")).toBe("on");diff --git a/src/components/PlacesRail.test.ts b/src/components/PlacesRail.test.tsindex 48f653cafd..4933283501 100644--- a/src/components/PlacesRail.test.ts+++ b/src/components/PlacesRail.test.ts@@ -924,3 +924,34 @@ it("a server saved by hand: its menu offers Rename, saved by main on this computexpect(rename.mock.calls, "by the circle's own id, which main listed").toEqual([["vps", "家里的服务器"], ["vps", "家里的服务器"]]);expect(host.querySelector("[data-rail-menu]"), "saved: the menu closes").toBeNull();});++it("Show bots together: one checkable row in the menu of This computer, the workspace of its own that runs, and My Cloud, for the same switch; no other circle has it", async () => {+ const expand = vi.fn();+ let on = true;+ const together = vi.fn(async (next: boolean) => { on = next; return on; });+ rail = { places: [+ place("local", "This Mac", { kind: "computer", profile: "default", active: true, paint: { swatch: null }, together: true }),+ place("work", "Work", { kind: "computer", profile: "work", named: true, paint: { swatch: null } }),+ place("home", "My Cloud", { paint: { swatch: null }, together: true }),+ place("acme", "Acme", { kind: "team", paint: { swatch: null } }),+ ], add: { cloud: false, link: true, address: false } };+ Object.assign(window, { ogb: { workspaces: { ...workspaces, together }, cloudAdd, rail: { expand, onSkin: () => () => {} } } });+ await mount(createElement(PlacesRail, { chrome: true }));+ const menuOf = async (id: string) => {+ await act(async () => { host.querySelector(`[data-rail-place="${id}"]`)!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true })); });+ return host.querySelector(`[data-rail-menu="${id}"]`);+ };+ const mine = await menuOf("local");+ const row = mine!.querySelector<HTMLButtonElement>("[data-rail-together-row]")!;+ expect([row.textContent, row.getAttribute("role"), row.getAttribute("aria-checked")]).toEqual(["Show bots together", "checkbox", "true"]);+ await click(row);+ await act(async () => { for (let i = 0; i < 6; i++) await Promise.resolve(); });+ expect(together).toHaveBeenCalledWith(false);+ expect(host.querySelector("[data-rail-menu='local'] [data-rail-together-row]")?.getAttribute("aria-checked"), "the menu stays open and shows main's answer").toBe("false");+ await act(async () => { host.querySelector("[data-rail-menu]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });+ expect((await menuOf("home"))?.querySelector("[data-rail-together-row]")).not.toBeNull();+ await act(async () => { host.querySelector("[data-rail-menu]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });+ expect((await menuOf("work"))?.querySelector("[data-rail-together-row]")).toBeNull();+ await act(async () => { host.querySelector("[data-rail-menu]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });+ expect((await menuOf("acme"))?.querySelector("[data-rail-together-row]")).toBeNull();+});diff --git a/src/components/PlacesRail.tsx b/src/components/PlacesRail.tsxindex b1cc64e7df..0995b32049 100644--- a/src/components/PlacesRail.tsx+++ b/src/components/PlacesRail.tsx@@ -9,7 +9,7 @@// main says this computer's bots may move to (one tap: main starts the move). With several accounts signed in here, the tiles// are grouped by account with a thin divider, and a click on another account's tile switches to it first (main does that).import { useEffect, useRef, useState, type CSSProperties, type MouseEvent as ReactMouseEvent } from "react";-import { Cloud, House, Laptop, Loader2, MoreHorizontal, Plus, Search, Server, UserRound } from "lucide-react";+import { Check, Cloud, House, Laptop, Loader2, MoreHorizontal, Plus, Search, Server, UserRound } from "lucide-react";import type { CloudSwatch } from "../../electron/cloud-list.mjs";import type { PlaceColorOutcome } from "../../electron/place-look.mjs";import { track } from "@/lib/analytics";@@ -19,7 +19,7 @@ import { activeLocale, t } from "@/lib/i18n";import { localizedRelativeTime } from "@/lib/relative-time";import { useAdvancedMode } from "@/lib/interface-mode";import { useBesideFramed } from "@/lib/chrome-rail";-import { computerName, editLocal, makeHome, placeInitials, recolorPlace, removeLocal, removePlace, renamePlace, usePlaces, type RailPlace } from "@/lib/places";+import { computerName, editLocal, makeHome, placeInitials, recolorPlace, removeLocal, removePlace, renamePlace, setTogetherFromRail, usePlaces, type RailPlace } from "@/lib/places";import { AccountsSheet, switchNote } from "./AccountMenu";import { useDesktopCapabilities, windowFramed } from "./DesktopCapabilities";import { MENU_ROW, MENU_SHEET } from "./menu-recipe";@@ -135,7 +135,7 @@ type MenuAt = { place: RailPlace; from: HTMLElement };* menu; elsewhere, nothing. */const menuOpener = (place: RailPlace, onMenu: (at: MenuAt) => void) => (event: ReactMouseEvent<HTMLElement>) => {event.preventDefault();- if (place.paint || place.removable) onMenu({ place, from: event.currentTarget });+ if (place.paint || place.removable || place.together !== undefined) onMenu({ place, from: event.currentTarget });};/** How far down the rail an element of it sits, in the rail's own units (offsets, not the screen's: the rail's page@@ -194,6 +194,27 @@ function RemoveRow({ place, onRemoved }: { place: RailPlace; onRemoved: () => vo</div>;}+/** Show bots together in the menu of This computer (or the workspace of its own that runs) and of My Cloud: one checkable+ * row for the same switch as Settings → Plan & billing; main says what it is once it changed, and the menu stays open. */+function TogetherRow({ on }: { on: boolean }) {+ const [shown, setShown] = useState(on);+ const [busy, setBusy] = useState(false);+ const [failed, setFailed] = useState(false);+ useEffect(() => setShown(on), [on]);+ const turn = () => {+ if (busy) return;+ setBusy(true); setFailed(false);+ void setTogetherFromRail(!shown).then((now) => { setBusy(false); if (now === null) setFailed(true); else setShown(now); });+ };+ return <div data-rail-together className="flex flex-col gap-0.5 border-t border-hairline/50 px-0.5 pt-1.5">+ <button type="button" role="checkbox" aria-checked={shown} data-rail-together-row className={MENU_ROW} disabled={busy} aria-busy={busy || undefined} onClick={turn}>+ <span className="min-w-0 flex-1 truncate text-start">{t("rail.together")}</span>+ {busy ? <Loader2 size={15} aria-hidden="true" className="shrink-0 animate-spin motion-reduce:animate-none" /> : shown && <Check size={15} aria-hidden="true" className="shrink-0" />}+ </button>+ {failed && <p role="alert" className="px-1.5 pb-1 text-[12px] text-danger">{t("together.switch.failed")}</p>}+ </div>;+}+/** Make … my home in a server's menu: one tap starts the move, and the menu closes once main has started it; the account* area then says how it goes. Main's own words when it can't start. */function MakeHomeRow({ place, onStarted }: { place: RailPlace; onStarted: () => void }) {@@ -232,7 +253,7 @@ function ListedMenu({ place, top, onClose }: { place: RailPlace; top: number; onconst [outcome, setOutcome] = useState<PlaceColorOutcome | null>(null);const ref = useRef<HTMLDivElement>(null);useEffect(() => { (ref.current?.querySelector<HTMLElement>("[data-rail-rename], [role='radio'][tabindex='0']") ?? ref.current?.querySelector<HTMLElement>("[data-rail-remove-ask], [data-rail-make-home-start]"))?.focus(); }, []);- if (!paint && !place.removable && !place.makeHome && !place.renames) return null;+ if (!paint && !place.removable && !place.makeHome && !place.renames && place.together === undefined) return null;const name = place.kind === "computer" ? computerName(place) : place.name;const choose = (swatch: CloudSwatch) => {if (!paint || paint.locked || pending || swatch === paint.swatch) return;@@ -256,6 +277,7 @@ function ListedMenu({ place, top, onClose }: { place: RailPlace; top: number; on{note && <p data-rail-menu-note className="px-2 pb-1 text-[12px] text-ink-secondary">{note}</p>}{outcome === "failed" && <p role="alert" className="px-2 pb-1 text-[12px] text-danger">{t("placeLook.failed")}</p>}</>}+ {place.together !== undefined && <TogetherRow on={place.together} />}{place.makeHome && <MakeHomeRow place={place} onStarted={onClose} />}{place.removable && <RemoveRow place={place} onRemoved={onClose} />}</div>;@@ -352,6 +374,7 @@ function LocalMenu({ place, top, onClose }: { place: RailPlace; top: number; onC<SwatchRadios value={(pending === undefined ? swatch : pending) ?? "slate"} onChange={choose} label={t("placeLook.aria", { name })} offset="menu" none /></div>{failed && <p role="alert" className="px-2 pb-1 text-[12px] text-danger">{t("placeLook.failed")}</p>}+ {place.together !== undefined && <TogetherRow on={place.together} />}<RemoveLocalRow place={place} onRemoved={onClose} /></div>;}diff --git a/src/components/PlacesTogetherSwitch.tsx b/src/components/PlacesTogetherSwitch.tsxindex d36126c9ff..2fa30d2c4b 100644--- a/src/components/PlacesTogetherSwitch.tsx+++ b/src/components/PlacesTogetherSwitch.tsx@@ -3,8 +3,8 @@ import { t } from "@/lib/i18n";import { setPlacesTogether, usePlacesTogether } from "@/lib/places-together";import { SettingRow, SettingsGroup, SettingsRows, Switch } from "./SettingsPrimitives";-/** Settings → MausBot Cloud: this computer's bots and My Cloud's in one sidebar. Shown only where main offers it;- * My Cloud's page can turn it off, and only this computer's page turns it on. */+/** Settings → Plan & billing: this computer's bots and My Cloud's in one sidebar, on by default once its notice was shown.+ * Shown only where main offers it; My Cloud's page can turn it off, and only this computer's page turns it on. */export function PlacesTogetherSwitch() {const together = usePlacesTogether();const [busy, setBusy] = useState(false), [failed, setFailed] = useState(false);@@ -16,7 +16,7 @@ export function PlacesTogetherSwitch() {return <SettingsGroup block="together"><SettingsRows><div data-places-together={together.on ? "on" : "off"} className="contents">- <SettingRow title={t("together.switch.title")} tag={t("settings.early.tag")} subtitle={`${t("together.switch.line")} ${t("together.switch.commands")}`}+ <SettingRow title={t("together.switch.title")} subtitle={`${t("together.switch.lineDefault")} ${t("together.switch.commandsAll")}`}message={failed ? <span role="alert" className="block text-danger">{t("together.switch.failed")}</span> : undefined}><Switch checked={together.on} disabled={busy} aria-label={t("together.switch.title")} onClick={turn} /></SettingRow>diff --git a/src/components/TogetherNotice.dom.test.ts b/src/components/TogetherNotice.dom.test.tsnew file mode 100644index 0000000000..d16ed84160--- /dev/null+++ b/src/components/TogetherNotice.dom.test.ts@@ -0,0 +1,119 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++import type { PlacesTogetherState } from "@/lib/places-together";+import { resetPlacesTogetherForTest } from "@/lib/places-together";+import { TogetherNotice } from "./TogetherNotice";++let container: HTMLDivElement, root: Root, said: PlacesTogetherState, changed: () => void, lent: boolean;+const state = (over: Partial<PlacesTogetherState> = {}): PlacesTogetherState => ({ v: 1, available: true, on: true, here: "computer",+ other: { home: "cloud", state: "ready", bots: [] }, notice: true, commands: lent, ...over });+const page = {+ state: vi.fn(async () => ({ ...said, commands: lent })),+ set: vi.fn(async (on: boolean) => { said = on ? state({ notice: undefined }) : state({ on: false, other: null, notice: undefined }); return said; }),+ open: vi.fn(async () => true),+ onChanged: vi.fn((cb: () => void) => { changed = cb; return () => {}; }),+ noticeShown: vi.fn(async () => true),+ noticeDone: vi.fn(async () => {}),+ setCommands: vi.fn(async (on: boolean) => { lent = on; return on; }),+};+const q = (selector: string) => document.body.querySelector<HTMLElement>(selector);+const onClose = vi.fn();+const render = async () => { await act(async () => root.render(createElement(TogetherNotice, { onClose }))); await act(async () => {}); };+const click = async (selector: string) => { await act(async () => { q(selector)!.click(); }); await act(async () => {}); };++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ lent = false;+ said = state();+ window.ogb = { placesTogether: page } as never;+ for (const fn of Object.values(page)) fn.mockClear();+ onClose.mockClear();+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);+});+afterEach(async () => { await act(async () => root.unmount()); container.remove(); resetPlacesTogetherForTest(); vi.unstubAllGlobals(); delete (window as { ogb?: unknown }).ogb; });++it("drawn, it tells main once (which turns the default on) and takes no focus: the person keeps typing", async () => {+ const input = document.createElement("textarea");+ document.body.append(input);+ input.focus();+ await render();+ expect(page.noticeShown).toHaveBeenCalledTimes(1);+ expect(document.activeElement).toBe(input);+ expect(q("[data-notice='together-default']")?.tagName).toBe("ASIDE");+ expect(q("[role='dialog'], [aria-modal]")).toBeNull();+ await act(async () => changed());+ expect(page.noticeShown).toHaveBeenCalledTimes(1);+ expect(q("[data-notice='together-default']")!.textContent).toContain("one list");+ expect(q("[data-together-notice-list]")!.getAttribute("aria-checked")).toBe("true");+ expect(q("[data-together-notice-commands]")!.getAttribute("aria-checked")).toBe("false");+ expect(page.noticeDone).not.toHaveBeenCalled();+ input.remove();+});++it("its first switch turns the joining off at once, without lending anything, and ends the notice for good while it stays up", async () => {+ await render();+ await click("[data-together-notice-list]");+ expect(page.set).toHaveBeenCalledWith(false, "notice");+ expect(page.noticeDone).toHaveBeenCalledTimes(1);+ expect(page.setCommands).not.toHaveBeenCalled();+ expect(q("[data-together-notice-list]")!.getAttribute("aria-checked")).toBe("false");+ expect(q("[data-together-notice-commands]")).toBeNull();+ expect(q("[data-together-notice-off]")).not.toBeNull();+ expect(onClose).not.toHaveBeenCalled();+ await click("[data-together-notice-list]");+ expect(page.set).toHaveBeenLastCalledWith(true, "notice");+});++it("its second switch is running commands, as lending says it: off unless they had it on, turned only by them, and live while the notice is up", async () => {+ await render();+ expect(q("[data-notice='together-default']")!.textContent).toContain("Let your Clouds' bots run commands on this computer");+ await click("[data-together-notice-commands]");+ expect(page.setCommands).toHaveBeenCalledWith(true);+ expect(q("[data-together-notice-commands]")!.getAttribute("aria-checked")).toBe("true");+ expect(page.noticeDone).toHaveBeenCalled();+ lent = false;+ await act(async () => changed());+ await act(async () => {});+ expect(q("[data-together-notice-commands]")!.getAttribute("aria-checked"), "turned off from the icon's menu meanwhile: the switch follows lending").toBe("false");+ page.setCommands.mockImplementationOnce(async () => false);+ await click("[data-together-notice-commands]");+ expect(q("[data-together-notice-commands]")!.getAttribute("aria-checked"), "Cancel in the icon's question: lending still says off").toBe("false");+ await act(async () => root.unmount());+ resetPlacesTogetherForTest();+ root = createRoot(container);+ lent = true;+ said = state();+ await render();+ expect(q("[data-together-notice-commands]")!.getAttribute("aria-checked")).toBe("true");+});++it("Got it, the close button and Escape each close it for good", async () => {+ await render();+ await click("[data-together-notice-done]");+ expect([page.noticeDone.mock.calls.length, onClose.mock.calls.length]).toEqual([1, 1]);+ await click("[data-notice='together-default'] button[aria-label]");+ expect([page.noticeDone.mock.calls.length, onClose.mock.calls.length]).toEqual([2, 2]);+ await act(async () => { q("[data-notice='together-default']")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });+ expect([page.noticeDone.mock.calls.length, onClose.mock.calls.length]).toEqual([3, 3]);+});++it("while main is still turning the default on, the list switch already reads on", async () => {+ said = state({ on: false, other: null });+ page.noticeShown.mockImplementationOnce(() => new Promise(() => {}));+ await render();+ expect(q("[data-together-notice-list]")!.getAttribute("aria-checked")).toBe("true");+});++it("for a person whose home is My Cloud, one more line says this computer's bots and their routines now run while the app is open; for others, none", async () => {+ await render();+ expect(q("[data-together-notice-background]")).toBeNull();+ await act(async () => root.unmount());+ resetPlacesTogetherForTest();+ root = createRoot(container);+ said = state({ profileHome: true });+ await render();+ expect(q("[data-together-notice-background]")!.textContent).toBe("This computer's bots and their routines now run while the app is open.");+});diff --git a/src/components/TogetherNotice.tsx b/src/components/TogetherNotice.tsxnew file mode 100644index 0000000000..f61dd741f7--- /dev/null+++ b/src/components/TogetherNotice.tsx@@ -0,0 +1,66 @@+import { useEffect, useState } from "react";+import { Merge } from "lucide-react";+import { t } from "@/lib/i18n";+import { setPlacesTogether, setTogetherCommands, togetherNoticeDone, togetherNoticeShown, usePlacesTogether } from "@/lib/places-together";+import { NoticeCard, PRIMARY_BUTTON } from "./NoticeCard";+import { Switch } from "./SettingsPrimitives";++/** The one-time notice of "This computer and My Cloud together" being on by default (electron/places-together.mjs): a+ * card in the corner, like every other notice, that never takes focus or waits for an answer. Drawing it is what turns the+ * default on (main does nothing before). Its first switch turns the joining off at once (back to two separate lists); its+ * second is "Let your Clouds' bots run commands on this computer", as lending says it now, never turned on for them, and+ * turned on only after the same question the OpenMausBot icon's menu asks. Got+ * it, the close button, Escape or either switch, and it never shows again. */+export function TogetherNotice({ onClose }: { onClose: () => void }) {+ const together = usePlacesTogether();+ // Told once per notice on screen (a kept object, not a ref: notices are also drawn outside a live tree in tests).+ const [told] = useState(() => ({ current: false }));+ // Lending's own word, live while the notice is up (also when the icon's menu changes it); while the person's own turn+ // waits on the icon's question, the switch shows where they turned it.+ const [turning, setTurning] = useState<boolean | null>(null);+ const [busy, setBusy] = useState<"list" | "commands" | null>(null);+ const [failed, setFailed] = useState(false);+ const [touched, setTouched] = useState(false);+ useEffect(() => {+ if (told.current) return;+ told.current = true;+ void togetherNoticeShown();+ }, []);+ const commands = turning ?? (typeof together?.commands === "boolean" ? together.commands : null);+ // Until the person turns it, the notice's own drawing is turning it on: never shown off for the moment main takes.+ const on = touched ? together?.on === true : together?.on !== false || together?.notice === true;+ const done = () => { togetherNoticeDone(); onClose(); };+ const turnList = () => {+ if (busy) return;+ setBusy("list"); setFailed(false); setTouched(true);+ togetherNoticeDone();+ void setPlacesTogether(!on, "notice").catch(() => setFailed(true)).finally(() => setBusy(null));+ };+ const turnCommands = () => {+ if (busy) return;+ const next = !(commands ?? false);+ setBusy("commands"); setFailed(false); setTurning(next);+ togetherNoticeDone();+ void setTogetherCommands(next).catch(() => setFailed(true)).finally(() => { setTurning(null); setBusy(null); });+ };+ return <NoticeCard titleId="together-notice-title" notice="together-default" icon={Merge} title={t("together.notice.title")} onDismiss={done}>+ <p className="mb-3 mt-1 text-[13px] text-ink-secondary">{t("together.notice.body")}</p>+ {together?.profileHome && <p data-together-notice-background className="-mt-2 mb-3 text-[12px] leading-snug text-ink-secondary">{t("together.notice.background")}</p>}+ <div className="mb-3 flex flex-col gap-2.5">+ <label className="flex items-center justify-between gap-3 text-[13px] text-ink">+ <span id="together-notice-list">{t("together.notice.list")}</span>+ <Switch data-together-notice-list checked={on} disabled={busy !== null} aria-labelledby="together-notice-list" onClick={turnList} />+ </label>+ {on && <div className="flex flex-col gap-1">+ <label className="flex items-center justify-between gap-3 text-[13px] text-ink">+ <span id="together-notice-commands">{t("together.notice.commands")}</span>+ <Switch data-together-notice-commands checked={commands === true} disabled={busy !== null || commands === null} aria-labelledby="together-notice-commands" onClick={turnCommands} />+ </label>+ <p className="text-[12px] leading-snug text-ink-secondary">{t(commands ? "together.notice.commandsOn" : "together.notice.commandsOff")}</p>+ </div>}+ {!on && <p data-together-notice-off className="text-[12px] leading-snug text-ink-secondary">{t("together.notice.off")}</p>}+ </div>+ {failed && <p role="alert" className="mb-3 text-[12px] text-danger">{t("together.switch.failed")}</p>}+ <button type="button" data-together-notice-done className={PRIMARY_BUTTON} onClick={done}>{t("together.notice.done")}</button>+ </NoticeCard>;+}diff --git a/src/lib/notices.test.ts b/src/lib/notices.test.tsindex 96a62913d2..c135988aa6 100644--- a/src/lib/notices.test.ts+++ b/src/lib/notices.test.ts@@ -3,7 +3,7 @@ import { EMPTY_ONBOARDING, type OnboardingStatus } from "@/lib/onboarding";import { withTourReset } from "@/lib/guided-tour";import { DESKTOP_NOTICES } from "../../electron/desktop-prefs.mjs";import { ANNOUNCEMENT_NOTICE, BOAT_OFFER_NOTICE, CLOUD_INTRO, CLOUD_NOTICE, CLOUD_TRIAL_NOTICE, dismissNotice, dismissNotices, EARLIER_WHATS_NEW_NOTICE, FOLLOWERS, GROK_MOVE_NOTICE, introShown, introStage, launchNotice, localDay, markLaunchNotice, MODELGO_OFFER_NOTICE, MUST_ACT,- nextNotice, noticeSeen, NOTICES, OLD_PRO_DISMISSALS, PHONE_UPDATE_NOTICE, phoneUpdateHint, PRODUCT_HUNT_NOTICE, SIMPLE_MODE_NOTICE, STAR_NOTICE, TEAMS_NOTICE, TWO_PLACES_NOTICE, UPDATES_CONSENT_NOTICE, usedBefore, WHATS_NEW_NOTICE, type NoticeFacts,+ nextNotice, noticeSeen, NOTICES, OLD_PRO_DISMISSALS, PHONE_UPDATE_NOTICE, phoneUpdateHint, PRODUCT_HUNT_NOTICE, SIMPLE_MODE_NOTICE, STAR_NOTICE, TEAMS_NOTICE, TOGETHER_NOTICE, TWO_PLACES_NOTICE, UPDATES_CONSENT_NOTICE, usedBefore, WHATS_NEW_NOTICE, type NoticeFacts,type NoticeId } from "./notices";let storage: Map<string, string>, session: Map<string, string>;@@ -17,8 +17,8 @@ afterEach(() => vi.unstubAllGlobals());const record = (hintsSeen: string[] = []): OnboardingStatus => ({ ...EMPTY_ONBOARDING, completedAt: "2026-09-01", version: 1, hintsSeen });const facts = (intro: boolean | null, trial: boolean | null, cloud: boolean | null, star: boolean | null, launch: boolean | null = false, popup: boolean | null = false,consent: boolean | null = false, simple: boolean | null = false, boat: boolean | null = false, two: boolean | null = false, grok: boolean | null = false,- phone: boolean | null = false, announcement: boolean | null = false, teams: boolean | null = false): NoticeFacts =>- ({ [TEAMS_NOTICE]: teams, [GROK_MOVE_NOTICE]: grok, [PHONE_UPDATE_NOTICE]: phone, [WHATS_NEW_NOTICE]: popup, [SIMPLE_MODE_NOTICE]: simple, [UPDATES_CONSENT_NOTICE]: consent, [TWO_PLACES_NOTICE]: two, [PRODUCT_HUNT_NOTICE]: launch, [CLOUD_INTRO]: intro, [CLOUD_TRIAL_NOTICE]: trial, [CLOUD_NOTICE]: cloud,+ phone: boolean | null = false, announcement: boolean | null = false, teams: boolean | null = false, together: boolean | null = false): NoticeFacts =>+ ({ [TOGETHER_NOTICE]: together, [TEAMS_NOTICE]: teams, [GROK_MOVE_NOTICE]: grok, [PHONE_UPDATE_NOTICE]: phone, [WHATS_NEW_NOTICE]: popup, [SIMPLE_MODE_NOTICE]: simple, [UPDATES_CONSENT_NOTICE]: consent, [TWO_PLACES_NOTICE]: two, [PRODUCT_HUNT_NOTICE]: launch, [CLOUD_INTRO]: intro, [CLOUD_TRIAL_NOTICE]: trial, [CLOUD_NOTICE]: cloud,[BOAT_OFFER_NOTICE]: boat, [ANNOUNCEMENT_NOTICE]: announcement, [STAR_NOTICE]: star });const none = () => false;const DAY = 86_400_000, NOON = new Date(2026, 9, 9, 12).getTime();@@ -38,7 +38,7 @@ it("is one queue: What's new first, then the Simple mode popup, the product-updaexpect(nextNotice(facts(true, true, true, true, true, null, true, true), none), "nothing shows while What's new waits").toBeNull();expect(nextNotice(facts(true, true, true, true, true, true, true, true), id => id === WHATS_NEW_NOTICE)).toBe(SIMPLE_MODE_NOTICE);expect(nextNotice(facts(true, true, true, true, true, false, true, null), none), "nothing shows while the Simple mode popup waits").toBeNull();- expect(NOTICES).toEqual([TEAMS_NOTICE, GROK_MOVE_NOTICE, PHONE_UPDATE_NOTICE, WHATS_NEW_NOTICE, SIMPLE_MODE_NOTICE, UPDATES_CONSENT_NOTICE, TWO_PLACES_NOTICE, PRODUCT_HUNT_NOTICE, CLOUD_INTRO, CLOUD_TRIAL_NOTICE, CLOUD_NOTICE, BOAT_OFFER_NOTICE, ANNOUNCEMENT_NOTICE, STAR_NOTICE]);+ expect(NOTICES).toEqual([TEAMS_NOTICE, GROK_MOVE_NOTICE, PHONE_UPDATE_NOTICE, WHATS_NEW_NOTICE, SIMPLE_MODE_NOTICE, UPDATES_CONSENT_NOTICE, TWO_PLACES_NOTICE, PRODUCT_HUNT_NOTICE, CLOUD_INTRO, CLOUD_TRIAL_NOTICE, CLOUD_NOTICE, TOGETHER_NOTICE, BOAT_OFFER_NOTICE, ANNOUNCEMENT_NOTICE, STAR_NOTICE]);expect(nextNotice(facts(true, true, true, true, true, false, false, false, false, true), none), "bots in two places come before any promotion").toBe(TWO_PLACES_NOTICE);expect(nextNotice(facts(true, true, true, true, true, false, true, false, false, true), none), "after the product-updates question").toBe(UPDATES_CONSENT_NOTICE);expect(nextNotice(facts(true, true, true, true, true, false, false, false, false, null), none), "nothing lower shows while main hasn't answered").toBeNull();@@ -269,3 +269,15 @@ it("a card from the announcements file follows the launch's notice in the same lexpect(nextNotice(remote({ popup: false, trial: true }), none, CLOUD_TRIAL_NOTICE, true), "and follows it there").toBe(ANNOUNCEMENT_NOTICE);expect(nextNotice(remote({ card: false }), popupSeen, WHATS_NEW_NOTICE, true), "none due (one a launch, a sponsor a week): nothing").toBeNull();});++it("the together notice comes after What's new and after every notice to act on, never in the launch What's new took", () => {+ const only = (more: Partial<NoticeFacts>): NoticeFacts => ({ ...facts(false, false, false, false), ...more });+ expect(nextNotice(only({ [TOGETHER_NOTICE]: true }), none)).toBe(TOGETHER_NOTICE);+ expect(nextNotice(only({ [TOGETHER_NOTICE]: true, [WHATS_NEW_NOTICE]: true }), none)).toBe(WHATS_NEW_NOTICE);+ expect(nextNotice(only({ [TOGETHER_NOTICE]: true }), none, WHATS_NEW_NOTICE), "What's new took this launch: it waits for the next").toBeNull();+ expect(nextNotice(only({ [TOGETHER_NOTICE]: true }), none, WHATS_NEW_NOTICE, true), "nor once What's new is closed in it").toBeNull();+ expect(nextNotice(only({ [TOGETHER_NOTICE]: true, [CLOUD_NOTICE]: true }), none)).toBe(CLOUD_NOTICE);+ expect(nextNotice(only({ [TOGETHER_NOTICE]: true, [CLOUD_TRIAL_NOTICE]: true }), none)).toBe(CLOUD_TRIAL_NOTICE);+ expect(nextNotice(only({ [TOGETHER_NOTICE]: true, [BOAT_OFFER_NOTICE]: true, [STAR_NOTICE]: true }), none), "ahead of offers and the star").toBe(TOGETHER_NOTICE);+ expect(nextNotice(only({ [TOGETHER_NOTICE]: null, [BOAT_OFFER_NOTICE]: true }), none), "nothing after it while main has not said").toBeNull();+});diff --git a/src/lib/notices.ts b/src/lib/notices.tsindex 08f4754091..d096ebe6de 100644--- a/src/lib/notices.ts+++ b/src/lib/notices.ts@@ -17,6 +17,8 @@ export const CLOUD_NOTICE = "cloud-notice";export const STAR_NOTICE = "github-star-dismissed";/** Bots on this computer and on another place of the person's (two-places.ts): dismissed per place, by main. */export const TWO_PLACES_NOTICE = "two-places";+/** "This computer and My Cloud together" is on by default now: once per person on this computer (main keeps that). */+export const TOGETHER_NOTICE = "together-default";export const PRODUCT_HUNT_NOTICE = "product-hunt-launch-2026-10";export const PRODUCT_HUNT_URL = "https://www.producthunt.com/products/mausbot";export const PRODUCT_HUNT_UNTIL = Date.UTC(2026, 10, 1);@@ -48,6 +50,7 @@ export const NOTICES = [CLOUD_INTRO,CLOUD_TRIAL_NOTICE,CLOUD_NOTICE,+ TOGETHER_NOTICE,BOAT_OFFER_NOTICE,ANNOUNCEMENT_NOTICE,STAR_NOTICE,diff --git a/src/lib/places-together.ts b/src/lib/places-together.tsindex 9a072dd456..2a8c92a4a9 100644--- a/src/lib/places-together.ts+++ b/src/lib/places-together.ts@@ -17,9 +17,11 @@ export function matchingRows(rows: readonly PlaceBotRow[], query: string): Placeconst bridge = () => (typeof window === "undefined" || window.ogb?.remoteClient?.active ? undefined : window.ogb?.placesTogether);let known: PlacesTogetherState | null = null;+/** Main has answered at least once (or failed to): a notice waiting on it waits no longer. */+let answered = false;let watching = 0, unsubscribe: (() => void) | null = null;const listeners = new Set<() => void>();-const publish = (next: PlacesTogetherState | null) => { known = next; for (const listener of listeners) listener(); };+const publish = (next: PlacesTogetherState | null) => { known = next ?? null; answered = true; for (const listener of listeners) listener(); };const read = () => { void bridge()?.state().then(publish, () => publish(null)); };function subscribe(listener: () => void): () => void {@@ -60,10 +62,40 @@ export function usePlacesTogetherPart<T>(select: (state: PlacesTogetherState | nreturn useSyncExternalStore(subscribe, () => select(known), () => select(null));}-/** Turns the switch, and says what main kept. */-export async function setPlacesTogether(on: boolean): Promise<void> {+/** Turns the switch, and says what main kept. From the notice of the default, turning it on never lends commands. */+export async function setPlacesTogether(on: boolean, from?: "notice"): Promise<void> {const page = bridge();- if (page) publish(await page.set(on));+ if (page) publish(await (from ? page.set(on, from) : page.set(on)));+}++/** Whether the one-time notice that this is on by default is due on this page: null until main first answers, false in a+ * browser, on another place's page or on an older app. */+export function useTogetherNoticeDue(): boolean | null {+ const hasBridge = Boolean(bridge()?.noticeShown);+ const due = usePlacesTogetherPart((state) => (state?.notice === true ? true : answered ? false : null));+ return hasBridge ? due : false;+}++/** The notice was drawn: main turns the default on from now (it never does before). */+export async function togetherNoticeShown(): Promise<void> {+ const page = bridge();+ if (!page?.noticeShown) return;+ await page.noticeShown().catch(() => false);+ read();+}++/** The person closed the notice or used one of its switches: it never shows again. */+export function togetherNoticeDone(): void {+ void bridge()?.noticeDone?.().catch(() => {});+}++/** The notice's own switch for "Let My Cloud's bots run commands on this computer": what main says it is now. */+export async function setTogetherCommands(on: boolean): Promise<boolean> {+ const page = bridge();+ if (!page?.setCommands) throw new Error("unavailable");+ const now = await page.setCommands(on);+ read();+ return now;}/** Opens one of the other place's bots there. */@@ -73,6 +105,9 @@ export function openOtherPlaceBot(id: string): void {export function resetPlacesTogetherForTest(): void {known = null;+ answered = false;+ watching = 0;+ unsubscribe = null;listeners.clear();}diff --git a/src/lib/places.ts b/src/lib/places.tsindex 5ebd42252e..59319b9110 100644--- a/src/lib/places.ts+++ b/src/lib/places.ts@@ -48,6 +48,19 @@ export function usePlaces(): RailState {return state;}+/** Show bots together, from a circle's menu on the window's rail: what main says it is now, or null when it could not change. */+export async function setTogetherFromRail(on: boolean): Promise<boolean | null> {+ const turn = bridge()?.together;+ if (!turn) return null;+ try {+ const now = await turn(on);+ void refreshPlaces();+ return now;+ } catch {+ return null;+ }+}+/** A place's colour, chosen in its menu on the window's rail: main saves it (on the Admin for a Cloud) whatever that* place's server runs, and the circle shows it once the list is read again. */export async function recolorPlace(id: string, swatch: CloudSwatch | null): Promise<PlaceColorOutcome> {diff --git a/src/locales/de.json b/src/locales/de.jsonindex fbf9c863e0..2e028c95be 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -4255,9 +4255,19 @@"devices.computers.pairTitle": "Anderen Computer koppeln","remote.tailscale.needsApproval": "Dieser Computer wartet auf die Genehmigung in Ihrem Tailscale-Netzwerk. Genehmigen Sie ihn in der Tailscale-Admin-Konsole und versuchen Sie es dann erneut.","together.switch.title": "Dieser Computer und Meine Cloud zusammen",- "together.switch.line": "Standardmäßig aus. Die Bots der Cloud und die Bots dieses Computers stehen in einer Liste, und jeder öffnet sich dort, wo er läuft.",- "together.switch.commands": "Wenn du es einschaltest, dürfen die Bots von Meine Cloud auch Befehle auf diesem Computer ausführen; das kannst du über das OpenMausBot-Symbol wieder ausschalten.",+ "together.switch.commandsAll": "Wenn du es hier einschaltest, dürfen die Bots deiner Clouds auch Befehle auf diesem Computer ausführen; das kannst du über das OpenMausBot-Symbol wieder ausschalten.","together.switch.failed": "Das konnte nicht gespeichert werden. Versuch es noch einmal.",+ "together.switch.lineDefault": "Standardmäßig an. Die Bots der Cloud und die Bots dieses Computers stehen in einer Liste, und jeder öffnet sich dort, wo er lebt.",+ "together.notice.title": "Deine Bots sind jetzt in einer Liste",+ "together.notice.body": "Die Bots von Meine Cloud und die Bots dieses Computers stehen jetzt hier zusammen und können einander Arbeit übergeben.",+ "together.notice.list": "Bots zusammen anzeigen",+ "together.notice.commands": "Bots deiner Clouds Befehle auf diesem Computer ausführen lassen",+ "together.notice.commandsOff": "Solange das aus ist, läuft Arbeit, die ein Cloud-Bot einem Bot hier übergibt, ohne Befehle und ohne Computersteuerung und ändert nur Dateien im eigenen Ordner dieser Arbeit.",+ "together.notice.commandsOn": "Die Bots deiner Clouds können jeden Befehl auf diesem Computer als du ausführen. Du kannst das über das OpenMausBot-Symbol ausschalten.",+ "together.notice.off": "Aus: Die Bots von Meine Cloud und die dieses Computers stehen wieder getrennt, wie vorher.",+ "together.notice.done": "Verstanden",+ "together.notice.background": "Die Bots dieses Computers und ihre Routinen laufen jetzt, solange die App geöffnet ist.",+ "rail.together": "Bots zusammen anzeigen","together.mark.workingCloud": "Arbeitet gerade in Meiner Cloud","together.mark.workingComputer": "Arbeitet gerade auf diesem Computer","together.mark.asleep": "Meine Cloud schläft. Wenn du {name} öffnest, wird sie geweckt.",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 8c71e40018..0f63876c71 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -11572,9 +11572,19 @@"together.state.offlineCloud": "My Cloud can't be reached right now.","together.state.offlineComputer": "This computer's bots can't be read right now.","together.switch.title": "This computer and My Cloud together",- "together.switch.line": "Off by default. The Cloud's bots and this computer's bots show in one list, and each opens where it lives.",- "together.switch.commands": "Turning it on also lets My Cloud's bots run commands on this computer; you can turn that off from the OpenMausBot icon.",+ "together.switch.commandsAll": "Turning it on here also lets your Clouds' bots run commands on this computer; you can turn that off from the OpenMausBot icon.","together.switch.failed": "That couldn't be saved. Try again.",+ "together.switch.lineDefault": "On by default. The Cloud's bots and this computer's bots show in one list, and each opens where it lives.",+ "together.notice.title": "Your bots are in one list now",+ "together.notice.body": "My Cloud's bots and this computer's bots now show together here, and they can hand work to each other.",+ "together.notice.list": "Show bots together",+ "together.notice.commands": "Let your Clouds' bots run commands on this computer",+ "together.notice.commandsOff": "While this is off, work a Cloud bot hands to a bot here runs without commands or computer use, and changes files only in that work's own folder.",+ "together.notice.commandsOn": "Your Clouds' bots can run any command on this computer as you. You can turn this off from the OpenMausBot icon.",+ "together.notice.off": "Off: My Cloud's bots and this computer's show apart again, as before.",+ "together.notice.done": "Got it",+ "together.notice.background": "This computer's bots and their routines now run while the app is open.",+ "rail.together": "Show bots together","together.mark.workingCloud": "Working on My Cloud now","together.mark.workingComputer": "Working on this computer now","together.mark.asleep": "My Cloud is asleep. Opening {name} wakes it.",diff --git a/src/locales/es.json b/src/locales/es.jsonindex d65515e7c4..f1491314ca 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -6533,9 +6533,19 @@"devices.computers.pairTitle": "Vincular otro ordenador","remote.tailscale.needsApproval": "Este ordenador espera la aprobación en tu red de Tailscale. Apruébalo en la consola de administración de Tailscale y vuelve a intentarlo.","together.switch.title": "Este equipo y My Cloud juntos",- "together.switch.line": "Desactivado de forma predeterminada. Los bots del Cloud y los de este equipo aparecen en una sola lista, y cada uno se abre donde está.",- "together.switch.commands": "Al activarlo, los bots de My Cloud también pueden ejecutar comandos en este equipo; puedes desactivarlo desde el icono de OpenMausBot.",+ "together.switch.commandsAll": "Al activarlo aquí, los bots de tus Clouds también pueden ejecutar comandos en este equipo; puedes desactivarlo desde el icono de OpenMausBot.","together.switch.failed": "No se pudo guardar. Inténtalo de nuevo.",+ "together.switch.lineDefault": "Activado por defecto. Los bots de la Cloud y los de este equipo aparecen en una sola lista, y cada uno se abre donde vive.",+ "together.notice.title": "Tus bots ya están en una sola lista",+ "together.notice.body": "Los bots de My Cloud y los de este equipo ahora aparecen juntos aquí y pueden pasarse trabajo entre ellos.",+ "together.notice.list": "Mostrar los bots juntos",+ "together.notice.commands": "Permitir que los bots de tus Clouds ejecuten comandos en este equipo",+ "together.notice.commandsOff": "Mientras esto esté desactivado, el trabajo que un bot de la Cloud pasa a un bot de aquí se ejecuta sin comandos ni control del equipo, y solo cambia archivos en la carpeta propia de ese trabajo.",+ "together.notice.commandsOn": "Los bots de tus Clouds pueden ejecutar cualquier comando en este equipo como tú. Puedes desactivarlo desde el icono de OpenMausBot.",+ "together.notice.off": "Desactivado: los bots de My Cloud y los de este equipo vuelven a aparecer por separado, como antes.",+ "together.notice.done": "Entendido",+ "together.notice.background": "Los bots de este equipo y sus rutinas ahora se ejecutan mientras la app está abierta.",+ "rail.together": "Mostrar los bots juntos","together.mark.workingCloud": "Trabajando ahora en My Cloud","together.mark.workingComputer": "Trabajando ahora en este equipo","together.mark.asleep": "My Cloud está en reposo. Al abrir {name} se despierta.",diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex fd561b3d3f..7b03c6c1bf 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -3946,9 +3946,19 @@"devices.computers.pairTitle": "Associer un autre ordinateur","remote.tailscale.needsApproval": "Cet ordinateur attend d'être approuvé sur votre réseau Tailscale. Approuvez-le dans la console d'administration Tailscale, puis réessayez.","together.switch.title": "Cet ordinateur et Mon Cloud ensemble",- "together.switch.line": "Désactivé par défaut. Les bots du Cloud et ceux de cet ordinateur s'affichent dans une seule liste, et chacun s'ouvre là où il se trouve.",- "together.switch.commands": "L'activer permet aussi aux bots de Mon Cloud d'exécuter des commandes sur cet ordinateur ; vous pouvez désactiver cela depuis l'icône OpenMausBot.",+ "together.switch.commandsAll": "L'activer ici permet aussi aux bots de vos Clouds d'exécuter des commandes sur cet ordinateur ; vous pouvez désactiver cela depuis l'icône OpenMausBot.","together.switch.failed": "Impossible d'enregistrer. Réessayez.",+ "together.switch.lineDefault": "Activé par défaut. Les bots du Cloud et ceux de cet ordinateur s'affichent dans une seule liste, et chacun s'ouvre là où il vit.",+ "together.notice.title": "Vos bots sont maintenant dans une seule liste",+ "together.notice.body": "Les bots de Mon Cloud et ceux de cet ordinateur s'affichent désormais ensemble ici, et ils peuvent se passer du travail.",+ "together.notice.list": "Afficher les bots ensemble",+ "together.notice.commands": "Autoriser les bots de vos Clouds à exécuter des commandes sur cet ordinateur",+ "together.notice.commandsOff": "Tant que c'est désactivé, le travail qu'un bot du Cloud confie à un bot d'ici s'exécute sans commandes ni contrôle de l'ordinateur, et ne modifie que les fichiers du dossier propre à ce travail.",+ "together.notice.commandsOn": "Les bots de vos Clouds peuvent exécuter n'importe quelle commande sur cet ordinateur en votre nom. Vous pouvez désactiver cela depuis l'icône OpenMausBot.",+ "together.notice.off": "Désactivé : les bots de Mon Cloud et ceux de cet ordinateur s'affichent de nouveau séparément, comme avant.",+ "together.notice.done": "Compris",+ "together.notice.background": "Les bots de cet ordinateur et leurs routines tournent désormais tant que l'app est ouverte.",+ "rail.together": "Afficher les bots ensemble","together.mark.workingCloud": "Travaille sur Mon Cloud en ce moment","together.mark.workingComputer": "Travaille sur cet ordinateur en ce moment","together.mark.asleep": "Mon Cloud est en veille. Ouvrir {name} le réveille.",diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex e79d63fcaf..bc2d017d32 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -3798,9 +3798,19 @@"devices.computers.pairTitle": "दूसरा कंप्यूटर जोड़ें","remote.tailscale.needsApproval": "यह कंप्यूटर आपके Tailscale नेटवर्क पर मंज़ूरी का इंतज़ार कर रहा है। Tailscale एडमिन कंसोल में इसे मंज़ूर करें, फिर दोबारा कोशिश करें।","together.switch.title": "यही कंप्यूटर और मेरा क्लाउड एक साथ",- "together.switch.line": "डिफ़ॉल्ट रूप से बंद। क्लाउड के बॉट और इस कंप्यूटर के बॉट एक ही सूची में दिखते हैं, और हर बॉट वहीं खुलता है जहाँ वह है।",- "together.switch.commands": "इसे चालू करने पर मेरा क्लाउड के बॉट इस कंप्यूटर पर कमांड भी चला सकते हैं; इसे आप OpenMausBot आइकन से बंद कर सकते हैं।",+ "together.switch.commandsAll": "इसे यहाँ चालू करने पर आपके क्लाउड के बॉट इस कंप्यूटर पर कमांड भी चला सकते हैं; इसे आप OpenMausBot आइकन से बंद कर सकते हैं।","together.switch.failed": "इसे सहेजा नहीं जा सका। फिर से कोशिश करें।",+ "together.switch.lineDefault": "डिफ़ॉल्ट रूप से चालू। क्लाउड के बॉट और इस कंप्यूटर के बॉट एक ही सूची में दिखते हैं, और हर बॉट वहीं खुलता है जहाँ वह रहता है।",+ "together.notice.title": "आपके बॉट अब एक ही सूची में हैं",+ "together.notice.body": "मेरा क्लाउड के बॉट और इस कंप्यूटर के बॉट अब यहाँ एक साथ दिखते हैं, और वे एक-दूसरे को काम सौंप सकते हैं।",+ "together.notice.list": "बॉट एक साथ दिखाएँ",+ "together.notice.commands": "आपके क्लाउड के बॉट को इस कंप्यूटर पर कमांड चलाने दें",+ "together.notice.commandsOff": "जब तक यह बंद है, क्लाउड का कोई बॉट यहाँ के किसी बॉट को जो काम सौंपता है, वह बिना कमांड और बिना कंप्यूटर नियंत्रण के चलता है, और केवल उसी काम के अपने फ़ोल्डर की फ़ाइलें बदलता है।",+ "together.notice.commandsOn": "आपके क्लाउड के बॉट इस कंप्यूटर पर आपकी ओर से कोई भी कमांड चला सकते हैं। इसे आप OpenMausBot आइकन से बंद कर सकते हैं।",+ "together.notice.off": "बंद: मेरा क्लाउड के बॉट और इस कंप्यूटर के बॉट फिर से अलग-अलग दिखते हैं, पहले की तरह।",+ "together.notice.done": "समझ गया",+ "together.notice.background": "इस कंप्यूटर के बॉट और उनके रूटीन अब ऐप खुला रहने तक चलते हैं।",+ "rail.together": "बॉट एक साथ दिखाएँ","together.mark.workingCloud": "अभी मेरे क्लाउड पर काम कर रहा है","together.mark.workingComputer": "अभी इस कंप्यूटर पर काम कर रहा है","together.mark.asleep": "मेरा क्लाउड सो रहा है। {name} खोलने पर यह जाग जाएगा।",diff --git a/src/locales/it.json b/src/locales/it.jsonindex 66aae3e672..6ba0e6a3e0 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -11400,9 +11400,19 @@"together.state.offlineCloud": "La mia nuvola non può essere raggiunta in questo momento.","together.state.offlineComputer": "I bot del computer non possono essere letti in questo momento.","together.switch.title": "Questo computer e Il mio Cloud insieme",- "together.switch.line": "Disattivato per impostazione predefinita. I bot del Cloud e quelli di questo computer compaiono in un unico elenco, e ognuno si apre dove si trova.",- "together.switch.commands": "Attivandolo, i bot di Il mio Cloud possono anche eseguire comandi su questo computer; puoi disattivarlo dall'icona di OpenMausBot.",+ "together.switch.commandsAll": "Attivandolo qui, i bot dei tuoi Cloud possono anche eseguire comandi su questo computer; puoi disattivarlo dall'icona di OpenMausBot.","together.switch.failed": "Non è stato possibile salvare. Riprova.",+ "together.switch.lineDefault": "Attivo per impostazione predefinita. I bot del Cloud e quelli di questo computer compaiono in un'unica lista, e ognuno si apre dove vive.",+ "together.notice.title": "I tuoi bot ora sono in un'unica lista",+ "together.notice.body": "I bot di Il mio Cloud e quelli di questo computer ora compaiono insieme qui e possono passarsi il lavoro.",+ "together.notice.list": "Mostra i bot insieme",+ "together.notice.commands": "Consenti ai bot dei tuoi Cloud di eseguire comandi su questo computer",+ "together.notice.commandsOff": "Finché è disattivato, il lavoro che un bot del Cloud passa a un bot di qui viene eseguito senza comandi né controllo del computer, e modifica solo i file nella cartella propria di quel lavoro.",+ "together.notice.commandsOn": "I bot dei tuoi Cloud possono eseguire qualsiasi comando su questo computer come te. Puoi disattivarlo dall'icona di OpenMausBot.",+ "together.notice.off": "Disattivato: i bot di Il mio Cloud e quelli di questo computer tornano separati, come prima.",+ "together.notice.done": "Ho capito",+ "together.notice.background": "I bot di questo computer e le loro routine ora girano finché l'app è aperta.",+ "rail.together": "Mostra i bot insieme","together.mark.workingCloud": "Al lavoro sul mio Cloud ora","together.mark.workingComputer": "Al lavoro su questo computer ora","together.mark.asleep": "Il mio Cloud è in sospensione. Aprire {name} lo riattiva.",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 50448b8b05..855af981ef 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -8073,9 +8073,19 @@"devices.computers.pairTitle": "別のコンピュータをペアリング","remote.tailscale.needsApproval": "このコンピューターは Tailscale ネットワークでの承認を待っています。Tailscale の管理コンソールで承認してから、もう一度お試しください。","together.switch.title": "このコンピューターと My Cloud をまとめる",- "together.switch.line": "既定ではオフです。Cloud のボットとこのコンピューターのボットを 1 つの一覧に表示し、それぞれがある場所で開きます。",- "together.switch.commands": "オンにすると、My Cloud のボットがこのコンピューターでコマンドも実行できるようになります。OpenMausBot アイコンからオフにできます。",+ "together.switch.commandsAll": "ここでオンにすると、Cloud のボットがこのコンピューターでコマンドも実行できるようになります。OpenMausBot アイコンからオフにできます。","together.switch.failed": "保存できませんでした。もう一度お試しください。",+ "together.switch.lineDefault": "既定でオンです。Cloud のボットとこのコンピューターのボットが 1 つのリストに並び、それぞれ自分がいる場所で開きます。",+ "together.notice.title": "ボットが 1 つのリストにまとまりました",+ "together.notice.body": "My Cloud のボットとこのコンピューターのボットがここに一緒に表示され、互いに作業を引き継げます。",+ "together.notice.list": "ボットをまとめて表示",+ "together.notice.commands": "Cloud のボットにこのコンピューターでのコマンド実行を許可",+ "together.notice.commandsOff": "オフの間、Cloud のボットがここのボットに引き継いだ作業は、コマンドもコンピューター操作も使わずに実行され、その作業専用のフォルダー内のファイルだけを変更します。",+ "together.notice.commandsOn": "Cloud のボットは、あなたとしてこのコンピューターで任意のコマンドを実行できます。OpenMausBot アイコンからオフにできます。",+ "together.notice.off": "オフ: My Cloud のボットとこのコンピューターのボットは、以前のように別々に表示されます。",+ "together.notice.done": "OK",+ "together.notice.background": "このコンピューターのボットとそのルーティンは、アプリを開いている間動くようになりました。",+ "rail.together": "ボットをまとめて表示","together.mark.workingCloud": "現在 My Cloud で作業中","together.mark.workingComputer": "現在このコンピューターで作業中","together.mark.asleep": "My Cloud はスリープ中です。{name} を開くと起動します。",diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex 6e24f4d4c1..0f86a9372e 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -7764,9 +7764,19 @@"devices.computers.pairTitle": "다른 컴퓨터 페어링","remote.tailscale.needsApproval": "이 컴퓨터는 Tailscale 네트워크에서 승인을 기다리고 있습니다. Tailscale 관리 콘솔에서 승인한 다음 다시 시도하세요.","together.switch.title": "이 컴퓨터와 내 클라우드 함께 보기",- "together.switch.line": "기본값은 꺼짐입니다. 클라우드의 봇과 이 컴퓨터의 봇이 하나의 목록에 표시되며, 각 봇은 자기가 있는 곳에서 열립니다.",- "together.switch.commands": "켜면 내 클라우드의 봇이 이 컴퓨터에서 명령도 실행할 수 있습니다. OpenMausBot 아이콘에서 끌 수 있습니다.",+ "together.switch.commandsAll": "여기서 켜면 내 클라우드들의 봇이 이 컴퓨터에서 명령도 실행할 수 있습니다. OpenMausBot 아이콘에서 끌 수 있습니다.","together.switch.failed": "저장하지 못했습니다. 다시 시도하세요.",+ "together.switch.lineDefault": "기본으로 켜져 있습니다. 클라우드의 봇과 이 컴퓨터의 봇이 한 목록에 보이고, 각 봇은 자기가 있는 곳에서 열립니다.",+ "together.notice.title": "이제 봇이 한 목록에 있습니다",+ "together.notice.body": "내 클라우드의 봇과 이 컴퓨터의 봇이 이제 여기에 함께 보이고, 서로 작업을 넘길 수 있습니다.",+ "together.notice.list": "봇 함께 보기",+ "together.notice.commands": "내 클라우드들의 봇이 이 컴퓨터에서 명령을 실행하도록 허용",+ "together.notice.commandsOff": "꺼져 있는 동안 클라우드 봇이 이곳의 봇에 넘긴 작업은 명령이나 컴퓨터 제어 없이 실행되며, 그 작업 전용 폴더의 파일만 바꿉니다.",+ "together.notice.commandsOn": "내 클라우드들의 봇이 이 컴퓨터에서 나로서 어떤 명령이든 실행할 수 있습니다. OpenMausBot 아이콘에서 끌 수 있습니다.",+ "together.notice.off": "꺼짐: 내 클라우드의 봇과 이 컴퓨터의 봇이 예전처럼 다시 따로 보입니다.",+ "together.notice.done": "확인",+ "together.notice.background": "이제 이 컴퓨터의 봇과 그 루틴이 앱이 열려 있는 동안 실행됩니다.",+ "rail.together": "봇 함께 보기","together.mark.workingCloud": "지금 내 클라우드에서 작업 중","together.mark.workingComputer": "지금 이 컴퓨터에서 작업 중","together.mark.asleep": "내 클라우드가 절전 중입니다. {name}을(를) 열면 깨어납니다.",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 99aa43a77c..7dbceaed5e 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -7232,9 +7232,19 @@"devices.computers.pairTitle": "Sparuj inny komputer","remote.tailscale.needsApproval": "Ten komputer czeka na zatwierdzenie w Twojej sieci Tailscale. Zatwierdź go w konsoli administracyjnej Tailscale, a potem spróbuj ponownie.","together.switch.title": "Ten komputer i My Cloud razem",- "together.switch.line": "Domyślnie wyłączone. Boty z Cloud i boty z tego komputera są na jednej liście, a każdy otwiera się tam, gdzie działa.",- "together.switch.commands": "Włączenie pozwala też botom z My Cloud uruchamiać polecenia na tym komputerze; możesz to wyłączyć w ikonie OpenMausBot.",+ "together.switch.commandsAll": "Włączenie tutaj pozwala też botom z Twoich Cloud uruchamiać polecenia na tym komputerze; możesz to wyłączyć w ikonie OpenMausBot.","together.switch.failed": "Nie udało się zapisać. Spróbuj ponownie.",+ "together.switch.lineDefault": "Domyślnie włączone. Boty z Cloud i boty z tego komputera są na jednej liście, a każdy otwiera się tam, gdzie mieszka.",+ "together.notice.title": "Twoje boty są teraz na jednej liście",+ "together.notice.body": "Boty z My Cloud i boty z tego komputera są teraz tutaj razem i mogą przekazywać sobie pracę.",+ "together.notice.list": "Pokaż boty razem",+ "together.notice.commands": "Pozwól botom z Twoich Cloud uruchamiać polecenia na tym komputerze",+ "together.notice.commandsOff": "Dopóki to jest wyłączone, praca, którą bot z Cloud przekazuje botowi tutaj, działa bez poleceń i bez sterowania komputerem, a zmienia tylko pliki we własnym folderze tej pracy.",+ "together.notice.commandsOn": "Boty z Twoich Cloud mogą uruchamiać dowolne polecenia na tym komputerze jako Ty. Możesz to wyłączyć w ikonie OpenMausBot.",+ "together.notice.off": "Wyłączone: boty z My Cloud i z tego komputera znów są osobno, jak wcześniej.",+ "together.notice.done": "Rozumiem",+ "together.notice.background": "Boty z tego komputera i ich rutyny działają teraz, dopóki aplikacja jest otwarta.",+ "rail.together": "Pokaż boty razem","together.mark.workingCloud": "Pracuje teraz w My Cloud","together.mark.workingComputer": "Pracuje teraz na tym komputerze","together.mark.asleep": "My Cloud śpi. Otwarcie {name} go wybudzi.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 1d0f3fb71f..b8d7a940c6 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -11545,9 +11545,19 @@"together.state.offlineCloud": "Não é possível acessar o My Cloud agora.","together.state.offlineComputer": "Não é possível ler os bots deste computador agora.","together.switch.title": "Este computador e o My Cloud juntos",- "together.switch.line": "Desativado por padrão. Os bots do Cloud e os deste computador aparecem em uma só lista, e cada um abre onde está.",- "together.switch.commands": "Ao ativar, os bots do My Cloud também podem executar comandos neste computador; você pode desativar isso pelo ícone do OpenMausBot.",+ "together.switch.commandsAll": "Ao ativar aqui, os bots das suas Clouds também podem executar comandos neste computador; você pode desativar isso pelo ícone do OpenMausBot.","together.switch.failed": "Não foi possível salvar. Tente de novo.",+ "together.switch.lineDefault": "Ativado por padrão. Os bots do Cloud e os deste computador aparecem em uma só lista, e cada um abre onde está.",+ "together.notice.title": "Seus bots agora estão em uma só lista",+ "together.notice.body": "Os bots do My Cloud e os deste computador agora aparecem juntos aqui e podem passar trabalho uns para os outros.",+ "together.notice.list": "Mostrar os bots juntos",+ "together.notice.commands": "Permitir que os bots das suas Clouds executem comandos neste computador",+ "together.notice.commandsOff": "Enquanto isso estiver desativado, o trabalho que um bot da Cloud passa para um bot daqui roda sem comandos nem uso do computador, e só altera arquivos na pasta desse trabalho.",+ "together.notice.commandsOn": "Os bots das suas Clouds podem executar qualquer comando neste computador como você. Você pode desativar isso pelo ícone do OpenMausBot.",+ "together.notice.off": "Desativado: os bots do My Cloud e os deste computador aparecem separados de novo, como antes.",+ "together.notice.done": "Entendi",+ "together.notice.background": "Os bots deste computador e as rotinas deles agora rodam enquanto o app está aberto.",+ "rail.together": "Mostrar os bots juntos","together.mark.workingCloud": "Trabalhando no My Cloud agora","together.mark.workingComputer": "Trabalhando neste computador agora","together.mark.asleep": "O My Cloud está em repouso. Abrir {name} o ativa.",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex 87b83ab71b..2313b6800a 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -7286,9 +7286,19 @@"devices.computers.pairTitle": "Подключить другой компьютер","remote.tailscale.needsApproval": "Этот компьютер ждёт одобрения в вашей сети Tailscale. Одобрите его в консоли администратора Tailscale, затем попробуйте снова.","together.switch.title": "Этот компьютер и Моё облако вместе",- "together.switch.line": "По умолчанию выключено. Боты из облака и боты этого компьютера показаны в одном списке, и каждый открывается там, где он находится.",- "together.switch.commands": "Если включить, боты из «Моё облако» смогут также выполнять команды на этом компьютере; это можно выключить через значок OpenMausBot.",+ "together.switch.commandsAll": "Если включить здесь, боты ваших облаков смогут также выполнять команды на этом компьютере; это можно выключить через значок OpenMausBot.","together.switch.failed": "Не удалось сохранить. Попробуйте ещё раз.",+ "together.switch.lineDefault": "Включено по умолчанию. Боты облака и боты этого компьютера показываются одним списком, и каждый открывается там, где живёт.",+ "together.notice.title": "Ваши боты теперь в одном списке",+ "together.notice.body": "Боты из «Моё облако» и боты этого компьютера теперь показываются здесь вместе и могут передавать друг другу работу.",+ "together.notice.list": "Показывать ботов вместе",+ "together.notice.commands": "Разрешить ботам ваших облаков выполнять команды на этом компьютере",+ "together.notice.commandsOff": "Пока это выключено, работа, которую бот облака передаёт боту здесь, выполняется без команд и без управления компьютером и меняет файлы только в собственной папке этой работы.",+ "together.notice.commandsOn": "Боты ваших облаков могут выполнять любые команды на этом компьютере от вашего имени. Это можно выключить через значок OpenMausBot.",+ "together.notice.off": "Выключено: боты из «Моё облако» и боты этого компьютера снова показываются отдельно, как раньше.",+ "together.notice.done": "Понятно",+ "together.notice.background": "Боты этого компьютера и их распорядки теперь работают, пока приложение открыто.",+ "rail.together": "Показывать ботов вместе","together.mark.workingCloud": "Сейчас работает в Моём облаке","together.mark.workingComputer": "Сейчас работает на этом компьютере","together.mark.asleep": "Моё облако спит. Если открыть {name}, оно проснётся.",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex cd1fe48616..4dd9f6496a 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -6028,9 +6028,19 @@"devices.computers.pairTitle": "Başka bir bilgisayar eşle","remote.tailscale.needsApproval": "Bu bilgisayar Tailscale ağınızda onay bekliyor. Tailscale yönetici konsolunda onaylayın, ardından tekrar deneyin.","together.switch.title": "Bu bilgisayar ve Cloud'um birlikte",- "together.switch.line": "Varsayılan olarak kapalı. Cloud'daki botlar ile bu bilgisayardaki botlar tek listede görünür ve her biri bulunduğu yerde açılır.",- "together.switch.commands": "Açtığınızda Cloud'um içindeki botlar bu bilgisayarda komut da çalıştırabilir; bunu OpenMausBot simgesinden kapatabilirsiniz.",+ "together.switch.commandsAll": "Burada açtığınızda Cloud'larınızın botları bu bilgisayarda komut da çalıştırabilir; bunu OpenMausBot simgesinden kapatabilirsiniz.","together.switch.failed": "Kaydedilemedi. Yeniden deneyin.",+ "together.switch.lineDefault": "Varsayılan olarak açık. Cloud'un botları ve bu bilgisayarın botları tek listede görünür ve her biri yaşadığı yerde açılır.",+ "together.notice.title": "Botlarınız artık tek listede",+ "together.notice.body": "Cloud'um botları ve bu bilgisayarın botları artık burada birlikte görünür ve birbirlerine iş devredebilir.",+ "together.notice.list": "Botları birlikte göster",+ "together.notice.commands": "Cloud'larınızın botlarının bu bilgisayarda komut çalıştırmasına izin ver",+ "together.notice.commandsOff": "Bu kapalıyken, bir Cloud botunun buradaki bir bota devrettiği iş komut ve bilgisayar kontrolü olmadan çalışır ve yalnızca o işin kendi klasöründeki dosyaları değiştirir.",+ "together.notice.commandsOn": "Cloud'larınızın botları bu bilgisayarda sizin adınıza her komutu çalıştırabilir. Bunu OpenMausBot simgesinden kapatabilirsiniz.",+ "together.notice.off": "Kapalı: Cloud'um botları ve bu bilgisayarın botları eskisi gibi yine ayrı görünür.",+ "together.notice.done": "Anladım",+ "together.notice.background": "Bu bilgisayarın botları ve rutinleri artık uygulama açıkken çalışıyor.",+ "rail.together": "Botları birlikte göster","together.mark.workingCloud": "Şu anda Cloud'umda çalışıyor","together.mark.workingComputer": "Şu anda bu bilgisayarda çalışıyor","together.mark.asleep": "Cloud'um uykuda. {name} açıldığında uyanır.",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex 43a49cdd79..e618db3bd1 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -4215,9 +4215,19 @@"devices.computers.pairTitle": "Підключити інший комп’ютер","remote.tailscale.needsApproval": "Цей комп’ютер чекає на схвалення у вашій мережі Tailscale. Схваліть його в консолі адміністратора Tailscale, потім спробуйте ще раз.","together.switch.title": "Цей комп'ютер і Моя хмара разом",- "together.switch.line": "Типово вимкнено. Боти з хмари й боти цього комп'ютера показані в одному списку, і кожен відкривається там, де він є.",- "together.switch.commands": "Якщо ввімкнути, боти з «Моя хмара» зможуть також виконувати команди на цьому комп'ютері; це можна вимкнути через значок OpenMausBot.",+ "together.switch.commandsAll": "Якщо ввімкнути тут, боти ваших хмар зможуть також виконувати команди на цьому комп'ютері; це можна вимкнути через значок OpenMausBot.","together.switch.failed": "Не вдалося зберегти. Спробуйте ще раз.",+ "together.switch.lineDefault": "Увімкнено за замовчуванням. Боти хмари й боти цього комп'ютера показуються одним списком, і кожен відкривається там, де живе.",+ "together.notice.title": "Ваші боти тепер в одному списку",+ "together.notice.body": "Боти з «Моя хмара» і боти цього комп'ютера тепер показуються тут разом і можуть передавати одне одному роботу.",+ "together.notice.list": "Показувати ботів разом",+ "together.notice.commands": "Дозволити ботам ваших хмар виконувати команди на цьому комп'ютері",+ "together.notice.commandsOff": "Поки це вимкнено, робота, яку бот хмари передає боту тут, виконується без команд і без керування комп'ютером і змінює файли лише у власній папці цієї роботи.",+ "together.notice.commandsOn": "Боти ваших хмар можуть виконувати будь-які команди на цьому комп'ютері від вашого імені. Це можна вимкнути через значок OpenMausBot.",+ "together.notice.off": "Вимкнено: боти з «Моя хмара» і боти цього комп'ютера знову показуються окремо, як раніше.",+ "together.notice.done": "Зрозуміло",+ "together.notice.background": "Боти цього комп'ютера та їхні розпорядки тепер працюють, поки застосунок відкритий.",+ "rail.together": "Показувати ботів разом","together.mark.workingCloud": "Зараз працює в Моїй хмарі","together.mark.workingComputer": "Зараз працює на цьому комп'ютері","together.mark.asleep": "Моя хмара спить. Відкрийте {name}, і вона прокинеться.",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex d61d01e84b..62d6abf5b4 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -6028,9 +6028,19 @@"devices.computers.pairTitle": "Ghép nối máy tính khác","remote.tailscale.needsApproval": "Máy tính này đang chờ được phê duyệt trên mạng Tailscale của bạn. Hãy phê duyệt trong bảng điều khiển quản trị Tailscale, rồi thử lại.","together.switch.title": "Máy tính này và My Cloud cùng nhau",- "together.switch.line": "Mặc định là tắt. Bot trên Cloud và bot trên máy tính này hiện trong một danh sách, và mỗi bot mở ở nơi nó đang ở.",- "together.switch.commands": "Khi bật, bot trên My Cloud cũng có thể chạy lệnh trên máy tính này; bạn có thể tắt việc đó từ biểu tượng OpenMausBot.",+ "together.switch.commandsAll": "Khi bật ở đây, bot trên các Cloud của bạn cũng có thể chạy lệnh trên máy tính này; bạn có thể tắt việc đó từ biểu tượng OpenMausBot.","together.switch.failed": "Không lưu được. Hãy thử lại.",+ "together.switch.lineDefault": "Bật theo mặc định. Bot trên Cloud và bot trên máy tính này hiện trong một danh sách, và mỗi bot mở ở nơi nó sống.",+ "together.notice.title": "Các bot của bạn giờ đã ở trong một danh sách",+ "together.notice.body": "Bot trên My Cloud và bot trên máy tính này giờ hiện cùng nhau ở đây, và chúng có thể giao việc cho nhau.",+ "together.notice.list": "Hiện các bot cùng nhau",+ "together.notice.commands": "Cho phép bot trên các Cloud của bạn chạy lệnh trên máy tính này",+ "together.notice.commandsOff": "Khi tắt, công việc mà một bot trên Cloud giao cho một bot ở đây sẽ chạy mà không có lệnh hay điều khiển máy tính, và chỉ thay đổi tệp trong thư mục riêng của công việc đó.",+ "together.notice.commandsOn": "Bot trên các Cloud của bạn có thể chạy bất kỳ lệnh nào trên máy tính này với tư cách là bạn. Bạn có thể tắt việc đó từ biểu tượng OpenMausBot.",+ "together.notice.off": "Tắt: bot trên My Cloud và bot trên máy tính này lại hiện riêng, như trước.",+ "together.notice.done": "Đã hiểu",+ "together.notice.background": "Các bot của máy tính này và các thói quen của chúng giờ chạy khi ứng dụng đang mở.",+ "rail.together": "Hiện các bot cùng nhau","together.mark.workingCloud": "Đang làm việc trên My Cloud","together.mark.workingComputer": "Đang làm việc trên máy tính này","together.mark.asleep": "My Cloud đang ngủ. Mở {name} sẽ đánh thức nó.",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 5de5a281b9..3c9813e678 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -10367,9 +10367,19 @@"devices.computers.pairTitle": "配對另一台電腦","remote.tailscale.needsApproval": "這台電腦正在等待你的 Tailscale 網路核准。請在 Tailscale 管理主控台中核准它,然後再試一次。","together.switch.title": "這台電腦和 My Cloud 合在一起",- "together.switch.line": "預設為關閉。Cloud 上的機器人和這台電腦上的機器人顯示在同一個清單中,各自在所在的位置開啟。",- "together.switch.commands": "開啟後,My Cloud 上的機器人也能在這台電腦上執行指令;你可以從 OpenMausBot 圖示關閉這項權限。",+ "together.switch.commandsAll": "在這裡開啟後,你的 Cloud 上的機器人也能在這台電腦上執行指令;你可以從 OpenMausBot 圖示關閉這項權限。","together.switch.failed": "無法儲存。請再試一次。",+ "together.switch.lineDefault": "預設開啟。Cloud 上的機器人和這台電腦上的機器人顯示在同一個清單裡,每個機器人都在它所在的地方開啟。",+ "together.notice.title": "你的機器人現在在同一個清單裡",+ "together.notice.body": "My Cloud 上的機器人和這台電腦上的機器人現在一起顯示在這裡,而且可以互相交接工作。",+ "together.notice.list": "一起顯示機器人",+ "together.notice.commands": "允許你的 Cloud 上的機器人在這台電腦上執行指令",+ "together.notice.commandsOff": "關閉時,Cloud 上的機器人交給這裡機器人的工作不會執行指令或控制電腦,只會更改該工作自己資料夾裡的檔案。",+ "together.notice.commandsOn": "你的 Cloud 上的機器人可以用你的身分在這台電腦上執行任何指令。你可以從 OpenMausBot 圖示關閉這項權限。",+ "together.notice.off": "已關閉:My Cloud 上的機器人和這台電腦上的機器人重新分開顯示,和以前一樣。",+ "together.notice.done": "知道了",+ "together.notice.background": "這台電腦上的機器人及其例行任務現在會在應用程式開啟時執行。",+ "rail.together": "一起顯示機器人","together.mark.workingCloud": "正在 My Cloud 上工作","together.mark.workingComputer": "正在這台電腦上工作","together.mark.asleep": "My Cloud 正在休眠。開啟 {name} 會喚醒它。",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex d7d800aab6..ea8658d00c 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -10250,9 +10250,19 @@"together.state.offlineCloud": "现在无法连接 My Cloud。","together.state.offlineComputer": "现在无法读取这台电脑上的机器人。","together.switch.title": "这台电脑和 My Cloud 合在一起",- "together.switch.line": "默认关闭。Cloud 上的机器人和这台电脑上的机器人显示在同一个列表中,各自在所在的位置打开。",- "together.switch.commands": "开启后,My Cloud 上的机器人也能在这台电脑上运行命令;你可以从 OpenMausBot 图标关闭此权限。",+ "together.switch.commandsAll": "在这里开启后,你的 Cloud 上的机器人也能在这台电脑上运行命令;你可以从 OpenMausBot 图标关闭此权限。","together.switch.failed": "未能保存。请重试。",+ "together.switch.lineDefault": "默认开启。Cloud 上的机器人和这台电脑上的机器人显示在同一个列表里,每个机器人都在它所在的地方打开。",+ "together.notice.title": "你的机器人现在在同一个列表里",+ "together.notice.body": "My Cloud 上的机器人和这台电脑上的机器人现在一起显示在这里,并且可以互相交接工作。",+ "together.notice.list": "一起显示机器人",+ "together.notice.commands": "允许你的 Cloud 上的机器人在这台电脑上运行命令",+ "together.notice.commandsOff": "关闭时,Cloud 上的机器人交给这里机器人的工作不会运行命令或控制电脑,只会更改该工作自己文件夹里的文件。",+ "together.notice.commandsOn": "你的 Cloud 上的机器人可以以你的身份在这台电脑上运行任何命令。你可以从 OpenMausBot 图标关闭此权限。",+ "together.notice.off": "已关闭:My Cloud 上的机器人和这台电脑上的机器人重新分开显示,和以前一样。",+ "together.notice.done": "知道了",+ "together.notice.background": "这台电脑上的机器人及其例行任务现在会在应用打开时运行。",+ "rail.together": "一起显示机器人","together.mark.workingCloud": "正在 My Cloud 上工作","together.mark.workingComputer": "正在这台电脑上工作","together.mark.asleep": "My Cloud 正在休眠。打开 {name} 会唤醒它。",diff --git a/src/together-preview.tsx b/src/together-preview.tsxnew file mode 100644index 0000000000..b9d18fee0b--- /dev/null+++ b/src/together-preview.tsx@@ -0,0 +1,98 @@+// Dev-only gallery of "This computer and My Cloud together" on by default, served at /together-preview.html; not in the+// packaged app. It mounts the real rail, sidebar and notice over fake bridges, with no server behind them.+// ?view=before|after|notice|notice-cloud-home|notice-off|rail-before|rail-after|rail-cloud-home&mode=simple|advanced&skin=midnight|daylight&lang=pt-br+import { StrictMode, useEffect } from "react";+import { createRoot } from "react-dom/client";+import type { RailState } from "../electron/cloud-rail.mjs";+import type { PlaceBotRow, PlacesTogetherState } from "../electron/places-together.mjs";+import { PlacesRail } from "@/components/PlacesRail";+import { Sidebar } from "@/components/Sidebar";+import { TogetherNotice } from "@/components/TogetherNotice";+import { loadLocale } from "@/lib/i18n";+import { setAdvancedMode } from "@/lib/interface-mode";+import { applySkinChoice, SKIN_IDS, type SkinId } from "@/lib/skins";+import { initialState, StoreContext, type AppState, type Bot, type Message } from "@/state/store";+import "./styles.css";++const params = new URLSearchParams(location.search);+const view = params.get("view") ?? "notice";+const skin = params.get("skin") ?? "midnight";+setAdvancedMode(params.get("mode") === "advanced");+applySkinChoice(SKIN_IDS.includes(skin as SkinId) ? (skin as SkinId) : "midnight");+await loadLocale(params.get("lang") ?? "en");++const AT = Date.now() - 40 * 60_000;+const said = (id: string, minutes: number, text: string): Message => ({ id, at: AT + minutes * 60_000, role: "bot", kind: "text", text }) as Message;+const here = (id: string, name: string, color: string, title: string, line: string, over: Partial<Bot> = {}): Bot => ({+ title: "", description: "", notifications: true, unread: false, modelSelection: { instanceId: "claude", model: "claude-opus-5-5" },+ id, name, color, threadId: `${id}-main`, mainThreadId: `${id}-main`, busy: false, activity: "idle",+ tasks: [{ threadId: `${id}-main`, title, createdAt: AT, updatedAt: AT + 5 * 60_000 }], messages: [said(`${id}-1`, 5, line)], ...over,+}) as Bot;+const bots: Bot[] = [+ here("mausbot", "MausBot", "violet", "Today", "Your week is planned; three things need you.", { chiefOfStaff: true } as Partial<Bot>),+ here("ledger", "Ledger", "orange", "Invoices", "The March invoices are filed in your Drive."),+ here("git", "Git Tasks", "teal", "Release notes", "Release notes drafted from the last 40 commits."),+];+const row = (id: string, name: string, color: string, over: Partial<PlaceBotRow> = {}): PlaceBotRow => ({ home: "cloud", id, threadId: `${id}-main`, name, color, lastAt: AT + 20 * 60_000, ...over });+const cloudRows: PlaceBotRow[] = [+ row("scout", "Scout", "blue", { preview: "Found four flats under budget near the park.", chat: "Flat hunt" }),+ row("atlas", "Atlas", "green", { preview: "Booked: the 9:40 train to Leeds on Friday.", chat: "Trip", unread: true }),+];+const joined = !["before", "rail-before"].includes(view) && view !== "notice-off";+const together: PlacesTogetherState = joined+ ? { v: 1, available: true, on: true, here: "computer", other: { home: "cloud", state: "ready", bots: cloudRows, newBot: true }, ...(view.startsWith("notice") ? { notice: true, commands: false, ...(view === "notice-cloud-home" ? { profileHome: true as const } : {}) } : {}) }+ : { v: 1, available: true, on: false, here: "computer", other: null, ...(view === "notice-off" ? { notice: true, commands: false } : {}) };++const cloudHome = view === "rail-cloud-home";+const rail: RailState = { places: cloudHome ? [+ { id: "profile:default", name: "This computer", color: null, kind: "computer", profile: "default", opens: true, active: true, paint: { swatch: null }, together: true },+ { id: "home", name: "My Cloud", color: "purple", kind: "cloud", opens: true, paint: { swatch: "violet" }, together: true },+] : [+ { id: "local", name: "This computer", color: null, kind: "computer", opens: true, active: true, paint: { swatch: null }, ...(view === "rail-before" ? {} : { together: joined }) },+ { id: "home", name: "My Cloud", color: "purple", kind: "cloud", opens: true, paint: { swatch: "violet" }, ...(view === "rail-before" ? {} : { together: joined }) },+], add: { cloud: true, link: true, address: false } };++let state = together;+Object.assign(window, { ogb: {+ platform: "darwin",+ placesTogether: {+ state: async () => state, set: async (on: boolean) => (state = { ...state, on, other: on ? together.other : null }), open: async () => true, onChanged: () => () => {},+ newBotChoice: async () => null, newBot: async () => true, onNewBot: () => () => {}, noticeShown: async () => true, noticeDone: async () => {}, setCommands: async (on: boolean) => on,+ },+ workspaces: { places: async () => rail, state: async () => ({ local: true, name: "This computer" }), menu: async () => {}, open: async () => {}, add: async () => {}, together: async (on: boolean) => on, onChanged: () => () => {} },+ rail: { expand: async () => {}, onSkin: () => () => {} },+} });++function Gallery() {+ const state: AppState = { ...initialState, bots, selectedId: "ledger", connected: true, config: { ...initialState.config, profile: { name: "Sam", email: "", aboutMe: "" } } as AppState["config"] };+ const value = { state, dispatch: () => {}, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };+ useEffect(() => {+ if (!view.startsWith("rail-")) return;+ const id = cloudHome ? "profile:default" : "local";+ const timer = setInterval(() => {+ const circle = document.querySelector(`[data-rail-place="${id}"]`);+ if (!circle || document.querySelector("[data-rail-menu]")) return;+ circle.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }));+ }, 100);+ return () => clearInterval(timer);+ }, []);+ return (+ <StoreContext.Provider value={value}>+ <div className="flex h-dvh w-full overflow-hidden bg-app text-ink" data-preview={view}>+ <div className="relative flex w-[44px] shrink-0 flex-col items-center border-e border-hairline/60 bg-sidebar pt-3 max-sm:hidden"><PlacesRail chrome /></div>+ <div className="flex h-full w-[280px] shrink-0 max-sm:w-full"><Sidebar open onClose={() => {}} /></div>+ <div className="min-w-0 flex-1 bg-canvas max-sm:hidden" />+ {view.startsWith("notice") && <TogetherNotice onClose={() => {}} />}+ </div>+ </StoreContext.Provider>+ );+}++const realFetch = window.fetch.bind(window);+window.fetch = async (input, init) => {+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;+ if (!new URL(url, location.href).pathname.startsWith("/api/")) return realFetch(input, init);+ return new Response("{}", { status: 200, headers: { "content-type": "application/json" } });+};++createRoot(document.getElementById("root")!).render(<StrictMode><Gallery /></StrictMode>);diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.tsindex fc8d511c89..62553af589 100644--- a/src/types/ogb.d.ts+++ b/src/types/ogb.d.ts@@ -231,6 +231,8 @@ const __APP_VERSION__: string;makeHome?: (id: string) => Promise<{ started: true }>;/** The ids of the servers main offers Make … my home for now (none once a move is done). Absent on an older app. */homeOffers?: () => Promise<string[]>;+ /** Show bots together (This computer and My Cloud together), from a circle's menu on the rail's own page: whether it is on now. */+ together?: (on: boolean) => Promise<boolean>;/** Main's word that the places or the sign-in changed: read them again. */onChanged?: (callback: () => void) => () => void;/** A workspace of this computer's own (main refuses any page but the rail's and this computer's own): a new one,diff --git a/together-preview.html b/together-preview.htmlnew file mode 100644index 0000000000..00f1f1775e--- /dev/null+++ b/together-preview.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Together Preview</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/together-preview.tsx"></script>+ </body>+</html>