Skip to content

Commit 0dd586c

Browse files
t3dotggclaude
andcommitted
fix: address review handoff P1/P2 findings
P1: - Claude workflow agents keyed by stable row index (parent:wf:N), not per-attempt agentId — queued/blocked rows now appear, retries update one card instead of duplicating - agent.snapshot payloads carry a monotonic per-thread revision; client latest-wins selection uses it (deterministic under same-ms appends) - Codex child turn/completed decodes turn.status: failed→failed with error summary, interrupted→stopped, completed→idle - roster hydration is lazy (only on agent-touching events), no longer a full thread-detail load on every first event per thread P2: - reducer re-derives kind from event taskType/parent (no first-guess pinning); reactivation counts any settled→active transition - workflow container rows excluded from worker counts; container usage only counted when it has no member rows - settled cards lead with error/result, never stale activity text - newest agents array is authoritative on the client — undecodable rosters no longer resurrect older running snapshots - idle (resumable) agents no longer share the terminal retention pool - Codex usage uses the cumulative total breakdown consistently Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 757895c commit 0dd586c

8 files changed

Lines changed: 173 additions & 51 deletions

File tree

‎apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts‎

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,12 @@ export function foldTaskAgentEvent(
141141
const summary = "summary" in payload ? payload.summary : undefined;
142142
const nextUsage = "usage" in payload ? taskUsage(payload.usage) : undefined;
143143
const lastToolName = "lastToolName" in payload ? payload.lastToolName : undefined;
144-
const currentActivity = summary ?? lastToolName ?? previous?.currentActivity;
144+
const settledNow = status === "idle" || THREAD_AGENT_TERMINAL_STATUSES.has(status);
145+
// A settled agent's card shows its result/error, not a stale in-flight
146+
// activity line ("Reading files…" on a failed card).
147+
const currentActivity = settledNow
148+
? undefined
149+
: (summary ?? lastToolName ?? previous?.currentActivity);
145150
const activityChanged =
146151
(summary !== undefined && summary !== previous?.currentActivity) ||
147152
(lastToolName !== undefined && lastToolName !== previous?.lastToolName);
@@ -154,15 +159,23 @@ export function foldTaskAgentEvent(
154159
const wasSettled =
155160
previous !== undefined &&
156161
(previous.status === "idle" || THREAD_AGENT_TERMINAL_STATUSES.has(previous.status));
157-
const reactivated = wasSettled && status === "running";
162+
// Any non-settled status counts as a fresh activation — an idle Codex agent
163+
// resumed via a waiting approval still increments, not just idle→running.
164+
const reactivated =
165+
wasSettled && status !== "idle" && !THREAD_AGENT_TERMINAL_STATUSES.has(status);
158166
const explicitEndTime = event.type === "task.updated" ? event.payload.endTime : undefined;
159167
const terminal = THREAD_AGENT_TERMINAL_STATUSES.has(status);
168+
// Re-derive kind whenever this event carries a taskType/parent — a child
169+
// registered from an early notification (before its parent linkage arrived)
170+
// must not stay pinned to a first-guess "other".
171+
const eventKind = taskKind(
172+
"taskType" in payload ? payload.taskType : undefined,
173+
payload.parentTaskId,
174+
);
160175
const next: ThreadAgentSnapshot = {
161176
agentId: payload.taskId,
162177
provider: event.provider,
163-
kind:
164-
previous?.kind ??
165-
taskKind("taskType" in payload ? payload.taskType : undefined, payload.parentTaskId),
178+
kind: eventKind !== "other" ? eventKind : (previous?.kind ?? eventKind),
166179
name: payload.name ?? description ?? payload.workflowName ?? previous?.name ?? payload.taskId,
167180
...((payload.agentType ?? previous?.agentType)
168181
? { agentType: payload.agentType ?? previous?.agentType }
@@ -240,8 +253,11 @@ export function foldTaskAgentEvent(
240253
}
241254

242255
export function pruneSettledAgents(agents: Map<string, ThreadAgentSnapshot>): void {
256+
// Idle agents are resumable identities, not history — only terminal agents
257+
// compete for the retention pool, so re-activating an old idle Codex child
258+
// never loses its usage/activation record to pruning.
243259
const settled = Array.from(agents.values())
244-
.filter((agent) => agent.status === "idle" || THREAD_AGENT_TERMINAL_STATUSES.has(agent.status))
260+
.filter((agent) => THREAD_AGENT_TERMINAL_STATUSES.has(agent.status))
245261
.sort((left, right) => left.lastActivityAt.localeCompare(right.lastActivityAt));
246262
for (const agent of settled.slice(
247263
0,
@@ -920,6 +936,10 @@ const make = Effect.gen(function* () {
920936
// client's latest-wins scan) always finds one while agents exist.
921937
const activitiesSinceAgentSnapshot = new Map<ThreadId, number>();
922938
const AGENT_SNAPSHOT_REFRESH_ACTIVITY_COUNT = 400;
939+
// Monotonic per-thread roster revision. Snapshot activities carry it so the
940+
// client picks the newest roster deterministically even when two appends
941+
// share a createdAt millisecond. Seeded from the hydrated snapshot.
942+
const agentRosterRevision = new Map<ThreadId, number>();
923943
let agentSnapshotDispatchCount = 0;
924944
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
925945
crypto.randomUUIDv4.pipe(
@@ -1533,7 +1553,12 @@ const make = Effect.gen(function* () {
15331553
return loadedThreadDetail;
15341554
});
15351555

1536-
if (!hydratedAgentThreads.has(thread.id)) {
1556+
// Hydrate lazily, only when an event actually touches the roster —
1557+
// never on ordinary traffic (message deltas would otherwise trigger a
1558+
// full thread-detail load per thread after every restart, serialized
1559+
// through the ingestion worker).
1560+
const eventTouchesAgents = isTaskAgentEvent(event) || event.type === "session.exited";
1561+
if (eventTouchesAgents && !hydratedAgentThreads.has(thread.id)) {
15371562
// Hydration source is the 500-capped activities projection — the same
15381563
// list clients derive from. While agents exist, the refresh counter
15391564
// below re-publishes the roster every ~400 activities so the latest
@@ -1556,8 +1581,11 @@ const make = Effect.gen(function* () {
15561581
);
15571582
const payload =
15581583
latestSnapshot?.payload !== null && typeof latestSnapshot?.payload === "object"
1559-
? (latestSnapshot.payload as { agents?: unknown })
1584+
? (latestSnapshot.payload as { agents?: unknown; revision?: unknown })
15601585
: undefined;
1586+
if (typeof payload?.revision === "number" && Number.isInteger(payload.revision)) {
1587+
agentRosterRevision.set(thread.id, payload.revision);
1588+
}
15611589
const agents = new Map<string, ThreadAgentSnapshot>();
15621590
if (Array.isArray(payload?.agents)) {
15631591
for (const candidate of payload.agents) {
@@ -1615,14 +1643,15 @@ const make = Effect.gen(function* () {
16151643
const settled = roster.length - active;
16161644
const count = active > 0 ? active : settled;
16171645
const summary = `${count} ${count === 1 ? "agent" : "agents"} ${active > 0 ? "active" : "settled"}`;
1646+
const nextRevision = (agentRosterRevision.get(thread.id) ?? 0) + 1;
16181647
const snapshotUuid = yield* crypto.randomUUIDv4;
16191648
const activity: OrchestrationThreadActivity = {
16201649
id: EventId.make(`${event.eventId}:agent-snapshot:${snapshotUuid}`),
16211650
createdAt: event.createdAt,
16221651
tone: "info",
16231652
kind: THREAD_AGENTS_ACTIVITY_KIND,
16241653
summary,
1625-
payload: { agents: roster },
1654+
payload: { agents: roster, revision: nextRevision },
16261655
turnId: toTurnId(event.turnId) ?? null,
16271656
};
16281657
// The in-memory roster is authoritative (already folded); if the
@@ -1646,6 +1675,7 @@ const make = Effect.gen(function* () {
16461675
Effect.gen(function* () {
16471676
pendingRosterRedispatch.delete(thread.id);
16481677
activitiesSinceAgentSnapshot.set(thread.id, 0);
1678+
agentRosterRevision.set(thread.id, nextRevision);
16491679
agentSnapshotDispatchCount += 1;
16501680
yield* Effect.logDebug("provider agent snapshot appended", {
16511681
threadId: thread.id,
@@ -1673,6 +1703,7 @@ const make = Effect.gen(function* () {
16731703
agentsByThread.delete(thread.id);
16741704
hydratedAgentThreads.delete(thread.id);
16751705
activitiesSinceAgentSnapshot.delete(thread.id);
1706+
agentRosterRevision.delete(thread.id);
16761707
}
16771708

16781709
const now = event.createdAt;

‎apps/server/src/provider/Layers/ClaudeAdapter.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1755,6 +1755,7 @@ describe("ClaudeAdapterLive", () => {
17551755
{ type: "workflow_phase", index: 0, title: "Inspect" },
17561756
{
17571757
type: "workflow_agent",
1758+
index: 1,
17581759
label: "Reviewer",
17591760
phaseIndex: 0,
17601761
phaseTitle: "Inspect",
@@ -1805,7 +1806,7 @@ describe("ClaudeAdapterLive", () => {
18051806
assert.deepEqual(phasePatch.payload.phases, [{ index: 0, title: "Inspect" }]);
18061807
}
18071808
const child = runtimeEvents.find(
1808-
(event) => event.type === "task.started" && event.payload.taskId === "agent-1",
1809+
(event) => event.type === "task.started" && event.payload.taskId === "workflow-1:wf:1",
18091810
);
18101811
assert.equal(child?.type, "task.started");
18111812
if (child?.type === "task.started") {

‎apps/server/src/provider/Layers/ClaudeAdapter.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2799,14 +2799,18 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
27992799
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) continue;
28002800
const item = entry as Record<string, unknown>;
28012801
if (item.type !== "workflow_agent") continue;
2802-
const agentId = readString(item.agentId);
2802+
// `index` is the stable identity: queued/blocked/pre-spawn-error
2803+
// events carry no agentId yet, and retries keep the index while
2804+
// minting a new agentId per attempt. Keying on agentId would drop
2805+
// queued agents and duplicate cards across retries.
2806+
const index = readNonNegativeInteger(item.index);
28032807
const label = readString(item.label);
2804-
if (!agentId || !label) continue;
2808+
if (index === undefined || !label) continue;
28052809
const state = readString(item.state);
28062810
const childUsage = readNonNegativeInteger(item.tokens);
28072811
const childToolUses = readNonNegativeInteger(item.toolCalls);
28082812
const childPayload = {
2809-
taskId: RuntimeTaskId.make(agentId),
2813+
taskId: RuntimeTaskId.make(`${message.task_id}:wf:${index}`),
28102814
description: label,
28112815
name: label,
28122816
taskType: "workflow_agent",

‎apps/server/src/provider/Layers/CodexAdapter.ts‎

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -546,14 +546,42 @@ function mapCollabAgentActivity(
546546
switch (wrapper.method) {
547547
case "turn/started":
548548
return [{ ...base, type: "task.started", payload: { ...base.payload } }];
549-
case "turn/completed":
549+
case "turn/completed": {
550+
const payload = readPayload(EffectCodexSchema.V2TurnCompletedNotification, inner.payload);
551+
const turnStatus = payload?.turn.status;
552+
const errorMessage = payload?.turn.error?.message;
553+
if (turnStatus === "failed") {
554+
return [
555+
{
556+
...base,
557+
type: "task.completed",
558+
payload: {
559+
taskId: base.payload.taskId,
560+
status: "failed",
561+
...(errorMessage ? { summary: errorMessage } : {}),
562+
timelineBypass: true,
563+
},
564+
},
565+
];
566+
}
567+
if (turnStatus === "interrupted") {
568+
return [
569+
{
570+
...base,
571+
type: "task.completed",
572+
payload: { taskId: base.payload.taskId, status: "stopped", timelineBypass: true },
573+
},
574+
];
575+
}
576+
// completed (or unparseable payload): the identity is idle-and-resumable.
550577
return [
551578
{
552579
...base,
553580
type: "task.updated",
554581
payload: { taskId: base.payload.taskId, status: "idle", timelineBypass: true },
555582
},
556583
];
584+
}
557585
case "subAgent/interrupted":
558586
return [
559587
{
@@ -614,26 +642,23 @@ function mapCollabAgentActivity(
614642
EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification,
615643
inner.payload,
616644
);
617-
const usage = payload ? normalizeCodexTokenUsage(payload.tokenUsage) : undefined;
618-
if (!usage) return [];
645+
// All fields from the cumulative `total` breakdown — mixing the
646+
// cumulative total with `last` (per-turn) breakdowns would make the
647+
// numbers internally inconsistent, and `last` can shrink on follow-ups.
648+
const total = payload?.tokenUsage.total;
649+
if (!total || total.totalTokens <= 0) return [];
619650
return [
620651
{
621652
...base,
622653
type: "task.progress",
623654
payload: {
624655
...base.payload,
625656
usage: {
626-
// Cumulative across the child's activations; `usedTokens` is
627-
// only the latest context window and can shrink on follow-ups.
628-
totalTokens: usage.totalProcessedTokens ?? usage.usedTokens,
629-
...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}),
630-
...(usage.cachedInputTokens !== undefined
631-
? { cachedInputTokens: usage.cachedInputTokens }
632-
: {}),
633-
...(usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : {}),
634-
...(usage.reasoningOutputTokens !== undefined
635-
? { reasoningOutputTokens: usage.reasoningOutputTokens }
636-
: {}),
657+
totalTokens: total.totalTokens,
658+
inputTokens: total.inputTokens,
659+
cachedInputTokens: total.cachedInputTokens,
660+
outputTokens: total.outputTokens,
661+
reasoningOutputTokens: total.reasoningOutputTokens,
637662
},
638663
},
639664
},

‎apps/web/src/components/AgentsPanel.tsx‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,13 +90,19 @@ function AgentElapsed({ agent }: { agent: ThreadAgentSnapshot }) {
9090
function AgentCard({ agent }: { agent: ThreadAgentSnapshot }) {
9191
const [expanded, setExpanded] = useState(false);
9292
const settled = isTerminalAgentStatus(agent.status);
93+
// Settled cards lead with outcome (error first); live cards with activity.
9394
const activity =
9495
agent.status === "waiting"
9596
? "Waiting on approval"
96-
: (agent.currentActivity ??
97-
(agent.lastToolName ? `▸ ${agent.lastToolName}` : null) ??
98-
agent.resultSummary ??
99-
agent.errorMessage);
97+
: settled || agent.status === "idle"
98+
? (agent.errorMessage ??
99+
agent.resultSummary ??
100+
agent.currentActivity ??
101+
(agent.lastToolName ? `▸ ${agent.lastToolName}` : null))
102+
: (agent.currentActivity ??
103+
(agent.lastToolName ? `▸ ${agent.lastToolName}` : null) ??
104+
agent.resultSummary ??
105+
agent.errorMessage);
100106
const hasFeed = agent.recentActivity.length > 0;
101107

102108
return (

‎packages/client-runtime/src/state/threadAgents.test.ts‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,33 @@ describe("deriveLatestAgentSnapshot", () => {
5151
expect(agents[0]?.resultSummary).toBe("Hi! How can I help you today?");
5252
});
5353

54-
it("skips rows whose payload fails to decode instead of failing", () => {
54+
it("treats the newest agents array as authoritative even when its rows fail to decode", () => {
55+
// Falling back to the older roster would resurrect a stale "running"
56+
// snapshot; an undecodable newest roster must yield an empty panel.
5557
const agents = deriveLatestAgentSnapshot([
56-
activity("agent.snapshot", { agents: [persistedAgent] }, 1),
57-
activity("agent.snapshot", { agents: [{ bogus: true }] }, 2),
58+
activity("agent.snapshot", { agents: [persistedAgent], revision: 1 }, 1),
59+
activity("agent.snapshot", { agents: [{ bogus: true }], revision: 2 }, 2),
60+
]);
61+
expect(agents).toHaveLength(0);
62+
});
63+
64+
it("skips bad rows within a roster while keeping decodable ones", () => {
65+
const agents = deriveLatestAgentSnapshot([
66+
activity("agent.snapshot", { agents: [persistedAgent, { bogus: true }], revision: 1 }, 1),
5867
]);
5968
expect(agents).toHaveLength(1);
6069
expect(agents[0]?.agentId).toBe(persistedAgent.agentId);
6170
});
6271

72+
it("selects the highest revision regardless of list position", () => {
73+
const older = { ...persistedAgent, status: "running" };
74+
const agents = deriveLatestAgentSnapshot([
75+
activity("agent.snapshot", { agents: [persistedAgent], revision: 5 }, 1),
76+
activity("agent.snapshot", { agents: [older], revision: 4 }, 2),
77+
]);
78+
expect(agents[0]?.status).toBe("completed");
79+
});
80+
6381
it("returns an empty roster when no snapshot activity exists", () => {
6482
expect(deriveLatestAgentSnapshot([activity("task.progress", {}, 1)])).toHaveLength(0);
6583
});

0 commit comments

Comments
 (0)