Skip to content

fix: unblock the UI thread and stop tray subprocess churn - #49

Merged
ElbertePlinio merged 4 commits into
mainfrom
fix/ui-thread-and-tray-churn
Jul 19, 2026
Merged

ElbertePlinio merged 4 commits into
mainfrom
fix/ui-thread-and-tray-churn

Conversation

@ElbertePlinio

Copy link
Copy Markdown
Member

Implements #48 (2026-07-19 complementary swarm review).

Checklist

P0 — UI-thread blocking & hot-path subprocess churn

  • list_cleanup_models is now async + tauri::async_runtime::spawn_blocking, mirroring export_history_entry; a slow/unreachable cleanup endpoint no longer freezes the UI. Same treatment for run_doctor (logic extracted to run_doctor_checks). No frontend changes needed — async commands are transparent to the JS invoke signature (bun run check + frontend tests confirm).
  • tray::sync no longer spawns gdbus on every state emit. The dark-mode probe is cached (Mutex<Option<(bool, Instant)>>, 30s TTL) and force-refreshed on explicit theme events: get_system_theme (called by the frontend on media-query change and window focus, see src/lib/theme.ts) now refreshes the cache and re-syncs the tray, and is itself async/spawn_blocking. set_icon is skipped when the (stage, theme) icon variant is unchanged.

