Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(usage): keep the phone's usage mirror fresh on a backgrounded desktop
enes612f6fec4d2d
diff --git a/src/core/usage/usage-service.poll-gate.test.ts b/src/core/usage/usage-service.poll-gate.test.tsnew file mode 100644index 000000000..40d8f3a1b--- /dev/null+++ b/src/core/usage/usage-service.poll-gate.test.ts@@ -0,0 +1,65 @@+// The background poll gate: on desktop `shouldPoll` is "window focused" (for the pill), but the+// phone reads the mirror's `usage` block with no window focused, so `mirrorMayBeRead` must be able+// to open the gate on its own — otherwise a backgrounded desktop froze the phone's bars into+// fossils (the same "nobody looking" starvation the Server Edition avoids by polling ungated).+//+// Observed through `localAccounts`: pollAll calls it ONLY after the gate passes, so a spy on it is+// a clean proxy for "did the background poll fire?" (run() itself is fire-and-forget and, with no+// credentials in a test, resolves to an error usage — localAccounts is the deterministic signal).+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'+import { startUsageService, type UsageService } from './usage-service'++let service: UsageService | undefined++beforeEach(() => {+ resetPlatformForTests()+ initPlatform(fakePlatform())+})++afterEach(() => {+ service?.dispose()+ service = undefined+ resetPlatformForTests()+})++describe('usage poll gate', () => {+ it('does NOT poll when the shell gate is shut and no phone may read the mirror', () => {+ const localAccounts = vi.fn(() => ['acc-1'])+ service = startUsageService({+ shouldPoll: () => false,+ mirrorMayBeRead: () => false,+ localAccounts+ })+ // The warm-up pollAll runs at start; a closed gate must skip it entirely.+ expect(localAccounts).not.toHaveBeenCalled()+ })++ it('polls when the shell gate is shut but a phone MAY be reading the mirror', () => {+ const localAccounts = vi.fn(() => ['acc-1'])+ service = startUsageService({+ shouldPoll: () => false,+ mirrorMayBeRead: () => true,+ localAccounts+ })+ // The phone-facing mirror needs fresh data even with the window unfocused → the poll fires.+ expect(localAccounts).toHaveBeenCalled()+ })++ it('polls when the shell gate is open, regardless of the mirror signal', () => {+ const localAccounts = vi.fn(() => ['acc-1'])+ service = startUsageService({+ shouldPoll: () => true,+ mirrorMayBeRead: () => false,+ localAccounts+ })+ expect(localAccounts).toHaveBeenCalled()+ })++ it('defaults mirrorMayBeRead to never — a shut shell gate alone skips the poll (legacy behavior)', () => {+ const localAccounts = vi.fn(() => ['acc-1'])+ service = startUsageService({ shouldPoll: () => false, localAccounts })+ expect(localAccounts).not.toHaveBeenCalled()+ })+})diff --git a/src/core/usage/usage-service.ts b/src/core/usage/usage-service.tsindex 969e2e6f5..f48dd7866 100644--- a/src/core/usage/usage-service.ts+++ b/src/core/usage/usage-service.ts@@ -185,6 +185,17 @@ export interface UsageServiceOptions {* informational, so a stale snapshot beats polling an idle app into 429s.*/shouldPoll?: () => boolean+ /**+ * Override the poll gate when the phone-facing MIRROR needs fresh data even though the shell's+ * own `shouldPoll` says no. On desktop `shouldPoll` is "is the window focused" — for the PILL —+ * but the phone reads the agent-status mirror's `usage` block with no window focused at all, so a+ * focus-only gate froze that block into fossil bars whenever the Mac was in the background (the+ * same "nobody connected ≠ nobody looking" bug the Server Edition already runs UNGATED to avoid).+ * When this returns true the background poll fires regardless of `shouldPoll`, at the same 15-min+ * cadence (4 req/hour/account — well inside the endpoint budget). Default: never (desktop wires it+ * to "a phone is paired / has a push grant"; the Server Edition leaves it unset and polls anyway).+ */+ mirrorMayBeRead?: () => boolean/*** Local managed accounts to poll ALONGSIDE the system account on the background cadence (spec:* mobile-usage-inbox). Returns their account ids (settings' non-`host`, non-`pending` claude@@ -231,6 +242,7 @@ export interface UsageService {*/export function startUsageService(opts: UsageServiceOptions = {}): UsageService {const shouldPoll = opts.shouldPoll ?? ((): boolean => true)+ const mirrorMayBeRead = opts.mirrorMayBeRead ?? ((): boolean => false)// Per-account caches keyed by `accountId ?? ''`. The empty key is the system account, the only// one that's proactively polled + pushed; managed-account rows fetch on demand from the popover.@@ -404,7 +416,9 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService// system row. Each account is one request per cadence; the request-budget gate (`shouldPoll`)// still fronts the whole sweep.const pollAll = (): void => {- if (!shouldPoll()) return+ // Fire when the shell wants it (focused pill) OR when a phone may be reading the mirror — the+ // latter keeps the phone's `usage` block fresh on a backgrounded desktop instead of fossilizing.+ if (!shouldPoll() && !mirrorMayBeRead()) return// Fire-and-forget: a poll that lands after shutdown (or a test's platform reset) throws// from platform()-dependent fetch paths — in an un-awaited chain that is an unhandled// rejection, not a signal (same hardening as push()'s broadcast).diff --git a/src/main/claude-usage.ts b/src/main/claude-usage.tsindex 559a44851..bf80f3fb4 100644--- a/src/main/claude-usage.ts+++ b/src/main/claude-usage.ts@@ -19,15 +19,22 @@ export interface InitClaudeUsageOpts {localAccounts?: () => string[]onCacheUpdate?: () => voidremote?: RemoteUsageDeps+ /** "A phone may be reading the agent-status mirror" (paired / has a push grant). When true the+ * background poll runs even while the window is unfocused, so the phone's `usage` block stays+ * fresh instead of freezing into fossil bars. See UsageServiceOptions.mirrorMayBeRead. */+ mirrorMayBeRead?: () => boolean}/** Start the usage service on the focused-window poll gate and return it, so the caller can wire* the agent-status mirror's `usage` provider off its `snapshot()`. */export function initClaudeUsage(win: BrowserWindow, opts: InitClaudeUsageOpts = {}): UsageService {- // Poll only while the window is focused, and re-check on focus — the usage endpoint has a- // tight request budget and this data is informational, so an unattended app should not spend it.+ // Poll while the window is focused (for the pill) OR while a phone may be reading the mirror (for+ // the phone's `usage` block) — a focus-only gate froze the phone's bars into fossils whenever the+ // Mac was backgrounded, the same starvation the Server Edition avoids by polling ungated. The+ // usage endpoint has a tight budget, so a pure-desktop user with no phone still only polls on focus.const service = startUsageService({shouldPoll: () => win.isFocused(),+ mirrorMayBeRead: opts.mirrorMayBeRead,localAccounts: opts.localAccounts,onCacheUpdate: opts.onCacheUpdate,remote: opts.remotediff --git a/src/main/index.ts b/src/main/index.tsindex 32067ee58..9942991a7 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2337,6 +2337,10 @@ app.whenReady().then(async () => {onCacheUpdate: () => {void flushAgentStatusMirror()},+ // A phone may be reading the mirror's `usage` block even with the window unfocused: relay-paired+ // (approved device) or SSH-with-a-push-grant. When so, keep polling on the background cadence so+ // the phone's bars/resets stay live instead of fossilizing at the last focused poll.+ mirrorMayBeRead: () => pushHasPairedPhone || allPushGrants().length > 0,// Remote (SSH host) Claude usage. Same shape as the Context Link remote deps: core owns the// command and the parsing, main owns the ControlMaster. `sshProjectManager` is assigned just// below, so both closures read it lazily — they only ever run after a project has connected.