feat(web): render workflow runs as inline timeline cards
A workflow previously appeared in the timeline as a bare subagent row per coordinator and per member — no phases, no live status, and each member double-reported as its own row. The coordinator's subagent item now renders as a run card: phase-grouped member rows with live status dots, a settled/total rollup, token usage, and a Details button that opens the Agents panel. Members of a present coordinator render nothing (the card already shows them); members orphaned by a missing coordinator keep their row rather than disappearing. Remote runs render their session link instead of member rows, re-checked against the http(s) allowlist as defense in depth for payloads persisted before the adapter-side filter. Rows cap at 8, keeping running and failed agents plus the most recently updated; the remainder defers to the Agents panel. Live subagents ride a dedicated context rather than TimelineRowCtx so progress-tick churn re-renders only subagent rows, not the whole list. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
04a12b8f1f
commit
2ac7918f5a
6 files changed
+825
-45
No files matched your search
@@ -342,6 +342,7 @@ const EMPTY_PROVIDERS: ServerProvider[] = [];
|
||||
const VISIT_DISPATCH_THROTTLE_MS = 10_000;
|
||||
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
|
||||
const EMPTY_PROJECTION_RUNS: OrchestrationV2ThreadProjection["runs"] = [];
|
||||
const EMPTY_PROJECTION_SUBAGENTS: OrchestrationV2ThreadProjection["subagents"] = [];
|
||||
const EMPTY_ATTACHMENT_IDS: string[] = [];
|
||||
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
|
||||
|
||||
@@ -6280,6 +6281,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
skills={activeProviderStatus?.skills ?? EMPTY_PROVIDER_SKILLS}
|
||||
providerStatuses={providerStatuses}
|
||||
runs={serverProjection?.runs ?? EMPTY_PROJECTION_RUNS}
|
||||
subagents={serverProjection?.subagents ?? EMPTY_PROJECTION_SUBAGENTS}
|
||||
onOpenAgentsPanel={addAgentsSurface}
|
||||
anchorMessageId={timelineAnchorMessageId}
|
||||
onAnchorReady={onTimelineAnchorReady}
|
||||
onAnchorSizeChanged={onTimelineAnchorSizeChanged}
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import {
|
||||
NodeId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
type OrchestrationV2Subagent,
|
||||
} from "@t3tools/contracts";
|
||||
import { deriveOrchestrationV2WorkflowRunCard } from "@t3tools/client-runtime/state/orchestration-v2-subagents";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { WorkflowRunCardV2, safeWorkflowSessionUrl } from "./WorkflowRunCardV2";
|
||||
|
||||
const now = DateTime.makeUnsafe("2026-07-26T00:00:00.000Z");
|
||||
const workflowId = NodeId.make("workflow-1");
|
||||
|
||||
const agent = (id: string, input: Partial<OrchestrationV2Subagent> = {}): OrchestrationV2Subagent =>
|
||||
({
|
||||
id: NodeId.make(id),
|
||||
threadId: ThreadId.make("thread-test"),
|
||||
runId: RunId.make("run-test"),
|
||||
parentNodeId: NodeId.make("root-node"),
|
||||
origin: "provider_native",
|
||||
createdBy: "agent",
|
||||
driver: ProviderDriverKind.make("claudeAgent"),
|
||||
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
providerThreadId: null,
|
||||
childThreadId: null,
|
||||
nativeTaskRef: null,
|
||||
prompt: "Work",
|
||||
title: id,
|
||||
model: "claude-opus-4-1",
|
||||
kind: "subagent",
|
||||
role: { name: "general-purpose", source: "provider" },
|
||||
status: "running",
|
||||
result: null,
|
||||
usage: null,
|
||||
currentActivationId: null,
|
||||
activationCount: 1,
|
||||
workflow: null,
|
||||
workflowMembership: null,
|
||||
recentActivity: [],
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
updatedAt: now,
|
||||
...input,
|
||||
}) as OrchestrationV2Subagent;
|
||||
|
||||
const membership = (agentIndex: number, phaseIndex: number | null) => ({
|
||||
workflowSubagentId: workflowId,
|
||||
agentIndex,
|
||||
phaseIndex,
|
||||
attempt: 1,
|
||||
});
|
||||
|
||||
const renderCard = (subagents: ReadonlyArray<OrchestrationV2Subagent>) => {
|
||||
const card = deriveOrchestrationV2WorkflowRunCard({ coordinatorId: workflowId, subagents });
|
||||
if (card === null) throw new Error("expected a workflow run card");
|
||||
return renderToStaticMarkup(<WorkflowRunCardV2 card={card} />);
|
||||
};
|
||||
|
||||
describe("WorkflowRunCardV2", () => {
|
||||
const coordinator = agent("workflow-1", {
|
||||
kind: "workflow",
|
||||
title: "Research and implement",
|
||||
status: "running",
|
||||
usage: { totalTokens: 1500 },
|
||||
workflow: {
|
||||
phases: [
|
||||
{ index: 0, title: "Research" },
|
||||
{ index: 1, title: "Implement" },
|
||||
],
|
||||
name: "research-implement",
|
||||
},
|
||||
});
|
||||
|
||||
it("renders phases, member rows, and the usage rollup", () => {
|
||||
const html = renderCard([
|
||||
coordinator,
|
||||
agent("member-research", {
|
||||
kind: "workflow_agent",
|
||||
title: "Researcher",
|
||||
status: "completed",
|
||||
usage: { totalTokens: 400 },
|
||||
workflowMembership: membership(0, 0),
|
||||
}),
|
||||
agent("member-implement", {
|
||||
kind: "workflow_agent",
|
||||
title: "Implementer",
|
||||
status: "running",
|
||||
usage: { totalTokens: 500 },
|
||||
workflowMembership: membership(1, 1),
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(html).toContain("Research and implement");
|
||||
expect(html).toContain("Research");
|
||||
expect(html).toContain("Implement");
|
||||
expect(html).toContain("Researcher");
|
||||
expect(html).toContain("Implementer");
|
||||
expect(html).toContain("1/2 agents");
|
||||
expect(html).toContain("1.5k tok");
|
||||
expect(html).toContain('data-workflow-status="running"');
|
||||
});
|
||||
|
||||
it("shows failed member rows with their error text and a failed chip on the coordinator", () => {
|
||||
const html = renderCard([
|
||||
agent("workflow-1", {
|
||||
...coordinator,
|
||||
status: "failed",
|
||||
}),
|
||||
agent("member-broken", {
|
||||
kind: "workflow_agent",
|
||||
title: "Broken agent",
|
||||
status: "failed",
|
||||
result: "TypeError: cannot read x",
|
||||
workflowMembership: membership(0, 0),
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(html).toContain('data-workflow-status="failed"');
|
||||
expect(html).toContain("TypeError: cannot read x");
|
||||
});
|
||||
|
||||
it("caps member rows and reports the hidden remainder", () => {
|
||||
const members = Array.from({ length: 11 }, (_, index) =>
|
||||
agent(`member-${index}`, {
|
||||
kind: "workflow_agent",
|
||||
title: `Agent ${index}`,
|
||||
status: "completed",
|
||||
workflowMembership: membership(index, 0),
|
||||
}),
|
||||
);
|
||||
const html = renderCard([
|
||||
agent("workflow-1", {
|
||||
...coordinator,
|
||||
workflow: { phases: [{ index: 0, title: "Sweep" }], name: "sweep" },
|
||||
}),
|
||||
...members,
|
||||
]);
|
||||
|
||||
expect(html).toContain("+3 more agents");
|
||||
});
|
||||
|
||||
it("renders a remote run as a session link instead of member rows", () => {
|
||||
const html = renderCard([
|
||||
agent("workflow-1", {
|
||||
...coordinator,
|
||||
workflow: {
|
||||
phases: [],
|
||||
name: "remote-run",
|
||||
sessionUrl: "https://claude.ai/session/abc",
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(html).toContain("Running in the cloud");
|
||||
expect(html).toContain('href="https://claude.ai/session/abc"');
|
||||
});
|
||||
|
||||
it("shows the coordinator warning when present", () => {
|
||||
const html = renderCard([
|
||||
agent("workflow-1", {
|
||||
...coordinator,
|
||||
workflow: {
|
||||
phases: [],
|
||||
name: "warned",
|
||||
warning: "workflow exceeded the size guideline",
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(html).toContain("workflow exceeded the size guideline");
|
||||
});
|
||||
});
|
||||
|
||||
describe("safeWorkflowSessionUrl", () => {
|
||||
it("only lets web URLs through", () => {
|
||||
expect(safeWorkflowSessionUrl("https://claude.ai/session/abc")).toBe(
|
||||
"https://claude.ai/session/abc",
|
||||
);
|
||||
expect(safeWorkflowSessionUrl("http://localhost:3000/run")).toBe("http://localhost:3000/run");
|
||||
// A hostile payload persisted before the adapter-side filter existed
|
||||
// must not reach an anchor href.
|
||||
expect(safeWorkflowSessionUrl("javascript:alert(1)")).toBeUndefined();
|
||||
expect(safeWorkflowSessionUrl("file:///etc/passwd")).toBeUndefined();
|
||||
expect(safeWorkflowSessionUrl("not a url")).toBeUndefined();
|
||||
expect(safeWorkflowSessionUrl(undefined)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,307 @@
|
||||
import {
|
||||
formatSubagentTokenCount,
|
||||
type OrchestrationV2WorkflowRunCardState,
|
||||
} from "@t3tools/client-runtime/state/orchestration-v2-subagents";
|
||||
import type { OrchestrationV2Subagent } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { ExternalLinkIcon, WorkflowIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Button } from "./ui/button";
|
||||
|
||||
const MAX_CARD_AGENT_ROWS = 8;
|
||||
|
||||
type WorkflowRunStatus = "running" | "completed" | "failed" | "stopped";
|
||||
|
||||
const RUN_STATUS_VISUALS: Record<
|
||||
WorkflowRunStatus,
|
||||
{ label: string; dotClass: string; textClass: string; pulse: boolean }
|
||||
> = {
|
||||
running: { label: "Running", dotClass: "bg-info", textClass: "text-info", pulse: true },
|
||||
completed: {
|
||||
label: "Completed",
|
||||
dotClass: "bg-success",
|
||||
textClass: "text-success",
|
||||
pulse: false,
|
||||
},
|
||||
failed: {
|
||||
label: "Failed",
|
||||
dotClass: "bg-destructive",
|
||||
textClass: "text-destructive",
|
||||
pulse: false,
|
||||
},
|
||||
stopped: {
|
||||
label: "Stopped",
|
||||
dotClass: "bg-muted-foreground",
|
||||
textClass: "text-muted-foreground",
|
||||
pulse: false,
|
||||
},
|
||||
};
|
||||
|
||||
export function workflowRunCardStatus(
|
||||
status: OrchestrationV2Subagent["status"],
|
||||
): WorkflowRunStatus {
|
||||
switch (status) {
|
||||
case "pending":
|
||||
case "running":
|
||||
case "waiting":
|
||||
return "running";
|
||||
case "completed":
|
||||
case "idle":
|
||||
return "completed";
|
||||
case "failed":
|
||||
return "failed";
|
||||
case "cancelled":
|
||||
case "interrupted":
|
||||
return "stopped";
|
||||
}
|
||||
}
|
||||
|
||||
const AGENT_STATUS_DOT: Record<OrchestrationV2Subagent["status"], string> = {
|
||||
pending: "bg-muted-foreground/50",
|
||||
running: "bg-info animate-pulse",
|
||||
waiting: "bg-warning animate-pulse",
|
||||
idle: "bg-success",
|
||||
completed: "bg-success",
|
||||
failed: "bg-destructive",
|
||||
cancelled: "bg-muted-foreground",
|
||||
interrupted: "bg-muted-foreground",
|
||||
};
|
||||
|
||||
/**
|
||||
* Only web URLs may reach an anchor href. The adapter already filters the
|
||||
* scheme at ingestion; this guards payloads persisted before that filter
|
||||
* (and any other producer) as defense in depth.
|
||||
*/
|
||||
export function safeWorkflowSessionUrl(sessionUrl: string | undefined): string | undefined {
|
||||
if (sessionUrl === undefined) return undefined;
|
||||
try {
|
||||
const parsed = new URL(sessionUrl);
|
||||
return parsed.protocol === "https:" || parsed.protocol === "http:" ? sessionUrl : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const agentActive = (agent: OrchestrationV2Subagent) =>
|
||||
agent.status === "running" || agent.status === "waiting" || agent.status === "failed";
|
||||
|
||||
/** Which member rows survive the card cap: running and failed first, then
|
||||
* most recently updated. The full list lives in the Agents panel. */
|
||||
function visibleMemberIds(
|
||||
members: ReadonlyArray<OrchestrationV2Subagent>,
|
||||
): Set<OrchestrationV2Subagent["id"]> {
|
||||
const prioritized = [...members].sort((left, right) => {
|
||||
const leftUrgent = agentActive(left) ? 0 : 1;
|
||||
const rightUrgent = agentActive(right) ? 0 : 1;
|
||||
if (leftUrgent !== rightUrgent) return leftUrgent - rightUrgent;
|
||||
return DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt);
|
||||
});
|
||||
return new Set(prioritized.slice(0, MAX_CARD_AGENT_ROWS).map((agent) => agent.id));
|
||||
}
|
||||
|
||||
function MemberRow({ agent }: { agent: OrchestrationV2Subagent }) {
|
||||
const failed = agent.status === "failed";
|
||||
// Failures often surface only in the streamed result (a thrown value the
|
||||
// runner stringified) — fall back to it so red rows always explain why.
|
||||
const errorText = failed ? agent.result?.trim() || agent.progress?.trim() : undefined;
|
||||
const meta = [
|
||||
agent.model,
|
||||
agent.usage === null ? undefined : `${formatSubagentTokenCount(agent.usage.totalTokens)} tok`,
|
||||
failed ? undefined : agent.progress?.trim() || undefined,
|
||||
]
|
||||
.filter((part): part is string => part !== undefined && part !== null && part.length > 0)
|
||||
.join(" · ");
|
||||
const attempt = agent.workflowMembership?.attempt ?? 1;
|
||||
return (
|
||||
<div
|
||||
className="flex min-w-0 items-start gap-1.5 px-0.5 py-0.5 text-[12px] leading-5"
|
||||
data-workflow-member={agent.id}
|
||||
data-agent-status={agent.status}
|
||||
>
|
||||
<span className="flex h-5 shrink-0 items-center">
|
||||
<span className={cn("size-1.5 shrink-0 rounded-full", AGENT_STATUS_DOT[agent.status])} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div
|
||||
className={cn(
|
||||
"break-words font-medium",
|
||||
failed ? "text-destructive" : "text-foreground/80",
|
||||
)}
|
||||
>
|
||||
{agent.title?.trim() || agent.role.name}
|
||||
</div>
|
||||
{(meta.length > 0 || attempt > 1 || errorText !== undefined) && (
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[11px] leading-4 text-muted-foreground/60">
|
||||
{meta.length > 0 && <span className="tabular-nums">{meta}</span>}
|
||||
{attempt > 1 && (
|
||||
<span className="shrink-0 rounded-sm bg-muted px-1 text-[10px] leading-4 text-muted-foreground/80">
|
||||
retry {attempt}
|
||||
</span>
|
||||
)}
|
||||
{errorText !== undefined && (
|
||||
<span className="min-w-0 break-words text-destructive/75">{errorText}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PhaseHeader(props: { title: string; done: number; total: number }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-2 px-0.5 pt-1.5 pb-0.5">
|
||||
<span className="truncate text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||
{props.title}
|
||||
</span>
|
||||
{props.total > 0 && (
|
||||
<span className="shrink-0 text-[10px] tabular-nums text-muted-foreground/55">
|
||||
{props.done}/{props.total}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const isSettledMember = (agent: OrchestrationV2Subagent) =>
|
||||
agent.status !== "pending" && agent.status !== "running" && agent.status !== "waiting";
|
||||
|
||||
export function WorkflowRunCardV2(props: {
|
||||
card: OrchestrationV2WorkflowRunCardState;
|
||||
onOpenDetails?: (() => void) | undefined;
|
||||
onStop?: (() => void) | undefined;
|
||||
}) {
|
||||
const { card, onOpenDetails, onStop } = props;
|
||||
const { coordinator } = card;
|
||||
const status = workflowRunCardStatus(coordinator.status);
|
||||
const visual = RUN_STATUS_VISUALS[status];
|
||||
const title = coordinator.title?.trim() || coordinator.workflow?.name?.trim() || "Workflow";
|
||||
const sessionUrl = safeWorkflowSessionUrl(coordinator.workflow?.sessionUrl);
|
||||
const remote = coordinator.workflow?.sessionUrl !== undefined;
|
||||
const members = [...card.phases.flatMap((phase) => phase.agents), ...card.unphasedAgents];
|
||||
const overCap = members.length > MAX_CARD_AGENT_ROWS;
|
||||
const visibleIds = overCap ? visibleMemberIds(members) : null;
|
||||
const hiddenCount = overCap ? members.length - MAX_CARD_AGENT_ROWS : 0;
|
||||
const showStop = onStop !== undefined && status === "running";
|
||||
|
||||
return (
|
||||
<div
|
||||
className="rounded-lg border border-border/70 bg-card/40 p-2.5"
|
||||
data-workflow-run-card={coordinator.id}
|
||||
data-workflow-status={status}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<WorkflowIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="truncate text-[13px] font-medium text-foreground">{title}</span>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex shrink-0 items-center gap-1 text-[11px] font-medium",
|
||||
visual.textClass,
|
||||
)}
|
||||
>
|
||||
<span className="relative flex size-1.5">
|
||||
{visual.pulse && (
|
||||
<span
|
||||
className={cn(
|
||||
"absolute inline-flex size-full animate-ping rounded-full opacity-60",
|
||||
visual.dotClass,
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<span className={cn("relative inline-flex size-1.5 rounded-full", visual.dotClass)} />
|
||||
</span>
|
||||
{visual.label}
|
||||
</span>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<div className="flex items-center gap-2 text-[11px] tabular-nums text-muted-foreground/70">
|
||||
{card.memberCount > 0 && (
|
||||
<span>
|
||||
{card.settledMemberCount}/{card.memberCount} agents
|
||||
</span>
|
||||
)}
|
||||
{card.totalTokens !== null && (
|
||||
<span>{formatSubagentTokenCount(card.totalTokens)} tok</span>
|
||||
)}
|
||||
</div>
|
||||
{(showStop || onOpenDetails !== undefined) && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
{showStop && (
|
||||
<Button type="button" size="xs" variant="outline" onClick={onStop}>
|
||||
Stop
|
||||
</Button>
|
||||
)}
|
||||
{onOpenDetails !== undefined && (
|
||||
<Button type="button" size="xs" variant="outline" onClick={onOpenDetails}>
|
||||
Details
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{remote ? (
|
||||
sessionUrl === undefined ? (
|
||||
<p className="mt-1.5 px-0.5 text-[12px] leading-5 text-muted-foreground/70">
|
||||
Running in the cloud
|
||||
</p>
|
||||
) : (
|
||||
<a
|
||||
href={sessionUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-1.5 flex items-center gap-1.5 rounded-md px-0.5 py-0.5 text-[12px] leading-5 text-foreground/80 hover:bg-accent/20 hover:text-foreground"
|
||||
>
|
||||
<ExternalLinkIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
Running in the cloud — open session
|
||||
</a>
|
||||
)
|
||||
) : members.length > 0 ? (
|
||||
<div className="mt-1 space-y-px">
|
||||
{card.phases.map((phase) => {
|
||||
const rows = phase.agents.filter(
|
||||
(agent) => visibleIds === null || visibleIds.has(agent.id),
|
||||
);
|
||||
if (rows.length === 0) return null;
|
||||
return (
|
||||
<div key={phase.index}>
|
||||
<PhaseHeader
|
||||
title={phase.title}
|
||||
done={phase.agents.filter(isSettledMember).length}
|
||||
total={phase.agents.length}
|
||||
/>
|
||||
{rows.map((agent) => (
|
||||
<MemberRow key={agent.id} agent={agent} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{card.unphasedAgents
|
||||
.filter((agent) => visibleIds === null || visibleIds.has(agent.id))
|
||||
.map((agent) => (
|
||||
<MemberRow key={agent.id} agent={agent} />
|
||||
))}
|
||||
{hiddenCount > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={onOpenDetails === undefined}
|
||||
onClick={onOpenDetails}
|
||||
className={cn(
|
||||
"w-full px-0.5 py-0.5 text-left text-[12px] leading-5 text-muted-foreground/60",
|
||||
onOpenDetails !== undefined &&
|
||||
"cursor-pointer rounded-md hover:bg-accent/20 hover:text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
+{hiddenCount} more agents — open details
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{coordinator.workflow?.warning !== undefined && (
|
||||
<p className="mt-1.5 text-[11px] text-warning">{coordinator.workflow.warning}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
type EnvironmentId,
|
||||
type MessageId,
|
||||
type OrchestrationV2Subagent,
|
||||
type OrchestrationV2TurnItem,
|
||||
type RunAttemptId,
|
||||
type ScopedThreadRef,
|
||||
@@ -10,6 +11,10 @@ import {
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import {
|
||||
deriveOrchestrationV2WorkflowRunCard,
|
||||
orchestrationV2WorkflowMemberIds,
|
||||
} from "@t3tools/client-runtime/state/orchestration-v2-subagents";
|
||||
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
|
||||
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import {
|
||||
@@ -67,6 +72,7 @@ import {
|
||||
ZapIcon,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { WorkflowRunCardV2 } from "../WorkflowRunCardV2";
|
||||
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
|
||||
import { ProposedPlanCard } from "./ProposedPlanCard";
|
||||
import { ChangedFilesCard } from "./ChangedFilesTree";
|
||||
@@ -162,6 +168,8 @@ interface TimelineRowSharedState {
|
||||
}) => void;
|
||||
onToggleTurnFold: (runId: RunId) => void;
|
||||
onToggleAttemptFold: (attemptId: RunAttemptId) => void;
|
||||
/** Opens the right-panel Agents surface; null when the host view has none. */
|
||||
onOpenAgentsPanel: (() => void) | null;
|
||||
}
|
||||
|
||||
interface TimelineRowActivityState {
|
||||
@@ -173,12 +181,19 @@ interface TimelineRowActivityState {
|
||||
|
||||
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
|
||||
const TimelineRowActivityCtx = createContext<TimelineRowActivityState>(null!);
|
||||
/**
|
||||
* Live projection subagents, kept out of TimelineRowCtx on purpose: they
|
||||
* churn on every progress tick, and only subagent rows (workflow run cards)
|
||||
* should re-render for that — not every row in the list.
|
||||
*/
|
||||
const TimelineSubagentsCtx = createContext<ReadonlyArray<OrchestrationV2Subagent>>([]);
|
||||
const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
|
||||
const TIMELINE_LIST_FADE_HEADER = <div className="h-10 sm:h-12" />;
|
||||
const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;
|
||||
const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
|
||||
const EMPTY_TIMELINE_PROVIDERS: ReadonlyArray<ServerProvider> = [];
|
||||
const EMPTY_TIMELINE_RUNS: ReadonlyArray<HandoffTimelineRun> = [];
|
||||
const EMPTY_TIMELINE_SUBAGENTS: ReadonlyArray<OrchestrationV2Subagent> = [];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Props (public API)
|
||||
@@ -219,6 +234,9 @@ interface MessagesTimelineProps {
|
||||
skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
|
||||
providerStatuses?: ReadonlyArray<ServerProvider>;
|
||||
runs?: ReadonlyArray<HandoffTimelineRun>;
|
||||
/** Live projection subagents — feeds the inline workflow run cards. */
|
||||
subagents?: ReadonlyArray<OrchestrationV2Subagent>;
|
||||
onOpenAgentsPanel?: (() => void) | null;
|
||||
anchorMessageId: MessageId | null;
|
||||
onAnchorReady: (messageId: MessageId, anchorIndex: number) => void;
|
||||
onAnchorSizeChanged: (messageId: MessageId, size: number) => void;
|
||||
@@ -259,6 +277,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
skills = EMPTY_TIMELINE_SKILLS,
|
||||
providerStatuses = EMPTY_TIMELINE_PROVIDERS,
|
||||
runs: runsProp = EMPTY_TIMELINE_RUNS,
|
||||
subagents = EMPTY_TIMELINE_SUBAGENTS,
|
||||
onOpenAgentsPanel = null,
|
||||
anchorMessageId,
|
||||
onAnchorReady,
|
||||
onAnchorSizeChanged,
|
||||
@@ -476,6 +496,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onRollbackCheckpoint,
|
||||
onToggleTurnFold,
|
||||
onToggleAttemptFold,
|
||||
onOpenAgentsPanel,
|
||||
}),
|
||||
[
|
||||
timestampFormat,
|
||||
@@ -495,6 +516,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onRollbackCheckpoint,
|
||||
onToggleTurnFold,
|
||||
onToggleAttemptFold,
|
||||
onOpenAgentsPanel,
|
||||
],
|
||||
);
|
||||
const activityState = useMemo<TimelineRowActivityState>(
|
||||
@@ -555,51 +577,53 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
return (
|
||||
<TimelineRowCtx value={sharedState}>
|
||||
<TimelineRowActivityCtx value={activityState}>
|
||||
<div ref={setTimelineViewportElement} className="relative h-full min-h-0">
|
||||
<LegendList<MessagesTimelineRow>
|
||||
ref={listRef}
|
||||
data={rows}
|
||||
keyExtractor={keyExtractor}
|
||||
getItemType={getItemType}
|
||||
renderItem={renderItem}
|
||||
estimatedItemSize={90}
|
||||
initialScrollAtEnd
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
// The app owns end-following (ChatView live-follow + scroll-to-end
|
||||
// pill), which respects the user's scroll gestures. LegendList's
|
||||
// internal maintainScrollAtEnd races post-mount measurement: it
|
||||
// caches its at-end flag while a maintain cycle is active, so
|
||||
// overlapping item-layout reconciliations keep snapping the view
|
||||
// to stale content ends even after the user scrolled away.
|
||||
maintainScrollAtEnd={false}
|
||||
maintainVisibleContentPosition={maintainVisibleContentPosition}
|
||||
onScroll={handleScroll}
|
||||
className={cn(
|
||||
"messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5",
|
||||
topFadeEnabled && "chat-timeline-scroll-fade",
|
||||
)}
|
||||
ListHeaderComponent={
|
||||
topFadeEnabled && parentThreadLink === null ? TIMELINE_LIST_FADE_HEADER : listHeader
|
||||
}
|
||||
ListFooterComponent={TIMELINE_LIST_FOOTER}
|
||||
/>
|
||||
<TimelineMinimap
|
||||
items={minimapItems}
|
||||
bottomInset={contentInsetEndAdjustment}
|
||||
hasPersistentGutter={minimapHasPersistentGutter}
|
||||
hitStripWidth={minimapHitStripWidth}
|
||||
stripMap={minimapStripMap}
|
||||
onSelect={(item) => {
|
||||
onManualNavigation();
|
||||
void listRef.current?.scrollToIndex({
|
||||
index: item.rowIndex,
|
||||
animated: true,
|
||||
viewOffset: 24,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<TimelineSubagentsCtx value={subagents}>
|
||||
<div ref={setTimelineViewportElement} className="relative h-full min-h-0">
|
||||
<LegendList<MessagesTimelineRow>
|
||||
ref={listRef}
|
||||
data={rows}
|
||||
keyExtractor={keyExtractor}
|
||||
getItemType={getItemType}
|
||||
renderItem={renderItem}
|
||||
estimatedItemSize={90}
|
||||
initialScrollAtEnd
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
// The app owns end-following (ChatView live-follow + scroll-to-end
|
||||
// pill), which respects the user's scroll gestures. LegendList's
|
||||
// internal maintainScrollAtEnd races post-mount measurement: it
|
||||
// caches its at-end flag while a maintain cycle is active, so
|
||||
// overlapping item-layout reconciliations keep snapping the view
|
||||
// to stale content ends even after the user scrolled away.
|
||||
maintainScrollAtEnd={false}
|
||||
maintainVisibleContentPosition={maintainVisibleContentPosition}
|
||||
onScroll={handleScroll}
|
||||
className={cn(
|
||||
"messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5",
|
||||
topFadeEnabled && "chat-timeline-scroll-fade",
|
||||
)}
|
||||
ListHeaderComponent={
|
||||
topFadeEnabled && parentThreadLink === null ? TIMELINE_LIST_FADE_HEADER : listHeader
|
||||
}
|
||||
ListFooterComponent={TIMELINE_LIST_FOOTER}
|
||||
/>
|
||||
<TimelineMinimap
|
||||
items={minimapItems}
|
||||
bottomInset={contentInsetEndAdjustment}
|
||||
hasPersistentGutter={minimapHasPersistentGutter}
|
||||
hitStripWidth={minimapHitStripWidth}
|
||||
stripMap={minimapStripMap}
|
||||
onSelect={(item) => {
|
||||
onManualNavigation();
|
||||
void listRef.current?.scrollToIndex({
|
||||
index: item.rowIndex,
|
||||
animated: true,
|
||||
viewOffset: 24,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</TimelineSubagentsCtx>
|
||||
</TimelineRowActivityCtx>
|
||||
</TimelineRowCtx>
|
||||
);
|
||||
@@ -1399,9 +1423,52 @@ function v2EventPresentation(item: OrchestrationV2TurnItem): {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A subagent event row that knows about workflows: a coordinator renders as
|
||||
* the inline run card, a member of a present coordinator renders nothing
|
||||
* (the card already shows it), and everything else falls back to the plain
|
||||
* lifecycle card. Split from V2EventTimelineRow so only subagent rows
|
||||
* subscribe to the live subagents context.
|
||||
*/
|
||||
function V2SubagentEventRow(props: {
|
||||
readonly item: Extract<OrchestrationV2TurnItem, { readonly type: "subagent" }>;
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const subagents = use(TimelineSubagentsCtx);
|
||||
const card = useMemo(
|
||||
() =>
|
||||
deriveOrchestrationV2WorkflowRunCard({
|
||||
coordinatorId: props.item.subagentId,
|
||||
subagents,
|
||||
}),
|
||||
[props.item.subagentId, subagents],
|
||||
);
|
||||
const hiddenMemberIds = useMemo(() => orchestrationV2WorkflowMemberIds(subagents), [subagents]);
|
||||
if (card !== null) {
|
||||
return <WorkflowRunCardV2 card={card} onOpenDetails={ctx.onOpenAgentsPanel ?? undefined} />;
|
||||
}
|
||||
if (hiddenMemberIds.has(props.item.subagentId)) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<V2LifecycleRow
|
||||
item={props.item}
|
||||
createdAt={props.createdAt}
|
||||
timestampFormat={ctx.timestampFormat}
|
||||
providerStatuses={ctx.providerStatuses}
|
||||
runs={ctx.runs}
|
||||
onOpenThread={ctx.onOpenThread}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function V2EventTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "event" }> }) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const { item, visibility, sourceThreadId } = row.projectedItem;
|
||||
if (item.type === "subagent") {
|
||||
return <V2SubagentEventRow item={item} createdAt={row.createdAt} />;
|
||||
}
|
||||
if (isV2LifecycleItem(item)) {
|
||||
return (
|
||||
<V2LifecycleRow
|
||||
|
||||
@@ -13,7 +13,9 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
deriveOrchestrationV2SubagentPanelState,
|
||||
deriveOrchestrationV2WorkflowRunCard,
|
||||
formatSubagentTokenCount,
|
||||
orchestrationV2WorkflowMemberIds,
|
||||
} from "./orchestrationV2Subagents.ts";
|
||||
|
||||
const now = DateTime.makeUnsafe("2026-07-26T00:00:00.000Z");
|
||||
@@ -269,3 +271,129 @@ describe("deriveOrchestrationV2SubagentPanelState", () => {
|
||||
expect(formatSubagentTokenCount(2_000_000)).toBe("2M");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveOrchestrationV2WorkflowRunCard", () => {
|
||||
const workflow = agent("workflow-1", {
|
||||
kind: "workflow",
|
||||
role: { name: "workflow-coordinator", source: "app_default" },
|
||||
usage: { totalTokens: 1500 },
|
||||
workflow: {
|
||||
phases: [
|
||||
{ index: 0, title: "Research" },
|
||||
{ index: 1, title: "Implement" },
|
||||
],
|
||||
name: "research-implement",
|
||||
runId: "wf_run_1",
|
||||
},
|
||||
});
|
||||
const researcher = agent("member-research", {
|
||||
kind: "workflow_agent",
|
||||
status: "completed",
|
||||
usage: { totalTokens: 400 },
|
||||
workflowMembership: {
|
||||
workflowSubagentId: workflowId,
|
||||
agentIndex: 0,
|
||||
phaseIndex: 0,
|
||||
attempt: 1,
|
||||
},
|
||||
});
|
||||
const implementer = agent("member-implement", {
|
||||
kind: "workflow_agent",
|
||||
status: "running",
|
||||
usage: { totalTokens: 500 },
|
||||
workflowMembership: {
|
||||
workflowSubagentId: workflowId,
|
||||
agentIndex: 1,
|
||||
phaseIndex: 1,
|
||||
attempt: 1,
|
||||
},
|
||||
});
|
||||
|
||||
it("derives phases, counts, and the coordinator's usage for a coordinator id", () => {
|
||||
const card = deriveOrchestrationV2WorkflowRunCard({
|
||||
coordinatorId: workflowId,
|
||||
subagents: [workflow, researcher, implementer, agent("unrelated")],
|
||||
});
|
||||
|
||||
expect(card?.coordinator.id).toBe(workflowId);
|
||||
expect(card?.phases.map((phase) => [phase.title, phase.status])).toEqual([
|
||||
["Research", "done"],
|
||||
["Implement", "running"],
|
||||
]);
|
||||
expect(card?.memberCount).toBe(2);
|
||||
expect(card?.settledMemberCount).toBe(1);
|
||||
expect(card?.failedMemberCount).toBe(0);
|
||||
expect(card?.totalTokens).toBe(1500);
|
||||
expect(card?.unphasedAgents).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns null for anything that is not a workflow coordinator", () => {
|
||||
const subagents = [workflow, researcher];
|
||||
expect(
|
||||
deriveOrchestrationV2WorkflowRunCard({
|
||||
coordinatorId: researcher.id,
|
||||
subagents,
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
deriveOrchestrationV2WorkflowRunCard({
|
||||
coordinatorId: NodeId.make("missing"),
|
||||
subagents,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps members without a declared phase visible and sums their usage as fallback", () => {
|
||||
const silentCoordinator = agent("workflow-1", {
|
||||
kind: "workflow",
|
||||
workflow: { phases: [{ index: 0, title: "Research" }] },
|
||||
});
|
||||
const phaseless = agent("member-phaseless", {
|
||||
kind: "workflow_agent",
|
||||
usage: { totalTokens: 250 },
|
||||
workflowMembership: {
|
||||
workflowSubagentId: workflowId,
|
||||
agentIndex: 2,
|
||||
phaseIndex: null,
|
||||
attempt: 1,
|
||||
},
|
||||
});
|
||||
const card = deriveOrchestrationV2WorkflowRunCard({
|
||||
coordinatorId: workflowId,
|
||||
subagents: [silentCoordinator, phaseless],
|
||||
});
|
||||
|
||||
expect(card?.unphasedAgents.map((member) => member.id)).toEqual([phaseless.id]);
|
||||
// No coordinator total reported — the member sum is better than
|
||||
// "usage unavailable" for a workflow that visibly spent tokens.
|
||||
expect(card?.totalTokens).toBe(250);
|
||||
});
|
||||
});
|
||||
|
||||
describe("orchestrationV2WorkflowMemberIds", () => {
|
||||
it("hides only members whose coordinator reached the projection", () => {
|
||||
const workflow = agent("workflow-1", { kind: "workflow" });
|
||||
const member = agent("member-1", {
|
||||
kind: "workflow_agent",
|
||||
workflowMembership: {
|
||||
workflowSubagentId: workflowId,
|
||||
agentIndex: 0,
|
||||
phaseIndex: 0,
|
||||
attempt: 1,
|
||||
},
|
||||
});
|
||||
const orphan = agent("member-orphan", {
|
||||
kind: "workflow_agent",
|
||||
workflowMembership: {
|
||||
workflowSubagentId: NodeId.make("missing-workflow"),
|
||||
agentIndex: 0,
|
||||
phaseIndex: 0,
|
||||
attempt: 1,
|
||||
},
|
||||
});
|
||||
const direct = agent("direct-1");
|
||||
|
||||
const hidden = orchestrationV2WorkflowMemberIds([workflow, member, orphan, direct]);
|
||||
expect([...hidden]).toEqual([member.id]);
|
||||
});
|
||||
});
|
||||
@@ -141,6 +141,89 @@ export function deriveOrchestrationV2SubagentPanelState(input: {
|
||||
};
|
||||
}
|
||||
|
||||
export interface OrchestrationV2WorkflowRunCardState {
|
||||
readonly coordinator: OrchestrationV2Subagent;
|
||||
readonly phases: ReadonlyArray<OrchestrationV2SubagentPhaseGroup>;
|
||||
/** Members that claim no declared phase — rendered after the phased ones
|
||||
* rather than dropped, so a provider that omits phase indices still shows
|
||||
* every agent. */
|
||||
readonly unphasedAgents: ReadonlyArray<OrchestrationV2Subagent>;
|
||||
readonly memberCount: number;
|
||||
readonly settledMemberCount: number;
|
||||
readonly failedMemberCount: number;
|
||||
readonly totalTokens: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The inline run card for one workflow coordinator. Returns null unless
|
||||
* `coordinatorId` names a workflow-kind subagent, so callers can probe any
|
||||
* subagent turn item with it.
|
||||
*/
|
||||
export function deriveOrchestrationV2WorkflowRunCard(input: {
|
||||
readonly coordinatorId: OrchestrationV2Subagent["id"];
|
||||
readonly subagents: ReadonlyArray<OrchestrationV2Subagent>;
|
||||
}): OrchestrationV2WorkflowRunCardState | null {
|
||||
const coordinator = input.subagents.find(
|
||||
(agent) => agent.id === input.coordinatorId && agent.kind === "workflow",
|
||||
);
|
||||
if (coordinator === undefined) return null;
|
||||
const members = input.subagents
|
||||
.filter(
|
||||
(agent) =>
|
||||
agent.kind !== "workflow" &&
|
||||
agent.workflowMembership?.workflowSubagentId === coordinator.id,
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
(left.workflowMembership?.agentIndex ?? 0) - (right.workflowMembership?.agentIndex ?? 0),
|
||||
);
|
||||
const phases = (coordinator.workflow?.phases ?? []).map((phase) => {
|
||||
const agents = members.filter((agent) => agent.workflowMembership?.phaseIndex === phase.index);
|
||||
return { ...phase, status: phaseStatus(agents), agents };
|
||||
});
|
||||
const phasedIds = new Set(phases.flatMap((phase) => phase.agents.map((agent) => agent.id)));
|
||||
// The coordinator's usage already covers its members (the panel derivation
|
||||
// relies on the same invariant); fall back to the member sum only when the
|
||||
// provider reported no coordinator total at all.
|
||||
const memberUsage = members.flatMap((agent) =>
|
||||
agent.usage === null ? [] : [agent.usage.totalTokens],
|
||||
);
|
||||
return {
|
||||
coordinator,
|
||||
phases,
|
||||
unphasedAgents: members.filter((agent) => !phasedIds.has(agent.id)),
|
||||
memberCount: members.length,
|
||||
settledMemberCount: members.filter(isSettledOrchestrationV2Subagent).length,
|
||||
failedMemberCount: members.filter((agent) => agent.status === "failed").length,
|
||||
totalTokens:
|
||||
coordinator.usage?.totalTokens ??
|
||||
(memberUsage.length === 0 ? null : memberUsage.reduce((total, tokens) => total + tokens, 0)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Ids of workflow members whose coordinator is present as a workflow-kind
|
||||
* subagent. The timeline hides these rows — the coordinator's run card
|
||||
* already renders them — while members orphaned by a missing coordinator
|
||||
* keep their own row rather than disappearing.
|
||||
*/
|
||||
export function orchestrationV2WorkflowMemberIds(
|
||||
subagents: ReadonlyArray<OrchestrationV2Subagent>,
|
||||
): ReadonlySet<OrchestrationV2Subagent["id"]> {
|
||||
const coordinatorIds = new Set(
|
||||
subagents.flatMap((agent) => (agent.kind === "workflow" ? [agent.id] : [])),
|
||||
);
|
||||
return new Set(
|
||||
subagents.flatMap((agent) =>
|
||||
agent.kind !== "workflow" &&
|
||||
agent.workflowMembership !== null &&
|
||||
coordinatorIds.has(agent.workflowMembership.workflowSubagentId)
|
||||
? [agent.id]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const formatSubagentTokenCount = (totalTokens: number) =>
|
||||
totalTokens >= 999_500
|
||||
? `${(totalTokens / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`
|
||||
|
||||
Reference in new issue
Block a user