Repository navigation
🤖 fix: refresh the parent's Costs tab when a sub-agent's usage changes - #7867
Conversation
|
Live check recording (parent Stats tab open; sub-agent usage driven through the sandbox server's own SessionUsageService): live-check.webm |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7717376878
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
🟢 e2e stories (Haiku): 14 passed22 agent steps · 7 replayed from cache · 15 model calls · 47.3k tokens (23% cached) All 14 tests in 9 files
e2e 0.20.0 · 1m 14s · web · run artifacts 🟢 e2e Electron stories (Haiku): 3 passed3 agent steps · 3 model calls · 8.0k tokens (22% cached) All 3 tests in 3 files
e2e 0.20.0 · 23.6s · electron · run artifacts 🟢 e2e agent repros (Haiku): no tests selectedSpend: $0.00 of the $1.00 cap (proxy ledger) e2e 0.20.0 · 5.8s · 2 targets (web, phone) · run artifacts |
…eave self deltas to the revision refetch
🛡️ Codex Security Review · Automatically triggeredSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1db8c82f60
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ef165a94fb
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…rs when a sub-agent registers
🛡️ Codex Security Review · Automatically triggeredSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3cdf74cc58
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
A usage move re-read and rebroadcast the activity snapshot. That read could resolve after a newer activity emit and resend older activity (streaming=true after the stop), and a failed read dropped the move. The activity subscription now carries a usage-revision event with no snapshot read. activity.list still carries each workspace's revision, so a resubscribe sees moves it missed.
…ption complexity flat
🛡️ Codex Security Review · Automatically triggeredSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 00032bf3b3
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…ge on resubscribe Drop the usage revision: its clock seed, its activity.list overlay and the UsageRevisionActivity module. Each usage write sends usage-changed on the activity subscription. A resubscribe does not replay missed events, so the re-list refetches every shown workspace's usage (projection only while its own stream is live here).
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
🛡️ Codex Security Review · Automatically triggeredSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
Summary
The Costs tab of a parent now follows its sub-agents' spend while they run, after their last stream, and when a roll-up delta never reaches the parent's chat. Every write to a workspace's usage files sends a
usage-changedevent for that workspace on the activity subscription. The store refetches the usage it shows for each event, and keeps at most one projection fetch in flight per parent plus one trailing fetch. Refs #7862 (items 1, 3 and 4).Background
After #7861 the parent's total can stay low, because nothing tells the parent's view that a descendant's usage changed:
refreshAncestorsWhenStreamEnds, on the streaming true->false activity transition).session-usage-deltato the sub-agent's own chat only, and never refreshed the ancestors.session-usage-deltaon sub-agent removal is emitted only when the parent has a liveAgentSession, and the store gets it only while it is subscribed to the parent's chat.Implementation
Data shape.
workspace.activity.subscribegets a third event type,{ type: "usage-changed", workspaceId }(src/common/orpc/schemas/api.ts). It carries no number and no snapshot. The VS Code activity pump already skips event types other thanactivity; its client type now lists the new one.Backend.
SessionUsageService.onUsageChanged(listener)fires at the end of every write that changes a workspace's totals:recordUsage(a stream's settle and every headless record, which goes through it),recordInFlightUsage(each finished step),discardInFlightUsage,rollUpUsageIntoParent(on the parent),resetSessionUsageandrebuildFromMessages. Reads and the orphan fold ingetSessionUsagedo not fire (totals unchanged).WorkspaceServiceemitsusage-changedfrom that listener, andsubscribeWorkspaceActivityforwards it. There is no snapshot read and no per-workspace state. Earlier rounds of this PR put a revision number on activity snapshots. The review found that a usage-triggered snapshot read could land after a newer activity emit and resend older activity, that a failed read dropped the move, and that a clock-seeded revision could collide across a restart. The plain event removes all three.Store (src/browser/stores/WorkspaceStore.ts).
refreshUsageAfterChangereplacesrefreshAncestorsWhenStreamEnds. For eachusage-changedevent of a workspace: (a) if its usage is on screen or subscribed, refetch its session usage (which also refreshes its projection); (b) refresh the projection of every on-screen or subscribed ancestor.isOwnStreamLive: chat subscribed and an active stream in the aggregator). Itsstream-endadds the stream's usage locally, and a usage-change refetch before it could already hold the settled stream and count it twice. Every terminal event (finalizeUsageStatsfor stream-end and stream-abort, and stream-error) now refetches the ledger after the local merge, so a change skipped during the stream lands there. (b) never waits.refreshSubagentUsagekeeps one fetch per workspace in flight. A refresh asked while one runs sets a trailing flag, and one trailing fetch runs when it settles. Each fetch has a 30 s deadline (AbortSignal.timeout), and a client change or removal frees the slot, so a fetch that never settles cannot block later fetches. A response applies only while the slot still holds its own fetch, which replaces the per-workspace request version (a removed-then-re-added workspace restarted that version).addWorkspacerefreshes the shown ancestors' projections when it registers a workspace: a new sub-agent changes their open sub-agent count, and its usage can change before its parent link reaches the store.session-usage-delta(headless spend) now changes nothing in the store. The headless write also sentusage-changed, and the refetch for it shows the spend. A local add could count it twice (that refetch can land first), and a second refetch could supersede it.refreshShownUsageAfterResubscribe) refetches each shown workspace's usage: its ledger and projection, or only the projection while its own stream is live here. The first list needs none, because registration and activation fetch. Ausage-changedevent does not count as an activity delta for a running list retry (activityDeltaTouchesDuringRetry): it carries no activity.Guards from #7861. All stay: the
rolledUpFromfilter at read time, the delta skip-dup for child sources, the refetch after a (child) delta, and the ancestor refresh inremoveWorkspace(it also updates the open sub-agent count when a sub-agent without usage is removed, which sends no event). The stream-end refresh is removed: every settle and discard sendsusage-changed, so it was redundant (the model below holds without it).Validation
Live check (scratch
XUM_ROOTbuilt from a real 45-workspace task tree: rootsolid-sheep-post, 44 open sub-agents, depth 2; every workspace{"type":"local"}on a scratch git repo, noproviders.jsonc, provider env vars unset,XUM_DISABLE_AGENT_TOOLS/TERMINALS/PROJECT_AUTOMATION=1). No model is available there, so a--requirepreload in the sandboxxum servercalls that server's ownSessionUsageService.recordInFlightUsage/recordUsage/recordHeadlessUsage, the callsUsageLedgerand the headless callers make. Everything from the usage write to the Costs tab is the shipped code. The parent's Stats tab stayed open the whole time; I did not switch workspaces.getSubagentUsagecalls(Numbers from head a410b21, which sends
usage-changed. Heads 7717376 and 00032bf, which used revision numbers, gave the same totals and call counts. Three more in-flight writes on this head showed in 189 to 411 ms, measured by polling the tab label through agent-browser. The first three screenshots are from an earlier commit with the same sequence. No step caused agetSessionUsagecall.)Before this change (the same driver on the base commit 645e7f8): an in-flight step (+$100) and a headless record (+$50) left the tab at $743.12, with zero
getSessionUsage/getSubagentUsagecalls.Request cost of a burst (one on-screen parent):
coalesces a burst of 50 sub-agent usage changes into one fetch and one trailing fetch): 50usage-changedevents from 50 sub-agents while one fetch runs cost 2getSubagentUsageand 0getSessionUsage.getSubagentUsageand 0getSessionUsage(counted in the server), never more than one in flight. The tab showed the exact $1,243.12 (+$250).getSubagentUsage(50 ends, 50 calls, not coalesced).getSessionUsageplus 1 coalescedgetSubagentUsage). Its own finished steps still sendusage-changedfor its ancestors, but they do not refetch its own ledger while the stream is live. Each activity resubscribe refetches every shown workspace's usage once.Mutation checks (scratch script; each mutation applied alone, the named tests run, then restored): 31 of 31 killed on head a410b21. They cover every notify call, the listener wiring, the router forwarding and its unsubscribe, the event path in the store, (a), (a)'s "shown" condition, (a)'s wait for a live own stream, the stream-end and stream-error refetches, (b), the single flight, the trailing fetch, the fetch deadline, slot ownership, the client-change and removal slot release, the response-to-fetch binding, the ancestor refresh on registration, the self-delta path (restoring either the add or the refetch), and the resubscribe refresh (its call, its first-list skip, its "shown" filter, and its two branches for a live own stream).
Formal model (TLA+, scratch only, not in the repo). I extended the #7861 model (parent R, child C, grandchild G) with: a per-workspace
usage-changedsignal that a usage write marks sent and a delivery marks seen (rev[w]), R's own streams (live usage from chat,stream-endlocal add), headless records, lostsession-usage-deltas, the single-flight projection with a trailing fetch, and the self delta that only refetches. The store refetches for every event with no dedup, so a delivery may also run when nothing is pending (a late event of an earlier write). This over-approximates one event per write. With featurelostRevthe subscription drops undelivered events, and aReliststep stands for the resubscribe refresh.facts.pyreads every guard from the source (whitespace-insensitive), so a removed guard becomes a model break; on head a410b21 it finds all 16 parts (Breaks = {}).ExactWhenQuietneeds every signal delivered or re-listed (rev[w] = "seen"for all w). WithliveStreamsit holds while sub-agent streams run (R's own ledger catches up when R's own stream ends, so quiescence needs R idle). The #7861 fetch paths keep the ordering assumption below. This PR's refetches (sessOrigin = "rev") get none, only "a ledger read issued before R starts a stream runs before that stream settles". Invariants:TypeOK,NoOvercount(never more than spent, per source),ExactWhenQuiet.ExactWhenQuietviolated (item 1)ExactWhenQuietviolated (item 3)ExactWhenQuietviolated (item 4)NoOvercountviolated (the self-delta add, see below)Model mutants (one guard removed each): 14 of 16 fail an invariant (
filter,deltaSkipDup,backendSkip,selfDeltaIgnored,liveSkip:NoOvercount;bumpRecord,bumpInFlight,bumpRollUp,revOverlay,relistRefresh,revSelf,revAncestors,projTrailing,endRefetch:ExactWhenQuiet). Two survive, both #7861 guards thatusage-changedmakes redundant for totals: the refetch after a child delta (the roll-up sends the parent's event) and the ancestor refresh inremoveWorkspace(kept for the open sub-agent count, which the model does not track). The model does not track activity snapshot contents, so it could not show the stale-snapshot defect of round 4; the plain event removed that path.Gates on head a410b21:
make static-check,make lint-eslint,make dry-check(pass),make crap-check COVERAGE=<lcov of the touched tests>(pass, 1 crap-tax warning on untouched hotspot size), and the touched test files (WorkspaceStore, sessionUsageService, workspaceService.usageChanged, workspaceService.remove and .fork, routerSubscriptions, VS Code activity pump: 435 pass).Risks
getSessionUsage/getSubagentUsage, so it cannot invent spend.XUM_ALLOW_MULTIPLE_INSTANCES) does not notify this one's renderers, as before.setClient, and its activity re-list refetches them again (one extragetSessionUsageper shown workspace per reconnect).usage-changedevent to each connected renderer: one per finished stream step, settle and headless record. Like every activity event, it goes through the subscription's unbounded FIFO (streamBridge.ts, buffer "all").stream-endadd if their read lands after the settle and beforestream-endis processed; the backend pushesstream-endright after the settle write, so this needs a reordered delivery. Unchanged by this PR.Follow-ups (not in this PR).
refreshSessionUsagekeeps a latest-wins request version, not a single flight like the projection fetch. Many usage writes on one shown workspace whose chat is not subscribed here (for example a burst of headless records) cost onegetSessionUsageeach. A shown workspace normally has its chat subscribed, so its own stream steps skip this refetch. Trigger: a profile that showsgetSessionUsagebursts.recordHeadlessUsagehas ananalyticsSourceand its ledger write fails, it still emits the self delta, but nousage-changedgoes out, and the store now drops that delta. The tab then matches the ledger. Before this PR it showed spend that the next ledger fetch removed. Note only.usage-changedrefetch that fails is logged and not retried. The next usage change of that workspace or a descendant, an activation, a Costs tab open, or a resubscribe refetches. Tracked in 🤖 Costs tab: follow-ups for open sub-agent spend #7862.Out of scope / found on the way
WorkspaceServicetests passed a partialSessionUsageServicewithoutonUsageChanged; they now include it.stream-abortadds nothing to the store's ledger copy, so on the base commit (by code reading, not live-tested) an aborted stream's spend stayed out of the tab until the next activation. The abort's settle now sendsusage-changed, so the shown workspace refetches.Generated with
xum• Model:anthropic:claude-opus-5-5• Thinking:xhigh• Cost:$51.03