Redesign the details panel around what changes

Run state, context window and provider limits on top; the agent's latest
to-do list; changes in git-status style with the diff and git quick action
on one line; a one-line branch summary; subagents with their status, the
finished ones folded; automations' next run as a short time; workspace,
model and mode as a quiet footer.
This commit is contained in:
Callum Alpass committed 2026-11-03 01:46:23 +11:00
1 parent 1cccff8031
commit 9702c31e62
8 files changed
+499 -131

No files matched your search

+146 -36
View File
@@ -2,23 +2,36 @@ import type {
DiscoveredLocalServer, DiscoveredLocalServer,
GitStackedAction, GitStackedAction,
OrchestrationProjectShell, OrchestrationProjectShell,
OrchestrationV2PlanStep,
OrchestrationV2ShellSnapshot, OrchestrationV2ShellSnapshot,
OrchestrationV2Subagent, OrchestrationV2Subagent,
OrchestrationV2ThreadProjection,
OrchestrationV2ThreadShell, OrchestrationV2ThreadShell,
ScheduledTask, ScheduledTask,
ServerConfig,
ThreadId, ThreadId,
VcsStatusResult, VcsStatusResult,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models"; import { formatWorkingDurationLabel, type ThreadStructureTurnItem } from "@t3tools/client-runtime/state/models";
import { homedir } from "node:os"; import { homedir } from "node:os";
import type { VcsState } from "../client/session.ts"; import type { VcsState } from "../client/session.ts";
import { formatClock, type T3tuiConfig } from "../config.ts"; import { formatClock, type T3tuiConfig } from "../config.ts";
import { buildMenuItems, resolveQuickAction } from "../../vendor/t3code/apps/web/src/components/GitActionsControl.logic.ts"; import { buildMenuItems, resolveQuickAction } from "../../vendor/t3code/apps/web/src/components/GitActionsControl.logic.ts";
import type { StatusTone } from "./threads.ts"; import { deriveLatestContextWindowSnapshot, formatContextWindowTokens, latestProviderTurnTokenUsage } from "../../vendor/t3code/apps/web/src/lib/contextWindow.ts";
import { statusLabel, threadState, type StatusTone } from "./threads.ts";
import { providerLimits, type LimitWindowLine } from "./usage.ts";
/** The web's thread details card, reduced to what a terminal column can show. Sections with nothing to say are left out. */ /** The web's thread details card, reduced to what a terminal column can show. Sections with nothing to say are left out. */
export interface ThreadDetails { export interface ThreadDetails {
/** The run state as the thread list words it; null for a thread with nothing to report. */
readonly status: { readonly text: string; readonly tone: StatusTone } | null;
/** Room left in the context window, as the web's usage card reads it. */
readonly context: { readonly left: number | null; readonly used: string } | null;
/** The thread's provider's limit windows. */
readonly limits: readonly LimitWindowLine[] | null;
/** The agent's latest to-do list. */
readonly tasks: Tasks | null;
readonly workspace: { readonly workspace: {
readonly path: string; readonly path: string;
readonly worktree: boolean; readonly worktree: boolean;
@@ -33,18 +46,18 @@ export interface ThreadDetails {
readonly changes: { readonly changes: {
readonly insertions: number; readonly insertions: number;
readonly deletions: number; readonly deletions: number;
readonly files: readonly { readonly path: string; readonly insertions: number; readonly deletions: number }[]; readonly files: readonly ChangedFile[];
/** The branch's total against its base, when it differs from the working tree's. */ /** The branch's total against its base, when it differs from the working tree's. */
readonly branchTotal: { readonly baseRef: string | null; readonly insertions: number; readonly deletions: number } | null; readonly branchTotal: { readonly baseRef: string | null; readonly insertions: number; readonly deletions: number } | null;
} | null; } | null;
/** The web's git quick action and menu: commit, push, create PR. */ /** The web's git quick action and menu: commit, push, create PR. */
readonly git: { readonly git: {
readonly quick: GitAction | null; readonly quick: GitAction | null;
/** Why there's no quick action ("Up to date", "Sync ref"), as the web's disabled button says. */
readonly hint: string | null;
readonly menu: readonly GitAction[]; readonly menu: readonly GitAction[];
} | null; } | null;
/** Parent, forks and subagents; finished subagents fold away. */
readonly lineage: readonly LineageLine[]; readonly lineage: readonly LineageLine[];
readonly subagents: { readonly total: number; readonly running: number };
readonly servers: readonly { readonly server: DiscoveredLocalServer; readonly label: string }[]; readonly servers: readonly { readonly server: DiscoveredLocalServer; readonly label: string }[];
readonly automations: readonly AutomationLine[]; readonly automations: readonly AutomationLine[];
readonly background: readonly { readonly glyph: string; readonly text: string }[]; readonly background: readonly { readonly glyph: string; readonly text: string }[];
@@ -60,22 +73,45 @@ export interface GitAction {
readonly commits: boolean; readonly commits: boolean;
} }
export interface ChangedFile {
readonly path: string;
/** M, or ? for a path git status has no counts for: untracked, as a file or a whole folder. */
readonly status: "M" | "?";
readonly insertions: number;
readonly deletions: number;
}
export interface Tasks {
readonly done: number;
readonly total: number;
readonly steps: readonly OrchestrationV2PlanStep[];
/** The steps shown while folded, around the current one; null when they all fit. */
readonly window: { readonly start: number; readonly end: number } | null;
}
export interface LineageLine { export interface LineageLine {
readonly glyph: string; readonly glyph: string;
readonly tone: StatusTone;
readonly text: string; readonly text: string;
/** The thread it links to, when there's one to open. */ /** The thread it links to, when there's one to open. */
readonly threadId?: ThreadId; readonly threadId?: ThreadId;
/** A finished subagent, folded away until asked for. */
readonly finished?: boolean;
} }
export interface AutomationLine { export interface AutomationLine {
readonly task: ScheduledTask; readonly task: ScheduledTask;
readonly schedule: string; /** The next run, or its state when it isn't waiting for one. */
readonly status: string; readonly when: string;
readonly tone: StatusTone; readonly tone: StatusTone;
} }
/** Sections that fold to a count. */
export type DetailsFold = "tasks" | "subagents";
/** Something in the panel you can select and activate, in display order. */ /** Something in the panel you can select and activate, in display order. */
export type DetailsAction = export type DetailsAction =
| { readonly kind: "fold"; readonly id: string; readonly fold: DetailsFold }
| { readonly kind: "diff"; readonly id: string; readonly path: string | null } | { readonly kind: "diff"; readonly id: string; readonly path: string | null }
| { readonly kind: "git"; readonly id: string; readonly git: GitAction } | { readonly kind: "git"; readonly id: string; readonly git: GitAction }
| { readonly kind: "thread"; readonly id: string; readonly threadId: ThreadId } | { readonly kind: "thread"; readonly id: string; readonly threadId: ThreadId }
@@ -87,8 +123,13 @@ export interface DetailsInput {
readonly project: OrchestrationProjectShell | undefined; readonly project: OrchestrationProjectShell | undefined;
readonly vcs: VcsState | null; readonly vcs: VcsState | null;
readonly snapshot: OrchestrationV2ShellSnapshot | null; readonly snapshot: OrchestrationV2ShellSnapshot | null;
/** From the thread's projection, when it's loaded: names idle subagents the shell leaves out. */ /**
readonly subagents?: readonly OrchestrationV2Subagent[]; * The thread's projection, when it's loaded: its to-do list and context window, and the
* idle subagents the shell leaves out.
*/
readonly projection?: OrchestrationV2ThreadProjection | null;
/** For the provider's limits. */
readonly serverConfig?: ServerConfig | null;
readonly servers?: readonly DiscoveredLocalServer[]; readonly servers?: readonly DiscoveredLocalServer[];
readonly automations?: readonly ScheduledTask[]; readonly automations?: readonly ScheduledTask[];
readonly now?: number; readonly now?: number;
@@ -117,7 +158,7 @@ export function detailsCwd(thread: OrchestrationV2ThreadShell, project: Orchestr
} }
export function threadDetails(input: DetailsInput): ThreadDetails { export function threadDetails(input: DetailsInput): ThreadDetails {
const { thread, project, vcs, snapshot } = input; const { thread, project, vcs, snapshot, projection } = input;
const now = input.now ?? Date.now(); const now = input.now ?? Date.now();
const local = vcs?.local?.isRepo ? vcs.local : null; const local = vcs?.local?.isRepo ? vcs.local : null;
const remote = local ? (vcs?.remote ?? null) : null; const remote = local ? (vcs?.remote ?? null) : null;
@@ -129,7 +170,7 @@ export function threadDetails(input: DetailsInput): ThreadDetails {
const branch = branchName const branch = branchName
? { ? {
name: branchName, name: branchName,
upstream: remote ? (remote.hasUpstream ? `↑${remote.aheadCount} ↓${remote.behindCount}` : local?.hasPrimaryRemote ? "not pushed" : null) : null, upstream: remote ? (remote.hasUpstream ? [remote.aheadCount > 0 ? `↑${remote.aheadCount}` : "", remote.behindCount > 0 ? `↓${remote.behindCount}` : ""].filter(Boolean).join(" ") || null : local?.hasPrimaryRemote ? "not pushed" : null) : null,
pullRequest: pullRequestLine(thread, remote), pullRequest: pullRequestLine(thread, remote),
} }
: null; : null;
@@ -141,7 +182,7 @@ export function threadDetails(input: DetailsInput): ThreadDetails {
? { ? {
insertions: tree.insertions, insertions: tree.insertions,
deletions: tree.deletions, deletions: tree.deletions,
files: tree.files, files: tree.files.map((file): ChangedFile => ({ ...file, status: file.path.endsWith("/") || file.insertions + file.deletions === 0 ? "?" : "M" })),
branchTotal: branchTotal:
branchChanges && !local?.isDefaultRef && (branchChanges.insertions !== tree.insertions || branchChanges.deletions !== tree.deletions) branchChanges && !local?.isDefaultRef && (branchChanges.insertions !== tree.insertions || branchChanges.deletions !== tree.deletions)
? { baseRef: branchChanges.baseRef, insertions: branchChanges.insertions, deletions: branchChanges.deletions } ? { baseRef: branchChanges.baseRef, insertions: branchChanges.insertions, deletions: branchChanges.deletions }
@@ -153,18 +194,25 @@ export function threadDetails(input: DetailsInput): ThreadDetails {
const titleOf = (id: string) => threads.find((other) => other.id === id)?.title ?? "another thread"; const titleOf = (id: string) => threads.find((other) => other.id === id)?.title ?? "another thread";
const lineage: LineageLine[] = []; const lineage: LineageLine[] = [];
const parentId = thread.lineage.parentThreadId ?? (thread.forkedFrom?.type === "run" ? thread.forkedFrom.threadId : null); const parentId = thread.lineage.parentThreadId ?? (thread.forkedFrom?.type === "run" ? thread.forkedFrom.threadId : null);
if (parentId) lineage.push({ glyph: "↰", text: `${thread.lineage.relationshipToParent === "subagent" ? "subagent of" : "forked from"} ${quote(titleOf(parentId))}`, threadId: parentId }); if (parentId) lineage.push({ glyph: "↰", tone: "muted", text: `${thread.lineage.relationshipToParent === "subagent" ? "subagent of" : "forked from"} ${titleOf(parentId)}`, threadId: parentId });
for (const fork of threads.filter((other) => other.lineage.parentThreadId === thread.id && other.lineage.relationshipToParent === "fork" && other.deletedAt === null)) { for (const fork of threads.filter((other) => other.lineage.parentThreadId === thread.id && other.lineage.relationshipToParent === "fork" && other.deletedAt === null)) {
lineage.push({ glyph: "↳", text: `fork ${quote(fork.title)}`, threadId: fork.id }); lineage.push({ glyph: "↳", tone: "muted", text: `fork ${fork.title || "New thread"}`, threadId: fork.id });
} }
// The projection names every subagent; the shell only the busy ones. // The projection names every subagent; the shell only the busy ones, but it knows their runs best.
const subagents = new Map<ThreadId, string>(); const subagents = new Map<ThreadId, { title: string; agent?: OrchestrationV2Subagent }>();
for (const subagent of input.subagents ?? []) if (subagent.childThreadId) subagents.set(subagent.childThreadId, subagent.title ?? titleOf(subagent.childThreadId)); for (const agent of projection?.subagents ?? []) if (agent.childThreadId) subagents.set(agent.childThreadId, { title: agent.title ?? titleOf(agent.childThreadId), agent });
for (const other of threads) if (other.lineage.parentThreadId === thread.id && other.lineage.relationshipToParent === "subagent") subagents.set(other.id, other.title); for (const other of threads) if (other.lineage.parentThreadId === thread.id && other.lineage.relationshipToParent === "subagent") subagents.set(other.id, { ...subagents.get(other.id), title: other.title });
const running = new Set(threads.filter((other) => other.activeRunId !== null).map((other) => other.id as string)); const children = [...subagents].map(([threadId, { title, agent }]) => {
for (const [threadId, title] of subagents) lineage.push({ glyph: running.has(threadId) ? "◐" : "↳", text: `subagent ${quote(title)}`, threadId }); const shell = threads.find((other) => other.id === threadId);
const status: SubagentStatus = shell?.activeRunId || (agent && LIVE_SUBAGENT.has(agent.status)) ? "running" : agent?.status === "failed" || (shell && threadState(shell).status === "failed") ? "failed" : "done";
return { status, line: { ...SUBAGENT_STATUS[status], text: title || "Subagent", threadId, ...(status === "done" ? { finished: true } : {}) } satisfies LineageLine };
});
const unnamed = (thread.pendingBackgroundTasks ?? []).filter((task) => task.kind === "subagent" && !(task.childThreadId && subagents.has(task.childThreadId))).length; const unnamed = (thread.pendingBackgroundTasks ?? []).filter((task) => task.kind === "subagent" && !(task.childThreadId && subagents.has(task.childThreadId))).length;
if (unnamed > 0) lineage.push({ glyph: "◐", text: `${plural(unnamed, "subagent")} running` }); const withStatus = (status: SubagentStatus) => children.filter((child) => child.status === status).map((child) => child.line);
lineage.push(...withStatus("running"));
if (unnamed > 0) lineage.push({ ...SUBAGENT_STATUS.running, text: `${plural(unnamed, "subagent")} running` });
lineage.push(...withStatus("failed"), ...withStatus("done"));
const subagentCounts = { total: children.length + unnamed, running: children.filter((child) => child.status === "running").length + unnamed };
const git = local ? gitActions({ ...local, ...(remote ?? { hasUpstream: false, aheadCount: 0, behindCount: 0, pr: null }) }) : null; const git = local ? gitActions({ ...local, ...(remote ?? { hasUpstream: false, aheadCount: 0, behindCount: 0, pr: null }) }) : null;
@@ -189,19 +237,69 @@ export function threadDetails(input: DetailsInput): ThreadDetails {
: null; : null;
const vcsNote = vcs?.status === "error" ? "Git status unavailable" : vcs?.local && !vcs.local.isRepo ? "Not a git repository" : null; const vcsNote = vcs?.status === "error" ? "Git status unavailable" : vcs?.local && !vcs.local.isRepo ? "Not a git repository" : null;
return { git, servers, automations, workspace: { path: tildify(path), worktree: thread.worktreePath !== null && project !== undefined && thread.worktreePath !== project.workspaceRoot, model, mode }, branch, changes, lineage, background, goal, vcsNote }; return {
status: statusLabel(threadState(thread), now),
context: contextLine(projection ?? null),
limits: providerLimits(input.serverConfig ?? null, thread.modelSelection.instanceId, now),
tasks: latestTasks(projection ?? null),
git,
servers,
automations,
workspace: { path: tildify(path), worktree: thread.worktreePath !== null && project !== undefined && thread.worktreePath !== project.workspaceRoot, model, mode },
branch,
changes,
lineage,
subagents: subagentCounts,
background,
goal,
vcsNote,
};
} }
/** Every selectable line, top to bottom, as the panel shows them. */ /** Steps shown before the rest of a to-do list folds into a count. */
export function detailsActions(details: ThreadDetails): DetailsAction[] { export const MAX_TASKS = 5;
/** The thread's context window as the web derives it, fed as its chat view feeds it. */
function contextLine(projection: OrchestrationV2ThreadProjection | null): ThreadDetails["context"] {
if (!projection) return null;
const providerThread = projection.providerThreads.find((candidate) => candidate.id === projection.thread.activeProviderThreadId);
const live = latestProviderTurnTokenUsage(projection.providerTurns, projection, providerThread);
const snapshot = deriveLatestContextWindowSnapshot(projection.visibleTurnItems as unknown as readonly { readonly item: ThreadStructureTurnItem }[], live, providerThread);
if (!snapshot) return null;
return { left: snapshot.remainingPercentage === null ? null : Math.round(snapshot.remainingPercentage), used: formatContextWindowTokens(snapshot.usedTokens) };
}
/** The agent's most recent to-do list, folded around the step it's on. */
function latestTasks(projection: OrchestrationV2ThreadProjection | null): Tasks | null {
const item = projection?.turnItems.findLast((candidate) => candidate.type === "todo_list");
if (item?.type !== "todo_list" || item.steps.length === 0) return null;
const steps = item.steps;
const running = steps.findIndex((step) => step.status === "running");
const current = running >= 0 ? running : Math.max(0, steps.findIndex((step) => step.status === "pending"));
// One more step than fits would fold into "1 more"; show it instead.
const start = Math.max(0, Math.min(current - 1, steps.length - MAX_TASKS));
return {
done: steps.filter((step) => step.status === "completed").length,
total: steps.length,
steps,
window: steps.length > MAX_TASKS + 1 ? { start, end: start + MAX_TASKS } : null,
};
}
/** Every selectable line, top to bottom, as the panel shows them with these folds open. */
export function detailsActions(details: ThreadDetails, unfolded: ReadonlySet<DetailsFold> = new Set()): DetailsAction[] {
const actions: DetailsAction[] = []; const actions: DetailsAction[] = [];
if (details.tasks?.window) actions.push({ kind: "fold", id: "fold:tasks", fold: "tasks" });
if (details.changes && details.changes.files.length > 0) {
for (const file of details.changes.files.slice(0, MAX_DETAIL_FILES)) actions.push({ kind: "diff", id: `diff:${file.path}`, path: file.path });
actions.push({ kind: "diff", id: "diff:*", path: null });
}
if (details.git?.quick) actions.push({ kind: "git", id: `git:quick:${details.git.quick.action}`, git: details.git.quick }); if (details.git?.quick) actions.push({ kind: "git", id: `git:quick:${details.git.quick.action}`, git: details.git.quick });
for (const git of details.git?.menu ?? []) actions.push({ kind: "git", id: `git:${git.action}`, git }); for (const git of details.git?.menu ?? []) actions.push({ kind: "git", id: `git:${git.action}`, git });
if (details.changes && details.changes.files.length > 0) { for (const line of details.lineage) {
actions.push({ kind: "diff", id: "diff:*", path: null }); if (line.finished && !actions.some((action) => action.id === "fold:subagents")) actions.push({ kind: "fold", id: "fold:subagents", fold: "subagents" });
for (const file of details.changes.files.slice(0, MAX_DETAIL_FILES)) actions.push({ kind: "diff", id: `diff:${file.path}`, path: file.path }); if (line.threadId && (!line.finished || unfolded.has("subagents"))) actions.push({ kind: "thread", id: `thread:${line.threadId}`, threadId: line.threadId });
} }
for (const line of details.lineage) if (line.threadId) actions.push({ kind: "thread", id: `thread:${line.threadId}`, threadId: line.threadId });
for (const { server } of details.servers) actions.push({ kind: "server", id: `server:${server.port}`, server }); for (const { server } of details.servers) actions.push({ kind: "server", id: `server:${server.port}`, server });
for (const { task } of details.automations) actions.push({ kind: "automation", id: `automation:${task.id}`, task }); for (const { task } of details.automations) actions.push({ kind: "automation", id: `automation:${task.id}`, task });
return actions; return actions;
@@ -220,21 +318,31 @@ function gitActions(status: VcsStatusResult): NonNullable<ThreadDetails["git"]>
const menu = buildMenuItems(status, false, status.hasPrimaryRemote) const menu = buildMenuItems(status, false, status.hasPrimaryRemote)
.filter((item) => !item.disabled && MENU_ACTIONS[item.id] && MENU_ACTIONS[item.id] !== quick?.action) .filter((item) => !item.disabled && MENU_ACTIONS[item.id] && MENU_ACTIONS[item.id] !== quick?.action)
.map((item) => ({ action: MENU_ACTIONS[item.id]!, label: item.label, commits: item.id === "commit" })); .map((item) => ({ action: MENU_ACTIONS[item.id]!, label: item.label, commits: item.id === "commit" }));
return { quick, hint: quick ? null : quickAction.hint ?? quickAction.label, menu }; return { quick, menu };
} }
function automationLine(task: ScheduledTask, now: number, timestampFormat: T3tuiConfig["timestampFormat"]): AutomationLine { function automationLine(task: ScheduledTask, now: number, timestampFormat: T3tuiConfig["timestampFormat"]): AutomationLine {
const schedule = if (!task.enabled) return { task, when: "off", tone: "muted" };
if (task.lastRunStatus === "running") return { task, when: "running", tone: "info" };
if (task.lastRunStatus === "failed") return { task, when: "failed", tone: "bad" };
const next = task.nextRunAt ? Date.parse(String(task.nextRunAt)) : NaN;
if (Number.isFinite(next) && next > now) return { task, when: shortTime(next, now, timestampFormat), tone: "muted" };
const when =
task.schedule.type === "interval" task.schedule.type === "interval"
? `every ${formatWorkingDurationLabel(task.schedule.everyMs)}` ? `every ${formatWorkingDurationLabel(task.schedule.everyMs)}`
: task.schedule.type === "fixed_time" : task.schedule.type === "fixed_time"
? `${task.schedule.weekdays && task.schedule.weekdays.length < 7 ? `${task.schedule.weekdays.map((day) => WEEKDAYS[day]).join(",")} ` : "daily "}${formatClock(task.schedule.timeOfDay, timestampFormat)}` ? `${task.schedule.weekdays && task.schedule.weekdays.length < 7 ? `${task.schedule.weekdays.map((day) => WEEKDAYS[day]).join(",")} ` : "daily "}${formatClock(task.schedule.timeOfDay, timestampFormat)}`
: "on webhook"; : "on webhook";
if (!task.enabled) return { task, schedule, status: "off", tone: "muted" }; return { task, when, tone: "muted" };
if (task.lastRunStatus === "running") return { task, schedule, status: "running", tone: "info" }; }
if (task.lastRunStatus === "failed") return { task, schedule, status: "failed", tone: "bad" };
const next = task.nextRunAt ? Date.parse(String(task.nextRunAt)) : NaN; /** A time to come, as briefly as it reads: "today 21:00", "tomorrow 9:00", "Mon 7:00", "4 Mar 7:00". */
return { task, schedule, status: Number.isFinite(next) && next > now ? `in ${formatWorkingDurationLabel(next - now)}` : "on", tone: "good" }; export function shortTime(at: number, now: number, timestampFormat: T3tuiConfig["timestampFormat"]): string {
const date = new Date(at);
const clock = formatClock(`${date.getHours()}:${String(date.getMinutes()).padStart(2, "0")}`, timestampFormat);
const days = Math.round((new Date(date).setHours(0, 0, 0, 0) - new Date(now).setHours(0, 0, 0, 0)) / 86_400_000);
const day = days === 0 ? "today" : days === 1 ? "tomorrow" : days < 7 ? WEEKDAYS[date.getDay()] : date.toLocaleDateString(undefined, { day: "numeric", month: "short" });
return `${day} ${clock}`;
} }
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
@@ -276,5 +384,7 @@ function tildify(path: string): string {
return path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path; return path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
} }
const quote = (text: string) => `"${text || "New thread"}"`; const LIVE_SUBAGENT: ReadonlySet<string> = new Set(["pending", "running", "waiting"]);
type SubagentStatus = "running" | "failed" | "done";
const SUBAGENT_STATUS: Record<SubagentStatus, { glyph: string; tone: StatusTone }> = { running: { glyph: "◐", tone: "info" }, failed: { glyph: "✕", tone: "bad" }, done: { glyph: "✓", tone: "good" } };
const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`; const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;
+7 -1
View File
@@ -59,8 +59,14 @@ export function needsAttention(row: Pick<ThreadRow, "status" | "unread">): boole
return row.status === "approval" || row.status === "input" || row.status === "request" || row.status === "failed" || row.status === "limited" || row.unread; return row.status === "approval" || row.status === "input" || row.status === "request" || row.status === "failed" || row.status === "limited" || row.unread;
} }
/** A thread's row status, for one that isn't listed (or that you have outside a list). */
export function threadState(thread: OrchestrationV2ThreadShell): Pick<ThreadRow, "shell" | "status" | "unread"> {
const shell = presentThreadShell(LOCAL_ENVIRONMENT, thread);
return { shell, status: resolveStatus(shell), unread: hasUnseenCompletion(shell) };
}
/** The sidebar's top-right status word, or null to show the time instead. */ /** 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 { export function statusLabel(row: Pick<ThreadRow, "shell" | "status" | "unread">, now = Date.now()): { readonly text: string; readonly tone: StatusTone } | null {
switch (row.status) { switch (row.status) {
case "working": { case "working": {
const label = row.shell.goal?.status === "active" ? "Goal" : "Working"; const label = row.shell.goal?.status === "active" ? "Goal" : "Working";
+25 -2
View File
@@ -1,5 +1,5 @@
import type { ProviderConsumeResetCreditInput, ServerConfig, ServerProviderResetCredits, UsageSummary } from "@t3tools/contracts"; import type { ProviderConsumeResetCreditInput, ProviderInstanceId, ServerConfig, ServerProviderResetCredits, UsageSummary } from "@t3tools/contracts";
import { collectLimitAccounts, collectLimitNotices, formatDuration, remainingPercent, type LimitPresentations } from "@t3tools/shared/usageLimits"; import { collectLimitAccounts, collectLimitNotices, collectProviderUsageLimits, formatDuration, limitsNotice, remainingPercent, type LimitPresentations } from "@t3tools/shared/usageLimits";
import { formatTokens, formatUsd } from "@t3tools/shared/usageFormat"; import { formatTokens, formatUsd } from "@t3tools/shared/usageFormat";
/** At or above this much of a window used, the status line calls the limit near. */ /** At or above this much of a window used, the status line calls the limit near. */
@@ -44,6 +44,29 @@ export function usageLimits(config: ServerConfig | null, now = Date.now()): Usag
return { lines, note: note?.text ?? null, credits }; return { lines, note: note?.text ?? null, credits };
} }
export interface LimitWindowLine {
readonly label: string;
/** Percent of the window left. */
readonly left: number;
/** Near or at the limit, as the status line reads it. */
readonly tone: "muted" | "warn" | "bad";
}
/**
* One provider instance's limit windows, picked as the web's thread details pick them; null
* when the provider reports none, or reports them unavailable.
*/
export function providerLimits(config: ServerConfig | null, instanceId: ProviderInstanceId, now = Date.now()): readonly LimitWindowLine[] | null {
if (!config) return null;
const report = collectProviderUsageLimits(instanceId, config.providers, config.usageLimitSources ?? [], now);
const limits = report?.accounts.find((entry) => entry.instanceId === instanceId)?.limits ?? config.providers.find((provider) => provider.instanceId === instanceId)?.usageLimits;
if (!limits || limitsNotice(limits) || limits.windows.length === 0) return null;
return limits.windows.map((window) => {
const left = remainingPercent(window);
return { label: window.label, left, tone: left === 0 ? "bad" : window.usedPercent >= NEAR_LIMIT_USED_PERCENT ? "warn" : "muted" };
});
}
/** The web's banked-credits wording: a count and when the next one expires. */ /** The web's banked-credits wording: a count and when the next one expires. */
export function resetCreditsSummary(credits: ServerProviderResetCredits, now = Date.now()): string { export function resetCreditsSummary(credits: ServerProviderResetCredits, now = Date.now()): string {
if (credits.availableCount === 0) return "No reset credits banked"; if (credits.availableCount === 0) return "No reset credits banked";
+4 -3
View File
@@ -6,7 +6,7 @@ import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId, Tu
import { homedir } from "node:os"; import { homedir } from "node:os";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ChatAttachment, OrchestrationMessageContext, OrchestrationV2Subagent } from "@t3tools/contracts"; import type { ChatAttachment, OrchestrationMessageContext } from "@t3tools/contracts";
import type { ServerConfigState, ShellState, T3Session, ThreadState } from "../client/session.ts"; import type { ServerConfigState, ShellState, T3Session, ThreadState } from "../client/session.ts";
import { createAlerts, type Alert } from "../model/alerts.ts"; import { createAlerts, type Alert } from "../model/alerts.ts";
import { modelSummary } from "../model/models.ts"; import { modelSummary } from "../model/models.ts";
@@ -80,7 +80,6 @@ const MAX_COMPOSER_LINES = 8;
/** Sections folded to a count unless you filter or press z, like the web sidebar's. */ /** Sections folded to a count unless you filter or press z, like the web sidebar's. */
const FOLDED_SECTIONS: readonly Section[] = ["snoozed", "settled"]; const FOLDED_SECTIONS: readonly Section[] = ["snoozed", "settled"];
const DETAILS_WIDTH = 38; const DETAILS_WIDTH = 38;
const NO_SUBAGENTS: readonly OrchestrationV2Subagent[] = [];
/** Below this, the details panel takes the conversation's place instead of a column beside it. */ /** Below this, the details panel takes the conversation's place instead of a column beside it. */
const MIN_CONVERSATION_WIDTH = 70; const MIN_CONVERSATION_WIDTH = 70;
@@ -431,7 +430,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
thread: threadShell, thread: threadShell,
project, project,
snapshot: detailsSnapshot, snapshot: detailsSnapshot,
subagents: projection?.subagents ?? NO_SUBAGENTS, projection: projection ?? null,
serverConfig: serverConfig?.config ?? null,
now, now,
config, config,
diff, diff,
@@ -1019,6 +1019,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
{...(threadId && !threadShell ? { empty: supportsFamilies ? "Loading details…" : "No details for idle subagent threads on this server. u goes to the parent." } : {})} {...(threadId && !threadShell ? { empty: supportsFamilies ? "Loading details…" : "No details for idle subagent threads on this server. u goes to the parent." } : {})}
width={inPlace ? width - listWidth : DETAILS_WIDTH} width={inPlace ? width - listWidth : DETAILS_WIDTH}
loading={panel.loading} loading={panel.loading}
unfolded={panel.unfolded}
inPlace={inPlace} inPlace={inPlace}
selected={mode === "details" || (mode === "confirm" && returnMode.current === "details") ? panel.selected : null} selected={mode === "details" || (mode === "confirm" && returnMode.current === "details") ? panel.selected : null}
onActivate={panel.activateById} onActivate={panel.activateById}
+198 -67
View File
@@ -1,16 +1,19 @@
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { MAX_DETAIL_FILES, type DetailsAction, type ThreadDetails } from "../model/details.ts"; import { MAX_DETAIL_FILES, type ChangedFile, type DetailsAction, type DetailsFold, type LineageLine, type ThreadDetails } from "../model/details.ts";
import { ClickRow } from "./Button.tsx"; import { ClickRow } from "./Button.tsx";
import { truncate } from "./text.ts"; import { truncate } from "./text.ts";
import { colors, statusColor } from "./theme.ts"; import { colors, statusColor } from "./theme.ts";
/** Rows stay readable when the panel takes the conversation's place on a narrow terminal. */ /** Rows stay readable when the panel takes the conversation's place on a narrow terminal. */
const IN_PLACE_MAX_WIDTH = 64; const IN_PLACE_MAX_WIDTH = 64;
/** Cells in the context bar. */
const BAR_CELLS = 10;
/** /**
* The web's thread details card as a right-hand column: workspace, branch and PR, git actions, * The web's thread details card as a right-hand column, what changes first: run state,
* changes, lineage, servers, automations, background work, goal. Lines that do something are * context and limits, the agent's tasks, changes, branch, subagents, servers, background
* work, goal, automations, then where and how the thread runs. Lines that do something are
* selectable with the keyboard and clickable. * selectable with the keyboard and clickable.
*/ */
export function DetailsPanel(props: { export function DetailsPanel(props: {
@@ -20,6 +23,7 @@ export function DetailsPanel(props: {
readonly inPlace?: boolean; readonly inPlace?: boolean;
/** The selected line's action id, while the panel has focus. */ /** The selected line's action id, while the panel has focus. */
readonly selected: string | null; readonly selected: string | null;
readonly unfolded: ReadonlySet<DetailsFold>;
readonly onActivate: (id: string) => void; readonly onActivate: (id: string) => void;
/** Shown when there are no details, which defaults to no thread being selected. */ /** Shown when there are no details, which defaults to no thread being selected. */
readonly empty?: string; readonly empty?: string;
@@ -41,7 +45,11 @@ export function DetailsPanel(props: {
backgroundColor={colors.panel} backgroundColor={colors.panel}
> >
<scrollbox flexGrow={1} minHeight={0} paddingLeft={1} paddingRight={1}> <scrollbox flexGrow={1} minHeight={0} paddingLeft={1} paddingRight={1}>
{!details ? <text fg={colors.faint}>{props.empty ?? "No thread selected."}</text> : <Sections details={details} inner={inner} loading={props.loading} selected={props.selected} onActivate={props.onActivate} />} {!details ? (
<text fg={colors.faint}>{props.empty ?? "No thread selected."}</text>
) : (
<Sections details={details} inner={inner} loading={props.loading} unfolded={props.unfolded} selected={props.selected} onActivate={props.onActivate} />
)}
</scrollbox> </scrollbox>
</box> </box>
); );
@@ -52,49 +60,50 @@ interface LineProps {
readonly onActivate: (id: string) => void; readonly onActivate: (id: string) => void;
} }
function Sections({ details, inner, loading, selected, onActivate }: { readonly details: ThreadDetails; readonly inner: number; readonly loading: boolean } & LineProps) { function Sections({ details, inner, loading, unfolded, selected, onActivate }: { readonly details: ThreadDetails; readonly inner: number; readonly loading: boolean; readonly unfolded: ReadonlySet<DetailsFold> } & LineProps) {
const { workspace, branch, changes, git } = details; const { branch, changes, git, tasks } = details;
const files = changes?.files ?? []; const files = changes?.files ?? [];
const line = { selected, onActivate }; const line = { selected, onActivate };
return ( const gitActions = git ? (
<> <>
<Section title="Workspace" first> {files.length > 0 || git.quick ? (
<text fg={colors.muted}>{startTruncate(workspace.path, inner)}</text> <box flexDirection="row" marginLeft={-1}>
{workspace.worktree ? <text fg={colors.faint}>worktree</text> : null} {files.length > 0 ? <Action id="diff:*" {...line} text="▸ View diff" /> : null}
<text fg={colors.muted}>{truncate(workspace.model, inner)}</text> {files.length > 0 && git.quick ? <text> </text> : null}
{workspace.mode ? <text fg={colors.muted}>{truncate(workspace.mode, inner)}</text> : null} {git.quick ? <Action id={`git:quick:${git.quick.action}`} {...line} text={`▸ ${git.quick.label}`} /> : null}
</Section>
{branch ? (
<Section title="Branch">
<box flexDirection="row">
<text fg={colors.muted}>{truncate(branch.name, inner - (branch.upstream?.length ?? 0) - 1)}</text>
<box flexGrow={1} />
<text fg={colors.faint}>{branch.upstream ?? ""}</text>
</box> </box>
{branch.pullRequest ? (
<>
<box flexDirection="row">
<text fg={colors.muted}>{`PR #${branch.pullRequest.number} `}</text>
<text fg={statusColor(branch.pullRequest.tone)}>{branch.pullRequest.state}</text>
<box flexGrow={1} />
{branch.pullRequest.checks ? <text fg={statusColor(branch.pullRequest.checks.tone)}>{branch.pullRequest.checks.text}</text> : null}
</box>
{branch.pullRequest.title ? <text fg={colors.muted}>{truncate(branch.pullRequest.title, inner)}</text> : null}
</>
) : null} ) : null}
{git?.quick ? <Selectable id={`git:quick:${git.quick.action}`} {...line} color={colors.accent} text={`▸ ${git.quick.label}`} inner={inner} /> : null} {git.menu.map((item) => <Selectable key={item.action} id={`git:${item.action}`} {...line} color={colors.muted} text={` ${item.label}`} inner={inner} />)}
{git?.menu.map((item) => <Selectable key={item.action} id={`git:${item.action}`} {...line} color={colors.muted} text={` ${item.label}`} inner={inner} />)} </>
{git && !git.quick && git.hint ? <text fg={colors.faint}>{truncate(git.hint, inner)}</text> : null} ) : files.length > 0 ? (
<box flexDirection="row" marginLeft={-1}>
<Action id="diff:*" {...line} text="▸ View diff" />
</box>
) : null;
const visibleTasks = tasks ? (tasks.window && !unfolded.has("tasks") ? tasks.steps.slice(tasks.window.start, tasks.window.end) : tasks.steps) : [];
const finished = details.lineage.filter((entry) => entry.finished);
const lineageTitle = details.subagents.total > 0 ? "Subagents" : "Lineage";
return (
<box flexDirection="column" rowGap={1} flexShrink={0}>
<StatusBlock details={details} inner={inner} />
{tasks ? (
<Section title="Tasks" right={<text fg={colors.faint}>{`${tasks.done}/${tasks.total}`}</text>}>
{visibleTasks.map((step) => (
<box key={step.id} flexDirection="row">
<text fg={step.status === "completed" ? colors.faint : step.status === "running" ? colors.info : colors.muted} flexShrink={0}>{`${TASK_GLYPHS[step.status]} `}</text>
<text fg={step.status === "completed" ? colors.faint : step.status === "running" ? colors.text : colors.muted}>{truncate(step.text, inner - 2)}</text>
</box>
))}
{tasks.window ? <Selectable id="fold:tasks" {...line} color={colors.faint} text={unfolded.has("tasks") ? "‹ fewer" : `› ${tasks.total - (tasks.window.end - tasks.window.start)} more`} inner={inner} /> : null}
</Section> </Section>
) : null} ) : null}
{changes ? ( {changes ? (
<Section title="Changes" right={<Counts insertions={changes.insertions} deletions={changes.deletions} />}> <Section title="Changes" right={<Counts insertions={changes.insertions} deletions={changes.deletions} />}>
{files.length > 0 ? <Selectable id="diff:*" {...line} color={colors.accent} text="▸ View diff" inner={inner} /> : null}
{files.slice(0, MAX_DETAIL_FILES).map((file) => ( {files.slice(0, MAX_DETAIL_FILES).map((file) => (
<Selectable key={file.path} id={`diff:${file.path}`} {...line} inner={inner}> <Selectable key={file.path} id={`diff:${file.path}`} {...line} inner={inner}>
<FileLine path={file.path} insertions={file.insertions} deletions={file.deletions} inner={inner} /> <FileLine file={file} inner={inner} />
</Selectable> </Selectable>
))} ))}
{files.length > MAX_DETAIL_FILES ? <text fg={colors.faint}>{`… ${files.length - MAX_DETAIL_FILES} more files (in the full diff)`}</text> : null} {files.length > MAX_DETAIL_FILES ? <text fg={colors.faint}>{`… ${files.length - MAX_DETAIL_FILES} more files (in the full diff)`}</text> : null}
@@ -106,23 +115,38 @@ function Sections({ details, inner, loading, selected, onActivate }: { readonly
<Counts insertions={changes.branchTotal.insertions} deletions={changes.branchTotal.deletions} /> <Counts insertions={changes.branchTotal.insertions} deletions={changes.branchTotal.deletions} />
</box> </box>
) : null} ) : null}
{gitActions}
</Section> </Section>
) : loading ? ( ) : loading ? (
<Section title="Changes"> <Section title="Changes">
<text fg={colors.faint}>Loading…</text> <text fg={colors.faint}>Loading…</text>
</Section> </Section>
) : null} ) : null}
{details.vcsNote ? <text fg={colors.faint} marginTop={1}>{details.vcsNote}</text> : null} {details.vcsNote ? <text fg={colors.faint}>{details.vcsNote}</text> : null}
{branch ? (
<box flexDirection="column" flexShrink={0}>
<BranchLine branch={branch} inner={inner} />
{branch.pullRequest?.title && branch.pullRequest.title.length <= inner ? <text fg={colors.faint}>{branch.pullRequest.title}</text> : null}
{changes ? null : gitActions}
</box>
) : null}
{details.lineage.length > 0 ? ( {details.lineage.length > 0 ? (
<Section title="Lineage"> <Section
{details.lineage.map((entry) => title={lineageTitle}
entry.threadId ? ( right={
<Selectable key={entry.threadId} id={`thread:${entry.threadId}`} {...line} color={colors.muted} text={`${entry.glyph} ${entry.text}`} inner={inner} /> details.subagents.total > 0 ? (
) : ( <box flexDirection="row">
<text key={entry.text} fg={colors.muted}>{truncate(`${entry.glyph} ${entry.text}`, inner)}</text> <text fg={colors.faint}>{`${details.subagents.total}`}</text>
), {details.subagents.running > 0 ? <text fg={colors.info}>{` · ${details.subagents.running} running`}</text> : null}
)} </box>
) : undefined
}
>
{details.lineage.filter((entry) => !entry.finished).map((entry) => <LineageRow key={entry.threadId ?? entry.text} entry={entry} inner={inner} {...line} />)}
{finished.length > 0 ? <Selectable id="fold:subagents" {...line} color={colors.faint} text={`${unfolded.has("subagents") ? "⌄" : "›"} ${finished.length} finished`} inner={inner} /> : null}
{unfolded.has("subagents") ? finished.map((entry) => <LineageRow key={entry.threadId ?? entry.text} entry={entry} inner={inner} {...line} />) : null}
</Section> </Section>
) : null} ) : null}
@@ -134,23 +158,6 @@ function Sections({ details, inner, loading, selected, onActivate }: { readonly
</Section> </Section>
) : null} ) : null}
{details.automations.length > 0 ? (
<Section title="Automations">
{details.automations.map((automation) => (
<Selectable key={automation.task.id} id={`automation:${automation.task.id}`} {...line} inner={inner}>
<box flexDirection="column">
<text fg={colors.muted}>{truncate(automation.task.title, inner)}</text>
<box flexDirection="row">
<text fg={colors.faint}>{truncate(automation.schedule, inner - automation.status.length - 1)}</text>
<box flexGrow={1} />
<text fg={statusColor(automation.tone)}>{automation.status}</text>
</box>
</box>
</Selectable>
))}
</Section>
) : null}
{details.background.length > 0 ? ( {details.background.length > 0 ? (
<Section title="Background"> <Section title="Background">
{details.background.map((task, index) => ( {details.background.map((task, index) => (
@@ -165,7 +172,118 @@ function Sections({ details, inner, loading, selected, onActivate }: { readonly
<text fg={statusColor(details.goal.tone)}>{details.goal.status}</text> <text fg={statusColor(details.goal.tone)}>{details.goal.status}</text>
</Section> </Section>
) : null} ) : null}
{details.automations.length > 0 ? (
<Section title="Automations">
{details.automations.map((automation) => (
<Selectable key={automation.task.id} id={`automation:${automation.task.id}`} {...line} inner={inner}>
<box flexDirection="row">
<text fg={colors.muted}>{truncate(automation.task.title, inner - automation.when.length - 1)}</text>
<box flexGrow={1} />
<text fg={automation.tone === "muted" ? colors.faint : statusColor(automation.tone)}>{automation.when}</text>
</box>
</Selectable>
))}
</Section>
) : null}
<Footer workspace={details.workspace} inner={inner} />
</box>
);
}
const TASK_GLYPHS = { completed: "✓", running: "◐", pending: "○" } as const;
/** Run state, context window and limits: what the thread is doing and how much room it has. */
function StatusBlock({ details, inner }: { readonly details: ThreadDetails; readonly inner: number }) {
const { status, context, limits } = details;
if (!status && !context && !limits) return null;
const filled = context?.left == null ? 0 : Math.round((context.left / 100) * BAR_CELLS);
return (
<box flexDirection="column" flexShrink={0}>
{status ? <text fg={statusColor(status.tone)}>{truncate(status.text, inner)}</text> : null}
{context ? (
<box flexDirection="row">
<text fg={colors.muted}>{"Context "}</text>
{context.left === null ? (
<text fg={colors.faint}>{`${context.used} used`}</text>
) : (
<>
<text fg={colors.muted}>{"█".repeat(filled)}</text>
<text fg={colors.faint}>{"░".repeat(BAR_CELLS - filled)}</text>
<text fg={context.left <= 10 ? colors.bad : context.left <= 25 ? colors.warn : colors.muted}>{` ${context.left}% left`}</text>
</> </>
)}
</box>
) : null}
{limits ? (
<box flexDirection="row">
<text fg={colors.muted} flexShrink={0}>{"Limits "}</text>
<box flexDirection="row" flexWrap="wrap" flexShrink={1}>
{limits.map((limit, index) => (
<box key={limit.label} flexDirection="row">
<text fg={colors.faint}>{`${index > 0 ? " · " : ""}${limit.label} `}</text>
<text fg={limit.tone === "muted" ? colors.muted : statusColor(limit.tone)}>{`${limit.left}%`}</text>
</box>
))}
</box>
</box>
) : null}
</box>
);
}
/** `main ↑2 · PR #1371 merged ✓ checks` */
function BranchLine({ branch, inner }: { readonly branch: NonNullable<ThreadDetails["branch"]>; readonly inner: number }) {
const pr = branch.pullRequest;
const prText = pr ? ` · PR #${pr.number} ${pr.state}` : "";
const checks = pr?.checks?.text ?? "";
const upstream = branch.upstream ? ` ${branch.upstream}` : "";
const name = truncate(branch.name, Math.max(6, inner - upstream.length - prText.length - (checks ? checks.length + 1 : 0)));
return (
<box flexDirection="row">
<text fg={colors.muted}>{name}</text>
{upstream ? <text fg={colors.faint}>{upstream}</text> : null}
{pr ? (
<>
<text fg={colors.faint}>{` · PR #${pr.number} `}</text>
<text fg={statusColor(pr.tone)}>{pr.state}</text>
</>
) : null}
<box flexGrow={1} />
{pr?.checks ? <text fg={statusColor(pr.checks.tone)}>{pr.checks.text}</text> : null}
</box>
);
}
function LineageRow({ entry, inner, ...line }: { readonly entry: LineageLine; readonly inner: number } & LineProps) {
const content = (
<box flexDirection="row">
<text fg={statusColor(entry.tone)} flexShrink={0}>{`${entry.glyph} `}</text>
<text fg={line.selected === `thread:${entry.threadId}` ? colors.text : colors.muted}>{truncate(entry.text, inner - 2)}</text>
</box>
);
return entry.threadId ? (
<Selectable id={`thread:${entry.threadId}`} {...line} inner={inner}>
{content}
</Selectable>
) : (
content
);
}
/** Where and how the thread runs, quiet at the bottom: one line, or two when it doesn't fit. */
function Footer({ workspace, inner }: { readonly workspace: ThreadDetails["workspace"]; readonly inner: number }) {
const where = `${workspace.path}${workspace.worktree ? " · worktree" : ""}`;
const how = [workspace.model, workspace.mode].filter(Boolean).join(" · ");
const one = `${where} · ${how}`;
return one.length <= inner ? (
<text fg={colors.faint}>{one}</text>
) : (
<box flexDirection="column" flexShrink={0}>
<text fg={colors.faint}>{startTruncate(where, inner)}</text>
<text fg={colors.faint}>{truncate(how, inner)}</text>
</box>
); );
} }
@@ -184,9 +302,20 @@ function Selectable(props: LineProps & { readonly id: DetailsAction["id"]; reado
); );
} }
function Section(props: { readonly title: string; readonly right?: ReactNode; readonly first?: boolean; readonly children: ReactNode }) { /** A selectable label that shares its line with another, as `▸ View diff ▸ Commit`. */
function Action(props: LineProps & { readonly id: DetailsAction["id"]; readonly text: string }) {
const active = props.selected === props.id;
return ( return (
<box flexDirection="column" marginTop={props.first ? 0 : 1} flexShrink={0}> <ClickRow flexDirection="row" flexShrink={0} paddingRight={1} selected={active} onPress={() => props.onActivate(props.id)}>
<text fg={colors.accent} selectable={false}>{active ? "▌" : " "}</text>
<text fg={active ? colors.text : colors.accent}>{props.text}</text>
</ClickRow>
);
}
function Section(props: { readonly title: string; readonly right?: ReactNode; readonly children: ReactNode }) {
return (
<box flexDirection="column" flexShrink={0}>
<box flexDirection="row"> <box flexDirection="row">
<text fg={colors.text}> <text fg={colors.text}>
<strong>{props.title}</strong> <strong>{props.title}</strong>
@@ -199,13 +328,15 @@ function Section(props: { readonly title: string; readonly right?: ReactNode; re
); );
} }
function FileLine(props: { readonly path: string; readonly insertions: number; readonly deletions: number; readonly inner: number }) { /** `M src/a.ts +3 −1`, git status style; `? docs/ new` for untracked paths, which have no counts. */
const counts = countsText(props.insertions, props.deletions); function FileLine({ file, inner }: { readonly file: ChangedFile; readonly inner: number }) {
const right = file.status === "?" ? "new" : countsText(file.insertions, file.deletions);
return ( return (
<box flexDirection="row"> <box flexDirection="row">
<text fg={colors.muted}>{startTruncate(props.path, Math.max(4, props.inner - counts.length - 1))}</text> <text fg={colors.muted} flexShrink={0}>{`${file.status} `}</text>
<text fg={colors.muted}>{startTruncate(file.path, Math.max(4, inner - right.length - 3))}</text>
<box flexGrow={1} /> <box flexGrow={1} />
<Counts insertions={props.insertions} deletions={props.deletions} /> {file.status === "?" ? <text fg={colors.faint}>new</text> : <Counts insertions={file.insertions} deletions={file.deletions} />}
</box> </box>
); );
} }
+25 -10
View File
@@ -1,9 +1,9 @@
import type { DiscoveredLocalServer, OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2Subagent, OrchestrationV2ThreadShell, ScheduledTask, ThreadId } from "@t3tools/contracts"; import type { DiscoveredLocalServer, OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadProjection, OrchestrationV2ThreadShell, ScheduledTask, ServerConfig, ThreadId } from "@t3tools/contracts";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import type { FeedState, T3Session, VcsState } from "../client/session.ts"; import type { FeedState, T3Session, VcsState } from "../client/session.ts";
import type { T3tuiConfig } from "../config.ts"; import type { T3tuiConfig } from "../config.ts";
import { detailsActions, detailsCwd, threadDetails, type DetailsAction, type GitAction } from "../model/details.ts"; import { detailsActions, detailsCwd, threadDetails, type DetailsAction, type DetailsFold, type GitAction } from "../model/details.ts";
import { keys, type Binding } from "../model/keymap.ts"; import { keys, type Binding } from "../model/keymap.ts";
import type { Automations } from "./useAutomations.ts"; import type { Automations } from "./useAutomations.ts";
import type { Confirmation } from "./ConfirmBar.tsx"; import type { Confirmation } from "./ConfirmBar.tsx";
@@ -25,7 +25,9 @@ export function useDetails(deps: {
readonly project: OrchestrationProjectShell | undefined; readonly project: OrchestrationProjectShell | undefined;
/** The shell, with fetched subagent families, so lineage can name idle subagents. */ /** The shell, with fetched subagent families, so lineage can name idle subagents. */
readonly snapshot: OrchestrationV2ShellSnapshot | null; readonly snapshot: OrchestrationV2ShellSnapshot | null;
readonly subagents: readonly OrchestrationV2Subagent[]; /** The open thread's projection, once loaded: its to-do list, context window and subagents. */
readonly projection: OrchestrationV2ThreadProjection | null;
readonly serverConfig: ServerConfig | null;
readonly now: number; readonly now: number;
readonly config: T3tuiConfig; readonly config: T3tuiConfig;
readonly diff: DiffState | null; readonly diff: DiffState | null;
@@ -44,6 +46,7 @@ export function useDetails(deps: {
/** null follows the terminal width; d sets it for the rest of the session. */ /** null follows the terminal width; d sets it for the rest of the session. */
const [pref, setPref] = useState<boolean | null>(null); const [pref, setPref] = useState<boolean | null>(null);
const [selected, setSelected] = useState<string | null>(null); const [selected, setSelected] = useState<string | null>(null);
const [unfolded, setUnfolded] = useState<ReadonlySet<DetailsFold>>(() => new Set());
const show = pref ?? deps.width >= AUTO_WIDTH; const show = pref ?? deps.width >= AUTO_WIDTH;
const cwd = thread ? detailsCwd(thread, project) : null; const cwd = thread ? detailsCwd(thread, project) : null;
@@ -64,8 +67,11 @@ export function useDetails(deps: {
}; };
}, [session, live]); }, [session, live]);
const vcsState = vcs?.cwd === cwd ? vcs.state : null; const vcsState = vcs?.cwd === cwd ? vcs.state : null;
// Another thread starts with nothing selected. // Another thread starts with nothing selected, and folded.
useEffect(() => setSelected(null), [thread?.id]); useEffect(() => {
setSelected(null);
setUnfolded(new Set());
}, [thread?.id]);
const details = useMemo( const details = useMemo(
() => () =>
@@ -75,16 +81,23 @@ export function useDetails(deps: {
project, project,
vcs: vcsState, vcs: vcsState,
snapshot: deps.snapshot, snapshot: deps.snapshot,
subagents: deps.subagents, projection: deps.projection,
serverConfig: deps.serverConfig,
servers: servers?.items ?? [], servers: servers?.items ?? [],
automations: automations?.items ?? [], automations: automations?.items ?? [],
now: deps.now, now: deps.now,
timestampFormat: config.timestampFormat, timestampFormat: config.timestampFormat,
}) })
: null, : null,
[thread, project, vcsState, deps.snapshot, deps.subagents, servers, automations, deps.now, config.timestampFormat], [thread, project, vcsState, deps.snapshot, deps.projection, deps.serverConfig, servers, automations, deps.now, config.timestampFormat],
); );
const actions = useMemo(() => (details ? detailsActions(details) : []), [details]); const actions = useMemo(() => (details ? detailsActions(details, unfolded) : []), [details, unfolded]);
const toggleFold = (fold: DetailsFold) =>
setUnfolded((current) => {
const next = new Set(current);
if (!next.delete(fold)) next.add(fold);
return next;
});
/** The folder's uncommitted changes, or one file's. */ /** The folder's uncommitted changes, or one file's. */
const openDiff = (path: string | null) => { const openDiff = (path: string | null) => {
@@ -139,6 +152,8 @@ export function useDetails(deps: {
const activate = (action: DetailsAction) => { const activate = (action: DetailsAction) => {
setSelected(action.id); setSelected(action.id);
switch (action.kind) { switch (action.kind) {
case "fold":
return toggleFold(action.fold);
case "diff": case "diff":
return openDiff(action.path); return openDiff(action.path);
case "git": case "git":
@@ -155,7 +170,7 @@ export function useDetails(deps: {
const activateById = (id: string) => { const activateById = (id: string) => {
const action = actions.find((candidate) => candidate.id === id); const action = actions.find((candidate) => candidate.id === id);
if (!action) return; if (!action) return;
if (action.kind !== "thread") deps.focus(true); if (action.kind !== "thread" && action.kind !== "fold") deps.focus(true);
activate(action); activate(action);
}; };
const move = (delta: number) => { const move = (delta: number) => {
@@ -218,7 +233,7 @@ export function useDetails(deps: {
{ keys: ["h", "←"], run: leave }, { keys: ["h", "←"], run: leave },
); );
return { show, setPref, cwd, details, loading: vcsState?.status !== "live", selected, activateById, leave, keys: { focus: focusKey, toggle: toggleKey, commands, focused } }; return { show, setPref, cwd, details, loading: vcsState?.status !== "live", selected, unfolded, activateById, leave, keys: { focus: focusKey, toggle: toggleKey, commands, focused } };
} }
const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error)); const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
+3 -3
View File
@@ -53,11 +53,11 @@ describe("modes and hints", () => {
test("d toggles the details column", async () => { test("d toggles the details column", async () => {
const app = await open(); const app = await open();
expect(app.frame()).not.toContain("Workspace"); expect(app.frame()).not.toContain("/workspace/project ·");
await app.press("d"); await app.press("d");
expect(app.frame()).toContain("Workspace"); expect(app.frame()).toContain("/workspace/project ·");
await app.press("d"); await app.press("d");
expect(app.frame()).not.toContain("Workspace"); expect(app.frame()).not.toContain("/workspace/project ·");
}); });
}); });
+91 -9
View File
@@ -1,12 +1,14 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import type { OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell } from "@t3tools/contracts"; import type { OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadProjection, OrchestrationV2ThreadShell } from "@t3tools/contracts";
import type { VcsState } from "../src/client/session.ts"; import type { VcsState } from "../src/client/session.ts";
import { detailsActions, detailsCwd, threadDetails } from "../src/model/details.ts"; import { detailsActions, detailsCwd, shortTime, threadDetails } from "../src/model/details.ts";
import { v2Projection, v2ThreadShell } from "../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts";
const project = { id: "p1", title: "tasknotes", workspaceRoot: "/repo/tasknotes" } as unknown as OrchestrationProjectShell; const project = { id: "p1", title: "tasknotes", workspaceRoot: "/repo/tasknotes" } as unknown as OrchestrationProjectShell;
const thread = (extra: Record<string, unknown> = {}) => const thread = (extra: Record<string, unknown> = {}) =>
({ ({
...v2ThreadShell,
id: "t1", id: "t1",
title: "Fix sync", title: "Fix sync",
projectId: "p1", projectId: "p1",
@@ -64,7 +66,7 @@ describe("threadDetails", () => {
), ),
null, null,
); );
expect(details.branch).toEqual({ name: "feat/sync", upstream: "↑2 ↓0", pullRequest: { number: 41, title: "Fix sync", state: "open", tone: "good", checks: null } }); expect(details.branch).toEqual({ name: "feat/sync", upstream: "↑2", pullRequest: { number: 41, title: "Fix sync", state: "open", tone: "good", checks: null } });
expect(details.changes?.files).toHaveLength(1); expect(details.changes?.files).toHaveLength(1);
expect(details.changes?.branchTotal).toEqual({ baseRef: "main", insertions: 40, deletions: 2 }); expect(details.changes?.branchTotal).toEqual({ baseRef: "main", insertions: 40, deletions: 2 });
}); });
@@ -97,11 +99,12 @@ describe("threadDetails", () => {
vcs({}), vcs({}),
snapshot, snapshot,
); );
expect(details.lineage.map((entry) => [entry.text, entry.threadId])).toEqual([ expect(details.lineage.map((entry) => [entry.glyph, entry.text, entry.threadId])).toEqual([
['forked from "Plan sync"', "parent"], ["↰", "forked from Plan sync", "parent"],
['fork "Try another way"', "fork"], ["↳", "fork Try another way", "fork"],
["1 subagent running", undefined], ["◐", "1 subagent running", undefined],
]); ]);
expect(details.subagents).toEqual({ total: 1, running: 1 });
expect(details.background).toEqual([{ glyph: "◐", text: "dev server :5173" }]); expect(details.background).toEqual([{ glyph: "◐", text: "dev server :5173" }]);
expect(details.goal).toEqual({ objective: "Ship sync", status: "active · 1m", tone: "info" }); expect(details.goal).toEqual({ objective: "Ship sync", status: "active · 1m", tone: "info" });
}); });
@@ -120,7 +123,86 @@ describe("threadDetails", () => {
{ servers, automations, timestampFormat: "24-hour" } as never, { servers, automations, timestampFormat: "24-hour" } as never,
); );
expect(details.git?.quick).toEqual({ action: "commit_push_pr", label: "Commit, push & PR", commits: true }); expect(details.git?.quick).toEqual({ action: "commit_push_pr", label: "Commit, push & PR", commits: true });
expect(details.automations[0]).toMatchObject({ schedule: "Mon,Tue 09:00", status: "on" }); expect(details.automations[0]).toMatchObject({ when: "Mon,Tue 09:00", tone: "muted" });
expect(detailsActions(details).map((action) => action.id)).toEqual(["git:quick:commit_push_pr", "git:commit", "diff:*", "diff:src/a.ts", "server:5173", "automation:a1"]); expect(detailsActions(details).map((action) => action.id)).toEqual(["diff:src/a.ts", "diff:*", "git:quick:commit_push_pr", "git:commit", "server:5173", "automation:a1"]);
});
test("hides ahead/behind when both are zero", () => {
const details = detailsOf(thread(), vcs({}, { hasUpstream: true, aheadCount: 0, behindCount: 0, pr: null }), null);
expect(details.branch?.upstream).toBeNull();
expect(detailsOf(thread(), vcs({}, { hasUpstream: true, aheadCount: 0, behindCount: 3, pr: null }), null).branch?.upstream).toBe("↓3");
});
test("marks paths without counts as untracked", () => {
const files = [
{ path: "README.md", insertions: 29, deletions: 167 },
{ path: "docs/", insertions: 0, deletions: 0 },
{ path: "scripts/demo-capture.tsx", insertions: 0, deletions: 0 },
];
const details = detailsOf(thread(), vcs({ workingTree: { files, insertions: 29, deletions: 167 } }), null);
expect(details.changes?.files.map((file) => [file.status, file.path])).toEqual([
["M", "README.md"],
["?", "docs/"],
["?", "scripts/demo-capture.tsx"],
]);
});
test("shows the run state, the context window left and the provider's limits", () => {
const projection = { ...v2Projection, providerTurns: [{ tokenUsage: { usedTokens: 62_000, maxTokens: 100_000, updatedAt: "2026-06-20T00:00:00.000Z" } }] } as unknown as OrchestrationV2ThreadProjection;
const serverConfig = {
providers: [{ instanceId: "codex", driver: "codex", enabled: true, usageLimits: { checkedAt: "2026-06-20T00:00:00.000Z", windows: [{ id: "5h", kind: "session", label: "5h", usedPercent: 39 }, { id: "week", kind: "weekly", label: "week", usedPercent: 95 }] } }],
};
const details = detailsOf(thread({ status: "running", activeRunId: "run-1", latestRunId: "run-1" }), null, null, { projection, serverConfig } as never);
expect(details.context).toEqual({ left: 38, used: "62k" });
expect(details.limits).toEqual([
{ label: "5h", left: 61, tone: "muted" },
{ label: "week", left: 5, tone: "warn" },
]);
// Without usage reports there's nothing to show.
const quiet = detailsOf(thread(), null, null, { projection: v2Projection });
expect(quiet.context).toBeNull();
expect(quiet.limits).toBeNull();
expect(quiet.status).toBeNull();
});
test("shows the latest to-do list, folded around the step under way", () => {
const steps = (running: number) => Array.from({ length: 9 }, (_, index) => ({ id: `s${index}`, text: `Step ${index}`, status: index < running ? "completed" : index === running ? "running" : "pending" }));
const projection = {
...v2Projection,
turnItems: [
{ id: "old", type: "todo_list", planId: "p", steps: steps(0) },
{ id: "new", type: "todo_list", planId: "p", steps: steps(6) },
],
} as unknown as OrchestrationV2ThreadProjection;
const tasks = detailsOf(thread(), null, null, { projection }).tasks;
expect(tasks).toMatchObject({ done: 6, total: 9, window: { start: 4, end: 9 } });
expect(detailsActions(detailsOf(thread(), null, null, { projection }))[0]?.id).toBe("fold:tasks");
expect(detailsOf(thread(), null, null, { projection: v2Projection }).tasks).toBeNull();
});
test("lists running and failed subagents, folding finished ones", () => {
const child = (id: string, title: string, extra: Record<string, unknown> = {}) => ({ ...v2ThreadShell, id, title, lineage: { rootThreadId: "t1", parentThreadId: "t1", relationshipToParent: "subagent" }, ...extra });
const snapshot = { threads: [child("a", "Staging soak", { activeRunId: "run-a" }), child("b", "Fix webhook"), child("c", "Write docs")] } as unknown as OrchestrationV2ShellSnapshot;
const projection = { ...v2Projection, subagents: [{ childThreadId: "b", title: "Fix webhook", status: "failed" }, { childThreadId: "c", title: "Write docs", status: "completed" }] } as unknown as OrchestrationV2ThreadProjection;
const details = detailsOf(thread(), null, snapshot, { projection });
expect(details.lineage.map((entry) => [entry.glyph, entry.text, entry.finished ?? false])).toEqual([
["◐", "Staging soak", false],
["✕", "Fix webhook", false],
["✓", "Write docs", true],
]);
expect(details.subagents).toEqual({ total: 3, running: 1 });
expect(detailsActions(details).map((action) => action.id)).toEqual(["thread:a", "thread:b", "fold:subagents"]);
expect(detailsActions(details, new Set(["subagents"])).map((action) => action.id)).toEqual(["thread:a", "thread:b", "fold:subagents", "thread:c"]);
});
test("shows an automation's next run as a short time", () => {
const now = new Date(2026, 10, 3, 12, 0).getTime();
const at = (days: number, hours: number) => new Date(2026, 10, 3 + days, hours, 0).getTime();
expect(shortTime(at(0, 21), now, "24-hour")).toBe("today 21:00");
expect(shortTime(at(1, 9), now, "24-hour")).toBe("tomorrow 09:00");
// 3 November 2026 is a Tuesday.
expect(shortTime(at(6, 7), now, "24-hour")).toBe("Mon 07:00");
const automations = [{ id: "a1", title: "Weekly report", enabled: true, schedule: { type: "fixed_time", timeOfDay: "07:00", weekdays: [1] }, threadId: "t1", nextRunAt: new Date(at(6, 7)).toISOString(), lastRunStatus: "succeeded" }];
expect(detailsOf(thread(), null, null, { automations, now, timestampFormat: "24-hour" } as never).automations[0]).toMatchObject({ when: "Mon 07:00", tone: "muted" });
}); });
}); });