Skip to content

[codex] Improve desktop startup warmup performance - #8013

Merged
ThomsenDrake merged 29 commits into
mainfrom
codex/desktop-startup-warmup-performance
Jun 26, 2026
Merged

ThomsenDrake merged 29 commits into
mainfrom
codex/desktop-startup-warmup-performance

Conversation

@ThomsenDrake

@ThomsenDrake ThomsenDrake commented Jun 18, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Improves macOS desktop startup and post-interactive warmup performance without changing visible IA, navigation, layout, or product behavior.

Key changes:

  • Keeps ViewModelContainer.loadAllData() focused on critical DB init and first-window readiness.
  • Moves staged post-interactive warmup into StartupWarmupCoordinator with DB-aware scheduling and retry recovery.
  • Defers app/service warmups such as chat apps, visible chat messages, prompt context, dashboard refresh, task-agent restore, screen activity sync, transcription retry recovery, recurring task scheduling, Crisp, file indexing, and related startup timers.
  • Preserves Tasks page correctness with first-use loading instead of eager global task hydration.
  • Restores Dashboard task freshness through a dashboard-scoped sync/reconciliation path that does not populate the full Tasks page list.
  • Bounds dashboard exact-ID reconciliation fanout with DashboardExactTaskFetchPolicy.maxConcurrentRequests.
  • Adds focused policy/reconciliation tests for startup delays, DB retry behavior, Tasks first-use loading, dashboard stale-row handling, and bounded exact-ID fetch concurrency.

Validation

  • cd desktop/macos && xcrun swift test --package-path Desktop --filter StartupWarmupPolicyTests
  • cd desktop/macos && xcrun swift test --package-path Desktop --filter DashboardTaskRefreshPolicyTests
  • cd desktop/macos && xcrun swift build -c debug --package-path Desktop
  • git diff --check
  • Local cubic review loop run; concrete P1/P2 findings were addressed. Remaining cubic comments are broader coordinator/task-sync consolidation follow-ups that would require a wider architectural migration.

Notes

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.

Review in cubic

@ThomsenDrake
ThomsenDrake marked this pull request as ready for review June 18, 2026 23:24
@greptile-apps

greptile-apps Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR restructures the macOS desktop startup sequence to improve time-to-interactive by moving all non-critical work out of ViewModelContainer.loadAllData() and into a new StartupWarmupCoordinator with DB-aware, staged scheduling. A new DashboardTaskRefreshService handles dashboard freshness without populating the full Tasks page list, and TasksPage now triggers its own first-use load on appearance.

  • Startup path now only blocks on SQLite init; every other warmup step (task-agent restore, screen sync, chat apps, prompt context, Crisp, file indexing, conversation fetch, proactive monitoring) is deferred behind StartupWarmupPolicy delays ranging from 0.25 s to 45 s.
  • Dashboard reconciliation fetches a server window + exact-ID truth for locally visible tasks, caps concurrent per-ID requests at 6, and syncs/hard-deletes without touching the Tasks page list.
  • Retry and cleanup plumbing is added for DB init failures (exponential backoff via coordinator), and per-task lifecycle tasks (apiKeyFetchTask, appLifecycleMaintenanceTask) are cancelled on app termination — though initialSettingsSyncTask is omitted from that cleanup.

Confidence Score: 4/5

Safe to merge with one small fix: the termination handler should cancel initialSettingsSyncTask alongside the two other stored tasks it already cancels.

The core warmup coordinator, policy gates, and dashboard reconciliation service are all sound and well-tested. initialSettingsSyncTask is stored for lifecycle management but missing from the termination cleanup that was added for the other two stored tasks — a concrete gap in the same code path. An unretained task in scheduleFloatingBarPlanFetch is also inconsistent with the pattern used elsewhere.

desktop/macos/Desktop/Sources/OmiApp.swift — the termination handler and scheduleFloatingBarPlanFetch both need the same cleanup treatment applied to the other stored tasks.

Important Files Changed

