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:
commit
4fe103b657
16 files changed
+633
-40
No files matched your search
@@ -61,7 +61,10 @@ Navigation:
|
||||
| `x` | dismiss the agent's question, or decline its secret request |
|
||||
| `enter` | with a secret request pending: type or paste the secret into a masked field (it never goes through the message box); `enter` saves it, `esc` cancels |
|
||||
| `Q` | go through queued messages: `j`/`k` move, `enter` sends one now (starts a turn, or steers it into the running one), `e` edits it in the message box (`enter` saves, `esc` cancels), `x` removes it. `alt+↑` in the message box edits the last one |
|
||||
| `e` | expand all folded turns and work groups |
|
||||
| `e` | expand all folded turns, work groups and command output |
|
||||
| `[` / `]` | select the previous / next turn; `esc` clears the selection |
|
||||
| `D` | view changes from the selected turn, or the latest turn with changes |
|
||||
| `R` | rewind to before the selected prompt, after confirmation |
|
||||
| `o` | load earlier turns |
|
||||
| `f` | find in the open thread; `enter` / `shift+enter` or `ctrl+n` / `ctrl+p` move between matches, `esc` closes |
|
||||
| `A` | show archived threads / return to active threads |
|
||||
@@ -79,9 +82,11 @@ Navigation:
|
||||
The layout follows T3 Code's web app, and much of it uses the web app's own code (vendored from upstream):
|
||||
|
||||
- **Sidebar:** the same sections (Pinned, Active, Working, then Snoozed and Settled folded to a count) and the same status words: `Working 2m`, `Waiting`, `Approval`, `Input`, `Request`, `Limited`, `Failed`, `Done`. Threads that need you are bold.
|
||||
- **Turns:** `[`/`]` select a turn and mark its prompt. `R` or `Revert to this turn` asks `Edit from here?`, then rewinds chat and returns the prompt to the composer, keeping file changes. `Revert files too` in the palette also restores files, including your own edits. Stop a running turn first. Rewinding messages with attachments still needs the web app.
|
||||
- **Command output:** expand work with `e` / `Expand all work`, or click a command. Output streams while its expanded row is in view; collapsing it, scrolling away or opening another thread stops the subscription.
|
||||
- **Conversation:** built by the web app's timeline logic. Each finished turn's work folds into one line (`Worked for 3m 12s`), your messages are right-aligned, and a running turn shows its live step and `Working for 12s`.
|
||||
- **Thread details:** a column beside the conversation with the workspace, model and mode, the branch with ahead/behind and its pull request, uncommitted changes per file, lineage (forks and subagents), background work and the goal. It opens by itself on terminals 160 columns or wider; on narrow ones `d` shows it in place of the conversation.
|
||||
- **Diffs:** pick `View diff` or a file under Changes to see uncommitted changes as unified diffs in place of the conversation. `j`/`k` scroll, `esc` closes.
|
||||
- **Diffs:** pick `View diff` or a file under Changes to see uncommitted changes as unified diffs in place of the conversation. `D` (or `View changes from this turn`) reviews a turn's checkpoint; `View all changes in this thread` reviews the whole thread. `j`/`k` scroll, `[`/`]` choose a file, and `esc` closes. In uncommitted diffs, `x` or `enter` shows the whole file, including unchanged context; press it again to collapse. Historical checkpoint context is unavailable, as in the web app.
|
||||
- **Git:** the branch section offers the web app's quick action (`Commit & push`, `Push`, `Create PR`…) and its menu. Every action asks first, says when you are on the default branch, and takes an optional commit message (blank lets T3 write one). Progress shows on the bottom line.
|
||||
- **Servers and automations:** local dev servers the thread started (stop one from the panel) and T3's scheduled tasks with their schedule and next run (run now, or turn on and off).
|
||||
- **Subagents:** subagent work in the conversation and the lineage rows in details are links; `enter` or a click opens the child thread, and `u` goes back. Idle subagents, which the thread list leaves out, are fetched from the server when you open one (on servers that serve them). A running subagent the web could stop gets a "Stop subagent" command in the palette.
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
"dependencies": {
|
||||
"@opentui/core": "0.2.7",
|
||||
"@opentui/react": "0.2.7",
|
||||
"diff": "9.0.0",
|
||||
"effect": "4.0.5",
|
||||
"mdast-util-directive": "^3.2.0",
|
||||
"micromark-extension-directive": "^4.0.0",
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"dependencies": {
|
||||
"@opentui/core": "0.2.7",
|
||||
"@opentui/react": "0.2.7",
|
||||
"diff": "9.0.0",
|
||||
"effect": "4.0.5",
|
||||
"mdast-util-directive": "^3.2.0",
|
||||
"micromark-extension-directive": "^4.0.0",
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import {
|
||||
CommandId,
|
||||
type OrchestrationGetTurnDiffInput,
|
||||
type OrchestrationGetFullThreadDiffInput,
|
||||
type ReviewDiffFileContentsInput,
|
||||
type OrchestrationV2Checkpoint,
|
||||
type TurnItemId,
|
||||
MessageId,
|
||||
ORCHESTRATION_PROTOCOL_HEADER,
|
||||
ORCHESTRATION_PROTOCOL_VERSION_TEXT,
|
||||
@@ -60,6 +65,7 @@ import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { applyShellStreamEvent, mergeShellSnapshotProjects } from "../../vendor/t3code/packages/client-runtime/src/state/shellReducer.ts";
|
||||
import { applyCommandOutputFrame, EMPTY_COMMAND_OUTPUT, type CommandOutputView } from "@t3tools/client-runtime/state/command-output";
|
||||
import { connect, type Connection } from "./rpc.ts";
|
||||
|
||||
export type ConnectionStatus =
|
||||
@@ -321,6 +327,68 @@ export class T3Session {
|
||||
return result.sources.find((source) => source.kind === "working-tree") ?? null;
|
||||
}
|
||||
|
||||
/** Checkpoint ranges, matching the web's turn and thread diff selections. */
|
||||
turnDiff(input: OrchestrationGetTurnDiffInput) {
|
||||
return Effect.runPromise(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.getTurnDiff](input));
|
||||
}
|
||||
|
||||
fullThreadDiff(input: OrchestrationGetFullThreadDiffInput) {
|
||||
return Effect.runPromise(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff](input));
|
||||
}
|
||||
|
||||
diffFileContents(input: ReviewDiffFileContentsInput) {
|
||||
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.reviewGetDiffFileContents](input));
|
||||
}
|
||||
|
||||
/** Expanded commands have no linger: closing their row stops the stream immediately. */
|
||||
watchCommandOutput(threadId: ThreadId, itemId: TurnItemId, listener: Listener<CommandOutputView>, onError: Listener<string>): () => void {
|
||||
let view = EMPTY_COMMAND_OUTPUT;
|
||||
const fiber = this.runInScope(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]({ threadId, itemId }).pipe(
|
||||
Stream.runForEach((frame) => Effect.sync(() => listener(view = applyCommandOutputFrame(view, frame)))),
|
||||
Effect.catchCause((cause) => Effect.sync(() => onError(prettyCause(cause)))),
|
||||
));
|
||||
return () => { Effect.runFork(Fiber.interrupt(fiber)); };
|
||||
}
|
||||
|
||||
/** Sends the checkpoint identity captured before opening the confirmation. */
|
||||
rollback(threadId: ThreadId, checkpoint: Pick<OrchestrationV2Checkpoint, "id" | "scopeId">, restoreFiles: boolean, commandId = newCommandId()): Promise<void> {
|
||||
return this.dispatch({ type: "checkpoint.rollback", commandId, threadId, scopeId: checkpoint.scopeId, checkpointId: checkpoint.id, restoreFiles });
|
||||
}
|
||||
|
||||
/** Waits for the settled suffix and provider conversation to rewind, as the web does. */
|
||||
async rewind(initial: OrchestrationV2ThreadProjection, checkpoint: Pick<OrchestrationV2Checkpoint, "id" | "scopeId">, turnCount: number, restoreFiles: boolean): Promise<void> {
|
||||
const witness = initial.runs.filter((run) => run.ordinal > turnCount && ["completed", "interrupted", "failed", "cancelled"].includes(run.status))
|
||||
.sort((a, b) => b.ordinal - a.ordinal)[0];
|
||||
if (!witness) throw new Error("The thread has changed. Select a message to rewind again.");
|
||||
const providerThread = initial.providerThreads.find((thread) => thread.id === initial.thread.activeProviderThreadId);
|
||||
const commandId = newCommandId();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
let accepted = false;
|
||||
let state: ThreadState | null = null;
|
||||
let unwatch = () => {};
|
||||
const finish = (error?: unknown) => {
|
||||
clearTimeout(timer);
|
||||
unwatch();
|
||||
if (error !== undefined) reject(error); else resolve();
|
||||
};
|
||||
const inspect = () => {
|
||||
const next = state?.projection;
|
||||
if (!next) return;
|
||||
if (next.thread.rollbackFailure?.requestId === commandId) return finish(new Error(next.thread.rollbackFailure.message));
|
||||
const providerRewound = next.providerThreads.some((thread) => {
|
||||
const sameThread = thread.id === providerThread?.id;
|
||||
const freshRoot = turnCount === 0 && thread.ownerNodeId === null && thread.appThreadId === initial.thread.id &&
|
||||
thread.providerInstanceId === providerThread?.providerInstanceId && !initial.providerThreads.some((old) => old.id === thread.id);
|
||||
return (sameThread || freshRoot) && thread.lastRunOrdinal === (turnCount === 0 ? null : turnCount);
|
||||
});
|
||||
if (accepted && providerRewound && next.runs.some((run) => run.id === witness.id && run.status === "rolled_back")) finish();
|
||||
};
|
||||
const timer = setTimeout(() => finish(new Error("Timed out waiting for the thread to rewind.")), 120_000);
|
||||
unwatch = this.watchThread(initial.thread.id, (next) => { state = next; inspect(); });
|
||||
this.rollback(initial.thread.id, checkpoint, restoreFiles, commandId).then(() => { accepted = true; inspect(); }, finish);
|
||||
});
|
||||
}
|
||||
|
||||
/** Runs a commit / push / PR action, reporting progress as it goes. Rejects with the server's message on failure. */
|
||||
async runGitAction(request: GitActionRequest, onProgress: Listener<GitActionProgressEvent>): Promise<GitRunStackedActionResult> {
|
||||
const rpc = this.requireConnection().rpc;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { createTwoFilesPatch, parsePatch } from "diff";
|
||||
import type { ReviewDiffFileContentsInput } from "@t3tools/contracts";
|
||||
|
||||
export interface PatchFile {
|
||||
readonly path: string;
|
||||
readonly oldPath: string;
|
||||
readonly changeType: ReviewDiffFileContentsInput["changeType"];
|
||||
readonly patch: string;
|
||||
}
|
||||
|
||||
/** Retains both paths so renamed and deleted files expand against the right revisions. */
|
||||
export function splitPatch(patch: string): PatchFile[] {
|
||||
return patch.split(/^(?=diff --git )/m).filter((chunk) => chunk.startsWith("diff --git ")).map((chunk) => {
|
||||
let parsed;
|
||||
try { parsed = parsePatch(chunk.split(/^@@ /m)[0]!)[0]; } catch { /* A truncated preview can end inside a file header. */ }
|
||||
const oldPath = cleanPath(parsed?.oldFileName ?? /^diff --git a\/(.+?) b\//.exec(chunk)?.[1] ?? "file");
|
||||
const newPath = cleanPath(parsed?.newFileName ?? oldPath);
|
||||
const renamed = /^rename from /m.test(chunk);
|
||||
return { path: newPath === "/dev/null" ? oldPath : newPath, oldPath: oldPath === "/dev/null" ? newPath : oldPath,
|
||||
changeType: parsed?.isCreate || oldPath === "/dev/null" ? "new" : parsed?.isDelete || newPath === "/dev/null" ? "deleted" : renamed ? /^@@ /m.test(chunk) ? "rename-changed" : "rename-pure" : "change", patch: chunk };
|
||||
});
|
||||
}
|
||||
|
||||
function cleanPath(path: string): string {
|
||||
return path.replace(/^[ab]\//, "");
|
||||
}
|
||||
|
||||
/** The same unified renderer can show all unchanged lines after loading both file versions. */
|
||||
export function wholeFilePatch(file: PatchFile, contents: { readonly oldContents: string; readonly newContents: string }): string {
|
||||
const patch = createTwoFilesPatch(file.oldPath, file.path, contents.oldContents, contents.newContents, undefined, undefined, { context: Infinity });
|
||||
if (contents.oldContents !== contents.newContents || contents.newContents.length === 0) return patch;
|
||||
const lines = contents.newContents.replace(/\n$/, "").split("\n");
|
||||
return `${patch}@@ -1,${lines.length} +1,${lines.length} @@\n${lines.map((line) => ` ${line}`).join("\n")}\n`;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { turnTargets, type TurnTarget } from "./turns.ts";
|
||||
import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
|
||||
import {
|
||||
deriveRunlessWorkStartedAt,
|
||||
@@ -28,6 +29,7 @@ export { liveWorkEntryLabel, workEntryDisplayLabel } from "../../vendor/t3code/a
|
||||
export interface Timeline {
|
||||
readonly rows: readonly MessagesTimelineRow[];
|
||||
readonly pending: PendingThreadRequests;
|
||||
readonly turns: readonly TurnTarget[];
|
||||
readonly isWorking: boolean;
|
||||
/** When the current run started working, for "Working for 12s". */
|
||||
readonly workStartedAt: string | null;
|
||||
@@ -53,7 +55,7 @@ const NOTHING = new Set<never>();
|
||||
|
||||
export function buildTimeline(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
options: { readonly expandAll: boolean },
|
||||
options: { readonly expandAll: boolean; readonly historyComplete: boolean },
|
||||
previous: Timeline | null,
|
||||
): Timeline {
|
||||
const cache = previous?.cache.expandAll === options.expandAll ? previous.cache : null;
|
||||
@@ -95,6 +97,7 @@ export function buildTimeline(
|
||||
return {
|
||||
rows: stable.result,
|
||||
pending,
|
||||
turns: turnTargets(projection, entries.entries, isWorking ? runtime?.activeRunId ?? null : null, options.historyComplete),
|
||||
isWorking,
|
||||
workStartedAt,
|
||||
cache: { entries, rows, stable, expandAll: options.expandAll },
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { MessageId, OrchestrationV2ThreadProjection, RunId } from "@t3tools/contracts";
|
||||
import { checkpointFileTotals, deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
import { deriveRevertTurnCountByUserMessageId, findRevertCheckpoint, type TimelineEntriesProjection } from "../../vendor/t3code/apps/web/src/session-logic.ts";
|
||||
|
||||
export { findRevertCheckpoint };
|
||||
export type TurnCheckpoint = ReturnType<typeof deriveThreadCheckpointSummaries>[number];
|
||||
export interface TurnTarget {
|
||||
readonly messageId: MessageId;
|
||||
readonly runId: RunId;
|
||||
readonly text: string;
|
||||
readonly hasAttachments: boolean;
|
||||
readonly checkpoint: TurnCheckpoint | undefined;
|
||||
readonly revertTurnCount: number | undefined;
|
||||
}
|
||||
|
||||
/** Uses the web's rewind mapping; run ordinals can have gaps after a rollback. */
|
||||
export function turnTargets(projection: OrchestrationV2ThreadProjection, entries: TimelineEntriesProjection["entries"], unsettledRunId: RunId | null, historyComplete: boolean): TurnTarget[] {
|
||||
const checkpoints = deriveThreadCheckpointSummaries(projection);
|
||||
const revertCounts = deriveRevertTurnCountByUserMessageId({
|
||||
timelineEntries: entries,
|
||||
checkpoints,
|
||||
threadStartCheckpointReady: historyComplete && findRevertCheckpoint(projection.checkpoints, 0) !== undefined,
|
||||
availableRevertTurnCounts: availableRevertTurnCounts(projection),
|
||||
unsettledRunId,
|
||||
});
|
||||
const seen = new Set<RunId>();
|
||||
return entries.flatMap((entry) => {
|
||||
if (entry.kind !== "message" || entry.message.role !== "user" || !entry.message.runId || seen.has(entry.message.runId)) return [];
|
||||
const message = entry.message;
|
||||
const runId = entry.message.runId;
|
||||
seen.add(runId);
|
||||
return [{ messageId: message.id, runId, text: message.text, hasAttachments: (message.attachments?.length ?? 0) > 0,
|
||||
checkpoint: checkpoints.findLast((checkpoint) => checkpoint.runId === message.runId), revertTurnCount: revertCounts.get(message.id) }];
|
||||
});
|
||||
}
|
||||
|
||||
/** Same provider-turn eligibility as ChatView.logic, without importing its browser state. */
|
||||
function availableRevertTurnCounts(projection: OrchestrationV2ThreadProjection): Set<number> {
|
||||
const available = new Set<number>();
|
||||
const providerThread = projection.providerThreads.find((thread) => thread.id === projection.thread.activeProviderThreadId);
|
||||
if (!providerThread?.providerSessionId || providerThread.providerInstanceId !== projection.thread.modelSelection.instanceId) return available;
|
||||
available.add(0);
|
||||
for (const run of projection.runs) {
|
||||
if (run.activeAttemptId === null) continue;
|
||||
const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId);
|
||||
const turn = projection.providerTurns.filter((candidate) => candidate.runAttemptId === run.activeAttemptId)
|
||||
.reduce<(typeof projection.providerTurns)[number] | undefined>((latest, candidate) => !latest || candidate.ordinal > latest.ordinal ? candidate : latest, undefined)
|
||||
?? projection.providerTurns.find((candidate) => candidate.id === attempt?.providerTurnId);
|
||||
if (turn?.providerThreadId === providerThread.id) available.add(run.ordinal);
|
||||
}
|
||||
return available;
|
||||
}
|
||||
|
||||
/** With no cursor, diff the most recent checkpoint that actually changed files. */
|
||||
export function diffTurn(turns: readonly TurnTarget[], selectedMessageId: string | null): TurnCheckpoint | undefined {
|
||||
return selectedMessageId !== null
|
||||
? turns.find((turn) => turn.messageId === selectedMessageId)?.checkpoint
|
||||
: turns.map((turn) => turn.checkpoint).filter((checkpoint): checkpoint is TurnCheckpoint => checkpoint !== undefined && checkpointFileTotals(checkpoint).count > 0)
|
||||
.sort((left, right) => right.checkpointTurnCount - left.checkpointTurnCount)[0];
|
||||
}
|
||||
|
||||
/** A cursor stays on its message when older history is prepended. */
|
||||
export function adjacentTurn(turns: readonly TurnTarget[], selectedMessageId: string | null, direction: -1 | 1): TurnTarget | undefined {
|
||||
const index = turns.findIndex((turn) => turn.messageId === selectedMessageId);
|
||||
return turns[index < 0 ? turns.length - 1 : Math.max(0, Math.min(turns.length - 1, index + direction))];
|
||||
}
|
||||
|
||||
+23
-6
@@ -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}
|
||||
|
||||
@@ -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
@@ -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
@@ -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 (
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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); }
|
||||
@@ -0,0 +1,29 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { parsePatch } from "diff";
|
||||
import { splitPatch, wholeFilePatch } from "../src/model/diffs.ts";
|
||||
|
||||
const changed = "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -2 +2 @@\n-old\n+new\n";
|
||||
|
||||
test("diff files retain old paths and change types for contents requests", () => {
|
||||
const files = splitPatch(changed + "diff --git a/old.ts b/new.ts\nsimilarity index 100%\nrename from old.ts\nrename to new.ts\n" + "diff --git a/gone.ts b/gone.ts\ndeleted file mode 100644\n--- a/gone.ts\n+++ /dev/null\n@@ -1 +0,0 @@\n-gone\n" + "diff --git a/add.ts b/add.ts\nnew file mode 100644\n--- /dev/null\n+++ b/add.ts\n@@ -0,0 +1 @@\n+added\n");
|
||||
expect(files.map(({ path, oldPath, changeType }) => ({ path, oldPath, changeType }))).toEqual([
|
||||
{ path: "a.ts", oldPath: "a.ts", changeType: "change" }, { path: "new.ts", oldPath: "old.ts", changeType: "rename-pure" },
|
||||
{ path: "gone.ts", oldPath: "gone.ts", changeType: "deleted" }, { path: "add.ts", oldPath: "add.ts", changeType: "new" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("whole-file expansion preserves unchanged context on both sides of the hunk", () => {
|
||||
const patch = wholeFilePatch(splitPatch(changed)[0]!, { oldContents: "before\nold\nafter\n", newContents: "before\nnew\nafter\n" });
|
||||
expect(parsePatch(patch)[0]?.hunks[0]).toMatchObject({ oldStart: 1, oldLines: 3, newStart: 1, newLines: 3, lines: [" before", "-old", "+new", " after"] });
|
||||
});
|
||||
|
||||
test("truncated patches keep their file identity without parsing an incomplete hunk", () => {
|
||||
expect(splitPatch(changed.slice(0, -4))[0]?.path).toBe("a.ts");
|
||||
expect(splitPatch("diff --git a/a.ts b/a.ts\n--- a/a.ts\n")[0]?.path).toBe("a.ts");
|
||||
});
|
||||
|
||||
test("whole-file expansion can show a pure rename with identical contents", () => {
|
||||
const file = splitPatch("diff --git a/old.ts b/new.ts\nsimilarity index 100%\nrename from old.ts\nrename to new.ts\n")[0]!;
|
||||
const patch = wholeFilePatch(file, { oldContents: "unchanged\n", newContents: "unchanged\n" });
|
||||
expect(parsePatch(patch)[0]?.hunks[0]?.lines).toEqual([" unchanged"]);
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { CheckpointId, CheckpointRef, CheckpointScopeId, MessageId, NodeId, ProviderSessionId, ProviderThreadId, ProviderTurnId, RunAttemptId, RunId, type OrchestrationV2ThreadProjection } from "@t3tools/contracts";
|
||||
import type { TimelineEntriesProjection } from "../vendor/t3code/apps/web/src/session-logic.ts";
|
||||
import { v2Now, v2Projection } from "../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts";
|
||||
import { adjacentTurn, diffTurn, findRevertCheckpoint, turnTargets } from "../src/model/turns.ts";
|
||||
|
||||
const providerThreadId = ProviderThreadId.make("pt");
|
||||
const scopeId = CheckpointScopeId.make("scope");
|
||||
function checkpoint(ordinal: number, runOrdinal: number | null = ordinal) {
|
||||
return { id: CheckpointId.make(`cp-${ordinal}`), threadId: v2Projection.thread.id, scopeId, runId: runOrdinal === null ? null : RunId.make(`run-${runOrdinal}`), nodeId: NodeId.make("node"), parentCheckpointId: null, ordinalWithinScope: ordinal, appRunOrdinal: runOrdinal, ref: CheckpointRef.make(`refs/checkpoints/${ordinal}`), status: "ready" as const,
|
||||
files: ordinal === 2 ? [] : [{ path: "file.ts", kind: "modified", additions: 1, deletions: 0 }], capturedAt: v2Now };
|
||||
}
|
||||
function entries(): TimelineEntriesProjection["entries"] {
|
||||
return [1, 2, 5].flatMap((ordinal) => [{ kind: "message" as const, id: `user-${ordinal}`, createdAt: "2026-06-20T00:00:00.000Z", message: { id: MessageId.make(`user-${ordinal}`), role: "user" as const, text: `prompt ${ordinal}`, runId: RunId.make(`run-${ordinal}`), streaming: false, inputIntent: "turn_start" as const, createdAt: "2026-06-20T00:00:00.000Z", updatedAt: "2026-06-20T00:00:00.000Z" } }]);
|
||||
}
|
||||
function projection(): OrchestrationV2ThreadProjection {
|
||||
const runs = [1, 2, 5].map((ordinal) => ({ id: RunId.make(`run-${ordinal}`), ordinal, activeAttemptId: RunAttemptId.make(`attempt-${ordinal}`), status: "completed" }));
|
||||
return { ...v2Projection, thread: { ...v2Projection.thread, activeProviderThreadId: providerThreadId }, checkpoints: [checkpoint(0, null), checkpoint(1), checkpoint(2), checkpoint(3, 5)],
|
||||
runs, attempts: [], providerThreads: [{ id: providerThreadId, providerSessionId: ProviderSessionId.make("session"), providerInstanceId: v2Projection.thread.modelSelection.instanceId }],
|
||||
providerTurns: runs.map((run) => ({ id: ProviderTurnId.make(`pt-${run.ordinal}`), runAttemptId: run.activeAttemptId, ordinal: run.ordinal, providerThreadId })),
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
}
|
||||
|
||||
describe("turn cursor and checkpoint targets", () => {
|
||||
test("navigates by message identity after earlier turns load", () => {
|
||||
const turns = turnTargets(projection(), entries(), null, true);
|
||||
expect(adjacentTurn(turns, null, -1)?.messageId).toBe(MessageId.make("user-5"));
|
||||
expect(adjacentTurn(turns, "user-5", -1)?.messageId).toBe(MessageId.make("user-2"));
|
||||
expect(adjacentTurn(turns, "user-1", -1)?.messageId).toBe(MessageId.make("user-1"));
|
||||
expect(adjacentTurn(turns, "user-5", 1)?.messageId).toBe(MessageId.make("user-5"));
|
||||
expect(adjacentTurn([], null, -1)).toBeUndefined();
|
||||
});
|
||||
test("rewinds before the prompt, using visible predecessors across ordinal gaps", () => {
|
||||
const turns = turnTargets(projection(), entries(), null, true);
|
||||
expect(turns.map((turn) => turn.revertTurnCount)).toEqual([0, 1, 2]);
|
||||
expect(findRevertCheckpoint(projection().checkpoints, turns[2]!.revertTurnCount!)?.id).toBe(CheckpointId.make("cp-2"));
|
||||
});
|
||||
test("does not mistake the first message in paged history for the thread start", () => {
|
||||
const turns = turnTargets(projection(), entries().slice(1), null, false);
|
||||
expect(turns.map((turn) => turn.revertTurnCount)).toEqual([undefined, 2]);
|
||||
});
|
||||
test("does not offer a running turn or a detached provider conversation for rollback", () => {
|
||||
expect(turnTargets(projection(), entries(), RunId.make("run-5"), true)[2]?.revertTurnCount).toBeUndefined();
|
||||
expect(turnTargets({ ...projection(), providerThreads: [] }, entries(), null, true).every((turn) => turn.revertTurnCount === undefined)).toBe(true);
|
||||
});
|
||||
test("defaults to the latest changed turn; a selection never falls back to another turn", () => {
|
||||
const turns = turnTargets(projection(), entries(), null, true);
|
||||
expect(diffTurn(turns, null)?.checkpointTurnCount).toBe(5);
|
||||
expect(diffTurn(turns.slice(0, 2), null)?.checkpointTurnCount).toBe(1);
|
||||
expect(diffTurn(turns, "user-2")?.checkpointTurnCount).toBe(2);
|
||||
expect(diffTurn(turns, "missing")).toBeUndefined();
|
||||
});
|
||||
test("keeps only one anchor for a turn with steering messages", () => {
|
||||
const all = entries();
|
||||
const first = all[0]!;
|
||||
expect(turnTargets(projection(), [first, first, ...all.slice(1)], null, true)).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { CheckpointId, CheckpointScopeId, OrchestrationGetFullThreadDiffInput, OrchestrationGetTurnDiffInput, OrchestrationV2Command, ProviderThreadId, ReviewDiffFileContentsInput, RunId, ThreadId, TurnItemId, type OrchestrationV2ThreadProjection } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { T3Session, type ThreadState } from "../src/client/session.ts";
|
||||
import { v2Projection } from "../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts";
|
||||
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const checkpoint = { id: CheckpointId.make("checkpoint-before-selected-prompt"), scopeId: CheckpointScopeId.make("root-scope") };
|
||||
|
||||
describe("turn RPCs without a server", () => {
|
||||
test("both rollback choices dispatch the captured checkpoint and validate against the contract", async () => {
|
||||
const session = new T3Session();
|
||||
const sent: unknown[] = [];
|
||||
Object.assign(session, { dispatch: async (command: unknown) => { sent.push(command); } });
|
||||
await session.rollback(threadId, checkpoint, false);
|
||||
await session.rollback(threadId, checkpoint, true);
|
||||
expect(sent.every(Schema.is(OrchestrationV2Command))).toBe(true);
|
||||
expect(sent[0]).toMatchObject({ type: "checkpoint.rollback", threadId, checkpointId: checkpoint.id, scopeId: checkpoint.scopeId, restoreFiles: false });
|
||||
expect(sent[1]).toMatchObject({ restoreFiles: true });
|
||||
expect(sent[0]).not.toHaveProperty("turnCount");
|
||||
});
|
||||
|
||||
test("checkpoint ranges and file-contents requests match the RPC schemas", async () => {
|
||||
const session = new T3Session();
|
||||
const sent: { method: string; input: unknown }[] = [];
|
||||
const rpc = Object.fromEntries(["orchestration.getTurnDiff", "orchestration.getFullThreadDiff", "review.getDiffFileContents"].map((method) => [method, (input: unknown) => { sent.push({ method, input }); return Effect.succeed({ diff: "", oldContents: "old", newContents: "new" }); }]));
|
||||
Object.assign(session, { connection: { rpc } });
|
||||
await session.turnDiff({ threadId, fromTurnCount: 4, toTurnCount: 5, ignoreWhitespace: true });
|
||||
await session.fullThreadDiff({ threadId, toTurnCount: 5, ignoreWhitespace: false });
|
||||
await session.diffFileContents({ cwd: "/workspace", sourceKind: "working-tree", baseRef: "HEAD", headRef: null, oldPath: "old.ts", newPath: "new.ts", changeType: "rename-changed" });
|
||||
expect(Schema.is(OrchestrationGetTurnDiffInput)(sent[0]?.input)).toBe(true);
|
||||
expect(Schema.is(OrchestrationGetFullThreadDiffInput)(sent[1]?.input)).toBe(true);
|
||||
expect(Schema.is(ReviewDiffFileContentsInput)(sent[2]?.input)).toBe(true);
|
||||
expect(sent.map((request) => request.method)).toEqual(["orchestration.getTurnDiff", "orchestration.getFullThreadDiff", "review.getDiffFileContents"]);
|
||||
});
|
||||
|
||||
test("expanded output normalizes frames and unsubscribes immediately", async () => {
|
||||
const session = new T3Session();
|
||||
let finishStream!: () => void;
|
||||
const finished = new Promise<void>((resolve) => { finishStream = resolve; });
|
||||
let receive!: () => void;
|
||||
const received = new Promise<void>((resolve) => { receive = resolve; });
|
||||
const outputs: string[] = [];
|
||||
const stream = Stream.concat(Stream.make(
|
||||
{ kind: "replace" as const, text: "first\n", running: true, truncated: false },
|
||||
{ kind: "append" as const, text: "second", running: true, truncated: false },
|
||||
), Stream.never).pipe(Stream.ensuring(Effect.sync(finishStream)));
|
||||
Object.assign(session, { connection: { rpc: { "orchestration.subscribeCommandOutput": (input: unknown) => {
|
||||
expect(input).toEqual({ threadId, itemId: TurnItemId.make("command-1") });
|
||||
return stream;
|
||||
} } }, runInScope: Effect.runFork });
|
||||
const close = session.watchCommandOutput(threadId, TurnItemId.make("command-1"), (view) => { outputs.push(view.output.text); if (outputs.length === 2) receive(); }, (error) => { throw new Error(error); });
|
||||
await received;
|
||||
close();
|
||||
await finished;
|
||||
expect(outputs).toEqual(["first\n", "first\nsecond"]);
|
||||
});
|
||||
});
|
||||
|
||||
function rewindSession() {
|
||||
const session = new T3Session();
|
||||
const providerThreadId = ProviderThreadId.make("provider-thread");
|
||||
const initial = { ...v2Projection, thread: { ...v2Projection.thread, activeProviderThreadId: providerThreadId }, runs: [{ id: RunId.make("run-5"), ordinal: 5, status: "completed" }], providerThreads: [{ id: providerThreadId, lastRunOrdinal: 5 }] } as unknown as OrchestrationV2ThreadProjection;
|
||||
let observe!: (state: ThreadState) => void;
|
||||
let command: { commandId: string } | undefined;
|
||||
let closed = false;
|
||||
Object.assign(session, { watchThread: (_: unknown, listener: (state: ThreadState) => void) => { observe = listener; return () => { closed = true; }; }, dispatch: async (next: { commandId: string }) => { command = next; } });
|
||||
const emit = (projection: OrchestrationV2ThreadProjection) => observe({ status: "live", projection, history: { cursor: null, hasMore: false, loading: false } });
|
||||
return { session, initial, emit, command: () => command!, closed: () => closed };
|
||||
}
|
||||
|
||||
test("rewind waits for the rolled-back suffix and the provider conversation, not just command acceptance", async () => {
|
||||
const rig = rewindSession();
|
||||
let resolved = false;
|
||||
const pending = rig.session.rewind(rig.initial, checkpoint, 2, false).then(() => { resolved = true; });
|
||||
await Promise.resolve();
|
||||
rig.emit(rig.initial);
|
||||
await Promise.resolve();
|
||||
expect(resolved).toBe(false);
|
||||
const next = { ...rig.initial, runs: rig.initial.runs.map((run) => ({ ...run, status: "rolled_back" as const })) };
|
||||
rig.emit(next);
|
||||
await Promise.resolve();
|
||||
expect(resolved).toBe(false);
|
||||
rig.emit({ ...next, providerThreads: next.providerThreads.map((thread) => ({ ...thread, lastRunOrdinal: 2 })) });
|
||||
await pending;
|
||||
expect(resolved).toBe(true);
|
||||
expect(rig.closed()).toBe(true);
|
||||
});
|
||||
|
||||
test("rewind reports the matching server failure and closes its listener", async () => {
|
||||
const rig = rewindSession();
|
||||
const pending = rig.session.rewind(rig.initial, checkpoint, 2, true);
|
||||
rig.emit({ ...rig.initial, thread: { ...rig.initial.thread, rollbackFailure: { requestId: rig.command().commandId, message: "cannot restore" } } } as OrchestrationV2ThreadProjection);
|
||||
await expect(pending).rejects.toThrow("cannot restore");
|
||||
expect(rig.closed()).toBe(true);
|
||||
});
|
||||
Reference in new issue
Block a user