From c199ee5235b79302cf6ddc5b300e705e4d5600aa Mon Sep 17 00:00:00 2001 From: Yash Date: Mon, 14 Sep 2026 21:17:19 +0000 Subject: [PATCH] feat(harness): show retained Assistant session history --- .changeset/saved-assistant-history.md | 5 + packages/harness/docs/assistant-history.md | 8 + .../harness/web/e2e/assistant-history.spec.ts | 238 ++++++++++++++++++ packages/harness/web/src/App.tsx | 55 +++- .../src/components/AssistantHistoryPane.tsx | 200 +++++++++++++++ .../web/src/components/DeadSessionPane.tsx | 4 +- .../web/src/components/WorkflowsRail.tsx | 31 ++- .../web/src/lib/assistant-history-client.ts | 197 +++++++++++++++ .../harness/web/src/lib/navigation-history.ts | 4 + .../harness/web/src/lib/use-harness-state.ts | 69 ++++- 10 files changed, 791 insertions(+), 20 deletions(-) create mode 100644 .changeset/saved-assistant-history.md create mode 100644 packages/harness/web/e2e/assistant-history.spec.ts create mode 100644 packages/harness/web/src/components/AssistantHistoryPane.tsx create mode 100644 packages/harness/web/src/lib/assistant-history-client.ts diff --git a/.changeset/saved-assistant-history.md b/.changeset/saved-assistant-history.md new file mode 100644 index 000000000..7a3abb6e6 --- /dev/null +++ b/.changeset/saved-assistant-history.md @@ -0,0 +1,5 @@ +--- +"@sapiom/harness": patch +--- + +Show retained Assistant history in Studio's existing session history, including sessions with no Terminal. diff --git a/packages/harness/docs/assistant-history.md b/packages/harness/docs/assistant-history.md index 198da95e2..a6e4c7e7b 100644 --- a/packages/harness/docs/assistant-history.md +++ b/packages/harness/docs/assistant-history.md @@ -48,6 +48,14 @@ so a successful GET can return an older `capturedAt`. Disposal and authority los cancel capture; opening a retained record never resumes execution. # Selected native availability +Open an Assistant entry from Studio's existing session history to read its saved +messages and tool excerpts. Mixed Terminal and Assistant entries are grouped by +Studio session ID. Sessions that have never started a Terminal remain visible. +The pane labels reconstructed, shortened and incomplete content, supports Back, +and discards results after an account, project or navigation change. Viewing a +record starts no native runtime. Native availability and Resume are separate +explicit actions. + Native inspection is explicit and separate from metadata listing. It validates the authorized saved Studio/native association, reads only that native session and its bounded history, and checks the saved execution context through the diff --git a/packages/harness/web/e2e/assistant-history.spec.ts b/packages/harness/web/e2e/assistant-history.spec.ts new file mode 100644 index 000000000..001980ad8 --- /dev/null +++ b/packages/harness/web/e2e/assistant-history.spec.ts @@ -0,0 +1,238 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; +import type { AssistantHistoryEntry } from "../../src/shared/assistant-history"; + +const cwd = "/Users/demo/acme-app"; +const entry = (id: string): AssistantHistoryEntry => ({ + kind: "assistant", + harnessSessionId: id, + title: `Saved ${id}`, + cwd, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-09-14T00:00:00.000Z", + lifecycle: { + version: 1, + harnessSessionId: id, + revision: 2, + lifecycle: "ended", + execution: "paused", + updatedAt: 2, + }, + history: "partial", + nativeResume: "unchecked", + recordRevision: 1, +}); +const record = (id: string) => ({ + schemaVersion: 1, + reconstructed: true, + revision: 1, + binding: { + harnessSessionId: id, + cwd, + conversationId: `ses_${id}`, + contextAuthorityScope: "PRIVATE_SCOPE", + }, + capturedAt: "2026-09-14T00:00:00.000Z", + turnCount: 1, + messageCount: 2, + limitations: ["field-truncation", "attachment-content-omitted"], + turns: [ + { + id: "user1", + incomplete: true, + acceptedContext: { hidden: "PRIVATE_CONTEXT" }, + messages: [ + { + id: "user1", + role: "user", + parentId: null, + createdAt: 1, + completedAt: null, + parts: [ + { + id: "p1", + type: "text", + text: "Read the README", + truncated: false, + }, + ], + }, + { + id: "answer1", + role: "assistant", + parentId: "user1", + createdAt: 2, + completedAt: 3, + parts: [ + { + id: "p2", + type: "text", + text: `Saved answer ${id}`, + truncated: false, + }, + { + id: "p3", + type: "tool", + callId: "call1", + name: "read", + status: "completed", + input: "README.md", + output: "A recorded excerpt", + error: null, + startedAt: 2, + completedAt: 3, + truncated: true, + }, + ], + }, + ], + }, + ], +}); +const publish = (page: Page, message: unknown) => + page.evaluate( + (message) => (window as any).__HARNESS_TEST__.publish(message), + message, + ); +const authority = (page: Page, revision: number, key = "account-a") => + publish(page, { + type: "assistant.state", + snapshot: { + hostInstanceId: "history-host", + authorityRevision: key, + revision, + enabled: true, + sessions: [], + lifecycles: [], + }, + }); +const rows = async (page: Page) => { + await page.getByTestId("history-trigger").click(); + await page.getByTestId("past-sessions-trigger").hover(); +}; +async function setup(page: Page, mode = "valid") { + const probe = { + calls: [] as string[], + holdList: false, + holdRecord: false, + lists: [] as Route[], + records: [] as Route[], + }; + await page.route("**/api/sessions/assistant-history?**", (route) => { + if (new URL(route.request().url()).searchParams.get("cwd") !== cwd) + return route.fulfill({ json: { entries: [] } }); + if (probe.holdList) { + probe.lists.push(route); + return; + } + return route.fulfill({ + json: { entries: [entry("assistant-only"), entry("sess-leasing")] }, + }); + }); + await page.route("**/api/sessions/*/assistant/record", (route) => { + if (probe.holdRecord) { + probe.records.push(route); + return; + } + const id = new URL(route.request().url()).pathname.split("/")[3]!; + return route.fulfill({ + status: mode === "missing" ? 404 : 200, + json: { record: record(mode === "foreign" ? "another-studio" : id) }, + }); + }); + page.on("request", (request) => { + if ( + /^\/opencode\/|\/assistant\/(inspect|resume|continue)$/.test( + new URL(request.url()).pathname, + ) + ) + probe.calls.push(request.url()); + }); + await page.goto("/?seed=0"); + await expect(page.locator(".harness-terminal")).toBeVisible(); + await authority(page, 1); + return probe; +} + +test("groups mixed records by Studio ID and reads pure Assistant history without native work", async ({ + page, +}, testInfo) => { + const probe = await setup(page); + await rows(page); + await expect( + page.getByTestId("assistant-history-sess-leasing"), + ).toContainText("Terminal + Assistant"); + await expect(page.getByTestId("exited-session-sess-leasing")).toHaveCount(0); + await expect(page.getByTestId("exited-session-sess-pricing")).toBeVisible(); + await page.getByTestId("assistant-history-assistant-only").click(); + const pane = page.getByTestId("assistant-history-pane"); + await expect(pane).toHaveAttribute("data-session-id", "assistant-only"); + await expect(pane).toContainText("Saved answer assistant-only"); + await expect(pane).toContainText("Reconstructed"); + await expect(pane).toContainText("Attachment contents are not saved"); + await expect(pane).toContainText("Turn incomplete when recorded"); + await pane.locator("summary").click(); + await expect(pane).toContainText("A recorded excerpt"); + await expect(pane).not.toContainText("PRIVATE_"); + await expect( + pane.getByRole("button", { name: /Resume|Continue|New session/ }), + ).toHaveCount(0); + await page.screenshot({ path: testInfo.outputPath("assistant-record.png") }); + await pane.getByRole("button", { name: "Close" }).click(); + await page.getByRole("button", { name: "Go back" }).click(); + await expect(pane).toContainText("Saved answer assistant-only"); + expect(probe.calls).toEqual([]); +}); + +for (const mode of ["missing", "foreign"]) { + test(`${mode} saved record never becomes a fabricated conversation`, async ({ + page, + }) => { + const probe = await setup(page, mode); + await rows(page); + await page.getByTestId("assistant-history-assistant-only").click(); + await expect(page.getByTestId("assistant-history-pane")).toContainText( + mode === "missing" + ? "No Assistant conversation was recorded" + : "Assistant history is unavailable", + ); + await expect(page.getByText("Saved answer another-studio")).toHaveCount(0); + expect(probe.calls).toEqual([]); + }); +} + +test("late history and record reads cannot cross account or navigation barriers", async ({ + page, +}) => { + const probe = await setup(page); + probe.holdList = true; + await rows(page); + await expect.poll(() => probe.lists.length).toBe(1); + await authority(page, 2, "account-b"); + await probe.lists[0]!.fulfill({ json: { entries: [entry("old-account")] } }); + await expect( + page + .getByTestId("past-sessions-card") + .getByText("Loading…", { exact: true }), + ).toHaveCount(0); + await expect( + page.getByText("Saved old-account", { exact: true }), + ).toHaveCount(0); + await page.keyboard.press("Escape"); + probe.holdList = false; + probe.holdRecord = true; + await rows(page); + await page.getByTestId("assistant-history-assistant-only").click(); + await expect.poll(() => probe.records.length).toBeGreaterThan(0); + await page + .getByTestId("assistant-history-pane") + .getByRole("button", { name: "Close", exact: true }) + .click(); + await Promise.all( + probe.records.map((route) => + route.fulfill({ json: { record: record("assistant-only") } }), + ), + ); + await expect(page.getByTestId("assistant-history-pane")).toHaveCount(0); + await expect(page.getByText("Saved answer assistant-only")).toHaveCount(0); + expect(probe.calls).toEqual([]); +}); diff --git a/packages/harness/web/src/App.tsx b/packages/harness/web/src/App.tsx index a9ab3ba43..69cb11609 100644 --- a/packages/harness/web/src/App.tsx +++ b/packages/harness/web/src/App.tsx @@ -86,6 +86,8 @@ import { TelemetryNotice } from "./components/TelemetryNotice"; import { TemplatesPanel } from "./components/TemplatesPanel"; import { Terminal } from "./components/Terminal"; import { AssistantPane } from "./components/AssistantPane"; +import { AssistantHistoryPane } from "./components/AssistantHistoryPane"; +import type { AssistantHistoryEntry } from "../../src/shared/assistant-history"; import type { ChatDraftStore } from "./components/OpenCodeChat"; import { Toast } from "./components/Toast"; import { TooltipLayer } from "./components/TooltipLayer"; @@ -731,9 +733,18 @@ export const App = (): JSX.Element => { // A PAST session under review: picked from the history menu, shown // in the terminal slot as a review pane — resuming/starting is the pane's // explicit action, never a side effect of the click that got here. - const [reviewSummary, setReviewSummary] = useState( + const [reviewSummary, setTerminalReviewSummary] = useState( null, ); + const [assistantReview, setAssistantReview] = useState<{ + entry: AssistantHistoryEntry; authority: string; navigation: number; + } | null>(null); + const setReviewSummary = useCallback((summary: SessionSummary | null) => { + setAssistantReview(null); + setTerminalReviewSummary(summary); + }, []); + const activeAssistantReview = assistantReview?.authority === harness.assistantHistoryAuthority && + assistantReview.navigation === studioRestoreGenerationRef.current ? assistantReview : null; // Template gallery opened from the command palette (browse is reachable // from anywhere, not only the add dialog / welcome panel entries). const [templatesOpen, setTemplatesOpen] = useState(false); @@ -1239,6 +1250,8 @@ export const App = (): JSX.Element => { }); } else if (templatesOpen) { recordVisit({ kind: "templates" }); + } else if (activeAssistantReview) { + recordVisit({ kind: "assistant-review", entry: activeAssistantReview.entry, authority: activeAssistantReview.authority }); } else if (reviewSummary) { recordVisit({ kind: "review", summary: reviewSummary }); } else if (composing) { @@ -1261,6 +1274,7 @@ export const App = (): JSX.Element => { effectiveStudioSelection, templatesOpen, reviewSummary, + activeAssistantReview, composing, activeSessionIdForNav, focusedAgentPath, @@ -1280,10 +1294,12 @@ export const App = (): JSX.Element => { setTemplatesOpen(visit.kind === "templates"); setComposing(visit.kind === "composer"); setReviewSummary(visit.kind === "review" ? visit.summary : null); + if (visit.kind === "assistant-review") + setAssistantReview({ entry: visit.entry, authority: visit.authority, navigation: studioRestoreGenerationRef.current }); if ( visit.kind === "templates" || visit.kind === "composer" || - visit.kind === "review" + visit.kind === "review" || visit.kind === "assistant-review" ) { setStudioSelection(null); } @@ -1600,7 +1616,7 @@ export const App = (): JSX.Element => { ) ? null : activeSession; - const showReview = reviewSummary != null; + const showReview = reviewSummary != null || activeAssistantReview != null; const showDead = !showReview && conversationSession?.status === "exited"; // An agent selected with no session that can WORK on it: honest absence, and // opening one lands on the "start a session" state. @@ -2476,6 +2492,19 @@ export const App = (): JSX.Element => { setSelectedProject(null); closeMobileDrawer(); }; + const reviewAssistant = (entry: AssistantHistoryEntry): void => { + const authority = harness.assistantHistoryAuthority; + if (!authority) return; + studioRestoreGenerationRef.current++; + setReviewSummary(null); + setAssistantReview({ entry, authority, navigation: studioRestoreGenerationRef.current }); + setStudioSelection(null); + setSelectedProject(null); + setComposing(false); + setTemplatesOpen(false); + setOverviewOpen(false); + closeMobileDrawer(); + }; // Jump from the Studio to the real code, in the editor the user picked. const openInEditor = (path: string): void => { @@ -2969,6 +2998,9 @@ export const App = (): JSX.Element => { setOverviewOpen(false); }} onReviewSummary={reviewPastSession} + onReviewAssistant={reviewAssistant} + assistantHistory={harness.assistantHistory} + assistantHistoryUnavailable={harness.assistantHistoryUnavailable} history={harness.history} historyLoading={harness.historyLoading} onOpenHistory={(cwds) => void harness.loadHistory(cwds)} @@ -3199,7 +3231,7 @@ export const App = (): JSX.Element => { openedAgentName={ showAgentEmpty ? (focusedWorkflow?.name ?? null) : null } - reviewTitle={reviewSummary ? reviewSummary.title : null} + reviewTitle={activeAssistantReview?.entry.title ?? reviewSummary?.title ?? null} // With no active CLI the centre still offers the ordinary // composer, but a selected project map must keep its real // session tabs visible so the user can activate one. Treating @@ -3347,7 +3379,19 @@ export const App = (): JSX.Element => { )}
- {showReview && reviewSummary ? ( + {activeAssistantReview ? ( + setAssistantReview(null)} + terminalNotStarted={state.sessions.find((session) => session.id === activeAssistantReview.entry.harnessSessionId)?.terminalState === "not-started"} + terminalLabel={state.sessions.find((session) => session.id === activeAssistantReview.entry.harnessSessionId)?.status !== "exited" ? "Open Terminal" : "View Terminal history"} + onOpenTerminal={state.sessions.some((session) => session.id === activeAssistantReview.entry.harnessSessionId && session.terminalState !== "not-started") + ? () => openSession(activeAssistantReview.entry.harnessSessionId) + : undefined} + /> + ) : showReview && reviewSummary ? ( { > diff --git a/packages/harness/web/src/components/AssistantHistoryPane.tsx b/packages/harness/web/src/components/AssistantHistoryPane.tsx new file mode 100644 index 000000000..d3409e1de --- /dev/null +++ b/packages/harness/web/src/components/AssistantHistoryPane.tsx @@ -0,0 +1,200 @@ +import { useEffect, useState, type ReactNode } from "react"; +import type { AssistantHistoryEntry } from "../../../src/shared/assistant-history"; +import { + readAssistantRecord, + type ReadableAssistantRecord, +} from "../lib/assistant-history-client"; +import { formatClockTime } from "../lib/session-record-view"; +import { Markdown } from "./Markdown"; + +const limitations: Record = { + "private-parts-omitted": + "Private reasoning and instructions are not included.", + "unknown-parts": "Some content could not be reconstructed.", + "attachment-content-omitted": + "Attachment contents are not saved in this record.", + "accepted-context-unavailable": + "Some workspace context is missing from this record.", + "field-truncation": "Long messages or tool results were shortened.", + "dropped-early-turns": "Only the most recent turns fit in this saved record.", + "dropped-message-content": + "Some message content was omitted to keep the record bounded.", +}; + +/** Read-only recorded material. Mounting this pane never starts a runtime. */ +export function AssistantHistoryPane({ + entry, + bootToken, + onClose, + actions, + onOpenTerminal, + terminalLabel, + terminalNotStarted, +}: { + entry: AssistantHistoryEntry; + bootToken: string; + onClose: () => void; + actions?: ReactNode; + onOpenTerminal?: () => void; + terminalLabel?: string; + terminalNotStarted?: boolean; +}) { + const [attempt, setAttempt] = useState(0); + const [state, setState] = useState<{ + loading: boolean; + record: ReadableAssistantRecord | null; + failed: boolean; + }>({ loading: true, record: null, failed: false }); + useEffect(() => { + const abort = new AbortController(); + setState({ loading: true, record: null, failed: false }); + void readAssistantRecord(entry, bootToken, abort.signal) + .then((record) => { + if (!abort.signal.aborted) + setState({ loading: false, record, failed: false }); + }) + .catch(() => { + if (!abort.signal.aborted) + setState({ loading: false, record: null, failed: true }); + }); + return () => abort.abort(); + }, [entry, bootToken, attempt]); + return ( +
+
+
+
{entry.title}
+
+ Assistant history · {entry.cwd} +
+
+
+ {actions} + {onOpenTerminal && ( + + )} + +
+
+ {terminalNotStarted && ( +

+ Terminal has not started for this session. +

+ )} +
+ {state.loading ? ( +
+ Loading Assistant history… +
+ ) : state.failed ? ( +
+ Assistant history is unavailable.{" "} + +
+ ) : !state.record ? ( +
+ No Assistant conversation was recorded for this session. +
+ ) : ( +
+
+ Reconstructed +
+

+ Saved Assistant messages and tool results from{" "} + {formatClockTime(state.record.capturedAt)}. This record may be + incomplete and does not restore the original conversation + context. +

+ {state.record.limitations.length > 0 && ( +
    + {state.record.limitations.map((code) => ( +
  • + {limitations[code] ?? + "Some recorded content is unavailable."} +
  • + ))} +
+ )} +
+
+
    + {state.record.turns.map((turn) => ( +
  1. + {turn.messages.map((message) => ( +
    +
    + + {message.role === "user" ? "You" : "Assistant"} + +
    + {message.parts.map((part) => + part.type === "text" ? ( +
    + + {part.truncated && ( + + Recorded text was shortened. + + )} +
    + ) : part.type === "tool" ? ( +
    + + {part.name} · {part.status} when recorded + {part.truncated ? " · shortened" : ""} + +
    +
    + Input +
    +
    +                                {part.input}
    +                              
    +
    + Recorded result +
    +
    +                                {part.output ??
    +                                  part.error ??
    +                                  "No result recorded."}
    +                              
    +
    +
    + ) : ( +

    + {part.type === "file" + ? `Attachment: ${part.name ?? part.mime} (contents not saved)` + : "Some content was omitted."} +

    + ), + )} +
    + ))} + {turn.incomplete && ( +
    + Turn incomplete when recorded +
    + )} +
  2. + ))} +
+
+ )} +
+
+ ); +} diff --git a/packages/harness/web/src/components/DeadSessionPane.tsx b/packages/harness/web/src/components/DeadSessionPane.tsx index 29f566954..25668ed62 100644 --- a/packages/harness/web/src/components/DeadSessionPane.tsx +++ b/packages/harness/web/src/components/DeadSessionPane.tsx @@ -9,6 +9,7 @@ import { trackingAttrs } from "../lib/analytics/tracking-attrs"; interface DeadSessionPaneProps { session: HarnessSession; + terminalOnly?: boolean; /** * Server-verified resumability for this session, from its history row. * Undefined while that lookup is still in flight — Resume stays available in @@ -74,6 +75,7 @@ function resumeBlockedReason(session: HarnessSession): string { */ export function DeadSessionPane({ session, + terminalOnly = false, resumeMode, loadRecord, onResume, @@ -107,7 +109,7 @@ export function DeadSessionPane({ -
Session exited
+
{terminalOnly ? "Terminal exited" : "Session exited"}
{session.cwd} {session.exitCode != null && ` · exit code ${session.exitCode}`} diff --git a/packages/harness/web/src/components/WorkflowsRail.tsx b/packages/harness/web/src/components/WorkflowsRail.tsx index a2fd18017..16f08eadd 100644 --- a/packages/harness/web/src/components/WorkflowsRail.tsx +++ b/packages/harness/web/src/components/WorkflowsRail.tsx @@ -1,4 +1,5 @@ import { AssistantActivity } from "./AssistantActivity"; +import type { AssistantHistoryEntry } from "../../../src/shared/assistant-history"; import type { AssistantProjection } from "../lib/assistant-state"; import { useCallback, @@ -158,6 +159,9 @@ interface WorkflowsRailProps { onNewSession: () => void; /** Opens the past-session review pane for a history entry. */ onReviewSummary: (summary: SessionSummary) => void; + onReviewAssistant: (entry: AssistantHistoryEntry) => void; + assistantHistory: AssistantHistoryEntry[]; + assistantHistoryUnavailable: boolean; history: SessionSummary[]; historyLoading: boolean; onOpenHistory: (cwds: string[]) => void; @@ -418,7 +422,7 @@ function PastSessionRow({ assistant?: AssistantProjection; sessionId?: string; testid: string; - harness: HarnessKind; + harness?: HarnessKind; title: string; meta: string; cwd: string; @@ -444,7 +448,7 @@ function PastSessionRow({ {...trackingAttrs({ object: "session" })} > - + {harness ? : } {title} @@ -489,6 +493,9 @@ export function WorkflowsRail({ onSelectOverview, onNewSession, onReviewSummary, + onReviewAssistant, + assistantHistory, + assistantHistoryUnavailable, history, historyLoading, onOpenHistory, @@ -642,6 +649,7 @@ export function WorkflowsRail({ const exitedSessions = sessions.filter( (session) => session.status === "exited", ); + const assistantByStudio = new Map(assistantHistory.map((entry) => [entry.harnessSessionId, entry])); const toggleHistory = (): void => { const next = !historyOpen; @@ -670,16 +678,17 @@ export function WorkflowsRail({ ) && !registryAgentIds.has(summary.agentSessionId), ); const pastRows = [ - ...exitedSessions.map((session) => ({ + ...exitedSessions.filter((session) => !assistantByStudio.has(session.id)).map((session) => ({ kind: "exited" as const, at: session.lastActiveAt, session, })), - ...pastSummaries.map((summary) => ({ + ...pastSummaries.filter((summary) => !summary.harnessSessionId || !assistantByStudio.has(summary.harnessSessionId)).map((summary) => ({ kind: "summary" as const, at: summary.lastActiveAt, summary, })), + ...assistantHistory.map((entry) => ({ kind: "assistant" as const, at: entry.updatedAt, entry })), ].sort((a, b) => b.at.localeCompare(a.at)); // Exited registry rows render from the session record (it carries live status @@ -1181,6 +1190,19 @@ export function WorkflowsRail({ data-testid="past-sessions-card" > {pastRows.map((row) => { + if (row.kind === "assistant") { + const terminal = sessions.find((session) => session.id === row.entry.harnessSessionId); + return { onReviewAssistant(row.entry); closeHistory(); }} + />; + } if (row.kind === "exited") { // No agentSessionId at all: the agent never established // a session, so there is provably nothing to resume — @@ -1250,6 +1272,7 @@ export function WorkflowsRail({ {historyLoading && (
Loading…
)} + {assistantHistoryUnavailable &&
Assistant history is unavailable. Reopen history to retry.
} {!historyLoading && pastRows.length === 0 && (
No past sessions yet diff --git a/packages/harness/web/src/lib/assistant-history-client.ts b/packages/harness/web/src/lib/assistant-history-client.ts new file mode 100644 index 000000000..eb9311723 --- /dev/null +++ b/packages/harness/web/src/lib/assistant-history-client.ts @@ -0,0 +1,197 @@ +import { z } from "zod"; +import type { AssistantHistoryEntry } from "../../../src/shared/assistant-history"; +import { + parseAssistantLifecycle, + type AssistantLifecycle, +} from "../../../src/shared/assistant-session"; + +const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); +const id = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/); +const timestamp = z.number().finite().nonnegative(); +const entrySchema = z + .object({ + kind: z.literal("assistant"), + harnessSessionId: id, + title: z.string(), + cwd: z.string(), + createdAt: z.string().datetime(), + updatedAt: z.string().datetime(), + lifecycle: z.custom( + (value) => parseAssistantLifecycle(value) !== null, + ), + history: z.enum(["available", "partial", "missing", "unavailable"]), + nativeResume: z.enum(["unchecked", "available", "missing", "unavailable"]), + recordRevision: count.positive().nullable(), + }) + .refine( + (entry) => entry.harnessSessionId === entry.lifecycle.harnessSessionId, + ); + +export function parseAssistantHistoryEntry( + value: unknown, +): AssistantHistoryEntry | null { + const result = entrySchema.safeParse(value); + return result.success ? result.data : null; +} + +const part = z.discriminatedUnion("type", [ + z.object({ + id, + type: z.literal("text"), + text: z.string().max(4000), + truncated: z.boolean(), + }), + z.object({ + id, + type: z.literal("tool"), + callId: id, + name: z.string().max(256), + status: z.enum(["pending", "running", "completed", "error"]), + input: z.string().max(512), + output: z.string().max(512).nullable(), + error: z.string().max(512).nullable(), + startedAt: timestamp.nullable(), + completedAt: timestamp.nullable(), + truncated: z.boolean(), + }), + z.object({ + id, + type: z.literal("file"), + name: z.string().nullable(), + mime: z.string(), + }), + z.object({ id, type: z.literal("omitted"), nativeType: z.string() }), +]); +const recordSchema = z.object({ + schemaVersion: z.literal(1), + reconstructed: z.literal(true), + revision: count.positive(), + binding: z.object({ + harnessSessionId: id, + cwd: z.string(), + conversationId: z.string().regex(/^ses_[A-Za-z0-9_-]{1,128}$/), + }), + capturedAt: z.string().datetime(), + turnCount: count, + messageCount: count, + limitations: z.array(z.string()), + turns: z.array( + z.object({ + id, + incomplete: z.boolean(), + messages: z + .array( + z.object({ + id, + role: z.enum(["user", "assistant"]), + parentId: id.nullable(), + createdAt: timestamp, + completedAt: timestamp.nullable(), + parts: z.array(part), + }), + ) + .min(1), + }), + ), +}); +export type ReadableAssistantRecord = Omit< + z.infer, + "binding" +>; + +/** Decode only displayed fields; accepted context and private binding scope are dropped. */ +export function parseReadableAssistantRecord( + value: unknown, + entry: AssistantHistoryEntry, +): ReadableAssistantRecord | null { + const result = recordSchema.safeParse(value); + if (!result.success) return null; + const { binding, ...record } = result.data; + if ( + binding.harnessSessionId !== entry.harnessSessionId || + binding.cwd !== entry.cwd || + record.revision < (entry.recordRevision ?? 0) + ) + return null; + const messages = new Set(), + parts = new Set(); + for (const turn of record.turns) { + if (turn.messages[0]!.id !== turn.id || turn.messages[0]!.role !== "user") + return null; + for (const message of turn.messages) { + if ( + messages.has(message.id) || + (message.role === "user" + ? message.id !== turn.id || message.parentId !== null + : message.parentId !== turn.id) + ) + return null; + messages.add(message.id); + for (const part of message.parts) { + if (parts.has(part.id)) return null; + parts.add(part.id); + } + } + } + return record.turnCount >= record.turns.length && + record.messageCount >= messages.size + ? record + : null; +} + +export async function assistantHistoryRequest( + path: string, + bootToken: string, + signal: AbortSignal, +): Promise { + const response = await fetch(path, { + headers: { "X-Harness-Token": bootToken }, + credentials: "omit", + cache: "no-store", + signal, + }); + if (response.status === 404) return null; + if (!response.ok) + throw new Error("Assistant history is unavailable. Try again."); + return response.json(); +} + +export async function readAssistantHistory( + cwd: string, + bootToken: string, + signal: AbortSignal, +): Promise { + const value = await assistantHistoryRequest( + `/api/sessions/assistant-history?cwd=${encodeURIComponent(cwd)}`, + bootToken, + signal, + ); + const result = z.object({ entries: z.array(entrySchema) }).safeParse(value); + if (!result.success) + throw new Error("Assistant history could not be verified."); + const ids = new Set( + result.data.entries.map((entry) => entry.harnessSessionId), + ); + if (ids.size !== result.data.entries.length) + throw new Error("Assistant history could not be verified."); + return result.data.entries; +} + +export async function readAssistantRecord( + entry: AssistantHistoryEntry, + bootToken: string, + signal: AbortSignal, +): Promise { + const value = await assistantHistoryRequest( + `/api/sessions/${encodeURIComponent(entry.harnessSessionId)}/assistant/record`, + bootToken, + signal, + ); + if (value === null) return null; + const record = parseReadableAssistantRecord( + (value as { record?: unknown }).record, + entry, + ); + if (!record) throw new Error("Assistant history could not be verified."); + return record; +} diff --git a/packages/harness/web/src/lib/navigation-history.ts b/packages/harness/web/src/lib/navigation-history.ts index 3b5492dc8..ac167ccb1 100644 --- a/packages/harness/web/src/lib/navigation-history.ts +++ b/packages/harness/web/src/lib/navigation-history.ts @@ -1,6 +1,7 @@ import { useCallback, useRef, useState } from "react"; import type { SessionSummary } from "@shared/types"; +import type { AssistantHistoryEntry } from "../../../src/shared/assistant-history"; import type { WorkspaceKey } from "@shared/workspace-scope"; import type { StudioProjectId } from "@shared/agent-map"; @@ -22,6 +23,7 @@ export type NavigationVisit = label: string; } | { kind: "review"; summary: SessionSummary } + | { kind: "assistant-review"; entry: AssistantHistoryEntry; authority: string } | { kind: "composer" } | { kind: "templates" }; @@ -54,6 +56,8 @@ export function sameNavigationVisit( if (a.kind === "review" && b.kind === "review") { return a.summary.agentSessionId === b.summary.agentSessionId; } + if (a.kind === "assistant-review" && b.kind === "assistant-review") + return a.entry.harnessSessionId === b.entry.harnessSessionId && a.authority === b.authority; return a.kind === b.kind; } diff --git a/packages/harness/web/src/lib/use-harness-state.ts b/packages/harness/web/src/lib/use-harness-state.ts index ce36258d0..4db6ce6c1 100644 --- a/packages/harness/web/src/lib/use-harness-state.ts +++ b/packages/harness/web/src/lib/use-harness-state.ts @@ -1,4 +1,6 @@ import { AssistantStateOrder, type AssistantProjection } from "./assistant-state"; +import type { AssistantHistoryEntry } from "../../../src/shared/assistant-history"; +import { readAssistantHistory } from "./assistant-history-client"; import { parseAgentMapInitializationStatus, type AgentMapInitializationStatus } from "@shared/agent-map-initialization"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { @@ -137,6 +139,9 @@ export interface PendingWorkspace { export interface HarnessStateHook { assistant: AssistantProjection; + assistantHistory: AssistantHistoryEntry[]; + assistantHistoryAuthority: string | null; + assistantHistoryUnavailable: boolean; endingSessionIds: ReadonlySet; authRevision: number; state: AppState | null; @@ -422,6 +427,16 @@ export function useHarnessState(): HarnessStateHook { const [state, setState] = useState(null); const assistantOrder = useRef(new AssistantStateOrder()).current; const [assistant, setAssistant] = useState(() => assistantOrder.current()); + const authoritySequence = useRef(0); + const assistantAuthorityKey = useCallback(() => { + const snapshot = assistantOrder.current().snapshot; + return snapshot?.enabled + ? `${authoritySequence.current}/${snapshot.hostInstanceId}/${snapshot.authorityRevision}` + : null; + }, [assistantOrder]); + const [assistantHistory, setAssistantHistory] = useState<{ + authority: string | null; entries: AssistantHistoryEntry[]; unavailable: boolean; + }>({ authority: null, entries: [], unavailable: false }); const endingSessions = useRef(new Set()); const [endingSessionIds, setEndingSessionIds] = useState>( new Set(), @@ -513,7 +528,9 @@ export function useHarnessState(): HarnessStateHook { const [historyLoading, setHistoryLoading] = useState(false); // History fan-out bookkeeping — see loadHistory. Refs, not state: neither // affects the render, and both are read/written within a single call. - const inFlightHistory = useRef>>( + const inFlightHistory = useRef>>( new Map(), ); const historyLoads = useRef(0); @@ -1368,6 +1385,7 @@ export function useHarnessState(): HarnessStateHook { }, BUSY_WINDOW_MS), ); } else if (message.type === "auth.changed") { + authoritySequence.current++; setAssistant(assistantOrder.authChanged()); // Accept a barrier synchronously: merely issuing the refresh cannot // stop an older in-flight success from restoring another account. @@ -1424,13 +1442,21 @@ export function useHarnessState(): HarnessStateHook { // deduplicates concurrent callers, it is NOT a cache, so a later open // still re-reads the directory. const unique = Array.from(new Set(cwds)); + const authority = assistantAuthorityKey(); const requests = unique.map((cwd) => { - const pending = inFlightHistory.current.get(cwd); + const key = `${authority ?? "terminal"}:${cwd}`; + const pending = inFlightHistory.current.get(key); if (pending) return pending; - const request = api.sessionHistory(cwd).finally(() => { - inFlightHistory.current.delete(cwd); - }); - inFlightHistory.current.set(cwd, request); + const request = Promise.allSettled([ + api.sessionHistory(cwd), + authority + ? readAssistantHistory(cwd, getBootToken(), AbortSignal.timeout(5000)) + : Promise.resolve([]), + ]).then(([terminal, assistant]) => ({ + terminal: terminal.status === "fulfilled" ? terminal.value : null, + assistant: assistant.status === "fulfilled" ? assistant.value : null, + })).finally(() => inFlightHistory.current.delete(key)); + inFlightHistory.current.set(key, request); return request; }); @@ -1444,17 +1470,34 @@ export function useHarnessState(): HarnessStateHook { const results = await Promise.allSettled(requests); const refreshed: SessionSummary[] = []; const refreshedCwds = new Set(); + const assistantEntries: AssistantHistoryEntry[] = []; + const assistantCwds = new Set(); + let unavailable = false; results.forEach((result, index) => { if (result.status !== "fulfilled") return; - refreshedCwds.add(unique[index]!); - refreshed.push(...result.value); + if (result.value.terminal) { + refreshedCwds.add(unique[index]!); + refreshed.push(...result.value.terminal); + } + if (result.value.assistant) { + assistantCwds.add(unique[index]!); + assistantEntries.push(...result.value.assistant); + } else unavailable = true; }); setHistory((prev) => mergeHistory(prev, refreshed, refreshedCwds)); + if (authority && authority === assistantAuthorityKey()) { + setAssistantHistory((prev) => ({ authority, unavailable, entries: [ + ...new Map([ + ...(prev.authority === authority ? prev.entries.filter((entry) => !assistantCwds.has(entry.cwd)) : []), + ...assistantEntries, + ].map((entry) => [entry.harnessSessionId, entry])).values(), + ] })); + } } finally { historyLoads.current -= 1; if (historyLoads.current === 0) setHistoryLoading(false); } - }, []); + }, [assistantAuthorityKey]); /** Refresh only the server-issued project identities after a root mutation. * Replacing the full AppState here could overwrite newer session/workflow bus @@ -1765,6 +1808,8 @@ export function useHarnessState(): HarnessStateHook { endingSessions.current.add(id); setEndingSessionIds(new Set(endingSessions.current)); const selectionAtStart = switchSeqRef.current; + const authorityAtStart = assistantAuthorityKey(); + const authAtStart = authoritySequence.current; const lifecycleAtStart = assistantOrder .current() .snapshot?.lifecycles?.find((row) => row.harnessSessionId === id); @@ -1782,6 +1827,7 @@ export function useHarnessState(): HarnessStateHook { endingSessions.current.delete(id); setEndingSessionIds(new Set(endingSessions.current)); } + if (authAtStart !== authoritySequence.current || authorityAtStart !== assistantAuthorityKey()) return; const lifecycles = assistantOrder.current().snapshot?.lifecycles ?? []; const lifecycle = lifecycles.find((row) => row.harnessSessionId === id); // A newer Resume can finish before this older End response arrives. @@ -1828,7 +1874,7 @@ export function useHarnessState(): HarnessStateHook { selectSession(nextRunning ? nextRunning.id : null); } }, - [assistantOrder, activeSessionId, selectSession], + [assistantOrder, assistantAuthorityKey, activeSessionId, selectSession], ); const connectWorkflow = useCallback( @@ -2453,6 +2499,9 @@ export function useHarnessState(): HarnessStateHook { return { assistant, + assistantHistory: assistantHistory.authority === assistantAuthorityKey() ? assistantHistory.entries : [], + assistantHistoryAuthority: assistantAuthorityKey(), + assistantHistoryUnavailable: assistantHistory.authority === assistantAuthorityKey() && assistantHistory.unavailable, endingSessionIds, state, authRevision,