diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 567936900789d..7da6c2e6c2eb0 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2603,6 +2603,7 @@ const make = Effect.gen(function* () { parentNodeId: parentRun.rootNodeId, task: taskPrompt(input), ...(input.title === undefined ? {} : { title: input.title }), + ...(input.group === undefined ? {} : { group: input.group }), modelSelection: target.modelSelection, runtimeMode, interactionMode, diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 2846f3de864ee..2b557033f7f51 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -396,6 +396,7 @@ describe("orchestrator MCP toolkit", () => { providerInstanceId: codexInstanceId, model: codexModel, }, + group: "Backend", mode: "async", clientRequestId: "delegate-codex-replay-1", }); @@ -510,10 +511,12 @@ describe("orchestrator MCP toolkit", () => { expect(followupTasks.every((task) => task.result === null)).toBe(true); // Each subagent keeps the milestone that was active when it started. const parentNow = yield* orchestrator.getThreadProjection(parentThreadId); - expect( - parentNow.subagents.find((task) => task.id === delegated.taskId)?.milestoneId, - ).toBe("m1"); + expect(parentNow.subagents.find((task) => task.id === delegated.taskId)).toMatchObject({ + milestoneId: "m1", + group: "Backend", + }); expect(followupTasks.map((task) => task.milestoneId)).toEqual(["m2", "m2"]); + expect(followupTasks.map((task) => task.group)).toEqual(["Backend", "Backend"]); expect( parentNow.turnItems .filter((item) => item.type === "milestone") diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 06ec015174373..04ac348792693 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -8562,6 +8562,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio nativeTaskRef: null, prompt: command.task, title: command.title ?? null, + ...(command.group === undefined ? {} : { group: command.group }), model: command.modelSelection.model, ...(command.completionWake === undefined ? {} : { completionWake: command.completionWake }), status: "running", @@ -8980,6 +8981,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio nativeTaskRef: null, prompt: command.task, title: command.title ?? null, + ...(command.group === undefined ? {} : { group: command.group }), model: command.modelSelection.model, ...(command.completionWake === undefined ? {} : { completionWake: command.completionWake }), status: "running", diff --git a/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts b/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts index 4bb8c103f6df7..5a456c665a72d 100644 --- a/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts +++ b/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts @@ -205,6 +205,7 @@ it.layer(layerTest)("a delegated task in a linked environment", (it) => { parentRunId: parent.runId, parentNodeId: parent.rootNodeId, task: "Run the suite there.", + group: "Backend", driver: ProviderDriverKind.make("remote"), modelSelection, remoteChild, @@ -218,6 +219,7 @@ it.layer(layerTest)("a delegated task in a linked environment", (it) => { assert.equal(task?.childThreadId, null); assert.deepEqual(task?.remoteChild, remoteChild); assert.equal(task?.status, "running"); + assert.equal(task?.group, "Backend"); const item = projection.turnItems.find((candidate) => candidate.type === "subagent"); assert.deepEqual(item?.type === "subagent" ? item.remoteChild : undefined, remoteChild); // No thread was created here for the child. diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 6798159edd74a..dc092dfb01e9a 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -307,6 +307,7 @@ const make = Effect.gen(function* () { parentNodeId, task, ...(input.title === undefined ? {} : { title: input.title }), + ...(input.group === undefined ? {} : { group: input.group }), // The driver runs there; this side only labels the task with it. driver: ProviderDriverKind.make("remote"), modelSelection: launched.modelSelection, diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 1a3b70c00fa43..a0b224c31b7ab 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { - "claudeSystemAppendBytes": 5756, - "codexAdditionalContextBytes": 7486, - "mcpToolListJsonBytes": 48930 + "claudeSystemAppendBytes": 5826, + "codexAdditionalContextBytes": 7556, + "mcpToolListJsonBytes": 49005 } diff --git a/apps/web/src/components/ChatView.logic.browser.test.ts b/apps/web/src/components/ChatView.logic.browser.test.ts index 2d887cb5acc2c..230e279cb993b 100644 --- a/apps/web/src/components/ChatView.logic.browser.test.ts +++ b/apps/web/src/components/ChatView.logic.browser.test.ts @@ -59,3 +59,17 @@ it("refocuses the composer on window return from a clicked area after a bare key expect(document.activeElement).toBe(conversation); expect(shouldRefocusComposerOnWindowFocus(document.activeElement)).toBe(false); }); + +it("keeps focus in a zoomed-in milestone on window return so Esc still zooms out", () => { + const panel = document.createElement("div"); + panel.tabIndex = -1; + panel.dataset.milestoneZoom = ""; + panel.innerHTML = ""; + document.body.append(panel); + using _panel = { [Symbol.dispose]: () => panel.remove() }; + + panel.focus(); + expect(shouldRefocusComposerOnWindowFocus(document.activeElement)).toBe(false); + panel.querySelector("button")!.focus(); + expect(shouldRefocusComposerOnWindowFocus(document.activeElement)).toBe(false); +}); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index a1c935ecf5d77..1d52cc0eef52c 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1091,7 +1091,7 @@ export function shouldRefocusComposerOnWindowFocus( } return ( activeElement.closest( - '[data-workspace-keyboard-focus], [data-sidebar-row]:focus-visible, [role="dialog"], [role="alertdialog"], [role="application"], [role="menu"], [role="listbox"], [data-slot$="-popup"], [data-terminal-owner]', + '[data-workspace-keyboard-focus], [data-milestone-zoom], [data-sidebar-row]:focus-visible, [role="dialog"], [role="alertdialog"], [role="application"], [role="menu"], [role="listbox"], [data-slot$="-popup"], [data-terminal-owner]', ) === null ); } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 1a8974a262c4c..5d322f5f9f310 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -396,6 +396,7 @@ import { import { useDraftHeroLayoutTransition } from "./chat/useDraftHeroLayoutTransition"; import { useLocalDispatchState } from "./chat/useLocalDispatchState"; import { ThreadMilestonesView } from "./chat/ThreadMilestonesView"; +import type { CoordinatorAsk } from "./chat/MilestoneBoard"; import { formatMilestoneCommentPrefix, pendingAskCard, @@ -2937,11 +2938,20 @@ export default function ChatView(props: ChatViewProps) { chatReveal !== null && chatReveal.threadKey === activeThreadKey ? chatReveal : null; const milestonesShortcutLabel = shortcutLabelForCommand(keybindings, "milestones.toggle"); const milestoneTurnItems = serverVisibleTurnItems.map(({ item }) => item); - // A secret or link card waits on you in the timeline; Milestones shows the same card. + // A secret or link card waits on you in the timeline; Milestones and the plan show it too. const milestoneAskCard = - showMilestones && activeThreadShell?.hasPendingUserInput === true - ? pendingAskCard(serverVisibleTurnItems) - : null; + activeThreadShell?.hasPendingUserInput === true ? pendingAskCard(serverVisibleTurnItems) : null; + const coordinatorAsk: CoordinatorAsk | null = + activePendingApproval !== null + ? { kind: "approval" } + : milestoneAskCard !== null + ? { kind: "card", item: milestoneAskCard } + : activePendingUserInput !== null || activeThreadShell?.hasPendingUserInput === true + ? { + kind: "input", + question: activePendingUserInput?.questions[0]?.question ?? null, + } + : null; // A comment goes through the composer, so it queues or steers like any message you send. const commentOnMilestoneStable = useStableCallback((milestone: OrchestrationV2Milestone) => { const composer = composerRef.current; @@ -3738,19 +3748,7 @@ export default function ChatView(props: ChatViewProps) { threadRef={activeThreadRef} projection={serverProjection} turnItems={milestoneTurnItems} - coordinatorAsk={ - activePendingApproval !== null - ? { kind: "approval" } - : milestoneAskCard !== null - ? { kind: "card", item: milestoneAskCard } - : activePendingUserInput !== null || - activeThreadShell?.hasPendingUserInput === true - ? { - kind: "input", - question: activePendingUserInput?.questions[0]?.question ?? null, - } - : null - } + coordinatorAsk={coordinatorAsk} bottomInset={composerReservedHeight} onOpenThread={openSubagentStable} onComment={canOperateThread ? commentOnMilestoneStable : null} @@ -4224,6 +4222,13 @@ export default function ChatView(props: ChatViewProps) { /> 0 + ? { projection: serverProjection, coordinatorAsk } + : null + } anchor={threadPanelPopoverAnchorRef} handle={threadPanelPopoverHandle} forceNewWorktree={multipleModelSelections !== null} diff --git a/apps/web/src/components/chat/MilestoneAgents.tsx b/apps/web/src/components/chat/MilestoneAgents.tsx deleted file mode 100644 index 141383b3292ae..0000000000000 --- a/apps/web/src/components/chat/MilestoneAgents.tsx +++ /dev/null @@ -1,291 +0,0 @@ -import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { - formatSubagentDisplayTitle, - summarizeSubagentStatuses, -} from "@t3tools/client-runtime/state/subagent-display"; -import { - deriveWorkflowGroups, - isActiveSubagentStatus, - projectedSubagentsToRuntime, -} from "@t3tools/client-runtime/state/subagentRuntime"; -import type { OrchestrationV2Subagent, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; -import { copySorted } from "@t3tools/shared/Array"; -import { formatModelSlugName } from "@t3tools/shared/model"; -import { useState } from "react"; - -import { cn } from "~/lib/utils"; -import { useQuietThreadShell } from "../../state/entities"; -import { Badge } from "../ui/badge"; -import { Tooltip, TooltipTrigger } from "../ui/tooltip"; -import { AgentElapsed } from "./AgentElapsed"; -import { - EnvironmentSubagentAvatar, - SubagentHoverCard, - subagentDetailLine, - SubagentTimelineLink, - useSubagentLink, -} from "./V2LifecycleRow"; - -/** How many agents a tray shows before folding the rest. */ -const TRAY_LIMIT = 6; - -const linkProps = ( - threadRef: ScopedThreadRef, - agent: OrchestrationV2Subagent, - onOpenThread: (threadId: ThreadId) => void, -) => ({ - parentRef: threadRef, - subagentId: agent.id, - providerInstanceId: agent.providerInstanceId, - origin: agent.origin, - status: agent.status, - driver: agent.driver, - title: formatSubagentDisplayTitle(agent.title ?? "Subagent"), - result: agent.result, - progress: agent.progress, - startedAt: agent.startedAt, - completedAt: agent.completedAt, - threadId: agent.childThreadId, - remote: agent.remoteChild, - onOpenThread, -}); - -type Tone = "info" | "success" | "error" | "warning" | "outline"; - -function statusBadge(status: OrchestrationV2Subagent["status"]): { - readonly label: string; - readonly tone: Tone; -} { - switch (status) { - case "running": - return { label: "Running", tone: "info" }; - case "waiting": - return { label: "Waiting", tone: "info" }; - case "pending": - return { label: "Queued", tone: "outline" }; - case "idle": - return { label: "Idle", tone: "outline" }; - case "completed": - return { label: "Done", tone: "success" }; - case "failed": - return { label: "Failed", tone: "error" }; - case "cancelled": - case "interrupted": - return { label: "Stopped", tone: "outline" }; - } -} - -function WorkflowBar(props: { readonly agent: OrchestrationV2Subagent }) { - const group = deriveWorkflowGroups(projectedSubagentsToRuntime([props.agent]))[0]; - if (group === undefined || group.phases.length === 0) return null; - const done = group.phases.filter((phase) => phase.state === "done").length; - return ( - - - {group.phases.map((phase) => ( - - ))} - - {done}/{group.phases.length} phases - - ); -} - -/** A subagent as a card: who it is, its state, the line it last reported, and its time. */ -function AgentCard(props: { - readonly threadRef: ScopedThreadRef; - readonly agent: OrchestrationV2Subagent; - readonly onOpenThread: (threadId: ThreadId) => void; -}) { - const { agent } = props; - const link = useSubagentLink(linkProps(props.threadRef, agent, props.onOpenThread)); - const status = link.liveStatus; - // "waiting" alone can mean waiting on its own tools; only a pending request is waiting on you. - const shell = useQuietThreadShell( - status === "waiting" && agent.childThreadId !== null - ? scopeThreadRef(props.threadRef.environmentId, agent.childThreadId) - : null, - ); - const approval = shell?.hasPendingApprovals === true; - const needsYou = approval || shell?.hasPendingUserInput === true; - const badge = needsYou ? { label: "Needs you", tone: "warning" as const } : statusBadge(status); - const failed = status === "failed"; - const settled = badge.tone === "success" || badge.tone === "outline"; - const detail = needsYou - ? approval - ? "It needs your approval to continue." - : "It has a question for you." - : subagentDetailLine(status, link.result, link.progress); - const subtitle = [ - agent.workflow === undefined ? null : "Workflow", - agent.model ? formatModelSlugName(agent.model) : null, - link.remote === undefined ? null : `on ${link.remote.label}`, - ] - .filter(Boolean) - .join(" · "); - const title = formatSubagentDisplayTitle(agent.title ?? "Subagent"); - const action = needsYou ? "Answer" : failed ? "Open" : null; - const className = cn( - "flex size-full min-w-0 flex-col gap-1.5 rounded-xl border bg-card px-2.5 py-2 text-left shadow-xs/5", - needsYou ? "border-warning/45" : failed ? "border-destructive/30" : null, - ); - const content = ( - <> - - - - {title} - {subtitle ? ( - {subtitle} - ) : null} - - - - {detail} - - - - - {badge.label} - - {agent.workflow === undefined ? null : } - - - {action !== null && link.open !== null ? ( - - {action} - - ) : null} - - - ); - return ( - - - {content} - - ) : ( - - ) - } - /> - - - ); -} - -/** Agents that need a look come first, then live ones, then settled ones, each in start order. */ -const trayRank = ({ status }: OrchestrationV2Subagent) => - status === "waiting" || status === "failed" ? 0 : isActiveSubagentStatus(status) ? 1 : 2; - -export function agentTraySummary(agents: ReadonlyArray) { - return summarizeSubagentStatuses(agents.map(({ status }) => status)); -} - -/** - * A milestone's agents in a tray: cards while the work is live, compact rows once it settled. - * Past {@link TRAY_LIMIT} the rest fold behind a button. - */ -export function AgentTray(props: { - readonly threadRef: ScopedThreadRef; - readonly agents: ReadonlyArray; - readonly layout: "cards" | "rows"; - readonly onOpenThread: (threadId: ThreadId) => void; -}) { - const [showAll, setShowAll] = useState(false); - if (props.agents.length === 0) return null; - const sorted = copySorted(props.agents, (left, right) => trayRank(left) - trayRank(right)); - const visible = showAll ? sorted : sorted.slice(0, TRAY_LIMIT); - const hidden = sorted.length - visible.length; - return ( -
-
    - {visible.map((agent) => ( -
  • - {props.layout === "cards" ? ( - - ) : ( - - )} -
  • - ))} -
- {sorted.length > TRAY_LIMIT ? ( - - ) : null} -
- ); -} - -/** A few overlapping provider tiles for a folded milestone. */ -export function AgentStack(props: { - readonly threadRef: ScopedThreadRef; - readonly agents: ReadonlyArray; -}) { - return ( - - {props.agents.slice(0, 3).map((agent, index) => ( - 0 && "-ml-2")}> - - - ))} - - ); -} diff --git a/apps/web/src/components/chat/MilestoneTrace.tsx b/apps/web/src/components/chat/MilestoneTrace.tsx new file mode 100644 index 0000000000000..0c83dac8208fb --- /dev/null +++ b/apps/web/src/components/chat/MilestoneTrace.tsx @@ -0,0 +1,368 @@ +import { secondTick } from "@t3tools/client-runtime/clock"; +import { + formatTraceClock, + traceFraction, + tracePosition, + traceTicks, + type TraceAgentStatus, + type TraceDomain, + type TraceRowStatus, + type TraceSpan, +} from "@t3tools/client-runtime/state/thread-milestone-trace"; +import { CheckIcon, XIcon } from "lucide-react"; +import type { ScopedThreadRef } from "@t3tools/contracts"; +import type { CSSProperties, ReactNode } from "react"; + +import { cn } from "~/lib/utils"; +import { useChildThreadInputs } from "../../state/entities"; + +type TraceTone = TraceRowStatus | TraceAgentStatus | "coordinator" | "group"; + +const pct = (value: number) => `${(value * 100).toFixed(3)}%`; +const NOW = "var(--trace-now)"; + +/** Left and width of a span; a running span ends at the live now line. */ +export function spanStyle(domain: TraceDomain, span: TraceSpan, minWidth = "5px"): CSSProperties { + const left = tracePosition(domain, span.startMs); + return { + left: pct(left), + width: + span.endMs === null + ? `max(${minWidth}, calc((${NOW} - ${left}) * 100%))` + : `max(${minWidth}, ${pct(tracePosition(domain, span.endMs) - left)})`, + }; +} + +/** Something that has not run yet, placed `offsetMs` after the moving now line. */ +export function afterNowStyle( + domain: TraceDomain, + offsetMs: number, + widthMs: number, +): CSSProperties { + return { + left: `calc(${NOW} * 100% + ${pct(traceFraction(domain, offsetMs))})`, + width: pct(traceFraction(domain, widthMs)), + }; +} + +export const atStyle = (domain: TraceDomain, atMs: number): CSSProperties => ({ + left: pct(tracePosition(domain, atMs)), +}); + +export const atNowStyle: CSSProperties = { left: `calc(${NOW} * 100%)` }; + +const BAR_TONE: Record = { + done: "border-success/40 bg-success/15", + active: "border-info/50 border-r-2 border-r-info bg-linear-to-r from-info/13 to-info/26", + running: "border-info/50 border-r-2 border-r-info bg-linear-to-r from-info/13 to-info/26", + planned: "border-dashed border-foreground/20", + queued: "border-dashed border-foreground/20", + dropped: + "border-foreground/20 bg-[repeating-linear-gradient(135deg,color-mix(in_srgb,var(--color-foreground)_9%,transparent)_0_3px,transparent_3px_6px)]", + failed: "border-destructive/50 bg-destructive/13", + "needs-you": "border-warning/50 border-r-2 border-r-warning bg-warning/14", + stopped: "border-foreground/20 bg-foreground/8", + coordinator: "h-2.5 border-foreground/20 bg-foreground/8", + group: "h-2 border-transparent bg-foreground/8", +}; + +export function TraceBar(props: { + readonly tone: TraceTone; + readonly style: CSSProperties; + /** Moves the bar up to make room for agent strands under it. */ + readonly raised?: boolean; + readonly className?: string; +}) { + return ( + + ); +} + +const STRAND_TONE: Record = { + done: "bg-success/45", + running: "bg-info", + "needs-you": "bg-warning", + failed: "bg-destructive", + stopped: "bg-foreground/25", + queued: "h-0! border-t-2 border-dotted border-foreground/25 bg-transparent", +}; + +/** One agent as a thin line; overlapping lines ran at the same time. */ +export function TraceStrand(props: { + readonly status: TraceAgentStatus; + readonly style: CSSProperties; + readonly thick?: boolean; +}) { + return ( + + ); +} + +export function TracePin(props: { + readonly style: CSSProperties; + readonly ask?: boolean; + readonly raised?: boolean; +}) { + return ( + + ); +} + +export function MilestoneStatusIcon(props: { readonly status: TraceRowStatus }) { + switch (props.status) { + case "done": + return ( + + + + ); + case "active": + return ( + + + + ); + case "failed": + return ( + + + + ); + case "dropped": + case "stopped": + return ( + + + + ); + case "planned": + return ( + + ); + } +} + +/** Shared row grid: a label column, the plot, and in a zoomed chart a status column. */ +export const traceRowClass = + "relative grid grid-cols-[var(--trace-label)_minmax(0,1fr)_var(--trace-side)] items-stretch border-t border-foreground/7 first:border-t-0"; + +/** A row-wide button under the row's content; controls inside the row sit above it. */ +export const traceCoverClass = + "absolute inset-0 cursor-pointer outline-none hover:bg-foreground/4 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"; + +export function TraceLabel(props: { + readonly className?: string | undefined; + readonly children: ReactNode; +}) { + return ( +
+ {props.children} +
+ ); +} + +export function TraceText(props: { + readonly title: ReactNode; + readonly meta?: ReactNode; + readonly titleClassName?: string | undefined; + readonly metaClassName?: string | undefined; +}) { + return ( +
+
+ {props.title} +
+ {props.meta === undefined ? null : ( +
+ {props.meta} +
+ )} +
+ ); +} + +export function TracePlot(props: { readonly children?: ReactNode }) { + return
{props.children}
; +} + +export function TraceLegendSwatch(props: { readonly tone: TraceTone; readonly label: string }) { + return ( + + + {props.label} + + ); +} + +/** + * The chart card: an axis row, the rows, and an overlay with ticks, idle breaks and the now line. + * While live, now moves through the `--trace-now` variable on the shared second tick, so rows + * never re-render for it; `onHorizon` fires once now passes the domain's headroom. + */ +export function TraceChart(props: { + readonly domain: TraceDomain; + readonly nowMs: number; + readonly live: boolean; + readonly zoomed: boolean; + readonly axisLabel: string; + readonly onHorizon: () => void; + readonly legend?: ReactNode; + readonly children: ReactNode; +}) { + const { domain, nowMs, live, onHorizon } = props; + const trackNow = (node: HTMLDivElement | null) => { + if (!node) return; + const write = () => { + const now = Math.max(Date.now(), nowMs); + if (live && now > domain.horizonMs) { + onHorizon(); + return; + } + const at = tracePosition(domain, live ? now : nowMs); + node.style.setProperty("--trace-now", String(at)); + // The now pill shares the tick row, so tick labels hide while it passes them. + if (!live) return; + for (const tick of node.querySelectorAll("[data-trace-tick]")) { + const position = Number(tick.dataset.traceTick); + tick.toggleAttribute("data-under-now", position > at - 0.15 && position < at + 0.06); + } + }; + write(); + return live ? secondTick.subscribe(write) : undefined; + }; + const showNow = live; + const nowAt = tracePosition(domain, nowMs); + // A label at the right edge would be cut off. + const ticks = traceTicks(domain).filter(({ position }) => position <= 0.93); + return ( +
+
+
+
+
+ {props.axisLabel} +
+
+ {props.children} +
+ {ticks.map((tick, index) => ( +
span]:invisible", + index % 2 === 1 && "@max-xl:[&>span]:invisible", + )} + style={{ left: pct(tick.position) }} + > + + {formatTraceClock(tick.elapsedMs)} + +
+ ))} + {domain.gaps.map((gap) => { + const at = tracePosition(domain, gap.startMs); + const left = pct(at); + return ( +
+
+ {/* Work resuming after a break puts now just right of it, so the label moves left. */} + + {formatTraceClock(gap.endMs - gap.startMs)} idle + +
+ ); + })} + {showNow ? ( + <> +
+ + now + + + ) : null} +
+
+ {props.legend === undefined ? null : ( +
+ {props.legend} +
+ )} +
+
+ ); +} + +/** Child threads waiting on you, and which of them wait on an approval. */ +export function useAgentsWaitingOnYou(threadRef: ScopedThreadRef) { + const children = useChildThreadInputs(threadRef); + const waiting = children.filter( + (child) => child.hasPendingApprovals || child.hasPendingUserInput, + ); + return { + needsYou: new Set(waiting.map(({ id }) => id)), + approvals: new Set( + waiting.filter(({ hasPendingApprovals }) => hasPendingApprovals).map(({ id }) => id), + ), + }; +} diff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsx index 4e8a47a39791a..a961a220103e6 100644 --- a/apps/web/src/components/chat/ThreadDetailsCard.tsx +++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx @@ -78,10 +78,10 @@ export function ThreadDetailsCard({ const measure = () => { const frame = element.closest("[data-thread-details-card]"); const next = element.offsetHeight + (frame ? frame.offsetHeight - frame.clientHeight : 0); - // PR lists, servers, lineage, side chats and automations scroll as they grow. Counting them + // The plan, PR lists, servers, lineage, side chats and automations scroll as they grow. Counting them // toward density would hide the section and workspace controls when the user asks to see more. const lists = element.querySelectorAll( - "[data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list], [data-thread-automations-panel], [data-thread-details-server-overflow]", + "[data-thread-details-plan-list], [data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list], [data-thread-automations-panel], [data-thread-details-server-overflow]", ); const fittingHeight = next - Array.from(lists).reduce((sum, list) => sum + list.offsetHeight, 0); diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx index d2ef6c9b7d63c..57f816b049e19 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx @@ -20,6 +20,7 @@ import { memo, useState, type ComponentProps } from "react"; import { ThreadDetailsCard } from "./ThreadDetailsCard"; import { OpenInPicker } from "./OpenInPicker"; import { ThreadDetailsSection } from "./ThreadDetailsSection"; +import { ThreadPlanSection } from "./ThreadPlanSection"; import { ThreadAutomationsPanel } from "./ThreadAutomationsPanel"; import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl"; import { ThreadServersPanel } from "./ThreadServersPanel"; @@ -87,6 +88,8 @@ interface ThreadDetailsPanelProps extends Pick< ) => Promise; onDeleteProjectScript: (scriptId: string) => Promise; usage: ThreadDetailsUsageInput; + /** The thread's milestones, for the Plan section; null for drafts. */ + plan: Omit, "threadRef" | "density"> | null; } export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { @@ -165,11 +168,14 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { return ( <>
+ {visible.plan && props.plan !== null && !props.draftId ? ( + + ) : null} + {show.environment || show.openIn || show.scripts ? (
diff --git a/apps/web/src/components/chat/ThreadMilestonesView.tsx b/apps/web/src/components/chat/ThreadMilestonesView.tsx index b2f4e41fb89e5..f395efa838758 100644 --- a/apps/web/src/components/chat/ThreadMilestonesView.tsx +++ b/apps/web/src/components/chat/ThreadMilestonesView.tsx @@ -1,23 +1,24 @@ -import { secondTick } from "@t3tools/client-runtime/clock"; -import { isActiveSubagentStatus } from "@t3tools/client-runtime/state/subagentRuntime"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; import type { ThreadStructureTurnItem } from "@t3tools/client-runtime/state/models"; -import { - deriveMilestoneBoards, - MILESTONE_BOARD_ROOT, - type MilestoneBoardItem, - parseMilestoneComment, -} from "@t3tools/client-runtime/state/thread-milestone-board"; +import { deriveMilestoneBoards } from "@t3tools/client-runtime/state/thread-milestone-board"; import { deriveCoordinatorActivity, - deriveThreadMilestoneGraph, type MilestoneCoordinator, - type MilestoneGraphNode, - type MilestoneGraphTurn, - milestoneStripWeights, } from "@t3tools/client-runtime/state/thread-milestone-graph"; -import { resolveActiveThreadRun } from "@t3tools/client-runtime/state/thread-workflows"; +import { + deriveThreadTrace, + formatTraceDuration, + threadTraceDomain, + type ThreadTrace, + type TraceAgent, + type TraceCounts, + type TraceDomain, + type TraceGroup, + type TraceRow, + traceRowDomain, +} from "@t3tools/client-runtime/state/thread-milestone-trace"; import type { - EnvironmentId, OrchestrationV2Milestone, OrchestrationV2Subagent, OrchestrationV2ThreadProjection, @@ -25,23 +26,17 @@ import type { ThreadId, } from "@t3tools/contracts"; import { formatModelSlugName } from "@t3tools/shared/model"; -import { - CheckIcon, - ChevronRightIcon, - CornerDownLeftIcon, - UserRoundIcon, - XIcon, -} from "lucide-react"; import * as DateTime from "effect/DateTime"; -import { type ReactNode, useState } from "react"; -import { flushSync } from "react-dom"; +import { ArrowLeftIcon, ChevronLeftIcon, ChevronRightIcon, TriangleAlertIcon } from "lucide-react"; +import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react"; -import { useThreadViewModeStore } from "../../threadViewModeStore"; import { cn } from "~/lib/utils"; +import { type MilestoneZoom, useThreadViewModeStore } from "../../threadViewModeStore"; import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; +import { Kbd } from "../ui/kbd"; +import { Tooltip, TooltipTrigger } from "../ui/tooltip"; import { AgentElapsed } from "./AgentElapsed"; -import { AgentStack, AgentTray, agentTraySummary } from "./MilestoneAgents"; import { boardCounts, CommentButton, @@ -49,373 +44,222 @@ import { CoordinatorAskCard, MilestoneBoard, } from "./MilestoneBoard"; -import { EnvironmentSubagentAvatar } from "./V2LifecycleRow"; +import { + afterNowStyle, + atNowStyle, + atStyle, + MilestoneStatusIcon, + spanStyle, + TraceBar, + TraceChart, + traceCoverClass, + TraceLabel, + TraceLegendSwatch, + TracePin, + TracePlot, + traceRowClass, + TraceStrand, + TraceText, + useAgentsWaitingOnYou, +} from "./MilestoneTrace"; +import { + EnvironmentSubagentAvatar, + SubagentHoverCard, + subagentDetailLine, + useSubagentLink, +} from "./V2LifecycleRow"; type Projection = Pick< OrchestrationV2ThreadProjection, "runs" | "subagents" | "milestones" | "messages" >; -type Run = Projection["runs"][number]; -type Line = "solid" | "dashed" | "none"; type Tone = "info" | "success" | "error" | "warning" | "outline"; -const iso = (value: DateTime.Utc | null) => (value === null ? null : DateTime.formatIso(value)); +const iso = (ms: number | null) => + ms === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ms)); +const plural = (count: number, word: string) => `${count} ${count === 1 ? word : `${word}s`}`; -function timesWord(count: number) { - return count === 1 ? "once" : count === 2 ? "twice" : `${count} times`; +/** Zooming in, from the view or the Plan panel, takes focus so Esc and the arrows reach the view. */ +function focusZoomedPanel(node: HTMLDivElement | null) { + const active = document.activeElement; + if ( + node === null || + (active instanceof HTMLElement && + (active.isContentEditable || active.closest("input, textarea, select") !== null)) + ) + return; + node.focus({ preventScroll: true }); } -/** The first line of the user's message for a run, when that message is loaded. */ -function turnText(projection: Projection, turn: MilestoneGraphTurn): string | null { - const message = projection.messages.find(({ id }) => id === turn.run.userMessageId); - const line = message?.text.trim().split("\n")[0]?.trim(); - return line ? line : null; -} +const linkProps = ( + threadRef: ScopedThreadRef, + agent: OrchestrationV2Subagent, + onOpenThread: (threadId: ThreadId) => void, +) => ({ + parentRef: threadRef, + subagentId: agent.id, + providerInstanceId: agent.providerInstanceId, + origin: agent.origin, + status: agent.status, + driver: agent.driver, + title: formatSubagentDisplayTitle(agent.title ?? "Subagent"), + result: agent.result, + progress: agent.progress, + startedAt: agent.startedAt, + completedAt: agent.completedAt, + threadId: agent.childThreadId, + remote: agent.remoteChild, + onOpenThread, +}); -function turnLabel(turn: MilestoneGraphTurn): string { - const at = DateTime.toDate(turn.run.requestedAt).toLocaleTimeString([], { - hour: "numeric", - minute: "2-digit", - }); - return `Turn ${turn.run.ordinal} · ${at}`; +function coordinatorPhrase( + coordinator: MilestoneCoordinator, + awaitingUser: boolean, + activity: string | null, +): string { + if (awaitingUser) return "Waiting for you"; + switch (coordinator.status) { + case "waiting": + return activity ?? `Waiting on ${plural(coordinator.liveAgents, "agent")}`; + case "working": + return activity ?? "Working"; + case "failed": + return "Failed"; + case "interrupted": + return "Stopped"; + case "idle": + return "Idle"; + } } -const lineClass = (line: Line) => - line === "solid" ? "w-px bg-muted-foreground/35" : "border-l border-dashed"; - -const focusRing = - "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset focus-visible:outline-none"; - -const scrollBehavior = (): ScrollBehavior => - window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth"; - -const scrollToSelector = (selector: string) => - document.querySelector(selector)?.scrollIntoView({ block: "center", behavior: scrollBehavior() }); - -/** - * One stop on the spine: a node in the left gutter, the line arriving at it (`lineAbove`) and the - * line leaving it toward the next stop (`line`). - */ -function SpineItem(props: { - readonly node: ReactNode; - readonly line: Line; - readonly lineAbove?: Line; - readonly first?: boolean; - readonly last?: boolean; - readonly enterDelay?: number | null; - readonly children: ReactNode; - readonly milestoneId?: string; -}) { - const above = props.lineAbove ?? props.line; - return ( -
  • - {props.first || above === "none" ? null : ( - - )} - {props.last || props.line === "none" ? null : ( - - )} - - {props.node} - - {props.children} -
  • - ); +function overallBadge( + coordinator: MilestoneCoordinator, + awaitingUser: boolean, + allDone: boolean, +): { readonly label: string; readonly tone: Tone } { + if (awaitingUser) return { label: "Needs you", tone: "warning" }; + switch (coordinator.status) { + case "working": + case "waiting": + return { label: "Working", tone: "info" }; + case "failed": + return { label: "Failed", tone: "error" }; + case "interrupted": + return { label: "Stopped", tone: "warning" }; + case "idle": + return allDone ? { label: "Done", tone: "success" } : { label: "Idle", tone: "outline" }; + } } -function MilestoneNode(props: { - readonly status: OrchestrationV2Milestone["status"]; - readonly live: boolean; -}) { - switch (props.status) { - case "done": - return ( - - - - ); +function rowBadge(status: TraceRow["status"]): { readonly label: string; readonly tone: Tone } { + switch (status) { case "active": - return ( - - - - ); + return { label: "In progress", tone: "info" }; + case "done": + return { label: "Done", tone: "success" }; + case "failed": + return { label: "Failed", tone: "error" }; + case "stopped": + return { label: "Stopped", tone: "outline" }; case "dropped": - return ( - - - - ); + return { label: "Dropped", tone: "outline" }; case "planned": - return ; + return { label: "Planned", tone: "outline" }; } } -/** A user message on the spine. */ -function YouNode() { - return ( - - - - ); -} - -function JumpHint() { - return ( - - - Show in chat - - ); -} +const AGENT_BADGE: Record = { + running: { label: "Running", tone: "info" }, + "needs-you": { label: "Needs you", tone: "warning" }, + done: { label: "Done", tone: "success" }, + failed: { label: "Failed", tone: "error" }, + queued: { label: "Queued", tone: "outline" }, + stopped: { label: "Stopped", tone: "outline" }, +}; -const headClass = cn( - "group/jump -ml-2.5 flex min-h-8 w-full min-w-0 items-center gap-2.5 rounded-lg px-2.5 py-1 text-left hover:bg-accent", - focusRing, -); - -/** Your message as it reads in Chat; selecting it opens Chat there. */ -function YouMessage(props: { readonly text: string; readonly onJump: () => void }) { +function StatusBadge(props: { + readonly label: string; + readonly tone: Tone; + readonly dot?: boolean; +}) { return ( - + {props.label} + ); } -function Elapsed(props: { - readonly running: boolean; - readonly startedAt: DateTime.Utc | null; - readonly completedAt: DateTime.Utc | null; -}) { - return ( - - - - ); -} +const live = (counts: TraceCounts) => counts.running + counts.needsYou; -function SectionHead(props: { readonly title: string; readonly detail: string }) { +/** "1 of 3 done · 1 failed · needs you" for a group sub-row. */ +function groupSummary(group: TraceGroup): ReactNode { + const { counts } = group; return ( -
    - {props.title} - {props.detail} -
    + <> + {counts.done} of {group.agents.length} done + {counts.failed > 0 ? ( + · {counts.failed} failed + ) : null} + {counts.needsYou > 0 ? · needs you : null} + ); } -/** - * The plan as one strip, each milestone sized by the time it took. The active segment grows on - * the shared second tick through the DOM, so the view doesn't re-render every second. - */ -function PlanStrip(props: { - readonly milestones: ReadonlyArray; - readonly ticking: boolean; - readonly onSelect: (milestone: OrchestrationV2Milestone) => void; -}) { - const { milestones, ticking } = props; - const labelled = milestones.length <= 5; - const current = - milestones.find(({ status }) => status === "active") ?? - milestones.findLast(({ status }) => status === "done"); - const sizeSegments = (node: HTMLDivElement | null) => { - if (!node) return; - const write = () => { - for (const [index, weight] of milestoneStripWeights(milestones, Date.now()).entries()) { - const segment = node.children[index]; - if (segment instanceof HTMLElement) segment.style.flexGrow = String(weight); - } - }; - write(); - return ticking ? secondTick.subscribe(write) : undefined; - }; +/** "1 running · 1/3 done · 1 failed" for a group header in a zoomed milestone. */ +function groupDetail(group: TraceGroup): ReactNode { + const { counts } = group; return ( -
    -
    - {milestones.map((milestone) => ( - - ))} -
    - {labelled || current === undefined ? null : ( -

    {current.title}

    - )} -
    + <> + {live(counts) > 0 ? `${live(counts)} running · ` : ""} + {counts.done}/{group.agents.length} done + {counts.failed > 0 ? ( + · {counts.failed} failed + ) : null} + {counts.needsYou > 0 ? ( + · {counts.needsYou} needs you + ) : null} + ); } -function coordinatorPhrase(coordinator: MilestoneCoordinator, awaitingUser: boolean): string { - if (awaitingUser) return "is waiting for you"; - switch (coordinator.status) { - case "waiting": - return `is waiting on ${coordinator.liveAgents} ${coordinator.liveAgents === 1 ? "agent" : "agents"}`; - case "working": - return "is working"; - case "failed": - return "failed"; - case "interrupted": - return "was interrupted"; - case "idle": - return "is idle"; - } -} - -/** The coordinator's own stop: what it is doing now and for how long. */ -function CoordinatorCard(props: { - readonly environmentId: EnvironmentId; - readonly coordinator: MilestoneCoordinator; - readonly run: Run | null; - readonly activity: string | null; - readonly awaitingUser: boolean; - /** Absent when the question already shows on a milestone. */ - readonly onAnswer?: (() => void) | undefined; - /** A secret or link card to answer here, when no milestone holds it. */ - readonly askCard?: ReactNode; - readonly lineAbove: Line; - readonly line: Line; - readonly last: boolean; -}) { - const { status } = props.coordinator; - const live = status === "working" || status === "waiting"; - const model = props.run ? formatModelSlugName(props.run.modelSelection.model) : null; - return ( - - } - > -
    - {props.run === null ? null : ( - - )} -
    -
    - Coordinator{" "} - {model ? `${model} · ` : ""} - {coordinatorPhrase(props.coordinator, props.awaitingUser)} -
    - {live && !props.awaitingUser && props.activity !== null ? ( -
    {props.activity}
    - ) : null} -
    - {props.awaitingUser && props.onAnswer !== undefined ? ( - - ) : live && props.run?.startedAt ? ( - - - - ) : null} -
    - {props.askCard ?
    {props.askCard}
    : null} -
    +function RowDuration(props: { readonly row: TraceRow }) { + const { span } = props.row; + if (span === null) return null; + return span.endMs === null ? ( + + ) : ( + {formatTraceDuration(span.endMs - span.startMs)} ); } -function focusBadge(status: OrchestrationV2Milestone["status"]): { - readonly label: string; - readonly tone: Tone; -} { - switch (status) { - case "active": - return { label: "In progress", tone: "info" }; - case "done": - return { label: "Done", tone: "success" }; - case "dropped": - return { label: "Dropped", tone: "outline" }; - case "planned": - return { label: "Planned", tone: "outline" }; +function rowMeta(row: TraceRow, trace: ThreadTrace, posts: number): ReactNode { + if (row.status === "planned") return trace.kind === "turns" ? "Queued" : "Planned"; + const parts: Array = [ + row.status === "dropped" ? "Dropped" : , + ]; + if (row.agentCount > 0) { + parts.push(plural(row.agentCount, "agent")); + if (live(row.counts) > 1) { + parts.push( + + {live(row.counts)} in parallel + , + ); + } else if (row.counts.failed > 0) { + parts.push( + + {row.counts.failed} failed + , + ); + } else if (row.peakParallel > 1) { + parts.push(`${row.peakParallel} in parallel`); + } } + if (posts > 0 && parts.length < 3) parts.push(`${posts} on the board`); + return parts.flatMap((part, index) => (index === 0 ? [part] : [" · ", part])); } function Revision(props: { readonly milestone: OrchestrationV2Milestone }) { @@ -423,6 +267,7 @@ function Revision(props: { readonly milestone: OrchestrationV2Milestone }) { if (milestone.revision !== undefined) { return (

    + Changed from{" "} {milestone.revision.previousTitle}
    {milestone.revision.reason} @@ -430,74 +275,172 @@ function Revision(props: { readonly milestone: OrchestrationV2Milestone }) { ); } return milestone.note === undefined ? null : ( -

    {milestone.note}

    +

    {milestone.note}

    ); } -/** What a folded milestone holds, as chips; selecting them unfolds it. */ -function FoldedSummary(props: { +function AnswerAgentButton(props: { readonly threadRef: ScopedThreadRef; - readonly agents: ReadonlyArray; - readonly items: ReadonlyArray; - readonly open: boolean; - readonly onToggle: () => void; + readonly agent: OrchestrationV2Subagent; + readonly onOpenThread: (threadId: ThreadId) => void; }) { - const failed = props.agents.filter(({ status }) => status === "failed").length; - const chip = - "inline-flex h-7 items-center gap-1.5 rounded-lg border bg-card px-2 text-xs text-foreground/80 group-hover/fold:border-foreground/20"; + const link = useSubagentLink(linkProps(props.threadRef, props.agent, props.onOpenThread)); + if (link.open === null) return null; return ( - + ); +} + +/** A subagent that waits on you, answerable from the whole-thread view. */ +function AgentNeedsYouRow(props: { + readonly threadRef: ScopedThreadRef; + readonly agent: OrchestrationV2Subagent; + readonly approval: boolean; + readonly group: string | null; + readonly rowTitle: string; + readonly onOpenThread: (threadId: ThreadId) => void; +}) { + return ( +
    + + + + {formatSubagentDisplayTitle(props.agent.title ?? "Subagent")} + {" "} + {props.approval ? "needs your approval" : "has a question for you"}{" "} + + {props.group === null ? "" : `· ${props.group} `}· {props.rowTitle} - ))} - - - {props.open ? "Hide" : "Show"} - + +
    ); } -function overallBadge( - coordinator: MilestoneCoordinator, - awaitingUser: boolean, - allDone: boolean, -): { readonly label: string; readonly tone: Tone } { - if (awaitingUser) return { label: "Needs you", tone: "warning" }; - switch (coordinator.status) { - case "working": - case "waiting": - return { label: "Working", tone: "info" }; - case "failed": - return { label: "Failed", tone: "error" }; - case "interrupted": - return { label: "Stopped", tone: "warning" }; - case "idle": - return allDone ? { label: "Done", tone: "success" } : { label: "Idle", tone: "outline" }; - } +/** One agent in a zoomed milestone; the row opens its chat. */ +function TraceAgentRow(props: { + readonly threadRef: ScopedThreadRef; + readonly entry: TraceAgent; + readonly domain: TraceDomain; + readonly indented: boolean; + readonly highlighted: boolean; + readonly approval: boolean; + readonly onOpenThread: (threadId: ThreadId) => void; +}) { + const { entry, domain } = props; + const { agent, status } = entry; + const link = useSubagentLink(linkProps(props.threadRef, agent, props.onOpenThread)); + const title = formatSubagentDisplayTitle(agent.title ?? "Subagent"); + const detail = + status === "needs-you" + ? props.approval + ? "Needs your approval" + : "Has a question for you" + : status === "failed" + ? (subagentDetailLine(link.liveStatus, link.result, link.progress) ?? "Failed") + : null; + const model = agent.model ? formatModelSlugName(agent.model) : null; + const badge = AGENT_BADGE[status]; + return ( +
    { + if (node && props.highlighted) node.scrollIntoView({ block: "nearest" }); + }} + data-milestone-agent={agent.id} + className={cn( + traceRowClass, + "min-h-[46px] border-transparent", + props.highlighted && "bg-info/12", + )} + > + {link.open === null ? null : ( + + + } + /> + + + )} + + + + {[model, link.remote === undefined ? null : `on ${link.remote.label}`] + .filter(Boolean) + .join(" · ")} + {status === "queued" ? ( + model ? null : ( + "Queued" + ) + ) : ( + <> + {model || link.remote ? " · " : ""} + + + )} + + ) + } + /> + + + {entry.span === null ? ( + + ) : ( + + )} + +
    + {status === "needs-you" ? ( + + ) : ( + + )} +
    +
    + ); } /** - * The coordinator's progress: an overview of the plan, then a spine where finished milestones - * fold, the current one carries its agents and board, and the coordinator says what it is doing. - * Selecting a title or one of your messages opens Chat at that point. + * The thread on one time axis. Zoomed out it shows every milestone (or turn) with its groups of + * agents running side by side; zoomed in it rescales to one milestone and lists each agent. */ export function ThreadMilestonesView(props: { readonly threadRef: ScopedThreadRef; @@ -511,557 +454,350 @@ export function ThreadMilestonesView(props: { }) { const { threadRef, projection } = props; const environmentId = threadRef.environmentId; - const graph = deriveThreadMilestoneGraph(projection); - const activity = deriveCoordinatorActivity(props.turnItems); - const awaitingUser = props.coordinatorAsk !== null; - const run = - resolveActiveThreadRun(projection) ?? - projection.runs.reduce( - (latest, candidate) => - candidate.status !== "rolled_back" && - (latest === null || candidate.ordinal > latest.ordinal) - ? candidate - : latest, - null, - ); + const [clockMs, setClockMs] = useState(() => Date.now()); + const [expanded, setExpanded] = useState>(() => new Set()); + const [transition, setTransition] = useState<"in" | "out" | null>(null); + const containerRef = useRef(null); + const waiting = useAgentsWaitingOnYou(threadRef); + const storedZoom = useThreadViewModeStore( + (state) => state.zoomByThreadKey[scopedThreadKey(threadRef)] ?? null, + ); + const setStoredZoom = useThreadViewModeStore((state) => state.setZoom); + const setMode = useThreadViewModeStore((state) => state.setMode); + const revealInChat = useThreadViewModeStore((state) => state.revealInChat); const boards = deriveMilestoneBoards(props.turnItems, (item) => item.textOmitted ? (projection.messages.find(({ id }) => id === item.messageId)?.text ?? "") : item.text, ); - const [unfolded, setUnfolded] = useState>(() => new Set()); - const revealInChat = useThreadViewModeStore((state) => state.revealInChat); - const setMode = useThreadViewModeStore((state) => state.setMode); - // Milestones already present when the view opened appear at once; only new ones cascade in. - const [seenAtMount] = useState(() => new Set(projection.milestones.map(({ id }) => id))); - const [openEarlierSets, setOpenEarlierSets] = useState>(() => new Set()); - const jump = (entryId: string | undefined) => { - if (entryId !== undefined) revealInChat(threadRef, entryId); + const trace = deriveThreadTrace({ + projection, + turnItems: props.turnItems, + boards, + needsYou: waiting.needsYou, + nowMs: clockMs, + }); + const activity = deriveCoordinatorActivity(props.turnItems); + const rows = trace?.rows ?? []; + const zoomIndex = storedZoom === null ? -1 : rows.findIndex(({ id }) => id === storedZoom.rowId); + const zoomedRow = rows[zoomIndex] ?? null; + const highlight = zoomedRow === null ? null : storedZoom!.highlight; + + const zoom = (next: MilestoneZoom | null) => { + setTransition(next === null ? "out" : "in"); + setStoredZoom(threadRef, next); }; - const answer = () => setMode(threadRef, "chat"); - const toggleFold = (id: string) => - setUnfolded((current) => { - const next = new Set(current); - if (!next.delete(id)) next.add(id); - return next; - }); - const trayLayout = (agents: ReadonlyArray) => - agents.some(({ status }) => isActiveSubagentStatus(status)) ? "cards" : "rows"; - const coordinatorCard = ( - options: Pick< - Parameters[0], - "lineAbove" | "line" | "last" | "onAnswer" | "askCard" - >, - ) => ( - - ); + const step = (delta: number) => { + const next = rows[zoomIndex + delta]; + if (next !== undefined) zoom({ rowId: next.id, highlight: null }); + }; + const onKeyDown = useEffectEvent((event: KeyboardEvent) => { + if ( + zoomedRow === null || + event.defaultPrevented || + event.isComposing || + event.altKey || + event.ctrlKey || + event.metaKey || + event.shiftKey + ) + return; + const target = event.target; + // Keys reach the view only from the page itself or from inside the view, never from the + // composer, a dialog or a field. + if ( + !(target instanceof Element) || + (target !== document.body && !containerRef.current?.contains(target)) || + target.closest("input, textarea, select, [contenteditable]:not([contenteditable='false'])") + ) + return; + if (event.key === "Escape") zoom(null); + else if (event.key === "ArrowLeft") step(-1); + else if (event.key === "ArrowRight") step(1); + else return; + event.preventDefault(); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- listens on the window for Esc and the arrow keys that zoom out and step milestones + useEffect(() => { + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }, []); + + const answerInChat = () => setMode(threadRef, "chat"); + const jump = (entryId: string) => revealInChat(threadRef, entryId); + const recompute = () => setClockMs(Date.now()); + const noun = trace?.kind === "turns" ? "turn" : "milestone"; + const coordinatorAvatar = + trace?.coordinator.run == null ? null : ( + + ); let body: ReactNode; - if (graph.mode === "empty") { + if (trace === null) { body = ( -
    - - - - -

    Describe what you want built

    +
    +

    Describe what you want built

    The coordinator's plan shows up here as milestones while it works.

    ); - } else if (graph.mode === "turns") { + } else if (zoomedRow === null) { body = ( -
      - {graph.turns.map((turn, index) => ( - - ) : ( - - ) - } - > - jump(turn.run.userMessageId)} - /> - {turn.agents.length === 0 ? null : ( -
      - -
      - )} -
      - ))} - {props.coordinatorAsk?.kind === "card" - ? coordinatorCard({ - lineAbove: "solid", - line: "none", - last: true, - askCard: ( - - ), - }) - : coordinatorCard({ lineAbove: "solid", line: "none", last: true, onAnswer: answer })} -
    + + (boards.get(rowId) ?? []).filter(({ kind }) => kind !== "comment").length + } + expanded={expanded} + onToggle={(rowId) => + setExpanded((current) => { + const next = new Set(current); + if (!next.delete(rowId)) next.add(rowId); + return next; + }) + } + onZoom={zoom} + onHorizon={recompute} + onAnswerInChat={answerInChat} + onOpenThread={props.onOpenThread} + /> ); } else { - const live = graph.coordinator.status === "working" || graph.coordinator.status === "waiting"; - const nodes = graph.milestones; - const activeIndex = nodes.findIndex(({ milestone }) => milestone.status === "active"); - const coordinatorAfter = - activeIndex !== -1 - ? activeIndex - : nodes.findLastIndex(({ milestone }) => milestone.status !== "planned"); - const firstMilestone = nodes[0]?.milestone; - const counted = nodes - .map(({ milestone }) => milestone) - .filter(({ status }) => status !== "dropped"); - const overall = overallBadge( - graph.coordinator, - awaitingUser, - counted.length > 0 && counted.every(({ status }) => status === "done"), + const row = zoomedRow; + const items = boards.get(row.id) ?? []; + const named = row.groups.some(({ name }) => name !== null); + const domain = traceRowDomain(trace, row); + const isActive = row.status === "active"; + const coordinatorRuns = trace.coordinator.runs.filter( + (run) => + row.span !== null && + run.startMs <= (row.span.endMs ?? trace.nowMs) && + (run.endMs ?? trace.nowMs) >= row.span.startMs, ); - const failedAgents = [ - ...(graph.root?.agents ?? []), - ...nodes.flatMap(({ agents }) => agents), - ].filter(({ status }) => status === "failed"); - const isOpen = (index: number) => - index === coordinatorAfter || unfolded.has(nodes[index]!.milestone.id); - const revealAgent = (agent: OrchestrationV2Subagent) => { - const owner = nodes.findIndex(({ agents }) => agents.some(({ id }) => id === agent.id)); - if (owner !== -1 && !isOpen(owner)) { - flushSync(() => toggleFold(nodes[owner]!.milestone.id)); - } - scrollToSelector(`[data-milestone-agent="${CSS.escape(agent.id)}"]`); - }; - const newIds = nodes.map(({ milestone }) => milestone.id).filter((id) => !seenAtMount.has(id)); - const rootItems = boards.get(MILESTONE_BOARD_ROOT) ?? []; - const rootText = graph.root === null ? null : turnText(projection, graph.root); - const userTurns = (node: MilestoneGraphNode) => - node.turns - .filter((turn) => { - const text = turnText(projection, turn); - // A comment shows on the board of the milestone it is about. - return text === null || parseMilestoneComment(text) === null; - }) - .map((turn) => ( - jump(turn.run.userMessageId)} - /> - )); - const anchorOf = (milestone: OrchestrationV2Milestone) => - milestone.status === "done" || milestone.status === "active" - ? (milestone.anchors.started ?? milestone.anchors.done) - : (milestone.anchors.dropped ?? milestone.anchors.changed ?? milestone.anchors.planned); - - const focusCard = (node: MilestoneGraphNode) => { - const { milestone, agents } = node; - const items = boards.get(milestone.id) ?? []; - const badge = focusBadge(milestone.status); - return ( -
    -
    -
    - - - {badge.label} - - - {milestone.revision !== undefined ? ( - - Changed - - ) : null} - -
    - -
    -
    - {userTurns(node)} - {props.coordinatorAsk === null ? null : ( - - )} - {agents.length === 0 ? null : ( -
    - - -
    - )} - {items.length === 0 ? null : ( -
    - text) - .join(" · ")} - /> - -
    - )} - {props.onComment === null ? null : ( - props.onComment!(milestone)} /> - )} -
    -
    - ); - }; - - const settledStop = (node: MilestoneGraphNode, index: number) => { - const { milestone, agents } = node; - const items = boards.get(milestone.id) ?? []; - const reached = milestone.status === "done"; - const open = isOpen(index); - const foldable = reached && (agents.length > 0 || items.length > 0 || node.turns.length > 0); - const turns = userTurns(node); - return ( - <> - + Esc + + + {noun === "turn" ? "Turn" : "Milestone"} {zoomIndex + 1} of {rows.length} + + + +
    +
    + + + +
    +

    - {milestone.title} - - - {milestone.revision !== undefined ? ( - - Changed - - ) : null} - {milestone.status === "dropped" ? ( - - Dropped - - ) : null} - {reached ? ( - - ) : null} - - - {foldable ? ( - toggleFold(milestone.id)} - /> - ) : null} - {(!foldable || open) && (turns.length > 0 || agents.length > 0 || items.length > 0) ? ( -
    - {turns} - - -
    - ) : null} - - ); - }; - - body = ( - <> -
    -
    -
    -

    - {rootText ?? "Plan"} -

    -
    - - Milestone {graph.summary.position} of {graph.summary.total} + {row.title} +

    +
    + {row.span === null ? "Not started" : } + {row.agentCount > 0 ? ( + + {plural(row.agentCount, "agent")} + {named ? ` in ${plural(row.groups.length, "group")}` : ""} - {graph.coordinator.liveAgents > 0 ? ( + ) : null} +
    +
    + +
    + {row.milestone === null ? null : } + {isActive && props.coordinatorAsk !== null ? ( +
    + +
    + ) : null} + {domain === null ? ( +

    + {row.status === "planned" + ? `This ${noun} starts after the current one. The coordinator may change it before then.` + : `This ${noun} never started.`} +

    + ) : ( +
    + 1 && named ? ( - {graph.coordinator.liveAgents}{" "} - {graph.coordinator.liveAgents === 1 ? "agent" : "agents"} running + {plural(row.groups.length, "group")} ran in parallel; overlapping bars ran at + the same time. - ) : null} - {failedAgents.length > 0 ? ( - - ) : null} - {graph.summary.startedAt === null ? null : ( - milestone.completedAt !== null)?.milestone - .completedAt ?? null, - ), - }} + ) : undefined + } + > +
    + + {coordinatorAvatar} + - )} - {graph.summary.changes > 0 ? ( - Plan changed {timesWord(graph.summary.changes)} - ) : null} + + + {coordinatorRuns.map((run) => ( + + ))} + +
    + {isActive && trace.live ? : null} +
    -
    - - - {overall.label} - -
    - - scrollToSelector(`[data-milestone-node="${CSS.escape(milestone.id)}"]`) - } - /> - -
      - {graph.root === null ? null : ( - }> - jump(graph.root!.run.userMessageId)} - /> - {graph.root.agents.length === 0 && - rootItems.length === 0 && - (coordinatorAfter !== -1 || props.coordinatorAsk === null) ? null : ( -
      - {coordinatorAfter === -1 && props.coordinatorAsk !== null ? ( - { + const headed = named; + const groupHighlighted = + highlight?.kind === "group" && highlight.name === group.name; + return [ + headed ? ( +
      + + + {group.name ?? "Agents"} + + + {groupDetail(group)} + + + + {group.span === null ? null : ( + + )} + +
      + ) : null, + ...group.agents.map((entry) => ( + - ) : null} - - + )), + ]; + })} + {row.agentCount === 0 ? ( +
      + + No agents in this {noun}. +
      - )} - - )} - {graph.earlierSets.map((set) => { - const open = openEarlierSets.has(set.setId); - return ( - } - > - - {open ? ( -
        - {set.milestones.map((milestone) => ( -
      • - -
      • - ))} -
      - ) : null} -
      - ); - })} - } - > -
      + )} + {items.length === 0 && + !(isActive && props.onComment !== null && row.milestone !== null) ? null : ( +
      +
      + Board + + {boardCounts(items) + .map(({ text }) => text) + .join(" · ")} - - - - {coordinatorAfter === -1 - ? coordinatorCard({ lineAbove: "solid", line: "dashed", last: nodes.length === 0 }) - : null} - {nodes.flatMap((node, index) => { - const { milestone } = node; - const newIndex = newIds.indexOf(milestone.id); - const reached = milestone.status === "done" || milestone.status === "active"; - const item = ( - - } - > - {index === coordinatorAfter ? focusCard(node) : settledStop(node, index)} - - ); - return index === coordinatorAfter - ? [ - item, - coordinatorCard({ - lineAbove: "solid", - line: "dashed", - last: index === nodes.length - 1, - }), - ] - : [item]; - })} -
    +
    + + {props.onComment === null || row.milestone === null ? null : ( + props.onComment!(row.milestone!)} /> + )} + + )} ); } return (
    {body} @@ -1069,3 +805,274 @@ export function ThreadMilestonesView(props: {
    ); } + +function ZoomedOut(props: { + readonly trace: ThreadTrace; + readonly threadRef: ScopedThreadRef; + readonly coordinatorAsk: CoordinatorAsk | null; + readonly coordinatorAvatar: ReactNode; + readonly activity: string | null; + readonly approvals: ReadonlySet; + readonly boardPosts: (rowId: string) => number; + readonly expanded: ReadonlySet; + readonly onToggle: (rowId: string) => void; + readonly onZoom: (zoom: MilestoneZoom) => void; + readonly onHorizon: () => void; + readonly onAnswerInChat: () => void; + readonly onOpenThread: (threadId: ThreadId) => void; +}) { + const { trace } = props; + const domain = threadTraceDomain(trace); + const turns = trace.kind === "turns"; + const counted = trace.rows.filter(({ current, status }) => current && status !== "dropped"); + const awaitingUser = props.coordinatorAsk !== null; + const overall = overallBadge( + trace.coordinator, + awaitingUser || trace.needsYou.length > 0, + counted.length > 0 && counted.every(({ status }) => status === "done"), + ); + const running = live(trace.counts); + const firstFailed = trace.firstFailed; + const titles = new Map(trace.rows.map((row) => [row.id, row.title])); + return ( + <> +
    + {props.coordinatorAvatar} +
    +

    {trace.title ?? "Plan"}

    +
    + + {turns ? "Turn" : "Milestone"} {trace.position} of {trace.total} + + {trace.agentCount > 0 ? {plural(trace.agentCount, "agent")} : null} + {running > 0 ? {running} running : null} + {firstFailed === null ? null : ( + + )} + +
    +
    + +
    + {props.coordinatorAsk === null ? null : ( +
    + +
    + )} + {trace.needsYou.length === 0 ? null : ( +
    + {trace.needsYou.map(({ agent, group, rowId }) => ( + + ))} +
    + )} +
    + + + + {trace.rows.some(({ estimate }) => estimate !== null) ? ( + + ) : null} + + Select a {turns ? "turn" : "milestone"} to zoom in + + } + > +
    + + + {props.coordinatorAvatar} + + + + {trace.coordinator.runs.map((run) => ( + + ))} + +
    + {trace.rows.map((row) => ( + props.onToggle(row.id)} + onZoom={props.onZoom} + /> + ))} +
    +
    + + ); +} + +const agentStrandStyle = (domain: TraceDomain, entry: TraceAgent, top: number) => ({ + top, + ...(entry.span === null ? { ...atNowStyle, width: "3%" } : spanStyle(domain, entry.span, "3px")), +}); + +function OverviewRow(props: { + readonly row: TraceRow; + readonly trace: ThreadTrace; + readonly domain: TraceDomain; + readonly ask: boolean; + readonly posts: number; + readonly open: boolean; + readonly onToggle: () => void; + readonly onZoom: (zoom: MilestoneZoom) => void; +}) { + const { row, domain } = props; + const agents = row.groups.flatMap(({ agents: members }) => members); + const expandable = agents.length > 0; + const strands = expandable && !props.open; + const barStyle = + row.estimate !== null + ? afterNowStyle(domain, row.estimate.offsetMs, row.estimate.durationMs) + : row.span !== null + ? spanStyle(domain, row.span) + : null; + return ( + <> +
    + + ) : ( + + )} + + + + + {barStyle === null ? null : ( + + )} + {row.pins.map((pin) => ( + + ))} + {props.ask ? : null} + {strands + ? agents.map((entry, index) => ( + + )) + : null} + +
    + {props.open + ? row.groups.map((group) => ( +
    +
    + )) + : null} + + ); +} diff --git a/apps/web/src/components/chat/ThreadPlanSection.tsx b/apps/web/src/components/chat/ThreadPlanSection.tsx new file mode 100644 index 0000000000000..d285f35e78dd8 --- /dev/null +++ b/apps/web/src/components/chat/ThreadPlanSection.tsx @@ -0,0 +1,180 @@ +import { linkRequestTargetName } from "@t3tools/client-runtime/link-request"; +import { MILESTONE_BOARD_ROOT } from "@t3tools/client-runtime/state/thread-milestone-board"; +import { + deriveThreadTrace, + formatTraceClock, + type TraceRow, +} from "@t3tools/client-runtime/state/thread-milestone-trace"; +import type { OrchestrationV2ThreadProjection, ScopedThreadRef } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { GitBranchIcon, TriangleAlertIcon } from "lucide-react"; +import { useState } from "react"; + +import { cn } from "~/lib/utils"; +import { useThreadViewModeStore } from "../../threadViewModeStore"; +import { AgentElapsed } from "./AgentElapsed"; +import type { CoordinatorAsk } from "./MilestoneBoard"; +import { MilestoneStatusIcon, useAgentsWaitingOnYou } from "./MilestoneTrace"; +import { ThreadDetailsSection } from "./ThreadDetailsSection"; + +const iso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); + +function askLine(ask: CoordinatorAsk): string { + switch (ask.kind) { + case "card": + return `Asks you for ${ + ask.item.type === "secret_request" ? ask.item.label : linkRequestTargetName(ask.item) + }`; + case "approval": + return "Needs your approval"; + case "input": + return "Has a question for you"; + } +} + +function Duration(props: { readonly row: TraceRow }) { + const { span } = props.row; + if (span === null || props.row.status === "planned") return null; + return ( + + {span.endMs === null ? ( + + ) : ( + formatTraceClock(span.endMs - span.startMs) + )} + + ); +} + +/** + * The milestone plan at the top of thread details, so Chat keeps it in view: progress, each + * milestone, and how the live one's groups are doing. Selecting one opens Milestones on it. + */ +export function ThreadPlanSection(props: { + readonly threadRef: ScopedThreadRef; + readonly projection: Pick< + OrchestrationV2ThreadProjection, + "runs" | "subagents" | "milestones" | "messages" + >; + readonly coordinatorAsk: CoordinatorAsk | null; + readonly density: "full" | "compact" | "essential"; +}) { + const [nowMs] = useState(() => Date.now()); + const { needsYou } = useAgentsWaitingOnYou(props.threadRef); + const openMilestones = useThreadViewModeStore((state) => state.openMilestones); + const trace = deriveThreadTrace({ + projection: props.projection, + turnItems: [], + boards: new Map(), + needsYou, + nowMs, + }); + if (trace === null || trace.kind !== "milestones") return null; + const rows = trace.rows.filter(({ current, id }) => current && id !== MILESTONE_BOARD_ROOT); + const segments = rows.filter(({ status }) => status !== "dropped"); + return ( + +
    +
    + Plan + + {trace.position} of {trace.total} ·{" "} + + +
    +
    + {segments.map((row) => ( + + ))} +
    + {props.density === "essential" ? null : ( +
    + {rows.map((row) => ( +
    + + {row.status !== "active" ? null : props.coordinatorAsk !== null ? ( +
    + + {askLine(props.coordinatorAsk)} +
    + ) : row.agentCount === 0 ? null : ( +
    + {row.groups.map((group) => ( +
    + {group.name ?? "Agents"} + + + + + {group.counts.done}/{group.agents.length} + {group.counts.failed > 0 ? ( + + {" "} + · {group.counts.failed} failed + + ) : null} + {group.counts.needsYou > 0 ? ( + · needs you + ) : null} + +
    + ))} +
    + )} +
    + ))} +
    + )} + +
    +
    + ); +} diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx index d87225abd8653..7cabe6954144f 100644 --- a/apps/web/src/components/chat/V2LifecycleRow.tsx +++ b/apps/web/src/components/chat/V2LifecycleRow.tsx @@ -477,7 +477,7 @@ export function SubagentHoverCard( ); } -export function SubagentTimelineLink( +function SubagentTimelineLink( props: SubagentLinkProps & { readonly event?: { readonly status: OrchestrationV2TurnItem["status"] | null; diff --git a/apps/web/src/components/chat/threadDetailsItems.ts b/apps/web/src/components/chat/threadDetailsItems.ts index e6f94cc4e11c8..e1fd886580063 100644 --- a/apps/web/src/components/chat/threadDetailsItems.ts +++ b/apps/web/src/components/chat/threadDetailsItems.ts @@ -2,6 +2,7 @@ import type { ClientSettings } from "@t3tools/contracts"; // Ids are stored in client settings, so never rename one. export const THREAD_DETAILS_ITEMS = [ + { id: "plan", label: "Milestone plan", defaultVisible: true }, { id: "environment", label: "Environment and worktree", defaultVisible: true }, { id: "openIn", label: "Open in editor", defaultVisible: true }, { id: "scripts", label: "Project scripts", defaultVisible: true }, diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 58fbf7b043d9f..b0617ce5e020f 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -225,8 +225,9 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil compositor updates discrete frames instead of every vsync. */ --animate-status-pulse: status-pulse 2s infinite; --animate-status-ping: status-ping 2s infinite; - /* Runs once when a milestone node is inserted; delays stagger a plan's cascade. */ - --animate-milestone-enter: milestone-enter 250ms cubic-bezier(0.2, 0.7, 0.2, 1) both; + /* Runs once as Milestones zooms into a milestone or back out to the whole thread. */ + --animate-trace-zoom-in: trace-zoom-in 180ms ease-out; + --animate-trace-zoom-out: trace-zoom-out 180ms ease-out; /* Stash pulses hold a highlight for 1.2s; the row then eases back over 200ms, the count snaps. The row alternates two identical keyframes so each stash restarts it without a remount. */ --animate-stash-pulse-row: stash-pulse-row 1400ms; @@ -346,10 +347,16 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil opacity: 1; } } - @keyframes milestone-enter { + @keyframes trace-zoom-in { from { opacity: 0; - translate: 0 4px; + scale: 0.975; + } + } + @keyframes trace-zoom-out { + from { + opacity: 0; + scale: 1.02; } } @keyframes status-ping { diff --git a/apps/web/src/threadViewModeStore.ts b/apps/web/src/threadViewModeStore.ts index 2a6578e129db1..f4f679b5ca062 100644 --- a/apps/web/src/threadViewModeStore.ts +++ b/apps/web/src/threadViewModeStore.ts @@ -14,13 +14,28 @@ export interface ThreadChatReveal { readonly requestId: number; } +/** The milestone (or turn) Milestones is zoomed into, and what it singles out there. */ +export interface MilestoneZoom { + readonly rowId: string; + readonly highlight: + | { readonly kind: "group"; readonly name: string | null } + | { readonly kind: "agent"; readonly id: string } + | null; +} + interface ThreadViewModeState { byThreadKey: Record; + /** Not persisted: a reload opens Milestones zoomed out. */ + zoomByThreadKey: Record; /** New threads open in the view used last. */ lastUsed: ThreadViewMode; reveal: ThreadChatReveal | null; setMode: (ref: ScopedThreadRef, mode: ThreadViewMode) => void; toggle: (ref: ScopedThreadRef) => void; + /** Zooms Milestones in, or out with null, without changing the mode. */ + setZoom: (ref: ScopedThreadRef, zoom: MilestoneZoom | null) => void; + /** Switches the thread to Milestones, zoomed as given. */ + openMilestones: (ref: ScopedThreadRef, zoom: MilestoneZoom | null) => void; /** Switches the thread to Chat and asks it to reveal `entryId`. */ revealInChat: (ref: ScopedThreadRef, entryId: string) => void; finishReveal: (requestId: number) => void; @@ -30,6 +45,7 @@ export const useThreadViewModeStore = create()( persist( (set, get) => ({ byThreadKey: {}, + zoomByThreadKey: {}, lastUsed: "chat", reveal: null, // A reveal left pending (its history page never landed) must not fire on a later visit. @@ -41,6 +57,17 @@ export const useThreadViewModeStore = create()( })), toggle: (ref) => get().setMode(ref, selectThreadViewMode(get(), ref) === "chat" ? "milestones" : "chat"), + setZoom: (ref, zoom) => + set((state) => { + const { [scopedThreadKey(ref)]: _previous, ...rest } = state.zoomByThreadKey; + return { + zoomByThreadKey: zoom === null ? rest : { ...rest, [scopedThreadKey(ref)]: zoom }, + }; + }), + openMilestones: (ref, zoom) => { + get().setMode(ref, "milestones"); + get().setZoom(ref, zoom); + }, revealInChat: (ref, entryId) => { get().setMode(ref, "chat"); set((state) => ({ diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 25964897aaeb2..88dcf356598d9 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -240,6 +240,7 @@ type DelegateTaskInput = { }; title?: string; role?: "implementation" | "research" | "review" | "design" | "test" | "general"; + group?: string; // work stream clients group parallel subagents by, such as "UI" mode?: "async" | "wait"; timeoutMs?: number; clientRequestId?: string; diff --git a/docs/user/milestones.md b/docs/user/milestones.md index 5c587ab836521..3916a8608b1e5 100644 --- a/docs/user/milestones.md +++ b/docs/user/milestones.md @@ -1,14 +1,30 @@ # Milestones -On long, multi-phase work, an agent plans its phases as milestones and marks each one as it starts and finishes. The thread's **Milestones** view shows that plan: where the agent is, what it finished, what changed since it planned, and which subagents work on each phase. Short tasks don't get milestones. +On long, multi-phase work, an agent plans its phases as milestones and marks each one as it starts and finishes. The thread's **Milestones** view shows that plan on one timeline: what is done, what is running, what is left, and which subagents worked on each phase. Short tasks don't get milestones. Switch a thread between **Chat** and **Milestones** with the toggle in its header, the command palette, or `mod+alt+m`. Each thread remembers its view, and a new thread opens in the view you used last. The composer stays at the bottom in both. Milestones is available on web and desktop. -- Select a milestone, or one of your messages, to jump to that point in Chat. -- Finished milestones fold into a summary of their agents and posts; select it to unfold one. When an agent fails, **N agents failed** at the top takes you to it. +## The whole thread + +Milestones opens zoomed out: every milestone on one time axis, with the coordinator's own work on top and a **now** line. Milestones still to come sit after now, sized by how long finished ones took. Long stretches where nothing ran fold into a short break labelled with the idle time, so the axis keeps the work readable while its labels still show real time. + +- The live milestone lists the groups its subagents work in, such as UI or Backend, with one line per subagent. Lines that overlap ran at the same time. Use the arrow beside any other milestone to show its groups. +- When the agent or a subagent waits on you, it shows above the timeline. Answer a secret or a link request right there; **Answer** opens a subagent's chat. +- When a subagent failed, **N failed** at the top opens its milestone and points at it. + +A thread without milestones shows one row per turn instead. + +## One milestone + +Select a milestone, or one of its groups, to zoom in. The axis rescales to that milestone, each group lists its subagents, and the milestone's board follows below. + - Select a subagent to open its chat beside the view. Closing that tab doesn't delete the subagent. -- When the agent or a subagent is waiting on you, the milestone it is working on says so. Answer the agent in the composer; **Answer** opens a subagent's chat. - Select **Comment on this milestone** to start a message that names it. The agent receives it like any other message, and the comment stays on that milestone. -- The agent can post notes and images to a milestone. Visual replies it shows during a milestone appear there too. +- The agent can post notes and images to a milestone. Visual replies it shows during a milestone appear there too; select one to see it in Chat. +- Press `Esc` or **All milestones** to zoom back out, and the left and right arrow keys to step through milestones. + +## The plan in Chat + +While you read Chat, the thread details card keeps the plan at its top: progress, each milestone, and how the live milestone's groups are doing. Select a milestone to open Milestones on it, or **Open in Milestones** for the whole thread. Hide it from the details card's menu with **Milestone plan**. -A thread without milestones shows one entry per turn instead. Only the loaded part of a long thread fills the view; scrolling back in Chat loads more. +Only the loaded part of a long thread fills the view; scrolling back in Chat loads more. diff --git a/evals/mcp-tool-use/cases/orchestration.ndjson b/evals/mcp-tool-use/cases/orchestration.ndjson index 954e189bbb11f..69a82079ea70c 100644 --- a/evals/mcp-tool-use/cases/orchestration.ndjson +++ b/evals/mcp-tool-use/cases/orchestration.ndjson @@ -42,3 +42,4 @@ {"id": "thread-send-fresh-context", "area": "orchestration", "kind": "guard", "pattern": "t3_thread_send that should start a fresh provider session", "experience": "The user wanted a confused long-running thread to start over in the same thread without its old context; a plain send would keep feeding it the history.", "rule": "`freshContext: true` on t3_thread_send starts a new provider session in the same thread, like /clear.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "The thread working on the CSV importer keeps reverting to the old column mapping from early in its history."}, {"role": "assistant", "text": "That thread has a long history with three different mappings in it, so the model keeps picking up the stale one."}], "mocks": {"t3_thread_send": {"threadId": "11111111-1111-4111-8111-111111111111", "link": "", "messageId": "msg-1", "runId": "run-1", "status": "starting", "delivery": "started"}}}, "prompt": "Send it the final mapping below and have it start over with a clean context in that same thread, so the old history stops leaking in: thread 11111111-1111-4111-8111-111111111111.\n\nFinal mapping: id -> customer_id, amt -> amount_cents, ts -> created_at.", "expect": {"calls": [{"tool": "t3_thread_send", "args": {"threadId": "11111111-1111-4111-8111-111111111111", "freshContext": true}}], "notCalls": ["delegate_task", "t3_thread_launch", "create_threads"]}, "source": {"request": "juliusmarminge (maintainer) request, 2026-11-03: fresh provider sessions in one T3 thread"}, "notes": "Pairs with thread-send-to-named-top-level-thread, where an ordinary send must not set freshContext."} {"id": "milestones-plan-multi-phase", "area": "orchestration", "kind": "guard", "pattern": "long multi-phase work without milestones", "experience": "A coordinator ran a four-phase migration across server, web and mobile without planning milestones, so the thread's Milestones view could only show turns.", "rule": "Long multi-phase work: t3_milestone plan first, then start/done as phases change. Skip it for short tasks.", "source": {"request": "milestones stack (OmarAlex24/t3code#5): t3_milestone records a coordinator's phases"}, "privacy": "commit-safe", "setup": {"role": "top", "world": {"files": {"apps/server/src/auth/session.ts": "export function readSession(req: Request) {\n return sessions.get(req.cookies.sid);\n}\n", "apps/web/src/auth/client.ts": "export const signIn = (body: Credentials) => fetch('/api/session', { method: 'POST', body: JSON.stringify(body) });\n", "apps/mobile/src/auth/client.ts": "export const signIn = (body: Credentials) => api.post('/api/session', body);\n"}}, "mocks": {"t3_milestone": {"state": "m1 active · 0/4 · next m2 m3 m4"}}}, "prompt": "Move auth from cookie sessions to short-lived JWTs with refresh tokens. Phases: design the token format and rotation, swap the server middleware, migrate the web and mobile clients, then delete the session table and its code. Work through all of it; use subagents for the client migrations if that helps.", "expect": {"calls": [{"tool": "t3_milestone", "args": {"action": "plan"}}]}} {"id": "control-milestones-short-task", "area": "orchestration", "kind": "control", "pattern": "milestones for a one-step change", "experience": "A one-file rename is ordinary work. Planning milestones for it would clutter the thread.", "rule": "Skip t3_milestone for short tasks.", "source": {"request": "milestones stack (OmarAlex24/t3code#5): control for the milestones instruction"}, "privacy": "commit-safe", "setup": {"role": "top", "world": {"files": {"src/user.ts": "export function getUserName(user: User) {\n return user.displayName ?? user.email;\n}\n", "src/header.tsx": "import { getUserName } from './user';\nexport const Header = ({ user }: Props) =>

    {getUserName(user)}

    ;\n"}}, "mocks": {"t3_milestone": {"state": "m1 active · 0/4 · next m2 m3 m4"}}}, "prompt": "Rename getUserName to getDisplayName and update its callers.", "expect": {"notCalls": ["t3_milestone"]}} +{"id": "milestone-parallel-streams-grouped", "area": "orchestration", "kind": "guard", "pattern": "parallel work streams delegated without a group", "experience": "A coordinator split a milestone into UI and backend workers; without a group on each delegate_task, the Milestones view could not show the two streams side by side.", "rule": "Parallel streams: set each `delegate_task` `group` (\"UI\", \"Backend\").", "source": {"request": "milestones stack (OmarAlex24/t3code): coordinator groups parallel subagents by work stream"}, "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default", "t3_milestone": {"state": "m2 active · 1/3 · next m3"}}, "world": {"files": {"apps/web/src/settings/ThemeToggle.tsx": "export function ThemeToggle() {\n return {}} />;\n}\n", "apps/web/src/settings/SettingsPage.tsx": "export function SettingsPage() {\n return

    Settings

    ;\n}\n", "apps/server/src/preferences/api.ts": "export const getPreferences = (userId: string) => db.preferences.find(userId);\n", "apps/server/src/preferences/schema.sql": "CREATE TABLE preferences (user_id TEXT PRIMARY KEY, locale TEXT);\n"}}}, "prompt": "Milestone 2 is dark mode, and it splits into two parallel streams. Start 2 Grok workers on the UI (one wires ThemeToggle, one adds the Appearance section to SettingsPage) and 2 Grok workers on the backend (one adds a theme column to preferences, one exposes it in the preferences API).", "expect": {"calls": [{"tool": "delegate_task", "args": {"group": "~ui"}}, {"tool": "delegate_task", "args": {"group": "~backend"}}], "callsMustNot": [{"tool": "delegate_task", "args": {"group": null}}], "minCalls": {"delegate_task": 4}}, "notes": "Grok needs delegate_task from every parent, so a native helper cannot pass or fail it. The prompt names the streams but not the parameter."} diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 30c4c32546db3..0611d5d0adaf4 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -387,6 +387,10 @@ "types": "./src/state/threadMilestoneGraph.ts", "default": "./src/state/threadMilestoneGraph.ts" }, + "./state/thread-milestone-trace": { + "types": "./src/state/threadMilestoneTrace.ts", + "default": "./src/state/threadMilestoneTrace.ts" + }, "./state/thread-milestone-board": { "types": "./src/state/threadMilestoneBoard.ts", "default": "./src/state/threadMilestoneBoard.ts" diff --git a/packages/client-runtime/src/state/threadMilestoneGraph.test.ts b/packages/client-runtime/src/state/threadMilestoneGraph.test.ts index 0f4041598315a..5bb8d49731b7a 100644 --- a/packages/client-runtime/src/state/threadMilestoneGraph.test.ts +++ b/packages/client-runtime/src/state/threadMilestoneGraph.test.ts @@ -11,11 +11,7 @@ import { } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; -import { - deriveCoordinatorActivity, - deriveThreadMilestoneGraph, - milestoneStripWeights, -} from "./threadMilestoneGraph.ts"; +import { deriveCoordinatorActivity, deriveThreadMilestoneGraph } from "./threadMilestoneGraph.ts"; const at = (minute: number) => DateTime.makeUnsafe(`2026-11-10T10:${String(minute).padStart(2, "0")}:00.000Z`); @@ -104,16 +100,17 @@ describe("deriveThreadMilestoneGraph", () => { expect(graph.mode).toBe("milestones"); if (graph.mode !== "milestones") return; expect(ids(graph.root!.agents)).toEqual(["scout"]); - expect(graph.milestones.map((node) => ids(node.agents))).toEqual([["mapper"], ["builder"], []]); - // The user's second turn landed while m2 was active. - expect(graph.milestones[1]!.turns.map((turn) => [turn.run.id, ids(turn.agents)])).toEqual([ - ["run-2", ["orphan"]], + // The user's second turn landed while m2 was active, so its unstamped agent joins m2. + expect(graph.milestones.map((node) => ids(node.agents))).toEqual([ + ["mapper"], + ["builder", "orphan"], + [], ]); expect(graph.coordinator).toEqual({ status: "waiting", liveAgents: 1 }); - expect(graph.summary).toMatchObject({ position: 2, total: 3, changes: 1 }); + expect(graph.summary).toEqual({ position: 2, total: 3 }); }); - it("collapses earlier sets and counts only the current one", () => { + it("keeps earlier sets in order with their agents, and counts only the current one", () => { const graph = deriveThreadMilestoneGraph({ runs: [run(1, "completed", 0)], milestones: [ @@ -127,10 +124,16 @@ describe("deriveThreadMilestoneGraph", () => { }); if (graph.mode !== "milestones") throw new Error(graph.mode); - expect(graph.earlierSets).toEqual([expect.objectContaining({ setId: "s1", agentCount: 1 })]); - expect(graph.earlierSets[0]!.milestones.map(({ id }) => id)).toEqual(["m1", "m2"]); - expect(graph.milestones.map(({ milestone }) => milestone.id)).toEqual(["m3", "m4", "m5"]); - expect(graph.summary).toMatchObject({ position: 2, total: 2 }); + expect( + graph.milestones.map((node) => [node.milestone.id, node.current, ids(node.agents)]), + ).toEqual([ + ["m1", false, ["early"]], + ["m2", false, []], + ["m3", true, []], + ["m4", true, []], + ["m5", true, []], + ]); + expect(graph.summary).toEqual({ position: 2, total: 2 }); expect(graph.coordinator.status).toBe("idle"); }); @@ -184,31 +187,3 @@ describe("deriveCoordinatorActivity", () => { expect(deriveCoordinatorActivity(items)).toBe(expected); }); }); - -describe("milestoneStripWeights", () => { - it("sizes milestones by time spent, the active one by time so far, and the rest by the average", () => { - const now = DateTime.toEpochMillis(at(20)); - const weights = milestoneStripWeights( - [ - milestone("m1", "s1", "done", 0, { completedAt: at(4) }), - milestone("m2", "s1", "done", 4, { completedAt: at(12) }), - milestone("m3", "s1", "active", 12), - milestone("m4", "s1", "planned", null), - ], - now, - ).map((weight) => weight / 60_000); - expect(weights).toEqual([4, 8, 8, 20 / 3]); - }); - - it("keeps a sliver for a milestone that took no time", () => { - const weights = milestoneStripWeights( - [ - milestone("m1", "s1", "done", 0, { completedAt: at(0) }), - milestone("m2", "s1", "done", 0, { completedAt: at(30) }), - ], - 0, - ); - expect(weights[0]).toBeGreaterThan(0); - expect(weights[0]! / weights[1]!).toBeGreaterThan(0.09); - }); -}); diff --git a/packages/client-runtime/src/state/threadMilestoneGraph.ts b/packages/client-runtime/src/state/threadMilestoneGraph.ts index ce28c2591b691..ac40ab70136a1 100644 --- a/packages/client-runtime/src/state/threadMilestoneGraph.ts +++ b/packages/client-runtime/src/state/threadMilestoneGraph.ts @@ -15,23 +15,18 @@ type Projection = Pick; } -export interface MilestoneGraphNode { +interface MilestoneGraphNode { readonly milestone: OrchestrationV2Milestone; + /** Agents stamped with this milestone, then unstamped ones from turns sent while it ran. */ readonly agents: ReadonlyArray; - /** Turns the user started while this milestone was active, in order. */ - readonly turns: ReadonlyArray; -} - -export interface MilestoneGraphEarlierSet { - readonly setId: OrchestrationV2Milestone["setId"]; - readonly milestones: ReadonlyArray; - readonly agentCount: number; + /** False for milestones of an earlier plan the coordinator replaced. */ + readonly current: boolean; } export type MilestoneCoordinatorStatus = "working" | "waiting" | "idle" | "failed" | "interrupted"; @@ -52,15 +47,13 @@ export type ThreadMilestoneGraph = readonly mode: "milestones"; /** The first turn, with the agents that ran before any plan. */ readonly root: MilestoneGraphTurn | null; - readonly earlierSets: ReadonlyArray; + /** Every set's milestones in order: earlier plans first, then the current one. */ readonly milestones: ReadonlyArray; readonly coordinator: MilestoneCoordinator; readonly summary: { /** 1-based position of the active milestone, or how many are done. */ readonly position: number; readonly total: number; - readonly changes: number; - readonly startedAt: DateTime.Utc | null; }; }; @@ -100,9 +93,9 @@ function milestoneActiveAt( } /** - * The coordinator's spine: milestones with the agents and user turns that belong to each, or one - * node per user turn on a thread that never planned. Subagents keep the milestone they were - * stamped with; one whose milestone is gone (rolled back) falls to its turn. + * Milestones with the agents that belong to each, or one node per user turn on a thread that + * never planned. Subagents keep the milestone they were stamped with; one whose milestone is gone + * (rolled back) falls to its turn, and a later turn's agents join the milestone it was sent during. */ export function deriveThreadMilestoneGraph(projection: Projection): ThreadMilestoneGraph { const rolledBack = new Set( @@ -125,14 +118,13 @@ export function deriveThreadMilestoneGraph(projection: Projection): ThreadMilest const milestoneIds = new Set(projection.milestones.map((milestone) => milestone.id)); const byMilestone = new Map>(); const byRun = new Map>(); + const push = (map: Map>, key: string, agents: ReadonlyArray) => + map.set(key, [...(map.get(key) ?? []), ...agents]); for (const subagent of subagents) { if (subagent.milestoneId !== undefined && milestoneIds.has(subagent.milestoneId)) { - byMilestone.set(subagent.milestoneId, [ - ...(byMilestone.get(subagent.milestoneId) ?? []), - subagent, - ]); + push(byMilestone, subagent.milestoneId, [subagent]); } else if (subagent.runId !== null) { - byRun.set(subagent.runId, [...(byRun.get(subagent.runId) ?? []), subagent]); + push(byRun, subagent.runId, [subagent]); } } const turnOf = (run: Run): MilestoneGraphTurn => ({ run, agents: byRun.get(run.id) ?? [] }); @@ -142,45 +134,28 @@ export function deriveThreadMilestoneGraph(projection: Projection): ThreadMilest } const currentSetId = projection.milestones.at(-1)!.setId; - const current = projection.milestones.filter((milestone) => milestone.setId === currentSetId); const [rootRun, ...laterRuns] = runs; - const turnsByMilestone = new Map>(); const rootAgents = rootRun === undefined ? [] : [...turnOf(rootRun).agents]; for (const run of laterRuns) { const owner = milestoneActiveAt(projection.milestones, run.requestedAt); - if (owner === undefined) { - rootAgents.push(...turnOf(run).agents); - } else if (owner.setId === currentSetId) { - turnsByMilestone.set(owner.id, [...(turnsByMilestone.get(owner.id) ?? []), turnOf(run)]); - } - } - - const earlierSets: Array = []; - for (const milestone of projection.milestones) { - if (milestone.setId === currentSetId) continue; - const last = earlierSets.at(-1); - const agentCount = byMilestone.get(milestone.id)?.length ?? 0; - if (last?.setId === milestone.setId) { - earlierSets[earlierSets.length - 1] = { - ...last, - milestones: [...last.milestones, milestone], - agentCount: last.agentCount + agentCount, - }; - } else { - earlierSets.push({ setId: milestone.setId, milestones: [milestone], agentCount }); - } + if (owner === undefined) rootAgents.push(...turnOf(run).agents); + else push(byMilestone, owner.id, turnOf(run).agents); } - const counted = current.filter((milestone) => milestone.status !== "dropped"); + const counted = projection.milestones.filter( + (milestone) => milestone.setId === currentSetId && milestone.status !== "dropped", + ); const activeIndex = counted.findIndex((milestone) => milestone.status === "active"); return { mode: "milestones", root: rootRun === undefined ? null : { run: rootRun, agents: rootAgents }, - earlierSets, - milestones: current.map((milestone) => ({ + milestones: projection.milestones.map((milestone) => ({ milestone, - agents: byMilestone.get(milestone.id) ?? [], - turns: turnsByMilestone.get(milestone.id) ?? [], + agents: copySorted( + byMilestone.get(milestone.id) ?? [], + (left, right) => startKey(left) - startKey(right) || left.id.localeCompare(right.id), + ), + current: milestone.setId === currentSetId, })), coordinator, summary: { @@ -189,37 +164,10 @@ export function deriveThreadMilestoneGraph(projection: Projection): ThreadMilest ? counted.filter((milestone) => milestone.status === "done").length : activeIndex + 1, total: counted.length, - changes: current.filter((milestone) => milestone.revision !== undefined).length, - startedAt: current[0]?.startedAt ?? rootRun?.startedAt ?? null, }, }; } -/** - * Relative widths for the plan strip: the time each milestone took, the active one's time so far, - * and the average for those not started. A floor keeps an instant milestone visible and clickable. - */ -export function milestoneStripWeights( - milestones: ReadonlyArray>, - nowMs: number, -): ReadonlyArray { - const spans = milestones.map(({ startedAt, completedAt }) => - startedAt === null - ? null - : Math.max( - 0, - (completedAt === null ? nowMs : DateTime.toEpochMillis(completedAt)) - - DateTime.toEpochMillis(startedAt), - ), - ); - const known = spans.filter((span) => span !== null); - const typical = - known.length === 0 ? 1 : known.reduce((sum, span) => sum + span, 0) / known.length || 1; - const raw = spans.map((span) => span ?? typical); - const floor = raw.reduce((sum, span) => sum + span, 0) * 0.1; - return raw.map((span) => Math.max(span, floor)); -} - const shortenPaths = (text: string) => text.replace(/(?:~|\.{0,2})?(?:\/[^\s/]+)+\/([^\s/]+)/gu, "$1"); const firstLine = (text: string) => text.trim().split("\n")[0]?.trim() ?? ""; diff --git a/packages/client-runtime/src/state/threadMilestoneTrace.test.ts b/packages/client-runtime/src/state/threadMilestoneTrace.test.ts new file mode 100644 index 0000000000000..6ce368d32a883 --- /dev/null +++ b/packages/client-runtime/src/state/threadMilestoneTrace.test.ts @@ -0,0 +1,382 @@ +import { describe, expect, it } from "vite-plus/test"; +import { + type OrchestrationV2Milestone, + type OrchestrationV2Subagent, + MessageId, + NodeId, + ProviderDriverKind, + ProviderInstanceId, + RunId, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; + +import { + deriveThreadTrace, + threadTraceDomain, + traceFraction, + tracePosition, + traceRowDomain, + traceTicks, +} from "./threadMilestoneTrace.ts"; + +const T0 = Date.parse("2026-11-10T10:00:00.000Z"); +const MIN = 60_000; +const at = (minute: number) => DateTime.makeUnsafe(T0 + minute * MIN); + +type Span = readonly [number, number | null]; + +const run = ( + ordinal: number, + [start, end]: Span, + status = end === null ? "running" : "completed", +) => + ({ + id: RunId.make(`run-${ordinal}`), + ordinal, + status, + userMessageId: MessageId.make(`msg-${ordinal}`), + providerInstanceId: ProviderInstanceId.make("claude"), + requestedAt: at(start), + startedAt: at(start), + completedAt: end === null ? null : at(end), + }) as never; + +function milestone( + id: string, + status: OrchestrationV2Milestone["status"], + span: Span | null, + extra: Partial = {}, +): OrchestrationV2Milestone { + return { + id, + setId: "s1", + title: `Milestone ${id}`, + status, + startedAt: span === null ? null : at(span[0]), + completedAt: span === null || span[1] === null ? null : at(span[1]), + anchors: {}, + ...extra, + } as OrchestrationV2Milestone; +} + +function agent( + id: string, + status: OrchestrationV2Subagent["status"], + span: Span | null, + extra: Partial = {}, +): OrchestrationV2Subagent { + return { + id: NodeId.make(id), + threadId: ThreadId.make("thread-1"), + runId: RunId.make("run-1"), + parentNodeId: NodeId.make("node-1"), + origin: "app_owned", + createdBy: "agent", + driver: ProviderDriverKind.make("codex"), + providerInstanceId: ProviderInstanceId.make("codex"), + providerThreadId: null, + childThreadId: ThreadId.make(`child-${id}`), + nativeTaskRef: null, + prompt: id, + title: id, + model: null, + status, + result: null, + startedAt: span === null ? null : at(span[0]), + completedAt: span === null || span[1] === null ? null : at(span[1]), + updatedAt: at(span?.[1] ?? span?.[0] ?? 0), + ...extra, + } as OrchestrationV2Subagent; +} + +function trace(input: { + readonly runs: ReadonlyArray; + readonly milestones?: ReadonlyArray; + readonly subagents?: ReadonlyArray; + readonly messages?: ReadonlyArray<{ readonly id: string; readonly text: string }>; + readonly turnItems?: ReadonlyArray; + readonly needsYou?: ReadonlyArray; + readonly now: number; +}) { + const result = deriveThreadTrace({ + projection: { + runs: input.runs, + milestones: input.milestones ?? [], + subagents: input.subagents ?? [], + messages: input.messages ?? [], + } as never, + turnItems: (input.turnItems ?? []) as never, + boards: new Map(), + needsYou: new Set(input.needsYou ?? []), + nowMs: T0 + input.now * MIN, + }); + if (result === null) throw new Error("expected a trace"); + return result; +} + +const minutes = (value: number) => Math.round((value / MIN) * 1000) / 1000; + +describe("threadTraceDomain", () => { + it.each([ + { + name: "collapses an 80 minute idle stretch and labels ticks after it with real time", + runs: [run(1, [0, 10]), run(2, [90, 100])], + gaps: [[10, 90]], + // 100 minutes, 80 idle, plus 3% headroom on a stopped thread. + length: 23, + ticks: [5, 95, 100], + }, + { + name: "keeps a 9 minute pause on the axis", + runs: [run(1, [0, 10]), run(2, [19, 30])], + gaps: [], + length: 30.9, + ticks: [10, 20, 30], + }, + ])("$name", ({ runs, gaps, length, ticks }) => { + const domain = threadTraceDomain(trace({ runs, now: 500 })); + expect(domain.gaps.map((gap) => [minutes(gap.startMs - T0), minutes(gap.endMs - T0)])).toEqual( + gaps, + ); + expect(minutes(domain.length)).toBe(length); + expect(traceTicks(domain).map(({ elapsedMs }) => minutes(elapsedMs))).toEqual(ticks); + for (const [start, end] of gaps) { + expect(tracePosition(domain, T0 + start! * MIN)).toBe(tracePosition(domain, T0 + end! * MIN)); + } + }); + + it("draws a milestone across a collapsed gap from its real start to its real end", () => { + const result = trace({ + runs: [run(1, [0, 10]), run(2, [90, 100])], + milestones: [milestone("m1", "done", [5, 95])], + now: 100, + }); + const domain = threadTraceDomain(result); + const { span } = result.rows[0]!; + const width = tracePosition(domain, span!.endMs!) - tracePosition(domain, span!.startMs); + expect(minutes(width * domain.length)).toBe(10); + }); + + it.each([ + { + name: "a live thread gets 15% headroom past now", + runs: [run(1, [0, null])], + now: 40, + expected: { nowMin: 40, horizonMin: 46 }, + }, + { + name: "a short live thread gets at least a minute", + runs: [run(1, [0, null])], + now: 2, + expected: { nowMin: 2, horizonMin: 3 }, + }, + { + name: "a clock behind the data counts from the newest record", + runs: [run(1, [0, null]), run(2, [30, 50], "completed")], + now: 20, + expected: { nowMin: 50, horizonMin: 57.5 }, + }, + { + name: "a thread stopped a day ago ends at its last record and never recomputes", + runs: [run(1, [0, 20], "interrupted")], + now: 24 * 60, + expected: { nowMin: 20, horizonMin: Number.POSITIVE_INFINITY }, + }, + ])("$name", ({ runs, now, expected }) => { + const result = trace({ runs, now }); + const domain = threadTraceDomain(result); + expect({ + nowMin: minutes(result.nowMs - T0), + horizonMin: Number.isFinite(domain.horizonMs) + ? minutes(domain.horizonMs - T0) + : domain.horizonMs, + }).toEqual(expected); + }); + + it("rescales a zoomed milestone to its own span, with labels from its start", () => { + const result = trace({ + runs: [run(1, [0, 60])], + milestones: [milestone("m1", "done", [0, 10]), milestone("m2", "done", [10, 60])], + now: 60, + }); + // A finished milestone ends at its own end, not at the thread's now. + expect(minutes(traceRowDomain(result, result.rows[0]!)!.endMs - T0)).toBe(10.6); + const domain = traceRowDomain(result, result.rows[1]!)!; + expect(minutes(domain.originMs - T0)).toBe(10); + expect(tracePosition(domain, T0 + 10 * MIN)).toBeCloseTo(0.04 / 1.1); + expect(traceTicks(domain).map(({ elapsedMs }) => minutes(elapsedMs))).toEqual([ + 10, 20, 30, 40, 50, + ]); + }); +}); + +describe("deriveThreadTrace", () => { + it.each([ + { + name: "the mean of done milestones", + milestones: [ + milestone("m1", "done", [0, 4]), + milestone("m2", "done", [4, 12]), + milestone("m3", "active", [12, null]), + milestone("m4", "planned", null), + milestone("m5", "planned", null), + ], + estimates: [null, null, null, [0, 6], [6, 6]], + }, + { + name: "a quarter of the elapsed time when nothing is done yet", + milestones: [milestone("m1", "active", [0, null]), milestone("m2", "planned", null)], + estimates: [null, [0, 10]], + }, + ])("estimates planned milestones from $name", ({ milestones, estimates }) => { + const result = trace({ runs: [run(1, [0, null])], milestones, now: 40 }); + expect( + result.rows.map(({ estimate }) => + estimate === null ? null : [minutes(estimate.offsetMs), minutes(estimate.durationMs)], + ), + ).toEqual(estimates); + const domain = threadTraceDomain(result); + expect(minutes(domain.length)).toBe( + minutes(domain.endMs - domain.startMs) + + estimates.reduce((sum, value) => sum + (value?.[1] ?? 0), 0), + ); + expect(traceFraction(domain, domain.length)).toBe(1); + }); + + it.each([ + { + name: "named groups in order of first start", + agents: [ + agent("api", "completed", [1, 5], { group: "Backend" }), + agent("page", "running", [2, null], { group: "UI" }), + agent("db", "failed", [3, 4], { group: "Backend" }), + agent("pdf", "waiting", [4, null], { group: "UI" }), + agent("e2e", "pending", null, { group: "Tests", updatedAt: at(9) }), + ], + groups: [ + ["Backend", ["api", "db"], { done: 1, failed: 1 }], + ["UI", ["page", "pdf"], { running: 1, needsYou: 1 }], + ["Tests", ["e2e"], { queued: 1 }], + ], + // db ends as pdf starts, so at most three ran at once. + peak: 3, + }, + { + name: "ungrouped agents alone", + agents: [agent("a", "completed", [1, 3]), agent("b", "completed", [4, 6])], + groups: [[null, ["a", "b"], { done: 2 }]], + peak: 1, + }, + { + name: "ungrouped agents beside named ones", + agents: [ + agent("solo", "completed", [1, 3]), + agent("ui", "cancelled", [2, 5], { group: "UI" }), + ], + groups: [ + [null, ["solo"], { done: 1 }], + ["UI", ["ui"], { stopped: 1 }], + ], + peak: 2, + }, + ])("groups agents: $name", ({ agents, groups, peak }) => { + const result = trace({ + runs: [run(1, [0, null])], + milestones: [milestone("m1", "active", [0, null])], + subagents: agents.map( + (entry) => ({ ...entry, milestoneId: "m1" }) as OrchestrationV2Subagent, + ), + needsYou: ["child-pdf"], + now: 10, + }); + const [row] = result.rows; + const zero = { done: 0, running: 0, needsYou: 0, failed: 0, queued: 0, stopped: 0 }; + expect( + row!.groups.map((group) => [ + group.name, + group.agents.map(({ agent }) => agent.id), + group.counts, + ]), + ).toEqual(groups.map(([name, ids, counts]) => [name, ids, { ...zero, ...(counts as object) }])); + expect(row!.peakParallel).toBe(peak); + expect(row!.agentCount).toBe(agents.length); + }); + + it("points at the first failed agent and lists agents waiting on you", () => { + const result = trace({ + runs: [run(1, [0, null])], + milestones: [milestone("m1", "done", [0, 5]), milestone("m2", "active", [5, null])], + subagents: [ + agent("ok", "completed", [1, 2], { milestoneId: "m1" }), + agent("broke", "failed", [6, 7], { milestoneId: "m2", group: "Backend" }), + agent("asks", "waiting", [6, null], { milestoneId: "m2", group: "UI" }), + ], + needsYou: ["child-asks"], + now: 10, + }); + expect(result.firstFailed).toEqual({ rowId: "m2", agentId: "broke" }); + expect(result.needsYou.map(({ rowId, group, agent }) => [rowId, group, agent.id])).toEqual([ + ["m2", "UI", "asks"], + ]); + expect(result.counts).toMatchObject({ done: 1, failed: 1, needsYou: 1 }); + expect([result.position, result.total]).toEqual([2, 2]); + }); + + it("lays out one row per turn on a thread that never planned", () => { + const result = trace({ + runs: [run(1, [0, 6]), run(2, [9, null]), run(3, [12, 12], "failed")], + messages: [{ id: "msg-1", text: "Fix the flaky checkout test\nIt fails one in five runs" }], + subagents: [agent("retry", "completed", [1, 3])], + now: 12.5, + }); + expect(result.kind).toBe("turns"); + expect(result.title).toBe("Fix the flaky checkout test"); + expect(result.rows.map(({ title, status, agentCount }) => [title, status, agentCount])).toEqual( + [ + ["Fix the flaky checkout test", "done", 1], + ["Turn 2", "active", 0], + ["Turn 3", "failed", 0], + ], + ); + expect([result.position, result.total]).toEqual([2, 3]); + }); + + it("keeps earlier plans and dropped milestones as rows", () => { + const dropItem = TurnItemId.make("drop-m4"); + const result = trace({ + runs: [run(1, [0, null])], + milestones: [ + milestone("m1", "done", [0, 3], { setId: "s1" } as never), + milestone("m2", "active", [3, null], { setId: "s1" } as never), + milestone("m3", "active", [6, null], { setId: "s2" } as never), + milestone("m4", "dropped", null, { + setId: "s2", + anchors: { dropped: { runId: RunId.make("run-1"), itemId: dropItem } }, + } as never), + milestone("m5", "planned", null, { setId: "s2" } as never), + ], + turnItems: [{ id: dropItem, startedAt: at(8), completedAt: at(8) }], + now: 10, + }); + expect( + result.rows.map(({ id, status, current, span }) => [ + id, + status, + current, + span === null + ? null + : [minutes(span.startMs - T0), span.endMs === null ? null : minutes(span.endMs - T0)], + ]), + ).toEqual([ + ["m1", "done", false, [0, 3]], + // The replaced plan's unfinished milestone shows as dropped where it stopped. + ["m2", "dropped", false, [3, 3]], + ["m3", "active", true, [6, null]], + ["m4", "dropped", true, [8, 8]], + ["m5", "planned", true, null], + ]); + expect([result.position, result.total]).toEqual([1, 2]); + }); +}); diff --git a/packages/client-runtime/src/state/threadMilestoneTrace.ts b/packages/client-runtime/src/state/threadMilestoneTrace.ts new file mode 100644 index 0000000000000..90fabe16e7929 --- /dev/null +++ b/packages/client-runtime/src/state/threadMilestoneTrace.ts @@ -0,0 +1,629 @@ +import * as DateTime from "effect/DateTime"; +import type { + OrchestrationV2Milestone, + OrchestrationV2Subagent, + OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; +import { copySorted } from "@t3tools/shared/Array"; + +import type { ThreadStructureTurnItem } from "./models.ts"; +import { isActiveSubagentStatus } from "./subagentRuntime.ts"; +import { MILESTONE_BOARD_ROOT, type MilestoneBoardItem } from "./threadMilestoneBoard.ts"; +import { + deriveThreadMilestoneGraph, + type MilestoneCoordinator, + type MilestoneGraphTurn, +} from "./threadMilestoneGraph.ts"; +import { resolveActiveThreadRun } from "./threadWorkflows.ts"; + +type Projection = Pick< + OrchestrationV2ThreadProjection, + "runs" | "subagents" | "milestones" | "messages" +>; +type Run = Projection["runs"][number]; +type Subagent = OrchestrationV2Subagent; + +/** Stretches where nothing ran for longer than this collapse to a break on the axis. */ +const TRACE_IDLE_GAP_MS = 10 * 60_000; +const MIN_ESTIMATE_MS = 2 * 60_000; +const MIN_HEADROOM_MS = 60_000; + +export type TraceAgentStatus = "done" | "running" | "needs-you" | "failed" | "queued" | "stopped"; +export type TraceRowStatus = "done" | "active" | "planned" | "dropped" | "failed" | "stopped"; + +export interface TraceCounts { + readonly done: number; + readonly running: number; + readonly needsYou: number; + readonly failed: number; + readonly queued: number; + readonly stopped: number; +} + +/** Times are epoch ms. `endMs` is null while the span still runs and ends at now. */ +export interface TraceSpan { + readonly startMs: number; + readonly endMs: number | null; +} + +export interface TraceAgent { + readonly agent: Subagent; + readonly status: TraceAgentStatus; + /** Null for a queued agent that has not started. */ + readonly span: TraceSpan | null; +} + +export interface TraceGroup { + /** Null for agents the coordinator did not group. */ + readonly name: string | null; + readonly agents: ReadonlyArray; + readonly counts: TraceCounts; + readonly span: TraceSpan | null; +} + +interface TracePin { + readonly id: string; + readonly kind: "post" | "visual"; + readonly title: string; + readonly atMs: number; +} + +export interface TraceRow { + /** The milestone id, the run id of a turn, or `root` for agents that ran before the plan. */ + readonly id: string; + readonly title: string; + readonly status: TraceRowStatus; + readonly milestone: OrchestrationV2Milestone | null; + /** False for a milestone of an earlier plan. */ + readonly current: boolean; + /** Null for a row that has not started, or a dropped one that never ran. */ + readonly span: TraceSpan | null; + /** Where a planned row would run, measured from now, by the average time a row took. */ + readonly estimate: { readonly offsetMs: number; readonly durationMs: number } | null; + readonly groups: ReadonlyArray; + readonly agentCount: number; + /** The most agents that ran at the same time. */ + readonly peakParallel: number; + readonly counts: TraceCounts; + readonly pins: ReadonlyArray; +} + +export interface ThreadTrace { + readonly kind: "milestones" | "turns"; + /** The first line of the thread's first request. */ + readonly title: string | null; + readonly rows: ReadonlyArray; + readonly coordinator: MilestoneCoordinator & { + readonly runs: ReadonlyArray; + /** The active run, else the latest one. */ + readonly run: Run | null; + }; + /** Whether the coordinator or an agent still runs; only then does now move. */ + readonly live: boolean; + /** Wall-clock now while live, else the last recorded moment. */ + readonly nowMs: number; + readonly startMs: number; + /** 1-based position of the active row, or how many are done, among counted rows. */ + readonly position: number; + readonly total: number; + readonly counts: TraceCounts; + readonly agentCount: number; + readonly firstFailed: { readonly rowId: string; readonly agentId: string } | null; + readonly needsYou: ReadonlyArray<{ + readonly rowId: string; + readonly group: string | null; + readonly agent: Subagent; + }>; + /** Merged spans where the coordinator or an agent ran, for idle gaps. */ + readonly activity: ReadonlyArray<{ readonly startMs: number; readonly endMs: number }>; +} + +export interface TraceDomain { + readonly startMs: number; + /** The real moment at the right edge, before planned estimates. */ + readonly endMs: number; + /** A live chart is recomputed once now passes this; Infinity when nothing runs. */ + readonly horizonMs: number; + /** Collapsed length of the axis in ms, planned estimates included. */ + readonly length: number; + /** The real time at the left edge that tick labels count from. */ + readonly originMs: number; + readonly gaps: ReadonlyArray<{ readonly startMs: number; readonly endMs: number }>; +} + +const ms = (value: DateTime.Utc) => DateTime.toEpochMillis(value); +const msOrNull = (value: DateTime.Utc | null) => (value === null ? null : ms(value)); +const firstLine = (text: string) => text.trim().split("\n")[0]?.trim() ?? ""; + +const zeroCounts = (): { -readonly [K in keyof TraceCounts]: number } => ({ + done: 0, + running: 0, + needsYou: 0, + failed: 0, + queued: 0, + stopped: 0, +}); + +const COUNT_KEY: Record = { + done: "done", + running: "running", + "needs-you": "needsYou", + failed: "failed", + queued: "queued", + stopped: "stopped", +}; + +function countAgents(agents: ReadonlyArray): TraceCounts { + const counts = zeroCounts(); + for (const { status } of agents) counts[COUNT_KEY[status]] += 1; + return counts; +} + +function agentStatus(agent: Subagent, needsYou: ReadonlySet): TraceAgentStatus { + switch (agent.status) { + case "completed": + case "idle": + return "done"; + case "running": + case "waiting": + return agent.childThreadId !== null && needsYou.has(agent.childThreadId) + ? "needs-you" + : "running"; + case "pending": + return agent.startedAt === null ? "queued" : "running"; + case "failed": + return "failed"; + case "cancelled": + case "interrupted": + return "stopped"; + } +} + +function spanEnvelope(spans: ReadonlyArray): TraceSpan | null { + if (spans.length === 0) return null; + const startMs = Math.min(...spans.map((span) => span.startMs)); + const ends = spans.map((span) => span.endMs); + return { startMs, endMs: ends.includes(null) ? null : Math.max(...(ends as Array)) }; +} + +function peakParallel(spans: ReadonlyArray, nowMs: number): number { + const edges = spans.flatMap(({ startMs, endMs }) => [ + [startMs, 1] as const, + [Math.max(startMs, endMs ?? nowMs), -1] as const, + ]); + edges.sort((left, right) => left[0] - right[0] || left[1] - right[1]); + let current = 0; + let peak = 0; + for (const [, step] of edges) { + current += step; + peak = Math.max(peak, current); + } + return peak; +} + +function mergeSpans( + spans: ReadonlyArray<{ readonly startMs: number; readonly endMs: number }>, +): ReadonlyArray<{ readonly startMs: number; readonly endMs: number }> { + const sorted = copySorted(spans, (left, right) => left.startMs - right.startMs); + const merged: Array<{ startMs: number; endMs: number }> = []; + for (const span of sorted) { + const last = merged.at(-1); + if (last !== undefined && span.startMs <= last.endMs) + last.endMs = Math.max(last.endMs, span.endMs); + else merged.push({ ...span }); + } + return merged; +} + +function runTitle(projection: Projection, run: Run): string | null { + const message = projection.messages.find(({ id }) => id === run.userMessageId); + const line = message === undefined ? "" : firstLine(message.text); + return line ? line : null; +} + +/** + * The thread on one time axis: a row per milestone (or per turn on a thread that never planned) + * with its agents grouped as the coordinator grouped them, the coordinator's runs, and what + * waits on you. `needsYou` holds the child threads that wait on an approval or answer. + */ +export function deriveThreadTrace(input: { + readonly projection: Projection; + readonly turnItems: ReadonlyArray; + readonly boards: ReadonlyMap>; + readonly needsYou: ReadonlySet; + readonly nowMs: number; +}): ThreadTrace | null { + const { projection } = input; + const graph = deriveThreadMilestoneGraph(projection); + if (graph.mode === "empty") return null; + + const activeRun = resolveActiveThreadRun(projection); + const runs = copySorted( + projection.runs.filter((run) => run.status !== "rolled_back"), + (left, right) => left.ordinal - right.ordinal, + ); + const live = + activeRun !== null || + projection.subagents.some((agent) => isActiveSubagentStatus(agent.status)); + const recorded = [ + ...runs.flatMap((run) => [ + ms(run.requestedAt), + msOrNull(run.startedAt), + msOrNull(run.completedAt), + ]), + ...projection.subagents.flatMap((agent) => [ + msOrNull(agent.startedAt), + msOrNull(agent.completedAt), + ]), + ...projection.milestones.flatMap((milestone) => [ + msOrNull(milestone.startedAt), + msOrNull(milestone.completedAt), + ]), + ].filter((value) => value !== null); + const newest = recorded.length === 0 ? input.nowMs : Math.max(...recorded); + // A stopped thread ends at its last recorded moment, however long ago that was. + const nowMs = live ? Math.max(input.nowMs, newest) : newest; + + const itemTimes = new Map(); + for (const item of input.turnItems) { + const at = item.completedAt ?? item.startedAt; + if (at !== null) itemTimes.set(item.id, ms(at)); + } + + const traceAgent = (agent: Subagent): TraceAgent => { + const status = agentStatus(agent, input.needsYou); + const startMs = msOrNull(agent.startedAt); + if (status === "queued" || startMs === null) return { agent, status, span: null }; + const live = status === "running" || status === "needs-you"; + return { + agent, + status, + span: { + startMs, + endMs: live + ? null + : (msOrNull(agent.completedAt) ?? Math.max(startMs, ms(agent.updatedAt))), + }, + }; + }; + + const pinsOf = (boardKey: string): ReadonlyArray => + (input.boards.get(boardKey) ?? []).flatMap((item) => { + const atMs = itemTimes.get(item.id); + if (atMs === undefined || item.kind === "comment") return []; + const title = item.kind === "visual" ? item.title : firstLine(item.text ?? "") || "Post"; + return [{ id: item.id, kind: item.kind, title, atMs }]; + }); + + const draft = (fields: { + readonly id: string; + readonly title: string; + readonly status: TraceRowStatus; + readonly milestone: OrchestrationV2Milestone | null; + readonly current: boolean; + readonly span: TraceSpan | null; + readonly agents: ReadonlyArray; + readonly boardKey: string | null; + }): TraceRow => { + const agents = fields.agents.map(traceAgent); + const groups = new Map>(); + for (const agent of agents) { + const key = agent.agent.group ?? null; + groups.set(key, [...(groups.get(key) ?? []), agent]); + } + const spans = agents.flatMap(({ span }) => (span === null ? [] : [span])); + return { + id: fields.id, + title: fields.title, + status: fields.status, + milestone: fields.milestone, + current: fields.current, + span: fields.span, + estimate: null, + groups: [...groups].map(([name, members]) => ({ + name, + agents: members, + counts: countAgents(members), + span: spanEnvelope(members.flatMap(({ span }) => (span === null ? [] : [span]))), + })), + agentCount: agents.length, + peakParallel: peakParallel(spans, nowMs), + counts: countAgents(agents), + pins: fields.boardKey === null ? [] : pinsOf(fields.boardKey), + }; + }; + + const liveEnd = (completedAt: DateTime.Utc | null, running: boolean, fallback: number) => + completedAt !== null ? ms(completedAt) : running ? (live ? null : nowMs) : fallback; + + let rows: Array; + if (graph.mode === "turns") { + rows = graph.turns.map(({ run, agents }: MilestoneGraphTurn, index) => { + const started = msOrNull(run.startedAt); + const status: TraceRowStatus = + run.status === "completed" + ? "done" + : run.status === "failed" + ? "failed" + : run.status === "interrupted" || run.status === "cancelled" + ? "stopped" + : started === null + ? "planned" + : "active"; + return draft({ + id: run.id, + title: runTitle(projection, run) ?? `Turn ${index + 1}`, + status, + milestone: null, + current: true, + span: + started === null + ? null + : { startMs: started, endMs: liveEnd(run.completedAt, status === "active", started) }, + agents, + boardKey: null, + }); + }); + } else { + rows = []; + if (graph.root !== null && graph.root.agents.length > 0) { + const agents = graph.root.agents.map(traceAgent); + const span = spanEnvelope(agents.flatMap(({ span }) => (span === null ? [] : [span]))); + rows.push( + draft({ + id: MILESTONE_BOARD_ROOT, + title: "Before the plan", + status: agents.some(({ span }) => span !== null && span.endMs === null) + ? "active" + : "done", + milestone: null, + current: true, + span, + agents: graph.root.agents, + boardKey: MILESTONE_BOARD_ROOT, + }), + ); + } + for (const { milestone, agents, current } of graph.milestones) { + const started = msOrNull(milestone.startedAt); + // A milestone an earlier plan never finished was replaced along with that plan. + const status: TraceRowStatus = + !current && milestone.status !== "done" ? "dropped" : milestone.status; + const droppedAt = + milestone.anchors.dropped === undefined + ? undefined + : itemTimes.get(milestone.anchors.dropped.itemId); + const span: TraceSpan | null = + started !== null + ? { + startMs: started, + endMs: liveEnd(milestone.completedAt, status === "active", droppedAt ?? started), + } + : status === "dropped" && droppedAt !== undefined + ? { startMs: droppedAt, endMs: droppedAt } + : null; + rows.push( + draft({ + id: milestone.id, + title: milestone.title, + status, + milestone, + current, + span: status === "planned" ? null : span, + agents, + boardKey: milestone.id, + }), + ); + } + } + + const coordinatorRuns = runs.flatMap((run): Array => { + const started = msOrNull(run.startedAt); + if (started === null) return []; + return [{ startMs: started, endMs: liveEnd(run.completedAt, run === activeRun, started) }]; + }); + const startCandidates = [ + ...coordinatorRuns.map(({ startMs }) => startMs), + ...rows.flatMap(({ span }) => (span === null ? [] : [span.startMs])), + ]; + const startMs = startCandidates.length === 0 ? nowMs : Math.min(...startCandidates); + + const finished = rows.flatMap(({ status, span }) => + status === "done" && span !== null && span.endMs !== null ? [span.endMs - span.startMs] : [], + ); + const estimateMs = + finished.length > 0 + ? Math.max(1000, finished.reduce((sum, value) => sum + value, 0) / finished.length) + : Math.max(MIN_ESTIMATE_MS, (nowMs - startMs) / 4); + let offsetMs = 0; + rows = rows.map((row) => { + if (row.status !== "planned") return row; + const estimate = { offsetMs, durationMs: estimateMs }; + offsetMs += estimateMs; + return { ...row, estimate }; + }); + + const activity = mergeSpans( + [ + ...coordinatorRuns, + ...rows.flatMap(({ groups }) => + groups.flatMap(({ agents }) => agents.flatMap(({ span }) => (span === null ? [] : [span]))), + ), + ].map((span) => ({ startMs: span.startMs, endMs: span.endMs ?? nowMs })), + ); + + const counted = rows.filter( + ({ current, status, id }) => current && status !== "dropped" && id !== MILESTONE_BOARD_ROOT, + ); + const activeIndex = counted.findIndex(({ status }) => status === "active"); + const allAgents = rows.flatMap(({ groups }) => groups.flatMap(({ agents }) => agents)); + const failedRow = rows.find(({ counts }) => counts.failed > 0); + return { + kind: graph.mode, + title: runs[0] === undefined ? null : runTitle(projection, runs[0]), + rows, + coordinator: { + ...graph.coordinator, + runs: coordinatorRuns, + run: activeRun ?? runs.at(-1) ?? null, + }, + live, + nowMs, + startMs, + position: + graph.mode === "milestones" + ? graph.summary.position + : activeIndex === -1 + ? counted.filter(({ status }) => status !== "planned").length + : activeIndex + 1, + total: graph.mode === "milestones" ? graph.summary.total : counted.length, + counts: countAgents(allAgents), + agentCount: allAgents.length, + firstFailed: + failedRow === undefined + ? null + : { + rowId: failedRow.id, + agentId: failedRow.groups + .flatMap(({ agents }) => agents) + .find(({ status }) => status === "failed")!.agent.id, + }, + needsYou: rows.flatMap((row) => + row.groups.flatMap((group) => + group.agents + .filter(({ status }) => status === "needs-you") + .map(({ agent }) => ({ rowId: row.id, group: group.name, agent })), + ), + ), + activity, + }; +} + +function buildDomain(input: { + readonly trace: ThreadTrace; + readonly startMs: number; + readonly contentEndMs: number; + readonly headroomMs: number; + readonly plannedMs: number; + readonly originMs: number; +}): TraceDomain { + const { trace, startMs } = input; + const endMs = Math.max(input.contentEndMs, startMs) + input.headroomMs; + const gaps: Array<{ startMs: number; endMs: number }> = []; + for (const [index, span] of trace.activity.entries()) { + const next = trace.activity[index + 1]; + if (next === undefined) break; + const gapStart = Math.max(span.endMs, startMs); + const gapEnd = Math.min(next.startMs, endMs); + if (gapEnd - gapStart > TRACE_IDLE_GAP_MS) gaps.push({ startMs: gapStart, endMs: gapEnd }); + } + const removed = gaps.reduce((sum, gap) => sum + gap.endMs - gap.startMs, 0); + return { + startMs, + endMs, + horizonMs: trace.live ? endMs : Number.POSITIVE_INFINITY, + length: Math.max(1000, endMs - startMs - removed + input.plannedMs), + originMs: input.originMs, + gaps, + }; +} + +/** The whole thread, with headroom past now so a live chart is recomputed only now and then. */ +export function threadTraceDomain(trace: ThreadTrace): TraceDomain { + const span = trace.nowMs - trace.startMs; + const plannedMs = trace.rows.reduce((sum, row) => sum + (row.estimate?.durationMs ?? 0), 0); + return buildDomain({ + trace, + startMs: trace.startMs, + contentEndMs: trace.nowMs, + headroomMs: trace.live ? Math.max(MIN_HEADROOM_MS, span * 0.15) : span * 0.03, + plannedMs, + originMs: trace.startMs, + }); +} + +/** One row's own span, with labels counted from its start. Null for a row that never ran. */ +export function traceRowDomain(trace: ThreadTrace, row: TraceRow): TraceDomain | null { + if (row.span === null) return null; + const agentEnds = row.groups.flatMap(({ agents }) => + agents.flatMap(({ span }) => (span === null ? [] : [span.endMs ?? trace.nowMs])), + ); + const endMs = Math.max(row.span.endMs ?? trace.nowMs, ...agentEnds); + const span = Math.max(1000, endMs - row.span.startMs); + const running = row.span.endMs === null; + return buildDomain({ + trace: running ? trace : { ...trace, live: false }, + startMs: row.span.startMs - span * 0.04, + contentEndMs: endMs, + headroomMs: running ? Math.max(MIN_HEADROOM_MS / 2, span * 0.18) : span * 0.06, + plannedMs: 0, + originMs: row.span.startMs, + }); +} + +const collapsedAt = (domain: TraceDomain, atMs: number) => { + const clamped = Math.max(domain.startMs, atMs); + let removed = 0; + for (const gap of domain.gaps) { + if (clamped >= gap.endMs) removed += gap.endMs - gap.startMs; + else if (clamped > gap.startMs) removed += clamped - gap.startMs; + } + return clamped - domain.startMs - removed; +}; + +/** Where `atMs` sits on the axis, from 0 to 1; idle gaps take no width. */ +export function tracePosition(domain: TraceDomain, atMs: number): number { + return Math.min(1, collapsedAt(domain, atMs) / domain.length); +} + +/** A duration as a share of the axis, for planned estimates placed after now. */ +export function traceFraction(domain: TraceDomain, durationMs: number): number { + return durationMs / domain.length; +} + +const TICK_STEPS = [ + 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 10_800, 21_600, 43_200, 86_400, +].map((seconds) => seconds * 1000); + +/** + * Tick marks at round collapsed steps, labelled with the real time since the origin, so a tick + * after a gap counts the idle time too. Ticks crowding a gap break are left out. + */ +export function traceTicks( + domain: TraceDomain, +): ReadonlyArray<{ readonly position: number; readonly elapsedMs: number }> { + const step = TICK_STEPS.find((candidate) => domain.length / candidate <= 6) ?? 172_800_000; + const gapPositions = domain.gaps.map((gap) => tracePosition(domain, gap.startMs)); + const originCollapsed = collapsedAt(domain, domain.originMs); + const ticks: Array<{ position: number; elapsedMs: number }> = []; + for (let value = originCollapsed + step; ; value += step) { + if (value > domain.length) break; + const position = value / domain.length; + if (gapPositions.some((gap) => Math.abs(gap - position) < 0.1)) continue; + let real = domain.startMs + value; + for (const gap of domain.gaps) { + if (collapsedAt(domain, gap.startMs) < value) real += gap.endMs - gap.startMs; + } + ticks.push({ position, elapsedMs: real - domain.originMs }); + } + return ticks; +} + +/** "45s", "3m 05s", "1h 20m". */ +export function formatTraceDuration(durationMs: number): string { + const seconds = Math.max(0, Math.round(durationMs / 1000)); + if (seconds < 60) return `${seconds}s`; + const minutes = Math.floor(seconds / 60); + if (minutes < 60) return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`; + return `${Math.floor(minutes / 60)}h ${minutes % 60}m`; +} + +/** Axis labels: "30s", "12m", "1h", "1h 20m". */ +export function formatTraceClock(durationMs: number): string { + const seconds = Math.round(durationMs / 1000); + if (seconds < 60) return `${seconds}s`; + const minutes = Math.round(seconds / 60); + if (minutes < 60) return `${minutes}m`; + const hours = Math.floor(minutes / 60); + return minutes % 60 === 0 ? `${hours}h` : `${hours}h ${minutes % 60}m`; +} diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 0e7e31ef98260..db7178585b1bb 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -908,6 +908,9 @@ export const OrchestrationV2RemoteTaskChild = Schema.Struct({ }); export type OrchestrationV2RemoteTaskChild = typeof OrchestrationV2RemoteTaskChild.Type; +/** A coordinator-chosen work stream, such as "UI" or "Backend", that clients group agents by. */ +export const SubagentGroup = TrimmedNonEmptyString.check(Schema.isMaxLength(40)); + export const OrchestrationV2Subagent = Schema.Struct({ id: NodeId, threadId: ThreadId, @@ -943,6 +946,7 @@ export const OrchestrationV2Subagent = Schema.Struct({ workflow: Schema.optional(OrchestrationV2SubagentWorkflow), /** The parent's active milestone when the subagent was first recorded. */ milestoneId: Schema.optional(MilestoneId), + group: Schema.optional(SubagentGroup), result: Schema.NullOr(Schema.String), startedAt: Schema.NullOr(Schema.DateTimeUtc), completedAt: Schema.NullOr(Schema.DateTimeUtc), @@ -3421,6 +3425,7 @@ export const OrchestrationV2Command = Schema.Union([ parentNodeId: NodeId, task: TrimmedNonEmptyString, title: Schema.optional(TrimmedNonEmptyString), + group: Schema.optional(SubagentGroup), modelSelection: ModelSelection, runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, @@ -3545,6 +3550,7 @@ const OrchestrationV2InternalCommand = Schema.Union([ parentNodeId: NodeId, task: TrimmedNonEmptyString, title: Schema.optional(TrimmedNonEmptyString), + group: Schema.optional(SubagentGroup), driver: ProviderDriverKind, modelSelection: ModelSelection, remoteChild: OrchestrationV2RemoteTaskChild, diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index f77ca12a0764b..8beb2cfe725ba 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -40,6 +40,7 @@ import { OrchestrationV2CreationSource, OrchestrationV2RunStatus, OrchestrationV2TurnItemStatus, + SubagentGroup, } from "./orchestrationV2.ts"; import { ProviderOptionSelection, ProviderOptionSelectionValue } from "./model.ts"; import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; @@ -182,6 +183,9 @@ export const OrchestratorMcpDelegateTaskInput = Schema.Struct({ target: Schema.optional(OrchestratorMcpDelegateTaskTarget), title: Schema.optional(OrchestratorMcpTitle), role: Schema.optional(OrchestratorMcpTaskRole), + group: Schema.optional(SubagentGroup).annotate({ + description: "Parallel work stream, e.g. 'UI'.", + }), isolation: Schema.optional( Schema.Literals(["shared", "worktree"]).annotate({ description: diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts index 93ba519aad56c..6956512a8a324 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.ts @@ -12,7 +12,7 @@ Ordinary coding tasks need no T3 tools. - Follow a running delegate's \`next\`. Don't poll it (\`task_status\`, \`sleep\`, watchers, Monitor, ScheduleWakeup). Stop a delegate run you replace or no longer need with \`task_cancel\`, never \`t3_thread_interrupt\` on a \`childThreadId\`. - As a subagent or child, do the work yourself. Start no subagents unless your task says to.`, `- \`t3_thread_launch\` and \`create_threads\` make new top-level threads, only when the user asks for a new thread. "Subagent", "delegate", and "parallel" never mean one. Worktree thread: set \`workspaceStrategy\`. Honor a requested base. Otherwise independent work uses the default branch as \`remote/branch\` with \`startFromOrigin:true\`; with no remote, use the local default. Required unpublished commits and dependent work use their local base. Shell worktrees don't bind it, and no checkout setup in its prompt. No \`workspaceStrategy\`: project root, not your worktree. -- Long multi-phase work (several phases, many steps or subagents): \`t3_milestone\` \`plan\` first, then \`start\`/\`done\` as phases change. Skip it for short tasks. +- Long multi-phase work (several phases, many steps or subagents): \`t3_milestone\` \`plan\` first, then \`start\`/\`done\` as phases change. Skip it for short tasks. Parallel streams: set each \`delegate_task\` \`group\` ("UI", "Backend"). - Given a thread id, \`t3_thread_read\` it before you answer about it. Asked to settle a thread, this one too: \`t3_thread_organize\`. - Another machine: \`t3_environment_links\` lists linked ones. Pass its \`environmentId\` to a T3 tool to act there. Ids are then that machine's, so pass \`threadId\`. - A machine the user names that isn't linked ("delegate this to my vps"): call \`t3_environment_link\` with a \`hint\` from their words. Never ask for a pairing code in chat.