From 018da700f835c3e18e21f73be2b65654eb3a9a9f Mon Sep 17 00:00:00 2001 From: OmarAlex24 Date: Wed, 11 Nov 2026 11:19:06 -0600 Subject: [PATCH 01/10] feat: a milestone map lays out a thread's plans, detours and agents Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/package.json | 4 + .../src/state/threadMilestoneMap.test.ts | 517 +++++++++++ .../src/state/threadMilestoneMap.ts | 807 ++++++++++++++++++ 3 files changed, 1328 insertions(+) create mode 100644 packages/client-runtime/src/state/threadMilestoneMap.test.ts create mode 100644 packages/client-runtime/src/state/threadMilestoneMap.ts diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 0611d5d0adaf4..2607ad2fd19d2 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-map": { + "types": "./src/state/threadMilestoneMap.ts", + "default": "./src/state/threadMilestoneMap.ts" + }, "./state/thread-milestone-trace": { "types": "./src/state/threadMilestoneTrace.ts", "default": "./src/state/threadMilestoneTrace.ts" diff --git a/packages/client-runtime/src/state/threadMilestoneMap.test.ts b/packages/client-runtime/src/state/threadMilestoneMap.test.ts new file mode 100644 index 0000000000000..7d0ca783b0b47 --- /dev/null +++ b/packages/client-runtime/src/state/threadMilestoneMap.test.ts @@ -0,0 +1,517 @@ +import { describe, expect, it } from "vite-plus/test"; +import { + type OrchestrationV2Milestone, + type OrchestrationV2Subagent, + NodeId, + ProviderDriverKind, + ProviderInstanceId, + RunId, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; + +import type { ThreadStructureTurnItem } from "./models.ts"; +import { + type AgentAsk, + type MapMilestone, + agentLine, + deriveMilestoneMap, + flattenAgents, + layoutMilestoneGraph, +} from "./threadMilestoneMap.ts"; + +const BASE_MS = Date.parse("2026-11-10T10:00:00.000Z"); +const sec = (seconds: number) => DateTime.makeUnsafe(BASE_MS + seconds * 1000); +const ENV = "env-1"; + +const run = (ordinal: number, status: string, startS: number, endS: number | null = null) => + ({ + id: RunId.make(`run-${ordinal}`), + ordinal, + status, + userMessageId: `msg-${ordinal}`, + requestedAt: sec(startS), + startedAt: sec(startS), + completedAt: endS === null ? null : sec(endS), + }) as never; + +const message = (id: string, role: "user" | "assistant", text: string, runOrdinal: number) => + ({ + id, + runId: RunId.make(`run-${runOrdinal}`), + role, + text, + streaming: false, + createdBy: role === "user" ? "user" : "agent", + }) as never; + +const anchor = (runOrdinal: number, id: string) => ({ + runId: RunId.make(`run-${runOrdinal}`), + itemId: TurnItemId.make(`item-${id}`), +}); + +function milestone( + id: string, + setId: string, + title: string, + status: OrchestrationV2Milestone["status"], + times: { readonly start?: number; readonly end?: number; readonly plannedIn?: number | null }, + extra: Partial = {}, +): OrchestrationV2Milestone { + const plannedIn = times.plannedIn === undefined ? 1 : times.plannedIn; + return { + id, + setId, + title, + status, + startedAt: times.start === undefined ? null : sec(times.start), + completedAt: times.end === undefined ? null : sec(times.end), + anchors: plannedIn === null ? {} : { planned: anchor(plannedIn, id) }, + ...extra, + } as OrchestrationV2Milestone; +} + +function agent( + id: string, + milestoneId: string, + status: OrchestrationV2Subagent["status"], + startS: number, + endS: number | null, + extra: Partial = {}, +): OrchestrationV2Subagent { + return { + id: NodeId.make(id), + threadId: ThreadId.make("thread-1"), + runId: RunId.make("run-1"), + parentNodeId: NodeId.make("root"), + origin: "app_owned", + createdBy: "agent", + driver: ProviderDriverKind.make("claude"), + providerInstanceId: ProviderInstanceId.make("claude"), + providerThreadId: null, + childThreadId: ThreadId.make(`child-${id}`), + nativeTaskRef: null, + prompt: id, + title: id, + model: null, + status, + result: null, + milestoneId, + startedAt: sec(startS), + completedAt: endS === null ? null : sec(endS), + updatedAt: sec(endS ?? startS), + ...extra, + } as OrchestrationV2Subagent; +} + +const milestoneItem = ( + id: string, + fields: Partial>, +): ThreadStructureTurnItem => + ({ + id: TurnItemId.make(id), + type: "milestone", + parentItemId: null, + status: "completed", + ...fields, + }) as never; + +const rows = (map: { readonly nodes: ReadonlyArray<{ id: string; col: number }> }) => + map.nodes.map(({ id, col }) => [id, col]); +const edges = (map: { + readonly edges: ReadonlyArray<{ from: string; to: string; style: string }>; +}) => map.edges.map(({ from, to, style }) => [from, to, style]); +const card = (map: { readonly nodes: ReadonlyArray<{ id: string }> }, id: string) => + map.nodes.find((node) => node.id === id) as MapMilestone; + +/** The mockup's live fixture: a GitHub OAuth task with a detour, a re-plan and two asks. */ +const OAUTH = { + runs: [run(1, "running", 0)], + messages: [ + message("msg-1", "user", "Agrega login con GitHub OAuth.\nY que la sesión sobreviva.", 1), + ], + milestones: [ + milestone("m1", "s1", "Leer el módulo de auth", "done", { start: 10, end: 82 }), + milestone("m2", "s1", "Reusar /api/session", "done", { start: 82, end: 205 }, { + revision: { previousTitle: "Diseñar la API de sesión", reason: "Ya existe /api/session." }, + } as never), + milestone("m3", "s1", "Backend y UI en paralelo", "done", { start: 205, end: 605 }), + milestone("m5", "s1", "Tests", "done", { start: 695, end: 880 }), + milestone("m6", "s1", "Docs", "planned", {}), + milestone("m4", "s1", "Actualizar @octokit/oauth-app", "done", { + start: 605, + end: 695, + plannedIn: null, + }), + milestone("m7", "s2", "Corregir refresh token", "active", { start: 880 }), + milestone("m8", "s2", "Tests e2e", "planned", {}), + milestone("m9", "s2", "Docs", "planned", {}), + ], + subagents: [ + agent("a3", "m3", "completed", 214, 380, { group: "Backend" } as never), + agent("a4", "m3", "failed", 216, 281, { title: "Migración users", group: "Backend" } as never), + agent("a1", "m3", "completed", 215, 345, { group: "UI" } as never), + agent("a2", "m3", "completed", 218, 400, { group: "UI" } as never), + agent("a5", "m3", "completed", 290, 390, { + title: "Migración users", + group: "Backend", + } as never), + agent("a3a", "m3", "completed", 300, 372, { parentNodeId: NodeId.make("a3") }), + agent("a6", "m5", "completed", 700, 870), + agent("a7", "m7", "running", 895, null, { group: "Backend" } as never), + agent("a9", "m7", "completed", 900, 1010, { group: "UI" } as never), + agent("a8", "m7", "running", 940, null, { group: "Backend" } as never), + ], +}; +const OAUTH_ASKS = new Map([ + [`${ENV}:child-a7`, { kind: "approval", command: "pnpm db:reset" }], + [`${ENV}:child-a8`, { kind: "secret", label: "GITHUB_CLIENT_SECRET" }], +]); +const OAUTH_ITEMS = [ + milestoneItem("plan-2", { + event: "plan", + setId: "s2" as never, + startedAt: sec(880), + closedMilestoneId: "m5" as never, + }), +]; + +/** "Trace groups check": two milestones started again by title, then a plan of ten. */ +const TRACE_GROUPS = { + runs: [run(1, "completed", 0, 30), run(2, "completed", 905, 1239)], + messages: [ + message("msg-1", "user", "Plan two milestones: 'Construir' and 'Revisar'.", 1), + message("msg-2", "user", "Segunda ronda, corta.", 2), + message("reply-2", "assistant", "Done.\nAll ten planned.", 2), + ], + milestones: [ + milestone("m1", "s1", "Construir", "done", { start: 7, end: 10 }, { + detailInTurnItem: true, + } as never), + milestone("m2", "s1", "Revisar", "planned", {}), + milestone("m3", "s1", "Construir", "done", { start: 10, end: 26, plannedIn: null }), + milestone("m4", "s1", "Revisar", "done", { start: 27, end: 30, plannedIn: null }), + milestone("m5", "s2", "Fase A", "done", { start: 910, end: 910, plannedIn: 2 }), + ...["B", "C", "D", "E", "F", "G", "H", "I", "J"].map((letter, index) => + milestone(`m${6 + index}`, "s2", `Fase ${letter}`, "planned", { plannedIn: 2 }), + ), + milestone("m15", "s2", "Fase A", "done", { start: 910.5, end: 1235, plannedIn: null }), + ], + subagents: ["r1", "r2", "r3", "r4"].map((id) => agent(id, "m3", "completed", 11, 16)), +}; +const TRACE_GROUPS_ITEMS = [ + milestoneItem("started-m3", { + event: "started", + milestoneId: "m3" as never, + setId: "s1" as never, + closedMilestoneId: "m1" as never, + note: "Closed when a second “Construir” started.", + }), +]; + +const derive = ( + projection: typeof OAUTH | typeof TRACE_GROUPS, + turnItems: ReadonlyArray, + asks: ReadonlyMap = new Map(), +) => + deriveMilestoneMap({ + environmentId: ENV, + projection: projection as never, + turnItems, + asks, + coordinatorAsks: false, + nowMs: BASE_MS + 1131_000, + })!; + +/** id, set, in the plan, dropped, started (seconds). */ +type GraphRow = readonly [string, string, boolean, boolean, number | null]; + +describe("layoutMilestoneGraph", () => { + it.each([ + { + name: "a detour that rejoins, and a plan forked from the last done milestone", + sets: [ + { id: "s1", from: null, you: null }, + { id: "s2", from: "m5", you: null }, + ], + milestones: [ + ["m1", "s1", true, false, 10], + ["m2", "s1", true, false, 82], + ["m3", "s1", true, false, 205], + ["m4", "s1", false, false, 605], + ["m5", "s1", true, false, 695], + ["m6", "s1", true, true, null], + ["m7", "s2", true, false, 880], + ["m8", "s2", true, false, null], + ["m9", "s2", true, false, null], + ], + nodes: [ + ["you", 0], + ["m1", 0], + ["m2", 0], + ["m3", 0], + ["m4", 1], + ["m5", 0], + ["m7", 1], + ["m6", 0], + ["m8", 1], + ["m9", 1], + ], + edges: [ + ["you", "m1", "live"], + ["m1", "m2", "live"], + ["m2", "m3", "live"], + ["m3", "m5", "live"], + ["m5", "m6", "dropped"], + ["m3", "m4", "live"], + ["m4", "m5", "live"], + ["m7", "m8", "future"], + ["m8", "m9", "future"], + ["m5", "m7", "live"], + ], + }, + { + name: "milestones started again by title, and a plan you asked for forked from the detour", + sets: [ + { id: "s1", from: null, you: null }, + { id: "s2", from: "m4", you: "Segunda ronda" }, + ], + milestones: [ + ["m1", "s1", true, false, 7], + ["m2", "s1", true, true, null], + ["m3", "s1", false, false, 10], + ["m4", "s1", false, false, 27], + ["m5", "s2", true, false, 910], + ...["m6", "m7", "m8", "m9", "m10", "m11", "m12", "m13", "m14"].map((id) => [ + id, + "s2", + true, + false, + null, + ]), + ["m15", "s2", false, false, 910.5], + ], + nodes: [ + ["you", 0], + ["m1", 0], + ["m3", 1], + ["m2", 0], + ["m4", 1], + ["you-s2", 0], + ["m5", 0], + ["m15", 1], + ...["m6", "m7", "m8", "m9", "m10", "m11", "m12", "m13", "m14"].map((id) => [id, 0]), + ], + edges: [ + ["you", "m1", "live"], + ["m1", "m2", "dropped"], + ["m3", "m4", "live"], + ["m1", "m3", "live"], + ["you-s2", "m5", "live"], + ["m5", "m6", "future"], + ["m6", "m7", "future"], + ["m7", "m8", "future"], + ["m8", "m9", "future"], + ["m9", "m10", "future"], + ["m10", "m11", "future"], + ["m11", "m12", "future"], + ["m12", "m13", "future"], + ["m13", "m14", "future"], + ["m4", "you-s2", "live"], + ["m5", "m15", "live"], + ["m15", "m6", "future"], + ], + }, + ] as const)("$name", ({ sets, milestones, nodes, edges: expected }) => { + const layout = layoutMilestoneGraph({ + milestones: (milestones as ReadonlyArray).map( + ([id, setId, planned, dropped, start]) => ({ + id, + setId, + planned, + dropped, + startMs: start === null ? null : start * 1000, + }), + ), + sets, + request: "Your request", + }); + expect(rows(layout)).toEqual(nodes); + expect(edges(layout)).toEqual(expected); + }); +}); + +describe("deriveMilestoneMap", () => { + it("lays out a live OAuth task with its detour, changes, retries, nesting and asks", () => { + const map = derive(OAUTH, OAUTH_ITEMS, OAUTH_ASKS); + expect(rows(map)).toEqual([ + ["you", 0], + ["m1", 0], + ["m2", 0], + ["m3", 0], + ["m4", 1], + ["m5", 0], + ["m7", 1], + ["m6", 0], + ["m8", 1], + ["m9", 1], + ]); + expect(map.title).toBe("Agrega login con GitHub OAuth."); + expect( + map.nodes.flatMap((node) => + node.kind === "milestone" ? [[node.id, node.status, node.subtitle, node.rollup.text]] : [], + ), + ).toEqual([ + ["m1", "done", "In the plan", "No agents"], + ["m2", "done", "Changed from “Diseñar la API de sesión”", "No agents"], + ["m3", "done", "In the plan", "1 failed, retried · 6 agents"], + ["m4", "done", "Not in the plan", "No agents"], + ["m5", "done", "In the plan", "1 agent done"], + ["m7", "needs-you", "New plan", "2 need you"], + ["m6", "dropped", "In the plan", "No agents"], + ["m8", "planned", "In the new plan", "No agents"], + ["m9", "planned", "In the new plan", "No agents"], + ]); + expect(card(map, "m6").why).toBe("Replaced by the new plan"); + expect(card(map, "m2").subtitleHint).toBe("Ya existe /api/session."); + + const build = card(map, "m3"); + expect( + build.groups.map(({ name, done, total, parallel, agents }) => [ + name, + `${done}/${total}`, + parallel, + agents.map(({ agent: { id }, retry, children }) => [ + id, + retry, + children.map((child) => child.agent.id), + ]), + ]), + ).toEqual([ + [ + "Backend", + "3/4", + true, + [ + ["a3", false, ["a3a"]], + ["a4", false, []], + ["a5", true, []], + ], + ], + [ + "UI", + "2/2", + true, + [ + ["a1", false, []], + ["a2", false, []], + ], + ], + ]); + + const live = card(map, "m7"); + expect(live.live).toBe(true); + expect(live.endMs).toBeNull(); + expect( + flattenAgents(live.groups.flatMap(({ agents }) => agents)).map( + ({ agent: { id }, status, ask }) => [id, status, agentLine(ask, null)], + ), + ).toEqual([ + ["a7", "needs-you", "Wants to run pnpm db:reset"], + ["a8", "needs-you", "Asks you for GITHUB_CLIENT_SECRET"], + ["a9", "done", null], + ]); + expect(map.stats).toMatchObject({ + done: 5, + total: 8, + agents: 10, + running: 2, + needsYou: 2, + endMs: null, + }); + }); + + it("turns titles started again into detours and forks the next plan from the last of them", () => { + const map = derive(TRACE_GROUPS, TRACE_GROUPS_ITEMS); + expect(rows(map)).toEqual([ + ["you", 0], + ["m1", 0], + ["m3", 1], + ["m2", 0], + ["m4", 1], + ["you-s2", 0], + ["m5", 0], + ["m15", 1], + ...["m6", "m7", "m8", "m9", "m10", "m11", "m12", "m13", "m14"].map((id) => [id, 0]), + ]); + expect(edges(map)).toContainEqual(["m4", "you-s2", "live"]); + expect(map.nodes.find(({ id }) => id === "you-s2")).toMatchObject({ + text: "Segunda ronda, corta.", + }); + expect(card(map, "m5").subtitle).toBe("New plan, 15m later"); + expect(card(map, "m3").subtitle).toBe("Not in the plan"); + expect(card(map, "m3").groups[0]).toMatchObject({ done: 4, total: 4, parallel: true }); + expect(card(map, "m1").note).toBe("Closed when a second “Construir” started."); + expect(map.live).toBe(false); + expect(map.stats).toMatchObject({ done: 5, total: 14, agents: 4, running: 0, needsYou: 0 }); + expect(map.stats.endMs).toBe(BASE_MS + 1239_000); + + const fromPlanItem = derive(TRACE_GROUPS, [ + ...TRACE_GROUPS_ITEMS, + milestoneItem("plan-2", { + event: "plan", + setId: "s2" as never, + closedMilestoneId: "m1" as never, + }), + ]); + expect(edges(fromPlanItem)).toContainEqual(["m1", "you-s2", "live"]); + }); + + it("shows one row per turn on a thread that never planned", () => { + const map = deriveMilestoneMap({ + environmentId: ENV, + projection: { + runs: [run(1, "completed", 0, 5), run(2, "completed", 66, 71)], + messages: [ + message("msg-1", "user", "go", 1), + message("reply-1", "assistant", "Ran the showcase.\nDetails.", 1), + message("msg-2", "user", "again", 2), + ], + milestones: [], + subagents: [], + } as never, + turnItems: [], + asks: new Map(), + coordinatorAsks: false, + nowMs: BASE_MS, + })!; + expect(map.mode).toBe("turns"); + expect( + map.nodes.map((node) => + node.kind === "milestone" + ? [node.id, node.col, node.title, node.subtitle, node.note, node.status] + : [], + ), + ).toEqual([ + ["run-1", 0, "go", "Turn 1", "Ran the showcase.", "done"], + ["run-2", 0, "again", "Turn 2", null, "done"], + ]); + expect(edges(map)).toEqual([["run-1", "run-2", "live"]]); + }); +}); + +describe("agentLine", () => { + it.each([ + [{ kind: "approval", command: "pnpm db:reset" }, null, "Wants to run pnpm db:reset"], + [ + { kind: "secret", label: "GITHUB_CLIENT_SECRET" }, + { summary: "Ran tests" }, + "Asks you for GITHUB_CLIENT_SECRET", + ], + [null, { summary: "Read", detail: "src/auth/session.ts" }, "Read · src/auth/session.ts"], + [null, null, null], + ] as const)("%o with %o reads %s", (ask, action, expected) => { + expect(agentLine(ask, action)).toBe(expected); + }); +}); diff --git a/packages/client-runtime/src/state/threadMilestoneMap.ts b/packages/client-runtime/src/state/threadMilestoneMap.ts new file mode 100644 index 0000000000000..2789e81df798c --- /dev/null +++ b/packages/client-runtime/src/state/threadMilestoneMap.ts @@ -0,0 +1,807 @@ +import * as DateTime from "effect/DateTime"; +import type { + OrchestrationV2LatestActionSummary, + OrchestrationV2Milestone, + OrchestrationV2Subagent, + OrchestrationV2ThreadProjection, + ProviderDriverKind, +} from "@t3tools/contracts"; +import { copySorted } from "@t3tools/shared/Array"; + +import type { ThreadStructureTurnItem } from "./models.ts"; +import { isActiveSubagentStatus } from "./subagentRuntime.ts"; +import { deriveThreadMilestoneGraph } from "./threadMilestoneGraph.ts"; +import { resolveActiveThreadRun } from "./threadWorkflows.ts"; + +type Projection = Pick< + OrchestrationV2ThreadProjection, + "runs" | "subagents" | "milestones" | "messages" +>; +type Run = Projection["runs"][number]; +type Subagent = OrchestrationV2Subagent; +type MilestoneItem = Extract; + +export interface GraphMilestone { + readonly id: string; + readonly setId: string; + /** In its set's plan; false for one the coordinator started by title. */ + readonly planned: boolean; + /** Dropped, or left over from a plan that a new one replaced. */ + readonly dropped: boolean; + readonly startMs: number | null; +} + +export interface GraphSet { + readonly id: string; + /** The milestone that was current when this plan replaced the last one. */ + readonly from: string | null; + /** What you wrote that started this plan, when you did. */ + readonly you: string | null; +} + +export interface GraphNode { + readonly kind: "you" | "milestone"; + readonly id: string; + readonly row: number; + readonly col: number; + /** Your message, for a `you` node. */ + readonly text: string | null; +} + +export type GraphEdgeStyle = "live" | "future" | "dropped"; + +export interface GraphEdge { + readonly from: string; + readonly to: string; + readonly style: GraphEdgeStyle; +} + +interface Lane { + readonly key: string; + readonly kind: "plan" | "detour"; + readonly setId: string; + readonly from: string | null; + readonly members: Array; + col: number; + parent: string | null; +} + +/** + * Rows in the order work started, the first plan on lane 0. Work outside the plan branches one lane + * out and rejoins at the plan's next milestone; a new plan forks from the milestone that was + * current into the first free lane other than its parent's. Leftovers of an abandoned plan sit one + * row past the work that replaced them, and the latest plan's unstarted milestones go last. + */ +export function layoutMilestoneGraph(input: { + /** In creation order. */ + readonly milestones: ReadonlyArray; + /** In order; the first is the first plan. */ + readonly sets: ReadonlyArray; + /** Your first message, shown above the first plan. */ + readonly request: string | null; + /** A node for the work done before any plan, right after your first message. */ + readonly before?: string | null; +}): { readonly nodes: ReadonlyArray; readonly edges: ReadonlyArray } { + const { milestones, sets } = input; + const setById = new Map(sets.map((set) => [set.id, set])); + const byId = new Map(milestones.map((milestone) => [milestone.id, milestone])); + const lanes = new Map(); + const laneOf = new Map(); + const lane = (key: string, kind: Lane["kind"], setId: string, from: string | null) => { + let existing = lanes.get(key); + if (existing === undefined) { + existing = { key, kind, setId, from, members: [], col: 0, parent: null }; + lanes.set(key, existing); + } + return existing; + }; + const planLane = (setId: string) => lane(`P:${setId}`, "plan", setId, null); + + const started = copySorted( + milestones.filter((milestone) => milestone.startMs !== null), + (left, right) => left.startMs! - right.startMs!, + ); + let detour: Lane | null = null; + started.forEach((milestone, index) => { + const previous = started[index - 1] ?? null; + if (milestone.planned) { + detour = null; + laneOf.set(milestone.id, planLane(milestone.setId)); + return; + } + if ( + detour === null || + detour.setId !== milestone.setId || + (previous !== null && laneOf.get(previous.id) !== detour) + ) { + detour = lane(`D:${milestone.id}`, "detour", milestone.setId, previous?.id ?? null); + } + laneOf.set(milestone.id, detour); + }); + for (const milestone of milestones) { + if (milestone.startMs === null) laneOf.set(milestone.id, planLane(milestone.setId)); + } + + const latestSetId = sets.at(-1)?.id ?? null; + const slots = [...started]; + for (const candidate of lanes.values()) { + const pending = milestones.filter( + (milestone) => milestone.startMs === null && laneOf.get(milestone.id) === candidate, + ); + if (pending.length === 0) continue; + if (candidate.setId === latestSetId) { + slots.push(...pending); + continue; + } + const anchor = Math.max( + -1, + ...slots.flatMap((slot, index) => (laneOf.get(slot.id) === candidate ? [index] : [])), + ); + slots.splice(Math.min(slots.length, anchor + 2), 0, ...pending); + } + + const firstSetId = sets[0]?.id ?? milestones[0]?.setId ?? "s1"; + const first = planLane(firstSetId); + const placed: Array<{ node: GraphNode & { row: number }; lane: Lane }> = []; + const place = (kind: GraphNode["kind"], id: string, text: string | null, into: Lane) => { + const node = { kind, id, row: placed.length, col: 0, text }; + placed.push({ node, lane: into }); + into.members.push(node); + }; + if (input.request !== null) place("you", "you", input.request, first); + if (input.before != null) place("milestone", input.before, null, first); + const seenSets = new Set(); + for (const milestone of slots) { + const into = laneOf.get(milestone.id)!; + if (into.kind === "plan" && !seenSets.has(milestone.setId)) { + seenSets.add(milestone.setId); + const you = setById.get(milestone.setId)?.you ?? null; + if (you !== null) place("you", `you-${milestone.setId}`, you, into); + } + place("milestone", milestone.id, null, into); + } + + const occupied = new Map>(); + const span = (candidate: Lane): readonly [number, number] => [ + Math.min(...candidate.members.map(({ row }) => row)), + Math.max(...candidate.members.map(({ row }) => row)), + ]; + const free = (col: number, [start, end]: readonly [number, number]) => + (occupied.get(col) ?? []).every(([from, to]) => end < from || start > to); + const take = (candidate: Lane, col: number) => { + candidate.col = col; + occupied.set(col, [...(occupied.get(col) ?? []), span(candidate)]); + }; + const placedLanes = [...lanes.values()].filter((candidate) => candidate.members.length > 0); + if (first.members.length > 0) take(first, 0); + for (const candidate of copySorted( + placedLanes, + (left, right) => span(left)[0] - span(right)[0], + )) { + if (candidate === first) continue; + const parentId = + candidate.kind === "detour" ? candidate.from : (setById.get(candidate.setId)?.from ?? null); + candidate.parent = parentId !== null && laneOf.has(parentId) ? parentId : null; + const parentCol = candidate.parent === null ? 0 : laneOf.get(candidate.parent)!.col; + let col = candidate.kind === "plan" ? 0 : parentCol + 1; + while (!free(col, span(candidate)) || (candidate.kind === "plan" && col === parentCol)) col++; + take(candidate, col); + } + + const nodes = placed.map(({ node, lane: owner }) => ({ ...node, col: owner.col })); + const nodeById = new Map(nodes.map((node) => [node.id, node])); + const styleOf = (node: GraphNode): GraphEdgeStyle => { + if (node.kind === "you") return "live"; + const milestone = byId.get(node.id); + if (milestone === undefined) return "live"; + return milestone.startMs !== null ? "live" : milestone.dropped ? "dropped" : "future"; + }; + const edges: Array = []; + const link = (from: string, to: GraphNode) => edges.push({ from, to: to.id, style: styleOf(to) }); + for (const candidate of placedLanes) { + const members = candidate.members.map(({ id }) => nodeById.get(id)!); + for (let index = 1; index < members.length; index++) { + link(members[index - 1]!.id, members[index]!); + } + if (candidate !== first && candidate.parent !== null) link(candidate.parent, members[0]!); + if (candidate.kind === "detour") { + const last = members.at(-1)!; + const next = placedLanes + .find((home) => home.kind === "plan" && home.setId === candidate.setId) + ?.members.find( + (member) => + member.row > last.row && + member.kind === "milestone" && + byId.get(member.id)?.dropped === false, + ); + const forks = sets.some((set) => set.from === last.id); + if (next !== undefined && !forks) link(last.id, nodeById.get(next.id)!); + } + } + return { nodes, edges }; +} + +export type MapStatus = + | "running" + | "done" + | "needs-you" + | "failed" + | "planned" + | "dropped" + | "stopped"; + +export type AgentAsk = + | { readonly kind: "secret"; readonly label: string } + | { readonly kind: "approval"; readonly command: string | null } + | { readonly kind: "input" }; + +export interface MapAgent { + readonly agent: Subagent; + readonly status: MapStatus; + readonly ask: AgentAsk | null; + /** The same task again after an earlier try failed. */ + readonly retry: boolean; + readonly startMs: number | null; + readonly endMs: number | null; + readonly children: ReadonlyArray; +} + +export interface MapGroup { + readonly name: string | null; + readonly agents: ReadonlyArray; + readonly done: number; + readonly total: number; + /** Two or more of its agents ran at the same time. */ + readonly parallel: boolean; +} + +export type MapRollupTone = "needs-you" | "running" | "none" | "failed" | "done"; + +export interface MapMilestone { + readonly kind: "milestone"; + readonly id: string; + readonly row: number; + readonly col: number; + /** Null for a turn on a thread that never planned. */ + readonly milestone: OrchestrationV2Milestone | null; + readonly title: string; + readonly subtitle: string; + /** Why it changed, for a milestone the coordinator rewrote. */ + readonly subtitleHint: string | null; + readonly status: MapStatus; + readonly started: boolean; + /** Why it was dropped. */ + readonly why: string | null; + readonly revision: { readonly previousTitle: string; readonly reason: string } | null; + /** The milestone's result, or the turn's last reply. */ + readonly note: string | null; + /** Live: the coordinator is working on it now, so its line follows the coordinator. */ + readonly live: boolean; + readonly rollup: { readonly tone: MapRollupTone; readonly text: string }; + readonly groups: ReadonlyArray; + readonly agentCount: number; + readonly drivers: ReadonlyArray; + readonly startMs: number | null; + readonly endMs: number | null; +} + +export interface MapBubble { + readonly kind: "you"; + readonly id: string; + readonly row: number; + readonly col: number; + readonly text: string; +} + +export interface MilestoneMap { + readonly mode: "milestones" | "turns"; + readonly title: string | null; + readonly nodes: ReadonlyArray; + readonly edges: ReadonlyArray; + readonly maxCol: number; + readonly live: boolean; + readonly coordinatorRun: Run | null; + readonly stats: { + readonly done: number; + readonly total: number; + readonly agents: number; + readonly running: number; + readonly needsYou: number; + readonly startMs: number; + /** Null while the thread is live. */ + readonly endMs: number | null; + }; +} + +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 plural = (count: number, word: string) => `${count} ${count === 1 ? word : `${word}s`}`; +const NEW_PLAN_GAP_MS = 10 * 60_000; +/** The node for agents that ran before the first plan. */ +const BEFORE_PLAN_NODE_ID = "before-plan"; + +export const flattenAgents = (agents: ReadonlyArray): ReadonlyArray => + agents.flatMap((agent) => [agent, ...flattenAgents(agent.children)]); + +/** Where an agent's own thread lives: here, or in the linked environment it was delegated to. */ +function agentThreadKey(agent: Subagent, environmentId: string): string | null { + if (agent.remoteChild !== undefined) { + return `${agent.remoteChild.environmentId}:${agent.remoteChild.threadId}`; + } + return agent.childThreadId === null ? null : `${environmentId}:${agent.childThreadId}`; +} + +/** An agent's one line: its ask while it needs you, else what it did last, else nothing. */ +export function agentLine( + ask: AgentAsk | null, + latestAction: Pick | null | undefined, +): string | null { + if (ask !== null) { + switch (ask.kind) { + case "secret": + return `Asks you for ${ask.label}`; + case "approval": + return ask.command === null ? "Wants your approval" : `Wants to run ${ask.command}`; + case "input": + return "Has a question for you"; + } + } + return actionLine(latestAction); +} + +function actionLine( + action: Pick | null | undefined, +): string | null { + if (action == null) return null; + return action.detail === undefined ? action.summary : `${action.summary} · ${action.detail}`; +} + +function agentStatus(agent: Subagent, ask: AgentAsk | null): MapStatus { + switch (agent.status) { + case "completed": + case "idle": + return "done"; + case "running": + case "waiting": + return ask === null ? "running" : "needs-you"; + case "pending": + return agent.startedAt === null ? "planned" : "running"; + case "failed": + return "failed"; + case "cancelled": + case "interrupted": + return "stopped"; + } +} + +function overlaps(agents: ReadonlyArray): boolean { + return agents.some((left, index) => + agents.some( + (right, other) => + other > index && + left.startMs !== null && + right.startMs !== null && + left.startMs < (right.endMs ?? Infinity) && + right.startMs < (left.endMs ?? Infinity), + ), + ); +} + +/** + * Agents nested by their real parent link, in start order. A task given again after its earlier + * try failed is a retry: same title and group, started once that try ended. There is no retry link + * in the record, so this is inferred. + */ +function buildAgents( + subagents: ReadonlyArray, + asks: ReadonlyMap, + environmentId: string, +): ReadonlyArray { + const ids = new Set(subagents.map(({ id }) => id)); + const failed: Array<{ key: string; endMs: number }> = []; + const build = (agent: Subagent): MapAgent => { + const key = agentThreadKey(agent, environmentId); + const ask = key === null ? null : (asks.get(key) ?? null); + const status = agentStatus(agent, ask); + const startMs = msOrNull(agent.startedAt); + const live = status === "running" || status === "needs-you"; + const endMs = live + ? null + : (msOrNull(agent.completedAt) ?? (startMs === null ? null : ms(agent.updatedAt))); + const identity = `${agent.group ?? ""}\u0000${agent.title ?? agent.prompt}`; + const retry = failed.some( + (earlier) => earlier.key === identity && startMs !== null && startMs >= earlier.endMs, + ); + if (status === "failed" && endMs !== null) failed.push({ key: identity, endMs }); + return { + agent, + status, + ask, + retry, + startMs, + endMs, + children: subagents.filter((child) => child.parentNodeId === agent.id).map(build), + }; + }; + return subagents.filter((agent) => !ids.has(agent.parentNodeId)).map(build); +} + +function groupsOf(agents: ReadonlyArray): ReadonlyArray { + const groups = new Map>(); + for (const agent of agents) { + const key = agent.agent.group ?? ""; + groups.set(key, [...(groups.get(key) ?? []), agent]); + } + return [...groups].map(([name, members]) => { + const all = flattenAgents(members); + return { + name: name === "" ? null : name, + agents: members, + done: all.filter(({ status }) => status === "done").length, + total: all.length, + parallel: members.length > 1 && overlaps(members), + }; + }); +} + +function rollup(status: MapStatus, agents: ReadonlyArray): MapMilestone["rollup"] { + const all = flattenAgents(agents); + if (status === "running" || status === "needs-you") { + const needs = all.filter(({ ask }) => ask !== null).length; + if (needs > 0) return { tone: "needs-you", text: `${needs} need${needs === 1 ? "s" : ""} you` }; + const running = all.filter((agent) => agent.status === "running").length; + return { + tone: "running", + text: all.length > 0 ? `${running} of ${all.length} running` : "Working", + }; + } + if (all.length === 0) return { tone: "none", text: "No agents" }; + const failed = all.filter((agent) => agent.status === "failed").length; + if (failed > 0) { + const retried = all.some(({ retry }) => retry) ? "retried" : "not retried"; + return { + tone: "failed", + text: `${failed} failed, ${retried} · ${plural(all.length, "agent")}`, + }; + } + return { tone: "done", text: all.length === 1 ? "1 agent done" : `All ${all.length} done` }; +} + +function drivers(agents: ReadonlyArray): ReadonlyArray { + return [...new Set(flattenAgents(agents).map(({ agent }) => agent.driver))].slice(0, 3); +} + +/** Older sets keep their notes and revisions only in their turn items. */ +function milestoneDetail(milestone: OrchestrationV2Milestone, items: ReadonlyArray) { + if (milestone.detailInTurnItem !== true) { + return { note: milestone.note ?? null, revision: milestone.revision ?? null }; + } + const own = items.filter((item) => item.milestoneId === milestone.id); + const changed = own.findLast((item) => item.event === "changed"); + const closing = items.findLast( + (item) => + (item.milestoneId === milestone.id && (item.event === "done" || item.event === "dropped")) || + ((item.event === "started" || item.event === "plan") && + item.closedMilestoneId === milestone.id), + ); + return { + note: closing?.event === "dropped" ? (closing.reason ?? null) : (closing?.note ?? null), + revision: + changed?.previousTitle !== undefined && changed.reason !== undefined + ? { previousTitle: changed.previousTitle, reason: changed.reason } + : null, + }; +} + +const runText = (projection: Projection, run: Run): string | null => { + const message = projection.messages.find(({ id }) => id === run.userMessageId); + return message === undefined ? null : message.text.trim() || null; +}; + +const lastReply = (projection: Projection, run: Run): string | null => { + const reply = projection.messages.findLast( + (message) => message.runId === run.id && message.role === "assistant" && !message.streaming, + ); + return reply === undefined ? null : firstLine(reply.text) || null; +}; + +/** + * The thread as a graph of milestones in the order work started, each with its agents grouped as + * the coordinator grouped them; one row per turn on a thread that never planned. `asks` holds what + * each agent's thread (by `agentThreadKey`) waits on you for. + */ +export function deriveMilestoneMap(input: { + readonly environmentId: string; + readonly projection: Projection; + readonly turnItems: ReadonlyArray; + readonly asks: ReadonlyMap; + /** The coordinator itself waits on you. */ + readonly coordinatorAsks: boolean; + readonly nowMs: number; +}): MilestoneMap | null { + const { projection, asks, environmentId } = 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 || graph.coordinator.liveAgents > 0; + const coordinatorFailed = graph.coordinator.status === "failed"; + + const card = (fields: { + readonly id: string; + readonly milestone: OrchestrationV2Milestone | null; + readonly title: string; + readonly subtitle: string; + readonly subtitleHint?: string | null; + readonly state: "done" | "active" | "planned" | "dropped"; + readonly why?: string | null; + readonly revision?: MapMilestone["revision"]; + readonly note: string | null; + readonly agents: ReadonlyArray; + readonly startMs: number | null; + readonly endMs: number | null; + }): Omit => { + const agents = buildAgents(fields.agents, asks, environmentId); + const asking = flattenAgents(agents).some(({ ask }) => ask !== null); + const status: MapStatus = + fields.state === "active" + ? !live + ? coordinatorFailed + ? "failed" + : "stopped" + : asking || input.coordinatorAsks + ? "needs-you" + : "running" + : fields.state; + return { + kind: "milestone", + id: fields.id, + milestone: fields.milestone, + title: fields.title, + subtitle: fields.subtitle, + subtitleHint: fields.subtitleHint ?? null, + status, + started: fields.startMs !== null, + why: fields.why ?? null, + revision: fields.revision ?? null, + note: fields.note, + live: fields.state === "active" && live, + rollup: rollup(status, agents), + groups: groupsOf(agents), + agentCount: flattenAgents(agents).length, + drivers: drivers(agents), + startMs: fields.startMs, + endMs: fields.state === "active" && live ? null : fields.endMs, + }; + }; + + let nodes: Array; + let edges: ReadonlyArray; + if (graph.mode === "turns") { + nodes = graph.turns.map(({ run, agents }, index) => { + const startMs = msOrNull(run.startedAt); + const state = + run.status === "completed" || + run.status === "failed" || + run.status === "interrupted" || + run.status === "cancelled" + ? "done" + : startMs === null + ? "planned" + : "active"; + const base = card({ + id: run.id, + milestone: null, + title: firstLine(runText(projection, run) ?? "") || `Turn ${index + 1}`, + subtitle: `Turn ${index + 1}`, + state, + note: lastReply(projection, run), + agents, + startMs, + endMs: msOrNull(run.completedAt) ?? startMs, + }); + return { + ...base, + status: + run.status === "failed" + ? "failed" + : run.status === "interrupted" || run.status === "cancelled" + ? "stopped" + : base.status, + row: index, + col: 0, + }; + }); + edges = nodes.slice(1).map((node, index) => ({ + from: nodes[index]!.id, + to: node.id, + style: node.kind === "milestone" && node.started ? "live" : "future", + })); + } else { + const rootAgents = graph.root?.agents ?? []; + const milestoneItems = input.turnItems.filter( + (item): item is MilestoneItem => item.type === "milestone", + ); + const setIds = [...new Set(projection.milestones.map(({ setId }) => setId))]; + const currentSetId = setIds.at(-1)!; + const agentsOf = new Map( + graph.milestones.map(({ milestone, agents }) => [milestone.id, agents]), + ); + const dropped = (milestone: OrchestrationV2Milestone) => + milestone.status === "dropped" || + (milestone.setId !== currentSetId && + milestone.status !== "done" && + milestone.startedAt === null); + const runById = new Map(runs.map((run) => [run.id, run])); + const planRunOf = (setId: string) => + projection.milestones.find((milestone) => milestone.setId === setId)?.anchors.planned + ?.runId ?? null; + const sets: Array = setIds.map((setId, index) => { + const planItem = milestoneItems.find((item) => item.event === "plan" && item.setId === setId); + const firstOfSet = projection.milestones.find((milestone) => milestone.setId === setId)!; + const atMs = + msOrNull(planItem?.startedAt ?? null) ?? + msOrNull(firstOfSet.startedAt) ?? + msOrNull(runById.get(planRunOf(setId) ?? ("" as never))?.requestedAt ?? null); + const lastDone = + atMs === null + ? undefined + : copySorted( + projection.milestones.filter( + (milestone) => + milestone.setId !== setId && + milestone.completedAt !== null && + ms(milestone.completedAt) <= atMs, + ), + (left, right) => ms(left.completedAt!) - ms(right.completedAt!), + ).at(-1); + const from = index === 0 ? null : (planItem?.closedMilestoneId ?? lastDone?.id ?? null); + const planRunId = planRunOf(setId); + const previousPlanRunId = index === 0 ? null : planRunOf(setIds[index - 1]!); + const planRun = planRunId === null ? undefined : runById.get(planRunId); + const message = + planRun === undefined || index === 0 || planRunId === previousPlanRunId + ? undefined + : projection.messages.find( + ({ id, createdBy }) => id === planRun.userMessageId && createdBy === "user", + ); + return { id: setId, from, you: message?.text.trim() || null, atMs }; + }); + const layout = layoutMilestoneGraph({ + milestones: projection.milestones.map((milestone) => ({ + id: milestone.id, + setId: milestone.setId, + planned: milestone.anchors.planned !== undefined, + dropped: dropped(milestone), + startMs: msOrNull(milestone.startedAt), + })), + sets, + request: runs[0] === undefined ? null : runText(projection, runs[0]), + before: rootAgents.length > 0 ? BEFORE_PLAN_NODE_ID : null, + }); + const byId = new Map(projection.milestones.map((milestone) => [milestone.id, milestone])); + const setIndex = new Map(setIds.map((setId, index) => [setId, index])); + const subtitleOf = ( + milestone: OrchestrationV2Milestone, + revision: MapMilestone["revision"], + ) => { + if (revision !== null) return `Changed from “${revision.previousTitle}”`; + if (milestone.anchors.planned === undefined) return "Not in the plan"; + if (setIndex.get(milestone.setId) === 0) return "In the plan"; + const firstOfSet = projection.milestones.find(({ setId }) => setId === milestone.setId); + if (firstOfSet !== milestone) return "In the new plan"; + const set = sets[setIndex.get(milestone.setId)!]!; + const parent = set.from === null ? undefined : byId.get(set.from); + const parentEnd = msOrNull(parent?.completedAt ?? null) ?? set.atMs; + const gap = set.atMs === null || parentEnd === null ? 0 : set.atMs - parentEnd; + return gap >= NEW_PLAN_GAP_MS ? `New plan, ${Math.round(gap / 60_000)}m later` : "New plan"; + }; + nodes = layout.nodes.map((node): MapMilestone | MapBubble => { + if (node.kind === "you") { + return { kind: "you", id: node.id, row: node.row, col: node.col, text: node.text ?? "" }; + } + if (node.id === BEFORE_PLAN_NODE_ID) { + const run = graph.root!.run; + const startMs = msOrNull(run.startedAt); + const busy = rootAgents.some(({ status }) => isActiveSubagentStatus(status)); + return { + ...card({ + id: node.id, + milestone: null, + title: "Before the plan", + subtitle: "Not in the plan", + state: busy ? "active" : "done", + note: null, + agents: rootAgents, + startMs, + endMs: + Math.max( + startMs ?? 0, + ...rootAgents.map((agent) => msOrNull(agent.completedAt) ?? 0), + ) || null, + }), + row: node.row, + col: node.col, + }; + } + const milestone = byId.get(node.id)!; + const { note, revision } = milestoneDetail(milestone, milestoneItems); + const isDropped = dropped(milestone); + const startMs = msOrNull(milestone.startedAt); + const state = isDropped + ? "dropped" + : milestone.status === "dropped" + ? "dropped" + : milestone.status === "active" && milestone.setId !== currentSetId + ? "done" + : milestone.status; + return { + ...card({ + id: milestone.id, + milestone, + title: milestone.title, + subtitle: subtitleOf(milestone, revision), + subtitleHint: revision?.reason ?? null, + state, + why: isDropped + ? milestone.status === "dropped" + ? note + : "Replaced by the new plan" + : null, + revision, + note: isDropped ? null : note, + agents: agentsOf.get(milestone.id) ?? [], + startMs, + endMs: msOrNull(milestone.completedAt) ?? startMs, + }), + row: node.row, + col: node.col, + }; + }); + edges = layout.edges; + } + + const milestones = nodes.filter((node): node is MapMilestone => node.kind === "milestone"); + const counted = milestones.filter(({ status }) => status !== "dropped"); + const agents = milestones.flatMap(({ groups }) => + flattenAgents(groups.flatMap(({ agents: members }) => members)), + ); + const recorded = [ + ...runs.flatMap((run) => [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 firstRun = runs[0]; + const startMs = + msOrNull(firstRun?.startedAt ?? null) ?? + msOrNull(firstRun?.requestedAt ?? null) ?? + (recorded.length > 0 ? Math.min(...recorded) : input.nowMs); + return { + mode: graph.mode, + title: firstRun === undefined ? null : firstLine(runText(projection, firstRun) ?? "") || null, + nodes, + edges, + maxCol: Math.max(0, ...nodes.map(({ col }) => col)), + live, + coordinatorRun: activeRun ?? runs.at(-1) ?? null, + stats: { + done: counted.filter(({ status }) => status === "done").length, + total: counted.length, + agents: agents.length, + running: agents.filter(({ status }) => status === "running" || status === "needs-you").length, + needsYou: agents.filter(({ ask }) => ask !== null).length, + startMs, + endMs: live ? null : recorded.length > 0 ? Math.max(...recorded) : startMs, + }, + }; +} From de35fa9a42dcadde395c6cf97b86c0f1e55ada44 Mon Sep 17 00:00:00 2001 From: OmarAlex24 Date: Wed, 11 Nov 2026 11:21:27 -0600 Subject: [PATCH 02/10] fix: the work before a plan stays out of the milestone counts Co-Authored-By: Claude Opus 5.5 --- .../src/state/threadMilestoneMap.test.ts | 28 +++++++++++++++++-- .../src/state/threadMilestoneMap.ts | 21 ++++++++------ 2 files changed, 38 insertions(+), 11 deletions(-) diff --git a/packages/client-runtime/src/state/threadMilestoneMap.test.ts b/packages/client-runtime/src/state/threadMilestoneMap.test.ts index 7d0ca783b0b47..d6324ea946027 100644 --- a/packages/client-runtime/src/state/threadMilestoneMap.test.ts +++ b/packages/client-runtime/src/state/threadMilestoneMap.test.ts @@ -16,6 +16,7 @@ import { type AgentAsk, type MapMilestone, agentLine, + BEFORE_PLAN_NODE_ID, deriveMilestoneMap, flattenAgents, layoutMilestoneGraph, @@ -221,7 +222,6 @@ const derive = ( turnItems, asks, coordinatorAsks: false, - nowMs: BASE_MS + 1131_000, })!; /** id, set, in the plan, dropped, started (seconds). */ @@ -432,6 +432,31 @@ describe("deriveMilestoneMap", () => { }); }); + it("puts agents that ran before the first plan on their own node, outside the counts", () => { + const { milestoneId: _unstamped, ...early } = agent("a0", "m1", "completed", 2, 8); + const map = derive( + { ...OAUTH, subagents: [early as never, ...OAUTH.subagents] }, + OAUTH_ITEMS, + OAUTH_ASKS, + ); + expect(rows(map).slice(0, 3)).toEqual([ + ["you", 0], + [BEFORE_PLAN_NODE_ID, 0], + ["m1", 0], + ]); + expect(card(map, BEFORE_PLAN_NODE_ID)).toMatchObject({ + title: "Before the plan", + status: "done", + milestone: null, + rollup: { text: "1 agent done" }, + }); + expect(edges(map).slice(0, 2)).toEqual([ + ["you", BEFORE_PLAN_NODE_ID, "live"], + [BEFORE_PLAN_NODE_ID, "m1", "live"], + ]); + expect(map.stats).toMatchObject({ done: 5, total: 8, agents: 11 }); + }); + it("turns titles started again into detours and forks the next plan from the last of them", () => { const map = derive(TRACE_GROUPS, TRACE_GROUPS_ITEMS); expect(rows(map)).toEqual([ @@ -484,7 +509,6 @@ describe("deriveMilestoneMap", () => { turnItems: [], asks: new Map(), coordinatorAsks: false, - nowMs: BASE_MS, })!; expect(map.mode).toBe("turns"); expect( diff --git a/packages/client-runtime/src/state/threadMilestoneMap.ts b/packages/client-runtime/src/state/threadMilestoneMap.ts index 2789e81df798c..9211c03ed6867 100644 --- a/packages/client-runtime/src/state/threadMilestoneMap.ts +++ b/packages/client-runtime/src/state/threadMilestoneMap.ts @@ -10,6 +10,7 @@ import { copySorted } from "@t3tools/shared/Array"; import type { ThreadStructureTurnItem } from "./models.ts"; import { isActiveSubagentStatus } from "./subagentRuntime.ts"; +import { MILESTONE_BOARD_ROOT } from "./threadMilestoneBoard.ts"; import { deriveThreadMilestoneGraph } from "./threadMilestoneGraph.ts"; import { resolveActiveThreadRun } from "./threadWorkflows.ts"; @@ -262,7 +263,7 @@ export interface MapMilestone { readonly id: string; readonly row: number; readonly col: number; - /** Null for a turn on a thread that never planned. */ + /** Null for a turn on a thread that never planned, and for the work before the first plan. */ readonly milestone: OrchestrationV2Milestone | null; readonly title: string; readonly subtitle: string; @@ -307,7 +308,8 @@ export interface MilestoneMap { readonly agents: number; readonly running: number; readonly needsYou: number; - readonly startMs: number; + /** Null only when nothing has run yet. */ + readonly startMs: number | null; /** Null while the thread is live. */ readonly endMs: number | null; }; @@ -319,7 +321,7 @@ const firstLine = (text: string) => text.trim().split("\n")[0]?.trim() ?? ""; const plural = (count: number, word: string) => `${count} ${count === 1 ? word : `${word}s`}`; const NEW_PLAN_GAP_MS = 10 * 60_000; /** The node for agents that ran before the first plan. */ -const BEFORE_PLAN_NODE_ID = "before-plan"; +export const BEFORE_PLAN_NODE_ID = MILESTONE_BOARD_ROOT; export const flattenAgents = (agents: ReadonlyArray): ReadonlyArray => agents.flatMap((agent) => [agent, ...flattenAgents(agent.children)]); @@ -448,7 +450,7 @@ function groupsOf(agents: ReadonlyArray): ReadonlyArray { function rollup(status: MapStatus, agents: ReadonlyArray): MapMilestone["rollup"] { const all = flattenAgents(agents); if (status === "running" || status === "needs-you") { - const needs = all.filter(({ ask }) => ask !== null).length; + const needs = all.filter(({ status }) => status === "needs-you").length; if (needs > 0) return { tone: "needs-you", text: `${needs} need${needs === 1 ? "s" : ""} you` }; const running = all.filter((agent) => agent.status === "running").length; return { @@ -518,7 +520,6 @@ export function deriveMilestoneMap(input: { readonly asks: ReadonlyMap; /** The coordinator itself waits on you. */ readonly coordinatorAsks: boolean; - readonly nowMs: number; }): MilestoneMap | null { const { projection, asks, environmentId } = input; const graph = deriveThreadMilestoneGraph(projection); @@ -546,7 +547,7 @@ export function deriveMilestoneMap(input: { readonly endMs: number | null; }): Omit => { const agents = buildAgents(fields.agents, asks, environmentId); - const asking = flattenAgents(agents).some(({ ask }) => ask !== null); + const asking = flattenAgents(agents).some(({ status }) => status === "needs-you"); const status: MapStatus = fields.state === "active" ? !live @@ -766,7 +767,9 @@ export function deriveMilestoneMap(input: { } const milestones = nodes.filter((node): node is MapMilestone => node.kind === "milestone"); - const counted = milestones.filter(({ status }) => status !== "dropped"); + const counted = milestones.filter( + (node) => node.status !== "dropped" && (graph.mode === "turns" || node.milestone !== null), + ); const agents = milestones.flatMap(({ groups }) => flattenAgents(groups.flatMap(({ agents: members }) => members)), ); @@ -785,7 +788,7 @@ export function deriveMilestoneMap(input: { const startMs = msOrNull(firstRun?.startedAt ?? null) ?? msOrNull(firstRun?.requestedAt ?? null) ?? - (recorded.length > 0 ? Math.min(...recorded) : input.nowMs); + (recorded.length > 0 ? Math.min(...recorded) : null); return { mode: graph.mode, title: firstRun === undefined ? null : firstLine(runText(projection, firstRun) ?? "") || null, @@ -799,7 +802,7 @@ export function deriveMilestoneMap(input: { total: counted.length, agents: agents.length, running: agents.filter(({ status }) => status === "running" || status === "needs-you").length, - needsYou: agents.filter(({ ask }) => ask !== null).length, + needsYou: agents.filter(({ status }) => status === "needs-you").length, startMs, endMs: live ? null : recorded.length > 0 ? Math.max(...recorded) : startMs, }, From e1032ab85fb6c86242171d72dd39c62266a2ff97 Mon Sep 17 00:00:00 2001 From: OmarAlex24 Date: Wed, 11 Nov 2026 11:47:52 -0600 Subject: [PATCH 03/10] feat: milestones show as a map of plans, detours and the agents on each The view draws milestones down a rail in the order work started, with detours and new plans on their own lanes. Selecting one zooms in and fans its agents and posts out beside it. Asks from subagents move to a dock above the composer, and the timeline view it replaces is gone. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/ChatView.tsx | 14 +- ...er.test.tsx => AgentAsks.browser.test.tsx} | 9 +- apps/web/src/components/chat/AgentAsks.tsx | 287 +++ .../components/chat/ChildThreadApprovals.tsx | 109 -- .../src/components/chat/MilestoneBoard.tsx | 237 --- .../src/components/chat/MilestoneMapCards.tsx | 400 +++++ .../src/components/chat/MilestoneTrace.tsx | 368 ---- .../src/components/chat/SecretRequestCard.tsx | 116 +- .../ThreadMilestonesView.browser.test.tsx | 131 ++ .../components/chat/ThreadMilestonesView.tsx | 1585 +++++++---------- .../src/components/chat/ThreadPlanSection.tsx | 103 +- .../src/components/chat/V2LifecycleRow.tsx | 4 +- .../src/components/chat/milestoneMapLayout.ts | 220 +++ apps/web/src/index.css | 15 +- apps/web/src/threadViewModeStore.ts | 6 +- docs/user/milestones.md | 18 +- packages/client-runtime/package.json | 4 - packages/client-runtime/src/state/models.ts | 12 + .../src/state/threadMilestoneGraph.test.ts | 36 +- .../src/state/threadMilestoneGraph.ts | 54 - .../src/state/threadMilestoneMap.test.ts | 5 +- .../src/state/threadMilestoneMap.ts | 30 +- .../src/state/threadMilestoneTrace.test.ts | 382 ---- .../src/state/threadMilestoneTrace.ts | 629 ------- .../src/state/threadShell.test.ts | 4 + 25 files changed, 1912 insertions(+), 2866 deletions(-) rename apps/web/src/components/chat/{ChildThreadApprovals.browser.test.tsx => AgentAsks.browser.test.tsx} (83%) create mode 100644 apps/web/src/components/chat/AgentAsks.tsx delete mode 100644 apps/web/src/components/chat/ChildThreadApprovals.tsx delete mode 100644 apps/web/src/components/chat/MilestoneBoard.tsx create mode 100644 apps/web/src/components/chat/MilestoneMapCards.tsx delete mode 100644 apps/web/src/components/chat/MilestoneTrace.tsx create mode 100644 apps/web/src/components/chat/ThreadMilestonesView.browser.test.tsx create mode 100644 apps/web/src/components/chat/milestoneMapLayout.ts delete mode 100644 packages/client-runtime/src/state/threadMilestoneTrace.test.ts delete mode 100644 packages/client-runtime/src/state/threadMilestoneTrace.ts diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 5d322f5f9f310..4c6ced71fd5c7 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1,4 +1,4 @@ -import { ChildThreadApprovals } from "./chat/ChildThreadApprovals"; +import { AgentAsks, type CoordinatorAsk } from "./chat/AgentAsks"; import { workspaceAreaProps } from "../lib/workspaceFocus"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; @@ -75,6 +75,7 @@ import { type ScopedThreadRef, type ThreadId, type OrchestrationV2Milestone, + type OrchestrationV2Subagent, ProviderInteractionMode, resolveIdleCompaction, RuntimeMode, @@ -396,7 +397,6 @@ 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, @@ -418,6 +418,8 @@ const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray = []; const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = []; const EMPTY_TURN_ITEMS: ThreadStructure["turnItems"] = []; const EMPTY_RUNS: ThreadStructure["runs"] = []; +const EMPTY_SUBAGENTS: ReadonlyArray = []; +const EMPTY_MILESTONES: ReadonlyArray = []; const EMPTY_AUTO_UPDATE_ENVIRONMENTS: ReadonlyArray = []; const EMPTY_COMPOSER_BANNER_ITEMS: ReadonlyArray = []; @@ -3745,6 +3747,7 @@ export default function ChatView(props: ChatViewProps) { {showMilestones && activeThreadRef !== null ? ( - +
({ respond: vi.fn(), approvalsAtom: null as unkno vi.mock("../../state/session", () => ({ useEnvironmentScope: () => true })); vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.respond })); vi.mock("./SecretRequestCard", () => ({ SecretRequestCard: () => null })); +vi.mock("./LinkRequestCard", () => ({ LinkRequestCard: () => null })); +vi.mock("./MilestoneMapCards", () => ({ ProviderTile: () => null })); +vi.mock("../../state/entities", () => ({ useChildThreadInputs: () => [] })); vi.mock("../../state/threads", () => ({ childThreadApprovalsAtom: () => state.approvalsAtom, childThreadSecretRequestsAtom: () => Atom.make([]), threadEnvironment: { respondToApproval: {} }, })); -import { ChildThreadApprovals } from "./ChildThreadApprovals"; +import { AgentAsks } from "./AgentAsks"; function setup() { state.respond.mockReset(); @@ -46,7 +49,9 @@ function setup() { it("shows a failed decision and clears the error when the user retries", async () => { const thread = setup(); - await using screen = await render(); + await using screen = await render( + , + ); await screen.getByRole("button", { name: "Approve", exact: true }).click(); await expect.element(screen.getByRole("alert")).toHaveTextContent("Child environment offline"); await screen.getByRole("button", { name: "Approve", exact: true }).click(); diff --git a/apps/web/src/components/chat/AgentAsks.tsx b/apps/web/src/components/chat/AgentAsks.tsx new file mode 100644 index 0000000000000..a80f5e31b6b67 --- /dev/null +++ b/apps/web/src/components/chat/AgentAsks.tsx @@ -0,0 +1,287 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import type { LinkRequestItem } from "@t3tools/client-runtime/link-request"; +import type { SecretRequestItem } from "@t3tools/client-runtime/secret-request"; +import { agentThreadRef, type AgentAsk } from "@t3tools/client-runtime/state/thread-milestone-map"; +import type { ChildThreadApproval } from "@t3tools/client-runtime/state/thread-requests"; +import { fullAccessOverrideExplanation } from "@t3tools/client-runtime/state/thread-requests"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { + AuthOrchestrationOperateScope, + type OrchestrationV2Milestone, + type OrchestrationV2Subagent, + type ScopedThreadRef, +} from "@t3tools/contracts"; +import { formatModelSlugName } from "@t3tools/shared/model"; +import { useState } from "react"; +import { flushSync } from "react-dom"; +import { create } from "zustand"; + +import { cn } from "~/lib/utils"; +import { useChildThreadInputs } from "../../state/entities"; +import { useEnvironmentScope } from "../../state/session"; +import { + childThreadApprovalsAtom, + childThreadSecretRequestsAtom, + threadEnvironment, +} from "../../state/threads"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions"; +import { LinkRequestCard } from "./LinkRequestCard"; +import { ProviderTile } from "./MilestoneMapCards"; +import { SecretRequestCard, type SecretRequestAttribution } from "./SecretRequestCard"; + +/** What the coordinator is asking you right now, shown on the milestone it is working on. */ +export type CoordinatorAsk = + | { readonly kind: "input"; readonly question: string | null } + | { readonly kind: "approval" } + /** A secret or link card is answered in place, never in the composer. */ + | { readonly kind: "card"; readonly item: SecretRequestItem | LinkRequestItem }; + +/** The ask an agent card's Answer picked, so the dock opens and flashes it. */ +const useAskFocusStore = create<{ readonly key: string | null; readonly nonce: number }>(() => ({ + key: null, + nonce: 0, +})); + +/** Opens the ask of the agent thread `key` in the dock and moves focus to its answer. */ +export function focusAgentAsk(key: string) { + flushSync(() => useAskFocusStore.setState((state) => ({ key, nonce: state.nonce + 1 }))); + const row = document.querySelector(`[data-agent-ask="${CSS.escape(key)}"]`); + row + ?.querySelector("input:not(:disabled), [data-ask-actions] button:not(:disabled)") + ?.focus(); +} + +/** What each of the thread's agents waits on you for, by the agent thread's key. */ +export function useAgentAsks(threadRef: ScopedThreadRef): ReadonlyMap { + const inputs = useChildThreadInputs(threadRef); + const approvals = useAtomValue(childThreadApprovalsAtom(threadRef)); + const secrets = useAtomValue(childThreadSecretRequestsAtom(threadRef)); + const asks = new Map(); + for (const child of inputs) { + if (child.hasPendingUserInput) { + asks.set(scopedThreadKey({ environmentId: child.environmentId, threadId: child.id }), { + kind: "input", + }); + } + } + for (const { thread, approval } of approvals) { + asks.set(scopedThreadKey(thread), { kind: "approval", command: approval.detail || null }); + } + for (const { thread, item } of secrets) { + asks.set(scopedThreadKey(thread), { kind: "secret", label: item.label }); + } + return asks; +} + +type Attribution = SecretRequestAttribution; + +function attributionOf( + thread: ScopedThreadRef, + fallbackTitle: string, + subagents: ReadonlyArray, + milestones: ReadonlyArray, +): Attribution { + const key = scopedThreadKey(thread); + const subagent = + subagents.findLast((agent) => { + const ref = agentThreadRef(agent, thread.environmentId); + return ref !== null && scopedThreadKey(ref) === key; + }) ?? null; + const milestone = + subagent?.milestoneId === undefined + ? undefined + : milestones.find(({ id }) => id === subagent.milestoneId); + return { + icon: , + title: subagent?.title ?? fallbackTitle, + subtitle: [subagent?.model ? formatModelSlugName(subagent.model) : null, milestone?.title] + .filter(Boolean) + .join(" · "), + }; +} + +function ApprovalRow({ + entry, + attribution, + flash, +}: { + entry: ChildThreadApproval; + attribution: Attribution; + flash: boolean; +}) { + const canRespond = useEnvironmentScope(entry.thread.environmentId, AuthOrchestrationOperateScope); + const respond = useAtomCommand(threadEnvironment.respondToApproval, { reportFailure: false }); + const [responding, setResponding] = useState(false); + const [error, setError] = useState(null); + const { approval } = entry; + const notes = [ + approval.appName ?? null, + approval.responseCapability === "live" + ? null + : "Provider process is gone. Interrupt or restart the child thread to respond.", + approval.reason ?? null, + approval.fullAccessOverride ? fullAccessOverrideExplanation(approval.fullAccessOverride) : null, + ].filter((note) => note !== null); + return ( +
+
+ {attribution.icon} + + {attribution.title}{" "} + {approval.detail ? ( + <> + wants to run{" "} + + {approval.detail} + + + ) : ( + <>needs approval for {approval.requestKind} + )} + + + { + if (!canRespond || responding) return; + setResponding(true); + setError(null); + const result = await respond({ + environmentId: entry.thread.environmentId, + input: { threadId: entry.thread.threadId, requestId, decision }, + }); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const failure = squashAtomCommandFailure(result); + setError( + failure instanceof Error + ? failure.message + : "Failed to submit approval decision.", + ); + } + setResponding(false); + return result; + }} + /> + +
+ {notes.map((note) => ( +

+ {note} +

+ ))} + {error !== null ? ( +

+ {error} +

+ ) : null} +
+ ); +} + +function AgentSecret(props: { + readonly askKey: string; + readonly environmentId: ScopedThreadRef["environmentId"]; + readonly item: SecretRequestItem; + readonly attribution: Attribution; + readonly flash: boolean; +}) { + const nonce = useAskFocusStore((state) => (state.key === props.askKey ? state.nonce : 0)); + const [collapsedAt, setCollapsedAt] = useState(null); + return ( + setCollapsedAt(useAskFocusStore.getState().nonce)} + onExpand={() => focusAgentAsk(props.askKey)} + /> + ); +} + +/** + * Asks waiting on you above the composer: each agent's secret, then each approval as one row, + * named after the agent and its milestone. A coordinator card joins them while Chat is hidden. + */ +export function AgentAsks(props: { + readonly threadRef: ScopedThreadRef | null; + readonly subagents: ReadonlyArray; + readonly milestones: ReadonlyArray; + readonly coordinatorCard: SecretRequestItem | LinkRequestItem | null; +}) { + const approvals = useAtomValue(childThreadApprovalsAtom(props.threadRef)); + const secrets = useAtomValue(childThreadSecretRequestsAtom(props.threadRef)); + const flashKey = useAskFocusStore((state) => state.key); + const card = props.coordinatorCard; + if (approvals.length === 0 && secrets.length === 0 && card === null) return null; + const attribution = (thread: ScopedThreadRef, title: string) => + attributionOf(thread, title, props.subagents, props.milestones); + return ( +
+ {card === null || props.threadRef === null ? null : card.type === "secret_request" ? ( + + ) : ( + + )} + {secrets.map((entry) => { + const key = scopedThreadKey(entry.thread); + return ( +
+ +
+ ); + })} + {approvals.map((entry) => { + const key = scopedThreadKey(entry.thread); + return ( +
+ +
+ ); + })} +
+ ); +} diff --git a/apps/web/src/components/chat/ChildThreadApprovals.tsx b/apps/web/src/components/chat/ChildThreadApprovals.tsx deleted file mode 100644 index 1c69fba07f444..0000000000000 --- a/apps/web/src/components/chat/ChildThreadApprovals.tsx +++ /dev/null @@ -1,109 +0,0 @@ -import { useAtomValue } from "@effect/atom-react"; -import { AuthOrchestrationOperateScope, type ScopedThreadRef } from "@t3tools/contracts"; -import type { ChildThreadApproval } from "@t3tools/client-runtime/state/thread-requests"; -import { fullAccessOverrideExplanation } from "@t3tools/client-runtime/state/thread-requests"; -import { - isAtomCommandInterrupted, - squashAtomCommandFailure, -} from "@t3tools/client-runtime/state/runtime"; -import { useState } from "react"; -import { useEnvironmentScope } from "../../state/session"; -import { - childThreadApprovalsAtom, - childThreadSecretRequestsAtom, - threadEnvironment, -} from "../../state/threads"; -import { useAtomCommand } from "../../state/use-atom-command"; -import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions"; -import { SecretRequestCard } from "./SecretRequestCard"; - -function ChildApproval({ entry }: { entry: ChildThreadApproval }) { - const canRespond = useEnvironmentScope(entry.thread.environmentId, AuthOrchestrationOperateScope); - const respond = useAtomCommand(threadEnvironment.respondToApproval, { reportFailure: false }); - const [responding, setResponding] = useState(false); - const [error, setError] = useState(null); - const { approval } = entry; - return ( -
-

Approval needed from {entry.title}

-
-        {approval.detail || approval.requestKind}
-      
- {approval.appName ?

{approval.appName}

: null} - {approval.responseCapability !== "live" ? ( -

- Provider process is gone. Interrupt or restart the child thread to respond. -

- ) : null} - {approval.reason ?

{approval.reason}

: null} - {approval.fullAccessOverride ? ( -

- {fullAccessOverrideExplanation(approval.fullAccessOverride)} -

- ) : null} -
- { - if (!canRespond || responding) return; - setResponding(true); - setError(null); - const result = await respond({ - environmentId: entry.thread.environmentId, - input: { threadId: entry.thread.threadId, requestId, decision }, - }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const failure = squashAtomCommandFailure(result); - setError( - failure instanceof Error ? failure.message : "Failed to submit approval decision.", - ); - } - setResponding(false); - return result; - }} - /> -
- {error !== null ? ( -

- {error} -

- ) : null} -
- ); -} - -export function ChildThreadApprovals({ threadRef }: { threadRef: ScopedThreadRef | null }) { - const approvals = useAtomValue(childThreadApprovalsAtom(threadRef)); - const secrets = useAtomValue(childThreadSecretRequestsAtom(threadRef)); - if (approvals.length === 0 && secrets.length === 0) return null; - return ( -
- {secrets.map((entry) => ( - - ))} - {approvals.map((entry) => ( - - ))} -
- ); -} diff --git a/apps/web/src/components/chat/MilestoneBoard.tsx b/apps/web/src/components/chat/MilestoneBoard.tsx deleted file mode 100644 index 416c348f009e0..0000000000000 --- a/apps/web/src/components/chat/MilestoneBoard.tsx +++ /dev/null @@ -1,237 +0,0 @@ -import type { LinkRequestItem } from "@t3tools/client-runtime/link-request"; -import type { SecretRequestItem } from "@t3tools/client-runtime/secret-request"; -import type { MilestoneBoardItem } from "@t3tools/client-runtime/state/thread-milestone-board"; -import type { ChatImageAttachment, EnvironmentId } from "@t3tools/contracts"; -import { - AppWindowIcon, - CornerDownLeftIcon, - MessageSquareIcon, - MessageSquarePlusIcon, - StickyNoteIcon, - TriangleAlertIcon, -} from "lucide-react"; -import { useState } from "react"; - -import { useAssetUrls } from "../../assets/assetUrls"; -import { Button } from "../ui/button"; -import { LinkRequestCard } from "./LinkRequestCard"; -import { SecretRequestCard } from "./SecretRequestCard"; - -/** What the coordinator is asking you right now, shown on the milestone it is working on. */ -export type CoordinatorAsk = - | { readonly kind: "input"; readonly question: string | null } - | { readonly kind: "approval" } - /** A secret or link card is answered in place, never in the composer. */ - | { readonly kind: "card"; readonly item: SecretRequestItem | LinkRequestItem }; - -/** How many board items show before the older ones fold. */ -const BOARD_LIMIT = 4; - -const BOARD_KINDS = [ - { kind: "post", icon: StickyNoteIcon, label: "post" }, - { kind: "visual", icon: AppWindowIcon, label: "visual" }, - { kind: "comment", icon: MessageSquareIcon, label: "comment" }, -] as const; - -/** Counts per kind, such as "3 posts · 1 visual", for headers and folded milestones. */ -export function boardCounts(items: ReadonlyArray) { - return BOARD_KINDS.flatMap(({ kind, icon, label }) => { - const count = items.filter((item) => item.kind === kind).length; - return count === 0 - ? [] - : [{ kind, icon, text: `${count} ${count === 1 ? label : `${label}s`}` }]; - }); -} - -function AskHeading() { - return ( -
- - Coordinator asks you -
- ); -} - -export function CoordinatorAskCard(props: { - readonly environmentId: EnvironmentId; - readonly ask: CoordinatorAsk; - readonly onAnswerInChat: () => void; -}) { - if (props.ask.kind === "card") { - const { item } = props.ask; - return ( -
- - {item.type === "secret_request" ? ( - - ) : ( - - )} -
- ); - } - const question = props.ask.kind === "input" ? props.ask.question : null; - return ( -
- - {question === null ? null :

{question}

} -
- {props.ask.kind === "approval" ? ( - <> - It needs your approval to continue. - - - ) : ( - Answer in the composer below. - )} -
-
- ); -} - -function PostImages(props: { - readonly environmentId: EnvironmentId; - readonly attachments: ReadonlyArray; -}) { - const urls = useAssetUrls( - props.environmentId, - props.attachments.map((attachment) => ({ - _tag: "attachment" as const, - attachmentId: attachment.id, - })), - ); - return ( -
- {props.attachments.map((attachment, index) => { - const url = urls[index]; - return ( - - {url ? ( - {attachment.name} - ) : null} - - ); - })} -
- ); -} - -type Block = - | { - readonly kind: "visuals"; - readonly items: ReadonlyArray; - } - | { readonly kind: "single"; readonly item: MilestoneBoardItem }; - -/** Visuals in a row share a grid; posts and comments stand alone. */ -function blocksOf(items: ReadonlyArray): ReadonlyArray { - const blocks: Array = []; - for (const item of items) { - const last = blocks.at(-1); - if (item.kind === "visual" && last?.kind === "visuals") { - blocks[blocks.length - 1] = { kind: "visuals", items: [...last.items, item] }; - } else if (item.kind === "visual") { - blocks.push({ kind: "visuals", items: [item] }); - } else { - blocks.push({ kind: "single", item }); - } - } - return blocks; -} - -/** - * A milestone's board: the coordinator's posts and visuals and your comments, newest last, with - * older items folded. Visuals open where they rendered in Chat rather than mounting a frame here. - */ -export function MilestoneBoard(props: { - readonly environmentId: EnvironmentId; - readonly items: ReadonlyArray; - readonly onJump: (entryId: string) => void; -}) { - const [showAll, setShowAll] = useState(false); - if (props.items.length === 0) return null; - const hidden = showAll ? 0 : Math.max(0, props.items.length - BOARD_LIMIT); - return ( -
- {props.items.length > BOARD_LIMIT ? ( - - ) : null} - {blocksOf(props.items.slice(hidden)).map((block) => - block.kind === "visuals" ? ( -
-
- {block.items.map((item) => ( - - ))} -
-
- ) : block.item.kind === "post" ? ( -
-
Coordinator
- {block.item.text === null ? null : ( -

{block.item.text}

- )} - {block.item.attachments.length === 0 ? null : ( - - )} -
- ) : block.item.kind === "comment" ? ( -
-
You · sent to the coordinator
-

{block.item.text}

-
- ) : null, - )} -
- ); -} - -export function CommentButton(props: { readonly onComment: () => void }) { - return ( - - ); -} diff --git a/apps/web/src/components/chat/MilestoneMapCards.tsx b/apps/web/src/components/chat/MilestoneMapCards.tsx new file mode 100644 index 0000000000000..62a826acee360 --- /dev/null +++ b/apps/web/src/components/chat/MilestoneMapCards.tsx @@ -0,0 +1,400 @@ +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; +import { + actionLine, + agentLine, + agentThreadRef, + type MapAgent, + type MapMilestone, + type MapRollupTone, + type MapStatus, +} from "@t3tools/client-runtime/state/thread-milestone-map"; +import type { ProviderDriverKind, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; +import { formatModelSlugName } from "@t3tools/shared/model"; +import * as DateTime from "effect/DateTime"; +import { + BotIcon, + CheckIcon, + CircleCheckIcon, + CircleXIcon, + ClockIcon, + LoaderCircleIcon, + UserIcon, + XIcon, +} from "lucide-react"; +import type { CSSProperties } from "react"; + +import { cn } from "~/lib/utils"; +import { useThreadShell } from "../../state/entities"; +import { Badge } from "../ui/badge"; +import { Button } from "../ui/button"; +import { AgentElapsed } from "./AgentElapsed"; +import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; +import { useSubagentLink } from "./V2LifecycleRow"; + +const iso = (ms: number | null) => + ms === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ms)); + +export function ProviderTile(props: { + readonly driver: ProviderDriverKind | null; + readonly size?: "md" | "sm" | "xs"; +}) { + const size = props.size ?? "md"; + return ( + + {props.driver === null ? ( + + ) : ( + + )} + + ); +} + +const BADGES: Record< + MapStatus, + { + readonly label: string; + readonly variant: "info" | "success" | "warning" | "error" | "secondary"; + readonly icon: typeof CheckIcon | null; + } +> = { + running: { label: "Running", variant: "info", icon: LoaderCircleIcon }, + done: { label: "Done", variant: "success", icon: CheckIcon }, + "needs-you": { label: "Needs you", variant: "warning", icon: ClockIcon }, + failed: { label: "Failed", variant: "error", icon: XIcon }, + planned: { label: "Planned", variant: "secondary", icon: null }, + dropped: { label: "Dropped", variant: "secondary", icon: null }, + stopped: { label: "Stopped", variant: "secondary", icon: null }, +}; + +function MapStatusBadge(props: { readonly status: MapStatus }) { + const { label, variant, icon: Icon } = BADGES[props.status]; + return ( + + {Icon === null ? null : } + {label} + + ); +} + +/** The milestone's status as a small mark, for lists. */ +export function MilestoneStatusIcon(props: { readonly status: MapStatus }) { + switch (props.status) { + case "done": + return ( + + + + ); + case "running": + case "needs-you": + return ( + + + + ); + case "failed": + return ( + + + + ); + case "dropped": + case "stopped": + return ( + + + + ); + case "planned": + return ( + + ); + } +} + +export function RailDot(props: { + readonly status: MapStatus | "you"; + readonly style: CSSProperties; +}) { + return ( + + ); +} + +const ROLLUP_ICON: Record = { + "needs-you": ClockIcon, + running: LoaderCircleIcon, + none: UserIcon, + failed: CircleXIcon, + done: CircleCheckIcon, +}; + +const cardClass = + "absolute flex flex-col justify-between rounded-xl border bg-card shadow-xs/5 transition-[opacity,box-shadow] duration-200 motion-reduce:transition-none"; + +/** The coordinator's latest step, for the milestone it is working on now. */ +function CoordinatorLine(props: { + readonly threadRef: ScopedThreadRef; + readonly fallback: string | null; +}) { + const shell = useThreadShell(props.threadRef); + return <>{actionLine(shell?.latestAction) ?? props.fallback ?? ""}; +} + +export function MilestoneCard(props: { + readonly node: MapMilestone; + readonly threadRef: ScopedThreadRef; + readonly lead: ProviderDriverKind | null; + readonly style: CSSProperties; + readonly selected: boolean; + readonly faded: boolean; + readonly onSelect: () => void; +}) { + const { node } = props; + const label = `Zoom into ${node.title}`; + const fade = props.faded && "opacity-42"; + if (!node.started) { + const dropped = node.status === "dropped"; + return ( + + ); + } + const RollupIcon = ROLLUP_ICON[node.rollup.tone]; + return ( + + ); +} + +function AgentTask(props: { readonly entry: MapAgent; readonly threadRef: ScopedThreadRef }) { + const ref = agentThreadRef(props.entry.agent, props.threadRef.environmentId); + const shell = useThreadShell(ref); + const line = agentLine(props.entry.ask, shell?.latestAction); + return {line}; +} + +export function AgentCard(props: { + readonly entry: MapAgent; + readonly threadRef: ScopedThreadRef; + readonly style: CSSProperties; + readonly width: number; + readonly onOpenThread: (threadId: ThreadId) => void; + readonly onAnswer: (threadKey: string) => void; +}) { + const { entry } = props; + const { agent } = entry; + const title = formatSubagentDisplayTitle(agent.title ?? "Subagent"); + const ref = agentThreadRef(agent, props.threadRef.environmentId); + const link = useSubagentLink({ + parentRef: props.threadRef, + subagentId: agent.id, + providerInstanceId: agent.providerInstanceId, + origin: agent.origin, + status: agent.status, + driver: agent.driver, + title, + result: agent.result, + progress: agent.progress, + startedAt: agent.startedAt, + completedAt: agent.completedAt, + threadId: agent.childThreadId, + remote: agent.remoteChild, + onOpenThread: props.onOpenThread, + }); + // A question in the agent's own chat is answered there; secrets and approvals in the dock. + const answer = + entry.ask === null + ? null + : entry.ask.kind === "input" || ref === null + ? link.open + : () => props.onAnswer(scopedThreadKey(ref)); + return ( +
+
+ +
+ {link.open === null ? ( + {title} + ) : ( + + )} + + {[ + agent.model ? formatModelSlugName(agent.model) : null, + link.remote ? `on ${link.remote.label}` : null, + ] + .filter(Boolean) + .join(" · ")} + +
+ +
+
+ {agent.group === undefined ? null : ( + + {agent.group} + + )} + +
+
+ + + + + {answer !== null ? ( + + ) : entry.retry ? ( + Second try + ) : null} +
+
+ ); +} diff --git a/apps/web/src/components/chat/MilestoneTrace.tsx b/apps/web/src/components/chat/MilestoneTrace.tsx deleted file mode 100644 index 0c83dac8208fb..0000000000000 --- a/apps/web/src/components/chat/MilestoneTrace.tsx +++ /dev/null @@ -1,368 +0,0 @@ -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/SecretRequestCard.tsx b/apps/web/src/components/chat/SecretRequestCard.tsx index b6cdabb8a7b69..93d10f7159d62 100644 --- a/apps/web/src/components/chat/SecretRequestCard.tsx +++ b/apps/web/src/components/chat/SecretRequestCard.tsx @@ -22,22 +22,51 @@ import type { SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; -import { CheckIcon, ExternalLinkIcon, LockIcon, MinusIcon, ShieldCheckIcon } from "lucide-react"; -import { useId, useRef, useState, type FormEvent } from "react"; +import { + CheckIcon, + ChevronDownIcon, + ClockIcon, + ExternalLinkIcon, + LockIcon, + MinusIcon, + ShieldCheckIcon, +} from "lucide-react"; +import { type FormEvent, type ReactNode, useId, useRef, useState } from "react"; +import { cn } from "~/lib/utils"; import { isSecretsFeatureEnabled } from "../../env"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; +import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { SecretSourceSelect } from "../settings/SecretSourceInput"; import { WorkLogRow } from "./WorkLog"; -export function SecretRequestCard(props: { - readonly environmentId: EnvironmentId; - readonly item: SecretRequestItem; - readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"]; -}) { +/** Who is asking, for a card shown away from the thread that asked. */ +export interface SecretRequestAttribution { + readonly icon: ReactNode; + readonly title: string; + readonly subtitle: string; +} + +interface CardChrome { + readonly attribution?: SecretRequestAttribution | undefined; + /** Points the card out after you chose to answer it elsewhere. */ + readonly flash?: boolean | undefined; + /** Folds the card to its header and an Answer button; the draft survives. */ + readonly collapsed?: boolean | undefined; + readonly onCollapse?: (() => void) | undefined; + readonly onExpand?: (() => void) | undefined; +} + +export function SecretRequestCard( + props: { + readonly environmentId: EnvironmentId; + readonly item: SecretRequestItem; + readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"]; + } & CardChrome, +) { const { item } = props; const display = secretRequestDisplay(item, props.visibility); if (display.kind === "answered" || display.kind === "pending-elsewhere") { @@ -59,7 +88,29 @@ export function SecretRequestCard(props: { /> ); } - return ; + return ; +} + +function AttributionHeader(props: { + readonly attribution: SecretRequestAttribution; + readonly children: ReactNode; +}) { + return ( +
+ {props.attribution.icon} +
+ + {props.attribution.title} + + {props.attribution.subtitle ? ( + + {props.attribution.subtitle} + + ) : null} +
+ {props.children} +
+ ); } const NO_SOURCES: ReadonlyArray = []; @@ -71,10 +122,12 @@ function useSecretRequestSources(environmentId: EnvironmentId) { : NO_SOURCES; } -function PendingSecretRequestForm(props: { - readonly environmentId: EnvironmentId; - readonly item: SecretRequestItem; -}) { +function PendingSecretRequestForm( + props: { + readonly environmentId: EnvironmentId; + readonly item: SecretRequestItem; + } & CardChrome, +) { const { item } = props; const inputId = useId(); const errorId = useId(); @@ -128,11 +181,29 @@ function PendingSecretRequestForm(props: { const draft = source === null ? secret : reference; const link = secretRequestLink(item); const describedBy = error !== null ? `${privacyId} ${errorId}` : privacyId; + const { attribution } = props; + const frame = cn( + "flex min-w-0 flex-col rounded-xl border bg-card", + attribution === undefined ? "gap-3 border-border/60 p-4" : "gap-2.75 p-3 pb-2.5 shadow-lg/5", + props.flash && "border-warning/60", + ); + + if (attribution !== undefined && props.collapsed) { + return ( +
+ + + +
+ ); + } return (
+ {attribution === undefined ? null : ( + + + + Needs you + + {props.onCollapse === undefined ? null : ( + + )} + + )}