Skip to content

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

A phone can take control of the shared Local VM, and a person's hold on it pauses every bot on that desktop

Xiaolei Shiaa7d2d8e8970
diff --git a/companion/src/viewer-relay.ts b/companion/src/viewer-relay.ts
index 5a0b280004..2fd1e2b86a 100644
--- a/companion/src/viewer-relay.ts
+++ b/companion/src/viewer-relay.ts
@@ -215,6 +215,7 @@ export class CompanionViewerRelay {
session.leaseHolds = leaseHolds;
let checking = false;
session.watch = setInterval(() => {
+ // The server takes each check as the phone's heartbeat for the lease.
if (checking || !session.sockets.size) return;
checking = true;
leaseHolds()
diff --git a/docs/ios-companion.md b/docs/ios-companion.md
index 73432e3ce0..cc0e6f8da8 100644
--- a/docs/ios-companion.md
+++ b/docs/ios-companion.md
@@ -342,8 +342,9 @@ Allowed in the first release:
that only for a loopback caller, only for a conversation on the Local VM,
and only to the lease that holds the computer. The sidecar rewrites the
loopback noVNC address into its device-scoped relay path, then asks the
- harness every few seconds whether that lease still holds
- (`action: "check"`, read-only) and closes the relay when it does not. The
+ harness every few seconds, while a viewer socket is open, whether that
+ lease still holds (`action: "check"`, which also renews it) and closes the
+ relay when it does not. The
phone speaks RFB over the relay. Hand back closes the viewer and releases
the lease, and so does backgrounding the app.
- A phone paired with the server directly (`openmausbot serve` behind
@@ -355,10 +356,13 @@ Allowed in the first release:
either lapses; hand back closes it at once. Computer access is the pairing's
scope: Full access (`openmausbot pair`) may, chat-only (`--client`) is
answered 403 and the app shows computer access as off.
-- Phone control requires per-bot Local VMs. Shared and pool modes are refused
- on both connection paths until a viewer can reserve its desktop against
- other bots; a control hold on one bot alone cannot do that. Stills remain
- available in every mode.
+- Phone control works in shared and per-bot Local VM modes. In shared mode
+ the take holds the one shared desktop, so every bot working on it pauses
+ until the hand-back. A phone's hold on a Local VM is released 60 seconds
+ after its last sign of life: the take, the join, a `check`, or the server
+ proxy's re-check. Pool mode is refused on both connection paths, since a
+ take does not say which seat to hold. Stills remain available in every
+ mode.
- Send messages, interrupt bots, answer approvals/questions, and mark chats
read.
- Create a basic bot.
diff --git a/server/computer-control.test.ts b/server/computer-control.test.ts
index 606ac14f41..282dc005db 100644
--- a/server/computer-control.test.ts
+++ b/server/computer-control.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ComputerControl, type ControlSnapshot } from "./computer-control.ts";
@@ -165,20 +165,6 @@ describe("computer control", () => {
expect(control.snapshot("b2").held).toBe(false);
});
- it("forget clears a hold and tells the listeners", () => {
- const { control, changes } = tracked();
- control.take("b1");
- control.forget("b1");
- expect(control.snapshot("b1").held).toBe(false);
- expect(changes.at(-1)?.snapshot).toEqual({ held: false, helpReason: null, heldSinceMs: null });
- });
-
- it("forgetting an unknown bot is silent", () => {
- const { control, changes } = tracked();
- control.forget("ghost");
- expect(changes).toEqual([]);
- });
-
it("reports whether a lease holds the computer without taking a free one", () => {
const control = new ComputerControl();
expect(control.ownsLease("bot", "lease-aaaaaaaaaaaaaa")).toBe(false);
@@ -189,4 +175,133 @@ describe("computer control", () => {
control.release("bot");
expect(control.ownsLease("bot", "lease-aaaaaaaaaaaaaa")).toBe(false);
});
+
+ describe("lease expiry", () => {
+ const lease = "6f1d2c4e-0b7a-4d58-9a3e-2c1f8e7b5a90";
+ const other = "a2b9c7d1-5e3f-4a6b-8c0d-1e2f3a4b5c6d";
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it("a beaten hold is released 60 s after the beat, keeping the plea and broadcasting", () => {
+ const { control, changes } = tracked();
+ control.requestHelp("b1", "sign in to example.com", ref("card-1"));
+ control.acquireLease("b1", lease);
+ expect(control.beat("b1", lease)).toBe(true);
+ vi.advanceTimersByTime(59_999);
+ expect(control.snapshot("b1").held).toBe(true);
+ const before = changes.length;
+ vi.advanceTimersByTime(2);
+ expect(control.snapshot("b1")).toMatchObject({ held: false, help: { messageId: "card-1" } });
+ expect(changes.slice(before)).toEqual([{ botId: "b1", snapshot: control.snapshot("b1") }]);
+ });
+
+ it("a second beat restarts the 60 s", () => {
+ const { control } = tracked();
+ control.acquireLease("b1", lease);
+ control.beat("b1", lease);
+ vi.advanceTimersByTime(30_000);
+ control.beat("b1", lease);
+ vi.advanceTimersByTime(59_999);
+ expect(control.snapshot("b1").held).toBe(true);
+ vi.advanceTimersByTime(2);
+ expect(control.snapshot("b1").held).toBe(false);
+ });
+
+ it("a beat with another lease is refused and does not renew", () => {
+ const { control } = tracked();
+ control.acquireLease("b1", lease);
+ control.beat("b1", lease);
+ vi.advanceTimersByTime(30_000);
+ expect(control.beat("b1", other)).toBe(false);
+ expect(control.beat("b2", lease)).toBe(false);
+ vi.advanceTimersByTime(30_001);
+ expect(control.snapshot("b1").held).toBe(false);
+ });
+
+ it.each([
+ ["a fresh armed acquire", (control: ComputerControl) => control.acquireLease("b1", lease, { armed: true })],
+ ["an armed acquire of a lease already held", (control: ComputerControl) => {
+ control.acquireLease("b1", lease);
+ return control.acquireLease("b1", lease, { armed: true });
+ }],
+ ])("%s with no beat expires at 60 s", (_name, acquire) => {
+ const { control } = tracked();
+ expect(acquire(control)).toMatchObject({ owned: true, snapshot: { held: true } });
+ vi.advanceTimersByTime(59_999);
+ expect(control.snapshot("b1").held).toBe(true);
+ vi.advanceTimersByTime(2);
+ expect(control.snapshot("b1").held).toBe(false);
+ });
+
+ it("an unarmed take or acquire that never beats is still held after 2 h", () => {
+ const { control } = tracked();
+ control.take("b1");
+ control.acquireLease("b2", lease);
+ vi.advanceTimersByTime(2 * 60 * 60_000);
+ expect(control.snapshot("b1").held).toBe(true);
+ expect(control.snapshot("b2").held).toBe(true);
+ });
+
+ it.each([
+ ["releaseLease", (control: ComputerControl) => control.releaseLease("b1", lease)],
+ ["release", (control: ComputerControl) => control.release("b1")],
+ ])("dropping a beaten hold by %s stops its clock", (_name, drop) => {
+ const { control } = tracked();
+ control.acquireLease("b1", lease);
+ control.beat("b1", lease);
+ vi.advanceTimersByTime(30_000);
+ drop(control);
+ control.acquireLease("b1", lease);
+ vi.advanceTimersByTime(2 * 60 * 60_000);
+ expect(control.snapshot("b1").held).toBe(true);
+ });
+ });
+
+ it("forgetBot removes only that bot's pleas, from every key", () => {
+ const { control, changes } = tracked();
+ const plea = (botId: string, messageId: string) => ({ botId, threadId: "t1", messageId, site: "example.com", place: "browser" as const });
+ control.requestHelp("desk", "a asks", plea("a", "a-1"));
+ control.requestHelp("desk", "b asks", plea("b", "b-1"));
+ control.requestHelp("desk", "a asks again", plea("a", "a-2"));
+ control.requestHelp("a", "a asks", plea("a", "a-3"));
+ control.take("held");
+ control.requestHelp("held", "a asks", plea("a", "a-4"));
+ control.requestHelp("b", "b asks", plea("b", "b-2"));
+ changes.length = 0;
+
+ control.forgetBot("a");
+
+ expect(control.snapshot("desk")).toEqual({ held: false, helpReason: "b asks", heldSinceMs: null, help: plea("b", "b-1") });
+ expect(control.snapshot("a")).toEqual({ held: false, helpReason: null, heldSinceMs: null });
+ expect(control.snapshot("held")).toMatchObject({ held: true, helpReason: null });
+ expect(control.snapshot("b")).toMatchObject({ helpReason: "b asks", help: { messageId: "b-2" } });
+ expect(control.settleHelp("a-1")).toEqual([]);
+ expect(changes.map((change) => change.botId).sort()).toEqual(["a", "desk", "held"]);
+ });
+
+ it("recheck tells every key with a plea from those conversations, and names the bots that asked", () => {
+ const { control, changes } = tracked();
+ const plea = (botId: string, threadId: string, messageId: string) => ({ botId, threadId, messageId, site: "example.com", place: "vm" as const });
+ control.requestHelp("desk", "a asks", plea("a", "t1", "m-1"));
+ control.requestHelp("b", "b asks", plea("b", "t2", "m-2"));
+ changes.length = 0;
+ expect(control.recheck(["t1", "t9"])).toEqual(["a"]);
+ expect(changes.map((change) => change.botId)).toEqual(["desk"]);
+ expect(control.snapshot("desk")).toMatchObject({ helpReason: "a asks" });
+ });
+
+ it("forgetThread removes only that conversation's pleas, from every key", () => {
+ const { control, changes } = tracked();
+ const plea = (threadId: string, messageId: string) => ({ botId: "a", threadId, messageId, site: "example.com", place: "vm" as const });
+ control.requestHelp("desk", "t1 asks", plea("t1", "m-1"));
+ control.requestHelp("desk", "t2 asks", plea("t2", "m-2"));
+ control.requestHelp("a", "t1 asks", plea("t1", "m-3"));
+ changes.length = 0;
+
+ expect(control.forgetThread("t1")).toEqual(["a"]);
+
+ expect(control.snapshot("desk")).toMatchObject({ helpReason: "t2 asks", help: { messageId: "m-2" } });
+ expect(control.snapshot("a")).toEqual({ held: false, helpReason: null, heldSinceMs: null });
+ expect(changes.map((change) => change.botId).sort()).toEqual(["a", "desk"]);
+ });
});
diff --git a/server/computer-control.ts b/server/computer-control.ts
index 096cc677d2..5596ab7908 100644
--- a/server/computer-control.ts
+++ b/server/computer-control.ts
@@ -27,6 +27,7 @@ export interface ControlLeaseReleaseResult {
const NO_CONTROL: ControlSnapshot = { held: false, helpReason: null, heldSinceMs: null };
const MAX_REASON_CHARS = 280;
+const LEASE_GRACE_MS = 60_000;
interface Entry {
heldSinceMs: number | null;
@@ -34,6 +35,7 @@ interface Entry {
pleas: Array<{ reason: string; ref: ComputerHelpRef }>;
/** Opaque workspace lease. It is deliberately absent from every snapshot. */
controlLeaseId: string | null;
+ expiry?: ReturnType<typeof setTimeout>;
}
export class ComputerControl {
@@ -78,25 +80,46 @@ export class ComputerControl {
return this.changed(botId);
}
- /** The opaque lease is never returned in a snapshot, broadcast or API response. */
- acquireLease(botId: string, controlLeaseId: string): ControlLeaseResult {
+ /**
+ * The opaque lease is never returned in a snapshot, broadcast or API response.
+ * `armed` starts the expiry clock at once, as a beat would, when the lease owns the hold.
+ */
+ acquireLease(botId: string, controlLeaseId: string, options: { armed?: boolean } = {}): ControlLeaseResult {
const entry = this.entries.get(botId);
if (entry?.heldSinceMs != null) {
- return {
- snapshot: this.snapshot(botId),
- owned: entry.controlLeaseId === controlLeaseId,
- acquired: false,
- };
+ const owned = entry.controlLeaseId === controlLeaseId;
+ if (owned && options.armed) this.beat(botId, controlLeaseId);
+ return { snapshot: this.snapshot(botId), owned, acquired: false };
}
this.entries.set(botId, { heldSinceMs: this.now(), pleas: entry?.pleas ?? [], controlLeaseId });
+ if (options.armed) this.beat(botId, controlLeaseId);
return { snapshot: this.changed(botId), owned: true, acquired: true };
}
+ /** The key whose hold this lease owns: the first, should a client reuse one lease for several takes. */
+ heldBy(controlLeaseId: string): string | undefined {
+ for (const [key, entry] of this.entries) if (entry.heldSinceMs !== null && entry.controlLeaseId === controlLeaseId) return key;
+ return undefined;
+ }
+
ownsLease(botId: string, controlLeaseId: string): boolean {
const entry = this.entries.get(botId);
return entry?.heldSinceMs != null && entry.controlLeaseId === controlLeaseId;
}
+ /**
+ * Answers as `ownsLease`; when owned, the hold is released 60 s after the latest beat.
+ * A hold that never beats never expires.
+ */
+ beat(botId: string, controlLeaseId: string): boolean {
+ const entry = this.entries.get(botId);
+ if (!entry || !this.ownsLease(botId, controlLeaseId)) return false;
+ clearTimeout(entry.expiry);
+ entry.expiry = setTimeout(() => this.releaseLease(botId, controlLeaseId), LEASE_GRACE_MS);
+ entry.expiry.unref?.();
+ return true;
+ }
+
/** An open plea stays: handing back is not answering the card that asked. */
release(botId: string): ControlSnapshot {
const entry = this.entries.get(botId);
@@ -143,11 +166,43 @@ export class ComputerControl {
return settled;
}
- forget(botId: string): void {
- if (this.entries.delete(botId)) this.onChange(botId, NO_CONTROL);
+ /** Removes the deleted bot's pleas from every key; holds stay. */
+ forgetBot(botId: string): void {
+ this.forgetPleas((ref) => ref.botId === botId);
+ }
+
+ /** Removes the pleas of a deleted conversation's sign-in cards from every key, and returns the bots that asked; holds stay. */
+ forgetThread(threadId: string): string[] {
+ return this.forgetPleas((ref) => ref.threadId === threadId);
+ }
+
+ /** Tells every key with a plea from these conversations that its cards may have stopped or started waiting, and returns the
+ * bots that asked. */
+ recheck(threadIds: Iterable<string>): string[] {
+ const threads = new Set(threadIds), askers = new Set<string>();
+ for (const [key, entry] of this.entries) {
+ const asked = entry.pleas.filter((plea) => threads.has(plea.ref.threadId));
+ for (const plea of asked) askers.add(plea.ref.botId);
+ if (asked.length) this.changed(key);
+ }
+ return [...askers];
+ }
+
+ private forgetPleas(gone: (ref: ComputerHelpRef) => boolean): string[] {
+ const askers = new Set<string>();
+ for (const [key, entry] of this.entries) {
+ const pleas = entry.pleas.filter((plea) => !gone(plea.ref));
+ if (pleas.length === entry.pleas.length) continue;
+ for (const plea of entry.pleas) if (gone(plea.ref)) askers.add(plea.ref.botId);
+ entry.pleas = pleas;
+ if (entry.heldSinceMs === null && !pleas.length) this.entries.delete(key);
+ this.changed(key);
+ }
+ return [...askers];
}
private drop(botId: string, entry: Entry): void {
+ clearTimeout(entry.expiry);
if (entry.pleas.length) this.entries.set(botId, { heldSinceMs: null, pleas: entry.pleas, controlLeaseId: null });
else this.entries.delete(botId);
}
diff --git a/server/host/shared-vm-control.test.ts b/server/host/shared-vm-control.test.ts
new file mode 100644
index 0000000000..2e29ba32e0
--- /dev/null
+++ b/server/host/shared-vm-control.test.ts
@@ -0,0 +1,277 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { ComputerControl } from "../computer-control.ts";
+import { SHARED_LOCAL_VM_TARGET, perBotLocalVmTarget, type LocalVmTarget } from "../container-computer.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import type { BotRecord } from "../store.ts";
+import { teamComputerOwner } from "../team-computers.ts";
+import { createSharedVmControl, SHARED_VM_CONTROL_KEY as DESK } from "./shared-vm-control.ts";
+
+type Fixture = {
+ mode?: "shared" | "per-bot" | "pool";
+ cloudHome?: boolean;
+ bots?: Array<Partial<BotRecord> & { id: string }>;
+ /** threadId → [botId, pinned place] */
+ tasks?: Record<string, [string, string | undefined]>;
+ team?: Record<string, string>;
+ teamTurns?: Record<string, { computerId: string; botId: string }>;
+ /** threadId → the settings a running turn there uses instead of the stored bot's */
+ turnBots?: Record<string, Partial<BotRecord>>;
+ /** threadId → the Local VM its running turn works on */
+ vmTurns?: Record<string, LocalVmTarget>;
+ busy?: boolean;
+};
+
+function fixture(f: Fixture = {}) {
+ const control = new ComputerControl();
+ const bots = (f.bots ?? [{ id: "ada" }]) as BotRecord[];
+ let mode = f.mode ?? "shared";
+ let places = 0;
+ const vm = createSharedVmControl({
+ control,
+ store: {
+ get bots() { return bots; },
+ bot: (id) => bots.find(bot => bot.id === id) ?? null,
+ tasks: (botId) => Object.entries(f.tasks ?? {}).filter(([, [owner]]) => owner === botId).map(([threadId, [, surface]]) => ({ threadId, surface })),
+ },
+ mode: () => f.cloudHome ? null : mode,
+ turnBots: { entries: () => Object.entries(f.turnBots ?? {}).flatMap(([threadId, settings]) => {
+ const stored = bots.find(bot => bot.id === settings.id);
+ return stored ? [[threadId, { ...stored, ...settings }] as [string, BotRecord]] : [];
+ }).values() },
+ botForThread: (botId, threadId) => {
+ const stored = bots.find(bot => bot.id === botId);
+ return stored ? { ...stored, ...f.turnBots?.[threadId] } : null;
+ },
+ teamTurns: { get: (threadId) => f.teamTurns?.[threadId], values: () => Object.values(f.teamTurns ?? {}).values() },
+ teamComputer: (bot) => f.team?.[bot.id],
+ place: (bot, threadId) => { places++; return f.tasks?.[threadId]?.[1] ?? bot.computer; },
+ turnVmTargets: { get: (threadId) => f.vmTurns?.[threadId] },
+ busy: () => f.busy ?? false,
+ });
+ const bot = (id: string) => bots.find(candidate => candidate.id === id)!;
+ return { control, vm, bot, setMode: (next: typeof mode) => { mode = next; }, places: () => places };
+}
+
+const phone: RequestAuth = { kind: "session", via: "bearer", scopes: ["admin"], session: {} as never };
+const desktop: RequestAuth = { kind: "loopback", scopes: ["admin"] };
+
+const keyRows = [
+ { row: "shared, Auto, no conversation", f: {}, thread: undefined, key: DESK },
+ { row: "shared, set to the VM", f: { bots: [{ id: "ada", computer: "vm" }] }, thread: undefined, key: DESK },
+ { row: "shared, cloud, conversation pinned to the VM", f: { bots: [{ id: "ada", computer: "cloud" }], tasks: { t: ["ada", "vm"] } }, thread: "t", key: DESK },
+ { row: "shared, cloud, asked without the conversation", f: { bots: [{ id: "ada", computer: "cloud" }], tasks: { t: ["ada", "vm"] } }, thread: undefined, key: "ada" },
+ { row: "shared, Auto, conversation pinned to this computer", f: { tasks: { t: ["ada", "local"] } }, thread: "t", key: "ada" },
+ { row: "shared, Auto on a VPS, unpinned conversation", f: { bots: [{ id: "ada", cloudBackend: "vps" }], tasks: { t: ["ada", undefined] } }, thread: "t", key: "ada" },
+ { row: "shared, Auto on a VPS, unpinned conversation whose running turn is on the shared VM",
+ f: { bots: [{ id: "ada", cloudBackend: "vps" }], tasks: { t: ["ada", undefined] }, vmTurns: { t: SHARED_LOCAL_VM_TARGET } }, thread: "t", key: DESK },
+ { row: "shared, Auto, unpinned conversation", f: { tasks: { t: ["ada", undefined] } }, thread: "t", key: DESK },
+ { row: "shared, Auto on a VPS, no conversation", f: { bots: [{ id: "ada", cloudBackend: "vps" }], tasks: { t: ["ada", undefined] } }, thread: undefined, key: "ada" },
+ { row: "shared, Auto on a VPS, its conversations on the VPS", f: { bots: [{ id: "ada", cloudBackend: "vps" }], tasks: { t: ["ada", "cloud"] } }, thread: "t", key: "ada" },
+ { row: "per-bot, Auto", f: { mode: "per-bot" }, thread: undefined, key: "ada" },
+ { row: "pool, Auto", f: { mode: "pool" }, thread: undefined, key: "ada" },
+ { row: "a Cloud home", f: { cloudHome: true }, thread: undefined, key: "ada" },
+ { row: "a team's cloud computer", f: { team: { ada: "c1" } }, thread: undefined, key: teamComputerOwner("c1") },
+ { row: "a turn on a team's cloud computer", f: { teamTurns: { t: { computerId: "c2", botId: "ada" } } }, thread: "t", key: teamComputerOwner("c2") },
+ { row: "another bot's turn on a team's cloud computer", f: { bots: [{ id: "ada" }, { id: "bea" }], teamTurns: { t: { computerId: "c2", botId: "bea" } } }, thread: "t", key: DESK },
+] as Array<{ row: string; f: Fixture; thread?: string; key: string }>;
+
+describe("the one control key", () => {
+ it.each(keyRows)("$row", ({ f, thread, key }) => {
+ const { vm, bot } = fixture(f);
+ expect(vm.keyFor(bot("ada"), thread)).toBe(key);
+ expect(vm.signInKey(bot("ada"), thread ?? "t", "vm")).toBe(vm.keyFor(bot("ada"), thread ?? "t"));
+ expect(vm.signInKey(bot("ada"), "t", "browser")).toBe("ada");
+ });
+
+ it.each(keyRows)("the bot list tells the bot about every hold a take through its panels lands on: $row", ({ f, thread }) => {
+ const { control, vm, bot } = fixture(f);
+ for (const key of [vm.keyFor(bot("ada"), thread), ...[thread, undefined].flatMap(t => [vm.holdKey(bot("ada"), t, "local/shared"), vm.holdKey(bot("ada"), t, "vps/ada")])]) {
+ if (!key) continue;
+ control.take(key);
+ expect(vm.botSnapshot("ada").held, key).toBe(true);
+ control.release(key);
+ }
+ });
+});
+
+describe("what a hold on the shared desktop reaches", () => {
+ it("a thread-less hold on a bot's default key pauses its conversation elsewhere, and a hold on the desktop pauses every Auto bot", () => {
+ const { control, vm } = fixture({ bots: [{ id: "ada" }, { id: "bea" }], tasks: { t: ["ada", "cloud"] } });
+ control.take(DESK);
+ expect(vm.snapshot("ada", "t").held).toBe(true);
+ expect(vm.snapshot("bea").held).toBe(true);
+ });
+
+ it.each(["cloud", "off"] as const)("a turn still on the shared VM after its bot moved to %s waits for a hold on the desktop", (computer) => {
+ const { control, vm } = fixture({ bots: [{ id: "ada", computer }], vmTurns: { r: SHARED_LOCAL_VM_TARGET } });
+ control.take(DESK);
+ expect(vm.snapshot("ada", "r").held).toBe(true);
+ expect(vm.snapshot("ada").held).toBe(false);
+ });
+
+ it.each([{ held: "ada", plea: DESK }, { held: DESK, plea: "ada" }])("a bot's hold on $held still shows its sign-in plea on $plea", ({ held, plea }) => {
+ const { control, vm } = fixture({ bots: [{ id: "ada" }] });
+ control.take(held);
+ control.requestHelp(plea, "sign in to a.example", { botId: "ada", threadId: "t", messageId: "m", site: "a.example", place: "browser" });
+ expect(vm.botSnapshot("ada")).toMatchObject({ held: true, helpReason: "sign in to a.example", help: { messageId: "m" } });
+ expect(vm.botSnapshot("ada").heldSinceMs).toBe(control.snapshot(held).heldSinceMs);
+ });
+
+ it("a control answer for a viewer who cannot see the asking conversation carries no sign-in request", () => {
+ const { control, vm } = fixture({ bots: [{ id: "ada" }] });
+ control.requestHelp(DESK, "sign in to a.example", { botId: "ada", threadId: "t", messageId: "m", site: "a.example", place: "vm" });
+ expect(vm.shown(control.snapshot(DESK), "ada", (id) => id === "t")).toEqual({ held: false, helpReason: null, heldSinceMs: null });
+ expect(vm.shown(control.snapshot("ada"), "ada", () => false)).toMatchObject({ helpReason: "sign in to a.example", help: { messageId: "m" } });
+ });
+
+ it("tells every bot with a conversation on the desktop, and each its merged state", () => {
+ const { control, vm } = fixture({ bots: [{ id: "ada" }, { id: "books", computer: "cloud" }, { id: "cy", computer: "cloud" }], tasks: { t: ["books", "vm"] } });
+ expect(vm.membersOf(DESK)).toEqual(["ada", "books"]);
+ expect(vm.membersOf("cy")).toEqual(["cy"]);
+ control.take(DESK);
+ control.requestHelp("books", "sign in", { botId: "books", threadId: "u", messageId: "m", site: "a.example", place: "browser" });
+ expect(vm.botSnapshot("books")).toMatchObject({ held: true });
+ expect(vm.botSnapshot("gone").held).toBe(false);
+ });
+
+ it.each([
+ { row: "its VPS", target: "vps/ada", vpsTurnHeld: true, vmBotHeld: false },
+ { row: "the shared VM", target: "local/shared", vpsTurnHeld: false, vmBotHeld: true },
+ ])("a person's take naming $row on a conversation Auto has not placed pauses the turns on that desktop", ({ target, vpsTurnHeld, vmBotHeld }) => {
+ const { control, vm, bot } = fixture({ bots: [{ id: "ada", cloudBackend: "vps" }, { id: "bea" }],
+ tasks: { t1: ["ada", "cloud"], t2: ["ada", undefined] }, turnBots: { t1: { id: "ada" } } });
+ control.take(vm.holdKey(bot("ada"), "t2", target)!);
+ expect([vm.snapshot("ada", "t1").held, vm.snapshot("bea").held]).toEqual([vpsTurnHeld, vmBotHeld]);
+ });
+
+ it("the gate pauses only the conversations on a held desktop, while the bot list shows the bot held", () => {
+ const { control, vm } = fixture({ bots: [{ id: "ada" }, { id: "books", computer: "cloud" }], tasks: { t: ["books", "vm"], c: ["books", "cloud"] } });
+ control.take(DESK);
+ expect([vm.snapshot("books", "t").held, vm.snapshot("books", "c").held, vm.snapshot("books").held]).toEqual([true, false, false]);
+ expect(vm.botSnapshot("books").held).toBe(true);
+ control.take("books");
+ expect(vm.snapshot("books", "c").held).toBe(true);
+ });
+
+ it("opens the shared desktop's viewer only to a lease on the desktop key", () => {
+ const { vm, bot, setMode } = fixture({ bots: [{ id: "ada" }, { id: "books", computer: "cloud" }] });
+ expect(vm.leaseKey(bot("ada"))).toBe(DESK);
+ expect(vm.leaseKey(bot("books"))).toBe(DESK);
+ setMode("per-bot");
+ expect(vm.leaseKey(bot("books"))).toBe("books");
+ });
+
+ it.each([
+ { row: "taken on a conversation off the desktop, released without it", f: { tasks: { t: ["ada", "cloud"] } }, take: "t", release: undefined },
+ { row: "taken without a conversation, released with one on a team's cloud computer",
+ f: { bots: [{ id: "ada", computer: "cloud" }], teamTurns: { t: { computerId: "c2", botId: "ada" } } }, take: undefined, release: "t" },
+ { row: "taken during a team turn that has ended", f: { teamTurns: { t: { computerId: "c2", botId: "ada" } } }, take: "t", release: "t",
+ after: (f: Fixture) => { delete f.teamTurns!.t; } },
+ { row: "taken on a conversation since re-pinned", f: { bots: [{ id: "ada", computer: "cloud" }], tasks: { t: ["ada", "vm"] } }, take: "t", release: "t",
+ after: (f: Fixture) => { f.tasks!.t = ["ada", "cloud"]; } },
+ { row: "taken before the bot's computer changed", f: {}, take: undefined, release: undefined,
+ after: (_f: Fixture, ada: BotRecord) => { ada.computer = "cloud"; } },
+ { row: "taken on the shared desktop through another bot", f: { bots: [{ id: "ada", computer: "cloud" }, { id: "bea" }], tasks: { t: ["ada", "cloud"] } }, held: DESK, release: "t" },
+ ] as Array<{ row: string; f: Fixture; held?: string; take?: string; release?: string; after?: (f: Fixture, ada: BotRecord) => void }>)(
+ "a lease's check and release act on the hold it owns: $row", ({ f, held, take, release, after }) => {
+ vi.useFakeTimers();
+ try {
+ const { control, vm, bot } = fixture(f);
+ const key = held ?? vm.keyFor(bot("ada"), take);
+ control.acquireLease(key, "lease-0123456789abcdef", { armed: true });
+ after?.(f, bot("ada"));
+ expect(vm.keyFor(bot("ada"), release)).not.toBe(key);
+ vi.advanceTimersByTime(50_000);
+ expect(vm.check(bot("ada"), release, "lease-0123456789abcdef")).toMatchObject({ held: true, owned: true });
+ expect(vm.check(bot("ada"), release, "lease-other-0123456789").owned).toBe(false);
+ vi.advanceTimersByTime(50_000);
+ expect(control.snapshot(key).held, "the check renewed the hold's clock").toBe(true);
+ expect(vm.release(bot("ada"), release, "lease-0123456789abcdef").released).toBe(true);
+ expect(control.snapshot(key).held).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("a lease reused for two takes is checked and released on the conversation's own key first", () => {
+ const { control, vm, bot } = fixture({ tasks: { t: ["ada", "cloud"] } });
+ control.acquireLease(DESK, "lease-0123456789abcdef");
+ control.acquireLease("ada", "lease-0123456789abcdef");
+ expect(vm.release(bot("ada"), "t", "lease-0123456789abcdef").released).toBe(true);
+ expect([control.snapshot("ada").held, control.snapshot(DESK).held]).toEqual([false, true]);
+ });
+
+ it.each([
+ { row: "an Auto bot on a VPS, without a conversation", f: { bots: [{ id: "ada", cloudBackend: "vps" }] }, thread: undefined, key: "ada", armed: false },
+ { row: "an Auto bot on a VPS, on an unpinned conversation", f: { bots: [{ id: "ada", cloudBackend: "vps" }], tasks: { t: ["ada", undefined] } }, thread: "t", key: "ada", armed: false },
+ { row: "an Auto bot on a VPS, without a conversation but with an unpinned one", f: { bots: [{ id: "ada", cloudBackend: "vps" }], tasks: { t: ["ada", undefined] } }, thread: undefined, key: "ada", armed: false },
+ { row: "an Auto bot without a VPS", f: {}, thread: undefined, key: DESK, armed: true },
+ { row: "a bot set to the VM, with a VPS", f: { bots: [{ id: "ada", computer: "vm", cloudBackend: "vps" }] }, thread: undefined, key: DESK, armed: true },
+ { row: "an Auto bot on a VPS, on a conversation pinned to the VM", f: { bots: [{ id: "ada", cloudBackend: "vps" }], tasks: { t: ["ada", "vm"] } }, thread: "t", key: DESK, armed: true },
+ { row: "an Auto bot on a VPS in per-bot mode", f: { mode: "per-bot", bots: [{ id: "ada", cloudBackend: "vps" }] }, thread: undefined, key: "ada", armed: false },
+ { row: "an Auto bot without a VPS in per-bot mode", f: { mode: "per-bot" }, thread: undefined, key: "ada", armed: true },
+ { row: "an Auto bot in pool mode", f: { mode: "pool" }, thread: undefined, key: "ada", armed: false },
+ { row: "a cloud bot", f: { bots: [{ id: "ada", computer: "cloud" }] }, thread: undefined, key: "ada", armed: false },
+ { row: "an Auto bot without a VPS, from the desktop", f: {}, auth: desktop, thread: undefined, key: DESK, armed: false },
+ { row: "an Auto bot without a VPS, from a companion device", f: {}, auth: { ...desktop, companionDevice: "phone-1" }, thread: undefined, key: DESK, armed: true },
+ ] as Array<{ row: string; f: Fixture; auth?: RequestAuth; thread?: string; key: string; armed: boolean }>)("a take of $row holds its key, lapsing only when a phone took a Local VM", ({ f, auth, thread, key, armed }) => {
+ vi.useFakeTimers();
+ try {
+ const { control, vm, bot } = fixture(f);
+ expect(vm.keyFor(bot("ada"), thread)).toBe(key);
+ control.acquireLease(key, "lease-0123456789abcdef", { armed: vm.armed(auth ?? phone, bot("ada"), thread, key) });
+ vi.advanceTimersByTime(2 * 60 * 60_000);
+ expect(control.snapshot(key).held).toBe(!armed);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("a phone's take naming the shared desktop, or a VPS its bot does not have, still starts the expiry clock", () => {
+ const { vm, bot } = fixture({ mode: "per-bot", bots: [{ id: "ada", computer: "vm" }] });
+ expect(vm.armed(phone, bot("ada"), undefined, "ada", "vps/ada")).toBe(true);
+ expect(fixture().vm.armed(phone, fixture().bot("ada"), undefined, DESK, "local/shared")).toBe(true);
+ });
+
+ it("refuses a desktop take while the shared VM is being changed", () => {
+ expect(fixture({ busy: true }).vm.takeRefusal(DESK)).toMatch(/being updated or changed/);
+ expect(fixture({ busy: true }).vm.takeRefusal("ada")).toBeNull();
+ expect(fixture().vm.takeRefusal(DESK)).toBeNull();
+ });
+
+ it("keeps the held desktop, or a per-bot VM held through its bot, in use, and keeps a new turn off the shared VM", () => {
+ const { control, vm } = fixture({ bots: [{ id: "ada" }] });
+ expect(vm.heldOnTarget(SHARED_LOCAL_VM_TARGET)).toBe(false);
+ control.take(DESK);
+ expect(vm.heldOnTarget(SHARED_LOCAL_VM_TARGET)).toBe(true);
+ expect(vm.personHolds("computer:vm:shared")).toBe(true);
+ expect(vm.personHolds(`computer:vm:${perBotLocalVmTarget("ada").key}`)).toBe(false);
+ expect(vm.heldOnTarget(perBotLocalVmTarget("ada"))).toBe(false);
+ control.take("ada");
+ expect(vm.heldOnTarget(perBotLocalVmTarget("ada"))).toBe(true);
+ });
+
+ it("treats the desktop and team keys as shared by several bots, and a bot's own key as its own", () => {
+ const { vm } = fixture();
+ expect([vm.sharedKey(DESK), vm.sharedKey(teamComputerOwner("c1")), vm.sharedKey("ada")]).toEqual([true, true, false]);
+ });
+
+ it("refuses moving a bot off the held desktop, not a move that keeps its key", () => {
+ const { control, vm, bot } = fixture();
+ control.take(DESK);
+ expect(vm.keyMovesWhileHeld(bot("ada"), { ...bot("ada"), computer: "cloud" })).toBe(true);
+ expect(vm.keyMovesWhileHeld(bot("ada"), { ...bot("ada"), computer: "vm" })).toBe(false);
+ });
+
+ it("a mode change ends the desktop's hold and every hold whose key moved, and keeps the rest", () => {
+ const { control, vm, setMode } = fixture({ mode: "per-bot", bots: [{ id: "ada" }, { id: "cy", computer: "cloud" }] });
+ control.take("ada");
+ control.take("cy");
+ control.take(DESK);
+ const changed = vm.modeChanging();
+ setMode("shared");
+ changed();
+ expect([control.snapshot("ada").held, control.snapshot("cy").held, control.snapshot(DESK).held]).toEqual([false, true, false]);
+ });
+});
diff --git a/server/host/shared-vm-control.ts b/server/host/shared-vm-control.ts
new file mode 100644
index 0000000000..1c05e1aec3
--- /dev/null
+++ b/server/host/shared-vm-control.ts
@@ -0,0 +1,173 @@
+import { viewerTargetId } from "../../shared/desktop-viewer.ts";
+import type { ComputerControl, ControlSnapshot } from "../computer-control.ts";
+import { SHARED_LOCAL_VM_TARGET, perBotLocalVmTarget, type LocalVmTarget } from "../container-computer.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import type { BotRecord } from "../store.ts";
+import type { Surface } from "../surface.ts";
+import { teamComputerOwner } from "../team-computers.ts";
+
+/** A person's hold on the one shared Local VM. Bot ids match [\w-]+, so no bot's own key can equal it. */
+export const SHARED_VM_CONTROL_KEY = "desktop:local/shared";
+const SHARED_VM_RESOURCE = `computer:vm:${SHARED_LOCAL_VM_TARGET.key}`;
+const SHARED_VM_VIEWER = viewerTargetId(SHARED_LOCAL_VM_TARGET);
+
+export interface SharedVmControlDeps {
+ control: Pick<ComputerControl, "snapshot" | "release" | "releaseLease" | "ownsLease" | "heldBy" | "beat" | "forgetBot">;
+ store: { readonly bots: BotRecord[]; bot(id: string): BotRecord | null; tasks(botId: string): ReadonlyArray<{ threadId: string; surface?: string }> };
+ /** The Local VM mode; null in a Cloud home, which has no Local VM. */
+ mode(): "shared" | "per-bot" | "pool" | null;
+ /** The bot a conversation runs with: its running turn's settings, else the stored bot. */
+ botForThread(botId: string, threadId: string): BotRecord | null;
+ /** The settings each running direct turn uses, by conversation. */
+ turnBots: Pick<ReadonlyMap<string, BotRecord>, "entries">;
+ /** The team cloud computer each conversation's running turn holds, by conversation. */
+ teamTurns: Pick<ReadonlyMap<string, { computerId: string; botId: string }>, "get" | "values">;
+ /** The id of the team cloud computer the bot inherits. */
+ teamComputer(bot: BotRecord): string | undefined;
+ /** The computer a conversation works on, person- or auto-pinned; undefined while Auto has not chosen. */
+ place(bot: BotRecord, threadId: string): string | undefined;
+ /** The Local VM each conversation's running turn works on, by conversation. */
+ turnVmTargets: Pick<ReadonlyMap<string, LocalVmTarget>, "get">;
+ /** True while the shared VM's image, container or isolation mode is being changed. */
+ busy(): boolean;
+}
+
+/** Where a person's hold on a bot's computer lives, and what reads it: one key resolution for every person's path. */
+export function createSharedVmControl(deps: SharedVmControlDeps) {
+ const { control, store } = deps;
+
+ const sharedDesk = (): boolean => deps.mode() === "shared";
+ /** Whether a conversation works on a Local VM: its chosen place; while Auto has not chosen, the shared VM its running
+ * turn is on, else the bot's default, where an Auto bot with a VPS works on the VPS. */
+ const onLocalVm = (bot: BotRecord, threadId?: string): boolean => {
+ const place = threadId ? deps.place(bot, threadId) : undefined;
+ if (place !== undefined) return place === "vm";
+ if (threadId && deps.turnVmTargets.get(threadId)?.key === SHARED_LOCAL_VM_TARGET.key) return true;
+ return bot.computer === "vm" || (bot.computer === undefined && bot.cloudBackend !== "vps");
+ };
+ /** The team cloud computer a conversation's hold lands on: its running team turn's, else the one the bot inherits. */
+ const teamKey = (bot: BotRecord, threadId?: string): string | undefined => {
+ const team = threadId ? deps.teamTurns.get(threadId) : undefined;
+ if (team?.botId === bot.id) return teamComputerOwner(team.computerId);
+ const inherited = deps.teamComputer(bot);
+ return inherited ? teamComputerOwner(inherited) : undefined;
+ };
+ /** The team's cloud computer, the shared Local VM, or the bot's own key. Without a conversation it follows the bot's
+ * default place. */
+ const keyFor = (bot: BotRecord, threadId?: string): string =>
+ teamKey(bot, threadId) ?? (sharedDesk() && onLocalVm(bot, threadId) ? SHARED_VM_CONTROL_KEY : bot.id);
+
+ /** Its own key first, then every key a take through its panels or a gate of its turns can land on, so no panel is told less
+ * than its own hold; read from stored pins (Off overrides them), as every broadcast asks it of every bot. */
+ const botKeys = (bot: BotRecord): string[] => {
+ const keys = [bot.id, keyFor(bot)];
+ for (const [threadId, turnBot] of deps.turnBots.entries()) if (turnBot.id === bot.id) keys.push(keyFor(turnBot, threadId), keyFor(turnBot));
+ for (const turn of deps.teamTurns.values()) if (turn.botId === bot.id) keys.push(teamComputerOwner(turn.computerId));
+ if (sharedDesk() && !deps.teamComputer(bot) && bot.computer !== "off" &&
+ store.tasks(bot.id).some(task => task.surface === "vm" || (task.surface === undefined && bot.computer === undefined))) keys.push(SHARED_VM_CONTROL_KEY);
+ return [...new Set(keys)];
+ };
+
+ /** Held if any key is held, with the first sign-in plea on any of them, so a hold on one computer never hides a plea on another. */
+ const merged = (keys: string[]): ControlSnapshot => {
+ const snapshots = keys.map(key => control.snapshot(key));
+ const held = snapshots.find(snapshot => snapshot.held);
+ const pleading = snapshots.find(snapshot => snapshot.helpReason !== null);
+ if (!held) return pleading ?? snapshots[0]!;
+ return held.helpReason !== null || !pleading ? held : { ...held, helpReason: pleading.helpReason, help: pleading.help };
+ };
+
+ /** A hold taken without a conversation pauses every conversation of the bot, as a hold on its own key does; a turn still
+ * on the shared VM waits for its hold whatever its bot is set to now. */
+ const snapshot = (botId: string, threadId?: string): ControlSnapshot => {
+ const bot = threadId ? deps.botForThread(botId, threadId) : store.bot(botId);
+ const mounted = threadId && sharedDesk() && deps.turnVmTargets.get(threadId)?.key === SHARED_LOCAL_VM_TARGET.key ? [SHARED_VM_CONTROL_KEY] : [];
+ return merged([...new Set([botId, ...(bot ? [keyFor(bot, threadId), keyFor(bot)] : []), ...mounted])]);
+ };
+
+ /** What a bot's panels and the bot list are told: the first of its keys held, else the first pleading, else its own. */
+ const botSnapshot = (botId: string): ControlSnapshot => {
+ const bot = store.bot(botId);
+ return bot ? merged(botKeys(bot)) : control.snapshot(botId);
+ };
+
+ /** A team cloud computer or the shared Local VM serves several bots, so one bot's sign-in card must not hand it back
+ * from under another. */
+ const sharedKey = (key: string): boolean => key === SHARED_VM_CONTROL_KEY || key.startsWith(teamComputerOwner(""));
+ /** Outside shared mode no bot's keys name the shared desktop, yet panels paused on it before the change must hear it ended. */
+ const membersOf = (key: string): string[] => key === SHARED_VM_CONTROL_KEY && !sharedDesk() ? store.bots.map(bot => bot.id)
+ : sharedKey(key) ? store.bots.filter(bot => botKeys(bot).includes(key)).map(bot => bot.id) : [key];
+
+ const personHolds = (resource: string): boolean => resource === SHARED_VM_RESOURCE && control.snapshot(SHARED_VM_CONTROL_KEY).held;
+
+ /** The hold this lease owns: the key a take resolved may differ now, as places, pins and team turns change. */
+ const leaseHolder = (bot: BotRecord, threadId: string | undefined, lease: string): string => {
+ const key = keyFor(bot, threadId);
+ return control.ownsLease(key, lease) ? key : control.heldBy(lease) ?? key;
+ };
+
+ return {
+ keyFor,
+ /** The key a take or a hand-back without a lease holds: the desktop a panel names, else the conversation's own. Only the
+ * shared VM names more than the bot's own key, so only it is checked: null when this conversation cannot show it. */
+ holdKey: (bot: BotRecord, threadId: string | undefined, target?: string): string | null => {
+ if (target === undefined) return keyFor(bot, threadId);
+ if (target !== SHARED_VM_VIEWER) return bot.id;
+ if (!threadId) return keyFor(bot) === SHARED_VM_CONTROL_KEY ? SHARED_VM_CONTROL_KEY : null;
+ const place = deps.place(bot, threadId);
+ return sharedDesk() && !teamKey(bot, threadId) && (place === undefined || place === "vm") ? SHARED_VM_CONTROL_KEY : null;
+ },
+ snapshot,
+ membersOf,
+ botSnapshot,
+ /** A snapshot carrying the bot's sign-in plea as this viewer may see it: an answer never hides a plea the bot's frames
+ * show, and never shows one from a conversation the viewer cannot see. */
+ shown: <T extends ControlSnapshot>(snapshot: T, botId: string, hides: (threadId: string) => boolean): T => {
+ const { helpReason, help } = botSnapshot(botId);
+ const { help: _help, ...rest } = snapshot;
+ return (help && hides(help.threadId) ? { ...rest, helpReason: null } : { ...rest, helpReason, ...(help ? { help } : {}) }) as T;
+ },
+ /** Deleting a bot a person's hold reaches would leave that hold to panels that may no longer exist. */
+ deletionRefusal: (botId: string): string | null =>
+ botSnapshot(botId).held ? "Hand back control of this bot's computer before deleting it" : null,
+ /** The key a phone's lease must own to open this conversation's Local VM: the shared desktop's in shared mode. */
+ leaseKey: (bot: BotRecord, threadId?: string): string => sharedDesk() ? SHARED_VM_CONTROL_KEY : keyFor(bot, threadId),
+ heldOnTarget: (target: LocalVmTarget): boolean => {
+ if (target.key === SHARED_LOCAL_VM_TARGET.key) return control.snapshot(SHARED_VM_CONTROL_KEY).held;
+ return store.bots.some(bot => perBotLocalVmTarget(bot.id).key === target.key && control.snapshot(bot.id).held);
+ },
+ /** True while a person holds the shared VM this turn resource names. */
+ personHolds,
+ sharedKey,
+ signInKey: (bot: BotRecord, threadId: string, place: Surface): string => place === "browser" ? bot.id : keyFor(bot, threadId),
+ keyMovesWhileHeld: (before: BotRecord, after: BotRecord): boolean =>
+ keyFor(before) !== keyFor(after) && snapshot(before.id).held,
+ takeRefusal: (key: string): string | null =>
+ key === SHARED_VM_CONTROL_KEY && deps.busy() ? "The Local VM is being updated or changed — wait before taking control" : null,
+ /** A phone's take of a Local VM starts the expiry clock at once: nothing else may ever beat for it. A take naming a VPS
+ * desktop is not one, though it lands on the key a per-bot VM shares. */
+ armed: (auth: RequestAuth, bot: BotRecord, threadId: string | undefined, key: string, target?: string): boolean => {
+ const phone = auth.kind === "loopback" ? Boolean(auth.companionDevice) : auth.via === "bearer";
+ return phone && !(target?.startsWith("vps/") && bot.cloudBackend === "vps") && (key === SHARED_VM_CONTROL_KEY ||
+ (key === bot.id && deps.mode() === "per-bot" && onLocalVm(bot, threadId)));
+ },
+ release: (bot: BotRecord, threadId: string | undefined, lease: string) =>
+ control.releaseLease(leaseHolder(bot, threadId, lease), lease),
+ check: (bot: BotRecord, threadId: string | undefined, lease: string) => {
+ const key = leaseHolder(bot, threadId, lease);
+ return { ...control.snapshot(key), owned: control.beat(key, lease) };
+ },
+ /** Ends the bot's pleas once the bot is gone; a deletion that was cancelled leaves them. */
+ botDeleted: (botId: string): void => {
+ if (!store.bot(botId)) control.forgetBot(botId);
+ },
+ /** Called before a Local VM mode change is saved; the returned call, once it is, ends the holds no path reads any more. */
+ modeChanging: (): (() => void) => {
+ const before = new Map(store.bots.map(bot => [bot.id, keyFor(bot)]));
+ return () => {
+ for (const bot of store.bots) if (before.has(bot.id) && before.get(bot.id) !== keyFor(bot)) control.release(before.get(bot.id)!);
+ control.release(SHARED_VM_CONTROL_KEY);
+ };
+ },
+ };
+}
diff --git a/server/host/sign-in-settle.test.ts b/server/host/sign-in-settle.test.ts
index 0ecfcc1cad..84db1419fd 100644
--- a/server/host/sign-in-settle.test.ts
+++ b/server/host/sign-in-settle.test.ts
@@ -30,7 +30,7 @@ function world(parked?: Partial<HandoffView>, pleas = new Map<string, string[]>(
}),
handBackBrowser: (_bot, threadId) => { handedBack.push(threadId); },
releaseComputer: (key) => { handedBackKeys.push(key); },
- computerKey: (bot) => bot.id,
+ computerKey: (bot, threadId) => `${bot.id}/${threadId}`,
sharedKey: (key) => key.startsWith("computer_"),
pleas: (key) => (pleas.get(key) ?? []).map((messageId) => ({ botId: "dachs", threadId: "work", messageId, site: "notion.so", place: "vm" })),
};
@@ -95,6 +95,17 @@ describe("the computer a sign-in card lent the person", () => {
return w.handedBackKeys.includes(key);
};
+ it("goes back from the card's own conversation when no plea of it is left, as after a restart", () => {
+ const w = world();
+ w.add({ ...card(), signIn: { ...card().signIn, place: "vm" } });
+ w.settle.settle("dachs", "work", "m1", "done");
+ expect(w.handedBackKeys).toEqual(["dachs/work"]);
+ const answered = world();
+ answered.add({ ...card(), signIn: { ...card().signIn, place: "vm" } });
+ answered.settle.answerInChat("dachs", "work", "Bin angemeldet");
+ expect(answered.handedBackKeys).toEqual(["dachs/work"]);
+ });
+
it("goes back on every path when it is the bot's own, and a shared one only when the person settles its last plea", () => {
const paths: Path[] = ["done", "cancelled", "answered in chat", "answered elsewhere", "verified"];
expect(paths.map((path) => [path, handsBack(path, "dachs", false), handsBack(path, "dachs", true), handsBack(path, "computer_team", false), handsBack(path, "computer_team", true)])).toEqual([
@@ -105,4 +116,19 @@ describe("the computer a sign-in card lent the person", () => {
["verified", true, true, false, false],
]);
});
+
+ it("on the person's Done or Cancel also goes back from where the conversation works now, as after a move", () => {
+ const released = (path: Path) => {
+ const w = world(undefined, new Map([["computer_team", ["m1"]]]));
+ w.add({ ...card(), signIn: { ...card().signIn, place: "vm" } });
+ if (path === "done" || path === "cancelled") w.settle.settle("dachs", "work", "m1", path);
+ if (path === "answered in chat") w.settle.answerInChat("dachs", "work", "Bin angemeldet");
+ return w.handedBackKeys;
+ };
+ expect([released("done"), released("cancelled"), released("answered in chat")]).toEqual([
+ ["computer_team", "dachs/work"],
+ ["computer_team", "dachs/work"],
+ [],
+ ]);
+ });
});
diff --git a/server/host/sign-in-settle.ts b/server/host/sign-in-settle.ts
index a0205d4cfa..2c24b66585 100644
--- a/server/host/sign-in-settle.ts
+++ b/server/host/sign-in-settle.ts
@@ -18,7 +18,8 @@ export interface SignInSettleDeps {
settleHelp(messageId: string): string[];
handBackBrowser(bot: BotRecord, threadId: string): void;
releaseComputer(key: string): void;
- computerKey(bot: BotRecord): string;
+ /** The control key a person's hold on this conversation's computer sits on. */
+ computerKey(bot: BotRecord, threadId: string): string;
/** True when several bots drive the computer behind this control key, so no one bot's card may hand it back alone. */
sharedKey(key: string): boolean;
/** The sign-in cards on this control key that still wait for the person. */
@@ -36,11 +37,12 @@ export function createSignInSettle(deps: SignInSettleDeps) {
const { store } = deps;
/** The person is through with the place the card lent them: its plea goes, and the browser or computer goes back to the
- * bot. A computer several bots share goes back only when the person pressed Done or Cancel and no other card waits for it. */
+ * bot. A computer several bots share goes back only when the person pressed Done or Cancel and no other card waits for it.
+ * Their Done also hands back where the conversation works now, which a repin since the card may have moved. */
const handPlaceBack = (bot: BotRecord, threadId: string, messageId: string, place: Surface, byPerson: boolean): void => {
const pleaded = deps.settleHelp(messageId);
if (place === "browser") deps.handBackBrowser(bot, threadId);
- else for (const key of pleaded.length ? pleaded : [deps.computerKey(bot)]) {
+ else for (const key of new Set([...pleaded, ...(byPerson || !pleaded.length ? [deps.computerKey(bot, threadId)] : [])])) {
if (!deps.sharedKey(key) || (byPerson && !deps.pleas(key).length)) deps.releaseComputer(key);
}
};
diff --git a/server/index.test.ts b/server/index.test.ts
index 3ca95bf97a..012d777cda 100644
--- a/server/index.test.ts
+++ b/server/index.test.ts
@@ -10561,6 +10561,26 @@ describe("harness HTTP API", () => {
}
});
+ it("gives a hold back by its lease after the conversation it was taken through is deleted", async () => {
+ const bot = (await api("POST", "/api/bots")).body.bot;
+ const lease = "viewer-lease-0123456789";
+ try {
+ const task = (await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Short-lived" })).body.task;
+ const control = `/api/bots/${bot.id}/computer/control?threadId=${task.threadId}`;
+ expect((await api("POST", control, { action: "take", controlLeaseId: lease })).body).toMatchObject({ held: true, owned: true });
+ expect((await api("DELETE", `/api/bots/${bot.id}/tasks/${task.threadId}`)).status).toBe(200);
+ expect((await api("GET", control)).status).toBe(404);
+ expect((await api("POST", control, { action: "take" })).status).toBe(404);
+ expect((await api("POST", control, { action: "release" })).status).toBe(404);
+ const released = await api("POST", control, { action: "release", controlLeaseId: lease });
+ expect(released.status).toBe(200);
+ expect(released.body).toMatchObject({ held: false, released: true });
+ } finally {
+ await api("POST", `/api/bots/${bot.id}/computer/control`, { action: "release" }).catch(() => undefined);
+ await api("DELETE", `/api/bots/${bot.id}`).catch(() => undefined);
+ }
+ });
+
it("hands out a Local VM's viewer only to the lease holding the computer, once the VM is ready", async () => {
const previous = (await api("GET", "/api/config")).body.localVm;
const bot = (await api("POST", "/api/bots")).body.bot;
@@ -10656,7 +10676,10 @@ describe("harness HTTP API", () => {
}
});
- it.each(["shared", "pool"])("refuses Local VM phone joins in %s mode for direct and companion callers", async testedMode => {
+ it.each([
+ { testedMode: "shared", refusal: expect.not.stringMatching(/take control|pool mode|per-bot Local VM/i) },
+ { testedMode: "pool", refusal: "Phone control is not available in pool mode. Select shared or per-bot mode in Settings → Computers." },
+ ])("answers Local VM phone joins in $testedMode mode for direct and companion callers past the mode check only when it is not pool", async ({ testedMode, refusal }) => {
const { mode, maxInstances } = (await api("GET", "/api/config")).body.localVm;
const previous = { mode, maxInstances };
const bot = (await api("POST", "/api/bots")).body.bot;
@@ -10666,9 +10689,10 @@ describe("harness HTTP API", () => {
expect((await api("PATCH", "/api/config", { localVm: { ...previous, mode: testedMode } })).status).toBe(200);
expect((await owner.call("POST", `/api/bots/${bot.id}/computer/control`, { action: "take", controlLeaseId: lease })).body.owned).toBe(true);
const join = `/api/bots/${bot.id}/local-computer/join?controlLeaseId=${lease}`;
+ // This suite's container runtime is unavailable, so a join past the mode and lease checks stops at readiness.
for (const response of [await owner.call("POST", join, {}), await api("POST", join, {})]) {
expect(response.status).toBe(409);
- expect(response.body.error).toContain("per-bot Local VM");
+ expect(response.body.error).toEqual(refusal);
expect(response.body.joinUrl).toBeUndefined();
expect(response.body.socketPath).toBeUndefined();
expect(response.body.password).toBeUndefined();
diff --git a/server/index.ts b/server/index.ts
index 7727d3c370..ab833513b5 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -184,7 +184,7 @@ import {
} from "./config.ts";
import { serveStatic } from "./static-files.ts";
import { startUpkeep } from "./host/start-upkeep.ts";
-import { ComputerControl } from "./computer-control.ts";
+import { ComputerControl, type ControlSnapshot } from "./computer-control.ts"; import { createSharedVmControl } from "./host/shared-vm-control.ts";
import { resetPathCache } from "./env-path.ts";
import { registerEnginesBinDir } from "./engine-install.ts"; import { engineUpdatesFor } from "./engine-updates-host.ts";
import { appendUsage, flushUsageLedger, queuedTurnTrigger, usageTriggerFor, type UsageRow, type UsageTrigger } from "./usage-ledger.ts"; import { createUsageAttribution } from "./usage-attribution.ts";
@@ -612,7 +612,7 @@ import { createDesktopViewer, desktopViewerUrl } from "./routes/desktop-viewer.t
import { createUpgrades } from "./routes/upgrades.ts";
import { createBrowserViewerRoutes } from "./routes/browser-viewers.ts";
import { localDesktopTarget, localVmViewerStatus } from "./desktop-viewer-targets.ts";
-import { viewerTargetId } from "../shared/desktop-viewer.ts";
+import { DESKTOP_VIEWER_TARGET, viewerTargetId } from "../shared/desktop-viewer.ts";
import { createComputerPreviews } from "./computer-previews.ts";
import { createAntigravityLeftoverRoutes } from "./routes/antigravity-leftovers.ts";
import { createAntigravityAccountRoutes } from "./routes/antigravity-accounts.ts";
@@ -2046,7 +2046,7 @@ function stopCards(threadId: string, ids: ReadonlySet<string>): void {
if (!ids.has(message.id)) continue;
if (message.secret) store.patchMessage(threadId, message.id, { secret: { ...message.secret, stopped: true } });
else if (message.connector) store.patchMessage(threadId, message.id, { connector: { ...message.connector, stopped: true } });
- else if (message.signIn) store.patchMessage(threadId, message.id, { signIn: { ...message.signIn, stopped: true } });
+ else if (message.signIn) { store.patchMessage(threadId, message.id, { signIn: { ...message.signIn, stopped: true } }); computerControl.settleHelp(message.id); }
else {
const closed = closedByStop(message.card);
if (closed) store.patchMessage(threadId, message.id, { card: closed });
@@ -2086,7 +2086,7 @@ const turnPlaces = new Map<string, { botId: string; place: Surface }>();
const settlingResourceOwners = new Map<string, string>();
function claimTurnResource(owner: TurnOwner, resource: string): boolean {
- if (!turnResources.claim(resource, owner)) return false;
+ if ((sharedVm.personHolds(resource) && !turnResources.owns(resource, owner)) || !turnResources.claim(resource, owner)) return false;
turnResourceOwners.set(owner.threadId, owner);
return true;
}
@@ -2167,7 +2167,7 @@ async function bindTurnComputer(owner: TurnOwner, resource: string, exclusive =
const position = turnResources.startWaiting(resource, owner);
const estimateMs = turnResources.waitEstimateMs(resource);
const blocker = turnResources.blocker(resource, owner);
- ({ holder, threadRef: holderThreadRef } = blocker ? holderOfTurn(blocker) : { holder: undefined, threadRef: undefined });
+ ({ holder, threadRef: holderThreadRef } = blocker ? holderOfTurn(blocker) : { holder: sharedVm.personHolds(resource) ? { name: "A person" } : undefined, threadRef: undefined });
waitingMessage = store.appendMessage(owner.threadId, {
role: "bot", kind: "activity",
tool: { name: computerWaitingText(holder, { position, estimateMs }) },
@@ -2456,19 +2456,17 @@ function setupConnectedApps(bot: Pick<BotRecord, "composio" | "connectorTools">,
}
const computerControlRevision = new Map<string, number>();
-const computerControl = new ComputerControl((key, snapshot) => {
- const members = key.startsWith("computer_")
- ? store.bots.filter(bot => inheritedTeamComputer(bot)?.id === key.slice("computer_".length)).map(bot => bot.id)
- : [key];
- for (const botId of members) {
+const computerControl = new ComputerControl((key) => { for (const botId of sharedVm.membersOf(key)) announceControl(botId);
+}, Date.now, (ref) => signInCardWaits(signInMessage(ref.botId, ref.threadId, ref.messageId)?.signIn));
+function announceControl(botId: string): void {
+ const snapshot = sharedVm.botSnapshot(botId);
computerControlRevision.set(botId, (computerControlRevision.get(botId) ?? 0) + 1);
// One-way, fail-closed mirror into Electron: never send release, since a loopback caller can influence the server record.
if (snapshot.held && /^[A-Za-z0-9_-]{1,120}$/.test(botId)) {
postDesktopPrivateMessage({ type: "openmausbot:browser-control", botId, held: true });
}
broadcast({ kind: "computer-control", botId, held: snapshot.held, helpReason: snapshot.helpReason, ...(snapshot.help ? { help: snapshot.help } : {}) });
- }
-}, Date.now, (ref) => signInCardWaits(signInMessage(ref.botId, ref.threadId, ref.messageId)?.signIn));
+}
const controlLeaseIdSchema = z.string().min(16).max(120).regex(/^[A-Za-z0-9_-]+$/);
function controlIntegration(
botId: string,
@@ -2794,6 +2792,9 @@ const store = new Store(
() => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale,
() => sharedMembership() ? undefined : cfg.profile?.name,
);
+const sharedVm = createSharedVmControl({ control: computerControl, store, mode: () => CLOUD_HOME ? null : localVmMode(cfg), botForThread, turnBots: directTurnBots,
+ teamTurns: teamComputerTurns, teamComputer: (bot) => inheritedTeamComputer(bot)?.id, place: (bot, threadId) => turnSurfacePlan(bot, undefined, threadId).computer,
+ turnVmTargets: { get: (threadId) => localVmThreadTargets.get(threadId) }, busy: () => localVmModeChangeBusy || localVmImageBusy || localVmLifecycleBusy.has(SHARED_LOCAL_VM_TARGET.key) });
const outsideLineage = createOutsideLineage({
home: Boolean(CLOUD_HOME), team: Boolean(CLOUD_TEAM), solo: () => cloudHome?.solo() === true, store,
confinedNow: (threadId) => guestDrivenTurns.has(threadId), activeRun: activeRoutineRunForThread,
@@ -4516,9 +4517,11 @@ store.onChange((change) => {
break;
case "thread":
broadcast({ kind: "thread", threadId: change.threadId, activeLeafId: change.activeLeafId });
+ for (const botId of computerControl.recheck([change.threadId])) announceControl(botId);
break;
case "thread.deleted":
directRequestOwners.delete(change.threadId);
+ for (const botId of computerControl.forgetThread(change.threadId)) announceControl(botId);
stoppedTurns.delete(change.threadId);
turnStops.forget(change.threadId);
repeats.settle(change.threadId);
@@ -4550,6 +4553,7 @@ store.onChange((change) => {
const group = store.group(change.groupId);
if (group) broadcast({ kind: "group", group: { ...publicGroupState(group), ...pageIfThreadChanged(group.id, group.threadId) } });
if (group) settleRoomFloor(group);
+ if (group) for (const botId of computerControl.recheck([group.threadId, ...(group.tasks ?? []).map((task) => task.threadId)])) announceControl(botId);
break;
}
case "group.deleted":
@@ -4662,8 +4666,8 @@ const desktopViewer = createDesktopViewer({
lease: (id, botId, controlLeaseId, threadId) => {
const bot = store.bot(botId);
if (!bot || viewerTargetId(localVmTargetForStatus(bot.id, threadId)) !== id) return;
- const key = botComputerControlKey(bot);
- const holds = () => computerControl.ownsLease(key, controlLeaseId);
+ const key = sharedVm.leaseKey(bot, threadId);
+ const holds = () => computerControl.beat(key, controlLeaseId);
return holds() ? holds : undefined;
},
});
@@ -5612,7 +5616,7 @@ const localVmUpdates = createLocalVmUpdater({
imageBusy: { get: () => localVmImageBusy, set: (busy) => { localVmImageBusy = busy; } },
provisionBusy: { get: () => localVmProvisionBusy, set: (busy) => { localVmProvisionBusy = busy; } },
lifecycleBusy: localVmLifecycleBusy,
- inUse: (target) => localVmModeChangeBusy || localVmActiveThreads.has(target.key) || Boolean(localVmLeaseFor(target).current(localVmOwnerBusy)),
+ inUse: (target) => localVmModeChangeBusy || localVmActiveThreads.has(target.key) || Boolean(localVmLeaseFor(target).current(localVmOwnerBusy)) || sharedVm.heldOnTarget(target),
updated: (target, status) => { noteLocalVmSeen(target, status); localVmIdleFor(target).touch(); },
keepApps: async (target, status, stop) => localVmPreservesInstalledApps(cfg)
? keepInstalledAppsBeforeRemove(target, status, stop)
@@ -5673,7 +5677,7 @@ async function computerCallGate(internalCapability: InternalCapability, signal?:
const deadline = askedAt + COMPUTER_CALL_WAIT_MS;
let personHeld = false;
for (;;) {
- const snapshot = botComputerControlSnapshot(botId, internalCapability.teamComputerId);
+ const snapshot = sharedVm.snapshot(botId, threadId);
const helpOpen = snapshot.helpReason !== null;
const slot = autoVmClaims.get(threadId);
const lazyClaim = slot && slot.owner.generation === generation ? slot : undefined;
@@ -5712,13 +5716,6 @@ async function computerCallGate(internalCapability: InternalCapability, signal?:
}
}
-function botComputerControlSnapshot(botId: string, pinnedComputerId?: string) {
- const own = computerControl.snapshot(botId);
- const bot = store.bot(botId);
- const key = pinnedComputerId ? teamComputerOwner(pinnedComputerId) : bot ? botComputerControlKey(bot) : botId;
- const shared = computerControl.snapshot(key);
- return own.held ? own : shared.held || shared.helpReason ? shared : own;
-}
function teamComputerInUse(computer: TeamComputerRecord): boolean {
computer = teamComputers.get(computer.id) ?? computer;
@@ -5736,10 +5733,11 @@ function claimTeamComputerLifecycle(computer: TeamComputerRecord): () => void {
}
function assertTeamComputerChangeIdle(before: BotRecord, after: BotRecord): void {
+ if (sharedVm.keyMovesWhileHeld(before, after)) throw Object.assign(new Error("Hand back control of this bot's computer before changing where it works"), { status: 409 });
const previous = inheritedTeamComputer(before);
const next = inheritedTeamComputer(after);
if (previous?.id === next?.id) return;
- if (botHasActiveTurn(before.id) || routines?.activeRunForBot(before.id) || botComputerControlSnapshot(before.id).held ||
+ if (botHasActiveTurn(before.id) || routines?.activeRunForBot(before.id) || sharedVm.snapshot(before.id).held ||
[previous, next].some(computer => computer && (teamComputerInUse(computer) || boatLifecycleBusyBots.has(teamComputerOwner(computer.id))))) {
throw Object.assign(new Error("Stop the affected team's work and release computer control before changing its computer access"), { status: 409 });
}
@@ -5930,7 +5928,7 @@ function managedBoatOwners(): boat.ManagedBoatOwner[] {
activeGroupTurnForBot(bot.id) !== null ||
Boolean(routines?.activeRunForBot(bot.id)) ||
activeVpsThreads.has(bot.id) ||
- computerControl.snapshot(bot.id).held,
+ sharedVm.snapshot(bot.id).held,
})), ...teamComputers.list().map(computer => ({
botId: teamComputerOwner(computer.id), name: computer.name, inUse: teamComputerInUse(computer),
}))];
@@ -6226,7 +6224,7 @@ function localVmIdleFor(target: LocalVmTarget): ComputerIdleTimer {
if (idle) return idle;
idle = new ComputerIdleTimer(
localVmIdleMs(),
- () => localVmImageBusy || localVmLifecycleBusy.has(target.key) || localVmActiveThreads.has(target.key),
+ () => localVmImageBusy || localVmLifecycleBusy.has(target.key) || localVmActiveThreads.has(target.key) || sharedVm.heldOnTarget(target),
async () => {
localVmLifecycleBusy.add(target.key);
try {
@@ -7428,7 +7426,7 @@ function startScreenPoller(
browser: guarded(captures.browser, browserSession ? `browser:${browserSession}` : undefined),
},
control: () => ({
- held: botComputerControlSnapshot(botId, teamComputerTurns.get(threadId)?.computerId).held,
+ held: sharedVm.snapshot(botId, threadId).held,
revision: computerControlRevision.get(botId) ?? 0,
}),
onFrame: (frame, surface) => { if (surface === "computer") rememberTurnFrame(turnComputerResources.get(threadId)?.resource, frame); broadcast({ kind: "screen", botId, threadId, surface, ...frame }); },
@@ -9003,6 +9001,7 @@ async function deleteBotWithLifecycle(botId: string, revalidate: () => void = ()
revalidate();
const bot = store.bot(botId);
if (!bot) return deletionResponse( 404, { error: "no such bot" }); if (bot.defaultBot) return deletionResponse(409, { error: defaultBotRefusal(bot.name) });
+ const heldRefusal = sharedVm.deletionRefusal(bot.id); if (heldRefusal) return deletionResponse(409, { error: heldRefusal });
if (computerProviderConfigTransitions.size > 0) {
return deletionResponse( 409, { error: "computer provider settings are being updated — wait before deleting this bot" });
}
@@ -9090,8 +9089,8 @@ async function deleteBotWithLifecycle(botId: string, revalidate: () => void = ()
}
const ownedBoatComputers = cloudInventory.instances.filter((instance) => instance.ownerBotId === bot.id);
- // Revalidate and record the browser cleanup intent before the first irreversible provider mutation.
- revalidate();
+ // Revalidate, re-check a person's holds (one may have come through another bot meanwhile) and record the browser cleanup intent before the first irreversible provider mutation.
+ revalidate(); const heldNow = sharedVm.deletionRefusal(bot.id); if (heldNow) return deletionResponse(409, { error: heldNow });
const browserCleanupRequest = browserCleanup.prepare("bot", bot.id);
try {
for (const instance of ownedBoatComputers) {
@@ -9129,14 +9128,12 @@ async function deleteBotWithLifecycle(botId: string, revalidate: () => void = ()
stopScreenPoller(bot.id);
activeVpsThreads.delete(bot.id);
lastReply.delete(bot.threadId);
- computerControl.forget(bot.id);
- computerControlRevision.delete(bot.id);
const target = perBotLocalVmTarget(bot.id);
localVmIdles.get(target.key)?.cancel();
localVmIdles.delete(target.key);
// Re-check the reviewed receipt at the final durable mutation, so a concurrent profile edit cannot be erased under a stale approval.
revalidate();
- store.deleteBot(bot.id, setupRequest);
+ store.deleteBot(bot.id, setupRequest); sharedVm.botDeleted(bot.id); computerControlRevision.delete(bot.id);
skillReview.dropBot(bot.id);
memoryUpkeep.forgetBot(bot.id);
calendarCalls!.removeBot(bot.id);
@@ -9263,7 +9260,7 @@ const teamSetupRequests = new TeamSetupRequestService({
Boolean(group && group.threadId !== sourceThreadId) || Boolean(run && run.threadId !== sourceThreadId);
},
validateModel: validateModelProposal,
- driverCapabilities: driverCapabilitiesFor,
+ driverCapabilities: driverCapabilitiesFor, deletionRefusal: sharedVm.deletionRefusal,
deleteBot: async (botId, revalidate, request) => {
const result = await deleteBotWithLifecycle(botId, revalidate, request);
if (result.status >= 400) throw new TeamSetupError(result.body.error ?? "The bot could not be deleted", result.status);
@@ -11534,12 +11531,6 @@ function signInPlace(bot: BotRecord, threadId: string): Surface | null {
return store.taskByThread(bot.id, threadId)?.surface ?? parseSurface(bot.computer) ?? null;
}
-function signInControlKey(bot: BotRecord, threadId: string, place: Surface): string {
- if (place === "browser") return bot.id;
- const team = teamComputerTurns.get(threadId);
- return team?.botId === bot.id ? teamComputerOwner(team.computerId) : botComputerControlKey(bot);
-}
-
/** Appends the new card first, so a failed append leaves the older one actionable. */
function requestSignIn(from: BotRecord, threadId: string, rawSite: unknown, rawReason: unknown):
{ messageId: string; site: string; place: Surface } | { status: number; error: string } {
@@ -11562,7 +11553,7 @@ function requestSignIn(from: BotRecord, threadId: string, rawSite: unknown, rawR
store.patchMessage(threadId, prior.id, { signIn: { ...prior.signIn, superseded: true } }); coordinator.followCard(threadId, prior.id, message.id);
computerControl.settleHelp(prior.id);
}
- computerControl.requestHelp(signInControlKey(from, threadId, place), `sign in to ${target.site}`,
+ computerControl.requestHelp(sharedVm.signInKey(from, threadId, place), `sign in to ${target.site}`,
{ botId: from.id, threadId, messageId: message.id, site: target.site, place });
return { messageId: message.id, site: target.site, place };
}
@@ -11580,7 +11571,7 @@ const signInSettle = createSignInSettle({
store, signInMessage, answerCardNode, releaseCardNode, resumableCards,
parkedDirect: (threadId) => coordinator.parkedDirect(threadId) ?? coordinator.active().find((n) => n.threadId === threadId && n.parentId && !n.groupId && n.status === "waiting" && n.cards?.length), settleHelp: (messageId) => computerControl.settleHelp(messageId),
handBackBrowser: (bot, threadId) => browserLive.handBack(currentBrowserSession(bot.id, bot.browserProfile, teamHost.browserAudience(threadId))),
- releaseComputer: (key) => computerControl.release(key), computerKey: botComputerControlKey, sharedKey: (key) => key.startsWith(teamComputerOwner("")), pleas: (key) => computerControl.pleas(key),
+ releaseComputer: (key) => computerControl.release(key), computerKey: sharedVm.keyFor, sharedKey: sharedVm.sharedKey, pleas: (key) => computerControl.pleas(key),
});
/** The open sign-in card the person is answering, and the page its bot's browser shows (null when none a login could fill). */
@@ -12067,7 +12058,7 @@ const workspaceBackupAccess = {
!localVmLifecycleBusy.size && !boatLifecycleBusyBots.size && !computerPreviews.size && !orphanBoatLifecycleBusyIds.size &&
!computerProviderConfigTransitions.size &&
teamComputers.list().every(computer => !teamComputerInUse(computer)) &&
- store.bots.every((bot) => !botHasActiveTurn(bot.id) && !routines?.activeRunForBot(bot.id) && !botComputerControlSnapshot(bot.id).held) &&
+ store.bots.every((bot) => !botHasActiveTurn(bot.id) && !routines?.activeRunForBot(bot.id) && !sharedVm.snapshot(bot.id).held) &&
store.groups.every((group) => !groupIsWorking(group)),
pause: () => { routines?.stop(); calendarCalls?.stop(); botWaits.stop(); watchdog.stop(); memoryUpkeep.pause(); },
resume: () => { if (!moveFreeze.frozen()) { routines?.start(); calendarCalls?.start(); botWaits.start(); } watchdog.start(); memoryUpkeep.resume(); },
@@ -12127,7 +12118,7 @@ ROUTES.push(createThreadRoutes({
companionMutationToken: () => companionMutationToken,
cliOwnerToken: () => cliOwnerToken,
pageSize, messagePage, messageWindow, publicBotQueuedMessages, publicGroupState, wireBot,
- botComputerControlSnapshot, messageFileRootsForThread, viewerFor, visibleTo, coordinator, groupThreadIsWorking, memberDefaultBot: CLOUD_TEAM ? (email) => { const own = ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM.name, opened: (made) => void mausbotOwnChat.claim(made) }); if (own) void mausbotOwnChat.claim(own); return own; } : undefined,
+ botComputerControlSnapshot: sharedVm.botSnapshot, messageFileRootsForThread, viewerFor, visibleTo, coordinator, groupThreadIsWorking, memberDefaultBot: CLOUD_TEAM ? (email) => { const own = ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM.name, opened: (made) => void mausbotOwnChat.claim(made) }); if (own) void mausbotOwnChat.claim(own); return own; } : undefined,
uploads: uploadsFor(createUploadOwners(DATA_DIR), Boolean(CLOUD_TEAM)),
attachmentInUse: (name) => threadsReferencing(name).length > 0 || store.bots.some((bot) => bot.avatarUrl === `/api/attachments/${name}`),
keptAttachments: CLOUD_TEAM ? undefined : keptAttachments,
@@ -12376,6 +12367,7 @@ const postiz = createPostiz({ cfg: () => cfg, mcpOAuth, persistMcpServers: persi
lendingEnabled: () => lendingEnabled() || ownerLends(), providerConfigs, localVmIdleMs, localVmIdles, localVmActiveThreads, localVmLifecycleBusy,
localVmImageBusy: { get: () => localVmImageBusy },
localVmModeChangeBusy: { set: (busy) => { localVmModeChangeBusy = busy; } },
+ localVmModeChanging: sharedVm.modeChanging,
providerConfigBusy: { get: () => providerConfigBusy, set: (busy) => { providerConfigBusy = busy; } },
computerProviderConfigTransitions, managedBoatOwners, providerOperationConflict, perBotLocalVmCountForModeChange,
checkedModelSelection, policyModelRefusal, browserSessionSpec, configStatus,
@@ -12407,7 +12399,7 @@ ROUTES.push(createComputerRoutes({
localVmModeChangeBusy: { get: () => localVmModeChangeBusy },
localVmOwnerBusy, localVmIdleMs, localVmLeaseFor, localVmIdleFor, localVmTargetForBot, localVmTargetForStatus,
localVmPayload, localVmInventoryPayload, existingPerBotLocalVmCount, teamComputersPayload, teamComputerInUse,
- managedBoatOwners, providerTransitionMessage, botHasActiveTurn, botComputerControlKey, botComputerControlSnapshot,
+ managedBoatOwners, providerTransitionMessage, botHasActiveTurn, localVmLeaseKey: sharedVm.leaseKey, botComputerControlSnapshot: sharedVm.snapshot,
computerPreviewBot, computerPreviewSurface, claimTeamComputerLifecycle, claimBotComputerLifecycle,
claimBoatInventoryRequest, claimManagedBoatMutation, claimManagedVpsMutation, cloudComputerUsed: owner => cloudComputerPower.used(owner),
}));
@@ -13301,7 +13293,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const runtime = (await containerRuntimeStatus()).runtime;
requireActiveInternalCapability();
if (!runtime || !internalCapabilityIsActive({ ...internalCapability, localVmTarget: vm }) ||
- botComputerControlSnapshot(internalSender.id).held) {
+ sharedVm.snapshot(internalSender.id, threadId).held) {
return json(res, 409, { error: "The Local VM is no longer available to this turn." });
}
const result = await containerExec(vm, typeof body.command === "string" ? body.command : "", {
@@ -15111,18 +15103,23 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
// The person's take and release; the bot has no verb here, only a sign-in request its card settles.
m = path.match(/^\/api\/bots\/([\w-]+)\/computer\/control$/);
if (m) {
- const bot = store.bot(m[1]);
+ const named = url.searchParams.get("threadId"), gone = Boolean(named && store.bot(m[1]) && !store.projectBotForTask(m[1], named));
+ if (gone && method === "POST") url.searchParams.delete("threadId");
+ if (!computerPreviewBot(m[1], url)) return json(res, 404, { error: "no such bot" });
+ if (method === "POST" && !String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {
+ return json(res, 415, { error: "content-type must be application/json" });
+ }
+ const body = method === "POST" ? await readBody(req) : undefined;
+ const bot = computerPreviewBot(m[1], url);
if (!bot) return json(res, 404, { error: "no such bot" });
- if (method === "GET") return json(res, 200, botComputerControlSnapshot(bot.id));
+ const threadId = url.searchParams.get("threadId") ?? undefined;
+ const shown = <T extends ControlSnapshot>(snapshot: T) => sharedVm.shown(snapshot, bot.id, (id) => visibleTo(viewerFor(auth)).hides(id));
+ if (method === "GET") return json(res, 200, shown(sharedVm.botSnapshot(bot.id)));
if (method === "POST") {
- if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {
- return json(res, 415, { error: "content-type must be application/json" });
- }
- const body = await readBody(req);
const action = String(body.action ?? "");
const currentBot = store.bot(bot.id);
if (!currentBot) return json(res, 404, { error: "no such bot" });
- const controlKey = botComputerControlKey(currentBot);
+ const boatKey = botComputerControlKey(currentBot);
const leaseResult =
body.controlLeaseId === undefined
? null
@@ -15131,28 +15128,30 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
return json(res, 400, { error: "controlLeaseId is invalid" });
}
const controlLeaseId = leaseResult?.data;
- if (action === "release") cloudComputerPower.renew(controlKey);
- if (action === "take" && (boatLifecycleBusyBots.has(bot.id) || boatLifecycleBusyBots.has(controlKey))) {
- return json(res, 409, { error: "this bot's cloud computer is being changed — wait before taking control" });
- }
- if (action === "take" && controlLeaseId) {
- const result = computerControl.acquireLease(controlKey, controlLeaseId);
- return json(res, 200, {
- ...result.snapshot,
- owned: result.owned,
- acquired: result.acquired,
- });
- }
+ // A viewer's lease outlives the conversation it was taken through, so only its release is still served.
+ if (gone && !(action === "release" && controlLeaseId)) return json(res, 404, { error: "no such task" });
+ if (action === "release") cloudComputerPower.renew(boatKey);
if (action === "release" && controlLeaseId) {
- const result = computerControl.releaseLease(controlKey, controlLeaseId);
- return json(res, 200, { ...result.snapshot, released: result.released });
+ const result = sharedVm.release(bot, threadId, controlLeaseId);
+ return json(res, 200, { ...shown(result.snapshot), released: result.released });
}
if (action === "check" && controlLeaseId) {
- return json(res, 200, { ...computerControl.snapshot(controlKey), owned: computerControl.ownsLease(controlKey, controlLeaseId) });
+ return json(res, 200, shown(sharedVm.check(bot, threadId, controlLeaseId)));
+ }
+ if (action !== "take" && action !== "release") return json(res, 400, { error: "action must be take, release, or check" });
+ if (body.target !== undefined && (typeof body.target !== "string" || !DESKTOP_VIEWER_TARGET.test(body.target))) return json(res, 400, { error: "target is not a desktop" });
+ const controlKey = sharedVm.holdKey(bot, threadId, body.target);
+ if (controlKey === null) return json(res, 409, { error: "This conversation does not show that desktop" });
+ if (action === "release") return json(res, 200, shown(computerControl.release(controlKey)));
+ if (boatLifecycleBusyBots.has(bot.id) || boatLifecycleBusyBots.has(boatKey)) {
+ return json(res, 409, { error: "this bot's cloud computer is being changed — wait before taking control" });
}
- if (action === "take") return json(res, 200, computerControl.take(controlKey));
- if (action === "release") return json(res, 200, computerControl.release(controlKey));
- return json(res, 400, { error: "action must be take, release, or check" });
+ const refusal = sharedVm.takeRefusal(controlKey);
+ if (refusal) return json(res, 409, { error: refusal });
+ const phoneVm = sharedVm.armed(auth, bot, threadId, controlKey, body.target);
+ if (!controlLeaseId) return phoneVm ? json(res, 400, { error: "A phone's take of a Local VM needs a controlLeaseId, so its hold can lapse when the phone goes away" }) : json(res, 200, shown(computerControl.take(controlKey)));
+ const result = computerControl.acquireLease(controlKey, controlLeaseId, { armed: phoneVm });
+ return json(res, 200, { ...shown(result.snapshot), owned: result.owned, acquired: result.acquired });
}
return json(res, 405, { error: "method not allowed" });
}
diff --git a/server/routes/computers.ts b/server/routes/computers.ts
index 6d9a172e16..9afec2a57c 100644
--- a/server/routes/computers.ts
+++ b/server/routes/computers.ts
@@ -41,7 +41,7 @@ export interface ComputerRouteDeps {
cfg: AppConfig;
sessions: Pick<SessionRegistry, "isLive">;
teamComputers: Pick<TeamComputers, "get" | "create" | "assign" | "setProblem" | "list">;
- computerControl: Pick<ComputerControl, "snapshot" | "take" | "release" | "acquireLease" | "releaseLease" | "ownsLease">;
+ computerControl: Pick<ComputerControl, "snapshot" | "take" | "release" | "acquireLease" | "releaseLease" | "beat">;
routines(): Pick<RoutineManager, "activeRunForBot"> | null;
controlLeaseIdSchema: ZodString;
boatLifecycleBusyBots: Pick<Set<string>, "has">;
@@ -66,8 +66,9 @@ export interface ComputerRouteDeps {
managedBoatOwners(): boat.ManagedBoatOwner[];
providerTransitionMessage(provider: RemoteComputerProvider): string;
botHasActiveTurn(botId: string): boolean;
- botComputerControlKey(bot: BotRecord): string;
- botComputerControlSnapshot(botId: string): { held: boolean };
+ /** The control key whose lease opens this conversation's Local VM to a phone. */
+ localVmLeaseKey(bot: BotRecord, threadId?: string): string;
+ botComputerControlSnapshot(botId: string): ReturnType<ComputerControl["snapshot"]>;
computerPreviewBot(botId: string, url: URL): BotRecord | null;
computerPreviewSurface(bot: BotRecord, threadId?: string): Promise<string | undefined>;
claimTeamComputerLifecycle(computer: TeamComputerRecord): () => void;
@@ -87,12 +88,13 @@ export function createComputerRoutes(deps: ComputerRouteDeps): RouteHandler {
localVmProvisionBusy, localVmModeChangeBusy, localVmOwnerBusy, localVmIdleMs, localVmLeaseFor, localVmIdleFor,
localVmTargetForBot, localVmTargetForStatus, localVmPayload, localVmInventoryPayload, existingPerBotLocalVmCount,
teamComputersPayload, teamComputerInUse, managedBoatOwners, providerTransitionMessage, botHasActiveTurn,
- botComputerControlKey, botComputerControlSnapshot, computerPreviewBot, computerPreviewSurface,
+ localVmLeaseKey, botComputerControlSnapshot, computerPreviewBot, computerPreviewSurface,
claimTeamComputerLifecycle, claimBotComputerLifecycle, claimBoatInventoryRequest, claimManagedBoatMutation,
claimManagedVpsMutation, cloudComputerUsed,
} = deps;
const usage = createComputerUsageRoutes(deps);
- const frames = createComputerFramesRoutes(deps);
+ // A map owner is a bot id or a team computer's key; a bot's hold may sit on the shared desktop's key.
+ const frames = createComputerFramesRoutes({ ...deps, computerControl: { snapshot: botComputerControlSnapshot } });
return async (context) => {
if (await usage(context) !== PASS) return;
if (await frames(context) !== PASS) return;
@@ -432,13 +434,12 @@ export function createComputerRoutes(deps: ComputerRouteDeps): RouteHandler {
if (threadId && await computerPreviewSurface(bot, threadId) !== "vm") {
return json(res, 409, { error: "This conversation is not using the Local VM" });
}
- if (localVmMode(cfg) !== "per-bot") {
- return json(res, 409, { error: "Phone control requires a per-bot Local VM. Select per-bot mode in Settings → Computers." });
+ if (localVmMode(cfg) === "pool") {
+ return json(res, 409, { error: "Phone control is not available in pool mode. Select shared or per-bot mode in Settings → Computers." });
}
const lease = controlLeaseIdSchema.safeParse(url.searchParams.get("controlLeaseId") ?? undefined);
if (!lease.success) return json(res, 400, { error: "controlLeaseId is required" });
- const controlBot = store.bot(bot.id);
- if (!controlBot || !computerControl.ownsLease(botComputerControlKey(controlBot), lease.data)) {
+ if (!store.bot(bot.id) || !computerControl.beat(localVmLeaseKey(bot, threadId), lease.data)) {
return json(res, 409, { error: "Take control of this computer first" });
}
const target = localVmTargetForStatus(bot.id, threadId);
diff --git a/server/routes/config.ts b/server/routes/config.ts
index fca387e224..63d79b8673 100644
--- a/server/routes/config.ts
+++ b/server/routes/config.ts
@@ -85,6 +85,8 @@ export interface ConfigRouteDeps {
localVmLifecycleBusy: { readonly size: number };
localVmImageBusy: Pick<BusyFlag, "get">;
localVmModeChangeBusy: Pick<BusyFlag, "set">;
+ /** Called before a Local VM mode change is saved; once it is saved, the returned call ends the holds no path reads any more. */
+ localVmModeChanging(): () => void;
providerConfigBusy: BusyFlag;
computerProviderConfigTransitions: Pick<Set<RemoteComputerProvider>, "add" | "delete">;
managedBoatOwners(): boat.ManagedBoatOwner[];
@@ -115,7 +117,7 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {
const {
store, cfg, registry, sessions, browserCleanup, browserLive, browserRuntime, usedBrowserSessions, decider,
closeBrowser, browserEngineSwitched, sharedComputers, sharedComputerControl, hostedModels, cloudHome: CLOUD_HOME, sharedMembership, lendingEnabled, providerConfigs,
- localVmIdleMs, localVmIdles, localVmActiveThreads, localVmLifecycleBusy, localVmImageBusy, localVmModeChangeBusy,
+ localVmIdleMs, localVmIdles, localVmActiveThreads, localVmLifecycleBusy, localVmImageBusy, localVmModeChangeBusy, localVmModeChanging,
providerConfigBusy, computerProviderConfigTransitions, managedBoatOwners, providerOperationConflict,
perBotLocalVmCountForModeChange, checkedModelSelection, policyModelRefusal, browserSessionSpec, configStatus,
configForAccess, resyncOpenCodeProviderKeys, revokeEngineCapabilities, reloadProviders, broadcast, drainQueuedSends, ownProfile, ownHints, postiz,
@@ -536,6 +538,7 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {
});
let configWriteCommitted = false;
const enginesBefore = engineLaunches(providerConfigs());
+ const localVmModeChanged = changingLocalVmMode ? localVmModeChanging() : null;
const externalSecretStorage = url.searchParams.get("secretStorage") === "external";
try {
if (patch.live) patch.live = liveSavePatch(cfg.live, patch.live);
@@ -594,6 +597,7 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {
throw error;
}
for (const key of resetKeys) if (key) forgetKey(key);
+ localVmModeChanged?.();
postiz?.configSaved(patch);
// A saved key reaches an engine through the environment its status read uses, often with no reload.
registry.forgetSnapshots();
diff --git a/server/routes/desktop-viewer.test.ts b/server/routes/desktop-viewer.test.ts
index 98c5626751..d43a12f80d 100644
--- a/server/routes/desktop-viewer.test.ts
+++ b/server/routes/desktop-viewer.test.ts
@@ -2,10 +2,11 @@ import { createHash } from "node:crypto";
import { once } from "node:events";
import { createServer, request, type IncomingHttpHeaders, type Server } from "node:http";
import { mkdtempSync, rmSync } from "node:fs";
+import { Socket } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { Duplex } from "node:stream";
-import { afterEach, beforeEach, expect, it } from "vitest";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { SessionRegistry } from "../sessions.ts";
import { resolveRequestAuth, type RequestAuth } from "../request-auth.ts";
import { json, readBody } from "../harness/http.ts";
@@ -337,8 +338,8 @@ const phoneTarget = viewerTargetId(perBotLocalVmTarget("test-bot"));
const phoneBase = `/api/desktop-viewer/${phoneTarget}`;
const bound = (query = `botId=test-bot&controlLeaseId=${lease}`) => `${phoneBase}/websockify?${query}`;
-it.each([SHARED_LOCAL_VM_TARGET, poolLocalVmTarget(1)])("refuses phone control of a shared desktop even with a valid bot lease: %j", async desktop => {
- const target = viewerTargetId(desktop);
+it("refuses phone control of a pool seat even with a valid bot lease", async () => {
+ const target = viewerTargetId(poolLocalVmTarget(1));
leases.add(leaseKey(target, "test-bot", lease));
const query = `botId=test-bot&threadId=th-1&controlLeaseId=${lease}`;
for (const response of [
@@ -346,11 +347,32 @@ it.each([SHARED_LOCAL_VM_TARGET, poolLocalVmTarget(1)])("refuses phone control o
await get(`/api/desktop-viewer/${target}?${query}`),
]) {
expect(response.status).toBe(409);
- expect(JSON.stringify(response.body)).toContain("per-bot Local VM");
+ expect(JSON.stringify(response.body)).toContain("pool mode");
}
expect(inspected).toEqual([]);
});
+it("opens the shared desktop to a phone lease that holds it", async () => {
+ const target = viewerTargetId(SHARED_LOCAL_VM_TARGET);
+ leases.add(leaseKey(target, "test-bot", lease));
+ const query = `botId=test-bot&threadId=th-1&controlLeaseId=${lease}`;
+ expect((await get(`/api/desktop-viewer/${target}?${query}`)).body).toEqual({ password: "fixture-secret" });
+ const answer = await open(`/api/desktop-viewer/${target}/websockify?${query}`);
+ expect(answer.status).toBe(101);
+ expect(inspected).toEqual(["shared", "shared"]);
+});
+
+it("keeps a TCP keepalive on a viewer's socket, so a phone that vanishes is found", async () => {
+ const keepAlive = vi.spyOn(Socket.prototype, "setKeepAlive");
+ try {
+ leases.add(leaseKey(phoneTarget, "test-bot", lease));
+ expect((await open(bound())).status).toBe(101);
+ expect(keepAlive).toHaveBeenCalledWith(true, 15_000);
+ } finally {
+ keepAlive.mockRestore();
+ }
+});
+
it("opens a lease-bound viewer only while that lease holds the bot's computer", async () => {
const refused = await open(bound());
expect(refused.status).toBe(409);
diff --git a/server/routes/desktop-viewer.ts b/server/routes/desktop-viewer.ts
index c4751dd245..0f444cd154 100644
--- a/server/routes/desktop-viewer.ts
+++ b/server/routes/desktop-viewer.ts
@@ -38,8 +38,8 @@ interface Viewer { socket: Socket; close: () => void; owner?: string; botId?: st
export function createDesktopViewer(deps: {
target: (id: string) => DesktopTarget | undefined;
live: (auth: RequestAuth) => boolean;
- /** Binds a viewer to a control lease: answers only while `controlLeaseId` holds `botId`'s computer and the target is
- * that computer. Shared and pool targets are refused: a bot hold cannot reserve their desktop. */
+ /** Binds a viewer to a control lease: answers only while `controlLeaseId` holds the control key that pauses every bot
+ * on the target, and the target is that computer. Pool targets are refused: no hold reserves one seat. */
lease?: (id: string, botId: string, controlLeaseId: string, threadId?: string) => (() => boolean) | undefined;
/** The server's shared upgrade gate; a viewer made without one keeps its own. */
upgrades?: Upgrades;
@@ -70,8 +70,8 @@ export function createDesktopViewer(deps: {
}
if (botId === null && threadId !== undefined) return json(res, 400, { error: "threadId needs botId and controlLeaseId" });
// A saved or constructed socket URL must not bypass the join refusal: a bot's lease does not exclude other users of a shared desktop.
- if (botId !== null && (match[1] === "local/shared" || match[1].startsWith("local/pool-"))) {
- return json(res, 409, { error: "Phone control requires a per-bot Local VM. Select per-bot mode in Settings → Computers." });
+ if (botId !== null && match[1].startsWith("local/pool-")) {
+ return json(res, 409, { error: "Phone control is not available in pool mode. Select shared or per-bot mode in Settings → Computers." });
}
const bound = botId === null ? undefined : deps.lease!(match[1], botId, controlLeaseId!, threadId);
if (botId !== null && !bound) return json(res, 409, { error: "Take control of this computer first" });
@@ -159,6 +159,8 @@ export function createDesktopViewer(deps: {
if (pending.head.length) remote.write(pending.head);
pending.head = Buffer.alloc(0);
socket.pipe(remote).pipe(socket);
+ // A phone that vanishes without closing is found by TCP keepalive; the lease's beats then stop.
+ socket.setKeepAlive(true, 15_000);
connection.touch?.();
recheck = setInterval(() => {
if (!live() || !holds()) upgrade.close();
diff --git a/server/team-setup-requests.test.ts b/server/team-setup-requests.test.ts
index d3e218a59b..7a76c31f07 100644
--- a/server/team-setup-requests.test.ts
+++ b/server/team-setup-requests.test.ts
@@ -38,8 +38,11 @@ function harness(caps?: Record<string, { driverKind: string; agentsMcp: boolean
patchBot: (id: string, patch: Partial<BotRecord>) => Object.assign(bots.find((item) => item.id === id)!, patch),
};
let sourceExists = true;
+ const deletionRefusal = vi.fn((_id: string): string | null => null);
const deleteBot = vi.fn(async (id: string, revalidate: () => void, request?: TeamSetupRequest) => {
revalidate();
+ const refusal = deletionRefusal(id);
+ if (refusal) throw new TeamSetupError(refusal, 409);
const target = bots.find((item) => item.id === id)!;
if (request) chief.lastTeamSetupReceipt = { requestId: request.requestId, result: { state: "applied", bots: [{ id, name: target.name, action: "deleted" }], newTeams: [] } };
bots.splice(bots.indexOf(target), 1);
@@ -50,7 +53,7 @@ function harness(caps?: Record<string, { driverKind: string; agentsMcp: boolean
const validateChange = vi.fn();
const canPersist = vi.fn((): { ok: true } | { ok: false; status: number; error: string } => ({ ok: true }));
const service = new TeamSetupRequestService({ store, teams: () => teams, maxBots: 100, hasTeamAuthority,
- canPersist, ownsThread: () => sourceExists, targetBusy, deleteBot, autoApply, validateChange,
+ canPersist, ownsThread: () => sourceExists, targetBusy, deleteBot, deletionRefusal, autoApply, validateChange,
validateModel: (selection, current) => {
if (!({ claude: ["sonnet", "opus"], codex: ["gpt-fixture"] }[selection.instanceId]?.includes(selection.model))) return "Model is not in the current catalog";
return current?.approvalMode === "full" && selection.instanceId !== current.modelSelection.instanceId ? "Existing permissions are incompatible" : null;
@@ -60,7 +63,7 @@ function harness(caps?: Record<string, { driverKind: string; agentsMcp: boolean
const propose = (operations: unknown[], newTeams: string[] = []) => service.propose({ botId: chief.id, threadId: chief.threadId, plan: { reason: "Requested specialist setup", operations, newTeams } });
const submit = (operations: unknown[], newTeams: string[] = []) => service.submit({ botId: chief.id, threadId: chief.threadId, plan: { reason: "Requested specialist setup", operations, newTeams } });
const resolve = (requestId: string, behavior = "allow") => service.resolve({ botId: chief.id, threadId: chief.threadId, requestId, behavior });
- return { service, store, chief, peer, bot, teams, propose, submit, resolve, apply, deleteBot, messages, autoApply, targetBusy, validateChange, canPersist, removeSource: () => { sourceExists = false; } };
+ return { service, store, chief, peer, bot, teams, propose, submit, resolve, apply, deleteBot, deletionRefusal, messages, autoApply, targetBusy, validateChange, canPersist, removeSource: () => { sourceExists = false; } };
}
const specialist = (key: string, section: string, modelSelection = { instanceId: "claude", model: "sonnet" }) => ({ action: "create", key,
fields: { name: key, title: "Specialist", soul: "Finish the assigned work.", section, modelSelection } });
@@ -571,6 +574,19 @@ describe("team setup below Full access", () => {
expect(h.deleteBot).not.toHaveBeenCalled();
});
+ it("refuses Undo up front, deleting none of the bots it created, while one of them may not be deleted, and undoes it all once it may", async () => {
+ const h = harness(); h.autoApply.mockReturnValue("level");
+ const response = await h.submit([specialist("Mira", "Work"), specialist("Noor", "Work")]);
+ const noor = h.store.bots.find((bot) => bot.name === "Noor")!;
+ h.deletionRefusal.mockImplementation((id) => id === noor.id ? "Hand back control of this bot's computer before deleting it" : null);
+ expect(await undo(h, response.requestId)).toMatchObject({ state: "invalid", error: "Hand back control of this bot's computer before deleting it" });
+ expect(h.deleteBot).not.toHaveBeenCalled();
+ expect(h.store.bots.filter((bot) => ["Mira", "Noor"].includes(bot.name))).toHaveLength(2);
+ h.deletionRefusal.mockImplementation(() => null);
+ expect(await undo(h, response.requestId)).toEqual({ claimed: true, state: "undone" });
+ expect(h.store.bots.some((bot) => ["Mira", "Noor"].includes(bot.name))).toBe(false);
+ });
+
it("deletes a teammate at Ask with no card and no Undo", async () => {
const h = harness(); h.autoApply.mockReturnValue("level");
const response = await h.service.submitDeletion({ botId: h.chief.id, threadId: h.chief.threadId, targetBotId: h.peer.id, reason: "User requested deletion" });
diff --git a/server/team-setup-requests.ts b/server/team-setup-requests.ts
index 2562ed7763..b2f4455d7e 100644
--- a/server/team-setup-requests.ts
+++ b/server/team-setup-requests.ts
@@ -88,6 +88,8 @@ interface Options {
ownsThread(botId: string, threadId: string): boolean;
/** `request` only for a reviewed deletion; Undo of a creation deletes without one. */
deleteBot(botId: string, revalidate: () => void, request?: TeamSetupRequest): Promise<void>;
+ /** Why deleting this bot would be refused now, as a person's hold reaches it; null when it would not. */
+ deletionRefusal(botId: string): string | null;
}
type RequestFrom = { botId: string; name: string; color: string };
@@ -409,6 +411,8 @@ export class TeamSetupRequestService {
const ids = Object.keys(revisions);
if (changed(ids)) return { ...cannot(UNDO_STALE), stale: true };
if (ids.some((id) => this.options.targetBusy(id))) return cannot("Wait for the bots this setup changed to finish their work, then undo.");
+ const refusal = created.map((id) => this.options.deletionRefusal(id)).find((reason) => reason !== null);
+ if (refusal) return cannot(refusal);
try {
for (const id of created) await this.options.deleteBot(id, () => { if (changed([id])) throw new TeamSetupError(UNDO_STALE, 409); });
const restore = before.filter((entry) => Object.keys(entry.fields).length);