From 13fa950e4ead7dceb0cf08be69c88c87807b0c4e Mon Sep 17 00:00:00 2001 From: Yash Date: Mon, 14 Sep 2026 20:48:35 +0000 Subject: [PATCH] feat(harness): discover retained Assistant sessions --- .changeset/assistant-history-discovery.md | 5 + packages/harness/docs/assistant-history.md | 9 + .../src/core/assistant-history.test.ts | 180 ++++++++++++++++++ .../harness/src/core/assistant-history.ts | 134 +++++++++++++ .../src/server/assistant-records.test.ts | 36 +++- .../harness/src/server/assistant-records.ts | 22 +++ packages/harness/src/server/index.ts | 6 +- .../harness/src/shared/assistant-history.ts | 18 ++ 8 files changed, 403 insertions(+), 7 deletions(-) create mode 100644 .changeset/assistant-history-discovery.md create mode 100644 packages/harness/src/core/assistant-history.test.ts create mode 100644 packages/harness/src/core/assistant-history.ts create mode 100644 packages/harness/src/shared/assistant-history.ts diff --git a/.changeset/assistant-history-discovery.md b/.changeset/assistant-history-discovery.md new file mode 100644 index 000000000..62453155b --- /dev/null +++ b/.changeset/assistant-history-discovery.md @@ -0,0 +1,5 @@ +--- +"@sapiom/harness": patch +--- + +Discover retained Assistant history by Studio identity without starting a native runtime or requiring a Terminal conversation. Keep missing records distinct from incomplete or unavailable history. diff --git a/packages/harness/docs/assistant-history.md b/packages/harness/docs/assistant-history.md index 439cbaa1c..96a43d171 100644 --- a/packages/harness/docs/assistant-history.md +++ b/packages/harness/docs/assistant-history.md @@ -1,5 +1,14 @@ # Retained Assistant history +`GET /api/sessions/assistant-history?cwd=` returns +`{ entries: AssistantHistoryEntry[] }`, ordered by latest retained activity. +It requires the current boot token and workspace/Assistant authority. Entries +use Studio IDs, including sessions whose Terminal never started, and initially +report `nativeResume: "unchecked"`. Listing never launches or queries native +runtimes. Missing, partial and unreadable checkpoints have distinct states. +Account changes during listing discard the result. Malformed metadata returns +503 rather than silently substituting a different conversation. + `GET /api/sessions/:id/assistant/record` returns `{ record: AssistantRecord }` for the currently authorized Studio session and Assistant binding. Supply the current boot token in `X-Harness-Token`. The server checks current Assistant diff --git a/packages/harness/src/core/assistant-history.test.ts b/packages/harness/src/core/assistant-history.test.ts new file mode 100644 index 000000000..9de6fd53d --- /dev/null +++ b/packages/harness/src/core/assistant-history.test.ts @@ -0,0 +1,180 @@ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { AssistantHistory } from "./assistant-history.js"; +import { AssistantRecordStore } from "./assistant-record-store.js"; +import { + AssistantSessionStore, + type AssistantAssociation, +} from "./assistant-session-store.js"; +import { OpenCodeAccessError } from "./opencode-host.js"; +import type { HarnessSession } from "../shared/types.js"; +import type { AssistantRecord } from "../shared/assistant-record.js"; + +let root: string, + cwd: string, + records: AssistantRecordStore, + sessions: HarnessSession[], + store: AssistantSessionStore, + history: AssistantHistory; +let bindings: Map; +const authorize = vi.fn(); +const record = (binding: AssistantAssociation): AssistantRecord => ({ + schemaVersion: 1, + binding: { + harnessSessionId: binding.harnessSessionId, + conversationId: binding.conversationId, + contextAuthorityScope: binding.contextAuthorityScope, + cwd: binding.cwd, + }, + revision: 1, + capturedAt: "2026-09-14T10:00:00.000Z", + reconstructed: true, + turns: [], + turnCount: 0, + messageCount: 0, + limitations: [], +}); +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), "assistant-discovery-")); + cwd = join(root, "project"); + await mkdir(cwd); + store = new AssistantSessionStore(root); + records = new AssistantRecordStore(root); + bindings = new Map(); + sessions = []; + for (const [index, id] of [ + "studio-a", + "studio-b", + "terminal-only", + ].entries()) { + sessions.push({ + id, + cwd, + harness: "claude-code", + title: id, + status: "exited", + ready: false, + agentSessionId: null, + boundWorkflowPath: null, + terminalState: "not-started", + createdAt: "2026-09-14T09:00:00.000Z", + lastActiveAt: "2026-09-14T09:00:00.000Z", + }); + if (index === 2) continue; + const binding = await store.associate( + { + harnessSessionId: id, + cwd, + contextAuthorityScope: String(index + 1).repeat(64), + }, + String(index + 3).repeat(64), + async () => `ses_${index}`, + ); + bindings.set(id, binding!); + await store.transition(id, 0, { lifecycle: "ended", execution: "paused" }); + await records.write(record(binding!)); + } + authorize + .mockReset() + .mockImplementation(async (id) => bindings.get(id) ?? null); + history = new AssistantHistory({ + sessions: { + list: () => sessions, + get: (id) => sessions.find((s) => s.id === id), + }, + authorize, + records, + lifecycle: { describe: async (id) => (await store.lifecycle(id))! }, + }); +}); +afterEach(async () => { + await rm(root, { recursive: true, force: true }); +}); + +it("discovers distinct same-folder Assistant identities with no Terminal vendor or native runtime", async () => { + const result = await history.list(cwd); + expect(result.map((entry) => entry.harnessSessionId)).toEqual([ + "studio-a", + "studio-b", + ]); + expect(result[0]).toMatchObject({ + kind: "assistant", + history: "available", + nativeResume: "unchecked", + recordRevision: 1, + lifecycle: { lifecycle: "ended" }, + }); + expect(JSON.stringify(result)).not.toContain("contextAuthorityScope"); + expect(JSON.stringify(result)).not.toContain("conversationId"); + const other = join(root, "other"); + await mkdir(other); + expect(await history.list(other)).toEqual([]); +}); + +it("distinguishes missing, partial and failed retained records", async () => { + const first = bindings.get("studio-a")!; + await records.write({ + ...record(first), + revision: 2, + limitations: ["private-parts-omitted"], + }); + expect((await history.entry("studio-a"))?.history).toBe("partial"); + const directory = join( + root, + "assistant-sessions", + "studio-a", + "bindings", + first.contextAuthorityScope, + ); + await rm(join(directory, "record.json")); + await rm(join(directory, "record.json.previous"), { force: true }); + expect((await history.entry("studio-a"))?.history).toBe("missing"); + await writeFile(join(directory, "record.json"), "invalid"); + expect((await history.entry("studio-a"))?.history).toBe("unavailable"); +}); + +it("retains discovery after native data disappears", async () => { + await rm(join(root, "opencode"), { recursive: true, force: true }); + expect((await history.list(cwd)).map((entry) => entry.history)).toEqual([ + "available", + "available", + ]); +}); + +it("discards a read whose binding changes before it returns", async () => { + authorize + .mockResolvedValueOnce(bindings.get("studio-a")) + .mockResolvedValueOnce({ + ...bindings.get("studio-a"), + contextAuthorityScope: "f".repeat(64), + }); + await expect(history.entry("studio-a")).rejects.toBeInstanceOf( + OpenCodeAccessError, + ); +}); + +it("checks earlier entries again after reading the rest of a history list", async () => { + let calls = 0; + authorize.mockImplementation(async (id) => { + const binding = bindings.get(id) ?? null; + if (id !== "studio-a") return binding; + calls++; + return calls < 3 + ? binding + : { ...binding, contextAuthorityScope: "f".repeat(64) }; + }); + await expect(history.list(cwd)).rejects.toBeInstanceOf(OpenCodeAccessError); +}); + +it("omits unauthorized entries and surfaces corrupt lifecycle metadata", async () => { + authorize.mockRejectedValue(new OpenCodeAccessError("expired")); + expect(await history.list(cwd)).toEqual([]); + authorize.mockImplementation(async (id) => bindings.get(id) ?? null); + await writeFile( + join(root, "assistant-sessions", "studio-a", "lifecycle.json"), + "corrupt", + ); + await expect(history.list(cwd)).rejects.toThrow(); +}); diff --git a/packages/harness/src/core/assistant-history.ts b/packages/harness/src/core/assistant-history.ts new file mode 100644 index 000000000..5ecc31112 --- /dev/null +++ b/packages/harness/src/core/assistant-history.ts @@ -0,0 +1,134 @@ +import { realpath } from "node:fs/promises"; +import { isAbsolute } from "node:path"; +import type { AssistantHistoryEntry } from "../shared/assistant-history.js"; +import type { HarnessSession } from "../shared/types.js"; +import type { AssistantRecordStore } from "./assistant-record-store.js"; +import type { AssistantAssociation } from "./assistant-session-store.js"; +import type { AssistantLifecycleCoordinator } from "./assistant-lifecycle.js"; +import { OpenCodeAccessError } from "./opencode-host.js"; + +interface Options { + sessions: { + list(): HarnessSession[]; + get(id: string): HarnessSession | undefined; + }; + authorize: (id: string) => Promise; + records: Pick; + lifecycle: Pick; +} + +/** Metadata-only discovery. Native availability is checked separately for a selected entry. */ +export class AssistantHistory { + constructor(private readonly options: Options) {} + + async entry(id: string): Promise { + return (await this.read(id))?.entry ?? null; + } + + private async read( + id: string, + ): Promise<{ + entry: AssistantHistoryEntry; + binding: AssistantAssociation; + } | null> { + const session = this.options.sessions.get(id); + if (!session) return null; + const binding = await this.options.authorize(id); + if (!binding) return null; + const lifecycle = await this.options.lifecycle.describe(id); + let history: AssistantHistoryEntry["history"] = "unavailable"; + let recordRevision: number | null = null; + let updatedAt = session.lastActiveAt; + try { + const { harnessSessionId, contextAuthorityScope, conversationId, cwd } = + binding; + const record = await this.options.records.read({ + harnessSessionId, + contextAuthorityScope, + conversationId, + cwd, + }); + history = !record + ? "missing" + : record.limitations.length || + record.turns.some((turn) => turn.incomplete) + ? "partial" + : "available"; + recordRevision = record?.revision ?? null; + updatedAt = record?.capturedAt ?? updatedAt; + } catch { + // Storage failure is distinct from an authorized binding with no checkpoint. + } + if ( + JSON.stringify(await this.options.authorize(id)) !== + JSON.stringify(binding) + ) + throw new OpenCodeAccessError("Assistant binding changed"); + const current = this.options.sessions.get(id); + if (!current || current.cwd !== session.cwd) + throw new OpenCodeAccessError("Workspace changed"); + return { + binding, + entry: { + kind: "assistant", + harnessSessionId: id, + title: current.title, + cwd: binding.cwd, + createdAt: current.createdAt, + updatedAt, + lifecycle, + history, + nativeResume: "unchecked", + recordRevision, + }, + }; + } + + async list(cwd: string): Promise { + if (!isAbsolute(cwd) || cwd.length > 4096) + throw new OpenCodeAccessError("Workspace unavailable"); + const canonical = await realpath(cwd); + const sessions = this.options.sessions.list(); + const entries: { + entry: AssistantHistoryEntry; + binding: AssistantAssociation; + }[] = []; + // Bound filesystem concurrency when a workspace has a long history. + for (let offset = 0; offset < sessions.length; offset += 8) { + const page = await Promise.allSettled( + sessions.slice(offset, offset + 8).map(async (session) => { + try { + if ((await realpath(session.cwd)) !== canonical) return null; + const entry = await this.read(session.id); + return entry?.entry.cwd === canonical ? entry : null; + } catch (error) { + if ( + error instanceof OpenCodeAccessError || + (error as NodeJS.ErrnoException).code === "ENOENT" + ) + return null; + throw error; + } + }), + ); + for (const result of page) { + if (result.status === "rejected") throw result.reason; + if (result.value) entries.push(result.value); + } + } + // Revalidate the complete result after IO for the other entries. No old + // authority's titles or existence may escape on a mid-list account change. + for (const { entry, binding: previous } of entries) { + const binding = await this.options.authorize(entry.harnessSessionId); + if (!binding || JSON.stringify(binding) !== JSON.stringify(previous)) + throw new OpenCodeAccessError("Assistant access changed"); + } + return entries + .map(({ entry }) => entry) + .sort( + (a, b) => + b.updatedAt.localeCompare(a.updatedAt) || + a.harnessSessionId.localeCompare(b.harnessSessionId), + ); + } +} diff --git a/packages/harness/src/server/assistant-records.test.ts b/packages/harness/src/server/assistant-records.test.ts index 07223605b..6e0ebed47 100644 --- a/packages/harness/src/server/assistant-records.test.ts +++ b/packages/harness/src/server/assistant-records.test.ts @@ -17,6 +17,7 @@ const binding: AssistantAssociation = { }; const authorize = vi.fn(), read = vi.fn(); +const list = vi.fn(); const request = (token = "boot") => fetch(`${origin}/sessions/studio-a/assistant/record`, { headers: { "X-Harness-Token": token }, @@ -24,12 +25,16 @@ const request = (token = "boot") => beforeEach(async () => { authorize.mockReset().mockResolvedValue(binding); read.mockReset().mockResolvedValue({ reconstructed: true }); + list + .mockReset() + .mockResolvedValue([{ kind: "assistant", harnessSessionId: "studio-a" }]); const app = express(); app.use( createAssistantRecordsRouter({ bootToken: "boot", authorize, store: { read }, + history: { list }, }), ); server = createServer(app); @@ -57,12 +62,10 @@ it("requires boot authorization and reads only the exact current binding without }); it("does not return content when authority changes during a read", async () => { - authorize - .mockResolvedValueOnce(binding) - .mockResolvedValueOnce({ - ...binding, - contextAuthorityScope: "c".repeat(64), - }); + authorize.mockResolvedValueOnce(binding).mockResolvedValueOnce({ + ...binding, + contextAuthorityScope: "c".repeat(64), + }); expect((await request()).status).toBe(403); authorize.mockRejectedValueOnce(new OpenCodeAccessError("expired")); expect((await request()).status).toBe(403); @@ -76,3 +79,24 @@ it("distinguishes missing history from failed reads without exposing diagnostics expect(response.status).toBe(503); expect(await response.text()).not.toContain("private diagnostic"); }); + +it("gates metadata listing and rejects ambiguous workspace queries", async () => { + const url = `${origin}/sessions/assistant-history?cwd=%2Fworkspace`; + expect((await fetch(url)).status).toBe(401); + expect(list).not.toHaveBeenCalled(); + const headers = { "X-Harness-Token": "boot" }; + const response = await fetch(url, { headers }); + expect(response.status).toBe(200); + expect(response.headers.get("cache-control")).toBe("no-store"); + expect(await response.json()).toEqual({ + entries: [{ kind: "assistant", harnessSessionId: "studio-a" }], + }); + expect(list).toHaveBeenCalledWith("/workspace"); + expect((await fetch(`${url}&cwd=%2Fother`, { headers })).status).toBe(400); + list.mockRejectedValueOnce(new OpenCodeAccessError("private")); + expect((await fetch(url, { headers })).status).toBe(403); + list.mockRejectedValueOnce(new Error("private")); + const failed = await fetch(url, { headers }); + expect(failed.status).toBe(503); + expect(await failed.text()).not.toContain("private"); +}); diff --git a/packages/harness/src/server/assistant-records.ts b/packages/harness/src/server/assistant-records.ts index 11be48e6c..19a8aab67 100644 --- a/packages/harness/src/server/assistant-records.ts +++ b/packages/harness/src/server/assistant-records.ts @@ -3,14 +3,36 @@ import { createBootTokenMiddleware } from "./auth.js"; import type { AssistantAssociation } from "../core/assistant-session-store.js"; import type { AssistantRecordStore } from "../core/assistant-record-store.js"; import { OpenCodeAccessError } from "../core/opencode-host.js"; +import type { AssistantHistory } from "../core/assistant-history.js"; export function createAssistantRecordsRouter(options: { bootToken: string; authorize: (id: string) => Promise; store: Pick; + history?: Pick; }): Router { const router = express.Router(); router.use(createBootTokenMiddleware(options.bootToken)); + if (options.history) + router.get("/sessions/assistant-history", (req, res) => { + void (async () => { + res.setHeader("Cache-Control", "no-store"); + if ( + Object.keys(req.query).length !== 1 || + typeof req.query.cwd !== "string" + ) { + res.status(400).json({ error: "Select a workspace" }); + return; + } + try { + res.json({ entries: await options.history!.list(req.query.cwd) }); + } catch (error) { + res + .status(error instanceof OpenCodeAccessError ? 403 : 503) + .json({ error: "Assistant history unavailable" }); + } + })(); + }); router.get("/sessions/:id/assistant/record", (req, res) => { void (async () => { res.setHeader("Cache-Control", "no-store"); diff --git a/packages/harness/src/server/index.ts b/packages/harness/src/server/index.ts index 9faeb8265..7e9f92106 100644 --- a/packages/harness/src/server/index.ts +++ b/packages/harness/src/server/index.ts @@ -204,6 +204,7 @@ import { OpenCodeHost, type HostedOpenCode } from "../core/opencode-host.js"; import { AssistantRecordStore } from "../core/assistant-record-store.js"; import { AssistantRecordCapture } from "../core/assistant-record-capture.js"; import { assistantHistoryAccess } from "../core/assistant-history-access.js"; +import { AssistantHistory } from "../core/assistant-history.js"; import { OpenCodeFinalResponse } from "../core/opencode-final-response.js"; import { createAssistantRecordsRouter } from "./assistant-records.js"; import { OpenCodeObserver } from "../core/opencode-observer.js"; @@ -3622,10 +3623,13 @@ export const startServer = async ( res.setHeader("Cache-Control", "no-store"); res.json(assistantAccess.getBrowserState()); }); + const authorizeAssistantHistory = assistantHistoryAccess({ access: assistantAccess, authorize: authorizeAssistantWorkspace, store: assistantSessions }); + const assistantHistory = new AssistantHistory({ sessions: sessionManager, authorize: authorizeAssistantHistory, records: assistantRecords, lifecycle: assistantLifecycle }); app.use("/api", createAssistantRecordsRouter({ bootToken: options.bootToken, store: assistantRecords, - authorize: assistantHistoryAccess({ access: assistantAccess, authorize: authorizeAssistantWorkspace, store: assistantSessions }), + authorize: authorizeAssistantHistory, + history: assistantHistory, })); app.use( "/api", diff --git a/packages/harness/src/shared/assistant-history.ts b/packages/harness/src/shared/assistant-history.ts new file mode 100644 index 000000000..c20e9d9e1 --- /dev/null +++ b/packages/harness/src/shared/assistant-history.ts @@ -0,0 +1,18 @@ +import type { + AssistantLifecycle, + AssistantSessionView, +} from "./assistant-session.js"; + +/** Additive history entry: a Studio identity does not require a Terminal vendor ID. */ +export interface AssistantHistoryEntry { + kind: "assistant"; + harnessSessionId: string; + title: string; + cwd: string; + createdAt: string; + updatedAt: string; + lifecycle: AssistantLifecycle; + history: AssistantSessionView["history"]; + nativeResume: AssistantSessionView["nativeResume"]; + recordRevision: number | null; +}