Filename Overview
desktop/macos/Desktop/Sources/StartupWarmupCoordinator.swift New coordinator that drives all post-interactive warmup stages; DB-availability gate, exponential-backoff retry loop, and cancellation on cancel() look correct.
desktop/macos/Desktop/Sources/OmiApp.swift Startup sequence refactored to use delayed tasks; initialSettingsSyncTask is stored but never cancelled on termination (unlike the two other stored tasks that are cancelled), and scheduleFloatingBarPlanFetch uses an unretained Task.
desktop/macos/Desktop/Sources/ViewModelContainer.swift Slimmed to DB init + isInitialLoadComplete flag; all warmup delegated to coordinator. isInitialLoadComplete is set before warmup is scheduled, ensuring the second-call guard is safe.
desktop/macos/Desktop/Sources/Stores/DashboardTaskRefreshService.swift New dashboard-scoped reconciliation service; reentrancy guard and auth-backoff integration look correct. Force-unwrap on calendar.date(byAdding:) is inconsistent with the companion planner.
desktop/macos/Desktop/Sources/Stores/DashboardTaskRefreshPolicy.swift Policy flags, chunk-based concurrency limiter, and reconciliation planner; chunking logic and isDashboardVisible window arithmetic are correct.
desktop/macos/Desktop/Sources/MainWindow/DesktopHomeView.swift Startup-critical work (VM provisioning, conversation warmup, file indexing, screen-analysis start) is now deferred with one-shot gates; @MainActor annotations are correctly added to Tasks that touch view state.
desktop/macos/Desktop/Sources/MainWindow/CrispManager.swift Added initialPollDelay parameter and an XCTest guard in pollForMessages; both changes are narrow and don't affect production behaviour outside their guarded paths.
desktop/macos/Desktop/Tests/StartupWarmupPolicyTests.swift Good coverage of policy ordering, schedule-state one-shot gates, and first-use load conditions.
desktop/macos/Desktop/Tests/DashboardTaskRefreshPolicyTests.swift Concurrency cap, reconciliation plan correctness (stale removal, completed/moved-out classification), and policy flags are all exercised.

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)
Loading
%%{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)
Loading

Reviews (1): Last reviewed commit: "Improve desktop startup warmup performan..." | Re-trigger Greptile

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

2 issues found across 18 files

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

No issues found across 18 files

Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@Git-on-my-level

Copy link
Copy Markdown
Member

Follow-up from David/Hermes review:

I pushed a minimal fix commit (44629ade2) to keep this PR scoped:

  • Crisp delayed initial poll is now retained/cancelled on stop() so it cannot fire after sign-out.
  • Crisp 401 now throws APIError.unauthorized, preserving auth-backoff behavior instead of reporting success.
  • Delayed desktop warmups now re-check cancellation/sign-in after sleep before side-effectful work (Agent VM provisioning, conversation warmup, initial file indexing, proactive monitoring).

Validation:

  • git diff --check origin/main...HEAD ✅
  • GitHub Lint & Format Check ✅
  • cubic review ✅
  • Local Swift/Xcode tests not runnable from this Linux workspace (swift/xcrun unavailable).

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.

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 + StartupWarmupPolicy to 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.

Comment on lines +32 to +41
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
)
Comment on lines +81 to +90
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
)
}
}

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@Git-on-my-level

Copy link
Copy Markdown
Member

Addressed the new review comments pragmatically in 1b5a1e180:

  • cubic: released delayed warmup one-shot/reservation state when early auth/cancellation guards exit, so Agent VM provisioning, conversation warmup, and initial file-indexing backfill can be scheduled again on a later signed-in appearance.
  • cubic: added a small DelayedFileIndexingBackfillState.releaseReservation() regression test.
  • Copilot: captured one now in DashboardTaskRefreshService.refresh(store:) and passed it through both the server fetch window and reconciliation plan to avoid midnight/DST boundary mismatches.
  • Copilot: added an auth guard before DB lifecycle warmups start TaskAgentManager.restoreSessionsFromDatabase() / ScreenActivitySyncService.start(...).

Validation:

  • git diff --check origin/main...HEAD ✅
  • cubic review on latest head ✅
  • Local Swift/Xcode tests still not runnable from this Linux workspace (swift/xcrun unavailable).

@eulicesl eulicesl left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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:1811
  • desktop/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...HEAD
  • cd desktop/macos && xcrun swift test --package-path Desktop --filter StartupWarmupPolicyTests — 20 tests passed
  • cd 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.

