Merge turns: turn cursor, turn diffs, whole-file context, rewind, live command output

# Conflicts:
#	README.md
#	src/ui/App.tsx
#	src/ui/ThreadView.tsx
This commit is contained in:
Callum Alpass committed 2026-11-02 20:45:09 +11:00
commit 4fe103b657
16 files changed
+633 -40

No files matched your search

+23 -6
View File
@@ -41,6 +41,7 @@ import { useWorkspace } from "./useWorkspace.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";
import { useQueue } from "./useQueue.ts";
import { useSecretRequest } from "./useSecretRequest.ts";
@@ -182,6 +183,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) ?? library.archive?.threads.find((thread) => thread.id === threadId) ?? library.merged?.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);
@@ -224,10 +227,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: expandAll || mode === "find" }, previous);
const next = buildTimeline(thread.projection, { expandAll: expandAll || mode === "find", historyComplete: !thread.history.hasMore }, previous);
previousTimeline.current = { id: watchedId, timeline: next };
return next;
}, [thread?.projection, watchedId, expandAll, mode === "find"]);
}, [thread?.projection, thread?.history.hasMore, watchedId, expandAll, mode === "find"]);
const current = watchedId === threadId ? timeline : null;
const find = useThreadFind(session, watchedId, thread, current, mode === "find");
const openFind = () => { setDiff(null); setSettingsIndex(null); setMode("find"); };
@@ -384,7 +387,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)),
);
};
@@ -915,8 +918,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" });
@@ -1124,7 +1137,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
}
return;
}
if (secret.key(key, mode === "nav", Boolean(pendingInput))) return key.preventDefault();
if (secret.key(key, mode === "nav" && !diff, Boolean(pendingInput))) return key.preventDefault();
if (queue.key(key, mode === "nav" ? "nav" : mode === "input" ? "input" : "other")) return key.preventDefault();
if (globalKey(key)) return key.preventDefault();
const digit = /^[1-9]$/.test(key.name) && !key.ctrl && !key.meta ? Number(key.name) - 1 : -1;
@@ -1193,6 +1206,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
if (workspace.key(key)) return;
if (mode === "nav" && library.key(key, threadId)) return key.preventDefault();
if (mode === "nav" && key.name === "f" && threadId && !draft) return openFind(), key.preventDefault();
if (mode === "nav" && turns.onKey(key)) return key.preventDefault();
switch (key.name) {
case "q":
if (diff) return setDiff(null);
@@ -1373,7 +1387,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 && mode !== "find" ? (
@@ -1389,6 +1403,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
timeline={current}
findQuery={find.open ? find.query.trim() : ""}
findMatch={find.match}
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" };
+28 -15
View File
@@ -2,13 +2,14 @@ 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 { findTextSegments } from "../model/search.ts";
import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
import type { OrchestrationV2SearchThreadResult } from "@t3tools/contracts";
import { FindText } from "./FindText.tsx";
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";
@@ -21,6 +22,9 @@ export function ThreadView(props: {
readonly timeline: Timeline | null;
readonly findQuery?: string | undefined;
readonly findMatch?: OrchestrationV2SearchThreadResult["match"] | undefined;
readonly selectedMessageId: string | null;
readonly session: T3Session;
readonly streamCommandOutput: boolean;
readonly history: ThreadHistory | null;
readonly loading: boolean;
readonly error?: string | undefined;
@@ -57,6 +61,9 @@ 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}
findQuery={props.findQuery ?? ""}
activeOccurrence={props.findMatch?.entryId === row.id ? props.findMatch.occurrence : null}
@@ -94,6 +101,9 @@ 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 findQuery: string;
readonly activeOccurrence: number | null;
@@ -111,7 +121,7 @@ const Row = memo(function Row(props: {
const segments = findTextSegments(message.text, message.role === "user");
if (segments.some((segment) => findThreadSearchOccurrences(segment, props.findQuery).length > 0)) return <FindText segments={segments} query={props.findQuery} activeOccurrence={props.activeOccurrence} scrollRef={props.scrollRef} />;
}
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}>
@@ -137,7 +147,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>
);
@@ -145,9 +155,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": {
@@ -183,25 +191,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;
}
@@ -211,11 +229,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); }