Architecture

Documentation

Architecture

Data flow

microphone / system / application audio
                  │
          resampling + PCM16
                  ├── cloud WebSocket client(s) ──────────────┐
                  └── temporary spool → speech detection → Whisper worker ─┤
                                     (processor, Metal, or the Vulkan helper)
scripted demo ───────── deterministic caption timeline ──────┤
                                                             ▼
                                              operator + caption overlay
                                                             │
                                              transcript / export / history

caption events ── optional, opt-in ── Zoom caption sender → Zoom meeting
  1. Live capture. Each live source owns a native capture thread. CaptureState downmixes, applies a Kaiser-windowed sinc anti-alias filter when downsampling, resamples to the provider rate by linear interpolation, converts to mono PCM16 and forms roughly 100 ms chunks. Real-time callbacks write only to bounded channels.
  2. Provider sessions. Gemini Live Translate, OpenAI and DeepL Voice produce translated captions; Mistral Voxtral and Gemini Transcribe Live produce same-language captions. One async client runs per selected source and owns setup, timeouts, backoff, reconnect classification, audio pumping, turn finalization, and graceful shutdown.
  3. Built-in demonstration. The compatibility provider id ondevice starts ondevice::run_session, which opens no device and contacts no service. A deterministic English or French timeline emits the same status, level, partial- and final-caption events as a live provider, so it exercises the shipping UI, timer, overlay, transcript and export paths on x64 and ARM64. It is presented as a demonstration, not speech recognition.
  4. Local Whisper. The whisper provider (subtitles) and whisper-translate (translation into English, whisper.cpp’s translate task) share one pipeline, Provider::is_local_whisper: 16 kHz PCM16, a bounded writer queue, an anonymous temporary audio file and a separate inference worker per source. Silero’s bundled voice-activity model (whisper/vad.rs) skips windows without speech and trims the rest. One verified model is shared, and the sources take turns at inference on it: in the app, on the processor or on a Mac’s graphics processor (Metal); or on Windows in whisper-vulkan, a helper program on the graphics processor (whisper/gpu.rs, src-tauri/whisper-vulkan/), with the processor as the fallback. Each source owns its inference state. Capture timestamps travel with the audio, so a slow recognizer preserves meeting timing. ggml is compiled for AVX2 on x64 and for dot-product on ARM64, so whisper/cpu.rs refuses an older processor before any native code runs and the interface offers another engine. Where the windows are decoded, and why not on the graphics processor if it failed, is sent to the interface on whisper-engine (whisper::Engine). See local Whisper.
  5. Render/export. Both windows receive caption events. Pending turns are keyed by (origin, turnId) and finalized lines remain available for plain-text or Markdown export.

Every caption carries an interval — startMs/endMs, milliseconds since the session started — stamped in the core by timing::SessionClock and shared by every source, so a document that interleaves the microphone and the system agrees with itself about what happened when. It is monotonic elapsed time rather than the audio timeline, because cloud clients drop stale buffered audio before reconnecting and an audio clock would lose every gap where the socket was down. realtime::emit_caption applies it for cloud protocols and the demonstration. Whisper stamps segments from capture timestamps carried through its spool, so CPU backlog does not shift the transcript to the later inference time.

Protocol handlers are pure: handle_message parses one server message into the turn accumulator and returns a CaptionUpdate (none, interim or final) with the connection control. The shared runner emits the caption and advances a finished turn, so each wire format is unit-tested without a socket or an AppHandle (realtime::test_support). The runner itself is three parts: realtime/mod.rs holds the loop, realtime/policy.rs the reconnect decisions as pure functions (what to report, whether to drop or replay queued audio, how long to wait), and realtime/socket.rs one connection’s open, pump and graceful close. It reports through an Events trait that AppHandle implements, so realtime/tests.rs drives the whole state machine against a loopback WebSocket server on a paused clock. Every status, from the runner, the demonstration, Whisper or the session itself, is built by a StatusUpdate constructor (session, source or lane, by what it addresses) and leaves through Events::status. SessionManager::start (session/mod.rs) builds each source through SessionBuilder (session/builder.rs) into a SourceSlot of its own: a producer (the demo’s own timeline, the rehearsal fixture or a CaptureTarget thread, session/capture.rs) and one client, spawned by ProviderSettings::spawn_client (session/settings.rs). The slot records its source’s engine and token, so Pause and Stop treat each source by its own engine; the session keeps the start options, the clock and the loaded Whisper model the slots are built from. Validation and the choice of sources are in session/options.rs; the preflight test (session/preflight.rs) opens devices through the same CaptureTarget.

The transcript document

