Add turn navigation, checkpoint diffs and confirmed rewind

This commit is contained in:
Callum Alpass committed 2026-11-02 20:42:55 +11:00
1 parent 43347d1d58
commit 7eb976f7ac
16 files changed
+634 -39

No files matched your search

+68
View File
@@ -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<CommandOutputView>, onError: Listener<string>): () => 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<OrchestrationV2Checkpoint, "id" | "scopeId">, restoreFiles: boolean, commandId = newCommandId()): Promise<void> {
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<OrchestrationV2Checkpoint, "id" | "scopeId">, turnCount: number, restoreFiles: boolean): Promise<void> {
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<void>((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<GitActionProgressEvent>): Promise<GitRunStackedActionResult> {
const rpc = this.requireConnection().rpc;
+34
View File
@@ -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`;
}
+4 -1
View File
@@ -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<never>();
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 },
+67
View File
@@ -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<typeof deriveThreadCheckpointSummaries>[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<RunId>();
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<number> {
const available = new Set<number>();
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))];
}
+22 -5
View File
@@ -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<PaletteCommand, "id" | "title"> = {}) => 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 ? (
<DiffView diff={diff} scrollRef={scrollRef} />
<DiffView diff={diff} scrollRef={scrollRef} selected={turns.diffContext.selected} expanded={turns.diffContext.expanded} />
) : draft ? (
<DraftView lines={draftLines} />
) : 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}
+36
View File
@@ -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<ScrollBoxRenderable | null> }) {
const box = useRef<BoxRenderable | null>(null);
const [visible, setVisible] = useState(false);
const [view, setView] = useState<CommandOutputView | null>(null);
const [error, setError] = useState<string | null>(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 <box ref={box} flexDirection="column" paddingLeft={2}>
{error ? <text fg={colors.bad}>{`Could not load output: ${error}`}</text> : null}
{view?.output.truncated || lines.length > 12 ? <text fg={colors.faint}>Earlier output not shown</text> : null}
<text fg={colors.muted}>{lines.slice(-12).join("\n") || (view ? view.running ? "Waiting for output…" : "No output." : "Loading output…")}</text>
</box>;
}
+15 -16
View File
@@ -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<ReviewDiffFileContentsInput, "cwd" | "sourceKind" | "baseRef" | "headRef">;
/** 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<ScrollBoxRenderable | null> }) {
/** Working-tree or checkpoint changes through the same unified diff renderer. */
export function DiffView(props: { readonly diff: DiffState; readonly scrollRef: RefObject<ScrollBoxRenderable | null>; readonly selected: number; readonly expanded: Readonly<Record<string, { patch?: string; error?: string }>> }) {
const { diff } = props;
const files = diff.patch ? splitPatch(diff.patch) : [];
return (
<box flexGrow={1} minHeight={0} flexDirection="column" paddingLeft={1} paddingRight={1}>
<box flexDirection="row" flexShrink={0} height={1}>
<text fg={colors.muted}>Uncommitted / </text>
<text fg={colors.muted}>{diff.title ?? "Uncommitted"} / </text>
<text fg={colors.text}>
<strong>{diff.path ?? `${files.length} ${files.length === 1 ? "file" : "files"}`}</strong>
</text>
<box flexGrow={1} />
<text fg={colors.faint}>esc close</text>
<text fg={colors.faint}>{diff.source ? "[/] file · x whole file / collapse · esc close" : "[/] file · esc close"}</text>
</box>
{diff.status === "loading" ? <text fg={colors.muted}>Loading diff…</text> : null}
{diff.status === "error" ? <text fg={colors.bad}>{`Could not load the diff: ${diff.error ?? "unknown error"}`}</text> : null}
{diff.status === "ready" && files.length === 0 ? <text fg={colors.muted}>No changes.</text> : null}
{diff.truncated ? <text fg={colors.warn}>The diff was too large and is cut short.</text> : null}
<scrollbox ref={props.scrollRef} flexGrow={1} minHeight={0}>
{files.map((file) => (
<box key={file.path} flexDirection="column" marginTop={1}>
{diff.path ? null : <text fg={colors.accent}>{file.path}</text>}
{files.map((file, index) => (
<box key={file.path} id={`diff-file-${index}`} flexDirection="column" marginTop={1}>
<text fg={index === props.selected ? colors.accent : colors.muted}>{`${index === props.selected ? "▸ " : " "}${file.path}`}</text>
{props.expanded[file.path] && !props.expanded[file.path]?.patch ? <text fg={props.expanded[file.path]?.error ? colors.bad : colors.muted}>{props.expanded[file.path]?.error ?? "Loading full file…"}</text> : null}
<diff
diff={file.patch}
diff={props.expanded[file.path]?.patch ?? file.patch}
view="unified"
{...(filetypeOf(file.path) ? { filetype: filetypeOf(file.path)! } : {})}
syntaxStyle={getMarkdownStyle()}
@@ -58,13 +63,7 @@ export function DiffView(props: { readonly diff: DiffState; readonly scrollRef:
);
}
/** Splits a multi-file patch at each `diff --git` header. */
export function splitPatch(patch: string): { path: string; patch: string }[] {
return patch
.split(/^(?=diff --git )/m)
.filter((chunk) => 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<string, string> = { 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" };
+30 -15
View File
@@ -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: {
<Row
key={row.id}
row={row}
selected={row.kind === "message" && row.message.id === props.selectedMessageId}
session={props.session}
streamCommandOutput={props.streamCommandOutput}
scrollRef={props.scrollRef}
pending={row.kind === "event" && pendingIds.has(eventRequestId(row) ?? "")}
workspaceRoot={props.workspaceRoot}
now={row.kind === "working" ? props.now : 0}
@@ -85,6 +93,10 @@ function Divider({ label, color }: { readonly label: string; readonly color: str
*/
const Row = memo(function Row(props: {
readonly row: MessagesTimelineRow;
readonly selected: boolean;
readonly session: T3Session;
readonly streamCommandOutput: boolean;
readonly scrollRef: RefObject<ScrollBoxRenderable | null>;
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 <UserMessage text={message.text} />;
if (message.role === "user") return <UserMessage text={message.text} messageId={message.id} selected={props.selected} />;
if (message.role === "system") return <text marginTop={1} fg={colors.muted}>{message.text}</text>;
return (
<box marginTop={1}>
@@ -121,7 +133,7 @@ const Row = memo(function Row(props: {
return (
<box marginTop={row.continuesWorkLog ? 0 : 1} flexDirection="column">
{row.groupedEntries.map((entry) => (
<WorkEntry key={entry.id} entry={entry} label={row.displayLabel && row.groupedEntries.length === 1 ? row.displayLabel : workEntryDisplayLabel(entry, workspaceRoot)} onOpenThread={props.onOpenThread} />
<WorkEntry key={entry.id} entry={entry} expanded={row.isExpandedToolGroup} label={row.displayLabel && row.groupedEntries.length === 1 ? row.displayLabel : workEntryDisplayLabel(entry, workspaceRoot)} onOpenThread={props.onOpenThread} session={props.session} streamCommandOutput={props.streamCommandOutput} scrollRef={props.scrollRef} />
))}
</box>
);
@@ -129,9 +141,7 @@ const Row = memo(function Row(props: {
return (
<box marginTop={1} flexDirection="column">
{row.thought?.detail ? <text fg={colors.faint}>{`∴ ${liveThoughtLine(row.thought.detail)}`}</text> : null}
<box onMouseDown={() => openChild(row.entry, props.onOpenThread)}>
<text fg={row.active ? colors.info : colors.muted}>{`${row.active ? "◐" : glyphFor(row.entry)} ${liveWorkEntryLabel(row.entry, workspaceRoot, row.active)}${childThreadOf(row.entry) ? " ↗" : ""}`}</text>
</box>
<WorkEntry entry={row.entry} expanded={row.expanded} label={liveWorkEntryLabel(row.entry, workspaceRoot, row.active)} onOpenThread={props.onOpenThread} session={props.session} streamCommandOutput={props.streamCommandOutput} scrollRef={props.scrollRef} />
</box>
);
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 (
<box marginTop={1} alignSelf="flex-end" maxWidth="80%" backgroundColor={colors.userBg} paddingLeft={1} paddingRight={1} flexDirection="column">
<box id={`turn-${messageId}`} border={selected ? ["left"] : []} borderColor={colors.accent} marginTop={1} alignSelf="flex-end" maxWidth="80%" backgroundColor={colors.userBg} paddingLeft={1} paddingRight={1} flexDirection="column">
<text fg={colors.text}>{shown}</text>
{folded ? <text fg={colors.faint}>{`… ${Math.max(1, lines.length - shown.split("\n").length)} more lines`}</text> : null}
</box>
);
}
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<ScrollBoxRenderable | null> }) {
const [open, setExpanded] = useState<boolean | null>(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 = <text fg={tone}>{`${failed ? "✕" : glyphFor(entry)} ${firstLine(label)}${child ? " ↗" : ""}`}</text>;
if (command) return <box flexDirection="column">
<box flexDirection="row" onMouseDown={() => setExpanded(!expanded)}><text fg={colors.faint}>{expanded ? "⌄ " : "› "}</text>{text}</box>
{expanded && streamCommandOutput && projected ? <CommandOutput session={session} threadId={projected.sourceThreadId} itemId={projected.sourceItemId} scrollRef={scrollRef} />
: expanded ? <text fg={colors.muted}>{command.output || "No output."}</text> : null}
</box>;
return child ? <box onMouseDown={() => onOpenThread(child)}>{text}</box> : 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 (
+45
View File
@@ -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<ScrollBoxRenderable | null>) {
const current = useRef(diff);
current.current = diff;
const files = useMemo(() => splitPatch(diff?.patch ?? ""), [diff?.patch]);
const [selected, setSelected] = useState(0);
const [expanded, setExpanded] = useState<Record<string, { patch?: string; error?: string }>>({});
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 };
}
+119
View File
@@ -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<SetStateAction<DiffState | null>>;
readonly scrollRef: RefObject<ScrollBoxRenderable | null>;
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); }