Skip to content

fix(dashboard): stop a stale usage stream from reopening itself - #651

Open
SantiagoDePolonia wants to merge 2 commits into
mainfrom
fix/live-usage-stale-reader
Open

fix(dashboard): stop a stale usage stream from reopening itself#651
SantiagoDePolonia wants to merge 2 commits into
mainfrom
fix/live-usage-stale-reader

Conversation

@SantiagoDePolonia

@SantiagoDePolonia SantiagoDePolonia commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Follow-up to #650, where Greptile flagged this (P1). The flaw predates that PR — the refactor moved the line, it did not introduce the bug.

The bug

liveTokensState.#readStream scheduled a reconnect whenever its reader finished, without checking whether its controller was still the active one:

await consumeEventStream(res.body.getReader(), );
this.#scheduleReconnect();   // runs even for a controller that was replaced

#startUsageSignalStream aborts and replaces #sseController on every start, so leaving the Overview page and coming back creates a new stream while an old reader may still be pending. If that old reader then completes normally (rather than rejecting with an abort), it schedules a reconnect against the current state and opens a second usage stream alongside the live one. An abort-rejected read is already handled by the isAbortError catch; this is the completion path it doesn't cover.

The fix

Guard the completion path with the same controller identity/abort check the audit-log stream has carried all along (liveLogs.svelte.js:178-183), so only the active stream can reconnect. The two streams now agree.

Verification

svelte-check 0 errors, 444/444 dashboard tests, clean build.

Honest limitation: no regression test. liveTokensState is a rune-based singleton importing through the $lib alias, so the existing node --test suite cannot drive it, and the pure-logic split for this page (liveTokensLogic.js) does not cover stream control. The change was verified by reading against the twin implementation it mirrors, plus the reproduction Greptile reported on #650. Making the stream layer testable would mean extracting its control flow the way live-logs-logic.js was — worth doing, but larger than this fix.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Prevented obsolete live usage streams from reconnecting after being aborted or replaced.
    • Reduced the likelihood of duplicate live usage connections.
    • Improved handling of aborted stream reads reported as errors.

#readStream scheduled a reconnect whenever its reader finished, without
checking whether its controller was still the active one. Leaving the
Overview page and returning replaces the controller, but the old reader can
still complete normally afterwards and schedule a reconnect against the
current state, opening a second usage stream alongside the live one.

Guard the completion path with the controller identity/abort check the
audit-log stream already uses (liveLogs.svelte.js), so only the active
stream can reconnect.

Reported by Greptile on #650; the flaw predates that PR.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Copilot AI lite review requested due to automatic review settings August 4, 2026 17:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 5ad45cf3-4792-49d7-b5b1-1f9a789d99a3

📥 Commits

Reviewing files that changed from the base of the PR and between 7c16a72 and 86c0d7a.

