Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(spaces): pick up where you left off in the first run (CUA-3319) (#6463)
Francesco Bonaccia79ecf8dddf2
diff --git a/apps/cua-spaces-desktop/src/bridge/agent-threads.ts b/apps/cua-spaces-desktop/src/bridge/agent-threads.tsnew file mode 100644index 0000000000..9dc77b9ba8--- /dev/null+++ b/apps/cua-spaces-desktop/src/bridge/agent-threads.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// "Pick up where you left off" (CUA-3319): `agents.recentThreads` and+// `agents.threadHistory`, the daemon's person-only tools `agent_threads` and+// `agent_thread_read`, as the SwiftUI host runs them. The arguments map with+// the web bridge's own `AGENT_THREADS_TOOLS` and the answer is the tool's+// JSON untouched (the page maps it). A daemon without the tools answers+// `unsupported`, and the Ready screen hides the list.+import {+ AGENT_THREADS_OPERATIONS,+ AGENT_THREADS_TOOLS,+ isMissingAgentThreadsTool,+ type AgentThreadsOpName,+} from "../../../cua-spaces-web/src/bridge/ops/agent-threads";+import { string } from "./args";+import type { BridgeContext } from "./context";+import { Failure, type Handlers } from "./host";+import { daemonTool } from "./host-parts";++type Tool = (name: string, args?: Record<string, unknown>) => Promise<unknown>;++/** `tool`: the daemon's tools (tests pass their own). */+export function agentThreadsMethods(ctx: BridgeContext, tool: () => Tool = () => daemonTool(ctx, "Your agents' chats")): Handlers {+ const run = (op: AgentThreadsOpName) => async (args: Record<string, unknown>) => {+ if (op === "agents.threadHistory") {+ string(args, "agent");+ string(args, "id");+ }+ const call = AGENT_THREADS_TOOLS[op] as { tool: string; args: (a: never) => Record<string, unknown> };+ try {+ return await tool()(call.tool, call.args(args as never));+ } catch (e) {+ if (isMissingAgentThreadsTool(e)) throw Failure.unsupported("This cua daemon can't list your agents' chats; update Cua");+ throw e;+ }+ };+ return Object.fromEntries(AGENT_THREADS_OPERATIONS.map((op) => [op, run(op)])) as Handlers;+}diff --git a/apps/cua-spaces-desktop/src/bridge/agents.ts b/apps/cua-spaces-desktop/src/bridge/agents.tsindex 9501377f99..c0065dd76b 100644--- a/apps/cua-spaces-desktop/src/bridge/agents.ts+++ b/apps/cua-spaces-desktop/src/bridge/agents.ts@@ -80,6 +80,10 @@ export function agentsMethods({ model }: BridgeContext): Handlers {branch: optionalString(args, "branch"),model: optionalString(args, "model"),envFromHost: env,+ // A continued chat (CUA-3319): the agent's own session, in its own folder.+ cwd: optionalString(args, "cwd"),+ resumeSession: optionalString(args, "resumeSession"),+ resumeContext: optionalString(args, "resumeContext"),});},"agents.message": async (args) => {diff --git a/apps/cua-spaces-desktop/src/bridge/index.ts b/apps/cua-spaces-desktop/src/bridge/index.tsindex c00a0303ed..e802a0a127 100644--- a/apps/cua-spaces-desktop/src/bridge/index.ts+++ b/apps/cua-spaces-desktop/src/bridge/index.ts@@ -33,6 +33,7 @@ import { linksMethods } from "./links";import { cliMethods } from "./cli";import { ciMethods } from "./ci";import { threadMethods } from "./thread";+import { agentThreadsMethods } from "./agent-threads";import { relayUsageMethods } from "./relay-usage";import { resourcesMethods } from "./resources";import { sessionMethods, sessionState } from "./session";@@ -84,6 +85,7 @@ export const AREAS = [cliMethods,ciMethods,threadMethods,+ agentThreadsMethods,presenceMethods,];diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.tsindex ad3c4d18fb..ff7515c46d 100644--- a/apps/cua-spaces-desktop/src/bridge/methods.ts+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts@@ -18,7 +18,7 @@ export const METHODS = ["machines.list", "host.status","agents.list", "agents.runs", "agents.events", "agents.pause", "agents.resume","agents.setup", "agents.configure", "agents.signIn",- "agents.status", "agents.connect", "agents.disconnect", "agents.signInStart", "agents.signInWait", "agents.start", "agents.message",+ "agents.status", "agents.connect", "agents.disconnect", "agents.recentThreads", "agents.threadHistory", "agents.signInStart", "agents.signInWait", "agents.start", "agents.message","agents.detail", "agents.readFile", "agents.restoreFile", "agents.addRoutine", "agents.setRoutine","agents.removeRoutine", "agents.allowComputer", "agents.revokeComputer","agentKeys.list", "agentKeys.check", "agentKeys.set", "agentKeys.remove", "agentKeys.use", "agentKeys.shell", "agentKeys.fromShell",diff --git a/apps/cua-spaces-desktop/src/model/agents.ts b/apps/cua-spaces-desktop/src/model/agents.tsindex 826cd4d681..1c058d60ca 100644--- a/apps/cua-spaces-desktop/src/model/agents.ts+++ b/apps/cua-spaces-desktop/src/model/agents.ts@@ -130,13 +130,24 @@ export class PersistentAgents {space: string,agent: string,prompt: string,- o: { repo: string | null; branch: string | null; model: string | null; envFromHost: string[] },+ o: {+ repo: string | null;+ branch: string | null;+ model: string | null;+ envFromHost: string[];+ cwd?: string | null;+ resumeSession?: string | null;+ resumeContext?: string | null;+ },): Promise<Json> {const args: Record<string, unknown> = { space, agent, prompt };if (o.repo) args.repo = o.repo;if (o.branch) args.branch = o.branch;if (o.model) args.model = o.model;if (o.envFromHost.length) args.env_from_host = o.envFromHost;+ if (o.cwd) args.cwd = o.cwd;+ if (o.resumeSession) args.resume_session = o.resumeSession;+ if (o.resumeContext) args.resume_context = o.resumeContext;return this.call("agent_start", args);}diff --git a/apps/cua-spaces-desktop/test/agent-threads.test.ts b/apps/cua-spaces-desktop/test/agent-threads.test.tsnew file mode 100644index 0000000000..f31b680928--- /dev/null+++ b/apps/cua-spaces-desktop/test/agent-threads.test.ts@@ -0,0 +1,37 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// `agents.recentThreads` / `agents.threadHistory` (CUA-3319): the daemon's+// person-only tools with the web bridge's own argument mapping, the answer+// untouched, and an old daemon answering `unsupported`.+import { describe, expect, it, vi } from "vitest";+import { recentThreadsFromTool } from "../../cua-spaces-web/src/bridge/ops/agent-threads";+import { agentThreadsMethods } from "../src/bridge/agent-threads";+import type { BridgeContext } from "../src/bridge/context";++const ctx = {} as BridgeContext;+const LIST = { threads: [{ agent: "claude-code", id: "abc", title: "Kettle timer", cwd: "/Users/sam/code/kettle", last_active_ms: 5, resume: ["claude", "--resume", "abc"] }] };++describe("agents.recentThreads / agents.threadHistory", () => {+ it("lists with the tool's arguments and answers its JSON as-is", async () => {+ const tool = vi.fn(async () => LIST);+ const m = agentThreadsMethods(ctx, () => tool);+ const r = await m["agents.recentThreads"]!({ limit: 4 }, {});+ expect(tool).toHaveBeenCalledWith("agent_threads", { limit: 4 });+ expect(r).toBe(LIST);+ expect(recentThreadsFromTool(r)[0]!.title).toBe("Kettle timer");+ });++ it("reads one chat by its agent and id", async () => {+ const tool = vi.fn(async () => ({}));+ const m = agentThreadsMethods(ctx, () => tool);+ await m["agents.threadHistory"]!({ agent: "openai-codex", id: "x1" }, {});+ expect(tool).toHaveBeenCalledWith("agent_thread_read", { agent: "openai-codex", id: "x1" });+ await expect(m["agents.threadHistory"]!({ agent: "hermes" }, {})).rejects.toMatchObject({ code: "bad_args" });+ });++ it("a daemon without the tools is unsupported", async () => {+ const m = agentThreadsMethods(ctx, () => async () => Promise.reject(new Error("unknown tool agent_threads")));+ await expect(m["agents.recentThreads"]!({}, {})).rejects.toMatchObject({ code: "unsupported" });+ });+});diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swiftindex 67fc8d099b..18c1231bd7 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift@@ -152,13 +152,19 @@ public final class PersistentModel {/// Starts a coding agent in a Space (`agent_start`): its answer as is/// (`run_id`, `agent`, `space`, ...). Saved provider keys the harness/// reads are forwarded by the daemon without being named here.+ /// With `resumeSession`, the run continues that session of the agent's+ /// own (a chat from `agent_threads`) in `cwd`, its folder.func startRun(space: String, agent: String, prompt: String, repo: String?, branch: String?, model: String?,- envFromHost: [String]) async throws -> [String: Any] {+ envFromHost: [String], cwd: String? = nil, resumeSession: String? = nil,+ resumeContext: String? = nil) async throws -> [String: Any] {var args: [String: Any] = ["space": space, "agent": agent, "prompt": prompt]if let repo { args["repo"] = repo }if let branch { args["branch"] = branch }if let model { args["model"] = model }if !envFromHost.isEmpty { args["env_from_host"] = envFromHost }+ if let cwd { args["cwd"] = cwd }+ if let resumeSession { args["resume_session"] = resumeSession }+ if let resumeContext { args["resume_context"] = resumeContext }return try await call("agent_start", args)}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swiftindex 92b25a8cab..2c1c400c3b 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift@@ -463,6 +463,34 @@ extension WebUIBridge {return try await model.persistent.daemonTool(name, args)}+ /// `agents.recentThreads {limit?}` and `agents.threadHistory {agent, id, limit?}`:+ /// the person-only daemon tools `agent_threads` and `agent_thread_read`,+ /// their JSON back untouched (`ops/agent-threads.ts` maps it). A daemon+ /// without them answers `unsupported`, and the Ready screen hides the list.+ func agentThreads(_ method: String, _ args: [String: Any]) async throws -> Any {+ var out: [String: Any] = [:]+ if let limit = args["limit"] as? NSNumber { out["limit"] = limit }+ let name: String+ if method == "agents.threadHistory" {+ guard let agent = args["agent"] as? String, !agent.isEmpty else { throw Failure.badArgs("agent: string") }+ guard let id = args["id"] as? String, !id.isEmpty else { throw Failure.badArgs("id: string") }+ out["agent"] = agent+ out["id"] = id+ name = "agent_thread_read"+ } else {+ name = "agent_threads"+ }+ do {+ return try await tool(name, out)+ } catch let f as Failure {+ throw f+ } catch {+ let words = LiveSpacesBackend.words(error)+ if Self.missingThreadTool(words) { throw Failure.unsupported("This cua daemon can't list your agents' chats; update Cua") }+ throw Failure(code: "failed", message: words)+ }+ }+/// `thread.read`, `thread.post`, `thread.members`, `thread.setRights`,/// `thread.agentAdd`, `thread.agentRemove`, `thread.joinCodeCreate`,/// `thread.joinCodeList`, `thread.joinCodeCancel`, `thread.settings`: the operation's@@ -564,7 +592,7 @@ extension WebUIBridge {static func missingThreadTool(_ message: String) -> Bool {let m = message.lowercased()let tools = ["thread_read", "thread_post", "agent_members", "thread_join_code_create", "thread_join_code_list",- "thread_join_code_cancel", "thread_settings"]+ "thread_join_code_cancel", "thread_settings", "agent_threads", "agent_thread_read"]return tools.contains { t in m.contains("spaces tool \(t)") || ((m.contains("unknown tool") || m.contains("no such tool")) && m.contains(t)) }}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swiftindex 89f3e7611f..ee9d6f28be 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift@@ -76,6 +76,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {"agents.list", "agents.runs", "agents.events", "agents.pause", "agents.resume","agents.setup", "agents.configure", "agents.signIn","agents.status", "agents.connect", "agents.disconnect",+ // The coding agents' own recent chats on this Mac (person-only daemon tools, CUA-3319).+ "agents.recentThreads", "agents.threadHistory",// An agent's device-code sign-in made for Cua (Codex), started and waited in two calls."agents.signInStart", "agents.signInWait",// Start a run in a Space and reply to it (the daemon's agent_start, agent_message).@@ -391,6 +393,9 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {"agents.signInStart", "agents.signInWait":return try await agents(method, args)+ case "agents.recentThreads", "agents.threadHistory":+ return try await agentThreads(method, args)+case "checklist.get": return ["state": model.checklist.stored]case "checklist.send":model.checklist.send(try checklistAction(args["action"]))@@ -843,7 +848,9 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {let text = { (key: String) in (args[key] as? String).flatMap { $0.isEmpty ? nil : $0 } }return try await persistent.startRun(space: spaceId, agent: agent, prompt: prompt, repo: text("repo"),branch: text("branch"), model: text("model"),- envFromHost: (args["envFromHost"] as? [String]) ?? [])+ envFromHost: (args["envFromHost"] as? [String]) ?? [],+ cwd: text("cwd"), resumeSession: text("resumeSession"),+ resumeContext: text("resumeContext"))case "agents.message":let spaceId = try string(args, "spaceId"), runId = try string(args, "runId"), text = try string(args, "text")guard persistent.canCallTools else { throw Failure.unsupported("Replying to a run needs the cua daemon") }diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swiftindex 71328bd85a..a0f70a0525 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift@@ -343,6 +343,8 @@ struct BridgeContractTests {"agents.events": "needs the daemon's agent_events; WebUIHostTests checks it is unsupported without it","agents.start": "starts a coding agent through the daemon; WebUIHostTests checks it is unsupported without it","agents.message": "as agents.start (the daemon's agent_message)",+ "agents.recentThreads": "needs the daemon's agent_threads; WebUIHostTests checks it is unsupported without it",+ "agents.threadHistory": "as agents.recentThreads (the daemon's agent_thread_read)","agents.pause": "changes the fake's state for agents.list", "agents.resume": "as agents.pause","agents.setupDriver": "writes the coding agents' configs on the fixture setup",// Teleport needs the SDK's handle and a reachable Space; its answersdiff --git a/apps/cua-spaces-web/src/__tests__/pick-up.test.tsx b/apps/cua-spaces-web/src/__tests__/pick-up.test.tsxnew file mode 100644index 0000000000..78ad079bf3--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/pick-up.test.tsx@@ -0,0 +1,113 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// CUA-3319: "Pick up where you left off". Continue in Cua opens the chat in a+// private Home task with its earlier messages; nothing runs until the person+// sends, and then the agent resumes its own session on this Mac, in the+// chat's folder.++import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { BridgeProvider, setFlagOverride, type HostStatus } from "@/bridge";+import { createDemoAdapter } from "@/bridge/adapters/demo";+import { testCore, wasmBuilt } from "@/bridge/__tests__/testCore";+import { PickUpWhereYouLeftOff, ReadyScreen } from "@/components/first-run-new/first-run-new";+import { readyView } from "@/lib/first-run-new";+import { addImportedTask, askTask, resetAskTasks, type AskTask } from "@/lib/ask-first";+import { mountApp, stubBrowserApis } from "./app-harness";++stubBrowserApis();+beforeEach(() => {+ localStorage.clear();+ resetAskTasks();+ setFlagOverride("spaces_ask_first_home", true);+});+afterEach(() => cleanup());++const q = (s: string) => document.querySelector<HTMLElement>(s);+const KETTLE = { agent: "claude-code", id: "0b1e5c2a-1111-4222-8333-944445555666", title: "Kettle timer test fails on CI", cwd: "/Users/demo/code/kettle", lastActiveMs: Date.now() - 60_000 };+const SHARED: Partial<HostStatus> = { configured: true, sharing: true, shareDesktop: true, mode: "relay", machineId: "this-mac-1" };++describe("Pick up where you left off", () => {+ it("lists the chats with their folder and time, and Continue in Cua makes a private Home task", async () => {+ const picked: AskTask[] = [];+ render(+ <BridgeProvider adapter={createDemoAdapter({ latencyMs: 1 })} core={await testCore()}>+ <PickUpWhereYouLeftOff onContinue={(t) => picked.push(t)} />+ </BridgeProvider>,+ );+ await waitFor(() => expect(document.querySelectorAll("[data-pick-up-row]").length).toBe(3));+ expect(screen.getByText("Kettle timer test fails on CI")).toBeTruthy();+ expect(screen.getByText("~/code/kettle, 25 min ago")).toBeTruthy();+ expect(screen.getByText("Your chats stay on this Mac until you pick one.")).toBeTruthy();+ fireEvent.click(document.querySelectorAll<HTMLElement>("[data-pick-up-continue]")[0]!);+ expect(picked).toHaveLength(1);+ expect(picked[0]!.imported).toMatchObject({ sessionId: KETTLE.id, cwd: KETTLE.cwd });+ expect(picked[0]!.runId).toBeNull();+ expect(picked[0]!.prompt).toBe("");+ // The same chat again opens the same task.+ fireEvent.click(document.querySelectorAll<HTMLElement>("[data-pick-up-continue]")[0]!);+ expect(picked[1]!.id).toBe(picked[0]!.id);+ });++ it("is hidden when this computer has no chats", async () => {+ render(+ <BridgeProvider adapter={createDemoAdapter({ latencyMs: 1, noChats: true })} core={await testCore()}>+ <PickUpWhereYouLeftOff onContinue={() => {}} />+ </BridgeProvider>,+ );+ await new Promise((r) => setTimeout(r, 50));+ expect(q("[data-pick-up]")).toBeNull();+ });+});++describe("the new setup's Ready screen", () => {+ it("offers the recent chats under the command, and Continue in Cua hands the task on", async () => {+ const picked: AskTask[] = [];+ const view = readyView({ os: "macos", agent: "claude-code", computers: ["this"] });+ render(+ <BridgeProvider adapter={createDemoAdapter({ latencyMs: 1 })} core={await testCore()}>+ <ReadyScreen view={view} agent="claude-code" place="this Mac" onDone={() => {}} onContinueChat={(t) => picked.push(t)} />+ </BridgeProvider>,+ );+ await waitFor(() => expect(document.querySelectorAll("[data-new-run=ready] [data-pick-up-row]").length).toBe(3));+ fireEvent.click(document.querySelectorAll<HTMLElement>("[data-pick-up-continue]")[0]!);+ expect(picked[0]!.imported).toMatchObject({ sessionId: KETTLE.id });+ });+});++describe.skipIf(!wasmBuilt)("a continued chat in Home", () => {+ it("shows what was said, runs nothing, and resumes the agent's own session on send", { timeout: 30000 }, async () => {+ const task = addImportedTask(KETTLE);+ const calls: { op: string; args: Record<string, unknown> }[] = [];+ await mountApp(`/home/${task.id}`, {+ failsCreates: false,+ listsGhost: false,+ demo: { onboarded: true },+ intercept: (op, args) => {+ calls.push({ op, args: args as Record<string, unknown> });+ return op === "agents.start" ? { run_id: "run-continued", agent: "claude-code" } : undefined;+ },+ answer: (op, out) => (op === "host.status" ? { ...(out as HostStatus), ...SHARED } : out),+ });+ await waitFor(() => expect(q("[data-imported-chat]")).not.toBeNull());+ // The earlier messages are read from the agent's own store when the task opens (the timeline is+ // virtualized, so jsdom draws none of its rows; the resume context below carries them).+ await waitFor(() => expect(calls.find((c) => c.op === "agents.threadHistory")?.args).toEqual({ agent: "claude-code", id: KETTLE.id }));+ expect(q("[data-earlier-heading]")?.textContent).toContain("Earlier on this Mac");+ expect(q("[data-continue-on]")?.textContent).toContain("This Mac");+ expect(q("[data-imported-note]")?.textContent).toContain("Nothing runs until you send");+ expect(calls.some((c) => c.op === "agents.start")).toBe(false);+ // Nothing goes to a Space thread: the chat stays private.+ const reply = q("[data-imported-reply]") as HTMLTextAreaElement;+ fireEvent.change(reply, { target: { value: "Pin it to UTC" } });+ fireEvent.keyDown(reply, { key: "Enter" });+ await waitFor(() => expect(calls.some((c) => c.op === "agents.start")).toBe(true));+ const start = calls.find((c) => c.op === "agents.start")!.args;+ expect(start).toMatchObject({ spaceId: "relay:this-mac-1", agent: "claude-code", prompt: "Pin it to UTC", cwd: KETTLE.cwd, resumeSession: KETTLE.id });+ expect(String(start.resumeContext)).toContain("Agent: It depends on the machine's time zone");+ expect(calls.some((c) => c.op === "thread.post")).toBe(false);+ await waitFor(() => expect(askTask(task.id)?.runId).toBeTruthy());+ });+});diff --git a/apps/cua-spaces-web/src/bridge/__tests__/agent-threads.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/agent-threads.test.tsnew file mode 100644index 0000000000..503154b0c0--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/__tests__/agent-threads.test.ts@@ -0,0 +1,66 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// "Pick up where you left off" (CUA-3319): the daemon tools' JSON as the page reads it.++import { describe, expect, it } from "vitest";++import { folderLabel, isMissingAgentThreadsTool, pastThreadFromTool, recentThreadsFromTool, resumeContext, webkitAgentThreadsOps } from "../ops/agent-threads";++const ROW = { agent: "claude-code", id: "abc", title: "Kettle timer", cwd: "/Users/sam/code/kettle", last_active_ms: 1_000, resume: ["claude", "--resume", "abc"] };++describe("agent threads", () => {+ it("maps the list, leaving out rows it can't read", () => {+ const out = recentThreadsFromTool({ threads: [ROW, { agent: "cursor", id: "x" }, { agent: "codex", id: "c1", title: "", cwd: null, last_active_ms: 2 }, "junk"] });+ expect(out).toEqual([+ { agent: "claude-code", id: "abc", title: "Kettle timer", cwd: "/Users/sam/code/kettle", lastActiveMs: 1_000, resume: ["claude", "--resume", "abc"] },+ { agent: "openai-codex", id: "c1", title: "Untitled chat", cwd: null, lastActiveMs: 2, resume: [] },+ ]);+ expect(recentThreadsFromTool(null)).toEqual([]);+ });++ it("maps one chat's messages", () => {+ const h = pastThreadFromTool({+ thread: ROW,+ messages: [+ { key: "m1", role: "person", text: "why?", ts_ms: 5 },+ { key: "m2", role: "agent", text: "time zones", ts_ms: null, cut: true },+ { key: "m3", role: "tool", text: "x" },+ { key: "m4", role: "agent", text: " " },+ ],+ earlier_omitted: 3,+ });+ expect(h.messages).toEqual([+ { key: "m1", role: "person", text: "why?", tsMs: 5, cut: false },+ { key: "m2", role: "agent", text: "time zones", tsMs: null, cut: true },+ ]);+ expect(h.earlierOmitted).toBe(3);+ expect(() => pastThreadFromTool({})).toThrow();+ });++ it("shortens folders under the home folder", () => {+ expect(folderLabel("/Users/sam/code/kettle")).toBe("~/code/kettle");+ expect(folderLabel("/Users/sam")).toBe("~");+ expect(folderLabel("/home/sam/a/b/c/d")).toBe("…/c/d");+ expect(folderLabel("/srv/app")).toBe("/srv/app");+ expect(folderLabel(null)).toBeNull();+ });++ it("gives the agent the newest of the earlier conversation that fits", () => {+ const msgs = [+ { key: "1", role: "person" as const, text: "a".repeat(100), tsMs: null, cut: false },+ { key: "2", role: "agent" as const, text: "the answer", tsMs: null, cut: false },+ { key: "3", role: "person" as const, text: "thanks", tsMs: null, cut: false },+ ];+ expect(resumeContext(msgs)).toBe(`User: ${"a".repeat(100)}\n\nAgent: the answer\n\nUser: thanks`);+ expect(resumeContext(msgs, 40)).toBe("Agent: the answer\n\nUser: thanks");+ });++ it("a daemon without the tools is unsupported", async () => {+ expect(isMissingAgentThreadsTool(new Error("unknown tool agent_threads"))).toBe(true);+ expect(isMissingAgentThreadsTool(new Error("NotFound: Spaces tool agent_thread_read"))).toBe(true);+ expect(isMissingAgentThreadsTool(new Error("no claude-code chat abc on this computer"))).toBe(false);+ const ops = webkitAgentThreadsOps(async () => Promise.reject(new Error("unknown tool agent_threads")));+ await expect(ops["agents.recentThreads"]({})).rejects.toMatchObject({ code: "unsupported" });+ });+});diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.tsindex 2db0cd09f6..ff36686476 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts@@ -126,6 +126,8 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"spaces.openStream": { spaceId: SPACE, tier: "tile" },"relay.usage": {},"nudges.pending": {},+ "agents.recentThreads": { limit: 4 },+ "agents.threadHistory": { agent: "claude-code", id: "0b1e5c2a-1111-4222-8333-944445555666" },"nudges.answer": { id: "risky-1-1", choice: "here" },"resources.get": { visible: true },"machines.rename": { id: "m-studio", name: "Studio" },diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.tsindex 02c872cf50..3f5adebf1c 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts@@ -26,6 +26,7 @@ import { CLI_ARGS } from "../ops/cli";import { THREAD_ARGS } from "../ops/thread";import { PRESENCE_ARGS } from "../ops/presence";import { CLOUD_APPROVE_ARGS } from "../ops/cloud-approve";+import { AGENT_THREADS_ARGS } from "../ops/agent-threads";import { RUNTIME_FIX_ARGS } from "../ops/runtime-fix";import type { HostWindow } from "../detect";import { ELECTRON_BRIDGE_CHANNEL } from "../electron-channels";@@ -176,6 +177,7 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {...THREAD_ARGS,...PRESENCE_ARGS,...CLOUD_APPROVE_ARGS,+ ...AGENT_THREADS_ARGS,...RUNTIME_FIX_ARGS,};diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.tsindex 62c2968780..38126ee39c 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts@@ -8,6 +8,7 @@*/import type { RiskyRequest } from "../ops/nudges";+import { demoAgentThreads } from "./demo/agent-threads";import { Emitter, HostError, UnsupportedOperationError, type DataAdapter } from "../adapter";import type { AgentSetupRow, ConnectionReport, PersistentAgent } from "../contracts/agents";import type { MachineRow, OnboardingState } from "../contracts/host";@@ -150,6 +151,8 @@ export interface DemoOptions {cli?: "local" | "missing";/** A daemon without the Space thread (`?demo=nothread`): the Space page keeps its old layout. */noThread?: boolean;+ /** No Claude Code, Codex or Hermes chats on this computer (`?demo=nochats`): the Ready screen hides "Pick up where you left off". */+ noChats?: boolean;/** You in the demo's thread as someone the Space is shared with: `guest` (`?demo=thread-guest`, view only) or `member` (`?demo=thread-member`); the owner by default. */threadRole?: "member" | "guest";/** Extra scenes in the demo's thread: `?demo=thread-lookalike` (CUA-2262). */@@ -283,6 +286,7 @@ export function demoOptionsFromSearch(search: string): DemoOptions {noTeam: flags.has("no-team"),teamFull: flags.has("team-full"),noThread: flags.has("nothread"),+ noChats: flags.has("nochats"),...(flags.has("thread-guest") ? { threadRole: "guest" as const } : flags.has("thread-member") ? { threadRole: "member" as const } : {}),threadLookalike: flags.has("thread-lookalike"),threadAuthFailed: flags.has("thread-auth-failed"),@@ -1048,6 +1052,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { reif (options.threadLongDm && !options.noThread) seedLongDm(h, options.threadLongDm);return options.threadSlow ? hangingSpace(h, DEMO_THREAD_SPACE) : h;})(),+ ...demoAgentThreads(now, options.noChats ?? false),"nudges.pending": () => risky.filter((r) => r.expiresMs > now()).map((r) => ({ ...r })),"nudges.answer": ({ id }) => {risky = risky.filter((r) => r.id !== id);diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/agent-threads.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/agent-threads.tsnew file mode 100644index 0000000000..9f91c16eaf--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/agent-threads.ts@@ -0,0 +1,54 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The demo's "Pick up where you left off" (CUA-3319): three made-up chats,+ * one per agent, as the daemon's `agent_threads` / `agent_thread_read`+ * answer them. `?demo=nochats` plays a computer with none.+ */++import { HostError } from "../../adapter";+import type { PastThread, RecentThread } from "../../ops/agent-threads";++const MIN = 60_000;++export function demoAgentThreads(now: () => number, none: boolean) {+ const threads: PastThread[] = none+ ? []+ : [+ {+ thread: { agent: "claude-code", id: "0b1e5c2a-1111-4222-8333-944445555666", title: "Kettle timer test fails on CI", cwd: "/Users/demo/code/kettle", lastActiveMs: now() - 25 * MIN, resume: ["claude", "--resume", "0b1e5c2a-1111-4222-8333-944445555666"] },+ messages: [+ { key: "m1", role: "person", text: "The kettle timer test fails on CI but passes locally, can you find out why?", tsMs: now() - 40 * MIN, cut: false },+ { key: "m2", role: "agent", text: "It depends on the machine's time zone: CI runs in UTC and the test expects local time.", tsMs: now() - 38 * MIN, cut: false },+ { key: "m3", role: "person", text: "Makes sense. Let's look again tomorrow.", tsMs: now() - 25 * MIN, cut: false },+ ],+ earlierOmitted: 0,+ },+ {+ thread: { agent: "openai-codex", id: "5f0c1d2e-3a4b-4c5d-8e6f-708192a3b4c5", title: "Checkout double charge", cwd: "/Users/demo/code/bike-shop", lastActiveMs: now() - 3 * 60 * MIN, resume: ["codex", "resume", "5f0c1d2e-3a4b-4c5d-8e6f-708192a3b4c5"] },+ messages: [+ { key: "u-1", role: "person", text: "Why does checkout double-charge when the coupon is applied twice?", tsMs: now() - 3 * 60 * MIN, cut: false },+ { key: "a-1", role: "agent", text: "The coupon handler isn't idempotent. I'd key it on the order id.", tsMs: now() - 3 * 60 * MIN + MIN, cut: false },+ ],+ earlierOmitted: 0,+ },+ {+ thread: { agent: "hermes", id: "20261103_201500_ab12cd", title: "Summarise my notes on the bakery lease", cwd: "/Users/demo/notes", lastActiveMs: now() - 26 * 60 * MIN, resume: ["hermes", "--resume", "20261103_201500_ab12cd"] },+ messages: [+ { key: "1", role: "person", text: "Summarise my notes on the bakery lease", tsMs: now() - 26 * 60 * MIN, cut: false },+ { key: "4", role: "agent", text: "The lease renews in March; the rent review clause is in section 4.", tsMs: now() - 26 * 60 * MIN + MIN, cut: false },+ ],+ earlierOmitted: 0,+ },+ ];+ const copy = (t: RecentThread): RecentThread => ({ ...t, resume: [...t.resume] });+ return {+ "agents.recentThreads": ({ limit }: { limit?: number }) => threads.slice(0, limit ?? 4).map((t) => copy(t.thread)),+ "agents.threadHistory": ({ agent, id }: { agent: string; id: string }) => {+ const t = threads.find((x) => x.thread.agent === agent && x.thread.id === id);+ if (!t) throw new HostError(`no ${agent} chat ${id} on this computer`, "not_found");+ return { thread: copy(t.thread), messages: t.messages.map((m) => ({ ...m })), earlierOmitted: t.earlierOmitted };+ },+ };+}diff --git a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts b/apps/cua-spaces-web/src/bridge/adapters/tauri.tsindex 361a490e4b..30994f33f0 100644--- a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts@@ -59,6 +59,7 @@ import { TAURI_SPACE_DETAIL_UNSUPPORTED, tauriSpaceDetailOps } from "../ops/spacimport { STREAM_OPERATIONS } from "../ops/stream";import { RELAY_USAGE_OPERATIONS } from "../ops/relay-usage";import { NUDGES_OPERATIONS } from "../ops/nudges";+import { AGENT_THREADS_OPERATIONS } from "../ops/agent-threads";import { RESOURCES_OPERATIONS } from "../ops/resources";import { MACHINES_OPERATIONS } from "../ops/machines";import { CHECKLIST_OPERATIONS } from "../ops/checklist";@@ -119,6 +120,7 @@ export const TAURI_UNSUPPORTED: readonly OpName[] = [...STREAM_OPERATIONS,...RELAY_USAGE_OPERATIONS,...NUDGES_OPERATIONS,+ ...AGENT_THREADS_OPERATIONS,...RESOURCES_OPERATIONS,...MACHINES_OPERATIONS,...CHECKLIST_OPERATIONS,diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.tsindex 6cb0e87d19..507ef68020 100644--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts@@ -54,6 +54,7 @@ import { STOPPED_SHARING_ERROR, stoppedSharingLine, withNotSharing } from "../shimport { teleportProgressFromWk, webkitPageOps } from "../ops/webkit-pages";import { webkitAgentDetailOps } from "../ops/agent-detail";import { webkitThreadOps } from "../ops/thread";+import { webkitAgentThreadsOps } from "../ops/agent-threads";import { webkitAgentKeysOps } from "../ops/agent-keys";import { webkitGithubOps } from "../ops/github";import { webkitKeyvaultManageOps } from "../ops/keyvault-manage";@@ -752,6 +753,7 @@ export function createWebkitAdapter(...webkitTelemetryNoticeOps(request),...webkitAgentDetailOps(request),...webkitThreadOps(request),+ ...webkitAgentThreadsOps(request),...webkitAgentKeysOps(request),...webkitGithubOps(request),...webkitKeyvaultManageOps(request, toKeyvaultOverview as (wk: never) => KeyvaultOverview),diff --git a/apps/cua-spaces-web/src/bridge/contracts/agents.ts b/apps/cua-spaces-web/src/bridge/contracts/agents.tsindex 212dabfb09..aec9f2f3ae 100644--- a/apps/cua-spaces-web/src/bridge/contracts/agents.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/agents.ts@@ -104,6 +104,12 @@ export interface AgentStartRequest {model?: string;/** Provider key names to forward (values never cross the bridge). Saved keys the harness reads go without being named. */envFromHost?: string[];+ /** The run's folder (a continued chat's own, with `resumeSession`). */+ cwd?: string;+ /** Continue this session of the agent's own (a chat from `agents.recentThreads`) instead of a new one. */+ resumeSession?: string;+ /** With `resumeSession`: the earlier conversation, for when the agent can't reload its session. */+ resumeContext?: string;}/** `agent_start`'s answer (snake_case, as the tool answers). */diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex 698e2b0cd3..cf3b3d1c14 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -4464,6 +4464,47 @@"kind"]},+ "RecentThread": {+ "type": "object",+ "properties": {+ "agent": {+ "enum": [+ "claude-code",+ "openai-codex",+ "hermes"+ ]+ },+ "id": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "cwd": {+ "type": [+ "string",+ "null"+ ]+ },+ "lastActiveMs": {+ "type": "number"+ },+ "resume": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "agent",+ "id",+ "title",+ "cwd",+ "lastActiveMs",+ "resume"+ ]+ },"RemoteWindow": {"type": "object","properties": {@@ -8169,6 +8210,12 @@"agents.readFile": {"$ref": "#/$defs/AgentOpenFile"},+ "agents.recentThreads": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/RecentThread"+ }+ },"agents.removeRoutine": {"type": "null"},@@ -8348,6 +8395,58 @@"agents.status": {"$ref": "#/$defs/ConnectionReport"},+ "agents.threadHistory": {+ "type": "object",+ "properties": {+ "thread": {+ "$ref": "#/$defs/RecentThread"+ },+ "messages": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "key": {+ "type": "string"+ },+ "role": {+ "enum": [+ "person",+ "agent"+ ]+ },+ "text": {+ "type": "string"+ },+ "tsMs": {+ "type": [+ "number",+ "null"+ ]+ },+ "cut": {+ "type": "boolean"+ }+ },+ "required": [+ "key",+ "role",+ "text",+ "tsMs",+ "cut"+ ]+ }+ },+ "earlierOmitted": {+ "type": "number"+ }+ },+ "required": [+ "thread",+ "messages",+ "earlierOmitted"+ ]+ },"checklist.get": {"type": "object","properties": {@@ -14177,6 +14276,8 @@}},"webkitUnshaped": {+ "agents.recentThreads": "the daemon tool's JSON as-is (agent_threads, agent_thread_read); ops/agent-threads.ts maps it for every host",+ "agents.threadHistory": "the daemon tool's JSON as-is (agent_threads, agent_thread_read); ops/agent-threads.ts maps it for every host","thread.agentAdd": "the daemon tool's JSON as-is (thread_read, thread_post, agent_members, agent_set_rights, agent_add, agent_remove, thread_join_code_create, thread_join_code_list, thread_join_code_cancel, thread_settings); ops/thread.ts maps it for every host","thread.agentRemove": "the daemon tool's JSON as-is (thread_read, thread_post, agent_members, agent_set_rights, agent_add, agent_remove, thread_join_code_create, thread_join_code_list, thread_join_code_cancel, thread_settings); ops/thread.ts maps it for every host","thread.joinCodeCancel": "the daemon tool's JSON as-is (thread_read, thread_post, agent_members, agent_set_rights, agent_add, agent_remove, thread_join_code_create, thread_join_code_list, thread_join_code_cancel, thread_settings); ops/thread.ts maps it for every host",diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex 24ca41646a..4624bd0dfd 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -69,6 +69,7 @@ import type { TelemetryLinkNotice } from "../ops/telemetry";import type { SentFileInfo, SpaceThumbnail, SpaceUsage, SpaceWindows } from "../ops/space-detail";import type { RelayUsage } from "../ops/relay-usage";import type { RiskyRequest } from "../ops/nudges";+import type { PastMessage, PastThread, RecentThread } from "../ops/agent-threads";import type { ComputerResources, DiskOnHost, DiskWarning, GuestUsage, ResourcesSnapshot, SharedBase, SpaceResources } from "../ops/resources";import type { HostChecklistState } from "../ops/checklist";import type { TipsState } from "./spaces-page";@@ -88,6 +89,10 @@ const ref = (name: string, s: Schema) => defs.ref(name, s);const strings = list(str);const limits = list(object({ resource: str, used: num, limit: num, reason: str }));const os = oneOf("macos", "windows", "linux", "unknown");+const RecentThreadShape = ref(+ "RecentThread",+ obj<RecentThread>()({ agent: oneOf("claude-code", "openai-codex", "hermes"), id: str, title: str, cwd: nullable(str), lastActiveMs: num, resume: strings }),+);/* ---- Spaces and machines --------------------------------------------------- */@@ -1526,6 +1531,12 @@ export const OP_SHAPES: Record<OpName, Schema> = {"machines.checkHealth": nul,"spaces.openStream": obj<StreamTicket>()({ wsUrl: str, expiresAt: nullable(str) }),"nudges.pending": list(obj<RiskyRequest>()({ id: str, agent: str, action: str, atMs: num, expiresMs: num })),+ "agents.recentThreads": list(RecentThreadShape),+ "agents.threadHistory": obj<PastThread>()({+ thread: RecentThreadShape,+ messages: list(obj<PastMessage>()({ key: str, role: oneOf("person", "agent"), text: str, tsMs: nullable(num), cut: bool })),+ earlierOmitted: num,+ }),"nudges.answer": nul,"relay.usage": nullable(obj<RelayUsage>()({@@ -2131,6 +2142,7 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {/** Methods whose answer has no shape here, and why. */const THREAD_TOOL_JSON ="the daemon tool's JSON as-is (thread_read, thread_post, agent_members, agent_set_rights, agent_add, agent_remove, thread_join_code_create, thread_join_code_list, thread_join_code_cancel, thread_settings); ops/thread.ts maps it for every host";+const AGENT_THREADS_TOOL_JSON = "the daemon tool's JSON as-is (agent_threads, agent_thread_read); ops/agent-threads.ts maps it for every host";export const WEBKIT_UNSHAPED: Partial<Record<WebkitMethod, string>> = {"thread.read": THREAD_TOOL_JSON,"thread.post": THREAD_TOOL_JSON,@@ -2142,6 +2154,8 @@ export const WEBKIT_UNSHAPED: Partial<Record<WebkitMethod, string>> = {"thread.joinCodeList": THREAD_TOOL_JSON,"thread.joinCodeCancel": THREAD_TOOL_JSON,"thread.settings": THREAD_TOOL_JSON,+ "agents.recentThreads": AGENT_THREADS_TOOL_JSON,+ "agents.threadHistory": AGENT_THREADS_TOOL_JSON,};/** The exported document (`bridge-shapes.json`): `ops` and `webkit` mapdiff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.tsindex fbe3cb17f0..37e1547e8c 100644--- a/apps/cua-spaces-web/src/bridge/coverage.ts+++ b/apps/cua-spaces-web/src/bridge/coverage.ts@@ -51,6 +51,7 @@ import { CLI_COVERAGE } from "./ops/cli";import { THREAD_COVERAGE } from "./ops/thread";import { PRESENCE_COVERAGE } from "./ops/presence";import { CLOUD_APPROVE_COVERAGE } from "./ops/cloud-approve";+import { AGENT_THREADS_COVERAGE } from "./ops/agent-threads";import { RUNTIME_FIX_COVERAGE } from "./ops/runtime-fix";import { TELEMETRY_COVERAGE } from "./ops/telemetry";import { STARTUP_COVERAGE } from "./ops/startup";@@ -229,6 +230,7 @@ export const HOST_COVERAGE = {...THREAD_COVERAGE,...PRESENCE_COVERAGE,...CLOUD_APPROVE_COVERAGE,+ ...AGENT_THREADS_COVERAGE,...RUNTIME_FIX_COVERAGE,} as const satisfies Record<OpName, OpCoverage>;diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.tsindex 575489a0cc..cc2e9eda06 100644--- a/apps/cua-spaces-web/src/bridge/index.ts+++ b/apps/cua-spaces-web/src/bridge/index.ts@@ -211,6 +211,7 @@ export {type ThreadPage,type ThreadRole,} from "./ops/thread";+export { folderLabel, resumeContext, THREAD_AGENTS, type PastMessage, type PastThread, type RecentThread, type ThreadAgent } from "./ops/agent-threads";export type { LinkAccess, LinkCreate, ShareLanding, ShareLink, ShareSettings } from "./ops/links";export {useResources,diff --git a/apps/cua-spaces-web/src/bridge/ops/agent-threads.ts b/apps/cua-spaces-web/src/bridge/ops/agent-threads.tsnew file mode 100644index 0000000000..fbbf027b33--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/ops/agent-threads.ts@@ -0,0 +1,194 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * "Pick up where you left off" (CUA-3319): the recent Claude Code, Codex and+ * Hermes chats on this computer, read from each agent's own store, and one+ * chat's messages once the person picked it. Each operation is one of the+ * daemon's person-only tools (no MCP server lists or runs them, and the+ * daemon answers only this computer's own user):+ *+ * | Operation | Daemon tool | SwiftUI / Electron host | Tauri |+ * |---|---|---|---|+ * | `agents.recentThreads {limit?}` | `agent_threads` | the tool's JSON as-is | unsupported |+ * | `agents.threadHistory {agent, id, limit?}` | `agent_thread_read` | the tool's JSON as-is | unsupported |+ *+ * The hosts stay thin (`AGENT_THREADS_TOOLS` is the argument mapping, which+ * the Electron host imports); this file maps the answers for every host. A+ * daemon without the tools answers `unsupported`, and the Ready screen hides+ * the list. Only titles, folders and times are listed; nothing is kept.+ */++import { HostError, isUnsupported, UnsupportedOperationError } from "../adapter";+import type { OpCoverage } from "../coverage";++/** The agents whose chats are read (their harness ids). */+export type ThreadAgent = "claude-code" | "openai-codex" | "hermes";+export const THREAD_AGENTS: readonly ThreadAgent[] = ["claude-code", "openai-codex", "hermes"];++/** One chat as the list shows it (`cua_agent_threads::ThreadSummary`). */+export interface RecentThread {+ agent: ThreadAgent;+ /** The agent's own session id. */+ id: string;+ /** The chat's name, or its first prompt (at most 80 characters). */+ title: string;+ /** The folder it worked in. */+ cwd: string | null;+ lastActiveMs: number;+ /** The agent's own command that resumes it in a terminal (argv). */+ resume: string[];+}++/** One message of a chat (`cua_agent_threads::Message`). */+export interface PastMessage {+ key: string;+ role: "person" | "agent";+ text: string;+ tsMs: number | null;+ /** The text was cut (at 8 KiB). */+ cut: boolean;+}++export interface PastThread {+ thread: RecentThread;+ /** Oldest first. */+ messages: PastMessage[];+ /** Older messages left out. */+ earlierOmitted: number;+}++export interface AgentThreadsOps {+ "agents.recentThreads": { args: { limit?: number }; result: RecentThread[] };+ "agents.threadHistory": { args: { agent: ThreadAgent; id: string; limit?: number }; result: PastThread };+}++export type AgentThreadsOpName = keyof AgentThreadsOps;++export const AGENT_THREADS_OPERATIONS = ["agents.recentThreads", "agents.threadHistory"] as const satisfies readonly AgentThreadsOpName[];+export const AGENT_THREADS_WEBKIT_METHODS = AGENT_THREADS_OPERATIONS;++const TAURI = "the coding agents' chats are read by the cua daemon's person-only tools, which the Tauri shell does not call";+export const AGENT_THREADS_COVERAGE = {+ "agents.recentThreads": { webkit: { methods: ["agents.recentThreads"] }, tauri: [], unsupported: { tauri: TAURI } },+ "agents.threadHistory": { webkit: { methods: ["agents.threadHistory"] }, tauri: [], unsupported: { tauri: TAURI } },+} as const satisfies Record<AgentThreadsOpName, OpCoverage>;++/** Each operation's daemon tool and its arguments (the native hosts use this mapping). */+export const AGENT_THREADS_TOOLS = {+ "agents.recentThreads": {+ tool: "agent_threads",+ args: (a: AgentThreadsOps["agents.recentThreads"]["args"]) => (a.limit ? { limit: a.limit } : {}),+ },+ "agents.threadHistory": {+ tool: "agent_thread_read",+ args: (a: AgentThreadsOps["agents.threadHistory"]["args"]) => ({ agent: a.agent, id: a.id, ...(a.limit ? { limit: a.limit } : {}) }),+ },+} as const;++/** Arguments that take each down its usual path (coverage tests). */+export const AGENT_THREADS_ARGS = {+ "agents.recentThreads": { limit: 4 },+ "agents.threadHistory": { agent: "claude-code" as ThreadAgent, id: "0b1e5c2a-1111-4222-8333-944445555666" },+};++/* ---- The tools' JSON (snake_case) as the page reads it ------------------------------ */++const rec = (v: unknown): Record<string, unknown> => (v && typeof v === "object" ? (v as Record<string, unknown>) : {});+const str = (v: unknown): string => (typeof v === "string" ? v : "");+const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0);++function agentOf(v: unknown): ThreadAgent | null {+ const s = str(v);+ if (s === "codex") return "openai-codex";+ return (THREAD_AGENTS as readonly string[]).includes(s) ? (s as ThreadAgent) : null;+}++function threadFromTool(v: unknown): RecentThread | null {+ const t = rec(v);+ const agent = agentOf(t.agent);+ const id = str(t.id);+ if (!agent || !id) return null;+ return {+ agent,+ id,+ title: str(t.title) || "Untitled chat",+ cwd: typeof t.cwd === "string" && t.cwd ? t.cwd : null,+ lastActiveMs: num(t.last_active_ms),+ resume: Array.isArray(t.resume) ? t.resume.filter((x): x is string => typeof x === "string") : [],+ };+}++/** `agent_threads`' answer; rows it can't read are left out. */+export function recentThreadsFromTool(v: unknown): RecentThread[] {+ const rows = rec(v).threads;+ return Array.isArray(rows) ? rows.map(threadFromTool).filter((t): t is RecentThread => t !== null) : [];+}++/** `agent_thread_read`'s answer; `asked` names the chat when the answer doesn't. */+export function pastThreadFromTool(v: unknown, asked?: { agent: ThreadAgent; id: string }): PastThread {+ const o = rec(v);+ const thread = threadFromTool(o.thread) ?? (asked ? { agent: asked.agent, id: asked.id, title: "Untitled chat", cwd: null, lastActiveMs: 0, resume: [] } : null);+ if (!thread) throw new HostError("The chat couldn't be read", "failed");+ const messages = (Array.isArray(o.messages) ? o.messages : [])+ .map((m): PastMessage | null => {+ const r = rec(m);+ const role = r.role === "person" || r.role === "agent" ? r.role : null;+ const text = str(r.text);+ if (!role || !text.trim()) return null;+ return { key: str(r.key), role, text, tsMs: typeof r.ts_ms === "number" ? r.ts_ms : null, cut: r.cut === true };+ })+ .filter((m): m is PastMessage => m !== null);+ return { thread, messages, earlierOmitted: num(o.earlier_omitted) };+}++/** A daemon from before these tools: its "unknown tool" is `unsupported`. */+export function isMissingAgentThreadsTool(e: unknown): boolean {+ const m = (e instanceof Error ? e.message : String(e)).toLowerCase();+ return ["agent_threads", "agent_thread_read"].some((t) => m.includes(`spaces tool ${t}`) || ((m.includes("unknown tool") || m.includes("no such tool")) && m.includes(t)));+}++type Request = <T>(method: AgentThreadsOpName, args?: Record<string, unknown>) => Promise<T>;++/** The SwiftUI and Electron hosts: the host method, then this file's mapping. */+export function webkitAgentThreadsOps(request: Request) {+ const call = async (op: AgentThreadsOpName, args: object) => {+ try {+ return await request<unknown>(op, { ...args });+ } catch (e) {+ if (!isUnsupported(e) && isMissingAgentThreadsTool(e)) throw new UnsupportedOperationError("webkit", op);+ throw e;+ }+ };+ return {+ "agents.recentThreads": async (a: AgentThreadsOps["agents.recentThreads"]["args"]) => recentThreadsFromTool(await call("agents.recentThreads", a)),+ "agents.threadHistory": async (a: AgentThreadsOps["agents.threadHistory"]["args"]) => pastThreadFromTool(await call("agents.threadHistory", a), a),+ };+}++/* ---- What the UI shows ------------------------------------------------------------- */++/** `/Users/sam/code/kettle` as `~/code/kettle`; a long path keeps its last two folders. */+export function folderLabel(cwd: string | null): string | null {+ if (!cwd) return null;+ const home = cwd.match(/^(\/Users\/[^/]+|\/home\/[^/]+|[A-Za-z]:\\Users\\[^\\]+)(?=$|[/\\])/);+ const short = home ? `~${cwd.slice(home[1]!.length)}` : cwd;+ const parts = short.split(/[/\\]/).filter(Boolean);+ return parts.length > 3 ? `…/${parts.slice(-2).join("/")}` : short || "~";+}++/** The earlier conversation as text for the agent, when it can't reload its own session (at most `max` bytes, newest kept). */+export function resumeContext(messages: readonly PastMessage[], max = 24 * 1024): string {+ const enc = new TextEncoder();+ const lines: string[] = [];+ let size = 0;+ for (let i = messages.length - 1; i >= 0; i--) {+ const m = messages[i]!;+ const line = `${m.role === "person" ? "User" : "Agent"}: ${m.text.trim()}`;+ const n = enc.encode(line).length + 2;+ if (size + n > max) break;+ lines.unshift(line);+ size += n;+ }+ return lines.join("\n\n");+}diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.tsindex fc0a793c04..fa4bb05754 100644--- a/apps/cua-spaces-web/src/bridge/protocol.ts+++ b/apps/cua-spaces-web/src/bridge/protocol.ts@@ -58,6 +58,7 @@ import { CI_OPERATIONS, type CiOps } from "./ops/ci";import { THREAD_OPERATIONS, type ThreadOps } from "./ops/thread";import { PRESENCE_OPERATIONS, type PresenceOps } from "./ops/presence";import { CLOUD_APPROVE_OPERATIONS, type CloudApproveOps } from "./ops/cloud-approve";+import { AGENT_THREADS_OPERATIONS, type AgentThreadsOps } from "./ops/agent-threads";import { RUNTIME_FIX_OPERATIONS, type RuntimeFixOps } from "./ops/runtime-fix";import { TELEMETRY_OPERATIONS, type TelemetryOps } from "./ops/telemetry";import type { TipsState } from "./contracts/spaces-page";@@ -241,6 +242,7 @@ export interface HostOperationsThreadOps,PresenceOps,CloudApproveOps,+ AgentThreadsOps,RuntimeFixOps {"spaces.list": { args: Record<string, never>; result: SpaceRow[] };/** `os`: the plan's OS, for a host that draws its own pending row (the SwiftUI app's notch). */@@ -470,6 +472,7 @@ export const OPERATIONS = [...THREAD_OPERATIONS,...PRESENCE_OPERATIONS,...CLOUD_APPROVE_OPERATIONS,+ ...AGENT_THREADS_OPERATIONS,...RUNTIME_FIX_OPERATIONS,...SETTINGS_OPERATIONS,...NOTIFICATIONS_OPERATIONS,diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.tsindex 95032d4ba6..72c7d2cb3c 100644--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts@@ -38,6 +38,7 @@ import { CI_WEBKIT_METHODS } from "./ops/ci";import { KEYVAULT_MANAGE_WEBKIT_METHODS } from "./ops/keyvault-manage";import { KEYVAULT_SETUP_WEBKIT_METHODS } from "./ops/keyvault-setup";import { THREAD_WEBKIT_METHODS } from "./ops/thread";+import { AGENT_THREADS_WEBKIT_METHODS } from "./ops/agent-threads";export const WEBKIT_HANDLER_NAME = "cua";/** The window event the host dispatches. */@@ -210,6 +211,7 @@ export const WEBKIT_METHODS = ["cli.install",...CI_WEBKIT_METHODS,...THREAD_WEBKIT_METHODS,+ ...AGENT_THREADS_WEBKIT_METHODS,] as const;export type WebkitMethod = (typeof WEBKIT_METHODS)[number];diff --git a/apps/cua-spaces-web/src/components/ask-first/imported-task.tsx b/apps/cua-spaces-web/src/components/ask-first/imported-task.tsxnew file mode 100644index 0000000000..fceb633f16--- /dev/null+++ b/apps/cua-spaces-web/src/components/ask-first/imported-task.tsx@@ -0,0 +1,226 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { Menu as MenuPrimitive } from "@base-ui/react/menu";+import { Link } from "@tanstack/react-router";+import { ArrowLeftIcon, ArrowUpIcon, CheckIcon, ChevronDownIcon, LaptopIcon, Loader2Icon, MonitorIcon } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";++import { folderLabel, resumeContext, useAgents, useAgentTimeline, useBridge, useMachines, type AgentTimeline, type HostStatus, type PastThread, type ThreadAgent, type TranscriptItem } from "@/bridge";+import { Timeline } from "@/components/agents/timeline";+import { Button } from "@/components/ui/button";+import { toastError } from "@/components/ui/toast";+import { HOST_NOT_SHARED, hostSpaceId, updateAskTask, type AskTask } from "@/lib/ask-first";+import { cn } from "@/lib/utils";++import { agentName, AppMark } from "./ask-box";+import { agoLabel } from "./pick-up";+import { StartFailed } from "./task-view";++/** The earlier messages as the run's timeline rows, before the run's own. */+export function earlierItems(history: PastThread | null): TranscriptItem[] {+ return (history?.messages ?? []).map((m, i) => ({+ id: `earlier:${m.key || i}`,+ kind: m.role === "person" ? "user" : "message",+ turn: -1,+ text: m.text,+ steps: [],+ startedMs: m.tsMs ?? 0,+ }));+}++/**+ * A chat picked from "Pick up where you left off" (CUA-3319, step 5): its+ * title, agent and folder, what was said so far under "Earlier on this Mac"+ * (read again from the agent's own store), and the box with **Continue on**+ * beside it. Nothing runs until the person sends; then the agent resumes its+ * own session on this Mac, in the chat's folder, and the run's turns follow+ * the earlier ones. The chat stays private: nothing goes to a Space thread.+ */+export function ImportedTaskView({ task }: { task: AskTask & { imported: NonNullable<AskTask["imported"]> } }) {+ const { data } = useBridge();+ const { startRun, sendMessage } = useAgents();+ const chat = task.imported;+ const name = agentName(task.agent);+ const [history, setHistory] = useState<PastThread | null>(null);+ const [historyError, setHistoryError] = useState<string | null>(null);+ useEffect(() => {+ let live = true;+ data+ ?.call("agents.threadHistory", { agent: task.agent as ThreadAgent, id: chat.sessionId })+ .then((h) => live && setHistory(h))+ .catch((e: unknown) => live && setHistoryError(e instanceof Error ? e.message : String(e)));+ return () => {+ live = false;+ };+ }, [data, task.agent, chat.sessionId]);++ const ref = task.runId && task.spaceId ? { spaceId: task.spaceId, runId: task.runId } : null;+ const live = useAgentTimeline(ref);+ const timeline = useMemo<AgentTimeline>(() => ({ ...live, items: [...earlierItems(history), ...live.items] }), [live, history]);+ const [reply, setReply] = useState("");+ const [starting, setStarting] = useState(false);+ const lastSent = useRef("");++ const start = async (text: string) => {+ setStarting(true);+ lastSent.current = text;+ try {+ const status = (await data?.call("host.status", {} as never).catch(() => null)) as HostStatus | null;+ const spaceId = hostSpaceId(status);+ if (!spaceId) throw new Error(HOST_NOT_SHARED);+ updateAskTask(task.id, { spaceId, onHost: true, prompt: text, error: null });+ const started = await startRun({+ spaceId,+ agent: task.agent,+ prompt: text,+ ...(chat.cwd ? { cwd: chat.cwd } : {}),+ resumeSession: chat.sessionId,+ ...(history?.messages.length ? { resumeContext: resumeContext(history.messages) } : {}),+ });+ updateAskTask(task.id, { runId: started.run_id });+ } catch (e) {+ updateAskTask(task.id, { error: e instanceof Error ? e.message : String(e) });+ } finally {+ setStarting(false);+ }+ };+ const send = async (text: string) => {+ const t = text.trim();+ if (!t || starting) return;+ setReply("");+ if (!ref) return start(t);+ await sendMessage(ref, t).catch(toastError(`Couldn't send that to ${name}`));+ };++ const folder = folderLabel(chat.cwd);+ const loading = !history && !historyError;+ const waiting = !ref && !task.error;+ return (+ <div className="flex h-full flex-col" data-ask-first-task={task.id} data-imported-chat={task.agent}>+ <header /* design-ok: page-wide header rule, as the task view's */ className="flex h-16 shrink-0 items-center gap-3 border-b px-8">+ <Button variant="ghost" className="-ml-2 h-9" render={<Link to="/home" />}>+ <ArrowLeftIcon /> Home+ </Button>+ <AppMark agent={task.agent} size={32} />+ <div className="min-w-0 flex-1">+ <h2 className="truncate text-[15px] font-semibold">{chat.title}</h2>+ <p className="truncate text-[13px] text-muted-foreground">+ {name}+ {folder ? ` in ${folder}` : ""}, last used {agoLabel(chat.lastActiveMs)}+ </p>+ </div>+ </header>+ <div className="flex min-h-0 flex-1 flex-col">+ <p className="mx-auto w-full max-w-[720px] shrink-0 px-8 pt-6 text-[12px] font-medium text-muted-foreground" data-earlier-heading="">+ Earlier on this Mac+ {history?.earlierOmitted ? ` (${history.earlierOmitted} older messages aren't shown)` : ""}+ </p>+ {loading ? (+ <div className="flex flex-1 items-center justify-center text-muted-foreground">+ <Loader2Icon className="size-5 animate-spin" />+ </div>+ ) : historyError && !timeline.items.length ? (+ <div className="mx-auto w-full max-w-[720px] flex-1 px-8 pt-4 text-[14px] text-muted-foreground" data-earlier-error="">+ {name} couldn't show the earlier messages. You can still continue: {name} picks up its own session when you send.+ </div>+ ) : (+ <Timeline+ className="flex-1"+ timeline={timeline}+ footer={+ task.error && !ref ? (+ <div className="pb-4">+ <StartFailed error={task.error} name={name} agent={task.agent} host onRetry={() => void start(lastSent.current || task.prompt)} />+ </div>+ ) : undefined+ }+ />+ )}+ <div className="shrink-0 px-8 pb-6">+ <div className="mx-auto flex max-w-[720px] flex-col gap-2">+ <div /* design-ok: the message box, as Home's and the task view's */ className="flex min-h-14 items-end gap-2 rounded-2xl border bg-card py-1.5 pr-1.5 pl-5 shadow-xs dark:bg-white/[0.03]">+ <textarea+ value={reply}+ rows={1}+ autoFocus+ disabled={starting}+ onChange={(e) => setReply(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {+ e.preventDefault();+ void send(reply);+ }+ }}+ aria-label={`Your next message to ${name}`}+ placeholder={waiting ? `Your next message to ${name}` : `Reply to ${name}`}+ className="min-h-11 flex-1 resize-none self-center bg-transparent py-2.5 text-[14px] outline-none placeholder:text-muted-foreground disabled:opacity-60"+ data-imported-reply=""+ />+ <ContinueOn />+ <button+ type="button"+ aria-label="Send"+ disabled={starting || !reply.trim()}+ onClick={() => void send(reply)}+ className={cn("flex size-11 shrink-0 items-center justify-center rounded-full", reply.trim() && !starting ? "bg-primary text-primary-foreground" : "bg-foreground/10 text-muted-foreground")}+ >+ {starting ? <Loader2Icon className="size-5 animate-spin" /> : <ArrowUpIcon className="size-5" />}+ </button>+ </div>+ {waiting ? (+ <p className="px-1 text-[12px] text-muted-foreground" data-imported-note="">+ Nothing runs until you send. {name} then carries on this chat on this Mac, in its own folder.+ </p>+ ) : null}+ </div>+ </div>+ </div>+ </div>+ );+}++/**+ * **Continue on**: where the chat carries on. This Mac today; the account's+ * other computers are listed but can't be picked yet, because the agent's+ * session lives on this Mac (continuing elsewhere is CUA-3331).+ */+function ContinueOn() {+ const { data: machines } = useMachines();+ const others = (machines ?? []).filter((m) => !m.current);+ return (+ <MenuPrimitive.Root>+ <MenuPrimitive.Trigger+ render={+ <button type="button" className="flex h-11 shrink-0 items-center gap-1.5 rounded-lg px-3 text-[13px] outline-none hover:bg-foreground/5 data-popup-open:bg-foreground/[0.07]" data-continue-on="">+ <span className="text-muted-foreground">Continue on:</span> This Mac <ChevronDownIcon className="size-3.5 text-muted-foreground" />+ </button>+ }+ />+ <MenuPrimitive.Portal>+ <MenuPrimitive.Positioner sideOffset={6} align="end" className="z-50 outline-none">+ <MenuPrimitive.Popup /* design-ok: a menu's popup, as Home's pickers */ className="glass w-[340px] origin-(--transform-origin) rounded-xl border p-2 text-popover-foreground shadow-float outline-none">+ <p className="px-3 pt-2 pb-1 text-[12px] font-medium text-muted-foreground">Continue on</p>+ <MenuPrimitive.Item className="flex min-h-12 cursor-default items-center gap-3 rounded-lg bg-foreground/[0.06] px-3 py-2 outline-none">+ <LaptopIcon className="size-4" />+ <div className="min-w-0 flex-1">+ <div className="text-[14px] font-medium">This Mac</div>+ <div className="text-[12px] text-muted-foreground">Where this chat's session is</div>+ </div>+ <CheckIcon className="size-4" />+ </MenuPrimitive.Item>+ {others.map((m) => (+ <MenuPrimitive.Item key={m.id} disabled className="flex min-h-12 cursor-default items-center gap-3 rounded-lg px-3 py-2 opacity-50 outline-none" data-continue-on-other={m.id}>+ <MonitorIcon className="size-4" />+ <div className="min-w-0 flex-1">+ <div className="truncate text-[14px] font-medium">{m.name}</div>+ <div className="text-[12px] text-muted-foreground">Not yet: the chat's session is on this Mac</div>+ </div>+ </MenuPrimitive.Item>+ ))}+ </MenuPrimitive.Popup>+ </MenuPrimitive.Positioner>+ </MenuPrimitive.Portal>+ </MenuPrimitive.Root>+ );+}diff --git a/apps/cua-spaces-web/src/components/ask-first/pick-up.tsx b/apps/cua-spaces-web/src/components/ask-first/pick-up.tsxnew file mode 100644index 0000000000..5792f9b4a7--- /dev/null+++ b/apps/cua-spaces-web/src/components/ask-first/pick-up.tsx@@ -0,0 +1,47 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { useEffect, useState } from "react";++import { isUnsupported, useBridge, type RecentThread } from "@/bridge";++/** How many chats the Ready screen offers. */+export const PICK_UP_LIMIT = 4;++/**+ * The recent Claude Code, Codex and Hermes chats on this computer+ * (`agents.recentThreads`), newest first. Null until the host answered;+ * empty when there are none or the host can't list them.+ */+export function useRecentThreads(limit = PICK_UP_LIMIT): RecentThread[] | null {+ const { data } = useBridge();+ const [threads, setThreads] = useState<RecentThread[] | null>(null);+ useEffect(() => {+ let live = true;+ if (!data) return;+ data+ .call("agents.recentThreads", { limit })+ .then((rows) => live && setThreads(rows))+ .catch((e: unknown) => {+ // A host or daemon without the list, or a store it couldn't read: the section stays hidden.+ if (live) setThreads([]);+ if (!isUnsupported(e)) console.warn("agents.recentThreads failed", e);+ });+ return () => {+ live = false;+ };+ }, [data, limit]);+ return threads;+}++/** "25 min ago", "3 h ago", "2 days ago". */+export function agoLabel(ms: number, now = Date.now()): string {+ const s = Math.max(0, Math.round((now - ms) / 1000));+ if (s < 60) return "just now";+ const m = Math.round(s / 60);+ if (m < 60) return `${m} min ago`;+ const h = Math.round(m / 60);+ if (h < 24) return `${h} h ago`;+ const d = Math.round(h / 24);+ return d === 1 ? "yesterday" : `${d} days ago`;+}diff --git a/apps/cua-spaces-web/src/components/ask-first/task-view.tsx b/apps/cua-spaces-web/src/components/ask-first/task-view.tsxindex bcdabd5148..016f0f528d 100644--- a/apps/cua-spaces-web/src/components/ask-first/task-view.tsx+++ b/apps/cua-spaces-web/src/components/ask-first/task-view.tsx@@ -19,6 +19,7 @@ import { createProgress, spaceState } from "@/lib/spaces";import { cn } from "@/lib/utils";import { agentName, AppMark, TASK_AGENTS, WherePicker } from "./ask-box";+import { ImportedTaskView } from "./imported-task";import { StateDot, taskRun } from "./home";import { useWherePick } from "./this-mac-confirm";import { useStartTask } from "./use-start-task";@@ -48,6 +49,8 @@ export function AskFirstTask({ taskId }: { taskId: string }) {</div>);}+ // A chat picked from "Pick up where you left off" (CUA-3319): its earlier messages and the box to continue it.+ if (task.imported) return <ImportedTaskView task={{ ...task, imported: task.imported }} />;return <TaskView task={task} />;}diff --git a/apps/cua-spaces-web/src/components/first-run-new/first-run-new.tsx b/apps/cua-spaces-web/src/components/first-run-new/first-run-new.tsxindex d57c9e770f..9ec4b407ef 100644--- a/apps/cua-spaces-web/src/components/first-run-new/first-run-new.tsx+++ b/apps/cua-spaces-web/src/components/first-run-new/first-run-new.tsx@@ -13,7 +13,7 @@ import { useNavigate } from "@tanstack/react-router";import { CheckIcon, ChevronRightIcon, CopyIcon, LoaderCircleIcon, MonitorIcon, PlusIcon, ShieldIcon, UserPlusIcon } from "lucide-react";import { useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";-import { newPendingId, useMachines, useSession, useSettings, useSpaces, type SignInPhase } from "@/bridge";+import { folderLabel, newPendingId, useMachines, useSession, useSettings, useSpaces, type SignInPhase } from "@/bridge";import { BridgeContext } from "@/bridge/BridgeProvider";import type { HostStatus } from "@/bridge/contracts/host";import { readFirstRun, useFirstRunSaved, writeFirstRun } from "@/bridge/first-run";@@ -23,7 +23,9 @@ import { readSavedOnboarding, writeSavedOnboarding } from "@/bridge/onboarding";import { extraName, spokenName } from "@/bridge/space-names";import { AddComputerSheet } from "@/components/add-computer-sheet";import { AppMarkImage } from "@/components/agents/harness-mark";+import { agoLabel, useRecentThreads } from "@/components/ask-first/pick-up";import { CuaLogo } from "@/components/cua-logo";+import { addImportedTask, type AskTask } from "@/lib/ask-first";import {agentView,chosenAgent,@@ -31,6 +33,7 @@ import {INSTALL_PAGES,NEW_RUN_EMPTY,nextView,+ placeName,readyView,signInView,togglePick,@@ -356,7 +359,46 @@ export function AgentScreen({ view, onPick, onContinue, onInstall, busy }: { vie);}-export function ReadyScreen({ view, agent, onDone }: { view: ReadyView; agent: string; onDone: () => void }) {+/**+ * "Pick up where you left off" (CUA-3319): 2 to 4 of the person's recent chats with their agents on+ * this computer, each with **Continue in Cua**, which opens it in a new Home task with what was said+ * so far. Nothing runs until they send. Hidden when there are none. Only each chat's title, folder+ * and time are read here; its messages are read when it is picked.+ */+export function PickUpWhereYouLeftOff({ onContinue, place = "this Mac", className }: { onContinue: (task: AskTask) => void; place?: string; className?: string }) {+ const threads = useRecentThreads();+ if (!threads?.length) return null;+ return (+ <section aria-labelledby="pick-up-heading" className={cn("w-full", className)} data-pick-up="">+ <h2 id="pick-up-heading" className="text-[15px] font-semibold text-white">+ Pick up where you left off+ </h2>+ <ul className={cn(CARD, "mt-2.5 max-w-[600px]")}>+ {threads.map((t) => {+ const folder = folderLabel(t.cwd);+ const when = agoLabel(t.lastActiveMs);+ return (+ <li key={`${t.agent}:${t.id}`} className="flex items-center gap-3 px-3 py-2.5" data-pick-up-row={t.agent}>+ <span className="flex size-7 shrink-0 items-center justify-center rounded-full shadow-[inset_0_0_0_1px_rgb(255_255_255/0.28)]">+ <AppMarkImage agent={t.agent} className="size-3.5" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-[15px] leading-5 font-medium text-white">{t.title}</span>+ <span className={cn("block truncate text-[13.5px] leading-[19px] font-medium", GREY)}>{folder ? `${folder}, ${when}` : when}</span>+ </span>+ <button type="button" className={cn(GLASS_CHIP, "h-[30px] shrink-0 px-3 text-[13.5px]")} onClick={() => onContinue(addImportedTask(t))} data-pick-up-continue="">+ Continue in Cua+ </button>+ </li>+ );+ })}+ </ul>+ <p className={cn("mt-2 text-[13.5px] font-medium", GREY)}>Your chats stay on {place} until you pick one.</p>+ </section>+ );+}++export function ReadyScreen({ view, agent, onDone, onContinueChat, place }: { view: ReadyView; agent: string; onDone: () => void; onContinueChat?: (task: AskTask) => void; place?: string }) {const [copied, setCopied] = useState(false);const copy = () => {void navigator.clipboard?.writeText(view.command).catch(() => {});@@ -379,6 +421,8 @@ export function ReadyScreen({ view, agent, onDone }: { view: ReadyView; agent: s{copied ? "Copied" : view.copy}</button></div>+ {/* The person's own recent chats on this computer (CUA-3319), hidden when there are none. */}+ {onContinueChat ? <PickUpWhereYouLeftOff className="mt-[min(28px,3vh)]" place={place} onContinue={onContinueChat} /> : null}<div className="mt-6"><button type="button" className={WHITE_BUTTON} onClick={onDone} data-onboarding-primary="">{view.done}@@ -705,6 +749,12 @@ export function NewFirstRun() {writeFirstRun({ finishedLater: false, todosClosed: false });await navigate({ to: "/home" });};+ // Continue in Cua (CUA-3319): setup is done and the picked chat opens as a Home task. Nothing runs until the person sends.+ const continueChat = async (task: AskTask) => {+ await session.completeOnboarding(thisState === "added" && signedIn ? "host" : "client").catch(() => {});+ writeFirstRun({ finishedLater: false, todosClosed: false });+ await navigate({ to: "/home/$taskId", params: { taskId: task.id } });+ };const startSignIn = () => {started.current = true;@@ -765,7 +815,9 @@ export function NewFirstRun() {);break;case "ready":- body = s.agent ? <ReadyScreen view={readyView({ os, agent: s.agent, computers: pickedNames() })} agent={s.agent} onDone={() => go("next")} /> : null;+ body = s.agent ? (+ <ReadyScreen view={readyView({ os, agent: s.agent, computers: pickedNames() })} agent={s.agent} place={placeName(os)} onDone={() => go("next")} onContinueChat={(task) => void continueChat(task)} />+ ) : null;break;case "next": {const granted = (id: string) => Boolean(host?.permissions.find((p) => p.id === id)?.granted);diff --git a/apps/cua-spaces-web/src/lib/ask-first.ts b/apps/cua-spaces-web/src/lib/ask-first.tsindex 5b1811156f..45f3002053 100644--- a/apps/cua-spaces-web/src/lib/ask-first.ts+++ b/apps/cua-spaces-web/src/lib/ask-first.ts@@ -48,6 +48,24 @@ export interface AskTask {onHost?: boolean;/** Started in its Space's thread: the job is the Space's first message, @mentioning the agent. */inSpace?: boolean;+ /**+ * A chat picked from "Pick up where you left off" (CUA-3319): the agent's+ * own session on this Mac. Only this reference is kept; the earlier+ * messages are read again from the agent's own store when the task opens,+ * and nothing is posted to a Space thread, so the chat stays private to+ * this device's user. The first message the person sends resumes it.+ */+ imported?: ImportedChat;+}++/** Which of the agent's own chats a task continues. */+export interface ImportedChat {+ /** The agent's session id. */+ sessionId: string;+ title: string;+ /** The chat's folder: the run continues there. */+ cwd: string | null;+ lastActiveMs: number;}const KEY = "cua.askFirst.tasks";@@ -123,6 +141,31 @@ export function updateAskTask(id: string, patch: Partial<AskTask> | ((t: AskTasksave(load().map((t) => (t.id === id ? { ...t, ...(typeof patch === "function" ? patch(t) : patch) } : t)));}+/**+ * A new Home task for one of the agent's own chats (Continue in Cua). Nothing+ * runs: the task waits for the person's next message. Picking the same chat+ * again opens the task already made for it.+ */+export function addImportedTask(chat: { agent: string; id: string; title: string; cwd: string | null; lastActiveMs: number }, now = Date.now()): AskTask {+ const existing = load().find((t) => t.imported?.sessionId === chat.id && t.agent === chat.agent && !t.runId);+ if (existing) return existing;+ return addAskTask(+ {+ prompt: "",+ agent: chat.agent,+ os: "macos",+ onHost: true,+ imported: { sessionId: chat.id, title: chat.title, cwd: chat.cwd, lastActiveMs: chat.lastActiveMs },+ },+ now,+ );+}++/** A task's title: what was asked, or the continued chat's own title. */+export function askTaskTitle(t: Pick<AskTask, "prompt" | "imported">): string {+ return t.prompt.trim() ? taskTitle(t.prompt) : (t.imported?.title ?? "");+}+/** Keeps the conversation with the task before its computer goes. */export function keepTranscript(items: readonly TranscriptItem[]): TranscriptItem[] {return items.slice(-MAX_ITEMS).map((i) => ({ ...i, steps: [...i.steps] }));diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lockindex fd40812159..7bba3e96de 100644--- a/apps/cua-spaces/src-tauri/Cargo.lock+++ b/apps/cua-spaces/src-tauri/Cargo.lock@@ -1723,6 +1723,17 @@ dependencies = ["toml_edit 0.25.13+spec-1.1.0",]+[[package]]+name = "cua-agent-threads"+version = "0.10.1"+dependencies = [+ "chrono",+ "rusqlite",+ "serde",+ "serde_json",+ "thiserror 2.0.20",+]+[[package]]name = "cua-agents"version = "0.10.1"@@ -2341,6 +2352,7 @@ dependencies = ["async-trait","base64 0.22.1","chrono",+ "cua-agent-threads","cua-agents","cua-auth","cua-chromium-storage",diff --git a/docs/content/docs/spaces/reference/agents.mdx b/docs/content/docs/spaces/reference/agents.mdxindex 2eacc55756..fc2bf2393f 100644--- a/docs/content/docs/spaces/reference/agents.mdx+++ b/docs/content/docs/spaces/reference/agents.mdx@@ -24,6 +24,8 @@ Run coding agents inside a Space.| [`agent_stop`](#agent_stop) | Stop an agent run. || [`agent_list`](#agent_list) | List agent runs in the Space. || [`agent_capabilities`](#agent_capabilities) | Report what the agent harnesses support. |+| [`agent_threads`](#agent_threads) | List the recent Claude Code, Codex and Hermes chats on this computer. For a person only. |+| [`agent_thread_read`](#agent_thread_read) | Read one of the recent Claude Code, Codex or Hermes chats on this computer. For a person only. |### agent_start@@ -62,6 +64,8 @@ Installs the harness if needed (pinned, checksum-verified), gives it the Space's| `model` | `string` | none | Model id. || `prompt` | `string` | required | The task. || `repo` | `string` | none | Git URL cloned into the working directory first. |+| `resume_context` | `string` | none | With `resume_session`: the earlier conversation as text, given to the agent before the prompt only when the harness cannot reload the session (up to 32 KiB). |+| `resume_session` | `string` | none | Continue this session of the harness's own (an id from `agent_threads`) instead of starting a new one: the harness reloads it from its own store on this computer. Give `cwd` as the chat's folder. Not with `home`. || `sandbox_mcp` | `boolean` | `true` | Give the agent the Space's own MCP tools. Default true. || `show` | `boolean` | `false` | Open a terminal on the Space's desktop following the run. Default false. || `skills` | `boolean` | `true` | Copy the cua skills into the harness. Default true. |@@ -298,6 +302,67 @@ JSON: `protocol`, `statuses`, `event_kinds`, `harnesses` (each `id`, `name`, `re[`invalid_argument`](/spaces/reference#invalid_argument)+### agent_threads++List the recent Claude Code, Codex and Hermes chats on this computer. For a person only.++Only for a person, never for an agent: no MCP server lists or runs it, and the daemon answers only this computer's own user (never a relay caller or a Space's agent). Reads the coding agents' own stores on this computer read-only (Claude Code's projects folder, Codex's sessions, Hermes's state.db) and returns only each chat's title, folder and time; nothing is kept or sent anywhere. A store that is missing or unreadable adds nothing.++| | |+| --- | --- |+| Providers | all (cloud, local, direct, relay) |+| Platforms | all (macos, windows, linux) |+| Metering | free |+| Approval | none: for a person only, never served over MCP; read-only, idempotent |+| Swift SDK | `spaces.callTool("agent_threads")` |+| Rust | `cua_agent_threads::recent` |++#### Parameters++| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `agents` | `string[]` | `[]` | Harness ids to look at: `claude-code`, `openai-codex`, `hermes`. Default: all three. |+| `limit` | `integer` | `4` | How many chats, newest first (1-50). Default 4. At least 0. |++#### Result++JSON: `threads`, newest first, each `agent` (harness id), `id`, `title` (the chat's name, or its first prompt cut to 80 characters), `cwd` (its folder, or null), `last_active_ms` and `resume` (the agent's own command that continues it in a terminal, as argv).++#### Errors++[`invalid_argument`](/spaces/reference#invalid_argument), [`permission_denied`](/spaces/reference#permission_denied)++### agent_thread_read++Read one of the recent Claude Code, Codex or Hermes chats on this computer. For a person only.++Only for a person, never for an agent: no MCP server lists or runs it, and the daemon answers only this computer's own user. Reads one chat from the agent's own store, read-only: what the person typed and the agent's replies, without tool calls, tool output, thinking or the agent's own injected instructions. Call it once the person picked the chat; continue it with agent_start's `resume_session`.++| | |+| --- | --- |+| Providers | all (cloud, local, direct, relay) |+| Platforms | all (macos, windows, linux) |+| Metering | free |+| Approval | none: for a person only, never served over MCP; read-only, idempotent |+| Swift SDK | `spaces.callTool("agent_thread_read")` |+| Rust | `cua_agent_threads::history` |++#### Parameters++| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `agent` | `string` | required | Its harness id (`claude-code`, `openai-codex`, `hermes`). |+| `id` | `string` | required | Its id, from `agent_threads`. |+| `limit` | `integer` | `200` | The newest messages to return (1-5000). Default 200. At least 0. |++#### Result++JSON: `thread` (as in `agent_threads`), `messages` (oldest first, each `key`, `role` (`person` or `agent`), `text` (cut to 8 KiB), `ts_ms`, and `cut` when cut) and `earlier_omitted` (older messages left out).++#### Errors++[`invalid_argument`](/spaces/reference#invalid_argument), [`permission_denied`](/spaces/reference#permission_denied), [`not_found`](/spaces/reference#not_found)+## Persistent agentsNamed agents whose memory outlives their Space: homes in Cua Volume, routines, notifications, pause and resume, access to the user's computers.diff --git a/docs/content/docs/spaces/reference/index.mdx b/docs/content/docs/spaces/reference/index.mdxindex 489cd446d7..587e76a5fb 100644--- a/docs/content/docs/spaces/reference/index.mdx+++ b/docs/content/docs/spaces/reference/index.mdx@@ -10,7 +10,7 @@ description: "Every Spaces tool by category, with parameters, results, errors anVersion: 0.9.0*/}-The Spaces contract: 119 tools with the same names and schemas on every surface: `cua mcp`, `cua daemon mcp` and the Spaces SDKs. Contract 0.9.0, MCP protocol revision 2025-06-18, transports `mcp_stdio` and `mcp_streamable_http`. Experimental: names and shapes can change between minor versions.+The Spaces contract: 121 tools with the same names and schemas on every surface: `cua mcp`, `cua daemon mcp` and the Spaces SDKs. Contract 0.9.0, MCP protocol revision 2025-06-18, transports `mcp_stdio` and `mcp_streamable_http`. Experimental: names and shapes can change between minor versions.## Tools@@ -82,6 +82,8 @@ Run coding agents inside a Space.| [`agent_stop`](/spaces/reference/agents#agent_stop) | Stop an agent run. | destructive || [`agent_list`](/spaces/reference/agents#agent_list) | List agent runs in the Space. | read-only, idempotent || [`agent_capabilities`](/spaces/reference/agents#agent_capabilities) | Report what the agent harnesses support. | read-only, idempotent |+| [`agent_threads`](/spaces/reference/agents#agent_threads) | List the recent Claude Code, Codex and Hermes chats on this computer. For a person only. | read-only, idempotent |+| [`agent_thread_read`](/spaces/reference/agents#agent_thread_read) | Read one of the recent Claude Code, Codex or Hermes chats on this computer. For a person only. | read-only, idempotent |### [Persistent agents](/spaces/reference/agents#persistent-agents)@@ -304,7 +306,7 @@ An argument is missing, malformed or out of range.Fix: Check the call against the tool's input schema; the message names the argument.-Listed by [`network_show`](/spaces/reference/spaces#network_show), [`network_set`](/spaces/reference/spaces#network_set), [`resize_space`](/spaces/reference/spaces#resize_space), [`space_service`](/spaces/reference/spaces#space_service), [`thread_join`](/spaces/reference/threads#thread_join), [`thread_join_code_create`](/spaces/reference/threads#thread_join_code_create), [`thread_join_code_cancel`](/spaces/reference/threads#thread_join_code_cancel), [`volume_storage_set`](/spaces/reference/agents#volume_storage_set), [`volume_cache_set`](/spaces/reference/agents#volume_cache_set), [`relay_unregister_space`](/spaces/reference/sharing-and-clouds#relay_unregister_space), [`cloud_connect`](/spaces/reference/sharing-and-clouds#cloud_connect), [`cloud_approve`](/spaces/reference/sharing-and-clouds#cloud_approve), [`cloud_add_host`](/spaces/reference/sharing-and-clouds#cloud_add_host), [`cloud_budget`](/spaces/reference/sharing-and-clouds#cloud_budget), [`prewarm`](/spaces/reference/sharing-and-clouds#prewarm).+Listed by [`network_show`](/spaces/reference/spaces#network_show), [`network_set`](/spaces/reference/spaces#network_set), [`resize_space`](/spaces/reference/spaces#resize_space), [`space_service`](/spaces/reference/spaces#space_service), [`agent_thread_read`](/spaces/reference/agents#agent_thread_read), [`thread_join`](/spaces/reference/threads#thread_join), [`thread_join_code_create`](/spaces/reference/threads#thread_join_code_create), [`thread_join_code_cancel`](/spaces/reference/threads#thread_join_code_cancel), [`volume_storage_set`](/spaces/reference/agents#volume_storage_set), [`volume_cache_set`](/spaces/reference/agents#volume_cache_set), [`relay_unregister_space`](/spaces/reference/sharing-and-clouds#relay_unregister_space), [`cloud_connect`](/spaces/reference/sharing-and-clouds#cloud_connect), [`cloud_approve`](/spaces/reference/sharing-and-clouds#cloud_approve), [`cloud_add_host`](/spaces/reference/sharing-and-clouds#cloud_add_host), [`cloud_budget`](/spaces/reference/sharing-and-clouds#cloud_budget), [`prewarm`](/spaces/reference/sharing-and-clouds#prewarm).#### not_found@@ -312,7 +314,7 @@ No Space, run, window, service, tool or file with that id.Fix: List what exists first (list_spaces, agent_list, list_space_windows, list_tools).-Listed by [`network_show`](/spaces/reference/spaces#network_show), [`network_log`](/spaces/reference/spaces#network_log), [`network_set`](/spaces/reference/spaces#network_set), [`space_job`](/spaces/reference/spaces#space_job), [`space_service`](/spaces/reference/spaces#space_service), [`thread_join_code_cancel`](/spaces/reference/threads#thread_join_code_cancel), [`volume_sync_resolve`](/spaces/reference/agents#volume_sync_resolve), [`cloud_remove_host`](/spaces/reference/sharing-and-clouds#cloud_remove_host).+Listed by [`network_show`](/spaces/reference/spaces#network_show), [`network_log`](/spaces/reference/spaces#network_log), [`network_set`](/spaces/reference/spaces#network_set), [`space_job`](/spaces/reference/spaces#space_job), [`space_service`](/spaces/reference/spaces#space_service), [`agent_thread_read`](/spaces/reference/agents#agent_thread_read), [`thread_join_code_cancel`](/spaces/reference/threads#thread_join_code_cancel), [`volume_sync_resolve`](/spaces/reference/agents#volume_sync_resolve), [`cloud_remove_host`](/spaces/reference/sharing-and-clouds#cloud_remove_host).#### spacesd_not_available@@ -356,7 +358,7 @@ The signed-in account may not reach that relay computer.Fix: Sign in with the account that owns the computer.-Listed by [`stop_space`](/spaces/reference/spaces#stop_space), [`start_space`](/spaces/reference/spaces#start_space), [`thread_import`](/spaces/reference/threads#thread_import), [`agent_set_rights`](/spaces/reference/threads#agent_set_rights), [`thread_join`](/spaces/reference/threads#thread_join), [`thread_join_code_create`](/spaces/reference/threads#thread_join_code_create), [`thread_join_code_cancel`](/spaces/reference/threads#thread_join_code_cancel), [`thread_join_redeem`](/spaces/reference/threads#thread_join_redeem), [`thread_settings`](/spaces/reference/threads#thread_settings), [`thread_device_revoke`](/spaces/reference/threads#thread_device_revoke), [`share_space`](/spaces/reference/sharing-and-clouds#share_space), [`unshare_space`](/spaces/reference/sharing-and-clouds#unshare_space), [`relay_unregister_space`](/spaces/reference/sharing-and-clouds#relay_unregister_space).+Listed by [`stop_space`](/spaces/reference/spaces#stop_space), [`start_space`](/spaces/reference/spaces#start_space), [`agent_threads`](/spaces/reference/agents#agent_threads), [`agent_thread_read`](/spaces/reference/agents#agent_thread_read), [`thread_import`](/spaces/reference/threads#thread_import), [`agent_set_rights`](/spaces/reference/threads#agent_set_rights), [`thread_join`](/spaces/reference/threads#thread_join), [`thread_join_code_create`](/spaces/reference/threads#thread_join_code_create), [`thread_join_code_cancel`](/spaces/reference/threads#thread_join_code_cancel), [`thread_join_redeem`](/spaces/reference/threads#thread_join_redeem), [`thread_settings`](/spaces/reference/threads#thread_settings), [`thread_device_revoke`](/spaces/reference/threads#thread_device_revoke), [`share_space`](/spaces/reference/sharing-and-clouds#share_space), [`unshare_space`](/spaces/reference/sharing-and-clouds#unshare_space), [`relay_unregister_space`](/spaces/reference/sharing-and-clouds#relay_unregister_space).#### ambiguous_hostdiff --git a/docs/content/docs/spaces/reference/sharing-and-clouds.mdx b/docs/content/docs/spaces/reference/sharing-and-clouds.mdxindex e53917dfab..6550a8ec94 100644--- a/docs/content/docs/spaces/reference/sharing-and-clouds.mdx+++ b/docs/content/docs/spaces/reference/sharing-and-clouds.mdx@@ -462,7 +462,7 @@ Only for a person, never for an agent: no MCP server lists or runs it, the daemo| Providers | all (cloud, local, direct, relay) || Platforms | all (macos, windows, linux) || Metering | free |-| Approval | permission `spaces:cloud_approve`; destructive |+| Approval | none: for a person only, never served over MCP; destructive || Swift SDK | `spaces.cloud.approve(_:deny:)` || Rust | `cua_cloud::Clouds::approve` |diff --git a/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock b/examples/openkoalabot-example-tauri/src-tauri/Cargo.lockindex c654c3f782..c727996698 100644--- a/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock+++ b/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock@@ -1714,6 +1714,17 @@ dependencies = ["toml_edit 0.25.13+spec-1.1.0",]+[[package]]+name = "cua-agent-threads"+version = "0.10.1"+dependencies = [+ "chrono",+ "rusqlite",+ "serde",+ "serde_json",+ "thiserror 2.0.20",+]+[[package]]name = "cua-agents"version = "0.10.1"@@ -2269,6 +2280,7 @@ dependencies = ["async-trait","base64 0.22.1","chrono",+ "cua-agent-threads","cua-agents","cua-auth","cua-chromium-storage",diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lockindex 5ba922e8a6..3dc97a46b8 100644--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock@@ -2069,6 +2069,17 @@ dependencies = ["toml_edit",]+[[package]]+name = "cua-agent-threads"+version = "0.10.1"+dependencies = [+ "chrono",+ "rusqlite",+ "serde",+ "serde_json",+ "thiserror 2.0.20",+]+[[package]]name = "cua-agents"version = "0.10.1"@@ -2869,6 +2880,7 @@ dependencies = ["async-trait","base64 0.22.1","chrono",+ "cua-agent-threads","cua-agents","cua-auth","cua-chromium-storage",diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lockindex b08e5eac9f..995fa3186f 100644--- a/libs/cua/Cargo.lock+++ b/libs/cua/Cargo.lock@@ -2337,6 +2337,18 @@ dependencies = ["toml_edit",]+[[package]]+name = "cua-agent-threads"+version = "0.10.1"+dependencies = [+ "chrono",+ "rusqlite",+ "serde",+ "serde_json",+ "tempfile",+ "thiserror 2.0.20",+]+[[package]]name = "cua-agents"version = "0.10.1"@@ -3391,6 +3403,7 @@ dependencies = ["async-trait","base64 0.22.1","chrono",+ "cua-agent-threads","cua-agents","cua-auth","cua-chromium-storage",diff --git a/libs/cua/Cargo.toml b/libs/cua/Cargo.tomlindex ac54617a9a..9a6008a756 100644--- a/libs/cua/Cargo.toml+++ b/libs/cua/Cargo.toml@@ -90,6 +90,9 @@ members = ["crates/cua-spacesd-html5",# Agent onboarding: detect coding agents, install skills, configure MCP."crates/cua-agent-setup",+ # The coding agents' own recent chats on this computer (Claude Code,+ # Codex, Hermes), read-only, for "Pick up where you left off".+ "crates/cua-agent-threads",# Sign-in and the shared credential store."crates/cua-auth",# Scripted mock LLM provider (tests and e2e: real harnesses, scripted output).diff --git a/libs/cua/crates/cua-agent-threads/Cargo.toml b/libs/cua/crates/cua-agent-threads/Cargo.tomlnew file mode 100644index 0000000000..688177dcf6--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/Cargo.toml@@ -0,0 +1,21 @@+[package]+name = "cua-agent-threads"+description = "Read-only listing and reading of the coding agents' own recent chats on this computer (Claude Code, Codex, Hermes), for continuing one in Cua."+version.workspace = true+edition.workspace = true+rust-version.workspace = true+authors.workspace = true+license.workspace = true+repository.workspace = true+publish = false++[dependencies]+serde.workspace = true+serde_json.workspace = true+thiserror.workspace = true+chrono = { version = "0.4", default-features = false, features = ["std"] }+# Hermes keeps its sessions in SQLite (`state.db`), opened read-only.+rusqlite = { version = "0.40.1", default-features = false, features = ["bundled"] }++[dev-dependencies]+tempfile.workspace = truediff --git a/libs/cua/crates/cua-agent-threads/src/claude.rs b/libs/cua/crates/cua-agent-threads/src/claude.rsnew file mode 100644index 0000000000..3ca5fed911--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/src/claude.rs@@ -0,0 +1,198 @@+//! Claude Code: `<config>/projects/<folder slug>/<session id>.jsonl`, one+//! JSON record per line.+//!+//! The records used: `user` and `assistant` (`message.content` a string or+//! content blocks; `cwd`, `timestamp`, `uuid`, `isMeta`, `isSidechain`),+//! and the titles `custom-title` (`customTitle`, set by `/rename`),+//! `ai-title` (`aiTitle`) and `summary` (`summary`, older versions). A+//! subagent's own chats (`<session>/subagents/*.jsonl`) are one level+//! deeper and are not listed.++use std::path::{Path, PathBuf};++use serde_json::Value;++use crate::lines::{self, str_at};+use crate::text::{injected, title};+use crate::{Agent, Message, Result, Role, ThreadSummary, mtime_ms, rfc3339_ms};++/// Files looked at per chat listed: most hold a real chat, some (a run+/// that never got a prompt) do not.+const SCAN_FACTOR: usize = 8;++pub(crate) fn recent(root: &Path, limit: usize) -> Vec<ThreadSummary> {+ let mut files = sessions(root);+ files.sort_by_key(|f| std::cmp::Reverse(f.1));+ files+ .into_iter()+ .take(limit * SCAN_FACTOR)+ .filter_map(|(path, mtime)| summary(&path, mtime))+ .take(limit)+ .collect()+}++/// Every `projects/*/*.jsonl` with its modification time.+fn sessions(root: &Path) -> Vec<(PathBuf, u64)> {+ let Ok(projects) = std::fs::read_dir(root.join("projects")) else {+ return vec![];+ };+ let mut out = vec![];+ for project in projects.flatten() {+ let Ok(files) = std::fs::read_dir(project.path()) else {+ continue;+ };+ for f in files.flatten() {+ let path = f.path();+ if path.extension().is_some_and(|e| e == "jsonl")+ && let Ok(meta) = f.metadata()+ && meta.is_file()+ && id_of(&path).is_some()+ {+ out.push((path, mtime_ms(&meta)));+ }+ }+ }+ out+}++fn id_of(path: &Path) -> Option<String> {+ let stem = path.file_stem()?.to_str()?;+ crate::valid_id(stem).then(|| stem.to_string())+}++#[derive(Default)]+struct Titles {+ custom: Option<String>,+ ai: Option<String>,+ summary: Option<String>,+}++impl Titles {+ fn read(&mut self, v: &Value) {+ match v.get("type").and_then(Value::as_str) {+ Some("custom-title") => {+ self.custom = str_at(v, &["customTitle"])+ .and_then(title)+ .or(self.custom.take())+ }+ Some("ai-title") => {+ self.ai = str_at(v, &["aiTitle"]).and_then(title).or(self.ai.take())+ }+ Some("summary") => {+ self.summary = str_at(v, &["summary"])+ .and_then(title)+ .or(self.summary.take())+ }+ _ => {}+ }+ }++ fn best(self) -> Option<String> {+ self.custom.or(self.ai).or(self.summary)+ }+}++fn summary(path: &Path, mtime: u64) -> Option<ThreadSummary> {+ let id = id_of(path)?;+ let (head, tail) = lines::edges(path).ok()?;+ let mut titles = Titles::default();+ let mut cwd = None;+ let mut first_prompt = None;+ let mut last_ts = None::<u64>;+ for v in head.iter().chain(tail.iter()) {+ titles.read(v);+ if cwd.is_none() {+ cwd = str_at(v, &["cwd"])+ .filter(|s| !s.is_empty())+ .map(String::from);+ }+ if first_prompt.is_none()+ && let Some(m) = message(v)+ && m.role == Role::Person+ {+ first_prompt = title(&m.text);+ }+ if let Some(t) = str_at(v, &["timestamp"]).and_then(rfc3339_ms) {+ last_ts = Some(last_ts.map_or(t, |l: u64| l.max(t)));+ }+ }+ // A chat with nothing the person said is a run that never started.+ let prompt = first_prompt?;+ Some(ThreadSummary {+ agent: Agent::ClaudeCode,+ resume: Agent::ClaudeCode.resume_command(&id),+ id,+ title: titles.best().unwrap_or(prompt),+ cwd,+ // The records' own times; a copied file's mtime says nothing.+ last_active_ms: last_ts.unwrap_or(mtime),+ })+}++/// The message a `user` or `assistant` record carries, if it is one the+/// person typed or a reply's text.+fn message(v: &Value) -> Option<Message> {+ let role = match v.get("type").and_then(Value::as_str)? {+ "user" => Role::Person,+ "assistant" => Role::Agent,+ _ => return None,+ };+ let flag = |k: &str| v.get(k).and_then(Value::as_bool).unwrap_or(false);+ if flag("isSidechain") || flag("isMeta") || flag("isCompactSummary") {+ return None;+ }+ let content = v.get("message")?.get("content")?;+ let text = match content {+ Value::String(s) => s.clone(),+ Value::Array(blocks) => blocks+ .iter()+ .filter(|b| b.get("type").and_then(Value::as_str) == Some("text"))+ .filter_map(|b| b.get("text").and_then(Value::as_str))+ .collect::<Vec<_>>()+ .join("\n\n"),+ _ => return None,+ };+ if text.trim().is_empty() || (role == Role::Person && injected(&text)) {+ return None;+ }+ Some(Message {+ key: str_at(v, &["uuid"]).unwrap_or_default().to_string(),+ role,+ text,+ ts_ms: str_at(v, &["timestamp"]).and_then(rfc3339_ms),+ cut: false,+ })+}++pub(crate) fn history(root: &Path, id: &str) -> Result<Option<(ThreadSummary, Vec<Message>)>> {+ let Some(path) = find(root, id) else {+ return Ok(None);+ };+ let mtime = std::fs::metadata(&path).map(|m| mtime_ms(&m)).unwrap_or(0);+ let Some(thread) = summary(&path, mtime) else {+ return Ok(None);+ };+ let mut out = vec![];+ lines::each(&path, |v| {+ if let Some(mut m) = message(&v) {+ if m.key.is_empty() {+ m.key = format!("line-{}", out.len());+ }+ out.push(m);+ }+ })+ .map_err(|source| crate::Error::Io {+ path: path.display().to_string(),+ source,+ })?;+ Ok(Some((thread, out)))+}++fn find(root: &Path, id: &str) -> Option<PathBuf> {+ let name = format!("{id}.jsonl");+ std::fs::read_dir(root.join("projects"))+ .ok()?+ .flatten()+ .map(|p| p.path().join(&name))+ .find(|p| p.is_file())+}diff --git a/libs/cua/crates/cua-agent-threads/src/codex.rs b/libs/cua/crates/cua-agent-threads/src/codex.rsnew file mode 100644index 0000000000..92ed5f65dd--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/src/codex.rs@@ -0,0 +1,245 @@+//! Codex: `<home>/sessions/YYYY/MM/DD/rollout-<time>-<id>.jsonl`, one JSON+//! record per line, and `<home>/session_index.jsonl` (`id`, `thread_name`,+//! `updated_at`) for the names chats were given.+//!+//! The records used: `session_meta` (`payload.id`, `payload.cwd`,+//! `payload.source`), `response_item` with `payload.type` `message`+//! (role `user` with `input_text`, role `assistant` with `output_text`; the+//! `developer` role is Codex's own instructions), and, from older versions,+//! `event_msg` `user_message`/`agent_message` (`payload.message`). As in+//! `codex resume`, only interactive chats are listed: `codex exec` runs,+//! MCP-started and subagent sessions are not.++use std::collections::HashMap;+use std::path::{Path, PathBuf};++use serde_json::Value;++use crate::lines::{self, str_at};+use crate::text::{injected, title};+use crate::{Agent, Message, Result, Role, ThreadSummary, mtime_ms, rfc3339_ms};++const SCAN_FACTOR: usize = 8;+/// The index is read whole up to this size, otherwise its tail only.+const INDEX_MAX: u64 = 4 * 1024 * 1024;++pub(crate) fn recent(root: &Path, limit: usize) -> Vec<ThreadSummary> {+ let mut files = vec![];+ walk(&root.join("sessions"), 0, &mut files);+ files.sort_by_key(|f| std::cmp::Reverse(f.1));+ let names = index(root);+ files+ .into_iter()+ .take(limit * SCAN_FACTOR)+ .filter_map(|(path, mtime)| summary(&path, mtime, &names))+ .take(limit)+ .collect()+}++/// `rollout-*.jsonl` files up to four folders down.+fn walk(dir: &Path, depth: usize, out: &mut Vec<(PathBuf, u64)>) {+ let Ok(entries) = std::fs::read_dir(dir) else {+ return;+ };+ for e in entries.flatten() {+ let Ok(meta) = e.metadata() else { continue };+ let path = e.path();+ if meta.is_dir() && depth < 4 {+ walk(&path, depth + 1, out);+ } else if meta.is_file()+ && path.extension().is_some_and(|x| x == "jsonl")+ && path+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.starts_with("rollout-"))+ {+ out.push((path, mtime_ms(&meta)));+ }+ }+}++/// The chats' names from `session_index.jsonl`, the latest per id.+fn index(root: &Path) -> HashMap<String, String> {+ let path = root.join("session_index.jsonl");+ let mut out = HashMap::new();+ let Ok(meta) = std::fs::metadata(&path) else {+ return out;+ };+ let mut add = |v: &Value| {+ if let (Some(id), Some(name)) = (+ str_at(v, &["id"]),+ str_at(v, &["thread_name"]).and_then(title),+ ) {+ out.insert(id.to_string(), name);+ }+ };+ if meta.len() <= INDEX_MAX {+ let _ = lines::each(&path, |v| add(&v));+ } else if let Ok((_, tail)) = lines::edges(&path) {+ tail.iter().for_each(add);+ }+ out+}++/// A session's sources that are not someone's own chat.+fn interactive(source: Option<&Value>) -> bool {+ match source {+ None | Some(Value::Null) => true,+ Some(Value::String(s)) => {+ matches!(s.as_str(), "cli" | "vscode" | "tui" | "app" | "desktop")+ }+ // `{"subagent": ...}` and other structured sources are spawned.+ Some(_) => false,+ }+}++struct Meta {+ id: String,+ cwd: Option<String>,+}++fn meta(v: &Value) -> Option<Meta> {+ if v.get("type").and_then(Value::as_str) != Some("session_meta") {+ return None;+ }+ let p = v.get("payload")?;+ if !interactive(p.get("source")) {+ return None;+ }+ let id = str_at(p, &["id"]).or_else(|| str_at(p, &["session_id"]))?;+ crate::valid_id(id).then(|| Meta {+ id: id.to_string(),+ cwd: str_at(p, &["cwd"])+ .filter(|s| !s.is_empty())+ .map(String::from),+ })+}++fn summary(path: &Path, mtime: u64, names: &HashMap<String, String>) -> Option<ThreadSummary> {+ let (head, tail) = lines::edges(path).ok()?;+ let m = head.iter().take(8).find_map(meta)?;+ let mut first_prompt = None;+ let mut last_ts = None::<u64>;+ for v in head.iter().chain(tail.iter()) {+ if first_prompt.is_none()+ && let Some(msg) = message(v).or_else(|| event_message(v))+ && msg.role == Role::Person+ {+ first_prompt = title(&msg.text);+ }+ if let Some(t) = str_at(v, &["timestamp"]).and_then(rfc3339_ms) {+ last_ts = Some(last_ts.map_or(t, |l: u64| l.max(t)));+ }+ }+ let prompt = first_prompt?;+ Some(ThreadSummary {+ agent: Agent::Codex,+ resume: Agent::Codex.resume_command(&m.id),+ title: names.get(&m.id).cloned().unwrap_or(prompt),+ id: m.id,+ cwd: m.cwd,+ last_active_ms: last_ts.unwrap_or(mtime),+ })+}++fn texts(content: &Value, kind: &str) -> String {+ match content {+ Value::String(s) => s.clone(),+ Value::Array(items) => items+ .iter()+ .filter(|b| b.get("type").and_then(Value::as_str) == Some(kind))+ .filter_map(|b| b.get("text").and_then(Value::as_str))+ .collect::<Vec<_>>()+ .join("\n\n"),+ _ => String::new(),+ }+}++/// A `response_item` message the person typed or the agent answered.+fn message(v: &Value) -> Option<Message> {+ if v.get("type").and_then(Value::as_str) != Some("response_item") {+ return None;+ }+ let p = v.get("payload")?;+ if p.get("type").and_then(Value::as_str) != Some("message") {+ return None;+ }+ let (role, kind) = match p.get("role").and_then(Value::as_str)? {+ "user" => (Role::Person, "input_text"),+ "assistant" => (Role::Agent, "output_text"),+ _ => return None,+ };+ build(v, p, role, texts(p.get("content")?, kind))+}++/// Older versions: `event_msg` `user_message` / `agent_message`.+fn event_message(v: &Value) -> Option<Message> {+ if v.get("type").and_then(Value::as_str) != Some("event_msg") {+ return None;+ }+ let p = v.get("payload")?;+ let role = match p.get("type").and_then(Value::as_str)? {+ "user_message" => Role::Person,+ "agent_message" => Role::Agent,+ _ => return None,+ };+ build(v, p, role, str_at(p, &["message"])?.to_string())+}++fn build(v: &Value, p: &Value, role: Role, text: String) -> Option<Message> {+ if text.trim().is_empty() || (role == Role::Person && injected(&text)) {+ return None;+ }+ Some(Message {+ key: str_at(p, &["id"]).unwrap_or_default().to_string(),+ role,+ text,+ ts_ms: str_at(v, &["timestamp"]).and_then(rfc3339_ms),+ cut: false,+ })+}++pub(crate) fn history(root: &Path, id: &str) -> Result<Option<(ThreadSummary, Vec<Message>)>> {+ let Some(path) = find(root, id) else {+ return Ok(None);+ };+ let mtime = std::fs::metadata(&path).map(|m| mtime_ms(&m)).unwrap_or(0);+ let Some(thread) = summary(&path, mtime, &index(root)) else {+ return Ok(None);+ };+ if thread.id != id {+ return Ok(None);+ }+ let (mut items, mut events) = (vec![], vec![]);+ lines::each(&path, |v| {+ if let Some(m) = message(&v) {+ items.push(m);+ } else if let Some(m) = event_message(&v) {+ events.push(m);+ }+ })+ .map_err(|source| crate::Error::Io {+ path: path.display().to_string(),+ source,+ })?;+ // Newer rollouts write each message both ways: the response items win.+ let mut out = if items.is_empty() { events } else { items };+ for (i, m) in out.iter_mut().enumerate() {+ if m.key.is_empty() {+ m.key = format!("item-{i}");+ }+ }+ Ok(Some((thread, out)))+}++/// The rollout whose name ends in `-<id>.jsonl`.+fn find(root: &Path, id: &str) -> Option<PathBuf> {+ let mut files = vec![];+ walk(&root.join("sessions"), 0, &mut files);+ let suffix = format!("-{id}.jsonl");+ files.into_iter().map(|(p, _)| p).find(|p| {+ p.file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.ends_with(&suffix))+ })+}diff --git a/libs/cua/crates/cua-agent-threads/src/hermes.rs b/libs/cua/crates/cua-agent-threads/src/hermes.rsnew file mode 100644index 0000000000..2b9aa2226f--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/src/hermes.rs@@ -0,0 +1,219 @@+//! Hermes: `<home>/state.db`, SQLite, opened read-only.+//!+//! The tables used: `sessions` (`id`, and when present `title`, `cwd`,+//! `source`, `parent_session_id`, `hidden`, `archived`, `started_at`,+//! `last_activity_at`, `ended_at`, times in Unix seconds) and `messages`+//! (`session_id`, `role`, `content`, `timestamp`, and `active` when+//! present). Columns differ between versions, so the query uses only those+//! the table has. Scheduled (`cron`) and subagent sessions, child sessions+//! and hidden or archived ones are not listed.++use std::path::Path;++use rusqlite::{Connection, OpenFlags, params};+use serde_json::Value;++use crate::text::{injected, title};+use crate::{Agent, Error, Message, Result, Role, ThreadSummary};++fn open(root: &Path) -> Option<Connection> {+ let path = root.join("state.db");+ if !path.is_file() {+ return None;+ }+ let c = Connection::open_with_flags(+ &path,+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,+ )+ .ok()?;+ let _ = c.busy_timeout(std::time::Duration::from_millis(500));+ Some(c)+}++fn columns(c: &Connection, table: &str) -> Vec<String> {+ let Ok(mut s) = c.prepare(&format!("PRAGMA table_info({table})")) else {+ return vec![];+ };+ s.query_map([], |r| r.get::<_, String>(1))+ .map(|rows| rows.flatten().collect())+ .unwrap_or_default()+}++/// The session query for `cols`: (select list, where clause, order).+fn session_sql(cols: &[String]) -> Option<(String, String, String)> {+ let has = |c: &str| cols.iter().any(|x| x == c);+ if !has("id") {+ return None;+ }+ let col = |c: &str| {+ if has(c) {+ c.to_string()+ } else {+ "NULL".to_string()+ }+ };+ let times: Vec<&str> = ["last_activity_at", "ended_at", "started_at"]+ .into_iter()+ .filter(|c| has(c))+ .collect();+ let when = match times.len() {+ 0 => "0".to_string(),+ 1 => times[0].to_string(),+ _ => format!("COALESCE({})", times.join(", ")),+ };+ let select = format!("id, {}, {}, {when}", col("title"), col("cwd"));+ let mut wh = vec!["1".to_string()];+ if has("source") {+ wh.push("COALESCE(source, '') NOT IN ('cron', 'subagent')".into());+ }+ if has("parent_session_id") {+ wh.push("(parent_session_id IS NULL OR parent_session_id = '')".into());+ }+ for flag in ["hidden", "archived"] {+ if has(flag) {+ wh.push(format!("COALESCE({flag}, 0) = 0"));+ }+ }+ Some((select, wh.join(" AND "), format!("{when} DESC")))+}++struct Row {+ id: String,+ title: Option<String>,+ cwd: Option<String>,+ when_s: f64,+}++fn rows(c: &Connection, extra: &str, limit: usize, id: Option<&str>) -> Vec<Row> {+ let Some((select, wh, order)) = session_sql(&columns(c, "sessions")) else {+ return vec![];+ };+ let sql = format!("SELECT {select} FROM sessions WHERE {wh}{extra} ORDER BY {order} LIMIT ?1");+ let Ok(mut s) = c.prepare(&sql) else {+ return vec![];+ };+ let map = |r: &rusqlite::Row| {+ Ok(Row {+ id: r.get(0)?,+ title: r.get::<_, Option<String>>(1).ok().flatten(),+ cwd: r.get::<_, Option<String>>(2).ok().flatten(),+ when_s: r.get::<_, Option<f64>>(3).ok().flatten().unwrap_or(0.0),+ })+ };+ let got = match id {+ Some(id) => s.query_map(params![limit as i64, id], map),+ None => s.query_map(params![limit as i64], map),+ };+ got.map(|rows| rows.flatten().collect()).unwrap_or_default()+}++/// The text of a message's `content`: plain, or a JSON list of parts.+fn content_text(raw: &str) -> String {+ let t = raw.trim_start();+ if t.starts_with('[')+ && let Ok(Value::Array(parts)) = serde_json::from_str::<Value>(t)+ {+ return parts+ .iter()+ .filter(|p| {+ p.get("type")+ .and_then(Value::as_str)+ .is_none_or(|k| k == "text")+ })+ .filter_map(|p| p.get("text").and_then(Value::as_str))+ .collect::<Vec<_>>()+ .join("\n\n");+ }+ raw.to_string()+}++fn first_prompt(c: &Connection, session: &str) -> Option<String> {+ let mut s = c+ .prepare("SELECT content FROM messages WHERE session_id = ?1 AND role = 'user' ORDER BY id LIMIT 20")+ .ok()?;+ let found = s+ .query_map(params![session], |r| r.get::<_, Option<String>>(0))+ .ok()?+ .flatten()+ .flatten()+ .map(|c| content_text(&c))+ .find(|t| !injected(t));+ found.and_then(|t| title(&t))+}++fn summary(c: &Connection, r: Row) -> Option<ThreadSummary> {+ if !crate::valid_id(&r.id) {+ return None;+ }+ // A session nobody typed into is not a chat.+ let prompt = first_prompt(c, &r.id)?;+ Some(ThreadSummary {+ agent: Agent::Hermes,+ resume: Agent::Hermes.resume_command(&r.id),+ title: r.title.as_deref().and_then(title).unwrap_or(prompt),+ cwd: r.cwd.filter(|s| !s.is_empty()),+ last_active_ms: (r.when_s.max(0.0) * 1000.0) as u64,+ id: r.id,+ })+}++pub(crate) fn recent(root: &Path, limit: usize) -> Vec<ThreadSummary> {+ let Some(c) = open(root) else { return vec![] };+ rows(&c, "", limit * 4, None)+ .into_iter()+ .filter_map(|r| summary(&c, r))+ .take(limit)+ .collect()+}++pub(crate) fn history(root: &Path, id: &str) -> Result<Option<(ThreadSummary, Vec<Message>)>> {+ let Some(c) = open(root) else { return Ok(None) };+ let Some(row) = rows(&c, " AND id = ?2", 1, Some(id)).into_iter().next() else {+ return Ok(None);+ };+ let Some(thread) = summary(&c, row) else {+ return Ok(None);+ };+ let active = if columns(&c, "messages").iter().any(|c| c == "active") {+ " AND COALESCE(active, 1) = 1"+ } else {+ ""+ };+ let sql = format!(+ "SELECT id, role, content, timestamp FROM messages \+ WHERE session_id = ?1 AND role IN ('user', 'assistant'){active} ORDER BY id"+ );+ let sqlite = |e: rusqlite::Error| Error::Sqlite(e.to_string());+ let mut s = c.prepare(&sql).map_err(sqlite)?;+ let messages = s+ .query_map(params![id], |r| {+ Ok((+ r.get::<_, i64>(0)?,+ r.get::<_, String>(1)?,+ r.get::<_, Option<String>>(2)?,+ r.get::<_, Option<f64>>(3).ok().flatten(),+ ))+ })+ .map_err(sqlite)?+ .flatten()+ .filter_map(|(key, role, content, ts)| {+ let role = if role == "user" {+ Role::Person+ } else {+ Role::Agent+ };+ let text = content_text(&content?);+ if text.trim().is_empty() || (role == Role::Person && injected(&text)) {+ return None;+ }+ Some(Message {+ key: key.to_string(),+ role,+ text,+ ts_ms: ts.map(|s| (s.max(0.0) * 1000.0) as u64),+ cut: false,+ })+ })+ .collect();+ Ok(Some((thread, messages)))+}diff --git a/libs/cua/crates/cua-agent-threads/src/lib.rs b/libs/cua/crates/cua-agent-threads/src/lib.rsnew file mode 100644index 0000000000..0a36b3d37f--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/src/lib.rs@@ -0,0 +1,347 @@+//! The coding agents' own recent chats on this computer, read-only:+//! Claude Code (`~/.claude/projects`), Codex (`~/.codex/sessions`) and+//! Hermes (`~/.hermes/state.db`).+//!+//! [`recent`] lists the newest chats with only what a picker shows: a title+//! (or the first prompt, cut short), the working folder and the last+//! activity. [`history`] reads one chat's messages (what the person and the+//! agent said, no tool calls or outputs) once the person picked it.+//!+//! Nothing here writes, caches or sends anything. Each agent's store stays+//! the source of truth, and every format is read defensively: a record,+//! column or line this crate does not know is skipped, a file it cannot read+//! is left out, and large files are read from their head and tail only when+//! listing.++use std::path::{Path, PathBuf};++use serde::{Deserialize, Serialize};++mod claude;+mod codex;+mod hermes;+mod lines;+mod text;++pub use text::{TITLE_MAX, truncate_chars};++/// A message in [`history`] is cut to this many bytes (on a char boundary).+pub const MESSAGE_MAX_BYTES: usize = 8 * 1024;+/// [`history`] keeps at most this many of the newest messages by default.+pub const HISTORY_DEFAULT: usize = 200;+/// [`recent`] lists at most this many chats.+pub const RECENT_MAX: usize = 50;++/// A coding agent whose chats this crate reads. The ids are the harness ids+/// `agent_start` takes.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum Agent {+ #[serde(rename = "claude-code")]+ ClaudeCode,+ #[serde(rename = "openai-codex", alias = "codex")]+ Codex,+ #[serde(rename = "hermes")]+ Hermes,+}++impl Agent {+ pub const ALL: [Agent; 3] = [Agent::ClaudeCode, Agent::Codex, Agent::Hermes];++ /// The harness id (`claude-code`, `openai-codex`, `hermes`).+ pub fn id(self) -> &'static str {+ match self {+ Agent::ClaudeCode => "claude-code",+ Agent::Codex => "openai-codex",+ Agent::Hermes => "hermes",+ }+ }++ /// Parses a harness id or the agent-setup id (`codex`).+ pub fn parse(s: &str) -> Option<Agent> {+ match s {+ "claude-code" | "claude" => Some(Agent::ClaudeCode),+ "openai-codex" | "codex" => Some(Agent::Codex),+ "hermes" => Some(Agent::Hermes),+ _ => None,+ }+ }++ /// The agent's own command that resumes chat `id` in a terminal (run it+ /// in the chat's folder).+ pub fn resume_command(self, id: &str) -> Vec<String> {+ let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();+ match self {+ Agent::ClaudeCode => v(&["claude", "--resume", id]),+ Agent::Codex => v(&["codex", "resume", id]),+ Agent::Hermes => v(&["hermes", "--resume", id]),+ }+ }+}++/// Where each agent keeps its chats. `None` skips that agent.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct Roots {+ /// Claude Code's config folder (`~/.claude`, or `$CLAUDE_CONFIG_DIR`).+ pub claude: Option<PathBuf>,+ /// Codex's home (`~/.codex`, or `$CODEX_HOME`).+ pub codex: Option<PathBuf>,+ /// Hermes's home (`~/.hermes`, or `$HERMES_HOME`).+ pub hermes: Option<PathBuf>,+}++impl Roots {+ /// The default folders under `home`.+ pub fn under_home(home: &Path) -> Roots {+ Roots {+ claude: Some(home.join(".claude")),+ codex: Some(home.join(".codex")),+ hermes: Some(home.join(".hermes")),+ }+ }++ /// This user's folders: each agent's own variable when set, otherwise+ /// the default under the home folder.+ pub fn from_env() -> Roots {+ let home = home_dir();+ let pick = |var: &str, default: &str| {+ std::env::var_os(var)+ .filter(|v| !v.is_empty())+ .map(PathBuf::from)+ .or_else(|| home.as_ref().map(|h| h.join(default)))+ };+ Roots {+ claude: pick("CLAUDE_CONFIG_DIR", ".claude"),+ codex: pick("CODEX_HOME", ".codex"),+ hermes: pick("HERMES_HOME", ".hermes"),+ }+ }++ fn root(&self, agent: Agent) -> Option<&Path> {+ match agent {+ Agent::ClaudeCode => self.claude.as_deref(),+ Agent::Codex => self.codex.as_deref(),+ Agent::Hermes => self.hermes.as_deref(),+ }+ }+}++fn home_dir() -> Option<PathBuf> {+ let var = if cfg!(windows) { "USERPROFILE" } else { "HOME" };+ std::env::var_os(var)+ .filter(|v| !v.is_empty())+ .map(PathBuf::from)+}++/// One chat, as a picker lists it.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct ThreadSummary {+ pub agent: Agent,+ /// The agent's own session id.+ pub id: String,+ /// The chat's title, or its first prompt, cut to [`TITLE_MAX`]+ /// characters on one line.+ pub title: String,+ /// The folder the chat worked in, when the store records one.+ pub cwd: Option<String>,+ /// The last activity (Unix ms).+ pub last_active_ms: u64,+ /// The agent's own command that resumes it in a terminal.+ pub resume: Vec<String>,+}++/// Who said a message.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum Role {+ /// The person (this computer's user).+ Person,+ /// The agent.+ Agent,+}++/// One message of a chat.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct Message {+ /// A stable id within the chat (the store's own record id when it has one).+ pub key: String,+ pub role: Role,+ /// The text, cut to [`MESSAGE_MAX_BYTES`].+ pub text: String,+ /// When it was said (Unix ms), when the store records it.+ pub ts_ms: Option<u64>,+ /// The text was cut.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub cut: bool,+}++/// One chat's messages, oldest first.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct ThreadHistory {+ pub thread: ThreadSummary,+ pub messages: Vec<Message>,+ /// Older messages were left out (more than the limit).+ pub earlier_omitted: usize,+}++/// What [`recent`] lists.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct ListOptions {+ /// The agents to look at (default: all three).+ pub agents: Vec<Agent>,+ /// How many chats in all, newest first (at most [`RECENT_MAX`]).+ pub limit: usize,+}++impl Default for ListOptions {+ fn default() -> Self {+ ListOptions {+ agents: Agent::ALL.to_vec(),+ limit: 4,+ }+ }+}++#[derive(Debug, thiserror::Error)]+pub enum Error {+ #[error("no {agent} chat {id} on this computer")]+ NotFound { agent: &'static str, id: String },+ #[error("{0}")]+ Invalid(String),+ #[error("couldn't read {path}: {source}")]+ Io {+ path: String,+ #[source]+ source: std::io::Error,+ },+ #[error("couldn't read Hermes's sessions: {0}")]+ Sqlite(String),+}++pub type Result<T> = std::result::Result<T, Error>;++/// The newest chats of the agents in `opts`, newest first. An agent whose+/// store is missing or unreadable adds nothing.+pub fn recent(roots: &Roots, opts: &ListOptions) -> Vec<ThreadSummary> {+ let limit = opts.limit.clamp(1, RECENT_MAX);+ let mut all = vec![];+ for agent in &opts.agents {+ let Some(root) = roots.root(*agent) else {+ continue;+ };+ let found = match agent {+ Agent::ClaudeCode => claude::recent(root, limit),+ Agent::Codex => codex::recent(root, limit),+ Agent::Hermes => hermes::recent(root, limit),+ };+ all.extend(found);+ }+ all.sort_by(|a, b| {+ b.last_active_ms+ .cmp(&a.last_active_ms)+ .then_with(|| a.id.cmp(&b.id))+ });+ all.truncate(limit);+ all+}++/// One chat's messages, the newest `max_messages` of them (default+/// [`HISTORY_DEFAULT`]).+pub fn history(+ roots: &Roots,+ agent: Agent,+ id: &str,+ max_messages: Option<usize>,+) -> Result<ThreadHistory> {+ if !valid_id(id) {+ return Err(Error::Invalid(format!("{id:?} is not a session id")));+ }+ let not_found = || Error::NotFound {+ agent: agent.id(),+ id: id.to_string(),+ };+ let root = roots.root(agent).ok_or_else(not_found)?;+ let max = max_messages.unwrap_or(HISTORY_DEFAULT).clamp(1, 5000);+ let (thread, messages) = match agent {+ Agent::ClaudeCode => claude::history(root, id)?,+ Agent::Codex => codex::history(root, id)?,+ Agent::Hermes => hermes::history(root, id)?,+ }+ .ok_or_else(not_found)?;+ let mut messages = text::merge_agent_runs(messages);+ let earlier_omitted = messages.len().saturating_sub(max);+ messages.drain(..earlier_omitted);+ for m in &mut messages {+ let (t, cut) = text::cut_bytes(&m.text, MESSAGE_MAX_BYTES);+ m.cut |= cut;+ m.text = t;+ }+ Ok(ThreadHistory {+ thread,+ messages,+ earlier_omitted,+ })+}++/// A session id: 1 to 128 letters, digits, `-`, `_` or `.` (never a path).+pub fn valid_id(id: &str) -> bool {+ !id.is_empty()+ && id.len() <= 128+ && id != "."+ && id != ".."+ && id+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))+}++/// An RFC 3339 time as Unix ms.+pub(crate) fn rfc3339_ms(s: &str) -> Option<u64> {+ chrono::DateTime::parse_from_rfc3339(s)+ .ok()+ .and_then(|t| u64::try_from(t.timestamp_millis()).ok())+}++/// A file's modification time as Unix ms.+pub(crate) fn mtime_ms(meta: &std::fs::Metadata) -> u64 {+ meta.modified()+ .ok()+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|d| d.as_millis() as u64)+ .unwrap_or(0)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ids_never_name_a_path() {+ assert!(valid_id("0b1e5c2a-1111-4222-8333-944445555666"));+ assert!(valid_id("20261104_101112_ab12cd"));+ for bad in [+ "",+ ".",+ "..",+ "../x",+ "a/b",+ "a\\b",+ "x y",+ &"a".repeat(129),+ ] {+ assert!(!valid_id(bad), "{bad:?}");+ }+ }++ #[test]+ fn agent_ids_round_trip() {+ for a in Agent::ALL {+ assert_eq!(Agent::parse(a.id()), Some(a));+ let j = serde_json::to_string(&a).unwrap();+ assert_eq!(serde_json::from_str::<Agent>(&j).unwrap(), a);+ }+ assert_eq!(Agent::parse("codex"), Some(Agent::Codex));+ assert_eq!(+ Agent::Codex.resume_command("x"),+ vec!["codex".to_string(), "resume".into(), "x".into()]+ );+ }+}diff --git a/libs/cua/crates/cua-agent-threads/src/lines.rs b/libs/cua/crates/cua-agent-threads/src/lines.rsnew file mode 100644index 0000000000..be5b1c71ed--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/src/lines.rs@@ -0,0 +1,150 @@+//! JSON Lines, read in bounded pieces: the head and tail of a file for a+//! listing, and every line (skipping any too long to be a message) for a+//! history.++use std::fs::File;+use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};+use std::path::Path;++use serde_json::Value;++/// Bytes read from each end of a file for a listing.+pub(crate) const EDGE_BYTES: u64 = 256 * 1024;+/// A line longer than this (an image, a huge tool output) is skipped.+pub(crate) const LINE_MAX: usize = 8 * 1024 * 1024;++/// The whole JSON objects in the first [`EDGE_BYTES`] of `path`, and those in+/// the last [`EDGE_BYTES`] (empty when the head already covered the file).+pub(crate) fn edges(path: &Path) -> std::io::Result<(Vec<Value>, Vec<Value>)> {+ let mut f = File::open(path)?;+ let len = f.metadata()?.len();+ let mut head = vec![];+ (&mut f).take(EDGE_BYTES).read_to_end(&mut head)?;+ let whole = len <= EDGE_BYTES;+ let head_objs = parse(&head, false, !whole);+ if whole {+ return Ok((head_objs, vec![]));+ }+ let start = len.saturating_sub(EDGE_BYTES).max(EDGE_BYTES);+ if start >= len {+ return Ok((head_objs, vec![]));+ }+ f.seek(SeekFrom::Start(start))?;+ let mut tail = vec![];+ f.take(len - start).read_to_end(&mut tail)?;+ Ok((head_objs, parse(&tail, true, false)))+}++/// The objects in `buf`, one per line. `skip_first`/`skip_last` drop a line+/// cut by the read's edge.+fn parse(buf: &[u8], skip_first: bool, skip_last: bool) -> Vec<Value> {+ let mut parts: Vec<&[u8]> = buf.split(|b| *b == b'\n').collect();+ if skip_first && !parts.is_empty() {+ parts.remove(0);+ }+ if skip_last {+ parts.pop();+ }+ parts.into_iter().filter_map(object).collect()+}++fn object(line: &[u8]) -> Option<Value> {+ let line = line.trim_ascii();+ if line.first() != Some(&b'{') {+ return None;+ }+ serde_json::from_slice::<Value>(line)+ .ok()+ .filter(Value::is_object)+}++/// Calls `f` with every JSON object line of `path`, in order. Lines over+/// [`LINE_MAX`] and lines that are not JSON objects are skipped.+pub(crate) fn each(path: &Path, mut f: impl FnMut(Value)) -> std::io::Result<()> {+ let mut r = BufReader::with_capacity(64 * 1024, File::open(path)?);+ let mut line: Vec<u8> = vec![];+ let mut too_long = false;+ loop {+ let buf = r.fill_buf()?;+ if buf.is_empty() {+ if !too_long && let Some(v) = object(&line) {+ f(v);+ }+ return Ok(());+ }+ let (chunk, done) = match buf.iter().position(|b| *b == b'\n') {+ Some(i) => (&buf[..i], Some(i + 1)),+ None => (buf, None),+ };+ if !too_long {+ if line.len() + chunk.len() > LINE_MAX {+ too_long = true;+ line.clear();+ } else {+ line.extend_from_slice(chunk);+ }+ }+ let used = done.unwrap_or(buf.len());+ r.consume(used);+ if done.is_some() {+ if !too_long && let Some(v) = object(&line) {+ f(v);+ }+ line.clear();+ too_long = false;+ }+ }+}++/// `v[a][b]...` as a string.+pub(crate) fn str_at<'a>(v: &'a Value, path: &[&str]) -> Option<&'a str> {+ let mut cur = v;+ for k in path {+ cur = cur.get(k)?;+ }+ cur.as_str()+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Write;++ #[test]+ fn edges_drop_cut_lines_and_bad_json() {+ let dir = tempfile::tempdir().unwrap();+ let p = dir.path().join("a.jsonl");+ let mut f = File::create(&p).unwrap();+ writeln!(f, "{{\"n\":0}}").unwrap();+ writeln!(f, "not json").unwrap();+ let pad = "x".repeat(1000);+ for n in 1..1000 {+ writeln!(f, "{{\"n\":{n},\"pad\":\"{pad}\"}}").unwrap();+ }+ drop(f);+ let (head, tail) = edges(&p).unwrap();+ assert_eq!(head[0]["n"], 0);+ assert!(head.iter().all(|v| v.is_object()));+ assert_eq!(tail.last().unwrap()["n"], 999);+ // Every object read is whole.+ assert!(+ tail.iter()+ .all(|v| v["pad"].as_str().unwrap().len() == 1000)+ );+ }++ #[test]+ fn each_skips_a_line_too_long() {+ let dir = tempfile::tempdir().unwrap();+ let p = dir.path().join("b.jsonl");+ let mut f = File::create(&p).unwrap();+ writeln!(f, "{{\"n\":1}}").unwrap();+ writeln!(f, "{{\"big\":\"{}\"}}", "y".repeat(LINE_MAX + 10)).unwrap();+ write!(f, "{{\"n\":3}}").unwrap();+ drop(f);+ let mut seen = vec![];+ each(&p, |v| seen.push(v)).unwrap();+ assert_eq!(seen.len(), 2);+ assert_eq!(seen[1]["n"], 3);+ }+}diff --git a/libs/cua/crates/cua-agent-threads/src/text.rs b/libs/cua/crates/cua-agent-threads/src/text.rsnew file mode 100644index 0000000000..405f252dce--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/src/text.rs@@ -0,0 +1,152 @@+//! Titles, cut text and the lines an agent writes into its own chat (not+//! what the person typed).++use crate::{Message, Role};++/// A title or first prompt is cut to this many characters.+pub const TITLE_MAX: usize = 80;++/// `s` on one line (runs of whitespace become one space), cut to `max`+/// characters with an ellipsis.+pub fn truncate_chars(s: &str, max: usize) -> String {+ let flat = s.split_whitespace().collect::<Vec<_>>().join(" ");+ if flat.chars().count() <= max {+ return flat;+ }+ let mut out: String = flat.chars().take(max.saturating_sub(1)).collect();+ out.truncate(out.trim_end().len());+ out.push('…');+ out+}++/// A title from a store, or `None` when it is blank.+pub(crate) fn title(s: &str) -> Option<String> {+ let t = truncate_chars(s, TITLE_MAX);+ (!t.is_empty()).then_some(t)+}++/// `s` cut to at most `max` bytes on a char boundary, and whether it was cut.+pub(crate) fn cut_bytes(s: &str, max: usize) -> (String, bool) {+ if s.len() <= max {+ return (s.to_string(), false);+ }+ let mut end = max;+ while !s.is_char_boundary(end) {+ end -= 1;+ }+ (s[..end].to_string(), true)+}++/// Tags an agent puts into the person's turn itself: slash-command+/// echoes, hook and task notifications, environment preambles.+const INJECTED_TAGS: &[&str] = &[+ "command-name",+ "command-message",+ "command-args",+ "command-contents",+ "local-command-stdout",+ "local-command-stderr",+ "local-command-caveat",+ "task-notification",+ "system-reminder",+ "user-prompt-submit-hook",+ "bash-input",+ "bash-stdout",+ "bash-stderr",+ "environment_context",+ "user_instructions",+ "permissions",+ "turn_aborted",+];++/// Whether a "user" message is one the agent wrote itself (an injected+/// preamble or notification), not one the person typed.+pub(crate) fn injected(text: &str) -> bool {+ let t = text.trim_start();+ if t.is_empty() || t.starts_with("# AGENTS.md instructions") || t.starts_with("Caveat: ") {+ return true;+ }+ let Some(rest) = t.strip_prefix('<') else {+ return false;+ };+ let tag: String = rest+ .chars()+ .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))+ .collect();+ INJECTED_TAGS.contains(&tag.as_str())+}++/// Consecutive agent messages (one reply split around tool calls) as one.+pub(crate) fn merge_agent_runs(messages: Vec<Message>) -> Vec<Message> {+ let mut out: Vec<Message> = Vec::with_capacity(messages.len());+ for m in messages {+ if m.text.trim().is_empty() {+ continue;+ }+ match out.last_mut() {+ Some(last) if last.role == Role::Agent && m.role == Role::Agent => {+ last.text.push_str("\n\n");+ last.text.push_str(&m.text);+ last.cut |= m.cut;+ if m.ts_ms.is_some() {+ last.ts_ms = last.ts_ms.or(m.ts_ms);+ }+ }+ _ => out.push(m),+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn titles_are_one_short_line() {+ assert_eq!(truncate_chars(" fix\n the tests ", 80), "fix the tests");+ let long = "word ".repeat(40);+ let t = truncate_chars(&long, 20);+ assert_eq!(t.chars().count(), 20);+ assert!(t.ends_with('…'));+ assert_eq!(title(" \n "), None);+ }++ #[test]+ fn cuts_on_a_char_boundary() {+ let (t, cut) = cut_bytes("ééé", 3);+ assert_eq!((t.as_str(), cut), ("é", true));+ assert_eq!(cut_bytes("abc", 3), ("abc".into(), false));+ }++ #[test]+ fn knows_what_the_agent_injected() {+ assert!(injected("<command-name>/clear</command-name>"));+ assert!(injected(" <environment_context>\n<cwd>/x</cwd>"));+ assert!(injected("# AGENTS.md instructions for /x"));+ assert!(injected(""));+ assert!(!injected("<div> renders wrong in Safari"));+ assert!(!injected("fix the flaky upload test"));+ }++ #[test]+ fn merges_one_reply_split_by_tools() {+ let m = |role, text: &str| Message {+ key: text.into(),+ role,+ text: text.into(),+ ts_ms: None,+ cut: false,+ };+ let out = merge_agent_runs(vec![+ m(Role::Person, "a"),+ m(Role::Agent, "b"),+ m(Role::Agent, " "),+ m(Role::Agent, "c"),+ m(Role::Person, "d"),+ ]);+ assert_eq!(out.len(), 3);+ assert_eq!(out[1].text, "b\n\nc");+ assert_eq!(out[1].key, "b");+ }+}diff --git a/libs/cua/crates/cua-agent-threads/tests/fixtures/claude/0b1e5c2a-1111-4222-8333-944445555666.jsonl b/libs/cua/crates/cua-agent-threads/tests/fixtures/claude/0b1e5c2a-1111-4222-8333-944445555666.jsonlnew file mode 100644index 0000000000..0998a953f1--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/tests/fixtures/claude/0b1e5c2a-1111-4222-8333-944445555666.jsonl@@ -0,0 +1,16 @@+{"type":"session-owner","sessionId":"0b1e5c2a-1111-4222-8333-944445555666"}+{"type":"queue-operation","operation":"enqueue","timestamp":"2026-11-02T09:00:00.000Z","sessionId":"0b1e5c2a-1111-4222-8333-944445555666","content":"x"}+{"type":"user","isMeta":true,"uuid":"m0","timestamp":"2026-11-02T09:00:00.500Z","cwd":"/Users/sam/code/kettle","sessionId":"0b1e5c2a-1111-4222-8333-944445555666","message":{"role":"user","content":"Caveat: the messages below were generated by the user while running local commands."}}+{"type":"user","uuid":"m1","timestamp":"2026-11-02T09:00:01.000Z","cwd":"/Users/sam/code/kettle","sessionId":"0b1e5c2a-1111-4222-8333-944445555666","message":{"role":"user","content":"<command-name>/clear</command-name>"}}+{"type":"user","uuid":"m2","timestamp":"2026-11-02T09:00:02.000Z","cwd":"/Users/sam/code/kettle","sessionId":"0b1e5c2a-1111-4222-8333-944445555666","message":{"role":"user","content":"The kettle timer test fails on CI but passes locally, can you find out why?"}}+this line is not json+{"type":"ai-title","aiTitle":"Flaky kettle timer test","sessionId":"0b1e5c2a-1111-4222-8333-944445555666"}+{"type":"assistant","uuid":"a1","timestamp":"2026-11-02T09:00:05.000Z","sessionId":"0b1e5c2a-1111-4222-8333-944445555666","message":{"id":"msg_1","role":"assistant","content":[{"type":"thinking","thinking":"secret thoughts"},{"type":"text","text":"Let me look at the timer test."}]}}+{"type":"assistant","uuid":"a2","timestamp":"2026-11-02T09:00:06.000Z","sessionId":"0b1e5c2a-1111-4222-8333-944445555666","message":{"id":"msg_1","role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"npm test"}}]}}+{"type":"user","uuid":"r1","timestamp":"2026-11-02T09:00:07.000Z","sessionId":"0b1e5c2a-1111-4222-8333-944445555666","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"1 failing"}]}}+{"type":"assistant","uuid":"a3","timestamp":"2026-11-02T09:00:09.000Z","sessionId":"0b1e5c2a-1111-4222-8333-944445555666","message":{"id":"msg_2","role":"assistant","content":[{"type":"text","text":"It depends on the machine's time zone."}]}}+{"type":"assistant","uuid":"s1","isSidechain":true,"timestamp":"2026-11-02T09:00:10.000Z","sessionId":"0b1e5c2a-1111-4222-8333-944445555666","message":{"role":"assistant","content":[{"type":"text","text":"a subagent's reply"}]}}+{"type":"user","uuid":"m3","timestamp":"2026-11-02T09:01:00.000Z","sessionId":"0b1e5c2a-1111-4222-8333-944445555666","message":{"role":"user","content":[{"type":"text","text":"Pin it to UTC then."}]}}+{"type":"some-future-record","whatever":{"nested":true}}+{"type":"custom-title","customTitle":"Kettle timer on CI","sessionId":"0b1e5c2a-1111-4222-8333-944445555666"}+{"type":"assistant","uuid":"a4","timestamp":"2026-11-02T09:02:00.000Z","sessionId":"0b1e5c2a-1111-4222-8333-944445555666","message":{"role":"assistant","content":[{"type":"text","text":"Done: the test now sets TZ=UTC."}]}}diff --git a/libs/cua/crates/cua-agent-threads/tests/fixtures/claude/77777777-aaaa-4bbb-8ccc-dddddddddddd.jsonl b/libs/cua/crates/cua-agent-threads/tests/fixtures/claude/77777777-aaaa-4bbb-8ccc-dddddddddddd.jsonlnew file mode 100644index 0000000000..951ea6709c--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/tests/fixtures/claude/77777777-aaaa-4bbb-8ccc-dddddddddddd.jsonl@@ -0,0 +1,2 @@+{"type":"user","uuid":"u1","timestamp":"2026-11-03T18:30:00.000Z","cwd":"/Users/sam/code/garden-planner","sessionId":"77777777-aaaa-4bbb-8ccc-dddddddddddd","message":{"role":"user","content":"Add a frost date column to the planting table and sort the beds by it, newest first please"}}+{"type":"assistant","uuid":"u2","timestamp":"2026-11-03T18:31:00.000Z","sessionId":"77777777-aaaa-4bbb-8ccc-dddddddddddd","message":{"role":"assistant","content":[{"type":"text","text":"Added it."}]}}diff --git a/libs/cua/crates/cua-agent-threads/tests/fixtures/claude/99999999-0000-4000-8000-000000000000.jsonl b/libs/cua/crates/cua-agent-threads/tests/fixtures/claude/99999999-0000-4000-8000-000000000000.jsonlnew file mode 100644index 0000000000..3929efc4cc--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/tests/fixtures/claude/99999999-0000-4000-8000-000000000000.jsonl@@ -0,0 +1,2 @@+{"type":"session-owner","sessionId":"99999999-0000-4000-8000-000000000000"}+{"type":"user","isMeta":true,"uuid":"x","timestamp":"2026-11-04T07:00:00.000Z","cwd":"/tmp","message":{"role":"user","content":"meta only"}}diff --git a/libs/cua/crates/cua-agent-threads/tests/fixtures/codex/rollout-2025-06-01T12-00-00-0ld0ld00-1111-4111-8111-111111111111.jsonl b/libs/cua/crates/cua-agent-threads/tests/fixtures/codex/rollout-2025-06-01T12-00-00-0ld0ld00-1111-4111-8111-111111111111.jsonlnew file mode 100644index 0000000000..63938dfa4c--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/tests/fixtures/codex/rollout-2025-06-01T12-00-00-0ld0ld00-1111-4111-8111-111111111111.jsonl@@ -0,0 +1,3 @@+{"timestamp":"2025-06-01T12:00:00.000Z","type":"session_meta","payload":{"id":"0ld0ld00-1111-4111-8111-111111111111","cwd":"/Users/sam/code/old"}}+{"timestamp":"2025-06-01T12:00:01.000Z","type":"event_msg","payload":{"type":"user_message","message":"rename the config loader"}}+{"timestamp":"2025-06-01T12:00:02.000Z","type":"event_msg","payload":{"type":"agent_message","message":"Renamed."}}diff --git a/libs/cua/crates/cua-agent-threads/tests/fixtures/codex/rollout-2026-11-03T10-00-00-5f0c1d2e-3a4b-4c5d-8e6f-708192a3b4c5.jsonl b/libs/cua/crates/cua-agent-threads/tests/fixtures/codex/rollout-2026-11-03T10-00-00-5f0c1d2e-3a4b-4c5d-8e6f-708192a3b4c5.jsonlnew file mode 100644index 0000000000..9f617ad7e1--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/tests/fixtures/codex/rollout-2026-11-03T10-00-00-5f0c1d2e-3a4b-4c5d-8e6f-708192a3b4c5.jsonl@@ -0,0 +1,12 @@+{"timestamp":"2026-11-03T10:00:00.000Z","type":"session_meta","payload":{"id":"5f0c1d2e-3a4b-4c5d-8e6f-708192a3b4c5","timestamp":"2026-11-03T10:00:00.000Z","cwd":"/Users/sam/code/bike-shop","originator":"codex_cli_rs","source":"cli","git":{"branch":"main"}}}+{"timestamp":"2026-11-03T10:00:01.000Z","type":"response_item","payload":{"type":"message","role":"developer","content":[{"type":"input_text","text":"You are Codex."}]}}+{"timestamp":"2026-11-03T10:00:01.100Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"# AGENTS.md instructions for /Users/sam/code/bike-shop\n\nUse pnpm."}]}}+{"timestamp":"2026-11-03T10:00:01.200Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"<environment_context>\n <cwd>/Users/sam/code/bike-shop</cwd>\n</environment_context>"}]}}+{"timestamp":"2026-11-03T10:00:02.000Z","type":"response_item","payload":{"type":"message","id":"u-1","role":"user","content":[{"type":"input_text","text":"Why does checkout double-charge when the coupon is applied twice?"}]}}+{"timestamp":"2026-11-03T10:00:02.000Z","type":"event_msg","payload":{"type":"user_message","message":"Why does checkout double-charge when the coupon is applied twice?"}}+{"timestamp":"2026-11-03T10:00:03.000Z","type":"response_item","payload":{"type":"reasoning","summary":[],"encrypted_content":"zzz"}}+{"timestamp":"2026-11-03T10:00:04.000Z","type":"response_item","payload":{"type":"function_call","name":"shell","arguments":"{}","call_id":"c1"}}+{"timestamp":"2026-11-03T10:00:05.000Z","type":"response_item","payload":{"type":"function_call_output","call_id":"c1","output":"ok"}}+{"timestamp":"2026-11-03T10:00:06.000Z","type":"response_item","payload":{"type":"message","id":"a-1","role":"assistant","content":[{"type":"output_text","text":"The coupon handler isn't idempotent."}]}}+{"timestamp":"2026-11-03T10:00:06.000Z","type":"event_msg","payload":{"type":"agent_message","message":"The coupon handler isn't idempotent."}}+{"timestamp":"2026-11-03T10:05:00.000Z","type":"world_state","payload":{"full":true}}diff --git a/libs/cua/crates/cua-agent-threads/tests/fixtures/codex/rollout-2026-11-04T08-00-00-1a2b3c4d-0000-4000-8000-aaaaaaaaaaaa.jsonl b/libs/cua/crates/cua-agent-threads/tests/fixtures/codex/rollout-2026-11-04T08-00-00-1a2b3c4d-0000-4000-8000-aaaaaaaaaaaa.jsonlnew file mode 100644index 0000000000..282977e99e--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/tests/fixtures/codex/rollout-2026-11-04T08-00-00-1a2b3c4d-0000-4000-8000-aaaaaaaaaaaa.jsonl@@ -0,0 +1,2 @@+{"timestamp":"2026-11-04T08:00:00.000Z","type":"session_meta","payload":{"id":"1a2b3c4d-0000-4000-8000-aaaaaaaaaaaa","cwd":"/tmp/ci","originator":"codex_exec","source":"exec"}}+{"timestamp":"2026-11-04T08:00:01.000Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"a scripted exec run"}]}}diff --git a/libs/cua/crates/cua-agent-threads/tests/fixtures/codex/session_index.jsonl b/libs/cua/crates/cua-agent-threads/tests/fixtures/codex/session_index.jsonlnew file mode 100644index 0000000000..ea9f6983f6--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/tests/fixtures/codex/session_index.jsonl@@ -0,0 +1,2 @@+{"id":"5f0c1d2e-3a4b-4c5d-8e6f-708192a3b4c5","thread_name":"Coupon applied twice","updated_at":"2026-11-03T10:01:00Z"}+{"id":"5f0c1d2e-3a4b-4c5d-8e6f-708192a3b4c5","thread_name":"Checkout double charge","updated_at":"2026-11-03T10:06:00Z"}diff --git a/libs/cua/crates/cua-agent-threads/tests/threads.rs b/libs/cua/crates/cua-agent-threads/tests/threads.rsnew file mode 100644index 0000000000..9f06b416b1--- /dev/null+++ b/libs/cua/crates/cua-agent-threads/tests/threads.rs@@ -0,0 +1,364 @@+//! The lister and reader against made-up stores laid out as each agent lays+//! out its own (`tests/fixtures`, and a Hermes `state.db` built here).++use std::path::{Path, PathBuf};++use cua_agent_threads::{Agent, ListOptions, Role, Roots, history, recent};+use rusqlite::Connection;++const KETTLE: &str = "0b1e5c2a-1111-4222-8333-944445555666";+const GARDEN: &str = "77777777-aaaa-4bbb-8ccc-dddddddddddd";+const META_ONLY: &str = "99999999-0000-4000-8000-000000000000";+const COUPON: &str = "5f0c1d2e-3a4b-4c5d-8e6f-708192a3b4c5";+const EXEC: &str = "1a2b3c4d-0000-4000-8000-aaaaaaaaaaaa";+const OLD: &str = "0ld0ld00-1111-4111-8111-111111111111";++fn fixtures() -> PathBuf {+ Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")+}++fn copy(from: &Path, to: &Path) {+ std::fs::create_dir_all(to.parent().unwrap()).unwrap();+ std::fs::copy(from, to).unwrap();+}++/// A home with all three agents' stores.+fn home() -> tempfile::TempDir {+ let d = tempfile::tempdir().unwrap();+ let h = d.path();+ let f = fixtures();+ for (id, slug) in [+ (KETTLE, "-Users-sam-code-kettle"),+ (GARDEN, "-Users-sam-code-garden-planner"),+ (META_ONLY, "-tmp"),+ ] {+ copy(+ &f.join(format!("claude/{id}.jsonl")),+ &h.join(format!(".claude/projects/{slug}/{id}.jsonl")),+ );+ }+ // A subagent's chat one level deeper is not a chat of its own.+ copy(+ &f.join(format!("claude/{GARDEN}.jsonl")),+ &h.join(format!(+ ".claude/projects/-Users-sam-code-garden-planner/{GARDEN}/subagents/agent-1.jsonl"+ )),+ );+ for (name, day) in [+ (+ format!("rollout-2026-11-03T10-00-00-{COUPON}.jsonl"),+ "2026/11/03",+ ),+ (+ format!("rollout-2026-11-04T08-00-00-{EXEC}.jsonl"),+ "2026/11/04",+ ),+ (+ format!("rollout-2025-06-01T12-00-00-{OLD}.jsonl"),+ "2025/06/01",+ ),+ ] {+ copy(+ &f.join("codex").join(&name),+ &h.join(".codex/sessions").join(day).join(&name),+ );+ }+ copy(+ &f.join("codex/session_index.jsonl"),+ &h.join(".codex/session_index.jsonl"),+ );+ hermes_db(&h.join(".hermes/state.db"), true);+ d+}++/// A Hermes store; `full` has the newer columns, otherwise only the oldest.+fn hermes_db(path: &Path, full: bool) {+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ let c = Connection::open(path).unwrap();+ if full {+ c.execute_batch(+ "CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT NOT NULL, parent_session_id TEXT, started_at REAL NOT NULL,+ ended_at REAL, cwd TEXT, title TEXT, last_activity_at REAL, archived INTEGER, hidden INTEGER, future_col BLOB);+ CREATE TABLE messages (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT,+ tool_calls TEXT, timestamp REAL NOT NULL, active INTEGER NOT NULL DEFAULT 1);+ INSERT INTO sessions VALUES ('20261103_201500_ab12cd', 'cli', NULL, 1793736900.0, NULL, '/Users/sam/notes', NULL, 1793740000.0, 0, 0, NULL);+ INSERT INTO sessions VALUES ('20261104_060000_cron01', 'cron', NULL, 1793772000.0, NULL, '/', 'Nightly digest', 1793772100.0, 0, 0, NULL);+ INSERT INTO sessions VALUES ('20261104_061000_child1', 'cli', '20261103_201500_ab12cd', 1793772600.0, NULL, '/', 'child', 1793772700.0, 0, 0, NULL);+ INSERT INTO sessions VALUES ('20261104_062000_hidden', 'cli', NULL, 1793773200.0, NULL, '/', 'hidden', 1793773300.0, 0, 1, NULL);+ INSERT INTO sessions VALUES ('20261101_090000_slack1', 'slack', NULL, 1793523600.0, NULL, NULL, 'Release checklist', NULL, 0, 0, NULL);+ INSERT INTO messages (session_id, role, content, timestamp) VALUES ('20261103_201500_ab12cd', 'user', 'Summarise my notes on the bakery lease', 1793736901.0);+ INSERT INTO messages (session_id, role, content, tool_calls, timestamp) VALUES ('20261103_201500_ab12cd', 'assistant', NULL, '[{}]', 1793736902.0);+ INSERT INTO messages (session_id, role, content, timestamp) VALUES ('20261103_201500_ab12cd', 'tool', 'file contents', 1793736903.0);+ INSERT INTO messages (session_id, role, content, timestamp) VALUES ('20261103_201500_ab12cd', 'assistant', '[{\"type\":\"text\",\"text\":\"The lease renews in March.\"}]', 1793736904.0);+ INSERT INTO messages (session_id, role, content, timestamp, active) VALUES ('20261103_201500_ab12cd', 'user', 'a rewound message', 1793736905.0, 0);+ INSERT INTO messages (session_id, role, content, timestamp) VALUES ('20261104_060000_cron01', 'user', 'run the digest', 1793772001.0);+ INSERT INTO messages (session_id, role, content, timestamp) VALUES ('20261104_061000_child1', 'user', 'child work', 1793772601.0);+ INSERT INTO messages (session_id, role, content, timestamp) VALUES ('20261104_062000_hidden', 'user', 'hidden work', 1793773201.0);+ INSERT INTO messages (session_id, role, content, timestamp) VALUES ('20261101_090000_slack1', 'user', 'what is left for the release?', 1793523601.0);",+ )+ .unwrap();+ } else {+ c.execute_batch(+ "CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT NOT NULL, started_at REAL NOT NULL);+ CREATE TABLE messages (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT, timestamp REAL NOT NULL);+ INSERT INTO sessions VALUES ('20250101_000000_old001', 'cli', 1735689600.0);+ INSERT INTO messages (session_id, role, content, timestamp) VALUES ('20250101_000000_old001', 'user', 'hello from an old Hermes', 1735689601.0);",+ )+ .unwrap();+ }+}++fn all(limit: usize) -> ListOptions {+ ListOptions {+ agents: Agent::ALL.to_vec(),+ limit,+ }+}++#[test]+fn lists_every_agents_chats_newest_first() {+ let h = home();+ let list = recent(&Roots::under_home(h.path()), &all(50));+ let ids: Vec<&str> = list.iter().map(|t| t.id.as_str()).collect();+ // Hermes's cron, child and hidden sessions, Codex's exec run, a Claude+ // chat with nothing typed and a subagent's file are left out.+ assert_eq!(+ ids,+ vec![+ "20261103_201500_ab12cd",+ GARDEN,+ COUPON,+ KETTLE,+ "20261101_090000_slack1",+ OLD+ ]+ );++ let kettle = list.iter().find(|t| t.id == KETTLE).unwrap();+ assert_eq!(kettle.agent, Agent::ClaudeCode);+ // The name the person gave it wins over the generated one.+ assert_eq!(kettle.title, "Kettle timer on CI");+ assert_eq!(kettle.cwd.as_deref(), Some("/Users/sam/code/kettle"));+ assert_eq!(kettle.last_active_ms, 1_793_610_120_000);+ assert_eq!(kettle.resume, vec!["claude", "--resume", KETTLE]);++ // No title: the first prompt, on one line and cut.+ let garden = list.iter().find(|t| t.id == GARDEN).unwrap();+ assert!(garden.title.starts_with("Add a frost date column"));+ assert!(garden.title.chars().count() <= 80);++ let coupon = list.iter().find(|t| t.id == COUPON).unwrap();+ assert_eq!(+ (coupon.agent, coupon.title.as_str()),+ (Agent::Codex, "Checkout double charge")+ );+ assert_eq!(coupon.cwd.as_deref(), Some("/Users/sam/code/bike-shop"));+ assert_eq!(coupon.resume, vec!["codex", "resume", COUPON]);+ let old = list.iter().find(|t| t.id == OLD).unwrap();+ assert_eq!(old.title, "rename the config loader");++ let notes = list+ .iter()+ .find(|t| t.id == "20261103_201500_ab12cd")+ .unwrap();+ assert_eq!(+ (notes.agent, notes.title.as_str()),+ (Agent::Hermes, "Summarise my notes on the bakery lease")+ );+ assert_eq!(notes.cwd.as_deref(), Some("/Users/sam/notes"));+ assert_eq!(notes.last_active_ms, 1_793_740_000_000);+ let slack = list+ .iter()+ .find(|t| t.id == "20261101_090000_slack1")+ .unwrap();+ assert_eq!(slack.title, "Release checklist");+}++#[test]+fn limit_and_agent_filter() {+ let h = home();+ let roots = Roots::under_home(h.path());+ assert_eq!(recent(&roots, &all(2)).len(), 2);+ let only = recent(+ &roots,+ &ListOptions {+ agents: vec![Agent::Codex],+ limit: 4,+ },+ );+ assert!(only.iter().all(|t| t.agent == Agent::Codex));+ assert_eq!(only.len(), 2);+}++#[test]+fn missing_or_broken_stores_list_nothing() {+ let d = tempfile::tempdir().unwrap();+ assert!(recent(&Roots::under_home(d.path()), &all(4)).is_empty());+ // Not a database, a projects file where a folder should be.+ std::fs::create_dir_all(d.path().join(".hermes")).unwrap();+ std::fs::write(d.path().join(".hermes/state.db"), b"not sqlite").unwrap();+ std::fs::create_dir_all(d.path().join(".claude")).unwrap();+ std::fs::write(d.path().join(".claude/projects"), b"x").unwrap();+ assert!(recent(&Roots::under_home(d.path()), &all(4)).is_empty());+ assert!(recent(&Roots::default(), &all(4)).is_empty());+}++#[test]+fn an_older_hermes_without_the_newer_columns() {+ let d = tempfile::tempdir().unwrap();+ hermes_db(&d.path().join(".hermes/state.db"), false);+ let list = recent(&Roots::under_home(d.path()), &all(4));+ assert_eq!(list.len(), 1);+ assert_eq!(+ (list[0].title.as_str(), list[0].cwd.as_deref()),+ ("hello from an old Hermes", None)+ );+ let h = history(+ &Roots::under_home(d.path()),+ Agent::Hermes,+ "20250101_000000_old001",+ None,+ )+ .unwrap();+ assert_eq!(h.messages.len(), 1);+}++#[test]+fn claude_history_is_what_was_said() {+ let h = home();+ let t = history(+ &Roots::under_home(h.path()),+ Agent::ClaudeCode,+ KETTLE,+ None,+ )+ .unwrap();+ let said: Vec<(Role, &str)> = t+ .messages+ .iter()+ .map(|m| (m.role, m.text.as_str()))+ .collect();+ // No meta, slash-command echo, thinking, tool call, tool result or+ // subagent; one reply split by a tool call reads as one.+ assert_eq!(+ said,+ vec![+ (+ Role::Person,+ "The kettle timer test fails on CI but passes locally, can you find out why?"+ ),+ (+ Role::Agent,+ "Let me look at the timer test.\n\nIt depends on the machine's time zone."+ ),+ (Role::Person, "Pin it to UTC then."),+ (Role::Agent, "Done: the test now sets TZ=UTC."),+ ]+ );+ assert_eq!(t.messages[0].key, "m2");+ assert_eq!(t.messages[0].ts_ms, Some(1_793_610_002_000));+ assert_eq!(t.earlier_omitted, 0);+ assert_eq!(t.thread.title, "Kettle timer on CI");+}++#[test]+fn history_keeps_the_newest_and_says_how_many_it_left_out() {+ let h = home();+ let t = history(+ &Roots::under_home(h.path()),+ Agent::ClaudeCode,+ KETTLE,+ Some(2),+ )+ .unwrap();+ assert_eq!(t.earlier_omitted, 2);+ assert_eq!(t.messages[0].text, "Pin it to UTC then.");+}++#[test]+fn codex_history_skips_instructions_and_duplicates() {+ let h = home();+ let roots = Roots::under_home(h.path());+ let t = history(&roots, Agent::Codex, COUPON, None).unwrap();+ let said: Vec<(Role, &str)> = t+ .messages+ .iter()+ .map(|m| (m.role, m.text.as_str()))+ .collect();+ assert_eq!(+ said,+ vec![+ (+ Role::Person,+ "Why does checkout double-charge when the coupon is applied twice?"+ ),+ (Role::Agent, "The coupon handler isn't idempotent."),+ ]+ );+ // An older rollout with only event messages.+ let old = history(&roots, Agent::Codex, OLD, None).unwrap();+ assert_eq!(old.messages.len(), 2);+ // A scripted exec run can't be opened as a chat.+ assert!(history(&roots, Agent::Codex, EXEC, None).is_err());+}++#[test]+fn hermes_history_is_active_user_and_assistant_text() {+ let h = home();+ let t = history(+ &Roots::under_home(h.path()),+ Agent::Hermes,+ "20261103_201500_ab12cd",+ None,+ )+ .unwrap();+ let said: Vec<(Role, &str)> = t+ .messages+ .iter()+ .map(|m| (m.role, m.text.as_str()))+ .collect();+ assert_eq!(+ said,+ vec![+ (Role::Person, "Summarise my notes on the bakery lease"),+ (Role::Agent, "The lease renews in March.")+ ]+ );+ assert_eq!(t.messages[0].ts_ms, Some(1_793_736_901_000));+}++#[test]+fn history_refuses_paths_and_unknown_ids() {+ let h = home();+ let roots = Roots::under_home(h.path());+ for bad in ["../../etc/passwd", "a/b", ""] {+ assert!(matches!(+ history(&roots, Agent::ClaudeCode, bad, None),+ Err(cua_agent_threads::Error::Invalid(_))+ ));+ }+ assert!(matches!(+ history(+ &roots,+ Agent::ClaudeCode,+ "00000000-0000-4000-8000-000000000001",+ None+ ),+ Err(cua_agent_threads::Error::NotFound { .. })+ ));+ // A file with nothing typed is not a chat either.+ assert!(history(&roots, Agent::ClaudeCode, META_ONLY, None).is_err());+}++#[test]+fn long_messages_are_cut() {+ let d = tempfile::tempdir().unwrap();+ let long = "é".repeat(10_000);+ let line = serde_json::json!({"type":"user","uuid":"u","timestamp":"2026-11-01T00:00:00Z","cwd":"/x","message":{"role":"user","content":long}});+ let p = d.path().join(".claude/projects/-x/abc.jsonl");+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();+ std::fs::write(&p, format!("{line}\n")).unwrap();+ let t = history(&Roots::under_home(d.path()), Agent::ClaudeCode, "abc", None).unwrap();+ assert!(t.messages[0].cut);+ assert!(t.messages[0].text.len() <= cua_agent_threads::MESSAGE_MAX_BYTES);+}diff --git a/libs/cua/crates/cua-agents/runner/acp-runner.mjs b/libs/cua/crates/cua-agents/runner/acp-runner.mjsindex 8928ce2b15..29a35c9680 100644--- a/libs/cua/crates/cua-agents/runner/acp-runner.mjs+++ b/libs/cua/crates/cua-agents/runner/acp-runner.mjs@@ -289,7 +289,9 @@ try {const state = {status: "starting",turn: prev.turn ?? 0,- sessionId: prev.sessionId ?? null,+ // A run that continues the agent's own earlier session (`resume`, from agent_start's+ // resume_session) reloads it like a restarted run reloads its own.+ sessionId: prev.sessionId ?? (!cfg.durable && typeof cfg.resume?.sessionId === "string" ? cfg.resume.sessionId : null),runnerPid: process.pid,agentPid: null,stopReason: prev.stopReason ?? null,@@ -981,7 +983,13 @@ if (durable) {for (const q of plan.unstarted) first.push({ op: "prompt", text: q.text, files: q.files ?? [], msgId: q.msgId });queue.push(...first);} else if (cfg.prompt && !prev.sessionId) {- queue.push({ op: "prompt", text: cfg.prompt, files: cfg.files ?? [] });+ queue.push({ op: "prompt", text: cfg.prompt, files: cfg.files ?? [], first: true });+}++/** The first prompt of a run whose earlier session could not be reloaded: the earlier conversation goes first. */+export function withResumeContext(text, context) {+ if (typeof context !== "string" || !context.trim()) return text;+ return `[cua] The agent could not reload this chat's earlier session, so here is what was said in it so far. This note is automatic; it is not from the user.\n\n${context.trim()}\n\n[cua] The user's next message:\n\n${text}`;}function drainInbox() {@@ -1170,6 +1178,11 @@ async function drive(a) {configOptions = res.configOptions ?? null;}if (stale()) return;+ // The earlier session of a `resume` run is gone: the first prompt carries the earlier conversation instead.+ if (!resumed && !durable && cfg.resume?.sessionId && wantSession === cfg.resume.sessionId) {+ const first = queue.find((q) => q.first);+ if (first) first.text = withResumeContext(first.text, cfg.resume.context);+ }save({ sessionId, status: "idle", ...(durable ? { degraded: state.degraded || degraded } : {}) });emit("session", { sessionId, resumed, modes });diff --git a/libs/cua/crates/cua-agents/runner/test/resume.test.mjs b/libs/cua/crates/cua-agents/runner/test/resume.test.mjsnew file mode 100644index 0000000000..49202e692d--- /dev/null+++ b/libs/cua/crates/cua-agents/runner/test/resume.test.mjs@@ -0,0 +1,66 @@+// A run that continues the agent's own earlier session (agent_start's+// resume_session, CUA-3319): the runner reloads it, and when the agent+// can't, the first prompt carries the earlier conversation instead.+//+// node --test libs/cua/crates/cua-agents/runner/test/+import { test } from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";+import { Box, sdkRoot } from "./helpers.mjs";++const sdk = sdkRoot();+const t = (name, fn) => test(name, { skip: sdk ? false : "@agentclientprotocol/sdk is not available", timeout: 60_000 }, async () => {+ const box = new Box(sdk);+ try {+ await fn(box);+ } finally {+ box.cleanup();+ }+});++/** A one-off (not durable) run that resumes `sessionId`. */+function resumeRun(box, { sessionId, context, known, script = {} }) {+ box.script({ prompts: [{ match: ".*", steps: [{ say: "carrying on" }] }], ...script });+ if (known) fs.writeFileSync(path.join(box.mock, "sessions.json"), JSON.stringify({ [sessionId]: true }));+ fs.writeFileSync(+ path.join(box.run, "run.json"),+ JSON.stringify({+ agent: { command: process.execPath, args: [path.join(box.root, "mock-acp-agent.mjs")] },+ cwd: box.run,+ prompt: "now pin it to UTC",+ env: { MOCK_DIR: box.mock, MOCK_SCRIPT: path.join(box.mock, "script.json") },+ exitWhenIdle: true,+ resume: { sessionId, context },+ }),+ );+}++t("reloads the agent's own session and sends the prompt as typed", async (box) => {+ resumeRun(box, { sessionId: "old-chat-1", context: "person: the timer test fails", known: true });+ const r = await box.go({ env: { CUA_SESSION: "", CUA_SESSION_EPOCH: "" } });+ assert.equal(r.code, 0, r.stderr);+ const log = box.agentLog();+ assert.ok(log.some((l) => l.ev === "session_load" && l.id === "old-chat-1"), JSON.stringify(log));+ assert.ok(!log.some((l) => l.ev === "session_new"));+ assert.deepEqual(box.prompts(), ["now pin it to UTC"]);+});++t("uses session/resume when the agent offers it", async (box) => {+ resumeRun(box, { sessionId: "old-chat-2", known: true, script: { resume: true } });+ const r = await box.go({ env: { CUA_SESSION: "", CUA_SESSION_EPOCH: "" } });+ assert.equal(r.code, 0, r.stderr);+ assert.ok(box.agentLog().some((l) => l.ev === "session_resume" && l.id === "old-chat-2"));+ assert.deepEqual(box.prompts(), ["now pin it to UTC"]);+});++t("a session the agent can't reload: a new one, with the earlier conversation first", async (box) => {+ resumeRun(box, { sessionId: "gone-chat", context: "person: the timer test fails\n\nagent: it depends on the time zone", known: false });+ const r = await box.go({ env: { CUA_SESSION: "", CUA_SESSION_EPOCH: "" } });+ assert.equal(r.code, 0, r.stderr);+ assert.ok(box.agentLog().some((l) => l.ev === "session_new"));+ const [prompt] = box.prompts();+ assert.match(prompt, /could not reload/);+ assert.match(prompt, /it depends on the time zone/);+ assert.ok(prompt.endsWith("now pin it to UTC"), prompt);+});diff --git a/libs/cua/crates/cua-agents/src/runs.rs b/libs/cua/crates/cua-agents/src/runs.rsindex da368c8a4e..919502b1e6 100644--- a/libs/cua/crates/cua-agents/src/runs.rs+++ b/libs/cua/crates/cua-agents/src/runs.rs@@ -132,6 +132,50 @@ pub struct RunOptions {/// from the guest's own setup. Ignored for other harnesses and with an/// endpoint.pub hermes_config: Option<String>,+ /// Continue this session of the harness's own (Claude Code, Codex or+ /// Hermes keep it on the computer the run is on) instead of opening a+ /// new one: the runner asks the agent to reload it (ACP `session/resume`+ /// or `session/load`). Not with `durable`, which keeps its own session.+ pub resume_session: Option<String>,+ /// With `resume_session`: the earlier conversation as text, put before+ /// the first prompt only when the agent cannot reload the session.+ pub resume_context: Option<String>,+}++/// The most of `resume_context` a run takes.+pub const RESUME_CONTEXT_MAX: usize = 32 * 1024;++/// `run.json`'s `resume`: the agent's own session to reload, and the+/// context for when it can't be.+fn resume_section(opts: &RunOptions) -> Result<Value> {+ let Some(id) = opts.resume_session.as_deref() else {+ return Ok(Value::Null);+ };+ let valid = !id.is_empty()+ && id.len() <= 128+ && id+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));+ if !valid {+ return Err(Error::Invalid(format!(+ "resume_session: {id:?} is not a session id"+ )));+ }+ if opts.durable.is_some() {+ return Err(Error::Invalid(+ "resume_session: a durable run keeps its own session".into(),+ ));+ }+ let context = opts+ .resume_context+ .as_deref()+ .filter(|c| !c.trim().is_empty());+ if context.is_some_and(|c| c.len() > RESUME_CONTEXT_MAX) {+ return Err(Error::Invalid(format!(+ "resume_context: at most {RESUME_CONTEXT_MAX} bytes"+ )));+ }+ Ok(json!({"sessionId": id, "context": context}))}/// `meta.json`.@@ -1158,6 +1202,7 @@ impl Agents {"guardModeKinds": crate::durable::guard_mode_kinds(h),"secretEnv": opts.durable.as_ref().map(|_| opts.env.keys().collect::<Vec<_>>()),"durable": opts.durable.as_ref().map(|d| d.run_section(Some(&rdir))),+ "resume": resume_section(&opts)?,});uploads.push((format!("{rdir}/run.json"),@@ -1680,6 +1725,32 @@ mod tests {assert!(!a.contains("one"));}+ #[test]+ fn a_resume_names_the_agents_own_session() {+ let opts = |id: &str, ctx: Option<&str>| RunOptions {+ resume_session: Some(id.into()),+ resume_context: ctx.map(String::from),+ ..Default::default()+ };+ assert_eq!(resume_section(&RunOptions::default()).unwrap(), Value::Null);+ assert_eq!(+ resume_section(&opts("0b1e5c2a-1111", Some("earlier"))).unwrap(),+ json!({"sessionId": "0b1e5c2a-1111", "context": "earlier"})+ );+ assert_eq!(+ resume_section(&opts("abc", Some(" "))).unwrap()["context"],+ Value::Null+ );+ assert!(resume_section(&opts("../x", None)).is_err());+ let big = "x".repeat(RESUME_CONTEXT_MAX + 1);+ assert!(resume_section(&opts("abc", Some(&big))).is_err());+ let durable = RunOptions {+ durable: Some(Default::default()),+ ..opts("abc", None)+ };+ assert!(resume_section(&durable).is_err());+ }+fn probe(h: &Harness, home: &std::path::Path, env: &[(&str, &str)]) -> String {let out = std::process::Command::new("/bin/sh").arg("-c")diff --git a/libs/cua/crates/cua-sdk/src/native/agents.rs b/libs/cua/crates/cua-sdk/src/native/agents.rsindex b69f303ba9..e2d247e5e9 100644--- a/libs/cua/crates/cua-sdk/src/native/agents.rs+++ b/libs/cua/crates/cua-sdk/src/native/agents.rs@@ -502,6 +502,9 @@ fn run_options(o: AgentRunOptions) -> Result<ca::RunOptions> {durable: None,// The saved connections are the Cua Spaces app's; an SDK run names its own keys.hermes_config: None,+ // Continuing a chat from this computer's own agent store is the Spaces app's (CUA-3319).+ resume_session: None,+ resume_context: None,})}diff --git a/libs/cua/crates/cua-sdk/src/native/spaces.rs b/libs/cua/crates/cua-sdk/src/native/spaces.rsindex 19c0a1593e..69b2575c1e 100644--- a/libs/cua/crates/cua-sdk/src/native/spaces.rs+++ b/libs/cua/crates/cua-sdk/src/native/spaces.rs@@ -62,6 +62,8 @@ pub const SPACES_TOOL_METHODS: &[(&str, &str)] = &[("agent_stop", "Space.agent_stop"),("agent_list", "Space.agent_list"),("agent_capabilities", "Spaces.agent_capabilities"),+ ("agent_threads", "Spaces.call_tool_json"),+ ("agent_thread_read", "Spaces.call_tool_json"),("agent_add", "Spaces.persistent_agent_create"),("persistent_agent_list", "Spaces.persistent_agents"),("agent_remove", "Spaces.persistent_agent_remove"),diff --git a/libs/cua/crates/cua-spaces-contract/src/inputs.rs b/libs/cua/crates/cua-spaces-contract/src/inputs.rsindex df94c7db7d..4a67fc5e4e 100644--- a/libs/cua/crates/cua-spaces-contract/src/inputs.rs+++ b/libs/cua/crates/cua-spaces-contract/src/inputs.rs@@ -678,6 +678,17 @@ pub struct AgentStart {/// a one-off run whose state lives only in the Space.#[serde(default)]pub home: Option<String>,+ /// Continue this session of the harness's own (an id from+ /// `agent_threads`) instead of starting a new one: the harness reloads+ /// it from its own store on this computer. Give `cwd` as the chat's+ /// folder. Not with `home`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub resume_session: Option<String>,+ /// With `resume_session`: the earlier conversation as text, given to+ /// the agent before the prompt only when the harness cannot reload the+ /// session (up to 32 KiB).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub resume_context: Option<String>,}/// `agent_message`: a follow-up in the same session.@@ -775,6 +786,30 @@ pub struct AgentStop {#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]pub struct AgentCapabilities {}+/// `agent_threads`: the coding agents' own recent chats on this computer.+#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]+pub struct AgentThreads {+ /// Harness ids to look at: `claude-code`, `openai-codex`, `hermes`.+ /// Default: all three.+ #[serde(default)]+ pub agents: Vec<String>,+ /// How many chats, newest first (1-50). Default 4.+ #[serde(default)]+ pub limit: Option<u32>,+}++/// `agent_thread_read`: one of those chats, what was said in it.+#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]+pub struct AgentThreadRead {+ /// Its harness id (`claude-code`, `openai-codex`, `hermes`).+ pub agent: String,+ /// Its id, from `agent_threads`.+ pub id: String,+ /// The newest messages to return (1-5000). Default 200.+ #[serde(default)]+ pub limit: Option<u32>,+}+/// `agent_add` (formerly `persistent_agent_create`): a named agent whose memory outlives its runs.#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]pub struct PersistentAgentCreate {diff --git a/libs/cua/crates/cua-spaces-contract/src/lib.rs b/libs/cua/crates/cua-spaces-contract/src/lib.rsindex c36cd2e03c..5fdae3756b 100644--- a/libs/cua/crates/cua-spaces-contract/src/lib.rs+++ b/libs/cua/crates/cua-spaces-contract/src/lib.rs@@ -1200,6 +1200,28 @@ pub fn tools() -> Vec<Tool> {..Spec::new("agent_capabilities", "Report what the agent harnesses support.")}.with::<i::AgentCapabilities>(),+ Spec {+ category: Category::Agents,+ result: "JSON: `threads`, newest first, each `agent` (harness id), `id`, `title` (the chat's name, or its first prompt cut to 80 characters), `cwd` (its folder, or null), `last_active_ms` and `resume` (the agent's own command that continues it in a terminal, as argv).",+ errors: &["permission_denied"],+ instructions: "Only for a person, never for an agent: no MCP server lists or runs it, and the daemon answers only this computer's own user (never a relay caller or a Space's agent). Reads the coding agents' own stores on this computer read-only (Claude Code's projects folder, Codex's sessions, Hermes's state.db) and returns only each chat's title, folder and time; nothing is kept or sent anywhere. A store that is missing or unreadable adds nothing.",+ capabilities: &["agent.threads.read"],+ sdk_symbol: "spaces.callTool(\"agent_threads\")",+ rust_symbol: "cua_agent_threads::recent",+ ..Spec::new("agent_threads", "List the recent Claude Code, Codex and Hermes chats on this computer. For a person only.")+ }+ .with::<i::AgentThreads>(),+ Spec {+ category: Category::Agents,+ result: "JSON: `thread` (as in `agent_threads`), `messages` (oldest first, each `key`, `role` (`person` or `agent`), `text` (cut to 8 KiB), `ts_ms`, and `cut` when cut) and `earlier_omitted` (older messages left out).",+ errors: &["permission_denied", "not_found", "invalid_argument"],+ instructions: "Only for a person, never for an agent: no MCP server lists or runs it, and the daemon answers only this computer's own user. Reads one chat from the agent's own store, read-only: what the person typed and the agent's replies, without tool calls, tool output, thinking or the agent's own injected instructions. Call it once the person picked the chat; continue it with agent_start's `resume_session`.",+ capabilities: &["agent.threads.read"],+ sdk_symbol: "spaces.callTool(\"agent_thread_read\")",+ rust_symbol: "cua_agent_threads::history",+ ..Spec::new("agent_thread_read", "Read one of the recent Claude Code, Codex or Hermes chats on this computer. For a person only.")+ }+ .with::<i::AgentThreadRead>(),// --- Persistent agents ----------------------------------------------------Spec {category: Category::PersistentAgents,@@ -2259,7 +2281,7 @@ pub fn canonical(name: &str) -> &str {/// Tools only a person may call: no MCP server lists or runs them for an/// agent (the apps, the CLI and the SDK call them through the daemon)./// Their capabilities are never granted to an agent.-pub const PERSON_ONLY_TOOLS: &[&str] = &["cloud_approve"];+pub const PERSON_ONLY_TOOLS: &[&str] = &["cloud_approve", "agent_threads", "agent_thread_read"];/// Whether `name` is a tool only a person may call ([`PERSON_ONLY_TOOLS`]).pub fn person_only(name: &str) -> bool {@@ -2366,7 +2388,7 @@ mod tests {#[test]fn advertises_every_tool() {- assert_eq!(tools().len(), 119);+ assert_eq!(tools().len(), 121);}#[test]@@ -2423,7 +2445,6 @@ mod tests {let t = tool(name).unwrap_or_else(|| panic!("{name} is not a contract tool"));assert!(person_only(name));assert!(t.instructions.contains("Only for a person"), "{name}");- assert!(!t.annotations.read_only, "{name}");}assert!(!person_only("cloud_connect"));}diff --git a/libs/cua/crates/cua-spaces-ext/Cargo.toml b/libs/cua/crates/cua-spaces-ext/Cargo.tomlindex caf690378b..b0608a3465 100644--- a/libs/cua/crates/cua-spaces-ext/Cargo.toml+++ b/libs/cua/crates/cua-spaces-ext/Cargo.toml@@ -28,6 +28,8 @@ dev-remotes = [][dependencies]cua-spaces = { path = "../cua-spaces" }cua-spaces-contract = { path = "../cua-spaces-contract" }+# The coding agents' own recent chats on this computer (`agent_threads`).+cua-agent-threads = { path = "../cua-agent-threads" }# The account's machines and the way to reach them (the replicated Volume).cua-mesh.workspace = truecua-cluster.workspace = truediff --git a/libs/cua/crates/cua-spaces-ext/src/agent_threads_tools.rs b/libs/cua/crates/cua-spaces-ext/src/agent_threads_tools.rsnew file mode 100644index 0000000000..b4e212bc74--- /dev/null+++ b/libs/cua/crates/cua-spaces-ext/src/agent_threads_tools.rs@@ -0,0 +1,129 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++//! `agent_threads` and `agent_thread_read`: the coding agents' own recent+//! chats on this computer, for "Pick up where you left off" (CUA-3319).+//!+//! Both are person-only tools (no MCP server lists or runs them), and they+//! answer only this computer's own user: a relay caller, an agent member+//! and an agent's own process are refused, so a chat never leaves this+//! computer before the person picked it. Reading is `cua_agent_threads`,+//! read-only, on a blocking thread.++use serde_json::{Value, json};++use crate::thread::policy::denied;+use cua_agent_threads::{Agent, ListOptions, Roots};+use cua_spaces::error::{Error, Result};+use cua_spaces::extension::Caller;+use cua_spaces::mcp::ToolOutcome;+use cua_spaces_contract::inputs as i;++pub(crate) const TOOLS: &[&str] = &["agent_threads", "agent_thread_read"];++pub(crate) async fn call(caller: &Caller, tool: &str, a: Value) -> Result<ToolOutcome> {+ own_user_only(caller, tool)?;+ let roots = Roots::from_env();+ match tool {+ "agent_threads" => {+ let a: i::AgentThreads = crate::args(tool, a)?;+ let agents = parse_agents(&a.agents)?;+ let opts = ListOptions {+ agents,+ limit: a+ .limit+ .unwrap_or(4)+ .clamp(1, cua_agent_threads::RECENT_MAX as u32) as usize,+ };+ let threads = blocking(move || Ok(cua_agent_threads::recent(&roots, &opts))).await?;+ Ok(ToolOutcome::json(&json!({ "threads": threads })))+ }+ "agent_thread_read" => {+ let a: i::AgentThreadRead = crate::args(tool, a)?;+ let agent = Agent::parse(&a.agent).ok_or_else(|| {+ Error::invalid(format!(+ "agent: {:?} is not claude-code, openai-codex or hermes",+ a.agent+ ))+ })?;+ let limit = a.limit.map(|n| n as usize);+ let id = a.id;+ let h = blocking(move || {+ cua_agent_threads::history(&roots, agent, &id, limit).map_err(|e| match e {+ cua_agent_threads::Error::NotFound { .. } => Error::NotFound(e.to_string()),+ cua_agent_threads::Error::Invalid(m) => Error::invalid(m),+ other => Error::extension("agent_threads", other.to_string()),+ })+ })+ .await?;+ Ok(ToolOutcome::json(&h))+ }+ _ => Err(Error::invalid(format!("{tool}: not an agent_threads tool"))),+ }+}++/// Only this computer's own user, never an agent (CUA-3319 privacy defaults).+fn own_user_only(caller: &Caller, tool: &str) -> Result<()> {+ if *caller != Caller::Owner || cua_sandbox_core::byoc::cua_agent().is_some() {+ return Err(denied(format!(+ "{tool}: only this computer's own user can read its coding agents' chats"+ )));+ }+ Ok(())+}++fn parse_agents(ids: &[String]) -> Result<Vec<Agent>> {+ if ids.is_empty() {+ return Ok(Agent::ALL.to_vec());+ }+ ids.iter()+ .map(|s| {+ Agent::parse(s).ok_or_else(|| {+ Error::invalid(format!(+ "agents: {s:?} is not claude-code, openai-codex or hermes"+ ))+ })+ })+ .collect()+}++async fn blocking<T: Send + 'static>(f: impl FnOnce() -> Result<T> + Send + 'static) -> Result<T> {+ tokio::task::spawn_blocking(f)+ .await+ .map_err(|e| Error::extension("agent_threads", e.to_string()))?+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn refuses_anyone_but_this_computers_user() {+ let relay = Caller::Relay {+ account: "acct_x".into(),+ name: None,+ role: "owner".into(),+ };+ assert!(own_user_only(&relay, "agent_threads").is_err());+ let agent = Caller::Agent {+ name: "bot".into(),+ space: "s".into(),+ };+ assert!(own_user_only(&agent, "agent_thread_read").is_err());+ }++ #[test]+ fn agents_default_to_all_three() {+ assert_eq!(parse_agents(&[]).unwrap(), Agent::ALL.to_vec());+ assert_eq!(parse_agents(&["codex".into()]).unwrap(), vec![Agent::Codex]);+ assert!(parse_agents(&["cursor".into()]).is_err());+ }++ #[test]+ fn they_are_person_only_tools() {+ for t in TOOLS {+ assert!(cua_spaces_contract::person_only(t), "{t}");+ assert!(cua_spaces_contract::tool(t).is_some(), "{t}");+ }+ }+}diff --git a/libs/cua/crates/cua-spaces-ext/src/lib.rs b/libs/cua/crates/cua-spaces-ext/src/lib.rsindex 476b0b1ebe..11771fe069 100644--- a/libs/cua/crates/cua-spaces-ext/src/lib.rs+++ b/libs/cua/crates/cua-spaces-ext/src/lib.rs@@ -26,6 +26,7 @@ use cua_spaces::{Error, Result, SpacesBuilder};use serde::de::DeserializeOwned;use serde_json::{Value, json};+mod agent_threads_tools;pub mod daemon;pub mod drive_runtime;pub mod drive_tools;@@ -197,6 +198,7 @@ impl SpacesExtension for DriveExtension {|| drive_tools::SERVICE_TOOLS.contains(&tool)|| persistent_tools::TOOLS.contains(&tool)|| thread_tools::TOOLS.contains(&tool)+ || agent_threads_tools::TOOLS.contains(&tool)|| persistent::phone::TOOLS.contains(&tool)|| tool == cua_spaces::agents::MEMBER_OP|| named_volumes::OPS.contains(&tool)@@ -288,6 +290,9 @@ impl SpacesExtension for DriveExtension {};return persistent_tools::start_with_home(spaces, &space, args).await;}+ if agent_threads_tools::TOOLS.contains(&tool) {+ return agent_threads_tools::call(&caller, tool, args).await;+ }if thread_tools::TOOLS.contains(&tool) || tool == cua_spaces::agents::MEMBER_OP {return thread_tools::call(spaces, &caller, tool, args).await;}diff --git a/libs/cua/crates/cua-spaces/src/agents/mod.rs b/libs/cua/crates/cua-spaces/src/agents/mod.rsindex 7f10dd59af..851d65119e 100644--- a/libs/cua/crates/cua-spaces/src/agents/mod.rs+++ b/libs/cua/crates/cua-spaces/src/agents/mod.rs@@ -583,8 +583,15 @@ pub fn start_options_with(skills: a.skills,label: a.label.clone(),exit_when_idle: a.exit_when_idle.unwrap_or(false),+ resume_session: a.resume_session.clone().filter(|s| !s.trim().is_empty()),+ resume_context: a.resume_context.clone(),..Default::default()};+ if opts.resume_session.is_some() && a.home.is_some() {+ return Err(Error::InvalidArgument(+ "agent_start: resume_session continues the harness's own session; it can't run as a persistent agent (home)".into(),+ ));+ }Ok((opts, missing))}@@ -826,6 +833,26 @@ mod tests {let (opts, _) = start_options_with(&k, &ep).unwrap();assert!(opts.env.is_empty());assert_eq!(opts.endpoint.unwrap().wire, Some(Wire::Anthropic));+ // Continuing the harness's own session (CUA-3319), never as a persistent agent.+ let mut resume = a.clone();+ resume.resume_session = Some("0b1e5c2a-1111".into());+ resume.resume_context = Some("earlier".into());+ resume.cwd = Some("/Users/sam/code/kettle".into());+ let (opts, _) = start_options_with(&k, &resume).unwrap();+ assert_eq!(+ (+ opts.resume_session.as_deref(),+ opts.resume_context.as_deref(),+ opts.cwd.as_deref()+ ),+ (+ Some("0b1e5c2a-1111"),+ Some("earlier"),+ Some("/Users/sam/code/kettle")+ )+ );+ resume.home = Some("helper".into());+ assert!(start_options_with(&k, &resume).is_err());// Bad input is refused without quoting any key.let mut bad = a.clone();bad.wire = Some("smoke-signals".into());diff --git a/libs/cua/python/tests/test_spaces.py b/libs/cua/python/tests/test_spaces.pyindex 90cc27828c..e2f9575955 100644--- a/libs/cua/python/tests/test_spaces.py+++ b/libs/cua/python/tests/test_spaces.py@@ -34,7 +34,7 @@ class Approver(cua.TeleportApprover):def test_every_contract_tool_maps_to_a_generated_method():rows = cua.spaces_tool_methods()- assert len(rows) == 119+ assert len(rows) == 121classes = {"Spaces": cua.Spaces, "Space": cua.Space}for row in rows:cls, method = row.method.split(".")diff --git a/libs/cua/spaces-contract/manifest.json b/libs/cua/spaces-contract/manifest.jsonindex 68cdf0d6cb..053049f037 100644--- a/libs/cua/spaces-contract/manifest.json+++ b/libs/cua/spaces-contract/manifest.json@@ -9,7 +9,7 @@"mcp_stdio","mcp_streamable_http"],- "tool_count": 119,+ "tool_count": 121,"categories": [{"id": "lifecycle",@@ -2181,6 +2181,14 @@"description": "Git URL cloned into the working directory first.","type": "string"},+ "resume_context": {+ "description": "With `resume_session`: the earlier conversation as text, given to\nthe agent before the prompt only when the harness cannot reload the\nsession (up to 32 KiB).",+ "type": "string"+ },+ "resume_session": {+ "description": "Continue this session of the harness's own (an id from\n`agent_threads`) instead of starting a new one: the harness reloads\nit from its own store on this computer. Give `cwd` as the chat's\nfolder. Not with `home`.",+ "type": "string"+ },"sandbox_mcp": {"description": "Give the agent the Space's own MCP tools. Default true.","type": "boolean"@@ -2618,6 +2626,122 @@"type": "object"}},+ {+ "name": "agent_threads",+ "category": "agents",+ "description": "List the recent Claude Code, Codex and Hermes chats on this computer. For a person only.",+ "instructions": "Only for a person, never for an agent: no MCP server lists or runs it, and the daemon answers only this computer's own user (never a relay caller or a Space's agent). Reads the coding agents' own stores on this computer read-only (Claude Code's projects folder, Codex's sessions, Hermes's state.db) and returns only each chat's title, folder and time; nothing is kept or sent anywhere. A store that is missing or unreadable adds nothing.",+ "platforms": [+ "macos",+ "windows",+ "linux"+ ],+ "providers": [+ "cloud",+ "local",+ "direct",+ "relay"+ ],+ "metering": "free",+ "capabilities": [+ "agent.threads.read"+ ],+ "requires": [],+ "host_requires": [],+ "annotations": {+ "read_only": true,+ "destructive": false,+ "idempotent": true,+ "open_world": true+ },+ "sdk_symbol": "spaces.callTool(\"agent_threads\")",+ "rust_symbol": "cua_agent_threads::recent",+ "notes": [],+ "result": "JSON: `threads`, newest first, each `agent` (harness id), `id`, `title` (the chat's name, or its first prompt cut to 80 characters), `cwd` (its folder, or null), `last_active_ms` and `resume` (the agent's own command that continues it in a terminal, as argv).",+ "errors": [+ "permission_denied"+ ],+ "input_schema": {+ "properties": {+ "agents": {+ "default": [],+ "description": "Harness ids to look at: `claude-code`, `openai-codex`, `hermes`.\nDefault: all three.",+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "limit": {+ "description": "How many chats, newest first (1-50). Default 4.",+ "format": "uint32",+ "minimum": 0,+ "type": "integer"+ }+ },+ "type": "object"+ }+ },+ {+ "name": "agent_thread_read",+ "category": "agents",+ "description": "Read one of the recent Claude Code, Codex or Hermes chats on this computer. For a person only.",+ "instructions": "Only for a person, never for an agent: no MCP server lists or runs it, and the daemon answers only this computer's own user. Reads one chat from the agent's own store, read-only: what the person typed and the agent's replies, without tool calls, tool output, thinking or the agent's own injected instructions. Call it once the person picked the chat; continue it with agent_start's `resume_session`.",+ "platforms": [+ "macos",+ "windows",+ "linux"+ ],+ "providers": [+ "cloud",+ "local",+ "direct",+ "relay"+ ],+ "metering": "free",+ "capabilities": [+ "agent.threads.read"+ ],+ "requires": [],+ "host_requires": [],+ "annotations": {+ "read_only": true,+ "destructive": false,+ "idempotent": true,+ "open_world": true+ },+ "sdk_symbol": "spaces.callTool(\"agent_thread_read\")",+ "rust_symbol": "cua_agent_threads::history",+ "notes": [],+ "result": "JSON: `thread` (as in `agent_threads`), `messages` (oldest first, each `key`, `role` (`person` or `agent`), `text` (cut to 8 KiB), `ts_ms`, and `cut` when cut) and `earlier_omitted` (older messages left out).",+ "errors": [+ "permission_denied",+ "not_found",+ "invalid_argument"+ ],+ "input_schema": {+ "properties": {+ "agent": {+ "description": "Its harness id (`claude-code`, `openai-codex`, `hermes`).",+ "type": "string"+ },+ "id": {+ "description": "Its id, from `agent_threads`.",+ "type": "string"+ },+ "limit": {+ "description": "The newest messages to return (1-5000). Default 200.",+ "format": "uint32",+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": [+ "agent",+ "id"+ ],+ "type": "object"+ }+ },{"name": "agent_add","category": "persistent-agents",diff --git a/libs/cua/swift/Tests/CuaTests/SpacesTests.swift b/libs/cua/swift/Tests/CuaTests/SpacesTests.swiftindex e959888446..6dbd067ac8 100644--- a/libs/cua/swift/Tests/CuaTests/SpacesTests.swift+++ b/libs/cua/swift/Tests/CuaTests/SpacesTests.swift@@ -125,7 +125,7 @@ func exerciseSpaces(_ cua: Cua, _ fx: Fixtures, tmp: URL, teleport: Bool = false@Suite(.serialized) struct SpacesTests {@Test func everyContractToolMapsToAGeneratedMethod() {let rows = spacesToolMethods()- #expect(rows.count == 119)+ #expect(rows.count == 121)// Swift spells `Class.method_name` as `methodName` on the generated// protocol; check each against the protocol's requirement list.let spaceMethods: Set<String> = [diff --git a/libs/cua/typescript/test/spaces.test.mjs b/libs/cua/typescript/test/spaces.test.mjsindex 4433950b2c..b291aee100 100644--- a/libs/cua/typescript/test/spaces.test.mjs+++ b/libs/cua/typescript/test/spaces.test.mjs@@ -45,7 +45,7 @@ function findFile(dir, name, budget = { n: 0 }) {test("every contract tool maps to a generated method", () => {const rows = spacesApi.spacesToolMethods()- assert.equal(rows.length, 119)+ assert.equal(rows.length, 121)const classes = { Spaces: spacesApi.Spaces, Space: spacesApi.Space }for (const row of rows) {const [cls, method] = row.method.split(".")diff --git a/scripts/docs-generators/spaces.ts b/scripts/docs-generators/spaces.tsindex 3a8125cc05..220189ca6e 100644--- a/scripts/docs-generators/spaces.ts+++ b/scripts/docs-generators/spaces.ts@@ -243,7 +243,10 @@ function toolSection(tool: Tool, manifest: Manifest): string[] {['Metering', tool.metering],['Approval',- `permission \`spaces:${tool.name}\`${tool.annotations.read_only ? ', in `spaces:readonly`' : ''}; ${effect(tool.annotations)}`,+ // A person's tool (cua_spaces_contract::PERSON_ONLY_TOOLS: "Only for a person" in its instructions) is no MCP permission.+ tool.instructions.startsWith('Only for a person')+ ? `none: for a person only, never served over MCP; ${effect(tool.annotations)}`+ : `permission \`spaces:${tool.name}\`${tool.annotations.read_only ? ', in `spaces:readonly`' : ''}; ${effect(tool.annotations)}`,],];if (tool.requires.length) facts.push(['Requires (spacesd)', tool.requires.map((r) => codeCell(r)).join(', ')]);