The transcript is an explicit document with a saved state, not a scrolling side effect.

  • No truncation. The log is unbounded. Past TRANSCRIPT_WARN_LINES (src/lib/document.ts) an unsaved log is flagged on screen; nothing is ever dropped.
  • Saved vs unsaved. savedLineId records the highest line id written to disk, so a second save of an unchanged document stays saved while one further line makes it unsaved again. clearTranscript resets the marker with the text, because line ids keep climbing and a stale marker would make a later run’s first lines look as if they were already saved.
  • Optional recovery spool. Off by default. When enabled, src/lib/recovery.ts writes the finalized lines to one file in the app’s local data directory every few seconds while the document is unsaved; recovery.rs treats it as opaque UTF-8, and the format (caption fields only, intervals validated but optional) lives in src/lib/document.ts. It is deleted on save, clear, discard, disable, and once a startup recovery offer is answered; a malformed or truncated spool is deleted rather than shown. Save, Clear, Disable, Restore and Quit share one renderer queue: deletion invalidates queued snapshots and waits for an active write. The core serializes filesystem access, and writes and flushes a sibling staging file before replacing the committed snapshot, so a failed write preserves the previous one; startup and deletion remove interrupted staging files.
  • Reading long transcripts. Paragraphs break on a source change, a five-second pause, a backwards timestamp, or before aggregation would exceed 600 characters. Individual caption lines remain intact. The monitor follows incoming text only while the operator is at the bottom and not selecting there, and provides a localized keyboard-accessible Jump to latest control. While a session runs, the stage’s Transcript tab (issue #124, remembered in stage.view) replaces the live turns with the whole log at the stage’s full height, with the turns still being spoken (inFlightLines) at its foot. Copy puts the last 5, 10 or 30 minutes, or everything, on the clipboard as plain text, in-flight turns included. Find searches the reader with historySearch.ts’s folding, placed back onto the text (transcriptFind.ts), and highlights through the CSS Custom Highlight API.
  • Markers. The operator’s markers (TranscriptMarker) are a list beside the lines, not lines, so nothing that reads captions can take one for speech; their ids come from the lines’ counter, which orders the two, and a marker makes the document unsaved as a line does. They are written into exports (transcript.ts), the recovery spool and the history log as records of their own, which older builds skip.

Provider contracts

Provider Mode Input Caption source Graceful stop
Google Gemini Live Translate Translate 16 kHz PCM16 output transcription audio stream end, drain to turn complete
OpenAI Realtime Translate 24 kHz PCM16 output transcript deltas close and drain
DeepL Voice API Translate 16 kHz PCM16 concluded and tentative target segments, lines closed at a concluded sentence end end of source media, drain to end of stream
Mistral Voxtral Realtime 3 Transcribe 16 kHz PCM16 transcription deltas, lines closed at detected turn ends flush, end, drain
Google Gemini Transcribe Live Transcribe 16 kHz PCM16 interim/final input transcription audio stream end, drain to final
OpenAI Realtime transcription Transcribe 24 kHz PCM16 transcription deltas, buffer committed by the client at pauses commit, drain to its completion
Local Whisper Transcribe 16 kHz PCM16 finalized multilingual segments EOF, finish queued audio
Local Whisper translation Translate, English only 16 kHz PCM16 finalized segments in English, no source text EOF, finish queued audio
Built-in demo Transcribe demo bundled deterministic timeline scripted partial/final events cancellation token

The two Gemini rows are separate Provider variants sharing one endpoint and one stored API key, because their wire format, rate and mode differ, and Provider::can_translate has to stay a plain function of the provider. Live Translate appends transcription deltas; Transcribe Live sends a revised hypothesis and then an authoritative final for the same segment, each replacing the last. See gemini-live-api.md. The two Whisper rows are split the same way, but they are one local pipeline: everything about running it follows Provider::is_local_whisper, and only the task handed to whisper.cpp follows the mode. The translating one captions in English only, so validation refuses any other caption language and any second one.

DeepL is the one provider that starts a connection over REST. RealtimeProtocol::prepare, run before every connection and cut short by Pause and Stop like the handshake, asks DeepL for a session (or resumes the one whose socket dropped) and receives a single-use streaming URL and token; its failures become the runner’s usual ends (PrepareError), so a refused key, a spent quota or a rate limit report and retry as a refused handshake would. Its socket takes no setup message (setup_json returns None). Because DeepL ends a session after 30 seconds without audio, and system audio can deliver no chunks at all when nothing plays, the runner sends the silence its keepalive asks for after 10 quiet seconds (Mistral, which ends an idle session the same way with its code 3401, asks for the same). A DeepL Free key (:fx) is refused when saved and again at Start (error.deeplPaidPlan): the Voice API is not on the free host. See deepl-voice-api.md.

OpenAI’s two rows are split like Gemini’s, on one stored key. Its transcription session has no turn detection of its own: the client commits the audio buffer at the end of each turn, from the loudness of the chunks it sends, through RealtimeProtocol::after_audio, a frame the runner sends straight after a chunk’s audio. See openai-transcribe-api.md.

The subtitle backends and the built-in demo are unavailable in translation mode; session/options.rs enforces this through Provider::can_translate.

Providers whose text has no turn boundary of its own close a line in the runner. Three rules apply, each opt-in through RealtimeProtocol:

  • Idle boundary: a line closes once new caption text has stopped for finalize_after (900 ms for both OpenAI engines and Mistral, 1 s for DeepL, whose lines mostly close earlier, on a concluded sentence).
  • End of turn: Signal::EndOfTurn(grace) sets a hard deadline: the line closes after the grace, however much text arrives meanwhile. Mistral sends it on turn.end, with its streaming delay as the grace, because the speaker’s last words are still on their way.
  • Mid-sentence hold: keeps_turn_open lets the provider hold a line at the idle boundary while the speaker is mid-sentence. The boundary checks again one interval later, and stops holding once the text has been still for MAX_HOLD (4 s). Mistral holds while turn detection says the speaker is talking and the text does not end a sentence; OpenAI’s transcription, which has no turn events, while the text does not end a sentence; DeepL while it still has tentative text it may revise.

See Mistral’s API notes and DeepL’s.

A drain ends on the provider’s own signal (RealtimeProtocol::drain_complete, or MessageControl::Closed), on its close or error, or after four seconds. When no turn is open, the provider holds nothing still to come (keeps_turn_open: DeepL’s tentative start of a sentence that is not on screen yet) and the connection has produced no caption for three seconds (QUIET_BEFORE_CLOSE), the closing frames are still sent but not waited on, so a Pause in a quiet room takes effect at once. Whatever ends a drain, the source reports the Pause or Stop that started it, and the runner finalizes the turn so far, so a provider that rejects a closing frame costs at most the drain.

Every provider’s error event goes through one classifier (realtime::wire::classify), so the providers cannot drift apart. A Close frame, during setup or mid-stream, is read by wire::Close: 1007, 1008 or key, quota or billing wording end the source with the reason; any other close, a bare 1000 included, is retried, and its code and reason are the Reconnecting detail. For error events: authentication, permission, quota, billing and credit wording stop the source with the provider’s message, whatever code it comes under; a backend failure (gRPC UNAVAILABLE), HTTP 408, 429 or 5xx, close codes 1001, 1011, 1012 and 1013, and Google’s transient names reconnect with backoff; an expired session (OpenAI’s or Mistral’s cap) is a planned handover; anything unrecognized stays fatal, 1007 and 1008 included, so a persistent failure reports itself instead of looping. A setup that times out, hits EOF or is closed with a retryable code is retried the same way, as Reconnecting, and the fifth such failure in a row ends the source; an accepted setup resets the count. A provider that sends no setup acknowledgement (OpenAI, Mistral, DeepL) has accepted a connection once it is open, so one that it ends within five seconds (UNCONFIRMED_OPEN) without having sent a message counts as a failed setup too (policy::unconfirmed_end); a connection that stays open, however quiet the room, does not. A provider that ends its session mid-stream (OpenAI’s session.closed, Mistral’s transcription.done, DeepL’s end_of_stream) does not end the source either: its last caption is emitted and the runner hands over to a new session.

Concurrency and shutdown

SessionManager serializes start and stop operations with a lifecycle mutex. A parent CancellationToken owns the run and each live source gets a child token. A capture failure cancels that source. Stop cancels producers, lets live providers flush and drain briefly, joins capture threads, clears meters and current captions, and retains completed transcript lines. The join gives up after three seconds and leaves a thread wedged in a driver call behind, so an unplugged device cannot make the app impossible to quit. A start that fails part-way shuts down what it had already started the same way (SessionManager::shutdown), without the Idle that would clear its error.

For Whisper, Stop cancels capture and closes input, then waits for every accepted frame and the final partial window, with no cloud drain timeout; an independent abort token lets the operator discard the remaining audio while Stop waits. The writer and inference worker cancel capture even on unwind, and producer outcome guards publish failures before EOF. Pause keeps processing the backlog but drops newly captured frames before the writer queue; a second of idle input releases the window the worker holds, so the last words before a Pause or a quiet spell are captioned at once. Quit discards the backlog rather than waiting for it. Backlog limits and disk or overflow failures are covered in local Whisper.

Continuing a source with Whisper (#248). switch_source_engine, granted to the operator window only, rebuilds one SourceSlot with offline Whisper inside the running session: same clock, pause channel and turn counters (realtime::TurnCounter, so turn ids keep increasing), while the other source runs on. It takes the lifecycle lock, and refuses (error.sessionFallback) unless the source is still on the engine the banner saw and has ended, or, when the banner saw it reconnecting for 30 seconds, is a cloud source whose reconnection it stops first. The old capture and clients are drained outside the session mutex, the model loads only if the session holds none, and Stop or Start cancel the shared switching token before they wait for the lock, so neither waits out a model load. The interface holds the run open while the banner offers the switch after the last source ended (heldSince in sessionStatus.ts), and a declined run’s history record ends at the failure’s time.

The built-in demo observes the same cancellation token on every short delay, so Stop remains responsive and cannot leave an audio or recognizer thread behind.

Pause is a watch channel per session: pause_session sets it, and every client holds a receiver. A connected client closes its provider connection through the same graceful close as Stop — so the last turn is flushed — reports Paused, and waits; on resume it connects afresh (Connecting, no backoff). A pause during a connect or setup abandons it at once, and one that lands just as setup completes closes the connection before Running is reported. A pause during a reconnect backoff ends the wait. An unchanged value is not sent, so a repeated Resume wakes nobody. Capture is untouched, so the meters keep running, and the demo’s pacer holds between steps. The renderer counts paused time out of the running cost estimate.

Connection health. Every send is bounded (three seconds), and a connected client pings every 15 seconds; 30 seconds with no inbound frame at all, pongs included, means the path is gone even if the operating system has not noticed, and the client reconnects. Without this, a Wi-Fi handoff or a dropped NAT entry left a source reporting Running while its sends blocked for minutes and Pause went unseen.

Planned handovers. Gemini’s goAway returns MessageControl::Handover, and a provider ending its session mid-stream is treated the same way. After a connection that lasted at least STABLE_CONNECTION, the runner reconnects without backoff and keeps the source Running. First it drains the old socket like a Pause, within min(timeLeft, 4 s): it sends the closing frames (audioStreamEnd for Gemini) and reads until the provider’s flush is done, so the audio already sent still comes back as text. From the drain on, and while the new socket connects and sets up, it keeps reading the producer into a backlog of up to 70 chunks (about seven seconds; the oldest go first beyond that), sends it in order once setup completes, then whatever is still queued (next_chunk’s catch-up) rather than coalescing it as a stall’s backlog. The gap becomes latency instead of lost speech.

A fresh start (Start, or Resume after a pause) holds audio the same way: the speech that begins while the socket opens and the provider confirms its setup goes into the same bounded backlog and out in order once streaming, so the speaker’s first words are not lost to the handshake. Only a recovery after a failure drops what queued meanwhile, as a stall’s backlog.

Device presence. Capture threads check that their endpoint still exists through audio::devices::PresenceCheck: at once when the device watcher reports a change, and otherwise on a fallback interval (5 s for the microphone’s enumeration, 1 s for loopback’s endpoint state), rather than polling on every wake.

Terminal provider exits cancel their source, finalize the pending turn, and then publish their terminal status. Cancellation stays local to that source, preserving the other half of a Both session. Capture returns runtime errors to its owner: a live session reports a session error, while preflight stops both test devices and reports on the test channel. Preflight workers wait until the active event is published, so an immediate device-open failure cannot be followed by a stale active event. With its receiver closed, preflight meters audio without resampling it or retaining a PCM buffer.

The operator’s src/lib/sessionController.ts serializes start and stop requests and resets a failed startup’s clock. A Stop requested during startup waits for startup to settle before stopping the core; repeated Stop requests share that operation.

Operator window

The operator page owns native event subscriptions, layout, launch and shortcuts, and delegates state to controller modules: preflightController.svelte.ts (device readiness, signal expiry, audio tests, and whether the chosen engine is ready: a stored key, an installed Whisper model on a supported processor, or the bundled demo), quitController.svelte.ts (tray and close prompts), overlayController.svelte.ts (appearance and window commands), sessionClock.svelte.ts, setupActions.ts (mode, source, language, engine, F2), deviceFailure.svelte.ts (capture failure recovery), recoveryOffer.svelte.ts (the start-up spool offer), zoomCaptions.svelte.ts (the share with Zoom: its status, and the caption link, held in memory only), updateCheck.svelte.ts (the new-version notice and its question), spendingGuard.svelte.ts (the cloud spending guard, on the session clock’s own tick) and nativeSync.svelte.ts (effects that mirror state to the core and the overlay). These controllers expose reactive getters and explicit actions; they do not subscribe globally when imported. Page teardown disposes the preflight timers and capture test. launchController.svelte.ts owns the rehearsal flag and the launch path: Start, Rehearse and Ctrl+Shift+Space read its one derived list of start blockers (busy, a run opening but not yet reporting, caption language, engine, application), so the three cannot disagree about whether a session can begin. operatorContext.ts hands the overlay and preflight controllers to the components that need them through a Svelte context, instead of props through every level.

The page renders OperatorToolbar (the window’s one bar, with SessionControls passed in as its actions), DeviceRecoveryBanner, SetupSheet (its four steps under src/lib/setup/) or LiveRail, IdleStage (with PreflightChecklist) or RunningStage (with LiveTurns), SettingsDialog and ZoomCaptionsDialog, over the shared primitives in src/lib/ui/. The transcript (TranscriptMonitor: TranscriptActions over TranscriptLog) is mounted once in the stage column for both states, so its copy window, follow state and an in-flight save survive Start and Stop. Every button is a ToolButton (variant default, primary, ghost, danger or warn; size sm, md or lg), drawn once under .ui-tool in app.css. Classes the components share (kicker, hint, divider, pref, rail-section) are global there too. app.css is also the only place a design value is written: colours (three surfaces, three lines, four text levels, the accent, warning, danger and room families), seven type roles, a six-step rem spacing scale and four radii. palette.test.ts, typeScale.test.ts and spacing.test.ts read the component stylesheets and fail on a value that bypasses them.

The colours come in two themes. :root is the dark one; :root[data-theme='light'] re-declares every colour for a white page and nothing else. theme.ts resolves the operator’s choice (System, Light or Dark) against Windows’ app mode, writes light or dark onto the root and tells the native title bar; an inline script in src/app.html makes the same decision before the first frame, so a light desktop never sees the dark ground while the modules load. The overlay carries no attribute and keeps the dark tokens. setTheme changes WebView2’s preferred colour scheme for the profile both windows share, which is why nothing styles by prefers-color-scheme.

shortcuts.ts holds the one table of shortcuts that the listener, aria-keyshortcuts and the printed key caps all read, and guards them against editable controls, dialogs, repeated keys and IME composition. CaptionAppearance.svelte renders the same appearance controls in the live rail and settings dialog, sharing persisted stores while keeping each contrast description’s accessible ID unique; CaptionPreview.svelte shares the presets and bright/dark samples. Settings uses the shared modal’s optional stable height, with a fixed header and tabs over a scrolling, keyed tab panel; other prompts size to their content. DateField.svelte shows localized year-month-day hints over ISO values, validates calendar dates before updating the bound value, and uses a native date input, excluded from the focus cycle, for its calendar button; that popup’s language can depend on the host runtime.

The eight appearance settings have one schema in appearance.ts: DEFAULT_APPEARANCE, normalizeAppearance, toOverlayConfig, its inverse fromOverlayConfig (which the overlay reads each push through, keeping what is on screen for a field that is missing) and the reading PRESETS. They persist one key each through persisted.ts, which reads and writes localStorage without ever throwing, and preferences.ts exposes them together as appearance with applyAppearance. stores.ts re-exports the four store modules: sessionStatus.ts, transcriptLog.ts, sourceActivity.ts and preferences.ts. Every other module that reads storage as it loads (history, the interface language, meeting profiles and the export format in exportFormat.ts) goes through persisted.ts too, so blocked site data cannot throw at import and leave a window blank. Names shared with the core (commands, events and the string values of serde enums) are checked against the Rust source by contract.test.ts.

Page-level tests render +page.svelte against Tauri’s own IPC mocks (src/lib/testing/tauriMock.ts, imported only by tests): the real tauri.ts runs, and the test plays the core, answering commands and emitting status and caption events as src-tauri does. src/routes/OperatorPage.svelte.test.ts scripts a built-in demo session from Start to Stop. These tests query by role and accessible name, not by page structure.

Two Playwright suites run on Windows, outside Vitest. e2e/style (npm run test:style) loads the production bundle in Edge, the engine WebView2 embeds, over a fake core installed in the page; its idle answers (src/lib/testing/idleCore.ts) are the Vitest mock’s too. It keeps text snapshots of computed styles in e2e/style/__snapshots__, which a failure reports property by property, and fails on any element whose content is wider than its box at the minimum window size, apart from two overflows listed as intended. e2e/native (npm run test:e2e) builds a debug exe whose identifier ends in .e2e, so its settings, history, models and WebView2 profile never touch a developer’s own, and drives both real windows over WebView2’s DevTools port. Each test starts on a first-launch profile and can quit and relaunch the app on it, as the placement spec does to check that the overlay reopens where it was placed. Both suites test the last npm run build.

ESLint (eslint.config.js) holds only typed checks that svelte-check cannot make: promises nobody handles, and Svelte’s reactivity mistakes. Its promise rules cannot see an async function passed as a Svelte event handler or as a () => void prop, because Svelte types handlers as returning any, so every such handler catches its own errors. knip (knip.jsonc) fails on unused files, exports and dependencies.

reading.ts throttles interim presentation per source at 450 ms in Steadier mode; finals flush immediately. Hold-time expiry affects the overlay only, and transcript storage is independent of presentation pacing and the display filter. profiles.ts validates local profile snapshots; MeetingProfiles.svelte rechecks devices before loading and excludes API keys, process IDs and rehearsal state, and operator-only placement commands bring a saved rectangle that no display can show back onto one. Profiles never start a session. liveActivity.ts classifies per-source connection, audio and caption observations; it is not voice activity detection. See usability.

Audio device lists carry stable endpoint IDs. audio/devices.rs forwards Windows notifications through a bounded worker queue; COM callbacks never enumerate or emit webview events. audioDevices.ts validates idle selections and migrates unambiguous legacy microphone names. Capture remains pinned to its opened endpoint when Windows changes the default. The explicit failure recovery controls stop and drain the session before starting again, preserving the transcript. See the hardware matrix for issue #28’s manual checks.

Optional persistent history

The renderer’s history coordinator creates a UUID at each Start and takes raw finalized lines from the transcript commit path, with session-relative cue timing. It queues and coalesces writes and remembers how many of each session’s lines are already on disk. It writes a session’s first line at once, later lines at most every 5 seconds, and anything waiting at Stop, quit, retry and the next Start. It retries failures, orders deletion after any in-flight write, finishes the record of a run whose sources all end by themselves, and keeps a tombstone so an active deleted session cannot reappear.

A session file is a log (file format). After the first write, append_history adds only the new lines; the first write and any write after a failure replace the file whole with the same flushed staging-and-replace operation as recovery. rename_history is serialized under the native history I/O mutex and changes only the title of the latest on-disk record, so a stale view cannot overwrite newer lines; it reads only a file’s header line to tell a log from the older format. list_history takes the [id, length] pairs the History tab already holds and sends contents only for files that are new or have grown, since a log only grows; it skips a file it cannot read with a warning rather than failing the list. createHistoryCache in history.ts decodes only what it was sent, so an unchanged session keeps its object and its search cache. Search normalizes text with NFKC, uses inclusive local-calendar dates and matches either caption language of a two-language session. Only the operator has permission to list, save, rename or delete these files, and UUID validation prevents renderer paths escaping the folder. History is opt-in, off by default and independent of crash recovery. See history.

Two caption languages

StartOptions.second_target_language adds lane 1 beside the target’s lane 0. SessionBuilder gives each source one client per lane; with two, the producer’s channel goes to a relay (relay_audio) that copies each chunk to both clients’ bounded queues without blocking, so no device is opened twice. Each lane client has a child of the source’s token: one failing leaves the other captioning, and the relay cancels the source — stopping capture — once both have gone. Caption and StatusUpdate carry lane; a status with no lane (a capture failure) applies to every lane of its source.

The renderer keys everything per stream by track (Origin | "<origin>:1"): current captions, pending turns, per-source state, the reading presenter and the overlay’s context. Lane 0 keeps the bare origin as its key, so a one-language session is keyed exactly as before. Committed lines of a two-language run record lane and language; groupTranscript groups each lane on its own and merges the paragraphs by first line, and exports section or label by language.

One voice captioned twice

With Both sources, a meeting played through the room’s loudspeakers reaches the room microphone too, and its remote speaker would be captioned twice. echo.rs sits where every caption leaves the core (Events::caption for AppHandle, before the Zoom tap and the windows) and drops the microphone’s copy, judged on the text alone: a microphone caption is an echo when at least two of its word pairs, and three in five, are pairs a system caption of the same lane has within four seconds of session time (characters stand for words in scripts written without spaces; a line of one or two words must appear whole, and only once finished). Pairs rather than words, because any two sentences share their common words; text rather than audio, because a person talking over the loudspeaker correlates with it about as well as its echo does, as OpenWhispr’s field logs showed. What it drops is on screen from the system source, so being wrong that way loses no words.

Both sides are compared on their last 200 words, split once and kept per turn, so a turn that streams for minutes is still caught and costs no more to check as it grows. The last 32 system turns of a lane are kept to compare with, and nothing forgets them on the clock: a microphone line local Whisper decodes behind a backlog can arrive long after its system line, with newer system lines between them, and is still judged by session time. A turn withdrawn as an echo stays withdrawn until its final, which is judged afresh, so a line near the threshold does not blink.

The engines do not finish in step, so a finished microphone line waits when the system source was sounding within four seconds of it in session time, sounding meaning loud on the meter (0.02) or covered by a system caption. Session time rather than the clock, because local Whisper with a backlog captions speech long after it was spoken. The wait is four seconds for a cloud engine and thirty for local Whisper, which decodes the two sources in turn in windows of up to 28 seconds; it ends early once a system caption starts more than four seconds after the line ends. Lines wait in a queue per caption language and leave from the front only, so captions keep their order: Whisper emits a window’s segments back to back, each a turn of its own, and all of them wait together. The first line of the queue is shown meanwhile, as an interim, and the microphone turn after the queue is kept back until it empties, because the windows commit what they show of a turn when the next one begins. A line is committed when its time is up or when the session ends (before its Idle). A withdrawal is the turn’s final caption with no text: the transcript commits nothing for it, and the operator stage and the overlay take the turn away. A committed line is never taken back. The guard emits under its lock, so a withdrawal cannot overtake the caption it withdraws. It is off unless the operator turns on Leave out the call heard by the room mic, offered under Both (StartOptions.drop_mic_echo), and then on only for a live session capturing both sources (SessionManager::start), never for the demonstration. Off, every caption passes as before.

Captions in Zoom

zoom.rs sends one caption language to a Zoom meeting’s third-party caption URL (captions in Zoom). It taps the one place every engine’s captions leave the core, Events::caption for AppHandle, so none of the providers, the demo or Whisper knows about it. The tap is cheap and cannot block: it filters by lane and origin, works out what is newly safe to publish, cuts it into captions of at most 120 characters and try_sends them into a queue of 64, counting a full queue as a drop. A sender task owns the queue, the HTTP client and Zoom’s seq counter, and reports a zoom-captions status after each delivery or drop.

Only text that cannot change is published. SessionManager::start tells the module whether the session’s provider only ever appends to an interim line (Gemini Live Translate, OpenAI and Mistral do; Gemini Transcribe and DeepL revise); for those, a completed sentence goes as soon as the next begins, and the rest of the line when it is final. Every other engine publishes final lines only. Each stream (origin, lane) remembers how far into its current turn it has published.

Sharing is independent of the caption session: it is started and stopped by its own commands, outlives Stop and Start, and costs nothing while off. The caption URL is a credential: the renderer holds it in memory only, the core never logs it (reqwest errors are logged without_url), and validation errors name the rule that failed, not the URL.

New versions, for copies installed from GitHub

The Microsoft Store and the Mac App Store update their copies; the Windows installer, the MSI and the Mac disk image do not. update.rs tells those copies, and only those, that a newer release exists (issue #217). Tell, don’t install: it shows the version and a link to its release page, and downloads nothing; there is no updater plugin and no signed update feed.

  • Which copies. update::installed_from_github, one function behind the per-feature cfg pattern: on Windows a process without package identity (GetCurrentPackageFullName answers APPMODEL_ERROR_NO_PACKAGE; any other answer counts as identity), so every MSIX, the Store’s and the sideloaded test packages, is left out; on macOS any build but the sandboxed Mac App Store one (support::app_store_build); elsewhere never. The Mac App Store forbids another update channel (App Review Guideline 2.4.5(vii)); the Microsoft Store does not, but its build already updates, and a notice there would send people to an installer that puts a second copy beside it. A copy that is not eligible gets UpdateStatus::default() from every command and its state file is never read or written.
  • Off until answered. The issue left the default open; the middle way was chosen: the switch (Check for new versions, Settings → App) starts unanswered, which means off. From the second launch (counted by the core, once per process, so a reloaded window is not a launch) the start screen shows one line, Check for new versions? This asks GitHub once a day., with Turn on and No thanks, until it is answered. Nothing is requested before Turn on.
  • When. The operator window asks check_for_update five seconds after it loads and, while a session runs, again every minute until it has ended. The core decides: it refuses without a request unless the copy is eligible, the switch is on, SessionManager::is_active is false and a day has passed since the last attempt (failed ones count, so a failure is retried the next day; a last check in the future, after the clock was set back, does not hold it off). One check runs at a time.
  • What it asks. One unauthenticated GET https://api.github.com/repos/fmadore/Live-translation/releases/latest from Rust with the core’s reqwest (native TLS, the system proxy), 15 seconds at most, no redirect, a body of at most 1 MiB, and a User-Agent of the app’s name and version alone. The webview’s CSP keeps connect-src 'self'. That endpoint leaves out drafts and prereleases; a tag that still reads as one (v1.15.0-rc.1, or prerelease: true) is ignored, and anything that is not exactly vMAJOR.MINOR.PATCH is malformed. Versions are compared field by field, by a dozen lines rather than a crate. Every failure is logged at info and shown nowhere.
  • The trust boundary for the release page. open_release_page takes no argument, as open_support_page takes none: the core builds https://github.com/fmadore/Live-translation/releases/tag/v<X.Y.Z> from the three numbers it parsed and hands that to the shell. The answer’s own html_url is never read, and the renderer cannot name a page. The state file keeps versions as text and parses them again on every read, so a damaged or edited file cannot put anything else into a status or a URL.
  • State. update-check.json in the app’s local data folder, replaced whole through atomic_file: the answer (unanswered, on, off), the launches counted until it is given, the last attempt’s time, the newest version seen and the one hidden with Not now. Kept by the core rather than in webview storage, so the core alone decides whether a request goes out. The notice shows the newest version seen while it is newer than the running one and than the skipped one, so installing the update, or a newer release, clears or replaces it.

The interface (updateCheck.svelte.ts, UpdateNotice.svelte, UpdateSettings.svelte) shows the notice and the question on the start screen only while no session runs, under a live region mounted a render before its sentence, and the switch, the notice and the last check’s time in Settings → App. In a browser preview, and on a store build, it shows nothing.

Responsive caption overlay

The overlay route’s overlayCaptions.svelte.ts owns current and previous turns per origin, a bounded in-memory history (12,000 characters per origin), their expiry and the reading-pace presenter; overlayPlacement.svelte.ts owns move mode and its keys, and OverlayMoveChrome.svelte draws it. The persisted overlay.captionLayout preference defaults to Fit window and reaches the overlay in OverlayConfig through overlayController.svelte.ts.

A push reaches only listeners already registered, so the overlay says when it can hear: once its listeners resolve it reports ready, and nativeSync.svelte.ts answers with a whole configuration (appearance, both caption languages, the interface language and move mode). An overlay that loads after the operator’s first push, at a cold start or after a WebView2 reload, therefore misses nothing. Move mode can also be left from both ends at once: a push carrying interactive: true (a colour drag, say) can cross the overlay’s own Lock on the way. The overlay counts its own exits from move mode and reports the count; every push hands back the last count the operator heard (moveExitsSeen), and the overlay ignores a push to stay in move mode that is behind it.

Pushes are coalesced to one per animation frame (or 100 ms, for an operator window hidden to the tray, which gets no frames), so a colour drag costs the overlay one re-read a frame rather than one per input event; move mode goes out as it stands when the push is sent. The overlay hands the hold time and the reading pace on to its captions only when they change, since setting them restarts every expiry timer and releases paced text.

The overlay window is created centred (tauri.conf.json) and paints nothing until there are captions or move mode, neither of which can start before the operator window has mounted. So the remembered placement lives in the interface like any other preference: overlayGeometry.ts keeps physical rectangles under overlay.geometry, one per display layout and at most eight, most recently used first. A layout is the signature display_layout (placement.rs) builds from the sorted monitors’ positions, sizes and scale factors, the work area left out. overlayController.svelte.ts saves the overlay’s rectangle when move mode ends with Done or the overlay’s own Lock/Enter (not Escape) and after a profile places it, never on move events, and restores once as the operator window mounts: the current layout’s entry, otherwise the most recent, always through set_overlay_placement. That command applies a rectangle the room can see as it was made, a strip stretched across two displays included, and gives any other the display watcher’s rescue (below). It moves the window before sizing it, because crossing to a display with another scale factor makes Windows rescale it (WM_DPICHANGED).

Displays can also change under a running app (issue #137). placement.rs polls the monitors about once a second, including their work areas, and once a change has held for two polls it rescues an overlay left unusable (its centre on no monitor, or larger than the one it is on) into the work area of the monitor nearest its centre, then emits displays-changed with the new layout signature. The operator window answers that with the layout’s own remembered placement, if it has one, and never saves the rescued rectangle, so the projector’s entry survives a lecture given on the laptop alone. recover_overlay_placement runs the same rescue on demand: before move mode, before showing a hidden overlay and when move mode ends. Escape in move mode restores the entry rectangle only if it still lies on a connected monitor.

  • Fit window. OverlayCaptionLine.svelte measures candidate text in a hidden paragraph with the visible text’s font, line height, available width and live-caret footprint. captionLayout.ts finds a fitting suffix, preserving the newest words and handling long unbroken tokens. Viewport size, measured row width and font changes trigger refitting. Visible origins share the usable height after padding and row gaps, with system audio above the microphone.
  • Compact retains the previous-turn character budget and an adjustable typographic width.
  • Stable reading retains context per origin in a top-left viewport whose height is rounded down to complete lines, and scrolls by whole lines; font and resize changes re-measure. The context is trimmed only at a rendered line start: once 180 lines are hidden, the line component measures the live layout and hands back the offset that leaves 60, so no visible line re-wraps. A whole-session idle event clears it.

Display-only filler cleanup runs before rendering and does not mutate caption events or transcript records. cleanSpeech.ts compiles the operator’s word list into one whole-word matcher (createFillerFilter) and owns the list’s validation and storage; the list travels in every OverlayConfig push beside the appearance but is not part of it. Stable reading cleans each turn once as it joins the context, so a mid-session change to the toggle or the list applies to the live turn and new turns.

Expiry and trimming affect only the overlay; the operator transcript is never truncated. Behaviour, idle timers and placement mode are described in caption layout.

Leaving the app

lifecycle.rs owns what closing means; src/lib/quit.ts owns the order it happens in. The window’s X, Quit in the tray, and the core’s watchdog all run the same sequence, so none of them is a cheap path that skips a step:

  1. Claim it. ack_close, before anything is stopped.
  2. Hide instead? With Keep running in the tray on, closing hides the window and stops here: the session, the overlay and the transcript all carry on. The first hide explains itself in the window rather than as a toast, which Focus Assist or a full-screen slideshow could swallow. Escape on that explanation neither hides nor quits: the window stays open, and the explanation is still owed to the first hide.
  3. May this session end? Asked while it is still running, so ending an event’s captions is a decision rather than a mis-aimed click.
  4. Stop and drain. stop_session cancels capture and gives the providers a bounded window to hand over their last turn; prepareClose bounds the wait on that.
  5. Finalize. The in-flight turn is committed, then unsaved text gets Save / Discard / Cancel. A save that fails keeps the app open.
  6. Exit. confirm_close stops the session again, so releasing the capture devices does not depend on the renderer having got that far, then calls app.exit(0).

CloseGuard intercepts a close only while the front-end reports unsaved text, a live session, or the tray preference. Two rules stop it from ever producing a window that refuses to close: it is off by default, and an interception that nothing acknowledges within ACK_TIMEOUT is released. WindowEvent::Destroyed on the operator window exits the process, so the undecorated always-on-top overlay cannot outlive its controls. Hiding to the tray never reaches it: that window is hidden, never destroyed. Closing the overlay itself (Alt+F4 in move mode, Task View’s X) hides it too, and the core announces that as overlay-state with visible: false, so the operator’s toggle and the tray offer Show.

Tray

Tray behaviour is deliberately explicit: a normal minimize keeps Windows taskbar semantics, and the operator chooses Minimize to tray or enables Keep running in the tray when I close this window. A live session must never disappear silently. The menu always provides Open, Show/Hide overlay, Stop session and Quit.

tray.rs builds the icon and menu once, in setup. The menu holds no state of its own: session and overlay state live in the front-end and are written onto the live menu items through set_tray_state, so a menu that offers Stop session is a session that is running. The front-end also passes localized TrayLabels; the menu uses them, plus a disabled status item showing the elapsed session time. set_tray_state is synchronous, so it runs on the main thread; tray.rs remembers the text and enabled state last written to each item and skips unchanged writes, which leaves one status write per second during a session.

Open is handled entirely in the core, because showing a window needs nothing from the renderer and the menu has to keep working even if the front-end is wedged. Everything else needs session or transcript state, so it goes back over TRAY_COMMAND for the front-end to carry out.

tauri-plugin-single-instance is registered first in the builder chain: a second launch focuses the running window instead of starting a second process to fight over the same capture devices.

System-wide keys

The opt-in Pause and Show/hide overlay keys (usability) live in hotkeys.rs, on tauri-plugin-global-shortcut (RegisterHotKey on Windows, Carbon’s RegisterEventHotKey on macOS; neither is a keyboard hook or an event tap, and the app is told of these combinations only). The switch is a renderer preference, mirrored like Keep running in the tray: nativeSync pushes it with whether a session is running or paused through set_global_shortcuts, on mount and on every change, and the core holds the keys only while both are true. The command answers which keys are held and which the system refused; Settings names a refused one. It is synchronous, so registration happens on the main thread, where macOS requires it.

A press does what a tray entry does: the core emits tray-command (toggle-pause or toggle-overlay) and the operator window carries it out with the function its own shortcut and button call, so a pause still goes through pause_session and the session’s lifecycle lock, and the button labels and the tray menu follow the state that function changes. In the core, only a press (not a release) of a key it holds acts, and presses of the same combination less than 400 ms apart count as one, so a held key or a system that repeats acts once. There is deliberately no Start or Stop key.

Registration is Rust-only. The plugin’s JavaScript package is not installed and no window is granted a global-shortcut: permission (pinned in command_names.rs): a window that could register any combination would hear it pressed in every application. The decisions (which keys, when they are held, what a refusal reports, the quiet period) are pure functions tested against a fake registrar, so the tests reach no display server.

Security and privacy

Provider authentication happens in Rust. Each optional key has its own entry in Windows Credential Manager or the macOS Keychain, with an environment-variable fallback, and never enters the Svelte renderer, whose content-security policy blocks direct connections. Only debug builds load .env or honour the *_WS_HOST host overrides. Local Whisper sends no audio over the network and deletes its temporary audio file on close; its pinned model downloads are integrity-checked and available only to the operator window. The built-in demo opens no audio device, uses no network and needs no credential. Caption text reaches Zoom only while the operator shares it with a meeting. The developer operates no backend, relay, telemetry, analytics or crash-reporting service. The one request the app makes of its own accord is the new-version check of a copy installed from GitHub, once the operator has turned it on (above). See SECURITY.md and the privacy policy for what is stored and what leaves the machine.

The two windows are not equally trusted

The operator window and the overlay are separate webviews, and the overlay is the one an audience looks at. It needs to listen for captions, move itself, resize itself, restore its own click-through while the operator is placing it, and tell the operator window what happened on it. It needs nothing else: not the commands that read a provider key’s presence, start a billable session, write the transcript or quit the app (issue #31), and not emitting events or moving another window (B4).

Two things make the split real rather than documentary:

  • build.rs declares an app ACL manifest (AppManifest::commands, fed from src/command_names.rs), which generates an allow-<command> permission per command. Once an app has such a manifest, Tauri checks every one of its own commands against the calling window’s capability and rejects anything not granted; without it, app commands are only checked for remote origins.
  • capabilities/operator.json grants the operator’s commands to operator; capabilities/overlay.json grants overlay its own short list and two core permissions, core:event:allow-listen and core:event:allow-unlisten. No emit: with it the overlay could pass for the core, sending a tray-command that stops a billable session or captions that reach the transcript. So it reports a Lock, an Escape or a caption size chosen on it through report_overlay_state, which takes only the fields of overlay::OverlayState and which the core sends on as overlay-state. No core window permissions either: those commands take any window’s label, so they would let it move or resize the operator window. It reads its rectangle with get_overlay_placement and moves itself with overlay-only commands that act on the overlay window alone — start_overlay_drag (in place of data-tauri-drag-region), nudge_overlay, snap_overlay_to_bottom, undo_overlay_move (Escape) — besides set_overlay_click_through.

The tests in src/command_names.rs hold the three pieces together: they fail if a command is registered without a permission (which would be rejected at runtime the first time an operator used it), if a capability grants something that no longer exists, if the overlay’s permissions, core ones included, differ in any way from the list pinned there, or if either window is granted the global-shortcut plugin’s commands. overlayPlacement.svelte.test.ts checks that what the overlay sends in move mode is all in its capability.

To see the boundary work, open the overlay’s dev tools in npm run tauri dev and invoke a command it does not have:

await window.__TAURI_INTERNALS__.invoke('stop_session')
// stop_session not allowed on window "overlay", webview "overlay", URL: local
// allowed on: [windows: "operator", URL: local]
// referenced by: capability: operator, permission: allow-stop-session

Operational limits

  • Windows is the supported release target; native x64 and ARM64 packages are built.
  • CI contract-tests provider messages but does not call billable services.
  • Cloud caption accuracy and availability depend on the selected third-party provider. Local Whisper accuracy and speed depend on its model, language and the computer’s processor or graphics processor.
  • The built-in demo verifies product presentation and workflow, not microphone recognition.