Merge branch 'pane'

This commit is contained in:
callumalpass committed 2026-11-03 01:10:04 +11:00
commit 673d314e46
9 files changed
+473 -89

No files matched your search

+32 -2
View File
@@ -1,11 +1,13 @@
import { turnTargets, type TurnTarget } from "./turns.ts"; import { turnTargets, type TurnTarget } from "./turns.ts";
import type { OrchestrationV2ThreadProjection, RunAttemptId, RunId } from "@t3tools/contracts"; import type { OrchestrationV2ThreadProjection, RunAttemptId, RunId } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import { import {
deriveRunlessWorkStartedAt, deriveRunlessWorkStartedAt,
deriveThreadActivityRun, deriveThreadActivityRun,
deriveThreadStructureRuntime, deriveThreadStructureRuntime,
} from "@t3tools/client-runtime/state/thread-execution"; } from "@t3tools/client-runtime/state/thread-execution";
import { derivePendingThreadRequests, type PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests"; import { derivePendingThreadRequests, type PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints";
// The web app's own timeline derivation: tui3 shows the same rows, folds and labels. // The web app's own timeline derivation: tui3 shows the same rows, folds and labels.
import { import {
@@ -26,6 +28,12 @@ export type { MessagesTimelineRow } from "../../vendor/t3code/apps/web/src/compo
export type { WorkLogEntry } from "../../vendor/t3code/apps/web/src/session-logic.ts"; export type { WorkLogEntry } from "../../vendor/t3code/apps/web/src/session-logic.ts";
export { liveWorkEntryLabel, workEntryDisplayLabel } from "../../vendor/t3code/apps/web/src/components/chat/MessagesTimeline.logic.ts"; export { liveWorkEntryLabel, workEntryDisplayLabel } from "../../vendor/t3code/apps/web/src/components/chat/MessagesTimeline.logic.ts";
/** What a turn footer needs of its run: the model, and how long it ran. */
export interface RunMeta {
readonly model: string;
readonly durationMs: number | null;
}
export interface Timeline { export interface Timeline {
readonly rows: readonly MessagesTimelineRow[]; readonly rows: readonly MessagesTimelineRow[];
readonly pending: PendingThreadRequests; readonly pending: PendingThreadRequests;
@@ -33,18 +41,28 @@ export interface Timeline {
readonly isWorking: boolean; readonly isWorking: boolean;
/** When the current run started working, for "Working for 12s". */ /** When the current run started working, for "Working for 12s". */
readonly workStartedAt: string | null; readonly workStartedAt: string | null;
/** Footers by run, keyed as messages key their runs. */
readonly runMeta: ReadonlyMap<string, RunMeta>;
/** Carried into the next build so unchanged rows keep their identity. */ /** Carried into the next build so unchanged rows keep their identity. */
readonly cache: TimelineCache; readonly cache: TimelineCache;
} }
type TurnDiffSummaries = ReturnType<typeof deriveThreadCheckpointSummaries>;
interface TimelineCache { interface TimelineCache {
readonly entries: TimelineEntriesProjection; readonly entries: TimelineEntriesProjection;
readonly rows: { readonly input: MessagesTimelineRowsInput; readonly rows: MessagesTimelineRow[] }; readonly rows: { readonly input: MessagesTimelineRowsInput; readonly rows: MessagesTimelineRow[] };
readonly stable: StableMessagesTimelineRowsState; readonly stable: StableMessagesTimelineRowsState;
readonly expandAll: boolean; readonly expandAll: boolean;
readonly expanded: ReadonlySet<string>; readonly expanded: ReadonlySet<string>;
/** The last summaries and what they were derived from, so unchanged replies keep their row identity. */
readonly turnDiffSummaries: TurnDiffSummaries;
readonly checkpoints: OrchestrationV2ThreadProjection["checkpoints"];
readonly checkpointMessages: OrchestrationV2ThreadProjection["messages"];
} }
const sameItems = <T,>(a: readonly T[], b: readonly T[]): boolean => a.length === b.length && a.every((item, index) => item === b[index]);
/** Answers yes for every id: "expand everything" without knowing the group ids up front. */ /** Answers yes for every id: "expand everything" without knowing the group ids up front. */
class EverySet<T> extends Set<T> { class EverySet<T> extends Set<T> {
override has(): boolean { override has(): boolean {
@@ -78,6 +96,11 @@ export function buildTimeline(
const isWorking = derivePhase(runtime) === "running" || runlessStartedAt !== null; const isWorking = derivePhase(runtime) === "running" || runlessStartedAt !== null;
const workStartedAt = deriveActiveWorkStartedAt(latestRun, runtime, null) ?? runlessStartedAt; const workStartedAt = deriveActiveWorkStartedAt(latestRun, runtime, null) ?? runlessStartedAt;
const pending = derivePendingThreadRequests(projection); const pending = derivePendingThreadRequests(projection);
const previousCache = previous?.cache;
const turnDiffSummaries =
previousCache && sameItems(previousCache.checkpoints, projection.checkpoints) && sameItems(previousCache.checkpointMessages, projection.messages)
? previousCache.turnDiffSummaries
: deriveThreadCheckpointSummaries(projection);
const expanded = options.expandAll ? EVERYTHING : opened; const expanded = options.expandAll ? EVERYTHING : opened;
const rows = deriveMessagesTimelineRowsWithState( const rows = deriveMessagesTimelineRowsWithState(
{ {
@@ -92,7 +115,7 @@ export function buildTimeline(
isWorking, isWorking,
runlessWorkActive: runlessStartedAt !== null, runlessWorkActive: runlessStartedAt !== null,
activeTurnStartedAt: workStartedAt, activeTurnStartedAt: workStartedAt,
turnDiffSummaries: [], turnDiffSummaries,
supportsConversationRollback: false, supportsConversationRollback: false,
}, },
cache?.rows ?? null, cache?.rows ?? null,
@@ -104,6 +127,13 @@ export function buildTimeline(
turns: turnTargets(projection, entries.entries, isWorking ? runtime?.activeRunId ?? null : null, options.historyComplete), turns: turnTargets(projection, entries.entries, isWorking ? runtime?.activeRunId ?? null : null, options.historyComplete),
isWorking, isWorking,
workStartedAt, workStartedAt,
cache: { entries, rows, stable, expandAll: options.expandAll, expanded: opened }, runMeta: new Map(
projection.runs.map((run) => {
const started = run.workStartedAt ?? run.startedAt ?? run.requestedAt;
const durationMs = run.completedAt ? DateTime.toEpochMillis(run.completedAt) - DateTime.toEpochMillis(started) : null;
return [run.id as string, { model: run.modelSelection.model, durationMs: durationMs !== null && durationMs >= 0 ? durationMs : null }] as const;
}),
),
cache: { entries, rows, stable, expandAll: options.expandAll, expanded: opened, turnDiffSummaries, checkpoints: projection.checkpoints, checkpointMessages: projection.messages },
}; };
} }
+19 -2
View File
@@ -17,7 +17,8 @@ import { paletteEntries, paletteGroups, pickerGroups, type Picker, type PickerIt
import { pullRequestRepository } from "../model/pullRequests.ts"; import { pullRequestRepository } from "../model/pullRequests.ts";
import { serverSettingLines, settingRows } from "../model/settings.ts"; import { serverSettingLines, settingRows } from "../model/settings.ts";
import { resetCreditOutcome, usageLimits, usageSummaryLines } from "../model/usage.ts"; import { resetCreditOutcome, usageLimits, usageSummaryLines } from "../model/usage.ts";
import { buildTimeline, type Timeline } from "../model/timeline.ts"; import { buildTimeline, liveWorkEntryLabel, type Timeline } from "../model/timeline.ts";
import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models";
import { statusLabel, type Section } from "../model/threads.ts"; import { statusLabel, type Section } from "../model/threads.ts";
import { ComposerMenu } from "./ComposerMenu.tsx"; import { ComposerMenu } from "./ComposerMenu.tsx";
import { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx"; import { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx";
@@ -32,6 +33,8 @@ import { useQuestion } from "./useQuestion.ts";
import { useThreadMenu } from "./useThreadMenu.ts"; import { useThreadMenu } from "./useThreadMenu.ts";
import { editInEditor } from "./editor.ts"; import { editInEditor } from "./editor.ts";
import { Palette } from "./Palette.tsx"; import { Palette } from "./Palette.tsx";
import { ApprovalPanel } from "./ApprovalPanel.tsx";
import { LiveStatus } from "./LiveStatus.tsx";
import { QuestionPanel } from "./QuestionPanel.tsx"; import { QuestionPanel } from "./QuestionPanel.tsx";
import { QueuePanel } from "./QueuePanel.tsx"; import { QueuePanel } from "./QueuePanel.tsx";
import { SecretPanel } from "./SecretPanel.tsx"; import { SecretPanel } from "./SecretPanel.tsx";
@@ -253,6 +256,12 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const pendingApproval = current?.pending.approvals[0]; const pendingApproval = current?.pending.approvals[0];
const pendingInput = current?.pending.userInputs[0]; const pendingInput = current?.pending.userInputs[0];
const working = current?.isWorking ?? false; const working = current?.isWorking ?? false;
// The status line above the composer: the timeline's working/thinking rows live here now.
const liveRow = current?.rows.findLast((row) => row.kind === "work-live");
const liveTool = liveRow?.kind === "work-live" ? truncate(firstLine(liveWorkEntryLabel(liveRow.entry, threadShell?.worktreePath ?? undefined, liveRow.active)), 60) : null;
const liveVerb = current?.rows.some((row) => row.kind === "working" && row.compacting) ? "Compacting" : !liveRow && current?.rows.some((row) => row.kind === "thinking") ? "Thinking" : "Working";
const liveSince = current?.workStartedAt ? Date.parse(current.workStartedAt) : NaN;
const liveLabel = Number.isFinite(liveSince) ? `${liveVerb} for ${formatWorkingDurationLabel(now - liveSince)}` : `${liveVerb}…`;
// A thread opens at its latest message: once its first snapshot renders, jump to the bottom. // A thread opens at its latest message: once its first snapshot renders, jump to the bottom.
const loaded = current !== null; const loaded = current !== null;
@@ -910,7 +919,6 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
// The mouse in the conversation: stable callbacks, since its rows are memoized. // The mouse in the conversation: stable callbacks, since its rows are memoized.
const conversationMouse: ConversationMouse = { const conversationMouse: ConversationMouse = {
respond: useEvent((decision: ProviderApprovalDecision) => respond(decision)),
selectTurn: useEvent((messageId: string) => turns.select(messageId)), selectTurn: useEvent((messageId: string) => turns.select(messageId)),
toggleFold: useEvent((id: string) => toggleFold: useEvent((id: string) =>
setExpandedIds((previous) => { setExpandedIds((previous) => {
@@ -921,6 +929,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
), ),
loadEarlier: useEvent(() => loadEarlier()), loadEarlier: useEvent(() => loadEarlier()),
menu: useEvent((target: ConversationTarget) => openConversationMenu(target)), menu: useEvent((target: ConversationTarget) => openConversationMenu(target)),
openTurnDiff: useEvent((checkpointTurnCount: number) => turns.openTurnDiff(checkpointTurnCount)),
}; };
const copy = (label: string, text: string) => { const copy = (label: string, text: string) => {
copyText(renderer, text); copyText(renderer, text);
@@ -944,6 +953,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
] ]
: [ : [
{ id: "copy-message", title: "Copy message", run: () => copy("the message", target.text) }, { id: "copy-message", title: "Copy message", run: () => copy("the message", target.text) },
...(target.checkpointTurnCount !== undefined ? [{ id: "turn-diff", title: "View changes from this turn", run: () => turns.openTurnDiff(target.checkpointTurnCount!) }] : []),
...(target.role === "user" ? turns.menuFor(target.messageId) : []), ...(target.role === "user" ? turns.menuFor(target.messageId) : []),
]; ];
if (target.kind === "message" && target.role === "user") turns.select(target.messageId); if (target.kind === "message" && target.role === "user") turns.select(target.messageId);
@@ -1122,6 +1132,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
loading={watchedId !== threadId || thread?.status === "loading"} loading={watchedId !== threadId || thread?.status === "loading"}
error={thread?.error} error={thread?.error}
workspaceRoot={threadShell?.worktreePath ?? undefined} workspaceRoot={threadShell?.worktreePath ?? undefined}
timestampFormat={config.timestampFormat}
now={now} now={now}
scrollRef={scrollRef} scrollRef={scrollRef}
parent={parent} parent={parent}
@@ -1168,8 +1179,14 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
<Button label="+ file" shortcut="a" onPress={attach.attachFile} /> <Button label="+ file" shortcut="a" onPress={attach.attachFile} />
</box> </box>
) : null} ) : null}
{working && threadId && !draft && !pendingApproval ? <LiveStatus label={liveLabel} tool={liveTool} /> : null}
{threadId || draft ? ( {threadId || draft ? (
<box flexDirection="column" flexShrink={0} marginTop={1} marginLeft={1} marginRight={1}> <box flexDirection="column" flexShrink={0} marginTop={1} marginLeft={1} marginRight={1}>
{pendingApproval && !draft ? (
<box marginBottom={1} flexShrink={0}>
<ApprovalPanel approval={pendingApproval} onRespond={respond} />
</box>
) : null}
<box <box
border={["left"]} border={["left"]}
customBorderChars={BAR} customBorderChars={BAR}
+46
View File
@@ -0,0 +1,46 @@
import type { ThreadPendingApproval } from "@t3tools/client-runtime/state/thread-requests";
import type { ProviderApprovalDecision } from "@t3tools/contracts";
import { Button, Buttons } from "./Button.tsx";
import { BAR, NO_BORDER } from "./edges.ts";
import { colors } from "./theme.ts";
/**
* A pending approval in the composer's place, as the web swaps it into the
* composer: the composer's own block and bar, the bar turned to the warning
* colour, with the same keys the hint bar names.
*/
export function ApprovalPanel(props: { readonly approval: ThreadPendingApproval; readonly onRespond: (decision: ProviderApprovalDecision) => void }) {
const { approval } = props;
return (
<>
<box border={["left"]} customBorderChars={BAR} borderColor={colors.warn} backgroundColor={colors.element} flexShrink={0} flexDirection="column" paddingTop={1} paddingBottom={1} paddingLeft={2} paddingRight={2}>
<text fg={colors.warn}>
<strong>{approvalTitle(approval.requestKind)}</strong>
</text>
{approval.detail ? <text fg={colors.text}>{approval.detail}</text> : null}
{approval.appName ? <text fg={colors.muted}>{approval.appName}</text> : null}
{approval.reason ? <text fg={colors.muted}>{approval.reason}</text> : null}
<box marginTop={1}>
<Buttons>
<Button label="Approve" shortcut="y" color={colors.good} onPress={() => props.onRespond("accept")} />
<Button label="Always allow this session" shortcut="Y" onPress={() => props.onRespond("acceptForSession")} />
<Button label="Decline" shortcut="n" color={colors.bad} onPress={() => props.onRespond("decline")} />
</Buttons>
</box>
</box>
<box height={1} flexShrink={0} border={["left"]} borderColor={colors.warn} customBorderChars={{ ...NO_BORDER, vertical: "╹" }}>
<box height={1} border={["bottom"]} borderColor={colors.element} customBorderChars={{ ...NO_BORDER, horizontal: "▀" }} />
</box>
</>
);
}
function approvalTitle(kind: string): string {
if (kind.includes("command")) return "Command approval";
if (kind.includes("read")) return "File read approval";
if (kind.includes("file")) return "File change approval";
if (kind.includes("elicitation") || kind.includes("access")) return "App access approval";
if (kind.includes("permission")) return "App permission approval";
return "Approval";
}
+20
View File
@@ -0,0 +1,20 @@
import { useEffect, useState } from "react";
import { SPINNER } from "./ThreadList.tsx";
import { colors } from "./theme.ts";
/** The one live status line pinned above the composer while a run is active. */
export function LiveStatus(props: { readonly label: string; readonly tool?: string | null }) {
const [spin, setSpin] = useState(0);
useEffect(() => {
const timer = setInterval(() => setSpin((frame) => frame + 1), 100);
return () => clearInterval(timer);
}, []);
return (
<box flexDirection="row" flexShrink={0} marginLeft={1} marginRight={1} paddingLeft={2}>
<text fg={colors.info} selectable={false}>{SPINNER[spin % SPINNER.length]!}</text>
<text fg={colors.muted} selectable={false}>{` ${props.label}`}</text>
{props.tool ? <text fg={colors.faint} selectable={false} wrapMode="none">{` · ${props.tool}`}</text> : null}
</box>
);
}
+2 -1
View File
@@ -8,7 +8,8 @@ import { BAR } from "./edges.ts";
import { truncate } from "./text.ts"; import { truncate } from "./text.ts";
import { colors, statusColor } from "./theme.ts"; import { colors, statusColor } from "./theme.ts";
const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; /** The braille spinner's frames, for anything that is working. */
export const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
/** The 2-column gutter's mark for a row: a spinner while it works, then what it needs from you. */ /** The 2-column gutter's mark for a row: a spinner while it works, then what it needs from you. */
function statusGlyph(row: ThreadRow, spin: number): { readonly glyph: string; readonly color: string } { function statusGlyph(row: ThreadRow, spin: number): { readonly glyph: string; readonly color: string } {
+181 -78
View File
@@ -1,38 +1,45 @@
import type { MouseEvent, ScrollBoxRenderable } from "@opentui/core"; import type { MouseEvent, ScrollBoxRenderable } from "@opentui/core";
import type { ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts"; import type { ThreadId, TurnItemId } from "@t3tools/contracts";
import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models";
import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation"; import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation";
import { memo, useEffect, useState, type RefObject } from "react"; import { memo, useEffect, useState, type RefObject } from "react";
import * as DateTime from "effect/DateTime";
import { findTextSegments } from "../model/search.ts"; import { findTextSegments } from "../model/search.ts";
import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
import type { OrchestrationV2SearchThreadResult } from "@t3tools/contracts"; import type { OrchestrationV2SearchThreadResult } from "@t3tools/contracts";
import { FindText } from "./FindText.tsx"; import { FindText } from "./FindText.tsx";
import { Button, Buttons, isLeftClick, isRightClick, useHover } from "./Button.tsx"; import { isLeftClick, isRightClick, useHover } from "./Button.tsx";
import { checkpointFileTotals, type ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
import type { Tui3Config } from "../config.ts";
import { CommandOutput } from "./CommandOutput.tsx"; import { CommandOutput } from "./CommandOutput.tsx";
import { BAR } from "./edges.ts"; import { BAR } from "./edges.ts";
import type { T3Session, ThreadHistory } from "../client/session.ts"; import type { T3Session, ThreadHistory } from "../client/session.ts";
import { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, type Timeline, type WorkLogEntry } from "../model/timeline.ts"; import { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, type Timeline, type WorkLogEntry } from "../model/timeline.ts";
import { blockFor } from "../model/transcript.ts"; import { blockFor } from "../model/transcript.ts";
import { firstLine } from "./text.ts"; import { firstLine, truncate } from "./text.ts";
import { colors, getMarkdownStyle, toneColor } from "./theme.ts"; import { colors, getMarkdownStyle, toneColor } from "./theme.ts";
/** What a right-click in the conversation was on. */ /** What a right-click in the conversation was on. */
export type ConversationTarget = export type ConversationTarget =
| { readonly kind: "message"; readonly messageId: string; readonly role: "user" | "assistant" | "system"; readonly text: string } | { readonly kind: "message"; readonly messageId: string; readonly role: "user" | "assistant" | "system"; readonly text: string; readonly checkpointTurnCount?: number }
/** `omitted`: the server left the output out of the thread; `source` is where to fetch it. */ /** `omitted`: the server left the output out of the thread; `source` is where to fetch it. */
| { readonly kind: "command"; readonly command: string; readonly output: string; readonly omitted: boolean; readonly source: { readonly threadId: ThreadId; readonly itemId: TurnItemId } | null }; | { readonly kind: "command"; readonly command: string; readonly output: string; readonly omitted: boolean; readonly source: { readonly threadId: ThreadId; readonly itemId: TurnItemId } | null };
export interface ConversationMouse { export interface ConversationMouse {
readonly respond: (decision: ProviderApprovalDecision) => void;
/** A click on a prompt: the turn cursor, as [ and ] move it. */ /** A click on a prompt: the turn cursor, as [ and ] move it. */
readonly selectTurn: (messageId: string) => void; readonly selectTurn: (messageId: string) => void;
/** A click on a folded turn or work group: its own expansion, apart from e. */ /** A click on a folded turn or work group: its own expansion, apart from e. */
readonly toggleFold: (id: string) => void; readonly toggleFold: (id: string) => void;
readonly loadEarlier: () => void; readonly loadEarlier: () => void;
readonly menu: (target: ConversationTarget) => void; readonly menu: (target: ConversationTarget) => void;
/** A click on a changed file: that turn's diff. */
readonly openTurnDiff: (checkpointTurnCount: number) => void;
} }
/** Prose stops at this width on wide terminals, left-aligned. */
const CONTENT_WIDTH = 100;
/** The conversation, row for row as the web app derives it (MessagesTimeline.logic). */ /** The conversation, row for row as the web app derives it (MessagesTimeline.logic). */
export function ThreadView(props: { export function ThreadView(props: {
readonly timeline: Timeline | null; readonly timeline: Timeline | null;
@@ -45,6 +52,7 @@ export function ThreadView(props: {
readonly loading: boolean; readonly loading: boolean;
readonly error?: string | undefined; readonly error?: string | undefined;
readonly workspaceRoot: string | undefined; readonly workspaceRoot: string | undefined;
readonly timestampFormat: Tui3Config["timestampFormat"];
readonly now: number; readonly now: number;
readonly scrollRef: RefObject<ScrollBoxRenderable | null>; readonly scrollRef: RefObject<ScrollBoxRenderable | null>;
/** For a subagent or fork: the thread it came from, shown as a link in the header. */ /** For a subagent or fork: the thread it came from, shown as a link in the header. */
@@ -65,9 +73,11 @@ export function ThreadView(props: {
) : null} ) : null}
{props.error ? <text fg={colors.bad} flexShrink={0}>{props.error}</text> : null} {props.error ? <text fg={colors.bad} flexShrink={0}>{props.error}</text> : null}
<scrollbox ref={props.scrollRef} flexGrow={1} flexShrink={1} minHeight={0} stickyScroll stickyStart="bottom"> <scrollbox ref={props.scrollRef} flexGrow={1} flexShrink={1} minHeight={0} stickyScroll stickyStart="bottom">
{/* Prose stops at reading width on wide terminals; the composer below stays full width. */}
<box flexDirection="column" maxWidth={CONTENT_WIDTH}>
{props.loading && !timeline ? <text fg={colors.muted}>Loading…</text> : null} {props.loading && !timeline ? <text fg={colors.muted}>Loading…</text> : null}
{history?.hasMore || history?.error ? <LoadEarlier history={history} onLoad={props.mouse.loadEarlier} /> : null} {history?.hasMore || history?.error ? <LoadEarlier history={history} onLoad={props.mouse.loadEarlier} /> : null}
{timeline?.rows.map((row) => ( {timeline?.rows.filter((row) => !isPendingApprovalRow(row, pendingIds)).map((row) => (
<Row <Row
key={row.id} key={row.id}
row={row} row={row}
@@ -77,19 +87,51 @@ export function ThreadView(props: {
scrollRef={props.scrollRef} scrollRef={props.scrollRef}
findQuery={props.findQuery ?? ""} findQuery={props.findQuery ?? ""}
activeOccurrence={props.findMatch?.entryId === row.id ? props.findMatch.occurrence : null} activeOccurrence={props.findMatch?.entryId === row.id ? props.findMatch.occurrence : null}
pending={row.kind === "event" && pendingIds.has(eventRequestId(row) ?? "")}
workspaceRoot={props.workspaceRoot} workspaceRoot={props.workspaceRoot}
now={row.kind === "working" ? props.now : 0} footer={assistantFooter(row, timeline, props.timestampFormat, props.now)}
workStartedAt={timeline.workStartedAt}
onOpenThread={props.onOpenThread} onOpenThread={props.onOpenThread}
mouse={props.mouse} mouse={props.mouse}
/> />
))} ))}
</box>
</scrollbox> </scrollbox>
</box> </box>
); );
} }
/**
* The turn footer's text: model, how long the run took, and when the reply
* landed, day-aware as the web's is. Parts a row doesn't carry are left out;
* only a finished turn's last reply (or its detached meta row) gets one.
*/
function assistantFooter(row: MessagesTimelineRow, timeline: Timeline, timestampFormat: Tui3Config["timestampFormat"], now: number): string {
const message = row.kind === "assistant-meta" ? row.message : row.kind === "message" && row.showAssistantMeta ? row.message : null;
if (message?.role !== "assistant" || message.streaming) return "";
const meta = message.runId ? timeline.runMeta.get(message.runId) : undefined;
const projected = row.kind === "message" || row.kind === "assistant-meta" ? row.projectedItem : undefined;
const status = projected && projected.item.status !== "completed" ? projected.item.status : "";
const parts = [
meta?.model && meta.model !== "default" ? meta.model : "",
meta?.durationMs !== null && meta?.durationMs !== undefined ? formatDuration(meta.durationMs) : "",
dayAwareTime(message.updatedAt, timestampFormat, now),
status,
];
return parts.filter(Boolean).join(" · ");
}
/** The web's day-aware timestamp: a time today, "yesterday at …", then a short date. */
function dayAwareTime(iso: string, format: Tui3Config["timestampFormat"], now: number): string {
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return "";
const time = date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit", ...(format === "locale" ? {} : { hour12: format === "12-hour" }) });
const today = new Date(now);
const dayDiff = Math.round((new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime() - new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()) / 86_400_000);
if (dayDiff <= 0) return time;
if (dayDiff === 1) return `yesterday at ${time}`;
const day = date.toLocaleDateString(undefined, { month: "numeric", day: "numeric", ...(date.getFullYear() === today.getFullYear() ? {} : { year: "numeric" as const }) });
return `${day} ${time}`;
}
function LoadEarlier({ history, onLoad }: { readonly history: ThreadHistory; readonly onLoad: () => void }) { function LoadEarlier({ history, onLoad }: { readonly history: ThreadHistory; readonly onLoad: () => void }) {
const label = history.loading ? "Loading earlier turns…" : history.error ? `Could not load earlier turns: ${history.error} (o to retry)` : "Load earlier turns (o)"; const label = history.loading ? "Loading earlier turns…" : history.error ? `Could not load earlier turns: ${history.error} (o to retry)` : "Load earlier turns (o)";
return <Divider label={label} color={history.error ? colors.bad : colors.accent} onPress={history.loading ? undefined : onLoad} />; return <Divider label={label} color={history.error ? colors.bad : colors.accent} onPress={history.loading ? undefined : onLoad} />;
@@ -106,8 +148,7 @@ function Divider({ label, color, onPress }: { readonly label: string; readonly c
/** /**
* Memoized: computeStableMessagesTimelineRows keeps unchanged rows identical, * Memoized: computeStableMessagesTimelineRows keeps unchanged rows identical,
* so a streamed update re-renders only its own rows. `now` is nonzero only for * so a streamed update re-renders only its own rows.
* the working row, which ticks.
*/ */
const Row = memo(function Row(props: { const Row = memo(function Row(props: {
readonly row: MessagesTimelineRow; readonly row: MessagesTimelineRow;
@@ -117,10 +158,9 @@ const Row = memo(function Row(props: {
readonly scrollRef: RefObject<ScrollBoxRenderable | null>; readonly scrollRef: RefObject<ScrollBoxRenderable | null>;
readonly findQuery: string; readonly findQuery: string;
readonly activeOccurrence: number | null; readonly activeOccurrence: number | null;
readonly pending: boolean;
readonly workspaceRoot: string | undefined; readonly workspaceRoot: string | undefined;
readonly now: number; /** The turn footer's text for this row, or "" for none. */
readonly workStartedAt: string | null; readonly footer: string;
readonly onOpenThread: (threadId: ThreadId) => void; readonly onOpenThread: (threadId: ThreadId) => void;
readonly mouse: ConversationMouse; readonly mouse: ConversationMouse;
}) { }) {
@@ -132,32 +172,32 @@ const Row = memo(function Row(props: {
const segments = findTextSegments(message.text, message.role === "user"); 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 (segments.some((segment) => findThreadSearchOccurrences(segment, props.findQuery).length > 0)) return <FindText segments={segments} query={props.findQuery} activeOccurrence={props.activeOccurrence} scrollRef={props.scrollRef} />;
} }
const menu = { kind: "message", messageId: message.id, role: message.role, text: message.text } as const; const summary = row.assistantTurnDiffSummary;
const menu = { kind: "message", messageId: message.id, role: message.role, text: message.text, ...(summary && summary.files.length > 0 ? { checkpointTurnCount: summary.checkpointTurnCount } : {}) } as const;
if (message.role === "user") return <UserMessage text={message.text} messageId={message.id} selected={props.selected} onSelect={() => mouse.selectTurn(message.id)} onMenu={() => mouse.menu(menu)} />; if (message.role === "user") return <UserMessage text={message.text} messageId={message.id} selected={props.selected} onSelect={() => mouse.selectTurn(message.id)} onMenu={() => mouse.menu(menu)} />;
if (message.role === "system") return <text marginTop={1} fg={colors.muted} onMouseDown={(event: MouseEvent) => isRightClick(event) && mouse.menu(menu)}>{message.text}</text>; if (message.role === "system") return <text marginTop={1} fg={colors.muted} onMouseDown={(event: MouseEvent) => isRightClick(event) && mouse.menu(menu)}>{message.text}</text>;
return ( return (
<box marginTop={1} onMouseDown={(event: MouseEvent) => isRightClick(event) && mouse.menu(menu)}> <box marginTop={1} flexDirection="column" onMouseDown={(event: MouseEvent) => isRightClick(event) && mouse.menu(menu)}>
<markdown content={message.text || "…"} syntaxStyle={getMarkdownStyle()} streaming={message.streaming} conceal /> <markdown content={message.text || "…"} syntaxStyle={getMarkdownStyle()} streaming={message.streaming} conceal />
{summary && summary.files.length > 0 ? <ChangedFiles summary={summary} onOpenTurnDiff={mouse.openTurnDiff} /> : null}
{props.footer ? <text marginTop={1} fg={colors.faint}>{props.footer}</text> : null}
</box> </box>
); );
} }
case "assistant-meta":
return props.footer ? <text marginTop={1} fg={colors.faint}>{props.footer}</text> : null;
case "turn-fold": case "turn-fold":
case "attempt-fold": case "attempt-fold":
// The finished turn's work, folded: the web's turn separator. // The finished turn's work, folded: the web's turn separator, in the work rows' columns.
return ( return (
<Toggle onPress={() => mouse.toggleFold(row.kind === "turn-fold" ? row.runId : row.attemptId)}> <Toggle onPress={() => mouse.toggleFold(row.kind === "turn-fold" ? row.runId : row.attemptId)}>
{(hover) => <text fg={hover ? colors.text : colors.faint} selectable={false}>{`${row.label} ${row.expanded ? "⌄" : "›"}`}</text>} {(hover) => <WorkLine glyph=" " glyphColor={colors.faint} label={`${row.label} ${row.expanded ? "⌄" : "›"}`} labelColor={hover ? colors.text : colors.faint} />}
</Toggle> </Toggle>
); );
case "work-toggle": case "work-toggle":
return ( return (
<Toggle onPress={() => mouse.toggleFold(row.groupId)}> <Toggle onPress={() => mouse.toggleFold(row.groupId)}>
{(hover) => ( {(hover) => <WorkLine glyph={SUMMARY_GLYPH[row.summaryKind] ?? "•"} glyphColor={row.hasFailure ? colors.bad : colors.faint} label={`${row.summary} ${row.expanded ? "⌄" : "›"}`} labelColor={hover ? colors.text : colors.muted} />}
<text fg={hover ? colors.text : colors.muted} selectable={false}>
<span fg={row.hasFailure ? colors.bad : hover ? colors.text : colors.faint}>{SUMMARY_GLYPH[row.summaryKind] ?? "•"}</span>
{` ${row.summary} ${row.expanded ? "⌄" : "›"}`}
</text>
)}
</Toggle> </Toggle>
); );
case "work": case "work":
@@ -175,18 +215,10 @@ const Row = memo(function Row(props: {
<WorkEntry entry={row.entry} expanded={row.expanded} label={liveWorkEntryLabel(row.entry, workspaceRoot, row.active)} onOpenThread={props.onOpenThread} onMenu={mouse.menu} session={props.session} streamCommandOutput={props.streamCommandOutput} scrollRef={props.scrollRef} /> <WorkEntry entry={row.entry} expanded={row.expanded} label={liveWorkEntryLabel(row.entry, workspaceRoot, row.active)} onOpenThread={props.onOpenThread} onMenu={mouse.menu} session={props.session} streamCommandOutput={props.streamCommandOutput} scrollRef={props.scrollRef} />
</box> </box>
); );
case "working": { case "working":
const since = props.workStartedAt ? Date.parse(props.workStartedAt) : NaN;
const verb = row.compacting ? "Compacting" : "Working";
return (
<text marginTop={1} fg={colors.muted}>
<span fg={colors.info}>◐</span>
{Number.isFinite(since) ? ` ${verb} for ${formatWorkingDurationLabel(props.now - since)}` : ` ${verb}…`}
</text>
);
}
case "thinking": case "thinking":
return <text marginTop={1} fg={colors.faint}>∴ Thinking…</text>; // The live status line above the composer carries these now.
return null;
case "context-compaction": case "context-compaction":
return <Divider label={row.failed ? `${row.title ?? "Compaction failed"}${row.failure ? `: ${row.failure}` : ""}` : (row.title ?? row.label)} color={row.failed ? colors.bad : colors.faint} />; return <Divider label={row.failed ? `${row.title ?? "Compaction failed"}${row.failure ? `: ${row.failure}` : ""}` : (row.title ?? row.label)} color={row.failed ? colors.bad : colors.faint} />;
case "proposed-plan": case "proposed-plan":
@@ -200,7 +232,7 @@ const Row = memo(function Row(props: {
</box> </box>
); );
case "event": case "event":
return <EventRow item={row.projectedItem.item} pending={props.pending} onRespond={mouse.respond} />; return <EventRow item={row.projectedItem.item} />;
case "worktree-setup": case "worktree-setup":
return ( return (
<text marginTop={1} fg={colors.muted}> <text marginTop={1} fg={colors.muted}>
@@ -209,11 +241,68 @@ const Row = memo(function Row(props: {
</text> </text>
); );
default: default:
// assistant-meta, html-render, mcp-app: nothing a terminal can show. // html-render, mcp-app: nothing a terminal can show.
return null; return null;
} }
}); });
/** The files a turn changed, folded to one line; a file opens that turn's diff. */
function ChangedFiles({ summary, onOpenTurnDiff }: { readonly summary: ThreadCheckpointSummary; readonly onOpenTurnDiff: (checkpointTurnCount: number) => void }) {
const [open, setOpen] = useState(false);
const [hover, hoverProps] = useHover();
const totals = checkpointFileTotals(summary);
const hidden = totals.count - summary.files.length;
const openDiff = () => onOpenTurnDiff(summary.checkpointTurnCount);
return (
<box marginTop={1} flexDirection="column">
<box flexDirection="row" {...hoverProps} onMouseDown={(event: MouseEvent) => isLeftClick(event) && setOpen(!open)}>
<text fg={hover ? colors.text : colors.muted} selectable={false}>
<span fg={hover ? colors.text : colors.faint}>✎</span>
{` ${totals.count} ${totals.count === 1 ? "file" : "files"} `}
</text>
<DiffCounts additions={totals.additions} deletions={totals.deletions} />
<text fg={colors.faint} selectable={false}>{` ${open ? "⌄" : "›"}`}</text>
</box>
{open ? (
<box flexDirection="column" paddingLeft={2}>
{summary.files.map((file) => (
<ChangedFile key={file.path} path={file.path} additions={file.additions} deletions={file.deletions} onPress={openDiff} />
))}
{hidden > 0 ? (
<box flexDirection="row" onMouseDown={(event: MouseEvent) => isLeftClick(event) && openDiff()}>
<text fg={colors.faint} selectable={false}>{`… ${hidden} more ${hidden === 1 ? "file" : "files"}`}</text>
</box>
) : null}
</box>
) : null}
</box>
);
}
function ChangedFile({ path, additions, deletions, onPress }: { readonly path: string; readonly additions: number; readonly deletions: number; readonly onPress: () => void }) {
const [hover, hoverProps] = useHover();
const counts = (additions > 0 ? `+${additions}`.length : 0) + (deletions > 0 ? `−${deletions}`.length : 0) + (additions > 0 && deletions > 0 ? 1 : 0);
return (
<box flexDirection="row" {...hoverProps} onMouseDown={(event: MouseEvent) => isLeftClick(event) && onPress()}>
<text fg={hover ? colors.text : colors.muted} selectable={false} wrapMode="none">{truncate(path, CONTENT_WIDTH - 2 - (counts ? counts + 2 : 0))}</text>
<box flexGrow={1} />
<DiffCounts additions={additions} deletions={deletions} />
</box>
);
}
/** `+42 −7`, each count in its own colour; a zero count is left out. */
function DiffCounts({ additions, deletions }: { readonly additions: number; readonly deletions: number }) {
if (additions === 0 && deletions === 0) return null;
return (
<text selectable={false} flexShrink={0}>
{additions > 0 ? <span fg={colors.good}>{`+${additions}`}</span> : null}
{additions > 0 && deletions > 0 ? " " : ""}
{deletions > 0 ? <span fg={colors.bad}>{`−${deletions}`}</span> : null}
</text>
);
}
const USER_FOLD_LINES = 8; const USER_FOLD_LINES = 8;
const USER_FOLD_CHARS = 600; const USER_FOLD_CHARS = 600;
@@ -226,7 +315,7 @@ function UserMessage({ text, messageId, selected, onSelect, onMenu }: { readonly
if (shown.length > USER_FOLD_CHARS) shown = `${shown.slice(0, USER_FOLD_CHARS).trimEnd()}…`; if (shown.length > USER_FOLD_CHARS) shown = `${shown.slice(0, USER_FOLD_CHARS).trimEnd()}…`;
const folded = shown.length < trimmed.length; const folded = shown.length < trimmed.length;
return ( return (
<box id={`turn-${messageId}`} border={["left"]} customBorderChars={BAR} borderColor={selected ? colors.accent : colors.border} marginTop={1} backgroundColor={hover ? colors.elementHover : colors.element} paddingTop={1} paddingBottom={1} paddingLeft={2} paddingRight={2} flexDirection="column" {...hoverProps} onMouseDown={(event: MouseEvent) => (isRightClick(event) ? onMenu() : isLeftClick(event) ? onSelect() : undefined)}> <box id={`turn-${messageId}`} border={["left"]} customBorderChars={BAR} borderColor={colors.accent} marginTop={1} backgroundColor={hover ? colors.elementHover : selected ? colors.selectedBg : colors.element} paddingTop={1} paddingBottom={1} paddingLeft={2} paddingRight={2} flexDirection="column" {...hoverProps} onMouseDown={(event: MouseEvent) => (isRightClick(event) ? onMenu() : isLeftClick(event) ? onSelect() : undefined)}>
<text fg={colors.text}>{shown}</text> <text fg={colors.text}>{shown}</text>
{folded ? <text fg={colors.faint}>{`… ${Math.max(1, lines.length - shown.split("\n").length)} more lines`}</text> : null} {folded ? <text fg={colors.faint}>{`… ${Math.max(1, lines.length - shown.split("\n").length)} more lines`}</text> : null}
</box> </box>
@@ -255,6 +344,37 @@ function OmittedOutput({ session, source }: { readonly session: T3Session; reado
return <text fg={colors.muted}>{state.text || "No output."}</text>; return <text fg={colors.muted}>{state.text || "No output."}</text>;
} }
/** One work/tool line, everywhere the same: glyph, label, result details right-aligned. */
function WorkLine(props: { readonly glyph: string; readonly glyphColor: string; readonly label: string; readonly labelColor: string; readonly detail?: string; readonly selectable?: boolean }) {
// The label gives up whatever the right-hand details take, within the reading width.
const label = truncate(props.label, CONTENT_WIDTH - 2 - (props.detail ? props.detail.length + 2 : 0));
return (
<box flexDirection="row" width="100%">
<text fg={props.glyphColor} flexShrink={0} selectable={false}>{`${props.glyph} `}</text>
<text fg={props.labelColor} flexShrink={1} wrapMode="none" selectable={props.selectable ?? false}>{label}</text>
{props.detail ? (
<>
<box flexGrow={1} />
<text fg={colors.faint} flexShrink={0} selectable={false}>{` ${props.detail}`}</text>
</>
) : null}
</box>
);
}
/** What a finished entry can say on the right: a failed exit, an edit's counts, its duration. */
function workEntryDetail(entry: WorkLogEntry): string {
const item = entry.structuredPayload;
const parts: string[] = [];
if (item?.type === "command_execution" && item.exitCode !== undefined && item.exitCode !== 0) parts.push(`exit ${item.exitCode}`);
if (item?.type === "file_change" && (item.additions || item.deletions)) parts.push(`+${item.additions ?? 0} −${item.deletions ?? 0}`);
if (item?.startedAt && item.completedAt) {
const ms = DateTime.toEpochMillis(item.completedAt) - DateTime.toEpochMillis(item.startedAt);
if (ms >= 1_000) parts.push(formatDuration(ms));
}
return parts.join(" · ");
}
function WorkEntry({ entry, expanded: groupExpanded, label, onOpenThread, onMenu, session, streamCommandOutput, scrollRef }: { readonly entry: WorkLogEntry; readonly expanded: boolean; readonly label: string; readonly onOpenThread: (threadId: ThreadId) => void; readonly onMenu: (target: ConversationTarget) => void; readonly session: T3Session; readonly streamCommandOutput: boolean; readonly scrollRef: RefObject<ScrollBoxRenderable | null> }) { function WorkEntry({ entry, expanded: groupExpanded, label, onOpenThread, onMenu, session, streamCommandOutput, scrollRef }: { readonly entry: WorkLogEntry; readonly expanded: boolean; readonly label: string; readonly onOpenThread: (threadId: ThreadId) => void; readonly onMenu: (target: ConversationTarget) => void; readonly session: T3Session; readonly streamCommandOutput: boolean; readonly scrollRef: RefObject<ScrollBoxRenderable | null> }) {
const [open, setExpanded] = useState<boolean | null>(null); const [open, setExpanded] = useState<boolean | null>(null);
const [hover, hoverProps] = useHover(); const [hover, hoverProps] = useHover();
@@ -264,19 +384,15 @@ function WorkEntry({ entry, expanded: groupExpanded, label, onOpenThread, onMenu
const projected = entry.projectedItem; const projected = entry.projectedItem;
const failed = workEntryDisplayIndicatesToolFailure(entry); const failed = workEntryDisplayIndicatesToolFailure(entry);
const child = childThreadOf(entry); const child = childThreadOf(entry);
const glyphColor = failed || entry.tone === "error" ? colors.bad : child ? colors.accent : colors.faint; const glyphColor = failed || entry.tone === "error" ? colors.bad : entry.toolLifecycleStatus === "inProgress" ? colors.info : colors.faint;
const clickable = Boolean(command || child); const clickable = Boolean(command || child);
const labelColor = clickable && hover ? colors.text : entry.tone === "thinking" ? colors.faint : colors.muted; const labelColor = clickable && hover ? colors.text : entry.tone === "thinking" ? colors.faint : colors.muted;
const text = ( const detail = workEntryDetail(entry);
<text fg={labelColor} selectable={!clickable}> const line = (text: string) => <WorkLine glyph={failed ? "✕" : glyphFor(entry)} glyphColor={glyphColor} label={text} labelColor={labelColor} detail={detail} selectable={!clickable} />;
<span fg={clickable && hover ? colors.text : glyphColor}>{failed ? "✕" : glyphFor(entry)}</span>
{` ${firstLine(label)}${child ? " ↗" : ""}`}
</text>
);
const source = projected ? { threadId: projected.sourceThreadId, itemId: projected.sourceItemId } : null; const source = projected ? { threadId: projected.sourceThreadId, itemId: projected.sourceItemId } : null;
const streaming = expanded && streamCommandOutput && source !== null; const streaming = expanded && streamCommandOutput && source !== null;
if (command) return <box flexDirection="column"> if (command) return <box flexDirection="column">
<box flexDirection="row" {...hoverProps} onMouseDown={(event: MouseEvent) => (isRightClick(event) ? onMenu({ kind: "command", command: command.input, output: command.output ?? "", omitted: command.outputOmitted === true, source }) : isLeftClick(event) ? setExpanded(!expanded) : undefined)}><text fg={colors.faint} selectable={false}>{expanded ? "⌄ " : "› "}</text>{text}</box> <box flexDirection="row" {...hoverProps} onMouseDown={(event: MouseEvent) => (isRightClick(event) ? onMenu({ kind: "command", command: command.input, output: command.output ?? "", omitted: command.outputOmitted === true, source }) : isLeftClick(event) ? setExpanded(!expanded) : undefined)}>{line(`${firstLine(label)} ${expanded ? "⌄" : "›"}`)}</box>
{expanded ? ( {expanded ? (
<box border={["left"]} customBorderChars={BAR} borderColor={colors.border} backgroundColor={colors.element} flexDirection="column" marginTop={1} paddingTop={1} paddingBottom={1} paddingLeft={2} paddingRight={2}> <box border={["left"]} customBorderChars={BAR} borderColor={colors.border} backgroundColor={colors.element} flexDirection="column" marginTop={1} paddingTop={1} paddingBottom={1} paddingLeft={2} paddingRight={2}>
<text fg={colors.text}>{`$ ${command.input}`}</text> <text fg={colors.text}>{`$ ${command.input}`}</text>
@@ -288,7 +404,7 @@ function WorkEntry({ entry, expanded: groupExpanded, label, onOpenThread, onMenu
</box> </box>
) : null} ) : null}
</box>; </box>;
return child ? <box {...hoverProps} onMouseDown={(event: MouseEvent) => isLeftClick(event) && onOpenThread(child)}>{text}</box> : text; return child ? <box {...hoverProps} onMouseDown={(event: MouseEvent) => isLeftClick(event) && onOpenThread(child)}>{line(`${firstLine(label)} ↗`)}</box> : line(firstLine(label));
} }
/** The thread a subagent work row ran in, when it has its own. */ /** The thread a subagent work row ran in, when it has its own. */
@@ -297,23 +413,7 @@ export function childThreadOf(entry: WorkLogEntry): ThreadId | null {
return item?.type === "subagent" ? (item.childThreadId ?? null) : null; return item?.type === "subagent" ? (item.childThreadId ?? null) : null;
} }
function EventRow({ item, pending, onRespond }: { readonly onRespond: (decision: ProviderApprovalDecision) => void; readonly item: MessagesTimelineRow extends infer R ? (R extends { kind: "event"; projectedItem: { item: infer I } } ? I : never) : never; readonly pending: boolean }) { function EventRow({ item }: { readonly item: MessagesTimelineRow extends infer R ? (R extends { kind: "event"; projectedItem: { item: infer I } } ? I : never) : never }) {
if (item.type === "approval_request" && pending) {
return (
<box marginTop={1} border={["left"]} customBorderChars={BAR} borderColor={colors.warn} backgroundColor={colors.panel} flexDirection="column" paddingTop={1} paddingBottom={1} paddingLeft={2} paddingRight={2}>
<text fg={colors.warn}>
<strong>{approvalTitle(item.requestKind)}</strong>
</text>
{item.prompt ? <text fg={colors.text}>{item.prompt}</text> : null}
{item.reason ? <text fg={colors.muted}>{item.reason}</text> : null}
<Buttons>
<Button label="Approve" shortcut="y" color={colors.good} onPress={() => onRespond("accept")} />
<Button label="Always allow this session" shortcut="Y" onPress={() => onRespond("acceptForSession")} />
<Button label="Decline" shortcut="n" color={colors.bad} onPress={() => onRespond("decline")} />
</Buttons>
</box>
);
}
const block = blockFor(item, new Set()); const block = blockFor(item, new Set());
if (!block) return null; if (!block) return null;
switch (block.kind) { switch (block.kind) {
@@ -321,10 +421,9 @@ function EventRow({ item, pending, onRespond }: { readonly onRespond: (decision:
return <text marginTop={1} fg={toneColor(block.tone)}>{block.text}</text>; return <text marginTop={1} fg={toneColor(block.tone)}>{block.text}</text>;
case "tool": case "tool":
return ( return (
<text marginTop={1} fg={colors.muted}> <box marginTop={1}>
<span fg={toneColor(block.tone)}>{block.icon}</span> <WorkLine glyph={block.icon} glyphColor={toneColor(block.tone)} label={block.label} labelColor={colors.muted} selectable />
{` ${block.label}`} </box>
</text>
); );
case "approval": case "approval":
return <text marginTop={1} fg={colors.muted}>{`Approval requested: ${block.title}`}</text>; return <text marginTop={1} fg={colors.muted}>{`Approval requested: ${block.title}`}</text>;
@@ -335,20 +434,24 @@ function EventRow({ item, pending, onRespond }: { readonly onRespond: (decision:
} }
} }
function approvalTitle(kind: string): string {
if (kind.includes("command")) return "Command approval";
if (kind.includes("read")) return "File read approval";
if (kind.includes("file")) return "File change approval";
if (kind.includes("access")) return "App access approval";
if (kind.includes("permission")) return "App permission approval";
return "Approval";
}
function eventRequestId(row: Extract<MessagesTimelineRow, { kind: "event" }>): string | undefined { function eventRequestId(row: Extract<MessagesTimelineRow, { kind: "event" }>): string | undefined {
const item = row.projectedItem.item; const item = row.projectedItem.item;
return item.type === "approval_request" ? item.requestId : undefined; return item.type === "approval_request" ? item.requestId : undefined;
} }
function entryRequestId(entry: WorkLogEntry): string | undefined {
const item = entry.structuredPayload;
return item?.type === "approval_request" ? item.requestId : undefined;
}
/** A live approval shows in the composer's place, not again as a timeline row. */
function isPendingApprovalRow(row: MessagesTimelineRow, pendingIds: ReadonlySet<string>): boolean {
if (pendingIds.size === 0) return false;
if (row.kind === "event") return pendingIds.has(eventRequestId(row) ?? "");
if (row.kind === "work-live") return pendingIds.has(entryRequestId(row.entry) ?? "");
return row.kind === "work" && row.groupedEntries.length > 0 && row.groupedEntries.every((entry) => pendingIds.has(entryRequestId(entry) ?? ""));
}
/** A folded turn or work group: a click opens or closes just this one. */ /** A folded turn or work group: a click opens or closes just this one. */
function Toggle({ onPress, children }: { readonly onPress: () => void; readonly children: (hover: boolean) => React.ReactNode }) { function Toggle({ onPress, children }: { readonly onPress: () => void; readonly children: (hover: boolean) => React.ReactNode }) {
const [hover, hoverProps] = useHover(); const [hover, hoverProps] = useHover();
+8 -3
View File
@@ -54,8 +54,13 @@ export function useTurns(input: {
const checkpoint = fullThread const checkpoint = fullThread
? turns.map((turn) => turn.checkpoint).filter((checkpoint): checkpoint is TurnCheckpoint => checkpoint?.status === "ready").sort((a, b) => b.checkpointTurnCount - a.checkpointTurnCount)[0] ? turns.map((turn) => turn.checkpoint).filter((checkpoint): checkpoint is TurnCheckpoint => checkpoint?.status === "ready").sort((a, b) => b.checkpointTurnCount - a.checkpointTurnCount)[0]
: diffTurn(turns, messageId); : diffTurn(turns, messageId);
if (!input.threadId || !input.cwd || !checkpoint) return input.say("No changes from this turn."); if (!checkpoint) return input.say("No changes from this turn.");
const toTurnCount = checkpoint.checkpointTurnCount; showDiff(checkpoint.checkpointTurnCount, fullThread);
};
/** The changed-files line's diff: it already knows its checkpoint's turn count. */
const openTurnDiff = (checkpointTurnCount: number) => showDiff(checkpointTurnCount, false);
const showDiff = (toTurnCount: number, fullThread: boolean) => {
if (!input.threadId || !input.cwd) return input.say("No changes from this turn.");
const state: DiffState = { cwd: input.cwd, path: null, title: fullThread ? "Changes" : `Turn ${toTurnCount}`, status: "loading" }; const state: DiffState = { cwd: input.cwd, path: null, title: fullThread ? "Changes" : `Turn ${toTurnCount}`, status: "loading" };
input.setDiff(state); input.setDiff(state);
input.showConversation(); input.showConversation();
@@ -134,7 +139,7 @@ export function useTurns(input: {
] : []), ] : []),
]; ];
}; };
return { selectedMessageId, bindings, diffContext, select, menuFor }; return { selectedMessageId, bindings, diffContext, select, menuFor, openTurnDiff };
} }
function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error); } function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error); }
+60 -3
View File
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, test } from "bun:test"; import { afterEach, describe, expect, test } from "bun:test";
import { omittedCommand, withApproval, withOmittedOutput, withQuestion } from "./fixtures.ts"; import { omittedCommand, withApproval, withCompletedTurn, withOmittedOutput, withQuestion, withWorking } from "./fixtures.ts";
import { loadLayout } from "../../src/layout.ts"; import { loadLayout } from "../../src/layout.ts";
import { fakeSession, renderApp, v2ThreadId } from "./harness.tsx"; import { fakeSession, renderApp, v2ThreadId } from "./harness.tsx";
@@ -138,7 +138,63 @@ describe("palette and pickers", () => {
}); });
}); });
describe("a finished turn", () => {
test("its changed files fold out under the reply, and a file opens the turn's diff", async () => {
const patch = "diff --git a/src/index.ts b/src/index.ts\n--- a/src/index.ts\n+++ b/src/index.ts\n@@ -1 +1 @@\n-old\n+new\n";
const app = await open({ session: fakeSession({ projection: withCompletedTurn(), results: { turnDiff: { diff: patch } } }) });
expect(app.frame()).toContain("✎ 3 files +42 −7 ›");
expect(app.frame()).not.toContain("src/util.ts");
const line = app.find("3 files");
await app.click(line.x, line.y);
expect(app.frame()).toContain("src/index.ts");
expect(app.frame()).toContain("src/util.ts");
expect(app.frame()).toContain("+30 −5");
const file = app.find("src/util.ts");
await app.click(file.x, file.y);
await app.settle(50);
expect(app.calls("turnDiff").map((call) => call.args[0])).toEqual([{ threadId: v2ThreadId, toTurnCount: 1, ignoreWhitespace: true, fromTurnCount: 0 }]);
expect(app.frame()).toContain("Turn 1");
});
test("its footer names the model, the duration and the time", async () => {
const app = await open({ session: fakeSession({ projection: withCompletedTurn() }) });
// The date half is locale- and timezone-shaped; the model and duration are not.
expect(app.frame()).toMatch(/gpt-5\.4 · 3m 12s · /);
});
});
describe("live status", () => {
test("while working, one status line sits above the composer and none in the timeline", async () => {
const app = await open({ session: fakeSession({ projection: withWorking() }) });
const frame = app.frame();
expect(frame).toMatch(/[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏] Working for /);
expect(frame.split("Working for")).toHaveLength(2);
expect(frame).not.toContain("◐");
const lines = frame.split("\n");
const status = lines.findIndex((line) => line.includes("Working for"));
const composer = lines.findIndex((line) => line.includes("Press i to type"));
expect(status).toBeGreaterThan(-1);
expect(status).toBeLessThan(composer);
// The live tool itself stays a timeline row.
expect(frame).toContain("Running bun");
});
});
describe("approvals", () => { describe("approvals", () => {
test("the request shows above the composer, with its buttons, and not in the timeline", async () => {
const app = await open({ session: fakeSession({ projection: withApproval() }) });
const frame = app.frame();
expect(frame).toContain("Command approval");
expect(frame).toContain("Deletes dist/ and rebuilds it.");
// Only the composer block names the command; its timeline row is hidden.
expect(frame.split("rm -rf dist && bun run build")).toHaveLength(2);
// The composer stays below it, so a message can still go with a decline.
expect(app.find("Command approval").y).toBeLessThan(app.find("gpt-5.4").y);
const approve = app.find("Approve");
await app.click(approve.x, approve.y);
expect(app.calls("respond").map((call) => call.args[2])).toEqual(["accept"]);
});
test("y, Y and n answer the request", async () => { test("y, Y and n answer the request", async () => {
const app = await open({ session: fakeSession({ projection: withApproval() }) }); const app = await open({ session: fakeSession({ projection: withApproval() }) });
expect(app.hints()).toStartWith("y approve · Y always · n decline · j/k threads"); expect(app.hints()).toStartWith("y approve · Y always · n decline · j/k threads");
@@ -292,8 +348,9 @@ describe("mouse", () => {
test("right-clicking a thread opens its actions", async () => { test("right-clicking a thread opens its actions", async () => {
const app = await open(); const app = await open();
const row = app.find("135d"); // The list row is the "Thread" below the header; its relative age grows daily, so don't look for it.
await app.click(row.x, row.y, 2); const y = app.frame().split("\n").findIndex((line, index) => index > 0 && line.includes("Thread"));
await app.click(5, y, 2);
expect(app.hints()).toBe("↑/↓ move · enter choose · esc close"); expect(app.hints()).toBe("↑/↓ move · enter choose · esc close");
expect(app.frame()).toContain("Mark unread"); expect(app.frame()).toContain("Mark unread");
}); });
+105
View File
@@ -4,14 +4,39 @@ import * as DateTime from "effect/DateTime";
import { v2Projection } from "../../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts"; import { v2Projection } from "../../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts";
const at = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); const at = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
/** `seconds` after the fixture's start. */
const after = (seconds: number) => DateTime.makeUnsafe(DateTime.toEpochMillis(at) + seconds * 1_000);
/** The thread with a command waiting for approval. */ /** The thread with a command waiting for approval. */
export function withApproval(supportsFeedback = false): OrchestrationV2ThreadProjection { export function withApproval(supportsFeedback = false): OrchestrationV2ThreadProjection {
const item = {
id: "item-approval",
threadId: v2Projection.thread.id,
runId: null,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 0,
status: "waiting",
title: null,
startedAt: at,
completedAt: null,
updatedAt: at,
type: "approval_request",
requestId: "approval-1",
requestKind: "command",
prompt: "rm -rf dist && bun run build",
reason: "Deletes dist/ and rebuilds it.",
};
return { return {
...v2Projection, ...v2Projection,
runtimeRequests: [ runtimeRequests: [
{ id: "approval-1", nodeId: "node-1", providerTurnId: null, nativeRequestRef: null, kind: "command", status: "pending", responseCapability: { type: "live", providerSessionId: "session-1", ...(supportsFeedback ? { supportsFeedback } : {}) }, createdAt: at, resolvedAt: null }, { id: "approval-1", nodeId: "node-1", providerTurnId: null, nativeRequestRef: null, kind: "command", status: "pending", responseCapability: { type: "live", providerSessionId: "session-1", ...(supportsFeedback ? { supportsFeedback } : {}) }, createdAt: at, resolvedAt: null },
], ],
turnItems: [item],
visibleTurnItems: [{ position: 0, visibility: "local", sourceThreadId: v2Projection.thread.id, sourceItemId: item.id, item }],
} as unknown as OrchestrationV2ThreadProjection; } as unknown as OrchestrationV2ThreadProjection;
} }
@@ -54,6 +79,86 @@ export const omittedCommand = {
exitCode: 0, exitCode: 0,
} as const; } as const;
/** A finished turn: one prompt, one reply 3m 12s later, and a checkpoint of three changed files. */
export function withCompletedTurn(): OrchestrationV2ThreadProjection {
const base = {
threadId: v2Projection.thread.id,
runId: "run-1",
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
title: null,
};
const turnItems = [
{ ...base, id: "item-user", ordinal: 0, status: "completed", startedAt: at, completedAt: at, updatedAt: at, type: "user_message", createdBy: "user", creationSource: "web", messageId: "msg-user-1", inputIntent: "turn_start", text: "Do the thing", attachments: [] },
{ ...base, id: "item-edit", ordinal: 1, status: "completed", startedAt: after(60), completedAt: after(65), updatedAt: after(65), type: "file_change", fileName: "src/index.ts", additions: 30, deletions: 5 },
{ ...base, id: "item-assistant", ordinal: 2, status: "completed", startedAt: after(192), completedAt: after(192), updatedAt: after(192), type: "assistant_message", messageId: "msg-assistant-1", text: "Done — the thing is done.", streaming: false },
];
return {
...v2Projection,
runs: [
{ id: "run-1", threadId: v2Projection.thread.id, ordinal: 1, providerInstanceId: "codex", modelSelection: { instanceId: "codex", model: "gpt-5.4" }, providerThreadId: null, userMessageId: "msg-user-1", rootNodeId: null, activeAttemptId: null, status: "completed", requestedAt: at, startedAt: at, completedAt: after(192), checkpointId: "checkpoint-1", contextHandoffId: null },
],
messages: [
{ createdBy: "user", creationSource: "web", id: "msg-user-1", threadId: v2Projection.thread.id, runId: "run-1", nodeId: null, role: "user", text: "Do the thing", attachments: [], streaming: false, createdAt: at, updatedAt: at },
{ createdBy: "user", creationSource: "web", id: "msg-assistant-1", threadId: v2Projection.thread.id, runId: "run-1", nodeId: null, role: "assistant", text: "Done — the thing is done.", attachments: [], streaming: false, createdAt: after(192), updatedAt: after(192) },
],
checkpoints: [
{
id: "checkpoint-1",
threadId: v2Projection.thread.id,
scopeId: "scope-1",
runId: "run-1",
nodeId: null,
parentCheckpointId: null,
ordinalWithinScope: 0,
appRunOrdinal: 1,
ref: "refs/t3/checkpoint-1",
status: "ready",
files: [
{ path: "src/index.ts", kind: "modified", additions: 30, deletions: 5 },
{ path: "src/util.ts", kind: "modified", additions: 10, deletions: 2 },
{ path: "README.md", kind: "modified", additions: 2, deletions: 0 },
],
capturedAt: after(192),
},
],
turnItems,
visibleTurnItems: turnItems.map((item, position) => ({ position, visibility: "local", sourceThreadId: v2Projection.thread.id, sourceItemId: item.id, item })),
} as unknown as OrchestrationV2ThreadProjection;
}
/** A thread mid-run, with a command under way. */
export function withWorking(): OrchestrationV2ThreadProjection {
const base = {
threadId: v2Projection.thread.id,
runId: "run-1",
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
title: null,
};
const turnItems = [
{ ...base, id: "item-user", ordinal: 0, status: "completed", startedAt: at, completedAt: at, updatedAt: at, type: "user_message", createdBy: "user", creationSource: "web", messageId: "msg-user-1", inputIntent: "turn_start", text: "Run the tests", attachments: [] },
{ ...base, id: "item-cmd", ordinal: 1, status: "running", startedAt: after(10), completedAt: null, updatedAt: after(10), type: "command_execution", input: "bun test", output: "" },
];
return {
...v2Projection,
runs: [
{ id: "run-1", threadId: v2Projection.thread.id, ordinal: 1, providerInstanceId: "codex", modelSelection: { instanceId: "codex", model: "gpt-5.4" }, providerThreadId: null, userMessageId: "msg-user-1", rootNodeId: null, activeAttemptId: null, status: "running", requestedAt: at, startedAt: at, completedAt: null, checkpointId: null, contextHandoffId: null },
],
messages: [
{ createdBy: "user", creationSource: "web", id: "msg-user-1", threadId: v2Projection.thread.id, runId: "run-1", nodeId: null, role: "user", text: "Run the tests", attachments: [], streaming: false, createdAt: at, updatedAt: at },
],
turnItems,
visibleTurnItems: turnItems.map((item, position) => ({ position, visibility: "local", sourceThreadId: v2Projection.thread.id, sourceItemId: item.id, item })),
} as unknown as OrchestrationV2ThreadProjection;
}
export function withOmittedOutput(): OrchestrationV2ThreadProjection { export function withOmittedOutput(): OrchestrationV2ThreadProjection {
return { return {
...v2Projection, ...v2Projection,