@Git-on-my-level

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +42 to +44
guard !isInitialLoadComplete else {
schedulePostInteractiveWarmup(dbAvailable: !databaseInitFailed)
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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 }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +1360 to +1363
let delay = StartupWarmupPolicy.apiKeyFetchDelay
if delay > 0 {
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@Git-on-my-level

Copy link
Copy Markdown
Member

Addressed latest review comments through a0e101086:

  • Fixed Tasks first-use maintenance without reverting to repeated full reloads:
    • loadTasksIfNeeded() now schedules the full-sync / AI-staging migration / conversation-item staging migration / unsynced retry / relevance-score backfill once.
    • TasksPage.loadTasksForFirstUse() is back to loadTasksIfNeeded() so zero-task users don't do repeated full reload work on every appearance.
  • Fixed auth/session reset concerns:
    • StartupWarmupCoordinator.reset() now nils all retained task handles after cancellation so DB retry scheduling is not blocked by a cancelled stale task.
    • sign-out clears conversation/folder arrays, conversation count/error/loading state, folder/date/starred filters, and warmup one-shot flags.
    • ViewModelContainer.resetStartupState() also resets TasksStore in-memory session state so the next account starts from clean task arrays/flags.
  • Fixed cubic's final stale selectedFolderId comment and also reset adjacent conversation filters (selectedDateFilter, showStarredOnly).

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:

  • git diff --check origin/main...HEAD ✅
  • GitHub Lint & Format Check ✅
  • cubic review on latest head ✅
  • Local Swift/Xcode tests still not runnable in this Linux workspace (swift/xcrun unavailable). eulicesl previously reported the focused Swift tests passing on macOS for the prior head.

@Git-on-my-level

Copy link
Copy Markdown
Member

@codex review

@cubic-dev-ai

cubic-dev-ai Bot commented Jun 23, 2026

Copy link
Copy Markdown

@cubic-dev-ai review
@codex review

@Git-on-my-level I have started the AI code review. It will take a few minutes to complete.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

0 issues found across 1 file (changes from recent commits).

Re-trigger cubic

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: b6894874fe

ℹ️ 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".

@Git-on-my-level Git-on-my-level left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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 passed
  • xcrun swift test --package-path Desktop --filter DashboardTaskRefreshPolicyTests: 3 passed
  • git diff --check origin/main...HEAD: clean
  • Built/launched /Applications/omi-pr-8013.app via ./run.sh --yolo with automation bridge; reached appState=main signed in
  • Navigated Tasks, Memories, and Home, then ran refresh_all_data successfully

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.

Git-on-my-level and others added 3 commits June 24, 2026 10:16
## 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. -->

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Git-on-my-level and others added 2 commits June 24, 2026 10:59
## 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. -->
@ThomsenDrake
ThomsenDrake requested a review from eulicesl June 24, 2026 14:05
@eulicesl

eulicesl commented Jun 24, 2026 •

Copy link
Copy Markdown
Collaborator

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 AppProvider is still left intact. Since this PR defers full app loading and the Apps page only fetches when provider state is empty, switching accounts in the same app process can leave prior-user app lists/enabled state visible or toggleable in the next session.

Please add a session reset path for AppProvider (for example AppProvider.resetSessionState() called from ViewModelContainer.resetStartupState()), and include regression coverage/source invariant coverage so this does not drift again. Once that is fixed and the stale/addressed threads are resolved, I can re-review/approve.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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
@ThomsenDrake

Copy link
Copy Markdown
Collaborator Author

@Git-on-my-level thanks for the careful pass. I addressed the account-switch hole by adding AppProvider.resetSessionState() and calling it from ViewModelContainer.resetStartupState(), with a StartupWarmupPolicyTests regression covering per-user AppProvider state reset.

I also updated the branch against the latest origin/main; the merge base is current, and the focused startup tests plus desktop debug build are passing locally.

@ThomsenDrake

Copy link
Copy Markdown
Collaborator Author

@eulicesl thanks, this was valid on 1b5a1e180. I kept Tasks first-use on loadTasksIfNeeded() to preserve the startup win, but extracted the missed full-sync, staging migrations, unsynced retry, and relevance backfill work into TasksStore.scheduleStartupMaintenanceIfNeeded(), which is now invoked from both loadTasksIfNeeded() and loadTasks().

Startup DB warmup also schedules the same maintenance path without hydrating the Tasks page, and StartupWarmupPolicyTests now cover the first-use/DB-warmup behavior. The duplicate return in the delayed file-indexing path is gone as well.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@eulicesl

eulicesl commented Jun 26, 2026 •

Copy link
Copy Markdown
Collaborator

@ThomsenDrake
Thanks for the follow-through here. I re-reviewed the current head (a54feb5f) and the remaining account-switch/session-state blocker looks addressed.

The new AppProvider.resetSessionState() clears the app/group/enabled lists, category/capability metadata, filters, pagination state, loading flags, and errors, and it is now wired through ViewModelContainer.resetStartupState() alongside the existing Tasks, Dashboard, Memories, and startup-warmup resets. That closes the stale per-user app-state concern from the previous review.

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:

  • xcrun swift test --package-path Desktop --filter StartupWarmupPolicyTests — 34 passed
  • xcrun swift test --package-path Desktop --filter DashboardTaskRefreshPolicyTests — 4 passed
  • xcrun swift build -c debug --package-path Desktop — passed
  • git diff --check origin/main...HEAD — clean

No remaining blocker from me. Non-blocking follow-up: consider clearing ChatProvider.selectedAppId in the auth-reset path as a belt-and-suspenders cleanup, since sends still use that selected app id directly after sign-out. I would not hold this PR on that unless app selection is meant to be strictly per-account.

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.

@ThomsenDrake
ThomsenDrake merged commit c243b09 into main Jun 26, 2026
3 checks passed
@ThomsenDrake
ThomsenDrake deleted the codex/desktop-startup-warmup-performance branch June 26, 2026 22:00
Git-on-my-level pushed a commit that referenced this pull request Jul 4, 2026
…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.
Git-on-my-level added a commit that referenced this pull request Jul 4, 2026
…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. -->
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.

5 participants