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]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-21 20:00:02 -07:00
1 parent a3248a123a
commit 4586d5f374
8 files changed
+173 -51

No files matched your search

@@ -141,7 +141,12 @@ export function foldTaskAgentEvent(
const summary = "summary" in payload ? payload.summary : undefined;
const nextUsage = "usage" in payload ? taskUsage(payload.usage) : undefined;
const lastToolName = "lastToolName" in payload ? payload.lastToolName : undefined;
const currentActivity = summary ?? lastToolName ?? previous?.currentActivity;
const settledNow = status === "idle" || THREAD_AGENT_TERMINAL_STATUSES.has(status);
// A settled agent's card shows its result/error, not a stale in-flight
// activity line ("Reading files…" on a failed card).
const currentActivity = settledNow
? undefined
: (summary ?? lastToolName ?? previous?.currentActivity);
const activityChanged =
(summary !== undefined && summary !== previous?.currentActivity) ||
(lastToolName !== undefined && lastToolName !== previous?.lastToolName);
@@ -154,15 +159,23 @@ export function foldTaskAgentEvent(
const wasSettled =
previous !== undefined &&
(previous.status === "idle" || THREAD_AGENT_TERMINAL_STATUSES.has(previous.status));
const reactivated = wasSettled && status === "running";
// Any non-settled status counts as a fresh activation — an idle Codex agent
// resumed via a waiting approval still increments, not just idle→running.
const reactivated =
wasSettled && status !== "idle" && !THREAD_AGENT_TERMINAL_STATUSES.has(status);
const explicitEndTime = event.type === "task.updated" ? event.payload.endTime : undefined;
const terminal = THREAD_AGENT_TERMINAL_STATUSES.has(status);
// Re-derive kind whenever this event carries a taskType/parent — a child
// registered from an early notification (before its parent linkage arrived)
// must not stay pinned to a first-guess "other".
const eventKind = taskKind(
"taskType" in payload ? payload.taskType : undefined,
payload.parentTaskId,
);
const next: ThreadAgentSnapshot = {
agentId: payload.taskId,
provider: event.provider,
kind:
previous?.kind ??
taskKind("taskType" in payload ? payload.taskType : undefined, payload.parentTaskId),
kind: eventKind !== "other" ? eventKind : (previous?.kind ?? eventKind),
name: payload.name ?? description ?? payload.workflowName ?? previous?.name ?? payload.taskId,
...((payload.agentType ?? previous?.agentType)
? { agentType: payload.agentType ?? previous?.agentType }
@@ -240,8 +253,11 @@ export function foldTaskAgentEvent(
}
export function pruneSettledAgents(agents: Map<string, ThreadAgentSnapshot>): void {
// Idle agents are resumable identities, not history — only terminal agents
// compete for the retention pool, so re-activating an old idle Codex child
// never loses its usage/activation record to pruning.
const settled = Array.from(agents.values())
.filter((agent) => agent.status === "idle" || THREAD_AGENT_TERMINAL_STATUSES.has(agent.status))
.filter((agent) => THREAD_AGENT_TERMINAL_STATUSES.has(agent.status))
.sort((left, right) => left.lastActivityAt.localeCompare(right.lastActivityAt));
for (const agent of settled.slice(
0,
@@ -920,6 +936,10 @@ const make = Effect.gen(function* () {
// client's latest-wins scan) always finds one while agents exist.
const activitiesSinceAgentSnapshot = new Map<ThreadId, number>();
const AGENT_SNAPSHOT_REFRESH_ACTIVITY_COUNT = 400;
// Monotonic per-thread roster revision. Snapshot activities carry it so the
// client picks the newest roster deterministically even when two appends
// share a createdAt millisecond. Seeded from the hydrated snapshot.
const agentRosterRevision = new Map<ThreadId, number>();
let agentSnapshotDispatchCount = 0;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
crypto.randomUUIDv4.pipe(
@@ -1533,7 +1553,12 @@ const make = Effect.gen(function* () {
return loadedThreadDetail;
});
if (!hydratedAgentThreads.has(thread.id)) {
// Hydrate lazily, only when an event actually touches the roster —
// never on ordinary traffic (message deltas would otherwise trigger a
// full thread-detail load per thread after every restart, serialized
// through the ingestion worker).
const eventTouchesAgents = isTaskAgentEvent(event) || event.type === "session.exited";
if (eventTouchesAgents && !hydratedAgentThreads.has(thread.id)) {
// Hydration source is the 500-capped activities projection — the same
// list clients derive from. While agents exist, the refresh counter
// below re-publishes the roster every ~400 activities so the latest
@@ -1556,8 +1581,11 @@ const make = Effect.gen(function* () {
);
const payload =
latestSnapshot?.payload !== null && typeof latestSnapshot?.payload === "object"
? (latestSnapshot.payload as { agents?: unknown })
? (latestSnapshot.payload as { agents?: unknown; revision?: unknown })
: undefined;
if (typeof payload?.revision === "number" && Number.isInteger(payload.revision)) {
agentRosterRevision.set(thread.id, payload.revision);
}
const agents = new Map<string, ThreadAgentSnapshot>();
if (Array.isArray(payload?.agents)) {
for (const candidate of payload.agents) {
@@ -1615,6 +1643,7 @@ const make = Effect.gen(function* () {
const settled = roster.length - active;
const count = active > 0 ? active : settled;
const summary = `${count} ${count === 1 ? "agent" : "agents"} ${active > 0 ? "active" : "settled"}`;
const nextRevision = (agentRosterRevision.get(thread.id) ?? 0) + 1;
const snapshotUuid = yield* crypto.randomUUIDv4;
const activity: OrchestrationThreadActivity = {
id: EventId.make(`${event.eventId}:agent-snapshot:${snapshotUuid}`),
@@ -1622,7 +1651,7 @@ const make = Effect.gen(function* () {
tone: "info",
kind: THREAD_AGENTS_ACTIVITY_KIND,
summary,
payload: { agents: roster },
payload: { agents: roster, revision: nextRevision },
turnId: toTurnId(event.turnId) ?? null,
};
// The in-memory roster is authoritative (already folded); if the
@@ -1646,6 +1675,7 @@ const make = Effect.gen(function* () {
Effect.gen(function* () {
pendingRosterRedispatch.delete(thread.id);
activitiesSinceAgentSnapshot.set(thread.id, 0);
agentRosterRevision.set(thread.id, nextRevision);
agentSnapshotDispatchCount += 1;
yield* Effect.logDebug("provider agent snapshot appended", {
threadId: thread.id,
@@ -1673,6 +1703,7 @@ const make = Effect.gen(function* () {
agentsByThread.delete(thread.id);
hydratedAgentThreads.delete(thread.id);
activitiesSinceAgentSnapshot.delete(thread.id);
agentRosterRevision.delete(thread.id);
}
const now = event.createdAt;
@@ -1755,6 +1755,7 @@ describe("ClaudeAdapterLive", () => {
{ type: "workflow_phase", index: 0, title: "Inspect" },
{
type: "workflow_agent",
index: 1,
label: "Reviewer",
phaseIndex: 0,
phaseTitle: "Inspect",
@@ -1805,7 +1806,7 @@ describe("ClaudeAdapterLive", () => {
assert.deepEqual(phasePatch.payload.phases, [{ index: 0, title: "Inspect" }]);
}
const child = runtimeEvents.find(
(event) => event.type === "task.started" && event.payload.taskId === "agent-1",
(event) => event.type === "task.started" && event.payload.taskId === "workflow-1:wf:1",
);
assert.equal(child?.type, "task.started");
if (child?.type === "task.started") {
@@ -2805,14 +2805,18 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) continue;
const item = entry as Record<string, unknown>;
if (item.type !== "workflow_agent") continue;
const agentId = readString(item.agentId);
// `index` is the stable identity: queued/blocked/pre-spawn-error
// events carry no agentId yet, and retries keep the index while
// minting a new agentId per attempt. Keying on agentId would drop
// queued agents and duplicate cards across retries.
const index = readNonNegativeInteger(item.index);
const label = readString(item.label);
if (!agentId || !label) continue;
if (index === undefined || !label) continue;
const state = readString(item.state);
const childUsage = readNonNegativeInteger(item.tokens);
const childToolUses = readNonNegativeInteger(item.toolCalls);
const childPayload = {
taskId: RuntimeTaskId.make(agentId),
taskId: RuntimeTaskId.make(`${message.task_id}:wf:${index}`),
description: label,
name: label,
taskType: "workflow_agent",
+39 -14
View File
@@ -546,7 +546,34 @@ function mapCollabAgentActivity(
switch (wrapper.method) {
case "turn/started":
return [{ ...base, type: "task.started", payload: { ...base.payload } }];
case "turn/completed":
case "turn/completed": {
const payload = readPayload(EffectCodexSchema.V2TurnCompletedNotification, inner.payload);
const turnStatus = payload?.turn.status;
const errorMessage = payload?.turn.error?.message;
if (turnStatus === "failed") {
return [
{
...base,
type: "task.completed",
payload: {
taskId: base.payload.taskId,
status: "failed",
...(errorMessage ? { summary: errorMessage } : {}),
timelineBypass: true,
},
},
];
}
if (turnStatus === "interrupted") {
return [
{
...base,
type: "task.completed",
payload: { taskId: base.payload.taskId, status: "stopped", timelineBypass: true },
},
];
}
// completed (or unparseable payload): the identity is idle-and-resumable.
return [
{
...base,
@@ -554,6 +581,7 @@ function mapCollabAgentActivity(
payload: { taskId: base.payload.taskId, status: "idle", timelineBypass: true },
},
];
}
case "subAgent/interrupted":
return [
{
@@ -614,8 +642,11 @@ function mapCollabAgentActivity(
EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification,
inner.payload,
);
const usage = payload ? normalizeCodexTokenUsage(payload.tokenUsage) : undefined;
if (!usage) return [];
// All fields from the cumulative `total` breakdown — mixing the
// cumulative total with `last` (per-turn) breakdowns would make the
// numbers internally inconsistent, and `last` can shrink on follow-ups.
const total = payload?.tokenUsage.total;
if (!total || total.totalTokens <= 0) return [];
return [
{
...base,
@@ -623,17 +654,11 @@ function mapCollabAgentActivity(
payload: {
...base.payload,
usage: {
// Cumulative across the child's activations; `usedTokens` is
// only the latest context window and can shrink on follow-ups.
totalTokens: usage.totalProcessedTokens ?? usage.usedTokens,
...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}),
...(usage.cachedInputTokens !== undefined
? { cachedInputTokens: usage.cachedInputTokens }
: {}),
...(usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : {}),
...(usage.reasoningOutputTokens !== undefined
? { reasoningOutputTokens: usage.reasoningOutputTokens }
: {}),
totalTokens: total.totalTokens,
inputTokens: total.inputTokens,
cachedInputTokens: total.cachedInputTokens,
outputTokens: total.outputTokens,
reasoningOutputTokens: total.reasoningOutputTokens,
},
},
},
+10 -4
View File
@@ -90,13 +90,19 @@ function AgentElapsed({ agent }: { agent: ThreadAgentSnapshot }) {
function AgentCard({ agent }: { agent: ThreadAgentSnapshot }) {
const [expanded, setExpanded] = useState(false);
const settled = isTerminalAgentStatus(agent.status);
// Settled cards lead with outcome (error first); live cards with activity.
const activity =
agent.status === "waiting"
? "Waiting on approval"
: (agent.currentActivity ??
(agent.lastToolName ? `▸ ${agent.lastToolName}` : null) ??
agent.resultSummary ??
agent.errorMessage);
: settled || agent.status === "idle"
? (agent.errorMessage ??
agent.resultSummary ??
agent.currentActivity ??
(agent.lastToolName ? `▸ ${agent.lastToolName}` : null))
: (agent.currentActivity ??
(agent.lastToolName ? `▸ ${agent.lastToolName}` : null) ??
agent.resultSummary ??
agent.errorMessage);
const hasFeed = agent.recentActivity.length > 0;
return (
@@ -51,15 +51,33 @@ describe("deriveLatestAgentSnapshot", () => {
expect(agents[0]?.resultSummary).toBe("Hi! How can I help you today?");
});
it("skips rows whose payload fails to decode instead of failing", () => {
it("treats the newest agents array as authoritative even when its rows fail to decode", () => {
// Falling back to the older roster would resurrect a stale "running"
// snapshot; an undecodable newest roster must yield an empty panel.
const agents = deriveLatestAgentSnapshot([
activity("agent.snapshot", { agents: [persistedAgent] }, 1),
activity("agent.snapshot", { agents: [{ bogus: true }] }, 2),
activity("agent.snapshot", { agents: [persistedAgent], revision: 1 }, 1),
activity("agent.snapshot", { agents: [{ bogus: true }], revision: 2 }, 2),
]);
expect(agents).toHaveLength(0);
});
it("skips bad rows within a roster while keeping decodable ones", () => {
const agents = deriveLatestAgentSnapshot([
activity("agent.snapshot", { agents: [persistedAgent, { bogus: true }], revision: 1 }, 1),
]);
expect(agents).toHaveLength(1);
expect(agents[0]?.agentId).toBe(persistedAgent.agentId);
});
it("selects the highest revision regardless of list position", () => {
const older = { ...persistedAgent, status: "running" };
const agents = deriveLatestAgentSnapshot([
activity("agent.snapshot", { agents: [persistedAgent], revision: 5 }, 1),
activity("agent.snapshot", { agents: [older], revision: 4 }, 2),
]);
expect(agents[0]?.status).toBe("completed");
});
it("returns an empty roster when no snapshot activity exists", () => {
expect(deriveLatestAgentSnapshot([activity("task.progress", {}, 1)])).toHaveLength(0);
});
@@ -16,43 +16,64 @@ import * as Schema from "effect/Schema";
const decodeAgent = Schema.decodeUnknownOption(ThreadAgentSnapshot);
interface DecodedRoster {
readonly agents: ReadonlyArray<ThreadAgentSnapshot>;
readonly revision: number | undefined;
}
/**
* Rows decode per-element: one malformed or forward-incompatible agent entry
* is skipped without discarding the rest of the roster. Only a payload with
* no decodable agents at all falls through to an older snapshot.
* is skipped without discarding the rest of the roster. Any payload with an
* `agents` array is authoritative — a roster whose rows all fail to decode
* yields an empty panel rather than resurrecting an older (possibly still
* "running") snapshot.
*/
function decodeRoster(payload: unknown): ReadonlyArray<ThreadAgentSnapshot> | undefined {
function decodeRoster(payload: unknown): DecodedRoster | undefined {
if (payload === null || typeof payload !== "object") {
return undefined;
}
const agents = (payload as { agents?: unknown }).agents;
if (!Array.isArray(agents)) {
const record = payload as { agents?: unknown; revision?: unknown };
if (!Array.isArray(record.agents)) {
return undefined;
}
const decoded: ThreadAgentSnapshot[] = [];
for (const candidate of agents) {
for (const candidate of record.agents) {
const result = decodeAgent(candidate);
if (result._tag === "Some") {
decoded.push(result.value);
}
}
return agents.length === 0 || decoded.length > 0 ? decoded : undefined;
return {
agents: decoded,
revision:
typeof record.revision === "number" && Number.isInteger(record.revision)
? record.revision
: undefined,
};
}
export function deriveLatestAgentSnapshot(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyArray<ThreadAgentSnapshot> {
for (let index = activities.length - 1; index >= 0; index -= 1) {
const activity = activities[index];
if (!activity || activity.kind !== THREAD_AGENTS_ACTIVITY_KIND) {
// Highest revision wins; list order breaks ties (and covers revision-less
// rosters from before the field existed). Guards against same-millisecond
// appends landing out of order in the capped projection.
let best: DecodedRoster | undefined;
for (const activity of activities) {
if (activity.kind !== THREAD_AGENTS_ACTIVITY_KIND) {
continue;
}
const roster = decodeRoster(activity.payload);
if (roster !== undefined) {
return roster;
if (!roster) {
continue;
}
if (!best || roster.revision === undefined || best.revision === undefined) {
best = roster;
} else if (roster.revision >= best.revision) {
best = roster;
}
}
return [];
return best?.agents ?? [];
}
export function isTerminalAgentStatus(status: ThreadAgentSnapshot["status"]): boolean {
@@ -140,15 +161,28 @@ export function deriveAgentPanelState(agents: ReadonlyArray<ThreadAgentSnapshot>
groups.push({ workflow: null, phases: [], rest: direct });
}
// Workflow container rows are grouping chrome, not workers: they are
// excluded from worker counts, and a container's own usage only counts when
// it has no member rows to avoid double-counting the same tokens.
const workflowsWithMembers = new Set(
agents.flatMap((agent) =>
agent.kind !== "workflow" && agent.parentAgentId ? [agent.parentAgentId] : [],
),
);
let runningCount = 0;
let waitingCount = 0;
let settledCount = 0;
let totalTokens = 0;
for (const agent of agents) {
if (agent.status === "running" || agent.status === "pending") runningCount += 1;
else if (agent.status === "waiting") waitingCount += 1;
else settledCount += 1; // idle + terminal
totalTokens += agent.usage?.totalTokens ?? 0;
const isContainer = agent.kind === "workflow";
if (!isContainer) {
if (agent.status === "running" || agent.status === "pending") runningCount += 1;
else if (agent.status === "waiting") waitingCount += 1;
else settledCount += 1; // idle + terminal
}
if (!isContainer || !workflowsWithMembers.has(agent.agentId)) {
totalTokens += agent.usage?.totalTokens ?? 0;
}
}
return { groups, runningCount, waitingCount, settledCount, totalTokens };
+3
View File
@@ -134,5 +134,8 @@ export const THREAD_AGENTS_ACTIVITY_KIND = "agent.snapshot";
*/
export const ThreadAgentsActivityPayload = Schema.Struct({
agents: Schema.Array(ThreadAgentSnapshot),
// Monotonic per-thread revision: latest-wins selection uses the highest
// revision (not list position), making same-timestamp appends deterministic.
revision: Schema.optional(NonNegativeInt),
});
export type ThreadAgentsActivityPayload = typeof ThreadAgentsActivityPayload.Type;