Repository navigation
feat(people): make speaker labels teach, persist and show how they were made - #20190
Conversation
Unblock client integration with additive label provenance, voice-learning state, and typed rejection and earlier-match boundaries. Keep these boundaries inert until durable behavior is implemented; rejection must not falsely acknowledge a saved decision. Generated with [Devin](https://devin.ai) Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
A transcript label looked the same whether the user made it or Omi guessed it, tagging gave no feedback on whether the voice was learned, and there was no way to say a label is wrong without naming who it is. - Transcript: a check beside a label the user decided, "Likely" beside one Omi matched by voice, with a one-time "Sounds like <name>" Yes / Not <name> under the first line of that voice (speaker_label_source). - Tag sheet: "Not Me", "Not <name>" and "Not a Person" send a rejection instead of leaving the wrong label or forcing a guess. - After tagging a person: a card says how many lines got the name, follows the server's voice_learning_state to "Voice learned" or "not learned yet" with the reason, and offers the same voice in earlier conversations for review with a playable clip. - Live: a banner when a label was carried over from the previous conversation of the same recording, with Change; "Someone Else…" on a suggestion now sends the rejection it implies. New strings are added for every locale through scripts/l10n.py. Visual audit scenarios cover the four surfaces. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The seven-day baseline stored 97 person voiceprints against 734 whole-voice and up to 2843 selected tags; live requests stored 0 of 227. Cross-scope transcript duplicates silently rejected clean audio, while 5888 attempts failed the single-long-segment gate. Pool clean turns instead, compare purity within their capture scope, and resolve delayed jobs from receipts. Require 10 seconds of distinct clean speech in bounded windows; preserve 0.9 text containment and 0.7 dominant-speaker gates. This changes evidence selection, not acceptance thresholds. Record outcomes and learning state, fence corrections and consent changes, and retry missing voiceprints after finalization without delaying or failing conversation processing. Generated with [Devin](https://devin.ai) Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
734 person tags attempted learning while 7243 whole-speaker owner tags never touched the owner voiceprint in the seven-day baseline. Route all three manual owner assignment forms through the existing verified confirmation pool, keeping owner checks free and the five-confirmation cap unchanged. Select scope-aware clean owner runs without counting gaps as speech, and require five seconds in both the cropped window and decoded audio before verification. Keep the conversation router within its line budget. Generated with [Devin](https://devin.ai) Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Windows sent null for the owner label, which the backend interprets as false. Send true explicitly. On macOS, live naming changed only a map cleared at finalization despite promising to save the decision. Persist cloud labels through REST before waking the live socket, or require a successful SQLite write for unsynced recordings. Fence stale completions, use the structured speaker id, preserve manual-only local authority, and keep the sheet open when nothing durable holds the assignment. Generated with [Devin](https://devin.ai) Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Clearing a label is not durable evidence that a voice is not the owner or a named person. Persist explicit rejections in the same encrypted manual receipt as positive labels, and honor them before live matching, speaker resolution, prompts, and subsequent transcript writes. Count person corrections transactionally, invalidate contradicted teaching, validate redirect selections without partial edits, and keep owner checks free while enforcing named-speaker entitlements. Derive one additive provenance projection from receipts and match evidence without a backfill. Generated with [Devin](https://devin.ai) Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Conversation rotation cleared live maps and stranded manual receipts even when the same provider voice continued seconds later. Seed the fresh row from explicit decisions on the still-active stream and project carried provenance without counting another human confirmation. Mint separate speaker scopes for provider restarts, including same-provider managed reconnects; bind late callbacks to their original stream. Reserve receipt ids on reconnect, never carry automatic matches, suppress automatic alternatives to manual authority, and fail open when carry lookup fails. Generated with [Devin](https://devin.ai) Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Import the existing chunk-span helper through audio_timeline's public re-export so the async blocker gate recognizes this pure calculation instead of misclassifying a database-namespaced call as blocking IO. Runtime behavior and the helper itself are unchanged. Generated with [Devin](https://devin.ai) Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
A tag-prompt assignment intentionally skips extraction when saving other voices is disabled, leaving no job to replace the person's pending state. Read consent inside the assignment transaction and project disabled on both new labels and contradicted profiles, preserving the version fence and ready voiceprints rather than reporting phantom queued work. Generated with [Devin](https://devin.ai) Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ywheel # Conflicts: # app/lib/l10n/app_ar.arb # app/lib/l10n/app_be.arb # app/lib/l10n/app_bg.arb # app/lib/l10n/app_bn.arb # app/lib/l10n/app_bs.arb # app/lib/l10n/app_ca.arb # app/lib/l10n/app_cs.arb # app/lib/l10n/app_da.arb # app/lib/l10n/app_de.arb # app/lib/l10n/app_el.arb # app/lib/l10n/app_en.arb # app/lib/l10n/app_es.arb # app/lib/l10n/app_et.arb # app/lib/l10n/app_fa.arb # app/lib/l10n/app_fi.arb # app/lib/l10n/app_fr.arb # app/lib/l10n/app_he.arb # app/lib/l10n/app_hi.arb # app/lib/l10n/app_hr.arb # app/lib/l10n/app_hu.arb # app/lib/l10n/app_id.arb # app/lib/l10n/app_it.arb # app/lib/l10n/app_ja.arb # app/lib/l10n/app_kn.arb # app/lib/l10n/app_ko.arb # app/lib/l10n/app_localizations.dart # app/lib/l10n/app_localizations_ar.dart # app/lib/l10n/app_localizations_be.dart # app/lib/l10n/app_localizations_bg.dart # app/lib/l10n/app_localizations_bn.dart # app/lib/l10n/app_localizations_bs.dart # app/lib/l10n/app_localizations_ca.dart # app/lib/l10n/app_localizations_cs.dart # app/lib/l10n/app_localizations_da.dart # app/lib/l10n/app_localizations_de.dart # app/lib/l10n/app_localizations_el.dart # app/lib/l10n/app_localizations_en.dart # app/lib/l10n/app_localizations_es.dart # app/lib/l10n/app_localizations_et.dart # app/lib/l10n/app_localizations_fa.dart # app/lib/l10n/app_localizations_fi.dart # app/lib/l10n/app_localizations_fr.dart # app/lib/l10n/app_localizations_he.dart # app/lib/l10n/app_localizations_hi.dart # app/lib/l10n/app_localizations_hr.dart # app/lib/l10n/app_localizations_hu.dart # app/lib/l10n/app_localizations_id.dart # app/lib/l10n/app_localizations_it.dart # app/lib/l10n/app_localizations_ja.dart # app/lib/l10n/app_localizations_kn.dart # app/lib/l10n/app_localizations_ko.dart # app/lib/l10n/app_localizations_lt.dart # app/lib/l10n/app_localizations_lv.dart # app/lib/l10n/app_localizations_mk.dart # app/lib/l10n/app_localizations_mr.dart # app/lib/l10n/app_localizations_ms.dart # app/lib/l10n/app_localizations_nl.dart # app/lib/l10n/app_localizations_no.dart # app/lib/l10n/app_localizations_pl.dart # app/lib/l10n/app_localizations_pt.dart # app/lib/l10n/app_localizations_ro.dart # app/lib/l10n/app_localizations_ru.dart # app/lib/l10n/app_localizations_sk.dart # app/lib/l10n/app_localizations_sl.dart # app/lib/l10n/app_localizations_sr.dart # app/lib/l10n/app_localizations_sv.dart # app/lib/l10n/app_localizations_ta.dart # app/lib/l10n/app_localizations_te.dart # app/lib/l10n/app_localizations_th.dart # app/lib/l10n/app_localizations_tl.dart # app/lib/l10n/app_localizations_tr.dart # app/lib/l10n/app_localizations_uk.dart # app/lib/l10n/app_localizations_ur.dart # app/lib/l10n/app_localizations_vi.dart # app/lib/l10n/app_localizations_zh.dart # app/lib/l10n/app_lt.arb # app/lib/l10n/app_lv.arb # app/lib/l10n/app_mk.arb # app/lib/l10n/app_mr.arb # app/lib/l10n/app_ms.arb # app/lib/l10n/app_nl.arb # app/lib/l10n/app_no.arb # app/lib/l10n/app_pl.arb # app/lib/l10n/app_pt.arb # app/lib/l10n/app_ro.arb # app/lib/l10n/app_ru.arb # app/lib/l10n/app_sk.arb # app/lib/l10n/app_sl.arb # app/lib/l10n/app_sr.arb # app/lib/l10n/app_sv.arb # app/lib/l10n/app_ta.arb # app/lib/l10n/app_te.arb # app/lib/l10n/app_th.arb # app/lib/l10n/app_tl.arb # app/lib/l10n/app_tr.arb # app/lib/l10n/app_uk.arb # app/lib/l10n/app_ur.arb # app/lib/l10n/app_vi.arb # app/lib/l10n/app_zh.arb # app/lib/pages/capture/widgets/widgets.dart # app/lib/pages/conversation_detail/widgets/transcript_tab.dart # app/lib/widgets/transcript.dart # backend/utils/stt/live_session.py
…arios main replaced initialTabIndex with ConversationTab and moved the detail transcript to flat lines; the scenarios open the Transcript tab through the new API and the outcome card keeps a margin under the tab bar. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pped The merge of origin/main into the locked-preview fix (bf4d6e2) kept the call to _buildCardContent but dropped its definition, re-added the old opaque overlay and removed isLocked from the row's rebuild key, so main did not compile for mobile and conversation_locked_preview_test could not pass. Restore the three pieces as the fix (3f1ab32) wrote them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Read only cached speaker embeddings from at most 25 conversations in the last 30 days and return at most five matches, newest first. A shared three-second deadline bounds executor reads and returns matches already found. Reuse pooled voice thresholds and exclude manual decisions, rejected voices, ignored voices, and inaccessible conversations. Co-authored-by: Codex Sol <[email protected]>
INV-UI-2 forbids scaling a ProgressView; the saving spinner added with durable live naming and the existing Add spinner now use controlSize(.small). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Automations to automatically generate PRs for you. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Co-authored-by: Codex Sol <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 90f7437308
ℹ️ 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".
| unawaited( | ||
| rejectConversationSpeaker(conversationId, segment.speakerId, SpeakerRejection.notPerson, personId: person.id), | ||
| ); |
There was a problem hiding this comment.
Serialize rejection before accepting a replacement label
When the user taps “Someone Else…” and promptly chooses a replacement person, this fire-and-forget rejection races the assignment started by _editSegmentSpeaker. If the assignment reaches the backend first but this rejection commits afterward, its newer receipt generation clears the newly selected person, so the user's correction is lost. Await the rejection before opening the naming sheet, or queue both mutations through the same serialized assignment path.
Useful? React with 👍 / 👎.
| for affected_speaker in sorted(affected): | ||
| voice_profiles_db.record_ignored_voice( | ||
| uid, raw['id'], affected_speaker, datetime.now(timezone.utc), assignment_generation=generation | ||
| ) |
There was a problem hiding this comment.
Avoid returning failure after the rejection has committed
For a not_a_person request, the conversation assignment transaction has already committed before record_ignored_voice performs a second Firestore transaction. If that auxiliary write raises during a transient Firestore failure, the route returns 500 even though the label was cleared; the mobile caller then rolls its optimistic state back and reports failure while the server retains the rejection. Make this write atomic with the assignment or treat its failure as fail-open/background work so the response reflects the committed mutation.
Useful? React with 👍 / 👎.
| background_tasks.add_task( | ||
| store_owner_voice_sample, | ||
| uid=uid, | ||
| conversation_id=conversation_id, | ||
| segment_ids=list(resolved), |
There was a problem hiding this comment.
Fence owner voice learning against later corrections
When a manual “You” assignment queues this task, store_owner_voice_sample reads the conversation once, then performs slow audio download, transcription, and embedding work before unconditionally pooling the result into the owner's voiceprint. If the user corrects the label to “Not Me” after that initial read, the rejection updates only the conversation receipt, so the stale task can still publish the rejected speaker's embedding and contaminate owner matching in future conversations. Pass the committed assignment generation into the task and revalidate it transactionally before updating the owner profile, analogous to the person-learning version fence.
Useful? React with 👍 / 👎.
| @router.get('/v1/users/people/{person_id}/voice-matches', response_model=VoiceMatchesResponse, tags=['v1']) | ||
| async def get_person_voice_matches(person_id: str, uid: str = Depends(auth.get_current_user_uid)): |
There was a problem hiding this comment.
Rate-limit the historical voice-match scan
This authenticated endpoint has no rate-limit dependency even though each request can scan 25 conversations and download an embedding cache for each one. The three-second timeout does not bound resource consumption because cancelling run_blocking cannot stop an in-flight storage SDK call, so repeated requests from one account can accumulate work and starve the shared storage_executor. Apply a UID-keyed with_rate_limit policy as done for the related speaker-tag prompt endpoints.
AGENTS.md reference: backend/AGENTS.md:L181-L181
Useful? React with 👍 / 👎.
| if drop_reason == 'already_mapped': | ||
| await self._drop_rejected_mapping(speaker_id, segment, generation, conversation_id) | ||
| self._record_exit(drop_reason, speaker_id) |
There was a problem hiding this comment.
Run rejection checks for already-mapped live speakers
The new receipt check is placed inside match, but the normal load_and_run loop never calls match once speaker_id is present in speaker_to_person; it exits through the already_mapped branch before reaching this code. Consequently, rejecting an accepted automatic label during an active recording leaves the matcher map intact, and subsequent segments continue receiving and emitting the rejected person until the session resets. Route mapped segments through the rejection check or explicitly invalidate the matcher when the rejection is committed.
Useful? React with 👍 / 👎.
Co-authored-by: Codex Sol <[email protected]>
Co-authored-by: Codex Sol <[email protected]>
Co-authored-by: Codex Sol <[email protected]>
There was a problem hiding this comment.
54 issues found across 197 files
Confidence score: 2/5
- Rejections and carried labels can cross capture scopes when the same numeric speaker ID is reused, causing the wrong voice to be rejected or assigned in
manual_speaker_assignments.py,speakers.py, andlive_speaker_carry.py. Key and filter these decisions by(speaker_id_scope, speaker_id). - Learning can also cross scope:
speaker_learning_policy.pycan authorize a label from another scope, andspeaker_voice_matches.pygroups voices by numeric ID. Add scope checks before authorizing learning or pooling matches so unrelated audio is not taught as the same person. - In
TranscriptionService.swift, an assignment during reconnect can lose its onlyspeaker_assignedwake-up, leaving the live transcript and voice-learning flush without the label. Queue a retry when the connection is unavailable. finishConversationclearsliveManualSpeakerPersonMapeven though recording continues, so later segments lose the manual person label. Preserve the map across the rotation.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="desktop/macos/Desktop/Sources/AppState/AppState+ListenEvents.swift">
<violation number="1" location="desktop/macos/Desktop/Sources/AppState/AppState+ListenEvents.swift:191">
P2: `segmentWithPersonId` overwrites the local capture-source flag used by echo deduplication. When a user labels speaker 0, subsequent mic rows become `is_user == false`, so `LocalTranscriptionDuplicatePolicy` no longer detects mic/system playback duplicates; preserve the capture-lane flag for dedup and apply the person label separately when building/persisting the assigned segment.</violation>
</file>
<file name="backend/routers/listen/transcripts.py">
<violation number="1" location="backend/routers/listen/transcripts.py:861">
P2: This unconditional call breaks the existing transcript-delivery regression fixture, whose allocator stub has no `hydrate_receipt` method. Update the stub to implement the new interface (or use the real allocator), otherwise the legacy delivery tests fail before exercising their assertions.</violation>
</file>
<file name="backend/utils/manual_speaker_assignments.py">
<violation number="1" location="backend/utils/manual_speaker_assignments.py:113">
P1: `manual_rejected_speakers` collapses decisions from different `(speaker_id_scope, speaker_id)` clusters into one numeric-keyed winner. Index and arbitrate rejections by the scope-qualified speaker identity so rejecting one merged source cannot be undone or hidden by a decision for another source.
(Based on your team's feedback about scope-qualified owner clusters.)</violation>
</file>
<file name="backend/utils/speaker_identification.py">
<violation number="1" location="backend/utils/speaker_identification.py:849">
P2: `clean_seconds` still contains the planned duration when no clip was decoded, so the C2 state records speech that does not exist. Set it to zero before returning `no_chunks`.</violation>
</file>
<file name="desktop/macos/Desktop/Sources/AppState/AppState+Transcription.swift">
<violation number="1" location="desktop/macos/Desktop/Sources/AppState/AppState+Transcription.swift:260">
P2: `finishConversation` clears `liveManualSpeakerPersonMap` even though recording continues across the rotation. Local `handleBackendSegments` consults this map, so later segments lose the user's manual person label; preserve the manual map here and clear it only when recording actually ends.</violation>
</file>
<file name="backend/utils/speaker_learning_policy.py">
<violation number="1" location="backend/utils/speaker_learning_policy.py:87">
P1: `winning_receipt_decision` accepts carried speaker labels from a different capture scope. This can authorize an auto-labelled segment in the new scope and teach the wrong audio; apply the same carried-scope fence before considering the speaker decision.</violation>
<violation number="2" location="backend/utils/speaker_learning_policy.py:122">
P3: `receipt_names_person` is dead code in this change. Remove the unused helper or wire it into the receipt-name check so this policy module does not carry an unreachable API.</violation>
<violation number="3" location="backend/utils/speaker_learning_policy.py:209">
P2: Overlapping authorized scopes can contribute transcript text for intervals whose audio is decoded only once. The expected verification text then contains duplicate or unchosen words, causing otherwise clean pooled samples to fail verification; align contributors with the non-overlapping decoded audio or select one scope's transcript.</violation>
</file>
<file name="app/lib/pages/conversation_detail/widgets/earlier_voice_matches_sheet.dart">
<violation number="1" location="app/lib/pages/conversation_detail/widgets/earlier_voice_matches_sheet.dart:205">
P2: Rapidly tapping Play can let an older request play after the newer request has started, so the sheet may play the wrong conversation's clip. Recheck `_ticket` after `stop()` and after `setFilePath()` before continuing playback.</violation>
</file>
<file name="backend/database/users.py">
<violation number="1" location="backend/database/users.py:1073">
P2: This marks a person as learned for any non-empty numeric embedding, even when the provider returns the wrong dimension and matching can never succeed. Validate the embedding against the engine’s expected dimension before publishing the learned profile.
(Based on your team's feedback about embedding dimension validation.) [b9c6e9f7-7e02-4009-94df-ed30dba94d7a]</violation>
</file>
<file name="desktop/macos/Desktop/Sources/MainWindow/Components/LiveNameSpeakerSheet.swift">
<violation number="1" location="desktop/macos/Desktop/Sources/MainWindow/Components/LiveNameSpeakerSheet.swift:274">
P2: An assignment can already be committed when `onSave` returns `false`, because `assignLiveSpeaker` rejects a stale UI generation after the backend request completes. This leaves the sheet showing a false error and prevents retry after recording stops; return a committed outcome separately from stale UI state, or dismiss the sheet whenever the backend has accepted the assignment.</violation>
</file>
<file name="desktop/macos/Desktop/Sources/Rewind/Core/TranscriptionStorage.swift">
<violation number="1" location="desktop/macos/Desktop/Sources/Rewind/Core/TranscriptionStorage.swift:673">
P2: This session-wide update can run before queued live-segment upserts, so it updates zero rows and the later upsert can overwrite the durable assignment with the old `personId`. Flush pending transcript writes before this update, or serialize the assignment with the queued upserts.</violation>
</file>
<file name="desktop/macos/Desktop/Sources/TranscriptionService.swift">
<violation number="1" location="desktop/macos/Desktop/Sources/TranscriptionService.swift:335">
P1: A speaker assignment made during a reconnect window drops the only `speaker_assigned` wake-up and is never retried. The REST mutation survives, but the live transcript and voice-learning flush can miss the label; queue and replay this message after reconnect.</violation>
</file>
<file name="backend/models/speaker_labels.py">
<violation number="1" location="backend/models/speaker_labels.py:17">
P2: This validation accepts surrounding whitespace but preserves it, so a padded existing `person_id` passes the request schema and then fails the exact Firestore lookup. Strip the ID before forwarding it (or reject padded IDs during validation).</violation>
</file>
<file name="backend/models/transcript_segment.py">
<violation number="1" location="backend/models/transcript_segment.py:75">
P2: `speaker_label_source` is lost when live speaker assignments are flushed. The writer rebuilds each segment from an explicit field allowlist that omits this new field, so automatic labels reload without their provenance; add `speaker_label_source` to the field-only update allowlist and reconstruction path.</violation>
</file>
<file name="app/lib/pages/conversation_detail/widgets/speaker_tag_outcome.dart">
<violation number="1" location="app/lib/pages/conversation_detail/widgets/speaker_tag_outcome.dart:108">
P2: `ApiFailure` is treated as a normal pending read, so six outages or auth/decode failures are eventually shown as `needs_more_speech`. Preserve the pending state or expose a retry/error state instead of reporting a speech-quality outcome from failed reads.</violation>
</file>
<file name="backend/routers/listen/speakers.py">
<violation number="1" location="backend/routers/listen/speakers.py:289">
P2: Reconcile an existing mapping when a rejection is written or before the mapped fast path emits. This check only handles an in-flight race; later segments never call `_drop_rejected_mapping`, so the live socket continues to publish the rejected person until the session state resets.</violation>
<violation number="2" location="backend/routers/listen/speakers.py:463">
P1: Scope-filter the rejection before treating it as authoritative. A rejection recorded for an older `speaker_id_scope` currently suppresses or retracts a distinct voice that reuses the same numeric ID after a provider rollover, unlike the persisted assignment path.</violation>
</file>
<file name="app/lib/pages/conversation_detail/conversation_detail_provider.dart">
<violation number="1" location="app/lib/pages/conversation_detail/conversation_detail_provider.dart:369">
P2: A successful rejection never schedules speaker-summary regeneration. Apply the same completed-conversation summary refresh used for assignments, otherwise the detail page can continue showing a summary generated from the rejected speaker label.</violation>
</file>
<file name="backend/routers/listen/receiver.py">
<violation number="1" location="backend/routers/listen/receiver.py:599">
P2: The per-stream callback factory loses the originating epoch on its v2 error fallback. Thread that stream epoch through `_run_on_listen_loop` and pass it to the fallback enqueue so failed late callbacks retain their own speaker scope.</violation>
</file>
<file name="backend/utils/live_speaker_carry.py">
<violation number="1" location="backend/utils/live_speaker_carry.py:33">
P1: Filter manual receipt entries by `speaker_id_scope` before `_winning` matches them by numeric ID. As written, a decision from an older provider scope can label a reused ID in the active scope, carrying the wrong person or rejection into the new conversation; preserve only explicitly unscoped legacy entries.
(Based on your team's feedback about scope-qualified speaker identity.)</violation>
</file>
<file name="backend/utils/person_evidence.py">
<violation number="1" location="backend/utils/person_evidence.py:188">
P2: `use_for_speech_training=False` makes `authorized` false, but every non-ready target still enters `pending` and loses its learning progress. Gate this reset on `authorized` so an explicit training opt-out does not create a phantom learning state.</violation>
</file>
<file name="backend/utils/speaker_voice_matches.py">
<violation number="1" location="backend/utils/speaker_voice_matches.py:60">
P2: `get_conversations` applies `limit=25` before this function’s `status == 'completed'` filter, so recent in-progress rows can hide eligible completed conversations. Pass `statuses=['completed']` to the query.</violation>
<violation number="2" location="backend/utils/speaker_voice_matches.py:93">
P1: This groups segments only by numeric `speaker_id`, even though capture numbering restarts across connections and `speaker_id_scope` disambiguates those voices. When conversation-wide resolution falls back to capture IDs, distinct speakers can be pooled and produce a false historical match; key the grouping and decision lookups by scope plus ID.</violation>
<violation number="3" location="backend/utils/speaker_voice_matches.py:103">
P3: `speaker_id_of` (utils/speaker_tag_prompts/selection.py:78) returns 0 both for a real integer id 0 and for segments with no parseable id/name, and this filter accepts 0, so a transcript whose diarization is missing (legacy/sync data) pools every unattributed segment into one candidate voice 0. If a single stray cached embedding matches, the resulting `VoiceMatch` carries `segment_ids`/`talk_seconds` spanning unrelated unmapped speech and a clip drawn from its longest segment. Skip segments whose speaker id is genuinely unknown rather than pooling them into 0.</violation>
<violation number="4" location="backend/utils/speaker_voice_matches.py:201">
P3: Only `TimeoutError` is converted into the partial-result path here, so any other failure from the deadline-bounded workers — a transient Firestore error in `get_person`/`get_conversations`, an exception inside `named_speaker_prompts_allowed`'s subscription lookup, or executor rejection — escapes `_read` and turns the whole best-effort scan into a 500, discarding matches already collected. Degrade those to the partial list (with a warning log) instead, while still re-raising `LookupError` so the route keeps its 404.</violation>
</file>
<file name="app/lib/pages/conversation_capturing/page.dart">
<violation number="1" location="app/lib/pages/conversation_capturing/page.dart:461">
P2: This marks the new conversation’s segments as manually confirmed after an assignment to the previous session finishes. The provider returns true on a session mismatch without updating current segments, but this `speakerId` branch still changes their provenance; guard this mutation with the same conversation/session fence.</violation>
</file>
<file name="backend/database/speaker_learning.py">
<violation number="1" location="backend/database/speaker_learning.py:54">
P2: Concurrent failed learning attempts can overwrite each other's diagnostics because this write leaves `updated_at` unchanged and the fence has no attempt ordering. A slower, older attempt can therefore regress the displayed speech progress or outcome after a newer attempt has completed; add an attempt/version token or otherwise make diagnostic writes monotonic.</violation>
</file>
<file name="desktop/macos/changelog/unreleased/2026-10-01-live-speaker-labels.json">
<violation number="1" location="desktop/macos/changelog/unreleased/2026-10-01-live-speaker-labels.json:2">
P3: The clause "the label is stored before the sheet closes" describes the persistence timing rather than the user-visible outcome, and the entry ends with a period against the no-period convention in AGENTS.md. Keep the fragment to the user-facing behavior: the label now saves and a failed save shows an error.</violation>
</file>
<file name="desktop/macos/Desktop/Tests/APIClientRoutingTests.swift">
<violation number="1" location="desktop/macos/Desktop/Tests/APIClientRoutingTests.swift:690">
P3: `requests[0]` crashes the test process when the request is not captured. If this endpoint is ever mis-routed (exactly what the test guards against), `assertRoutes` fails its count check and returns, leaving `requests` empty, and `requests[0]` traps with an index-out-of-range fatal error that aborts the whole test run. Guard it like `testGetOmiCaptureUsesStrictArchiveDetailContract` does in this file: `guard let firstRequest = requests.first else { return XCTFail(...) }`.</violation>
</file>
<file name="backend/tests/unit/fixtures/strict_firestore_transaction.py">
<violation number="1" location="backend/tests/unit/fixtures/strict_firestore_transaction.py:81">
P3: The module docstring enumerates supported projections but is not updated for the newly allowed speaker-receipt projection that the error message now advertises. Update the docstring so the documented operations stay in sync with what the fixture accepts.</violation>
</file>
<file name="backend/route_policy_manifest.yaml">
<violation number="1" location="backend/route_policy_manifest.yaml:3787">
P2: This route authenticates with `auth.get_current_user_uid` (backend/routers/speaker_labels.py), which runs `validate_byok_request(uid)` on every request, so BYOK validation applies whenever BYOK headers are present. Record it as `byok: validated_when_headers_present` instead of `not_applicable`, consistent with sibling `get_current_user_uid` routes in the manifest.</violation>
</file>
<file name="app/lib/l10n/app_pt.arb">
<violation number="1" location="app/lib/l10n/app_pt.arb:3812">
P3: "O Omi precisa de mais fala clara de {name}" is a literal calque of "needs more clear speech" and sounds stilted in Portuguese. Suggest "O Omi precisa ouvir {name} com mais clareza e vai continuar tentando."</violation>
<violation number="2" location="app/lib/l10n/app_pt.arb:3814">
P3: The `carried` branch reads as a machine-translation artifact: "Mantido da sua última conversa" doesn't convey "carried over from your last conversation". Use "Mantido desde a sua última conversa".</violation>
</file>
<file name="desktop/macos/Desktop/Tests/SpeakerAssignmentTests.swift">
<violation number="1" location="desktop/macos/Desktop/Tests/SpeakerAssignmentTests.swift:242">
P3: The `isUser` assertion after reload is vacuous: `appendSegment` creates rows with the record's default (`false`), so `[false, false, false]` holds whether or not `updateLiveSpeakerAssignment` clears `isUser`. The comment claims "assignment clears isUser", but no row ever starts as the user, so the test can't verify that. Append one segment with `isUser == true` (requires an `isUser` parameter on the append path or an explicit update to set it first) so the clear is actually exercised, or drop the assertion and its claim.</violation>
</file>
<file name="app/lib/pages/conversation_detail/page.dart">
<violation number="1" location="app/lib/pages/conversation_detail/page.dart:897">
P2: `_openAskOmi` no longer starts a fresh chat, so the Ask Omi sheet resumes whatever session the shared `MessageProvider` already holds. `ChatPageState.initState` refreshes messages only when the provider is empty, so after any earlier chat in the same run the sheet can display the previous conversation's transcript instead of the one in `initialChatContext`. Confirm the conversation-scope switch reloads messages (or reset the session for a fresh Ask Omi scope) so each "Ask about this conversation" opens on the selected conversation.</violation>
</file>
<file name="app/lib/l10n/app_en.arb">
<violation number="1" location="app/lib/l10n/app_en.arb:14487">
P3: The two new count strings use a bare `{count}` (int) instead of the `{count, plural, ...}` form used by `transcriptSpeakerCount` just above. Languages with count-dependent noun inflection cannot localize "Lines labeled: 1" vs "Lines labeled: 2" correctly without the plural clause, and English itself reads better with `=1{Line labeled}`. Apply the plural form to both `speakerLabelLinesLabeled` and `speakerLabelEarlierMatches`.</violation>
</file>
<file name="backend/utils/speaker_assignment.py">
<violation number="1" location="backend/utils/speaker_assignment.py:44">
P2: This stamps `speaker_label_source = 'auto'` for user-initiated assignments too: `_handle_speaker_assigned` in receiver.py:1595 populates `speakers.segment_assignments` from the user's explicit `speaker_assigned` event, and those segments are carried through `process_speaker_assigned_segments` at transcripts.py:408/509, so a manual assignment is reported to the client as 'auto', which misrepresents the provenance this PR adds. Thread the label source through the maps (e.g. store it with each `segment_assignments`/`speaker_to_person` entry, or set a 'manual' marker in `_handle_speaker_assigned`) instead of unconditionally writing 'auto'.</violation>
</file>
<file name="app/lib/l10n/app_zh.arb">
<violation number="1" location="app/lib/l10n/app_zh.arb:3777">
P3: The disabled branch of `speakerLabelVoiceDetail` tells users to turn on "声音保存" in Settings, but the same Settings feature is already translated in this file with different terminology: `voiceSettingsSaveOthersSubtitle` (line 3519) and `speakerTagPromptSaveVoicesBody` (line 3512) describe Omi as keeping "一小段声音样本". Users pointed to Settings will not recognize the new "声音保存" wording. Align this hint with the existing zh phrasing, e.g. "请在设置中开启声音样本保存".</violation>
</file>
<file name="app/lib/l10n/app_sv.arb">
<violation number="1" location="app/lib/l10n/app_sv.arb:3776">
P3: These machine-produced Swedish strings are non-idiomatic and inconsistent with each other: `speakerLabelVoiceStatus` disabled says "Sparande av röst är avstängt" (singular) while the sibling `speakerLabelVoiceDetail` disabled says "sparande av röster" (plural) for the same voice-saving setting. In `speakerLabelVoiceDetail` other, "mer tydligt tal" reads as a word-for-word translation and should be "tydligare tal". Suggest native review of this batch; e.g. "Röstsparande är avstängt" for the status.</violation>
</file>
<file name="backend/tests/unit/test_transcript_owner_teaching.py">
<violation number="1" location="backend/tests/unit/test_transcript_owner_teaching.py:191">
P3: `test_owner_teaching_never_checks_named_entitlement` cannot catch what it claims: for `assign_type=is_user`, `_assign_manual_speaker` computes `person_id = None` and guards entitlement with `if person_id and not named_speaker_prompts_allowed(uid)`, so that check short-circuits and the `world.naming_checks` recorder is never appended regardless of the monkeypatch. The `banned` patch on `service.named_speaker_prompts_allowed` is unreachable from the endpoint path (the router uses its own module binding, which the fixture already replaced with the recorder), and the real assignment code where teaching queueing lives (`commit_manual_assignment`/`assign_conversation_speaker`) is entirely replaced by the fixture fake, so an entitlement consultation there would not be caught either. The test passes trivially and gives a false sense of coverage. Remove the dead `banned` monkeypatch (it can never fire) and instead assert the is_user commit never raises the named-people `TagPromptForbidden`/403 outcome, or rename the test to what it actually guards (router short-circuit).</violation>
</file>
<file name="backend/tests/unit/test_speaker_learning_jobs.py">
<violation number="1" location="backend/tests/unit/test_speaker_learning_jobs.py:142">
P2: The deadline assertion is vacuous: the collection loop in `retry_people_without_voiceprint` already caps `extract_speaker_samples` at `VOICE_LEARNING_RETRY_MAX_PEOPLE`, so `extract.call_count <= VOICE_LEARNING_RETRY_MAX_PEOPLE` holds even if `asyncio.timeout` is removed. In that regression the test would then sleep 60s per call (~5 minutes, since `slow` awaits `asyncio.sleep(60)`) and still pass on the same assertion, hiding the deadline loss and stalling CI. Assert `extract.call_count == 1`, which proves the deadline interrupted the first in-flight extraction.</violation>
</file>
<file name="app/lib/l10n/app_et.arb">
<violation number="1" location="app/lib/l10n/app_et.arb:3777">
P3: In the `other` arm, "Omi vajab inimeselt {name} rohkem selget kõnet" is a machine-translation artifact: "inimeselt" ("from the person") is inserted before the name even though the template source ("Omi needs more clear speech from {name}") has no such word, and the other arms of this string use {name} directly. It reads unnaturally — a native-speaker rendering would be "Omi vajab {name}-lt rohkem selget kõnet ja proovib edasi." Since the PR notes these strings have not had native review, this one is worth fixing before merge.</violation>
</file>
<file name="backend/tests/unit/test_speaker_voice_matches.py">
<violation number="1" location="backend/tests/unit/test_speaker_voice_matches.py:284">
P2: This test races the clock: with SCAN_SECONDS=0.25 the deadline expires ~0.2s after `_read` submits the c2 database read, and the assertions `entered.is_set()`, `env.reads == ['c1', 'c2']`, and `completed.wait(timeout=2.0)` depend on the storage_executor worker starting `slow_download` before `asyncio.wait_for` times out. On a loaded CI runner the wait can expire before the worker thread runs, so `entered` stays unset and `completed` is never set, and the test fails despite correct behavior. Give the executor an explicit margin so the timeout lands while the slow read is blocked, e.g. SCAN_SECONDS=1.0, which still fires the deadline mid-scan while making worker startup deterministic.</violation>
</file>
<file name="backend/tests/unit/test_conversation_events_bounds.py">
<violation number="1" location="backend/tests/unit/test_conversation_events_bounds.py:489">
P3: The second half of this test passes regardless of whether "null" is coerced to None: the router sets rejection to None for every person_id assignment (the condition is `assign_type == 'is_user' and not is_user`), so `captured["rejection"] is None` cannot catch a regression where the null value is persisted as the literal string. Assert the actual contract being protected: `assert captured["person_id"] is None` (and `assert captured["is_user"] is False` if the intent is to also guard the parsing).</violation>
</file>
<file name="backend/tests/unit/test_speaker_label_provenance.py">
<violation number="1" location="backend/tests/unit/test_speaker_label_provenance.py:74">
P3: This test passes `{'rejection': {'kind': 'not_me', 'person_id': None}}` as the decision, a shape `project_source` never receives in production: `apply_manual_assignments` (utils/manual_speaker_assignments.py:82) passes the full receipt entry, which always carries top-level `person_id`/`is_user`/`generation` alongside `rejection`. The assertion passes only because `decision.get('person_id')` and `decision.get('is_user')` miss on a dict lacking those keys, so the test does not actually guard the negative-decision contract. Build the decision in the production shape so the projection is exercised with the real query.</violation>
</file>
<file name="backend/tests/unit/test_live_speaker_carry.py">
<violation number="1" location="backend/tests/unit/test_live_speaker_carry.py:116">
P3: The sentinel case never exercises the sentinel exclusion: in `carried_receipt` (utils/live_speaker_carry.py) the `speaker_id == OMI_SPEAKER_ID_SENTINEL` check skips the segment before any receipt decision is looked up, and `_person_receipt()` carries a decision only for speaker '0' — so this assertion also holds if the sentinel guard were removed entirely. Pin the guard by giving the receipt a decision on speaker 99 (import `OMI_SPEAKER_ID_SENTINEL` instead of hardcoding 99), otherwise this asserts nothing beyond the earlier empty-receipt cases.</violation>
</file>
<file name="backend/tests/unit/test_speaker_learning_pool.py">
<violation number="1" location="backend/tests/unit/test_speaker_learning_pool.py:195">
P3: `scope_b` segments carry `person_id=None`, so in the no-receipt branch they can never be candidates (`candidates` requires `person_id == PERSON`) and never feed the plan. The test then proves only that person-less segments are dropped, not the claimed cross-scope dedup/wall-time-count-once behavior. Give the second scope the same person with a distinct speaker_id so the same shared wall time is actually in the pool twice.</violation>
</file>
<file name="backend/utils/speaker_tag_prompts/service.py">
<violation number="1" location="backend/utils/speaker_tag_prompts/service.py:723">
P2: The new `impure` check only disqualifies an overlapping different-speaker segment when it carries the same `speaker_id_scope` as the owner run. When the owner run is scoped (post-epoch segments) but the conversation also contains legacy unscoped (`speaker_id_scope` None) segments — the normal state during rollout — an overlapping unscoped foreign-speaker segment no longer rejects the clip, whereas the previous implementation rejected any overlapping non-owner segment. That loosens the purity gate for owner voiceprint teaching; the docstring only justifies ignoring *cross-scope duplicates*, not unscoped segments of unknown capture provenance overlapping the same window.</violation>
</file>
<file name="app/lib/pages/conversation_detail/widgets/transcript_tab.dart">
<violation number="1" location="app/lib/pages/conversation_detail/widgets/transcript_tab.dart:140">
P2: The "Yes" confirm labels every line of that voice on screen but persists only the tapped segment. `_startSpeakerAssignment` forwards `segmentIds` unchanged to `provider.startSpeakerAssignment`, which persists `List.of(segmentIds)`; the provider's optimistic update (and `linesLabeled` here) covers the whole `speakerId`, so after a server refresh the voice can come back partially labeled while the outcome card reports the full count. Send the full voice segment list, matching what `NameSpeakerBottomSheet` sends when "apply to speaker" is checked.</violation>
</file>
<file name="backend/routers/listen/stt_callbacks.py">
<violation number="1" location="backend/routers/listen/stt_callbacks.py:49">
P2: `build_stt_callbacks` replaces `receiver.speaker_provider_epoch` with a freshly minted epoch on every call, including mid-session failover rebuilds (`_rebuild_stt_socket_locked` -> `rebuild[0]()`). The pre-PR builder never reassigned this attribute, so a same-provider rebuild kept the session scope; now `_active_speaker_scope()` (conversations.py:333) can return a connection scope that segments stamped before the rebuild never carry, so rollover carry of the active scope's manual decisions silently misses pre-rebuild decisions. If the merged epoch reset is intentional, the rollover carry path needs to resolve decisions from all scopes seen this session (or be passed the specific scope of the stream it is carrying) instead of trusting the receiver's current epoch.</violation>
</file>
<file name="backend/utils/speaker_learning_jobs.py">
<violation number="1" location="backend/utils/speaker_learning_jobs.py:57">
P2: Each receipt-named person's extraction runs sequentially inside the single 45s `asyncio.timeout`, so one slow person (audio download + STT verification + embedding can each take 10-30s) consumes the whole deadline and the remaining eligible people are cancelled without ever being taught this pass — and nothing re-schedules them unless the conversation is finalized again. Run the extractions concurrently within the deadline (bounded by `VOICE_LEARNING_RETRY_MAX_PEOPLE`) or give each person its own smaller deadline.</violation>
</file>
<file name="backend/routers/speaker_labels.py">
<violation number="1" location="backend/routers/speaker_labels.py:58">
P2: Make `record_ignored_voice` fail-open or background work; a transient failure currently returns 500 after the label clear commits, leaving client and server state inconsistent.</violation>
<violation number="2" location="backend/routers/speaker_labels.py:67">
P2: Add a UID-keyed rate limit to this route; repeated historical voice-match scans can exhaust the shared storage workers.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| A rejection only stands while no newer explicit positive decision | ||
| (an entry without ``rejection``) covers the same voice. | ||
| """ | ||
| decisions: dict = {} |
There was a problem hiding this comment.
P1: manual_rejected_speakers collapses decisions from different (speaker_id_scope, speaker_id) clusters into one numeric-keyed winner. Index and arbitrate rejections by the scope-qualified speaker identity so rejecting one merged source cannot be undone or hidden by a decision for another source.
(Based on your team's feedback about scope-qualified owner clusters.)
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/manual_speaker_assignments.py, line 113:
<comment>`manual_rejected_speakers` collapses decisions from different `(speaker_id_scope, speaker_id)` clusters into one numeric-keyed winner. Index and arbitrate rejections by the scope-qualified speaker identity so rejecting one merged source cannot be undone or hidden by a decision for another source.
(Based on your team's feedback about scope-qualified owner clusters.) </comment>
<file context>
@@ -56,32 +57,87 @@ def apply_manual_assignments(segments: list[dict], receipt: dict) -> list[dict]:
+ A rejection only stands while no newer explicit positive decision
+ (an entry without ``rejection``) covers the same voice.
+ """
+ decisions: dict = {}
+ for key, entry in (receipt.get('speakers') or {}).items():
+ if not isinstance(entry, dict):
</file context>
| (receipt.get('speakers') or {}).get(str(segment.get('speaker_id'))), | ||
| ) | ||
| if isinstance(decision, Mapping) | ||
| ] | ||
| if not decisions: | ||
| return None | ||
| return max(decisions, key=lambda decision: decision.get('generation', 0)) | ||
|
|
There was a problem hiding this comment.
P1: winning_receipt_decision accepts carried speaker labels from a different capture scope. This can authorize an auto-labelled segment in the new scope and teach the wrong audio; apply the same carried-scope fence before considering the speaker decision.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/speaker_learning_policy.py, line 87:
<comment>`winning_receipt_decision` accepts carried speaker labels from a different capture scope. This can authorize an auto-labelled segment in the new scope and teach the wrong audio; apply the same carried-scope fence before considering the speaker decision.</comment>
<file context>
@@ -0,0 +1,219 @@
+ decision
+ for decision in (
+ (receipt.get('segments') or {}).get(segment.get('id')),
+ (receipt.get('speakers') or {}).get(str(segment.get('speaker_id'))),
+ )
+ if isinstance(decision, Mapping)
</file context>
| (receipt.get('speakers') or {}).get(str(segment.get('speaker_id'))), | |
| ) | |
| if isinstance(decision, Mapping) | |
| ] | |
| if not decisions: | |
| return None | |
| return max(decisions, key=lambda decision: decision.get('generation', 0)) | |
| segment_decision = (receipt.get('segments') or {}).get(segment.get('id')) | |
| speaker_decision = (receipt.get('speakers') or {}).get(str(segment.get('speaker_id'))) | |
| if ( | |
| isinstance(speaker_decision, Mapping) | |
| and speaker_decision.get('source') == 'carried' | |
| and speaker_decision.get('speaker_id_scope') != segment.get('speaker_id_scope') | |
| ): | |
| speaker_decision = None | |
| decisions = [ | |
| decision | |
| for decision in (segment_decision, speaker_decision) | |
| if isinstance(decision, Mapping) | |
| ] |
|
|
||
| func notifySpeakerAssigned(personId: String, segmentIds: [String]) { | ||
| guard streamingMode == .conversation, | ||
| isConnected, |
There was a problem hiding this comment.
P1: A speaker assignment made during a reconnect window drops the only speaker_assigned wake-up and is never retried. The REST mutation survives, but the live transcript and voice-learning flush can miss the label; queue and replay this message after reconnect.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At desktop/macos/Desktop/Sources/TranscriptionService.swift, line 335:
<comment>A speaker assignment made during a reconnect window drops the only `speaker_assigned` wake-up and is never retried. The REST mutation survives, but the live transcript and voice-learning flush can miss the label; queue and replay this message after reconnect.</comment>
<file context>
@@ -330,6 +330,30 @@ class TranscriptionService: @unchecked Sendable {
+ func notifySpeakerAssigned(personId: String, segmentIds: [String]) {
+ guard streamingMode == .conversation,
+ isConnected,
+ let webSocketTask,
+ let message = Self.speakerAssignedMessage(personId: personId, segmentIds: segmentIds)
</file context>
| if (drop_reason := self._drop_reason(generation, conversation_id, speaker_id)) is not None: | ||
| self._record_exit(drop_reason, speaker_id) | ||
| return | ||
| if speaker_id in rejected: |
There was a problem hiding this comment.
P1: Scope-filter the rejection before treating it as authoritative. A rejection recorded for an older speaker_id_scope currently suppresses or retracts a distinct voice that reuses the same numeric ID after a provider rollover, unlike the persisted assignment path.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/routers/listen/speakers.py, line 463:
<comment>Scope-filter the rejection before treating it as authoritative. A rejection recorded for an older `speaker_id_scope` currently suppresses or retracts a distinct voice that reuses the same numeric ID after a provider rollover, unlike the persisted assignment path.</comment>
<file context>
@@ -386,37 +445,65 @@ async def _match_unmapped(
if (drop_reason := self._drop_reason(generation, conversation_id, speaker_id)) is not None:
self._record_exit(drop_reason, speaker_id)
return
+ if speaker_id in rejected:
+ for voice in rejected:
+ self._retract_rejected_voice(voice, self._voice_segments.get(voice))
</file context>
|
|
||
| def test_negative_decision_projects_none(): | ||
| segment = _raw('s0', 4, speaker_match_source='live_embedding', speaker_label_source='auto') | ||
| decision = {'rejection': {'kind': 'not_me', 'person_id': None}} |
There was a problem hiding this comment.
P3: This test passes {'rejection': {'kind': 'not_me', 'person_id': None}} as the decision, a shape project_source never receives in production: apply_manual_assignments (utils/manual_speaker_assignments.py:82) passes the full receipt entry, which always carries top-level person_id/is_user/generation alongside rejection. The assertion passes only because decision.get('person_id') and decision.get('is_user') miss on a dict lacking those keys, so the test does not actually guard the negative-decision contract. Build the decision in the production shape so the projection is exercised with the real query.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_speaker_label_provenance.py, line 74:
<comment>This test passes `{'rejection': {'kind': 'not_me', 'person_id': None}}` as the decision, a shape `project_source` never receives in production: `apply_manual_assignments` (utils/manual_speaker_assignments.py:82) passes the full receipt entry, which always carries top-level `person_id`/`is_user`/`generation` alongside `rejection`. The assertion passes only because `decision.get('person_id')` and `decision.get('is_user')` miss on a dict lacking those keys, so the test does not actually guard the negative-decision contract. Build the decision in the production shape so the projection is exercised with the real query.</comment>
<file context>
@@ -0,0 +1,194 @@
+
+def test_negative_decision_projects_none():
+ segment = _raw('s0', 4, speaker_match_source='live_embedding', speaker_label_source='auto')
+ decision = {'rejection': {'kind': 'not_me', 'person_id': None}}
+ assert project_source(segment, decision) is None
+
</file context>
| decision = {'rejection': {'kind': 'not_me', 'person_id': None}} | |
| decision = {'generation': 1, 'person_id': None, 'is_user': False, 'rejection': {'kind': 'not_me', 'person_id': None}} |
| assert carried_receipt(_conversation(_person_receipt(), segments), 'other-scope') == {} | ||
| unscoped = _conversation(_person_receipt(), [_segment('s0', scope=None)]) | ||
| assert carried_receipt(unscoped, SCOPE) == {} | ||
| sentinel = _conversation(_person_receipt(), [_segment('s0', speaker_id=99)]) |
There was a problem hiding this comment.
P3: The sentinel case never exercises the sentinel exclusion: in carried_receipt (utils/live_speaker_carry.py) the speaker_id == OMI_SPEAKER_ID_SENTINEL check skips the segment before any receipt decision is looked up, and _person_receipt() carries a decision only for speaker '0' — so this assertion also holds if the sentinel guard were removed entirely. Pin the guard by giving the receipt a decision on speaker 99 (import OMI_SPEAKER_ID_SENTINEL instead of hardcoding 99), otherwise this asserts nothing beyond the earlier empty-receipt cases.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_live_speaker_carry.py, line 116:
<comment>The sentinel case never exercises the sentinel exclusion: in `carried_receipt` (utils/live_speaker_carry.py) the `speaker_id == OMI_SPEAKER_ID_SENTINEL` check skips the segment before any receipt decision is looked up, and `_person_receipt()` carries a decision only for speaker '0' — so this assertion also holds if the sentinel guard were removed entirely. Pin the guard by giving the receipt a decision on speaker 99 (import `OMI_SPEAKER_ID_SENTINEL` instead of hardcoding 99), otherwise this asserts nothing beyond the earlier empty-receipt cases.</comment>
<file context>
@@ -0,0 +1,650 @@
+ assert carried_receipt(_conversation(_person_receipt(), segments), 'other-scope') == {}
+ unscoped = _conversation(_person_receipt(), [_segment('s0', scope=None)])
+ assert carried_receipt(unscoped, SCOPE) == {}
+ sentinel = _conversation(_person_receipt(), [_segment('s0', speaker_id=99)])
+ assert carried_receipt(sentinel, SCOPE) == {}
+ unplaced = _conversation(_person_receipt(), [_segment('s0', audio_alignment='unplaced')])
</file context>
| seg('b1', 0.0, 6.0, speaker_id=3, person_id=None, scope='v2'), | ||
| seg('b2', 10.0, 14.0, speaker_id=3, person_id=None, scope='v2'), |
There was a problem hiding this comment.
P3: scope_b segments carry person_id=None, so in the no-receipt branch they can never be candidates (candidates requires person_id == PERSON) and never feed the plan. The test then proves only that person-less segments are dropped, not the claimed cross-scope dedup/wall-time-count-once behavior. Give the second scope the same person with a distinct speaker_id so the same shared wall time is actually in the pool twice.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_speaker_learning_pool.py, line 195:
<comment>`scope_b` segments carry `person_id=None`, so in the no-receipt branch they can never be candidates (`candidates` requires `person_id == PERSON`) and never feed the plan. The test then proves only that person-less segments are dropped, not the claimed cross-scope dedup/wall-time-count-once behavior. Give the second scope the same person with a distinct speaker_id so the same shared wall time is actually in the pool twice.</comment>
<file context>
@@ -0,0 +1,631 @@
+def test_cross_scope_duplicate_transcript_is_ignored(world):
+ scope_a = [seg('a1', 0.0, 6.0, scope='rt'), seg('a2', 10.0, 14.0, scope='rt')]
+ scope_b = [
+ seg('b1', 0.0, 6.0, speaker_id=3, person_id=None, scope='v2'),
+ seg('b2', 10.0, 14.0, speaker_id=3, person_id=None, scope='v2'),
+ ]
</file context>
| seg('b1', 0.0, 6.0, speaker_id=3, person_id=None, scope='v2'), | |
| seg('b2', 10.0, 14.0, speaker_id=3, person_id=None, scope='v2'), | |
| seg('b1', 0.0, 6.0, speaker_id=3, person_id=PERSON, scope='v2'), | |
| seg('b2', 10.0, 14.0, speaker_id=3, person_id=PERSON, scope='v2'), |
| candidates = { | ||
| speaker_id: segments | ||
| for speaker_id, segments in voices.items() | ||
| if speaker_id >= 0 |
There was a problem hiding this comment.
P3: speaker_id_of (utils/speaker_tag_prompts/selection.py:78) returns 0 both for a real integer id 0 and for segments with no parseable id/name, and this filter accepts 0, so a transcript whose diarization is missing (legacy/sync data) pools every unattributed segment into one candidate voice 0. If a single stray cached embedding matches, the resulting VoiceMatch carries segment_ids/talk_seconds spanning unrelated unmapped speech and a clip drawn from its longest segment. Skip segments whose speaker id is genuinely unknown rather than pooling them into 0.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/speaker_voice_matches.py, line 103:
<comment>`speaker_id_of` (utils/speaker_tag_prompts/selection.py:78) returns 0 both for a real integer id 0 and for segments with no parseable id/name, and this filter accepts 0, so a transcript whose diarization is missing (legacy/sync data) pools every unattributed segment into one candidate voice 0. If a single stray cached embedding matches, the resulting `VoiceMatch` carries `segment_ids`/`talk_seconds` spanning unrelated unmapped speech and a clip drawn from its longest segment. Skip segments whose speaker id is genuinely unknown rather than pooling them into 0.</comment>
<file context>
@@ -0,0 +1,205 @@
+ candidates = {
+ speaker_id: segments
+ for speaker_id, segments in voices.items()
+ if speaker_id >= 0
+ and speaker_id != OMI_SPEAKER_ID_SENTINEL
+ and str(speaker_id) not in decided_speakers
</file context>
| matches.extend(found) | ||
| if len(matches) >= MAX_MATCHES: | ||
| break | ||
| except TimeoutError: |
There was a problem hiding this comment.
P3: Only TimeoutError is converted into the partial-result path here, so any other failure from the deadline-bounded workers — a transient Firestore error in get_person/get_conversations, an exception inside named_speaker_prompts_allowed's subscription lookup, or executor rejection — escapes _read and turns the whole best-effort scan into a 500, discarding matches already collected. Degrade those to the partial list (with a warning log) instead, while still re-raising LookupError so the route keeps its 404.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/speaker_voice_matches.py, line 201:
<comment>Only `TimeoutError` is converted into the partial-result path here, so any other failure from the deadline-bounded workers — a transient Firestore error in `get_person`/`get_conversations`, an exception inside `named_speaker_prompts_allowed`'s subscription lookup, or executor rejection — escapes `_read` and turns the whole best-effort scan into a 500, discarding matches already collected. Degrade those to the partial list (with a warning log) instead, while still re-raising `LookupError` so the route keeps its 404.</comment>
<file context>
@@ -0,0 +1,205 @@
+ matches.extend(found)
+ if len(matches) >= MAX_MATCHES:
+ break
+ except TimeoutError:
+ # Cancelling the await cannot kill an already-running SDK call. That
+ # leaf read can finish, but cannot start another conversation scan.
</file context>
Co-authored-by: Codex Sol <[email protected]>
Co-authored-by: Codex Sol <[email protected]>
Co-authored-by: Codex Sol <[email protected]>
Co-authored-by: Codex Sol <[email protected]>
Co-authored-by: Codex Sol <[email protected]>
Co-authored-by: Codex Sol <[email protected]>
…ywheel # Conflicts: # backend/utils/stt/live_session.py
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 138220402b
ℹ️ 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".
| persistLocal: { sessionId in | ||
| try await TranscriptionStorage.shared.updateLiveSpeakerAssignment( | ||
| sessionId: sessionId, speakerId: speakerId, personId: personId) |
There was a problem hiding this comment.
Persist manual-decision metadata for local-only labels
When local STT has no backend conversation ID, this path saves only personId/isUser in SQLite. The eventual /from-segments upload likewise carries those fields but no manual-assignment receipt or speaker_label_source; consequently the backend preserves the name but treats it as having unknown provenance, and the receipt-driven voice-learning retry never includes that person. Persist enough manual-decision metadata to create/replay the receipt when the session syncs.
Useful? React with 👍 / 👎.
| await flushPendingWrites() | ||
| guard isCurrent() else { return false } | ||
| guard let sessionId = context.sessionId else { return false } |
There was a problem hiding this comment.
Close the gap between flushing and applying the live label
During a local-STT recording, a transcript callback can run after this flush returns but before applyAssignment() installs liveManualSpeakerPersonMap. That new segment is therefore queued and persisted without the selected person, while the intervening SQL update may already have run and missed it; later segments get the label, but this one remains unlabeled in the final upload. Install a fenced provisional mapping before reopening transcript ingestion, or repeat the flush/update after the mapping is active.
Useful? React with 👍 / 👎.
| conversation_id=conversation_id, | ||
| expected_receipt_generation=(conversation.get('manual_speaker_assignments') or {}).get('generation', 0), |
There was a problem hiding this comment.
Fence owner learning by the owner decision, not global generation
If the user labels or rejects any other speaker while owner audio transcription/embedding is in flight, the conversation-wide receipt generation changes even though the selected owner segments are still assigned to the owner. Passing that global generation makes add_owner_voice_confirmation return 0, permanently discarding a valid owner sample as stale_assignment. Revalidate the winning decisions for the supplied owner segment IDs instead of requiring the entire receipt generation to remain unchanged.
Useful? React with 👍 / 👎.
| person_id = value if assign_type == 'person_id' else None | ||
| if person_id and not named_speaker_prompts_allowed(uid): | ||
| raise HTTPException(status_code=403, detail='Naming other people needs a paid plan') |
There was a problem hiding this comment.
Surface the paid-plan gate before opening the speaker picker
For a free account, the existing Flutter and macOS naming flows still present the normal person picker, but this new gate rejects every named-person save with 403; Flutter reports failedToSaveCheckConnection with a retry action and the macOS live sheet reports only a generic save failure. The retry can never succeed without an upgrade, so propagate a typed entitlement result or gate the picker with the upgrade UI instead of presenting this as a transport failure.
Useful? React with 👍 / 👎.
| if (result case ApiSuccess<ServerConversation>(:final data)) { | ||
| if (!_isDisposed && | ||
| _speakerEditGenerationByConversation[target.id] == generation && | ||
| identical(conversationOrNull, target)) { | ||
| if (data.id == target.id) { | ||
| conversationProvider?.updateConversation(data); | ||
| } else { | ||
| conversationProvider?.replaceBridgedConversation(target.id, data); | ||
| selectedDate = conversationLocalDayKey(data.startedAt ?? data.createdAt); | ||
| } | ||
| setCachedConversation(data); | ||
| } | ||
| return true; |
There was a problem hiding this comment.
Refresh the summary after clearing a speaker label
When a label is rejected in a completed conversation with an existing overview, the successful branch installs the corrected transcript but never adds the conversation to _automaticSpeakerSummaryRefreshIds, unlike the assignment path. _finishSpeakerSave therefore has nothing to schedule, leaving the summary and action items derived from it potentially naming the rejected person until some unrelated reprocessing occurs. Mark identity-changing rejections for the same summary refresh used by assignments.
Useful? React with 👍 / 👎.
| earned = assignment_evidence(before, person_id=person_id, source=source) | ||
| if rejected_person_id: | ||
| earned[rejected_person_id] = AUTO_CORRECTED |
There was a problem hiding this comment.
Avoid counting manual relabels as automatic corrections
The name sheet exposes “Not ” for every named segment, including labels whose speaker_label_source is manual or carried. Rejecting one of those labels reaches this code with rejected_person_id and unconditionally increments AUTO_CORRECTED, even though there was no automatic match; reconciliation also retracts the prior positive evidence, so the person's confidence is doubly and incorrectly penalized. Only record AUTO_CORRECTED when the rejected identity came from automatic evidence or an explicit automatic suggestion.
Useful? React with 👍 / 👎.
The analyzer ratchet allows no unused imports; the review's rejection test left one behind. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Evidence from an offline replay on one account's own hand-labeled data (owner-requested; aggregates only, no text or names) that bears on the teaching path here. 1. Stored segment times often do not locate the audio.
Per conversation (43 with ≥ 5 located runs): 16 aligned, 5 constant shift (e.g. 1,784 s, 3,647 s, 9,149 s), 14 step changes (offset jumps partway through), 8 scattered. Sources: Why it matters for this PR: pooling clean turns and scoping contamination will not help a clip that is cut from the wrong place — the 0.9 text-containment gate will (correctly) keep rejecting it. On this account 50 of 72 labeled people have a ≥ 8 s labeled run and 0 have a stored sample. Suggest either locating the clip by text (transcribe a wider window and align to the segment text before cutting) or fixing the time mapping; and recording 2. A guard worth adding at teaching time: "this sounds like the owner". 3. Pool across conversations, not within one.
Gain saturates around 5 clips and is mostly a variance reduction, but only when the clips come from different conversations. False accepts at a fixed threshold rise as the bank grows, so the threshold (or margin) should tighten with bank size. Limits: one account; the text-located subset favours clear speech; only 5 non-owner people had clean clips in ≥ 2 conversations, so nothing here supports per-person threshold changes. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 87c2c98619
ℹ️ 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".
| if (personId == null || !_requireConnection()) return; | ||
| final name = context.read<PeopleProvider>().people.where((p) => p.id == personId).firstOrNull?.name ?? ''; | ||
| OmiHaptics.light(); | ||
| _startSpeakerAssignment(provider, provider.conversation.id, segment.speakerId, personId, name, [segment.id], true); |
There was a problem hiding this comment.
Send every speaker segment when confirming
When an automatic label covers multiple segments, this passes only the tapped segment ID while also setting applyToSpeaker to true. startSpeakerAssignment therefore optimistically marks every segment with that speakerId as manual, but the backend treats a non-empty segment_ids list as a segment-scoped assignment and persists only the tapped line. After a reload, the other lines revert to automatic provenance and may prompt for confirmation again; voice learning is also authorized from only one line. Pass all matching segment IDs or invoke the speaker-wide endpoint without a segment filter.
Useful? React with 👍 / 👎.
| personName: outcome.personName, | ||
| matches: outcome.matches, |
There was a problem hiding this comment.
Reprocess earlier conversations after relabeling
When the user answers an earlier voice match, both branches mutate a completed historical conversation directly but never schedule the summary reprocessing used by normal speaker edits. If that conversation already has an overview or action items, its transcript gains or loses the identity while those derived fields retain the old attribution indefinitely because the conversation is not open in a provider that could schedule the refresh. Trigger a receipt-fenced reprocess after each successful answer.
Useful? React with 👍 / 👎.
| person_id=None, | ||
| is_user=False, | ||
| speaker_id=speaker_id, | ||
| segment_ids=data.segment_ids, |
There was a problem hiding this comment.
Clear segment rejections when restoring an ignored voice
When a not_a_person request includes segment_ids, as the conversation-detail client does, manual_assignment stores the rejection under the receipt's segment entries rather than its speaker entry. The existing restore path removes only receipt['speakers'][speaker_id], so restoring this voice returns success and removes its ignored-voice marker while the segment rejection remains; manual_rejected_speakers continues suppressing matching and prompts. Either persist this decision speaker-wide or remove the matching generation's segment decisions during restore.
Useful? React with 👍 / 👎.
…ywheel # Conflicts: # app/lib/l10n/app_ar.arb # app/lib/l10n/app_be.arb # app/lib/l10n/app_bg.arb # app/lib/l10n/app_bn.arb # app/lib/l10n/app_bs.arb # app/lib/l10n/app_ca.arb # app/lib/l10n/app_cs.arb # app/lib/l10n/app_da.arb # app/lib/l10n/app_de.arb # app/lib/l10n/app_el.arb # app/lib/l10n/app_en.arb # app/lib/l10n/app_es.arb # app/lib/l10n/app_et.arb # app/lib/l10n/app_fa.arb # app/lib/l10n/app_fi.arb # app/lib/l10n/app_fr.arb # app/lib/l10n/app_he.arb # app/lib/l10n/app_hi.arb # app/lib/l10n/app_hr.arb # app/lib/l10n/app_hu.arb # app/lib/l10n/app_id.arb # app/lib/l10n/app_it.arb # app/lib/l10n/app_ja.arb # app/lib/l10n/app_kn.arb # app/lib/l10n/app_ko.arb # app/lib/l10n/app_localizations.dart # app/lib/l10n/app_localizations_ar.dart # app/lib/l10n/app_localizations_be.dart # app/lib/l10n/app_localizations_bg.dart # app/lib/l10n/app_localizations_bn.dart # app/lib/l10n/app_localizations_bs.dart # app/lib/l10n/app_localizations_ca.dart # app/lib/l10n/app_localizations_cs.dart # app/lib/l10n/app_localizations_da.dart # app/lib/l10n/app_localizations_de.dart # app/lib/l10n/app_localizations_el.dart # app/lib/l10n/app_localizations_en.dart # app/lib/l10n/app_localizations_es.dart # app/lib/l10n/app_localizations_et.dart # app/lib/l10n/app_localizations_fa.dart # app/lib/l10n/app_localizations_fi.dart # app/lib/l10n/app_localizations_fr.dart # app/lib/l10n/app_localizations_he.dart # app/lib/l10n/app_localizations_hi.dart # app/lib/l10n/app_localizations_hr.dart # app/lib/l10n/app_localizations_hu.dart # app/lib/l10n/app_localizations_id.dart # app/lib/l10n/app_localizations_it.dart # app/lib/l10n/app_localizations_ja.dart # app/lib/l10n/app_localizations_kn.dart # app/lib/l10n/app_localizations_ko.dart # app/lib/l10n/app_localizations_lt.dart # app/lib/l10n/app_localizations_lv.dart # app/lib/l10n/app_localizations_mk.dart # app/lib/l10n/app_localizations_mr.dart # app/lib/l10n/app_localizations_ms.dart # app/lib/l10n/app_localizations_nl.dart # app/lib/l10n/app_localizations_no.dart # app/lib/l10n/app_localizations_pl.dart # app/lib/l10n/app_localizations_pt.dart # app/lib/l10n/app_localizations_ro.dart # app/lib/l10n/app_localizations_ru.dart # app/lib/l10n/app_localizations_sk.dart # app/lib/l10n/app_localizations_sl.dart # app/lib/l10n/app_localizations_sr.dart # app/lib/l10n/app_localizations_sv.dart # app/lib/l10n/app_localizations_ta.dart # app/lib/l10n/app_localizations_te.dart # app/lib/l10n/app_localizations_th.dart # app/lib/l10n/app_localizations_tl.dart # app/lib/l10n/app_localizations_tr.dart # app/lib/l10n/app_localizations_uk.dart # app/lib/l10n/app_localizations_ur.dart # app/lib/l10n/app_localizations_vi.dart # app/lib/l10n/app_localizations_zh.dart # app/lib/l10n/app_lt.arb # app/lib/l10n/app_lv.arb # app/lib/l10n/app_mk.arb # app/lib/l10n/app_mr.arb # app/lib/l10n/app_ms.arb # app/lib/l10n/app_nl.arb # app/lib/l10n/app_no.arb # app/lib/l10n/app_pl.arb # app/lib/l10n/app_pt.arb # app/lib/l10n/app_ro.arb # app/lib/l10n/app_ru.arb # app/lib/l10n/app_sk.arb # app/lib/l10n/app_sl.arb # app/lib/l10n/app_sr.arb # app/lib/l10n/app_sv.arb # app/lib/l10n/app_ta.arb # app/lib/l10n/app_te.arb # app/lib/l10n/app_th.arb # app/lib/l10n/app_tl.arb # app/lib/l10n/app_tr.arb # app/lib/l10n/app_uk.arb # app/lib/l10n/app_ur.arb # app/lib/l10n/app_vi.arb # app/lib/l10n/app_zh.arb
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fd0c42095f
ℹ️ 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".
| if drop_reason == 'already_mapped': | ||
| await self._drop_rejected_mapping(speaker_id, segment, generation, conversation_id) | ||
| self._record_exit(drop_reason, speaker_id) | ||
| return |
There was a problem hiding this comment.
Apply positive manual decisions to mapped live speakers
When a voice is already auto-mapped to one person and the user relabels it to someone else during the active recording, load_and_run classifies every later segment as already_mapped, while this branch only checks for rejections and returns. The positive receipt handling in _match_unmapped is therefore never reached, leaving speaker_to_person on the old identity and allowing subsequent live suggestions to keep reporting the person the user just corrected; reconcile mapped speakers against positive manual decisions here as well.
Useful? React with 👍 / 👎.
| applyAssignment: { [weak self] in | ||
| self?.liveSpeakerPersonMap[speakerId] = personId | ||
| self?.liveManualSpeakerPersonMap[speakerId] = personId |
There was a problem hiding this comment.
Preserve manual labels against late suggestion events
If an automatic speaker_label_suggestion was queued before this save completed but arrives afterward, the existing event handler unconditionally rewrites liveSpeakerPersonMap[speakerId], overriding the newly selected person in the UI. For local STT, liveManualSpeakerPersonMap still persists future segments with the manual person, so the displayed name and stored identity can disagree for the remainder of the recording; suggestion handling should refuse to replace a speaker present in the manual map.
Useful? React with 👍 / 👎.
| final state = switch (result) { | ||
| ApiSuccess(:final data) => data.voiceLearningState, | ||
| ApiFailure() => 'pending', | ||
| }; | ||
| final lastAttempt = attempt + 1 >= maxPolls; | ||
| if (state == 'pending' || state == 'unknown') { | ||
| if (!lastAttempt) return _schedule(generation, attempt + 1); | ||
| _settle(generation, 'needs_more_speech'); |
There was a problem hiding this comment.
Do not report transport failures as insufficient speech
When every person-status poll fails because the device is offline or the endpoint is temporarily unavailable, each ApiFailure is converted to pending, and the final attempt then permanently settles the card as needs_more_speech. This tells the user that voice learning failed for lack of audio even if it actually succeeded on the server, and polling never resumes; preserve an unavailable/pending state for request failures instead of inferring a learning outcome from them.
Useful? React with 👍 / 👎.
| if (result is! ApiSuccess<ServerConversation>) { | ||
| OmiFeedback.error(context, context.l10n.speakerTagPromptAnswerFailed); | ||
| return; | ||
| } |
There was a problem hiding this comment.
Remove a rejected live suggestion after success
After “Someone Else…” is successfully persisted, this path opens the naming sheet without removing the matching entry from provider.suggestionsBySegmentId. If the user dismisses that sheet, the same “Sounds like ” chip remains visible and can be answered again even though the server has already recorded that this voice is not that person; clear suggestions for the rejected speaker immediately on the successful response.
Useful? React with 👍 / 👎.
…free again (#20252) #20190 applied the named speaker-ID entitlement to the manual transcript routes. Free-plan users naming another person got a 403 ('Naming other people needs a paid plan') from assign-speaker and the segment assign routes, which had always been free; the new 'not this person' rejection was gated the same way. In production after the deploy, 9 of 18 assign-speaker requests were refused; none were before. The entitlement stays where it was ruled: automatic naming (tag prompts and earlier voice matches). Labeling and correcting your own transcript never consults it. Co-authored-by: Claude Opus 5.5 <[email protected]>
…dence follows its label (#20320) ## Summary Follow-up to #20190 and #20252. A review of the speaker-label work found that learned voice evidence could outlive the decision that authorised it, and that automatic naming of other people was plan-gated on some surfaces and not others. This PR closes those gaps and makes "earlier matches" compete against every known voice. It changes no routes, wire models, thresholds, flags or stored-data format requiring migration. Product ruling applied (David, 2026-10-02): automatically naming other people is a paid feature on every surface; free plans get automatic identification of the account owner only. Naming, correcting and rejecting labels by hand stays free, and a free manual tag may still teach a voiceprint. ## Change - **Entitlement at candidate selection.** Live matching, sync speaker identification, conversation-wide resolution, the transcription shadow, spoken-introduction detection and earlier matches no longer load or score non-owner voiceprints for a free plan. Owner recognition, manual edits, same-stream carry of a manual label and every answer to an already-served card, including one that names a person, are unaffected. The plan is read once per live conversation or sync batch; a plan change is observed at the next conversation or batch. A failed read stays closed for that call and is retried. - **A wrong "this is me" can be undone.** Owner confirmations now record their source segments and decision generation. Correcting or rejecting those segments removes the contribution and rebuilds the owner voiceprint in the same transaction. Older confirmations, which only record their conversation, are removed for that conversation on correction. One conversation holds at most one of the five slots. - **Delayed teaching honours the current decision.** An owner-teaching task that runs after the user re-tagged the same segments with training turned off no longer publishes. - **Person samples are fenced to their source.** Publication rereads the conversation inside the transaction and refuses if it was deleted, the label changed, or training consent was withdrawn. An unrelated edit elsewhere in the conversation (tagging a second speaker) does not void the attempt. - **Earlier matches compete.** A cached voice is offered for a person only when that person beats the owner and every other usable voiceprint under the existing threshold and margin; near-ties abstain. - Owner clip download moved off the storage pool its own child downloads use. - **Audit follow-ups (2026-10-03).** Naming a person on a served card is free: the answer route no longer refuses a free plan (ruled by David; automatic suggestions stay paid). A speaker-level receipt entry stamped with a capture scope governs teaching only inside that scope, for people and for the owner, so a label carried in one scope cannot authorize another scope's audio in a merged conversation. Owner publication rechecks its own contributing segments in the transaction instead of requiring an unchanged receipt generation, so tagging another voice no longer discards valid owner teaching. A plan change taking effect at the next conversation is the ruled behaviour, not a gap. ## Evidence Offline replay on one hand-labeled account (aggregates only; the production embedding model's stored vectors; real backend policy functions). It is one account with few repeat people, so none of this is a population false-accept rate. | Measured | Baseline | Candidate | | --- | --- | --- | | Earlier-match offers, 26,243 candidate/query pairs | 584 offered, 453 wrong | 136 offered, 41 wrong (36 correct offers lost) | Measured and deliberately **not** shipped: - Pooling separated owner turns: 56 of 61 selections usable against 52 of 61; too small a gain to change the rule without acoustic validation of the four new clips. - A voiced-speech floor: 58 of 62 ten-second plans hold under ten seconds of voiced audio, so adding the floor alone would reject nearly everything. - Several exemplars from different conversations: owner recall 85.3% against 73.5% at the current threshold with equal retained audio, but impostor accepts rise from 8.8% to 11.5%; needs calibration on more than one account. - Replacing the transcript check with acoustic consistency: 12 of 54 uniformly wrong-voice pairs pass, so it cannot stand in for placement. - Corrected audio placement: transcript-check passes rise from 134 to 251 of 882 windows; still too low to ship a recovery rule. - Pooling short live fragments: 719 against 694 of 1,426 speaker groups reach five seconds, on a stored-segment proxy without real event timing. ## Tests - New `backend/tests/unit/test_voiceprint_authority.py`: free/paid/downgrade matrix across live, sync and resolution; delayed opt-out; correction and rejection retracting owner evidence; duplicate delivery; publication after delete, tombstone, label change and consent change; publication surviving an unrelated edit; entitlement read failure; carried-label teaching inside and outside its capture scope; owner publication surviving a tag on another voice and denied on revocation, opt-out and rejection. `test_speaker_tag_prompts_service.py` now asserts a free plan can name a person on a served card. - `test_speaker_voice_matches.py`: owner and duplicate-person competition. - 27 affected unit files pass through `backend/test.sh`; all four unit shards passed locally through `backend/scripts/run-unit-ci.sh --all` before the final review commit; backend typecheck reports 0 errors; the pusher import graph gains no torch or onnxruntime dependency. - Not run: anything against a live backend or device, Firestore contention, or a Docker image build. ## Rollout notes - Behaviour change for free plans: other people stop being named automatically in live, sync and reprocessed conversations. Existing labels are not removed, and manual tags keep working. - Backend only; deploy Cloud Run, listen and pusher together so all three apply the same rule. ## Product invariants affected none ## Failure class Failure-Class: FC-stale-selection-used-as-write-authority Teaching read a label, did slow audio work, then wrote a voiceprint without re-reading the label's authority. The publication and correction transactions now reread the source and write only for still-authorised segments. Guard: `backend/tests/unit/test_voiceprint_authority.py`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/20320?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
…ips there (#20390) ## Summary Labeling a speaker teaches a voiceprint only when the clip cut for that label is the audio that was actually spoken. On live conversations it usually is not: text is timed from the provider stream, stored audio from chunk arrival, and reconnects or provider failover pull the two clocks apart. On one hand-labeled account, `started_at + segment.start` lands within 1 s of the speech for 20% of 1,416 labeled runs and more than 10 s away for 68%. In production the first 13 hours after #20190/#20252 stored 11 of 105 person teaching attempts (text_mismatch 38, insufficient_speech 29). This PR makes new live conversations carry where each segment's audio was captured, and makes every teaching reader use it. ## Change - **Persist the receiver's capture window on live segments.** The receiver already computes a capture-clock window per segment for transient speaker identification and then drops it. Legacy (v2-off) persistence now stores it in two private fields, `audio_capture_start` / `audio_capture_end` (absolute Unix seconds). Text, speaker, `start`/`end` and ordering are unchanged; the fields are absent when unknown, cleared when a text merge spans a capture gap, kept out of the client schema and stripped from every client frame. `AUDIO_TIMELINE_V2` is untouched. New counter `omi_live_audio_capture_windows_total{outcome,reason}` shows what share of new segments are placeable. - **One placement module** (`utils/conversations/audio_placement.py`). `locate()` returns a trusted window only for audio-timeline v2 manifests and `sync:`-timed segments and refuses otherwise. `candidate_window()` gives verified readers the capture-clock position when every contributor recorded one with a consistent offset, else the legacy origin. Person teaching, the owner clip, tag-prompt clips and the text search all go through it. A capture window is a better candidate, not proof: every teaching path still runs the 0.9 transcript containment check before publishing. - **Bounded text-anchored recovery for teaching**, default off (`SPEAKER_TEACHING_TEXT_PLACEMENT`): after a text mismatch, search at most 32 s around the candidate using the verification transcript's word times, re-verify at most 12 s. Containment gate unchanged. - **Manual merge keeps source clocks.** The manual merge writer offset each donor by the prior transcript end plus a wall gap while copying audio at unchanged absolute timestamps, shifting later donors' text early. It now rebases from source wall-clock origins. - **Conversation-wide resolution never names from unplaced text.** Unplaced or abstained segments no longer inherit a cluster's name through a shared old speaker id. ## Evidence Offline replay on one hand-labeled account (aggregates only; one account, so no population claim): - Stored live conversations cannot be re-placed from metadata: strict `locate()` returns 0 of 1,416 runs (it refuses rather than guesses), and bounded text search recovers 13 of 748 mismatched windows, all 13 within 1 s. Old conversations stay as they are; this PR fixes forward. - Synthetic replay through the real receiver and persistence: capture windows stored for 0 of 18 segments before, 11 of 18 after (receiver had a window for 14 of 20 inputs; gaps and partial sentence repair clear it by design). All 18 stored payloads are byte-identical to before once the two new fields are removed. - A burst/clock-jump fixture shows the capture clock and the stored-chunk clock can still disagree (known metadata 2 of 2, exact stored-audio matches 0 of 2). That is why the capture window is used only behind transcript verification and `locate()` does not trust it. Not measured: production availability of capture windows (the new counter will show it) and the change in production store rates. ## Tests - New: `test_live_capture_windows.py`, `test_live_capture_persistence.py`, `test_live_capture_lifecycle.py`, `test_audio_placement.py`, `test_audio_placement_merge.py`, `test_teaching_placement.py`, `test_audio_capture_candidate.py`; additions to `test_conversation_speakers.py` and `test_merge_validation.py`. - `BACKEND_UNIT_TEST_FILE_LIST` over 19 related files via `backend/test.sh`: all pass. `scripts/typecheck.sh`: 0 errors. - TranscriptSegment and Conversation JSON schemas compared equal to pre-change snapshots; no generated client changed. - Not run: anything against a live backend or device, Docker image build. ## Rollout notes - Backend, listen and pusher should deploy together: the fields are written on the live path and read by teaching in the backend. - No migration or backfill. Existing conversations behave as before (legacy origin candidate). - Turn off: `LIVE_SPEAKER_CAPTURE_CLOCK=false` stops new windows being attached (it also changes the existing live matching path; use its established procedure). The text search is off unless `SPEAKER_TEACHING_TEXT_PLACEMENT` is set. - Watch: `omi_live_audio_capture_windows_total` persisted share; `omi_person_voice_learning_total` and the owner sample outcomes for text_mismatch falling on new conversations. ## Product invariants affected none ## Failure class Failure-Class: FC-transcript-and-audio-on-independent-clocks Teaching read transcript coordinates as if they addressed stored audio. This records the capture position at write time, routes every teaching reader through one placement gate that refuses unknown clocks for trusted use, and keeps transcript verification in front of every publication. Guards: `test_live_capture_persistence.py`, `test_audio_placement.py`, `test_audio_capture_candidate.py`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/20390?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
Summary
Labeling a speaker fixed that one conversation and taught Omi almost nothing. Measured in production over 7 days (all users): 97 person voiceprints stored against 734 whole-speaker person tags plus up to 2,843 selected-segment tags; the live-socket teaching path stored 0 of 227 requests; 7,243 whole-speaker "this is me" transcript tags never reached the owner voiceprint. Clients also dropped or inverted answers (Windows "You" was sent as an unassign; macOS live naming was never sent), and nothing told the user what a tag did.
This PR makes a label durable, teachable and visible.
Backend
voice_learning_stateon the person; people still without a voiceprint are retried at finalization, fail-open.POST /v1/conversations/{id}/speakers/{speaker_id}/reject(not_me,not_person,not_a_person) writes a receipt decision that the live matcher, processing, speaker resolution and tag prompts honor, instead of only clearing a label.speaker_label_source:manual,autoorcarried.GET /v1/users/people/{id}/voice-matchesreturns unnamed voices in recent conversations that match a learned person, from cached conversation speaker embeddings only.Clients
value: 'true'.Also in this branch
maindid not compile for mobile when this branch merged it, so no mobile check could pass. Two repairs are included:ConversationDetailPagestill passedstartFreshtoChatPageafter revert(app): remove mobile chat history and new chats #20015 removed that parameter; the argument is dropped.maininto the locked-preview fix (bf4d6e2) kept the call to_buildCardContentbut dropped its definition, re-added the old opaque overlay and removedisLockedfrom the row's rebuild key. The three pieces are restored as 3f1ab32 wrote them;conversation_locked_preview_test.dartpasses again.Tests
backend/test.shfile lists.test/widgets/speaker_label_feedback_test.dart(provenance, rejection and rollback, outcome polling, review sheet, carried banner) and four visual-audit scenarios (speaker-labels-transcript,speaker-labels-tag-outcome,speaker-labels-tag-outcome-more-speech,speaker-labels-carried-live).people.test.ts; macOSSpeakerAssignmentandAPIClientRoutingtests.Review
A Codex Sol review of the first pushed head reproduced and fixed five defects, one commit each: owner teaching could publish after its label was rejected or its conversation deleted; the mobile rejection discarded the server's response and kept labels the server had cleared; a rejection could race an earlier assignment and be undone; a late tag save could revive a disposed outcome controller; and "Someone Else…" opened naming before its rejection had committed. It also repaired the backend unit harnesses and registries the first CI run failed on (import isolation, a listen fake, the serving-query witness and the speaker-match exit contract), and ran all four unit shards locally through
backend/scripts/run-unit-ci.sh --all.Hermetic Backend E2Efails ontesting/e2e/test_webhooks.py(blocked DNS lookup forwebhook.test); the same job fails onmain's own push run and is not touched here.Rollout notes
Product invariants affected
none
Failure class
Failure-Class: FC-split-mutation-authority
The manual-assignment receipt is the one authority for a speaker label. UI maps, match evidence, processing snapshots and teaching read it and cannot overwrite it; rejections are receipt decisions rather than cleared fields. Guard:
backend/tests/unit/test_manual_speaker_assignments.py, extended here, with the new rejection, provenance and carry suites.🤖 Generated with Claude Code