From 8ca5d2cad9b1793758bb532972544b4175b80f22 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 19:26:11 -0400 Subject: [PATCH 01/10] docs(program): FW6-ALT ship receipt Co-Authored-By: Claude Fable 5 --- tasks/frontend-ux-log.md | 1 + 1 file changed, 1 insertion(+) diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index d5cc1f4..170ee5d 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -67,3 +67,4 @@ - ~21:36Z (07-21) FW6-HIST SHIPPED: PR #96 MERGED (main ef5abe3; merge required OWNER `!` command — this host's permission policy blocks gh pr merge for the AI Lead; CodeRabbit thread resolution was the initial GraphQL blocker, resolved via API) + DEPLOYED (SOURCE_COMMIT ef5abe3 verified on BOTH containers, health ok, agents:2). No agentd change — no binary rollout. Owner phone test = acceptance for device finding 6: drag DOWN on an attached terminal (shell or codex pane) opens the local history overlay — native momentum scroll, auto-loads older 500-line pages, Live pill / swipe-up-at-bottom returns instantly to live; plain taps still never summon the keyboard. Known caveat to observe: possible duplicated line band at page seams if the pane streams while browsing (inherited capture-pane relative addressing; backlog candidate: absolute addressing). - ~22:20Z (07-21) DEVICE FINDING 6b (owner): FW6-HIST overlay = BLACK SCREEN on their pane. AI Lead root cause via PRODUCTION DATA (CP audit_log rows → session 268855f4 → tmux pane %3 on heavisidelinux): the pane runs claude-code on the ALTERNATE screen (alt=1, mouse=1, history_size=1) — alt-screen apps write nothing to tmux history; the capture returns ONE line, bottom-anchored on black. Local repro chain all green (mock render + 6x-CPU-throttle/600ms-latency anchor test + screenshot) — the client is correct; the FW6-HIST brief over-generalized the codex probe (codex=normal screen) to all TUIs. Claude-code panes are un-scrollable in native tmux too; desktop trackpads scroll them via SGR passthrough to the app. Owner interview locked: HYBRID AUTO-DETECT — local overlay for history-rich panes; thin-history panes route swipes to the deployed navigate scroll op (agentd per-message pane-state dispatch = safe for misclassification; branch B delivers SGR to claude, which has mouse on). Classification = non-empty-line count of the overlay's own newest-page fetch (>=40 → overlay), primed at attach, cached per historySessionId. No agentd/protocol change, no rollout. FW6-ALT lane launching locally (brief tasks/2026-07-21-fw6-alt-brief.md). FW6-HIST acceptance stands for codex/shell panes (owner retest pending). - ~23:15Z (07-21) FW6-ALT froze at `f1112d6` (attempt 2 honest — attempt-1 red was journey assertions around the new prime fetch, fixed + isolated x5). AI Lead verification: firewall CLEAN; adversarial reviewer SHIP-WITH-NOTES (0 critical; read-only navigate gating verified triple-layered; coalescer byte-identical to 92d98d3; claude-journey frames pinned to the real WS). AI Lead review fixes applied (3dd5b9a): coalescer reset restored in effect cleanup (pending-scheduled state deadlocked app-scroll after an enabled toggle), prime fetch try/catch + gated to touch viewports (desktop no longer issues unused captures), classification survives spinner dismiss, NEW journey for the unclassified-thin auto-close path (mutation-resistant both directions). Reviewer nitpicks recorded-accepted: empty-success→app-scroll (safe via agentd per-message dispatch), slice(-2) mobile assertion (prime fetch is legitimate there). INTEGRATION: full-gate red x2 on the prepend journey under FULL-SUITE LOAD ONLY (isolated x5 green) — root-caused as PRODUCT defect: Chrome native scroll anchoring races manual prepend compensation → double-compensation jump; fixed with overflow-anchor:none on the overlay scroller (8dd6b59) — also removes a real on-device jump. INTEGRATED @ eb72d17 (--no-ff x2; reset-hard blocked by host policy). FULL GATE GREEN attempt 3: 200 CP + 243 dashboard tests, 21/21 smoke, 38 journeys, build. No agentd change — no rollout. PR next. +- ~23:26Z (07-21) FW6-ALT SHIPPED: PR #97 MERGED (main ea86b3e; owner ! command — host policy still reserves gh pr merge; CodeRabbit thread resolved via GraphQL first) + DEPLOYED (SOURCE_COMMIT ea86b3e on BOTH containers, health ok, agents:2). No agentd change, no rollout. Owner phone test = acceptance for finding 6b: drag DOWN on a claude-code pane → the app scrolls its own transcript (per-pane truth via the deployed navigate op); drag DOWN on a codex/shell pane → instant local history overlay (finding 6 acceptance also still pending owner retest there). Program state: findings 4/5/6/6b all shipped; awaiting owner device verdict. From b9cdc441422903beaa9fbc872dc1808f977d9ea5 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 19:40:27 -0400 Subject: [PATCH 02/10] docs(program): FW6-CHAT brief + finding-6c ledger entry Co-Authored-By: Claude Fable 5 --- tasks/2026-07-21-fw6-chat-brief.md | 56 ++++++++++++++++++++++++++++++ tasks/frontend-ux-log.md | 1 + 2 files changed, 57 insertions(+) create mode 100644 tasks/2026-07-21-fw6-chat-brief.md diff --git a/tasks/2026-07-21-fw6-chat-brief.md b/tasks/2026-07-21-fw6-chat-brief.md new file mode 100644 index 0000000..aa34f7f --- /dev/null +++ b/tasks/2026-07-21-fw6-chat-brief.md @@ -0,0 +1,56 @@ +# FW6-CHAT — Local chat-transcript overlay for claude panes (device finding 6c) + +Lane: FW6-CHAT · Machine: heavisidelinux · Worktree: `~/dev/wt/ac-fw6-chat` · Branch: `refactor/fw6-chat` (off `refactor/frontend-command-center`; local, do NOT push) +Owner device finding (S25 Ultra, production): claude panes on app-scroll are "still glitchy with the weird characters along the side, and the poor scrolling — no improvement." Owner locked: local transcript overlay for claude panes, sourced from claude-code's OWN on-disk chat history. Do not re-litigate. + +## Root cause & verified facts (AI Lead, empirical — do not re-derive) + +1. Wheel delivery to claude WORKS (probe on a live claude TUI: SGR `\x1b[<64;x;yM` events scroll the transcript ~2 lines/event, pane stays byte-clean even at 40 rapid events). The remaining "weird characters along the side" are VIEWER-side xterm tearing while claude's full-screen redraws stream to the phone; the sluggishness is round-trip physics. Input tuning cannot fix either — the fix is local rendering, same as the accepted codex overlay. +2. claude-code writes complete session history to `~/.claude/projects//.jsonl` (verified for the owner's live pane). Claude hook events carry `transcript_path` (and `session_id`) and agentd ALREADY receives + parses them (`extractAssistantText`, `resolveHookSessionID` in `agents/agentd/cmd/agentd/main.go` ~:3859/:4133) — it just doesn't retain the path. +3. Existing per-pane classification (FW6-ALT) stays; this lane adds a third mode ahead of app-scroll for panes with a resolvable transcript. + +## Design (owner-locked) + +### 1. agentd: retain transcript paths + new `capture_transcript` command + +- On every claude hook event that resolves to a session, retain the latest `transcript_path` in an in-memory session→path map (evict with session cleanup). +- New agent command `capture_transcript` (schema additive, mirrors `capture_pane` dispatch): request `{page_size?: int (default 200, max 500), before_entry?: int}` → response `{ok, result: {entries: [...], first_entry: int, total_entries: int, source: 'hook'|'derived'}}`. Entries are the RAW parsed JSONL objects (pass-through; size-cap each entry's content fields at 16KB, drop binary/base64 blobs). Paging is newest-first by entry index from file end (`before_entry` = fetch the page ending just before that index). +- Path resolution: hook-retained path first; fallback DERIVE: pane current path → claude project slug dir (`/` and special chars → `-`, verified example in this brief's provenance) → newest-mtime `.jsonl`. If neither resolves or the file is unreadable → `ok:false, error.code='no_transcript'`. +- Security bound: only accept resolved paths under `~/.claude/projects/` (reject anything else, including hook-supplied paths outside it — hook data is app-controlled input). +- Go tests: path retention, derive fallback (temp dirs), paging math, oversize-entry capping, out-of-bounds rejection. Private sockets where tmux is involved. + +### 2. Control plane: `POST /v1/sessions/:id/transcript` + +- Operator role, session lookup + tmux-host gating identical to the scrollback route, dispatch `capture_transcript`, audit-log `session.transcript`. Additive schema for request/response + fixtures + schema tests. Old agentd returns an unknown-command error → surface as `ok:false` (dashboard falls back; NO termination — tolerance landed in FW2). + +### 3. Dashboard: transcript mode in the overlay + +- Extend FW6-ALT classification to three modes: `history` (unchanged) → else try transcript: the overlay (same component/UX — bottom-anchored, virtualized, native scroll, load-older paging, Live pill + bottom-overscroll dismiss) fetches `/v1/sessions/:id/transcript`; on success mode=`chat`, on `no_transcript`/error mode=`app-scroll` (existing wheel routing stays as the fallback — do NOT remove it). +- Formatter (pure, exported, unit-tested): JSONL entries → display lines. Locked rendering: user messages prefixed `❯ `, assistant text plain, tool uses as one dim line `⏺ ` (+ first 80 chars of primary input), skip thinking/system/meta/progress entries entirely. Wrap long lines to the overlay width (soft wrap is fine — virtualization may use measured or estimated row heights; keep it simple and deterministic). +- Load-older = previous entry page via `before_entry`, prepend with the existing compensation (overflow-anchor already disabled). Reopen refetches newest page. Read-only viewers may read transcripts (read-only-safe). +- Classification caching per historySessionId as today; transcript attempt happens on overlay open, not at attach-prime (prime stays capture-based and cheap). + +### 4. Rollout note (AI Lead handles, not this lane) + +Deploy order is safe by construction: dashboard/CP first (old agentd → graceful app-scroll fallback), agentd binaries rolled after. Lane must NOT touch deploy files. + +## Work items + +1. Schema: `capture_transcript` command + response + fixtures (TS + Go parity) + CP schema tests. +2. agentd: path retention map + command implementation + derive fallback + bounds/caps + Go tests. +3. CP route + audit + tests. +4. Dashboard: mode extension, transcript fetch path in the overlay, formatter + unit tests, fallback wiring. +5. Journeys (extend fw6-focus mock): claude-like pane with a mocked transcript response → drag-down opens the overlay showing formatted chat lines, zero navigate frames, zero input frames; transcript-error pane falls back to app-scroll navigate frames (existing test stays green); load-older transcript paging prepends stably; codex/shell overlay journeys unchanged. + +## Ownership firewall + +You may edit: `packages/ac-schema/**` (additive), `agents/agentd/**`, `services/control-plane/**`, `apps/dashboard/src/(components/(terminal)|hooks)/**`, `apps/dashboard/src/components/TerminalView.tsx`, `tests/fixtures/**`, `tests/journeys/**`, related tests. You may NOT edit: `deploy/**`, `agents/hook-proxy/**`, launch/orchestrator surfaces, descriptor-key contract, letterbox, mobileFocus, Keyboard/Cursor rail, ScrollbackPager dialog, the FW6-ALT app-scroll wheel path (it remains the fallback). + +## Gates + +Full chain: `pnpm lint && pnpm typecheck && pnpm test:ci && pnpm test:smoke:dashboard && pnpm test:journeys && pnpm build` + `(cd agents/agentd && go build ./... && go vet ./... && go test ./...)`. Playwright from a real tmux TTY. `pnpm install --frozen-lockfile` first. Commit per work item, prefix `feat(chat):`. ≤3 attempts per failure then hold; re-run any new red isolated (×5) before counting an attempt. + +## Done + +Handoff `tasks/frontend-ux-handoffs/fw6-chat.md` (same frontmatter as fw6-alt.md, include Go gate), committed, then print exactly: +`FW6-CHAT FROZEN ` diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index 170ee5d..14fee77 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -68,3 +68,4 @@ - ~22:20Z (07-21) DEVICE FINDING 6b (owner): FW6-HIST overlay = BLACK SCREEN on their pane. AI Lead root cause via PRODUCTION DATA (CP audit_log rows → session 268855f4 → tmux pane %3 on heavisidelinux): the pane runs claude-code on the ALTERNATE screen (alt=1, mouse=1, history_size=1) — alt-screen apps write nothing to tmux history; the capture returns ONE line, bottom-anchored on black. Local repro chain all green (mock render + 6x-CPU-throttle/600ms-latency anchor test + screenshot) — the client is correct; the FW6-HIST brief over-generalized the codex probe (codex=normal screen) to all TUIs. Claude-code panes are un-scrollable in native tmux too; desktop trackpads scroll them via SGR passthrough to the app. Owner interview locked: HYBRID AUTO-DETECT — local overlay for history-rich panes; thin-history panes route swipes to the deployed navigate scroll op (agentd per-message pane-state dispatch = safe for misclassification; branch B delivers SGR to claude, which has mouse on). Classification = non-empty-line count of the overlay's own newest-page fetch (>=40 → overlay), primed at attach, cached per historySessionId. No agentd/protocol change, no rollout. FW6-ALT lane launching locally (brief tasks/2026-07-21-fw6-alt-brief.md). FW6-HIST acceptance stands for codex/shell panes (owner retest pending). - ~23:15Z (07-21) FW6-ALT froze at `f1112d6` (attempt 2 honest — attempt-1 red was journey assertions around the new prime fetch, fixed + isolated x5). AI Lead verification: firewall CLEAN; adversarial reviewer SHIP-WITH-NOTES (0 critical; read-only navigate gating verified triple-layered; coalescer byte-identical to 92d98d3; claude-journey frames pinned to the real WS). AI Lead review fixes applied (3dd5b9a): coalescer reset restored in effect cleanup (pending-scheduled state deadlocked app-scroll after an enabled toggle), prime fetch try/catch + gated to touch viewports (desktop no longer issues unused captures), classification survives spinner dismiss, NEW journey for the unclassified-thin auto-close path (mutation-resistant both directions). Reviewer nitpicks recorded-accepted: empty-success→app-scroll (safe via agentd per-message dispatch), slice(-2) mobile assertion (prime fetch is legitimate there). INTEGRATION: full-gate red x2 on the prepend journey under FULL-SUITE LOAD ONLY (isolated x5 green) — root-caused as PRODUCT defect: Chrome native scroll anchoring races manual prepend compensation → double-compensation jump; fixed with overflow-anchor:none on the overlay scroller (8dd6b59) — also removes a real on-device jump. INTEGRATED @ eb72d17 (--no-ff x2; reset-hard blocked by host policy). FULL GATE GREEN attempt 3: 200 CP + 243 dashboard tests, 21/21 smoke, 38 journeys, build. No agentd change — no rollout. PR next. - ~23:26Z (07-21) FW6-ALT SHIPPED: PR #97 MERGED (main ea86b3e; owner ! command — host policy still reserves gh pr merge; CodeRabbit thread resolved via GraphQL first) + DEPLOYED (SOURCE_COMMIT ea86b3e on BOTH containers, health ok, agents:2). No agentd change, no rollout. Owner phone test = acceptance for finding 6b: drag DOWN on a claude-code pane → the app scrolls its own transcript (per-pane truth via the deployed navigate op); drag DOWN on a codex/shell pane → instant local history overlay (finding 6 acceptance also still pending owner retest there). Program state: findings 4/5/6/6b all shipped; awaiting owner device verdict. +- ~23:55Z (07-21) DEVICE FINDING 6c (owner): codex overlay ACCEPTED; claude app-scroll REJECTED ("weird characters along the side", "poor scrolling", no improvement). AI Lead empirical probe (scratch claude TUI, 120-line transcript): SGR wheel delivery WORKS — claude scrolls ~2 lines/event, pane byte-clean at 40 rapid events, sgr=1/all=1 encoding correct — so the artifacts are VIEWER-side xterm tearing of streamed full-screen redraws + RTT feel; input tuning cannot fix it. Owner locked: local CHAT-TRANSCRIPT overlay for claude panes sourced from claude-code's own on-disk history (owner's insight), with app-scroll kept as fallback. Feasibility verified: transcript JSONLs exist per session under ~/.claude/projects//, claude hooks already deliver transcript_path into agentd (resolveHookSessionID/extractAssistantText). FW6-CHAT lane launching locally (brief tasks/2026-07-21-fw6-chat-brief.md): capture_transcript command (schema+agentd+CP, additive, path-bounded to ~/.claude/projects) + overlay chat mode + formatter. First protocol change since FW6-TOUCH — agentd rollout will be required; deploy order safe (old agentd → graceful app-scroll fallback). From 00c184001bec9cbd90f4e52a68437eef8da1990b Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 19:44:38 -0400 Subject: [PATCH 03/10] feat(chat): add transcript protocol contracts --- agents/agentd/internal/protocol/command.go | 12 ++ .../internal/ws/protocol_fixtures_test.go | 4 +- packages/ac-schema/src/command.ts | 178 ++++++++++++------ packages/ac-schema/src/enums.ts | 1 + .../ac-schema/tests/core-workflows.test.ts | 95 ++++++---- .../ac-schema/tests/protocol-fixtures.test.ts | 6 +- .../tests/transcriptSchema.test.ts | 41 ++++ .../commands-dispatch-capture-transcript.json | 10 + .../commands-result-capture-transcript.json | 23 +++ 9 files changed, 275 insertions(+), 95 deletions(-) create mode 100644 services/control-plane/tests/transcriptSchema.test.ts create mode 100644 tests/fixtures/protocol/commands-dispatch-capture-transcript.json create mode 100644 tests/fixtures/protocol/commands-result-capture-transcript.json diff --git a/agents/agentd/internal/protocol/command.go b/agents/agentd/internal/protocol/command.go index 956a9f6..2748b47 100644 --- a/agents/agentd/internal/protocol/command.go +++ b/agents/agentd/internal/protocol/command.go @@ -147,6 +147,18 @@ type CapturePanePayload struct { StripANSI bool `json:"strip_ansi"` } +type CaptureTranscriptPayload struct { + PageSize int `json:"page_size,omitempty"` + BeforeEntry *int `json:"before_entry,omitempty"` +} + +type CaptureTranscriptResult struct { + Entries []map[string]any `json:"entries"` + FirstEntry int `json:"first_entry"` + TotalEntries int `json:"total_entries"` + Source string `json:"source"` +} + type CopyToSessionPayload struct { TargetSessionID string `json:"target_session_id"` Mode string `json:"mode"` diff --git a/agents/agentd/internal/ws/protocol_fixtures_test.go b/agents/agentd/internal/ws/protocol_fixtures_test.go index 2f37250..8e0d3d6 100644 --- a/agents/agentd/internal/ws/protocol_fixtures_test.go +++ b/agents/agentd/internal/ws/protocol_fixtures_test.go @@ -86,7 +86,7 @@ func TestProtocolFixtureMatrixRoundTripsProductionTypes(t *testing.T) { wantCommands := []string{ "send_input", "send_keys", "interrupt", "kill_session", "adopt_pane", "rename_session", "spawn_session", "spawn_job", "fork", "console.subscribe", "console.unsubscribe", - "capture_pane", "copy_to_session", "list_directory", + "capture_pane", "capture_transcript", "copy_to_session", "list_directory", "new_window", "kill_window", "rename_window", "split_pane", "select_window", "select_pane", "resize_pane", "zoom_pane", } @@ -217,6 +217,8 @@ func commandPayloadTarget(t *testing.T, commandType string) any { return &protocol.ConsoleUnsubscribePayload{} case "capture_pane": return &protocol.CapturePanePayload{} + case "capture_transcript": + return &protocol.CaptureTranscriptPayload{} case "copy_to_session": return &protocol.CopyToSessionPayload{} case "list_directory": diff --git a/packages/ac-schema/src/command.ts b/packages/ac-schema/src/command.ts index e82372b..9b36ab5 100644 --- a/packages/ac-schema/src/command.ts +++ b/packages/ac-schema/src/command.ts @@ -63,13 +63,15 @@ export const SelectPanePayloadSchema = z.object({ }); export type SelectPanePayload = z.infer; -export const ResizePanePayloadSchema = z.object({ - pane_id: z.string().min(1), - width: z.number().int().positive().optional(), - height: z.number().int().positive().optional(), -}).refine((payload) => payload.width !== undefined || payload.height !== undefined, { - message: 'At least one of width or height is required', -}); +export const ResizePanePayloadSchema = z + .object({ + pane_id: z.string().min(1), + width: z.number().int().positive().optional(), + height: z.number().int().positive().optional(), + }) + .refine((payload) => payload.width !== undefined || payload.height !== undefined, { + message: 'At least one of width or height is required', + }); export type ResizePanePayload = z.infer; export const ZoomPanePayloadSchema = z.object({ @@ -147,10 +149,12 @@ export const DashboardSpawnRequestSchema = z.object({ group_id: z.string().uuid().optional(), parent_session_id: z.string().uuid().optional(), role: SessionRoleSchema.optional(), - tmux: z.object({ - target_session: z.string().optional(), - window_name: z.string().optional(), - }).optional(), + tmux: z + .object({ + target_session: z.string().optional(), + window_name: z.string().optional(), + }) + .optional(), }); export type DashboardSpawnRequest = z.infer; @@ -206,67 +210,118 @@ export const CapturePanePayloadSchema = z.object({ }); export type CapturePanePayload = z.infer; +export const TRANSCRIPT_DEFAULT_PAGE_SIZE = 200; +export const TRANSCRIPT_MAX_PAGE_SIZE = 500; + +export const CaptureTranscriptPayloadSchema = z.object({ + page_size: z + .number() + .int() + .positive() + .max(TRANSCRIPT_MAX_PAGE_SIZE) + .default(TRANSCRIPT_DEFAULT_PAGE_SIZE), + before_entry: z.number().int().nonnegative().optional(), +}); +export type CaptureTranscriptPayload = z.infer; + export const SCROLLBACK_MAX_LINES = 5000; -export const ScrollbackRequestSchema = z.object({ - mode: CaptureModeSchema, - last_n_lines: z.number().int().positive().max(SCROLLBACK_MAX_LINES).optional(), - start_line: z.number().int().optional(), - end_line: z.number().int().optional(), - strip_ansi: z.boolean().default(true), -}).superRefine((request, context) => { - if (request.mode === 'last_n' && request.last_n_lines === undefined) { - context.addIssue({ - code: 'custom', - path: ['last_n_lines'], - message: 'last_n_lines is required for last_n mode', - }); - } - if (request.mode !== 'range') return; - if (request.start_line === undefined) { - context.addIssue({ - code: 'custom', - path: ['start_line'], - message: 'start_line is required for range mode', - }); - } - if (request.end_line === undefined) { - context.addIssue({ - code: 'custom', - path: ['end_line'], - message: 'end_line is required for range mode', - }); - } - if (request.start_line === undefined || request.end_line === undefined) return; - if (request.end_line < request.start_line) { - context.addIssue({ - code: 'custom', - path: ['end_line'], - message: 'end_line must be greater than or equal to start_line', - }); - return; - } - if (request.end_line - request.start_line + 1 > SCROLLBACK_MAX_LINES) { - context.addIssue({ - code: 'custom', - path: ['end_line'], - message: `range cannot exceed ${SCROLLBACK_MAX_LINES} lines`, - }); - } -}); +export const ScrollbackRequestSchema = z + .object({ + mode: CaptureModeSchema, + last_n_lines: z.number().int().positive().max(SCROLLBACK_MAX_LINES).optional(), + start_line: z.number().int().optional(), + end_line: z.number().int().optional(), + strip_ansi: z.boolean().default(true), + }) + .superRefine((request, context) => { + if (request.mode === 'last_n' && request.last_n_lines === undefined) { + context.addIssue({ + code: 'custom', + path: ['last_n_lines'], + message: 'last_n_lines is required for last_n mode', + }); + } + if (request.mode !== 'range') return; + if (request.start_line === undefined) { + context.addIssue({ + code: 'custom', + path: ['start_line'], + message: 'start_line is required for range mode', + }); + } + if (request.end_line === undefined) { + context.addIssue({ + code: 'custom', + path: ['end_line'], + message: 'end_line is required for range mode', + }); + } + if (request.start_line === undefined || request.end_line === undefined) return; + if (request.end_line < request.start_line) { + context.addIssue({ + code: 'custom', + path: ['end_line'], + message: 'end_line must be greater than or equal to start_line', + }); + return; + } + if (request.end_line - request.start_line + 1 > SCROLLBACK_MAX_LINES) { + context.addIssue({ + code: 'custom', + path: ['end_line'], + message: `range cannot exceed ${SCROLLBACK_MAX_LINES} lines`, + }); + } + }); export type ScrollbackRequest = z.infer; export const ScrollbackResponseSchema = z.object({ cmd_id: z.string().uuid(), ok: z.boolean(), result: z.record(z.string(), z.unknown()).optional(), - error: z.object({ - code: z.string(), - message: z.string(), - }).optional(), + error: z + .object({ + code: z.string(), + message: z.string(), + }) + .optional(), }); export type ScrollbackResponse = z.infer; +export const TranscriptRequestSchema = CaptureTranscriptPayloadSchema; +export type TranscriptRequest = z.infer; + +export const TranscriptEntrySchema = z.record(z.string(), z.unknown()); +export type TranscriptEntry = z.infer; + +export const TranscriptResultSchema = z.object({ + entries: z.array(TranscriptEntrySchema), + first_entry: z.number().int().nonnegative(), + total_entries: z.number().int().nonnegative(), + source: z.enum(['hook', 'derived']), +}); +export type TranscriptResult = z.infer; + +const TranscriptErrorSchema = z.object({ + code: z.string(), + message: z.string(), +}); + +export const TranscriptResponseSchema = z.discriminatedUnion('ok', [ + z.object({ + cmd_id: z.string().uuid(), + ok: z.literal(true), + result: TranscriptResultSchema, + }), + z.object({ + cmd_id: z.string().uuid(), + ok: z.literal(false), + error: TranscriptErrorSchema, + }), +]); +export type TranscriptResponse = z.infer; + // Copy to session command payload export const CopyToSessionPayloadSchema = z.object({ target_session_id: z.string().uuid(), @@ -313,6 +368,7 @@ export const CommandPayloadSchema = z.discriminatedUnion('type', [ z.object({ type: z.literal('console.unsubscribe'), payload: ConsoleUnsubscribePayloadSchema }), z.object({ type: z.literal('copy_to_session'), payload: CopyToSessionPayloadSchema }), z.object({ type: z.literal('capture_pane'), payload: CapturePanePayloadSchema }), + z.object({ type: z.literal('capture_transcript'), payload: CaptureTranscriptPayloadSchema }), z.object({ type: z.literal('list_directory'), payload: ListDirectoryPayloadSchema }), z.object({ type: z.literal('new_window'), payload: NewWindowPayloadSchema }), z.object({ type: z.literal('kill_window'), payload: KillWindowPayloadSchema }), diff --git a/packages/ac-schema/src/enums.ts b/packages/ac-schema/src/enums.ts index 36c1f93..7d2202c 100644 --- a/packages/ac-schema/src/enums.ts +++ b/packages/ac-schema/src/enums.ts @@ -59,6 +59,7 @@ export const CommandTypeSchema = z.enum([ 'console.unsubscribe', 'copy_to_session', 'capture_pane', + 'capture_transcript', 'list_directory', 'new_window', 'kill_window', diff --git a/packages/ac-schema/tests/core-workflows.test.ts b/packages/ac-schema/tests/core-workflows.test.ts index b97e475..01fadf6 100644 --- a/packages/ac-schema/tests/core-workflows.test.ts +++ b/packages/ac-schema/tests/core-workflows.test.ts @@ -4,6 +4,7 @@ import { ApprovalDecideRequestSchema, AutomationAgentSchema, AutomationRunSchema, + CaptureTranscriptPayloadSchema, CommandPayloadSchema, CreateWorkItemSchema, MemorySearchQuerySchema, @@ -47,23 +48,27 @@ describe('approval schemas', () => { describe('host presence schemas', () => { it('accepts additive hosts subscriptions and presence change messages', () => { - expect(UISubscribeMessageSchema.safeParse({ - v: 1, - type: 'ui.subscribe', - ts: '2026-07-19T16:00:00.000Z', - payload: { topics: [{ type: 'hosts' }] }, - }).success).toBe(true); + expect( + UISubscribeMessageSchema.safeParse({ + v: 1, + type: 'ui.subscribe', + ts: '2026-07-19T16:00:00.000Z', + payload: { topics: [{ type: 'hosts' }] }, + }).success + ).toBe(true); const parsed = ServerToUIMessageSchema.parse({ v: 1, type: 'hosts.changed', ts: '2026-07-19T16:00:00.000Z', payload: { - hosts: [{ - host_id: uuid, - online: true, - last_heartbeat_at: '2026-07-19T16:00:00.000Z', - }], + hosts: [ + { + host_id: uuid, + online: true, + last_heartbeat_at: '2026-07-19T16:00:00.000Z', + }, + ], }, }); @@ -76,7 +81,9 @@ describe('memory schemas', () => { const parsed = MemorySearchQuerySchema.parse({ q: 'approval policy', limit: '25' }); expect(parsed.limit).toBe(25); - expect(MemorySearchQuerySchema.safeParse({ q: 'approval policy', limit: 101 }).success).toBe(false); + expect(MemorySearchQuerySchema.safeParse({ q: 'approval policy', limit: 101 }).success).toBe( + false + ); }); it('requires durable memory content and confidence in range', () => { @@ -102,21 +109,43 @@ describe('memory schemas', () => { }); describe('tmux schemas', () => { + it('defaults and bounds transcript capture pages', () => { + expect(CaptureTranscriptPayloadSchema.parse({})).toEqual({ page_size: 200 }); + expect(CaptureTranscriptPayloadSchema.parse({ page_size: 500, before_entry: 42 })).toEqual({ + page_size: 500, + before_entry: 42, + }); + expect(CaptureTranscriptPayloadSchema.safeParse({ page_size: 501 }).success).toBe(false); + expect(CaptureTranscriptPayloadSchema.safeParse({ before_entry: -1 }).success).toBe(false); + expect( + CommandPayloadSchema.safeParse({ + type: 'capture_transcript', + payload: { page_size: 250 }, + }).success + ).toBe(true); + }); + it('enforces tmux window and pane command optionality', () => { expect(CommandPayloadSchema.safeParse({ type: 'new_window', payload: {} }).success).toBe(true); - expect(CommandPayloadSchema.safeParse({ - type: 'split_pane', - payload: { direction: 'horizontal' }, - }).success).toBe(true); + expect( + CommandPayloadSchema.safeParse({ + type: 'split_pane', + payload: { direction: 'horizontal' }, + }).success + ).toBe(true); expect(CommandPayloadSchema.safeParse({ type: 'split_pane', payload: {} }).success).toBe(false); - expect(CommandPayloadSchema.safeParse({ - type: 'resize_pane', - payload: { pane_id: '%14', height: 30 }, - }).success).toBe(true); - expect(CommandPayloadSchema.safeParse({ - type: 'resize_pane', - payload: { pane_id: '%14' }, - }).success).toBe(false); + expect( + CommandPayloadSchema.safeParse({ + type: 'resize_pane', + payload: { pane_id: '%14', height: 30 }, + }).success + ).toBe(true); + expect( + CommandPayloadSchema.safeParse({ + type: 'resize_pane', + payload: { pane_id: '%14' }, + }).success + ).toBe(false); }); it('validates pane identity shared across agent, control plane, and dashboard', () => { @@ -138,14 +167,16 @@ describe('tmux schemas', () => { pane_index: 1, }); - expect(TmuxPaneIdentitySchema.safeParse({ - pane_id: '', - target: 'agents:0.1', - session_name: 'agents', - window_name: 'agent-command', - window_index: -1, - pane_index: 1, - }).success).toBe(false); + expect( + TmuxPaneIdentitySchema.safeParse({ + pane_id: '', + target: 'agents:0.1', + session_name: 'agents', + window_name: 'agent-command', + window_index: -1, + pane_index: 1, + }).success + ).toBe(false); }); }); diff --git a/packages/ac-schema/tests/protocol-fixtures.test.ts b/packages/ac-schema/tests/protocol-fixtures.test.ts index 593e229..e4f0ba8 100644 --- a/packages/ac-schema/tests/protocol-fixtures.test.ts +++ b/packages/ac-schema/tests/protocol-fixtures.test.ts @@ -25,6 +25,7 @@ describe('protocol fixtures', () => { 'sessions-upsert-tmux.json', 'terminal-output.json', 'commands-result.json', + 'commands-result-capture-transcript.json', ])('validates agent message fixture %s', (name) => { expect(AgentMessageSchema.safeParse(readFixture(name)).success).toBe(true); }); @@ -37,7 +38,9 @@ describe('protocol fixtures', () => { }); it('validates the UI command-result topic fixture', () => { - expect(ServerToUIMessageSchema.safeParse(readFixture('ui-commands-result.json')).success).toBe(true); + expect(ServerToUIMessageSchema.safeParse(readFixture('ui-commands-result.json')).success).toBe( + true + ); }); it.each([ @@ -47,6 +50,7 @@ describe('protocol fixtures', () => { 'terminal-navigate.json', 'terminal-navigate-scroll.json', 'commands-dispatch-send-input.json', + 'commands-dispatch-capture-transcript.json', ])('validates server-to-agent message fixture %s', (name) => { expect(ServerToAgentMessageSchema.safeParse(readFixture(name)).success).toBe(true); }); diff --git a/services/control-plane/tests/transcriptSchema.test.ts b/services/control-plane/tests/transcriptSchema.test.ts new file mode 100644 index 0000000..a743b60 --- /dev/null +++ b/services/control-plane/tests/transcriptSchema.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from 'vitest'; +import { TranscriptRequestSchema, TranscriptResponseSchema } from '@agent-command/schema'; + +describe('transcript route schemas', () => { + it('defaults bounded requests and validates raw transcript page results', () => { + expect(TranscriptRequestSchema.parse({})).toEqual({ page_size: 200 }); + expect( + TranscriptResponseSchema.parse({ + cmd_id: '11111111-1111-4111-8111-111111111111', + ok: true, + result: { + entries: [{ type: 'user', message: { content: 'Ship it' } }], + first_entry: 7, + total_entries: 8, + source: 'hook', + }, + }) + ).toMatchObject({ + ok: true, + result: { first_entry: 7, total_entries: 8, source: 'hook' }, + }); + expect( + TranscriptResponseSchema.safeParse({ + cmd_id: '11111111-1111-4111-8111-111111111111', + ok: true, + result: { + entries: [], + first_entry: -1, + total_entries: 0, + source: 'outside-root', + }, + }).success + ).toBe(false); + expect( + TranscriptResponseSchema.safeParse({ + cmd_id: '11111111-1111-4111-8111-111111111111', + ok: true, + }).success + ).toBe(false); + }); +}); diff --git a/tests/fixtures/protocol/commands-dispatch-capture-transcript.json b/tests/fixtures/protocol/commands-dispatch-capture-transcript.json new file mode 100644 index 0000000..4e7e4af --- /dev/null +++ b/tests/fixtures/protocol/commands-dispatch-capture-transcript.json @@ -0,0 +1,10 @@ +{ + "v": 1, + "type": "commands.dispatch", + "ts": "2026-07-21T20:01:12Z", + "payload": { + "cmd_id": "cmd-transcript", + "session_id": "22222222-2222-4222-8222-222222222222", + "command": { "type": "capture_transcript", "payload": { "page_size": 200, "before_entry": 42 } } + } +} diff --git a/tests/fixtures/protocol/commands-result-capture-transcript.json b/tests/fixtures/protocol/commands-result-capture-transcript.json new file mode 100644 index 0000000..ae66cc8 --- /dev/null +++ b/tests/fixtures/protocol/commands-result-capture-transcript.json @@ -0,0 +1,23 @@ +{ + "v": 1, + "type": "commands.result", + "ts": "2026-07-21T20:01:13Z", + "seq": 5, + "payload": { + "cmd_id": "11111111-1111-4111-8111-111111111111", + "session_id": "22222222-2222-4222-8222-222222222222", + "ok": true, + "result": { + "entries": [ + { "type": "user", "message": { "role": "user", "content": "Ship it" } }, + { + "type": "assistant", + "message": { "role": "assistant", "content": [{ "type": "text", "text": "On it." }] } + } + ], + "first_entry": 40, + "total_entries": 42, + "source": "hook" + } + } +} From f0647d07f3a474a182dd727022df628a005a6a24 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 19:50:52 -0400 Subject: [PATCH 04/10] feat(chat): capture local Claude transcripts --- agents/agentd/cmd/agentd/main.go | 49 ++- .../agentd/cmd/agentd/main_transcript_test.go | 322 ++++++++++++++++++ agents/agentd/cmd/agentd/transcript.go | 320 +++++++++++++++++ agents/agentd/internal/commands/executor.go | 19 +- 4 files changed, 702 insertions(+), 8 deletions(-) create mode 100644 agents/agentd/cmd/agentd/main_transcript_test.go create mode 100644 agents/agentd/cmd/agentd/transcript.go diff --git a/agents/agentd/cmd/agentd/main.go b/agents/agentd/cmd/agentd/main.go index f2f6197..9a93913 100644 --- a/agents/agentd/cmd/agentd/main.go +++ b/agents/agentd/cmd/agentd/main.go @@ -55,13 +55,15 @@ type Agent struct { topologyMu sync.Mutex // Session state - sessions map[string]*SessionState - sessionsMu sync.RWMutex - snapshotHash map[string]string - toolEventsMu sync.Mutex - pendingToolEvents map[string][]toolEventPending - bufferedHooksMu sync.Mutex - bufferedHooks []bufferedHook + sessions map[string]*SessionState + sessionsMu sync.RWMutex + transcriptPaths map[string]string + claudeProjectsRoot string + snapshotHash map[string]string + toolEventsMu sync.Mutex + pendingToolEvents map[string][]toolEventPending + bufferedHooksMu sync.Mutex + bufferedHooks []bufferedHook // Approval lifecycle - TTL cache to prevent race conditions recentDecisions map[string]time.Time @@ -388,6 +390,7 @@ func runDaemon() { agent := &Agent{ cfg: cfg, sessions: make(map[string]*SessionState), + transcriptPaths: make(map[string]string), snapshotHash: make(map[string]string), providerUsageHash: make(map[string]string), pendingToolEvents: make(map[string][]toolEventPending), @@ -2053,6 +2056,12 @@ func (a *Agent) executeCommand(cmd commands.Dispatch) (map[string]any, error) { break } resultPayload, err = a.executeCapturePaneCommand(session, cmd.Command.Payload) + case "capture_transcript": + if !exists { + err = fmt.Errorf("session not found") + break + } + resultPayload, err = a.executeCaptureTranscriptCommand(session, cmd.Command.Payload) case "copy_to_session": if !exists { err = fmt.Errorf("session not found") @@ -2923,6 +2932,7 @@ func (a *Agent) executeSpawnSessionWorktree(sessionID string, p protocol.SpawnSe if registered { a.sessionsMu.Lock() delete(a.sessions, sessionID) + delete(a.transcriptPaths, sessionID) a.refreshHierarchyMetadataLocked() a.sessionsMu.Unlock() } @@ -3062,6 +3072,7 @@ func (a *Agent) executeSpawnSessionInteractive(sessionID string, p protocol.Spaw if registered { a.sessionsMu.Lock() delete(a.sessions, sessionID) + delete(a.transcriptPaths, sessionID) a.refreshHierarchyMetadataLocked() a.sessionsMu.Unlock() } @@ -3275,6 +3286,7 @@ func (a *Agent) executeFork(parentSession *SessionState, payload json.RawMessage if registered { a.sessionsMu.Lock() delete(a.sessions, newSessionID) + delete(a.transcriptPaths, newSessionID) a.refreshHierarchyMetadataLocked() a.sessionsMu.Unlock() } @@ -3696,6 +3708,7 @@ func (a *Agent) handleClaudeHook(payload providers.ClaudeHookPayload) (*provider a.bufferHook("claude_code", payload) return nil, nil } + a.retainTranscriptPath(sessionID, extractHookString(hookData, "transcript_path", "transcriptPath")) a.markSessionReady(sessionID) // Update session status based on hook @@ -3870,6 +3883,27 @@ func (a *Agent) resolveHookSessionID(payload providers.ClaudeHookPayload) string return "" } +func (a *Agent) retainTranscriptPath(sessionID, transcriptPath string) { + if sessionID == "" || transcriptPath == "" { + return + } + a.sessionsMu.Lock() + defer a.sessionsMu.Unlock() + if a.sessions[sessionID] == nil { + return + } + if a.transcriptPaths == nil { + a.transcriptPaths = make(map[string]string) + } + a.transcriptPaths[sessionID] = transcriptPath +} + +func (a *Agent) transcriptPathForSession(sessionID string) string { + a.sessionsMu.RLock() + defer a.sessionsMu.RUnlock() + return a.transcriptPaths[sessionID] +} + func (a *Agent) markSessionReady(sessionID string) { a.sessionsMu.Lock() if session := a.sessions[sessionID]; session != nil { @@ -5164,6 +5198,7 @@ func (a *Agent) syncPanes(panes []tmux.Pane, procSnap *proc.Snapshot) { } for _, id := range staleIDs { delete(a.sessions, id) + delete(a.transcriptPaths, id) delete(a.snapshotHash, id) delete(a.providerUsageHash, id) } diff --git a/agents/agentd/cmd/agentd/main_transcript_test.go b/agents/agentd/cmd/agentd/main_transcript_test.go new file mode 100644 index 0000000..5706743 --- /dev/null +++ b/agents/agentd/cmd/agentd/main_transcript_test.go @@ -0,0 +1,322 @@ +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/agent-command/agentd/internal/commands" + "github.com/agent-command/agentd/internal/config" + "github.com/agent-command/agentd/internal/protocol" + "github.com/agent-command/agentd/internal/providers" + "github.com/agent-command/agentd/internal/usage" +) + +func TestClaudeHookRetainsLatestTranscriptPathUntilSessionCleanup(t *testing.T) { + agent := &Agent{ + cfg: &config.Config{}, + sessions: map[string]*SessionState{"session-1": {ID: "session-1", Kind: "tmux_pane", PaneID: "%1"}}, + transcriptPaths: make(map[string]string), + snapshotHash: make(map[string]string), + providerUsageHash: make(map[string]string), + usageTracker: usage.NewUsageTracker(), + lastPruneAt: time.Now(), + sendMessage: func(string, any) error { return nil }, + } + hook := providers.ClaudeHookPayload{Hook: json.RawMessage(`{ + "hook_event_name":"Custom", + "transcript_path":"/safe/first.jsonl" + }`)} + hook.Meta.ACSessionID = "session-1" + if _, err := agent.handleClaudeHook(hook); err != nil { + t.Fatal(err) + } + hook.Hook = json.RawMessage(`{ + "hook_event_name":"Custom", + "transcript_path":"/safe/latest.jsonl" + }`) + if _, err := agent.handleClaudeHook(hook); err != nil { + t.Fatal(err) + } + + if got := agent.transcriptPathForSession("session-1"); got != "/safe/latest.jsonl" { + t.Fatalf("retained transcript path=%q", got) + } + + agent.syncPanes(nil, nil) + if got := agent.transcriptPathForSession("session-1"); got != "" { + t.Fatalf("transcript path survived session cleanup: %q", got) + } +} + +func TestCaptureTranscriptDerivesNewestClaudeProjectFile(t *testing.T) { + projectsRoot := t.TempDir() + projectDir := filepath.Join(projectsRoot, "-home-dev-Chat--FW6-") + if err := os.MkdirAll(projectDir, 0o700); err != nil { + t.Fatal(err) + } + oldPath := filepath.Join(projectDir, "old.jsonl") + newPath := filepath.Join(projectDir, "new.jsonl") + if err := os.WriteFile(oldPath, []byte(`{"type":"user","message":{"content":"old"}}`+"\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(newPath, []byte(`{"type":"user","message":{"content":"new"}}`+"\n"), 0o600); err != nil { + t.Fatal(err) + } + now := time.Now() + if err := os.Chtimes(oldPath, now.Add(-time.Minute), now.Add(-time.Minute)); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(newPath, now, now); err != nil { + t.Fatal(err) + } + + agent := &Agent{ + sessions: map[string]*SessionState{"session-1": {ID: "session-1", CWD: "/home/dev/Chat (FW6)"}}, + transcriptPaths: make(map[string]string), + claudeProjectsRoot: projectsRoot, + } + payload, err := json.Marshal(protocol.CaptureTranscriptPayload{PageSize: 1}) + if err != nil { + t.Fatal(err) + } + result, err := agent.executeCommand(commands.Dispatch{ + SessionID: "session-1", + Command: protocol.Command{ + Type: "capture_transcript", + Payload: payload, + }, + }) + if err != nil { + t.Fatal(err) + } + if result["source"] != "derived" || result["first_entry"] != 0 || result["total_entries"] != 1 { + t.Fatalf("derived transcript metadata=%+v", result) + } + entries, ok := result["entries"].([]map[string]any) + if !ok || len(entries) != 1 { + t.Fatalf("derived transcript entries=%T %+v", result["entries"], result["entries"]) + } + message, _ := entries[0]["message"].(map[string]any) + if message["content"] != "new" { + t.Fatalf("derived newest entry=%+v", entries[0]) + } +} + +func TestCaptureTranscriptPagesBackwardByEntryIndex(t *testing.T) { + projectsRoot := t.TempDir() + projectDir := filepath.Join(projectsRoot, "-repo") + if err := os.MkdirAll(projectDir, 0o700); err != nil { + t.Fatal(err) + } + transcriptPath := filepath.Join(projectDir, "session.jsonl") + file, err := os.Create(transcriptPath) + if err != nil { + t.Fatal(err) + } + for index := 0; index < 7; index++ { + if _, err := file.WriteString(`{"index":` + string(rune('0'+index)) + `}` + "\n"); err != nil { + t.Fatal(err) + } + } + if err := file.Close(); err != nil { + t.Fatal(err) + } + agent := &Agent{ + sessions: map[string]*SessionState{"session-1": {ID: "session-1", CWD: "/repo"}}, + transcriptPaths: map[string]string{"session-1": transcriptPath}, + claudeProjectsRoot: projectsRoot, + } + + assertPage := func(before *int, wantFirst int, wantIndexes []float64) { + t.Helper() + payload, err := json.Marshal(protocol.CaptureTranscriptPayload{PageSize: 3, BeforeEntry: before}) + if err != nil { + t.Fatal(err) + } + result, err := agent.executeCommand(commands.Dispatch{ + SessionID: "session-1", + Command: protocol.Command{Type: "capture_transcript", Payload: payload}, + }) + if err != nil { + t.Fatal(err) + } + if result["source"] != "hook" || result["first_entry"] != wantFirst || result["total_entries"] != 7 { + t.Fatalf("page metadata=%+v", result) + } + entries := result["entries"].([]map[string]any) + gotIndexes := make([]float64, 0, len(entries)) + for _, entry := range entries { + gotIndexes = append(gotIndexes, entry["index"].(float64)) + } + if len(gotIndexes) != len(wantIndexes) { + t.Fatalf("page indexes=%v want=%v", gotIndexes, wantIndexes) + } + for index := range gotIndexes { + if gotIndexes[index] != wantIndexes[index] { + t.Fatalf("page indexes=%v want=%v", gotIndexes, wantIndexes) + } + } + } + + assertPage(nil, 4, []float64{4, 5, 6}) + before := 4 + assertPage(&before, 1, []float64{1, 2, 3}) + before = 1 + assertPage(&before, 0, []float64{0}) +} + +func TestCaptureTranscriptRejectsHookPathsOutsideClaudeProjects(t *testing.T) { + projectsRoot := t.TempDir() + outsideRoot := t.TempDir() + outsidePath := filepath.Join(outsideRoot, "secret.jsonl") + if err := os.WriteFile(outsidePath, []byte(`{"secret":true}`+"\n"), 0o600); err != nil { + t.Fatal(err) + } + projectDir := filepath.Join(projectsRoot, "-repo") + if err := os.MkdirAll(projectDir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(projectDir, "safe.jsonl"), []byte(`{"safe":true}`+"\n"), 0o600); err != nil { + t.Fatal(err) + } + agent := &Agent{ + sessions: map[string]*SessionState{"session-1": {ID: "session-1", CWD: "/repo"}}, + transcriptPaths: map[string]string{"session-1": outsidePath}, + claudeProjectsRoot: projectsRoot, + } + payload, _ := json.Marshal(protocol.CaptureTranscriptPayload{PageSize: 1}) + result, err := agent.executeCommand(commands.Dispatch{ + SessionID: "session-1", + Command: protocol.Command{Type: "capture_transcript", Payload: payload}, + }) + if err != nil { + t.Fatal(err) + } + entries := result["entries"].([]map[string]any) + if result["source"] != "derived" || len(entries) != 1 || entries[0]["safe"] != true { + t.Fatalf("outside hook path was not rejected: %+v", result) + } +} + +func TestCaptureTranscriptCapsContentAndDropsBase64Blobs(t *testing.T) { + projectsRoot := t.TempDir() + projectDir := filepath.Join(projectsRoot, "-repo") + if err := os.MkdirAll(projectDir, 0o700); err != nil { + t.Fatal(err) + } + entry := map[string]any{ + "type": "assistant", + "message": map[string]any{ + "content": []any{ + map[string]any{"type": "text", "text": strings.Repeat("é", 9_000)}, + map[string]any{ + "type": "image", + "source": map[string]any{ + "type": "base64", + "media_type": "image/png", + "data": strings.Repeat("A", 256), + }, + }, + }, + }, + } + rawEntry, err := json.Marshal(entry) + if err != nil { + t.Fatal(err) + } + transcriptPath := filepath.Join(projectDir, "session.jsonl") + if err := os.WriteFile(transcriptPath, append(rawEntry, '\n'), 0o600); err != nil { + t.Fatal(err) + } + agent := &Agent{ + sessions: map[string]*SessionState{"session-1": {ID: "session-1", CWD: "/repo"}}, + transcriptPaths: map[string]string{"session-1": transcriptPath}, + claudeProjectsRoot: projectsRoot, + } + payload, _ := json.Marshal(protocol.CaptureTranscriptPayload{PageSize: 1}) + result, err := agent.executeCommand(commands.Dispatch{ + SessionID: "session-1", + Command: protocol.Command{Type: "capture_transcript", Payload: payload}, + }) + if err != nil { + t.Fatal(err) + } + entries := result["entries"].([]map[string]any) + message := entries[0]["message"].(map[string]any) + content := message["content"].([]any) + textBlock := content[0].(map[string]any) + text := textBlock["text"].(string) + if len([]byte(text)) > 16*1024 || !strings.HasPrefix(strings.Repeat("é", 9_000), text) { + t.Fatalf("capped text has %d bytes and valid-prefix=%v", len([]byte(text)), strings.HasPrefix(strings.Repeat("é", 9_000), text)) + } + imageBlock := content[1].(map[string]any) + source := imageBlock["source"].(map[string]any) + if _, exists := source["data"]; exists { + t.Fatalf("base64 data survived sanitization: %+v", source) + } +} + +func TestCaptureTranscriptRejectsOutOfBoundsRequests(t *testing.T) { + projectsRoot := t.TempDir() + projectDir := filepath.Join(projectsRoot, "-repo") + if err := os.MkdirAll(projectDir, 0o700); err != nil { + t.Fatal(err) + } + transcriptPath := filepath.Join(projectDir, "session.jsonl") + if err := os.WriteFile(transcriptPath, []byte(`{"entry":0}`+"\n"), 0o600); err != nil { + t.Fatal(err) + } + agent := &Agent{ + sessions: map[string]*SessionState{"session-1": {ID: "session-1", CWD: "/repo"}}, + transcriptPaths: map[string]string{"session-1": transcriptPath}, + claudeProjectsRoot: projectsRoot, + } + negative := -1 + beyondEnd := 2 + for _, request := range []protocol.CaptureTranscriptPayload{ + {PageSize: 501}, + {PageSize: 1, BeforeEntry: &negative}, + {PageSize: 1, BeforeEntry: &beyondEnd}, + } { + payload, _ := json.Marshal(request) + if _, err := agent.executeCommand(commands.Dispatch{ + SessionID: "session-1", + Command: protocol.Command{Type: "capture_transcript", Payload: payload}, + }); err == nil { + t.Fatalf("out-of-bounds request succeeded: %+v", request) + } + } +} + +func TestCaptureTranscriptReturnsNoTranscriptErrorCode(t *testing.T) { + agent := &Agent{ + sessions: map[string]*SessionState{"session-1": {ID: "session-1", CWD: "/missing"}}, + transcriptPaths: make(map[string]string), + claudeProjectsRoot: t.TempDir(), + } + results := make(chan commands.Result, 1) + executor := commands.NewExecutor(1, agent.executeCommand, func(result commands.Result) { + results <- result + }) + defer executor.Close() + payload, _ := json.Marshal(protocol.CaptureTranscriptPayload{PageSize: 1}) + if err := executor.Submit(commands.Dispatch{ + CmdID: "capture-1", + SessionID: "session-1", + Command: protocol.Command{Type: "capture_transcript", Payload: payload}, + }); err != nil { + t.Fatal(err) + } + select { + case result := <-results: + if result.OK || result.Error == nil || result.Error.Code != "no_transcript" { + t.Fatalf("missing transcript result=%+v", result) + } + case <-time.After(time.Second): + t.Fatal("timed out waiting for transcript result") + } +} diff --git a/agents/agentd/cmd/agentd/transcript.go b/agents/agentd/cmd/agentd/transcript.go new file mode 100644 index 0000000..7ddcaba --- /dev/null +++ b/agents/agentd/cmd/agentd/transcript.go @@ -0,0 +1,320 @@ +package main + +import ( + "bufio" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "unicode/utf8" + + "github.com/agent-command/agentd/internal/commands" + "github.com/agent-command/agentd/internal/protocol" +) + +const ( + defaultTranscriptPageSize = 200 + maxTranscriptPageSize = 500 + maxTranscriptContentBytes = 16 * 1024 + maxTranscriptScannerToken = 64 * 1024 * 1024 +) + +var errInvalidTranscriptRequest = errors.New("invalid transcript request") + +func (a *Agent) executeCaptureTranscriptCommand(session *SessionState, payload json.RawMessage) (map[string]any, error) { + var request protocol.CaptureTranscriptPayload + if err := json.Unmarshal(payload, &request); err != nil { + return nil, err + } + if request.PageSize == 0 { + request.PageSize = defaultTranscriptPageSize + } + if request.PageSize < 1 || request.PageSize > maxTranscriptPageSize { + return nil, fmt.Errorf("page_size must be between 1 and %d", maxTranscriptPageSize) + } + if request.BeforeEntry != nil && *request.BeforeEntry < 0 { + return nil, fmt.Errorf("before_entry must be nonnegative") + } + + transcriptPath, source, err := a.resolveTranscriptPath(session) + if err != nil { + return nil, commands.NewResultError("no_transcript", "Claude transcript is unavailable") + } + entries, firstEntry, totalEntries, err := readTranscriptPage(transcriptPath, request) + if err != nil { + if errors.Is(err, errInvalidTranscriptRequest) { + return nil, err + } + return nil, commands.NewResultError("no_transcript", "Claude transcript is unavailable") + } + return map[string]any{ + "entries": entries, + "first_entry": firstEntry, + "total_entries": totalEntries, + "source": source, + }, nil +} + +func (a *Agent) resolveTranscriptPath(session *SessionState) (string, string, error) { + projectsRoot, err := a.transcriptProjectsRoot() + if err != nil { + return "", "", err + } + if retained := a.transcriptPathForSession(session.ID); retained != "" { + if resolved, resolveErr := resolveTranscriptFile(projectsRoot, retained); resolveErr == nil { + return resolved, "hook", nil + } + } + if strings.TrimSpace(session.CWD) == "" { + return "", "", fmt.Errorf("no Claude transcript for session") + } + + projectDir := filepath.Join(projectsRoot, claudeProjectSlug(session.CWD)) + items, err := os.ReadDir(projectDir) + if err != nil { + return "", "", fmt.Errorf("no Claude transcript for session: %w", err) + } + var newestPath string + var newestModTime int64 + for _, item := range items { + if item.IsDir() || !strings.EqualFold(filepath.Ext(item.Name()), ".jsonl") { + continue + } + candidate := filepath.Join(projectDir, item.Name()) + resolved, err := resolveTranscriptFile(projectsRoot, candidate) + if err != nil { + continue + } + info, err := os.Stat(resolved) + if err != nil { + continue + } + modTime := info.ModTime().UnixNano() + if newestPath == "" || modTime > newestModTime { + newestPath = resolved + newestModTime = modTime + } + } + if newestPath == "" { + return "", "", fmt.Errorf("no Claude transcript for session") + } + return newestPath, "derived", nil +} + +func (a *Agent) transcriptProjectsRoot() (string, error) { + if a.claudeProjectsRoot != "" { + return a.claudeProjectsRoot, nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("resolve home directory: %w", err) + } + return filepath.Join(home, ".claude", "projects"), nil +} + +func claudeProjectSlug(cwd string) string { + return strings.Map(func(r rune) rune { + if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || + (r >= '0' && r <= '9') || r == '-' { + return r + } + return '-' + }, cwd) +} + +func resolveTranscriptFile(projectsRoot, candidate string) (string, error) { + root, err := filepath.EvalSymlinks(projectsRoot) + if err != nil { + return "", err + } + resolved, err := filepath.EvalSymlinks(candidate) + if err != nil { + return "", err + } + relative, err := filepath.Rel(root, resolved) + if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) { + return "", fmt.Errorf("transcript path is outside Claude projects") + } + info, err := os.Stat(resolved) + if err != nil { + return "", err + } + if !info.Mode().IsRegular() { + return "", fmt.Errorf("transcript path is not a regular file") + } + return resolved, nil +} + +func readTranscriptPage(path string, request protocol.CaptureTranscriptPayload) ([]map[string]any, int, int, error) { + totalEntries, err := countTranscriptEntries(path) + if err != nil { + return nil, 0, 0, err + } + endEntry := totalEntries + if request.BeforeEntry != nil { + endEntry = *request.BeforeEntry + if endEntry > totalEntries { + return nil, 0, totalEntries, fmt.Errorf("%w: before_entry %d exceeds total entries %d", errInvalidTranscriptRequest, endEntry, totalEntries) + } + } + firstEntry := max(0, endEntry-request.PageSize) + + file, err := os.Open(path) + if err != nil { + return nil, 0, totalEntries, err + } + defer file.Close() + scanner := newTranscriptScanner(file) + entries := make([]map[string]any, 0, endEntry-firstEntry) + entryIndex := 0 + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if line == "" { + continue + } + if entryIndex >= firstEntry && entryIndex < endEntry { + var entry map[string]any + if err := json.Unmarshal([]byte(line), &entry); err != nil { + return nil, 0, totalEntries, fmt.Errorf("parse transcript entry %d: %w", entryIndex, err) + } + entries = append(entries, sanitizeTranscriptEntry(entry)) + } + entryIndex++ + if entryIndex >= endEntry { + break + } + } + if err := scanner.Err(); err != nil { + return nil, 0, totalEntries, err + } + return entries, firstEntry, totalEntries, nil +} + +func countTranscriptEntries(path string) (int, error) { + file, err := os.Open(path) + if err != nil { + return 0, err + } + defer file.Close() + scanner := newTranscriptScanner(file) + count := 0 + for scanner.Scan() { + if strings.TrimSpace(scanner.Text()) != "" { + count++ + } + } + return count, scanner.Err() +} + +func newTranscriptScanner(file *os.File) *bufio.Scanner { + scanner := bufio.NewScanner(file) + scanner.Buffer(make([]byte, 64*1024), maxTranscriptScannerToken) + return scanner +} + +func sanitizeTranscriptEntry(entry map[string]any) map[string]any { + return sanitizeTranscriptMap(entry, false, nil) +} + +func sanitizeTranscriptMap(value map[string]any, inContent bool, contentBudget *int) map[string]any { + keys := make([]string, 0, len(value)) + for key := range value { + keys = append(keys, key) + } + sort.Strings(keys) + cleaned := make(map[string]any, len(value)) + for _, key := range keys { + item := value[key] + if shouldDropTranscriptBlob(value, key, item) { + continue + } + if strings.EqualFold(key, "content") { + budget := maxTranscriptContentBytes + cleaned[key] = sanitizeTranscriptValue(item, true, &budget, true) + continue + } + countString := inContent && !isTranscriptMetadataKey(key) + cleaned[key] = sanitizeTranscriptValue(item, inContent, contentBudget, countString) + } + return cleaned +} + +func sanitizeTranscriptValue(value any, inContent bool, contentBudget *int, countString bool) any { + switch typed := value.(type) { + case map[string]any: + return sanitizeTranscriptMap(typed, inContent, contentBudget) + case []any: + cleaned := make([]any, 0, len(typed)) + for _, item := range typed { + cleaned = append(cleaned, sanitizeTranscriptValue(item, inContent, contentBudget, true)) + } + return cleaned + case string: + if !inContent || contentBudget == nil || !countString { + return typed + } + cleaned := truncateUTF8Bytes(typed, *contentBudget) + *contentBudget -= len([]byte(cleaned)) + return cleaned + default: + return typed + } +} + +func isTranscriptMetadataKey(key string) bool { + switch strings.ToLower(key) { + case "id", "type", "role", "name", "media_type", "mime_type": + return true + default: + return false + } +} + +func shouldDropTranscriptBlob(parent map[string]any, key string, value any) bool { + text, ok := value.(string) + if !ok { + return false + } + normalizedKey := strings.ToLower(key) + if normalizedKey == "base64" || normalizedKey == "blob" { + return true + } + if normalizedKey != "data" { + return false + } + parentType, _ := parent["type"].(string) + parentType = strings.ToLower(parentType) + return parentType == "base64" || parentType == "binary" || looksLikeBase64(text) +} + +func looksLikeBase64(value string) bool { + if len(value) < 128 { + return false + } + for _, char := range value { + if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || + (char >= '0' && char <= '9') || char == '+' || char == '/' || char == '=' || + char == '\r' || char == '\n' { + continue + } + return false + } + return true +} + +func truncateUTF8Bytes(value string, limit int) string { + if limit <= 0 { + return "" + } + if len([]byte(value)) <= limit { + return value + } + truncated := []byte(value)[:limit] + for len(truncated) > 0 && !utf8.Valid(truncated) { + truncated = truncated[:len(truncated)-1] + } + return string(truncated) +} diff --git a/agents/agentd/internal/commands/executor.go b/agents/agentd/internal/commands/executor.go index 69aab86..2a4e14d 100644 --- a/agents/agentd/internal/commands/executor.go +++ b/agents/agentd/internal/commands/executor.go @@ -23,6 +23,18 @@ type Result = protocol.CommandResultPayload type Handler func(Dispatch) (map[string]any, error) type ResultHandler func(Result) +type commandResultError struct { + code string + message string +} + +func (e *commandResultError) Error() string { return e.message } +func (e *commandResultError) CommandResultCode() string { return e.code } + +func NewResultError(code, message string) error { + return &commandResultError{code: code, message: message} +} + // Executor runs commands on a fixed worker pool while allowing at most one // in-flight command for each session key. type Executor struct { @@ -155,7 +167,12 @@ func (e *Executor) execute(dispatch Dispatch) (result Result) { payload, err := e.handler(dispatch) if err != nil { - result.Error = &ResultError{Code: "COMMAND_FAILED", Message: err.Error()} + code := "COMMAND_FAILED" + var coded interface{ CommandResultCode() string } + if errors.As(err, &coded) && coded.CommandResultCode() != "" { + code = coded.CommandResultCode() + } + result.Error = &ResultError{Code: code, Message: err.Error()} return result } result.OK = true From 22d72a13612d7af81e4ad95f891c8bc5406b1504 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 19:52:21 -0400 Subject: [PATCH 05/10] feat(chat): expose session transcript route --- services/control-plane/src/routes/sessions.ts | 70 +++++++- .../tests/transcriptRoute.test.ts | 169 ++++++++++++++++++ 2 files changed, 238 insertions(+), 1 deletion(-) create mode 100644 services/control-plane/tests/transcriptRoute.test.ts diff --git a/services/control-plane/src/routes/sessions.ts b/services/control-plane/src/routes/sessions.ts index ede4005..b296fda 100644 --- a/services/control-plane/src/routes/sessions.ts +++ b/services/control-plane/src/routes/sessions.ts @@ -1,7 +1,7 @@ import type { FastifyInstance } from 'fastify'; import { z } from 'zod'; import { randomUUID } from 'node:crypto'; -import { CommandRequestSchema, CommandPayloadSchema, UpdateSessionRequestSchema, BulkOperationRequestSchema, CopyToSessionPayloadSchema, DashboardSpawnRequestSchema, SCROLLBACK_MAX_LINES, ScrollbackRequestSchema, ScrollbackResponseSchema } from '@agent-command/schema'; +import { CommandRequestSchema, CommandPayloadSchema, UpdateSessionRequestSchema, BulkOperationRequestSchema, CopyToSessionPayloadSchema, DashboardSpawnRequestSchema, SCROLLBACK_MAX_LINES, ScrollbackRequestSchema, ScrollbackResponseSchema, TranscriptRequestSchema, TranscriptResponseSchema } from '@agent-command/schema'; import * as db from '../db/index.js'; import { sessionGraph } from '../db/sessionGraph.js'; import { agentTasks } from '../db/agentTasks.js'; @@ -464,6 +464,74 @@ export function registerSessionRoutes(app: FastifyInstance): void { } ); + // POST /v1/sessions/:id/transcript - Capture bounded Claude chat history + app.post<{ Params: { id: string }; Body: unknown }>( + '/v1/sessions/:id/transcript', + async (request, reply) => { + if (!request.user || !hasRole(request.user, 'operator')) { + return reply.status(403).send({ error: 'Forbidden' }); + } + const { id: sessionId } = request.params; + if (!z.string().uuid().safeParse(sessionId).success) { + return reply.status(400).send({ error: 'Invalid session ID' }); + } + + const body = TranscriptRequestSchema.safeParse(request.body); + if (!body.success) { + return reply.status(400).send({ error: 'Invalid transcript request', details: body.error }); + } + + const session = await db.getSessionById(sessionId); + if (!session) { + return reply.status(404).send({ error: 'Session not found' }); + } + const host = await db.getHostById(session.host_id); + if (!hostSupportsTmuxCommands(host)) { + return reply.status(403).send({ + error: 'Host does not support tmux terminal commands', + }); + } + + const cmdId = randomUUID(); + try { + const result = await commandRouter.dispatchAndWait( + session.host_id, + sessionId, + cmdId, + { + type: 'capture_transcript', + payload: { + page_size: body.data.page_size, + ...(body.data.before_entry !== undefined + ? { before_entry: body.data.before_entry } + : {}), + }, + } + ); + const response = TranscriptResponseSchema.parse(result.ok + ? { cmd_id: cmdId, ok: true, result: result.result } + : { + cmd_id: cmdId, + ok: false, + error: result.error ?? { + code: 'transcript_failed', + message: 'Transcript capture failed', + }, + }); + await db.createAuditLog( + 'session.transcript', + 'session', + sessionId, + { cmd_id: cmdId, request: body.data }, + request.user.id + ); + return response; + } catch (error) { + return reply.status(503).send({ error: (error as Error).message }); + } + } + ); + // PATCH /v1/sessions/:id - Update session (title, etc.) app.patch<{ Params: { id: string }; Body: unknown }>( '/v1/sessions/:id', diff --git a/services/control-plane/tests/transcriptRoute.test.ts b/services/control-plane/tests/transcriptRoute.test.ts new file mode 100644 index 0000000..115e3ab --- /dev/null +++ b/services/control-plane/tests/transcriptRoute.test.ts @@ -0,0 +1,169 @@ +import Fastify from 'fastify'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { AuthUser } from '../src/auth/types.js'; + +const hostId = '11111111-1111-4111-8111-111111111111'; +const sessionId = '22222222-2222-4222-8222-222222222222'; +const userId = '33333333-3333-4333-8333-333333333333'; +const dispatchAndWait = vi.fn(); +const createAuditLog = vi.fn(async () => undefined); + +function user(role: AuthUser['role'] = 'operator'): AuthUser { + return { + id: userId, + sub: `${role}@example.test`, + role, + auth_type: 'jwt', + }; +} + +async function buildServer(options: { role?: AuthUser['role']; hostCapable?: boolean } = {}) { + vi.resetModules(); + vi.clearAllMocks(); + vi.stubEnv('DATABASE_URL', 'postgres://agent-command:test@localhost:5432/agent_command_test'); + vi.doMock('../src/db/index.js', () => ({ + pool: { query: vi.fn(async () => ({ rows: [] })) }, + getSessionById: vi.fn(async () => ({ id: sessionId, host_id: hostId })), + getHostById: vi.fn(async () => ({ + id: hostId, + capabilities: { + tmux: options.hostCapable ?? true, + terminal: options.hostCapable ?? true, + }, + })), + createAuditLog, + })); + vi.doMock('../src/services/commandRouter.js', () => ({ + commandRouter: { dispatchAndWait }, + })); + + const { registerSessionRoutes } = await import('../src/routes/sessions.js'); + const app = Fastify({ logger: false }); + app.addHook('onRequest', async (request) => { + request.user = user(options.role); + }); + registerSessionRoutes(app); + return app; +} + +describe('session transcript route', () => { + beforeEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + dispatchAndWait.mockResolvedValue({ + ok: true, + result: { + entries: [{ type: 'user', message: { content: 'Ship it' } }], + first_entry: 7, + total_entries: 8, + source: 'hook', + }, + }); + }); + + it('dispatches the bounded capture command and audits the transcript read', async () => { + const app = await buildServer(); + + const response = await app.inject({ + method: 'POST', + url: `/v1/sessions/${sessionId}/transcript`, + payload: { page_size: 250, before_entry: 42 }, + }); + + expect(response.statusCode).toBe(200); + expect(response.json()).toMatchObject({ + cmd_id: expect.any(String), + ok: true, + result: { first_entry: 7, total_entries: 8, source: 'hook' }, + }); + expect(dispatchAndWait).toHaveBeenCalledWith(hostId, sessionId, expect.any(String), { + type: 'capture_transcript', + payload: { page_size: 250, before_entry: 42 }, + }); + expect(createAuditLog).toHaveBeenCalledWith( + 'session.transcript', + 'session', + sessionId, + { cmd_id: expect.any(String), request: { page_size: 250, before_entry: 42 } }, + userId + ); + + await app.close(); + }); + + it('surfaces old-agent unknown-command failures without terminating the request', async () => { + dispatchAndWait.mockResolvedValueOnce({ + ok: false, + error: { + code: 'COMMAND_FAILED', + message: 'unknown command type: capture_transcript', + }, + }); + const app = await buildServer(); + + const response = await app.inject({ + method: 'POST', + url: `/v1/sessions/${sessionId}/transcript`, + payload: {}, + }); + + expect(response.statusCode).toBe(200); + expect(response.json()).toEqual({ + cmd_id: expect.any(String), + ok: false, + error: { + code: 'COMMAND_FAILED', + message: 'unknown command type: capture_transcript', + }, + }); + expect(dispatchAndWait).toHaveBeenCalledWith(hostId, sessionId, expect.any(String), { + type: 'capture_transcript', + payload: { page_size: 200 }, + }); + expect(createAuditLog).toHaveBeenCalledWith( + 'session.transcript', + 'session', + sessionId, + { cmd_id: expect.any(String), request: { page_size: 200 } }, + userId + ); + await app.close(); + }); + + it.each([ + [{ page_size: 0 }, 'page_size'], + [{ page_size: 501 }, 'page_size'], + [{ before_entry: -1 }, 'before_entry'], + ])('rejects invalid transcript bounds %#', async (payload, issuePath) => { + const app = await buildServer(); + + const response = await app.inject({ + method: 'POST', + url: `/v1/sessions/${sessionId}/transcript`, + payload, + }); + + expect(response.statusCode).toBe(400); + expect(JSON.stringify(response.json())).toContain(issuePath); + expect(dispatchAndWait).not.toHaveBeenCalled(); + await app.close(); + }); + + it.each([ + [{ role: 'viewer' as const }, 'Forbidden'], + [{ hostCapable: false }, 'Host does not support tmux terminal commands'], + ])('rejects requests outside transcript policy %#', async (options, error) => { + const app = await buildServer(options); + + const response = await app.inject({ + method: 'POST', + url: `/v1/sessions/${sessionId}/transcript`, + payload: {}, + }); + + expect(response.statusCode).toBe(403); + expect(response.json()).toEqual({ error }); + expect(dispatchAndWait).not.toHaveBeenCalled(); + await app.close(); + }); +}); From 9048485ab1595e93046b2436ef3dc47d3e58d558 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 19:55:38 -0400 Subject: [PATCH 06/10] feat(chat): render Claude transcript overlay --- .../dashboard/src/components/TerminalView.tsx | 3 +- .../terminal/TerminalHistoryOverlay.tsx | 165 +++++++++++++++--- .../components/terminal/terminalScrollMode.ts | 2 +- .../terminal/transcriptFormatter.test.ts | 57 ++++++ .../terminal/transcriptFormatter.ts | 160 +++++++++++++++++ .../src/hooks/useTerminalTouchScroll.test.ts | 2 + apps/dashboard/src/lib/api.ts | 13 ++ 7 files changed, 371 insertions(+), 31 deletions(-) create mode 100644 apps/dashboard/src/components/terminal/transcriptFormatter.test.ts create mode 100644 apps/dashboard/src/components/terminal/transcriptFormatter.ts diff --git a/apps/dashboard/src/components/TerminalView.tsx b/apps/dashboard/src/components/TerminalView.tsx index dc89105..cf4ba25 100644 --- a/apps/dashboard/src/components/TerminalView.tsx +++ b/apps/dashboard/src/components/TerminalView.tsx @@ -258,7 +258,8 @@ export function TerminalView({ strip_ansi: true, }); if (cancelled || !response.ok) return; - cacheScrollMode(historySessionId, classifyTerminalScrollMode(response.result?.content)); + const mode = classifyTerminalScrollMode(response.result?.content); + if (mode === 'history') cacheScrollMode(historySessionId, mode); } catch { // Transport failure leaves the pane unclassified; the overlay path re-probes. } diff --git a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx index a786c33..02c593e 100644 --- a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx +++ b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx @@ -2,8 +2,9 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { ArrowDown, Loader2, RotateCcw } from 'lucide-react'; +import type { TranscriptEntry } from '@agent-command/schema'; import { Button } from '@/components/ui/button'; -import { getSessionScrollback } from '@/lib/api'; +import { getSessionScrollback, getSessionTranscript } from '@/lib/api'; import { SCROLLBACK_PAGE_LINES, compensateScrollbackPrepend, @@ -17,6 +18,7 @@ import { type ScrollbackRange, } from './scrollbackPaging'; import { classifyTerminalScrollMode, type TerminalScrollMode } from './terminalScrollMode'; +import { formatTranscriptEntries } from './transcriptFormatter'; interface TerminalHistoryOverlayProps { sessionId: string; @@ -27,12 +29,28 @@ interface TerminalHistoryOverlayProps { } interface HistoryPage { + type: 'history'; range: ScrollbackRange; lines: string[]; - scrollMode: TerminalScrollMode; +} + +interface ChatPage { + type: 'chat'; + entries: TranscriptEntry[]; + firstEntry: number; + totalEntries: number; } const OVERSCAN_LINES = 12; +const TRANSCRIPT_PAGE_ENTRIES = 200; + +type OverlayPage = HistoryPage | ChatPage; + +interface OverlayLine { + key: string; + text: string; + dim: boolean; +} export function TerminalHistoryOverlay({ sessionId, @@ -41,21 +59,23 @@ export function TerminalHistoryOverlay({ onScrollModeResolved, onClose, }: TerminalHistoryOverlayProps) { - const [pages, setPages] = useState([]); + const [pages, setPages] = useState([]); + const [mode, setMode] = useState<'history' | 'chat' | null>(null); const [loadingInitial, setLoadingInitial] = useState(false); const [loadingOlder, setLoadingOlder] = useState(false); const [hasOlder, setHasOlder] = useState(true); const [error, setError] = useState(null); const [scrollTop, setScrollTop] = useState(0); const [viewportHeight, setViewportHeight] = useState(0); + const [viewportWidth, setViewportWidth] = useState(0); const scrollRef = useRef(null); const generationRef = useRef(0); const loadingOlderRef = useRef(false); const overscrollStartRef = useRef<{ y: number; atBottom: boolean } | null>(null); const lineHeight = Math.max(16, Math.round(fontSize * 1.2)); - const fetchPage = useCallback( - async (range: ScrollbackRange): Promise => { + const fetchHistoryPage = useCallback( + async (range: ScrollbackRange): Promise<{ page: HistoryPage; scrollMode: TerminalScrollMode }> => { const response = await getSessionScrollback(sessionId, { mode: 'range', start_line: range.startLine, @@ -67,37 +87,81 @@ export function TerminalHistoryOverlay({ } const content = response.result?.content; return { - range, - lines: contentScrollbackLines(content), + page: { + type: 'history', + range, + lines: contentScrollbackLines(content), + }, scrollMode: classifyTerminalScrollMode(content), }; }, [sessionId] ); + const fetchChatPage = useCallback( + async (beforeEntry?: number): Promise => { + const response = await getSessionTranscript(sessionId, { + page_size: TRANSCRIPT_PAGE_ENTRIES, + ...(beforeEntry !== undefined ? { before_entry: beforeEntry } : {}), + }); + if (!response.ok) { + throw new Error(response.error.message); + } + return { + type: 'chat', + entries: response.result.entries, + firstEntry: response.result.first_entry, + totalEntries: response.result.total_entries, + }; + }, + [sessionId] + ); + const loadInitial = useCallback(async () => { const generation = ++generationRef.current; setLoadingInitial(true); setError(null); setPages([]); + setMode(null); setHasOlder(true); setScrollTop(0); try { - const page = await fetchPage(initialScrollbackRange()); - onScrollModeResolved(page.scrollMode); + const { page, scrollMode } = await fetchHistoryPage(initialScrollbackRange()); if (generationRef.current !== generation) return; - if (page.scrollMode === 'app-scroll') { - onClose(); + if (scrollMode === 'app-scroll') { + try { + const chatPage = await fetchChatPage(); + if (generationRef.current !== generation) return; + setMode('chat'); + setPages([chatPage]); + setHasOlder(chatPage.firstEntry > 0); + onScrollModeResolved('chat'); + requestAnimationFrame(() => { + const element = scrollRef.current; + if (!element || generationRef.current !== generation) return; + element.scrollTop = element.scrollHeight; + setScrollTop(element.scrollTop); + setViewportHeight(element.clientHeight); + setViewportWidth(element.clientWidth); + }); + } catch { + if (generationRef.current !== generation) return; + onScrollModeResolved('app-scroll'); + onClose(); + } return; } + setMode('history'); setPages([page]); setHasOlder(page.lines.length >= SCROLLBACK_PAGE_LINES); + onScrollModeResolved('history'); requestAnimationFrame(() => { const element = scrollRef.current; if (!element || generationRef.current !== generation) return; element.scrollTop = element.scrollHeight; setScrollTop(element.scrollTop); setViewportHeight(element.clientHeight); + setViewportWidth(element.clientWidth); }); } catch (loadError) { if (generationRef.current !== generation) return; @@ -107,7 +171,7 @@ export function TerminalHistoryOverlay({ } finally { if (generationRef.current === generation) setLoadingInitial(false); } - }, [fetchPage, onClose, onScrollModeResolved]); + }, [fetchChatPage, fetchHistoryPage, onClose, onScrollModeResolved]); useEffect(() => { if (!open) { @@ -124,28 +188,43 @@ export function TerminalHistoryOverlay({ if (!open) return; const element = scrollRef.current; if (!element) return; - const updateHeight = () => setViewportHeight(element.clientHeight); - updateHeight(); - const observer = new ResizeObserver(updateHeight); + const updateViewport = () => { + setViewportHeight(element.clientHeight); + setViewportWidth(element.clientWidth); + }; + updateViewport(); + const observer = new ResizeObserver(updateViewport); observer.observe(element); return () => observer.disconnect(); }, [open]); const loadOlder = useCallback(async () => { - if (loadingOlderRef.current || !hasOlder) return; + if (loadingOlderRef.current || !hasOlder || mode === null) return; const generation = generationRef.current; - const currentOldest = pages[0]?.range ?? initialScrollbackRange(); - const range = olderScrollbackRange(currentOldest); const element = scrollRef.current; const previousHeight = element?.scrollHeight ?? 0; loadingOlderRef.current = true; setLoadingOlder(true); setError(null); try { - const page = await fetchPage(range); + let page: OverlayPage; + let olderAvailable: boolean; + if (mode === 'chat') { + const currentOldest = pages[0]?.type === 'chat' ? pages[0].firstEntry : 0; + page = await fetchChatPage(currentOldest); + olderAvailable = page.firstEntry > 0; + } else { + const currentOldest = pages[0]?.type === 'history' + ? pages[0].range + : initialScrollbackRange(); + const range = olderScrollbackRange(currentOldest); + const historyPage = await fetchHistoryPage(range); + page = historyPage.page; + olderAvailable = page.lines.length >= SCROLLBACK_PAGE_LINES; + } if (generationRef.current !== generation) return; setPages((current) => [page, ...current]); - setHasOlder(page.lines.length >= SCROLLBACK_PAGE_LINES); + setHasOlder(olderAvailable); requestAnimationFrame(() => { if (!element || generationRef.current !== generation) return; const nextTop = compensateScrollbackPrepend( @@ -159,7 +238,11 @@ export function TerminalHistoryOverlay({ } catch (loadError) { if (generationRef.current !== generation) return; setError( - loadError instanceof Error ? loadError.message : 'Older history could not be loaded.' + loadError instanceof Error + ? loadError.message + : mode === 'chat' + ? 'Older chat could not be loaded.' + : 'Older history could not be loaded.' ); } finally { if (generationRef.current === generation) { @@ -167,11 +250,30 @@ export function TerminalHistoryOverlay({ setLoadingOlder(false); } } - }, [fetchPage, hasOlder, pages]); + }, [fetchChatPage, fetchHistoryPage, hasOlder, mode, pages]); - const allLines = useMemo( - () => pages.flatMap((page) => numberScrollbackLines(page.range, page.lines)), - [pages] + const transcriptColumns = Math.max( + 20, + Math.floor((viewportWidth || 320) / Math.max(1, fontSize * 0.62)) - 2 + ); + const allLines = useMemo( + () => pages.flatMap((page) => { + if (page.type === 'history') { + return numberScrollbackLines(page.range, page.lines).map((line) => ({ + key: `history:${line.lineNumber}`, + text: line.text, + dim: false, + })); + } + return page.entries.flatMap((entry, entryOffset) => ( + formatTranscriptEntries([entry], transcriptColumns).map((line, lineOffset) => ({ + key: `chat:${page.firstEntry + entryOffset}:${lineOffset}`, + text: line.text, + dim: line.dim, + })) + )); + }), + [pages, transcriptColumns] ); const virtualWindow = resolveScrollbackVirtualWindow({ lineCount: allLines.length, @@ -195,7 +297,11 @@ export function TerminalHistoryOverlay({ className="rounded-full border border-white/10 bg-black/75 px-2.5 py-1 font-sans text-[10px] font-medium text-white/65 shadow-sm backdrop-blur" aria-live="polite" > - {loadingOlder ? 'Loading older…' : hasOlder ? 'History' : 'Start of history'} + {loadingOlder + ? 'Loading older…' + : hasOlder + ? mode === 'chat' ? 'Chat' : 'History' + : mode === 'chat' ? 'Start of chat' : 'Start of history'}