Skip to content

fix: release dictation session listeners when speech workers exit - #23077

Merged
OrcaWin merged 6 commits into
mainfrom
nwparker/perf-09-25-speech-worker-exit
Sep 26, 2026
Merged

OrcaWin merged 6 commits into
mainfrom
nwparker/perf-09-25-speech-worker-exit

Conversation

@nwparker

@nwparker nwparker commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​308 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​302
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​7 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4

ELI5

When a speech worker exits, remove the finished session's window-close callback instead of leaving it attached until the window closes.

What Changed

Unexpected worker exits now send the existing stopped event after clearing that worker's state and listeners. Desktop IPC uses it to remove its session callback. Previously the worker vanished without that notification, and even a later explicit stop left the callback attached.

The persistence worker test now waits for real worker startup before advancing its simulated write deadline. The former 150 ms limit could expire during initialization instead of exercising the intended dispatched-write failure; production timeouts are unchanged.

Why

The current worker's exit is the lifecycle boundary that already owns cleanup. Reusing its stopped event avoids a second desktop-only cleanup mechanism. An explicit stop in flight remains the sole owner of its notification, and cleanup runs before notifying so a synchronous restart cannot reuse the exiting worker.

Linked Issue

Fixes #23076

Visual Proof

N/A — internal session-listener cleanup. No normal dictation controls, layout or transcript rendering change. This does not automatically stop microphone capture or reset the UI on unexpected exit: the existing desktop stopped consumer records completion for its waits.

Performance proof

Actual speech IPC and SttService with synthetic EventEmitter workers/windows; 15 successful starts followed by unexpected exits:

Count Before After
Retained window-close callbacks after 15 exits 15 0
Stopped notifications 0 15
Retained callbacks after normal stop 0 0

An independent reviewer repeated the 15-cycle result. This removes retained callbacks and their later close-time work; heap bytes, latency and unexpected-exit frequency were not measured.

Persistence test prerequisite

The branch also fixes a CI-only race in the existing writer-worker timeout test. Worker initialization now uses the normal startup deadline; only the deliberately non-responding command is timed with a fake clock. The test still verifies an indeterminate timeout, actual worker exit and unchanged persisted state, and now also checks the timeout error code. This changes no production persistence behavior. All 13 writer-worker tests pass on the exact revised head under Bun 1.4.2 on macOS; final-head platform CI remains required.

Testing

  • Nine new cases cover exit codes 0 and 1, repeated sessions, one notification during stop, warm reuse, failed startup, cancellation, error delivery, mobile partial-text completion, immediate restart and retired-event isolation.
  • Original source fails three new regressions and passes six controls. Candidate: 38 tests across four suites pass, independently repeated.
  • Six additional independent probes cover final ordering, foreign listeners, synchronous exit during stop, window close during startup, another window's replacement owner and errors during explicit stop.
  • Reproduce: ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/speech-worker-exit-lifetime.test.ts src/main/ipc/speech.test.ts src/main/speech/stt-service.test.ts src/main/speech/speech-model-deletion.test.ts.
  • macOS Node; Node typecheck, scoped lint/format/whitespace and changed-code quality pass. No app, microphone, native worker, permission prompt, audio decoder or network launched. Native Linux/Windows/SSH remain untested.

The 13 persistence worker tests pass under Node and Bun 1.4.2. A controlled 250 ms startup delay reproduces the original initialization failure; all three corrected fault cases pass with that delay. The timeout case also requires the exact timeout error code, real worker exit, and unchanged SQLite contents. Fresh hosted validation is pending.

Review

Merge risk: low. Independent review found no blocker at the published hashes. The current-worker guard and explicit stop waiter retain ownership, and cleanup precedes potentially reentrant notification.

Negative user-facing trade-offs: none identified. One existing stopped event is newly delivered on unexpected exit, including a startup exit before its existing promise rejection. The desktop's completion cache is already capped at 16 entries. Current normal/error/stop behavior remains covered; no hot audio-loop work is added.

Agent skill upstream boundary

  • Not applicable; no skill source changed.

Notes

