Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(spaces-web): persistent agent Memory, Routines and Access in the React UI (CUA-1408) (#5033)

Francesco Bonacci541abc55c64b
diff --git a/apps/cua-spaces-desktop/src/bridge/agents.ts b/apps/cua-spaces-desktop/src/bridge/agents.ts
index 18d1ebabdb..40d0b099b7 100644
--- a/apps/cua-spaces-desktop/src/bridge/agents.ts
+++ b/apps/cua-spaces-desktop/src/bridge/agents.ts
@@ -5,8 +5,9 @@
// agents, a Space's runs and their events, and the coding agents on this
// machine (the SwiftUI host's `agents`, `PersistentModel`, `AgentRunsModel`).
import type { AppModel } from "../model/app-model";
+import type { AppAgentsRequest } from "../native/generated/index";
import type { BridgeContext } from "./context";
-import { count, string, strings } from "./args";
+import { bool, count, optionalString, string, strings } from "./args";
import { Failure, type Handlers } from "./host";
import { encode } from "./value";
@@ -30,6 +31,16 @@ export function agentsMethods({ model }: BridgeContext): Handlers {
if (persistent.state.error !== undefined) throw Failure.failed(persistent.state.error);
return null;
};
+ const needTools = () => {
+ const persistent = model.agents.persistent;
+ if (!persistent.canCallTools) throw Failure.unsupported("Agents need the cua daemon");
+ return persistent;
+ };
+ type Requests = AppModel["native"]["AppAgentsRequest"];
+ const change = (request: (args: Record<string, unknown>, R: Requests) => AppAgentsRequest) => async (args: Record<string, unknown>) => {
+ await needTools().perform(request(args, model.native.AppAgentsRequest));
+ return null;
+ };
return {
"agents.list": async () => {
const persistent = model.agents.persistent;
@@ -70,6 +81,29 @@ export function agentsMethods({ model }: BridgeContext): Handlers {
else await coding.act(strings(args, "agents"), false);
return encode(coding.rows ?? []);
},
+ // A persistent agent's Memory, Routines and Access: what the native
+ // Agents page reads and the changes it runs, one method each.
+ "agents.detail": async (args) => {
+ const persistent = needTools();
+ return { ...(await persistent.detail(string(args, "name"))), thisMachine: persistent.thisMachine() };
+ },
+ "agents.readFile": async (args) => needTools().readFile(string(args, "path")),
+ "agents.restoreFile": change((a, R) => new R.Restore({ path: string(a, "path"), version: string(a, "version") })),
+ "agents.addRoutine": change(
+ (a, R) =>
+ new R.AddRoutine({
+ agent: string(a, "agent"),
+ title: string(a, "title"),
+ prompt: string(a, "prompt"),
+ everyMinutes: count(a, "everyMinutes") ?? undefined,
+ dailyAt: optionalString(a, "dailyAt") ?? undefined,
+ weeklyOn: optionalString(a, "weeklyOn") ?? undefined,
+ }),
+ ),
+ "agents.setRoutine": change((a, R) => new R.SetRoutine({ id: string(a, "id"), enabled: bool(a, "enabled") })),
+ "agents.removeRoutine": change((a, R) => new R.RemoveRoutine({ id: string(a, "id") })),
+ "agents.allowComputer": change((a, R) => new R.Allow({ agent: string(a, "agent"), machine: string(a, "machine") })),
+ "agents.revokeComputer": change((a, R) => new R.Revoke({ agent: string(a, "agent"), machine: string(a, "machine") })),
"agents.setupDriver": async (args) => {
needSetup();
return encode(await model.agents.coding.setup!.setUpCuaDriver(strings(args, "agents")));
diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.ts
index 4c216ef485..11df20cc94 100644
--- a/apps/cua-spaces-desktop/src/bridge/methods.ts
+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts
@@ -16,6 +16,8 @@ export const METHODS = [
"machines.list", "host.status",
"agents.list", "agents.runs", "agents.events", "agents.pause", "agents.resume",
"agents.setup", "agents.configure",
+ "agents.detail", "agents.readFile", "agents.restoreFile", "agents.addRoutine", "agents.setRoutine",
+ "agents.removeRoutine", "agents.allowComputer", "agents.revokeComputer",
"agentKeys.list", "agentKeys.set", "agentKeys.remove",
"spaces.add", "clouds.status", "clouds.test", "clouds.connect",
"teleport.catalog", "teleport.entryForPath", "teleport.windows", "teleport.remoteWindows",
diff --git a/apps/cua-spaces-desktop/src/model/agents.ts b/apps/cua-spaces-desktop/src/model/agents.ts
index 45baf95ca7..3a9aff02ac 100644
--- a/apps/cua-spaces-desktop/src/model/agents.ts
+++ b/apps/cua-spaces-desktop/src/model/agents.ts
@@ -20,6 +20,7 @@ import type {
AppAgentSetupOutcomeInput,
AppAgentSetupStatus,
AppAgentsAction,
+ AppAgentsRequest,
AppAgentsState,
AppAgentsView,
AppSpaceAgentRun,
@@ -122,7 +123,10 @@ export class PersistentAgents {
return this.call("agent_events", args);
}
- private async loadDetail(name: string): Promise<void> {
+ /** The selected agent's home (files only, recursively), its routines, every
+ * computer grant and the recent audit: the core's input records. The web
+ * UI's `agents.detail` answers it. */
+ async detail(name: string): Promise<{ home: Json[]; routines: Json[]; grants: Json[]; audit: Json[] }> {
const files: Json[] = [];
const queue = [`agents/${name}/`];
let folders = 0;
@@ -141,10 +145,67 @@ export class PersistentAgents {
enabled: typeof r.isEnabled === "boolean" ? r.isEnabled : true,
}));
const access = await this.call("computer_access_list", { audit: 20 });
- this.input.home = files;
- this.input.routines = routines;
- this.input.grants = arr(access, "grants").map((g) => ({ agent: g.agent ?? "", machine: g.machine ?? "", revoked: g.revoked ?? false }));
- this.input.audit = arr(access, "audit").map((a) => ({ tsMs: a.ts_ms ?? 0, action: a.action ?? "", principal: a.principal ?? "", path: a.path ?? "", detail: a.detail ?? "" }));
+ return {
+ home: files,
+ routines,
+ grants: arr(access, "grants").map((g) => ({ agent: g.agent ?? "", machine: g.machine ?? "", revoked: g.revoked ?? false })),
+ audit: arr(access, "audit").map((a) => ({ tsMs: a.ts_ms ?? 0, action: a.action ?? "", principal: a.principal ?? "", path: a.path ?? "", detail: a.detail ?? "" })),
+ };
+ }
+
+ private async loadDetail(name: string): Promise<void> {
+ Object.assign(this.input, await this.detail(name));
+ }
+
+ /** A home file's text and versions (`OpenFileInput`). */
+ async readFile(path: string): Promise<Json> {
+ const [file, history] = await Promise.all([this.call("volume_read", { path }), this.call("volume_history", { path })]);
+ const binary = file.encoding === "base64";
+ return {
+ path,
+ text: binary ? "" : (file.content ?? ""),
+ binary,
+ versions: arr(history, "versions").map((v) => ({ version: v.version ?? "", modifiedMs: v.modified_ms ?? 0, deleted: v.deleted ?? false, latest: v.latest ?? false })),
+ };
+ }
+
+ /** Runs one of the core's changes (`AgentsRequest`) with the daemon's tools. */
+ async perform(request: AppAgentsRequest): Promise<void> {
+ switch (request.tag) {
+ case "Load":
+ case "ReadFile":
+ return;
+ case "Pause":
+ await this.call("agent_pause", { name: request.inner.name });
+ return;
+ case "Resume":
+ await this.call("agent_resume", { name: request.inner.name });
+ return;
+ case "Restore":
+ await this.call("volume_restore", { path: request.inner.path, version: request.inner.version });
+ return;
+ case "AddRoutine": {
+ const r = request.inner;
+ const args: Record<string, unknown> = { agent: r.agent, title: r.title, prompt: r.prompt };
+ if (r.everyMinutes !== undefined) args.every_minutes = r.everyMinutes;
+ if (r.dailyAt !== undefined) args.daily_at = r.dailyAt;
+ if (r.weeklyOn !== undefined) args.weekly_on = r.weeklyOn;
+ await this.call("routine_add", args);
+ return;
+ }
+ case "SetRoutine":
+ await this.call("routine_set_enabled", { id: request.inner.id, enabled: request.inner.enabled });
+ return;
+ case "RemoveRoutine":
+ await this.call("routine_remove", { id: request.inner.id });
+ return;
+ case "Allow":
+ await this.call("computer_access_grant", { agent: request.inner.agent, machine: request.inner.machine });
+ return;
+ case "Revoke":
+ await this.call("computer_access_revoke", { agent: request.inner.agent, machine: request.inner.machine });
+ return;
+ }
}
/** Reduces `action` through the core and runs the request it asks for (the page's Pause and Resume, the Agents page's actions). */
@@ -159,50 +220,16 @@ export class PersistentAgents {
case "Load":
await this.loadDetail(request.inner.name);
break;
- case "ReadFile": {
- const path = request.inner.path;
- const [file, history] = await Promise.all([this.call("volume_read", { path }), this.call("volume_history", { path })]);
- const binary = file.encoding === "base64";
- this.input.file = {
- path,
- text: binary ? "" : (file.content ?? ""),
- binary,
- versions: arr(history, "versions").map((v) => ({ version: v.version ?? "", modifiedMs: v.modified_ms ?? 0, deleted: v.deleted ?? false, latest: v.latest ?? false })),
- };
+ case "ReadFile":
+ this.input.file = await this.readFile(request.inner.path);
break;
- }
case "Pause":
- await this.call("agent_pause", { name: request.inner.name });
- await this.load();
- break;
case "Resume":
- await this.call("agent_resume", { name: request.inner.name });
+ await this.perform(request);
await this.load();
break;
- case "Restore":
- await this.call("volume_restore", { path: request.inner.path, version: request.inner.version });
- break;
- case "AddRoutine": {
- const r = request.inner;
- const args: Record<string, unknown> = { agent: r.agent, title: r.title, prompt: r.prompt };
- if (r.everyMinutes !== undefined) args.every_minutes = r.everyMinutes;
- if (r.dailyAt !== undefined) args.daily_at = r.dailyAt;
- if (r.weeklyOn !== undefined) args.weekly_on = r.weeklyOn;
- await this.call("routine_add", args);
- break;
- }
- case "SetRoutine":
- await this.call("routine_set_enabled", { id: request.inner.id, enabled: request.inner.enabled });
- break;
- case "RemoveRoutine":
- await this.call("routine_remove", { id: request.inner.id });
- break;
- case "Allow":
- await this.call("computer_access_grant", { agent: request.inner.agent, machine: request.inner.machine });
- break;
- case "Revoke":
- await this.call("computer_access_revoke", { agent: request.inner.agent, machine: request.inner.machine });
- break;
+ default:
+ await this.perform(request);
}
// What changed something is read again for the open agent.
if (!["Load", "ReadFile", "Pause", "Resume"].includes(request.tag) && this.state.selected !== undefined) {
diff --git a/apps/cua-spaces-desktop/test/agents-fixtures.ts b/apps/cua-spaces-desktop/test/agents-fixtures.ts
index ea6204fa61..639af66308 100644
--- a/apps/cua-spaces-desktop/test/agents-fixtures.ts
+++ b/apps/cua-spaces-desktop/test/agents-fixtures.ts
@@ -52,6 +52,23 @@ export class FakeAgentsTools {
case "computer_access_grant":
this.grants = [{ agent: "ada", machine: args.machine ?? "", revoked: false }];
return this.grants[0];
+ case "computer_access_revoke":
+ this.grants = [];
+ return {};
+ case "volume_read":
+ return { path: args.path, content: "# Ada\n", encoding: "utf8" };
+ case "volume_history":
+ return {
+ versions: [
+ { version: "v2", modified_ms: this.now - 60_000, deleted: false, latest: true },
+ { version: "v1", modified_ms: this.now - 3_600_000, deleted: false, latest: false },
+ ],
+ };
+ case "volume_restore":
+ case "routine_add":
+ case "routine_set_enabled":
+ case "routine_remove":
+ return {};
case "agent_events":
return { run_id: args.run_id, status: "idle", phase: "idle", events: [], cursor: args.cursor, caught_up: true };
default:
diff --git a/apps/cua-spaces-desktop/test/agents.test.ts b/apps/cua-spaces-desktop/test/agents.test.ts
index f9e6668431..ec4d073161 100644
--- a/apps/cua-spaces-desktop/test/agents.test.ts
+++ b/apps/cua-spaces-desktop/test/agents.test.ts
@@ -168,6 +168,35 @@ describe.skipIf(!built)("agents", () => {
expect(p.view(now).rows[0]!.state).toBe("Running");
});
+ it("answers an agent's detail and file for the page, and runs its changes with the native tools", async () => {
+ const { bridge } = makeBridge();
+ const detail = (await call(bridge, "agents.detail", { name: "ada" })) as { home: { path: string }[]; routines: { title: string }[]; thisMachine: unknown };
+ expect(shapeProblems("agents.detail", detail)).toEqual([]);
+ expect(detail.home.map((f) => f.path)).toEqual(["agents/ada/hermes/MEMORY.md"]);
+ expect(detail.routines.map((r) => r.title)).toEqual(["Morning"]);
+ const file = await call(bridge, "agents.readFile", { path: "agents/ada/hermes/MEMORY.md" });
+ expect(shapeProblems("agents.readFile", file)).toEqual([]);
+ expect((file as { text: string }).text).toBe("# Ada\n");
+
+ await call(bridge, "agents.addRoutine", { agent: "ada", title: "Inbox", prompt: "Sort my inbox", everyMinutes: null, dailyAt: null, weeklyOn: "mon 09:00" });
+ expect(daemon.calls.at(-1)).toBe("routine_add");
+ expect(daemon.args.at(-1)).toEqual({ agent: "ada", title: "Inbox", prompt: "Sort my inbox", weekly_on: "mon 09:00" });
+ await call(bridge, "agents.setRoutine", { id: "R1", enabled: false });
+ expect(daemon.args.at(-1)).toEqual({ id: "R1", enabled: false });
+ await call(bridge, "agents.allowComputer", { agent: "ada", machine: "relay:0123" });
+ expect(daemon.calls.at(-1)).toBe("computer_access_grant");
+ for (const [method, args] of [
+ ["agents.restoreFile", { path: "agents/ada/hermes/MEMORY.md", version: "v1" }],
+ ["agents.removeRoutine", { id: "R1" }],
+ ["agents.revokeComputer", { agent: "ada", machine: "relay:0123" }],
+ ] as const) {
+ expect(await call(bridge, method, args)).toBeNull();
+ }
+ expect(daemon.calls.slice(-3)).toEqual(["volume_restore", "routine_remove", "computer_access_revoke"]);
+ expect(await code(bridge, "agents.setRoutine", { id: "R1" })).toBe("bad_args");
+ expect(await code(makeBridge({ tools: null }).bridge, "agents.detail", { name: "ada" })).toBe("unsupported");
+ });
+
it("pauses and resumes by name, one change at a time", async () => {
const { bridge, model } = makeBridge();
expect(await call(bridge, "agents.pause", { name: "ada" })).toBeNull();
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift
index 6b65d4a209..365034fc9e 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift
@@ -146,7 +146,10 @@ public final class PersistentModel {
return try await call("agent_events", args)
}
- private func loadDetail(_ name: String) async throws {
+ /// The selected agent's home (`agents/<name>/`, recursively, files only),
+ /// its routines, every computer grant and the recent audit: the core's
+ /// input records (`AgentsInput`). The web UI's `agents.detail` answers it.
+ func detail(_ name: String) async throws -> [String: Any] {
var files: [[String: Any]] = []
var queue = ["agents/\(name)/"]
var folders = 0
@@ -163,10 +166,47 @@ public final class PersistentModel {
"enabled": (r["isEnabled"] as? Bool) ?? true] as [String: Any]
}
let access = try await call("computer_access_list", ["audit": 20])
- agentsInput["home"] = files
- agentsInput["routines"] = routines
- agentsInput["grants"] = access.arr("grants").map { ["agent": $0["agent"] ?? "", "machine": $0["machine"] ?? "", "revoked": $0["revoked"] ?? false] }
- agentsInput["audit"] = access.arr("audit").map { ["tsMs": $0["ts_ms"] ?? 0, "action": $0["action"] ?? "", "principal": $0["principal"] ?? "", "path": $0["path"] ?? "", "detail": $0["detail"] ?? ""] }
+ return [
+ "home": files,
+ "routines": routines,
+ "grants": access.arr("grants").map { ["agent": $0["agent"] ?? "", "machine": $0["machine"] ?? "", "revoked": $0["revoked"] ?? false] },
+ "audit": access.arr("audit").map { ["tsMs": $0["ts_ms"] ?? 0, "action": $0["action"] ?? "", "principal": $0["principal"] ?? "", "path": $0["path"] ?? "", "detail": $0["detail"] ?? ""] },
+ ]
+ }
+
+ private func loadDetail(_ name: String) async throws {
+ for (k, v) in try await detail(name) { agentsInput[k] = v }
+ }
+
+ /// A home file's text and versions (`OpenFileInput`).
+ func readFile(_ path: String) async throws -> [String: Any] {
+ async let f = call("volume_read", ["path": path])
+ async let h = call("volume_history", ["path": path])
+ let (file, history) = try await (f, h)
+ let binary = file["encoding"] as? String == "base64"
+ return ["path": path, "text": binary ? "" : (file["content"] ?? ""), "binary": binary,
+ "versions": history.arr("versions").map { ["version": $0["version"] ?? "", "modifiedMs": $0["modified_ms"] ?? 0, "deleted": $0["deleted"] ?? false, "latest": $0["latest"] ?? false] }]
+ }
+
+ /// Runs one of the core's changes (`AgentsRequest`) with the daemon's tools.
+ func perform(_ request: AppAgentsRequest) async throws {
+ switch request {
+ case .load, .readFile: break
+ case let .pause(name): _ = try await call("agent_pause", ["name": name])
+ case let .resume(name): _ = try await call("agent_resume", ["name": name])
+ case let .restore(path, version):
+ _ = try await call("volume_restore", ["path": path, "version": version])
+ case let .addRoutine(agent, title, prompt, everyMinutes, dailyAt, weeklyOn):
+ var args: [String: Any] = ["agent": agent, "title": title, "prompt": prompt]
+ if let m = everyMinutes { args["every_minutes"] = m }
+ if let d = dailyAt { args["daily_at"] = d }
+ if let w = weeklyOn { args["weekly_on"] = w }
+ _ = try await call("routine_add", args)
+ case let .setRoutine(id, enabled): _ = try await call("routine_set_enabled", ["id": id, "enabled": enabled])
+ case let .removeRoutine(id): _ = try await call("routine_remove", ["id": id])
+ case let .allow(agent, machine): _ = try await call("computer_access_grant", ["agent": agent, "machine": machine])
+ case let .revoke(agent, machine): _ = try await call("computer_access_revoke", ["agent": agent, "machine": machine])
+ }
}
public func send(_ action: AppAgentsAction) async {
@@ -176,33 +216,12 @@ public final class PersistentModel {
do {
switch request {
case let .load(name): try await loadDetail(name)
- case let .readFile(path):
- async let f = call("volume_read", ["path": path])
- async let h = call("volume_history", ["path": path])
- let (file, history) = try await (f, h)
- let binary = file["encoding"] as? String == "base64"
- agentsInput["file"] = ["path": path, "text": binary ? "" : (file["content"] ?? ""), "binary": binary,
- "versions": history.arr("versions").map { ["version": $0["version"] ?? "", "modifiedMs": $0["modified_ms"] ?? 0, "deleted": $0["deleted"] ?? false, "latest": $0["latest"] ?? false] }] as [String: Any]
- case let .pause(name):
- _ = try await call("agent_pause", ["name": name]); await loadAgents()
- case let .resume(name):
- _ = try await call("agent_resume", ["name": name]); await loadAgents()
- case let .restore(path, version):
- _ = try await call("volume_restore", ["path": path, "version": version])
- case let .addRoutine(agent, title, prompt, everyMinutes, dailyAt, weeklyOn):
- var args: [String: Any] = ["agent": agent, "title": title, "prompt": prompt]
- if let m = everyMinutes { args["every_minutes"] = m }
- if let d = dailyAt { args["daily_at"] = d }
- if let w = weeklyOn { args["weekly_on"] = w }
- _ = try await call("routine_add", args)
- case let .setRoutine(id, enabled): _ = try await call("routine_set_enabled", ["id": id, "enabled": enabled])
- case let .removeRoutine(id): _ = try await call("routine_remove", ["id": id])
- case let .allow(agent, machine): _ = try await call("computer_access_grant", ["agent": agent, "machine": machine])
- case let .revoke(agent, machine): _ = try await call("computer_access_revoke", ["agent": agent, "machine": machine])
- }
- switch request {
- case .load, .readFile, .pause, .resume: break
- default: if let n = agentsState.selected { try? await loadDetail(n) }
+ case let .readFile(path): agentsInput["file"] = try await readFile(path)
+ case .pause, .resume:
+ try await perform(request); await loadAgents()
+ default:
+ try await perform(request)
+ if let n = agentsState.selected { try? await loadDetail(n) }
}
agentsState = appAgentsReduce(input: typedAgents(), state: agentsState, action: .done)
} catch {
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
index 452447bc80..b01a047ac4 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
@@ -68,6 +68,9 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
"machines.list", "host.status",
"agents.list", "agents.runs", "agents.events", "agents.pause", "agents.resume",
"agents.setup", "agents.configure",
+ // A persistent agent's Memory, Routines and Access (`PersistentModel`).
+ "agents.detail", "agents.readFile", "agents.restoreFile", "agents.addRoutine", "agents.setRoutine",
+ "agents.removeRoutine", "agents.allowComputer", "agents.revokeComputer",
"agentKeys.list", "agentKeys.set", "agentKeys.remove",
// New Space's address form and Connect a cloud, Teleport and Share,
// Cua Volume, Settings and Notifications, a Space's detail and This
@@ -259,6 +262,9 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
case "agents.list", "agents.runs", "agents.events", "agents.pause", "agents.resume",
"agents.setup", "agents.configure":
return try await agents(method, args)
+ case "agents.detail", "agents.readFile", "agents.restoreFile", "agents.addRoutine", "agents.setRoutine",
+ "agents.removeRoutine", "agents.allowComputer", "agents.revokeComputer":
+ return try await agentDetail(method, args)
case "settings.get": return settings()
case "settings.choose":
@@ -608,6 +614,52 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
}
}
+ /// One persistent agent's Memory, Routines and Access: what the native
+ /// Agents page reads (`PersistentModel.detail`, `readFile`) and the
+ /// changes it runs (`perform`), one method each. The page reduces and
+ /// draws with the app core itself.
+ func agentDetail(_ method: String, _ args: [String: Any]) async throws -> Any {
+ let persistent = model.persistent
+ guard persistent.canCallTools else { throw Failure.unsupported("Agents need the cua daemon") }
+ switch method {
+ case "agents.detail":
+ var detail = try await persistent.detail(try string(args, "name"))
+ // As the native Agents page sets it when it opens.
+ let id = model.sidebar.thisMachine?.id
+ detail["thisMachine"] = id?.hasPrefix("relay:") == true ? id : NSNull()
+ return detail
+ case "agents.readFile":
+ return try await persistent.readFile(try string(args, "path"))
+ default:
+ try await persistent.perform(try agentsRequest(method, args))
+ return NSNull()
+ }
+ }
+
+ /// The core's request for one of the change methods.
+ func agentsRequest(_ method: String, _ args: [String: Any]) throws -> AppAgentsRequest {
+ let text = { (key: String) in (args[key] as? String).flatMap { $0.isEmpty ? nil : $0 } }
+ switch method {
+ case "agents.restoreFile":
+ return .restore(path: try string(args, "path"), version: try string(args, "version"))
+ case "agents.addRoutine":
+ return .addRoutine(agent: try string(args, "agent"), title: try string(args, "title"), prompt: try string(args, "prompt"),
+ everyMinutes: (args["everyMinutes"] as? NSNumber)?.uint32Value,
+ dailyAt: text("dailyAt"), weeklyOn: text("weeklyOn"))
+ case "agents.setRoutine":
+ guard let enabled = args["enabled"] as? Bool else { throw Failure.badArgs("enabled: boolean") }
+ return .setRoutine(id: try string(args, "id"), enabled: enabled)
+ case "agents.removeRoutine":
+ return .removeRoutine(id: try string(args, "id"))
+ case "agents.allowComputer":
+ return .allow(agent: try string(args, "agent"), machine: try string(args, "machine"))
+ case "agents.revokeComputer":
+ return .revoke(agent: try string(args, "agent"), machine: try string(args, "machine"))
+ default:
+ throw Failure.unimplemented(method)
+ }
+ }
+
func keyvault() -> [String: Any] {
let kv = model.keyvault
return [
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentsPagesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentsPagesTests.swift
index 9ec9dd45d1..2d108b609a 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentsPagesTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentsPagesTests.swift
@@ -43,6 +43,12 @@ final class FakeAgentsTools: AgentsToolRunning, @unchecked Sendable {
case "computer_access_list": return ["grants": grants, "audit": []]
case "computer_access_grant":
grants = [["agent": "ada", "machine": args["machine"] ?? "", "revoked": false]]; return grants[0]
+ case "computer_access_revoke": grants = []; return [:]
+ case "volume_read": return ["path": args["path"] ?? "", "content": "# Ada\n", "encoding": "utf8"]
+ case "volume_history":
+ return ["versions": [["version": "v2", "modified_ms": now - 60_000, "deleted": false, "latest": true],
+ ["version": "v1", "modified_ms": now - 3_600_000, "deleted": false, "latest": false]]]
+ case "volume_restore", "routine_add", "routine_set_enabled", "routine_remove": return [:]
case "volume_requests":
return ["requests": [["id": "q1", "principal": "agent:ada", "prefix": "agents/writer/outputs/", "mode": "r", "reason": "cite the draft"]]]
case "volume_grants": return ["grants": []]
@@ -82,6 +88,22 @@ struct AgentsPagesTests {
#expect(seen == UInt64(tools.now - 60_000))
}
+ /// The web UI's `agents.detail`, `agents.readFile` and change methods run
+ /// the tools the native page runs.
+ @Test func detailFileAndChangesUseTheNativeTools() async throws {
+ let tools = FakeAgentsTools()
+ let m = PersistentModel(tools: tools)
+ let d = try await m.detail("ada")
+ #expect((d["home"] as? [[String: Any]])?.compactMap { $0["path"] as? String } == ["agents/ada/hermes/MEMORY.md"])
+ #expect((d["routines"] as? [[String: Any]])?.first?["title"] as? String == "Morning")
+ let f = try await m.readFile("agents/ada/hermes/MEMORY.md")
+ #expect(f["text"] as? String == "# Ada\n")
+ #expect((f["versions"] as? [[String: Any]])?.count == 2)
+ try await m.perform(.addRoutine(agent: "ada", title: "Inbox", prompt: "Sort my inbox", everyMinutes: nil, dailyAt: "08:00", weeklyOn: nil))
+ try await m.perform(.removeRoutine(id: "R1"))
+ #expect(tools.calls.suffix(2) == ["routine_add", "routine_remove"])
+ }
+
@Test func snapshots() async throws {
let tools = FakeAgentsTools()
let m = PersistentModel(tools: tools)
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
index df6032f656..730f34a759 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
@@ -112,7 +112,10 @@ struct BridgeContractTests {
func agentsTool(_ tool: String, _ args: [String: Any]) async throws -> Any {
if tool.hasPrefix("agent_keys.") { return try await keys.agentsTool(tool, args) }
- if tool.hasPrefix("volume_") && !["volume_requests", "volume_grants"].contains(tool) {
+ // An agent's home and its files: the Agents fake.
+ let home = ["volume_read", "volume_history", "volume_restore"].contains(tool)
+ || (tool == "volume_ls" && (args["path"] as? String ?? "").hasPrefix("agents/"))
+ if tool.hasPrefix("volume_") && !["volume_requests", "volume_grants"].contains(tool) && !home {
return try await drive.agentsTool(tool, args)
}
return try await agents.agentsTool(tool, args)
@@ -204,6 +207,13 @@ struct BridgeContractTests {
("machines.list", [:]), ("host.status", [:]),
("agents.list", [:]), ("agents.runs", ["spaceId": "local:aurora"]), ("agents.setup", [:]),
("agents.configure", ["agents": ["claude-code"]]),
+ ("agents.detail", ["name": "ada"]), ("agents.readFile", ["path": "agents/ada/hermes/MEMORY.md"]),
+ ("agents.restoreFile", ["path": "agents/ada/hermes/MEMORY.md", "version": "v1"]),
+ ("agents.addRoutine", ["agent": "ada", "title": "Inbox", "prompt": "Sort my inbox", "everyMinutes": NSNull(),
+ "dailyAt": "08:00", "weeklyOn": NSNull()]),
+ ("agents.setRoutine", ["id": "R1", "enabled": false]), ("agents.removeRoutine", ["id": "R1"]),
+ ("agents.allowComputer", ["agent": "ada", "machine": "relay:0123"]),
+ ("agents.revokeComputer", ["agent": "ada", "machine": "relay:0123"]),
("agentKeys.list", [:]), ("agentKeys.set", ["provider": "anthropic", "value": "sk-ant-test-0000"]),
("agentKeys.remove", ["env": "ANTHROPIC_API_KEY"]),
("clouds.status", [:]), ("clouds.test", ["target": ["provider": "aws", "region": "us-west-2"]]),
diff --git a/apps/cua-spaces-web/src/__tests__/agents-detail-tabs.test.tsx b/apps/cua-spaces-web/src/__tests__/agents-detail-tabs.test.tsx
new file mode 100644
index 0000000000..777ffaca02
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/agents-detail-tabs.test.tsx
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// The Agents page's persistent-agent detail, as the SwiftUI app's: the run's
+// conversation, then the core's Memory, Routines and "Access to this
+// computer" tabs (the access audit under Access).
+
+import { cleanup, fireEvent, waitFor, within } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { wasmBuilt } from "@/bridge/__tests__/testCore";
+import { mountApp, stubBrowserApis } from "./app-harness";
+
+afterEach(cleanup);
+stubBrowserApis();
+
+const tab = (name: string) => document.querySelector<HTMLElement>(`[data-agent-tab="${name}"]`);
+const panel = (name: string) => document.querySelector<HTMLElement>(`[data-agent-panel="${name}"]`);
+
+describe.skipIf(!wasmBuilt)("Agents, a persistent agent's detail", () => {
+ it("shows Memory, adds a routine and lists Access with its audit", { timeout: 20_000 }, async () => {
+ await mountApp("/agents?agent=ada", { failsCreates: false, listsGhost: false });
+ await waitFor(() => expect(tab("memory")).not.toBeNull(), { timeout: 8000 });
+ expect([...document.querySelectorAll("[data-agent-tab]")].map((t) => t.textContent)).toEqual(["Conversation", "Memory", "Routines", "Access to this computer"]);
+ expect(tab("run")!.getAttribute("aria-selected")).toBe("true");
+
+ fireEvent.click(tab("memory")!);
+ await waitFor(() => expect(within(panel("memory")!).getByText("notes/review-checklist.md")).toBeTruthy());
+ fireEvent.click(within(panel("memory")!).getByText("MEMORY.md"));
+ await waitFor(() => expect(panel("memory")!.querySelector("[data-agent-file-text]")?.textContent).toContain("light and dark"));
+ expect(within(panel("memory")!).getAllByRole("button", { name: "Restore" })).toHaveLength(2);
+ fireEvent.click(within(panel("memory")!).getByRole("button", { name: "Close" }));
+
+ fireEvent.click(tab("routines")!);
+ const routines = await waitFor(() => panel("routines")!);
+ expect(within(routines).getByText("Morning design notes")).toBeTruthy();
+ expect(within(routines).getByText("Every day at 9:00 AM")).toBeTruthy();
+ const add = within(routines).getByRole("button", { name: "Add routine" }) as HTMLButtonElement;
+ expect(add.disabled).toBe(true);
+ fireEvent.change(routines.querySelector("[data-routine-title]")!, { target: { value: "Inbox" } });
+ fireEvent.change(routines.querySelector("[data-routine-prompt]")!, { target: { value: "Sort my inbox" } });
+ await waitFor(() => expect(add.disabled).toBe(false));
+ fireEvent.click(add);
+ await waitFor(() => expect(within(panel("routines")!).getByText("Inbox")).toBeTruthy());
+ expect(within(panel("routines")!).getByText("Every day at 8:00 AM")).toBeTruthy();
+
+ fireEvent.click(tab("access")!);
+ const access = await waitFor(() => panel("access")!);
+ expect(within(access).getByText("This computer")).toBeTruthy();
+ expect(within(access).getByRole("button", { name: "Revoke" })).toBeTruthy();
+ expect(within(access).getByText("Audit")).toBeTruthy();
+ expect(within(access).getByText("Used relay:this-mac")).toBeTruthy();
+ });
+});
diff --git a/apps/cua-spaces-web/src/bridge/README.md b/apps/cua-spaces-web/src/bridge/README.md
index 8c8260720f..7f53e07789 100644
--- a/apps/cua-spaces-web/src/bridge/README.md
+++ b/apps/cua-spaces-web/src/bridge/README.md
@@ -37,6 +37,7 @@ import { BridgeProvider, useSpaces } from "@/bridge";
| `useKeyvault()` | `{ overview, groups, views, vaultState }`. `views` holds the core's `page`, `sidebar` and `vault` (the list grouped by app, then site). Actions: `unlock(passphrase?)`, `lockItem(id)`, `lockItems(ids)`, `unlockItems(ids)`, `setDisabled`, `approve`, `deny`, `revokeGrant`, `vaultAction(action)` (search, select, open), and `pane(selection)`. |
| `useSession()` | `{ fleet, onboarding, daemon, signedIn, identity, signIn }`, where `signIn` is the sign-in phase. Actions: `signIn()`, `signOut()`, `completeOnboarding(mode)`, `openExternal(url)`. |
| `useAgents()` | `{ agents, runs, unread, canList }`: persistent agents (state `running`, `paused` or `idle`, the core's row line and action label, the run the detail opens) and the runs in every running Space, in the core's order. Actions: `pauseAgent(name)`, `resumeAgent(name)`, `agentSetup()`, `configureAgents(agents?)`. |
+| `useAgentDetail(agent)` | A persistent agent's Memory, Routines and Access to this computer (`agent-detail.ts`): `{ view, busy, error, unsupported, thisMachine, act(action) }`. The page runs the core's `agents.pageReduce` / `agents.pageView`, as `PersistentModel` does natively, and the host runs each command (`ops/agent-detail.ts`). |
| `useAgentTimeline(run)` | One run's conversation while mounted: `{ items, status, phase, caughtUp, isLoading, error, unsupported, lastEventMs }`. It reads `agents.events` with a cursor (every 500 ms while a turn runs, 4 s otherwise) and folds the events like cua-agents' `Transcript` (`transcript.ts`). Items are immutable, so a row memoized by item re-renders only when its item changed. |
| `useOnboarding()` | The first run from the core (`onboarding.initial/reduce/view/copy`): `{ state, view, copy, signInText, permissions, hostConfigured, images }`. Actions: `send(action)`, `skip()`, `finish()`, `restart()`. See below. |
| `useSavedOnboarding()` | `{ state, skipped }`: the saved progress the shell reads to reopen or offer the first run. |
@@ -104,6 +105,7 @@ Each is an existing Tauri command under a host-neutral name:
| `agents.events` `{spaceId, runId, cursor, max?}` | none yet: unsupported (`TAURI_UNSUPPORTED`) |
| `agents.pause` / `.resume` `{name}` | `agents_tool` `agent_pause` / `agent_resume` |
| `agents.setup` / `.configure` `{agents}` | `agent_setup_detect` / `agent_setup_configure` |
+| `agents.detail`, `.readFile`, `.restoreFile`, `.addRoutine`, `.setRoutine`, `.removeRoutine`, `.allowComputer`, `.revokeComputer` | `agents_tool` (the tools `PersistentModel` runs; see `ops/agent-detail.ts`) |
Events (`HostEvent`): `spaces.changed`, `spaces.createProgress`,
`machines.changed`, `settings.changed`, `keyvault.changed`,
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/agent-detail.test.tsx b/apps/cua-spaces-web/src/bridge/__tests__/agent-detail.test.tsx
new file mode 100644
index 0000000000..64724b7a13
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/__tests__/agent-detail.test.tsx
@@ -0,0 +1,214 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { act, cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { createDemoAdapter } from "../adapters/demo";
+import { routineLabel } from "../adapters/demo/agent-detail";
+import type { PersistentAgent } from "../contracts/agents";
+import type { CoreClient } from "../core";
+import { BridgeProvider, useAgentDetail, type AgentDetailHook } from "../index";
+import { agentDetailFromTools, agentFileFromTools, routineAddArgs, tauriAgentDetailOps, webkitAgentDetailOps } from "../ops/agent-detail";
+import { noCore, testCore, wasmBuilt } from "./testCore";
+
+afterEach(cleanup);
+
+/* ---- The ops ----------------------------------------------------------------- */
+
+describe("agent detail ops", () => {
+ it("reads a home recursively and maps the tools' JSON onto the core's input", async () => {
+ const calls: [string, Record<string, unknown>][] = [];
+ const tool = async (name: string, args: Record<string, unknown>) => {
+ calls.push([name, args]);
+ switch (name) {
+ case "volume_ls":
+ return args.path === "agents/ada/"
+ ? { entries: [{ path: "agents/ada/notes/", name: "notes", folder: true }, { path: "agents/ada/MEMORY.md", name: "MEMORY.md", size: 12 }] }
+ : { entries: [{ path: "agents/ada/notes/a.md", name: "a.md", size: 3 }] };
+ case "routine_list":
+ return { routines: [{ id: "R1", title: "Morning", label: "Every day at 8:00 AM", isEnabled: false }, { id: "R2", title: "Noon", label: "x" }] };
+ case "computer_access_list":
+ return { grants: [{ agent: "ada", machine: "relay:m1", revoked: false }], audit: [{ ts_ms: 5, action: "use", principal: "agent:ada", path: "relay:m1", detail: "" }] };
+ default:
+ throw new Error(name);
+ }
+ };
+ const d = await agentDetailFromTools(tool, "ada", "relay:m1");
+ expect(d.home.map((f) => f.path)).toEqual(["agents/ada/MEMORY.md", "agents/ada/notes/a.md"]);
+ expect(d.routines.map((r) => r.enabled)).toEqual([false, true]);
+ expect(d.audit).toEqual([{ tsMs: 5, action: "use", principal: "agent:ada", path: "relay:m1", detail: "" }]);
+ expect(d.thisMachine).toBe("relay:m1");
+ expect(calls.find(([n]) => n === "computer_access_list")?.[1]).toEqual({ audit: 20 });
+ });
+
+ it("reads a file with its versions, and shows no bytes of a binary one", async () => {
+ const tool = async (name: string) =>
+ name === "volume_read"
+ ? { content: "AAEC", encoding: "base64" }
+ : { versions: [{ version: "v2", modified_ms: 9, latest: true }, { version: "v1", modified_ms: 1, deleted: true }] };
+ expect(await agentFileFromTools(tool, "agents/ada/x.bin")).toEqual({
+ path: "agents/ada/x.bin",
+ text: "",
+ binary: true,
+ versions: [
+ { version: "v2", modifiedMs: 9, deleted: false, latest: true },
+ { version: "v1", modifiedMs: 1, deleted: true, latest: false },
+ ],
+ });
+ });
+
+ it("sends routine_add only the schedule that is set", () => {
+ const base = { agent: "ada", title: "T", prompt: "P", everyMinutes: null, dailyAt: null, weeklyOn: null };
+ expect(routineAddArgs({ ...base, everyMinutes: 30 })).toEqual({ agent: "ada", title: "T", prompt: "P", every_minutes: 30 });
+ expect(routineAddArgs({ ...base, weeklyOn: "fri 16:00" })).toEqual({ agent: "ada", title: "T", prompt: "P", weekly_on: "fri 16:00" });
+ });
+
+ it("Tauri runs each change through agents_tool", async () => {
+ const seen: unknown[] = [];
+ const ops = tauriAgentDetailOps(async <T,>(cmd: string, args?: Record<string, unknown>) => {
+ seen.push([cmd, args]);
+ return {} as T;
+ });
+ await ops["agents.setRoutine"]({ id: "R1", enabled: true });
+ await ops["agents.allowComputer"]({ agent: "ada", machine: "relay:m1" });
+ expect(seen).toEqual([
+ ["agents_tool", { tool: "routine_set_enabled", args: { id: "R1", enabled: true } }],
+ ["agents_tool", { tool: "computer_access_grant", args: { agent: "ada", machine: "relay:m1" } }],
+ ]);
+ });
+
+ it("the native hosts get each operation under its own name, and a sparse detail reads as empty", async () => {
+ const seen: unknown[] = [];
+ const ops = webkitAgentDetailOps(async <T,>(method: string, args?: Record<string, unknown>) => {
+ seen.push([method, args]);
+ return (method === "agents.detail" ? { home: [{ path: "agents/ada/a", name: "a", size: 1 }] } : null) as T;
+ });
+ expect(await ops["agents.detail"]({ name: "ada" })).toEqual({ home: [{ path: "agents/ada/a", name: "a", size: 1 }], routines: [], grants: [], audit: [], thisMachine: null });
+ expect(await ops["agents.removeRoutine"]({ id: "R1" })).toBeNull();
+ expect(seen).toEqual([
+ ["agents.detail", { name: "ada" }],
+ ["agents.removeRoutine", { id: "R1" }],
+ ]);
+ });
+
+ it("the demo labels routines as the daemon does", () => {
+ expect(routineLabel(60, null, null)).toBe("Every hour");
+ expect(routineLabel(null, "08:05", null)).toBe("Every day at 8:05 AM");
+ expect(routineLabel(null, null, "fri 16:00")).toBe("Every Friday at 4:00 PM");
+ });
+});
+
+/* ---- The hook, with the core, on the demo host ------------------------------------ */
+
+const ADA: PersistentAgent = { name: "ada", harness: "claude-code", space: "local:design-review", paused: false, spaceState: "running", runId: "run-ada-7", savedMs: Date.UTC(2026, 9, 3, 12) };
+
+function mount(core: CoreClient, agent: PersistentAgent = ADA) {
+ const adapter = createDemoAdapter({ latencyMs: 0, stepMs: 4 });
+ const got: { d?: AgentDetailHook } = {};
+ function Probe() {
+ got.d = useAgentDetail(agent);
+ return null;
+ }
+ render(
+ <BridgeProvider adapter={adapter} core={core}>
+ <Probe />
+ </BridgeProvider>,
+ );
+ return got;
+}
+
+const idle = async (got: { d?: AgentDetailHook }) => waitFor(() => expect(got.d?.busy).toBe(false));
+
+describe.skipIf(!wasmBuilt)("useAgentDetail with the core", () => {
+ it("draws the agent's memory, opens a file and restores an older version", async () => {
+ const got = mount(await testCore());
+ await waitFor(() => expect(got.d?.view?.memory.length).toBeGreaterThan(0));
+ const v = got.d!.view!;
+ expect(v.tabs.map((t) => t.label)).toEqual(["Memory", "Routines", "Access to this computer"]);
+ expect(v.subtitle).toMatch(/^Home agents\/ada\/, saved /);
+ expect(v.memory.map((l) => l.text)).toEqual(["MEMORY.md", "notes/review-checklist.md", "notes/open-questions.md"]);
+
+ act(() => got.d!.act({ type: "open-file", path: "agents/ada/MEMORY.md" }));
+ await waitFor(() => expect(got.d?.view?.file).toBeTruthy());
+ const file = got.d!.view!.file!;
+ expect(file.path).toBe("MEMORY.md");
+ expect(file.text).toContain("light and dark");
+ expect(file.versions.map((l) => [l.text === "Current", l.actionLabel ?? null])).toEqual([
+ [true, null],
+ [false, "Restore"],
+ [false, "Restore"],
+ ]);
+
+ act(() => got.d!.act({ type: "restore", version: file.versions[1]!.id }));
+ await idle(got);
+ // Restored: the file closes, as in the native page.
+ expect(got.d!.view!.file ?? null).toBeNull();
+ act(() => got.d!.act({ type: "open-file", path: "agents/ada/MEMORY.md" }));
+ await waitFor(() => expect(got.d?.view?.file?.text).not.toContain("light and dark"));
+ });
+
+ it("adds, turns off and removes a routine; the form checks what it sends", async () => {
+ const got = mount(await testCore());
+ await waitFor(() => expect(got.d?.view?.routines.length).toBe(2));
+ const send = (a: Parameters<AgentDetailHook["act"]>[0]) => act(() => got.d!.act(a));
+ send({ type: "set-tab", tab: "routines" });
+ expect(got.d!.view!.canAddRoutine).toBe(false);
+ send({ type: "set-title", title: "Inbox" });
+ send({ type: "set-prompt", prompt: "Sort my inbox" });
+ send({ type: "set-schedule", schedule: "weekly" });
+ send({ type: "set-time", time: "25:00" });
+ expect(got.d!.view!.canAddRoutine).toBe(false);
+ send({ type: "set-time", time: "16:30" });
+ send({ type: "set-weekday", weekday: "fri" });
+ expect(got.d!.view!.canAddRoutine).toBe(true);
+ send({ type: "add-routine" });
+ await waitFor(() => expect(got.d!.view!.routines.map((l) => l.text)).toContain("Inbox"));
+ await idle(got);
+ const added = got.d!.view!.routines.find((l) => l.text === "Inbox")!;
+ expect(added).toMatchObject({ trailing: "Every Friday at 4:30 PM", on: true, actionLabel: "Remove" });
+ // The form starts over.
+ expect(got.d!.view!.form.title).toBe("");
+
+ send({ type: "toggle-routine", id: added.id });
+ await waitFor(() => expect(got.d!.view!.routines.find((l) => l.id === added.id)?.on).toBe(false));
+ await idle(got);
+ send({ type: "remove-routine", id: added.id });
+ await waitFor(() => expect(got.d!.view!.routines.map((l) => l.id)).not.toContain(added.id));
+ });
+
+ it("revokes and allows this computer, and shows the agent's audit", async () => {
+ const got = mount(await testCore());
+ await waitFor(() => expect(got.d?.view?.access.length).toBe(1));
+ expect(got.d!.view!.access[0]).toMatchObject({ text: "This computer", actionLabel: "Revoke" });
+ expect(got.d!.view!.allowThisMachineLabel ?? null).toBeNull();
+ // Ada's own lines only (Claw's refusal and Atlas's use are not hers).
+ expect(got.d!.view!.audit.map((l) => l.text)).toEqual(["Used relay:this-mac", "Allowed relay:this-mac"]);
+
+ act(() => got.d!.act({ type: "revoke-computer", machine: "relay:this-mac" }));
+ await waitFor(() => expect(got.d!.view!.access).toEqual([]));
+ await idle(got);
+ expect(got.d!.view!.accessEmpty).toBe("This agent cannot use your computers.");
+ expect(got.d!.view!.allowThisMachineLabel).toBe("Allow on this computer");
+ expect(got.d!.thisMachine).toBe("relay:this-mac");
+ expect(got.d!.view!.audit[0]!.text).toBe("Revoked relay:this-mac");
+
+ act(() => got.d!.act({ type: "allow-computer", machine: got.d!.thisMachine! }));
+ await waitFor(() => expect(got.d!.view!.access.map((l) => l.text)).toEqual(["This computer"]));
+ });
+
+ it("says why a change failed", async () => {
+ const got = mount(await testCore());
+ await waitFor(() => expect(got.d?.view?.memory.length).toBeGreaterThan(0));
+ await idle(got);
+ act(() => got.d!.act({ type: "open-file", path: "agents/ada/missing.md" }));
+ await waitFor(() => expect(got.d!.error).toMatch(/not found/));
+ });
+});
+
+describe("useAgentDetail without the core", () => {
+ it("draws nothing (the page shows the run only)", async () => {
+ const got = mount(noCore);
+ await act(async () => {});
+ expect(got.d!.view).toBeNull();
+ });
+});
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
index 51c4877153..af7ba31b07 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
@@ -47,6 +47,14 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {
"agents.resume": { name: "ada" },
"agents.setup": {},
"agents.configure": { agents: null },
+ "agents.detail": { name: "ada" },
+ "agents.readFile": { path: "agents/ada/MEMORY.md" },
+ "agents.restoreFile": { path: "agents/ada/MEMORY.md", version: "agents/ada/MEMORY.md@1" },
+ "agents.addRoutine": { agent: "ada", title: "Contract check", prompt: "Say hi", everyMinutes: 30, dailyAt: null, weeklyOn: null },
+ "agents.setRoutine": { id: "rt-ada-standup", enabled: false },
+ "agents.removeRoutine": { id: "rt-ada-standup" },
+ "agents.allowComputer": { agent: "ada", machine: "relay:this-mac" },
+ "agents.revokeComputer": { agent: "ada", machine: "relay:this-mac" },
"spaces.createOptions": {},
"spaces.add": { url: "studio.local:7400", token: null, name: null },
"clouds.status": {},
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
index 704ad1abb6..0f891b2af9 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
@@ -9,6 +9,7 @@ import { createTauriAdapter } from "../adapters/tauri";
import { createWebkitAdapter } from "../adapters/webkit";
import { HOST_COVERAGE, WEBKIT_HOST_ONLY } from "../coverage";
import { NEW_SPACE_ARGS } from "../ops/new-space";
+import { AGENT_DETAIL_ARGS } from "../ops/agent-detail";
import { AGENT_KEYS_ARGS } from "../ops/agent-keys";
import { KEYVAULT_MANAGE_ARGS } from "../ops/keyvault-manage";
import { KEYVAULT_SETUP_ARGS } from "../ops/keyvault-setup";
@@ -51,6 +52,7 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {
"agents.resume": { name: "ada" },
"agents.setup": {},
"agents.configure": { agents: null },
+ ...AGENT_DETAIL_ARGS,
...NEW_SPACE_ARGS,
...AGENT_KEYS_ARGS,
...KEYVAULT_SETUP_ARGS,
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
index f411555922..25893136aa 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
@@ -34,6 +34,7 @@ import {
} from "./demo-data";
import { demoNewSpaceState, newSpaceDemoHandlers, type DemoNewSpaceState } from "./demo/new-space";
import { demoShareHandlers } from "./demo/share";
+import { demoAgentDetailHandlers } from "./demo/agent-detail";
import { demoAgentKeysHandlers } from "./demo/agent-keys";
import { demoKeyvaultManageHandlers, demoKeyvaultManageState, withDemoCopies, type DemoKeyvaultManageState } from "./demo/keyvault-manage";
import { demoKeyvaultSetupHandlers, demoKeyvaultSetupState, demoNoVaultOverview, type DemoKeyvaultSetupState } from "./demo/keyvault-setup";
@@ -459,6 +460,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
...newSpaceDemoHandlers({ state, wait, emit, step, now }),
...demoTeleportHandlers({ wait, emit, now, stepMs: step }),
...demoShareHandlers({ wait, stepMs: step }),
+ ...demoAgentDetailHandlers({ wait, stepMs: step, now }),
...demoAgentKeysHandlers({ wait, stepMs: step, now }),
...demoVolumeHandlers({ state: state.volume, now, wait, step, emit, platform: state.platform }),
...createDemoSettings({ now, wait, emit, stepMs: step, platform: state.platform, unenrolled: options.unenrolled, experiments: state.volume.experiments, signedIn: () => Boolean(state.identity), settings: () => state.settings, setSettings: (p) => ((state.settings = { ...state.settings, ...p }), emit({ type: "settings.changed" })), addMachine: (m) => ((state.paired = [...state.paired, m]), emit({ type: "machines.changed" })) }),
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/agent-detail.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/agent-detail.ts
new file mode 100644
index 0000000000..6325ff326b
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/agent-detail.ts
@@ -0,0 +1,190 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * The demo host's persistent-agent detail: each demo agent's home files
+ * (with a few versions), routines, computer grants and access audit, in
+ * memory, answered as the native hosts answer `agents.detail` and
+ * `agents.readFile`. This Mac is `relay:this-mac`. All synthetic.
+ */
+
+import { HostError } from "../../adapter";
+import type { AgentAccessAudit, AgentComputerGrant, AgentFileVersion, AgentRoutine } from "../../contracts/agents";
+import type { AgentDetailOp } from "../../ops/agent-detail";
+import type { DemoHandlers } from "./context";
+
+const MIN = 60_000;
+const HOUR = 60 * MIN;
+const THIS_MACHINE = "relay:this-mac";
+
+interface DemoFile {
+ text: string;
+ /** Older texts, newest first (`versions[0]` is the one before the current). */
+ history: { text: string; at: number }[];
+ at: number;
+}
+
+const DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
+const WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
+
+/** The daemon's routine label (`cua_spaces::routines::Schedule::label`). */
+function clock(time: string): string {
+ const [h = 0, m = 0] = time.split(":").map(Number);
+ return `${h % 12 === 0 ? 12 : h % 12}:${String(m).padStart(2, "0")} ${h < 12 ? "AM" : "PM"}`;
+}
+
+export function routineLabel(everyMinutes: number | null, dailyAt: string | null, weeklyOn: string | null): string {
+ if (everyMinutes !== null) {
+ if (everyMinutes === 1) return "Every minute";
+ if (everyMinutes === 60) return "Every hour";
+ if (everyMinutes % 60 === 0) return `Every ${everyMinutes / 60} hours`;
+ return `Every ${everyMinutes} minutes`;
+ }
+ if (dailyAt) return `Every day at ${clock(dailyAt)}`;
+ const [day = "mon", time = "09:00"] = (weeklyOn ?? "").split(" ");
+ return `Every ${DAYS[Math.max(0, WEEKDAYS.indexOf(day))]} at ${clock(time)}`;
+}
+
+function demoHomes(now: number): Map<string, Map<string, DemoFile>> {
+ const file = (text: string, at: number, ...history: [string, number][]): DemoFile => ({ text, at, history: history.map(([t, a]) => ({ text: t, at: a })) });
+ return new Map([
+ [
+ "ada",
+ new Map([
+ [
+ "MEMORY.md",
+ file(
+ "# Ada\n\n- The design review runs in local:design-review.\n- Francesco wants screenshots in light and dark.\n- Figma exports go to public/design/.\n",
+ now - 2 * MIN,
+ ["# Ada\n\n- The design review runs in local:design-review.\n- Figma exports go to public/design/.\n", now - 3 * HOUR],
+ ["# Ada\n\n- The design review runs in local:design-review.\n", now - 2 * 24 * HOUR],
+ ),
+ ],
+ ["notes/review-checklist.md", file("1. Contrast in both themes\n2. Keyboard focus on every control\n3. Copy matches the native app\n", now - 50 * MIN)],
+ ["notes/open-questions.md", file("- Should the notch show routines?\n", now - 26 * HOUR)],
+ ]),
+ ],
+ [
+ "atlas",
+ new Map([
+ ["MEMORY.md", file("# Atlas\n\nBuilds the Linux images in relay:linux-box/ubuntu-build.\n", now - 38 * MIN, ["# Atlas\n", now - 5 * 24 * HOUR])],
+ ["runbooks/nightly-build.md", file("cargo build --release, then upload the artifacts to public/builds/.\n", now - 9 * HOUR)],
+ ]),
+ ],
+ ["claw", new Map([["MEMORY.md", file("# Claw\n\nRuns the Windows QA pass.\n", now - 3 * HOUR)]])],
+ ["scout", new Map([["MEMORY.md", file("# Scout\n\nChecks each release candidate before it ships.\n", now - 26 * HOUR)]])],
+ ]);
+}
+
+function demoRoutines(): Map<string, AgentRoutine[]> {
+ return new Map([
+ [
+ "ada",
+ [
+ { id: "rt-ada-standup", title: "Morning design notes", label: "Every day at 9:00 AM", enabled: true },
+ { id: "rt-ada-weekly", title: "Weekly screenshot sweep", label: "Every Friday at 4:00 PM", enabled: false },
+ ],
+ ],
+ ["atlas", [{ id: "rt-atlas-nightly", title: "Nightly build", label: "Every day at 2:00 AM", enabled: true }]],
+ ["claw", []],
+ ["scout", [{ id: "rt-scout-rc", title: "Check the latest release candidate", label: "Every 6 hours", enabled: true }]],
+ ]);
+}
+
+export function demoAgentDetailHandlers({ wait, stepMs, now }: { wait(ms: number): Promise<void>; stepMs: number; now: () => number }): DemoHandlers<AgentDetailOp> {
+ const homes = demoHomes(now());
+ const routines = demoRoutines();
+ let grants: AgentComputerGrant[] = [
+ { agent: "ada", machine: THIS_MACHINE, revoked: false },
+ { agent: "atlas", machine: "relay:linux-box", revoked: false },
+ ];
+ const audit: AgentAccessAudit[] = [
+ { tsMs: now() - 4 * MIN, action: "use", principal: "agent:ada", path: THIS_MACHINE, detail: "screenshot" },
+ { tsMs: now() - 3 * HOUR, action: "grant", principal: "user", path: THIS_MACHINE, detail: "agent:ada" },
+ { tsMs: now() - 7 * HOUR, action: "use", principal: "agent:atlas", path: "relay:linux-box", detail: "shell" },
+ { tsMs: now() - 2 * 24 * HOUR, action: "denied", principal: "agent:claw", path: THIS_MACHINE, detail: "not allowed" },
+ ];
+ let nextRoutine = 1;
+
+ const split = (path: string): [string, string] => {
+ const m = /^agents\/([^/]+)\/(.+)$/.exec(path);
+ if (!m) throw new HostError(`not found: ${path}`, "not_found");
+ return [m[1]!, m[2]!];
+ };
+ const fileAt = (path: string) => {
+ const [agent, rel] = split(path);
+ const f = homes.get(agent)?.get(rel);
+ if (!f) throw new HostError(`not found: ${path}`, "not_found");
+ return f;
+ };
+ const versions = (path: string, f: DemoFile): AgentFileVersion[] => [
+ { version: `${path}@0`, modifiedMs: f.at, deleted: false, latest: true },
+ ...f.history.map((h, i) => ({ version: `${path}@${i + 1}`, modifiedMs: h.at, deleted: false, latest: false })),
+ ];
+ const audited = (action: string, agent: string, machine: string) =>
+ audit.unshift({ tsMs: now(), action, principal: "user", path: machine, detail: `agent:${agent}` });
+
+ return {
+ "agents.detail": async ({ name }) => {
+ await wait(stepMs / 4);
+ const home = [...(homes.get(name) ?? new Map<string, DemoFile>()).entries()].map(([rel, f]) => ({
+ path: `agents/${name}/${rel}`,
+ name: rel.split("/").pop()!,
+ size: new TextEncoder().encode(f.text).length,
+ }));
+ return {
+ home,
+ routines: (routines.get(name) ?? []).map((r) => ({ ...r })),
+ grants: grants.map((g) => ({ ...g })),
+ audit: audit.map((a) => ({ ...a })),
+ thisMachine: THIS_MACHINE,
+ };
+ },
+ "agents.readFile": async ({ path }) => {
+ await wait(stepMs / 4);
+ const f = fileAt(path);
+ return { path, text: f.text, binary: false, versions: versions(path, f) };
+ },
+ "agents.restoreFile": async ({ path, version }) => {
+ const f = fileAt(path);
+ const i = Number(version.split("@").pop());
+ const old = f.history[i - 1];
+ if (!old) throw new HostError(`not found: version ${version}`, "not_found");
+ await wait(stepMs / 2);
+ f.history.unshift({ text: f.text, at: f.at });
+ f.text = old.text;
+ f.at = now();
+ return null;
+ },
+ "agents.addRoutine": async ({ agent, title, prompt, everyMinutes, dailyAt, weeklyOn }) => {
+ if (!title.trim() || !prompt.trim()) throw new HostError("a routine needs a title and a prompt", "bad_args");
+ await wait(stepMs / 2);
+ const list = routines.get(agent) ?? [];
+ routines.set(agent, [...list, { id: `rt-${agent}-new-${nextRoutine++}`, title, label: routineLabel(everyMinutes ?? null, dailyAt ?? null, weeklyOn ?? null), enabled: true }]);
+ return null;
+ },
+ "agents.setRoutine": async ({ id, enabled }) => {
+ await wait(stepMs / 4);
+ for (const [agent, list] of routines) routines.set(agent, list.map((r) => (r.id === id ? { ...r, enabled } : r)));
+ return null;
+ },
+ "agents.removeRoutine": async ({ id }) => {
+ await wait(stepMs / 4);
+ for (const [agent, list] of routines) routines.set(agent, list.filter((r) => r.id !== id));
+ return null;
+ },
+ // The daemon asks for Touch ID first; the demo takes a moment instead.
+ "agents.allowComputer": async ({ agent, machine }) => {
+ await wait(stepMs);
+ grants = [...grants.filter((g) => !(g.agent === agent && g.machine === machine)), { agent, machine, revoked: false }];
+ audited("grant", agent, machine);
+ return null;
+ },
+ "agents.revokeComputer": async ({ agent, machine }) => {
+ await wait(stepMs / 4);
+ grants = grants.map((g) => (g.agent === agent && g.machine === machine ? { ...g, revoked: true } : g));
+ audited("revoke", agent, machine);
+ return null;
+ },
+ };
+}
diff --git a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts
index 6f2bf8025b..53e1ab42cc 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts
@@ -34,6 +34,7 @@ import type { AgentSetupRow, PersistentAgent, SpaceAgentRun } from "../contracts
import type { HostWindow } from "../detect";
import { newSpaceTauriOps } from "../ops/new-space";
import { tauriShareOps } from "../ops/share";
+import { tauriAgentDetailOps } from "../ops/agent-detail";
import { tauriAgentKeysOps } from "../ops/agent-keys";
import { KEYVAULT_MANAGE_TAURI_UNSUPPORTED } from "../ops/keyvault-manage";
import { tauriKeyvaultSetupOps } from "../ops/keyvault-setup";
@@ -270,6 +271,7 @@ export function createTauriAdapter(win: HostWindow = globalThis.window as HostWi
...newSpaceTauriOps(invoke, readUi),
...tauriTeleportOps(invoke, win.__TAURI_INTERNALS__, (e) => events.emit(e)),
...tauriShareOps(invoke),
+ ...tauriAgentDetailOps(invoke),
...tauriAgentKeysOps(invoke),
...tauriKeyvaultSetupOps(invoke),
...tauriVolumeOps(invoke, win),
diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
index 7e3471cfe2..74db291e32 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
@@ -48,6 +48,7 @@ import { syncDragRegions } from "../drag-regions";
import { requestNewSpace } from "../new-space";
import { STOPPED_SHARING_ERROR, stoppedSharingLine, withNotSharing } from "../sharing";
import { teleportProgressFromWk, webkitPageOps } from "../ops/webkit-pages";
+import { webkitAgentDetailOps } from "../ops/agent-detail";
import { webkitAgentKeysOps } from "../ops/agent-keys";
import { webkitKeyvaultManageOps } from "../ops/keyvault-manage";
import { webkitKeyvaultSetupOps } from "../ops/keyvault-setup";
@@ -573,6 +574,7 @@ export function createWebkitAdapter(
...webkitSettingsOps(request),
...webkitPageOps(request, toHostStatus, spaceToRow),
...webkitStartupOps(request),
+ ...webkitAgentDetailOps(request),
...webkitAgentKeysOps(request),
...webkitKeyvaultManageOps(request, toKeyvaultOverview as (wk: never) => KeyvaultOverview),
...webkitKeyvaultSetupOps(request, () => new HostError("Enter the passphrase in the Cua Spaces window", "native_only")),
diff --git a/apps/cua-spaces-web/src/bridge/agent-detail.ts b/apps/cua-spaces-web/src/bridge/agent-detail.ts
new file mode 100644
index 0000000000..b5aff82dbb
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/agent-detail.ts
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * One persistent agent's Memory, Routines and Access to this computer, as
+ * the SwiftUI app's Agents page draws them (`AgentsPageView`). Every word
+ * and rule is the app core's (`agents.pageReduce` / `agents.pageView`,
+ * `cua-spaces-app-core/src/persistent.rs`); this runs the command each
+ * action asks for through `ops/agent-detail.ts` and keeps the answers, as
+ * `PersistentModel.send` does natively.
+ *
+ * Without the core there is no detail (`view` stays null): the page shows
+ * the agent's run only.
+ */
+
+import { useCallback, useEffect, useRef, useState } from "react";
+
+import { isUnsupported, type DataAdapter } from "./adapter";
+import type { CoreClient } from "./core";
+import type {
+ AgentDetailView,
+ AgentsPageAction,
+ AgentsPageInput,
+ AgentsPageRequest,
+ AgentsPageState,
+ AgentsPageView,
+ PersistentAgent,
+} from "./contracts/agents";
+import { useBridge } from "./hooks";
+
+export function agentsPageReduce(core: CoreClient, input: AgentsPageInput, state: AgentsPageState, action: AgentsPageAction): AgentsPageState {
+ return core.call<AgentsPageState>("agents.pageReduce", { input, state, action });
+}
+
+export function agentsPageDetail(core: CoreClient, input: AgentsPageInput, state: AgentsPageState, nowMs: number): AgentsPageView | null {
+ return core.tryCall<AgentsPageView>("agents.pageView", { input, state, nowMs }) ?? null;
+}
+
+/** Runs one request against the host and answers what it read into the input. */
+export async function runAgentsRequest(data: DataAdapter, request: AgentsPageRequest, selected: string | null): Promise<Partial<AgentsPageInput>> {
+ const reload = async () => (selected ? await data.call("agents.detail", { name: selected }).catch(() => ({})) : {});
+ switch (request.kind) {
+ case "load":
+ return data.call("agents.detail", { name: request.name });
+ case "read-file":
+ return { file: await data.call("agents.readFile", { path: request.path }) };
+ case "pause":
+ await data.call("agents.pause", { name: request.name });
+ return {};
+ case "resume":
+ await data.call("agents.resume", { name: request.name });
+ return {};
+ case "restore":
+ await data.call("agents.restoreFile", { path: request.path, version: request.version });
+ return reload();
+ case "add-routine":
+ await data.call("agents.addRoutine", {
+ agent: request.agent,
+ title: request.title,
+ prompt: request.prompt,
+ everyMinutes: request.every_minutes,
+ dailyAt: request.daily_at,
+ weeklyOn: request.weekly_on,
+ });
+ return reload();
+ case "set-routine":
+ await data.call("agents.setRoutine", { id: request.id, enabled: request.enabled });
+ return reload();
+ case "remove-routine":
+ await data.call("agents.removeRoutine", { id: request.id });
+ return reload();
+ case "allow":
+ await data.call("agents.allowComputer", { agent: request.agent, machine: request.machine });
+ return reload();
+ case "revoke":
+ await data.call("agents.revokeComputer", { agent: request.agent, machine: request.machine });
+ return reload();
+ }
+}
+
+export interface AgentDetailHook {
+ /** The agent as the core draws it; null until its first read, or without the core. */
+ view: AgentDetailView | null;
+ /** A command is running (`request` in the core's words, `requestText`). */
+ busy: boolean;
+ /** Why the last command failed. */
+ error: string | null;
+ /** The host can't read an agent's detail. */
+ unsupported: boolean;
+ /** This machine's Space id, which "Allow on this computer" grants. */
+ thisMachine: string | null;
+ /** Sends a page action; runs the command the core asks for. */
+ act(action: AgentsPageAction): void;
+}
+
+const message = (e: unknown) => (e instanceof Error ? e.message : String(e));
+
+/** `agent`'s detail while mounted (the SwiftUI `AgentsPageView`'s detail section). */
+export function useAgentDetail(agent: PersistentAgent | null, now: () => number = Date.now): AgentDetailHook {
+ const { core, data } = useBridge();
+ const ready = core.status === "ready" && core.methods.includes("agents.pageReduce");
+ const [input, setInput] = useState<Omit<AgentsPageInput, "agents">>({});
+ const [state, setState] = useState<AgentsPageState | null>(null);
+ const [unsupported, setUnsupported] = useState(false);
+ const current = useRef({ input, state, agent });
+ current.current = { input, state, agent };
+
+ const typed = (i: Omit<AgentsPageInput, "agents">): AgentsPageInput => ({ ...i, agents: current.current.agent ? [current.current.agent] : [] });
+
+ const act = useCallback(
+ (action: AgentsPageAction) => {
+ const before = current.current.state;
+ if (!ready || !data || !before) return;
+ const next = agentsPageReduce(core, typed(current.current.input), before, action);
+ current.current.state = next;
+ setState(next);
+ const request = next.request;
+ if (before.busy || !request) return;
+ const finish = (a: AgentsPageAction) => {
+ const s = agentsPageReduce(core, typed(current.current.input), current.current.state!, a);
+ current.current.state = s;
+ setState(s);
+ };
+ runAgentsRequest(data, request, next.selected ?? null).then(
+ (read) => {
+ const merged = { ...current.current.input, ...read };
+ current.current.input = merged;
+ setInput(merged);
+ finish({ type: "done" });
+ },
+ (e: unknown) => {
+ if (request.kind === "load" && isUnsupported(e)) setUnsupported(true);
+ finish({ type: "failed", error: message(e) });
+ },
+ );
+ },
+ // `typed` reads the refs.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [core, data, ready],
+ );
+
+ // A new page per agent, then its first read (the core's `select`).
+ const name = agent?.name ?? null;
+ useEffect(() => {
+ if (!ready || !name) return;
+ const initial = core.call<AgentsPageState>("agents.pageInitial", {});
+ current.current = { ...current.current, input: {}, state: initial };
+ setInput({});
+ setState(initial);
+ setUnsupported(false);
+ act({ type: "select", name });
+ }, [ready, core, name, act]);
+
+ const page = ready && state && agent ? agentsPageDetail(core, { ...input, agents: [agent] }, state, now()) : null;
+ return {
+ view: page?.detail ?? null,
+ busy: state?.busy ?? false,
+ error: page?.error ?? null,
+ unsupported,
+ thisMachine: input.thisMachine ?? null,
+ act,
+ };
+}
diff --git a/apps/cua-spaces-web/src/bridge/contracts/agents.ts b/apps/cua-spaces-web/src/bridge/contracts/agents.ts
index f9826dd6bc..b84ac466a7 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/agents.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/agents.ts
@@ -104,3 +104,208 @@ export interface AgentSetupRow {
mcpConfig: string | null;
skillsDir: string | null;
}
+
+/* ---- One persistent agent's detail ---------------------------------------------
+ * `cua-spaces-app-core/src/persistent.rs`: what the page reads
+ * (`AgentsInput`), its state and actions (`AgentsState`, `AgentsAction`,
+ * `AgentsRequest`) and what it draws (`AgentDetailView`). The page runs
+ * `agents.pageReduce` / `agents.pageView` in the core, as the SwiftUI
+ * app's `PersistentModel` does; the host runs the tools each request names.
+ */
+
+/** A file in the agent's home (`volume_ls`, files only). */
+export interface AgentHomeEntry {
+ path: string;
+ name: string;
+ size: number;
+}
+
+/** One version of a file (`volume_history`, newest first). */
+export interface AgentFileVersion {
+ version: string;
+ modifiedMs: number;
+ deleted: boolean;
+ latest: boolean;
+}
+
+/** An opened memory file (`volume_read` + `volume_history`). */
+export interface AgentOpenFile {
+ path: string;
+ /** Empty for a binary file. */
+ text: string;
+ binary: boolean;
+ versions: AgentFileVersion[];
+}
+
+/** A routine (`routine_list`). */
+export interface AgentRoutine {
+ id: string;
+ title: string;
+ /** `Every day at 8:00 AM`. */
+ label: string;
+ enabled: boolean;
+}
+
+/** A computer grant (`computer_access_list`). */
+export interface AgentComputerGrant {
+ agent: string;
+ machine: string;
+ revoked: boolean;
+}
+
+/** A computer-access audit line (`computer_access_list` with `audit`). */
+export interface AgentAccessAudit {
+ tsMs: number;
+ /** `grant`, `revoke`, `use`, `denied`. */
+ action: string;
+ /** `agent:ada` or `user`. */
+ principal: string;
+ /** The machine. */
+ path: string;
+ detail: string;
+}
+
+/** `agents.detail`: the selected agent's home, routines, every grant and the recent audit. */
+export interface AgentDetailInput {
+ home: AgentHomeEntry[];
+ routines: AgentRoutine[];
+ grants: AgentComputerGrant[];
+ audit: AgentAccessAudit[];
+ /** This machine's Space id when it is set up for access (`relay:<id>`). */
+ thisMachine: string | null;
+}
+
+/** `AgentsInput`: everything the core's Agents page reads. */
+export interface AgentsPageInput extends Partial<Omit<AgentDetailInput, "thisMachine">> {
+ agents: PersistentAgent[];
+ file?: AgentOpenFile | null;
+ thisMachine?: string | null;
+}
+
+export type AgentTab = "memory" | "routines" | "access";
+export type RoutineScheduleKind = "every" | "daily" | "weekly";
+
+/** The new-routine form (`RoutineForm`). */
+export interface RoutineForm {
+ title: string;
+ prompt: string;
+ schedule: RoutineScheduleKind;
+ /** Minutes for `every`. */
+ minutes: number;
+ /** `HH:MM` for daily and weekly. */
+ time: string;
+ /** `mon` ... `sun` for weekly. */
+ weekday: string;
+}
+
+/** The command the core asks the host to run (`AgentsRequest`). */
+export type AgentsPageRequest =
+ | { kind: "pause"; name: string }
+ | { kind: "resume"; name: string }
+ | { kind: "load"; name: string }
+ | { kind: "read-file"; path: string }
+ | { kind: "restore"; path: string; version: string }
+ | {
+ kind: "add-routine";
+ agent: string;
+ title: string;
+ prompt: string;
+ every_minutes: number | null;
+ daily_at: string | null;
+ weekly_on: string | null;
+ }
+ | { kind: "set-routine"; id: string; enabled: boolean }
+ | { kind: "remove-routine"; id: string }
+ | { kind: "allow"; agent: string; machine: string }
+ | { kind: "revoke"; agent: string; machine: string };
+
+/** The page's state (`AgentsState`). */
+export interface AgentsPageState {
+ selected?: string | null;
+ tab: AgentTab;
+ openPath?: string | null;
+ form: RoutineForm;
+ busy: boolean;
+ error?: string | null;
+ request?: AgentsPageRequest | null;
+}
+
+/** An input to the page (`AgentsAction`). */
+export type AgentsPageAction =
+ | { type: "select"; name: string }
+ | { type: "set-tab"; tab: AgentTab }
+ | { type: "open-file"; path: string }
+ | { type: "close-file" }
+ | { type: "pause"; name: string }
+ | { type: "resume"; name: string }
+ | { type: "restore"; version: string }
+ | { type: "set-title"; title: string }
+ | { type: "set-prompt"; prompt: string }
+ | { type: "set-schedule"; schedule: RoutineScheduleKind }
+ | { type: "set-minutes"; minutes: number }
+ | { type: "set-time"; time: string }
+ | { type: "set-weekday"; weekday: string }
+ | { type: "add-routine" }
+ | { type: "toggle-routine"; id: string }
+ | { type: "remove-routine"; id: string }
+ | { type: "allow-computer"; machine: string }
+ | { type: "revoke-computer"; machine: string }
+ | { type: "done" }
+ | { type: "failed"; error: string };
+
+/** One line with an id and an optional action (`LineView`). */
+export interface AgentLineView {
+ id: string;
+ text: string;
+ trailing: string;
+ actionLabel?: string | null;
+ secondaryLabel?: string | null;
+ on?: boolean | null;
+}
+
+export interface AgentTabView {
+ tab: AgentTab;
+ label: string;
+ selected: boolean;
+}
+
+/** The open memory file (`FileView`). */
+export interface AgentFileView {
+ path: string;
+ text: string;
+ versions: AgentLineView[];
+ closeLabel: string;
+}
+
+/** The selected agent (`AgentDetailView`). */
+export interface AgentDetailView {
+ name: string;
+ /** `Home agents/ada/, saved 5m ago`. */
+ subtitle: string;
+ tabs: AgentTabView[];
+ memory: AgentLineView[];
+ memoryEmpty: string;
+ file?: AgentFileView | null;
+ routines: AgentLineView[];
+ routinesEmpty: string;
+ form: RoutineForm;
+ /** The schedule choices; `on` marks the form's. */
+ schedules: AgentLineView[];
+ canAddRoutine: boolean;
+ addRoutineLabel: string;
+ access: AgentLineView[];
+ accessEmpty: string;
+ /** `Allow on this computer` when this machine is set up and not granted. */
+ allowThisMachineLabel?: string | null;
+ audit: AgentLineView[];
+ error?: string | null;
+}
+
+/** The page as drawn (`AgentsView`); the detail is what the agent detail shows. */
+export interface AgentsPageView {
+ title: string;
+ detail?: AgentDetailView | null;
+ busy: boolean;
+ error?: string | null;
+ requestText?: string | null;
+}
diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
index d96e34f769..87e634cf18 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
@@ -54,6 +54,124 @@
"checking"
]
},
+ "AgentDetailInput": {
+ "type": "object",
+ "properties": {
+ "home": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "size": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "path",
+ "name",
+ "size"
+ ]
+ }
+ },
+ "routines": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ },
+ "label": {
+ "type": "string"
+ },
+ "enabled": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "id",
+ "title",
+ "label",
+ "enabled"
+ ]
+ }
+ },
+ "grants": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "agent": {
+ "type": "string"
+ },
+ "machine": {
+ "type": "string"
+ },
+ "revoked": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "agent",
+ "machine",
+ "revoked"
+ ]
+ }
+ },
+ "audit": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "tsMs": {
+ "type": "number"
+ },
+ "action": {
+ "type": "string"
+ },
+ "principal": {
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ },
+ "detail": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "tsMs",
+ "action",
+ "principal",
+ "path",
+ "detail"
+ ]
+ }
+ },
+ "thisMachine": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "home",
+ "routines",
+ "grants",
+ "audit",
+ "thisMachine"
+ ]
+ },
"AgentKeysReport": {
"type": "object",
"properties": {
@@ -130,6 +248,52 @@
"unavailable"
]
},
+ "AgentOpenFile": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string"
+ },
+ "text": {
+ "type": "string"
+ },
+ "binary": {
+ "type": "boolean"
+ },
+ "versions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "version": {
+ "type": "string"
+ },
+ "modifiedMs": {
+ "type": "number"
+ },
+ "deleted": {
+ "type": "boolean"
+ },
+ "latest": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "version",
+ "modifiedMs",
+ "deleted",
+ "latest"
+ ]
+ }
+ }
+ },
+ "required": [
+ "path",
+ "text",
+ "binary",
+ "versions"
+ ]
+ },
"AgentSetupRow": {
"type": "object",
"properties": {
@@ -3566,12 +3730,21 @@
"agentKeys.set": {
"$ref": "#/$defs/AgentKeysReport"
},
+ "agents.addRoutine": {
+ "type": "null"
+ },
+ "agents.allowComputer": {
+ "type": "null"
+ },
"agents.configure": {
"type": "array",
"items": {
"$ref": "#/$defs/AgentSetupRow"
}
},
+ "agents.detail": {
+ "$ref": "#/$defs/AgentDetailInput"
+ },
"agents.events": {
"type": "object",
"properties": {
@@ -3690,9 +3863,21 @@
"agents.pause": {
"type": "null"
},
+ "agents.readFile": {
+ "$ref": "#/$defs/AgentOpenFile"
+ },
+ "agents.removeRoutine": {
+ "type": "null"
+ },
+ "agents.restoreFile": {
+ "type": "null"
+ },
"agents.resume": {
"type": "null"
},
+ "agents.revokeComputer": {
+ "type": "null"
+ },
"agents.runs": {
"type": "array",
"items": {
@@ -3744,6 +3929,9 @@
]
}
},
+ "agents.setRoutine": {
+ "type": "null"
+ },
"agents.setup": {
"type": "array",
"items": {
@@ -4899,12 +5087,21 @@
"available"
]
},
+ "agents.addRoutine": {
+ "type": "null"
+ },
+ "agents.allowComputer": {
+ "type": "null"
+ },
"agents.configure": {
"type": "array",
"items": {
"$ref": "#/$defs/AgentSetupRow"
}
},
+ "agents.detail": {
+ "$ref": "#/$defs/AgentDetailInput"
+ },
"agents.events": {
"type": "object",
"properties": {
@@ -5021,7 +5218,19 @@
}
},
"agents.pause": {},
+ "agents.readFile": {
+ "$ref": "#/$defs/AgentOpenFile"
+ },
+ "agents.removeRoutine": {
+ "type": "null"
+ },
+ "agents.restoreFile": {
+ "type": "null"
+ },
"agents.resume": {},
+ "agents.revokeComputer": {
+ "type": "null"
+ },
"agents.runs": {
"type": "array",
"items": {
@@ -5073,6 +5282,9 @@
]
}
},
+ "agents.setRoutine": {
+ "type": "null"
+ },
"agents.setup": {
"type": "array",
"items": {
diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
index 43a484e8d0..c28597be43 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
@@ -22,7 +22,7 @@
* contract test fails when it is out of date.
*/
-import type { AgentEventsPage, AgentSetupRow, PersistentAgent, SpaceAgentRun } from "./agents";
+import type { AgentDetailInput, AgentEventsPage, AgentOpenFile, AgentSetupRow, PersistentAgent, SpaceAgentRun } from "./agents";
import type { DeviceInput, DevicesInput, EnrollResult, MachineAccessNotice, PairingCode } from "./devices";
import type {
CancelOutcome,
@@ -567,6 +567,25 @@ const KvGrantShape = ref(
const hostStatusOrNull = HostStatusShape;
const agentSetupRows = list(AgentSetupRowShape);
+const AgentDetailShape = ref(
+ "AgentDetailInput",
+ obj<AgentDetailInput>()({
+ home: list(object({ path: str, name: str, size: num })),
+ routines: list(object({ id: str, title: str, label: str, enabled: bool })),
+ grants: list(object({ agent: str, machine: str, revoked: bool })),
+ audit: list(object({ tsMs: num, action: str, principal: str, path: str, detail: str })),
+ thisMachine: nullable(str),
+ }),
+);
+const AgentOpenFileShape = ref(
+ "AgentOpenFile",
+ obj<AgentOpenFile>()({
+ path: str,
+ text: str,
+ binary: bool,
+ versions: list(object({ version: str, modifiedMs: num, deleted: bool, latest: bool })),
+ }),
+);
const shares = list(ShareShape);
export const OP_SHAPES: Record<OpName, Schema> = {
@@ -634,6 +653,14 @@ export const OP_SHAPES: Record<OpName, Schema> = {
"agents.resume": nul,
"agents.setup": agentSetupRows,
"agents.configure": agentSetupRows,
+ "agents.detail": AgentDetailShape,
+ "agents.readFile": AgentOpenFileShape,
+ "agents.restoreFile": nul,
+ "agents.addRoutine": nul,
+ "agents.setRoutine": nul,
+ "agents.removeRoutine": nul,
+ "agents.allowComputer": nul,
+ "agents.revokeComputer": nul,
"spaces.createOptions": NewSpaceOptionsShape,
"spaces.add": SpaceRowShape,
@@ -997,6 +1024,14 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {
"agents.setup": agentSetupRows,
"agents.configure": agentSetupRows,
"agents.setupDriver": OP_SHAPES["agents.setupDriver"],
+ "agents.detail": AgentDetailShape,
+ "agents.readFile": AgentOpenFileShape,
+ "agents.restoreFile": nul,
+ "agents.addRoutine": nul,
+ "agents.setRoutine": nul,
+ "agents.removeRoutine": nul,
+ "agents.allowComputer": nul,
+ "agents.revokeComputer": nul,
"agentKeys.list": AgentKeysWire,
"agentKeys.set": AgentKeysWire,
"agentKeys.remove": AgentKeysWire,
diff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.ts
index 74a2554e29..0ae903e5f4 100644
--- a/apps/cua-spaces-web/src/bridge/coverage.ts
+++ b/apps/cua-spaces-web/src/bridge/coverage.ts
@@ -26,6 +26,7 @@
import { NEW_SPACE_COVERAGE } from "./ops/new-space";
import { SHARE_COVERAGE } from "./ops/share";
+import { AGENT_DETAIL_COVERAGE } from "./ops/agent-detail";
import { AGENT_KEYS_COVERAGE } from "./ops/agent-keys";
import { KEYVAULT_MANAGE_COVERAGE } from "./ops/keyvault-manage";
import { KEYVAULT_SETUP_COVERAGE } from "./ops/keyvault-setup";
@@ -119,6 +120,7 @@ export const HOST_COVERAGE = {
"agents.resume": { webkit: { methods: ["agents.resume"] }, tauri: ["agents_tool"] },
"agents.setup": { webkit: { methods: ["agents.setup"] }, tauri: ["agent_setup_detect"] },
"agents.configure": { webkit: { methods: ["agents.configure"] }, tauri: ["agent_setup_configure"] },
+ ...AGENT_DETAIL_COVERAGE,
...NEW_SPACE_COVERAGE,
...TELEPORT_COVERAGE,
...SHARE_COVERAGE,
diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.ts
index 95ce809716..912881eed4 100644
--- a/apps/cua-spaces-web/src/bridge/index.ts
+++ b/apps/cua-spaces-web/src/bridge/index.ts
@@ -29,6 +29,7 @@ export {
type SpacesHook,
} from "./hooks";
+export { useAgentDetail, type AgentDetailHook } from "./agent-detail";
export type { BridgeMode, DataAdapter } from "./adapter";
export { HostError, UnsupportedOperationError, isNativeHost, isUnsupported } from "./adapter";
export { createAdapter, createDemoAdapter, createElectronAdapter, createTauriAdapter, createWebkitAdapter } from "./adapters";
diff --git a/apps/cua-spaces-web/src/bridge/ops/agent-detail.ts b/apps/cua-spaces-web/src/bridge/ops/agent-detail.ts
new file mode 100644
index 0000000000..649f4f90e9
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/ops/agent-detail.ts
@@ -0,0 +1,201 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * One persistent agent's Memory, Routines and Access to this computer: the
+ * commands the app core's Agents page asks for (`AgentsRequest` in
+ * `cua-spaces-app-core/src/persistent.rs`), one operation each. Every one is
+ * a daemon Spaces tool the SwiftUI app's `PersistentModel.send` already
+ * calls; the page reduces and draws with the core (`agent-detail.ts`).
+ *
+ * | Operation | Daemon tools | SwiftUI / Electron host |
+ * |---|---|---|
+ * | `agents.detail {name}` | `volume_ls` (the home, recursively), `routine_list`, `computer_access_list` (audit 20) | `PersistentModel.detail` |
+ * | `agents.readFile {path}` | `volume_read` + `volume_history` | `PersistentModel.readFile` |
+ * | `agents.restoreFile {path, version}` | `volume_restore` | `PersistentModel.perform(.restore)` |
+ * | `agents.addRoutine {agent, title, prompt, everyMinutes?, dailyAt?, weeklyOn?}` | `routine_add` | `.addRoutine` |
+ * | `agents.setRoutine {id, enabled}` | `routine_set_enabled` | `.setRoutine` |
+ * | `agents.removeRoutine {id}` | `routine_remove` | `.removeRoutine` |
+ * | `agents.allowComputer {agent, machine}` | `computer_access_grant` (the daemon asks for presence) | `.allow` |
+ * | `agents.revokeComputer {agent, machine}` | `computer_access_revoke` | `.revoke` |
+ *
+ * The SwiftUI and Electron hosts answer `agents.detail` and `agents.readFile`
+ * as the core's input records (camelCase); Tauri maps the tools' JSON here.
+ */
+
+import type { OpCoverage } from "../coverage";
+import type { AgentDetailInput, AgentOpenFile } from "../contracts/agents";
+import type { OpArgs, OpResult } from "../protocol";
+
+type Ok = null;
+
+declare module "../protocol" {
+ interface HostOperations {
+ /** The agent's home files, its routines, every computer grant and the recent audit. */
+ "agents.detail": { args: { name: string }; result: AgentDetailInput };
+ /** A home file's text and versions. */
+ "agents.readFile": { args: { path: string }; result: AgentOpenFile };
+ "agents.restoreFile": { args: { path: string; version: string }; result: Ok };
+ /** Exactly one of `everyMinutes`, `dailyAt` (`HH:MM`) and `weeklyOn` (`mon HH:MM`). */
+ "agents.addRoutine": {
+ args: { agent: string; title: string; prompt: string; everyMinutes: number | null; dailyAt: string | null; weeklyOn: string | null };
+ result: Ok;
+ };
+ "agents.setRoutine": { args: { id: string; enabled: boolean }; result: Ok };
+ "agents.removeRoutine": { args: { id: string }; result: Ok };
+ /** Lets the agent use `machine` (the daemon asks for presence first). */
+ "agents.allowComputer": { args: { agent: string; machine: string }; result: Ok };
+ "agents.revokeComputer": { args: { agent: string; machine: string }; result: Ok };
+ }
+}
+
+export const AGENT_DETAIL_OPERATIONS = [
+ "agents.detail",
+ "agents.readFile",
+ "agents.restoreFile",
+ "agents.addRoutine",
+ "agents.setRoutine",
+ "agents.removeRoutine",
+ "agents.allowComputer",
+ "agents.revokeComputer",
+] as const;
+export type AgentDetailOp = (typeof AGENT_DETAIL_OPERATIONS)[number];
+
+/** The SwiftUI host and the Electron shell route each under its own name. */
+export const AGENT_DETAIL_WEBKIT_METHODS = AGENT_DETAIL_OPERATIONS;
+
+export const AGENT_DETAIL_COVERAGE = {
+ "agents.detail": { webkit: { methods: ["agents.detail"] }, tauri: ["agents_tool"] },
+ "agents.readFile": { webkit: { methods: ["agents.readFile"] }, tauri: ["agents_tool"] },
+ "agents.restoreFile": { webkit: { methods: ["agents.restoreFile"] }, tauri: ["agents_tool"] },
+ "agents.addRoutine": { webkit: { methods: ["agents.addRoutine"] }, tauri: ["agents_tool"] },
+ "agents.setRoutine": { webkit: { methods: ["agents.setRoutine"] }, tauri: ["agents_tool"] },
+ "agents.removeRoutine": { webkit: { methods: ["agents.removeRoutine"] }, tauri: ["agents_tool"] },
+ "agents.allowComputer": { webkit: { methods: ["agents.allowComputer"] }, tauri: ["agents_tool"] },
+ "agents.revokeComputer": { webkit: { methods: ["agents.revokeComputer"] }, tauri: ["agents_tool"] },
+} as const satisfies Record<AgentDetailOp, OpCoverage>;
+
+/** Arguments that take each operation down its usual path (the coverage test). */
+export const AGENT_DETAIL_ARGS: { [K in AgentDetailOp]: OpArgs<K> } = {
+ "agents.detail": { name: "ada" },
+ "agents.readFile": { path: "agents/ada/notes.md" },
+ "agents.restoreFile": { path: "agents/ada/notes.md", version: "v1" },
+ "agents.addRoutine": { agent: "ada", title: "Inbox", prompt: "Sort my inbox", everyMinutes: null, dailyAt: "08:00", weeklyOn: null },
+ "agents.setRoutine": { id: "r1", enabled: false },
+ "agents.removeRoutine": { id: "r1" },
+ "agents.allowComputer": { agent: "ada", machine: "relay:this-mac" },
+ "agents.revokeComputer": { agent: "ada", machine: "relay:this-mac" },
+};
+
+/* ---- The tools' JSON as the core reads it (PersistentModel.loadDetail) ------------- */
+
+type Json = Record<string, unknown>;
+const rows = (v: unknown, key: string): Json[] => {
+ const a = v && typeof v === "object" ? (v as Json)[key] : undefined;
+ return Array.isArray(a) ? a.filter((x): x is Json => !!x && typeof x === "object") : [];
+};
+const str = (v: unknown) => (typeof v === "string" ? v : "");
+const num = (v: unknown) => (typeof v === "number" ? v : 0);
+
+/** At most 50 folders and 500 files, as the native hosts read a home. */
+const MAX_FOLDERS = 50;
+const MAX_FILES = 500;
+
+type Tool = (tool: string, args: Json) => Promise<unknown>;
+
+/** `agents.detail` from the daemon's tools (what the native hosts do in Swift and in the Electron main process). */
+export async function agentDetailFromTools(tool: Tool, name: string, thisMachine: string | null): Promise<AgentDetailInput> {
+ const home: AgentDetailInput["home"] = [];
+ const queue = [`agents/${name}/`];
+ for (let folders = 0; queue.length && folders < MAX_FOLDERS && home.length < MAX_FILES; folders++) {
+ for (const e of rows(await tool("volume_ls", { path: queue.shift()! }), "entries")) {
+ if (e.folder === true) queue.push(str(e.path));
+ else home.push({ path: str(e.path), name: str(e.name), size: num(e.size) });
+ }
+ }
+ const routines = rows(await tool("routine_list", { agent: name }), "routines").map((r) => ({
+ id: str(r.id),
+ title: str(r.title),
+ label: str(r.label),
+ enabled: typeof r.isEnabled === "boolean" ? r.isEnabled : true,
+ }));
+ const access = await tool("computer_access_list", { audit: 20 });
+ return {
+ home,
+ routines,
+ grants: rows(access, "grants").map((g) => ({ agent: str(g.agent), machine: str(g.machine), revoked: g.revoked === true })),
+ audit: rows(access, "audit").map((a) => ({ tsMs: num(a.ts_ms), action: str(a.action), principal: str(a.principal), path: str(a.path), detail: str(a.detail) })),
+ thisMachine,
+ };
+}
+
+/** `agents.readFile` from `volume_read` and `volume_history`. */
+export async function agentFileFromTools(tool: Tool, path: string): Promise<AgentOpenFile> {
+ const [file, history] = await Promise.all([tool("volume_read", { path }), tool("volume_history", { path })]);
+ const f = (file ?? {}) as Json;
+ const binary = f.encoding === "base64";
+ return {
+ path,
+ text: binary ? "" : str(f.content),
+ binary,
+ versions: rows(history, "versions").map((v) => ({ version: str(v.version), modifiedMs: num(v.modified_ms), deleted: v.deleted === true, latest: v.latest === true })),
+ };
+}
+
+/** `routine_add`'s arguments: only the schedule field that is set. */
+export function routineAddArgs(a: OpArgs<"agents.addRoutine">): Json {
+ const out: Json = { agent: a.agent, title: a.title, prompt: a.prompt };
+ if (a.everyMinutes !== null && a.everyMinutes !== undefined) out.every_minutes = a.everyMinutes;
+ if (a.dailyAt) out.daily_at = a.dailyAt;
+ if (a.weeklyOn) out.weekly_on = a.weeklyOn;
+ return out;
+}
+
+type Handlers = { [K in AgentDetailOp]: (args: OpArgs<K>) => Promise<OpResult<K>> };
+type Invoke = <T>(cmd: string, args?: Record<string, unknown>) => Promise<T>;
+type Request = <T>(method: AgentDetailOp, args?: Record<string, unknown>) => Promise<T>;
+
+/** Each mutation: one tool, then nothing to answer. */
+function mutations(run: (tool: string, args: Json) => Promise<unknown>): Omit<Handlers, "agents.detail" | "agents.readFile"> {
+ const done = (tool: string, args: Json) => run(tool, args).then(() => null);
+ return {
+ "agents.restoreFile": ({ path, version }) => done("volume_restore", { path, version }),
+ "agents.addRoutine": (args) => done("routine_add", routineAddArgs(args)),
+ "agents.setRoutine": ({ id, enabled }) => done("routine_set_enabled", { id, enabled }),
+ "agents.removeRoutine": ({ id }) => done("routine_remove", { id }),
+ "agents.allowComputer": ({ agent, machine }) => done("computer_access_grant", { agent, machine }),
+ "agents.revokeComputer": ({ agent, machine }) => done("computer_access_revoke", { agent, machine }),
+ };
+}
+
+/** Tauri: the tools through `agents_tool` (all on its allow-list). The Tauri
+ * shell does not know this machine's relay Space, so it offers no "Allow". */
+export function tauriAgentDetailOps(invoke: Invoke): Handlers {
+ const tool: Tool = (name, args) => invoke("agents_tool", { tool: name, args });
+ return {
+ "agents.detail": ({ name }) => agentDetailFromTools(tool, name, null),
+ "agents.readFile": ({ path }) => agentFileFromTools(tool, path),
+ ...mutations(tool),
+ };
+}
+
+/** The SwiftUI host and the Electron shell: each method keeps its operation's name and arguments. */
+export function webkitAgentDetailOps(request: Request): Handlers {
+ const none = (op: AgentDetailOp) => async (args: object) => {
+ await request(op, { ...args });
+ return null;
+ };
+ return {
+ "agents.detail": async ({ name }) => {
+ const d = (await request<Partial<AgentDetailInput> | null>("agents.detail", { name })) ?? {};
+ return { home: d.home ?? [], routines: d.routines ?? [], grants: d.grants ?? [], audit: d.audit ?? [], thisMachine: d.thisMachine ?? null };
+ },
+ "agents.readFile": ({ path }) => request("agents.readFile", { path }),
+ "agents.restoreFile": none("agents.restoreFile"),
+ "agents.addRoutine": none("agents.addRoutine"),
+ "agents.setRoutine": none("agents.setRoutine"),
+ "agents.removeRoutine": none("agents.removeRoutine"),
+ "agents.allowComputer": none("agents.allowComputer"),
+ "agents.revokeComputer": none("agents.revokeComputer"),
+ };
+}
diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.ts
index 90ef79d44a..ce848d2cee 100644
--- a/apps/cua-spaces-web/src/bridge/protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/protocol.ts
@@ -34,6 +34,7 @@ import type { SpaceOs, SpaceRow } from "./contracts/spaces";
import { NEW_SPACE_OPERATIONS, type NewSpaceOperations } from "./ops/new-space";
import { SHARE_OPERATIONS, type ShareOperations } from "./ops/share";
import { AGENT_KEYS_OPERATIONS } from "./ops/agent-keys";
+import { AGENT_DETAIL_OPERATIONS } from "./ops/agent-detail";
import { KEYVAULT_MANAGE_OPERATIONS } from "./ops/keyvault-manage";
import { KEYVAULT_SETUP_OPERATIONS } from "./ops/keyvault-setup";
import { TELEPORT_EVENTS, TELEPORT_OPERATIONS, type TeleportHostEvent, type TeleportOperations } from "./ops/teleport";
@@ -259,6 +260,7 @@ export const OPERATIONS = [
"agents.resume",
"agents.setup",
"agents.configure",
+ ...AGENT_DETAIL_OPERATIONS,
...NEW_SPACE_OPERATIONS,
...TELEPORT_OPERATIONS,
...SHARE_OPERATIONS,
diff --git a/apps/cua-spaces-web/src/bridge/store.ts b/apps/cua-spaces-web/src/bridge/store.ts
index 872addb192..5d777943c9 100644
--- a/apps/cua-spaces-web/src/bridge/store.ts
+++ b/apps/cua-spaces-web/src/bridge/store.ts
@@ -117,6 +117,8 @@ export interface AgentSummary {
/** The run the detail opens: its current run, else its latest in its Space. */
run: RunRef | null;
lastError: string | null;
+ /** The host's record, as the core's Agents page reads it (the detail's Memory, Routines and Access). */
+ record: PersistentAgent;
}
export interface AgentRunSummary extends SpaceAgentRun {
@@ -1023,6 +1025,7 @@ export class BridgeStore {
lastActivityMs: Math.max(a.savedMs, current?.status === "running" ? now : 0),
run: latest ? { spaceId: latest.spaceId, runId: latest.runId } : null,
lastError: a.lastError ?? null,
+ record: a,
},
];
});
diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
index 811548f587..99a5b17e89 100644
--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
@@ -30,6 +30,7 @@
*/
import type { MachineAccessNotice } from "./contracts/devices";
+import { AGENT_DETAIL_WEBKIT_METHODS } from "./ops/agent-detail";
import { AGENT_KEYS_WEBKIT_METHODS } from "./ops/agent-keys";
import { KEYVAULT_MANAGE_WEBKIT_METHODS } from "./ops/keyvault-manage";
import { KEYVAULT_SETUP_WEBKIT_METHODS } from "./ops/keyvault-setup";
@@ -64,6 +65,7 @@ export const WEBKIT_METHODS = [
"agents.resume",
"agents.setup",
"agents.configure",
+ ...AGENT_DETAIL_WEBKIT_METHODS,
...AGENT_KEYS_WEBKIT_METHODS,
...KEYVAULT_SETUP_WEBKIT_METHODS,
...KEYVAULT_MANAGE_WEBKIT_METHODS,
diff --git a/apps/cua-spaces-web/src/components/agents/agent-panels.tsx b/apps/cua-spaces-web/src/components/agents/agent-panels.tsx
new file mode 100644
index 0000000000..b69b164076
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/agents/agent-panels.tsx
@@ -0,0 +1,211 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import type { ReactNode } from "react";
+
+import type { AgentDetailHook, AgentDetailView, AgentLineView, AgentTab, RoutineScheduleKind } from "@/bridge";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Select } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+
+const WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const;
+
+/**
+ * A persistent agent's Memory, Routines and Access to this computer, as the
+ * SwiftUI app's Agents page draws them (`AgentsViews.swift`). Every word in
+ * the lists and buttons is the app core's (`AgentDetailView`).
+ */
+export function AgentPanel({ tab, detail }: { tab: AgentTab; detail: AgentDetailHook }) {
+ const view = detail.view;
+ if (!view) return <div className="flex-1" />;
+ return (
+ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4" data-agent-panel={tab}>
+ {tab === "memory" ? <Memory view={view} detail={detail} /> : tab === "routines" ? <Routines view={view} detail={detail} /> : <Access view={view} detail={detail} />}
+ {detail.error ? (
+ <p className="mt-3 px-1 text-[13px] text-destructive" role="alert" data-agent-detail-error="">
+ {detail.error}
+ </p>
+ ) : null}
+ </div>
+ );
+}
+
+function Memory({ view, detail }: { view: AgentDetailView; detail: AgentDetailHook }) {
+ const { act, busy } = detail;
+ const f = view.file;
+ if (f) {
+ return (
+ <>
+ <Section title={f.path} kind="file">
+ <pre className="max-h-72 overflow-auto px-4 py-3 font-mono text-xs whitespace-pre-wrap select-text" data-agent-file-text="">
+ {f.text}
+ </pre>
+ </Section>
+ <Section kind="versions">
+ {f.versions.map((l) => (
+ <Line key={l.id} line={l} busy={busy} onAction={() => act({ type: "restore", version: l.id })} />
+ ))}
+ </Section>
+ <Button variant="outline" size="sm" onClick={() => act({ type: "close-file" })} data-agent-file-close="">
+ {f.closeLabel}
+ </Button>
+ </>
+ );
+ }
+ return (
+ <Section kind="memory">
+ {view.memory.length === 0 ? <Empty>{view.memoryEmpty}</Empty> : null}
+ {view.memory.map((l) => (
+ <Line key={l.id} line={l} busy={busy} onOpen={() => act({ type: "open-file", path: l.id })} />
+ ))}
+ </Section>
+ );
+}
+
+function Routines({ view, detail }: { view: AgentDetailView; detail: AgentDetailHook }) {
+ const { act, busy } = detail;
+ const form = view.form;
+ const schedules = view.schedules.map((s) => ({ value: s.id as RoutineScheduleKind, label: s.text }));
+ return (
+ <>
+ <Section kind="routines">
+ {view.routines.length === 0 ? <Empty>{view.routinesEmpty}</Empty> : null}
+ {view.routines.map((l) => (
+ <Line
+ key={l.id}
+ line={l}
+ busy={busy}
+ onToggle={() => act({ type: "toggle-routine", id: l.id })}
+ onAction={() => act({ type: "remove-routine", id: l.id })}
+ />
+ ))}
+ </Section>
+ <Section kind="new-routine">
+ <Field label="Title">
+ <Input value={form.title} onValueChange={(title) => act({ type: "set-title", title })} data-routine-title="" />
+ </Field>
+ <Field label="Prompt">
+ <Input value={form.prompt} onValueChange={(prompt) => act({ type: "set-prompt", prompt })} data-routine-prompt="" />
+ </Field>
+ <Field label="Schedule">
+ <Select aria-label="Schedule" value={form.schedule} options={schedules} onValueChange={(schedule) => act({ type: "set-schedule", schedule })} />
+ </Field>
+ {form.schedule === "every" ? (
+ <Field label="Minutes">
+ <Input
+ type="number"
+ min={1}
+ max={1440}
+ className="w-24"
+ value={String(form.minutes)}
+ onValueChange={(v) => act({ type: "set-minutes", minutes: Math.min(1440, Math.max(1, Math.floor(Number(v) || 1))) })}
+ data-routine-minutes=""
+ />
+ </Field>
+ ) : (
+ <Field label="Time">
+ <Input type="time" className="w-32" value={form.time} onValueChange={(time) => act({ type: "set-time", time })} data-routine-time="" />
+ </Field>
+ )}
+ {form.schedule === "weekly" ? (
+ <Field label="Day">
+ <Select aria-label="Day" value={form.weekday} options={WEEKDAYS.map((d) => ({ value: d, label: d }))} onValueChange={(weekday) => act({ type: "set-weekday", weekday })} />
+ </Field>
+ ) : null}
+ <div className="flex justify-end px-4 py-2.5">
+ <Button size="sm" disabled={!view.canAddRoutine} onClick={() => act({ type: "add-routine" })} data-routine-add="">
+ {view.addRoutineLabel}
+ </Button>
+ </div>
+ </Section>
+ </>
+ );
+}
+
+function Access({ view, detail }: { view: AgentDetailView; detail: AgentDetailHook }) {
+ const { act, busy, thisMachine } = detail;
+ return (
+ <>
+ <Section kind="access">
+ {view.access.length === 0 ? <Empty>{view.accessEmpty}</Empty> : null}
+ {view.access.map((l) => (
+ <Line key={l.id} line={l} busy={busy} onAction={() => act({ type: "revoke-computer", machine: l.id })} />
+ ))}
+ {view.allowThisMachineLabel && thisMachine ? (
+ <div className="flex justify-end px-4 py-2.5">
+ <Button size="sm" disabled={busy} onClick={() => act({ type: "allow-computer", machine: thisMachine })} data-agent-allow="">
+ {view.allowThisMachineLabel}
+ </Button>
+ </div>
+ ) : null}
+ </Section>
+ {view.audit.length > 0 ? (
+ <Section title="Audit" kind="audit">
+ {view.audit.map((l) => (
+ <Line key={l.id} line={l} busy={busy} />
+ ))}
+ </Section>
+ ) : null}
+ </>
+ );
+}
+
+function Section({ title, kind, children }: { title?: string; kind: string; children: ReactNode }) {
+ return (
+ <section className="mb-4" data-agent-section={kind}>
+ {title ? <h3 className="mb-2 truncate px-1 text-xs font-semibold text-muted-foreground">{title}</h3> : null}
+ <div className="divide-y overflow-hidden rounded-xl border bg-card shadow-xs">{children}</div>
+ </section>
+ );
+}
+
+function Empty({ children }: { children: ReactNode }) {
+ return <p className="px-4 py-3 text-[13px] text-muted-foreground">{children}</p>;
+}
+
+function Field({ label, children }: { label: string; children: ReactNode }) {
+ return (
+ <label className="flex min-h-11 items-center gap-4 px-4 py-2">
+ <span className="w-20 shrink-0 text-[13px]">{label}</span>
+ <span className="flex min-w-0 flex-1 justify-end">{children}</span>
+ </label>
+ );
+}
+
+/** A `LineView`: its text (a link when it opens), a muted trailing part, a switch and a button. */
+function Line({ line, busy, onOpen, onToggle, onAction }: { line: AgentLineView; busy: boolean; onOpen?: () => void; onToggle?: () => void; onAction?: () => void }) {
+ return (
+ <div className="flex min-h-11 items-center gap-4 px-4 py-2" data-agent-line={line.id}>
+ {onOpen ? (
+ <button
+ type="button"
+ disabled={busy}
+ onClick={onOpen}
+ className="min-w-0 flex-1 cursor-default truncate text-left text-[13px] text-brand outline-none hover:underline focus-visible:underline disabled:opacity-60"
+ title={line.text}
+ data-line-text=""
+ >
+ {line.text}
+ </button>
+ ) : (
+ <span className="min-w-0 flex-1 truncate text-[13px]" title={line.text} data-line-text="">
+ {line.text}
+ </span>
+ )}
+ {line.trailing ? (
+ <span className="max-w-[45%] shrink-0 truncate text-xs text-muted-foreground" title={line.trailing} data-line-trailing="">
+ {line.trailing}
+ </span>
+ ) : null}
+ {line.on !== null && line.on !== undefined && onToggle ? (
+ <Switch aria-label={line.text} checked={line.on} disabled={busy} onCheckedChange={onToggle} data-line-toggle="" />
+ ) : null}
+ {line.actionLabel && onAction ? (
+ <Button variant="outline" size="sm" disabled={busy} onClick={onAction} data-line-action="">
+ {line.actionLabel}
+ </Button>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/cua-spaces-web/src/lib/agents.test.ts b/apps/cua-spaces-web/src/lib/agents.test.ts
index b51b2d29e0..f7660eade1 100644
--- a/apps/cua-spaces-web/src/lib/agents.test.ts
+++ b/apps/cua-spaces-web/src/lib/agents.test.ts
@@ -20,6 +20,7 @@ const agent = (name: string, state: AgentSummary["state"], run: AgentSummary["ru
lastActivityMs: 0,
run,
lastError: null,
+ record: { name, harness: "claude-code", space: "local:dev", paused: state === "paused", spaceState: "running", savedMs: 0 },
});
const run = (runId: string, agentName: string | null = null): AgentRunSummary => ({
diff --git a/apps/cua-spaces-web/src/routes/agents/index.tsx b/apps/cua-spaces-web/src/routes/agents/index.tsx
index 8e6200199e..19a018badf 100644
--- a/apps/cua-spaces-web/src/routes/agents/index.tsx
+++ b/apps/cua-spaces-web/src/routes/agents/index.tsx
@@ -7,14 +7,17 @@ import { useEffect, useState } from "react";
import {
isUnsupported,
+ useAgentDetail,
useAgents,
useAgentTimeline,
useSession,
type AgentRunSummary,
type AgentsData,
type AgentSummary,
+ type AgentTab,
type AgentTimeline,
} from "@/bridge";
+import { AgentPanel } from "@/components/agents/agent-panels";
import { ConnectAgentDialog } from "@/components/agents/connect-dialog";
import { Timeline } from "@/components/agents/timeline";
import { EmptyState, PageHeader } from "@/components/page";
@@ -305,8 +308,11 @@ function AgentDetail({ agent, run, runRef }: { agent: AgentSummary | null; run:
const { pauseAgent, resumeAgent } = useAgents();
const { openExternal } = useSession();
const timeline = useAgentTimeline(runRef);
+ const detail = useAgentDetail(agent?.record ?? null);
const now = useNow();
const [busy, setBusy] = useState(false);
+ // The run's conversation, or one of the core's tabs (Memory, Routines, Access).
+ const [pane, setPane] = useState<"run" | AgentTab>("run");
const harness = agent?.harnessName ?? run?.harnessName ?? "";
const space = spaceLabel(agent?.spaceName ?? run?.spaceName ?? "");
@@ -363,11 +369,56 @@ function AgentDetail({ agent, run, runRef }: { agent: AgentSummary | null; run:
{needsAgentKey(agent.lastError) ? <AgentKeysLink size="sm" /> : null}
</div>
) : null}
- <DetailBody agent={agent} run={run} hasRun={runRef !== null} timeline={timeline} onOpenLink={(url) => void openExternal(url)} />
+ {detail.view ? (
+ <AgentTabs
+ tabs={[{ tab: "run", label: "Conversation" }, ...detail.view.tabs]}
+ selected={pane}
+ onSelect={(tab) => {
+ setPane(tab);
+ if (tab !== "run") detail.act({ type: "set-tab", tab });
+ }}
+ />
+ ) : null}
+ {pane !== "run" && detail.view ? (
+ <AgentPanel tab={pane} detail={detail} />
+ ) : (
+ <DetailBody agent={agent} run={run} hasRun={runRef !== null} timeline={timeline} onOpenLink={(url) => void openExternal(url)} />
+ )}
</>
);
}
+function AgentTabs({
+ tabs,
+ selected,
+ onSelect,
+}: {
+ tabs: { tab: "run" | AgentTab; label: string }[];
+ selected: "run" | AgentTab;
+ onSelect: (tab: "run" | AgentTab) => void;
+}) {
+ return (
+ <div role="tablist" aria-label="Agent" className="flex shrink-0 gap-1 border-b bg-card px-4">
+ {tabs.map((t) => (
+ <button
+ key={t.tab}
+ type="button"
+ role="tab"
+ aria-selected={selected === t.tab}
+ onClick={() => onSelect(t.tab)}
+ data-agent-tab={t.tab}
+ className={cn(
+ "-mb-px cursor-default border-b-2 border-transparent px-2 py-2 text-xs font-medium text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:text-foreground",
+ selected === t.tab && "border-foreground text-foreground",
+ )}
+ >
+ {t.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
function DetailBody({
agent,
run,
@@ -385,7 +436,7 @@ function DetailBody({
return (
<Centered title={agent?.state === "paused" ? `${agent.name} is paused` : "No runs yet"}>
{agent?.state === "paused"
- ? `Its home is saved and its routines are on hold. Resume it to let it work in ${spaceLabel(agent.spaceName)} again.`
+ ? `Its home is saved. Resume it to let it work in ${spaceLabel(agent.spaceName)} again.`
: `Runs show up here once ${agent?.name ?? "this agent"} starts working.`}
</Centered>
);