Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

One list: a My Cloud bot in place plays its files, never escapes its routes, never runs My Cloud's bytes, and never wakes My Cloud by itself

milind-soni01142da97e4d
diff --git a/electron/place-chat-main.node-test.mjs b/electron/place-chat-main.node-test.mjs
index 7f66f82cbd..82efff0d08 100644
--- a/electron/place-chat-main.node-test.mjs
+++ b/electron/place-chat-main.node-test.mjs
@@ -82,6 +82,20 @@ test("a session My Cloud refused is replaced when asked: the old one let go, a n
assert.equal(f.grants, 2);
});
+test("a session redeemed after the account changed is signed out, never kept or told to the server", async () => {
+ let release;
+ const f = setup({ pair: () => new Promise((done) => { release = done; }) });
+ const opening = f.chat.ensure();
+ await settle();
+ f.cloud = { ...f.cloud, account: "acct-b" };
+ release(answer(200, { token: TOKEN }));
+ assert.deepEqual(await opening, { ok: false });
+ assert.equal(f.chat.open(), false);
+ assert.deepEqual(f.told, []);
+ await settle();
+ assert.ok(f.asked.some(([url, init]) => url === `${CLOUD}/api/auth/logout` && init.headers.authorization === `Bearer ${TOKEN}`), "signed out at My Cloud");
+});
+
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 });
@@ -103,25 +117,49 @@ function together(inPlace, over = {}) {
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);
+test("only a bot main listed, and only from this computer's page: neither asks for a session", async () => {
+ const calls = { ensure: 0 };
+ const f = together({ ensure: async () => { calls.ensure += 1; return { ok: true }; }, close: () => {} });
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);
+ assert.deepEqual(await f.together.openInPlace("computer", "scout"), { ok: true }, "a listed bot from this computer's page does");
+ assert.equal(calls.ensure, 1);
+});
+
+test("the row says My Cloud is waking while the click readies it, and the session goes with the lists", async () => {
+ let release;
+ const calls = { close: 0 };
+ const f = together({ ensure: () => new Promise((done) => { release = done; }), close: () => { calls.close += 1; } });
+ f.together.state("computer");
+ await f.together.refresh("cloud");
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");
+ assert.equal(f.together.state("computer").other.state, "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.
+ const before = calls.close;
f.together.set("computer", false);
- assert.ok(calls.close >= 1);
+ assert.equal(calls.close, before + 1, "switched off: the session is let go");
+});
+
+test("whether My Cloud is awake comes from the Admin's word, never from My Cloud, and only for this computer's page", async () => {
+ let checks = 0, admin = true;
+ const f = together({ ensure: async () => ({ ok: true }), close: () => {} }, { powerChecked: async () => { checks += 1; return admin; } });
+ f.together.state("computer");
+ await f.together.refresh("cloud");
+ const before = checks;
+ assert.equal(await f.together.cloudAwake("cloud"), false);
+ assert.equal(checks, before, "My Cloud's own page is never answered");
+ assert.equal(await f.together.cloudAwake("computer"), true);
+ f.cloud = { ...f.cloud, asleep: true };
+ assert.equal(await f.together.cloudAwake("computer"), false, "the Admin says it sleeps: not asked again");
+ f.cloud = { ...f.cloud, asleep: false };
+ admin = false;
+ assert.equal(await f.together.cloudAwake("computer"), false, "the Admin could not be asked just now");
});
test("the page asks to open in place over its own channel, and main answers for its own page only", async () => {
@@ -133,4 +171,5 @@ test("the page asks to open in place over its own channel, and main answers for
await handlers.get("places-together:open-in-place")({ page: "local" }, "scout", true);
assert.deepEqual(asked, [["computer", "scout", { fresh: false }], ["computer", "scout", { fresh: true }]]);
await assert.rejects(async () => handlers.get("places-together:open-in-place")({ page: null }, "scout"));
+ assert.equal(asked.length, 2, "another page never reaches main's side");
});
diff --git a/electron/places-together.d.mts b/electron/places-together.d.mts
index 52acb94911..ca82e98017 100644
--- a/electron/places-together.d.mts
+++ b/electron/places-together.d.mts
@@ -79,6 +79,8 @@ export interface PlacesTogetherBridge {
* 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, fresh?: boolean): Promise<{ ok: boolean }>;
+ /** This computer's page only: whether My Cloud is awake now, by the Admin's word (never asking My Cloud). */
+ cloudAwake?(): Promise<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[]>;
@@ -126,6 +128,7 @@ export interface PlacesTogether {
switchedOff(): boolean;
chosen(): boolean | null;
openInPlace(asking: BotHome, botId: string, options?: { fresh?: boolean }): Promise<{ ok: boolean }>;
+ cloudAwake(asking: BotHome): Promise<boolean>;
close(): void;
}
export function createPlacesTogether(deps: Record<string, unknown>): PlacesTogether;
diff --git a/electron/places-together.mjs b/electron/places-together.mjs
index 8c5873d856..b6057ae021 100644
--- a/electron/places-together.mjs
+++ b/electron/places-together.mjs
@@ -555,6 +555,14 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, loca
} catch { return { ok: false }; }
finally { if (mine === epoch) { readying = Math.max(0, readying - 1); tell(); } }
},
+ /** Whether My Cloud is awake now, as the Admin says it (asked again when its word is old), for a bot open in place
+ * whose stream went quiet: never a request to My Cloud itself, which would wake it. This computer's page only. */
+ async cloudAwake(asking) {
+ sameScope();
+ if (asking !== "computer" || !active() || cloud().asleep) return false;
+ const answered = await powerChecked().catch(() => false);
+ return answered === true && active() && !cloud().asleep;
+ },
/** 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) {
@@ -642,6 +650,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:cloud-awake", (event) => together.cloudAwake(side(event)));
ipcMain.handle("places-together:open-in-place", (event, botId, fresh) => together.openInPlace(side(event), String(botId), { fresh: fresh === true }));
ipcMain.handle("places-together:arrange", (event, entries) => together.arrange(side(event), entries));
ipcMain.handle("places-together:new-bot-choice", (event) => together.newBotChoice(side(event)));
diff --git a/electron/places-together.node-test.mjs b/electron/places-together.node-test.mjs
index 3629819f97..6cc0a65c6f 100644
--- a/electron/places-together.node-test.mjs
+++ b/electron/places-together.node-test.mjs
@@ -489,7 +489,7 @@ test("only this computer's page and My Cloud's own page are answered", async ()
const handlers = new Map();
const f = setup();
installPlacesTogether({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, asking: (event) => event.page, together: f.together });
- assert.deepEqual([...handlers.keys()], ["places-together:state", "places-together:set", "places-together:open", "places-together:open-in-place", "places-together:arrange", "places-together:new-bot-choice", "places-together:new-bot", "places-together:new-bot-heard",
+ assert.deepEqual([...handlers.keys()], ["places-together:state", "places-together:set", "places-together:open", "places-together:cloud-awake", "places-together:open-in-place", "places-together:arrange", "places-together:new-bot-choice", "places-together:new-bot", "places-together:new-bot-heard",
"places-together:notice-shown", "places-together:notice-done", "places-together:commands", "places-together:rail-set"]);
for (const [channel, handler] of handlers) assert.throws(() => handler({ page: null }, "nova"), channel === "places-together:rail-set" ? /Only the window's rail/ : /Only this computer's page and My Cloud's page/);
assert.equal(handlers.get("places-together:state")({ page: "local" }).here, "computer");
@@ -520,7 +520,7 @@ test("main wires it to the one rule for this app's own pages, and the preload of
const preload = readFileSync(join(HERE, "preload.cjs"), "utf8");
assert.match(preload.match(/const REMOTE_SAFE = new Set\(\[([^\]]*)\]\)/)[1], /"placesTogether"/);
const bridge = preload.slice(preload.indexOf(" placesTogether: "), preload.indexOf(" twoPlaces: {"));
- assert.deepEqual(bridge.match(/"places-together:[a-z-]+"/g), ['"places-together:state"', '"places-together:set"', '"places-together:open"', '"places-together:open-in-place"', '"places-together:arrange"', '"places-together:changed"', '"places-together:changed"',
+ assert.deepEqual(bridge.match(/"places-together:[a-z-]+"/g), ['"places-together:state"', '"places-together:set"', '"places-together:open"', '"places-together:cloud-awake"', '"places-together:open-in-place"', '"places-together:arrange"', '"places-together:changed"', '"places-together:changed"',
'"places-together:notice-shown"', '"places-together:notice-done"', '"places-together:commands"', '"places-together:new-bot-choice"', '"places-together:new-bot"']);
});
diff --git a/electron/preload.cjs b/electron/preload.cjs
index b4ec20662a..57444063c1 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -650,6 +650,7 @@ const bridge = {
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).
+ cloudAwake: () => (isLocalPage ? ipcRenderer.invoke("places-together:cloud-awake") : Promise.resolve(false)),
openInPlace: (botId, fresh) => (isLocalPage ? ipcRenderer.invoke("places-together:open-in-place", String(botId), fresh === true) : 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) : []),
diff --git a/server/places/place-proxy.test.ts b/server/places/place-proxy.test.ts
index a3d6ad97f6..a4cd2ffb2b 100644
--- a/server/places/place-proxy.test.ts
+++ b/server/places/place-proxy.test.ts
@@ -11,7 +11,7 @@ import { createPlaceProxy, frameForBot, parsePlaceSession, placedPath, type Plac
const TOKEN = "omb_sess_test-token-0123456789";
const OWNER = "o".repeat(43);
-interface Seen { method: string; url: string; authorization: string | undefined; body: string }
+interface Seen { method: string; url: string; authorization: string | undefined; body: string; background?: string; range?: string }
const codeOf = async (response: Response) => ((await response.json()) as { code?: string }).code;
let cloud: Server, local: Server, cloudUrl: string, localUrl: string, proxy: PlaceProxy;
@@ -19,6 +19,8 @@ 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;
+/** How this computer's server says the caller signed in: the app's window, unless a test says a phone or a shared server. */
+let callerAuth: Parameters<PlaceProxy["route"]>[0]["auth"] = { kind: "loopback", scopes: [] };
const scout = {
id: "scout", name: "Scout", threadId: "t1", mainThreadId: "t1", chiefOfStaff: true,
@@ -31,6 +33,7 @@ const listen = (server: Server) => new Promise<string>((done) => server.listen(0
beforeEach(async () => {
seen.length = 0;
streamTo = null;
+ callerAuth = { kind: "loopback", scopes: [] };
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 }));
@@ -39,7 +42,8 @@ beforeEach(async () => {
let body = "";
req.on("data", (chunk) => { body += chunk; });
req.on("end", () => {
- seen.push({ method: req.method!, url: req.url!, authorization: req.headers.authorization, body });
+ seen.push({ method: req.method!, url: req.url!, authorization: req.headers.authorization, body,
+ ...(req.headers["x-omb-background"] ? { background: String(req.headers["x-omb-background"]) } : {}), ...(req.headers.range ? { range: String(req.headers.range) } : {}) });
if (req.url?.startsWith("/api/events") && streamTo) return streamTo(res, req);
answerWith(req, res, body);
});
@@ -50,7 +54,7 @@ beforeEach(async () => {
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) => {
+ void proxy.route({ req, res, url, path: url.pathname, method: req.method!, auth: callerAuth, json, readBody }).then((out) => {
if (typeof out === "symbol") res.writeHead(418).end("passed");
});
});
@@ -230,7 +234,7 @@ describe("pieces", () => {
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/bots/cloud:../x")).toBe("");
expect(placedPath("/api/groups/cloud:g")).toBeNull();
});
@@ -253,3 +257,119 @@ describe("pieces", () => {
expect(frameForBot({ kind: "power", state: "sleeping" }, "scout", threads)).not.toBeNull();
});
});
+
+describe("what the fix round closed", () => {
+ it("never forwards a path that leaves the route: dot segments and encoded slashes are refused here, and My Cloud is not asked", async () => {
+ for (const path of ["/api/attachments/cloud--..", "/api/attachments/cloud--.", "/api/attachments/cloud--..%2F..%2Fsettings", "/api/attachments/cloud--%2E%2E",
+ "/api/attachments/cloud--a/b", "/api/threads/cloud:t1/messages/..%2Fx/file", "/api/threads/cloud:t1/messages/m1%2F..%2F../file", "/api/bots/cloud:scout/tasks/%2E"]) {
+ const answer = await ask(path);
+ expect(answer.status, path).toBe(404);
+ expect(await codeOf(answer), path).toBe("place_unsupported");
+ }
+ expect(seen).toEqual([]);
+ for (const path of ["/api/attachments/cloud--..", "/api/attachments/cloud--.", "/api/attachments/cloud--%2E%2E", "/api/threads/cloud:t1/messages/..%2Fx/file", "/api/bots/cloud:scout/%2e%2e"]) {
+ expect(placedPath(path), path).toBe("");
+ }
+ expect(placedPath("/api/attachments/cloud--a1.b2-c.png")).toBe("/api/attachments/a1.b2-c.png");
+ });
+
+ it("forwards a message's file, and hands back its media link on the conversation's place route", async () => {
+ await (await ask("/api/bots/cloud%3Ascout?messages=80")).text();
+ seen.length = 0;
+ answerWith = (_req, res) => void res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ url: "/api/threads/t1/messages/m1/file?media=abc-123", mime: "video/mp4" }));
+ const linked = await ask("/api/threads/cloud%3At1/messages/m1/file", { method: "POST", body: JSON.stringify({ path: "cloud--aa11-bb22.png", media: true }) });
+ expect(linked.status).toBe(200);
+ expect(await linked.json()).toEqual({ url: "/api/threads/cloud%3At1/messages/m1/file?media=abc-123", mime: "video/mp4" });
+ expect(seen[0]).toMatchObject({ method: "POST", url: "/api/threads/t1/messages/m1/file" });
+ expect(JSON.parse(seen[0]!.body)).toEqual({ path: "/data/attachments/aa11-bb22.png", media: true });
+ answerWith = (_req, res) => void res.writeHead(206, { "content-type": "video/mp4", "content-range": "bytes 0-2/10", "accept-ranges": "bytes", "content-length": "3" }).end(Buffer.from([1, 2, 3]));
+ const played = await ask("/api/threads/cloud%3At1/messages/m1/file?media=abc-123", { headers: { range: "bytes=0-2" } });
+ expect(played.status).toBe(206);
+ expect(played.headers.get("content-range")).toBe("bytes 0-2/10");
+ expect(seen.at(-1)).toMatchObject({ url: "/api/threads/t1/messages/m1/file?media=abc-123", range: "bytes=0-2" });
+ // A folder a message names comes back as its list, still marked as one.
+ answerWith = (_req, res) => void res.writeHead(200, { "content-type": "application/json", "x-openmausbot-folder": "1" }).end(JSON.stringify({ entries: [] }));
+ const folder = await ask("/api/threads/cloud%3At1/messages/m1/file", { method: "POST", body: JSON.stringify({ path: "/data/out", listFolder: true }) });
+ expect(folder.headers.get("x-openmausbot-folder")).toBe("1");
+ });
+
+ it("serves My Cloud's bytes so this origin never runs or sniffs them: only raster pictures and sound are inline", async () => {
+ const served = async (type: string) => {
+ answerWith = (_req, res) => void res.writeHead(200, { "content-type": type, "content-disposition": "inline; filename=\"x\"" }).end("<script>parent.x=1</script>");
+ const answer = await ask("/api/threads/cloud%3At1/messages/m1/file", { method: "POST", body: JSON.stringify({ path: "/data/x" }) });
+ await answer.arrayBuffer();
+ return answer.headers;
+ };
+ for (const type of ["text/html", "image/svg+xml", "application/pdf", "video/mp4", "text/plain; charset=utf-8", "application/xhtml+xml"]) {
+ const headers = await served(type);
+ expect(headers.get("content-disposition"), type).toMatch(/^attachment/);
+ expect(headers.get("x-content-type-options"), type).toBe("nosniff");
+ expect(headers.get("content-security-policy"), type).toBe("sandbox; default-src 'none'");
+ }
+ for (const type of ["image/png", "image/jpeg", "audio/mpeg"]) {
+ const headers = await served(type);
+ expect(headers.get("content-disposition"), type).toBeNull();
+ expect(headers.get("x-content-type-options"), type).toBe("nosniff");
+ expect(headers.get("content-security-policy"), type).toBe("sandbox; default-src 'none'");
+ }
+ });
+
+ it("answers neither a paired phone nor a shared server's loopback, and a header My Cloud's token can't match is a plain refusal", async () => {
+ callerAuth = { kind: "loopback", scopes: [], companionDevice: "phone-1" };
+ expect((await ask("/api/bots/cloud:scout")).status).toBe(404);
+ callerAuth = { kind: "loopback", scopes: [], trust: "service" };
+ expect((await ask("/api/bots/cloud:scout")).status).toBe(404);
+ callerAuth = { kind: "loopback", scopes: [] };
+ // Same character count as the capability, more bytes: compared as bytes, never a crash.
+ const { request } = await import("node:http");
+ const status = await new Promise<number>((done, fail) => {
+ const sent = request(`${localUrl}/api/bots/cloud:scout`, { headers: { "x-openmausbot-desktop-owner": `é${"o".repeat(42)}` } }, (res) => { res.resume(); done(res.statusCode!); });
+ sent.on("error", fail);
+ sent.end();
+ });
+ expect(status).toBe(404);
+ expect(seen).toEqual([]);
+ });
+
+ it("reads and streams as background work, so a page left open never keeps My Cloud awake", async () => {
+ streamTo = (res) => { res.writeHead(200, { "content-type": "text/event-stream" }); res.write(`data: ${JSON.stringify({ kind: "hello", cursor: "s:1", resumed: false })}\n\n`); };
+ const stop = new AbortController();
+ const answer = await ask("/api/places/cloud/events?bot=cloud:scout", { signal: stop.signal });
+ const reader = answer.body!.getReader();
+ await reader.read();
+ expect(seen.map(({ url, background }) => [url.split("?")[0], background])).toEqual([["/api/bots/scout", "1"], ["/api/events", "1"]]);
+ stop.abort();
+ });
+
+ it("ends every live stream the moment the session goes, and passes no frame after it", async () => {
+ let more!: (frame: unknown) => void;
+ streamTo = (res) => {
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ res.write(`data: ${JSON.stringify({ kind: "hello", cursor: "s:1", resumed: false })}\n\n`);
+ more = (frame) => { if (!res.writableEnded) res.write(`data: ${JSON.stringify(frame)}\n\n`); };
+ };
+ const answer = await ask("/api/places/cloud/events?bot=cloud:scout");
+ const reader = answer.body!.getReader(), decoder = new TextDecoder();
+ let text = decoder.decode((await reader.read()).value);
+ expect(text).toContain("hello");
+ proxy.setSession(null);
+ more({ kind: "message", threadId: "t1", message: { id: "late", role: "bot", text: "after the session went" } });
+ for (;;) { const { value, done } = await reader.read(); if (done) break; text += decoder.decode(value); }
+ expect(text).not.toContain("after the session went");
+ });
+
+ it("drops another bot's live turn", async () => {
+ streamTo = (res) => {
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ res.write(`data: ${JSON.stringify({ kind: "runtime", event: { type: "text.delta", threadId: "t9", text: "theirs" } })}\n\n`);
+ res.write(`data: ${JSON.stringify({ kind: "runtime", event: { type: "text.delta", threadId: "t2", text: "ours" } })}\n\n`);
+ };
+ const stop = new AbortController();
+ const answer = await ask("/api/places/cloud/events?bot=cloud:scout", { signal: stop.signal });
+ const reader = answer.body!.getReader(), decoder = new TextDecoder();
+ let text = "";
+ while (!text.includes("ours")) text += decoder.decode((await reader.read()).value);
+ expect(text).not.toContain("theirs");
+ stop.abort();
+ });
+});
diff --git a/server/places/place-proxy.ts b/server/places/place-proxy.ts
index c647f68c62..eaeaa2d69b 100644
--- a/server/places/place-proxy.ts
+++ b/server/places/place-proxy.ts
@@ -60,7 +60,9 @@ const ROUTES: ReadonlyArray<readonly [string, RegExp]> = [
["POST", /^\/api\/threads\/[\w-]+\/job\/[\w-]+\/stop$/],
["GET", /^\/api\/threads\/[\w-]+\/messages$/],
["GET", /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/(?:image|file|tool)$/],
- ["GET", /^\/api\/attachments\/[\w.-]+$/],
+ // A file a message names: its bytes, a folder's list, or a link a <video> or <audio> element can play (`?media=`).
+ ["POST", /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/file$/],
+ ["GET", /^\/api\/attachments\/[\w-][\w.-]*$/],
];
/** The frames of My Cloud's stream that are about one bot's conversations. Anything else (its other bots, its rooms,
@@ -74,30 +76,36 @@ 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. */
+/** One segment of a path forwarded to My Cloud, decoded: a name of letters, digits, `_`, `-` and dots that never starts
+ * with a dot, so never `.`, `..`, empty, or anything holding a slash, a backslash or a percent sign. */
+const SEGMENT = /^[\w-][\w.-]*$/;
+
+/** The request names My Cloud's bot, conversation or file in its path: the path in My Cloud's own ids, else null. A path
+ * that names one but holds any other segment (`.`, `..`, an encoded slash) is answered here, never forwarded: "" stands
+ * for "placed, and refused". */
export function placedPath(path: string): string | null {
const parts = path.split("/");
if (parts[1] !== "api") return null;
- if (parts[2] === "attachments" && parts.length === 4) {
+ 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 (!name.startsWith(PLACE_FILE_PREFIX)) return null;
+ const own = name.slice(PLACE_FILE_PREFIX.length);
+ return parts.length === 4 && SEGMENT.test(own) ? `/api/attachments/${own}` : "";
}
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 rest = parts.slice(4).map((part) => { const value = decoded(part); return isPlaceId(value) ? ownId(value) : value; });
+ return OWN_ID.test(own) && rest.every((part) => SEGMENT.test(part)) ? ["", "api", parts[2], own, ...rest].join("/") : "";
}
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));
+ if (typeof given !== "string") return false;
+ const a = Buffer.from(given), b = Buffer.from(expected);
+ return a.length === b.length && timingSafeEqual(a, b);
}
/** A message main sends this server over its private port: My Cloud's address and the owner session for it, or none. */
@@ -135,6 +143,43 @@ function learnThreads(bot: Record<string, unknown>, threads: Set<string>): void
if (Array.isArray(bot.tasks)) for (const task of bot.tasks) if (record(task) && typeof task.threadId === "string") threads.add(task.threadId);
}
+/** Image kinds a page may draw inline from My Cloud: raster pictures only, never SVG (it can carry script). */
+const INLINE_IMAGE = /^image\/(?:png|jpeg|gif|webp|avif|bmp)$/i;
+const INLINE_AUDIO = /^audio\//i;
+
+/** The headers My Cloud's bytes are served with on this server's own (trusted) origin: never sniffed, never run, and
+ * anything but a raster picture or a sound is a download, whatever My Cloud said it was. */
+export function servedFileHeaders(upstream: Pick<Response, "headers">): Record<string, string> {
+ const type = (upstream.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase() || "application/octet-stream";
+ const headers: Record<string, string> = {
+ "content-type": type, "cache-control": "private, no-store",
+ "x-content-type-options": "nosniff", "content-security-policy": "sandbox; default-src 'none'",
+ };
+ for (const name of ["content-length", "content-range", "accept-ranges"]) {
+ const value = upstream.headers.get(name);
+ if (value && /^[\w ,=/*-]{1,200}$/.test(value)) headers[name] = value;
+ }
+ if (!INLINE_IMAGE.test(type) && !INLINE_AUDIO.test(type)) {
+ const named = /filename\*?=(?:UTF-8'')?"?([^";]{1,200})"?/i.exec(upstream.headers.get("content-disposition") ?? "")?.[1];
+ const safe = named ? named.replace(/[^\w .()-]/g, "_") : "";
+ headers["content-disposition"] = safe ? `attachment; filename="${safe}"` : "attachment";
+ }
+ return headers;
+}
+
+/** Writes `chunk`, waiting for the page to take what it was sent before more is read from My Cloud. False once the page
+ * has gone. */
+async function written(res: ServerResponse, chunk: string | Uint8Array): Promise<boolean> {
+ if (res.destroyed || res.writableEnded) return false;
+ if (res.write(chunk)) return true;
+ return new Promise((done) => {
+ const drained = () => { res.off("close", closed); done(true); };
+ const closed = () => { res.off("drain", drained); done(false); };
+ res.once("drain", drained);
+ res.once("close", closed);
+ });
+}
+
/** 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();
@@ -173,6 +218,8 @@ export async function* sseEvents(body: ReadableStream<Uint8Array>): AsyncGenerat
*/
export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch }: { fetch?: Fetch } = {}) {
let session: PlaceSession | null = null;
+ /** Every live stream open on the session: a new session, or none, ends them all at once. */
+ const streams = new Set<AbortController>();
let ownerToken: string | null = null;
const files = new Map<string, string>();
const remember = (name: string, path: string) => {
@@ -212,18 +259,15 @@ export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch
const { code: _code, ...said } = placed;
return json(res, upstream.status === 403 ? 409 : upstream.status, { ...said, code: "place_refused" });
}
+ // A folder a message names comes back as its list, marked so the page draws it as one.
+ if (upstream.headers.get("x-openmausbot-folder") === "1") res.setHeader("x-openmausbot-folder", "1");
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);
+ // A file or an image: its bytes as they come, kept by nobody, never run on this origin.
+ res.writeHead(upstream.status, servedFileHeaders(upstream));
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));
+ if (!(await written(res, chunk))) { await upstream.body.cancel().catch(() => {}); return; }
}
res.end();
}
@@ -253,6 +297,7 @@ export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch
accept: String(req.headers.accept ?? "application/json"), authorization: `Bearer ${own.token}`,
...(body !== undefined ? { "content-type": "application/json" } : {}),
...(req.headers[BACKGROUND_HEADER] ? { [BACKGROUND_HEADER]: "1" } : {}),
+ ...(typeof req.headers.range === "string" && /^bytes=[\d,-]{1,100}$/.test(req.headers.range) ? { range: req.headers.range } : {}),
},
});
} catch {
@@ -271,8 +316,12 @@ export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch
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}` };
+ streams.add(stop);
+ stop.signal.addEventListener("abort", () => { streams.delete(stop); if (!res.writableEnded) res.end(); }, { once: true });
+ res.on("close", () => stop.abort());
+ // Neither the read nor the stream is the person using My Cloud: a page left open never keeps it awake, and one that
+ // fell asleep answers so rather than being counted as a visit (the person's own sends and clicks wake it).
+ const headers = { authorization: `Bearer ${own.token}`, [BACKGROUND_HEADER]: "1" };
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;
@@ -305,11 +354,12 @@ export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch
void (async () => {
try {
for await (const event of sseEvents(upstream.body!)) {
+ if (stop.signal.aborted) break;
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`);
+ if (!(await written(res, `${event.id ? `id: ${event.id}\n` : ""}data: ${JSON.stringify(intoPlace(kept, remember))}\n\n`))) break;
}
} catch {
// The end of either side ends the stream; the page reconnects.
@@ -325,6 +375,7 @@ export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch
const events = path === PLACE_EVENTS_PATH;
const placed = events ? null : placedPath(path);
if (!events && placed === null) return PASS;
+ if (placed === "") { ctx.req.resume(); return refuse(res, json, 404, "serverError.place.unsupported", "place_unsupported"); }
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." });
@@ -334,7 +385,11 @@ export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch
return {
route,
- setSession(next: PlaceSession | null) { session = next; if (!next) files.clear(); },
+ setSession(next: PlaceSession | null) {
+ if (session && (next?.token !== session.token || next?.origin !== session.origin)) for (const stop of streams) stop.abort();
+ session = next;
+ if (!next) files.clear();
+ },
setOwnerToken(token: string | null) { ownerToken = typeof token === "string" && token ? token : null; },
hasSession: () => session !== null,
};
diff --git a/shared/place-ids.test.ts b/shared/place-ids.test.ts
new file mode 100644
index 0000000000..5e28403f2e
--- /dev/null
+++ b/shared/place-ids.test.ts
@@ -0,0 +1,40 @@
+// The boundary between My Cloud's ids and this page's: only ids and file references move, never what anyone wrote.
+import { describe, expect, it } from "vitest";
+import { intoPlace, outOfPlace } from "./place-ids.ts";
+
+describe("ids and files cross the boundary, words never do", () => {
+ it("leaves a message whose text is exactly a file address as written, both ways", () => {
+ const message = { id: "m1", threadId: "t1", text: "/api/attachments/aa11.png", kind: "text" };
+ expect(intoPlace(message)).toEqual({ ...message, threadId: "cloud:t1" });
+ expect(outOfPlace({ text: "/api/attachments/cloud--aa11.png", threadId: "cloud:t1" }, () => "/api/attachments/aa11.png")).toEqual({ text: "/api/attachments/cloud--aa11.png", threadId: "t1" });
+ expect(outOfPlace({ text: "cloud:t1 is the thread" })).toEqual({ text: "cloud:t1 is the thread" });
+ });
+
+ it("leaves what a bot wrote alone, ids and all: a widget, an app, a tool call", () => {
+ const written = { kind: "widget", threadId: "t1", widget: { botId: "scout", threadId: "t1", html: "<b>/api/attachments/x.png</b>" }, app: { botId: "scout" }, tool: { input: { threadId: "t1" } } };
+ const placed = intoPlace(written) as typeof written;
+ expect(placed.threadId).toBe("cloud:t1");
+ expect(placed.widget).toEqual(written.widget);
+ expect(placed.app).toEqual(written.app);
+ expect(placed.tool).toEqual(written.tool);
+ const sent = outOfPlace({ threadId: "cloud:t1", widget: { botId: "cloud:keep" } }) as { threadId: string; widget: { botId: string } };
+ expect(sent).toEqual({ threadId: "t1", widget: { botId: "cloud:keep" } });
+ });
+
+ it("names a message's files and a bot's avatar under the page's names, and never shows where a file came from on My Cloud", () => {
+ const kept = new Map<string, string>();
+ const bot = { bot: { id: "scout", avatarUrl: "/api/attachments/face.png", messages: [{ id: "m1", attachments: [{ kind: "file", path: "/data/out/report.pdf", name: "report.pdf", source: "/Users/someone/report.pdf" }] }] } };
+ const placed = intoPlace(bot, (name, path) => kept.set(name, path)) as { bot: { id: string; avatarUrl: string; messages: Array<{ attachments: Array<Record<string, unknown>> }> } };
+ expect(placed.bot.id).toBe("cloud:scout");
+ expect(placed.bot.avatarUrl).toBe("/api/attachments/cloud--face.png");
+ expect(placed.bot.messages[0]!.attachments[0]).toEqual({ kind: "file", path: "cloud--report.pdf", name: "report.pdf" });
+ // A file named back goes back as My Cloud gave it, wherever the request puts it.
+ expect(outOfPlace({ path: "cloud--report.pdf" }, (name) => kept.get(name))).toEqual({ path: "/data/out/report.pdf" });
+ expect(outOfPlace({ attachments: [{ path: "cloud--report.pdf" }] }, (name) => kept.get(name))).toEqual({ attachments: [{ path: "/data/out/report.pdf" }] });
+ });
+
+ it("puts a media link on the conversation's place route, and nothing else that looks like one", () => {
+ expect(intoPlace({ url: "/api/threads/t1/messages/m1/file?media=abc" })).toEqual({ url: "/api/threads/cloud%3At1/messages/m1/file?media=abc" });
+ expect(intoPlace({ message: { url: "/api/threads/t1/messages/m1/file?media=abc" } })).toEqual({ message: { url: "/api/threads/t1/messages/m1/file?media=abc" } });
+ });
+});
diff --git a/shared/place-ids.ts b/shared/place-ids.ts
index e26356de31..7a5be6eb4e 100644
--- a/shared/place-ids.ts
+++ b/shared/place-ids.ts
@@ -22,55 +22,68 @@ export const ownId = (id: string): string => (isPlaceId(id) ? id.slice(PREFIX.le
/** 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.-]+)$/;
+/** A picture of My Cloud's this page shows by its address: a bot's own avatar. */
+const FILE_URL_KEYS = new Set(["avatarUrl"]);
+const FILE_URL = /^\/api\/attachments\/([\w-][\w.-]*)$/;
+/** A link My Cloud's file route gives a <video> or <audio> element: on the conversation's own route. */
+const MEDIA_URL = /^\/api\/threads\/([\w-]+)\/messages\/([\w-]+)\/file\?media=([\w-]+)$/;
+/** What a bot or a person wrote, or an engine's own words and tool calls: never rewritten, whatever keys they hold. */
+const WRITTEN = new Set(["text", "widget", "app", "tool", "card", "digest", "compaction", "summary", "content", "markdown", "html", "input", "output", "args", "result"]);
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;
+type Way = { ids: Ids; path: (path: string) => string; url: (url: string) => string; into: boolean };
-function rewrite(value: unknown, ids: Ids, files: (path: string) => string, key: string | null, depth: number): unknown {
+function rewrite(value: unknown, way: Way, 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 (typeof value === "string") return key !== null && ID_KEY.test(key) ? way.ids(value) : 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)));
+ return value.map((item) => (listOfIds && typeof item === "string" ? way.ids(item) : rewrite(item, way, 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)) {
+ if (WRITTEN.has(name)) { out[name] = item; continue; }
// 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);
+ if (name === "id" && key === "bot" && typeof item === "string") out[name] = way.ids(item);
+ else if (name === "path" && (key === "attachment" || key === null && depth === 0) && typeof item === "string") out[name] = way.path(item);
+ // Where a file came from on My Cloud's own disk is My Cloud's, never shown on this computer.
+ else if (name === "source" && key === "attachment" && way.into) continue;
+ else if (FILE_URL_KEYS.has(name) && typeof item === "string") out[name] = way.url(item);
+ else if (name === "url" && depth === 0 && typeof item === "string") out[name] = way.url(item);
+ else out[name] = rewrite(item, way, 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. */
+/** My Cloud's answer as this page receives it: each bot and conversation id with My Cloud's key in front, each of its
+ * files under a name this page asks for through its own server, and a media link on the conversation's place route.
+ * `remember(name, path)` keeps the path My Cloud gave a file, so a request 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 named = (name: string, path: string) => {
+ if (!name || name.startsWith(PLACE_FILE_PREFIX) || !/^[\w-][\w.-]*$/.test(name)) return null;
const placed = `${PLACE_FILE_PREFIX}${name}`;
remember(placed, path);
- return at ? `/api/attachments/${placed}` : placed;
+ return placed;
};
- return rewrite(value, placeId, files, null, 0);
+ return rewrite(value, {
+ ids: placeId, into: true,
+ path: (path) => named(basename(path), path) ?? path,
+ url: (url) => {
+ const file = FILE_URL.exec(url);
+ if (file) { const placed = named(file[1]!, url); return placed ? `/api/attachments/${placed}` : url; }
+ const media = MEDIA_URL.exec(url);
+ return media ? `/api/threads/${encodeURIComponent(placeId(media[1]!))}/messages/${media[2]}/file?media=${media[3]}` : url;
+ },
+ }, 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);
+ const back = (path: string) => { const name = basename(path); return name.startsWith(PLACE_FILE_PREFIX) ? recall(name) ?? path : path; };
+ return rewrite(value, { ids: ownId, into: false, path: back, url: back }, null, 0);
}
diff --git a/src/App.tsx b/src/App.tsx
index 31933a46a9..3747b04ff7 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -120,7 +120,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
const { capabilities } = useDesktopCapabilities();
const captionChrome = useCaptionChrome();
const unreadCount =
- state.bots.filter((bot) => !bot.hidden).reduce((sum, bot) => sum + botUnreadCount(bot), 0) +
+ state.bots.filter((bot) => !bot.hidden && !isPlaceId(bot.id)).reduce((sum, bot) => sum + botUnreadCount(bot), 0) +
state.groups.filter((group) => group.unread).length;
const remoteClient = window.ogb?.remoteClient?.active === true;
const twoSidePanelsFit = useMediaQuery(TWO_SIDE_PANELS_FIT, true);
diff --git a/src/components/AttachmentPreview.tsx b/src/components/AttachmentPreview.tsx
index a47336a2c1..3bcbb90713 100644
--- a/src/components/AttachmentPreview.tsx
+++ b/src/components/AttachmentPreview.tsx
@@ -38,7 +38,7 @@ import { serverErrorText } from "@/lib/server-error";
import { CopyImageButton } from "./CopyImageButton";
import { FilePreviewButton } from "./FilePreviewButton";
import { chipNameAction, SaveIconButton, useHtmlPreview } from "./HtmlFilePreview";
-import { ImageLoading } from "./ImageLoading"; import { openLinkedFolder } from "./RevealOriginalMenu"; import { serverFetch } from "@/lib/relay-server";
+import { ImageLoading } from "./ImageLoading"; import { openLinkedFolder } from "./RevealOriginalMenu"; import { isPlaceId } from "@/lib/place-chat"; import { serverFetch } from "@/lib/relay-server";
export interface PreviewImage {
src: string;
@@ -304,7 +304,7 @@ export function useLocalFileSave(filePath: string, name?: string, message?: Mess
const listing = await response.json() as MessageFolderListing;
if (!mounted.current || controller.signal.aborted) return;
setState("idle");
- if (!(await openLinkedFolder(filePath)) && !controller.signal.aborted) setFolder(listing); // Security: only a path this message's route just authorized reaches the desktop bridge.
+ if (!(!isPlaceId(message.threadId) && await openLinkedFolder(filePath)) && !controller.signal.aborted) setFolder(listing); // Security: only a path this message's route just authorized reaches the desktop bridge.
return;
}
const blob = await response.blob();
diff --git a/src/components/AwakeBotsPicker.tsx b/src/components/AwakeBotsPicker.tsx
index 3d159d4188..c2f50e0fcd 100644
--- a/src/components/AwakeBotsPicker.tsx
+++ b/src/components/AwakeBotsPicker.tsx
@@ -1,3 +1,4 @@
+import { isPlaceId } from "@/lib/place-chat";
import { useState } from "react";
import { Check } from "lucide-react";
import { awakeCandidates, showBotLimit } from "@/lib/bot-limit";
@@ -24,7 +25,7 @@ export function initialAwake(bots: readonly Candidate[], paused: ReadonlySet<str
/** Which of a Starter Cloud's bots stay awake: the plan's number of them, the rest paused until swapped in or an upgrade. */
export function AwakeBotsPicker({ limit, onSaved, swapIn }: { limit: number; onSaved: () => void; swapIn?: string }) {
const { state } = useStore();
- const bots = awakeCandidates(state.bots);
+ const bots = awakeCandidates(state.bots.filter((bot) => !isPlaceId(bot.id)));
const paused = new Set(state.config?.pausedBots ?? []);
const wanted = Math.min(limit, bots.length);
const [chosen, setChosen] = useState<Set<string>>(() => initialAwake(bots, paused, wanted, swapIn));
diff --git a/src/components/BotPickerList.tsx b/src/components/BotPickerList.tsx
index a45bcb3666..b9c50a6aa9 100644
--- a/src/components/BotPickerList.tsx
+++ b/src/components/BotPickerList.tsx
@@ -3,9 +3,10 @@ import type { Bot } from "@/state/store";
import { teamBotName, useTeamPeople } from "@/state/team-people";
import { BotAvatar } from "./Avatar";
import { cn } from "@/lib/cn";
+import { isPlaceId } from "@/lib/place-chat";
export function BotPickerList({
- bots,
+ bots: offered,
picked,
onToggle,
emptyHint,
@@ -16,6 +17,8 @@ export function BotPickerList({
emptyHint: string;
}) {
const team = useTeamPeople();
+ // A My Cloud bot open in place is in this page's store but not this computer's: no room, team or routine here takes it.
+ const bots = offered.filter((bot) => !isPlaceId(bot.id));
return (
<div className="flex max-h-64 flex-col gap-0.5 overflow-y-auto">
{bots.length === 0 && <div className="px-2 py-4 text-center text-[13px] text-ink-secondary">{emptyHint}</div>}
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index 051f9d06b1..407c1fb25b 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -35,7 +35,7 @@ import { CodeBlock, CodePlate, codeHash } from "./CodeBlock";
export { CodeBlock, HIGHLIGHT_CACHE_MAX, HIGHLIGHT_CACHE_MAX_CHARS, HIGHLIGHT_MAX_CHARS, type CodeBlockProps } from "./CodeBlock";
import { FilePreviewButton } from "./FilePreviewButton";
import { SaveIconButton, useHtmlPreview } from "./HtmlFilePreview";
-import { useRevealOriginalMenu } from "./RevealOriginalMenu";
+import { useRevealOriginalMenu } from "./RevealOriginalMenu"; import { isPlaceId } from "@/lib/place-chat";
const mermaidCache = new Map<string, string>();
const MERMAID_CACHE_MAX = 50;
@@ -365,7 +365,7 @@ function LocalFileLink({ filePath, shownPath, shownName, name, source, children,
const save = useLocalFileSave(filePath, name, message);
const revealMenu = useRevealOriginalMenu();
const fileOutsideWorkspace = useMessageFileOutsideWorkspace(filePath, message);
- const revealHere = typeof window !== "undefined" && Boolean(window.ogb?.revealInFolder) && !window.ogb?.remoteClient?.active;
+ const revealHere = typeof window !== "undefined" && Boolean(window.ogb?.revealInFolder) && !window.ogb?.remoteClient?.active && !isPlaceId(message?.threadId); // a My Cloud path is never one on this computer
// A text file outside the chat's folder keeps Show in folder, so where the desktop app checks, the preview waits for it.
const preview = useHtmlPreview(filePath, shownName, message, shownPath, fileOutsideWorkspace === false || !(revealHere && canRevealHostPath(filePath)));
const revealOnClick = fileOutsideWorkspace === true && canRevealHostPath(shownPath) && revealHere;
@@ -399,7 +399,7 @@ function LocalFileLink({ filePath, shownPath, shownName, name, source, children,
const pathTitle = preview.opens ? preview.label : revealOnClick ? t("attach.showInFolder") : t("chat.file.saveCopy");
return (
- <span dir="ltr" className="inline-flex flex-wrap items-center gap-x-1.5 [unicode-bidi:isolate]" {...revealMenu.targetProps(source)}>
+ <span dir="ltr" className="inline-flex flex-wrap items-center gap-x-1.5 [unicode-bidi:isolate]" {...revealMenu.targetProps(isPlaceId(message?.threadId) ? undefined : source)}>
{revealMenu.menu}
{preview.opens
? <SaveIconButton name={shownName} save={save} retryable={save.retryable} />
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index 5dd308d024..e65ab65517 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -88,7 +88,7 @@ import { AttachmentGallery, collectMessageFiles, replyAttachmentGroup, splitMess
import { ScreenFrame } from "./ScreenFrame";
import { CompactionChip, DigestChip } from "./DigestChip";
import { RenameTitle } from "./RenameTitle"; import { ChatHeadRole, chiefOfStaffBadge } from "./BotRole";
-import { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill"; import { HeaderShare } from "./bot-access/HeaderShare"; import { isPlaceId } from "@/lib/place-chat"; import { ThreadPresenceFaces } from "./TeamPresence"; import { useStoreRef } from "@/state/store-ref"; import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { sameDrawnBots } from "@/lib/drawn-bots"; import { ChatActivityControls, chatActivityMessages, useChatActivity } from "./ChatActivity";
+import { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill"; import { HeaderShare } from "./bot-access/HeaderShare"; import { isPlaceId } from "@/lib/place-chat"; import { PlacedModelPill } from "./PlacedBotMenu"; import { ThreadPresenceFaces } from "./TeamPresence"; import { useStoreRef } from "@/state/store-ref"; import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { sameDrawnBots } from "@/lib/drawn-bots"; import { ChatActivityControls, chatActivityMessages, useChatActivity } from "./ChatActivity";
import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated"; import { NewThreadHeaderButton } from "./NewThreadHeaderButton"; import { HeaderThreadTabs, useThreadTabsShown } from "./HeaderThreadTabs";
import { ModelPicker } from "./ModelPicker"; import { useFailedTurnFix } from "./FailedTurnFix";
import { ChatHeaderMenu, ChatMoreMenu } from "./ChatMoreMenu"; import { TeamOwnHelperHeader, TeamPrivateFirstLine, TeamPrivateHeader, TeamSharedHeader } from "./TeamPrivateChatsLine"; import { ownChatStarted } from "@/state/team-chats"; import { isNewChatThread } from "@/state/new-chat";
@@ -951,7 +951,7 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal
}
}}
onActivate={() => dispatch({ type: "toggleSettings", open: true })}
- showEditButton
+ showEditButton editable={!isPlaceId(bot.id)}
className="truncate text-[14px] font-semibold text-ink"
editButtonClassName="size-6 rounded-full"
inputClassName="max-w-[220px] rounded-full bg-inset px-2 py-0.5 text-[14px] font-semibold"
@@ -1007,13 +1007,13 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal
<ThreadContextWarning bot={bot} messages={messages} />
{phone && <UsageAlert engine={bot.modelSelection?.instanceId} />}
{/* Simple mode keeps the model here and moves only ⋯ into the bot panel; Advanced shows it under the composer's field. */}
- {!phone && (!advanced || canWrite === false) && <ModelPicker key={bot.threadId} bot={bot} threadId={bot.threadId} folded={state.settingsOpen || state.computerOpen} />}
+ {!phone && (!advanced || canWrite === false) && (isPlaceId(bot.id) ? <PlacedModelPill bot={bot} /> : <ModelPicker key={bot.threadId} bot={bot} threadId={bot.threadId} folded={state.settingsOpen || state.computerOpen} />)}
<LiveCallChip currentBotId={bot.id} onOpen={(botId, threadId) => openThread(dispatch, { botId, threadId }, store.state(), showThreads)} />{!phoneMenu && <WatchScreenButton botId={bot.id} messages={messages} liveTools={liveTools} place={place} />}
<PinnedMessagesMenu
pins={pinnedPreview(messages, bot.pinnedMessageId, bot.name)}
triggerClassName={cn(ELEVATED_FLOAT, ELEVATED_HOVER)}
onJump={(messageId) => dispatch({ type: "focusMessage", threadId: bot.threadId, messageId })}
- onUnpin={remoteClient || isPlaceId(bot.id) ? undefined : () => dispatch({ type: "updateTask", botId: bot.id, threadId: bot.threadId, patch: { pinnedMessageId: "" } })}
+ onUnpin={remoteClient ? undefined : () => dispatch({ type: "updateTask", botId: bot.id, threadId: bot.threadId, patch: { pinnedMessageId: "" } })}
/>
{!phoneMenu && !isPlaceId(bot.id) && <button
data-tour="computer"
diff --git a/src/components/Composer.simple.test.ts b/src/components/Composer.simple.test.ts
index 9bbc731f68..79e776a92d 100644
--- a/src/components/Composer.simple.test.ts
+++ b/src/components/Composer.simple.test.ts
@@ -361,3 +361,16 @@ it("a My Cloud bot open in place has no call here, and a file dropped on it says
await vi.waitFor(() => expect(container.textContent).toContain("To send files to a My Cloud bot, open it on My Cloud's page"));
expect(uploads).not.toHaveBeenCalled();
});
+
+it("a file picked for a My Cloud bot open in place says where files go and is never uploaded here", async () => {
+ const placed: Bot = { ...bot, id: "cloud:atlas", threadId: "cloud:atlas-thread" };
+ restoreComposerDraft(`bot:${placed.id}:${placed.threadId}`, { text: "", attachments: [] });
+ const uploads = vi.fn(async () => new Response("{}"));
+ vi.stubGlobal("fetch", uploads);
+ render({ bot: placed });
+ const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;
+ Object.defineProperty(input, "files", { configurable: true, value: [new File(["%PDF"], "lease.pdf", { type: "application/pdf" })] });
+ flushSync(() => input.dispatchEvent(new Event("change", { bubbles: true })));
+ await vi.waitFor(() => expect(container.textContent).toContain("To send files to a My Cloud bot, open it on My Cloud's page"));
+ expect(uploads).not.toHaveBeenCalled();
+});
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index d81216df5f..97925c3476 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -352,14 +352,14 @@ export function Composer({
const mention = mentionQueryAt(text, caret); const teammates = useTeammates(); const viewer = useViewerEmail();
const candidates = useMemo(() => {
- if (!mention || mention.start === dismissedAt) return [];
+ if (!mention || mention.start === dismissedAt || isPlaceId(bot?.id)) return []; // a My Cloud bot's chat names none of this computer's
const pool: MentionChoice[] = group
? [
...(!group.dm ? [{ id: "__everyone__", name: "everyone" }] : []),
...(members ?? []).map((member) => ({ id: member.id, name: member.name, bot: member })),
]
: bots
- .filter((member) => member.id !== bot?.id && !member.hidden && !hiddenFromSidebar(member, viewer))
+ .filter((member) => member.id !== bot?.id && !member.hidden && !isPlaceId(member.id) && !hiddenFromSidebar(member, viewer))
.map((member) => ({ id: member.id, name: member.name, bot: member }));
return mentionChoicesForQuery([...pool, ...teammateChoices(teammates.people), DEVS_CHOICE], mention.query);
}, [mention, dismissedAt, bots, bot?.id, group, members, teammates, viewer]);
diff --git a/src/components/ComposerAdvancedTools.tsx b/src/components/ComposerAdvancedTools.tsx
index 381bc8f429..f19862e131 100644
--- a/src/components/ComposerAdvancedTools.tsx
+++ b/src/components/ComposerAdvancedTools.tsx
@@ -2,7 +2,7 @@ import { approvalModeFor } from "../../shared/approval-mode";
import { personPin, type Place } from "@/lib/place";
import type { Bot, Task } from "@/state/store";
import { ApprovalChip, GoalToggle } from "./ComposerPlusMenu";
-import { ModelPicker } from "./ModelPicker";
+import { ModelPicker } from "./ModelPicker"; import { isPlaceId } from "@/lib/place-chat"; import { PlacedModelPill } from "./PlacedBotMenu";
import { PhonePlus } from "./PhonePlus";
import { PlaceChip } from "./PlaceChip";
import type { ApprovalChoice } from "./thread-approval";
@@ -33,7 +33,7 @@ export function ComposerAdvancedTools({ profile, bot, task, locked, remoteClient
<PhonePlus quiet onAttach={onAttach} goal={goal} teach={teach} callBotId={callBotId}
approval={approval && bot && { name: bot.name, choice: approval }} place={place} />
)}
- {bot && <ModelPicker key={bot.threadId} bot={bot} threadId={bot.threadId} quiet />}
+ {bot && (isPlaceId(bot.id) ? <PlacedModelPill bot={bot} quiet /> : <ModelPicker key={bot.threadId} bot={bot} threadId={bot.threadId} quiet />)}
{!locked && goal?.on && <GoalToggle {...goal} />}
{!locked && ownLevel && <ApprovalChip choice={approval} quiet />}
{!locked && place && personPin(task) && <PlaceChip bot={place.bot} task={task} live={place.disabled} disabled={place.disabled} onPin={onPin} />}
diff --git a/src/components/FailedTurnFix.tsx b/src/components/FailedTurnFix.tsx
index b45936de7c..f59958ecf0 100644
--- a/src/components/FailedTurnFix.tsx
+++ b/src/components/FailedTurnFix.tsx
@@ -10,7 +10,7 @@ import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
import type { Message } from "@/state/store";
import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { settingFix } from "../../shared/setting-fixes";
-import { ModelPicker } from "./ModelPicker";
+import { ModelPicker } from "./ModelPicker"; import { isPlaceId } from "@/lib/place-chat";
export type FailedTurnAction = { label: string; onClick: () => void };
@@ -23,7 +23,8 @@ export function useFailedTurnFix(tool: NonNullable<Message["tool"]>, botId: stri
const dispatch = useStoreDispatch();
const bot = useStoreSelector((state) => (botId ? state.bots.find((candidate) => candidate.id === botId) : undefined));
const phone = useMediaQuery(PHONE_LAYOUT), admin = useOwnerOrAdmin() !== false, advanced = useAdvancedMode();
- const fix = settingFix(tool);
+ // A My Cloud bot open in place: its spending and its model are My Cloud's, set on its own page.
+ const fix = botId && isPlaceId(botId) ? null : settingFix(tool);
if (fix === "spend-limit") {
if (!admin) return { action: null, control: line(t("chat.error.askOwnerSpendLimit")) };
if (!advanced) return { action: null, control: line(t("chat.error.raiseSpendLimitAdvanced")) };
diff --git a/src/components/ModelPicker.tsx b/src/components/ModelPicker.tsx
index e7b2845b2f..6bc7f512a9 100644
--- a/src/components/ModelPicker.tsx
+++ b/src/components/ModelPicker.tsx
@@ -26,7 +26,7 @@ import { SimpleModelMenu, type SimpleThinking } from "./SimpleModelMenu";
import { apiKeysLabel, ClaudeAccountSelect, engineStatus, FollowBotModelRow, ModelEngineRail, ModelRow, ModelSearch } from "./ModelPickerFull";
import { MENU_LABEL, MENU_LINE, MENU_ROW, MENU_SEPARATOR, MENU_TRAILING } from "./menu-recipe";
import { modelMenuKey, modelMenuPointerMove } from "./model-menu-keys";
-import { lockedWhileBusy, offersReasoning, useRefocusAfterPick, variantChoices, variantLabel } from "./model-picker-reasoning"; import { isPlaceId } from "@/lib/place-chat";
+import { lockedWhileBusy, offersReasoning, useRefocusAfterPick, variantChoices, variantLabel } from "./model-picker-reasoning";
import { BusyModelMenu } from "./ModelPickerBusyMenu";
import { useAdvancedMode } from "@/lib/interface-mode";
import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
@@ -218,7 +218,7 @@ export function ModelPicker({
const { dispatch: storeDispatch, refreshInstances, refreshModels: refreshInstanceModels } = useStoreActions(), state = useStoreSelector((s) => ({ instances: s.instances, modelVariantSessions: s.modelVariantSessions, profile: s.bots.find((candidate) => candidate.id === shown.id) }), sameFields);
const [open, setOpen] = useState(false);
const { bot, dispatch } = useAiSwitch({ bot: shown, threadId, contained, dispatch: storeDispatch, setOpen: (next) => (next ? openMenu() : setOpen(false)) });
- const locked = lockedWhileBusy(state, bot, contained, threadId) || isPlaceId(shown.id); // a My Cloud bot open in place: its model is chosen on its own page
+ const locked = lockedWhileBusy(state, bot, contained, threadId);
const motion = useMenuMotion(open && !locked);
const [railId, setRailId] = useState<string | null>(null);
const [query, setQuery] = useState("");
@@ -566,7 +566,7 @@ export function ModelPicker({
};
const currentOption = active?.models.options.find((option) => option.id === selection.model);
- const attention = !active || isPlaceId(shown.id) ? undefined
+ const attention = !active ? undefined
: active.policy ? t("policy.managedBy", { organization: active.policy.organizationName })
: needsCli(active) ? t("model.setupRequired")
: needsSignIn(active) && !isCustomOnly(active) && !currentOption?.custom ? t("model.signInRequired") : currentOption?.orgBlocked ? t("model.orgBlocked") : currentOption?.needsCliUpdate ? t("engines.updateClaude") : undefined;
diff --git a/src/components/PlacedBotMenu.tsx b/src/components/PlacedBotMenu.tsx
index be6079c81a..14fed24ce6 100644
--- a/src/components/PlacedBotMenu.tsx
+++ b/src/components/PlacedBotMenu.tsx
@@ -13,6 +13,7 @@ import { isPlacedBot, type PlacedBot } from "@/lib/place-rows";
import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { useAdvancedMode } from "@/lib/interface-mode";
import { sidePanelCls } from "./bot-panel/side-panel";
+import { ELEVATED_FLOAT } from "./elevated";
import type { Bot } from "@/state/store";
import { MENU_ITEM, MENU_SHEET } from "./menu-recipe";
import type { MenuState } from "./Sidebar";
@@ -110,3 +111,17 @@ export function PlacedBotPanel({ bot }: { bot: Bot }) {
</div>
</aside>;
}
+
+/** The model a My Cloud bot open in place uses, as My Cloud names it: shown plainly where the model pill is, never
+ * matched to this computer's engines, accounts or usage, and changed only on My Cloud's own page. */
+export function PlacedModelPill({ bot, quiet = false }: { bot: Bot; quiet?: boolean }) {
+ const task = bot.tasks?.find((candidate) => candidate.threadId === bot.threadId);
+ const own = task?.modelSelection?.model;
+ const model = own && own !== "profile-default" ? own : bot.modelSelection?.model ?? "";
+ if (!model) return null;
+ const said = t("together.inPlace.model");
+ return <button type="button" disabled data-placed-model="" title={said} aria-label={`${model}. ${said}`}
+ className={cn("flex h-9 min-w-0 max-w-[16rem] items-center rounded-full px-3 text-[13px] text-ink-secondary disabled:cursor-default", !quiet && ELEVATED_FLOAT)}>
+ <span className="min-w-0 truncate">{model}</span>
+ </button>;
+}
diff --git a/src/components/RenameTitle.tsx b/src/components/RenameTitle.tsx
index 3a9523e55c..8f40118172 100644
--- a/src/components/RenameTitle.tsx
+++ b/src/components/RenameTitle.tsx
@@ -12,6 +12,7 @@ export function RenameTitle({
onEditingChange,
onActivate,
showEditButton = false,
+ editable = true,
editRequest = 0,
title,
className,
@@ -23,6 +24,8 @@ export function RenameTitle({
onEditingChange?: (editing: boolean) => void;
onActivate?: () => void;
showEditButton?: boolean;
+ /** False: the name is shown and opens `onActivate`, with no way to rename it here (a My Cloud bot open in place). */
+ editable?: boolean;
editRequest?: number;
title?: string;
className?: string;
@@ -45,7 +48,7 @@ export function RenameTitle({
useEffect(() => {
if (editRequest === handledRequest.current) return;
handledRequest.current = editRequest;
- if (editRequest === 0) return;
+ if (editRequest === 0 || !editable) return;
setDraft(value);
setMode(true);
}, [editRequest]);
@@ -108,7 +111,7 @@ export function RenameTitle({
) : (
<span className={cn("min-w-0 truncate", className)}>{value}</span>
)}
- <button
+ {editable && <button
type="button"
onClick={startRename}
aria-label={t("rename.named", { name: value })}
@@ -116,7 +119,7 @@ export function RenameTitle({
className={cn("flex size-10 shrink-0 items-center justify-center rounded text-ink-secondary opacity-70 hover:bg-raised hover:text-ink hover:opacity-100", editButtonClassName)}
>
<Pencil size={12} />
- </button>
+ </button>}
</span>
);
}
diff --git a/src/components/RoutineCalendarPage.tsx b/src/components/RoutineCalendarPage.tsx
index 9954a3a775..0a689358ac 100644
--- a/src/components/RoutineCalendarPage.tsx
+++ b/src/components/RoutineCalendarPage.tsx
@@ -1,4 +1,4 @@
-import { boatCapableEngine } from "@/lib/remote-desktop";
+import { boatCapableEngine } from "@/lib/remote-desktop"; import { isPlaceId } from "@/lib/place-chat";
import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
import {
CheckCircle2,
@@ -233,7 +233,7 @@ function BotPicker({
onChange: (ids: string[]) => void;
}) {
const [query, setQuery] = useState("");
- const filtered = bots.filter((bot) => `${bot.name} ${bot.title}`.toLowerCase().includes(query.toLowerCase()));
+ const filtered = bots.filter((bot) => !isPlaceId(bot.id) && `${bot.name} ${bot.title}`.toLowerCase().includes(query.toLowerCase())); // a My Cloud bot open in place has no routines here
return (
<div className="rounded-xl border border-hairline/50 bg-inset/60 p-2">
{!locked && bots.length > 5 && (
diff --git a/src/components/SidebarNewChatPanel.tsx b/src/components/SidebarNewChatPanel.tsx
index e049f6b4ab..c9c064cfd8 100644
--- a/src/components/SidebarNewChatPanel.tsx
+++ b/src/components/SidebarNewChatPanel.tsx
@@ -1,3 +1,4 @@
+import { isPlaceId } from "@/lib/place-chat";
import { useLayoutEffect, useRef, useState, type CSSProperties } from "react";
import { Plus, Users, X } from "lucide-react";
import { openBot, useStore, type Bot } from "@/state/store";
@@ -83,7 +84,7 @@ export function SidebarNewChatPanel({
selectedRef.current?.scrollIntoView({ block: "nearest" });
}, [cursor]);
- const bots = rankByName(state.bots.filter((bot) => !bot.hidden), query);
+ const bots = rankByName(state.bots.filter((bot) => !bot.hidden && !isPlaceId(bot.id)), query);
const actions = [
...(onNewBot ? [{ key: "bot", icon: <Plus size={16} />, label: t("sidebar.newChat.createBot"), run: onNewBot }] : []),
{ key: "group", icon: <Users size={16} />, label: t("sidebar.newChat.createGroup"), run: onNewGroup },
diff --git a/src/components/TeamMapPage.tsx b/src/components/TeamMapPage.tsx
index e6c24008f8..78f713d425 100644
--- a/src/components/TeamMapPage.tsx
+++ b/src/components/TeamMapPage.tsx
@@ -1,3 +1,4 @@
+import { isPlaceId } from "@/lib/place-chat";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { ArrowRight, BookOpen, Box, Loader2, Monitor, Plus, Save, Users, UsersRound, X } from "lucide-react";
@@ -287,7 +288,7 @@ export function TeamMapPage() {
const pendingMoveRef = useRef(pendingMove);
pendingMoveRef.current = pendingMove;
useEffect(() => () => pendingMoveRef.current?.resolve(false), []);
- const bots = useMemo(() => state.bots.filter((bot) => !bot.hidden), [state.bots]);
+ const bots = useMemo(() => state.bots.filter((bot) => !bot.hidden && !isPlaceId(bot.id)), [state.bots]);
const sections = useMemo(() => {
const names = [...new Set([...(state.sections ?? []), ...state.groups.flatMap((group) => group.section ? [group.section] : [])])];
const order = (key: string) => key === "" ? -1 : names.includes(key) ? names.indexOf(key) : names.length;
diff --git a/src/lib/place-chat-live.test.ts b/src/lib/place-chat-live.test.ts
new file mode 100644
index 0000000000..616f7034de
--- /dev/null
+++ b/src/lib/place-chat-live.test.ts
@@ -0,0 +1,87 @@
+// The live stream of a My Cloud bot open in place never wakes My Cloud by itself: once it has gone quiet it opens again
+// only after main says My Cloud is awake (the Admin's word), on a retry or on the person's input.
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { keepLive, resetPlaceChatForTest } from "./place-chat";
+
+class Source {
+ onopen: (() => void) | null = null; onerror: (() => void) | null = null; onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;
+ closed = false;
+ constructor(readonly url: string) {}
+ close() { this.closed = true; }
+}
+
+let made: Source[], target: EventTarget, awake: ReturnType<typeof vi.fn<() => Promise<boolean>>>;
+const platform = () => ({ createEventSource: (url: string) => { const source = new Source(url); made.push(source); return source; }, visible: () => true, awake, target: target as unknown as Window });
+const settle = async () => { for (let i = 0; i < 5; i++) await Promise.resolve(); };
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("{}")));
+ made = [];
+ target = new EventTarget();
+ awake = vi.fn(async () => false);
+});
+afterEach(() => {
+ resetPlaceChatForTest();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+it("after My Cloud agrees to sleep, the person's input reconnects only once main says it is awake, and asks at most every 10 s", async () => {
+ keepLive("cloud:scout", () => {}, platform());
+ made[0]!.onopen?.();
+ made[0]!.onmessage?.({ data: JSON.stringify({ kind: "power", state: "sleeping" }) });
+ expect(made[0]!.closed).toBe(true);
+ target.dispatchEvent(new Event("keydown"));
+ await settle();
+ expect(awake).toHaveBeenCalledTimes(1);
+ expect(made).toHaveLength(1);
+ // Typing on asks nothing more for a while: the Admin is not asked on every key.
+ for (let i = 0; i < 20; i++) target.dispatchEvent(new Event("keydown"));
+ await settle();
+ expect(awake).toHaveBeenCalledTimes(1);
+ // One look again a while later (a send of theirs wakes it): now awake, the stream opens.
+ awake.mockResolvedValue(true);
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(awake).toHaveBeenCalledTimes(2);
+ expect(made).toHaveLength(2);
+ // Left alone after that, nothing asks again.
+ made[1]!.onopen?.();
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ expect(awake).toHaveBeenCalledTimes(2);
+});
+
+it("a dropped stream retries only after main says My Cloud is awake, and never keeps retrying while it sleeps", async () => {
+ keepLive("cloud:scout", () => {}, platform());
+ made[0]!.onopen?.();
+ made[0]!.onerror?.();
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(awake).toHaveBeenCalledTimes(1);
+ expect(made).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ expect(awake).toHaveBeenCalledTimes(1);
+ awake.mockResolvedValue(true);
+ target.dispatchEvent(new Event("pointerdown"));
+ await settle();
+ expect(made).toHaveLength(2);
+});
+
+it("a stream that never opens gives the bot to My Cloud's page after its tries", async () => {
+ const cannot = vi.fn();
+ awake.mockResolvedValue(true);
+ keepLive("cloud:scout", cannot, platform());
+ for (let i = 0; i < 3; i++) {
+ made.at(-1)!.onerror?.();
+ await vi.advanceTimersByTimeAsync(20_000);
+ }
+ expect(cannot).toHaveBeenCalledOnce();
+});
+
+it("reads the bot again as background work when the stream starts over", async () => {
+ keepLive("cloud:scout", () => {}, platform());
+ made[0]!.onmessage?.({ data: JSON.stringify({ kind: "hello", cursor: "s:1", resumed: false }) });
+ await settle();
+ const [path, init] = (fetch as unknown as ReturnType<typeof vi.fn>).mock.calls[0]!;
+ expect(String(path)).toBe("/api/bots/cloud%3Ascout?messages=80");
+ expect(new Headers((init as RequestInit).headers).get("x-omb-background")).toBe("1");
+});
diff --git a/src/lib/place-chat.ts b/src/lib/place-chat.ts
index cdcf54278d..8eeb5298fd 100644
--- a/src/lib/place-chat.ts
+++ b/src/lib/place-chat.ts
@@ -87,10 +87,11 @@ export function closePlaceBot(key: string): void {
placeFrame({ kind: "bot.deleted", botId: key });
}
-/** Reads the bot again (the stream started over, or resumed from too far back). */
+/** Reads the bot again (the stream started over, or resumed from too far back): as background work, which My Cloud
+ * never counts as the person using it. */
async function reread(key: string): Promise<void> {
try {
- const { bot } = await api<{ bot: Bot }>(`/api/bots/${encodeURIComponent(key)}?messages=${OPEN_MESSAGES}`);
+ const { bot } = await api<{ bot: Bot }>(`/api/bots/${encodeURIComponent(key)}?messages=${OPEN_MESSAGES}`, { background: true });
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.
@@ -100,6 +101,8 @@ async function reread(key: string): Promise<void> {
interface Platform {
createEventSource(url: string): { onopen: (() => void) | null; onerror: (() => void) | null; onmessage: ((event: { data: string; lastEventId?: string }) => void) | null; close(): void };
visible(): boolean;
+ /** Main's word that My Cloud is awake now (the Admin's, never a request to My Cloud, which would wake it). */
+ awake(): Promise<boolean>;
target?: Pick<Window, "addEventListener" | "removeEventListener">;
}
@@ -113,18 +116,25 @@ const browser = (): Platform => ({
return source;
},
visible: () => typeof document === "undefined" || document.visibilityState === "visible",
+ awake: async () => { const page = bridge(); return page?.cloudAwake ? page.cloudAwake().catch(() => false) : true; },
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. */
+/** How often the person's input may ask main whether My Cloud is awake, and the one look again after it said no. */
+const AWAKE_LOOK_MS = 10_000;
+const AWAKE_AGAIN_MS = 20_000;
+
+/** The bot's live stream while it is open here and the page is in sight. Nothing here wakes My Cloud: the stream and its
+ * reads are background work, and once it has gone quiet (My Cloud agreed to sleep, the connection dropped, the window was
+ * hidden) it opens again only after main says My Cloud is awake: on a retry, or on the person's next click, key or
+ * return to the window. A person who leaves the bot open never keeps My Cloud awake. Their own sends wake it. */
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;
+ let source: ReturnType<Platform["createEventSource"]> | null = null, since: string | null = null, tries = 0, opened = false, stopped = false;
+ let timer: ReturnType<typeof setTimeout> | null = null, again: ReturnType<typeof setTimeout> | null = null, looking = false, lookedAt = -Infinity;
const close = () => { if (source) { source.onopen = source.onerror = source.onmessage = null; source.close(); source = null; } };
const connect = () => {
- if (stopped || source || asleep || !platform.visible()) return;
+ if (stopped || source || !platform.visible()) return;
const url = `${PLACE_EVENTS_PATH}?bot=${encodeURIComponent(key)}${since ? `&since=${encodeURIComponent(since)}` : ""}`;
const current = platform.createEventSource(url);
source = current;
@@ -134,9 +144,7 @@ export function keepLive(key: string, cannot: () => void, platform: Platform = b
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)]);
+ timer = setTimeout(() => { timer = null; void look(true); }, RETRY_MS[Math.min(tries - 1, RETRY_MS.length - 1)]);
};
current.onmessage = (event) => {
if (source !== current) return;
@@ -146,23 +154,44 @@ export function keepLive(key: string, cannot: () => void, platform: Platform = b
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(); }
+ if (frame.state === "sleeping") close();
return;
}
placeFrame(frame as ServerFrame);
};
};
- const wake = () => {
+ /** Opens the stream again once main says My Cloud is awake. `retry`: the stream's own retry, not the person. */
+ const look = async (retry: boolean) => {
+ if (stopped || source || looking || !platform.visible()) return;
+ if (!retry && performance.now() - lookedAt < AWAKE_LOOK_MS) return;
+ looking = true;
+ lookedAt = performance.now();
+ let awake = false;
+ try { awake = await platform.awake(); } catch { awake = false; }
+ looking = false;
+ if (stopped || source) return;
+ if (!awake) {
+ // Asleep, as far as main knows: one look again a while after the person's input (a send of theirs wakes it), then
+ // nothing until they do something here again.
+ if (!retry && again === null) again = setTimeout(() => { again = null; lookedAt = -Infinity; void look(true); }, AWAKE_AGAIN_MS);
+ return;
+ }
+ // This computer's server may have restarted since, without the session: main tells it again.
+ if (opened) await bridge()?.openInPlace?.(ownId(key)).catch(() => {});
+ connect();
+ };
+ const input = () => {
if (!platform.visible()) { close(); return; }
- if (asleep) { asleep = false; connect(); } else if (!source && timer === null) connect();
+ if (!source && timer === null) void look(false);
};
const events = ["pointerdown", "keydown", "focus", "visibilitychange"] as const;
- for (const name of events) platform.target?.addEventListener(name, wake, { capture: true });
+ for (const name of events) platform.target?.addEventListener(name, input, { capture: true });
const stop = () => {
stopped = true;
if (timer !== null) clearTimeout(timer);
+ if (again !== null) clearTimeout(again);
close();
- for (const name of events) platform.target?.removeEventListener(name, wake, { capture: true });
+ for (const name of events) platform.target?.removeEventListener(name, input, { capture: true });
};
live = { key, stop };
connect();
diff --git a/src/locales/en.json b/src/locales/en.json
index 3a2dad4605..eb4de01cf8 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -11618,6 +11618,7 @@
"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.inPlace.model": "This bot's model is changed on My Cloud's page.",
"together.inPlace.files": "To send files to a My Cloud bot, open it on My Cloud's page: its ⋯ menu in the list.",
"together.inPlace.panel": "{name}'s settings, files, computer and everything else besides this conversation are on My Cloud's own page.",
"together.state.offlineCloud": "My Cloud can't be reached right now.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 374687344f..bd7a32d00e 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -11591,6 +11591,7 @@
"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.inPlace.model": "O modelo deste bot é alterado na página do My Cloud.",
"together.inPlace.files": "Para enviar arquivos a um bot do My Cloud, abra-o na página do My Cloud: no menu ⋯ dele na lista.",
"together.inPlace.panel": "As configurações, os arquivos, o computador e tudo o mais de {name}, além desta conversa, ficam na própria página do My Cloud.",
"together.state.offlineCloud": "Não é possível acessar o My Cloud agora.",