CI prerequisite: this branch also restores the three diff-note catalog entries missing from the updated main baseline (the correction tracked in #23256), with Japanese and Korean wording clarified to make AI the recipient. The strict localization checks remain enabled. These entries are shared baseline maintenance and will drop out of this diff once they land on main.

The actual mobile controller ignores stopped events; partial text and finish replies stay unchanged in the regression test. No wire fields, opcodes, mobile publications, cloud transcription, provider paths, folder/worktree assumptions or execution-host authority change. An exit is reported by the current local worker, never inferred from remote connection loss.

Checklist

  • Focused change with mechanism, ELI5, alternatives, measured proof and merge risk.
  • Independent review, baseline regression proof and ownership probes complete.
  • Visual proof N/A; platform/runtime limits recorded.
  • Full lint/build/native matrix; local checks above pass and CI covers the branch.

@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: d7306b43-6903-449e-a052-1562dcfe3b6f

📥 Commits

Reviewing files that changed from the base of the PR and between 847b605 and b510aa1.

📒 Files selected for processing (3)
  • src/main/persistence/profile-state/profile-state-writer-worker.test.ts
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

The worker exit handler now sends a stopped event to the captured event sink after handling an unexpected worker failure. It suppresses that event when an explicit stop is already in flight. New tests cover repeated exits, cleanup, startup and stop behavior, error delivery, mobile dictation completion, and replacement-session isolation. The profile state writer timeout test now uses fake timers. The Japanese and Korean translations for an AI note label are updated.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to b510a

No actionable merge risk remains in the reviewed changes; the worker lifecycle and timeout behavior have focused coverage.

Architecture Summary

Architecture risk: 🔵 Low · up to b510a

The change affects 1 system.

Changed systems: src

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — src (service) was modified; 5 changed files map to changed impact.

Before / after behavior

  • observed — Modified behavior in src/main/ipc/speech-worker-exit-lifetime.test.ts: Adds mocked Electron and worker-thread dependencies, test helpers, and setup/teardown that registers speech handlers and creates a speech service for each test.
  • observed — Modified behavior in src/main/ipc/speech-worker-exit-lifetime.test.ts: Tests that unexpected worker exits with codes 0 or 1 deactivate the service, remove window and worker listeners, and produce one stopped notification per session across 15 cycles.
  • observed — Modified behavior in src/main/ipc/speech-worker-exit-lifetime.test.ts: Tests that an exit during a pending stop does not duplicate the stopped notification and that the window listener is removed.
  • observed — Modified behavior in src/main/ipc/speech-worker-exit-lifetime.test.ts: Tests that a normal stop leaves the worker reusable, and that its later idle exit does not add another stopped notification.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The pull request includes changes unrelated to speech-worker lifecycle handling. profile-state-writer-worker.test.ts changes timeout-test timer setup. ja.json and ko.json change unrelated AI tra… Remove the persistence test and localization changes from this pull request, or move them to separate pull requests.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 3 files. (2 skipped: 2 … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Issue #23076 is closed and supplies historical context only. No active directly linked issue supplies coding requirements for this pull request. The speech-worker changes and regression tests remain c…
Title check ✅ Passed The title clearly and concisely describes the main change: releasing dictation session listeners when speech workers exit.
Description check ✅ Passed The description covers the required sections, including the user impact, implementation, rationale, linked issue, visual proof, testing, review risk, platform limits, and checklist status. It also exp…
Full details: Out of Scope Changes check

Explanation

The pull request includes changes unrelated to speech-worker lifecycle handling. profile-state-writer-worker.test.ts changes timeout-test timer setup. ja.json and ko.json change unrelated AI translation text. These changes do not support the historical issue #23076 objective.

Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 3 files. (2 skipped: 2 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes — the 4-line behavior change in stt-session-start.ts plus its new 9-case suite.

  • stopped on unexpected worker exit — onExit now captures state.eventSink before handleSttWorkerFailure clears it, skips emission when a stop is already in flight, and otherwise emits { type: 'stopped' }. This lets the desktop IPC sink detach its per-session window.once('closed') listener.
  • New regression suite — speech-worker-exit-lifetime.test.ts covers exit codes 0/1, 15-cycle listener retention, no duplicate stopped during an in-flight stop, warm reuse, failed startup, error delivery, cancellation, mobile partial/completion, and reentrant restart ordering.

The suppression guard is sound: during an explicit stop the lifecycle exit listener runs before waitForSttWorkerStop's listener, so the stop waiter owns the single notification; unexpected exits with no stop in flight deliver exactly one. Teardown and terminate paths remove listeners before terminate(), so warm/idle teardown cannot produce a spurious event. Mobile's acceptEvent ignores stopped (partial/final text preserved), and the renderer's recordStoppedSession already handles early stopped events for abandoned startups.

Verified locally: vitest run …speech-worker-exit-lifetime.test.ts stt-service.test.ts → 31 passed (9 + 22).

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the nwparker/perf-09-25-speech-worker-exit branch from 033e732 to 847b605 Compare September 26, 2026 19:50
@nwparker

Copy link
Copy Markdown
Contributor Author

Reviewed the CodeRabbit docstring-coverage warning. This repository explicitly requires concise comments limited to non-obvious reasoning (AGENTS.md), so I am declining the generic 80% docstring suggestion. The existing ownership/behavior comments and focused regression tests cover the decisions in this change. No code change is warranted for that style-only warning.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes — the incremental delta since the prior pullfrog review is one catalog-restoration commit (21741ca353) merged in by f8d7c66c73; the speech-worker fix under stt-session-start.ts and its 288-line suite are byte-for-byte unchanged from the reviewed 0ce7c69 content.

  • Restored missing diff-note catalog entries — re-adds DiffCommentPopover.{f6c449191e, 5fa4bfebaa, 5e9b3d0c2e} with translations across all six locales. DiffCommentDraftCard.tsx already referenced all three and origin/main's en.json lacked them, so this closes a real localization gap rather than duplicating an existing entry.
  • Speech-worker exit cleanup unchanged — onExit still captures the sink before handleSttWorkerFailure and emits stopped exactly once; the merge did not regress it.

ℹ️ The i18n restore is unrelated to this PR's stated purpose

The title and body describe only the speech-worker exit fix, but the head now also carries a diff-note catalog restore and a merge of that branch. It is a correct, needed fix — origin/main references the keys without having them — so there is nothing to change in the code; the flag is only that reverting this PR would also revert that catalog fix, and a reviewer reading the body would not expect locale changes.

Technical details
# Unrelated catalog fix bundled into the speech PR

## Affected sites
- `src/renderer/src/i18n/locales/{en,es,fr,ja,ko,zh}.json` — restored `auto.components.diff.comments.DiffCommentPopover.{f6c449191e,5fa4bfebaa,5e9b3d0c2e}`.
- commit `21741ca353` — the restoration; merged by `f8d7c66c73`.
- `src/renderer/src/components/diff-comments/DiffCommentDraftCard.tsx:220,246,254` — consumer that already referenced these keys on `main`.

## Required outcome
- No code change required. Confirm whether the catalog restore should ride along here or land in its own PR; if it stays, a line in the PR body would spare reviewers the surprise.

## Open questions for the human
- Was the restore folded in to unblock a catalog check that `main` was failing?

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@OrcaWin
OrcaWin merged commit fe50f3e into main Sep 26, 2026
39 of 40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Release dictation window listeners after unexpected speech worker exit

2 participants