Match T3 Code's sidebar, timeline and composer

Reuse the web app's timeline derivation (turn folds, work groups, live
work), its sidebar sections and status words, steer-by-default sending,
the question panel, decline-with-feedback, and visit/read marking.
This commit is contained in:
Callum Alpass committed 2026-11-02 17:35:56 +11:00
1 parent 4f42407099
commit 2dac4763d2
17 files changed
+988 -430

No files matched your search

+120 -42
View File
@@ -1,66 +1,142 @@
import type { OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ProjectId } from "@t3tools/contracts";
import type { EnvironmentId, OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ProjectId } from "@t3tools/contracts";
import { formatWorkingDurationLabel, presentThreadShell, resolveThreadWorkingStartedAt, type EnvironmentThreadShell } from "@t3tools/client-runtime/state/models";
import { isThreadWorking, sortInboxThreadsByReturn, sortWorkingThreadsBySend } from "@t3tools/client-runtime/state/thread-inbox";
import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import { sortPinnedThreadsByOrderKey, sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort";
import * as DateTime from "effect/DateTime";
export type ThreadGroup = "needs-you" | "running" | "recent";
/** The web sidebar's sections, in its order. Active has no header unless others show. */
export type Section = "pinned" | "active" | "working" | "snoozed" | "settled";
/** The web sidebar's row status (resolveSidebarThreadStatus). */
export type ThreadStatus = "approval" | "input" | "request" | "waiting" | "working" | "limited" | "failed" | "ready";
export interface ThreadRow {
readonly thread: OrchestrationV2ThreadShell;
readonly group: ThreadGroup;
readonly shell: EnvironmentThreadShell;
readonly section: Section;
readonly status: ThreadStatus;
/** Finished since you last opened it. */
readonly unread: boolean;
readonly projectName: string;
}
export const GROUP_LABELS: Record<ThreadGroup, string> = {
"needs-you": "Needs you",
running: "Running",
recent: "Recent",
export const SECTION_LABELS: Record<Section, string> = {
pinned: "Pinned",
active: "Active",
working: "Working",
snoozed: "Snoozed",
settled: "Settled",
};
const ACTIVE_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
export const SECTION_ORDER: readonly Section[] = ["pinned", "active", "working", "snoozed", "settled"];
export function needsUser(thread: OrchestrationV2ThreadShell): boolean {
return thread.pendingRuntimeRequest !== null && thread.pendingRuntimeRequest.blocking !== false;
/** Only one server, so any constant id works for presentThreadShell. */
const LOCAL_ENVIRONMENT = "local" as EnvironmentId;
export function resolveStatus(shell: EnvironmentThreadShell): ThreadStatus {
if (shell.hasPendingApprovals || shell.pendingSubagentRequest === "approval") return "approval";
if (shell.hasPendingUserInput || shell.pendingSubagentRequest === "user_input") return "input";
if ((shell.pendingGuestMessageCount ?? 0) > 0) return "request";
const runtime = shell.runtime;
if (runtime?.status === "running" && shell.blockedOnThreadWait) return "waiting";
if (runtime && ["preparing", "queued", "starting", "running", "waiting"].includes(runtime.status)) return "working";
if (runtime?.status === "idle") return "waiting";
if (runtime?.status === "failed") return runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
return "ready";
}
export function isRunning(thread: OrchestrationV2ThreadShell): boolean {
return thread.activeRunId !== null || ACTIVE_STATUSES.has(thread.status);
export function hasUnseenCompletion(shell: EnvironmentThreadShell): boolean {
const completedAt = Date.parse(shell.latestRun?.completedAt ?? "");
if (Number.isNaN(completedAt) || !shell.lastVisitedAt) return false;
const visitedAt = Date.parse(shell.lastVisitedAt);
return Number.isNaN(visitedAt) || completedAt > visitedAt;
}
export function groupOf(thread: OrchestrationV2ThreadShell): ThreadGroup {
if (needsUser(thread)) return "needs-you";
if (isRunning(thread)) return "running";
return "recent";
/** Whether the thread is waiting on you: the rows the web sidebar shows in bold. */
export function needsAttention(row: Pick<ThreadRow, "status" | "unread">): boolean {
return row.status === "approval" || row.status === "input" || row.status === "request" || row.status === "failed" || row.status === "limited" || row.unread;
}
/** The sidebar's top-right status word, or null to show the time instead. */
export function statusLabel(row: ThreadRow, now = Date.now()): { readonly text: string; readonly tone: StatusTone } | null {
switch (row.status) {
case "working": {
const label = row.shell.goal?.status === "active" ? "Goal" : "Working";
const since = resolveThreadWorkingStartedAt(row.shell);
return { text: since ? `${label} ${formatWorkingDurationLabel(now - Date.parse(since))}` : label, tone: "info" };
}
case "waiting":
return { text: "Waiting", tone: "muted" };
case "approval":
return { text: "Approval", tone: "warn" };
case "input":
return { text: "Input", tone: "input" };
case "request":
return { text: "Request", tone: "input" };
case "limited":
return { text: "Limited", tone: "warn" };
case "failed":
return { text: "Failed", tone: "bad" };
case "ready":
return row.unread ? { text: "Done", tone: "good" } : null;
}
}
export type StatusTone = "info" | "muted" | "warn" | "input" | "bad" | "good";
/** Threads in the web sidebar's sections and order. Subagent threads stay under their parent, so they're left out. */
export function threadRows(
snapshot: OrchestrationV2ShellSnapshot | null,
options: { readonly query?: string; readonly settledLimit?: number; readonly now?: string } = {},
): ThreadRow[] {
if (!snapshot) return [];
const projects = new Map<ProjectId, OrchestrationProjectShell>(snapshot.projects.map((project) => [project.id, project]));
const query = options.query?.trim().toLowerCase();
const now = options.now ?? new Date().toISOString();
const bySection: Record<Section, EnvironmentThreadShell[]> = { pinned: [], active: [], working: [], snoozed: [], settled: [] };
for (const thread of snapshot.threads) {
if (thread.archivedAt !== null || thread.deletedAt !== null || thread.lineage.relationshipToParent === "subagent") continue;
const projectName = projectLabel(projects.get(thread.projectId));
if (query && !thread.title.toLowerCase().includes(query) && !projectName.toLowerCase().includes(query)) continue;
const shell = presentThreadShell(LOCAL_ENVIRONMENT, thread);
const section: Section = effectiveSnoozed(shell, { now })
? "snoozed"
: shell.settledOverride === "settled"
? "settled"
: shell.pinnedAt != null
? "pinned"
: isThreadWorking(shell)
? "working"
: "active";
bySection[section].push(shell);
}
const sorted: Record<Section, EnvironmentThreadShell[]> = {
pinned: sortPinnedThreadsByOrderKey(bySection.pinned),
active: sortInboxThreadsByReturn(bySection.active),
working: sortWorkingThreadsBySend(bySection.working),
snoozed: bySection.snoozed.toSorted((a, b) => Date.parse(a.snoozedUntil ?? "") - Date.parse(b.snoozedUntil ?? "")),
settled: sortSettledThreads(bySection.settled).slice(0, options.settledLimit ?? 30),
};
return SECTION_ORDER.flatMap((section) =>
sorted[section].map((shell) => ({
thread: shell.source as OrchestrationV2ThreadShell,
shell,
section,
status: resolveStatus(shell),
unread: hasUnseenCompletion(shell),
projectName: projectLabel(projects.get(shell.projectId)),
})),
);
}
export function lastActivity(thread: OrchestrationV2ThreadShell): number {
return DateTime.toEpochMillis(thread.updatedAt);
}
const millis = (value: DateTime.Utc | null | undefined) => (value ? DateTime.toEpochMillis(value) : 0);
/**
* Sort key within a group. Active threads update every second while they
* stream, so they sort by something that holds still: when they started
* waiting on you, or when their run began.
*/
export function sortKey(thread: OrchestrationV2ThreadShell, group: ThreadGroup): number {
if (group === "needs-you") return millis(thread.pendingRuntimeRequest?.createdAt) || millis(thread.createdAt);
if (group === "running") return millis(thread.latestRunStartedAt) || millis(thread.latestRunRequestedAt) || millis(thread.createdAt);
return lastActivity(thread);
}
/** Threads in display order: the ones waiting on you, then running, then the most recent. */
export function threadRows(snapshot: OrchestrationV2ShellSnapshot | null, options: { readonly recentLimit?: number; readonly query?: string } = {}): ThreadRow[] {
if (!snapshot) return [];
const projects = new Map<ProjectId, OrchestrationProjectShell>(snapshot.projects.map((project) => [project.id, project]));
const query = options.query?.trim().toLowerCase();
const order: ThreadGroup[] = ["needs-you", "running", "recent"];
const rows = snapshot.threads
.map((thread) => ({ thread, group: groupOf(thread), projectName: projectLabel(projects.get(thread.projectId)) }))
.filter((row) => !query || row.thread.title.toLowerCase().includes(query) || row.projectName.toLowerCase().includes(query))
.sort((a, b) => order.indexOf(a.group) - order.indexOf(b.group) || sortKey(b.thread, b.group) - sortKey(a.thread, a.group) || a.thread.id.localeCompare(b.thread.id));
const limit = options.recentLimit ?? 60;
let recent = 0;
return rows.filter((row) => row.group !== "recent" || recent++ < limit);
/** The time the sidebar shows: your latest message, else the last update. */
export function rowTime(thread: OrchestrationV2ThreadShell): number {
return thread.latestUserMessageAt ? DateTime.toEpochMillis(thread.latestUserMessageAt) : lastActivity(thread);
}
export function projectLabel(project: OrchestrationProjectShell | undefined): string {
@@ -84,8 +160,10 @@ export function shortId(id: string): string {
return id.slice(-8);
}
/** Compact relative time, like the sidebar's: "now", "45s", "3m", "2h", "4d". */
export function relativeTime(ms: number, now = Date.now()): string {
const seconds = Math.max(0, Math.round((now - ms) / 1000));
if (seconds < 5) return "now";
if (seconds < 60) return `${seconds}s`;
const minutes = Math.round(seconds / 60);
if (minutes < 60) return `${minutes}m`;
+102
View File
@@ -0,0 +1,102 @@
import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
import {
deriveRunlessWorkStartedAt,
deriveThreadActivityRun,
deriveThreadStructureRuntime,
} from "@t3tools/client-runtime/state/thread-execution";
import { derivePendingThreadRequests, type PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
// The web app's own timeline derivation: tui3 shows the same rows, folds and labels.
import {
computeStableMessagesTimelineRows,
deriveMessagesTimelineRowsWithState,
type MessagesTimelineRow,
type MessagesTimelineRowsInput,
type StableMessagesTimelineRowsState,
} from "../../vendor/t3code/apps/web/src/components/chat/MessagesTimeline.logic.ts";
import {
deriveActiveWorkStartedAt,
derivePhase,
deriveTimelineEntriesFromVisibleTurnItemsWithState,
type TimelineEntriesProjection,
} from "../../vendor/t3code/apps/web/src/session-logic.ts";
export type { MessagesTimelineRow } from "../../vendor/t3code/apps/web/src/components/chat/MessagesTimeline.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 interface Timeline {
readonly rows: readonly MessagesTimelineRow[];
readonly pending: PendingThreadRequests;
readonly isWorking: boolean;
/** When the current run started working, for "Working for 12s". */
readonly workStartedAt: string | null;
/** Carried into the next build so unchanged rows keep their identity. */
readonly cache: TimelineCache;
}
interface TimelineCache {
readonly entries: TimelineEntriesProjection;
readonly rows: { readonly input: MessagesTimelineRowsInput; readonly rows: MessagesTimelineRow[] };
readonly stable: StableMessagesTimelineRowsState;
readonly expandAll: boolean;
}
/** Answers yes for every id: "expand everything" without knowing the group ids up front. */
class EverySet<T> extends Set<T> {
override has(): boolean {
return true;
}
}
const EVERYTHING = new EverySet<never>();
const NOTHING = new Set<never>();
export function buildTimeline(
projection: OrchestrationV2ThreadProjection,
options: { readonly expandAll: boolean },
previous: Timeline | null,
): Timeline {
const cache = previous?.cache.expandAll === options.expandAll ? previous.cache : null;
const entries = deriveTimelineEntriesFromVisibleTurnItemsWithState(
{
visibleTurnItems: projection.visibleTurnItems,
optimisticMessages: [],
attempts: projection.attempts,
nodes: projection.nodes,
plans: projection.plans,
},
cache?.entries ?? null,
);
const runtime = deriveThreadStructureRuntime(projection);
const latestRun = deriveThreadActivityRun(projection);
const runlessStartedAt = deriveRunlessWorkStartedAt(projection);
const isWorking = derivePhase(runtime) === "running" || runlessStartedAt !== null;
const workStartedAt = deriveActiveWorkStartedAt(latestRun, runtime, null) ?? runlessStartedAt;
const pending = derivePendingThreadRequests(projection);
const expanded = options.expandAll ? EVERYTHING : NOTHING;
const rows = deriveMessagesTimelineRowsWithState(
{
timelineEntries: entries.entries,
pendingApprovalRequestIds: new Set(pending.approvals.map((approval) => approval.requestId)),
latestRun,
runningRunId: runtime?.activeRunId ?? null,
expandedRunIds: expanded,
expandedAttemptIds: expanded,
expandedWorkGroupIds: expanded,
isWorking,
runlessWorkActive: runlessStartedAt !== null,
activeTurnStartedAt: workStartedAt,
turnDiffSummaries: [],
supportsConversationRollback: false,
},
cache?.rows ?? null,
);
const stable = computeStableMessagesTimelineRows(rows.rows, cache?.stable ?? { byId: new Map(), result: [] });
return {
rows: stable.result,
pending,
isWorking,
workStartedAt,
cache: { entries, rows, stable, expandAll: options.expandAll },
};
}
+2 -104
View File
@@ -1,6 +1,6 @@
import type { OrchestrationV2ThreadProjection, OrchestrationV2TurnItem, RuntimeRequestId } from "@t3tools/contracts";
import type { OrchestrationV2TurnItem, RuntimeRequestId } from "@t3tools/contracts";
/** One rendered row of the transcript. Markdown blocks get the markdown renderer; the rest are plain lines. */
/** A turn item as one line or card: the fallback for timeline event rows the web app renders specially. */
export type Block =
| { readonly kind: "user"; readonly id: string; readonly text: string }
| { readonly kind: "assistant"; readonly id: string; readonly markdown: string; readonly streaming: boolean }
@@ -12,110 +12,8 @@ export type Block =
export type Tone = "normal" | "muted" | "good" | "bad" | "warn";
/** Tool calls, reasoning and minor notices: the agent's working, as opposed to what it says. */
export type Step = Extract<Block, { kind: "tool" | "reasoning" | "notice" }>;
/** What the conversation view renders: messages stand alone, runs of work fold into one segment. */
export type Segment =
| Extract<Block, { kind: "user" | "assistant" | "approval" | "question" }>
| { readonly kind: "work"; readonly id: string; readonly steps: readonly Step[]; readonly active: boolean }
| { readonly kind: "alert"; readonly id: string; readonly text: string; readonly tone: Tone };
export interface Transcript {
readonly segments: readonly Segment[];
/** Turn items left out because only the tail is shown. */
readonly hiddenCount: number;
}
const OUTPUT_TAIL_LINES = 3;
/** Blocks keyed by turn item object: the projection reducer keeps unchanged items identical. */
const blockCache = new WeakMap<object, Block | null>();
function cachedBlock(item: OrchestrationV2TurnItem, pending: ReadonlySet<string>): Block | null {
// Approval and question blocks depend on request state, not just the item.
if (item.type === "approval_request" || item.type === "user_input_request") return blockFor(item, pending);
let block = blockCache.get(item);
if (block === undefined) {
block = blockFor(item, pending);
blockCache.set(item, block);
}
return block;
}
export function buildTranscript(
projection: OrchestrationV2ThreadProjection,
options: { readonly tail?: number; readonly running?: boolean; readonly previous?: Transcript | null } = {},
): Transcript {
const pending = new Set(projection.runtimeRequests.filter((request) => request.status === "pending").map((request) => request.id as string));
const items = projection.visibleTurnItems;
const tail = options.tail ?? 200;
const start = Math.max(0, items.length - tail);
const segments: Segment[] = [];
let work: Step[] | null = null;
const flushWork = () => {
if (work && work.length > 0) segments.push({ kind: "work", id: `work-${work[0]!.id}`, steps: work, active: false });
work = null;
};
for (let index = start; index < items.length; index++) {
const block = cachedBlock(items[index]!.item, pending);
if (!block) continue;
if (block.kind === "tool" || block.kind === "reasoning" || (block.kind === "notice" && block.tone !== "bad" && block.tone !== "warn")) {
(work ??= []).push(block);
continue;
}
flushWork();
segments.push(block.kind === "notice" ? { kind: "alert", id: block.id, text: block.text, tone: block.tone } : block);
}
flushWork();
const last = segments.at(-1);
if (options.running && last?.kind === "work") segments[segments.length - 1] = { ...last, active: true };
return { segments: reuseUnchanged(segments, options.previous ?? null), hiddenCount: start };
}
/** Keeps the previous segment object when nothing in it changed, so memoized views skip it. */
function reuseUnchanged(segments: Segment[], previous: Transcript | null): Segment[] {
if (!previous) return segments;
const byId = new Map(previous.segments.map((segment) => [segment.id, segment]));
return segments.map((segment) => {
const old = byId.get(segment.id);
return old && sameSegment(old, segment) ? old : segment;
});
}
function sameSegment(a: Segment, b: Segment): boolean {
if (a === b) return true;
if (a.kind !== b.kind) return false;
if (a.kind === "work" && b.kind === "work") {
return a.active === b.active && a.steps.length === b.steps.length && a.steps.every((step, index) => step === b.steps[index]);
}
return shallowEqual(a as unknown as Record<string, unknown>, b as unknown as Record<string, unknown>);
}
function shallowEqual(a: Record<string, unknown>, b: Record<string, unknown>): boolean {
const keys = Object.keys(a);
return keys.length === Object.keys(b).length && keys.every((key) => Object.is(a[key], b[key]) || (Array.isArray(a[key]) && Array.isArray(b[key]) && shallowEqualArray(a[key] as unknown[], b[key] as unknown[])));
}
function shallowEqualArray(a: unknown[], b: unknown[]): boolean {
return a.length === b.length && a.every((value, index) => Object.is(value, b[index]));
}
/** One line describing a folded run of work, e.g. "5 commands · 3 edits · 2 searches". */
export function summarizeWork(steps: readonly Step[]): string {
const counts = new Map<string, number>();
const bump = (label: string) => counts.set(label, (counts.get(label) ?? 0) + 1);
for (const step of steps) {
if (step.kind === "reasoning") continue;
if (step.kind === "notice") bump("update");
else bump(STEP_LABELS[step.icon] ?? "tool call");
}
const parts = [...counts].sort((a, b) => b[1] - a[1]).map(([label, count]) => `${count} ${count === 1 ? label : `${label}s`}`);
return parts.length > 0 ? parts.join(" · ") : "thinking";
}
const STEP_LABELS: Record<string, string> = { $: "command", "✎": "edit", "⌕": "search", "⚙": "tool call", "↳": "subagent", "☐": "plan update" };
export function blockFor(item: OrchestrationV2TurnItem, pending: ReadonlySet<string>): Block | null {
const id = item.id;
switch (item.type) {