Repository navigation
[codex] Improve desktop startup warmup performance - #8013
Conversation
Greptile SummaryThis PR restructures the macOS desktop startup sequence to improve time-to-interactive by moving all non-critical work out of
Confidence Score: 4/5Safe to merge with one small fix: the termination handler should cancel The core warmup coordinator, policy gates, and dashboard reconciliation service are all sound and well-tested. desktop/macos/Desktop/Sources/OmiApp.swift — the termination handler and Important Files Changed
Sequence Diagram%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
participant App as OmiApp/AppDelegate
participant VMC as ViewModelContainer
participant WC as StartupWarmupCoordinator
participant DTRS as DashboardTaskRefreshService
participant DHV as DesktopHomeView
App->>VMC: loadAllData()
VMC->>VMC: RewindDatabase.initialize()
VMC->>VMC: "isInitialLoadComplete = true"
VMC->>WC: schedulePostInteractiveWarmup(dbAvailable)
Note over WC: +0.25s: loadDashboardTasks() + loadCachedDashboardData()
Note over WC: +2.25s: TaskAgentManager.restoreSessions() + ScreenActivitySync.start()
Note over WC: +2.25s: fetchChatAppsForStartup() + initializeVisibleMessages()
Note over WC: +4s: DashboardTaskRefreshService.refresh()
WC->>DTRS: refresh(store)
DTRS->>DTRS: fetchDashboardWindowItems()
DTRS->>DTRS: fetchExactServerTruth(forDashboardIds)
DTRS->>DTRS: reconcile + syncTaskActionItems()
DHV->>DHV: scheduleConversationWarmup() (+6s)
DHV->>DHV: scheduleAgentVMProvisioning() (+20s)
DHV->>DHV: scheduleProactiveMonitoringStart() (+30s)
App->>App: scheduleAPIKeyFetch() (+9s)
App->>App: scheduleAppLifecycleMaintenance() (+8s recovery, +12s scheduler)
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
participant App as OmiApp/AppDelegate
participant VMC as ViewModelContainer
participant WC as StartupWarmupCoordinator
participant DTRS as DashboardTaskRefreshService
participant DHV as DesktopHomeView
App->>VMC: loadAllData()
VMC->>VMC: RewindDatabase.initialize()
VMC->>VMC: "isInitialLoadComplete = true"
VMC->>WC: schedulePostInteractiveWarmup(dbAvailable)
Note over WC: +0.25s: loadDashboardTasks() + loadCachedDashboardData()
Note over WC: +2.25s: TaskAgentManager.restoreSessions() + ScreenActivitySync.start()
Note over WC: +2.25s: fetchChatAppsForStartup() + initializeVisibleMessages()
Note over WC: +4s: DashboardTaskRefreshService.refresh()
WC->>DTRS: refresh(store)
DTRS->>DTRS: fetchDashboardWindowItems()
DTRS->>DTRS: fetchExactServerTruth(forDashboardIds)
DTRS->>DTRS: reconcile + syncTaskActionItems()
DHV->>DHV: scheduleConversationWarmup() (+6s)
DHV->>DHV: scheduleAgentVMProvisioning() (+20s)
DHV->>DHV: scheduleProactiveMonitoringStart() (+30s)
App->>App: scheduleAPIKeyFetch() (+9s)
App->>App: scheduleAppLifecycleMaintenance() (+8s recovery, +12s scheduler)
Reviews (1): Last reviewed commit: "Improve desktop startup warmup performan..." | Re-trigger Greptile |
There was a problem hiding this comment.
2 issues found across 18 files
Reply with feedback, questions, or to request a fix.
Fix all with cubic | Re-trigger cubic
There was a problem hiding this comment.
2 issues found across 2 files (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Fix all with cubic | Re-trigger cubic
|
Follow-up from David/Hermes review:
I pushed a minimal fix commit (
Validation:
|
There was a problem hiding this comment.
Pull request overview
This PR restructures the macOS desktop app’s startup work into an explicit staged warmup pipeline so the first usable window appears sooner, while deferring non-critical network/DB/background tasks until after the app is interactive.
Changes:
- Introduces
StartupWarmupCoordinator+StartupWarmupPolicyto schedule post-interactive warmups (service vs DB-dependent) with DB retry handling. - Reworks dashboard/task startup behavior to avoid eager Tasks page hydration while still keeping the Dashboard task snapshot fresh via a dashboard-scoped reconciliation path with bounded exact-ID fetch concurrency.
- Defers additional startup maintenance (API key fetch, floating bar plan fetch, transcription recovery, recurring scheduler, Crisp initial poll, file indexing backfill, agent VM provisioning, proactive monitoring) and adds targeted policy/reconciliation tests.
Reviewed changes
Copilot reviewed 18 out of 18 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| desktop/macos/Desktop/Tests/StartupWarmupPolicyTests.swift | Adds tests for warmup delay ordering and small scheduling state helpers. |
| desktop/macos/Desktop/Tests/DashboardTaskRefreshPolicyTests.swift | Adds tests for dashboard-scoped task refresh and bounded exact-ID fetch concurrency. |
| desktop/macos/Desktop/Sources/ViewModelContainer.swift | Narrows initial startup to DB init + schedules staged warmups; changes DB retry to return Bool. |
| desktop/macos/Desktop/Sources/Stores/TasksStore.swift | Adds dashboard-specific server refresh entrypoint. |
| desktop/macos/Desktop/Sources/Stores/DashboardTaskRefreshService.swift | Implements dashboard-scoped server reconciliation without hydrating the Tasks page list. |
| desktop/macos/Desktop/Sources/Stores/DashboardTaskRefreshPolicy.swift | Adds refresh + limiter policies and the reconciliation planner. |
| desktop/macos/Desktop/Sources/StartupWarmupPolicy.swift | Defines startup delay constants and small helper policies/state. |
| desktop/macos/Desktop/Sources/StartupWarmupCoordinator.swift | Schedules and runs staged warmups and DB retry loop. |
| desktop/macos/Desktop/Sources/ScreenActivitySyncService.swift | Adds optional initial delay parameter before entering sync loop. |
| desktop/macos/Desktop/Sources/Providers/ChatProvider.swift | Splits visible-message init vs prompt-context warmup. |
| desktop/macos/Desktop/Sources/Providers/AppProvider.swift | Adds startup-only chat-app fetch path. |
| desktop/macos/Desktop/Sources/OmiApp.swift | Defers API key fetch, floating bar plan fetch, transcription recovery, recurring scheduler, and initial settings sync. |
| desktop/macos/Desktop/Sources/MainWindow/Pages/TasksPage.swift | Implements Tasks page “first-use” loading behavior. |
| desktop/macos/Desktop/Sources/MainWindow/Pages/MemoriesPage.swift | Adds “load if needed” behavior on page task. |
| desktop/macos/Desktop/Sources/MainWindow/Pages/DashboardPage.swift | Switches dashboard tasks to dashboard-scoped refresh; adds cached goals snapshot load. |
| desktop/macos/Desktop/Sources/MainWindow/DesktopHomeView.swift | Defers agent VM provisioning, conversation warmup, proactive monitoring start, and file indexing backfill. |
| desktop/macos/Desktop/Sources/MainWindow/CrispManager.swift | Supports delayed initial poll and improves auth/backoff integration; skips network in XCTest. |
| desktop/macos/Desktop/Sources/APIClient.swift | Adds getActionItem(id:) endpoint helper used by dashboard reconciliation. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| let calendar = Calendar.current | ||
| let windowItems = try await fetchDashboardWindowItems(calendar: calendar) | ||
| let serverTruth = await fetchExactServerTruth(forDashboardIds: dashboardIds) | ||
| let plan = DashboardTaskReconciliationPlanner.plan( | ||
| localDashboardIds: dashboardIds, | ||
| dashboardWindowServerItems: windowItems, | ||
| exactServerItemsById: serverTruth.itemsById, | ||
| missingServerIds: serverTruth.missingIds, | ||
| calendar: calendar | ||
| ) |
| await measurePerfAsync("DATA LOAD: DB lifecycle warmup") { | ||
| await measurePerfAsync("DATA LOAD: Task agent restore") { | ||
| await TaskAgentManager.shared.restoreSessionsFromDatabase() | ||
| } | ||
| await measurePerfAsync("DATA LOAD: Screen activity sync") { | ||
| await ScreenActivitySyncService.shared.start( | ||
| initialDelay: StartupWarmupPolicy.screenActivitySyncInitialDelay | ||
| ) | ||
| } | ||
| } |
There was a problem hiding this comment.
1 issue found across 5 files (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Fix all with cubic | Re-trigger cubic
|
Addressed the new review comments pragmatically in
Validation:
|
eulicesl
left a comment
There was a problem hiding this comment.
Requesting changes on one remaining behavior regression.
Thanks for the follow-up commit. The latest head appears to address Copilot's two comments: DashboardTaskRefreshService.refresh now captures a single now and passes it through the dashboard window fetch + reconciliation planner, and StartupWarmupCoordinator.runDatabaseWarmup() now guards the DB lifecycle warmup when signed out.
The remaining blocker is the Tasks first-use path. This PR removes the old startup call to tasksStore.loadTasks(), but the replacement first-use entry point calls store.loadTasksIfNeeded():
desktop/macos/Desktop/Sources/MainWindow/Pages/TasksPage.swift:1811desktop/macos/Desktop/Sources/Stores/TasksStore.swift:464
loadTasksIfNeeded() only loads incomplete/dashboard/deleted task slices. The one-time full sync, AI-task staging migration, conversation-item staging migration, unsynced local retry, and relevance-score backfill are still only triggered from TasksStore.loadTasks():
desktop/macos/Desktop/Sources/Stores/TasksStore.swift:475
That means the common path for a normal user opening Tasks after startup no longer runs maintenance work that previously happened during startup. It will only happen later if the user manually refreshes or hits a retry/error path. I would either make first-use loading call loadTasks() directly, or extract those maintenance side effects into a shared post-first-load routine that both loadTasks() and loadTasksIfNeeded() invoke.
Validation I ran on latest head 1b5a1e180:
git diff --check 0d8109328013bfc428d1557d23da01fef13eb8d8...HEADcd desktop/macos && xcrun swift test --package-path Desktop --filter StartupWarmupPolicyTests— 20 tests passedcd desktop/macos && xcrun swift test --package-path Desktop --filter DashboardTaskRefreshPolicyTests— 3 tests passed
Non-blocking cleanup: there is a duplicated return in DesktopHomeView.scheduleInitialFileIndexing() after releaseReservation(); harmless, but worth removing while touching the file.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1b5a1e180e
ℹ️ 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".
| guard !isInitialLoadComplete else { | ||
| schedulePostInteractiveWarmup(dbAvailable: !databaseInitFailed) | ||
| return |
There was a problem hiding this comment.
Reinitialize startup state when the auth user changes
ViewModelContainer is held as a @StateObject by DesktopHomeView, so it survives the Sign Out menu flow. With this new early return, a later sign-in in the same app process skips the per-user RewindDatabase.configure/initialize path and only asks the already-reserved warmup coordinator to schedule more work; the in-memory stores are not reset here, so switching accounts can leave the new session reading or showing the prior user's cached local state. Key the initial-load state by auth_userId or reset it on .userDidSignOut before returning here.
Useful? React with 👍 / 👎.
| serviceWarmupTask = Task { [weak self] in | ||
| await self?.runServiceWarmup() | ||
| } | ||
| scheduleChatPromptContextWarmup() |
There was a problem hiding this comment.
Gate prompt-context warmup on database availability
When DB init fails (dbAvailable == false), this still schedules chatProvider.warmupPromptContext(), which reads local DB-backed tasks/schema. Those loaders mark themselves loaded on DB-unavailable failures, so after the retry path later succeeds the prompt context is not retried and first chat/bridge prompts can permanently miss tasks/schema for that session. Schedule this warmup only after DB warmup is reserved or recovered, or clear its loaded flags on retry.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 20b21f1cd6
ℹ️ 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".
| } | ||
|
|
||
| private func scheduleConversationWarmup() { | ||
| guard !didScheduleConversationWarmup else { return } |
There was a problem hiding this comment.
Reset conversation warmups on account switch
After a successful startup this flag stays true, while the sign-out handler below does not clear appState.conversations/folders. If a user signs out and signs into another account in the same app process, the next main-content .task returns here and never reloads the new user's conversation/folder lists; the Conversations page also skips loading because the old arrays are non-empty, so the previous account's data can remain visible. Reset these per-user warmup flags/caches on sign-out or key them by auth_userId.
Useful? React with 👍 / 👎.
| let delay = StartupWarmupPolicy.apiKeyFetchDelay | ||
| if delay > 0 { | ||
| try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) | ||
| } |
There was a problem hiding this comment.
Start key fetch before auto-start transcription waits
For signed-in launches where transcriptionEnabled is true and no developer/proxy env key is present, DesktopHomeView defers recording until apiKeyService.isLoaded changes, but this new path sleeps for apiKeyFetchDelay before it even starts fetching those in-memory keys. That means auto-start recording begins at least ~9 seconds late on every cold launch and can miss speech during that window; start the key fetch immediately when transcription is enabled, or have that path call waitForKeys() without the startup delay.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
3 issues found across 6 files (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Fix all with cubic | Re-trigger cubic
There was a problem hiding this comment.
1 issue found across 5 files (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Fix all with cubic | Re-trigger cubic
|
Addressed latest review comments through
One comment I intentionally did not address: Codex's API-key/transcription startup delay comment. David explicitly accepted missing the first few seconds of capture/transcription in exchange for better perceived startup UI/UX, so that tradeoff is intentional for this PR. Validation:
|
|
@codex review |
@Git-on-my-level I have started the AI code review. It will take a few minutes to complete. |
|
To use Codex here, create a Codex account and connect to github. |
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
There was a problem hiding this comment.
Approved after local macOS validation. I pulled the latest PR head (fab16b1a5), ran the focused desktop tests, and sanity-launched a named bundle locally.
Validation run:
xcrun swift test --package-path Desktop --filter StartupWarmupPolicyTests: 29 passedxcrun swift test --package-path Desktop --filter DashboardTaskRefreshPolicyTests: 3 passedgit diff --check origin/main...HEAD: clean- Built/launched
/Applications/omi-pr-8013.appvia./run.sh --yolowith automation bridge; reachedappState=mainsigned in - Navigated Tasks, Memories, and Home, then ran
refresh_all_datasuccessfully
I also chased the SQLite error seen during the PR sanity run. The failing insert path is TaskPromotionService -> ActionItemStorage.insertLocalActionItem, which this PR does not change.
A fresh origin/main named-bundle run reproduced the same family of errors repeatedly: TaskPromotion insert failures against action_items_fts, plus disk I/O errors on PRAGMA schema_version. I’m treating that as an existing/environmental desktop DB issue rather than a regression from this startup warmup PR.
## Summary - share/await an in-flight dashboard refresh so concurrent callers still reload local dashboard state - paginate dashboard freshness buckets instead of relying on offset=0 only - add a targeted authoritative visibility reconciliation path for completed/deleted/dueAt without overwriting user-edited task text ## Testing - `git diff --check` - `xcrun swift package --package-path Desktop describe --type json` - `xcrun swiftc -parse Desktop/Sources/Stores/DashboardTaskRefreshPolicy.swift Desktop/Sources/Stores/DashboardTaskRefreshService.swift Desktop/Sources/Rewind/Core/ActionItemStorage.swift Desktop/Tests/DashboardTaskRefreshPolicyTests.swift Desktop/Tests/ActionItemStorageVisibilityReconciliationTests.swift` - attempted `xcrun swift test --package-path Desktop --filter 'DashboardTaskRefreshPolicyTests|ActionItemStorageVisibilityReconciliationTests'`; blocked while downloading SwiftPM binary artifacts with duplicate GitHub keychain entries, then killed after ~5m\n\nFixes #8124\n\nStacked on #8013 because `DashboardTaskRefreshService` is introduced there. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/8156?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. -->
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c7f01e6044
ℹ️ 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".
| warmupCoordinator.reset() | ||
| tasksStore.resetSessionState() | ||
| dashboardViewModel.resetSessionState() | ||
| memoriesViewModel.resetSessionState() |
There was a problem hiding this comment.
Reset AppProvider on account switches
When this reset runs during .userDidSignOut/account switches, it clears tasks, dashboard, and memories state but leaves appProvider.apps, enabledApps, category lists, and their per-user enabled flags intact. Because this change no longer does a full fetchApps() during startup warmup and AppsPage only fetches when appProvider.apps.isEmpty, a user who opened Apps before switching accounts can keep seeing and toggling the previous account's app state in the new session; reset AppProvider here or force a full apps refresh after auth changes.
Useful? React with 👍 / 👎.
## Summary - centralize delayed startup warmups behind a session-scoped coordinator task registry - cancel/reset startup warmups on sign-out, onboarding reset, and app termination - move DesktopHomeView delayed warmups through the coordinator and scope Crisp initial polling to the signed-in user - add focused lifecycle/source-invariant tests for session scoping and cancellation hooks ## Testing - `git diff --check` - `sh scripts/pre-commit` - `xcrun swiftc -parse Desktop/Sources/StartupWarmupPolicy.swift Desktop/Sources/StartupWarmupCoordinator.swift Desktop/Sources/ViewModelContainer.swift Desktop/Sources/MainWindow/DesktopHomeView.swift Desktop/Sources/MainWindow/CrispManager.swift Desktop/Tests/StartupWarmupPolicyTests.swift` - `xcrun swift package --package-path Desktop describe` - Attempted `xcrun swift test --package-path Desktop --filter StartupWarmupPolicyTests`; blocked/killed during SwiftPM binary artifact downloads with duplicate GitHub keychain-entry warning, same local environment blocker seen on earlier Desktop runs. Stacked on #8013. Fixes #8123 <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/8159?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. -->
|
Maintainer feedback: Please clear/address the remaining account-switch/session reset issue identified by Codex. Reference: #8013 (comment) The PR already resets several per-user stores on sign-out/startup reset, but Please add a session reset path for |
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for the continued iteration here. The staged startup direction still looks valuable, and the focused checks are green, but I’m not comfortable re-approving the current head yet because one account-switch/session-state hole remains.
ViewModelContainer.resetStartupState() now clears Tasks, Dashboard, and Memories state, but it does not reset appProvider. This PR also adds startup warmup through appProvider.fetchChatAppsForStartup(), while the full Apps page fetch/enrichment keeps user-specific enabled state in apps, enabledApps, chatApps, and the other grouped lists. On an in-process account switch, those AppProvider lists/filters/loading states can survive into the next session until a full refetch happens, which can expose the previous user's enabled app state or allow toggling from stale UI state.
Please add an AppProvider.resetSessionState() path and call it from ViewModelContainer.resetStartupState(). It should clear the published app/group/enabled lists, category/capability metadata where appropriate, filters/search/category pagination state, loading states, and errors, and include a small regression/source-invariant test alongside the existing startup reset tests.
Also note that GitHub currently reports this PR as conflicting with main, so it will need an update before merge regardless.
…-warmup-performance # Conflicts: # desktop/macos/Desktop/Sources/MainWindow/DesktopHomeView.swift # desktop/macos/Desktop/Sources/Providers/ChatProvider.swift
|
@Git-on-my-level thanks for the careful pass. I addressed the account-switch hole by adding I also updated the branch against the latest |
|
@eulicesl thanks, this was valid on Startup DB warmup also schedules the same maintenance path without hydrating the Tasks page, and |
…-warmup-performance
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for addressing the remaining account-switch/session-state blocker. I re-reviewed the current head (a54feb5): the new AppProvider reset path is wired into ViewModelContainer.resetStartupState(), the regression coverage checks the expected per-user AppProvider clears, the branch is mergeable again, and the latest checks are green.\n\nI do not see a remaining blocker from the maintainer side. Please still rely on the existing focused macOS validation for the startup behavior, since I only re-reviewed this iteration statically plus live GitHub metadata here.
|
@ThomsenDrake The new I also re-checked the adjacent startup paths: dashboard-scoped task refresh still does not require full Tasks-page hydration, and one-time task maintenance still runs from the DB warmup path without forcing the Tasks page list to load. Validation run locally:
No remaining blocker from me. Non-blocking follow-up: consider clearing Please resolve the now-addressed review/bot threads so the conversation state matches the current code. I’ll handle the formal approval from my side. |
…t to 6s Since #8013, proactiveAssistantsStartDelay (30s) was applied as a fixed delay from whatever event triggered scheduling (launch, key load, app active), so late triggers re-paid the full 30s and the Capture pill sat 'paused' for 30-60+ seconds after every launch. Measure the delay as a launch-anchored budget instead (max(0, delay - elapsedSinceLaunch)) and reduce it to 6s, keeping capture start strictly after the 5s settings sync and 2s deferred warmup that #8013's ordering tests pin.
…0-60s (launch-anchored warmup) (#9021) ## Summary - Problem: since #8013, the home-screen "Capture" pill stays **paused for 30–60+ seconds after every launch** before screen capture starts. `StartupWarmupPolicy.proactiveAssistantsStartDelay` (30s) is applied as a fixed delay **from whatever event triggers scheduling**, not from launch — so a launch with cached keys waits 30s, a launch whose API keys load late waits key-load + 30s (~40–60s), and re-activating the app (`reason: "app active"`, e.g. right after granting Screen Recording) waits a fresh 30s even minutes after launch. For a product whose core feature is capturing your screen, the first half-minute of every session is silently lost. - What changed: the warmup delay is now a **launch-anchored budget** — `remainingProactiveAssistantsStartDelay(elapsedSinceLaunch:)` returns `max(0, delay − elapsed)`, so the delay is paid once per session, not once per trigger — and the budget is reduced from 30s to **6s**. A `Scheduling screen analysis start in Xs (reason)` log line makes the effective delay observable. - What did NOT change (scope boundary): the staged-warmup ordering from #8013 is preserved — capture still starts strictly after `initialSettingsSyncDelay` (5s) so a remote `screenAnalysisEnabled=false` lands before monitoring starts, and still after `deferredWarmupDelay` (2s). Both existing ordering tests pass unchanged. No other warmup delays are touched. ## Linked Issue / Bounty - N/A — independent contribution (behavioral regression introduced by #8013) ## Root Cause (bug fixes only) - Root cause: #8013 introduced `proactiveAssistantsStartDelay = 30.0` and `scheduleProactiveMonitoringStart()` passes it verbatim to `scheduleSessionWarmup` on every trigger (`launch`, `key load`, `app active`). The delay's purpose is to keep capture out of the busy launch window, but measuring it from the trigger instead of from launch makes late triggers re-pay the full 30s. - Why it wasn't caught before: #8013 was validated with policy unit tests and build checks ("without changing product behavior"); the pill-stays-paused effect only shows up when running the app and watching the first minute. Verified on production v0.12.0 (which contains both #8013 and the later paywall launch fix): capture consistently starts ~30s after window appear. ## How It Works `StartupWarmupPolicy.remainingProactiveAssistantsStartDelay(elapsedSinceLaunch:)` computes the remaining launch-anchored budget (clamping negative elapsed to the full delay). `DesktopHomeView` captures a `proactiveMonitoringWarmupAnchor = Date()` when the view is created (≈ launch) and passes the computed remainder to `scheduleSessionWarmup`. Behavior by scenario: | Scenario | Before | After | |---|---|---| | Launch, keys cached | 30s | 6s | | Launch, keys load at +9s | ~39s | 9s (budget already elapsed → starts at key load) | | Slow key fetch (e.g. +30s) | ~60s | at key load | | App re-activation (e.g. after permission grant) | +30s | immediate | ## Change Type - [x] Bug fix ## Scope - [x] Desktop app (Swift/macOS) ## Security Impact - New permissions or capabilities introduced? No - Auth or token handling changed? No - Data access scope changed (screen data, OCR, user data)? No — capture still requires the same permission and enabled setting; it just starts sooner - New or changed network calls? No - Plugin or tool execution surface changed? No ## Testing - [x] Built locally — `xcrun swift build -c debug --package-path Desktop`, clean (macOS 26.5.1, arm64) - [x] Manual verification: launch/key-load/app-active timing on a named bundle (see Human Verification) - [x] Existing tests pass — `StartupWarmupPolicyTests` (including the two ordering invariants that pin capture after settings sync and deferred warmup) - [x] New tests added — 4 cases covering the anchored-budget helper: full delay at elapsed 0, countdown mid-window, zero after the window, negative-elapsed clamp ## Human Verification Verified on a dedicated named bundle (`com.omi.omi-verify-capture`) built from this branch, signed in, macOS 26.5.1: - Verified scenarios: 1. **Launch with permission granted**: capture running **5.5s after the main window appeared** (`Scheduling screen analysis start in 5.2s (launch)` → `Screen analysis started (launch, delayed)`), versus +30.4s measured on production v0.12.0. 2. **Launch-anchoring**: the scheduled delay is the launch budget minus elapsed time (logged `5.2s`/`5.4s` across launches depending on view-appear latency), and the start attempt consistently fired at launch+6s. 3. **Permission still gates correctly**: with Screen Recording not yet granted, the launch+6s attempt entered the existing dialog-free retry loop and left the setting enabled; after granting in System Settings, the next launch started capture at +5.5s and macOS registered active capture usage for the bundle (`ScreenCaptureApprovals.plist` LastUsed). - Edge cases checked: trigger arriving after the window has fully elapsed (app-active → 0.0s delay); re-launch repeats the 6s budget per session. - What was **not** verified: Intel macs; the `key load` trigger with a genuinely slow network fetch (exercised the code path via the anchored computation instead). ## Evidence - [x] Log output (before/after) Production v0.12.0 (before — fixed 30s from window appear): ``` [13:33:09.220] DesktopHomeView: Showing mainContent (signed in and onboarded) [13:33:18.221] DesktopHomeView: API keys loaded — retrying deferred services [13:33:39.612] DesktopHomeView: Screen analysis started (launch, delayed) ← +30.4s ``` This branch (after): ``` [19:06:38.366] DesktopHomeView: Showing mainContent (signed in and onboarded) [19:06:38.410] DesktopHomeView: Scheduling screen analysis start in 5.2s (launch) [19:06:43.830] DesktopHomeView: Screen analysis started (launch, delayed) ← +5.5s ``` Permission-missing launch on the same build (retry loop intact, timing unchanged): ``` [18:56:41.588] DesktopHomeView: Scheduling screen analysis start in 5.4s (launch) [18:56:47.320] Screen recording permission not yet granted, retrying in 2.0s (attempt 1/3) ``` ## Docs - [x] N/A — no docs impact (changelog fragment added) ## Performance, Privacy, and Reliability Launch performance: capture-start work now runs at +6s instead of +30s. This sits after the first-window render and the 5s settings sync; the heavier startup warmups (`crispInitialPoll` 15s, `agentVMProvisioning` 20s, `initialFileIndexing` 45s) remain untouched, so launch responsiveness — the goal of #8013 — is preserved. If capture start measurably contends at +6s, the constant is a single knob to tune; the launch-anchoring fix stands on its own regardless of the chosen value. ## Migration / Backward Compatibility - Backward compatible? Yes - Migration needed? No ## Risks and Mitigations - Risk: starting capture at +6s could contend with remaining launch work on slow machines. - Mitigation: still strictly after settings sync (5s) and deferred warmup (2s); ordering tests enforce this. The 30s value predates any measured contention data for capture specifically. - Risk: remote `screenAnalysisEnabled=false` arriving after capture starts (settings sync slower than 6s on a slow network) would leave monitoring running this session. - Mitigation: pre-existing behavior — nothing stops a running monitor on remote-sync disable today, at 30s or 6s; the 5s-before-6s ordering keeps the common case correct. A remote-sync stop hook would be a separable follow-up. ## AI Disclosure - Tools used: Claude Code - AI-assisted portions: diagnosis (production log timeline analysis), fix implementation, tests, and this PR body - How you verified correctness: measured the regression on production v0.12.0 logs; built and ran a named bundle from this branch and measured launch→capture-start and app-active→start timings from app logs; ran the warmup-policy test suite. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/9021?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. -->
Summary
Improves macOS desktop startup and post-interactive warmup performance without changing visible IA, navigation, layout, or product behavior.
Key changes:
ViewModelContainer.loadAllData()focused on critical DB init and first-window readiness.StartupWarmupCoordinatorwith DB-aware scheduling and retry recovery.DashboardExactTaskFetchPolicy.maxConcurrentRequests.Validation
cd desktop/macos && xcrun swift test --package-path Desktop --filter StartupWarmupPolicyTestscd desktop/macos && xcrun swift test --package-path Desktop --filter DashboardTaskRefreshPolicyTestscd desktop/macos && xcrun swift build -c debug --package-path Desktopgit diff --checkNotes
This intentionally avoids reintroducing full Tasks page hydration during dashboard warmup. Dashboard freshness remains dashboard-scoped, with full task list hydration reserved for Tasks page first use.