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
+501 -133

No files matched your search

+146 -36
View File
@@ -2,23 +2,36 @@ import type {
DiscoveredLocalServer,
GitStackedAction,
OrchestrationProjectShell,
OrchestrationV2PlanStep,
OrchestrationV2ShellSnapshot,
OrchestrationV2Subagent,
OrchestrationV2ThreadProjection,
OrchestrationV2ThreadShell,
ScheduledTask,
ServerConfig,
ThreadId,
VcsStatusResult,
} 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 type { VcsState } from "../client/session.ts";
import { formatClock, type T3tuiConfig } from "../config.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. */
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 path: string;
readonly worktree: boolean;
@@ -33,18 +46,18 @@ export interface ThreadDetails {
readonly changes: {
readonly insertions: 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. */
readonly branchTotal: { readonly baseRef: string | null; readonly insertions: number; readonly deletions: number } | null;
} | null;
/** The web's git quick action and menu: commit, push, create PR. */
readonly git: {
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[];
} | null;
/** Parent, forks and subagents; finished subagents fold away. */
readonly lineage: readonly LineageLine[];
readonly subagents: { readonly total: number; readonly running: number };
readonly servers: readonly { readonly server: DiscoveredLocalServer; readonly label: string }[];
readonly automations: readonly AutomationLine[];
readonly background: readonly { readonly glyph: string; readonly text: string }[];
@@ -60,22 +73,45 @@ export interface GitAction {
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 {
readonly glyph: string;
readonly tone: StatusTone;
readonly text: string;
/** The thread it links to, when there's one to open. */
readonly threadId?: ThreadId;
/** A finished subagent, folded away until asked for. */
readonly finished?: boolean;
}
export interface AutomationLine {
readonly task: ScheduledTask;
readonly schedule: string;
readonly status: string;
/** The next run, or its state when it isn't waiting for one. */
readonly when: string;
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. */
export type DetailsAction =
| { readonly kind: "fold"; readonly id: string; readonly fold: DetailsFold }
| { readonly kind: "diff"; readonly id: string; readonly path: string | null }
| { readonly kind: "git"; readonly id: string; readonly git: GitAction }
| { readonly kind: "thread"; readonly id: string; readonly threadId: ThreadId }
@@ -87,8 +123,13 @@ export interface DetailsInput {
readonly project: OrchestrationProjectShell | undefined;
readonly vcs: VcsState | 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 automations?: readonly ScheduledTask[];
readonly now?: number;
@@ -117,7 +158,7 @@ export function detailsCwd(thread: OrchestrationV2ThreadShell, project: Orchestr
}
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 local = vcs?.local?.isRepo ? vcs.local : null;
const remote = local ? (vcs?.remote ?? null) : null;
@@ -129,7 +170,7 @@ export function threadDetails(input: DetailsInput): ThreadDetails {
const branch = 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),
}
: null;
@@ -141,7 +182,7 @@ export function threadDetails(input: DetailsInput): ThreadDetails {
? {
insertions: tree.insertions,
deletions: tree.deletions,
files: tree.files,
files: tree.files.map((file): ChangedFile => ({ ...file, status: file.path.endsWith("/") || file.insertions + file.deletions === 0 ? "?" : "M" })),
branchTotal:
branchChanges && !local?.isDefaultRef && (branchChanges.insertions !== tree.insertions || branchChanges.deletions !== tree.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 lineage: LineageLine[] = [];
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)) {
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.
const subagents = new Map<ThreadId, string>();
for (const subagent of input.subagents ?? []) if (subagent.childThreadId) subagents.set(subagent.childThreadId, subagent.title ?? titleOf(subagent.childThreadId));
for (const other of threads) if (other.lineage.parentThreadId === thread.id && other.lineage.relationshipToParent === "subagent") subagents.set(other.id, other.title);
const running = new Set(threads.filter((other) => other.activeRunId !== null).map((other) => other.id as string));
for (const [threadId, title] of subagents) lineage.push({ glyph: running.has(threadId) ? "◐" : "↳", text: `subagent ${quote(title)}`, threadId });
// The projection names every subagent; the shell only the busy ones, but it knows their runs best.
const subagents = new Map<ThreadId, { title: string; agent?: OrchestrationV2Subagent }>();
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, { ...subagents.get(other.id), title: other.title });
const children = [...subagents].map(([threadId, { title, agent }]) => {
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;
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;
@@ -189,19 +237,69 @@ export function threadDetails(input: DetailsInput): ThreadDetails {
: 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. */
export function detailsActions(details: ThreadDetails): DetailsAction[] {
/** Steps shown before the rest of a to-do list folds into a count. */
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[] = [];
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 });
for (const git of details.git?.menu ?? []) actions.push({ kind: "git", id: `git:${git.action}`, git });
if (details.changes && details.changes.files.length > 0) {
actions.push({ kind: "diff", id: "diff:*", path: null });
for (const file of details.changes.files.slice(0, MAX_DETAIL_FILES)) actions.push({ kind: "diff", id: `diff:${file.path}`, path: file.path });
for (const line of details.lineage) {
if (line.finished && !actions.some((action) => action.id === "fold:subagents")) actions.push({ kind: "fold", id: "fold:subagents", fold: "subagents" });
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 { task } of details.automations) actions.push({ kind: "automation", id: `automation:${task.id}`, task });
return actions;
@@ -220,21 +318,31 @@ function gitActions(status: VcsStatusResult): NonNullable<ThreadDetails["git"]>
const menu = buildMenuItems(status, false, status.hasPrimaryRemote)
.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" }));
return { quick, hint: quick ? null : quickAction.hint ?? quickAction.label, menu };
return { quick, menu };
}
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"
? `every ${formatWorkingDurationLabel(task.schedule.everyMs)}`
: 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)}`
: "on webhook";
if (!task.enabled) return { task, schedule, status: "off", 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;
return { task, schedule, status: Number.isFinite(next) && next > now ? `in ${formatWorkingDurationLabel(next - now)}` : "on", tone: "good" };
return { task, when, tone: "muted" };
}
/** A time to come, as briefly as it reads: "today 21:00", "tomorrow 9:00", "Mon 7:00", "4 Mar 7:00". */
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"];
@@ -276,5 +384,7 @@ function tildify(path: string): string {
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"}`;
+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;
}
/** 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. */
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) {
case "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 { collectLimitAccounts, collectLimitNotices, formatDuration, remainingPercent, type LimitPresentations } from "@t3tools/shared/usageLimits";
import type { ProviderConsumeResetCreditInput, ProviderInstanceId, ServerConfig, ServerProviderResetCredits, UsageSummary } from "@t3tools/contracts";
import { collectLimitAccounts, collectLimitNotices, collectProviderUsageLimits, formatDuration, limitsNotice, remainingPercent, type LimitPresentations } from "@t3tools/shared/usageLimits";
import { formatTokens, formatUsd } from "@t3tools/shared/usageFormat";
/** 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 };
}
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. */
export function resetCreditsSummary(credits: ServerProviderResetCredits, now = Date.now()): string {
if (credits.availableCount === 0) return "No reset credits banked";