⛔ Files ignored due to path filters (2)
  • internal/admin/dashboard/static/dist/assets/index-CyRbnFzv.js is excluded by !**/dist/**
  • internal/admin/dashboard/static/dist/index.html is excluded by !**/dist/**
📒 Files selected for processing (1)
  • web/dashboard/src/pages/overview/liveTokensState.svelte.js

📝 Walkthrough

Walkthrough

The live usage SSE stream now skips reconnect scheduling when its controller was aborted or replaced. The error path also ignores aborted reads reported as TypeError.

Changes

Live usage SSE lifecycle

Layer / File(s) Summary
Guard SSE reconnect scheduling
web/dashboard/src/pages/overview/liveTokensState.svelte.js
reconnectIfCurrent prevents obsolete or aborted controllers from scheduling duplicate streams. The error path checks abort state before reconnecting.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: copilot

Poem

A rabbit checks the stream with care,
And stops stale hops from filling the air.
Aborted reads stay quiet and still,
Active streams reconnect by will.
“Thump!” says Bunny, “guard the flow.”

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the fix for stale usage streams reopening.
Description check ✅ Passed The description explains the bug, fix, impact, and verification results, with only the template heading structure differing.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/live-usage-stale-reader

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@web/dashboard/src/pages/overview/liveTokensState.svelte.js`:
- Around line 168-174: Update `#scheduleReconnect`() and every call site in the
stream reader to accept and propagate the reader controller, including
invalid-response and catch paths. Before scheduling, require the stream to
remain active, un-aborted, and identical to the current `#sseController`; preserve
the existing final-branch guard behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: d6debd08-82d3-4cd3-8c01-62f166927046

📥 Commits

Reviewing files that changed from the base of the PR and between 7c16a72 and 4325016.

⛔ Files ignored due to path filters (2)
  • internal/admin/dashboard/static/dist/assets/index-DTrQJRSk.js is excluded by !**/dist/**
  • internal/admin/dashboard/static/dist/index.html is excluded by !**/dist/**
📒 Files selected for processing (1)
  • web/dashboard/src/pages/overview/liveTokensState.svelte.js

Comment on lines +168 to +174
// A reader that ends normally after this stream was replaced (navigate
// away and back) must not resurrect it — reconnecting here would open a
// second stream alongside the live one. Same guard as the audit-log
// stream in liveLogs.svelte.js.
if (controller.signal.aborted || this.#sseController !== controller) {
return;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 8 \
  '`#scheduleReconnect`|isAbortError|signal\.aborted|`#sseController`' \
  web/dashboard/src/pages/overview/liveTokensState.svelte.js \
  web/dashboard/src/lib/api/client.js \
  web/dashboard/src/pages/audit-logs/liveLogs.svelte.js

Repository: ENTERPILOT/GoModel

Length of output: 17927


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== liveLogs.svelte.js reconnect implementation =="
sed -n '198,230p' web/dashboard/src/pages/audit-logs/liveLogs.svelte.js | cat -n

echo
echo "== eventStream.js =="
sed -n '1,220p' web/dashboard/src/lib/api/eventStream.js | cat -n

echo
echo "== all scheduleReconnect/reconnect call sites in overview page =="
rg -n -C 4 '\bschedule(UsageSignal|LiveLogs|Reconnect)|`#scheduleReconnect`|liveLogsController|`#sseController`|consumeEventStream|start\(' web/dashboard/src/pages/overview/liveTokensState.svelte.js web/dashboard/src/pages/audit-logs/liveLogs.svelte.js

Repository: ENTERPILOT/GoModel

Length of output: 22276


Guard #scheduleReconnect() against stale controllers.

Replace only the final reconnect branch, but the invalid-response branch and catch block also call #scheduleReconnect(). Those calls do not pass the reader controller, so #scheduleReconnect() only checks active and can restart an obsolete stream when start() has replaced #sseController. Propagate controller to every reconnect path, then keep #scheduleReconnect(controller) from scheduling a reconnect while the current sseController is different or aborted.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/dashboard/src/pages/overview/liveTokensState.svelte.js` around lines 168
- 174, Update `#scheduleReconnect`() and every call site in the stream reader to
accept and propagate the reader controller, including invalid-response and catch
paths. Before scheduling, require the stream to remain active, un-aborted, and
identical to the current `#sseController`; preserve the existing final-branch
guard behavior.

@greptile-apps

greptile-apps Bot commented Aug 4, 2026

Copy link
Copy Markdown

Confidence Score: 4/5

T-Rex T-Rex Logs

What T-Rex did

  • T-Rex produced a proof for the posted P1 finding and linked it to the related review comment.
  • T-Rex opened and reviewed the focused stale usage-reader rejection harness source to ground the P1 finding.
  • T-Rex inspected the usage stream state before stale reader rejection to verify the pre-rejection condition.
  • T-Rex inspected the usage stream state after stale non-AbortError rejection and the shared SSE framing and reconnect-backoff test output to confirm stability.

View all artifacts

T-Rex Ran code and verified through T-Rex

Comments Outside Diff (1)

  1. web/dashboard/src/pages/overview/liveTokensState.svelte.js, line 176-179 (link)

    P1 Stale error path reconnects over the active stream

    A replaced usage-stream reader can reject with a non-AbortError, such as an abort reported as TypeError. This catch schedules a reconnect without checking whether controller is still #sseController. When the timer runs, #startUsageSignalStream() aborts the healthy current controller and opens another stream, interrupting live usage updates. Return when the controller is aborted or is no longer current before scheduling the reconnect, matching the normal-completion guard above.

    Artifacts

    Focused stale usage-reader rejection harness source

    • This authored Node harness drives replacement of an older usage stream and then rejects its stale reader with a non-AbortError, proving the exact failure path—the catch can reconnect over the active stream.

    Usage stream state before stale reader rejection

    • This executed before capture shows two stream fetches and confirms the newer replacement stream is still active before the stale reader fails—the prerequisite state is correct.

    Usage stream state after stale non-AbortError rejection

    • This executed after capture shows the stale rejection creates a third fetch and sets the newer stream to aborted—the stale catch replaces the active stream.

    Shared SSE framing and reconnect-backoff test output

    • This executed dashboard test output reports all six shared event-stream tests passing—the focused finding is isolated to stale-controller handling in the usage stream catch path.

    View artifacts

    T-Rex Ran code and verified through T-Rex

Reviews (1): Last reviewed commit: "fix(dashboard): stop a stale usage strea..." | Re-trigger Greptile

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

The first pass only guarded the normal-completion path. The invalid-response
branch and the catch block also schedule reconnects, and both are reachable
by a reader whose stream was already replaced — the fetch can resolve before
the abort lands. Route all three through one controller-identity check.

Firefox also rejects a deliberately-aborted read with a plain TypeError
instead of an AbortError, so the catch now trusts the controller state as
well as the error name, matching liveLogs.svelte.js.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings August 4, 2026 19:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants