From 7eb976f7ace0b6fe4b7ed22112c28ceec9837a04 Mon Sep 17 00:00:00 2001 From: Callum Alpass Date: Mon, 2 Nov 2026 20:42:55 +1100 Subject: [PATCH] Add turn navigation, checkpoint diffs and confirmed rewind --- README.md | 9 ++- bun.lock | 1 + package.json | 1 + src/client/session.ts | 68 ++++++++++++++++++++++ src/model/diffs.ts | 34 +++++++++++ src/model/timeline.ts | 5 +- src/model/turns.ts | 67 +++++++++++++++++++++ src/ui/App.tsx | 27 +++++++-- src/ui/CommandOutput.tsx | 36 ++++++++++++ src/ui/DiffView.tsx | 31 +++++----- src/ui/ThreadView.tsx | 45 +++++++++----- src/ui/useDiffContext.ts | 45 ++++++++++++++ src/ui/useTurns.ts | 119 ++++++++++++++++++++++++++++++++++++++ test/diffs.test.ts | 29 ++++++++++ test/turns.test.ts | 58 +++++++++++++++++++ test/turnsSession.test.ts | 98 +++++++++++++++++++++++++++++++ 16 files changed, 634 insertions(+), 39 deletions(-) create mode 100644 src/model/diffs.ts create mode 100644 src/model/turns.ts create mode 100644 src/ui/CommandOutput.tsx create mode 100644 src/ui/useDiffContext.ts create mode 100644 src/ui/useTurns.ts create mode 100644 test/diffs.test.ts create mode 100644 test/turns.test.ts create mode 100644 test/turnsSession.test.ts diff --git a/README.md b/README.md index 901d0d3..648f31e 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,10 @@ Navigation: | `y` / `Y` / `n` | approve / always allow this session / decline the pending approval | | `1`–`9` | pick an option when the agent asks a question (also in an empty message box) | | `x` | dismiss the agent's question | -| `e` | expand all folded turns and work groups | +| `e` | expand all folded turns, work groups and command output | +| `[` / `]` | select the previous / next turn; `esc` clears the selection | +| `D` | view changes from the selected turn, or the latest turn with changes | +| `R` | rewind to before the selected prompt, after confirmation | | `o` | load earlier turns | | `d` | show or hide thread details | | `l` / `→` | move into the details panel: `j`/`k` choose, `enter` opens, `t` turns an automation on or off, `esc` comes back | @@ -71,9 +74,11 @@ Navigation: The layout follows T3 Code's web app, and much of it uses the web app's own code (vendored from upstream): - **Sidebar:** the same sections (Pinned, Active, Working, then Snoozed and Settled folded to a count) and the same status words: `Working 2m`, `Waiting`, `Approval`, `Input`, `Request`, `Limited`, `Failed`, `Done`. Threads that need you are bold. +- **Turns:** `[`/`]` select a turn and mark its prompt. `R` or `Revert to this turn` asks `Edit from here?`, then rewinds chat and returns the prompt to the composer, keeping file changes. `Revert files too` in the palette also restores files, including your own edits. Stop a running turn first. Rewinding messages with attachments still needs the web app. +- **Command output:** expand work with `e` / `Expand all work`, or click a command. Output streams while its expanded row is in view; collapsing it, scrolling away or opening another thread stops the subscription. - **Conversation:** built by the web app's timeline logic. Each finished turn's work folds into one line (`Worked for 3m 12s`), your messages are right-aligned, and a running turn shows its live step and `Working for 12s`. - **Thread details:** a column beside the conversation with the workspace, model and mode, the branch with ahead/behind and its pull request, uncommitted changes per file, lineage (forks and subagents), background work and the goal. It opens by itself on terminals 160 columns or wider; on narrow ones `d` shows it in place of the conversation. -- **Diffs:** pick `View diff` or a file under Changes to see uncommitted changes as unified diffs in place of the conversation. `j`/`k` scroll, `esc` closes. +- **Diffs:** pick `View diff` or a file under Changes to see uncommitted changes as unified diffs in place of the conversation. `D` (or `View changes from this turn`) reviews a turn's checkpoint; `View all changes in this thread` reviews the whole thread. `j`/`k` scroll, `[`/`]` choose a file, and `esc` closes. In uncommitted diffs, `x` or `enter` shows the whole file, including unchanged context; press it again to collapse. Historical checkpoint context is unavailable, as in the web app. - **Git:** the branch section offers the web app's quick action (`Commit & push`, `Push`, `Create PR`…) and its menu. Every action asks first, says when you are on the default branch, and takes an optional commit message (blank lets T3 write one). Progress shows on the bottom line. - **Servers and automations:** local dev servers the thread started (stop one from the panel) and T3's scheduled tasks with their schedule and next run (run now, or turn on and off). - **Subagents:** subagent work in the conversation and the lineage rows in details are links; `enter` or a click opens the child thread, and `u` goes back. Idle subagents, which the thread list leaves out, are fetched from the server when you open one (on servers that serve them). diff --git a/bun.lock b/bun.lock index 589cce6..c8c515b 100644 --- a/bun.lock +++ b/bun.lock @@ -7,6 +7,7 @@ "dependencies": { "@opentui/core": "0.2.7", "@opentui/react": "0.2.7", + "diff": "9.0.0", "effect": "4.0.5", "mdast-util-directive": "^3.2.0", "micromark-extension-directive": "^4.0.0", diff --git a/package.json b/package.json index 2eb203a..2258e44 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "dependencies": { "@opentui/core": "0.2.7", "@opentui/react": "0.2.7", + "diff": "9.0.0", "effect": "4.0.5", "mdast-util-directive": "^3.2.0", "micromark-extension-directive": "^4.0.0", diff --git a/src/client/session.ts b/src/client/session.ts index e5d8848..1e4f0ce 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -1,5 +1,10 @@ import { CommandId, + type OrchestrationGetTurnDiffInput, + type OrchestrationGetFullThreadDiffInput, + type ReviewDiffFileContentsInput, + type OrchestrationV2Checkpoint, + type TurnItemId, MessageId, ORCHESTRATION_PROTOCOL_HEADER, ORCHESTRATION_PROTOCOL_VERSION_TEXT, @@ -47,6 +52,7 @@ import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import { applyShellStreamEvent, mergeShellSnapshotProjects } from "../../vendor/t3code/packages/client-runtime/src/state/shellReducer.ts"; +import { applyCommandOutputFrame, EMPTY_COMMAND_OUTPUT, type CommandOutputView } from "@t3tools/client-runtime/state/command-output"; import { connect, type Connection } from "./rpc.ts"; export type ConnectionStatus = @@ -308,6 +314,68 @@ export class T3Session { return result.sources.find((source) => source.kind === "working-tree") ?? null; } + /** Checkpoint ranges, matching the web's turn and thread diff selections. */ + turnDiff(input: OrchestrationGetTurnDiffInput) { + return Effect.runPromise(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.getTurnDiff](input)); + } + + fullThreadDiff(input: OrchestrationGetFullThreadDiffInput) { + return Effect.runPromise(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff](input)); + } + + diffFileContents(input: ReviewDiffFileContentsInput) { + return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.reviewGetDiffFileContents](input)); + } + + /** Expanded commands have no linger: closing their row stops the stream immediately. */ + watchCommandOutput(threadId: ThreadId, itemId: TurnItemId, listener: Listener, onError: Listener): () => void { + let view = EMPTY_COMMAND_OUTPUT; + const fiber = this.runInScope(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]({ threadId, itemId }).pipe( + Stream.runForEach((frame) => Effect.sync(() => listener(view = applyCommandOutputFrame(view, frame)))), + Effect.catchCause((cause) => Effect.sync(() => onError(prettyCause(cause)))), + )); + return () => { Effect.runFork(Fiber.interrupt(fiber)); }; + } + + /** Sends the checkpoint identity captured before opening the confirmation. */ + rollback(threadId: ThreadId, checkpoint: Pick, restoreFiles: boolean, commandId = newCommandId()): Promise { + return this.dispatch({ type: "checkpoint.rollback", commandId, threadId, scopeId: checkpoint.scopeId, checkpointId: checkpoint.id, restoreFiles }); + } + + /** Waits for the settled suffix and provider conversation to rewind, as the web does. */ + async rewind(initial: OrchestrationV2ThreadProjection, checkpoint: Pick, turnCount: number, restoreFiles: boolean): Promise { + const witness = initial.runs.filter((run) => run.ordinal > turnCount && ["completed", "interrupted", "failed", "cancelled"].includes(run.status)) + .sort((a, b) => b.ordinal - a.ordinal)[0]; + if (!witness) throw new Error("The thread has changed. Select a message to rewind again."); + const providerThread = initial.providerThreads.find((thread) => thread.id === initial.thread.activeProviderThreadId); + const commandId = newCommandId(); + await new Promise((resolve, reject) => { + let accepted = false; + let state: ThreadState | null = null; + let unwatch = () => {}; + const finish = (error?: unknown) => { + clearTimeout(timer); + unwatch(); + if (error !== undefined) reject(error); else resolve(); + }; + const inspect = () => { + const next = state?.projection; + if (!next) return; + if (next.thread.rollbackFailure?.requestId === commandId) return finish(new Error(next.thread.rollbackFailure.message)); + const providerRewound = next.providerThreads.some((thread) => { + const sameThread = thread.id === providerThread?.id; + const freshRoot = turnCount === 0 && thread.ownerNodeId === null && thread.appThreadId === initial.thread.id && + thread.providerInstanceId === providerThread?.providerInstanceId && !initial.providerThreads.some((old) => old.id === thread.id); + return (sameThread || freshRoot) && thread.lastRunOrdinal === (turnCount === 0 ? null : turnCount); + }); + if (accepted && providerRewound && next.runs.some((run) => run.id === witness.id && run.status === "rolled_back")) finish(); + }; + const timer = setTimeout(() => finish(new Error("Timed out waiting for the thread to rewind.")), 120_000); + unwatch = this.watchThread(initial.thread.id, (next) => { state = next; inspect(); }); + this.rollback(initial.thread.id, checkpoint, restoreFiles, commandId).then(() => { accepted = true; inspect(); }, finish); + }); + } + /** Runs a commit / push / PR action, reporting progress as it goes. Rejects with the server's message on failure. */ async runGitAction(request: GitActionRequest, onProgress: Listener): Promise { const rpc = this.requireConnection().rpc; diff --git a/src/model/diffs.ts b/src/model/diffs.ts new file mode 100644 index 0000000..ad2f861 --- /dev/null +++ b/src/model/diffs.ts @@ -0,0 +1,34 @@ +import { createTwoFilesPatch, parsePatch } from "diff"; +import type { ReviewDiffFileContentsInput } from "@t3tools/contracts"; + +export interface PatchFile { + readonly path: string; + readonly oldPath: string; + readonly changeType: ReviewDiffFileContentsInput["changeType"]; + readonly patch: string; +} + +/** Retains both paths so renamed and deleted files expand against the right revisions. */ +export function splitPatch(patch: string): PatchFile[] { + return patch.split(/^(?=diff --git )/m).filter((chunk) => chunk.startsWith("diff --git ")).map((chunk) => { + let parsed; + try { parsed = parsePatch(chunk.split(/^@@ /m)[0]!)[0]; } catch { /* A truncated preview can end inside a file header. */ } + const oldPath = cleanPath(parsed?.oldFileName ?? /^diff --git a\/(.+?) b\//.exec(chunk)?.[1] ?? "file"); + const newPath = cleanPath(parsed?.newFileName ?? oldPath); + const renamed = /^rename from /m.test(chunk); + return { path: newPath === "/dev/null" ? oldPath : newPath, oldPath: oldPath === "/dev/null" ? newPath : oldPath, + changeType: parsed?.isCreate || oldPath === "/dev/null" ? "new" : parsed?.isDelete || newPath === "/dev/null" ? "deleted" : renamed ? /^@@ /m.test(chunk) ? "rename-changed" : "rename-pure" : "change", patch: chunk }; + }); +} + +function cleanPath(path: string): string { + return path.replace(/^[ab]\//, ""); +} + +/** The same unified renderer can show all unchanged lines after loading both file versions. */ +export function wholeFilePatch(file: PatchFile, contents: { readonly oldContents: string; readonly newContents: string }): string { + const patch = createTwoFilesPatch(file.oldPath, file.path, contents.oldContents, contents.newContents, undefined, undefined, { context: Infinity }); + if (contents.oldContents !== contents.newContents || contents.newContents.length === 0) return patch; + const lines = contents.newContents.replace(/\n$/, "").split("\n"); + return `${patch}@@ -1,${lines.length} +1,${lines.length} @@\n${lines.map((line) => ` ${line}`).join("\n")}\n`; +} diff --git a/src/model/timeline.ts b/src/model/timeline.ts index 0377ead..c889a24 100644 --- a/src/model/timeline.ts +++ b/src/model/timeline.ts @@ -1,3 +1,4 @@ +import { turnTargets, type TurnTarget } from "./turns.ts"; import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; import { deriveRunlessWorkStartedAt, @@ -28,6 +29,7 @@ export { liveWorkEntryLabel, workEntryDisplayLabel } from "../../vendor/t3code/a export interface Timeline { readonly rows: readonly MessagesTimelineRow[]; readonly pending: PendingThreadRequests; + readonly turns: readonly TurnTarget[]; readonly isWorking: boolean; /** When the current run started working, for "Working for 12s". */ readonly workStartedAt: string | null; @@ -53,7 +55,7 @@ const NOTHING = new Set(); export function buildTimeline( projection: OrchestrationV2ThreadProjection, - options: { readonly expandAll: boolean }, + options: { readonly expandAll: boolean; readonly historyComplete: boolean }, previous: Timeline | null, ): Timeline { const cache = previous?.cache.expandAll === options.expandAll ? previous.cache : null; @@ -95,6 +97,7 @@ export function buildTimeline( return { rows: stable.result, pending, + turns: turnTargets(projection, entries.entries, isWorking ? runtime?.activeRunId ?? null : null, options.historyComplete), isWorking, workStartedAt, cache: { entries, rows, stable, expandAll: options.expandAll }, diff --git a/src/model/turns.ts b/src/model/turns.ts new file mode 100644 index 0000000..8bce316 --- /dev/null +++ b/src/model/turns.ts @@ -0,0 +1,67 @@ +import type { MessageId, OrchestrationV2ThreadProjection, RunId } from "@t3tools/contracts"; +import { checkpointFileTotals, deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints"; +import { deriveRevertTurnCountByUserMessageId, findRevertCheckpoint, type TimelineEntriesProjection } from "../../vendor/t3code/apps/web/src/session-logic.ts"; + +export { findRevertCheckpoint }; +export type TurnCheckpoint = ReturnType[number]; +export interface TurnTarget { + readonly messageId: MessageId; + readonly runId: RunId; + readonly text: string; + readonly hasAttachments: boolean; + readonly checkpoint: TurnCheckpoint | undefined; + readonly revertTurnCount: number | undefined; +} + +/** Uses the web's rewind mapping; run ordinals can have gaps after a rollback. */ +export function turnTargets(projection: OrchestrationV2ThreadProjection, entries: TimelineEntriesProjection["entries"], unsettledRunId: RunId | null, historyComplete: boolean): TurnTarget[] { + const checkpoints = deriveThreadCheckpointSummaries(projection); + const revertCounts = deriveRevertTurnCountByUserMessageId({ + timelineEntries: entries, + checkpoints, + threadStartCheckpointReady: historyComplete && findRevertCheckpoint(projection.checkpoints, 0) !== undefined, + availableRevertTurnCounts: availableRevertTurnCounts(projection), + unsettledRunId, + }); + const seen = new Set(); + return entries.flatMap((entry) => { + if (entry.kind !== "message" || entry.message.role !== "user" || !entry.message.runId || seen.has(entry.message.runId)) return []; + const message = entry.message; + const runId = entry.message.runId; + seen.add(runId); + return [{ messageId: message.id, runId, text: message.text, hasAttachments: (message.attachments?.length ?? 0) > 0, + checkpoint: checkpoints.findLast((checkpoint) => checkpoint.runId === message.runId), revertTurnCount: revertCounts.get(message.id) }]; + }); +} + +/** Same provider-turn eligibility as ChatView.logic, without importing its browser state. */ +function availableRevertTurnCounts(projection: OrchestrationV2ThreadProjection): Set { + const available = new Set(); + const providerThread = projection.providerThreads.find((thread) => thread.id === projection.thread.activeProviderThreadId); + if (!providerThread?.providerSessionId || providerThread.providerInstanceId !== projection.thread.modelSelection.instanceId) return available; + available.add(0); + for (const run of projection.runs) { + if (run.activeAttemptId === null) continue; + const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId); + const turn = projection.providerTurns.filter((candidate) => candidate.runAttemptId === run.activeAttemptId) + .reduce<(typeof projection.providerTurns)[number] | undefined>((latest, candidate) => !latest || candidate.ordinal > latest.ordinal ? candidate : latest, undefined) + ?? projection.providerTurns.find((candidate) => candidate.id === attempt?.providerTurnId); + if (turn?.providerThreadId === providerThread.id) available.add(run.ordinal); + } + return available; +} + +/** With no cursor, diff the most recent checkpoint that actually changed files. */ +export function diffTurn(turns: readonly TurnTarget[], selectedMessageId: string | null): TurnCheckpoint | undefined { + return selectedMessageId !== null + ? turns.find((turn) => turn.messageId === selectedMessageId)?.checkpoint + : turns.map((turn) => turn.checkpoint).filter((checkpoint): checkpoint is TurnCheckpoint => checkpoint !== undefined && checkpointFileTotals(checkpoint).count > 0) + .sort((left, right) => right.checkpointTurnCount - left.checkpointTurnCount)[0]; +} + +/** A cursor stays on its message when older history is prepended. */ +export function adjacentTurn(turns: readonly TurnTarget[], selectedMessageId: string | null, direction: -1 | 1): TurnTarget | undefined { + const index = turns.findIndex((turn) => turn.messageId === selectedMessageId); + return turns[index < 0 ? turns.length - 1 : Math.max(0, Math.min(turns.length - 1, index + direction))]; +} + diff --git a/src/ui/App.tsx b/src/ui/App.tsx index da7fabd..896b0c0 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -39,6 +39,7 @@ import { attachTerminal } from "./terminalAttach.ts"; import { copyText, desktopNotify, ring } from "./terminalOut.ts"; import { colors } from "./theme.ts"; import { ThreadList } from "./ThreadList.tsx"; +import { useTurns } from "./useTurns.ts"; import { ThreadView } from "./ThreadView.tsx"; /** @@ -171,6 +172,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C const threadRow = allRows.find((row) => row.thread.id === threadId); const threadShell = threadRow?.thread ?? shell.snapshot?.threads.find((thread) => thread.id === threadId) ?? (threadId ? familyShells.get(threadId) : undefined); const composerKey: string = draft ? DRAFT_KEY : (threadId ?? ""); + const activeComposerKey = useRef(composerKey); + activeComposerKey.current = composerKey; // Pin the initial selection to a thread, or it would follow whatever sorts first. useEffect(() => { if (selectedId === undefined && rows[0]) setSelectedId(rows[0].thread.id); @@ -213,10 +216,10 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C const timeline = useMemo(() => { if (!thread?.projection || !watchedId) return null; const previous = previousTimeline.current?.id === watchedId ? previousTimeline.current.timeline : null; - const next = buildTimeline(thread.projection, { expandAll }, previous); + const next = buildTimeline(thread.projection, { expandAll, historyComplete: !thread.history.hasMore }, previous); previousTimeline.current = { id: watchedId, timeline: next }; return next; - }, [thread?.projection, watchedId, expandAll]); + }, [thread?.projection, thread?.history.hasMore, watchedId, expandAll]); const current = watchedId === threadId ? timeline : null; const pendingApproval = current?.pending.approvals[0]; const pendingInput = current?.pending.userInputs[0]; @@ -360,7 +363,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C const cwd = vcsCwd; setDiff({ cwd, path, status: "loading" }); session.workingTreeDiff(cwd, path ?? undefined, config.diffIgnoreWhitespace).then( - (source) => setDiff((value) => (value?.cwd === cwd && value.path === path ? { cwd, path, status: "ready", patch: source?.diff ?? "", truncated: source?.truncated ?? false } : value)), + (source) => setDiff((value) => (value?.cwd === cwd && value.path === path ? { cwd, path, status: "ready", patch: source?.diff ?? "", ...(source ? { source: { cwd, sourceKind: source.kind, baseRef: source.baseRef, headRef: source.headRef } } : {}), truncated: source?.truncated ?? false } : value)), (error) => setDiff((value) => (value?.cwd === cwd && value.path === path ? { cwd, path, status: "error", error: messageOf(error) } : value)), ); }; @@ -920,8 +923,18 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C const scrollPage = (direction: 1 | -1) => scrollRef.current?.scrollBy(direction * Math.max(1, height - 10)); + const turns = useTurns({ session, threadId, projection, timeline: current, config: providerConfig, cwd: vcsCwd, ignoreWhitespace: config.diffIgnoreWhitespace, enabled: draft === null, diff, setDiff, scrollRef, confirm, say, + showConversation: () => { setMode("nav"); setDetailsPref((value) => width < MIN_CONVERSATION_WIDTH + DETAILS_WIDTH ? false : value); }, + restorePrompt: (id, text) => { + const previous = id === activeComposerKey.current ? composerRef.current?.plainText ?? "" : drafts.current.get(id) ?? ""; + const next = text ? previous ? `${previous}\n\n${text}` : text : previous; + drafts.current.set(id, next); + if (id === activeComposerKey.current) { composerRef.current?.setText(next); setMode("input"); } + }, + }); + // The command palette: everything the keys do, plus what the details panel offers. - const commands: (PaletteCommand & { readonly run: () => void })[] = []; + const commands: (PaletteCommand & { readonly run: () => void })[] = [...turns.commands]; const command = (id: string, label: string, action: () => void, extra: Omit = {}) => commands.push({ id, title: label, run: action, ...extra }); if (pendingApproval) { command("approve", "Approve request", () => respond("accept"), { shortcut: "y" }); @@ -1176,6 +1189,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C return setMode("nav"); } } + if (mode === "nav" && turns.onKey(key)) return key.preventDefault(); switch (key.name) { case "q": if (diff) return setDiff(null); @@ -1351,7 +1365,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C }} /> ) : diff ? ( - + ) : draft ? ( ) : threadId && detailsInPlace ? ( @@ -1365,6 +1379,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C title={title} detail={threadShell?.branch ?? ""} timeline={current} + selectedMessageId={turns.selectedMessageId} + session={session} + streamCommandOutput={live && providerConfig?.environment.capabilities.commandOutputStreaming === true} history={watchedId === threadId ? (thread?.history ?? null) : null} loading={watchedId !== threadId || thread?.status === "loading"} error={thread?.error} diff --git a/src/ui/CommandOutput.tsx b/src/ui/CommandOutput.tsx new file mode 100644 index 0000000..408c199 --- /dev/null +++ b/src/ui/CommandOutput.tsx @@ -0,0 +1,36 @@ +import type { BoxRenderable, ScrollBoxRenderable } from "@opentui/core"; +import type { CommandOutputView } from "@t3tools/client-runtime/state/command-output"; +import type { ThreadId, TurnItemId } from "@t3tools/contracts"; +import { terminalOutputPlainText } from "@t3tools/shared/terminalOutput"; +import { useEffect, useRef, useState, type RefObject } from "react"; +import type { T3Session } from "../client/session.ts"; +import { colors } from "./theme.ts"; + +/** Only expanded command rows in the viewport subscribe; the server bounds the output tail. */ +export function CommandOutput(props: { readonly session: T3Session; readonly threadId: ThreadId; readonly itemId: TurnItemId; readonly scrollRef: RefObject }) { + const box = useRef(null); + const [visible, setVisible] = useState(false); + const [view, setView] = useState(null); + const [error, setError] = useState(null); + useEffect(() => { + const inspect = () => { + const row = box.current; + const viewport = props.scrollRef.current?.viewport; + setVisible(Boolean(row && viewport && row.y + row.height > viewport.y && row.y < viewport.y + viewport.height)); + }; + inspect(); + const timer = setInterval(inspect, 250); + return () => clearInterval(timer); + }, [props.scrollRef]); + useEffect(() => { + if (!visible) return; + setError(null); + return props.session.watchCommandOutput(props.threadId, props.itemId, setView, setError); + }, [props.session, props.threadId, props.itemId, visible]); + const lines = view ? terminalOutputPlainText(view.output.text).trimEnd().split("\n") : []; + return + {error ? {`Could not load output: ${error}`} : null} + {view?.output.truncated || lines.length > 12 ? Earlier output not shown : null} + {lines.slice(-12).join("\n") || (view ? view.running ? "Waiting for output…" : "No output." : "Loading output…")} + ; +} diff --git a/src/ui/DiffView.tsx b/src/ui/DiffView.tsx index d9f4fe6..a7466d6 100644 --- a/src/ui/DiffView.tsx +++ b/src/ui/DiffView.tsx @@ -1,3 +1,5 @@ +import type { ReviewDiffFileContentsInput } from "@t3tools/contracts"; +import { splitPatch } from "../model/diffs.ts"; import type { ScrollBoxRenderable } from "@opentui/core"; import type { RefObject } from "react"; @@ -5,7 +7,9 @@ import { colors, getMarkdownStyle } from "./theme.ts"; export interface DiffState { readonly cwd: string; - /** null for the whole working tree. */ + readonly title?: string; + readonly source?: Pick; + /** null to show every changed file. */ readonly path: string | null; readonly status: "loading" | "ready" | "error"; readonly patch?: string; @@ -13,30 +17,31 @@ export interface DiffState { readonly error?: string; } -/** Uncommitted changes as unified diffs, one block per file, in place of the conversation. */ -export function DiffView(props: { readonly diff: DiffState; readonly scrollRef: RefObject }) { +/** Working-tree or checkpoint changes through the same unified diff renderer. */ +export function DiffView(props: { readonly diff: DiffState; readonly scrollRef: RefObject; readonly selected: number; readonly expanded: Readonly> }) { const { diff } = props; const files = diff.patch ? splitPatch(diff.patch) : []; return ( - Uncommitted / + {diff.title ?? "Uncommitted"} / {diff.path ?? `${files.length} ${files.length === 1 ? "file" : "files"}`} - esc close + {diff.source ? "[/] file · x whole file / collapse · esc close" : "[/] file · esc close"} {diff.status === "loading" ? Loading diff… : null} {diff.status === "error" ? {`Could not load the diff: ${diff.error ?? "unknown error"}`} : null} {diff.status === "ready" && files.length === 0 ? No changes. : null} {diff.truncated ? The diff was too large and is cut short. : null} - {files.map((file) => ( - - {diff.path ? null : {file.path}} + {files.map((file, index) => ( + + {`${index === props.selected ? "▸ " : " "}${file.path}`} + {props.expanded[file.path] && !props.expanded[file.path]?.patch ? {props.expanded[file.path]?.error ?? "Loading full file…"} : null} chunk.startsWith("diff --git ")) - .map((chunk) => ({ path: /^diff --git a\/(.+?) b\//.exec(chunk)?.[1] ?? "file", patch: chunk })); -} +export { splitPatch } from "../model/diffs.ts"; const FILETYPES: Record = { ts: "typescript", tsx: "tsx", js: "javascript", jsx: "javascript", json: "json", md: "markdown", rs: "rust", py: "python", go: "go", css: "css", html: "html", sh: "bash", yml: "yaml", yaml: "yaml", zig: "zig" }; diff --git a/src/ui/ThreadView.tsx b/src/ui/ThreadView.tsx index 584844c..5f28ce7 100644 --- a/src/ui/ThreadView.tsx +++ b/src/ui/ThreadView.tsx @@ -2,9 +2,10 @@ import type { ScrollBoxRenderable } from "@opentui/core"; import type { ThreadId } from "@t3tools/contracts"; import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models"; import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation"; -import { memo, type RefObject } from "react"; +import { memo, useState, type RefObject } from "react"; -import type { ThreadHistory } from "../client/session.ts"; +import { CommandOutput } from "./CommandOutput.tsx"; +import type { T3Session, ThreadHistory } from "../client/session.ts"; import { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, type Timeline, type WorkLogEntry } from "../model/timeline.ts"; import { blockFor } from "../model/transcript.ts"; import { colors, getMarkdownStyle, toneColor } from "./theme.ts"; @@ -15,6 +16,9 @@ export function ThreadView(props: { readonly title: string; readonly detail: string; readonly timeline: Timeline | null; + readonly selectedMessageId: string | null; + readonly session: T3Session; + readonly streamCommandOutput: boolean; readonly history: ThreadHistory | null; readonly loading: boolean; readonly error?: string | undefined; @@ -51,6 +55,10 @@ export function ThreadView(props: { ; readonly pending: boolean; readonly workspaceRoot: string | undefined; readonly now: number; @@ -95,7 +107,7 @@ const Row = memo(function Row(props: { switch (row.kind) { case "message": { const { message } = row; - if (message.role === "user") return ; + if (message.role === "user") return ; if (message.role === "system") return {message.text}; return ( @@ -121,7 +133,7 @@ const Row = memo(function Row(props: { return ( {row.groupedEntries.map((entry) => ( - + ))} ); @@ -129,9 +141,7 @@ const Row = memo(function Row(props: { return ( {row.thought?.detail ? {`∴ ${liveThoughtLine(row.thought.detail)}`} : null} - openChild(row.entry, props.onOpenThread)}> - {`${row.active ? "◐" : glyphFor(row.entry)} ${liveWorkEntryLabel(row.entry, workspaceRoot, row.active)}${childThreadOf(row.entry) ? " ↗" : ""}`} - + ); case "working": { @@ -166,25 +176,35 @@ const USER_FOLD_LINES = 8; const USER_FOLD_CHARS = 600; /** The web's user bubble: right-aligned, at most 80% wide, folded past 8 lines or 600 characters. */ -function UserMessage({ text }: { readonly text: string }) { +function UserMessage({ text, messageId, selected }: { readonly text: string; readonly messageId: string; readonly selected: boolean }) { const trimmed = text.trim(); const lines = trimmed.split("\n"); let shown = lines.slice(0, USER_FOLD_LINES).join("\n"); if (shown.length > USER_FOLD_CHARS) shown = `${shown.slice(0, USER_FOLD_CHARS).trimEnd()}…`; const folded = shown.length < trimmed.length; return ( - + {shown} {folded ? {`… ${Math.max(1, lines.length - shown.split("\n").length)} more lines`} : null} ); } -function WorkEntry({ entry, label, onOpenThread }: { readonly entry: WorkLogEntry; readonly label: string; readonly onOpenThread: (threadId: ThreadId) => void }) { +function WorkEntry({ entry, expanded: groupExpanded, label, onOpenThread, session, streamCommandOutput, scrollRef }: { readonly entry: WorkLogEntry; readonly expanded: boolean; readonly label: string; readonly onOpenThread: (threadId: ThreadId) => void; readonly session: T3Session; readonly streamCommandOutput: boolean; readonly scrollRef: RefObject }) { + const [open, setExpanded] = useState(null); + const expanded = open ?? groupExpanded; + const item = entry.structuredPayload; + const command = item?.type === "command_execution" ? item : null; + const projected = entry.projectedItem; const failed = workEntryDisplayIndicatesToolFailure(entry); const child = childThreadOf(entry); const tone = failed || entry.tone === "error" ? colors.bad : child ? colors.accent : entry.tone === "thinking" ? colors.faint : colors.muted; const text = {`${failed ? "✕" : glyphFor(entry)} ${firstLine(label)}${child ? " ↗" : ""}`}; + if (command) return + setExpanded(!expanded)}>{expanded ? "⌄ " : "› "}{text} + {expanded && streamCommandOutput && projected ? + : expanded ? {command.output || "No output."} : null} + ; return child ? onOpenThread(child)}>{text} : text; } @@ -194,11 +214,6 @@ export function childThreadOf(entry: WorkLogEntry): ThreadId | null { return item?.type === "subagent" ? (item.childThreadId ?? null) : null; } -function openChild(entry: WorkLogEntry, onOpenThread: (threadId: ThreadId) => void): void { - const child = childThreadOf(entry); - if (child) onOpenThread(child); -} - function EventRow({ item, pending }: { readonly item: MessagesTimelineRow extends infer R ? (R extends { kind: "event"; projectedItem: { item: infer I } } ? I : never) : never; readonly pending: boolean }) { if (item.type === "approval_request" && pending) { return ( diff --git a/src/ui/useDiffContext.ts b/src/ui/useDiffContext.ts new file mode 100644 index 0000000..a648063 --- /dev/null +++ b/src/ui/useDiffContext.ts @@ -0,0 +1,45 @@ +import type { KeyEvent, ScrollBoxRenderable } from "@opentui/core"; +import { useEffect, useMemo, useRef, useState, type RefObject } from "react"; +import type { T3Session } from "../client/session.ts"; +import { splitPatch, wholeFilePatch } from "../model/diffs.ts"; +import type { DiffState } from "./DiffView.tsx"; + +/** Full-file expansion is loaded only on request and belongs to this diff selection. */ +export function useDiffContext(session: T3Session, diff: DiffState | null, scrollRef: RefObject) { + const current = useRef(diff); + current.current = diff; + const files = useMemo(() => splitPatch(diff?.patch ?? ""), [diff?.patch]); + const [selected, setSelected] = useState(0); + const [expanded, setExpanded] = useState>({}); + useEffect(() => { setSelected(0); setExpanded({}); }, [diff]); + const expand = () => { + const file = files[selected]; + if (!file || !diff?.source) return; + if (expanded[file.path]?.patch) { + setExpanded((old) => { const next = { ...old }; delete next[file.path]; return next; }); + return; + } + if (expanded[file.path] && !expanded[file.path]?.error) return; + const selection = diff; + setExpanded((old) => ({ ...old, [file.path]: {} })); + session.diffFileContents({ ...diff.source, changeType: file.changeType, oldPath: file.oldPath, newPath: file.path }).then( + (contents) => current.current === selection && setExpanded((old) => ({ ...old, [file.path]: { patch: wholeFilePatch(file, contents) } })), + (error) => current.current === selection && setExpanded((old) => ({ ...old, [file.path]: { error: error instanceof Error ? error.message : String(error) } })), + ); + }; + const move = (direction: -1 | 1) => { + const next = Math.max(0, Math.min(files.length - 1, selected + direction)); + setSelected(next); + scrollRef.current?.scrollChildIntoView(`diff-file-${next}`); + }; + const onKey = (key: KeyEvent): boolean => { + if (!diff) return false; + if (key.name === "[" || key.name === "]") { + move(key.name === "[" ? -1 : 1); + return true; + } + if (key.name === "x" || key.name === "return") { expand(); return true; } + return false; + }; + return { selected, expanded, onKey, move, expand }; +} diff --git a/src/ui/useTurns.ts b/src/ui/useTurns.ts new file mode 100644 index 0000000..3dcb6a2 --- /dev/null +++ b/src/ui/useTurns.ts @@ -0,0 +1,119 @@ +import type { KeyEvent, ScrollBoxRenderable } from "@opentui/core"; +import type { OrchestrationV2ThreadProjection, ServerConfig, ThreadId } from "@t3tools/contracts"; +import { useEffect, useRef, useState, type Dispatch, type RefObject, type SetStateAction } from "react"; +import type { T3Session } from "../client/session.ts"; +import type { PaletteCommand } from "../model/palette.ts"; +import type { Timeline } from "../model/timeline.ts"; +import { recallableComposerPrompt } from "../../vendor/t3code/apps/web/src/components/chat/composerPromptHistory.ts"; +import { adjacentTurn, diffTurn, findRevertCheckpoint, type TurnCheckpoint } from "../model/turns.ts"; +import type { Confirmation } from "./ConfirmBar.tsx"; +import type { DiffState } from "./DiffView.tsx"; +import { useDiffContext } from "./useDiffContext.ts"; + +/** Turn navigation, checkpoint review and rewind stay local to the open conversation. */ +export function useTurns(input: { + readonly session: T3Session; + readonly threadId: ThreadId | undefined; + readonly projection: OrchestrationV2ThreadProjection | null | undefined; + readonly timeline: Timeline | null; + readonly config: ServerConfig | null; + readonly cwd: string | null; + readonly ignoreWhitespace: boolean; + readonly enabled: boolean; + readonly diff: DiffState | null; + readonly setDiff: Dispatch>; + readonly scrollRef: RefObject; + readonly confirm: (confirmation: Confirmation) => void; + readonly say: (text: string, bad?: boolean) => void; + readonly showConversation: () => void; + readonly restorePrompt: (threadId: ThreadId, text: string) => void; +}) { + const [cursor, setCursor] = useState<{ threadId: ThreadId; messageId: string } | null>(null); + const [reverting, setReverting] = useState(false); + const currentThread = useRef(input.threadId); + currentThread.current = input.threadId; + const turns = input.timeline?.turns ?? []; + const selectedMessageId = input.enabled && cursor !== null && cursor.threadId === input.threadId && turns.some((turn) => turn.messageId === cursor.messageId) ? cursor.messageId : null; + const selected = turns.find((turn) => turn.messageId === selectedMessageId); + const diffContext = useDiffContext(input.session, input.diff, input.scrollRef); + useEffect(() => { setCursor(null); }, [input.threadId]); + + const move = (direction: -1 | 1) => { + const next = adjacentTurn(turns, selectedMessageId, direction); + if (!next || !input.threadId) return; + input.setDiff(null); + input.showConversation(); + setCursor({ threadId: input.threadId, messageId: next.messageId }); + setTimeout(() => input.scrollRef.current?.scrollChildIntoView(`turn-${next.messageId}`), 0); + }; + const openDiff = (fullThread: boolean) => { + const checkpoint = fullThread + ? turns.map((turn) => turn.checkpoint).filter((checkpoint): checkpoint is TurnCheckpoint => checkpoint?.status === "ready").sort((a, b) => b.checkpointTurnCount - a.checkpointTurnCount)[0] + : diffTurn(turns, selectedMessageId); + if (!input.threadId || !input.cwd || !checkpoint) return input.say("No changes from this turn."); + const toTurnCount = checkpoint.checkpointTurnCount; + const state: DiffState = { cwd: input.cwd, path: null, title: fullThread ? "Changes" : `Turn ${toTurnCount}`, status: "loading" }; + input.setDiff(state); + input.showConversation(); + const request = { threadId: input.threadId, toTurnCount, ignoreWhitespace: input.ignoreWhitespace }; + const pending = fullThread ? input.session.fullThreadDiff(request) : input.session.turnDiff({ ...request, fromTurnCount: Math.max(0, toTurnCount - 1) }); + pending.then( + (result) => input.setDiff((current) => current === state ? { ...state, status: "ready", patch: result.diff } : current), + (error) => input.setDiff((current) => current === state ? { ...state, status: "error", error: messageOf(error) } : current), + ); + }; + const revert = (restoreFiles = false) => { + const projection = input.projection; + if (!selected || !projection || reverting) return input.say("Select a turn with [ or ] first."); + const provider = input.config?.providers.find((provider) => provider.instanceId === projection.thread.providerInstanceId); + if (!provider || provider.supportsConversationRollback === false) return input.say("This provider does not support reverting conversation history. Start a new thread instead.", true); + if (input.timeline?.isWorking) return input.say("Interrupt the current turn before reverting checkpoints.", true); + const turnCount = selected.revertTurnCount; + const checkpoint = turnCount === undefined ? undefined : findRevertCheckpoint(projection.checkpoints, turnCount); + if (turnCount === undefined || !checkpoint) return input.say("This message has no available checkpoint to rewind to.", true); + if (selected.hasAttachments) return input.say("Use the T3 Code app to rewind a message with attachments.", true); + input.confirm({ + title: "Edit from here?", + detail: "Rewind chat to before this message. Your prompt returns to the composer. “Revert files too” also undoes your own edits.", + confirmLabel: restoreFiles ? "Revert files too" : "Revert and keep changes", + run: () => { + setReverting(true); + input.session.rewind(projection, checkpoint, turnCount, restoreFiles).then(() => { + input.restorePrompt(projection.thread.id, recallableComposerPrompt(selected.text)); + if (currentThread.current === projection.thread.id) { setCursor(null); input.setDiff(null); } + input.say("Thread rewound"); + }, (error) => input.say(`Could not rewind: ${messageOf(error)}`, true)).finally(() => setReverting(false)); + }, + }); + }; + const commands: (PaletteCommand & { readonly run: () => void })[] = input.enabled && turns.length ? [ + { id: "previous-turn", title: "Select previous turn", shortcut: "[", keywords: ["turn", "cursor"], run: () => move(-1) }, + { id: "next-turn", title: "Select next turn", shortcut: "]", keywords: ["turn", "cursor"], run: () => move(1) }, + { id: "turn-diff", title: "View changes from this turn", shortcut: "D", keywords: ["diff", "checkpoint"], run: () => openDiff(false) }, + { id: "thread-diff", title: "View all changes in this thread", keywords: ["diff", "checkpoint"], run: () => openDiff(true) }, + ...(selected ? [ + { id: "turn-revert", title: "Revert to this turn", shortcut: "R", keywords: ["rollback", "rewind", "keep changes"], run: () => revert() }, + { id: "turn-revert-files", title: "Revert files too", keywords: ["rollback", "rewind", "turn"], run: () => revert(true) }, + { id: "turn-clear", title: "Clear turn selection", shortcut: "esc", run: () => setCursor(null) }, + ] : []), + ] : []; + if (input.diff) { + commands.push( + { id: "diff-previous-file", title: "Previous changed file", shortcut: "[", keywords: ["diff"], run: () => diffContext.move(-1) }, + { id: "diff-next-file", title: "Next changed file", shortcut: "]", keywords: ["diff"], run: () => diffContext.move(1) }, + ); + if (input.diff.source) commands.push({ id: "diff-context", title: "Show whole file / collapse context", shortcut: "x", keywords: ["diff", "expand", "unchanged"], run: diffContext.expand }); + } + const onKey = (key: KeyEvent): boolean => { + if (key.ctrl || key.meta || !input.enabled) return false; + if (diffContext.onKey(key)) return true; + if (key.name === "[" || key.name === "]") { move(key.name === "[" ? -1 : 1); return true; } + if (key.name.toLowerCase() === "d" && key.shift) { openDiff(false); return true; } + if (key.name.toLowerCase() === "r" && key.shift) { revert(); return true; } + if (key.name === "escape" && !input.diff && selectedMessageId) { setCursor(null); return true; } + return false; + }; + return { selectedMessageId, commands, onKey, diffContext }; +} + +function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error); } diff --git a/test/diffs.test.ts b/test/diffs.test.ts new file mode 100644 index 0000000..5614268 --- /dev/null +++ b/test/diffs.test.ts @@ -0,0 +1,29 @@ +import { expect, test } from "bun:test"; +import { parsePatch } from "diff"; +import { splitPatch, wholeFilePatch } from "../src/model/diffs.ts"; + +const changed = "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -2 +2 @@\n-old\n+new\n"; + +test("diff files retain old paths and change types for contents requests", () => { + const files = splitPatch(changed + "diff --git a/old.ts b/new.ts\nsimilarity index 100%\nrename from old.ts\nrename to new.ts\n" + "diff --git a/gone.ts b/gone.ts\ndeleted file mode 100644\n--- a/gone.ts\n+++ /dev/null\n@@ -1 +0,0 @@\n-gone\n" + "diff --git a/add.ts b/add.ts\nnew file mode 100644\n--- /dev/null\n+++ b/add.ts\n@@ -0,0 +1 @@\n+added\n"); + expect(files.map(({ path, oldPath, changeType }) => ({ path, oldPath, changeType }))).toEqual([ + { path: "a.ts", oldPath: "a.ts", changeType: "change" }, { path: "new.ts", oldPath: "old.ts", changeType: "rename-pure" }, + { path: "gone.ts", oldPath: "gone.ts", changeType: "deleted" }, { path: "add.ts", oldPath: "add.ts", changeType: "new" }, + ]); +}); + +test("whole-file expansion preserves unchanged context on both sides of the hunk", () => { + const patch = wholeFilePatch(splitPatch(changed)[0]!, { oldContents: "before\nold\nafter\n", newContents: "before\nnew\nafter\n" }); + expect(parsePatch(patch)[0]?.hunks[0]).toMatchObject({ oldStart: 1, oldLines: 3, newStart: 1, newLines: 3, lines: [" before", "-old", "+new", " after"] }); +}); + +test("truncated patches keep their file identity without parsing an incomplete hunk", () => { + expect(splitPatch(changed.slice(0, -4))[0]?.path).toBe("a.ts"); + expect(splitPatch("diff --git a/a.ts b/a.ts\n--- a/a.ts\n")[0]?.path).toBe("a.ts"); +}); + +test("whole-file expansion can show a pure rename with identical contents", () => { + const file = splitPatch("diff --git a/old.ts b/new.ts\nsimilarity index 100%\nrename from old.ts\nrename to new.ts\n")[0]!; + const patch = wholeFilePatch(file, { oldContents: "unchanged\n", newContents: "unchanged\n" }); + expect(parsePatch(patch)[0]?.hunks[0]?.lines).toEqual([" unchanged"]); +}); diff --git a/test/turns.test.ts b/test/turns.test.ts new file mode 100644 index 0000000..e06207f --- /dev/null +++ b/test/turns.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, test } from "bun:test"; +import { CheckpointId, CheckpointRef, CheckpointScopeId, MessageId, NodeId, ProviderSessionId, ProviderThreadId, ProviderTurnId, RunAttemptId, RunId, type OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import type { TimelineEntriesProjection } from "../vendor/t3code/apps/web/src/session-logic.ts"; +import { v2Now, v2Projection } from "../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts"; +import { adjacentTurn, diffTurn, findRevertCheckpoint, turnTargets } from "../src/model/turns.ts"; + +const providerThreadId = ProviderThreadId.make("pt"); +const scopeId = CheckpointScopeId.make("scope"); +function checkpoint(ordinal: number, runOrdinal: number | null = ordinal) { + return { id: CheckpointId.make(`cp-${ordinal}`), threadId: v2Projection.thread.id, scopeId, runId: runOrdinal === null ? null : RunId.make(`run-${runOrdinal}`), nodeId: NodeId.make("node"), parentCheckpointId: null, ordinalWithinScope: ordinal, appRunOrdinal: runOrdinal, ref: CheckpointRef.make(`refs/checkpoints/${ordinal}`), status: "ready" as const, + files: ordinal === 2 ? [] : [{ path: "file.ts", kind: "modified", additions: 1, deletions: 0 }], capturedAt: v2Now }; +} +function entries(): TimelineEntriesProjection["entries"] { + return [1, 2, 5].flatMap((ordinal) => [{ kind: "message" as const, id: `user-${ordinal}`, createdAt: "2026-06-20T00:00:00.000Z", message: { id: MessageId.make(`user-${ordinal}`), role: "user" as const, text: `prompt ${ordinal}`, runId: RunId.make(`run-${ordinal}`), streaming: false, inputIntent: "turn_start" as const, createdAt: "2026-06-20T00:00:00.000Z", updatedAt: "2026-06-20T00:00:00.000Z" } }]); +} +function projection(): OrchestrationV2ThreadProjection { + const runs = [1, 2, 5].map((ordinal) => ({ id: RunId.make(`run-${ordinal}`), ordinal, activeAttemptId: RunAttemptId.make(`attempt-${ordinal}`), status: "completed" })); + return { ...v2Projection, thread: { ...v2Projection.thread, activeProviderThreadId: providerThreadId }, checkpoints: [checkpoint(0, null), checkpoint(1), checkpoint(2), checkpoint(3, 5)], + runs, attempts: [], providerThreads: [{ id: providerThreadId, providerSessionId: ProviderSessionId.make("session"), providerInstanceId: v2Projection.thread.modelSelection.instanceId }], + providerTurns: runs.map((run) => ({ id: ProviderTurnId.make(`pt-${run.ordinal}`), runAttemptId: run.activeAttemptId, ordinal: run.ordinal, providerThreadId })), + } as unknown as OrchestrationV2ThreadProjection; +} + +describe("turn cursor and checkpoint targets", () => { + test("navigates by message identity after earlier turns load", () => { + const turns = turnTargets(projection(), entries(), null, true); + expect(adjacentTurn(turns, null, -1)?.messageId).toBe(MessageId.make("user-5")); + expect(adjacentTurn(turns, "user-5", -1)?.messageId).toBe(MessageId.make("user-2")); + expect(adjacentTurn(turns, "user-1", -1)?.messageId).toBe(MessageId.make("user-1")); + expect(adjacentTurn(turns, "user-5", 1)?.messageId).toBe(MessageId.make("user-5")); + expect(adjacentTurn([], null, -1)).toBeUndefined(); + }); + test("rewinds before the prompt, using visible predecessors across ordinal gaps", () => { + const turns = turnTargets(projection(), entries(), null, true); + expect(turns.map((turn) => turn.revertTurnCount)).toEqual([0, 1, 2]); + expect(findRevertCheckpoint(projection().checkpoints, turns[2]!.revertTurnCount!)?.id).toBe(CheckpointId.make("cp-2")); + }); + test("does not mistake the first message in paged history for the thread start", () => { + const turns = turnTargets(projection(), entries().slice(1), null, false); + expect(turns.map((turn) => turn.revertTurnCount)).toEqual([undefined, 2]); + }); + test("does not offer a running turn or a detached provider conversation for rollback", () => { + expect(turnTargets(projection(), entries(), RunId.make("run-5"), true)[2]?.revertTurnCount).toBeUndefined(); + expect(turnTargets({ ...projection(), providerThreads: [] }, entries(), null, true).every((turn) => turn.revertTurnCount === undefined)).toBe(true); + }); + test("defaults to the latest changed turn; a selection never falls back to another turn", () => { + const turns = turnTargets(projection(), entries(), null, true); + expect(diffTurn(turns, null)?.checkpointTurnCount).toBe(5); + expect(diffTurn(turns.slice(0, 2), null)?.checkpointTurnCount).toBe(1); + expect(diffTurn(turns, "user-2")?.checkpointTurnCount).toBe(2); + expect(diffTurn(turns, "missing")).toBeUndefined(); + }); + test("keeps only one anchor for a turn with steering messages", () => { + const all = entries(); + const first = all[0]!; + expect(turnTargets(projection(), [first, first, ...all.slice(1)], null, true)).toHaveLength(3); + }); +}); diff --git a/test/turnsSession.test.ts b/test/turnsSession.test.ts new file mode 100644 index 0000000..2179ae6 --- /dev/null +++ b/test/turnsSession.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, test } from "bun:test"; +import { CheckpointId, CheckpointScopeId, OrchestrationGetFullThreadDiffInput, OrchestrationGetTurnDiffInput, OrchestrationV2Command, ProviderThreadId, ReviewDiffFileContentsInput, RunId, ThreadId, TurnItemId, type OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import { T3Session, type ThreadState } from "../src/client/session.ts"; +import { v2Projection } from "../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts"; + +const threadId = ThreadId.make("thread-1"); +const checkpoint = { id: CheckpointId.make("checkpoint-before-selected-prompt"), scopeId: CheckpointScopeId.make("root-scope") }; + +describe("turn RPCs without a server", () => { + test("both rollback choices dispatch the captured checkpoint and validate against the contract", async () => { + const session = new T3Session(); + const sent: unknown[] = []; + Object.assign(session, { dispatch: async (command: unknown) => { sent.push(command); } }); + await session.rollback(threadId, checkpoint, false); + await session.rollback(threadId, checkpoint, true); + expect(sent.every(Schema.is(OrchestrationV2Command))).toBe(true); + expect(sent[0]).toMatchObject({ type: "checkpoint.rollback", threadId, checkpointId: checkpoint.id, scopeId: checkpoint.scopeId, restoreFiles: false }); + expect(sent[1]).toMatchObject({ restoreFiles: true }); + expect(sent[0]).not.toHaveProperty("turnCount"); + }); + + test("checkpoint ranges and file-contents requests match the RPC schemas", async () => { + const session = new T3Session(); + const sent: { method: string; input: unknown }[] = []; + const rpc = Object.fromEntries(["orchestration.getTurnDiff", "orchestration.getFullThreadDiff", "review.getDiffFileContents"].map((method) => [method, (input: unknown) => { sent.push({ method, input }); return Effect.succeed({ diff: "", oldContents: "old", newContents: "new" }); }])); + Object.assign(session, { connection: { rpc } }); + await session.turnDiff({ threadId, fromTurnCount: 4, toTurnCount: 5, ignoreWhitespace: true }); + await session.fullThreadDiff({ threadId, toTurnCount: 5, ignoreWhitespace: false }); + await session.diffFileContents({ cwd: "/workspace", sourceKind: "working-tree", baseRef: "HEAD", headRef: null, oldPath: "old.ts", newPath: "new.ts", changeType: "rename-changed" }); + expect(Schema.is(OrchestrationGetTurnDiffInput)(sent[0]?.input)).toBe(true); + expect(Schema.is(OrchestrationGetFullThreadDiffInput)(sent[1]?.input)).toBe(true); + expect(Schema.is(ReviewDiffFileContentsInput)(sent[2]?.input)).toBe(true); + expect(sent.map((request) => request.method)).toEqual(["orchestration.getTurnDiff", "orchestration.getFullThreadDiff", "review.getDiffFileContents"]); + }); + + test("expanded output normalizes frames and unsubscribes immediately", async () => { + const session = new T3Session(); + let finishStream!: () => void; + const finished = new Promise((resolve) => { finishStream = resolve; }); + let receive!: () => void; + const received = new Promise((resolve) => { receive = resolve; }); + const outputs: string[] = []; + const stream = Stream.concat(Stream.make( + { kind: "replace" as const, text: "first\n", running: true, truncated: false }, + { kind: "append" as const, text: "second", running: true, truncated: false }, + ), Stream.never).pipe(Stream.ensuring(Effect.sync(finishStream))); + Object.assign(session, { connection: { rpc: { "orchestration.subscribeCommandOutput": (input: unknown) => { + expect(input).toEqual({ threadId, itemId: TurnItemId.make("command-1") }); + return stream; + } } }, runInScope: Effect.runFork }); + const close = session.watchCommandOutput(threadId, TurnItemId.make("command-1"), (view) => { outputs.push(view.output.text); if (outputs.length === 2) receive(); }, (error) => { throw new Error(error); }); + await received; + close(); + await finished; + expect(outputs).toEqual(["first\n", "first\nsecond"]); + }); +}); + +function rewindSession() { + const session = new T3Session(); + const providerThreadId = ProviderThreadId.make("provider-thread"); + const initial = { ...v2Projection, thread: { ...v2Projection.thread, activeProviderThreadId: providerThreadId }, runs: [{ id: RunId.make("run-5"), ordinal: 5, status: "completed" }], providerThreads: [{ id: providerThreadId, lastRunOrdinal: 5 }] } as unknown as OrchestrationV2ThreadProjection; + let observe!: (state: ThreadState) => void; + let command: { commandId: string } | undefined; + let closed = false; + Object.assign(session, { watchThread: (_: unknown, listener: (state: ThreadState) => void) => { observe = listener; return () => { closed = true; }; }, dispatch: async (next: { commandId: string }) => { command = next; } }); + const emit = (projection: OrchestrationV2ThreadProjection) => observe({ status: "live", projection, history: { cursor: null, hasMore: false, loading: false } }); + return { session, initial, emit, command: () => command!, closed: () => closed }; +} + +test("rewind waits for the rolled-back suffix and the provider conversation, not just command acceptance", async () => { + const rig = rewindSession(); + let resolved = false; + const pending = rig.session.rewind(rig.initial, checkpoint, 2, false).then(() => { resolved = true; }); + await Promise.resolve(); + rig.emit(rig.initial); + await Promise.resolve(); + expect(resolved).toBe(false); + const next = { ...rig.initial, runs: rig.initial.runs.map((run) => ({ ...run, status: "rolled_back" as const })) }; + rig.emit(next); + await Promise.resolve(); + expect(resolved).toBe(false); + rig.emit({ ...next, providerThreads: next.providerThreads.map((thread) => ({ ...thread, lastRunOrdinal: 2 })) }); + await pending; + expect(resolved).toBe(true); + expect(rig.closed()).toBe(true); +}); + +test("rewind reports the matching server failure and closes its listener", async () => { + const rig = rewindSession(); + const pending = rig.session.rewind(rig.initial, checkpoint, 2, true); + rig.emit({ ...rig.initial, thread: { ...rig.initial.thread, rollbackFailure: { requestId: rig.command().commandId, message: "cannot restore" } } } as OrchestrationV2ThreadProjection); + await expect(pending).rejects.toThrow("cannot restore"); + expect(rig.closed()).toBe(true); +});