Repository navigation
Add iMessage, Telegram & WhatsApp connectors: ingest, per-person context, reply drafting & auto-reply - #8816
Archit-lal wants to merge 145 commits into
Conversation
Dedicated first-party connector (mirrors x_connector) that accepts normalized
iMessage threads from the desktop app and turns them into real Omi conversations
with per-message speaker + person attribution, reusing the normal
process_conversation pipeline (summary + memory extraction + knowledge graph).
- models/imessage.py: thread/message/settings/status DTOs
- utils/imessage_connector.py: thread->conversation mapping, handle->Person
resolution (populates the People graph), consent + per-contact opt-out,
processed-GUID dedup, background post-processing
- routers/imessage.py: /v1/imessage/{threads,connection-status,settings,disconnect}
- models/conversation_enums.py: new `imessage` ConversationSource (routes through
the segment-based memory extractor, not the text-only external_integration path)
- models/other.py: Person gains handles/source + profile fields (used in Phase 2)
- database/users.py: get_person_by_handle, get_or_create_person_by_handle,
update_person_profile
- tests: _build_conversation attribution + ingest dedup/consent
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Local read-only iMessage ingestion on the Mac, wired into the Apps page as an Imports connector (mirrors the Apple Notes local reader, not the X OAuth flow). - IMessageReaderService: GRDB read-only open of ~/Library/Messages/chat.db, incremental by ROWID, 90-day first-run backfill, ns/s date detection - AttributedBodyDecoder: typedstream body decode with message.text fast path - IMessageContactResolver: Contacts name lookup (cached, best-effort) - IMessagePermissionPolicy: Full Disk Access probe + Messages automation status - IMessageSyncCoordinator: group -> resolve names -> POST /v1/imessage/threads - IMessageModels: records + snake_case payloads (ISO8601 timestamps) - AppsPage: "iMessage" connector card + connectIMessage() action - ConnectorBrandIcon: Messages app icon; Info.plist: NSContactsUsageDescription - APIClient: imessageIngest / imessageConnectionStatus Co-Authored-By: Claude Opus 4.8 <[email protected]>
Lets Omi's agentic chat answer questions about a specific person the user talks to (directly powers the "context on every person" goal). - Conversation gains an unencrypted person_ids index, populated in process_conversation, so we can query "conversations with person X" without decrypting segments. - database/conversations.py: get_conversations_by_person_id (array_contains) - database/memories.py: get_memories_by_subject_entity - utils/retrieval/tool_services/person_service.py: assembles profile + facts + recent conversation snippets into one context block - utils/retrieval/tools/person_tools.py: get_person_context_tool, appended to the END of CORE_TOOLS (preserves the prompt-cached prefix) + display-map label - tests: context assembly, unknown-person honesty, resolver precedence Co-Authored-By: Claude Opus 4.8 <[email protected]>
utils/llm/person_profile.py::generate_person_profile builds {relationship,
profile_summary, tone_notes} for a person from their conversations + attributed
facts — tone_notes captures how the USER writes to that specific person, which
the reply drafter will use. Self-gates on staleness (7d) and minimum material;
never fabricates.
The iMessage connector's background coordinator refreshes each involved person's
profile after their conversations are stored/indexed (llm_executor, best-effort).
Tests: staleness gate, JSON extraction, stores parsed fields, skips when thin.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
POST /v1/imessage/draft-reply drafts a reply the user can send to a specific person, in the user's voice, using the per-person profile (relationship, tone) + attributed facts + the recent thread + an optional intent. Draft string only — nothing is ever sent by the backend. - utils/llm/reply_draft.py::draft_reply (offloaded via llm_executor) - models/imessage.py: draft request/response DTOs - tests: profile/thread/intent wiring, unknown-person fallback, quote stripping Co-Authored-By: Claude Opus 4.8 <[email protected]>
A "Replies" sidebar surface that lists recent iMessage threads awaiting a reply, drafts a suggested reply in the user's voice via the backend, and sends the approved text through Messages.app. Nothing is auto-sent. - IMessageReaderService.readInboxThreads: recent inbound threads (read-only, does not advance the ingest cursor); shared row->record helper - IMessageSenderService: AppleScript send targeting the exact chat GUID (main-actor; chat-id path, not flaky buddy targeting) - IMessageInboxStore + IMessageInboxPage: draft-and-approve UI (no purple) - SidebarView/DesktopHomeView: Replies nav item + routing + automation target - APIClient.imessageDraftReply; draft payloads + inbox model Co-Authored-By: Claude Opus 4.8 <[email protected]>
- testing/e2e/test_imessage_flow.py: drives the REAL FastAPI app (fake Firestore/Redis/Storage, no credentials) through the full connector flow — ingest accepts threads, contact handles populate the People graph, connection status/cursor recorded, re-send deduped, settings opt-out round-trips, disconnect clears state. Same harness CI runs. - run.sh: add com.apple.security.cs.disable-library-validation to the LOCAL-DEV entitlements fallback only, so self-signed named bundles launch (embedded Sparkle/Sentry frameworks otherwise fail hardened-runtime library validation). Production entitlements (Desktop/Omi.entitlements) are untouched. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Lets the reply drafter and per-person profile generator produce text via a local CLI (e.g. the `claude` CLI) when OMI_LOCAL_LLM_CLI is set, so the backend runs end-to-end on a machine with no OpenAI/Gemini key. Returns None when unset → falls back to the normal get_llm() path, so production behavior is unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Draft replies primarily from the user's own past messages (ground truth for their texting voice) plus recent-day life context, so drafts sound like the user and can answer factual questions. Force the local-dev CLI shim to return only the wrapped message text, stripping agent preamble. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Improve the desktop Replies inbox UI and contact resolution, enrich the reader with attachment/media handling, and remove a debug log that dumped chat metadata to the system log. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
40 issues found across 42 files
Confidence score: 2/5
- The riskiest issue is identity resolution in
backend/database/users.pyandbackend/utils/retrieval/tool_services/person_service.py: matching/merging bydisplay_name(and first-match fallback) can attach messages to the wrong person, which can produce incorrect or privacy-sensitive reply drafts if merged as-is — require stable identifiers (handle/phone/email) and deterministic disambiguation before merging. - Inbox behavior has concrete regression risk across
desktop/macos/Desktop/Sources/IMessageInboxStore.swiftanddesktop/macos/Desktop/Sources/IMessageReaderService.swift: first unread inbound messages and attachment-only latest messages can be skipped or mis-ranked, so users may miss threads or not get pre-drafts — update transition tracking for newlyawaitingReplychats and support attachment-only thread ranking before merge. - Data integrity/query correctness is still shaky in
backend/database/users.py(get_or_create_person_by_handle) andbackend/database/conversations.py: non-atomic handle updates can drop concurrent writes, and applying.limit()without ordering can return the wrong “recent” conversations — switch to atomic array updates/transactional writes and add explicitorder_bybeforelimit. - Security/production-safety concerns need a gate before merge:
backend/utils/llm/reply_draft.pycurrently allows prompt-injection of untrusted message text into sensitive context,backend/utils/llm/local_shim.pycan be enabled in production via env var, anddesktop/macos/Desktop/Sources/IMessageContactResolver.swiftbypasses the Contacts permission path by reading AddressBook DB directly — add prompt hardening and runtime environment guard, and route contact access through the proper TCC-approved framework.
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="backend/database/users.py">
<violation number="1" location="backend/database/users.py:624">
P2: The new `get_or_create_person_by_handle` in the database layer does more than persist data: it encodes contact-resolution business logic (lookup order, fallback by display name, handle merging, deterministic id seeding, and source tagging). This is the kind of orchestration that should live in a service/util layer rather than the DB layer, so persistence primitives stay focused and testable. Consider moving the resolve/merge logic into the iMessage/person service layer and keeping `get_person_by_handle`, `get_person_by_name`, and `create_person` as pure DB helpers.</violation>
</file>
<file name="desktop/macos/run.sh">
<violation number="1" location="desktop/macos/run.sh:758">
P2: The `disable-library-validation` entitlement is added whenever `USE_FALLBACK_ENTITLEMENTS` is true, which covers any named bundle, profile parse failure, or profile/identity team mismatch — not just self-signed or local-dev identities. This broadens the hardened-runtime relaxation beyond the 'self-signed builds only' intent stated in the PR description, so a dev build with a valid Apple Development certificate still strips library validation. Suggest gating the `disable-library-validation` addition to an explicit local/self-signed condition (for example, only when the identity has no team or local profile mode is enabled) instead of applying it to all fallback entitlement paths.</violation>
</file>
<file name="desktop/macos/Desktop/Sources/IMessageSenderService.swift">
<violation number="1" location="desktop/macos/Desktop/Sources/IMessageSenderService.swift:25">
P2: Synchronous AppleScript execution on the main actor can freeze the macOS UI during send. The `send` method is `@MainActor` and calls `NSAppleScript.executeAndReturnError(_:)` synchronously, so the main thread/run loop is blocked while the Apple event is delivered to Messages.app — including during first-launch TCC automation prompts or slow chat resolution. Because the call is made from `Task { await send() }` in a SwiftUI view, the entire send operation runs on the main actor. Consider making `send` async, wrapping the execution in an async boundary (e.g., `withCheckedThrowingContinuation` on `MainActor` or `Process`/`osascript` in a background task), and surfacing a sending progress indicator so the Replies inbox remains responsive.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Git-on-my-level
left a comment
There was a problem hiding this comment.
I like the overall direction and reuse of Omi Conversation/Person primitives. A few design changes I think we should make before this lands:
| _MARKER_RE = re.compile(r'<<<DRAFT>>>(.*?)<<<END>>>', re.S) | ||
|
|
||
|
|
||
| def local_cli_llm_text(prompt: str) -> str | None: |
There was a problem hiding this comment.
This local LLM wrapper looks like dev/test infrastructure rather than part of the iMessage feature. Please remove local_shim.py / OMI_LOCAL_LLM_CLI from the final PR and have the new profile/draft paths use the normal get_llm(...) path only. If a local CLI shim is useful, it should be a separate, explicit infra PR.
| guard watchTask == nil else { return } | ||
| watchTask = Task { [weak self] in | ||
| while !Task.isCancelled { | ||
| try? await Task.sleep(nanoseconds: 8_000_000_000) // 8s |
There was a problem hiding this comment.
The steady-state watcher should avoid an 8s broad reload of chat.db. Prefer an event-driven incremental sync: watch chat.db/chat.db-wal/chat.db-shm, debounce changes, then query only WHERE m.ROWID > lastSeenROWID ORDER BY m.ROWID ASC LIMIT ?, with a slower fallback timer. Keep the full readChats(days: 365, ...) path for initial load/manual refresh rather than the normal polling loop.
| opted_out = set(settings.opted_out_handles) | ||
|
|
||
| doc = await run_blocking(db_executor, _get_doc, uid) | ||
| processed_guids = set(doc.get('processed_guids') or []) |
There was a problem hiding this comment.
A bounded processed_guids array in the integration doc is too fragile for ingestion idempotency: cursor resets, reinstall/multi-Mac use, or concurrent ingests can replay messages once they fall out of the 5k window. Please move this to a durable server-side ledger, e.g. users/{uid}/integrations/imessage/processed_messages/{hash(chat_guid + message_guid)}, and transactionally create/claim each message key before ingesting it. The desktop row cursor should be an optimization, not the correctness mechanism.
| handle_to_person[h] = person['id'] | ||
| people_ids.add(person['id']) | ||
|
|
||
| create = _build_conversation(thread, new_messages, handle_to_person, req.language) |
There was a problem hiding this comment.
This makes each sync batch eligible to become its own Omi conversation. With frequent sync, one real iMessage thread can turn into many tiny conversations, which will hurt summaries, memories, retrieval, and person profiles. Please add a deterministic conversation-windowing strategy (for example chat_guid + day, or chat_guid + inactivity window) rather than treating one poll batch as one conversation.
| """ | ||
| user_ref = db.collection('users').document(uid) | ||
| conversations_ref = user_ref.collection(conversations_collection) | ||
| conversations_ref = conversations_ref.where(filter=FieldFilter('person_ids', 'array_contains', person_id)).limit( |
There was a problem hiding this comment.
This query limits before sorting in Python, so Firestore is not guaranteed to return the most recent conversations involving this person. Since this feeds profile generation/reply context, please either add an indexed order_by(created_at desc) query (with the needed composite index) or maintain a per-person conversation index that can reliably return recent items.
Addresses PR review findings on per-person context retrieval: - get_conversations_by_person_id: order_by(created_at desc) + discarded==False server-side instead of limiting before an unordered sample and sorting in Python (which also crashed on legacy non-datetime created_at). Adds the required conversations composite index (person_ids array-contains + discarded + created_at desc). - Conversation: derive the unencrypted person_ids index from segments via a model_validator, and refresh it in update_conversation_segments so person reassignments stay queryable. - get_memories_by_subject_entity: filter active facts before slicing to limit, so it never returns fewer active facts than requested. - get_or_create_person_by_handle: atomic ArrayUnion handle merge (no lost handles under concurrent ingests); update_person_profile guards missing docs. - person_service: wrap untrusted facts/conversation snippets in delimiters with a boundary notice (prompt-injection), skip malformed conversations instead of aborting, and only emit the conversations header when a snippet survives. - person_tools: log exception type/uid only (no PII in logs). Co-Authored-By: Claude Opus 4.8 <[email protected]>
- Remove utils/llm/local_shim.py and OMI_LOCAL_LLM_CLI; reply_draft and
person_profile now use the standard get_llm('memories').invoke path only
(per maintainer request — a dev CLI shim belongs in a separate infra PR).
- reply_draft/person_profile: wrap untrusted conversation text, facts, and
user-style samples in XML delimiters with a boundary notice so injected
instructions in inbound messages can't exfiltrate private context.
- person_profile: validate LLM JSON output — only persist non-empty string
fields (no None overwrite, no .strip() crash on non-strings); gate profile
generation on rendered transcript/facts text, not raw counts.
- reply_draft: defensively order the thread by timestamp when present; add an
optional timestamp field to IMessageDraftMessage so ordering is deterministic.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
- Promote message GUIDs into processed_guids only after their conversation's post-processing succeeds, so a failed conversation stays retryable on the next sync instead of being silently dropped forever. - Preserve processed_guids insertion order for the cap trim (newest survive), using a set only for O(1) dedup membership. Co-Authored-By: Claude Opus 4.8 <[email protected]>
- IMessageInboxStore: baseline latest message id for all chats so a thread's first inbound message triggers a pre-draft; stop the watcher loop when the store deallocs (deinit cancel + guard self); surface revoked Full Disk Access in poll(). - IMessageReaderService: keep attachment-only messages in the inbox (select cache_has_attachments, add hasAttachment, show a placeholder preview); select distinct recent chats then fetch per-chat context so one noisy thread can't starve the inbox. - IMessageContactResolver: shared phone normalization that preserves full digits (only strips a leading US 1), applied consistently in resolve + loadDatabase. - IMessageInboxPage: don't surface task cancellation as a draft error; render image + caption together; load/cache attachment images off the render path. - IMessagePermissionPolicy: treat a missing chat.db as accessible, not an FDA denial. - DesktopHomeView: add .replies to the visible-pages whitelist so it isn't redirected away for tiers 1-5. - AppsPage: accumulate iMessage source count so status shows a cumulative total. - IMessageModels/SyncCoordinator: type-safe Date timestamps with a shared ISO8601 encoder; send draft-thread timestamps for deterministic ordering. - run.sh: don't mask a failed local-dev entitlement Set with || true. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Per maintainer + bot P1 review: display names are not unique, so using them to merge/resolve people conflates distinct contacts (cross-contact context/reply leak). - get_or_create_person_by_handle: drop the display_name merge fallback; rely on handle identity only (id is handle-seeded so ingests still converge). Name is still stored on create, never used to merge. - users: add get_people_by_name (returns ALL matches, no limit(1)). - resolve_person: on >1 name match return an AmbiguousPerson sentinel instead of guessing; get_person_context / draft_reply surface a disambiguation ask. id and handle resolution stay unambiguous. - tests updated for the new resolution path + ambiguity coverage. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Per maintainer review:
- New database/imessage.py: durable per-message processed ledger at
users/{uid}/integrations/imessage/processed_messages/{hash(chat_guid:msg_guid)}.
claim_message uses Firestore create() as an atomic compare-and-set — closes the
concurrent-ingest race and replaces the fragile bounded processed_guids array
(still read for back-compat, no longer written). Messages are claimed only
after their conversation processes successfully, so failures stay retryable.
- Connector: group new messages by (chat_guid, calendar day) into a conversation
with a deterministic id (document_id_from_seed) so the same chat+day converges
into ONE conversation across syncs instead of one-per-poll-batch. First sync
creates + fully post-processes; later same-day syncs append segments + extend
finished_at (conservative: no re-summarization, to avoid duplicate memories/
action-items/external-task pushes — documented for a future window-close pass).
- tests rewritten for the new segment builder, deterministic id, and ledger dedup.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Per maintainer + bot P1 review: - IMessageInboxStore: replace the 8s full chat.db reload with an event-driven watcher (DispatchSource on chat.db/-wal/-shm, 1.2s debounce), an incremental ROWID gate (new IMessageReaderService.newMessages), and a 45s fallback timer. Full readChats stays for initial load / manual refresh. Preserves the pre-draft baseline, deinit teardown, and revoked-FDA handling. - IMessageContactResolver: resolve names/photos via CNContactStore (Contacts framework) instead of reading the AddressBook SQLite DB directly under Full Disk Access — closes the cross-feature consent gap. Adds NSContactsUsageDescription; degrades gracefully (falls back to prettyHandle) when access isn't granted. Public API unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pushed changes addressing this review (all 40 Backend — correctness & safety
Backend — ingest redesign (maintainer asks)
Desktop
Verification: backend compiles + async-blocker scan clean, affected unit tests pass, clean Deliberately left for discussion / not auto-applied:
Still to do before merge: deploy the new Firestore composite index before/with the backend, and a local run-through of the desktop watcher + Contacts prompt. |
…ge-replies # Conflicts: # firestore.indexes.json
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ebc3d2a359
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } | ||
|
|
||
| let response = try await APIClient.shared.imessageIngest(threads: threads, lastRowID: maxROWID) | ||
| await IMessageReaderService.shared.setLastProcessedROWID(maxROWID) |
There was a problem hiding this comment.
Don't advance the cursor before durable ingest
Because /v1/imessage/threads only queues _process_windows in the background and returns before the ledger claims messages, this advances the local ROWID even when a later LLM/Firestore error or worker restart prevents the conversation from being written. On the next sync readNewMessages starts after maxROWID, so those unclaimed messages are never resent and the intended retry-on-failure path is bypassed. Advance the cursor only after a durable server-side ack, or persist/claim the raw messages before returning 200.
Useful? React with 👍 / 👎.
| # Claim on success. AlreadyExists just means a concurrent ingest won | ||
| # the race for this message — safe to skip. | ||
| for m in usable: | ||
| key = processed_message_key(chat_guid, m.guid) | ||
| await run_blocking(db_executor, imessage_db.claim_message, uid, key, chat_guid, m.guid) |
There was a problem hiding this comment.
Claim messages before running side effects
Under two overlapping syncs for the same new iMessage batch, both requests can pass filter_claimed_keys before either reaches this post-processing, so both can run process_conversation and its webhooks/app integrations/action-item syncs before claim_message races one out. The post-success ledger create prevents future retries, but it does not serialize in-flight work; claim or lease the message/window before invoking the pipeline, or make those side effects idempotent.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
1 issue found across 26 files (changes from recent commits).
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="backend/database/conversations.py">
<violation number="1" location="backend/database/conversations.py:210">
P2: The server-side `discarded == False` filter in `get_conversations_by_person_id` now excludes legacy conversations that lack the `discarded` field, whereas the previous Python-side filter included them. Because the docstring explicitly mentions legacy documents, this change can silently drop valid per-person context and reduce recall in the new iMessage flows. Consider either backfilling `discarded: False` on legacy documents that are missing the field, or keeping a Python-side fallback that re-includes documents without `discarded` after the server-side query.</violation>
</file>
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
Adds an opt-in 'Auto-reply' switch in each chat's detail header. When on, a new inbound message in that chat triggers Omi to draft a reply and send it immediately via the existing sender (no review) — off by default, persisted per chat_guid in UserDefaults. Chats without the toggle keep the current draft-and-review behavior. - IMessageInboxStore: autoReplyChats set (UserDefaults-backed) with enable/disable helpers; refresh() routes new inbound messages in opted-in chats to autoReply() (draft -> IMessageSenderService.send -> optimistic append) instead of pre-draft. Reuses lastLatestMessageID gating so a message is never auto-sent twice, and the outbound reply clears awaitingReply so there is no reply loop. - IMessageInboxPage: mini switch in the chat detail header (accent-tinted, never purple), bound to the store per chat. - Tests: cover enable/disable and cross-session persistence. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Previously auto-reply only fired on a newly-arriving message, so flipping the toggle on for a chat whose message was already waiting did nothing until the contact sent again. setAutoReply now immediately drafts+sends to the current unanswered inbound message when enabled. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
# Conflicts: # backend/utils/llm/reply_draft.py
The grounding rewrite replaced the old durable/AI-profile fallback chain (MemoryService.read + users_db.get_ai_user_profile, capped by PROFILE_TEXT_CHAR_CAP / DURABLE_FACTS_CAP) with query-scoped ranking: ranked memory facts + reranked related conversations + verbatim chunks, and returns '' when there is no inbound query or nothing topic-relevant. - Replace the 6 stale _relevant_context tests (and the _FakeMemoryService / AI-profile helpers) with 4 that exercise the new behavior: empty on no inbound query, facts-led block, related-conversations block, empty when nothing relevant. - Fix test_build_reply_prompt_has_no_hardcoded_example_slang: the 'ngl' check was a substring match that false-positived on the word 'single' in the rewritten prompt; use a word-boundary regex. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…on facts + anti-fabrication)
Merges feat/people-intelligence into worktree-omi-imessage-replies so the PR
carries the full people-intelligence work alongside the connectors, reply
drafting, auto-reply, calendar/notify, and grounding rewrite.
Adds (auto-merged, additive): per-person messaging facts + enrichment,
first-sync roster backfill, live-conversation person updates, subject-memory
writer with strict same-subject isolation, structured person profiles, and
their unit tests (person_service/backfill/messaging/subject_memory_writer/kg).
Two hand-resolved conflicts in reply_draft.py — both branches rewrote the same
regions:
- Prompt grounding rule: take people-intelligence's simplified "THE ONE RULE —
only say what you actually know" (the "be simple with your logic" iteration)
over the older stacked GROUNDING/ASSUMED-FACTS block, and keep the PR
branch's "COVER WHAT YOU DID" recount nudge (pairs with recount distillation).
- omi_context assembly: hybrid. Default to person-only grounding for a known
1:1 (people-intelligence's fix for the self/other leak — "Brooklyn Bridge" as
an answer to "how's your girl?"), but for an open recount question
("what did you do this weekend?") fall back to general grounding + recount
distillation, since that case is genuinely about the user's own activities.
Unknown contacts and group threads keep general grounding.
test_reply_draft.py conflict: dropped the stale profile-cap test (the merged
_relevant_context has no PROFILE_TEXT_CHAR_CAP/AI-profile fallback), kept the
Phase-4 person tests, and captured the drafting prompt (not the later
escalation-classifier call) in their fake_invoke.
Verified: all 9 affected unit files pass individually (CI-style), async-blocker
scan reports 0 blocking findings, new test files are auto-discovered by
scripts/select_backend_unit_tests.py.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for the continued iteration. I re-reviewed the new head (1f63046712457afa10d9513586fcb830a878738f). The new people-context/anti-fabrication work is directionally useful and the changed Python entry points I extracted from the PR head still compile with py_compile, but I’m still requesting changes because several safety/correctness blockers remain in the private-message ingest and auto-reply paths.
Main blockers I’d want fixed before this can be merge-ready:
-
WhatsApp auto-reply can still burst-send stale conversations on launch.
WhatsAppInboxStore.bootstrap()schedules every opted-in chat whose latest message is inbound, with no recency/session/rate guard. If Omi was closed for a while or a send previously failed, relaunching can generate and send replies to old conversations. For an irreversible auto-send feature, please gate startup catch-up by freshness/last-session state and add explicit retry/rate bounds. -
The ingest durability signal is still fail-open. The backend
all_persistedresponse fields for iMessage/Telegram/WhatsApp still default toTrue, and the desktop decoders still treat absent or malformed values as safe. This is the cursor-advance signal; retrying a successful batch is safe because the ledger dedups, but advancing after partial/malformed durability data can skip messages permanently. Please make the new response paths conservative and distinguish older-backend absence from a present-but-invalid value. -
WhatsApp
@lididentity continuity can still split person context. The reader now prefers a resolved dialable phone when available, but before that resolution exists the same chat can be keyed by the opaque handle. That can create two backend Person identities for one contact and fragment per-person facts/context/auto-reply behavior. Please use a stable canonical identity or explicitly migrate/normalize the@lid-> phone transition. -
The local reply-draft retrieval fallback can still build an unbounded embedding batch.
_retrieve_chunks()windows up to 40 conversations and sends all windows to_embed_rank()in one batch when vector chunk search is unavailable. Long transcripts can turn this into hundreds/thousands of embedding inputs on the reply path. Please cap candidate windows before embedding. -
The new per-person context/MCP exposure needs maintainer security/product review. Exposing a
people/contextMCP route and adding subject-keyed memories are high-sensitivity data-surfacing changes. I did not find an obvious malicious attempt, and the route does go through the memory-read authorization path, but this still changes how external/agent tools can retrieve private person context and should be reviewed deliberately by a maintainer before merge.
I did not find changed agent-instruction documentation in this head. Given the scope (private messaging databases, contacts, Telegram session handling, per-person memory, MCP context exposure, reply drafting, and opt-in auto-send), I’d keep needs-maintainer-review, feature-fit-review, security-review, dependency-review, and needs-tests in place. Formal approval remains disallowed for this PR; this needs the remaining safety fixes plus human product/security review before merge.
|
@Archit-lal I'm gonna convert this to draft for now until it's ready since it's a big feature |
Two reply-draft bugs surfaced on real chats:
RC1 — "not specific/detailed": a known 1:1 draft was blanking omi_context,
so questions about the user ("what are you working on", "what's new",
"how's the startup going", "where do you live now") drafted generically
instead of using what Omi knows. Per the user's call — be specific and true
when asked, the self-"leak" is acceptable — always ground the draft on the
user's relevant memories/conversations/chunks (known 1:1, unknown, and group
alike). The prompt still only uses a specific to answer something actually
asked, and the anti-fabrication rule keeps it true. `_is_about_user` now only
gates the concrete-recap distillation (so life/work/status questions share
the real specifics). Also merge (was XOR) the per-person semantic +
subject-keyed facts so one weak semantic hit can't shadow the fact list.
RC2 — invite auto-commit: the escalation classifier under-escalated an
invite when the winning best-of-5 candidate happened to commit ("yeah I'm
down, see you at 8"), making escalation non-deterministic. Harden the
`decision` category so invites/plans/commitments escalate regardless of the
draft's tone (a committing draft is the most dangerous case), while the
precision test keeps casual questions from over-escalating. Also stop
creating a calendar hold for a needs_input (unsent) reply.
Verified: 70 backend unit tests; real-model batteries (escalation 16/16,
about-user distillation trigger 21/21 with 0 leak false-positives); live on
the product endpoint (specific grounded replies; committing invite still
escalates).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…nvented vibe
Follow-up to the grounding work: the "be detailed" push over-corrected into
off-voice drafts — verbose fact-stuffed paragraphs and invented jokes/sentiment
("hahah playing the grammar cop", "missed your texts") a terse texter would
never send, plus a fact-dump injected even into greetings.
- Ground ONLY when the latest inbound actually asks/requests something
(`_asks_something`) — greetings/reactions/statements reply in plain voice
with no injected facts, killing the embellishment trigger.
- Voice + length are the hard constraint, in BOTH directions: match the user's
measured length (terse stays terse even when answering; a fuller writer stays
fuller) — a reply longer/smoother/more elaborate than their own messages is
wrong even if true.
- Forbid invented personality: no manufactured feeling, reaction, joke, cutesy
label, or relationship sentiment — an invented vibe is as wrong as an invented
fact (prompt + selection reject it).
- But stay SPECIFIC + TIMED when asked: name the real projects/events/people
and WHEN they happened; reject vague filler ("work stuff mostly", "the
usual") when the context has real specifics. Distillation now preserves
timing.
Verified: 71 unit tests; instrumented product-path repro across terse and
verbose voices (terse -> "won a hackathon w maher, building ai for omi, india
trip"; verbose -> fuller sentence; greeting -> no invented sentiment); live on
the product endpoint (specific, timed answers; invite still escalates).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…d phrases
Per user steer ("nothing hardcoded — every user and the people they talk to
differ"; "don't give it pre-written options, let it think, teach how to
think"):
- Removed user-specific names that had leaked into prompt examples (a real
friend's name, the user's company/plans) — they would bias every user's
drafts toward one person's life.
- Removed canned reply-phrase examples from the drafting-quality prompts
(COVER, DON'T-INVENT, THE-ONE-RULE, distillation, selection, escalation) and
replaced them with the underlying principle to reason from. Pre-written reply
phrases invite parroting and sameness; principles let the model produce the
user's own words, learned from their real per-person message history (the
thread) and the retrieved context.
No logic change. Verified on the product path (real data): drafts stay
specific + timed + in the user's terse voice, with no invented jokes/sentiment
and no example-phrase parroting; invites/money still escalate. 71 unit tests
pass.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…t voice When a user's messages sync (iMessage/Telegram/WhatsApp), synthesize a prose "Tone & Style" guide from their own outgoing texts — a Voice section (openers, closers, capitalization, punctuation, emoji, slang, cadence, hedging, ...) plus a By-recipient section — grounded only in real messages, with a measured-fingerprint stat block so it never contradicts the objective data. - New utils/llm/user_tone_guide.py: generate_user_tone_guide(uid, force) mirrors person_profile; self-gates on weekly staleness; skips when too few samples. - Storage: messaging_tone_guide on the user doc via cached get/update helpers in database/users.py (mirrors the ai_user_profile pattern). - Trigger: regenerated after each connector sync (end of _enrich_conversations, so the By-recipient section sees fresh person tone_notes). - Drafting: reply_draft injects the guide's Voice section into build_reply_prompt alongside the (hard-constraint) fingerprint; absent on cold start. - Endpoints: GET /v1/users/tone-guide and POST /v1/users/tone-guide/regenerate. - Tests: gating/collection/generation (test_user_tone_guide.py) + prompt-injection and end-to-end draft_reply wiring (test_reply_draft.py). 45 reply tests pass; async + import-side-effect scans clean. Verified generation quality on real sent-message data via the reply-draft harness: produces a Voice + By-recipient guide matching the reference format. Co-Authored-By: Claude Opus 4.8 <[email protected]>
A "Writing Voice" panel next to AI User Profile renders the learned Tone & Style guide (scrollable, selectable), shows when it was last updated and how many messages it drew from, and offers Regenerate. Empty state prompts the user to sync messages. - APIClient: getToneGuide() / regenerateToneGuide() + ToneGuideResponse. - SettingsPage: writingVoice AdvancedSubsection + state. - SettingsContentView+Advanced: writingVoiceSubsection + load/regenerate. - Uses neutral/white accent (no purple, per brand). Swift package builds clean. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The tone-guide generator now also produces a card-friendly persona_summary alongside the full prose guide, so the redesign "Persona — How I sound as you" card is a thin renderer over the same learned voice: - sounds_like: an example line generated in the user's real voice - not_like: a stiff/formal contrast line they'd never send - traits: the four "Your defaults" toggles (short_and_direct, warm_not_formal, emoji, match_each_person) computed DETERMINISTICALLY from the measured fingerprint (read-only reflections, never an LLM guess) Stored under messaging_tone_guide.persona_summary and returned by the existing GET /v1/users/tone-guide (no new endpoint). Desktop ToneGuideResponse gains optional PersonaSummary/PersonaTrait decoding. Traits are pure fingerprint math (unit-tested); examples are best-effort (guide still stores if that call fails). Verified on real sent-message data via the harness: sounds_like/not_like read true to voice and the toggles match the fingerprint. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for the continued work here. I re-reviewed the current head (e96ad044669b3d332605cb7ac51f4cb3c6094e96). A number of earlier issues are improved — notably the durable per-message ledger shape in backend/utils/imessage_connector.py, the fail-closed Telegram credential gate in desktop/macos/Desktop/Sources/TelegramClientService.swift, prompt-injection separation in backend/utils/llm/reply_draft.py, bounded draft image payloads in backend/models/draft_common.py, and the WhatsApp recipient guard in desktop/macos/Desktop/Sources/WhatsAppSenderService.swift.
I’m still requesting changes because there are safety/correctness blockers on the private-message ingest and auto-send surfaces:
-
The durability signal still fails open. The backend response models in
backend/models/imessage.py,backend/models/telegram.py, andbackend/models/whatsapp.pystill defaultall_persistedtoTrue. That field controls whether clients advance/retry after partial persistence; defaulting to success is the unsafe direction for a cursor/at-least-once signal.backend/utils/imessage_connector.py,backend/utils/telegram_connector.py, andbackend/utils/whatsapp_connector.pynow computefailed_windows == 0, which is good, but the schema should be conservative if a path omits/mis-serializes the field. -
WhatsApp auto-reply can still send stale conversations on launch.
desktop/macos/Desktop/Sources/WhatsAppInboxStore.swiftbootstrap()schedules auto-reply for every persisted opted-in chat whose latest bubble is inbound. That makes relaunch/offline catch-up an irreversible auto-send path for old threads or previously failed sends, with no freshness/session/rate guard. Please gate startup catch-up much more tightly, or keep those as drafts requiring review. -
Telegram auto-send is acknowledged before Telegram confirms the send.
desktop/macos/Desktop/Sources/TelegramClientService.swiftsendConfirmed()returns true once the JSON command is written to helper stdin;TelegramInboxStore.swiftthen callsappendSent(...). But the helper only emitssentafterawait self.client.send_message(...)indesktop/macos/telegram-helper/omi_telegram_helper.py, and the Swift store currently ignores that event. For an auto-reply feature, a successful stdin write is not a delivery/send confirmation; please wait for the matchingsentevent (or otherwise surface/retain the draft on helper-side failure) before showing/suppressing the reply as sent. -
WhatsApp
@lididentity continuity can still split per-person context.desktop/macos/Desktop/Sources/WhatsAppReaderService.swiftprefersphoneByChat[chatID]when available, but otherwise falls back tolatest.handle/ opaque@lididentity forpersonRef. That can create a Person and memories under an opaque handle, then later create/use a separate phone-keyed Person onceZCONTACTIDENTIFIERis available. Please normalize or migrate the transition so one contact has one stable backend identity. -
The new MCP/person-context surface still needs a maintainer security/product pass.
backend/routers/mcp.pyexposes/v1/mcp/people/contextvia the memory-read auth path, andbackend/utils/retrieval/tool_services/person_service.pyassembles per-person profile fields, facts, and recent conversation snippets. I like the explicit untrusted-data markers there, but this materially expands how external tools/agents can retrieve private person context; it should be deliberately signed off before merge.
Validation I could run here: Python syntax compilation passed for the changed backend connector/drafter/person-service routers and the Telegram helper. I could not run the macOS Swift app/build in this Linux review environment, and GitHub has no passing check summary on this draft PR.
Given the scope — private local message databases, contacts, Telegram session handling, per-person memory/context, MCP exposure, reply drafting, and opt-in auto-send — this should keep human maintainer/product/security review before merge. No obvious malicious or supply-chain attempt found, and I did not find agent-instruction documentation changes.
Reviewed by gpt-5.5 for the Omi maintainer automation. Human maintainer sign-off is needed specifically for the private messaging auto-send, identity, and MCP person-context surfaces.
Focused backend tests pass for sync speaker assignment and group draft validation. Failure-Class: none
|
Closing as uncomposable, not as stale. This draft is still +19990 / 134 files across iMessage, Telegram, and WhatsApp ingest, person context, reply drafting, and auto-send. It is CONFLICTING and not rebaseable onto current origin/main (1ef3b91). The connectors are still absent on main, so the product gap is real — but this branch cannot be reviewed or landed as one change. Existing review already blocked merge on fail-open durability ( If this work continues, it needs split PRs (read-only ingest per connector, then draft-only, then any auto-send behind explicit guards) against a fresh main. |
|
Hey @Archit-lal 👋 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:
Before your next PR, please skim:
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! |
Summary
Adds an iMessage feature to Omi: ingest the user's iMessage history, build per-person context/profiles from it, and draft replies in the user's own voice — surfaced through a new Replies inbox in the desktop app.
What's included
Backend
utils/imessage_connector.py,routers/imessage.py,models/imessage.py)utils/llm/person_profile.py,utils/retrieval/tool_services/person_service.py,utils/retrieval/tools/person_tools.py)utils/llm/reply_draft.py)OMI_LOCAL_LLM_CLI) — off by default; production falls back toget_llm('memories')Desktop (macOS)
run.sh(disables library validation for self-signed builds only; production entitlements untouched)Notes
Testing
🤖 Generated with Claude Code
Update — expanded to also add Telegram + WhatsApp connectors
On top of iMessage, this PR now adds the Telegram and WhatsApp connectors (both mirror the iMessage architecture: ingest → conversations with speaker attribution, durable ledger, per-person context, and voice-matched reply drafting), plus shared inbox polish and correctness fixes.
Backend: Telegram + WhatsApp connector routers/ingest/ledger/draft; reply-draft texting-voice sources now include telegram + whatsapp.
Desktop (macOS):
@lidviaZCONTACTIDENTIFIER); default person-silhouette avatar; real sender names via push-name/phone fallback; compact compose bar + row dividers.@lid(privacy) 1:1 sessions so new-contact chats appear + auto-reply; resolve dialable phone for@lidsends; WhatsApp store is a singleton so the watcher/auto-reply run app-wide even off-tab; send via System Events keystroke (CGEvent is ignored by WhatsApp's Catalyst app).Known pre-prod follow-ups: Telegram helper uses the public
2040api_id (flagged in code) — needs Omi's own; the frozen Telegram helper binary is bundled by Codemagic, not in this diff.Tests: backend connector unit tests (telegram/whatsapp/canonical-handle) passing; clean
swift build -c releasepassing.