Skip to content

feat(desktop): free-tier screen embeddings on-device, Gemini per-frame call stops for free users (#13465) - #13473

Closed
Git-on-my-level wants to merge 45 commits into
feat/desktop-local-embeddings-hybridfrom
feat/desktop-free-tier-local-embeddings
Closed

Git-on-my-level wants to merge 45 commits into
feat/desktop-local-embeddings-hybridfrom
feat/desktop-free-tier-local-embeddings

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #13465. Stacked on #13456 (retarget to main after it merges; the diff below dbde4c39f8 is #13456).

  • Free desktop users get on-device screen embeddings and stop calling Gemini per frame. ScreenEmbeddingPolicy decides from the cached subscription plan plus the local engine probe: free or unknown plan + local engine → local index only; free + no engine → FTS-only, never Gemini; active paid → today's Gemini upload continues (Pinecone parity for phone search) and desktop search still routes local when available; hard kill restores Gemini everywhere. Unknown plan resolves as free, so a missing plan never spends Gemini.
  • Capture (RewindIndexer), queued flushes and backfill (OCREmbeddingService) enforce the gate; the plan is read synchronously from the cached value, nothing blocks capture.
  • Rewind UI search now goes through the same ScreenHistorySearchRoute as the chat tool.
  • Stable-channel sync fix: the legacy screen sync selected only rows with a Gemini vector, so free rows would have stopped reaching Firestore (what cloud chat and the phone's time-window browse read). Vectorless rows now sync once their OCR bucket is final when the policy says no Gemini; paid behaviour unchanged. Backend /v1/screen-activity/sync already accepts rows without embedding and forwards only vector rows to Pinecone.
  • Route telemetry is one bounded event per decision change plus an hourly heartbeat, never per frame.
  • Backend gate is on by default, with no config step. The new desktop build sends a bare capability header (X-Omi-Local-Embeddings: 1) on its Gemini proxy calls; a basic-plan embedContent/batchEmbedContents that carries it gets the plan-gated 402. Calls without the header are pre-migration builds and pass through to Gemini unchanged, counted as desktop_embed_legacy_client so the stale-client share is visible. A hard-killed client sends nothing and behaves like an old one. BYOK, paid, and the release probe stay allowed. DESKTOP_EMBED_PLAN_GATE_DISABLED=1 is the only switch.
  • Real-DB benchmark fixture (fixture=real, privacy-safe: counts and metrics only) added next to the synthetic one.

Why

Ruled by David 2026-09-10: free first, paid later. plan_catalog.json already declares desktop_free.cloud_screen_vectors: false and the backend honours it for Pinecone; the client never read it, so every OCR'd frame on every plan went through gemini-embedding-001 (modelled $28.85/day, ~85% from free users). A free user's Gemini vector only ever served desktop-local cosine search.

Benchmark (real fixture, this Mac, Apple silicon, 144 Gemini-embedded rows, engine apple_nlce 512-d)

slice mode recall@1 recall@10 nDCG@10
agreement with Gemini top-10 fts – 0.14 0.24
agreement with Gemini top-10 vector – 0.27 0.33
agreement with Gemini top-10 hybrid – 0.30 0.42
held-out self-retrieval fts 0.71 0.98 –
held-out self-retrieval vector 0.34 0.66 –
held-out self-retrieval hybrid 0.84 1.00 –

96 queries. Gemini's own self-retrieval is the degenerate 1.0 (stored vector as query) and is omitted. Read: hybrid beats FTS-only and vector-only on both slices; the Apple model alone is a weak retriever and FTS carries the hybrid. Agreement with Gemini's ranking is low, which says the rankings differ, not which is better; a labelled query set is the only way to settle that. Sample is small (one Beta DB). Embed p50 86 ms / p95 324 ms inside the harness on a loaded machine.

Product invariants affected

Failure-Class

Failure-Class: none

The two fix: commits repair defects introduced earlier on this same unreleased branch (per-frame telemetry, vectorless sync rows); neither is a recurring class with a merged instance.

Line-Count-Exception

Line-Count-Exception: desktop/macos/Desktop/Sources/DesktopAutomationBridge.swift | 5019 -> 5103 | reason: register local_embedding_benchmark next to local_summary_benchmark; body lives in LocalEmbeddingBenchmark.
Line-Count-Exception: desktop/macos/Desktop/Sources/Providers/ChatToolExecutor.swift | 3852 -> 3900 | reason: route search_screen_history through ScreenHistorySearchRoute and dispatch search_transcripts to ChatLocalHybridTool; new search body is not in this file.
Line-Count-Exception: desktop/macos/Desktop/Sources/Rewind/Core/MemoryStorage.swift | 1837 -> 1860 | reason: index memories into local_embeddings on insert/update; table/FTS live in LocalEmbeddingStore.
Line-Count-Exception: desktop/macos/Desktop/Sources/Rewind/Core/RewindDatabase.swift | 3630 -> 3631 | reason: foundation migration hook only; store and search live in new files.
Line-Count-Exception: backend/database/firestore_index_registry.py | 1527 -> 1542 | reason: register SCREEN_ACTIVITY_KEYWORD_RANGE_QUERY so keyword fallback is a named serving spec.
Line-Count-Exception: backend/routers/desktop_proxy.py | 1679 -> 1731 | reason: flagged embed plan gate lives beside the existing managed plan gate it extends; splitting the proxy is out of scope.

What changed

  • LocalInference/ScreenEmbeddingPolicy.swift (new) — the policy type, cached() reader, bounded route recorder.
  • LocalInference/LocalEmbeddingKillSwitches.swift, LocalEmbeddingRuntime.swift — local route defaults on for free/unknown plans and non-production; paid production stays opt-in.
  • Rewind/Services/RewindIndexer.swift, OCREmbeddingService.swift, LocalEmbeddingIndexer.swift — entitlement-gated dispatch at capture, flush, and backfill.
  • Rewind/Services/RewindScreenSearch.swift (new), Rewind/UI/RewindViewModel.swift, Providers/ChatToolExecutor.swift, LocalHybridSearch.swift — one search route for Rewind UI and chat.
  • ScreenActivitySyncService.swift — vectorless finalized rows sync on the free plan.
  • LocalInference/LocalEmbeddingBenchmark.swift — fixture=real.
  • backend/routers/desktop_proxy.py — capability-handshake embed gate (default on); tests in test_desktop_gemini_gateway.py and test_desktop_proxy.py.
  • DesktopGeminiProxyRequest (shared request builder for EmbeddingService and GeminiClient) — sends the capability header unless hard-killed.
  • Tests: ScreenEmbeddingPolicyTests, RewindScreenEmbeddingPolicyTests, RewindScreenSearchTests, ScreenActivityLosslessSyncTests, LocalEmbeddingBenchmarkTests, LocalEmbeddingFoundationTests.
  • Docs: LocalInference/ARCHITECTURE.md (plan ladder, legacy-sync dependency, real fixture rules), PRODUCT.md, changelog fragment, e2e covers:.

Verification (from desktop/macos, Xcode 26.6)

  • xcrun swift build --build-tests --package-path Desktop — passed
  • xcrun swift test --package-path Desktop --filter 'LocalEmbedding|ScreenEmbeddingPolicy|ChatLocalHybridTool|Rewind.*Search|ScreenActivityLosslessSync|RewindScreenEmbeddingPolicy' — 108 tests, 0 failures
  • Backend: pyright on routers/desktop_proxy.py 0 errors; pytest tests/unit/test_desktop_proxy.py 108 passed, test_desktop_gemini_gateway.py + gate cases 18 passed (header+basic → 402; no header+basic → allowed + legacy counter; header+paid/BYOK/probe → allowed; kill switch → allowed)
  • check-e2e-flow-coverage.py --strict — 0 uncovered; check_desktop_test_quality.py OK

Rollout

  1. Merge feat(desktop): opt-in on-device embeddings with FTS hybrid retrieval; backend keyword fallback for screen search #13456, retarget and merge this.
  2. Release the desktop build. Free clients stop calling Gemini as they upgrade; the server rejects any that still try; old builds keep Gemini until they upgrade. Watch screen_embedding_route by plan_class and desktop_embed_legacy_client draining to zero.
  3. Paid users' cross-device parity (server-side encoder) is a separate follow-on.

🤖 Generated with Claude Code

Git-on-my-level and others added 30 commits September 10, 2026 17:21
Use Firestore keyword recall after embedding/vector failure, empty or malformed
vector results, or server-owned account vector opt-out. Scan the newest 500
screens in the requested window (default seven days), require every query
term, rank by occurrence count and recency, and preserve text/evidence shape.
Read snapshots through the shared boundary; report keyword relevance and
honest empty scan counts without logging queries, OCR, or provider errors.

SCREEN_ACTIVITY_KEYWORD_FALLBACK_ENABLED defaults on.
SCREEN_ACTIVITY_VECTORS_DISABLED_UIDS accepts comma-separated UIDs or *;
an unset list preserves legacy accounts' vector eligibility.

Verification:
- scripts/backend-python-format --write backend/utils/retrieval/tools/screen_activity_tools.py backend/tests/unit/test_screen_activity_evidence.py: passed.
- BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-screen-activity-tests.txt bash backend/test.sh: 27 passed across test_screen_activity_evidence.py (14), test_screen_activity_search_utc.py (5), and test_screen_activity_tool_result_bound.py (8).
- git diff --check: passed.
All tool invocations used fake providers and Firestore. No live service was
contacted. Env/guide documentation and PR gates belong to the follow-up agent.
Define the Sendable on-device embedding service, task types, capabilities,
and readiness probe. Selection checks the kill switch, configured engine,
assets, hardware, 32-token fixture, dimension and measured two-second budget.
Failures produce no local vectors. There is no HTTP or cloud adapter in the
runtime; the default engine registry is deliberately empty.

Add env-or-UserDefaults disable/forced-engine resolution. Hash-based engines
and an injected fail-on-HTTP trap exist only in the test target.

Verification:
- xcrun swift build --build-tests --package-path desktop/macos/Desktop: passed on installed Xcode with strict-concurrency=complete and warnings-as-errors. Existing linker warnings remain.
- xcrun swift test --package-path desktop/macos/Desktop --filter 'LocalEmbeddingRuntimeTests|LocalEmbeddingFoundationTests|OCREmbeddingLosslessTests|ScreenActivityLosslessSyncTests': 22 passed, including 3 runtime tests.
- desktop/macos/scripts/swift-format-wrapper.sh format -i on changed Swift files: passed.
- python3 desktop/macos/scripts/check_desktop_test_quality.py: passed.
- python3 desktop/macos/scripts/check-sources-root-layout.py: existing failure, 94 loose Sources-root files versus baseline 77; git ls-tree at bf079e0 confirms the same 94. All new files are in feature directories.

The probe budget is an admission measurement, not preemption of an engine
that ignores cancellation. Apple asset/probe integration, docs, changelog,
e2e coverage and PR preflight remain assigned to the follow-up agent.
Add local_embeddings with source/model uniqueness, dimension/blob checks,
text hashes and timestamps. Share the existing completed five-minute app/
window winner SQL with Gemini selection. Local vectors never use the cloud
embedding column. Bind stores to the captured owner's pool, fence commits,
and reject stale screenshot text or deleted sources at commit time.

Fuse FTS5 BM25 top 50 with vDSP cosine top 50 using RRF k=60. Scan newest
local vectors first in bounded batches, at most 20,000, filtering exact model,
dimension, date and app. Return typed keyword/vector/both evidence with stable
tie ordering. A selected engine's failure stays keyword-only. Chat retains
its legacy Gemini path and threshold/output when local is disabled/unavailable.
Existing Gemini flush and cloud sync remain untouched.

Verification:
- xcrun swift build --build-tests --package-path desktop/macos/Desktop: passed.
- xcrun swift test --package-path desktop/macos/Desktop --filter 'LocalEmbeddingRuntimeTests|LocalEmbeddingFoundationTests|OCREmbeddingLosslessTests|ScreenActivityLosslessSyncTests': 22 passed (8 foundation, 3 runtime, 2 OCR, 9 sync).
- Foundation tests call production migration/storage/fusion APIs with a fixture DB, including model isolation, uniqueness, owner revocation, stale writes, completed buckets, filters, scan limits, query failure and actual ChatToolExecutor disabled-local rendering.
- desktop/macos/scripts/swift-format-wrapper.sh format -i on changed Swift files: passed.
- python3 desktop/macos/scripts/check_desktop_test_quality.py: passed.
- python3 desktop/macos/scripts/check-sources-root-layout.py: existing failure (94 vs baseline 77), unchanged from bf079e0; no new loose Sources-root files.
- git diff --check: passed.
Tests were hermetic; no app launch or production service was used. The build
still reports existing README-resource and webp deployment-floor linker warnings.

Setup used make -o setup-main -o setup-backend setup to install/verify the
worktree hook dispatchers while preserving the user-pinned base and ready venv.
No branch refresh, push, PR, or workflow changes were performed.

Follow-up ownership: NLContextualEmbedding adapter and real asset probe,
screenshot indexing integration with the selected engine, transcript-chunk
FTS/indexing, memory indexing, synthetic retrieval benchmark, changelog,
e2e covers, LocalInference/desktop docs, free-tier Gemini-flush policy,
and PR body/preflight mechanics.
Keyword fallback now formats Firestore range bounds through
normalize_screen_activity_timestamp, including the post-scan window
filter, so a document written at the window edge is found.

Failure-Class: none

Verification:
- scripts/backend-python-format --write backend/utils/retrieval/tools/screen_activity_tools.py backend/tests/unit/test_screen_activity_evidence.py: passed.
- BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-screen-activity-tests.txt bash backend/test.sh: 16 passed in test_screen_activity_evidence.py including the new window-edge case.

Co-authored-by: Cursor <[email protected]>
Read SCREEN_ACTIVITY_VECTORS_DISABLED_UIDS through the same whitespace-
tolerant CSV/flag parsing as other backend flags so empty tokens cannot
crash dispatch. This remains a temporary server-owned opt-out.

Failure-Class: none

Verification:
- scripts/backend-python-format --write backend/utils/retrieval/tools/screen_activity_tools.py backend/tests/unit/test_screen_activity_evidence.py: passed.
- BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-screen-activity-tests.txt bash backend/test.sh: 16 passed, including whitespace/star UID parsing.

Co-authored-by: Cursor <[email protected]>
…ipt/memory indexing

Apple NLContextualEmbedding is the production default behind the existing kill
switches; a failed probe stays keyword-only (never Gemini). Probe verdicts are
cached in-process. Transcript chunks and memories join hybrid search behind a
sourceKind filter so screen search stays screen-only.

Verification: xcrun swift test --package-path desktop/macos/Desktop --filter 'LocalEmbedding|AppleNLContextualEmbedding' — 20 passed (benchmark not in this commit).
Co-authored-by: Cursor <[email protected]>
In-repo synthetic fixtures only. Reports recall@10 and nDCG@10 for FTS,
vector, and hybrid. Headless via omi-ctl action local_embedding_benchmark.

Verification: xcrun swift test --package-path desktop/macos/Desktop --filter LocalEmbeddingBenchmarkTests — 1 passed; hybrid paraphrase recall@10 >= FTS-only with HashEmbeddingEngine.
Co-authored-by: Cursor <[email protected]>
…2e covers

LocalInference crossed 12 source files. Changelog fragment and
local-hybrid-search.yaml covers entries satisfy the desktop pre-push gates.

Co-authored-by: Cursor <[email protected]>
SwiftLint omi_inline_userdefaults_key and force_unwrapping rejected the new
runtime files. Typed keys keep the same UserDefaults names.

Verification: desktop/macos/scripts/swiftlint-wrapper.sh lint — 0 violations; xcrun swift test --filter 'LocalEmbeddingRuntimeTests|LocalEmbeddingFoundationTests|LocalEmbeddingBenchmarkTests|AppleNLContextualEmbedding' — 20 passed.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
Point at LocalInference/ARCHITECTURE.md for embedding kill switches and the
synthetic benchmark instead of expanding the desktop guide.

Verification: python3 .github/scripts/check_agents_md_lean.py — desktop/macos/AGENTS.md is 47000 bytes (budget 47000).
Co-authored-by: Cursor <[email protected]>
agent-doc-references resolves links from desktop/macos/AGENTS.md.

Co-authored-by: Cursor <[email protected]>
…uery spec

The bounded timestamp scan is a serving compound shape. Route it through
SCREEN_ACTIVITY_KEYWORD_RANGE_QUERY.build so firestore-query-coverage does not
treat it as new unregistered debt.

Verification: python3 backend/scripts/firestore_query_coverage.py --check-ratchet — pass; BACKEND_UNIT_TEST_FILE_LIST screen-activity + firestore contract tests — 16 + 48 passed.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
…l embeddings are opted in

Production-family defaults stay on today's Gemini path; non-production dogfoods hybrid search, matching the lossless-sync rollout shape.

Co-authored-by: Cursor <[email protected]>
…tion

Capture the owner snapshot first, then schedule NLCE indexing on a background Task so finalize/insert return without waiting on the engine.

Co-authored-by: Cursor <[email protected]>
NSLock is unavailable from async contexts under complete concurrency; park hang continuations with OSAllocatedUnfairLock instead.

Co-authored-by: Cursor <[email protected]>
Complete-concurrency tests cannot use NSLock or OSAllocatedUnfairLock here; an actor gate keeps the hang deterministic.

Co-authored-by: Cursor <[email protected]>
… tests

Xcode 16.4 rejects non-Sendable XCTestCase transfers from @mainactor async lifecycle hooks.

Co-authored-by: Cursor <[email protected]>
…ts typed as Any

The pre-push pyright gate flagged isinstance(m, dict) as unnecessary because
search_screen_activity_vectors is typed List[Dict[str, Any]]. The runtime
check is deliberate (Pinecone metadata is external input), so iterate over
cast(List[Any], ...) as the original tool did. No behaviour change.

Verification: BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-screen-suites.txt bash backend/test.sh
(evidence 16 passed, utc 8 passed, result-bound 5 passed).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ot park the indexer

Race each embed/probe engine call against Task.sleep; on timeout record engine_timeout and fail closed to keyword, never Gemini.

Co-authored-by: Cursor <[email protected]>
A HangGate resume-before-park race left work parked on LocalEmbeddingIndexer.shared and wedged later suites in the same SwiftPM batch.

Co-authored-by: Cursor <[email protected]>
…-mode test build compiles

CI's 'Test UserNotifications callback regression in release mode' step runs
swift test -c release, which compiles the whole test target. Three tests here
assign RealtimeTurnEvidenceLedger.testingAttachRealtimeUserEvidence, a seam
declared under #if DEBUG (since #13235), so the release build fails on any PR
that touches desktop tests. Main stayed green only because the step is skipped
on pushes that do not touch Desktop/Tests. Wrap the three tests in #if DEBUG to
match the seam. Tracked as #13458.

Verification: xcrun swift build --build-tests --package-path desktop/macos/Desktop
(Build complete); release-mode step run locally before push.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…oll drain

UserScrollDetectorTests.testCompletedLiveScrollAtBottomCanResumeFollowing fails
order-dependently when it shares a SwiftPM process with certain other suites
(reproduced on an unmodified origin/main desktop tree with CI's batch
worker-0-2-h1 composition). The detector queues its terminal bounds read with
DispatchQueue.main.async; the test drained with one RunLoop.main.run(mode:before:),
which returns as soon as any source fires, so a repeating .common-mode timer
left behind by an earlier suite ended the drain before the read ran. Pump the
run loop until the deadline instead, as ChatTranscriptGestureHarnessTests and
AuthRestoreWatchdogTests already do. The existing wall-clock-wait annotation is
retained; no new wait is added.

Verification: the 38-suite batch that failed on CI (exact composition) now
passes 3/3 locally (242 tests, 0 failures); suite alone and the whole file pass;
python3 desktop/macos/scripts/check_desktop_test_quality.py OK.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…vector dimension

Existing chunks no longer skip backfill: completed sessions are rewritten when
the source fingerprint changes, including an empty result. Keyword candidates
keep FTS BM25 order into fusion, write() checks the engine dimension instead of
vector.count, and hybrid search exposes a vector-only retrieval mode.

Review: 3984237061, 3984237113, 3984237136, 3984237067
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingFoundationTests/'
  →  (run with owned-suite batch after remaining commits)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
A hit the model cannot read is useless. Fetch each matched chunk (capped at
the search limit) and append a timestamp plus a 300-character content preview
before formatting the tool response.

Review: 3984237058
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'ChatLocalHybridToolTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
…e chunks

Fabricating startedAt as Date() would poison date filters. If getSession
fails, record missing_session_origin and return. Re-indexing deletes the
session's old chunks before writing, and drainForTesting cancels parked
detached work instead of only awaiting it.

Review: 3984237075, 3984237061, 3984237117
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingCapturePathTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
…ctor rank

Date-bounded fixtures now include out-of-range distractors so a missing date
filter fails the slice. Vector mode searches with retrieval=.vector instead of
post-filtering fused hits, and the unused Mode.gemini case is removed.

Review: 3984237064, 3984237067, 3984237131
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingBenchmarkTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
… seconds

Concurrent searches for the same engine now share one probe task. The probe
itself races LocalEmbeddingCallBound so a hung engine falls back to FTS-only
instead of waiting past the budget. Cancellation is stored as reason cancelled
and is not cached.

Review: 3984237072, 3984237099
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingRuntimeTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
syncServerMemories reconciled rows without indexing, so hybrid memory search
stayed FTS-only until a later backfill. Schedule scheduleMemoryIndex for each
inserted/adopted row after the write, detached and never awaited.

Review: 3984237089
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingCapturePathTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
…glish

prepareAssets now takes englishDominant and requests the multilingual model
when that is the selected engine. The system-engine test asserts permits only
when the probe succeeded (reason empty), so a first-embed timeout is not a
false failure.

Review: 3984237092, 3984237104
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'AppleNLContextualEmbeddingTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
… teardown

The previous test only checked completed==0, which also holds if scheduling is
removed, and a synchronous-await regression would hang on gate.park(). Assert
a continuation actually parked, fail if the 400ms bound expires, and cancel
detached indexer tasks in drainForTesting before the DB is torn down.

Review: 3984237111, 3984237117
Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingCapturePathTests/'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Git-on-my-level and others added 13 commits September 10, 2026 23:59
Natural-language queries failed because every token, including "when"/"was"/"I",
had to appear in the same screen record. Keep only content tokens (length > 1,
not in a small stopword list) before the all-token match.

Review: 3984237093
Verification:
  /Users/dazheng/workspace/omi/upstream-keep-clean/backend/.venv/bin/python -m pytest tests/unit/test_screen_activity_evidence.py -q
  → 17 passed in 0.30s
  scripts/backend-python-format --write on the two files
  PYRIGHT_PYTHON=... backend/scripts/typecheck.sh → 0 errors

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
…drives

local-hybrid-search now expects result.detail.kind=local_embedding_benchmark.
covers lists the sources the benchmark action actually reaches, including
ChatLocalHybridTool via the bridge, while capture-lifecycle covers the
indexer and chunker on the session-finalize path.

Review: 3984237095, 3984237097
Verification:
  python3 desktop/macos/scripts/check-e2e-flow-coverage.py --strict
  → Uncovered: 0

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Drop the internal rollout clause from the unreleased changelog fragment so the
entry states what the user gains (faster, offline, private, on-device search).

Review: 3984237120
Verification:
  python3 -c 'import json; json.load(open("desktop/macos/changelog/unreleased/2026-09-10-local-hybrid-search.json"))'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
…west bound

sessionsNeedingTranscriptChunks was limiting to the 20 newest completed
sessions and then filtering those, so older unchunked sessions were never
picked up. Restore the original unchunked-with-segments progress query (LIMIT
bound) and add a separate bounded stale-reconcile set using stored segment
count/max id so Swift re-chunk does not scan all history.

Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingFoundationTests/'
  → testUnchunkedOlderSessionIsPickedUpPastTheBound passed

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
…e task

embedTexts now drops items that already have a matching local_embeddings
textHash for the selected model, so a memory API refresh does not re-run
NLCE. syncServerMemories schedules one detached batch instead of one task per
row.

Verification:
  cd desktop/macos && xcrun swift test --package-path Desktop --filter 'LocalEmbeddingCapturePathTests/'
  → testUnchangedMemoryRefreshDoesNotReembed passed

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Resolve free and unknown plans without Gemini spend, retain active paid
capture uploads, and expose local/Gemini/FTS search intent. Free and unknown
cached plans now enable local embeddings by default; paid production bundles
remain opt-in. Explicit local opt-out stays distinct from the hard rollback.

The existing FloatingBarUsageLimiter cache persists only active paid identities;
inactive subscriptions become basic, so this policy needs no network request
or second entitlement store. Document the ladder and route telemetry envelope.
The updated paid-default test follows David's 2026-09-10 decision in #13465;
the former production default is retained specifically for paid identities.

Verification from desktop/macos:
- xcrun swift build --build-tests --package-path Desktop: passed (199.83s).
- xcrun swift test --package-path Desktop --filter 'ScreenEmbeddingPolicyTests/':
  passed, 10 tests (2 policy and 8 capture integration tests in the working tree).
- xcrun swift test --package-path Desktop --filter 'LocalEmbeddingOptInTests/':
  passed, 4 tests.
From repo root:
- desktop/macos/scripts/swift-format-wrapper.sh format -i <changed Swift files>:
  passed using pinned swift-format 602.0.0.
- python3 desktop/macos/scripts/check-main-actor-xctest-hooks.py: passed.
- python3 desktop/macos/scripts/check_desktop_test_quality.py: passed.
- python3 desktop/macos/scripts/desktop-flow-lint.py: passed, 82 flows.
- check-e2e-flow-coverage.py --strict for the new policy and changed Rewind
  services: passed, 4/4 sources covered.
- make setup -o setup-main -o setup-backend: installed/verified hooks only;
  omitted ref-refresh and backend setup to retain the prescribed stacked base.

No live app acceptance or real-engine benchmark claimed. Rewind UI search,
backend proxy gate, benchmark run, and changelog remain follow-up work.
No push, PR, main-branch operation, or Omi production API call was performed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Both Rewind capture variants share one tested post-OCR embedding boundary:
free and unknown plans never enter Gemini's queue; active paid plans retain
Gemini uploads; available local engines write the local screenshot index.
Refresh production runtime switches instead of retaining launch-time plan
state. OCR persistence and screen-activity row-sync code remain unchanged.

Gemini flush rechecks the cached entitlement immediately before each batch,
including batches queued before a downgrade. The shared backfill entrypoint
skips free/unknown plans without marking recovery complete, rechecks after
awaits, and uses the same injected batch embedder. An injected backfill sleeper
keeps tests deterministic while production retains its 200ms pacing.

Route telemetry uses recordFallback with route_event=screen_embedding_route,
plan_class, route, and route_reason. The envelope reserves event for
fallback_triggered, so a behavioral snapshot test verifies that the route
identity survives serialization. Standard reason is policy/dispatch_disabled.
No OCR/query text or unknown raw plan identity is accepted by telemetry.

Verification (all successful; cwd desktop/macos for xcrun commands):
- xcrun swift build --build-tests --package-path Desktop
  Passed, 25.47s on Apple Swift 6.3.3; package strict-concurrency settings active.
  Existing resource warnings and linker warnings (duplicate rpath, Homebrew
  libwebp deployment target) remain; Xcode 16.4 itself was not run.
- xcrun swift test --package-path Desktop --filter 'ScreenEmbeddingPolicyTests/'
  Passed, 14 tests: 3 policy/telemetry and 11 Rewind capture/backfill tests.
- xcrun swift test --package-path Desktop --filter 'RewindScreenEmbeddingPolicyTests/'
  Passed, 11 tests before the final telemetry-only correction.
- xcrun swift test --package-path Desktop --filter '(OCREmbedding.*Tests|LocalEmbedding.*Tests|RewindCaptureExclusionGenerationTests)/'
  Passed, 51 tests: local runtime/index/search, OCR timer/owner/compaction, and
  capture-exclusion regressions. Benchmark XCTest uses a stub, not Apple NLCE.
- xcrun swift test --package-path Desktop --filter 'ScreenActivityLosslessSyncTests/'
  Passed, 9 tests, including vectorless text delivery followed by embeddings.

Verification from repo root:
- desktop/macos/scripts/swift-format-wrapper.sh format -i desktop/macos/Desktop/Sources/LocalInference/ScreenEmbeddingPolicy.swift desktop/macos/Desktop/Sources/LocalInference/LocalEmbeddingKillSwitches.swift desktop/macos/Desktop/Sources/LocalInference/LocalEmbeddingRuntime.swift desktop/macos/Desktop/Sources/Rewind/Services/RewindIndexer.swift desktop/macos/Desktop/Sources/Rewind/Services/OCREmbeddingService.swift desktop/macos/Desktop/Sources/Rewind/Services/LocalEmbeddingIndexer.swift desktop/macos/Desktop/Tests/ScreenEmbeddingPolicyTests.swift desktop/macos/Desktop/Tests/RewindScreenEmbeddingPolicyTests.swift desktop/macos/Desktop/Tests/LocalEmbeddingRuntimeTests.swift
  Passed, pinned swift-format 602.0.0; final pass made no Swift changes.
- python3 desktop/macos/scripts/check_desktop_test_quality.py
  Passed; no trapping dictionaries and no increased test-quality debt.
- python3 desktop/macos/scripts/check-main-actor-xctest-hooks.py
  Passed, lifecycle hooks meet the Xcode 16.4 isolation guard.
- python3 desktop/macos/scripts/check-e2e-flow-coverage.py --strict desktop/macos/Desktop/Sources/LocalInference/ScreenEmbeddingPolicy.swift desktop/macos/Desktop/Sources/LocalInference/LocalEmbeddingKillSwitches.swift desktop/macos/Desktop/Sources/LocalInference/LocalEmbeddingRuntime.swift desktop/macos/Desktop/Sources/Rewind/Services/RewindIndexer.swift desktop/macos/Desktop/Sources/Rewind/Services/OCREmbeddingService.swift desktop/macos/Desktop/Sources/Rewind/Services/LocalEmbeddingIndexer.swift
  Passed, 6/6 changed production sources covered.
- python3 desktop/macos/scripts/desktop-flow-lint.py
  Passed, 82 flows and 209 registered actions.
- git diff --check
  Passed.

Rollout caveat found while reviewing #13465: legacy ScreenActivitySyncService
syncRowsSQL requires embedding IS NOT NULL, so vectorless free frames do not
sync on that path. Lossless sync supports them after a 15-minute grace period,
but stable defaults to legacy unless its rollout flag is enabled. Documented
this dependency; resolving it is required before rollout and intentionally not
folded into this vector-call-only foundation.

Rewind UI search routing, the real-engine benchmark, backend desktop_proxy.py
gate, and changelog fragment remain explicitly deferred to the follow-up.
No live app/UI acceptance claimed; production paths were exercised with
synthetic database rows and stub engines. No api.omi.me request, push, PR,
branch switch, rebase, stash, or workflow edit was performed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Capture still records every frame, but PostHog only gets a change of
(planClass, searchRoute, reason) plus an hourly heartbeat so a free user
does not generate thousands of remote events per day.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Stable still uses the legacy ScreenActivitySyncService path until the
lossless PostHog flag is on. When Gemini capture is off, a row is eligible
once OCR is final and its five-minute bucket has closed, so cloud chat and
phone time-window browse keep receiving screen text. Paid Gemini capture
still waits for an embedding.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Free Rewind UI search uses the same ScreenHistorySearchRoute as chat, so
it reads local vectors or FTS and never embeds the query with Gemini.
Paid hard-kill keeps the existing FTS-then-Gemini merge and ordering.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
local_embedding_benchmark now accepts fixture=real on non-production
bundles, copies the database first, and reports agreement with stored
Gemini neighbors plus held-out self-retrieval. The JSON contains counts,
metrics, engine identity, timings, and machine class only.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
DESKTOP_EMBED_PLAN_GATE_ENABLED is off so existing free clients keep
vectors until the local-embedding release ships. When on, basic-plan
embedContent and batchEmbedContents return 402 plan_gated; paid, BYOK,
and RELEASE_PROBE_UID stay allowed. Document the free-plan on-device
screen search ladder and changelog the user-visible outcome.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>

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

15 issues found across 28 files

Confidence score: 2/5

  • ScreenActivitySyncService.swift can permanently drop unfinished OCR rows when finalized and unfinished rows are interleaved, creating durable data loss; avoid advancing the shared ID cursor past ineligible rows and use durable per-row delivery state.
  • RewindScreenSearch.swift can bypass prefix/compound-word expansion on local-vector failure and can cap free/unknown-user FTS results at 50 instead of 100, causing relevant search results to disappear; preserve the declared FTS budget and expansion path across fallback routes.
  • LocalEmbeddingBenchmark.swift can report misleading metrics from mismatched retrieval corpora, or fail with inconsistent data when the live database and WAL are copied independently; constrain all modes to the same corpus and create an atomic SQLite snapshot.
  • OCREmbeddingService.swift and ScreenEmbeddingPolicy.swift can write Gemini results after entitlement changes or keep local embedding enabled after a user becomes paid, while DesktopAutomationBridge.swift also accepts misspelled fixtures as synthetic; recheck policy at resume, rebuild or update runtime state, and validate fixture values explicitly.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="desktop/macos/Desktop/Sources/DesktopAutomationBridge.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/DesktopAutomationBridge.swift:1460">
P2: When a caller misspells `fixture`, the action silently runs `runSynthetic` and reports `fixture: synthetic` instead of rejecting the request. Validate that the value is `synthetic` or `real` before selecting the benchmark.</violation>
</file>

<file name="desktop/macos/e2e/flows/local-hybrid-search.yaml">

<violation number="1" location="desktop/macos/e2e/flows/local-hybrid-search.yaml:7">
P2: This flow runs only the `local_embedding_benchmark` bridge action, which drives `LocalEmbeddingBenchmark`/`ChatLocalHybridTool` straight through `LocalHybridSearch.search` with explicit retrieval modes. It never constructs a `ScreenEmbeddingPolicy` (that type is only instantiated inside `ScreenHistorySearchRoute`, which the benchmark path never calls) and never reaches `RewindScreenSearch.search` (only invoked from `RewindViewModel`'s Rewind-UI search). Listing `ScreenEmbeddingPolicy.swift` and `RewindScreenSearch.swift` under `covers:` claims they are exercised and verified here, which is not the case; the entries only exist to satisfy the mechanical `check-e2e-flow-coverage` strict check. Keep covers entries limited to sources this flow actually drives, or extend the flow to genuinely touch the plan policy and Rewind-UI route.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/ScreenActivitySyncService.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/ScreenActivitySyncService.swift:213">
P1: When finalized and unfinished OCR rows are interleaved, the free legacy query can permanently drop the unfinished rows. Do not advance the shared ID cursor past rows that are not yet eligible; use durable per-row delivery state or advance only through a contiguous eligible prefix.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/Rewind/Services/OCREmbeddingService.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/Rewind/Services/OCREmbeddingService.swift:88">
P2: When a free user has a usable local engine, this production policy closure records backfill as FTS-only because it never supplies the runtime's local selection. Pass the actual local selection into the policy used for telemetry, or omit this cloud-service telemetry call so route metrics remain accurate.</violation>

<violation number="2" location="desktop/macos/Desktop/Sources/Rewind/Services/OCREmbeddingService.swift:317">
P2: When the cached plan changes to free while a Gemini batch is in flight, this preflight has already passed and the resumed code writes the result without rereading entitlement. Recheck `screenPolicy().shouldEmbedWithGemini` after the await and before any vector writes in both flush and backfill paths.</violation>
</file>

<file name="desktop/macos/e2e/flows/rewind.yaml">

<violation number="1" location="desktop/macos/e2e/flows/rewind.yaml:10">
P3: The new covers entry claims S3c exercises RewindScreenSearch (the free/local/FTS route), but the flow never specifies which plan S3c runs under. Step S3c's `do:` still verifies the Gemini "vector pass" ("a phrase that is semantically close but not literally present also returns frames") and its comment block still says "The semantic pass reads embedding blobs newest-first", yet the comment you added above RewindDatabase+Embeddings.swift states free/unknown plans go through RewindScreenSearch → ScreenHistorySearchRoute and never call OCREmbeddingService.searchSimilar. So as written S3c only validates one route and the coverage claim for RewindScreenSearch is not independently verifiable. Make the plan/route explicit in S3c (or split the step) so the claimed coverage is real.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/Rewind/Services/RewindScreenSearch.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/Rewind/Services/RewindScreenSearch.swift:48">
P2: When the local route handles free or unknown users, this call caps FTS-backed results at 50 instead of the declared 100-item FTS budget. Preserve the 100-item keyword result budget while keeping the local vector slice at 50, so valid matches ranked 51–100 remain visible.</violation>

<violation number="2" location="desktop/macos/Desktop/Sources/Rewind/Services/RewindScreenSearch.swift:48">
P2: When local vectors are unavailable or a local query embedding fails, this call falls back to exact-token `keywordCandidates` and bypasses Rewind’s prefix and compound-word expansion. Free users can therefore lose existing matches such as `ActivityPerformance` against `Activity Performance`; route keyword fallback through the existing FTS expansion or share that expansion logic.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/LocalInference/LocalEmbeddingBenchmark.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/LocalInference/LocalEmbeddingBenchmark.swift:226">
P2: The benchmark emits `recallAt1: 0` for metric rows where recall@1 was never measured, making the JSON report falsely look like a measured zero. Compute recall@1 for those slices or represent the metric as explicitly unavailable instead of hard-coding zero.</violation>

<violation number="2" location="desktop/macos/Desktop/Sources/LocalInference/LocalEmbeddingBenchmark.swift:354">
P2: When the Beta app writes during a real benchmark, copying the main database and WAL files independently can create a torn or unreadable SQLite snapshot, causing the benchmark to fail or report inconsistent data. Create the scratch DB with SQLite/GRDB's online backup API instead of copying the live database files individually.</violation>

<violation number="3" location="desktop/macos/Desktop/Sources/LocalInference/LocalEmbeddingBenchmark.swift:449">
P3: indexedRows is a whole-DB count for the model, so for a source DB that already contains local embeddings it includes screenshots outside the 500-row sample and rows that were not embedded this run, letting it exceed sampledRows. Scope the count to the sampled row ids to make the metric reflect rows indexed in this benchmark run.</violation>

<violation number="4" location="desktop/macos/Desktop/Sources/LocalInference/LocalEmbeddingBenchmark.swift:467">
P2: The real benchmark compares a capped Gemini corpus with unrestricted local search, so existing embeddings or FTS rows outside the sample can change the reported metrics. Restrict every retrieval mode and the indexed-row count to the sampled source IDs, or materialize the sample as the search corpus before measuring it.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/Rewind/UI/RewindViewModel.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/Rewind/UI/RewindViewModel.swift:433">
P3: The per-iteration `ownerSnapshot.isCurrent()` checks inside the merge loop were removed; the ownership check now runs once after the entire search completes. If the capture owner changes mid-search, the search keeps fetching screenshots before being discarded. The result is still dropped, so this is wasted work rather than a correctness bug, but it weakens the early-abort the previous code had.</violation>
</file>

<file name="desktop/macos/Desktop/Sources/LocalInference/ScreenEmbeddingPolicy.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/LocalInference/ScreenEmbeddingPolicy.swift:36">
P2: When a runtime is created before the subscription cache resolves, a later-paid user remains locally enabled and `ScreenEmbeddingPolicy` routes searches locally without explicit opt-in. Rebuild the runtime or carry the opt-in source so the implicit free/unknown default cannot persist into paid sessions.</violation>
</file>

<file name="desktop/macos/Desktop/Tests/LocalEmbeddingBenchmarkTests.swift">

<violation number="1" location="desktop/macos/Desktop/Tests/LocalEmbeddingBenchmarkTests.swift:100">
P3: This opt-in test is named 'Copied' but passes the live DB path directly to runReal, which creates the local_embeddings table and inserts vectors with .unrestricted authorization into the user's real DB. Mirror the bridge action: copy the DB (LocalEmbeddingBenchmark.copyDatabase) into a temp scratch dir and run the benchmark against the copy so a real user database is never mutated.</violation>
</file>

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

Re-trigger cubic

let now = Date()
let rowsPayload: ScreenActivityRowsPayload = try await dbPool.read {
[lastSyncedId, batchSize, requireEmbedding, now] db in
let dbRows = try Self.fetchLegacySyncRows(

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: When finalized and unfinished OCR rows are interleaved, the free legacy query can permanently drop the unfinished rows. Do not advance the shared ID cursor past rows that are not yet eligible; use durable per-row delivery state or advance only through a contiguous eligible prefix.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/ScreenActivitySyncService.swift, line 213:

<comment>When finalized and unfinished OCR rows are interleaved, the free legacy query can permanently drop the unfinished rows. Do not advance the shared ID cursor past rows that are not yet eligible; use durable per-row delivery state or advance only through a contiguous eligible prefix.</comment>

<file context>
@@ -206,8 +206,12 @@ actor ScreenActivitySyncService {
+      let now = Date()
+      let rowsPayload: ScreenActivityRowsPayload = try await dbPool.read {
+        [lastSyncedId, batchSize, requireEmbedding, now] db in
+        let dbRows = try Self.fetchLegacySyncRows(
+          db: db, afterId: lastSyncedId, limit: batchSize, requireEmbedding: requireEmbedding, now: now)
         let rows = dbRows.compactMap(Self.payloadRow)
</file context>

"error": "local_engine_unavailable",
]
}
let fixture = params["fixture"]?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "synthetic"

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: When a caller misspells fixture, the action silently runs runSynthetic and reports fixture: synthetic instead of rejecting the request. Validate that the value is synthetic or real before selecting the benchmark.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/DesktopAutomationBridge.swift, line 1460:

<comment>When a caller misspells `fixture`, the action silently runs `runSynthetic` and reports `fixture: synthetic` instead of rejecting the request. Validate that the value is `synthetic` or `real` before selecting the benchmark.</comment>

<file context>
@@ -1451,12 +1457,36 @@ final class DesktopAutomationActionRegistry {
           "error": "local_engine_unavailable",
         ]
       }
+      let fixture = params["fixture"]?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "synthetic"
       let report: LocalEmbeddingBenchmark.Report
       do {
</file context>
Suggested change
let fixture = params["fixture"]?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "synthetic"
let fixture = params["fixture"]?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "synthetic"
guard fixture == "synthetic" || fixture == "real" else {
throw DesktopAutomationActionError.invalidParams("fixture must be synthetic or real")
}

description: Headless synthetic local hybrid retrieval benchmark via the automation bridge. Local embeddings are on by default in non-production; free and unknown plans also default on in production; paid production bundles opt in with localEmbeddingsEnabled / OMI_LOCAL_EMBEDDINGS=1. Paid capture continues Gemini upload for phone search. Apple NLCE assets are OS-managed; a Mac without them (once opted in) must report local_engine_unavailable (FTS-only) rather than calling Gemini.
app: non-prod
covers:
- desktop/macos/Desktop/Sources/LocalInference/ScreenEmbeddingPolicy.swift

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: This flow runs only the local_embedding_benchmark bridge action, which drives LocalEmbeddingBenchmark/ChatLocalHybridTool straight through LocalHybridSearch.search with explicit retrieval modes. It never constructs a ScreenEmbeddingPolicy (that type is only instantiated inside ScreenHistorySearchRoute, which the benchmark path never calls) and never reaches RewindScreenSearch.search (only invoked from RewindViewModel's Rewind-UI search). Listing ScreenEmbeddingPolicy.swift and RewindScreenSearch.swift under covers: claims they are exercised and verified here, which is not the case; the entries only exist to satisfy the mechanical check-e2e-flow-coverage strict check. Keep covers entries limited to sources this flow actually drives, or extend the flow to genuinely touch the plan policy and Rewind-UI route.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/e2e/flows/local-hybrid-search.yaml, line 7:

<comment>This flow runs only the `local_embedding_benchmark` bridge action, which drives `LocalEmbeddingBenchmark`/`ChatLocalHybridTool` straight through `LocalHybridSearch.search` with explicit retrieval modes. It never constructs a `ScreenEmbeddingPolicy` (that type is only instantiated inside `ScreenHistorySearchRoute`, which the benchmark path never calls) and never reaches `RewindScreenSearch.search` (only invoked from `RewindViewModel`'s Rewind-UI search). Listing `ScreenEmbeddingPolicy.swift` and `RewindScreenSearch.swift` under `covers:` claims they are exercised and verified here, which is not the case; the entries only exist to satisfy the mechanical `check-e2e-flow-coverage` strict check. Keep covers entries limited to sources this flow actually drives, or extend the flow to genuinely touch the plan policy and Rewind-UI route.</comment>

<file context>
@@ -1,9 +1,10 @@
+description: Headless synthetic local hybrid retrieval benchmark via the automation bridge. Local embeddings are on by default in non-production; free and unknown plans also default on in production; paid production bundles opt in with localEmbeddingsEnabled / OMI_LOCAL_EMBEDDINGS=1. Paid capture continues Gemini upload for phone search. Apple NLCE assets are OS-managed; a Mac without them (once opted in) must report local_engine_unavailable (FTS-only) rather than calling Gemini.
 app: non-prod
 covers:
+  - desktop/macos/Desktop/Sources/LocalInference/ScreenEmbeddingPolicy.swift
   - desktop/macos/Desktop/Sources/LocalInference/LocalEmbeddingService.swift
   - desktop/macos/Desktop/Sources/LocalInference/LocalEmbeddingRuntime.swift
</file context>

await MainActor.run { ScreenActivityLosslessSyncFeature.isEnabled }
}
self.now = Date.init
self.screenPolicy = { ScreenEmbeddingPolicy.cached() }

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: When a free user has a usable local engine, this production policy closure records backfill as FTS-only because it never supplies the runtime's local selection. Pass the actual local selection into the policy used for telemetry, or omit this cloud-service telemetry call so route metrics remain accurate.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/Rewind/Services/OCREmbeddingService.swift, line 88:

<comment>When a free user has a usable local engine, this production policy closure records backfill as FTS-only because it never supplies the runtime's local selection. Pass the actual local selection into the policy used for telemetry, or omit this cloud-service telemetry call so route metrics remain accurate.</comment>

<file context>
@@ -77,10 +80,13 @@ actor OCREmbeddingService {
       await MainActor.run { ScreenActivityLosslessSyncFeature.isEnabled }
     }
     self.now = Date.init
+    self.screenPolicy = { ScreenEmbeddingPolicy.cached() }
+    self.recordRoute = { $0.recordRoute() }
   }
</file context>

do {
// Re-read after compaction awaits and before every outbound batch. A paid
// batch queued before downgrade must never spend under the new free plan.
guard screenPolicy().shouldEmbedWithGemini else {

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: When the cached plan changes to free while a Gemini batch is in flight, this preflight has already passed and the resumed code writes the result without rereading entitlement. Recheck screenPolicy().shouldEmbedWithGemini after the await and before any vector writes in both flush and backfill paths.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/Rewind/Services/OCREmbeddingService.swift, line 317:

<comment>When the cached plan changes to free while a Gemini batch is in flight, this preflight has already passed and the resumed code writes the result without rereading entitlement. Recheck `screenPolicy().shouldEmbedWithGemini` after the await and before any vector writes in both flush and backfill paths.</comment>

<file context>
@@ -298,6 +312,13 @@ actor OCREmbeddingService {
       do {
+        // Re-read after compaction awaits and before every outbound batch. A paid
+        // batch queued before downgrade must never spend under the new free plan.
+        guard screenPolicy().shouldEmbedWithGemini else {
+          pendingItems.removeAll()
+          recentHashes.removeAll()
</file context>

shouldIndexLocally = false
searchRoute = .gemini
reason = .hardKill
} else if killSwitches.isEnabled, case .engine = localRoute {

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: When a runtime is created before the subscription cache resolves, a later-paid user remains locally enabled and ScreenEmbeddingPolicy routes searches locally without explicit opt-in. Rebuild the runtime or carry the opt-in source so the implicit free/unknown default cannot persist into paid sessions.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/LocalInference/ScreenEmbeddingPolicy.swift, line 36:

<comment>When a runtime is created before the subscription cache resolves, a later-paid user remains locally enabled and `ScreenEmbeddingPolicy` routes searches locally without explicit opt-in. Rebuild the runtime or carry the opt-in source so the implicit free/unknown default cannot persist into paid sessions.</comment>

<file context>
@@ -0,0 +1,116 @@
+      shouldIndexLocally = false
+      searchRoute = .gemini
+      reason = .hardKill
+    } else if killSwitches.isEnabled, case .engine = localRoute {
+      shouldIndexLocally = true
+      searchRoute = .local
</file context>

- desktop/macos/Desktop/Sources/Rewind/Core/RewindOCRService.swift
- desktop/macos/Desktop/Sources/Rewind/UI/RewindPage.swift
- desktop/macos/Desktop/Sources/Rewind/UI/RewindViewModel.swift
- desktop/macos/Desktop/Sources/Rewind/Services/RewindScreenSearch.swift

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The new covers entry claims S3c exercises RewindScreenSearch (the free/local/FTS route), but the flow never specifies which plan S3c runs under. Step S3c's do: still verifies the Gemini "vector pass" ("a phrase that is semantically close but not literally present also returns frames") and its comment block still says "The semantic pass reads embedding blobs newest-first", yet the comment you added above RewindDatabase+Embeddings.swift states free/unknown plans go through RewindScreenSearch → ScreenHistorySearchRoute and never call OCREmbeddingService.searchSimilar. So as written S3c only validates one route and the coverage claim for RewindScreenSearch is not independently verifiable. Make the plan/route explicit in S3c (or split the step) so the claimed coverage is real.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/e2e/flows/rewind.yaml, line 10:

<comment>The new covers entry claims S3c exercises RewindScreenSearch (the free/local/FTS route), but the flow never specifies which plan S3c runs under. Step S3c's `do:` still verifies the Gemini "vector pass" ("a phrase that is semantically close but not literally present also returns frames") and its comment block still says "The semantic pass reads embedding blobs newest-first", yet the comment you added above RewindDatabase+Embeddings.swift states free/unknown plans go through RewindScreenSearch → ScreenHistorySearchRoute and never call OCREmbeddingService.searchSimilar. So as written S3c only validates one route and the coverage claim for RewindScreenSearch is not independently verifiable. Make the plan/route explicit in S3c (or split the step) so the claimed coverage is real.</comment>

<file context>
@@ -7,6 +7,7 @@ covers:
   - desktop/macos/Desktop/Sources/Rewind/Core/RewindOCRService.swift
   - desktop/macos/Desktop/Sources/Rewind/UI/RewindPage.swift
   - desktop/macos/Desktop/Sources/Rewind/UI/RewindViewModel.swift
+  - desktop/macos/Desktop/Sources/Rewind/Services/RewindScreenSearch.swift
   - desktop/macos/Desktop/Sources/Rewind/UI/RewindSearchBar.swift
   - desktop/macos/Desktop/Sources/Rewind/UI/RewindSearchLayout.swift
</file context>

db,
sql: """
SELECT COUNT(*) FROM local_embeddings
WHERE sourceKind = 'screenshot' AND modelId = ?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: indexedRows is a whole-DB count for the model, so for a source DB that already contains local embeddings it includes screenshots outside the 500-row sample and rows that were not embedded this run, letting it exceed sampledRows. Scope the count to the sampled row ids to make the metric reflect rows indexed in this benchmark run.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/LocalInference/LocalEmbeddingBenchmark.swift, line 449:

<comment>indexedRows is a whole-DB count for the model, so for a source DB that already contains local embeddings it includes screenshots outside the 500-row sample and rows that were not embedded this run, letting it exceed sampledRows. Scope the count to the sampled row ids to make the metric reflect rows indexed in this benchmark run.</comment>

<file context>
@@ -278,6 +293,231 @@ enum LocalEmbeddingBenchmark {
+        db,
+        sql: """
+          SELECT COUNT(*) FROM local_embeddings
+          WHERE sourceKind = 'screenshot' AND modelId = ?
+          """,
+        arguments: [engine.modelID]) ?? 0
</file context>

screenshots = merged
emitRewindSearchAnalytics(query: trimmedQuery, resultsCount: merged.count)
}
let merged = try await RewindScreenSearch.search(query: trimmedQuery, appFilter: selectedApp)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The per-iteration ownerSnapshot.isCurrent() checks inside the merge loop were removed; the ownership check now runs once after the entire search completes. If the capture owner changes mid-search, the search keeps fetching screenshots before being discarded. The result is still dropped, so this is wasted work rather than a correctness bug, but it weakens the early-abort the previous code had.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/Rewind/UI/RewindViewModel.swift, line 433:

<comment>The per-iteration `ownerSnapshot.isCurrent()` checks inside the merge loop were removed; the ownership check now runs once after the entire search completes. If the capture owner changes mid-search, the search keeps fetching screenshots before being discarded. The result is still dropped, so this is wasted work rather than a correctness bug, but it weakens the early-abort the previous code had.</comment>

<file context>
@@ -430,41 +430,10 @@ class RewindViewModel: ObservableObject {
-          screenshots = merged
-          emitRewindSearchAnalytics(query: trimmedQuery, resultsCount: merged.count)
-        }
+        let merged = try await RewindScreenSearch.search(query: trimmedQuery, appFilter: selectedApp)
+        guard ownerSnapshot.isCurrent(), !Task.isCancelled else { return }
+        screenshots = merged
</file context>

return XCTFail("local_engine_unavailable")
}
XCTAssertEqual(engine.engineID, AppleNLContextualEmbeddingEngine.defaultEngineID)
let pool = try DatabasePool(path: dbPath)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This opt-in test is named 'Copied' but passes the live DB path directly to runReal, which creates the local_embeddings table and inserts vectors with .unrestricted authorization into the user's real DB. Mirror the bridge action: copy the DB (LocalEmbeddingBenchmark.copyDatabase) into a temp scratch dir and run the benchmark against the copy so a real user database is never mutated.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Tests/LocalEmbeddingBenchmarkTests.swift, line 100:

<comment>This opt-in test is named 'Copied' but passes the live DB path directly to runReal, which creates the local_embeddings table and inserts vectors with .unrestricted authorization into the user's real DB. Mirror the bridge action: copy the DB (LocalEmbeddingBenchmark.copyDatabase) into a temp scratch dir and run the benchmark against the copy so a real user database is never mutated.</comment>

<file context>
@@ -44,4 +49,93 @@ final class LocalEmbeddingBenchmarkTests: XCTestCase {
+      return XCTFail("local_engine_unavailable")
+    }
+    XCTAssertEqual(engine.engineID, AppleNLContextualEmbeddingEngine.defaultEngineID)
+    let pool = try DatabasePool(path: dbPath)
+    let report = try await LocalEmbeddingBenchmark.runReal(pool: pool, runtime: runtime, engine: engine)
+    let url = URL(fileURLWithPath: output)
</file context>

Git-on-my-level and others added 2 commits September 11, 2026 02:34
…requests

EmbeddingService and GeminiClient.send share DesktopGeminiProxyRequest so a
live policy sends X-Omi-Local-Embeddings: 1 and a hard-killed client looks
like an old build. Rollout is merge then release; no backend config step.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Remove DESKTOP_EMBED_PLAN_GATE_ENABLED. Header-bearing basic-plan
embedContent/batchEmbedContents return 402 plan_gated; requests without
the header fail open and emit desktop_embed_legacy_client. The only
switch is DESKTOP_EMBED_PLAN_GATE_DISABLED.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
@Git-on-my-level
Git-on-my-level force-pushed the feat/desktop-local-embeddings-hybrid branch from 59c76ac to bfdebc6 Compare September 11, 2026 12:50
@Git-on-my-level
Git-on-my-level marked this pull request as draft September 11, 2026 16:38
@Git-on-my-level
Git-on-my-level force-pushed the feat/desktop-local-embeddings-hybrid branch from 3b56505 to 10c742e Compare September 17, 2026 11:50
@Git-on-my-level
Git-on-my-level deleted the branch feat/desktop-local-embeddings-hybrid September 21, 2026 09:53
@github-actions

Copy link
Copy Markdown
Contributor

Hey @Git-on-my-level 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

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.

1 participant