Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
One list: a My Cloud bot opens in this window, through this computer's server
milind-soni551141570c1c
diff --git a/electron/main.mjs b/electron/main.mjsindex 598ed71d89..4b03f4f5b0 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, START_QUIET_MS, togetherComputer, togetherPrefFile } from "./places-together.mjs"; import { createBotLinkMain } from "./bot-link-main.mjs"; import { createTogetherBackground } from "./together-background.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 { createPlaceChatMain } from "./place-chat-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";@@ -2596,7 +2596,7 @@ 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 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 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, inPlace: createPlaceChatMain({ cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep() }), grant: () => ensureCloudAccount().pairHome(), wake: () => cloudAccount?.wakeHome(), server: () => serverProc, fetch: (...args) => session.defaultSession.fetch(...args), log: slog }), 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),diff --git a/electron/place-chat-main.mjs b/electron/place-chat-main.mjsnew file mode 100644index 0000000000..105c289b8d--- /dev/null+++ b/electron/place-chat-main.mjs@@ -0,0 +1,114 @@+// Main's side of a My Cloud bot opened in place on this computer's page (src/lib/place-chat.ts): the one owner session at+// My Cloud that this computer's server forwards that bot's conversation with (server/places/place-proxy.ts).+//+// The session is opened on the person's first click on a My Cloud row, never at start, and kept for the app's run: the+// Admin's one-time code for the person's own My Cloud, redeemed there alone, as every send to My Cloud is+// (cloud-send-main.mjs). Its token goes to this computer's server over the server's private port and is kept in memory+// only, here and there: never on disk, never to a page. It is signed out at My Cloud when the joined list goes off, the+// account or My Cloud changes, and the app quits.+//+// A sleeping My Cloud is woken through the Admin first, as opening its page does; the row shows "waking" meanwhile.+import { BACKGROUND_HEADERS } from "./cloud-power.mjs";++/** How a session this opens is named in My Cloud's list of signed-in devices. */+export const PLACE_CHAT_LABEL = "This computer's window";+/** A click waits this long for My Cloud to wake and sign this in, and no longer: then it opens My Cloud's page instead. */+export const OPEN_WAIT_MS = 60_000;+const PAIR_MS = 30_000;+const SESSION_TOKEN = /^omb_sess_[\w-]{8,256}$/;++const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);++/**+ * @param {{+ * cloud(): { origin: string | null, account: string | null, asleep: boolean },+ * grant(): Promise<{ origin: string, code: string }>,+ * wake(): Promise<unknown>,+ * server(): { postMessage(message: unknown): void } | null | undefined,+ * fetch: typeof fetch,+ * log?(line: string): void,+ * now?(): number,+ * delay?(ms: number): Promise<void>,+ * }} deps `grant()`: the Admin's one-time code for the person's My Cloud (`pairHome`). `wake()`: starts a sleeping My Cloud+ * through the Admin (`wakeHome`). `server()`: this computer's server process, null while it is not running.+ */+export function createPlaceChatMain({ cloud, grant, wake, server, fetch: fetchImpl, log = () => {}, now = Date.now, delay = (ms) => new Promise((done) => setTimeout(done, ms)) }) {+ /** The open session: the Cloud and account it belongs to, and its token. */+ let session = null;+ let opening = null;+ let epoch = 0;++ const scope = () => { const { origin, account } = cloud(); return origin ? `${origin}\n${account ?? ""}` : null; };+ const tell = (value) => {+ try { server()?.postMessage({ type: "openmausbot:place-session", place: "cloud", ...value }); } catch (error) { log(`place chat: server not told (${error?.message ?? error})`); }+ };++ async function pair(origin) {+ const given = await grant();+ if (!record(given) || given.origin !== origin || typeof given.code !== "string") throw new Error("no grant for this Cloud");+ const response = await fetchImpl(`${origin}/api/auth/pair`, {+ method: "POST", redirect: "error", credentials: "omit", cache: "no-store", signal: AbortSignal.timeout(PAIR_MS),+ headers: { accept: "application/json", "content-type": "application/json" }, body: JSON.stringify({ code: given.code, label: PLACE_CHAT_LABEL }),+ });+ const body = await response.json().catch(() => null);+ if (!response.ok || typeof body?.token !== "string" || !SESSION_TOKEN.test(body.token)) throw Object.assign(new Error(`pair refused (${response.status})`), { status: response.status });+ return body.token;+ }++ async function open(mine) {+ const { origin, asleep } = cloud();+ const key = scope();+ if (!origin || !key) return { ok: false };+ if (asleep) await Promise.resolve().then(wake).catch(() => null);+ const deadline = now() + OPEN_WAIT_MS;+ for (let attempt = 0; ; attempt += 1) {+ try {+ const token = await pair(origin);+ if (mine !== epoch || scope() !== key) { void signOut({ origin, token }); return { ok: false }; }+ session = { key, origin, token };+ tell({ origin, token });+ return { ok: true };+ } catch (error) {+ // A Cloud that is starting answers nothing for a while; one that refuses the code says so at once.+ const refused = typeof error?.status === "number" && error.status >= 400 && error.status < 500;+ if (refused || now() >= deadline || mine !== epoch) { log(`place chat: no session (${error?.message ?? error})`); return { ok: false }; }+ await delay(Math.min(2_000 * (attempt + 1), 5_000));+ }+ }+ }++ async function signOut(old) {+ try {+ const response = await fetchImpl(`${old.origin}/api/auth/logout`, { method: "POST", redirect: "error", credentials: "omit", cache: "no-store", signal: AbortSignal.timeout(10_000),+ headers: { "content-type": "application/json", authorization: `Bearer ${old.token}`, ...BACKGROUND_HEADERS }, body: "{}" });+ await response.body?.cancel?.();+ } catch {}+ }++ return {+ /** Gets the session ready for a click on a My Cloud row: the one already open (told to the server again, which may+ * have restarted since), or a new one. `{ ok: false }` when there is no My Cloud or it can't sign this in. */+ ensure() {+ const key = scope();+ if (session && session.key !== key) this.close();+ if (session) { tell({ origin: session.origin, token: session.token }); return Promise.resolve({ ok: true }); }+ if (!opening) {+ const mine = epoch;+ opening = open(mine).finally(() => { if (epoch === mine) opening = null; });+ }+ return opening;+ },+ /** The session is let go: at My Cloud, and in this computer's server. */+ close() {+ epoch += 1;+ opening = null;+ const old = session;+ session = null;+ if (!old) return Promise.resolve();+ tell({ token: null });+ return signOut(old);+ },+ /** Whether a session is open now (tests and the log). */+ open: () => session !== null,+ };+}diff --git a/electron/place-chat-main.node-test.mjs b/electron/place-chat-main.node-test.mjsnew file mode 100644index 0000000000..e25b91e9ee--- /dev/null+++ b/electron/place-chat-main.node-test.mjs@@ -0,0 +1,126 @@+import assert from "node:assert/strict";+import test from "node:test";++import { createPlaceChatMain, PLACE_CHAT_LABEL } from "./place-chat-main.mjs";+import { createPlacesTogether, installPlacesTogether } from "./places-together.mjs";++const CLOUD = "https://mine.cloud.test";+const TOKEN = "omb_sess_abcdefghijklmnop";+const answer = (status, body) => ({ ok: status < 400, status, json: async () => body, body: { cancel: async () => {} } });+const settle = () => new Promise((done) => setImmediate(done));++function setup(over = {}) {+ const f = { cloud: { origin: CLOUD, account: "acct-a", asleep: false }, asked: [], told: [], grants: 0, wakes: 0, waited: [], pair: () => answer(200, { token: TOKEN }), ...over };+ f.chat = createPlaceChatMain({+ cloud: () => f.cloud,+ grant: async () => { f.grants += 1; return { origin: f.cloud.origin, code: `code-${f.grants}` }; },+ wake: async () => { f.wakes += 1; f.cloud = { ...f.cloud, asleep: false }; },+ server: () => ({ postMessage: (message) => f.told.push(message) }),+ fetch: async (url, init) => { f.asked.push([url, init]); if (url.endsWith("/api/auth/pair")) return f.pair(); return answer(200, { ok: true }); },+ delay: async (ms) => { f.waited.push(ms); },+ });+ return f;+}++test("nothing is opened at My Cloud until a row is clicked; the click opens one session, kept for the run and told to this computer's server only", async () => {+ const f = setup();+ await settle();+ assert.deepEqual([f.asked, f.told, f.grants], [[], [], 0], "nothing at start");+ assert.deepEqual(await f.chat.ensure(), { ok: true });+ assert.equal(f.asked.length, 1);+ const [url, init] = f.asked[0];+ assert.equal(url, `${CLOUD}/api/auth/pair`);+ assert.equal(init.credentials, "omit");+ assert.deepEqual(JSON.parse(init.body), { code: "code-1", label: PLACE_CHAT_LABEL });+ assert.deepEqual(f.told, [{ type: "openmausbot:place-session", place: "cloud", origin: CLOUD, token: TOKEN }]);+ // The next click reuses it, and tells the server again (it may have restarted since).+ assert.deepEqual(await f.chat.ensure(), { ok: true });+ assert.equal(f.grants, 1);+ assert.equal(f.told.length, 2);+});++test("a sleeping My Cloud is woken through the Admin first, and a Cloud still starting is asked again until it answers", async () => {+ let tries = 0;+ const f = setup({ cloud: { origin: CLOUD, account: "acct-a", asleep: true }, pair: () => { tries += 1; if (tries < 3) throw new Error("starting"); return answer(200, { token: TOKEN }); } });+ assert.deepEqual(await f.chat.ensure(), { ok: true });+ assert.equal(f.wakes, 1);+ assert.equal(tries, 3);+ assert.equal(f.grants, 3, "each try redeems a fresh one-time code");+ assert.equal(f.waited.length, 2);+});++test("a code My Cloud refuses ends the click at once: the page opens My Cloud's page instead", async () => {+ const f = setup({ pair: () => answer(403, { error: "no" }) });+ assert.deepEqual(await f.chat.ensure(), { ok: false });+ assert.deepEqual(f.told, []);+ assert.deepEqual(f.waited, []);+});++test("the session is signed out at My Cloud and dropped from the server when let go, and when the account changes", async () => {+ const f = setup();+ await f.chat.ensure();+ f.asked.length = 0;+ await f.chat.close();+ assert.equal(f.asked.length, 1);+ assert.equal(f.asked[0][0], `${CLOUD}/api/auth/logout`);+ assert.equal(f.asked[0][1].headers.authorization, `Bearer ${TOKEN}`);+ assert.deepEqual(f.told.at(-1), { type: "openmausbot:place-session", place: "cloud", token: null });+ assert.equal(f.chat.open(), false);+ await f.chat.ensure();+ f.cloud = { ...f.cloud, account: "acct-b" };+ f.asked.length = 0;+ await f.chat.ensure();+ assert.deepEqual(f.asked.map(([url]) => url.slice(CLOUD.length)), ["/api/auth/logout", "/api/auth/pair"], "the old one signed out, a new one opened");+});++test("no My Cloud, no session", async () => {+ const f = setup({ cloud: { origin: null, account: null, asleep: false } });+ assert.deepEqual(await f.chat.ensure(), { ok: false });+ assert.deepEqual(f.asked, []);+});++function together(inPlace, over = {}) {+ const changes = [];+ const f = { cloud: { origin: CLOUD, account: "acct-a", asleep: false }, saved: { v: 1, on: true } };+ f.together = createPlacesTogether({+ pref: { read: () => f.saved, write: (value) => { f.saved = value; } },+ cloud: () => f.cloud, computer: () => true, powerChecked: async () => true,+ local: async () => answer(200, { bots: [] }),+ cloudFetch: async () => answer(200, { bots: [{ id: "scout", threadId: "t1", name: "Scout" }] }),+ shown: () => "computer", focused: () => true, openPlace: () => new Promise(() => {}), send: () => {}, changed: () => changes.push(1),+ setTimer: () => ({}), clearTimer: () => {}, later: () => ({}), cancelLater: () => {}, startQuietMs: 0, inPlace, ...over,+ });+ f.changes = changes;+ return f;+}++test("a click on a My Cloud row readies the session for a bot main listed, with the row waking meanwhile; My Cloud's page and unknown bots get nothing", async () => {+ let release;+ const calls = { ensure: 0, close: 0 };+ const inPlace = { ensure: () => { calls.ensure += 1; return new Promise((done) => { release = done; }); }, close: () => { calls.close += 1; } };+ const f = together(inPlace);+ f.together.state("computer");+ await f.together.refresh("cloud");+ assert.deepEqual(await f.together.openInPlace("computer", "atlas"), { ok: false }, "not a bot main listed");+ assert.deepEqual(await f.together.openInPlace("cloud", "scout"), { ok: false }, "My Cloud's own page has nothing to open in place");+ assert.equal(calls.ensure, 0);+ f.cloud = { ...f.cloud, asleep: true };+ const opening = f.together.openInPlace("computer", "scout");+ assert.equal(f.together.state("computer").other.state, "waking", "the row says My Cloud is waking");+ release({ ok: true });+ assert.deepEqual(await opening, { ok: true });+ assert.equal(f.together.state("computer").other.state, "asleep");+ // Switched off: the lists go, and the session with them.+ f.together.set("computer", false);+ assert.ok(calls.close >= 1);+});++test("the page asks to open in place over its own channel, and main answers for its own page only", async () => {+ const handlers = new Map();+ const asked = [];+ installPlacesTogether({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, asking: (event) => event.page,+ together: { openInPlace: async (asking, id) => { asked.push([asking, id]); return { ok: true }; } } });+ assert.deepEqual(await handlers.get("places-together:open-in-place")({ page: "local" }, "scout"), { ok: true });+ assert.deepEqual(asked, [["computer", "scout"]]);+ await assert.rejects(async () => handlers.get("places-together:open-in-place")({ page: null }, "scout"));+});diff --git a/electron/places-together.d.mts b/electron/places-together.d.mtsindex aaee510f39..e0f1a76bd8 100644--- a/electron/places-together.d.mts+++ b/electron/places-together.d.mts@@ -75,6 +75,10 @@ export interface PlacesTogetherBridge {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>;+ /** This computer's page only: gets one of My Cloud's listed bots ready to open in this window (main opens the session+ * this computer's server forwards it with, waking My Cloud first if it sleeps). `ok` false: open it with `open` instead.+ * Older apps lack it. */+ openInPlace?(botId: string): Promise<{ ok: boolean }>;onChanged(callback: () => void): () => void;/** Keeps where the person moved bots in the one list; what main keeps now. Older apps lack it. */arrange?(entries: ArrangedBot[]): Promise<ArrangedBot[]>;@@ -121,6 +125,7 @@ export interface PlacesTogether {commandsChanged(on: boolean): void;switchedOff(): boolean;chosen(): boolean | null;+ openInPlace(asking: BotHome, botId: string): Promise<{ ok: boolean }>;close(): void;}export function createPlacesTogether(deps: Record<string, unknown>): PlacesTogether;diff --git a/electron/places-together.mjs b/electron/places-together.mjsindex f9a49d2bd4..749b9759a0 100644--- a/electron/places-together.mjs+++ b/electron/places-together.mjs@@ -217,6 +217,7 @@ const needsSignIn = (response) => response?.status === 401 || response?.status =* openPlace(home: "computer" | "cloud"): unknown,* send(channel: string, value: unknown): void,* changed(): void,+ * inPlace?: { ensure(): Promise<{ ok: boolean }>, close(): unknown } | null,* now?(): number,* setTimer?: typeof setInterval,* clearTimer?: typeof clearInterval,@@ -234,13 +235,15 @@ const needsSignIn = (response) => response?.status === 401 || response?.status =* own switch to that place, waking My Cloud as opening it always does. `send`: to the page on screen. `changed()`: the* list or the switch changed, so a page that draws it asks again. `address(home, botId)`: the address the link between* the two places gives that bot (electron/bot-link-main.mjs), or null while no link of this Cloud and account is on.+ * `inPlace`: the session this computer's server opens a My Cloud bot in place with (place-chat-main.mjs): readied on a+ * click from this computer's page, and let go whenever the lists are dropped.** Security: My Cloud is never asked while it sleeps, since any request would wake it and run up its hours. It is asked* only right after the Admin said it is awake, at most once a minute, and only while the person is using the window. What* 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 = () => {}, commands = null, now = Date.now,+export function createPlacesTogether({ pref, cloud, powerChecked, computer, local, cloudFetch, napped = () => {}, address = () => null, shown, focused, openPlace, send, changed, turnedOn = () => {}, commands = null, inPlace = 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();@@ -251,7 +254,7 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, localet epoch = 0;// 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;+ let commandsSeen = null, saved = null, timer = null, pending = null, scope = null, cloudAskedAt = neverAsked, signIn = false, unheard = null, readying = 0;const placeShown = () => { const place = shown(); return place === "computer" || place === "cloud" ? place : null; };/** The file as last read or written: read once, then kept here. */@@ -290,6 +293,8 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, locaaisWanted.clear();cloudAskedAt = neverAsked;signIn = false;+ readying = 0;+ try { void inPlace?.close(); } catch {}drop();}function drop() {@@ -435,7 +440,7 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, locafunction otherOf(asking) {const home = otherHome(asking), known = kept.get(home);- const state = home === "cloud" && pending?.home === home && (cloud().asleep || known?.state !== "ready") ? "waking"+ const state = home === "cloud" && (pending?.home === home || readying > 0) && (cloud().asleep || known?.state !== "ready") ? "waking": home === "cloud" && cloud().asleep ? "asleep" : known?.state ?? "loading";return { home, state, bots: (known?.bots ?? []).map((row) => addressed(row)), ...(known?.sections?.length ? { sections: known.sections } : {}), ...(typeof known?.newBot === "boolean" ? { newBot: known.newBot } : {}) };}@@ -532,6 +537,23 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, locago(home, "desktop-notifications:open", { botId: row.id, threadId: row.threadId }, OPEN_WAIT_MS);return true;},+ /** A row's click on this computer's page, where a My Cloud bot opens in this window: the session this computer's server+ * forwards it with is readied (waking My Cloud first), with the row "waking" meanwhile. `ok` false: the page opens it+ * with `open` instead, on My Cloud's own page. Only a bot main listed itself, for this Cloud and account. */+ async openInPlace(asking, botId) {+ sameScope();+ if (asking !== "computer" || !active() || !inPlace) return { ok: false };+ const row = kept.get("cloud")?.bots.find((bot) => bot.id === botId);+ if (!row) return { ok: false };+ const mine = epoch;+ readying += 1;+ tell();+ try {+ const ready = await inPlace.ensure();+ return { ok: mine === epoch && active() && ready?.ok === true };+ } catch { return { ok: false }; }+ finally { if (mine === epoch) { readying = Math.max(0, readying - 1); tell(); } }+ },/** The person moved bots in the one list (a drag or Alt+Up/Down, on either page): their entries replace the ones they* had. Nothing of either place's own server changes here. What this account has kept now. */arrange(asking, entries) {@@ -619,6 +641,7 @@ export function installPlacesTogether({ ipcMain, asking, together, rail = () =>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:open-in-place", (event, botId) => together.openInPlace(side(event), String(botId)));ipcMain.handle("places-together:arrange", (event, entries) => together.arrange(side(event), entries));ipcMain.handle("places-together:new-bot-choice", (event) => together.newBotChoice(side(event)));ipcMain.handle("places-together:new-bot", (event) => together.newBot(side(event)));diff --git a/electron/preload.cjs b/electron/preload.cjsindex 48ede65bca..2d83b54535 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -649,6 +649,8 @@ const bridge = {? 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.")),+ // A My Cloud bot opened in this computer's window (main readies the session this computer's server forwards it with).+ openInPlace: botId => (isLocalPage ? ipcRenderer.invoke("places-together:open-in-place", String(botId)) : Promise.resolve({ ok: false })),// Where the person dragged bots in the one list: main keeps it beside the switch, and checks every entry.arrange: entries => ipcRenderer.invoke("places-together:arrange", Array.isArray(entries) ? entries.slice(0, 2000) : []),onChanged: cb => {diff --git a/scripts/testing/cloud-send-fixture.ts b/scripts/testing/cloud-send-fixture.tsindex b3b4d4c9ab..4bf1fea91e 100644--- a/scripts/testing/cloud-send-fixture.ts+++ b/scripts/testing/cloud-send-fixture.ts@@ -70,6 +70,8 @@ export interface CloudSendFixture {desktopInstallation: { id: string; token: string; userId: string } | null;/** This computer's server's private port, asked as main asks it (cloud-logins.mjs). */handoff(what: ConnectionAsk): Promise<any>;+ /** A message on this computer's server's private port, as main sends one (a My Cloud session for a bot opened in place). */+ tellDesktop(message: object): void;/** The one-time move (one-home.mjs), as main runs it in the app that is open now. */oneHome: { kick(): Promise<void>; view(): OneHomeView | null; away(): boolean };/** The MausBot Cloud sign-in main reads: the Admin's word on this account's Cloud, its export of a held one, the Admin@@ -605,6 +607,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cllisten();},handoff: (what) => asks.request(port, what as ConnectionAsk),+ tellDesktop: (message) => port.postMessage(message),async picture(bytes) {const response = await fetch(`${desktopBase}/api/attachments`, { method: "POST", headers: { "x-openmausbot-desktop-owner": ownerCapability, "content-type": "image/png" }, body: bytes });return `/api/attachments/${((await response.json()) as { path: string }).path.split(/[\\/]/).pop()}`;diff --git a/server/places/place-proxy.e2e.test.ts b/server/places/place-proxy.e2e.test.tsnew file mode 100644index 0000000000..062dcb85b8--- /dev/null+++ b/server/places/place-proxy.e2e.test.ts@@ -0,0 +1,103 @@+// A My Cloud bot opened in place, end to end on two real servers (scripts/testing/cloud-send-fixture.ts): this computer's+// server, told the session over its private port as main tells it, forwards the page's reads, sends and live stream to a+// real Cloud home through a stand-in for the Cloud's edge. The page's side speaks only `cloud:` ids; the Cloud's turn+// streams back through this computer's server while it runs. Disposable homes, the fake Claude CLI; no network.+import { randomBytes } from "node:crypto";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { afterAll, beforeAll, expect, it } from "vitest";+import { launchCloudSendFixture, type CloudSendFixture } from "../../scripts/testing/cloud-send-fixture.ts";+import { hostTimeout } from "../testing/host-timeout.ts";++let fx: CloudSendFixture, edge: Server, edgeBase: string, token: string;++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-place-${randomBytes(8).toString("hex")}` });+ // The Cloud's edge: what Fly's proxy adds in front of a Cloud home, for whatever comes to its public address.+ edge = createServer((req, res) => {+ const chunks: Buffer[] = [];+ req.on("data", (chunk) => chunks.push(chunk));+ req.on("end", async () => {+ const headers = new Headers();+ for (const [name, value] of Object.entries(req.headers)) if (typeof value === "string" && !["host", "connection", "content-length"].includes(name)) headers.set(name, value);+ for (const [name, value] of Object.entries(fx.edge)) headers.set(name, value);+ const body = chunks.length ? Buffer.concat(chunks) : undefined;+ try {+ const upstream = await fetch(`${fx.cloudBase}${req.url}`, { method: req.method, headers, body, redirect: "manual" });+ res.writeHead(upstream.status, Object.fromEntries([...upstream.headers].filter(([name]) => !["content-encoding", "content-length", "transfer-encoding"].includes(name))));+ res.flushHeaders();+ if (upstream.body) for await (const chunk of upstream.body as unknown as AsyncIterable<Uint8Array>) res.write(chunk);+ res.end();+ } catch { res.destroy(); }+ });+ });+ await new Promise<void>((resolve) => edge.listen(0, "127.0.0.1", resolve));+ edgeBase = `http://127.0.0.1:${(edge.address() as AddressInfo).port}`;+ // Main's session for it: the Admin's one-time code, redeemed at My Cloud (electron/place-chat-main.mjs).+ const { code } = await fx.grant("This computer's window");+ const paired = await fetch(`${edgeBase}/api/auth/pair`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code, label: "This computer's window" }) });+ token = ((await paired.json()) as { token: string }).token;+ expect(token).toMatch(/^omb_sess_/);+}, hostTimeout(120_000));++afterAll(async () => {+ edge?.closeAllConnections();+ await new Promise((resolve) => edge ? edge.close(resolve) : resolve(null));+ await fx?.close();+});++const page = (path: string, init: RequestInit = {}) => fetch(`${fx.desktopBase}${path}`, { ...init, headers: { "x-openmausbot-desktop-owner": fx.ownerCapability, ...(init.body ? { "content-type": "application/json" } : {}), ...init.headers } });++it("reads, streams and sends a My Cloud bot's conversation through this computer's server, in the page's ids, with no session in sight", async () => {+ // Before main tells it a session, this computer's server forwards nothing.+ const { body: listed } = await fx.onCloud("GET", "/api/bots?messages=0");+ const bot = (listed.bots as Array<{ id: string; threadId: string; name: string }>)[0]!;+ expect((await (await page(`/api/bots/cloud:${bot.id}`)).json()).code).toBe("place_closed");++ fx.tellDesktop({ type: "openmausbot:place-session", place: "cloud", origin: edgeBase, token });+ let opened: Response | null = null;+ for (let tries = 0; tries < 50; tries++) {+ opened = await page(`/api/bots/cloud%3A${bot.id}?messages=80`);+ if (opened.status !== 503) break;+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ expect(opened!.status).toBe(200);+ const text = await opened!.text();+ expect(text).not.toContain(token);+ expect(text).not.toContain(edgeBase);+ const { bot: shown } = JSON.parse(text);+ expect(shown.id).toBe(`cloud:${bot.id}`);+ expect(shown.threadId).toBe(`cloud:${bot.threadId}`);+ expect(shown.name).toBe(bot.name);++ // The live stream, open before the send: the Cloud's turn arrives on it while it runs.+ const stop = new AbortController();+ const stream = await page(`/api/places/cloud/events?bot=${encodeURIComponent(shown.id)}`, { signal: stop.signal });+ expect(stream.status).toBe(200);+ const reader = stream.body!.getReader(), decoder = new TextDecoder();+ let said = "";+ const frames = () => said.split("\n").filter((line) => line.startsWith("data: ")).map((line) => JSON.parse(line.slice(6)) as { kind: string; threadId?: string; message?: { role?: string; text?: string }; event?: { threadId?: string } });+ const until = async (found: () => boolean) => { while (!found()) { const { value, done } = await reader.read(); if (done) throw new Error(`stream ended:\n${said}`); said += decoder.decode(value, { stream: true }); } };+ await until(() => frames().some((frame) => frame.kind === "hello"));++ const sent = await page(`/api/bots/${encodeURIComponent(shown.id)}/messages`, { method: "POST", body: JSON.stringify({ threadId: shown.threadId, text: "cloud: say hello" }) });+ expect(sent.status, await sent.clone().text()).toBeLessThan(300);+ await until(() => frames().some((frame) => frame.kind === "message" && frame.message?.role === "bot"));+ const ours = frames().filter((frame) => frame.kind === "message");+ expect(ours.every((frame) => frame.threadId === shown.threadId)).toBe(true);+ expect(ours.some((frame) => frame.message?.role === "user" && frame.message.text === "cloud: say hello")).toBe(true);+ expect(frames().filter((frame) => frame.kind === "runtime").every((frame) => frame.event?.threadId === shown.threadId)).toBe(true);+ expect(said).not.toContain(token);++ // What the Cloud keeps is the same conversation, in its own ids.+ const { body: there } = await fx.onCloud("GET", `/api/threads/${bot.threadId}/messages?limit=10`);+ expect((there.messages as Array<{ text?: string }>).some((message) => message.text === "cloud: say hello")).toBe(true);++ // Stopping is forwarded too, in the Cloud's ids.+ expect((await page(`/api/bots/${encodeURIComponent(shown.id)}/interrupt`, { method: "POST", body: JSON.stringify({ threadId: shown.threadId }) })).status).toBeLessThan(500);+ stop.abort();++ // Nobody but the app's window gets anything through, and a bot's settings stay on its own page.+ expect((await fetch(`${fx.desktopBase}/api/bots/cloud:${bot.id}`)).status).toBeGreaterThanOrEqual(400);+ expect((await (await page(`/api/bots/cloud:${bot.id}/soul`)).json()).code).toBe("place_unsupported");+}, hostTimeout(120_000));diff --git a/server/places/place-proxy.test.ts b/server/places/place-proxy.test.tsnew file mode 100644index 0000000000..c8f9abb6ce--- /dev/null+++ b/server/places/place-proxy.test.ts@@ -0,0 +1,244 @@+// The proxy that serves a My Cloud bot opened in place, against a stand-in My Cloud: the page asks this computer's server+// in its own (`cloud:`) ids, My Cloud is asked in its own, the session never leaves this process, and the bot's live+// stream is passed on frame by frame.+import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";+import type { AddressInfo } from "node:net";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { json, readBody } from "../harness/http.ts";+import { createPlaceProxy, frameForBot, parsePlaceSession, placedPath, type PlaceProxy } from "./place-proxy.ts";++const TOKEN = "omb_sess_test-token-0123456789";+const OWNER = "o".repeat(43);++interface Seen { method: string; url: string; authorization: string | undefined; body: string }++let cloud: Server, local: Server, cloudUrl: string, localUrl: string, proxy: PlaceProxy;+const seen: Seen[] = [];+/** The stand-in Cloud's answer to each request; the live stream is handled apart. */+let answerWith: (req: IncomingMessage, res: ServerResponse, body: string) => void;+let streamTo: ((res: ServerResponse, req: IncomingMessage) => void) | null = null;++const scout = {+ id: "scout", name: "Scout", threadId: "t1", mainThreadId: "t1", chiefOfStaff: true,+ tasks: [{ threadId: "t1", title: "Flats" }, { threadId: "t2", title: "Trains" }],+ messages: [{ id: "m1", role: "bot", kind: "text", text: "cloud: four flats", attachments: [{ kind: "image", path: "/data/attachments/aa11-bb22.png", mime: "image/png" }] }],+};++const listen = (server: Server) => new Promise<string>((done) => server.listen(0, "127.0.0.1", () => done(`http://127.0.0.1:${(server.address() as AddressInfo).port}`)));++beforeEach(async () => {+ seen.length = 0;+ streamTo = null;+ answerWith = (req, res) => {+ if (req.url?.startsWith("/api/bots/scout")) return void res.writeHead(200, { "content-type": "application/json", "set-cookie": "omb_session=secret" }).end(JSON.stringify({ bot: scout }));+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ ok: true }));+ };+ cloud = createServer((req, res) => {+ let body = "";+ req.on("data", (chunk) => { body += chunk; });+ req.on("end", () => {+ seen.push({ method: req.method!, url: req.url!, authorization: req.headers.authorization, body });+ if (req.url?.startsWith("/api/events") && streamTo) return streamTo(res, req);+ answerWith(req, res, body);+ });+ });+ cloudUrl = await listen(cloud);+ proxy = createPlaceProxy();+ proxy.setOwnerToken(OWNER);+ proxy.setSession({ origin: cloudUrl, token: TOKEN });+ local = createServer((req, res) => {+ const url = new URL(req.url!, "http://127.0.0.1");+ void proxy.route({ req, res, url, path: url.pathname, method: req.method!, auth: { kind: "loopback", scopes: [] }, json, readBody }).then((out) => {+ if (typeof out === "symbol") res.writeHead(418).end("passed");+ });+ });+ localUrl = await listen(local);+});++afterEach(async () => {+ local.closeAllConnections();+ cloud.closeAllConnections();+ await Promise.all([new Promise((done) => local.close(done)), new Promise((done) => cloud.close(done))]);+});++const ask = (path: string, init: RequestInit = {}, owner: string | null = OWNER) =>+ fetch(`${localUrl}${path}`, { ...init, headers: { ...(owner ? { "x-openmausbot-desktop-owner": owner } : {}), ...(init.body ? { "content-type": "application/json" } : {}), ...init.headers } });++describe("the conversation of a My Cloud bot, through this computer's server", () => {+ it("reads it in My Cloud's ids and hands it back in the page's, files included, with no session or cookie in it", async () => {+ const answer = await ask("/api/bots/cloud%3Ascout?messages=80");+ expect(answer.status).toBe(200);+ expect(answer.headers.get("set-cookie")).toBeNull();+ const text = await answer.text();+ expect(text).not.toContain(TOKEN);+ expect(text).not.toContain(cloudUrl);+ const { bot } = JSON.parse(text);+ expect(bot.id).toBe("cloud:scout");+ expect(bot.threadId).toBe("cloud:t1");+ expect(bot.mainThreadId).toBe("cloud:t1");+ expect(bot.tasks.map((task: { threadId: string }) => task.threadId)).toEqual(["cloud:t1", "cloud:t2"]);+ // Words are never rewritten; a file is asked for under a name of the page's.+ expect(bot.messages[0].text).toBe("cloud: four flats");+ expect(bot.messages[0].attachments[0].path).toBe("cloud--aa11-bb22.png");+ expect(seen).toEqual([{ method: "GET", url: "/api/bots/scout?messages=80", authorization: `Bearer ${TOKEN}`, body: "" }]);+ });++ it("sends, stops and pages back in My Cloud's ids, and a file a message names goes back as My Cloud gave it", async () => {+ await (await ask("/api/bots/cloud%3Ascout?messages=80")).text();+ seen.length = 0;+ expect((await ask("/api/bots/cloud:scout/messages", { method: "POST", body: JSON.stringify({ threadId: "cloud:t1", text: "cloud: hi", attachments: [{ path: "cloud--aa11-bb22.png" }] }) })).status).toBe(200);+ expect((await ask("/api/bots/cloud:scout/interrupt", { method: "POST", body: JSON.stringify({ threadId: "cloud:t1" }) })).status).toBe(200);+ expect((await ask("/api/threads/cloud%3At2/messages?limit=40&before=m1")).status).toBe(200);+ expect(seen.map(({ method, url }) => `${method} ${url}`)).toEqual(["POST /api/bots/scout/messages", "POST /api/bots/scout/interrupt", "GET /api/threads/t2/messages?limit=40&before=m1"]);+ expect(JSON.parse(seen[0]!.body)).toEqual({ threadId: "t1", text: "cloud: hi", attachments: [{ path: "/data/attachments/aa11-bb22.png" }] });+ expect(JSON.parse(seen[1]!.body)).toEqual({ threadId: "t1" });+ });++ it("serves My Cloud's file by the page's name for it", async () => {+ answerWith = (_req, res) => void res.writeHead(200, { "content-type": "image/png", "content-length": "3" }).end(Buffer.from([1, 2, 3]));+ const answer = await ask("/api/attachments/cloud--aa11-bb22.png");+ expect(answer.status).toBe(200);+ expect(answer.headers.get("content-type")).toBe("image/png");+ expect([...new Uint8Array(await answer.arrayBuffer())]).toEqual([1, 2, 3]);+ expect(seen[0]!.url).toBe("/api/attachments/aa11-bb22.png");+ });++ it("answers nobody but the app's own window, and asks My Cloud nothing for anyone else", async () => {+ for (const owner of [null, "x".repeat(43)]) {+ const answer = await ask("/api/bots/cloud:scout", {}, owner);+ expect(answer.status).toBe(404);+ expect(await answer.text()).not.toContain(cloudUrl);+ }+ // A page from another site carries the header too (Chromium adds it below JavaScript): not its own page, refused.+ expect((await ask("/api/bots/cloud:scout", { headers: { "sec-fetch-site": "cross-site", origin: "https://elsewhere.example" } })).status).toBe(404);+ expect(seen).toEqual([]);+ });++ it("refuses what a conversation does not need, without asking My Cloud: settings, deleting the bot, renaming", async () => {+ for (const [method, path] of [["PATCH", "/api/bots/cloud:scout"], ["DELETE", "/api/bots/cloud:scout"], ["GET", "/api/bots/cloud:scout/soul"], ["PATCH", "/api/bots/cloud:scout/tasks/cloud:t1"]] as const) {+ const answer = await ask(path, { method, ...(method === "PATCH" ? { body: "{}" } : {}) });+ expect(answer.status).toBe(404);+ expect((await answer.json()).code).toBe("place_unsupported");+ }+ expect(seen).toEqual([]);+ });++ it("leaves this computer's own bots alone", async () => {+ expect((await ask("/api/bots/ledger/messages", { method: "POST", body: "{}" })).status).toBe(418);+ expect((await ask("/api/attachments/aa11-bb22.png")).status).toBe(418);+ expect(seen).toEqual([]);+ });++ it("says a sleeping My Cloud, a sign-in it refused and a route it lacks as My Cloud's, never as this server's own", async () => {+ answerWith = (_req, res) => void res.writeHead(503, { "content-type": "application/json", "x-omb-cloud-power": "asleep" }).end(JSON.stringify({ error: "asleep" }));+ let answer = await ask("/api/bots/cloud:scout/messages", { method: "POST", body: "{}" });+ expect(answer.status).toBe(503);+ expect(answer.headers.get("x-omb-cloud-power")).toBeNull();+ expect((await answer.json()).code).toBe("place_asleep");++ answerWith = (_req, res) => void res.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify({ error: "unauthorized" }));+ answer = await ask("/api/bots/cloud:scout");+ expect(answer.status).toBe(502);+ expect((await answer.json()).code).toBe("place_signin");++ // An older My Cloud: no such route, answered by whatever serves unknown paths there.+ answerWith = (_req, res) => void res.writeHead(404, { "content-type": "text/html" }).end("<h1>Not found</h1>");+ answer = await ask("/api/bots/cloud:scout/read", { method: "POST", body: "{}" });+ expect(answer.status).toBe(404);+ expect((await answer.json()).code).toBe("place_unsupported");++ // My Cloud's own refusal keeps its words, never its code: this page must not read it as its own bot limit.+ answerWith = (_req, res) => void res.writeHead(409, { "content-type": "application/json" }).end(JSON.stringify({ error: "Too many bots", code: "bot_limit" }));+ answer = await ask("/api/bots/cloud:scout/messages", { method: "POST", body: "{}" });+ expect(answer.status).toBe(409);+ expect(await answer.json()).toEqual({ error: "Too many bots", code: "place_refused" });+ });++ it("says My Cloud can't be reached, and that nothing is open before main opened a session", async () => {+ proxy.setSession({ origin: "http://127.0.0.1:9", token: TOKEN });+ expect((await (await ask("/api/bots/cloud:scout")).json()).code).toBe("place_offline");+ proxy.setSession(null);+ const answer = await ask("/api/bots/cloud:scout");+ expect(answer.status).toBe(503);+ expect((await answer.json()).code).toBe("place_closed");+ });+});++describe("the bot's live stream", () => {+ it("passes each of the bot's frames on as it arrives, in the page's ids, and nothing of My Cloud's other bots", async () => {+ let more!: () => void;+ const later = new Promise<void>((done) => { more = done; });+ let upstreamClosed!: () => void;+ const closed = new Promise<void>((done) => { upstreamClosed = done; });+ streamTo = (res, req) => {+ req.on("close", () => upstreamClosed());+ res.writeHead(200, { "content-type": "text/event-stream" });+ res.write(`data: ${JSON.stringify({ kind: "hello", cursor: "s:4", resumed: false })}\n\n`);+ res.write(`id: s:5\ndata: ${JSON.stringify({ kind: "message", threadId: "t9", message: { id: "x", role: "bot", text: "another bot's" } })}\n\n`);+ res.write(`id: s:6\ndata: ${JSON.stringify({ kind: "routine", routine: { id: "r" } })}\n\n`);+ res.write(`id: s:7\ndata: ${JSON.stringify({ kind: "runtime", event: { type: "text.delta", threadId: "t1", text: "Fou" } })}\n\n`);+ void later.then(() => res.write(`id: s:8\ndata: ${JSON.stringify({ kind: "message", threadId: "t2", message: { id: "y", role: "bot", kind: "text", text: "Trains at 9" } })}\n\n`));+ };+ const stop = new AbortController();+ const answer = await ask("/api/places/cloud/events?bot=cloud%3Ascout&since=s%3A3", { signal: stop.signal });+ expect(answer.status).toBe(200);+ expect(answer.headers.get("content-type")).toMatch(/^text\/event-stream/);+ const reader = answer.body!.getReader(), decoder = new TextDecoder();+ let text = "";+ const until = async (part: string) => { while (!text.includes(part)) { const { value, done } = await reader.read(); if (done) throw new Error(`ended before ${part}`); text += decoder.decode(value, { stream: true }); } };+ // The runtime frame arrives while My Cloud's stream is still open: nothing waits for more.+ await until("text.delta");+ expect(text).toContain(`"threadId":"cloud:t1"`);+ expect(text).toContain("id: s:7\n");+ expect(text).not.toContain("another bot's");+ expect(text).not.toContain("routine");+ more();+ await until("Trains at 9");+ expect(text).toContain(`"threadId":"cloud:t2"`);+ const events = seen.find((request) => request.url.startsWith("/api/events"))!;+ expect(events.authorization).toBe(`Bearer ${TOKEN}`);+ expect(new URL(events.url, "http://x").searchParams.get("since")).toBe("s:3");+ // The page closing its stream closes My Cloud's.+ stop.abort();+ await closed;+ });++ it("refuses a stream for anyone but the app's window, and says a My Cloud without the stream plainly", async () => {+ expect((await ask("/api/places/cloud/events?bot=cloud:scout", {}, null)).status).toBe(404);+ streamTo = (res) => void res.writeHead(200, { "content-type": "text/html" }).end("old");+ const answer = await ask("/api/places/cloud/events?bot=cloud:scout");+ expect(answer.status).toBe(502);+ expect((await answer.json()).code).toBe("place_unsupported");+ });+});++describe("pieces", () => {+ it("names My Cloud's own path for a placed one, and nothing for this computer's", () => {+ expect(placedPath("/api/bots/cloud%3Ascout/tasks/cloud:t1")).toBe("/api/bots/scout/tasks/t1");+ expect(placedPath("/api/threads/cloud:t1/respond")).toBe("/api/threads/t1/respond");+ expect(placedPath("/api/attachments/cloud--a1.png")).toBe("/api/attachments/a1.png");+ expect(placedPath("/api/bots/scout/messages")).toBeNull();+ expect(placedPath("/api/bots/cloud:../x")).toBeNull();+ expect(placedPath("/api/groups/cloud:g")).toBeNull();+ });++ it("takes a session only as main sends it", () => {+ expect(parsePlaceSession({ type: "openmausbot:place-session", place: "cloud", origin: "https://c.example", token: TOKEN })).toEqual({ origin: "https://c.example", token: TOKEN });+ expect(parsePlaceSession({ type: "openmausbot:place-session", place: "cloud", token: null })).toBeNull();+ expect(parsePlaceSession({ type: "openmausbot:place-session", place: "cloud", origin: "https://c.example/path", token: TOKEN })).toBeUndefined();+ expect(parsePlaceSession({ type: "openmausbot:place-session", place: "cloud", origin: "file:///x", token: TOKEN })).toBeUndefined();+ expect(parsePlaceSession({ type: "openmausbot:place-session", place: "cloud", origin: "https://c.example", token: "nope" })).toBeUndefined();+ expect(parsePlaceSession({ type: "other" })).toBeUndefined();+ });++ it("keeps the frames of the bot's conversations, learning new ones from the bot", () => {+ const threads = new Set(["t1"]);+ expect(frameForBot({ kind: "thread", threadId: "t3", activeLeafId: "a" }, "scout", threads)).toBeNull();+ expect(frameForBot({ kind: "bot", bot: { id: "scout", tasks: [{ threadId: "t3" }] } }, "scout", threads)).not.toBeNull();+ expect(frameForBot({ kind: "thread", threadId: "t3", activeLeafId: "a" }, "scout", threads)).not.toBeNull();+ expect(frameForBot({ kind: "bot", bot: { id: "atlas" } }, "scout", threads)).toBeNull();+ expect(frameForBot({ kind: "bot.queued", queues: {} }, "scout", threads)).toBeNull();+ expect(frameForBot({ kind: "power", state: "sleeping" }, "scout", threads)).not.toBeNull();+ });+});diff --git a/server/places/place-proxy.ts b/server/places/place-proxy.tsnew file mode 100644index 0000000000..777335a6ea--- /dev/null+++ b/server/places/place-proxy.ts@@ -0,0 +1,346 @@+// A My Cloud bot opened in place on this computer's page. The page talks only to this computer's own server, as for any+// bot: what it asks of a bot whose id carries My Cloud's key (shared/place-ids.ts) is forwarded here to My Cloud, as the+// person, with the owner session the desktop app opened there for this purpose. The page never learns My Cloud's address+// or that session: main hands both to this server over its private port (no HTTP route sets them), they live in this+// process's memory only, and every answer is rebuilt here from My Cloud's body with its ids in this page's names.+//+// Only what a conversation needs goes through (ROUTES): reading it and its other conversations, its live turns, sending,+// stopping, answering its cards, marking it read and its files. Anything else asked of such a bot is refused plainly+// with the words to open My Cloud's own page, which the bot's row offers.+//+// Who may ask: only the app's own window, by the desktop capability Chromium adds to its requests below JavaScript, from+// this server's own page (the same proof request-auth.ts asks of a change). A shell, a phone, a remote session, a bot's+// browser or another site never reaches My Cloud through here, reads included.+import { timingSafeEqual } from "node:crypto";+import type { ServerResponse } from "node:http";++import { intoPlace, isPlaceId, outOfPlace, ownId, PLACE_FILE_PREFIX, PLACE_KEY } from "../../shared/place-ids.ts";+import { fromOwnPage } from "../request-auth.ts";+import { userError, type UserErrorKey } from "../user-errors.ts";+import { PASS, type RouteContext, type RouteHandler } from "../routes/table.ts";++/** The live stream of the one bot open in place: `?bot=<cloud:id>`, and `since` (or Last-Event-ID) to resume. */+export const PLACE_EVENTS_PATH = `/api/places/${PLACE_KEY}/events`;+const OWNER_HEADER = "x-openmausbot-desktop-owner";+const CLOUD_POWER_HEADER = "x-omb-cloud-power";+const BACKGROUND_HEADER = "x-omb-background";+const SESSION_TOKEN = /^omb_sess_[\w-]{8,256}$/;+const OWN_ID = /^[\w-]{1,128}$/;+/** How long one forwarded request may take: a send on a Cloud that has to start first takes about 20 s. */+const REQUEST_MS = 90_000;+const BODY_MAX = 4_000_000;+/** The most file names kept to send back a message that names one. */+const FILES_KEPT = 5_000;++/** My Cloud's own routes, in its own ids, that a conversation opened in place uses. */+const ROUTES: ReadonlyArray<readonly [string, RegExp]> = [+ ["GET", /^\/api\/bots\/[\w-]+$/],+ ["POST", /^\/api\/bots\/[\w-]+\/tasks$/],+ ["POST", /^\/api\/bots\/[\w-]+\/tasks\/[\w-]+$/],+ ["POST", /^\/api\/bots\/[\w-]+\/messages$/],+ ["POST", /^\/api\/bots\/[\w-]+\/read$/],+ ["POST", /^\/api\/bots\/[\w-]+\/interrupt$/],+ ["DELETE", /^\/api\/bots\/[\w-]+\/queue\/[\w-]+$/],+ ["POST", /^\/api\/bots\/[\w-]+\/queue\/[\w-]+\/steer$/],+ ["POST", /^\/api\/bots\/[\w-]+\/cards\/[\w-]+$/],+ ["POST", /^\/api\/threads\/[\w-]+\/respond$/],+ ["GET", /^\/api\/threads\/[\w-]+\/messages$/],+ ["GET", /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/(?:image|file|tool)$/],+ ["GET", /^\/api\/attachments\/[\w.-]+$/],+];++/** The frames of My Cloud's stream that are about one bot's conversations. Anything else (its other bots, its rooms,+ * routines, settings, notifications, queues) is never this page's to apply. */+const BOT_FRAMES = new Set(["message", "message.patch", "thread"]);++export interface PlaceSession { origin: string; token: string }++type Fetch = (url: string, init: RequestInit) => Promise<Response>;++const record = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);+const decoded = (segment: string): string => { try { return decodeURIComponent(segment); } catch { return segment; } };++/** The request names My Cloud's bot, conversation or file in its path: the path in My Cloud's own ids, else null. */+export function placedPath(path: string): string | null {+ const parts = path.split("/");+ if (parts[1] !== "api") return null;+ if (parts[2] === "attachments" && parts.length === 4) {+ const name = decoded(parts[3]!);+ return name.startsWith(PLACE_FILE_PREFIX) ? `/api/attachments/${encodeURIComponent(name.slice(PLACE_FILE_PREFIX.length))}` : null;+ }+ if ((parts[2] !== "bots" && parts[2] !== "threads") || parts.length < 4) return null;+ const id = decoded(parts[3]!);+ if (!isPlaceId(id)) return null;+ const rest = parts.slice(4).map((part) => {+ const value = decoded(part);+ return encodeURIComponent(isPlaceId(value) ? ownId(value) : value);+ });+ const own = ownId(id);+ return OWN_ID.test(own) ? ["", "api", parts[2], own, ...rest].join("/") : null;+}++const allowed = (method: string, path: string): boolean => ROUTES.some(([verb, pattern]) => verb === method && pattern.test(path));++function sameToken(given: unknown, expected: string): boolean {+ if (typeof given !== "string" || given.length !== expected.length) return false;+ return timingSafeEqual(Buffer.from(given), Buffer.from(expected));+}++/** A message main sends this server over its private port: My Cloud's address and the owner session for it, or none. */+export function parsePlaceSession(message: unknown): PlaceSession | null | undefined {+ if (!record(message) || message.type !== "openmausbot:place-session" || message.place !== PLACE_KEY) return undefined;+ if (message.token === null) return null;+ if (typeof message.origin !== "string" || typeof message.token !== "string" || !SESSION_TOKEN.test(message.token)) return undefined;+ let origin: URL;+ try { origin = new URL(message.origin); } catch { return undefined; }+ if ((origin.protocol !== "https:" && origin.protocol !== "http:") || origin.origin !== message.origin) return undefined;+ return { origin: origin.origin, token: message.token };+}++/** The one My Cloud stream frame, if this page applies it for the bot `own` (My Cloud's id), with the conversations it+ * learned from it. */+export function frameForBot(frame: unknown, own: string, threads: Set<string>): unknown | null {+ if (!record(frame) || typeof frame.kind !== "string") return null;+ switch (frame.kind) {+ case "hello": case "ping": case "power": return frame;+ case "bot": {+ const bot = frame.bot;+ if (!record(bot) || bot.id !== own) return null;+ learnThreads(bot, threads);+ return frame;+ }+ case "bot.deleted": return frame.botId === own ? frame : null;+ case "runtime": return record(frame.event) && typeof frame.event.threadId === "string" && threads.has(frame.event.threadId) ? frame : null;+ default: return BOT_FRAMES.has(frame.kind) && typeof frame.threadId === "string" && threads.has(frame.threadId) ? frame : null;+ }+}++function learnThreads(bot: Record<string, unknown>, threads: Set<string>): void {+ if (typeof bot.threadId === "string") threads.add(bot.threadId);+ if (typeof bot.mainThreadId === "string") threads.add(bot.mainThreadId);+ if (Array.isArray(bot.tasks)) for (const task of bot.tasks) if (record(task) && typeof task.threadId === "string") threads.add(task.threadId);+}++/** Events in the text/event-stream format, one at a time as their blank line arrives: never held for more. */+export async function* sseEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<{ id: string | null; data: string }> {+ const reader = body.getReader();+ const decoder = new TextDecoder();+ let pending = "", data: string[] = [], id: string | null = null;+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) return;+ pending += decoder.decode(value, { stream: true });+ const lines = pending.split(/\r\n|\r|\n/);+ pending = lines.pop()!;+ for (const line of lines) {+ if (line === "") {+ if (data.length) yield { id, data: data.join("\n") };+ data = [];+ id = null;+ continue;+ }+ if (line.startsWith(":")) continue;+ const colon = line.indexOf(":");+ const field = colon < 0 ? line : line.slice(0, colon);+ const text = colon < 0 ? "" : line.slice(line[colon + 1] === " " ? colon + 2 : colon + 1);+ if (field === "data") data.push(text);+ else if (field === "id" && !text.includes("\0")) id = text;+ }+ }+ } finally {+ void reader.cancel().catch(() => {});+ }+}++/**+ * `fetch`: requests to My Cloud. The session arrives with `setSession` (main, over the private port) and goes with+ * `setSession(null)`; the app's capability with `setOwnerToken`.+ */+export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch }: { fetch?: Fetch } = {}) {+ let session: PlaceSession | null = null;+ let ownerToken: string | null = null;+ const files = new Map<string, string>();+ const remember = (name: string, path: string) => {+ files.delete(name);+ files.set(name, path);+ if (files.size > FILES_KEPT) files.delete(files.keys().next().value!);+ };+ const recall = (name: string) => files.get(name);++ /** The app's own window, from this server's own page: the only caller anything here answers. */+ const ownWindow = ({ req, auth }: Pick<RouteContext, "req" | "auth">): boolean =>+ auth.kind === "loopback" && auth.trust !== "service" && auth.companionDevice === undefined && ownerToken !== null+ && sameToken(req.headers[OWNER_HEADER], ownerToken) && fromOwnPage(req);++ const refuse = (res: ServerResponse, json: RouteContext["json"], status: number, key: UserErrorKey, code: string) => json(res, status, { ...userError(key), code });++ /** My Cloud's answer in this page's terms. Its sleeping, sign-in and limit answers are said as My Cloud's, so this+ * page never takes them for its own server going to sleep, its own sign-in ending or its own bot limit. */+ async function answer(ctx: RouteContext, upstream: Response): Promise<void> {+ const { res, json } = ctx;+ if (upstream.status === 503 && upstream.headers.get(CLOUD_POWER_HEADER) === "asleep") {+ await upstream.body?.cancel().catch(() => {});+ return refuse(res, json, 503, "serverError.place.asleep", "place_asleep");+ }+ if (upstream.status === 401) {+ await upstream.body?.cancel().catch(() => {});+ return refuse(res, json, 502, "serverError.place.signIn", "place_signin");+ }+ const type = upstream.headers.get("content-type") ?? "";+ if (/^application\/json\b/i.test(type) || !upstream.ok) {+ let body: unknown = null;+ try { body = await upstream.json(); } catch { body = null; }+ if (!upstream.ok && !record(body)) return refuse(res, json, upstream.status === 404 ? 404 : 502, "serverError.place.unsupported", "place_unsupported");+ const placed = intoPlace(body, remember);+ if (!upstream.ok && record(placed)) {+ // A refusal of My Cloud's is passed on in its words, never as one of this server's own kinds.+ const { code: _code, ...said } = placed;+ return json(res, upstream.status === 403 ? 409 : upstream.status, { ...said, code: "place_refused" });+ }+ return json(res, upstream.status, placed);+ }+ // A file or an image: its bytes as they come, kept by nobody.+ const headers: Record<string, string> = { "content-type": type || "application/octet-stream", "cache-control": "private, no-store" };+ const length = upstream.headers.get("content-length");+ if (length && /^\d+$/.test(length)) headers["content-length"] = length;+ const disposition = upstream.headers.get("content-disposition");+ if (disposition) headers["content-disposition"] = disposition;+ res.writeHead(upstream.status, headers);+ if (!upstream.body) { res.end(); return; }+ for await (const chunk of upstream.body as unknown as AsyncIterable<Uint8Array>) {+ if (!res.write(chunk)) await new Promise((done) => res.once("drain", done));+ }+ res.end();+ }++ async function forward(ctx: RouteContext, own: PlaceSession, path: string): Promise<void> {+ const { req, res, url, method, json, readBody } = ctx;+ let body: string | undefined;+ if (method !== "GET" && method !== "HEAD") {+ const type = String(req.headers["content-type"] ?? "");+ if (type && !/^application\/json\b/i.test(type)) { req.resume(); return refuse(res, json, 415, "serverError.place.unsupported", "place_unsupported"); }+ let parsed: unknown;+ try { parsed = await readBody(req, BODY_MAX); } catch (error) { return json(res, (error as { status?: number }).status ?? 400, { error: (error as Error).message }); }+ body = JSON.stringify(outOfPlace(parsed, recall));+ }+ const search = new URLSearchParams();+ for (const [name, value] of url.searchParams) search.append(name, isPlaceId(value) ? ownId(value) : value);+ const query = search.size ? `?${search}` : "";+ const stop = new AbortController();+ const gone = () => { if (!res.writableEnded) stop.abort(); };+ res.once("close", gone);+ let upstream: Response;+ try {+ upstream = await fetchImpl(`${own.origin}${path}${query}`, {+ method, redirect: "error", cache: "no-store", body,+ signal: AbortSignal.any([stop.signal, AbortSignal.timeout(REQUEST_MS)]),+ headers: {+ accept: String(req.headers.accept ?? "application/json"), authorization: `Bearer ${own.token}`,+ ...(body !== undefined ? { "content-type": "application/json" } : {}),+ ...(req.headers[BACKGROUND_HEADER] ? { [BACKGROUND_HEADER]: "1" } : {}),+ },+ });+ } catch {+ res.off("close", gone);+ if (res.headersSent || res.destroyed) return;+ return refuse(res, json, 502, "serverError.place.offline", "place_offline");+ }+ try { await answer(ctx, upstream); } finally { res.off("close", gone); }+ }++ /** The bot's live stream: My Cloud's own stream, opened as the person, cut to this bot's frames and passed on frame by+ * frame as each arrives. It lives exactly as long as the page's connection: closing either closes the other. */+ async function stream(ctx: RouteContext, own: PlaceSession): Promise<void> {+ const { req, res, url, json } = ctx;+ const named = url.searchParams.get("bot");+ const bot = isPlaceId(named) ? ownId(named) : "";+ if (!OWN_ID.test(bot)) return json(res, 400, { error: "name the bot" });+ const stop = new AbortController();+ req.on("close", () => stop.abort());+ const headers = { authorization: `Bearer ${own.token}` };+ const threads = new Set<string>();+ // The conversations the bot has now, so the frames of each are known before the stream's first word about the bot.+ let seed: Response;+ try {+ seed = await fetchImpl(`${own.origin}/api/bots/${encodeURIComponent(bot)}?messages=0`, { redirect: "error", cache: "no-store", signal: AbortSignal.any([stop.signal, AbortSignal.timeout(REQUEST_MS)]), headers: { ...headers, accept: "application/json" } });+ } catch {+ return stop.signal.aborted ? undefined : refuse(res, json, 502, "serverError.place.offline", "place_offline");+ }+ if (!seed.ok) return answer(ctx, seed);+ const seeded = await seed.json().catch(() => null) as { bot?: Record<string, unknown> } | null;+ if (!record(seeded?.bot)) return refuse(res, json, 502, "serverError.place.unsupported", "place_unsupported");+ learnThreads(seeded.bot, threads);+ const since = url.searchParams.get("since") ?? (typeof req.headers["last-event-id"] === "string" ? req.headers["last-event-id"] : null);+ const query = new URLSearchParams({ window: "1", frames: "thread", screens: "off", ...(since ? { since } : {}) });+ let upstream: Response;+ try {+ upstream = await fetchImpl(`${own.origin}/api/events?${query}`, { redirect: "error", cache: "no-store", signal: stop.signal, headers: { ...headers, accept: "text/event-stream" } });+ } catch {+ return stop.signal.aborted ? undefined : refuse(res, json, 502, "serverError.place.offline", "place_offline");+ }+ if (!upstream.ok || !upstream.body || !/^text\/event-stream\b/i.test(upstream.headers.get("content-type") ?? "")) {+ if (!upstream.ok) return answer(ctx, upstream);+ await upstream.body?.cancel().catch(() => {});+ return refuse(res, json, 502, "serverError.place.unsupported", "place_unsupported");+ }+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive", "x-accel-buffering": "no" });+ res.flushHeaders();+ req.socket.setTimeout(0);+ // Not awaited: the request is answered, and the stream runs on until either side closes it.+ void (async () => {+ try {+ for await (const event of sseEvents(upstream.body!)) {+ let frame: unknown;+ try { frame = JSON.parse(event.data); } catch { continue; }+ const kept = frameForBot(frame, bot, threads);+ if (kept === null) continue;+ res.write(`${event.id ? `id: ${event.id}\n` : ""}data: ${JSON.stringify(intoPlace(kept, remember))}\n\n`);+ }+ } catch {+ // The end of either side ends the stream; the page reconnects.+ } finally {+ stop.abort();+ if (!res.writableEnded) res.end();+ }+ })();+ }++ const route: RouteHandler = async (ctx) => {+ const { path, method, res, json } = ctx;+ const events = path === PLACE_EVENTS_PATH;+ const placed = events ? null : placedPath(path);+ if (!events && placed === null) return PASS;+ if (!ownWindow(ctx)) { ctx.req.resume(); return refuse(res, json, 404, "serverError.place.unsupported", "place_unsupported"); }+ if (!session) { ctx.req.resume(); return refuse(res, json, 503, "serverError.place.offline", "place_closed"); }+ if (events) return method === "GET" ? stream(ctx, session) : json(res, 405, { error: "Use GET." });+ if (!allowed(method, placed!)) { ctx.req.resume(); return refuse(res, json, 404, "serverError.place.unsupported", "place_unsupported"); }+ return forward(ctx, session, placed!);+ };++ return {+ route,+ setSession(next: PlaceSession | null) { session = next; if (!next) files.clear(); },+ setOwnerToken(token: string | null) { ownerToken = typeof token === "string" && token ? token : null; },+ hasSession: () => session !== null,+ };+}++export type PlaceProxy = ReturnType<typeof createPlaceProxy>;++/** This server's one proxy, and main's private port feeding it: the session, and the app's capability as main sends it+ * at start (the same message request-auth.ts is given it by). Plain Node, with no port, leaves it with neither. */+export const placeProxy: PlaceProxy = createPlaceProxy();+type Port = { on(event: "message", listener: (event: { data?: unknown }) => void): void };+export function listenPlacePort(port: Port | undefined, proxy: PlaceProxy = placeProxy): void {+ port?.on("message", (event) => {+ const message = event.data;+ const session = parsePlaceSession(message);+ if (session !== undefined) { proxy.setSession(session); return; }+ if (record(message) && message.type === "openmausbot:desktop-mutation-token" && typeof message.token === "string") proxy.setOwnerToken(message.token);+ });+}+listenPlacePort((process as NodeJS.Process & { parentPort?: Port }).parentPort);++export const placeProxyRoutes: RouteHandler = (ctx) => placeProxy.route(ctx);+diff --git a/server/routes/table.ts b/server/routes/table.tsindex a587fa2607..50b9523a00 100644--- a/server/routes/table.ts+++ b/server/routes/table.ts@@ -6,6 +6,7 @@ import { announcementRoutes } from "./announcements.ts";import { cloudSyncRoutes } from "./cloud-sync.ts";import { ownMcpHttpRoutes } from "./own-mcp-http.ts";import { webPanelRoutes } from "./web-panels.ts";+import { placeProxyRoutes } from "../places/place-proxy.ts";export const PASS: unique symbol = Symbol("route.pass");@@ -24,7 +25,7 @@ export interface RouteContext {export type RouteHandler = (ctx: RouteContext) => Promise<typeof PASS | void>;/** Modules with no wiring from index.ts are listed here; index.ts pushes the rest. */-export const ROUTES: RouteHandler[] = [cloudSyncRoutes, ownMcpHttpRoutes, webPanelRoutes, announcementRoutes];+export const ROUTES: RouteHandler[] = [placeProxyRoutes, cloudSyncRoutes, ownMcpHttpRoutes, webPanelRoutes, announcementRoutes];/** True means stop routing. A handler that wrote a response but returned PASS still counts as answered. */export async function dispatchRoutes(routes: readonly RouteHandler[], ctx: RouteContext): Promise<boolean> {diff --git a/server/user-errors.ts b/server/user-errors.tsindex 26eb2c6f3c..2b06cc4bed 100644--- a/server/user-errors.ts+++ b/server/user-errors.ts@@ -78,6 +78,10 @@ export const USER_ERROR = {"serverError.voice.utteranceTooLong": "voice utterances are limited to 500 characters","serverError.goal.alreadyRunning": "A goal is already running in this chat. Stop it before starting another.","serverError.chat.missingConversation": "no such conversation",+ "serverError.place.unsupported": "This works on My Cloud's own page. Open it from the bot's menu.",+ "serverError.place.asleep": "My Cloud is asleep. Send again to wake it.",+ "serverError.place.offline": "My Cloud can't be reached right now. Try again in a moment.",+ "serverError.place.signIn": "This computer isn't signed in to My Cloud. Open My Cloud's page once, then try again.","serverError.department.chiefResponsibility": "Only a Chief of Staff can be made responsible for additional departments","serverError.department.confirmResponsibility": "Confirm which additional departments this Chief is responsible for (acknowledgePeerScope)","serverError.owner.teamOnly": "Only a team's bots report to someone.",diff --git a/shared/place-ids.ts b/shared/place-ids.tsnew file mode 100644index 0000000000..e26356de31--- /dev/null+++ b/shared/place-ids.ts@@ -0,0 +1,76 @@+// A My Cloud bot opened in place on this computer's page (server/places/place-proxy.ts, src/lib/place-chat.ts): its+// conversation is read and written through this computer's own server, which forwards it to My Cloud. Every id of My+// Cloud's that crosses into this page carries My Cloud's key in front (`cloud:<id>`), the same key the one list's rows+// already use (src/lib/place-rows.ts), so a bot, a conversation or a file of My Cloud's never meets one of this computer's+// with the same id. This computer's own ids are `[\w-]` only, so nothing of its own ever starts with the key.+//+// Pure: the server rewrites with it at the boundary, and the page tells a placed id by it.++/** The one place a bot opens in place from today: the person's own My Cloud. */+export const PLACE_KEY = "cloud";+const PREFIX = `${PLACE_KEY}:`;+/** A file of My Cloud's, by the name this page asks for it (`/api/attachments/<name>`): the page only asks for names+ * of letters, digits and dashes, so the key goes in front with dashes. */+export const PLACE_FILE_PREFIX = `${PLACE_KEY}--`;++export const isPlaceId = (value: unknown): value is string => typeof value === "string" && value.startsWith(PREFIX) && value.length > PREFIX.length;+/** My Cloud's own id as this page names it. */+export const placeId = (id: string): string => (isPlaceId(id) ? id : `${PREFIX}${id}`);+/** The id My Cloud itself knows, from the one this page names. */+export const ownId = (id: string): string => (isPlaceId(id) ? id.slice(PREFIX.length) : id);++/** The keys whose values are a bot's or a conversation's id, or a list of them: `botId`, `threadId`, `fromThreadId`,+ * `mainThreadId`, `botIds`… Only these are rewritten, never words: a message that starts with "cloud:" stays as written. */+export const ID_KEY = /^(?:[a-z][a-zA-Z]*(?:Bot|Thread)|bot|thread)Ids?$/;+const FILE_URL = /^\/api\/attachments\/([\w.-]+)$/;++const record = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);+const basename = (path: string): string => path.split(/[\\/]/).pop() ?? "";++type Ids = (id: string) => string;++function rewrite(value: unknown, ids: Ids, files: (path: string) => string, key: string | null, depth: number): unknown {+ if (depth > 64) return value;+ if (typeof value === "string") {+ if (key !== null && ID_KEY.test(key)) return ids(value);+ return value;+ }+ if (Array.isArray(value)) {+ const listOfIds = key !== null && ID_KEY.test(key);+ return value.map((item) => (listOfIds && typeof item === "string" ? ids(item) : rewrite(item, ids, files, key === "bots" ? "bot" : key === "attachments" ? "attachment" : null, depth + 1)));+ }+ if (!record(value)) return value;+ const out: Record<string, unknown> = {};+ for (const [name, item] of Object.entries(value)) {+ // A bot's own id: the bot under `bot`, and each one under `bots`.+ if (name === "id" && key === "bot" && typeof item === "string") out[name] = ids(item);+ else if (name === "path" && key === "attachment" && typeof item === "string") out[name] = files(item);+ else if (typeof item === "string" && FILE_URL.test(item)) out[name] = files(item);+ else out[name] = rewrite(item, ids, files, name, depth + 1);+ }+ return out;+}++/** My Cloud's answer as this page receives it: each bot and conversation id with My Cloud's key in front, and each of+ * its files under a name this page asks for through its own server. `remember(name, path)` keeps the path My Cloud+ * gave a file, so a message sent back that names it names My Cloud's own path again. */+export function intoPlace(value: unknown, remember: (name: string, path: string) => void = () => {}): unknown {+ const files = (path: string) => {+ const at = FILE_URL.exec(path);+ const name = at ? at[1]! : basename(path);+ if (!name || name.startsWith(PLACE_FILE_PREFIX)) return path;+ const placed = `${PLACE_FILE_PREFIX}${name}`;+ remember(placed, path);+ return at ? `/api/attachments/${placed}` : placed;+ };+ return rewrite(value, placeId, files, null, 0);+}++/** What this page sends My Cloud, in My Cloud's own ids. `recall(name)` gives back the path a file came with. */+export function outOfPlace(value: unknown, recall: (name: string) => string | undefined = () => undefined): unknown {+ const files = (path: string) => {+ const name = basename(path);+ return name.startsWith(PLACE_FILE_PREFIX) ? recall(name) ?? path : path;+ };+ return rewrite(value, ownId, files, null, 0);+}diff --git a/src/components/PlacedBotMenu.tsx b/src/components/PlacedBotMenu.tsxnew file mode 100644index 0000000000..1d15477e37--- /dev/null+++ b/src/components/PlacedBotMenu.tsx@@ -0,0 +1,90 @@+// A My Cloud bot's row in this computer's one list: its ⋯ menu (and right-click) offers My Cloud's own page at that bot,+// the way every click opened it before bots opened in place (src/lib/place-chat.ts). Nothing on that menu changes+// anything here: the bot's settings, files and everything else not in its conversation stay on its own page.+// PlaceChatKeeper lets the bot open in place go once the person chooses anything else.+import { useEffect, useLayoutEffect, useRef, useSyncExternalStore } from "react";+import { createPortal } from "react-dom";+import { ExternalLink, MoreHorizontal } from "lucide-react";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { closePlaceBot, isPlaceId, noteChosen } from "@/lib/place-chat";+import { openOtherPlaceBot } from "@/lib/places-together";+import { isPlacedBot, type PlacedBot } from "@/lib/place-rows";+import { useStoreSelector } from "@/state/store-select";+import type { Bot } from "@/state/store";+import { MENU_ITEM, MENU_SHEET } from "./menu-recipe";+import type { MenuState } from "./Sidebar";++let open: { menu: MenuState; ownId: string; name: string } | null = null;+const listeners = new Set<() => void>();+const set = (next: typeof open) => { open = next; for (const listener of listeners) listener(); };+const subscribe = (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; };++/** Placed rows' menus, by the row's key: each row hands its bot here so its right-click finds it. */+const rows = new Map<string, PlacedBot>();++/** What a row of the other place opens as its menu: right-click or its ⋯ button. */+export function openPlacedMenu(menu: MenuState): void {+ const bot = rows.get(menu.botId);+ if (bot) set({ menu, ownId: bot.placedFrom.id, name: bot.name });+}++/** The ⋯ button on a My Cloud row of this computer's page. Elsewhere (My Cloud's own page lists this computer's bots)+ * its row keeps no menu, as before. */+export function PlacedRowActions({ bot, selected, simpleRow }: { bot: Bot; selected: boolean; simpleRow: boolean }) {+ const placed = isPlacedBot(bot) && bot.placedFrom.place.kind === "my-cloud" && Boolean(window.ogb?.placesTogether?.openInPlace) ? bot : null;+ useEffect(() => {+ if (!placed) return;+ rows.set(placed.id, placed);+ return () => { if (rows.get(placed.id) === placed) rows.delete(placed.id); };+ }, [placed]);+ if (!placed) return null;+ return <button type="button" data-placed-actions={placed.id} aria-label={t("sidebar.bot.actions", { name: placed.name })} title={t("sidebar.bot.actions", { name: placed.name })} aria-haspopup="menu"+ onClick={(event) => { const rect = event.currentTarget.getBoundingClientRect(); openPlacedMenu({ botId: placed.id, x: rect.left, y: rect.bottom }); }}+ className={cn("absolute top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded text-ink-secondary hover:bg-raised hover:text-ink", simpleRow ? "end-[3px] top-1.5 size-6 translate-y-0 rounded-lg" : "right-1",+ selected && !simpleRow ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 max-md:pointer-events-auto max-md:opacity-70 touch:pointer-events-auto touch:opacity-70")}><MoreHorizontal size={16} /></button>;+}++/** The menu itself, drawn once for the whole list. */+export function PlacedBotMenuHost() {+ const shown = useSyncExternalStore(subscribe, () => open, () => null);+ const sheet = useRef<HTMLDivElement>(null);+ useLayoutEffect(() => {+ const element = sheet.current;+ if (!shown || !element) return;+ const { width, height } = element.getBoundingClientRect();+ element.style.left = `${Math.max(8, Math.min(shown.menu.x, window.innerWidth - width - 8))}px`;+ element.style.top = `${Math.max(8, Math.min(shown.menu.y, window.innerHeight - height - 8))}px`;+ element.querySelector<HTMLButtonElement>("button")?.focus();+ }, [shown]);+ useEffect(() => {+ if (!shown) return;+ const close = () => set(null);+ const onDown = (event: MouseEvent) => { if (!(event.target instanceof Element) || !event.target.closest("[data-placed-menu]")) close(); };+ const onKey = (event: KeyboardEvent) => { if (event.key === "Escape") close(); };+ window.addEventListener("mousedown", onDown);+ window.addEventListener("keydown", onKey);+ window.addEventListener("blur", close);+ return () => { window.removeEventListener("mousedown", onDown); window.removeEventListener("keydown", onKey); window.removeEventListener("blur", close); };+ }, [shown]);+ if (!shown) return null;+ return createPortal(<div ref={sheet} data-placed-menu="" data-sidebar="" role="menu" data-look="menu" aria-label={t("sidebar.bot.actions", { name: shown.name })}+ className={cn(MENU_SHEET, "fixed z-50 min-w-[220px]")} style={{ left: shown.menu.x, top: shown.menu.y }}>+ <button type="button" role="menuitem" className={cn(MENU_ITEM, "hover:bg-menu-hover")} onClick={() => { const id = shown.ownId; set(null); openOtherPlaceBot(id); }}>+ <ExternalLink size={16} className="shrink-0 text-ink-secondary" aria-hidden="true" />{t("together.openThere")}+ </button>+ </div>, document.body);+}++/** Keeps the store to what the person has open: a My Cloud bot opened in place goes once they choose anything else. */+export function PlaceChatKeeper() {+ const chosen = useStoreSelector((state) => state.selectedId);+ const held = useRef<string | null>(null);+ useEffect(() => {+ noteChosen(chosen);+ const was = held.current;+ held.current = isPlaceId(chosen) ? chosen : null;+ if (was && was !== chosen) closePlaceBot(was);+ }, [chosen]);+ return null;+}diff --git a/src/components/Sidebar.in-place.dom.test.ts b/src/components/Sidebar.in-place.dom.test.tsnew file mode 100644index 0000000000..4734035465--- /dev/null+++ b/src/components/Sidebar.in-place.dom.test.ts@@ -0,0 +1,178 @@+// @vitest-environment happy-dom+// A My Cloud bot opened in place from the real Sidebar's one list: the click readies it through main and opens its+// conversation in this page's own store (src/lib/place-chat.ts), never moving the window; when that can't be done it+// opens on My Cloud's page as before. Its row's menu keeps a way to My Cloud's own page.+import { act, createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Bot } from "@/state/store";+import type { ArrangedBot, PlaceBotRow, PlacesTogetherState } from "@/lib/places-together";++const mode = vi.hoisted(() => ({ advanced: false }));+vi.mock("@/lib/interface-mode", async (original) => ({+ ...await original<typeof import("@/lib/interface-mode")>(), useAdvancedMode: () => mode.advanced,+}));+vi.mock("@/lib/thread-preferences", async (original) => ({+ ...await original<typeof import("@/lib/thread-preferences")>(), useShowThreads: () => mode.advanced,+}));+vi.mock("./DesktopCapabilities", async (original) => ({+ ...await original<typeof import("./DesktopCapabilities")>(),+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: false, platform: "other" }, localComputer: { available: false } }, ready: true }),+}));+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));+vi.mock("@/lib/cloud-guest", () => ({ useCanWriteIn: () => true }));++const { Sidebar } = await import("./Sidebar");+const { BotEditorStore, initialState } = await import("@/state/store");+const { setLocale } = await import("@/lib/i18n");+const { resetPlacesTogetherForTest } = await import("@/lib/places-together");+const { resetPlaceRowsForTest } = await import("@/lib/place-rows");++const bot = (id: string, extra: Partial<Bot> = {}): Bot => ({+ id, name: id[0]!.toUpperCase() + id.slice(1), threadId: `${id}-t`, title: "", description: "", color: "green", unread: false,+ notifications: true, messages: [], modelSelection: { instanceId: "test", model: "test" },+ tasks: [{ threadId: `${id}-t`, title: "Chat", createdAt: 1 }], ...extra,+});+const row = (id: string, over: Partial<PlaceBotRow> = {}): PlaceBotRow => ({ home: "cloud", id, threadId: `t-${id}`, name: id[0]!.toUpperCase() + id.slice(1), color: "blue", ...over });+const said = (over: Partial<PlacesTogetherState> = {}): PlacesTogetherState => ({ v: 1, available: true, on: true, here: "computer",+ other: { home: "cloud", state: "ready", bots: [row("scout", { title: "Open issues" }), row("tech", { unread: true, title: "Deploy check", lastAt: 9_000, preview: "Deploy **passed** on staging." })] }, ...over });+const OWN = [bot("mausbot", { chiefOfStaff: true }), bot("git"), bot("ledger")];++const dispatch = vi.fn();+let host: HTMLDivElement, root: Root, answer: () => Promise<PlacesTogetherState>, changed: () => void;+const page = {+ state: vi.fn(() => answer()),+ set: vi.fn(async () => said()),+ open: vi.fn(async () => true),+ onChanged: vi.fn((callback: () => void) => { changed = callback; return () => {}; }),+ arrange: vi.fn(async (entries: ArrangedBot[]) => entries),+ openInPlace: vi.fn(async (_id: string) => ({ ok: true })),+};+/** This page's store has loaded (its departments are known for sure). */+let hydrated = false;+const tree = (bots: Bot[], icons = false) => createElement(BotEditorStore, {+ value: { state: { ...initialState, connected: true, bots, selectedId: bots[0]!.id, ...(hydrated ? { hydrated: true as const } : {}) }, dispatch,+ flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} },+ children: createElement(Sidebar, { open: true, onClose: () => {}, collapseToIcons: icons }),+});+async function render(bots = OWN, icons = false) {+ await act(async () => root.render(tree(bots, icons)));+ await act(async () => { await Promise.resolve(); });+}+const q = (selector: string) => host.querySelector<HTMLElement>(selector);+const { resetPlaceChatForTest } = await import("@/lib/place-chat");+const scoutThere = { id: "scout", name: "Scout", threadId: "t1", title: "", description: "", color: "blue", notifications: true, unread: false, chiefOfStaff: true,+ modelSelection: { instanceId: "claude", model: "opus" }, tasks: [{ threadId: "t1", title: "Flats", createdAt: 1 }], messages: [{ id: "m1", role: "bot", kind: "text", text: "Four flats.", at: 1 }] };+/** This computer's server, forwarding to My Cloud: the bot in the page's ids, or a refusal. */+let served: (path: string) => Response;+const fetched: string[] = [];+class Source { static made: Source[] = []; url: string; onopen: (() => void) | null = null; onerror: (() => void) | null = null; onmessage: ((event: { data: string }) => void) | null = null; closed = false;+ constructor(url: string) { this.url = url; Source.made.push(this); } close() { this.closed = true; } }++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ fetched.length = 0;+ Source.made = [];+ served = (path) => path.startsWith("/api/bots/cloud%3Ascout")+ ? new Response(JSON.stringify({ bot: { ...scoutThere, id: "cloud:scout", threadId: "cloud:t1", tasks: [{ threadId: "cloud:t1", title: "Flats", createdAt: 1 }] } }), { headers: { "content-type": "application/json" } })+ : new Response("{}", { status: 404 });+ vi.stubGlobal("fetch", async (path: string) => { fetched.push(String(path)); return served(String(path)); });+ vi.stubGlobal("EventSource", Source);+ dispatch.mockReset();+ for (const fn of Object.values(page)) fn.mockClear();+ page.openInPlace.mockImplementation(async () => ({ ok: true }));+ answer = async () => said();+ localStorage.clear();+ hydrated = false;+ setLocale("en");+ mode.advanced = false;+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(async () => {+ await act(async () => root.unmount());+ host.remove();+ resetPlacesTogetherForTest();+ resetPlaceRowsForTest();+ resetPlaceChatForTest();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ delete (window as { ogb?: unknown }).ogb;+});+const settled = () => act(async () => { for (let i = 0; i < 5; i++) await new Promise((done) => setTimeout(done, 0)); });++describe("a My Cloud bot opens in this window", () => {+ it("a click opens its conversation in this page's store, by its place's id: the window never moves", async () => {+ window.ogb = { placesTogether: page } as never;+ await render();+ await act(async () => q('[data-sidebar-bot-row="cloud:scout"]')!.click());+ await settled();+ expect(page.openInPlace.mock.calls).toEqual([["scout"]]);+ expect(page.open).not.toHaveBeenCalled();+ expect(fetched).toContain("/api/bots/cloud%3Ascout?messages=80");+ const actions = dispatch.mock.calls.map(([action]) => action);+ const added = actions.find((action) => action.type === "botPatched");+ expect(added.bot.id).toBe("cloud:scout");+ expect(added.bot.threadId).toBe("cloud:t1");+ // My Cloud's Chief is never this page's Chief, and nothing of it notifies here.+ expect(added.bot.chiefOfStaff).toBe(false);+ expect(added.bot.notifications).toBe(false);+ expect(actions.at(-1)).toEqual({ type: "select", id: "cloud:scout" });+ // Its live stream, through this computer's own server.+ expect(Source.made.map((source) => source.url)).toEqual(["/api/places/cloud/events?bot=cloud%3Ascout"]);+ });++ it("opens on My Cloud's page instead when main can't ready it, or this computer's server can't read it", async () => {+ window.ogb = { placesTogether: page } as never;+ await render();+ page.openInPlace.mockImplementation(async () => ({ ok: false }));+ await act(async () => q('[data-sidebar-bot-row="cloud:scout"]')!.click());+ await settled();+ expect(page.open.mock.calls).toEqual([["scout"]]);+ page.openInPlace.mockImplementation(async () => ({ ok: true }));+ served = () => new Response(JSON.stringify({ error: "no", code: "place_unsupported" }), { status: 404 });+ await act(async () => q('[data-sidebar-bot-row="cloud:tech"]')!.click());+ await settled();+ expect(page.open.mock.calls).toEqual([["scout"], ["tech"]]);+ expect(dispatch.mock.calls.some(([action]) => action.type === "select")).toBe(false);+ });++ it("an app without it opens on My Cloud's page, as before", async () => {+ const { openInPlace: _gone, ...older } = page;+ window.ogb = { placesTogether: older } as never;+ await render();+ await act(async () => q('[data-sidebar-bot-row="cloud:scout"]')!.click());+ expect(page.open.mock.calls).toEqual([["scout"]]);+ expect(q('[data-placed-actions]')).toBeNull();+ });++ it("the row's menu opens My Cloud's own page at that bot, and offers nothing that changes it", async () => {+ window.ogb = { placesTogether: page } as never;+ await render();+ await act(async () => q('[data-placed-actions="cloud:scout"]')!.click());+ // Choosing the menu's button chooses nothing else: the bot is not opened by it.+ expect(page.openInPlace).not.toHaveBeenCalled();+ const menu = document.querySelector<HTMLElement>("[data-placed-menu]")!;+ expect([...menu.querySelectorAll("[role=menuitem]")].map((item) => item.textContent)).toEqual(["Open on My Cloud's page"]);+ await act(async () => menu.querySelector<HTMLElement>("[role=menuitem]")!.click());+ expect(page.open.mock.calls).toEqual([["scout"]]);+ expect(document.querySelector("[data-placed-menu]")).toBeNull();+ // Right-click opens the same menu.+ await act(async () => { q('[data-sidebar-bot-row="cloud:scout"]')!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 5 })); });+ expect(document.querySelector("[data-placed-menu]")).not.toBeNull();+ });++ it("the bot open in place is drawn once, as its row, which shows it chosen", async () => {+ window.ogb = { placesTogether: page } as never;+ const open = { ...bot("scout"), id: "cloud:scout", threadId: "cloud:t1", name: "Scout" };+ await act(async () => root.render(createElement(BotEditorStore, {+ value: { state: { ...initialState, connected: true, bots: [...OWN, open], selectedId: "cloud:scout" }, dispatch, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} },+ children: createElement(Sidebar, { open: true, onClose: () => {} }),+ })));+ await act(async () => { await Promise.resolve(); });+ expect(host.querySelectorAll('[data-sidebar-bot-row="cloud:scout"]').length).toBe(1);+ expect(host.querySelector('[aria-current="page"][data-sidebar-bot-row], [aria-current="page"] [data-sidebar-bot-row]')?.getAttribute("data-sidebar-bot-row")).toBe("cloud:scout");+ });+});diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex 4a5f162314..b4de06df23 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -73,7 +73,7 @@ import { SidebarProfileMenu } from "./SidebarProfileMenu";import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";import { GlassBar, GlassScrollFrame, GlassScroller } from "./GlassScrollFrame";import { DesktopWorkspaceSwitcher, endCloudHowTo } from "./DesktopWorkspaceSwitcher"; import { PlaceTint } from "./PlaceTint"; import { ChromeRailToggle } from "./ChromeRailToggle";-import { useCloudOwner } from "./CloudOwner"; import { OtherPlaceLine } from "./OtherPlaceBots"; import { BotPlaceBadge, BotPlaceMark } from "./BotPlaceMark"; import { isPlacedBot, NO_MENU, otherPlaceDispatch, placedLine, rowPlaceMark, useOneListHere, useOtherPlaceBots } from "@/lib/place-rows"; import { useOneList } from "./one-list-sidebar"; const NO_SECTIONS: string[] = []; import type { BotHome } from "@/lib/places-together"; import { NewBotOtherPlaceItem, useNewBotHereLabel } from "./NewBotPlaceItems";+import { useCloudOwner } from "./CloudOwner"; import { OtherPlaceLine } from "./OtherPlaceBots"; import { BotPlaceBadge, BotPlaceMark } from "./BotPlaceMark"; import { isPlacedBot, otherPlaceDispatch, placedLine, rowPlaceMark, useOneListHere, useOtherPlaceBots } from "@/lib/place-rows"; import { openPlacedMenu, PlaceChatKeeper, PlacedBotMenuHost, PlacedRowActions } from "./PlacedBotMenu"; import { isPlaceId } from "@/lib/place-chat"; import { useOneList } from "./one-list-sidebar"; const NO_SECTIONS: string[] = []; import type { BotHome } from "@/lib/places-together"; import { NewBotOtherPlaceItem, useNewBotHereLabel } from "./NewBotPlaceItems";import { SidebarSectionHeader } from "./SidebarSectionHeader";import { NeedsYouButton, OwnerPickerHost } from "./TeamOwner"; import { SidebarPeople } from "./SidebarPeople"; import { SidebarInboxRow } from "./SidebarInboxRow"; import { TeamSideSwitch, useTeamSideLists } from "./TeamSideSwitch"; import { SidebarActiveThreads } from "./SidebarActiveThreads"; import { setAttentionPinned, useAttentionPinned } from "./inbox/attention-pinned"; import { useInboxSupport } from "@/state/inbox";import { TeamMenuItems } from "./SidebarTeamMenu";@@ -902,7 +902,7 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {<button type="button" data-bot-actions={bot.id} aria-label={t("sidebar.bot.actions", { name: bot.name })} title={t("sidebar.bot.actions", { name: bot.name })} aria-haspopup="menu" onClick={(event) => { const rect = event.currentTarget.getBoundingClientRect(); onMenu({ botId: bot.id, x: rect.left, y: rect.bottom }); }}className={cn("absolute top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded text-ink-secondary hover:bg-raised hover:text-ink", simpleRow ? "end-[3px] top-1.5 size-6 translate-y-0 rounded-lg" : "right-1",selected && !simpleRow ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 max-md:pointer-events-auto max-md:opacity-70 touch:pointer-events-auto touch:opacity-70")}><MoreHorizontal size={16} /></button>- </>}{!renaming && !deleting && simpleRow && !placed && <ThreadFoldChevron bot={bot} dispatch={dispatch} />}+ </>}{!renaming && !deleting && simpleRow && !placed && <ThreadFoldChevron bot={bot} dispatch={dispatch} />}{placed && !iconOnly && <PlacedRowActions bot={bot} selected={selected} simpleRow={simpleRow} />}{deleting && iconOnly && (<span className="pointer-events-none absolute bottom-1 right-1 rounded-full bg-card p-1 text-ink-secondary"><Loader2 size={12} className="animate-spin" />@@ -1078,7 +1078,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =onError: (text) => setTeamFeedback({ error: true, text }), onCancelled: () => sidebarRef.current?.focus() }), roomDrag = useSidebarRoomDrag({ dispatch, announce: sections.announce, enabled: (sections.interactive || density === "icons") && !phone && !q, groups: state.groups });const sideLists = useTeamSideLists(state), matchingBots = sideLists.bots- .filter((b) => !b.hidden)+ .filter((b) => !b.hidden && !isPlaceId(b.id)) // a My Cloud bot open in place is drawn as its own row of the one list.filter((b) =>!q ||@@ -1118,7 +1118,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =const showAttention = (advanced && inboxSupport === "no") || (attentionPinned && density !== "icons");const attention = showAttention ? crossBotAttentionThreads(state.bots, state.pendingQueued, undefined, state.groups) : [];const restoreBot = teamFeedback?.restoreBot, pendingUndo = teamFeedback?.undo ?? (restoreBot ? () => void undoBotArchive(restoreBot) : undefined);- const botRow = (bot: Bot) => isPlacedBot(bot) ? botRowProps(state, otherPlaceDispatch(bot), bot, { density, query: q, onMenu: NO_MENU, placeHere, ...drops.row(bot.id) }) : botRowProps(state, dispatch, bot, { density, query: q, onMenu: setMenu, placeHere, renameRequest: renameRequest?.botId === bot.id ? renameRequest.nonce : 0, ...drops.row(bot.id) });+ const botRow = (bot: Bot) => isPlacedBot(bot) ? botRowProps(state, otherPlaceDispatch(bot, dispatch), bot, { density, query: q, onMenu: openPlacedMenu, placeHere, ...drops.row(bot.id) }) : botRowProps(state, dispatch, bot, { density, query: q, onMenu: setMenu, placeHere, renameRequest: renameRequest?.botId === bot.id ? renameRequest.nonce : 0, ...drops.row(bot.id) });const railSearch = () => {if (collapseToIcons) return openCommandPalette();setSearchOpen(true);@@ -1457,7 +1457,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =</div>);})}- <OtherPlaceLine query={query} icons={density === "icons"} /><MovedBotRows bots={state.bots} /><MovedToMyCloudRow bots={state.bots} /><SearchResults query={query} onLanded={() => { setQuery(""); setSearchOpen(false); }} />+ <OtherPlaceLine query={query} icons={density === "icons"} /><PlacedBotMenuHost /><PlaceChatKeeper /><MovedBotRows bots={state.bots} /><MovedToMyCloudRow bots={state.bots} /><SearchResults query={query} onLanded={() => { setQuery(""); setSearchOpen(false); }} />{showPinnedCircleThreads && (<PinnedCircleThreadSectionbots={pinnedBots}diff --git a/src/lib/live-events.ts b/src/lib/live-events.tsindex 5600f0ff82..81cc63d647 100644--- a/src/lib/live-events.ts+++ b/src/lib/live-events.ts@@ -100,6 +100,16 @@ export function withoutScreenPixels(frame: ServerFrame): ServerFrame {return { ...rest, png: "" };}+/** Where frames of a bot open in place (src/lib/place-chat.ts) go: the store's own way in for this page's live frames. */+let placeSink: ((frame: LiveFrame) => void) | null = null;+export function placeFrames<T extends (frame: LiveFrame) => void>(sink: T): T {+ placeSink = sink;+ return sink;+}+export function placeFrame(frame: ServerFrame): void {+ placeSink?.(frame as LiveFrame);+}+export function publishLiveFrame(frame: ServerFrame): void {for (const listener of liveFrameListeners) listener.onFrame(frame);}diff --git a/src/lib/place-chat.dom.test.ts b/src/lib/place-chat.dom.test.tsnew file mode 100644index 0000000000..f3b8c40943--- /dev/null+++ b/src/lib/place-chat.dom.test.ts@@ -0,0 +1,114 @@+// @vitest-environment happy-dom+// A My Cloud bot opened in place, in this page's real store: its conversation comes in under its place's ids, its live+// frames land in it exactly as this page's own do, a fresh read of this computer's server keeps it, and it leaves the+// store (its stream with it) once the person chooses another bot.+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { StoreProvider, useStore } from "@/state/store";+import { PlaceChatKeeper } from "@/components/PlacedBotMenu";+import { openPlaceBot, resetPlaceChatForTest } from "./place-chat";++class Source {+ static made: Source[] = [];+ url: string; closed = false;+ onopen: (() => void) | null = null; onerror: (() => void) | null = null; onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;+ constructor(url: string) { this.url = url; Source.made.push(this); }+ close() { this.closed = true; }+ say(frame: unknown, id = "") { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }+}+const local = () => Source.made.filter((source) => source.url.startsWith("/api/events")).at(-1)!;+const placed = () => Source.made.filter((source) => source.url.startsWith("/api/places/cloud/events")).at(-1)!;++const ledger = { id: "ledger", name: "Ledger", threadId: "l1", title: "", description: "", color: "orange", notifications: true, unread: false, createdAt: 1,+ modelSelection: { instanceId: "claude", model: "opus" }, tasks: [{ threadId: "l1", title: "Invoices", createdAt: 1 }], messages: [] };+const scout = { id: "cloud:scout", name: "Scout", threadId: "cloud:t1", title: "", description: "", color: "blue", notifications: true, unread: false, createdAt: 1, chiefOfStaff: true,+ modelSelection: { instanceId: "claude", model: "opus" }, tasks: [{ threadId: "cloud:t1", title: "Flats", createdAt: 1 }],+ messages: [{ id: "m1", role: "bot", kind: "text", text: "Four flats under budget.", at: 1 }] };++let store!: ReturnType<typeof useStore>;+function Reader() { store = useStore(); return null; }+let root: Root;+const asked: string[] = [];+const settle = () => act(async () => { for (let i = 0; i < 8; i++) await new Promise((done) => setTimeout(done, 0)); });+const bots = () => store.state.bots.map((bot) => bot.id);++beforeEach(async () => {+ Source.made = [];+ asked.length = 0;+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.stubGlobal("EventSource", Source);+ vi.stubGlobal("fetch", async (path: unknown) => {+ const url = String(path);+ asked.push(url);+ const body = url.startsWith("/api/bots/cloud%3Ascout") ? { bot: scout } : url.startsWith("/api/bots?") || url === "/api/bots" ? { bots: [ledger, { ...ledger, id: "git", name: "Git", threadId: "g1", tasks: [{ threadId: "g1", title: "Notes", createdAt: 1 }] }], groups: [], sections: [], botQueuedMessages: {}, computerControl: {} } : {};+ return new Response(JSON.stringify(body), { headers: { "content-type": "application/json" } });+ });+ window.ogb = { placesTogether: { openInPlace: async () => ({ ok: true }), open: vi.fn(async () => true) } } as never;+ root = createRoot(document.createElement("div"));+ await act(async () => root.render(createElement(StoreProvider, null, createElement(Reader), createElement(PlaceChatKeeper))));+ await act(async () => local().say({ kind: "hello", cursor: "s:1", resumed: false }));+ await settle();+});+afterEach(async () => {+ await act(async () => root.unmount());+ resetPlaceChatForTest();+ vi.unstubAllGlobals();+ delete (window as { ogb?: unknown }).ogb;+});++it("opens in the store under its place's ids, takes its live frames, survives a fresh read and leaves when another bot is chosen", async () => {+ expect(bots()).toEqual(["ledger", "git"]);+ let opened: string | undefined;+ await act(async () => { opened = await openPlaceBot("scout", store.dispatch); });+ await settle();+ expect(opened).toBe("here");+ expect(store.state.selectedId).toBe("cloud:scout");+ expect(bots()).toContain("cloud:scout");+ const shown = store.state.bots.find((bot) => bot.id === "cloud:scout")!;+ expect(shown.chiefOfStaff).toBe(false);+ expect(shown.messages.map((message) => message.id)).toEqual(["m1"]);++ // A turn's message on the bot's own stream lands in its conversation, by the conversation's place id.+ expect(placed().url).toBe("/api/places/cloud/events?bot=cloud%3Ascout");+ await act(async () => placed().say({ kind: "message", threadId: "cloud:t1", message: { id: "m2", role: "bot", kind: "text", text: "Trains at 9.", at: 2 } }, "s:9"));+ await settle();+ expect(store.state.bots.find((bot) => bot.id === "cloud:scout")!.messages.map((message) => message.id)).toEqual(["m1", "m2"]);++ // This computer's own stream starting over reads its server again: the bot open in place stays, and stays chosen.+ await act(async () => local().say({ kind: "hello", cursor: "s:2", resumed: false }));+ await settle();+ expect(bots()).toEqual(["ledger", "git", "cloud:scout"]);+ expect(store.state.selectedId).toBe("cloud:scout");++ // Choosing another bot lets it go, and its stream with it.+ await act(async () => store.dispatch({ type: "select", id: "ledger" }));+ await settle();+ expect(bots()).toEqual(["ledger", "git"]);+ expect(placed().closed).toBe(true);+ expect((window.ogb!.placesTogether!.open as ReturnType<typeof vi.fn>)).not.toHaveBeenCalled();+});++it("My Cloud going to sleep closes its stream quietly; the person's next click opens it again", async () => {+ await act(async () => { await openPlaceBot("scout", store.dispatch); });+ await settle();+ const first = placed();+ await act(async () => first.say({ kind: "power", state: "sleeping" }));+ expect(first.closed).toBe(true);+ expect(Source.made.filter((source) => source.url.startsWith("/api/places/")).length).toBe(1);+ await act(async () => { window.dispatchEvent(new Event("pointerdown")); });+ expect(placed()).not.toBe(first);+ expect(store.state.error ?? null).toBeNull();+});++it("a click overtaken by the person choosing something else lands nowhere", async () => {+ let release!: (value: { ok: boolean }) => void;+ window.ogb = { placesTogether: { openInPlace: () => new Promise((done) => { release = done; }), open: vi.fn(async () => true) } } as never;+ let opened: Promise<string> | undefined;+ await act(async () => { opened = openPlaceBot("scout", store.dispatch); });+ await act(async () => store.dispatch({ type: "select", id: "git" }));+ await act(async () => { release({ ok: true }); });+ expect(await opened).toBe("overtaken");+ expect(store.state.selectedId).toBe("git");+ expect(bots()).toEqual(["ledger", "git"]);+});diff --git a/src/lib/place-chat.ts b/src/lib/place-chat.tsnew file mode 100644index 0000000000..9cd824101b--- /dev/null+++ b/src/lib/place-chat.ts@@ -0,0 +1,173 @@+// A My Cloud bot opened in place: clicking its row in the one list shows its conversation here, in this window, with+// the sidebar and everything else as they were. This page still talks only to its own server: the bot is this page's+// as `cloud:<id>` (shared/place-ids.ts), and this computer's server forwards what is asked of it to My Cloud+// (server/places/place-proxy.ts) with the session main opened there for it (electron/place-chat-main.mjs).+//+// The bot is in the page's store only while it is the one open: it comes in when its row is chosen, and goes when+// another bot or page is chosen (PlaceChatKeeper). Its live turns come on a stream of their own, cut to that bot, and+// feed the store exactly as this page's own stream does.+//+// A My Cloud that can't do this (an app from before it, a sign-in that fails, a route it lacks) opens as before: main+// moves the window to My Cloud's own page at that bot. Nothing is half-shown.+import type { Dispatch } from "react";+import { isPlaceId, ownId, placeId } from "../../shared/place-ids";+import type { ServerFrame } from "../../shared/wire";+import { placeFrame } from "./live-events";+import { openOtherPlaceBot } from "./places-together";+import { api } from "@/state/api";+import type { Action, Bot } from "@/state/store";++export { isPlaceId };++/** How many of its newest messages the conversation opens with, as switching to one of this page's own conversations. */+const OPEN_MESSAGES = 80;+export const PLACE_EVENTS_PATH = "/api/places/cloud/events";+const RETRY_MS = [1_000, 2_000, 5_000, 15_000];+/** A stream that never opened after this many tries: the conversation can't be kept live here, so it opens there. */+const FIRST_TRIES = 3;++const bridge = () => (typeof window === "undefined" || window.ogb?.remoteClient?.active ? undefined : window.ogb?.placesTogether);++/** The bots a fresh read of this page's own server keeps: the one My Cloud bot open in place is not its server's to list. */+export function keptPlaceBots<T extends { id: string }>(bots: readonly T[]): T[] {+ return bots.filter((bot) => isPlaceId(bot.id));+}++/** My Cloud's bot as this page holds it. Never this page's Chief (there is one per place), and nothing of it notifies here. */+export function placeBot(bot: Bot): Bot {+ return { ...bot, chiefOfStaff: false, notifications: false, messages: bot.messages ?? [] } as Bot;+}++/** What the person last chose in this page (PlaceChatKeeper keeps it): a click that is overtaken by another choice lands nowhere. */+let chosen: string | null = null;+let clicks = 0;+let live: { key: string; stop: () => void } | null = null;++export function noteChosen(id: string | null): void {+ chosen = id;+}++/** Opens My Cloud's bot `id` (its id on My Cloud) here. `dispatch` is this page's store. Falls back to opening My Cloud's+ * page at it whenever it can't open here. */+export async function openPlaceBot(id: string, dispatch: Dispatch<Action>): Promise<"here" | "there" | "overtaken"> {+ const mine = ++clicks, before = chosen, key = placeId(id);+ const overtaken = () => mine !== clicks || chosen !== before;+ const there = () => { openOtherPlaceBot(id); return "there" as const; };+ const page = bridge();+ if (!page?.openInPlace) return there();+ let opened: { ok: boolean } | null = null;+ try { opened = await page.openInPlace(id); } catch { opened = null; }+ if (overtaken()) return "overtaken";+ if (!opened?.ok) return there();+ let bot: Bot;+ try {+ ({ bot } = await api<{ bot: Bot }>(`/api/bots/${encodeURIComponent(key)}?messages=${OPEN_MESSAGES}`));+ if (!bot || bot.id !== key) throw new Error("not this bot");+ } catch {+ return overtaken() ? "overtaken" : there();+ }+ if (overtaken()) return "overtaken";+ dispatch({ type: "botPatched", bot: placeBot(bot) });+ dispatch({ type: "select", id: key });+ chosen = key;+ keepLive(key, () => there());+ return "here";+}++/** The person left the bot open in place: its stream ends, and it leaves the store. */+export function closePlaceBot(key: string): void {+ if (live?.key === key) { live.stop(); live = null; }+ placeFrame({ kind: "bot.deleted", botId: key });+}++/** Reads the bot again (the stream started over, or resumed from too far back). */+async function reread(key: string): Promise<void> {+ try {+ const { bot } = await api<{ bot: Bot }>(`/api/bots/${encodeURIComponent(key)}?messages=${OPEN_MESSAGES}`);+ if (bot?.id === key && live?.key === key) placeFrame({ kind: "bot", bot: placeBot(bot) } as unknown as ServerFrame);+ } catch {+ // The stream's own retry reads again.+ }+}++interface Platform {+ createEventSource(url: string): { onopen: (() => void) | null; onerror: (() => void) | null; onmessage: ((event: { data: string; lastEventId?: string }) => void) | null; close(): void };+ visible(): boolean;+ target?: Pick<Window, "addEventListener" | "removeEventListener">;+}++const browser = (): Platform => ({+ createEventSource: (url) => {+ const native = new EventSource(url);+ const source: ReturnType<Platform["createEventSource"]> = { onopen: null, onerror: null, onmessage: null, close: () => native.close() };+ native.onopen = () => source.onopen?.();+ native.onerror = () => source.onerror?.();+ native.onmessage = (event) => source.onmessage?.(event);+ return source;+ },+ visible: () => typeof document === "undefined" || document.visibilityState === "visible",+ target: typeof window === "undefined" ? undefined : window,+});++/** The bot's live stream while it is open here and the page is in sight. My Cloud going to sleep closes it quietly; the+ * person's next click, key or return to the window opens it again, which wakes My Cloud as any use of it does. */+export function keepLive(key: string, cannot: () => void, platform: Platform = browser()): () => void {+ live?.stop();+ let source: ReturnType<Platform["createEventSource"]> | null = null, since: string | null = null, tries = 0, opened = false, stopped = false, asleep = false;+ let timer: ReturnType<typeof setTimeout> | null = null;+ const close = () => { if (source) { source.onopen = source.onerror = source.onmessage = null; source.close(); source = null; } };+ const connect = () => {+ if (stopped || source || asleep || !platform.visible()) return;+ const url = `${PLACE_EVENTS_PATH}?bot=${encodeURIComponent(key)}${since ? `&since=${encodeURIComponent(since)}` : ""}`;+ const current = platform.createEventSource(url);+ source = current;+ current.onopen = () => { opened = true; tries = 0; };+ current.onerror = () => {+ if (source !== current) return;+ close();+ tries += 1;+ if (!opened && tries >= FIRST_TRIES) { stop(); cannot(); return; }+ // This computer's server may have restarted since, without the session: main tells it again.+ if (opened) void bridge()?.openInPlace?.(ownId(key)).catch(() => {});+ timer = setTimeout(() => { timer = null; connect(); }, RETRY_MS[Math.min(tries - 1, RETRY_MS.length - 1)]);+ };+ current.onmessage = (event) => {+ if (source !== current) return;+ if (event.lastEventId) since = event.lastEventId;+ let frame: { kind?: unknown; resumed?: unknown; state?: unknown };+ try { frame = JSON.parse(event.data); } catch { return; }+ if (frame.kind === "ping") return;+ if (frame.kind === "hello") { if (frame.resumed !== true) void reread(key); return; }+ if (frame.kind === "power") {+ if (frame.state === "sleeping") { asleep = true; close(); }+ return;+ }+ placeFrame(frame as ServerFrame);+ };+ };+ const wake = () => {+ if (!platform.visible()) { close(); return; }+ if (asleep) { asleep = false; connect(); } else if (!source && timer === null) connect();+ };+ const events = ["pointerdown", "keydown", "focus", "visibilitychange"] as const;+ for (const name of events) platform.target?.addEventListener(name, wake, { capture: true });+ const stop = () => {+ stopped = true;+ if (timer !== null) clearTimeout(timer);+ close();+ for (const name of events) platform.target?.removeEventListener(name, wake, { capture: true });+ };+ live = { key, stop };+ connect();+ return stop;+}++/** The open bot's own id on My Cloud, for "Open on My Cloud's page". */+export const placeOwnId = (key: string): string => ownId(key);++export function resetPlaceChatForTest(): void {+ live?.stop();+ live = null;+ chosen = null;+ clicks = 0;+}diff --git a/src/lib/place-rows.ts b/src/lib/place-rows.tsindex 893c88c523..33c5bacae4 100644--- a/src/lib/place-rows.ts+++ b/src/lib/place-rows.ts@@ -19,6 +19,7 @@ import { localizedTaskTitle } from "./task-title";import { plainPreviewText } from "../../shared/plain-preview";import { MAUS_COLOR_NAMES, type MausColor } from "./mascot";import { openOtherPlaceBot, usePlacesTogetherPart, type BotHome, type PlaceBotRow, type PlacesTogetherState } from "./places-together";+import { openPlaceBot } from "./place-chat";/** How a place is doing, as main last said. Asleep and waking are normal for a Cloud, never an error. */export type PlaceHealth = NonNullable<PlacesTogetherState["other"]>["state"];@@ -137,23 +138,25 @@ export function useOtherPlaceBots(query: string): readonly PlacedBot[] {/** The last search's rows, kept while the list and the words stay the same (no hook: the sidebar calls this on every draw). */let lastSearch: { all: readonly PlacedBot[]; query: string; found: readonly PlacedBot[] } = { all: NONE, query: "", found: NONE };-const openers = new Map<string, Dispatch<Action>>();+const openers = new Map<string, { store: Dispatch<Action> | undefined; opener: Dispatch<Action> }>();-/** What a row of the other place does with what its row would send this place's store: choosing it opens its bot where- * it lives (main switches the window there, as a row of the old group did), once per click or key; renaming, a new- * conversation, a folder or anything else is not for this place and is dropped. */-export function otherPlaceDispatch(bot: PlacedBot): Dispatch<Action> {+/** What a row of the other place does with what its row would send this place's store: choosing it opens its bot, once+ * per click or key. A My Cloud bot on this computer's page opens right here, in this window (src/lib/place-chat.ts:+ * `store` is this page's store); anywhere else, or when that can't be done, main switches the window to the place it+ * lives in, as before. Renaming, a folder or anything else is not for this place and is dropped. */+export function otherPlaceDispatch(bot: PlacedBot, store?: Dispatch<Action>): Dispatch<Action> {const had = openers.get(bot.id);- if (had) return had;- const { id } = bot.placedFrom;+ if (had && had.store === store) return had.opener;+ const { id, place } = bot.placedFrom;let opening = false;const opener: Dispatch<Action> = (action) => {if ((action.type !== "select" && action.type !== "switchTask") || opening) return;opening = true;queueMicrotask(() => { opening = false; });- openOtherPlaceBot(id);+ if (store && place.kind === "my-cloud") void openPlaceBot(id, store);+ else openOtherPlaceBot(id);};- openers.set(bot.id, opener);+ openers.set(bot.id, { store, opener });return opener;}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 6dd78e269f..aeda640bdd 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -10155,6 +10155,10 @@"serverError.decider.accountId": "A Cloudflare account ID is 32 letters and digits.","serverError.goal.alreadyRunning": "A goal is already running in this chat. Stop it before starting another.","serverError.chat.missingConversation": "no such conversation",+ "serverError.place.unsupported": "This works on My Cloud's own page. Open it from the bot's menu.",+ "serverError.place.asleep": "My Cloud is asleep. Send again to wake it.",+ "serverError.place.offline": "My Cloud can't be reached right now. Try again in a moment.",+ "serverError.place.signIn": "This computer isn't signed in to My Cloud. Open My Cloud's page once, then try again.","serverError.department.chiefResponsibility": "Only a Chief of Staff can be made responsible for additional departments","serverError.department.confirmResponsibility": "Confirm which additional departments this Chief is responsible for (acknowledgePeerScope)","serverError.owner.teamOnly": "Only a team's bots report to someone.",@@ -11613,6 +11617,7 @@"together.onComputer": "On this computer","together.state.asleep": "My Cloud is asleep. Open a bot to wake it.","together.state.waking": "My Cloud is waking up…",+ "together.openThere": "Open on My Cloud's page","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",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 6085952c5b..eef85c96ed 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -10078,6 +10078,10 @@"serverError.decider.accountId": "O ID de uma conta da Cloudflare tem 32 letras e números.","serverError.goal.alreadyRunning": "Já há um objetivo em andamento nesta conversa. Interrompa esse objetivo antes de iniciar outro.","serverError.chat.missingConversation": "esta conversa não existe",+ "serverError.place.unsupported": "Isso funciona na própria página do My Cloud. Abra-a pelo menu do bot.",+ "serverError.place.asleep": "O My Cloud está dormindo. Envie de novo para ativá-lo.",+ "serverError.place.offline": "Não é possível acessar o My Cloud agora. Tente de novo em instantes.",+ "serverError.place.signIn": "Este computador não está conectado ao My Cloud. Abra a página do My Cloud uma vez e tente de novo.","serverError.department.chiefResponsibility": "Só um chefe de gabinete pode ser responsável por outras equipes","serverError.department.confirmResponsibility": "Confirme por quais outras equipes este chefe de gabinete é responsável (acknowledgePeerScope)","serverError.owner.teamOnly": "Só os bots de uma equipe respondem a alguém.",@@ -11586,6 +11590,7 @@"together.onComputer": "Neste computador","together.state.asleep": "O My Cloud está em repouso. Abra um bot para ativá-lo.","together.state.waking": "O My Cloud está sendo ativado…",+ "together.openThere": "Abrir na página do My Cloud","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",diff --git a/src/state/store.tsx b/src/state/store.tsxindex 29feddb6ce..76c4b4b755 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -69,7 +69,7 @@ export { formatTime } from "@/lib/clock-time";import { createBotPatchQueue, flushWhenLeaving, keepaliveFits, type BotUpdatePatch } from "./bot-patch-queue"; import { createNewTaskOnce } from "./new-task-once"; import { createNewChat, reduceNewChat, type MakeNewChatAction, type NewChat } from "./new-chat";import { liveCallFromFrame, nextLiveCallLookup } from "./live-call";import { isNoAiRefusal, useChatErrorClear } from "./chat-error";-import { openLiveEvents, publishLiveFrame, publishMissedFrames, withoutScreenPixels } from "@/lib/live-events";+import { openLiveEvents, placeFrames, publishLiveFrame, publishMissedFrames, withoutScreenPixels } from "@/lib/live-events"; import { keptPlaceBots } from "@/lib/place-chat";import { unlessRefused } from "@/lib/admin-scope";import { olderRunsSince, ROUTINE_RUNS_WINDOW_MS, trimRoutineRuns, withOlderRoutineRuns } from "./routine-runs";import { reconcileSnapshotQueues, rememberConsumedQueueId, replaceBotQueues } from "./queue-receipts";@@ -876,15 +876,15 @@ function reduceApp(state: AppState, action: Action): AppState {if (isNotificationFeedAction(action)) return { ...state, notifications: reduceNotificationFeed(state.notifications, action) };switch (action.type) {case "hydrate": {- const selectedId = hydratedSelectedId(state.selectedId, action.bots, action.groups, action.resumeId);+ const placed = keptPlaceBots(state.bots), selectedId = hydratedSelectedId(state.selectedId, [...action.bots, ...placed], action.groups, action.resumeId); // a bot open in place is My Cloud'sconst hydrated = {...state,- bots: action.bots.map((sent) => {+ bots: [...action.bots.map((sent) => {const bot = sent.messages ? sent : { ...sent, messages: [] };const previous = state.bots.find((candidate) => candidate.id === bot.id);return keepBotNavigation(previous, previous ? { ...bot, tasks: mergeTaskStamps(previous.tasks, bot.tasks) } : bot,action.preserveNavigation === true && navigatedSince(previous, action.navigationSince, state.transcriptGeneration), action.taskIdsAtStart);- }),+ }), ...placed],groups: action.groups.map((group) => {const previous = state.groups.find((candidate) => candidate.id === group.id);const merged = previous ? { ...group, tasks: mergeTaskStamps(previous.tasks, group.tasks) } : group;@@ -3183,11 +3183,11 @@ export function StoreProvider({ children }: { children: ReactNode }) {forgetLiveTurns();return hydrate();},- onFrame: (frame) => {+ onFrame: placeFrames((frame) => { // a bot open in place feeds the store the same way (src/lib/place-chat.ts)publishLiveFrame(frame as ServerFrame);const queued = withoutScreenPixels(frame as ServerFrame); // the store reads only a screen frame's botIdif (hydrated) store.enqueueFrame(queued, frame.kind === "live.call"); else pendingFrames.push(queued);- },+ }),});return () => {alive = false;