Repository navigation
Cut the Windows app's idle and focus-driven backend request volume - #11835
Conversation
`retentionMode` is optional and falls back to 'dry-run', and only 'off' returned early, so every default install ran the full sweep every 30 minutes: a complete `/v3/memories` page-through plus `GET /v1/conversations?limit=200`. In dry-run the entire result is handed to a console.log and discarded, so all of it was paid to write a line into a DevTools console that is not open. Scheduled passes now require live mode, which is the only mode that deletes anything. Dry-run becomes what its label already claims: a preview the user asks for. Selecting Preview in Settings runs one pass immediately, so the logged plan appears when the button is pressed instead of 48 times a day regardless. Verification, run in desktop/windows: - `npx vitest run src/renderer/src/lib/retentionSweep.test.ts` - 7 passed. - 5 mutations seeded, each turning the suite red now and leaving it green before: guard deleted, guard weakened to allow dry-run on the timer, scheduler re-wired to pass 'manual', guard widened to skip live too, and manual Preview broken. - The scheduler wiring itself is covered end to end: with fake timers on a default install, the 8s startup pass plus four 30-minute windows make zero requests.
…promote The safety net POSTed /v1/staged-tasks/promote on a flat 60s timer for the life of the process, with no local pre-check and no backoff: about 1,440 requests per user per day, essentially all answered `promoted:false`. Each one costs the backend two full collection scans (staged_tasks plus candidates) to report that there was nothing to do. A failing endpoint got the same flat 60s forever, because `lastPromotedAt` only advances on success and the timer bypasses the debounce. The net exists for staged rows created out of band, on another device or by a backend extraction. Every in-app path that stages a task already promotes inline or on the task-complete and task-delete events, and none of those go through this timer, so its cadence is discovery latency for a rare case rather than responsiveness for a common one. Ticks now walk 60s, 2m, 5m, 10m and hold, and any tick that actually promotes returns to the 60s floor so a backlog still drains one per minute exactly as before. Signed-out ticks make no request and do not walk the ladder, so a user who signs back in is not stranded on the slow rung. An idle hour costs single-digit requests instead of 60. `getLastPromotedAt` is exported from create.ts so the net can tell "promoted something" from "found nothing" without duplicating the debounce state. Verification, run in desktop/windows: - `npx vitest run src/main/assistants/tasks/promotionService.test.ts` - 12 passed. - 5 mutations seeded, all caught, all previously green: ladder flattened to 60s, reset-on-promote removed, signed-out reset removed, ladder cap removed, and the stop guard removed. - One existing case pinned the flat cadence (5 minutes buys 5 ticks). It now pins the ladder instead. The guard it was written for, that the session poll stops rather than running 60 five-second attempts, is unchanged and still asserted. - Self-review caught a defect in this change before it shipped: a tick re-arms from inside its own promise chain, so a stop landing mid-promote resurrected the timer that `stopTaskPromotionService` had just cleared, which `clearInterval` had made impossible for free. `scheduleSafetyTick` now no-ops once stopped, with a case.
MainViews mounts every panel 1.8 seconds after launch and never unmounts them, so a `window` focus listener registered by any page is live app-wide no matter which tab the user is on. Three pages register one, none route-gated and none throttled: - Memories, a full `/v3/memories` page-through - Apps, three requests - the Home goal chips, one request That is six or more backend requests per focus event for surfaces that are mostly not on screen. The trigger is not rare either: the app blurs its own main window every time the floating bar, the orb, or the capture window takes focus, so ordinary voice use pays it repeatedly per minute. Revalidating on focus is still the right behavior, so the first focus always runs and only the repeats are dropped. A shared `useThrottledWindowFocus` holds the clock in a ref, so the constant resubscribe these call sites cause (each passes a fresh closure over `loading`/`refresh`) neither reopens nor extends the window. Verification, run in desktop/windows: - `npx vitest run src/renderer/src/lib/focusRefetch.test.tsx` - 6 passed. - The two existing page-side guards, Memories.focusRefresh and Apps.focusRefresh, pass unchanged. They assert that focus revalidates, which is why the throttle exempts the first focus rather than deferring it. - 6 mutations seeded, all caught, all previously green: throttle deleted, interval set to 0, clock reseeded on every resubscribe, window never advanced, listener not removed on unmount, and the caller-supplied interval ignored. - One of my own cases could not fail at first: it re-rendered with the same handler reference, so the effect never actually resubscribed. Rewritten to pass a fresh closure, which is what the real call sites do, and it then caught the mutation.
`sync()` had an in-flight dedupe and nothing else, which does nothing for calls that are merely sequential. It runs on every floating-bar reveal (BarApp's onShow) and after every completed chat reply (UsageLimitTriggerHost), both driven by the primary voice interaction, so N interactions meant N `GET /v1/users/me/usage-quota`. The per-reply probe doubles the request count of every chat turn: its "at most once per session" latch only sets when the quota is already exhausted, so for an under-cap user it never sets at all. Refreshes of the snapshot are now floored at 60 seconds. A month-to-date counter does not move meaningfully inside a minute, and the gate already tracks sends between refreshes with `recordQuery()`'s optimistic delta, so the verdict stays correct across the gap. The first probe of a session is never throttled, because `check()` depends on it to stop an already-over-cap user getting a free send. Failures are throttled, deliberately: `fetchChatQuota` goes through apiClient, which already retries 429/503 five times with capped backoff, so a rejection means the endpoint is genuinely down and re-probing it on every reveal is the waste being removed. Verification, run in desktop/windows: - `npx vitest run src/renderer/src/lib/chatQuotaGate.test.ts` - 23 passed, the 17 pre-existing ones unchanged. - 5 mutations seeded, all caught, all previously green: throttle deleted, interval set to 0, failing probes exempted, attempt never stamped, and the cold start throttled too. - The failing-probe case was written first and failed against my own initial implementation, which keyed the floor on holding a snapshot and so re-probed a down backend on every reveal. The floor keys on the attempt instead. - `MIN_SYNC_INTERVAL_MS` escaped the first mutation round because every case passed an explicit interval, while production `barSend.ts` constructs the gate with no arguments and runs entirely on the default. Added a case that does the same.
`refreshAboutUserCard()` runs on every hub warm and deduped only against a build already in flight. The hub deliberately re-warms for the whole session (the aliveFor>60 strike reset in hubController, against a provider that idle-closes roughly every two minutes), and those warms are far enough apart that the in-flight dedupe never applies. Each rebuild issues a `GET /v3/memories`, so an idle machine re-downloaded the card's memories several hundred times a day to produce a card that had not changed. A built card is now reused for five minutes. The warm behavior itself is untouched: keeping the hub warm so the next press takes the warm lane is a deliberate, documented latency tradeoff, and this changes only the request it was dragging along with it. Neither invalidation path is affected. An account switch fails the uid check and rebuilds immediately, and `resetAboutUserCard` nulls the cached card, which the floor requires. Verification, run in desktop/windows: - `npx vitest run src/renderer/src/lib/voice/aboutUser.test.ts` - 17 passed, the 13 pre-existing ones unchanged. - 5 mutations seeded, all caught, all previously green: floor deleted, TTL set to 0, uid check dropped from the guard, stamp never advanced, and reset no longer nulling the card. - A sixth mutation escaped and was a finding about this change rather than the tests: clearing the timestamp in `resetAboutUserCard` was unobservable, since nulling the card already defeats the guard. The dead line is gone.
`runGoalGenerationIfDue` fetched the whole context bundle, five parallel reads including `/v3/memories?limit=500` and `/v1/conversations?limit=100`, and only then checked whether the user was already at the three-active-goal cap. Sitting at the cap is the ordinary resting state for an engaged user, and that bail deliberately does not stamp the day so that finishing a goal at noon can still generate a replacement, which means the 4-hourly tick repeats indefinitely. Every one of those ticks re-paid all five reads to learn a number it could have had from one. The count now comes from a single `/v1/goals/all` ahead of the bundle. The bail path costs one read instead of five; the proceed path is unchanged, since the bundle fetches goals anyway. The file's own header already described the intended order as "cheap ones first, then the heavy context fetch" - the code now matches it. `fetchActiveGoalCountWith` derives the count exactly as `assembleGoalContext` does, so the cap means the same thing whichever path evaluates it. Verification, run in desktop/windows: - `npx vitest run src/main/assistants/goals/` - 51 passed, the 49 pre-existing ones unchanged. - 2 mutations seeded, both caught, both previously green: the cap check moved back behind the context build, and the comparison loosened so the gate never fires. - The existing cap case passed either way, since both orderings bail. It now also asserts that the context build is never reached, which is the actual saving. - Two new context cases hold the derivations together: the count agrees with `assembleGoalContext.activeGoalCount` on the same goals, and it reads goals and nothing else.
Both of these fetch from inside a component that is mounted but not visible, which on this app is the normal state: MainViews mounts every panel 1.8 seconds after launch and never unmounts them. ChatAppPicker called `useChatApps()` above its own gate, so it issued `GET /v1/apps` and then returned null because `chatAppPickerEnabled` is optional and off for almost everyone. The chat panel mounts whenever the ask bar takes focus, so that is one wasted request per ask-bar focus cycle. Split into a gate wrapper plus an inner component, which is exactly what the sibling HubChatHeader already does, for the same stated reason. Tasks fetched `GET /v1/conversations?limit=200` on mount to build a title and emoji map for per-task source links, so every launch paid it whether or not the user ever opened Tasks. It also wrote `cache.convs` and never read it back. The fetch now waits until the Tasks panel is actually the active route and short-circuits on the populated cache, so it is one request on first open and none thereafter, against one per launch before. Local task reads are untouched; they are SQLite over IPC. Verification, run in desktop/windows: - `npx vitest run` - 5,266 passed, 18 skipped, 544 files. - `npm run typecheck` - clean. - `npx eslint .` - 0 errors. I did NOT exercise these two by hand. Both are gating changes on panels whose request behavior I traced by reading the mount and route paths, and neither has a test that observes the request from the page side. The Tasks change in particular trades a launch-time fetch for a first-visit fetch, so the visible thing to confirm is that source-link titles still render on the first visit to Tasks. Worth a look during review.
…r-mount Two defects in this branch's own earlier commits, found by re-reading the diff and asking what each change costs on the paths it did not target. The goal cap check moved in front of the context build, but the bundle still fetched `/v1/goals/all` itself, so a run that actually generated asked for the same list twice: five reads became six. The bail path is the common one and got much cheaper, so the net was still a large win, but a change about removing redundant requests should not add one. The gate now hands its list to `fetchGoalContext`, which serves `fetchGoals` from it and leaves the other four reads alone. Bail costs one read, proceed costs the same five it always did. `withPrefetchedGoals` is split out rather than inlined because `fetchGoalContext` needs a live session, and the substitution is the part worth testing. Gating the Tasks conversation-title fetch on the active route also folded the route into the deps of the effect that reads local tasks, so `readTasks` re-ran on every navigation in and out of the tab instead of once per mount. Local SQLite over IPC, so no backend cost and no spinner, but it was an unintended change and not what the commit claimed. Split into two effects: the local read keyed only on `readTasks`, the title map keyed on the route. Both keep the async-IIFE wrapper the original had, which exists to satisfy `react-hooks/set-state-in-effect` — calling the loaders straight from the effect body fails lint. Verification, run in desktop/windows: - `npx vitest run` - 5,270 passed, 18 skipped, 544 files. - `npm run typecheck` - clean. `npx eslint` on the changed paths - 0 errors. - `npm run build` - clean. - 6 mutations seeded, all caught, all previously green: cap check moved back behind the context build, goals not handed on, cap comparison loosened, activeGoalCount no longer excluding completed goals, prefetched goals ignored, and the prefetch wrapper dropping the other four fetchers. - The "prefetched goals ignored" mutation escaped the first round: the schedule test proved the list was PASSED, and `fetchGoalContext` is mocked there, so nothing proved it was USED. That is what `withPrefetchedGoals` and its three cases fix. - Renaming the helper left `schedule.ts` importing a symbol that no longer existed. The suite caught it, since the thrown error is swallowed by the job's catch.
|
Thanks @ZachL111 — this is a careful, well-evidenced sweep. I went through the full diff and verified the claims against the current code; everything I checked holds up. What I verified per change, then the handful of behavior tradeoffs I'd like a human maintainer to sign off on before merge. Verified
What I'd like a human maintainer to sign off on — the implementation looks right, but each of these is a user-facing tradeoff rather than a pure cost fix:
None of these look wrong to me; they're product calls about freshness vs. request volume that deserve a maintainer's explicit OK, so I'm leaving the approval decision to a human maintainer. Minor, non-blocking: switching Auto-cleanup to Delete doesn't trigger an immediate live pass (the first sweep still waits for the next 30-minute tick) — same as before this PR, just noting it as possible polish alongside the Preview-output UX. The test discipline here is genuinely excellent — boundary assertions one millisecond either side, the shipped-default interval exercised explicitly, and the backoff ladder pinned rung by rung. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
…tion-item ID scan, and meter it (#11849) ## What `get_visible_action_item_ids()` (`backend/database/action_items.py`) backs `GET /v1/action-items/ids?completed=...` and used to stream the entire per-user `action_items` collection with a bare projection query, filtering `completed` in Python. A projection query still bills one document read per document scanned, so every call cost one read per action item the user has ever created, regardless of how many were actually in the requested bucket. The function also never called `record_firestore_read`, so this scan was invisible in `backend/database/firestore_read_metrics.py`, unlike every other reviewed read path in the module. This PR: 1. Pushes the `completed` filter server-side with `.where(filter=FieldFilter('completed', '==', completed))`, so Firestore only streams (and bills) documents in the requested bucket instead of the whole collection. 2. Adds a `record_firestore_read` call with a new `FirestoreReadFamily.ACTION_ITEMS_VISIBLE_IDS` family, so this path is finally counted. 3. Drops `status` from the field projection — it is fetched but never read in the function body. ## What this does NOT change: the `deleted` semantics The trap in this change is `deleted`. It is tempting to also push `.where('deleted', '==', False)` server-side. **Don't** — Firestore equality filters never match a document where the field is absent, and most action items have no `deleted` field at all (it is only ever set on soft-deleted rows). A server-side `deleted` filter would silently drop every ordinary, undeleted row from every bucket. The `if data.get('deleted'): continue` check stays in Python, and the diff adds a comment on the function saying why. ## Does the `completed` semantics shift? Current code matched with `completed_value is completed` — Python identity against a bool, so a doc with `completed` absent/`None` or any non-bool value (e.g. a stray `1`/`0`) never matched either bucket, since `is` requires the exact `True`/`False` singleton, not just equality. Firestore's `== True` / `== False` also never matches a missing field, and Firestore equality does not coerce an int `1`/`0` into a bool match either. So the server-side filter returns exactly the same document set the old Python identity check selected, and that check is now redundant and was removed. The new unit test `test_visible_action_item_ids_matches_explicit_bucket_and_excludes_deleted` still exercises the same legacy-row fixtures (`completed: None`, status-only rows) to pin this. ## Value — please read this section literally **This is a correctness and instrumentation fix, not a measured cost win.** PR #11835's follow-up notes attributed a large share of the Windows app's backend request volume to this function, estimating "24 full collection scans per idle hour per running client." Production log sampling on 2026-08-19 found that attribution is wrong: there is effectively zero traffic to `GET /v1/action-items/ids`. The ~60k req/hr Windows volume goes to `GET /v1/action-items` (the listing endpoint), a different code path already addressed by #11830. This PR does not claim to reduce measured load. The reason to land it anyway: the scan this function runs is unbounded per call and, until this PR, completely unmetered. It is a latent cliff — cost grows linearly with each user's lifetime action-item count — that we currently cannot see coming because nothing records it. Fixing the query shape and adding the metric closes both problems at once, independent of today's traffic level. ## Testing `backend/tests/unit/test_action_item_ids_endpoint.py` already covered `get_visible_action_item_ids`; extended rather than duplicated: - Updated the fake Firestore query fixture (`_Query`) to implement real equality-filter semantics for `.where()` — a filter only matches a document where the field is present and matches by both value and type (so a stray `int` 1/0 is never treated as `True`/`False`), same as real Firestore. This lets the tests actually distinguish server-side filtering from the old Python-side filtering it replaces. - `test_visible_action_item_ids_matches_explicit_bucket_and_excludes_deleted`: now also asserts the projection is `['completed', 'deleted']` (not `status`) and that the `completed` filter was pushed to Firestore. - `test_visible_action_item_ids_excludes_legacy_null_completion_rows`: unchanged behavior, kept as a regression pin. - New `test_visible_action_item_ids_includes_docs_with_absent_deleted_field`: the trap case — rows with no `deleted` field, and rows with an explicit `deleted: False`, must both still come back; only `deleted: True` is excluded, and no `deleted` filter reaches Firestore. - New `test_visible_action_item_ids_records_firestore_read`: asserts the `omi_firestore_read_operations_total{family="action_items_visible_ids", mode="unbounded"}` counter increments by exactly one per call. Ran locally via `backend/test.sh` with a scoped file list (`BACKEND_UNIT_TEST_FILE_LIST`) covering the touched test file plus the neighboring action-item pagination and Firestore-read-cache suites — all pass. ### Mutation testing Four mutations against `database/action_items.py`, each turned red by an existing or new test, then reverted: | Mutation | Caught by | | --- | --- | | Remove the `.where(filter=FieldFilter('completed', ...))` push-down (revert to scanning the whole collection) | `test_visible_action_item_ids_matches_explicit_bucket_and_excludes_deleted`, `test_visible_action_item_ids_excludes_legacy_null_completion_rows`, `test_visible_action_item_ids_includes_docs_with_absent_deleted_field` | | Add the forbidden `.where('deleted', '==', False)` server-side filter | `test_visible_action_item_ids_matches_explicit_bucket_and_excludes_deleted`, `test_visible_action_item_ids_includes_docs_with_absent_deleted_field` | | Remove the Python `if data.get('deleted'): continue` guard | `test_visible_action_item_ids_matches_explicit_bucket_and_excludes_deleted`, `test_visible_action_item_ids_includes_docs_with_absent_deleted_field` | | Remove the `record_firestore_read(...)` call | `test_visible_action_item_ids_records_firestore_read` | ## Product invariants affected None — `scripts/pr-preflight --suggest` reports no locked invariant paths touched by this diff. ## Failure class `scripts/pr-preflight --suggest` confirms this is a `fix:` commit requiring a declaration. I checked `.github/failure-classes/` for a genuine match: the closest candidates — `FC-bounded-read-exceeds-request-budget` (about per-query limits composing against a request-scoped middleware budget, not applicable here — there's no request budget in play, just an unbounded per-user scan), `FC-unbounded-user-collection-in-prompt` (about rendering a full collection into a provider/LLM prompt, not a Firestore billing concern), and `FC-unthrottled-read-revalidation` (about a *client's* revalidation cadence lacking a throttle; that class already exists and its `canonical_prevention_artifact` targets `desktop/windows` — this PR is the backend-side query fix, not the client cadence fix, and doesn't produce a new reusable guard surface) — none genuinely describe this specific defect (a per-user Firestore scan filtering in Python instead of pushing an equality predicate server-side, paired with a missing metering call). Declaring `new` isn't warranted either: this is a narrow, already-tested query and instrumentation fix, not a recurring class worth a permanent registry entry on its own evidence. Failure-Class: none <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/11849?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
undivisible
left a comment
There was a problem hiding this comment.
Cline review agrees: throttles idle/focus-driven Windows backend fetches (useThrottledWindowFocus, picker/goals/tasks/quota/retention) with unit tests and first-focus preserved. Typecheck/Lint/Test and Windows build smoke green. Merge.
A systematic sweep of what the Windows app asks the backend for when nobody is asking it to, following the billing RCA that
index.ts:997already records. Seven changes, each with the mutation that proves its test can fail.The single largest item is first, and it is worth reading on its own: a full memory page-through, every 30 minutes, on every default install, whose entire result is thrown away.
What was found
I inventoried every recurring timer, every mount-time fetch, and every focus listener in
desktop/windows, then traced each candidate to the endpoint it reaches and the work that endpoint does. Below is what is fixed here. Findings I did NOT act on are listed at the end, including three that turned out to be deliberate and one backend change that is worth more than anything in this PR but does not belong in it.1. The retention sweep runs on a timer for every default install, and discards the result
retentionModeis optional, and the sweep falls back todry-run. Onlyoffreturned early. So on default settings, every 30 minutes forever:fetchAllMemories()pages/v3/memoriesto exhaustionGET /v1/conversations?limit=200and then, in dry-run, hands all of it to a
console.logand returns. Every request was paid to write a line into a DevTools console that is not open, 48 times a day, for every user.Scheduled passes now require
live, the only mode that deletes anything.dry-runbecomes what its own label already claims: pressing Preview in Settings runs one pass, so the plan is logged when the user asks for it.This is the item where the backend cost is concentrated. Every page after the first takes the
offset>0path inmemories.py, which streams the wholememory_itemscollection and slices in Python.2. The staged-task promote timer POSTs about 1,440 times a day to be told "nothing"
promotionServiceranPOST /v1/staged-tasks/promoteon a flat 60s timer for the life of the process, withbypassDebounce: true, no local pre-check, and no backoff of any kind. Nearly every call returnspromoted:false, and each one costs the backend two full collection scans to say so. A 500ing endpoint got the same flat 60s forever.The net exists for staged rows created out of band. Every in-app path that stages a task already promotes inline or on the task-complete and task-delete events, none of which go through this timer, so its cadence is discovery latency for a rare case rather than responsiveness for a common one.
Ticks now walk 60s, 2m, 5m, 10m and hold. Any tick that actually promotes drops back to the 60s floor, so a backlog still drains one per minute exactly as before. Signed-out ticks make no request and do not walk the ladder.
3. Six-plus requests per window focus, for surfaces that are not on screen
MainViewsmounts every panel 1.8s after launch and never unmounts them, so awindowfocus listener registered by any page is live app-wide regardless of the current tab. Three pages register one, none route-gated and none throttled: Memories (a full/v3/memoriespage-through), Apps (three requests), and the Home goal chips (one).The trigger is not rare. The app blurs its own main window every time the floating bar, the orb, or the capture window takes focus, so ordinary voice use pays this repeatedly per minute.
Now throttled to once a minute per surface. The first focus always runs, so the behavior these surfaces promise is intact and the two existing page-side guards pass unchanged.
4. The chat quota is re-fetched on every bar reveal and every reply
sync()had an in-flight dedupe and nothing else, which does nothing for sequential calls. It runs fromBarApp'sonShowand fromUsageLimitTriggerHostafter every completed reply, both driven by the primary voice interaction.The per-reply probe doubles the request count of every chat turn: the "at most once per session" latch it relies on only sets when the quota is already exhausted, so for an under-cap user it never sets.
Refreshes are now floored at 60s. The gate already tracks sends between refreshes with
recordQuery()'s optimistic delta, so the verdict stays correct across the gap, and the first probe of a session is never throttled becausecheck()depends on it.This endpoint is cheap per call, unlike the others here. It is in the PR for call volume, not read cost.
5. The about-user card is rebuilt on every hub warm
refreshAboutUserCard()deduped only against a build already in flight. The hub deliberately re-warms all session long, and those warms are minutes apart, so the dedupe never applied. Each rebuild is aGET /v3/memories, several hundred times a day on an idle machine, to produce a card that had not changed. Now reused for five minutes.The warm loop itself is untouched. See the deliberate-behavior note below.
6. The goal cap is checked after the expensive read, not before
runGoalGenerationIfDuefetched five parallel reads including/v3/memories?limit=500and/v1/conversations?limit=100, and only then checked the three-active-goal cap. Sitting at the cap is the ordinary resting state, and that bail deliberately does not stamp the day, so the 4-hourly tick repeats indefinitely, re-paying all five reads each time.The count now comes from one
/v1/goals/allahead of the bundle, and that list is handed on to the context build so a run that proceeds reuses it rather than asking for the same list twice. Bail costs one read, proceed costs the same five it always did. The file's header already described the intended order as "cheap ones first, then the heavy context fetch"; the code now matches it.Default-off, so this is latent rather than live, but it is a real wedge for anyone who turns it on.
7. Two panels fetch for surfaces the user is not looking at
ChatAppPickercalleduseChatApps()above its own gate, issuingGET /v1/appsand then returning null because the pref is off for almost everyone. Split into gate plus inner, exactly as the siblingHubChatHeaderalready does for the same stated reason.TasksfetchedGET /v1/conversations?limit=200on mount for source-link labels, at every launch, whether or not Tasks was ever opened, and wrote a cache it never read. Now waits for the panel to be the active route and short-circuits on the cache: one request on first open, none after, against one per launch before.Verification
Run in
desktop/windows:npx vitest run- 5,267 passed, 18 skipped, 544 files.npm run typecheck- clean.npx eslint .- 0 errors. The 735 warnings are pre-existing prettier formatting in files this PR does not touch; the changed files add none.npm run build- builds clean, bytecode patch and verify both OK.29 mutations seeded across the seven changes. Every one turns the suite red now. Every one left it green before. They are listed per-commit with what each represents.
Three of those rounds found something rather than confirming something:
MIN_SYNC_INTERVAL_MSescaped, because every quota case passed an explicit interval while productionbarSend.tsconstructs the gate with no arguments and runs entirely on the default. Added a case that does the same.resetAboutUserCardwas unobservable, since nulling the card already defeats the guard. Dead line removed.Self-review also caught a defect in change 2 before it shipped: a tick re-arms from inside its own promise chain, so a stop landing mid-promote resurrected the timer
stopTaskPromotionServicehad just cleared, whichclearIntervalhad made impossible for free. Guarded, with a case.Two defects of my own, fixed in a follow-up commit
Both found by re-reading this diff and asking what each change costs on the paths it did NOT target, rather than by a test failing:
/v1/goals/allitself, so a run that generated asked for the same list twice: five reads became six. The bail path is the common one and got far cheaper, so the net was still a large win, but a PR about removing redundant requests should not add one.readTasksre-ran on every navigation in and out of the tab instead of once per mount. Local SQLite over IPC, so no backend cost and no spinner, but unintended and not what the commit claimed.The first fix needed a second round of mutation work: the schedule test proved the goal list was PASSED to the context build, but that build is mocked there, so nothing proved it was USED.
withPrefetchedGoalsexists to make that substitution testable without a live session.What is not verified
I did not exercise these against a live signed-in account. Signed out the app makes no backend requests at all, so a signed-out run cannot observe any of these paths, and I was not willing to generate real load on a real account to measure. Everything above is traced from the mount, route, and timer paths and covered by hermetic tests.
The two changes in commit 7 are the ones where that matters most, since neither has a test observing the request from the page side. The visible thing to confirm is that source-link titles still render on the first visit to Tasks.
One existing test changed
promotionService.test.tspinned the flat cadence ("5 minutes buys 5 ticks"). It now pins the ladder. The guard it was written for, that the session poll stops rather than running 60 five-second attempts, is unchanged and still asserted. The new expected values come from the ladder constants introduced in the same commit, and four separate mutations hold that ladder in place.Deliberate behavior I did not touch
Worth stating, since two of these look like bugs and are not:
hubControllerresets its strike budget on any socket that lived past the idle window, and the provider idle-closes at roughly two minutes, so an idle user's hub rebuilds indefinitely. The code documents this at length as the mechanism that keeps the next press on the warm lane. That is a latency-versus-cost product decision, not spam, so I left it and fixed only the memory fetch it was dragging along (change 5). If the tradeoff is worth revisiting, the lever is an idle release below the provider's close, and that is a product call.taskEnabled. Deliberate Mac parity, so backlog staged before the toggle was turned off still drains. Unchanged.Follow-ups, deliberately not in this PR
Each is real and located, and each is a different review surface:
GET /v1/action-items/idsis the biggest remaining item, and the fix is server-side.taskSyncEngineruns an ID census every 5 minutes, two requests, anddatabase/action_items.py:111streams the collection with no.where()and filterscompletedin Python, so each call reads every doc and the pair scans the collection twice. That is 24 full collection scans per idle hour per running client. Pushing.where('completed','==',completed)server-side roughly halves it immediately; a change token orupdated_sincewould make a steady-state round nearly free. Worth more than anything in this PR, and it is a backend change with its own correctness questions around soft-deleted andstatusrows, so it should not ride along here. Alsoget_visible_action_item_idsnever callsrecord_firestore_read, so this path is invisible in the read metrics.DELETE /v3/memories/{id}costs a full canonical scan per id, and Windows deletes serially in a loop.DELETE /v3/memories/batchexists and pays the scan once per batch. Windows already uses the batch POST but not the batch DELETE.preferences.retention.test.tscannot fail. Its default assertion isgetPreferences().retentionMode ?? 'dry-run', which is the fallback the test itself supplies. Left in place because the correct fix is to assert against the production default, and that default is exactly what change 1 is about.Product invariants affected
From
scripts/pr-preflight --suggest, matched on thechatQuotaGatechange. The gate's verdict is unchanged: the cold-start probe that blocks an over-cap user is explicitly exempt from the new floor, and the optimistic delta still counts sends between refreshes, both of which are asserted. Only the refresh cadence moved.scripts/pr-preflightalso reports nofix:commits, so noFailure-Classdeclaration is required.