From a40376b28f77240ce2c9bedee1d82fb3573950e1 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Tue, 21 Jul 2026 20:54:59 -0700 Subject: [PATCH] fix: dual-review pass (Fable + gpt-5.6-sol high) on rebased branch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bot rounds (Macroscope/Bugbot): - taskKind: explicit shell/monitor types win over parentTaskId fallback - lastStartedAt per activation; elapsed timers exclude idle gaps - client revision selection uses (revision ?? -1) matching server hydration - orphan-sweep append retries once on session.exited (often the last event) - live-strip wrapper keyed off hasLiveAgents (no phantom spacer) gpt-5.6-sol (high): - thread.reverted now invalidates the cached roster (no resurrecting reverted agents); new domain-event subscription - endedAt: explicit > existing > first-terminal ingestion time - roster strings bounded at 180 chars (recentActivity + currentActivity) - task_updated.patch.description maps to name - empty failed workflow renders its container card Fable: - deriveLatestAgentSnapshot picks the winner by peeking revision, decodes only that roster (was: full schema-decode of every roster per recompute) - idle Codex children get their own retention cap (25) — they never reach terminal status mid-session, so they were unbounded - v1 collab receivers re-checked inside the v2 diversion branch (arrival- order race); task usage schema committed to typed RuntimeTaskUsage; Claude usage carries input/output/cache breakdowns; assorted nits Co-Authored-By: Claude Fable 5 --- .../Layers/ProviderRuntimeIngestion.ts | 116 +++++++++++++----- .../src/provider/Layers/ClaudeAdapter.ts | 10 +- .../provider/Layers/CodexSessionRuntime.ts | 11 +- apps/web/src/components/AgentsPanel.tsx | 22 +++- apps/web/src/components/ChatView.tsx | 12 +- .../src/components/chat/AgentsLiveStrip.tsx | 2 + .../client-runtime/src/state/threadAgents.ts | 68 +++++----- packages/contracts/src/providerRuntime.ts | 4 +- packages/contracts/src/threadAgents.ts | 8 +- 9 files changed, 177 insertions(+), 76 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index aa4d62f828..6c4b81fcff 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -49,6 +49,7 @@ import { ServerSettingsService } from "../../serverSettings.ts"; const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`; const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`; const AGENT_SETTLED_RETENTION_LIMIT = 50; +const AGENT_IDLE_RETENTION_LIMIT = 25; const AGENT_USAGE_MATERIAL_STEP = 25_000; // Fields must satisfy the contract's NonNegativeInt or the persisted roster @@ -91,9 +92,12 @@ function taskStatus(event: ProviderRuntimeEvent): ThreadAgentStatus | undefined function taskKind(taskType: string | undefined, parentTaskId: string | undefined) { if (taskType === "local_agent") return "subagent" as const; if (taskType === "local_workflow") return "workflow" as const; - if (taskType === "workflow_agent" || parentTaskId) return "workflow_agent" as const; + if (taskType === "workflow_agent") return "workflow_agent" as const; if (taskType === "local_bash" || taskType === "shell") return "shell" as const; if (taskType === "monitor") return "monitor" as const; + // Parent linkage is only a workflow-membership hint when the type itself is + // unknown — a nested shell/monitor task keeps its explicit kind above. + if (parentTaskId) return "workflow_agent" as const; return "other" as const; } @@ -127,6 +131,13 @@ function workflowPhasesEqual( ); } +const AGENT_TEXT_LIMIT = 180; + +/** Roster snapshots duplicate these strings on every append — keep them small. */ +function boundAgentText(value: string): string { + return value.length > AGENT_TEXT_LIMIT ? `${value.slice(0, AGENT_TEXT_LIMIT - 1)}…` : value; +} + export function foldTaskAgentEvent( agents: Map, event: Extract< @@ -144,16 +155,23 @@ export function foldTaskAgentEvent( 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 + const rawCurrentActivity = settledNow ? undefined : (summary ?? lastToolName ?? previous?.currentActivity); + const currentActivity = + rawCurrentActivity === undefined ? undefined : boundAgentText(rawCurrentActivity); const activityChanged = (summary !== undefined && summary !== previous?.currentActivity) || (lastToolName !== undefined && lastToolName !== previous?.lastToolName); const recentActivity = activityChanged ? [ ...(previous?.recentActivity ?? []), - { at: event.createdAt, summary: summary ?? lastToolName ?? "Activity updated" }, + { + at: event.createdAt, + // Bounded: Codex child item summaries can carry full command/item + // text, and each entry is duplicated into every roster snapshot. + summary: boundAgentText(summary ?? lastToolName ?? "Activity updated"), + }, ].slice(-THREAD_AGENT_RECENT_ACTIVITY_LIMIT) : (previous?.recentActivity ?? []); const wasSettled = @@ -192,9 +210,19 @@ export function foldTaskAgentEvent( ? { usage: { ...previous?.usage, ...nextUsage } as ThreadAgentUsage } : {}), firstStartedAt: previous?.firstStartedAt ?? event.createdAt, + // Reset per activation so live timers exclude idle gaps between runs. + lastStartedAt: reactivated + ? event.createdAt + : (previous?.lastStartedAt ?? previous?.firstStartedAt ?? event.createdAt), lastActivityAt: event.createdAt, - ...(!reactivated && (explicitEndTime ?? (terminal ? event.createdAt : previous?.endedAt)) - ? { endedAt: explicitEndTime ?? (terminal ? event.createdAt : previous?.endedAt) } + // Prefer the provider's explicit end time, then an already-recorded one; + // only stamp ingestion time on the FIRST terminal transition so duplicate + // terminal events don't keep sliding the end forward. + ...(!reactivated && + (explicitEndTime ?? previous?.endedAt ?? (terminal ? event.createdAt : undefined)) + ? { + endedAt: explicitEndTime ?? previous?.endedAt ?? (terminal ? event.createdAt : undefined), + } : {}), activationCount: previous ? previous.activationCount + (reactivated ? 1 : 0) : 1, ...((event.turnId ?? previous?.lastTurnId) @@ -259,9 +287,7 @@ export function foldTaskAgentEvent( } export function pruneSettledAgents(agents: Map): 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. + // Terminal agents are history and compete for the standard retention pool. const settled = Array.from(agents.values()) .filter((agent) => THREAD_AGENT_TERMINAL_STATUSES.has(agent.status)) .sort((left, right) => left.lastActivityAt.localeCompare(right.lastActivityAt)); @@ -271,6 +297,19 @@ export function pruneSettledAgents(agents: Map): vo )) { agents.delete(agent.agentId); } + // Idle agents are resumable identities, so they get their own (generous) + // cap rather than sharing the terminal pool — but Codex children end every + // run idle and never terminal until close/interrupt, so without a bound a + // long session accumulates them all and every material append persists the + // full roster. Evicting oldest-idle is safe: a resumed identity + // re-registers from its next event (the activation counter tolerates the + // restart). + const idle = Array.from(agents.values()) + .filter((agent) => agent.status === "idle") + .sort((left, right) => left.lastActivityAt.localeCompare(right.lastActivityAt)); + for (const agent of idle.slice(0, Math.max(0, idle.length - AGENT_IDLE_RETENTION_LIMIT))) { + agents.delete(agent.agentId); + } } // Fallback when the in-memory description cache no longer has the task name @@ -325,9 +364,9 @@ const TASK_DESCRIPTION_BY_TASK_TTL = Duration.minutes(120); const MAX_BUFFERED_ASSISTANT_CHARS = 24_000; const STRICT_PROVIDER_LIFECYCLE_GUARD = process.env.T3CODE_STRICT_PROVIDER_LIFECYCLE_GUARD !== "0"; -type TurnStartRequestedDomainEvent = Extract< +type IngestionDomainEvent = Extract< OrchestrationEvent, - { type: "thread.turn-start-requested" } + { type: "thread.turn-start-requested" | "thread.reverted" } >; type RuntimeIngestionInput = @@ -337,7 +376,7 @@ type RuntimeIngestionInput = } | { source: "domain"; - event: TurnStartRequestedDomainEvent; + event: IngestionDomainEvent; }; function toTurnId(value: TurnId | string | undefined): TurnId | undefined { @@ -1565,13 +1604,9 @@ const make = Effect.gen(function* () { // message deltas after a restart must not each trigger a full // thread-detail load through the serialized ingestion worker. const eventTouchesAgents = isTaskAgentEvent(event) || event.type === "session.exited"; - const unhydratedActivityPressure = - !hydratedAgentThreads.has(thread.id) && + const activityPressure = (activitiesSinceAgentSnapshot.get(thread.id) ?? 0) >= AGENT_SNAPSHOT_REFRESH_ACTIVITY_COUNT; - if ( - (eventTouchesAgents || unhydratedActivityPressure) && - !hydratedAgentThreads.has(thread.id) - ) { + if ((eventTouchesAgents || activityPressure) && !hydratedAgentThreads.has(thread.id)) { const detail = yield* getLoadedThreadDetail(); const activityList = detail?.activities ?? []; // Select the snapshot the same way the client does — highest revision @@ -1686,7 +1721,7 @@ const make = Effect.gen(function* () { // never block the rest of this event's ingestion (message deltas, // session status, timeline activities). Interrupts still propagate. pendingRosterRedispatch.add(thread.id); - yield* orchestrationEngine + const appendSnapshot = orchestrationEngine .dispatch({ type: "thread.activity.append", commandId: yield* providerCommandId(event, "agent-snapshot-append"), @@ -1708,16 +1743,24 @@ const make = Effect.gen(function* () { }); }), ), - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) - ? Effect.failCause(cause) - : Effect.logWarning("provider agent snapshot append failed; will re-dispatch", { - threadId: thread.id, - agentCount: roster.length, - cause: Cause.pretty(cause), - }), - ), ); + // session.exited is often the thread's LAST event — the usual + // "re-dispatch on the next event" recovery never fires, so retry the + // final orphan-sweep roster once before giving up on it. + yield* appendSnapshot.pipe( + event.type === "session.exited" + ? Effect.retry({ times: 1 }) + : (effect: typeof appendSnapshot) => effect, + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.failCause(cause) + : Effect.logWarning("provider agent snapshot append failed; will re-dispatch", { + threadId: thread.id, + agentCount: roster.length, + cause: Cause.pretty(cause), + }), + ), + ); } // Sessions are done producing agent events once they exit; release the @@ -2212,7 +2255,22 @@ const make = Effect.gen(function* () { ).pipe(Effect.asVoid); }); - const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void; + const processDomainEvent = (event: IngestionDomainEvent) => + Effect.sync(() => { + if (event.type !== "thread.reverted") { + return; + } + // A checkpoint revert pruned reverted-turn activities (including agent + // snapshots) from the projection. Drop the cached roster so the next + // agent event rehydrates from post-revert state instead of folding a + // stale map and resurrecting reverted agents. + const threadId = event.payload.threadId; + agentsByThread.delete(threadId); + hydratedAgentThreads.delete(threadId); + activitiesSinceAgentSnapshot.delete(threadId); + agentRosterRevision.delete(threadId); + pendingRosterRedispatch.delete(threadId); + }); const processInput = (input: RuntimeIngestionInput) => input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event); @@ -2243,7 +2301,7 @@ const make = Effect.gen(function* () { ); yield* Effect.forkScoped( Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => { - if (event.type !== "thread.turn-start-requested") { + if (event.type !== "thread.turn-start-requested" && event.type !== "thread.reverted") { return Effect.void; } return worker.enqueue({ source: "domain", event }); diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 0fb9f372ad..a40d8e2e9c 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -723,8 +723,14 @@ function normalizeRuntimeTaskUsage(value: unknown) { } const toolUses = readNonNegativeInteger(usage.tool_uses); const durationMs = readNonNegativeInteger(usage.duration_ms); + const inputTokens = readNonNegativeInteger(usage.input_tokens); + const outputTokens = readNonNegativeInteger(usage.output_tokens); + const cachedInputTokens = readNonNegativeInteger(usage.cache_read_input_tokens); return { totalTokens, + ...(inputTokens !== undefined ? { inputTokens } : {}), + ...(outputTokens !== undefined ? { outputTokens } : {}), + ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}), ...(toolUses !== undefined ? { toolUses } : {}), ...(durationMs !== undefined ? { durationMs } : {}), }; @@ -2895,12 +2901,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( } case "task_updated": { const record = message as unknown as Record; - // SDK shape: {task_id, patch: {status?, end_time?, is_backgrounded?, error?}} + // SDK shape: {task_id, patch: {status?, description?, end_time?, is_backgrounded?, error?}} const patch = record.patch !== null && typeof record.patch === "object" && !Array.isArray(record.patch) ? (record.patch as Record) : {}; const status = readString(patch.status); + const patchedDescription = readString(patch.description); const endTime = typeof patch.end_time === "number" ? epochMillisToIso(patch.end_time) : undefined; yield* offerRuntimeEvent({ @@ -2917,6 +2924,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( ? { status } : {}), ...(endTime ? { endTime } : {}), + ...(patchedDescription ? { name: patchedDescription } : {}), ...(typeof patch.is_backgrounded === "boolean" ? { isBackgrounded: patch.is_backgrounded } : {}), diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index ab21b3eaa1..c66e132122 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -899,9 +899,14 @@ export const makeCodexSessionRuntime = ( // 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; + // Re-check v1 receiver registration on every notification: if a + // thread was provisionally classified as a v2 child before the + // parent's collabAgentToolCall arrived, hand it back to the v1 + // suppression path once the receiver registration lands. + const knownChild = + notificationThreadId && !collabReceiverTurns.has(notificationThreadId) + ? collabChildAgents.get(notificationThreadId) + : undefined; const isForeignThread = notificationThreadId !== undefined && providerThreadId !== undefined && diff --git a/apps/web/src/components/AgentsPanel.tsx b/apps/web/src/components/AgentsPanel.tsx index 0a8ad6234d..7b6752d40b 100644 --- a/apps/web/src/components/AgentsPanel.tsx +++ b/apps/web/src/components/AgentsPanel.tsx @@ -58,7 +58,10 @@ function AgentStatusDot({ status }: { status: ThreadAgentSnapshot["status"] }) { function AgentElapsed({ agent }: { agent: ThreadAgentSnapshot }) { const textRef = useRef(null); const settled = isTerminalAgentStatus(agent.status) || agent.status === "idle"; - const startMs = parseTimestampDate(agent.firstStartedAt)?.getTime() ?? null; + // Current-activation start (falls back to firstStartedAt for pre-field + // snapshots) so a resumed agent's timer excludes prior runs and idle gaps. + const startMs = + parseTimestampDate(agent.lastStartedAt ?? agent.firstStartedAt)?.getTime() ?? null; const endMs = (agent.endedAt ? parseTimestampDate(agent.endedAt)?.getTime() : null) ?? (settled ? (parseTimestampDate(agent.lastActivityAt)?.getTime() ?? null) : null); @@ -93,7 +96,7 @@ function AgentCard({ agent }: { agent: ThreadAgentSnapshot }) { // Settled cards lead with outcome (error first); live cards with activity. const activity = agent.status === "waiting" - ? "Waiting on approval" + ? "Waiting on approval or input" : settled || agent.status === "idle" ? (agent.errorMessage ?? agent.resultSummary ?? @@ -119,7 +122,7 @@ function AgentCard({ agent }: { agent: ThreadAgentSnapshot }) { {agent.name} {agent.agentType ? ( - + {agent.agentType} ) : null} @@ -262,6 +265,19 @@ function AgentGroup({ )} + {/* A failed/errored workflow with no member rows would otherwise render + as a bare header — surface the container itself so its status and + error are visible. */} + {group.workflow && + group.rest.length === 0 && + group.phases.every((phase) => phase.agents.length === 0) && + (group.workflow.status === "failed" || + group.workflow.status === "stopped" || + group.workflow.errorMessage) ? ( +
+ +
+ ) : null} {group.phases.map((phase) => (
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 8648ad7fe7..aabf86521a 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1869,6 +1869,16 @@ function ChatViewContent(props: ChatViewProps) { () => deriveLatestAgentSnapshot(threadActivities), [threadActivities], ); + // Mirrors AgentsLiveStrip's own visibility rule so the wrapper doesn't + // reserve space (mb-1.5) after all agents settle. + const hasLiveAgents = useMemo( + () => + threadAgents.some( + (agent) => + agent.status === "running" || agent.status === "pending" || agent.status === "waiting", + ), + [threadAgents], + ); const pendingApprovals = useMemo( () => derivePendingApprovals(threadActivities), [threadActivities], @@ -5380,7 +5390,7 @@ function ChatViewContent(props: ChatViewProps) { ) : ( )} - {threadAgents.length > 0 ? ( + {hasLiveAgents ? (
diff --git a/apps/web/src/components/chat/AgentsLiveStrip.tsx b/apps/web/src/components/chat/AgentsLiveStrip.tsx index f85f8d9051..81aee88627 100644 --- a/apps/web/src/components/chat/AgentsLiveStrip.tsx +++ b/apps/web/src/components/chat/AgentsLiveStrip.tsx @@ -21,6 +21,8 @@ const AgentsLiveStrip = memo(function AgentsLiveStrip({ const state = deriveAgentPanelState(agents); const liveCount = state.runningCount + state.waitingCount; if (liveCount === 0) { + // Parent wrappers must not reserve space when nothing renders (the + // caller keys visibility off hasLiveAgents with the same derivation). return null; } diff --git a/packages/client-runtime/src/state/threadAgents.ts b/packages/client-runtime/src/state/threadAgents.ts index fbe114ab5b..0bdf496bc0 100644 --- a/packages/client-runtime/src/state/threadAgents.ts +++ b/packages/client-runtime/src/state/threadAgents.ts @@ -3,8 +3,8 @@ * * The server ships the full per-thread roster latest-wins in the payload of * `agent.snapshot` activities (see `@t3tools/contracts` ThreadAgentsActivityPayload). - * Mirrors the `context-window.updated` pattern: scan activities newest-first, - * decode tolerantly, ignore rows that fail to decode. + * Mirrors the `context-window.updated` pattern: select the newest roster + * (highest revision), decode tolerantly, skip rows that fail to decode. */ import { THREAD_AGENT_TERMINAL_STATUSES, @@ -16,19 +16,12 @@ import * as Schema from "effect/Schema"; const decodeAgent = Schema.decodeUnknownOption(ThreadAgentSnapshot); -interface DecodedRoster { - readonly agents: ReadonlyArray; - readonly revision: number | undefined; +interface RosterCandidate { + readonly payload: { readonly agents: ReadonlyArray }; + readonly revision: number; } -/** - * Rows decode per-element: one malformed or forward-incompatible agent entry - * 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): DecodedRoster | undefined { +function peekRoster(payload: unknown): RosterCandidate | undefined { if (payload === null || typeof payload !== "object") { return undefined; } @@ -36,44 +29,49 @@ function decodeRoster(payload: unknown): DecodedRoster | undefined { if (!Array.isArray(record.agents)) { return undefined; } - const decoded: ThreadAgentSnapshot[] = []; - for (const candidate of record.agents) { - const result = decodeAgent(candidate); - if (result._tag === "Some") { - decoded.push(result.value); - } - } return { - agents: decoded, + payload: record as RosterCandidate["payload"], + // Missing revision ranks lowest (-1), mirroring server hydration: a + // revision-less legacy roster never beats a revisioned one, and among + // equals the later list position wins. revision: typeof record.revision === "number" && Number.isInteger(record.revision) ? record.revision - : undefined, + : -1, }; } export function deriveLatestAgentSnapshot( activities: ReadonlyArray, ): ReadonlyArray { - // 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; + // Two passes so only ONE roster is schema-decoded per recompute: rosters + // can dominate the 500-row activity window in busy sessions, and this runs + // inside a useMemo that re-fires on every activities change. Winner = + // highest revision, later list position breaking ties. + let best: RosterCandidate | undefined; for (const activity of activities) { if (activity.kind !== THREAD_AGENTS_ACTIVITY_KIND) { continue; } - const roster = decodeRoster(activity.payload); - if (!roster) { - continue; - } - if (!best || roster.revision === undefined || best.revision === undefined) { - best = roster; - } else if (roster.revision >= best.revision) { - best = roster; + const candidate = peekRoster(activity.payload); + if (candidate && (!best || candidate.revision >= best.revision)) { + best = candidate; } } - return best?.agents ?? []; + if (!best) { + return []; + } + // The winning roster is authoritative: rows decode per-element (one bad row + // is skipped, the rest kept), and a fully undecodable roster yields an + // empty panel rather than resurrecting an older snapshot. + const decoded: ThreadAgentSnapshot[] = []; + for (const candidate of best.payload.agents) { + const result = decodeAgent(candidate); + if (result._tag === "Some") { + decoded.push(result.value); + } + } + return decoded; } export function isTerminalAgentStatus(status: ThreadAgentSnapshot["status"]): boolean { diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts index 2b86b18a93..99ca1050f4 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -518,7 +518,7 @@ const TaskProgressPayload = Schema.Struct({ taskId: RuntimeTaskId, description: TrimmedNonEmptyStringSchema, summary: Schema.optional(TrimmedNonEmptyStringSchema), - usage: Schema.optional(Schema.Union([RuntimeTaskUsage, Schema.Unknown])), + usage: Schema.optional(RuntimeTaskUsage), lastToolName: Schema.optional(TrimmedNonEmptyStringSchema), ...TaskAgentLinkage, }); @@ -555,7 +555,7 @@ const TaskCompletedPayload = Schema.Struct({ taskId: RuntimeTaskId, status: Schema.Literals(["completed", "failed", "stopped"]), summary: Schema.optional(TrimmedNonEmptyStringSchema), - usage: Schema.optional(Schema.Union([RuntimeTaskUsage, Schema.Unknown])), + usage: Schema.optional(RuntimeTaskUsage), ...TaskAgentLinkage, }); export type TaskCompletedPayload = typeof TaskCompletedPayload.Type; diff --git a/packages/contracts/src/threadAgents.ts b/packages/contracts/src/threadAgents.ts index 3a50a56831..02d5021ac0 100644 --- a/packages/contracts/src/threadAgents.ts +++ b/packages/contracts/src/threadAgents.ts @@ -96,6 +96,10 @@ export const ThreadAgentSnapshot = Schema.Struct({ lastToolName: Schema.optional(TrimmedNonEmptyString), usage: Schema.optional(ThreadAgentUsage), firstStartedAt: IsoDateTime, + // Start of the CURRENT activation. Live elapsed timers derive from this so + // idle gaps between resumptions don't inflate the display; absent on + // pre-field snapshots (clients fall back to firstStartedAt). + lastStartedAt: Schema.optional(IsoDateTime), lastActivityAt: IsoDateTime, // Cleared when a re-activation (Codex follow-up) starts a new run. endedAt: Schema.optional(IsoDateTime), @@ -112,9 +116,9 @@ export const ThreadAgentSnapshot = Schema.Struct({ phases: Schema.optional(Schema.Array(ThreadAgentWorkflowPhase)), scriptPath: Schema.optional(TrimmedNonEmptyString), runId: Schema.optional(TrimmedNonEmptyString), - // Set while waiting on an approval so the UI can deep-link to the request. + // Reserved for the approval deep-link milestone; no emitter populates it yet. approvalRequestId: Schema.optional(ApprovalRequestId), - // Claude transcript/output path; the drill-in RPC reads it on demand. + // Claude transcript/output path; reserved for the transcript drill-in milestone. outputFile: Schema.optional(TrimmedNonEmptyString), resultSummary: Schema.optional(TrimmedNonEmptyString), errorMessage: Schema.optional(TrimmedNonEmptyString),