P1 — responsiveness & correctness

  • Engine::cancel no longer blocks the command thread up to 2s: recorder teardown + incremental drain moved to a background thread (mirroring how stop offloads via run_pipeline). cancel_dictation returns immediately.
  • 250ms recorder warm-up moved off the sync command path: recorder::start returns immediately; the immediate-exit check is now Recording::exit_error(), polled by the desktop engine 250ms after start on a background thread. A dead recorder surfaces the same error and tears the session down.
  • Incremental fallback policy is now explicit (IncrementalResult::{Complete, Partial, Unavailable}). When the final segment exceeds the 5s drain cap (or the worker otherwise falls back), the finished contiguous prefix is salvaged (segments::salvage_completed_prefix, unit-tested) and only the remaining tail — with the configured overlap — is re-transcribed, instead of silently discarding all incremental work. Failed segments or non-contiguous completion still fall back to a full re-transcription (safety-first). The incremental state machine is untouched (Architecture: deepen transcription orchestration seams #47 CAND-1 territory).

P1 — simplify

  • ms_to_sample/sample_to_ms hoisted from three definitions into engine::audio_segments (which owns SAMPLE_RATE_HZ); CLI and Tauri engine now call the shared versions.

Constraints held

Validation

  • cargo test --workspace --locked --all-targets: 83 passed (61 lib + 10 pickscribe bin + 3 pickscribe-cleanup + 9 src-tauri), 0 failed.
  • bun run check: 0 errors, 0 warnings. bun run test: 23 passed. bun run test:coverage: ratchet green. bun run build: OK.
  • cargo clippy --workspace --all-targets: clean on all touched files (remaining pre-existing warnings are in untouched files: config.rs, stt.rs, cleanup.rs, pickscribe-cleanup.rs).
  • cargo check -p pickscribe-app --features pickscribe-app/custom-protocol: OK.

Closes #48

- list_cleanup_models and run_doctor now run via
  tauri::async_runtime::spawn_blocking (mirroring export_history_entry), so
  a slow or unreachable cleanup endpoint no longer freezes the UI.
- tray sync no longer spawns a gdbus subprocess on every state emit: the
  dark-mode probe is cached with a 30s TTL and force-refreshed on explicit
  theme events (get_system_theme, called by the frontend on media-query
  change and window focus). set_icon is skipped when the stage/theme icon
  variant is unchanged.
- collapse nested ifs flagged by clippy on the touched file.

Refs #48
… fallback

- Engine::cancel now moves recorder teardown and the incremental worker
  drain (up to 2s) to a background thread, like stop does via run_pipeline;
  cancel_dictation returns immediately and the UI stays responsive.
- recorder::start no longer sleeps 250ms on the sync command path. The
  immediate-exit check moved to Recording::exit_error(), polled by the
  desktop engine 250ms after start on a background thread; a dead recorder
  still surfaces the same error and tears the session down.
- Incremental fallback policy is now explicit (IncrementalResult):
  Complete uses the worker transcript, Partial preserves the finished
  contiguous prefix (segments::salvage_completed_prefix, with tests) and
  re-transcribes only the remaining tail with the configured overlap, and
  Unavailable re-transcribes the whole recording. The 5s drain cap no
  longer silently discards all completed incremental segments. The state
  machine itself is untouched (that is #47 CAND-1).
- clippy: collapse nested ifs in recorder.rs, move engine.rs tests module
  after the items it references.

Refs #48
The pair was defined three times (audio_segments.rs, src-tauri/engine.rs,
bin/pickscribe.rs). audio_segments already owns SAMPLE_RATE_HZ, so the
canonical u64 versions are now public there; both callers convert at the
call site where a usize index is needed. Also collapses two clippy
nested-if warnings in the touched CLI file.

Refs #48
@ElbertePlinio
ElbertePlinio merged commit b3951ed into main Jul 19, 2026
1 check passed
@ElbertePlinio
ElbertePlinio deleted the fix/ui-thread-and-tray-churn branch July 19, 2026 13:14
ElbertePlinio added a commit that referenced this pull request Jul 19, 2026
…cremental

CAND-1 (#47) step 3/3: src-tauri/src/engine.rs's run_incremental_worker now
drives segment scheduling through engine::incremental::run instead of its
own copy of the state machine. TauriIncrementalHost adapts the module's
IncrementalHost trait to the desktop worker's in-process signals
(worker_cancel_token, the recording session's CancelToken via
is_session_current, stop_requested) and in-process STT execution
(stt::transcribe_with_cancel).

Preserved exactly:
- Tauri events: publish() still calls emit_incremental_session, so segment
  status transitions (Transcribing/RawReady/Cleaning/Failed) reach the
  frontend at the same points.
- Stage transitions: unchanged, driven by run_pipeline/incremental_result
  which don't change here.
- The IncrementalResult::Partial salvage path (PR #49): incremental_result
  and segments::salvage_completed_prefix are untouched; run_incremental_worker
  still returns an IncrementalDone with the same session/complete/
  fallback_required shape.
- keep_audio retention: host.keep_audio() and cleanup_session_dir calls use
  the same worker.cfg.general.keep_audio.
- The extra TOCTOU guard desktop had around `complete` (re-checking
  worker_cancel_token/is_session_current after the module returns, since a
  cancel/supersession can race in during the last segment's STT call) is
  kept in the run_incremental_worker wrapper rather than the shared module.

Behavior change (intentional, per b0e8c13): live backlog overflow now stops
scheduling immediately instead of flagging fallback_required and continuing
to schedule segments a fallback would discard. This was already the CLI's
behavior; desktop's loop now matches it. See engine::incremental::next_step
docs for the full rationale.

choose_segment_end here is now dead code (the module owns the equivalent
logic); left in place for the step 4 cleanup commit.

Next: delete the now-duplicate loop internals/helpers from both adapters.
ElbertePlinio added a commit that referenced this pull request Jul 19, 2026
…hared module (#55)

* refactor(incremental): replace tests-only IncrementalRunner with a real scheduling policy module

CAND-1 (#47) step 1/3: build the deep module both worker loops will
route through. src/engine/incremental.rs now owns:

- SchedulingConfig: target/max/overlap/backlog clamps (target >= 1000ms,
  overlap <= half target, backlog = max_ms * max_queue), centralized from
  two duplicated copies.
- next_step/choose_segment_end/after_boundary/classify_slice: the pure
  segment-cut decisions (250ms residual tail, stop-before-first-segment,
  empty/failed slice handling) previously duplicated verbatim in
  src/bin/pickscribe.rs and src-tauri/src/engine.rs.
- IncrementalHost + run(): the driver loop, generic over an adapter trait
  for STT execution, live segment cleanup, and progress publication. run()
  owns progress state (the RecordingSession and when to publish it), the
  fallback/completion decision, and the final drain.
- Unifies the one live policy divergence between the two production
  loops: live backlog overflow now always stops scheduling immediately
  (the CLI's existing behavior) instead of desktop's prior behavior of
  flagging fallback_required and continuing to schedule segments a
  fallback will discard. Documented on next_step().

CancelToken and cleanup_session_dir (used outside incremental scheduling)
are unchanged. IncrementalRunner/SegmentTranscriber/EnqueueResult/
IncrementalSession are removed: grep confirms nothing outside this
module's own tests ever constructed them, so they characterized an
orchestration path production never ran.

Neither production loop routes through this module yet (next commits).

* refactor(incremental): route the CLI worker loop through engine::incremental

CAND-1 (#47) step 2/3: src/bin/pickscribe.rs's run_incremental_worker_loop
now drives segment scheduling through engine::incremental::run instead of
its own copy of the state machine. CliIncrementalHost adapts the module's
IncrementalHost trait to the CLI's file-based control signals (stop/
stopping/cancel paths, parent recorder pid liveness) and subprocess STT
execution (transcribe_incremental_segment, still polling the same
is-cancelled condition via Control::Abandoned | Control::Cancelled).

Process files, exit codes, worker-output.json shape, and orphan/parent-
death handling are unchanged: CliIncrementalHost::control() reproduces the
exact precedence (cancel > stop > stopping-grace > orphan-with-startup-
deadline) that run_incremental_worker_loop had inline. The one intentional
behavior shift is upstream: live backlog overflow now stops immediately
rather than flagging-and-continuing, which was already the CLI's own
behavior pre-refactor (see b0e8c13) and only changes desktop's loop
(next commit).

queue_segment_cleanup/drain_segment_cleanup_results are folded into
CliIncrementalHost::try_queue_cleanup/drain_cleanup, which is what the
module's run() calls instead. growing_audio_duration_ms and the CLI's
choose_segment_end are now dead code (equivalent functions live in the
shared module); left in place for the step 4 cleanup commit alongside
desktop's duplicates so each adapter's dedup lands together.

Next: route the Tauri worker loop in src-tauri/src/engine.rs through the
same module.

* refactor(incremental): route the Tauri worker loop through engine::incremental

CAND-1 (#47) step 3/3: src-tauri/src/engine.rs's run_incremental_worker now
drives segment scheduling through engine::incremental::run instead of its
own copy of the state machine. TauriIncrementalHost adapts the module's
IncrementalHost trait to the desktop worker's in-process signals
(worker_cancel_token, the recording session's CancelToken via
is_session_current, stop_requested) and in-process STT execution
(stt::transcribe_with_cancel).

Preserved exactly:
- Tauri events: publish() still calls emit_incremental_session, so segment
  status transitions (Transcribing/RawReady/Cleaning/Failed) reach the
  frontend at the same points.
- Stage transitions: unchanged, driven by run_pipeline/incremental_result
  which don't change here.
- The IncrementalResult::Partial salvage path (PR #49): incremental_result
  and segments::salvage_completed_prefix are untouched; run_incremental_worker
  still returns an IncrementalDone with the same session/complete/
  fallback_required shape.
- keep_audio retention: host.keep_audio() and cleanup_session_dir calls use
  the same worker.cfg.general.keep_audio.
- The extra TOCTOU guard desktop had around `complete` (re-checking
  worker_cancel_token/is_session_current after the module returns, since a
  cancel/supersession can race in during the last segment's STT call) is
  kept in the run_incremental_worker wrapper rather than the shared module.

Behavior change (intentional, per b0e8c13): live backlog overflow now stops
scheduling immediately instead of flagging fallback_required and continuing
to schedule segments a fallback would discard. This was already the CLI's
behavior; desktop's loop now matches it. See engine::incremental::next_step
docs for the full rationale.

choose_segment_end here is now dead code (the module owns the equivalent
logic); left in place for the step 4 cleanup commit.

Next: delete the now-duplicate loop internals/helpers from both adapters.

* refactor(incremental): delete duplicate scheduling helpers from both adapters

CAND-1 (#47) step 4/4: growing_audio_duration_ms and choose_segment_end in
src/bin/pickscribe.rs, and choose_segment_end in src-tauri/src/engine.rs,
were left as dead code by the previous two commits once each worker loop
routed through engine::incremental (audio_segments::duration_ms and
incremental::choose_segment_end are the equivalents the module now owns).
Removed, along with the now-unused audio_segments import in the CLI binary
(src-tauri/src/engine.rs still uses audio_segments::slice_wav directly for
its fallback-tail slicing, so its import stays).

Both worker loops now contain zero scheduling policy of their own; all of
it lives in src/engine/incremental.rs, exercised by that module's own test
suite plus each adapter's existing integration coverage.
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.

Reliability: unblock the UI thread and stop tray subprocess churn

1 participant