fix: address PR review feedback; remove HTML plan docs
- CI: client-runtime test imports @effect/vitest (vitest types unresolved in package context) - CodexSessionRuntime: divert child-thread events that arrive before subAgentActivity registers them (probe: child status/changed lands first); emit a terminal event on subAgent interruption - CodexAdapter: systemError -> failed; cumulative totalProcessedTokens for child usage (last-turn count can shrink on follow-ups) - Ingestion: waiting agents counted as active in roster summaries; reactivation clears stale resultSummary/errorMessage; usage fields validated as non-negative integers; failed snapshot dispatch drops the hydration marker so the roster re-syncs from persisted state - Panel/strip: idle counts as settled everywhere; phase labels show active counts (not '0 running'); parseTimestampDate for ISO parsing - Drop docs/project/plans HTML files Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
f99429b371
commit
0892ce3710
10 files changed
+189
-2723
No files matched your search
@@ -51,21 +51,29 @@ const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${t
|
||||
const AGENT_SETTLED_RETENTION_LIMIT = 50;
|
||||
const AGENT_USAGE_MATERIAL_STEP = 25_000;
|
||||
|
||||
// Fields must satisfy the contract's NonNegativeInt or the persisted roster
|
||||
// row becomes undecodable on the client.
|
||||
function usageCount(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined;
|
||||
}
|
||||
|
||||
function taskUsage(value: unknown): ThreadAgentUsage | undefined {
|
||||
if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
|
||||
const usage = value as Record<string, unknown>;
|
||||
if (typeof usage.totalTokens !== "number" || usage.totalTokens < 0) return undefined;
|
||||
const totalTokens = usageCount(usage.totalTokens);
|
||||
if (totalTokens === undefined) return undefined;
|
||||
const inputTokens = usageCount(usage.inputTokens);
|
||||
const cachedInputTokens = usageCount(usage.cachedInputTokens);
|
||||
const outputTokens = usageCount(usage.outputTokens);
|
||||
const reasoningOutputTokens = usageCount(usage.reasoningOutputTokens);
|
||||
const toolUses = usageCount(usage.toolUses);
|
||||
return {
|
||||
totalTokens: usage.totalTokens,
|
||||
...(typeof usage.inputTokens === "number" ? { inputTokens: usage.inputTokens } : {}),
|
||||
...(typeof usage.cachedInputTokens === "number"
|
||||
? { cachedInputTokens: usage.cachedInputTokens }
|
||||
: {}),
|
||||
...(typeof usage.outputTokens === "number" ? { outputTokens: usage.outputTokens } : {}),
|
||||
...(typeof usage.reasoningOutputTokens === "number"
|
||||
? { reasoningOutputTokens: usage.reasoningOutputTokens }
|
||||
: {}),
|
||||
...(typeof usage.toolUses === "number" ? { toolUses: usage.toolUses } : {}),
|
||||
totalTokens,
|
||||
...(inputTokens !== undefined ? { inputTokens } : {}),
|
||||
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
|
||||
...(outputTokens !== undefined ? { outputTokens } : {}),
|
||||
...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),
|
||||
...(toolUses !== undefined ? { toolUses } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -192,14 +200,16 @@ export function foldTaskAgentEvent(
|
||||
...((payload.outputFile ?? previous?.outputFile)
|
||||
? { outputFile: payload.outputFile ?? previous?.outputFile }
|
||||
: {}),
|
||||
// A re-activated agent starts a fresh run: prior result/error text would
|
||||
// read as the live run's output, so clear both unless this event sets them.
|
||||
...(event.type === "task.completed" && event.payload.summary
|
||||
? { resultSummary: event.payload.summary }
|
||||
: previous?.resultSummary
|
||||
: !reactivated && previous?.resultSummary
|
||||
? { resultSummary: previous.resultSummary }
|
||||
: {}),
|
||||
...(event.type === "task.updated" && event.payload.errorMessage
|
||||
? { errorMessage: event.payload.errorMessage }
|
||||
: previous?.errorMessage
|
||||
: !reactivated && previous?.errorMessage
|
||||
? { errorMessage: previous.errorMessage }
|
||||
: {}),
|
||||
recentActivity,
|
||||
@@ -1561,12 +1571,14 @@ const make = Effect.gen(function* () {
|
||||
if (agentRosterMaterial) {
|
||||
pruneSettledAgents(threadAgents);
|
||||
const roster = Array.from(threadAgents.values());
|
||||
const running = roster.filter((agent) => agent.status === "running").length;
|
||||
const settled = roster.filter(
|
||||
(agent) => agent.status === "idle" || THREAD_AGENT_TERMINAL_STATUSES.has(agent.status),
|
||||
// "active" covers everything non-settled (running/pending/waiting) so a
|
||||
// roster of blocked agents doesn't read as "0 agents settled".
|
||||
const active = roster.filter(
|
||||
(agent) => agent.status !== "idle" && !THREAD_AGENT_TERMINAL_STATUSES.has(agent.status),
|
||||
).length;
|
||||
const count = running > 0 ? running : settled;
|
||||
const summary = `${count} ${count === 1 ? "agent" : "agents"} ${running > 0 ? "running" : "settled"}`;
|
||||
const settled = roster.length - active;
|
||||
const count = active > 0 ? active : settled;
|
||||
const summary = `${count} ${count === 1 ? "agent" : "agents"} ${active > 0 ? "active" : "settled"}`;
|
||||
const snapshotUuid = yield* crypto.randomUUIDv4;
|
||||
const activity: OrchestrationThreadActivity = {
|
||||
id: EventId.make(`${event.eventId}:agent-snapshot:${snapshotUuid}`),
|
||||
@@ -1577,13 +1589,26 @@ const make = Effect.gen(function* () {
|
||||
payload: { agents: roster },
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
};
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: yield* providerCommandId(event, "agent-snapshot-append"),
|
||||
threadId: thread.id,
|
||||
activity,
|
||||
createdAt: activity.createdAt,
|
||||
});
|
||||
// The reducer map was already mutated; if the append fails, drop the
|
||||
// hydration marker so the next event re-hydrates from the last
|
||||
// *persisted* snapshot and re-detects the missed material change —
|
||||
// otherwise the roster silently stays stale until the next transition.
|
||||
yield* orchestrationEngine
|
||||
.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: yield* providerCommandId(event, "agent-snapshot-append"),
|
||||
threadId: thread.id,
|
||||
activity,
|
||||
createdAt: activity.createdAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.tapError(() =>
|
||||
Effect.sync(() => {
|
||||
hydratedAgentThreads.delete(thread.id);
|
||||
agentsByThread.delete(thread.id);
|
||||
}),
|
||||
),
|
||||
);
|
||||
agentSnapshotDispatchCount += 1;
|
||||
yield* Effect.logDebug("provider agent snapshot appended", {
|
||||
threadId: thread.id,
|
||||
|
||||
@@ -554,6 +554,14 @@ function mapCollabAgentActivity(
|
||||
payload: { taskId: base.payload.taskId, status: "idle", timelineBypass: true },
|
||||
},
|
||||
];
|
||||
case "subAgent/interrupted":
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
type: "task.completed",
|
||||
payload: { taskId: base.payload.taskId, status: "stopped", timelineBypass: true },
|
||||
},
|
||||
];
|
||||
case "thread/status/changed": {
|
||||
const payload = readPayload(
|
||||
EffectCodexSchema.V2ThreadStatusChangedNotification,
|
||||
@@ -576,6 +584,21 @@ function mapCollabAgentActivity(
|
||||
},
|
||||
];
|
||||
}
|
||||
if (status.type === "systemError") {
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
type: "task.completed",
|
||||
payload: {
|
||||
taskId: base.payload.taskId,
|
||||
status: "failed",
|
||||
summary: "Codex reported a system error for this agent",
|
||||
timelineBypass: true,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
// notLoaded/idle are covered by turn lifecycle events.
|
||||
return [];
|
||||
}
|
||||
case "thread/closed":
|
||||
@@ -600,7 +623,9 @@ function mapCollabAgentActivity(
|
||||
payload: {
|
||||
...base.payload,
|
||||
usage: {
|
||||
totalTokens: usage.usedTokens,
|
||||
// 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 }
|
||||
|
||||
@@ -586,7 +586,7 @@ function readRouteFields(notification: CodexServerNotification): {
|
||||
}
|
||||
|
||||
interface CollabChildAgent {
|
||||
readonly agentPath: string;
|
||||
readonly agentPath: string | undefined;
|
||||
readonly interrupted: boolean;
|
||||
}
|
||||
|
||||
@@ -595,23 +595,26 @@ interface CollabChildAgent {
|
||||
* the parent stream (the probe shows no child `thread/started`, and v2
|
||||
* `collabAgentToolCall` items carry empty receiver lists). Track them so their
|
||||
* notifications can be folded into agent telemetry instead of leaking into the
|
||||
* parent timeline as unattributed items.
|
||||
* parent timeline as unattributed items. Returns the interruption transition
|
||||
* when this notification carries one, so the caller can emit a terminal event.
|
||||
*/
|
||||
function rememberSubAgentActivity(
|
||||
childAgents: Map<string, CollabChildAgent>,
|
||||
notification: CodexServerNotification,
|
||||
): void {
|
||||
): { readonly agentThreadId: string; readonly agentPath: string } | undefined {
|
||||
if (notification.method !== "item/started" && notification.method !== "item/completed") {
|
||||
return;
|
||||
return undefined;
|
||||
}
|
||||
const item = notification.params.item;
|
||||
if (item.type !== "subAgentActivity") {
|
||||
return;
|
||||
return undefined;
|
||||
}
|
||||
childAgents.set(item.agentThreadId, {
|
||||
agentPath: item.agentPath,
|
||||
interrupted: item.kind === "interrupted",
|
||||
});
|
||||
const interrupted = item.kind === "interrupted";
|
||||
const previous = childAgents.get(item.agentThreadId);
|
||||
childAgents.set(item.agentThreadId, { agentPath: item.agentPath, interrupted });
|
||||
return interrupted && !previous?.interrupted
|
||||
? { agentThreadId: item.agentThreadId, agentPath: item.agentPath }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/** Synthetic method carrying an intercepted child-thread notification. */
|
||||
@@ -869,17 +872,49 @@ export const makeCodexSessionRuntime = (
|
||||
: undefined;
|
||||
|
||||
rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId);
|
||||
rememberSubAgentActivity(collabChildAgents, notification);
|
||||
const interruption = rememberSubAgentActivity(collabChildAgents, notification);
|
||||
yield* Ref.set(collabChildAgentsRef, collabChildAgents);
|
||||
if (interruption) {
|
||||
// Surface the interruption as its own child event so the agent
|
||||
// tracker can terminalize the child (the child thread itself goes
|
||||
// silent when interrupted).
|
||||
yield* emitEvent({
|
||||
kind: "notification",
|
||||
threadId: options.threadId,
|
||||
method: COLLAB_AGENT_ACTIVITY_METHOD,
|
||||
payload: {
|
||||
agentThreadId: interruption.agentThreadId,
|
||||
agentPath: interruption.agentPath,
|
||||
method: "subAgent/interrupted",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// v2 collab child threads: their notifications arrive on this
|
||||
// connection keyed by the child threadId. Divert the whole stream into
|
||||
// a synthetic collab/agentActivity event for the agent tracker and keep
|
||||
// it out of the parent timeline.
|
||||
const childAgent = notificationThreadId
|
||||
// it out of the parent timeline. A child's first event can arrive
|
||||
// BEFORE the parent's subAgentActivity registers it (probe: child
|
||||
// thread/status/changed lands first), so any thread that is neither
|
||||
// the session's own provider thread nor a v1 collab receiver is
|
||||
// treated as an unregistered child.
|
||||
const providerThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));
|
||||
const knownChild = notificationThreadId
|
||||
? collabChildAgents.get(notificationThreadId)
|
||||
: undefined;
|
||||
if (childAgent && notificationThreadId) {
|
||||
const isForeignThread =
|
||||
notificationThreadId !== undefined &&
|
||||
providerThreadId !== undefined &&
|
||||
notificationThreadId !== providerThreadId &&
|
||||
!collabReceiverTurns.has(notificationThreadId);
|
||||
if (notificationThreadId && (knownChild || isForeignThread)) {
|
||||
if (!knownChild) {
|
||||
yield* Ref.update(collabChildAgentsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
next.set(notificationThreadId, { agentPath: undefined, interrupted: false });
|
||||
return next;
|
||||
});
|
||||
}
|
||||
yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);
|
||||
yield* emitEvent({
|
||||
kind: "notification",
|
||||
@@ -887,7 +922,7 @@ export const makeCodexSessionRuntime = (
|
||||
method: COLLAB_AGENT_ACTIVITY_METHOD,
|
||||
payload: {
|
||||
agentThreadId: notificationThreadId,
|
||||
agentPath: childAgent.agentPath,
|
||||
...(knownChild?.agentPath ? { agentPath: knownChild.agentPath } : {}),
|
||||
method: notification.method,
|
||||
params: payload,
|
||||
},
|
||||
|
||||
@@ -12,6 +12,7 @@ import { cn } from "~/lib/utils";
|
||||
import { Badge } from "./ui/badge";
|
||||
import { ScrollArea } from "./ui/scroll-area";
|
||||
import { formatDuration } from "../session-logic";
|
||||
import { parseTimestampDate } from "../timestampFormat";
|
||||
|
||||
interface AgentsPanelProps {
|
||||
agents: ReadonlyArray<ThreadAgentSnapshot>;
|
||||
@@ -57,19 +58,18 @@ function AgentStatusDot({ status }: { status: ThreadAgentSnapshot["status"] }) {
|
||||
function AgentElapsed({ agent }: { agent: ThreadAgentSnapshot }) {
|
||||
const textRef = useRef<HTMLSpanElement>(null);
|
||||
const settled = isTerminalAgentStatus(agent.status) || agent.status === "idle";
|
||||
const startMs = Date.parse(agent.firstStartedAt);
|
||||
const endMs = agent.endedAt
|
||||
? Date.parse(agent.endedAt)
|
||||
: settled
|
||||
? Date.parse(agent.lastActivityAt)
|
||||
: null;
|
||||
const initialText = formatDuration((endMs ?? Date.now()) - startMs);
|
||||
const startMs = parseTimestampDate(agent.firstStartedAt)?.getTime() ?? null;
|
||||
const endMs =
|
||||
(agent.endedAt ? parseTimestampDate(agent.endedAt)?.getTime() : null) ??
|
||||
(settled ? (parseTimestampDate(agent.lastActivityAt)?.getTime() ?? null) : null);
|
||||
const initialText =
|
||||
startMs === null ? null : formatDuration(Math.max(0, (endMs ?? Date.now()) - startMs));
|
||||
|
||||
useEffect(() => {
|
||||
if (endMs !== null) return;
|
||||
if (startMs === null || endMs !== null) return;
|
||||
const update = () => {
|
||||
if (textRef.current) {
|
||||
textRef.current.textContent = formatDuration(Date.now() - startMs);
|
||||
textRef.current.textContent = formatDuration(Math.max(0, Date.now() - startMs));
|
||||
}
|
||||
};
|
||||
update();
|
||||
@@ -77,6 +77,9 @@ function AgentElapsed({ agent }: { agent: ThreadAgentSnapshot }) {
|
||||
return () => clearInterval(id);
|
||||
}, [startMs, endMs]);
|
||||
|
||||
if (initialText === null) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<span ref={textRef} className="font-mono text-[11px] tabular-nums text-muted-foreground">
|
||||
{initialText}
|
||||
@@ -183,8 +186,12 @@ function AgentCard({ agent }: { agent: ThreadAgentSnapshot }) {
|
||||
}
|
||||
|
||||
function PhaseHeader({ phase }: { phase: AgentPanelPhase }) {
|
||||
const runningCount = phase.agents.filter((agent) => agent.status === "running").length;
|
||||
const doneCount = phase.agents.filter((agent) => isTerminalAgentStatus(agent.status)).length;
|
||||
// "active" (not just status==="running"): a phase whose agents are all
|
||||
// pending/waiting is still in progress and must not read "0 running".
|
||||
const doneCount = phase.agents.filter(
|
||||
(agent) => agent.status === "idle" || isTerminalAgentStatus(agent.status),
|
||||
).length;
|
||||
const activeCount = phase.agents.length - doneCount;
|
||||
return (
|
||||
<div className="flex items-center gap-2 px-1 pt-2 pb-1 text-[10px] text-muted-foreground">
|
||||
<span
|
||||
@@ -200,7 +207,7 @@ function PhaseHeader({ phase }: { phase: AgentPanelPhase }) {
|
||||
</span>
|
||||
{phase.status === "running" ? (
|
||||
<span>
|
||||
{runningCount} running{doneCount > 0 ? ` · ${doneCount} done` : ""}
|
||||
{activeCount} active{doneCount > 0 ? ` · ${doneCount} done` : ""}
|
||||
</span>
|
||||
) : phase.status === "pending" ? (
|
||||
<span>pending</span>
|
||||
|
||||
@@ -48,8 +48,13 @@ const AgentsLiveStrip = memo(function AgentsLiveStrip({
|
||||
) : null}
|
||||
{runningPhase ? (
|
||||
<span className="truncate text-muted-foreground">
|
||||
{runningPhase.title} · {runningPhase.agents.filter((a) => a.status === "running").length}{" "}
|
||||
running
|
||||
{runningPhase.title} ·{" "}
|
||||
{
|
||||
runningPhase.agents.filter(
|
||||
(a) => a.status === "running" || a.status === "pending" || a.status === "waiting",
|
||||
).length
|
||||
}{" "}
|
||||
active
|
||||
</span>
|
||||
) : null}
|
||||
<span className="ml-auto shrink-0 font-mono text-[11px] tabular-nums text-muted-foreground">
|
||||
|
||||
@@ -40,7 +40,7 @@ function getTimestampFormatter(
|
||||
return formatter;
|
||||
}
|
||||
|
||||
function parseTimestampDate(isoDate: string): Date | null {
|
||||
export function parseTimestampDate(isoDate: string): Date | null {
|
||||
const date = new Date(isoDate);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import type { OrchestrationThreadActivity, ThreadAgentSnapshot } from "@t3tools/contracts";
|
||||
import {
|
||||
deriveAgentPanelState,
|
||||
|
||||
@@ -9,13 +9,35 @@
|
||||
import {
|
||||
THREAD_AGENT_TERMINAL_STATUSES,
|
||||
THREAD_AGENTS_ACTIVITY_KIND,
|
||||
ThreadAgentsActivityPayload,
|
||||
ThreadAgentSnapshot,
|
||||
type OrchestrationThreadActivity,
|
||||
type ThreadAgentSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const decodePayload = Schema.decodeUnknownOption(ThreadAgentsActivityPayload);
|
||||
const decodeAgent = Schema.decodeUnknownOption(ThreadAgentSnapshot);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
function decodeRoster(payload: unknown): ReadonlyArray<ThreadAgentSnapshot> | undefined {
|
||||
if (payload === null || typeof payload !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const agents = (payload as { agents?: unknown }).agents;
|
||||
if (!Array.isArray(agents)) {
|
||||
return undefined;
|
||||
}
|
||||
const decoded: ThreadAgentSnapshot[] = [];
|
||||
for (const candidate of agents) {
|
||||
const result = decodeAgent(candidate);
|
||||
if (result._tag === "Some") {
|
||||
decoded.push(result.value);
|
||||
}
|
||||
}
|
||||
return agents.length === 0 || decoded.length > 0 ? decoded : undefined;
|
||||
}
|
||||
|
||||
export function deriveLatestAgentSnapshot(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
@@ -25,9 +47,9 @@ export function deriveLatestAgentSnapshot(
|
||||
if (!activity || activity.kind !== THREAD_AGENTS_ACTIVITY_KIND) {
|
||||
continue;
|
||||
}
|
||||
const decoded = decodePayload(activity.payload);
|
||||
if (decoded._tag === "Some") {
|
||||
return decoded.value.agents;
|
||||
const roster = decodeRoster(activity.payload);
|
||||
if (roster !== undefined) {
|
||||
return roster;
|
||||
}
|
||||
}
|
||||
return [];
|
||||
@@ -60,9 +82,15 @@ export interface AgentPanelState {
|
||||
readonly totalTokens: number;
|
||||
}
|
||||
|
||||
function isSettledAgentStatus(status: ThreadAgentSnapshot["status"]): boolean {
|
||||
// idle counts as settled for phase/summary purposes: the run finished even
|
||||
// though the agent identity could be resumed.
|
||||
return status === "idle" || isTerminalAgentStatus(status);
|
||||
}
|
||||
|
||||
function phaseStatus(agents: ReadonlyArray<ThreadAgentSnapshot>): "pending" | "running" | "done" {
|
||||
if (agents.length === 0) return "pending";
|
||||
if (agents.every((agent) => isTerminalAgentStatus(agent.status))) return "done";
|
||||
if (agents.every((agent) => isSettledAgentStatus(agent.status))) return "done";
|
||||
return "running";
|
||||
}
|
||||
|
||||
@@ -119,7 +147,7 @@ export function deriveAgentPanelState(agents: ReadonlyArray<ThreadAgentSnapshot>
|
||||
for (const agent of agents) {
|
||||
if (agent.status === "running" || agent.status === "pending") runningCount += 1;
|
||||
else if (agent.status === "waiting") waitingCount += 1;
|
||||
else if (isTerminalAgentStatus(agent.status)) settledCount += 1;
|
||||
else settledCount += 1; // idle + terminal
|
||||
totalTokens += agent.usage?.totalTokens ?? 0;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user