Commit Graph

224 Commits

Author SHA1 Message Date
a5bc45e847 fix(cr-2026-04-22): list_transcripts accepts omitted arguments
Regression surfaced by the batch review: commit 8400128 switched
list_transcripts from unwrap_or_default to map_err(-32602). This
correctly errors on malformed payloads but also rejected the common
case where a client omits the 'arguments' field entirely — which
arrives as Value::Null, and serde_json::from_value does not
deserialise Null into a struct.

Short-circuits the Null case to Args::default() before attempting
deserialisation. Genuine shape mismatches ("limit": "twenty")
still return -32602 as the previous test asserts.

New regression test: tools/call with list_transcripts and no
arguments key must return a successful response.
2026-04-22 09:23:17 +01:00
b376b98f33 refactor(cr-2026-04-22): remove dead code and stale allow(dead_code) suppressions
2026-04-22 review MINORs and NITs:

- crates/core/src/providers.rs: delete entire module. SpeechToText /
  TextProcessor / ProviderRegistry were forward-looking traits that
  never got wired — the Transcriber trait in kon-transcription
  (A.2 #13) has since superseded SpeechToText, and the Registry
  pattern was redundant against LocalEngine. Keeping them as dead
  public surface signalled future direction that is no longer
  accurate.
- crates/core/src/types.rs: delete TranscriptMetadata. Forward-
  looking struct with an unfulfilled TODO; storage has evolved
  independently through v7/v8 migrations without adopting it.
- crates/ai-formatting/src/llm_client.rs: remove #[allow(dead_code)]
  from CLEANUP_PROMPT and format_dictionary_suffix. Both are
  actively called; the suppressions would hide future genuine
  dead-code warnings in this regression-sensitive prompt file.
- src-tauri/src/commands/live.rs: remove #[allow(dead_code)] from
  LiveStatusMessage. Every variant (Warning, Overload, Error,
  Finished) is constructed in the module today.
- README.md: update kon-transcription row from "SpeechToText
  trait" to "Transcriber trait" and mention the new streaming/
  module.

Workspace test gate green (225 lib tests across all crates).
2026-04-22 09:17:05 +01:00
840012822f fix(cr-2026-04-22): list_transcripts tool returns -32602 on malformed params
MAJOR from the 2026-04-22 review (crates/mcp/src/lib.rs:188-195):
the handler called serde_json::from_value(args).unwrap_or_default(),
so a request like { "limit": "twenty" } silently became the default
limit of 20. Every other tool handler in this file map_errs to
-32602 Invalid arguments; this one was the outlier.

Switches to the same map_err pattern. Empty params still
deserialise cleanly to Args::default (via #[serde(default)] on the
Option<i64> field), so callers that send no args are unaffected —
only genuinely malformed shapes now error.

Regression test: tools/call with list_transcripts and a
string-typed limit must return code -32602 with an "Invalid
arguments" message.
2026-04-22 09:14:42 +01:00
d25b095788 fix(cr-2026-04-22): MCP stdio replies with parse-error on malformed JSON
MAJOR from the 2026-04-22 review (crates/mcp/src/main.rs:26-30): the
stdio transport logged malformed JSON lines to stderr and continued
without sending any JSON-RPC response. Clients saw silence instead of
the -32700 Parse Error they could key off. handle_message has a
parse-error branch for shape mismatch, but it never ran for bytes
that failed to parse as JSON at all.

Exposes a new public helper kon_mcp::parse_error_response(detail)
that mirrors the existing internal error_response pattern, filling
id with null per JSON-RPC 2.0 §5.1 (parse error, no id recoverable).
main.rs now writes that response out before continuing the read
loop.

Regression test on the helper asserts: jsonrpc "2.0", id null,
code -32700, message starts with "Parse error" and includes the
underlying serde detail.
2026-04-22 09:13:33 +01:00
7ece0df0ac fix(cr-2026-04-22): CSP guard matches connect-src as exact directive name
MINOR from the 2026-04-22 review (build.rs:47-64): the guard used
strip_prefix("connect-src") to find the directive, which would also
match hypothetical future directives like connect-src-elem and
validate the wrong allow-list.

Switches to split_once(char::is_whitespace) on each directive and
requires the first token to equal "connect-src" exactly. Robust
against prefix collisions with any future CSP3 directive
additions.
2026-04-22 09:11:53 +01:00
53d303f4b7 fix(cr-2026-04-22): uncomplete_task reopens auto-completed parents
MAJOR from the 2026-04-22 review (database.rs:389-449):
complete_subtask_and_check_parent auto-completes a parent task when
the last child completes, but uncomplete_task only flipped the
requested row — reopening a child left the parent wrongly marked
done, breaking the "parent done iff every child done" invariant.

Wraps uncomplete_task in a transaction and, after flipping the
subtask, looks up its parent_task_id. If present, resets the
parent to done=0 as well. Scoped to "done=1" on the parent update
so an already-open parent is untouched.

Two regression tests:
- uncomplete_subtask_reopens_auto_completed_parent: the direct
  mirror of the existing subtask_crud_roundtrip completion flow.
- uncomplete_top_level_task_does_not_touch_siblings: ensures the
  parent-reopen branch is a no-op for tasks with no parent, and
  siblings without a parent relationship are unaffected.
2026-04-22 09:11:14 +01:00
93a7165dac fix(cr-2026-04-22): reject HTTP 4xx/5xx on non-resume download path
MAJOR from the 2026-04-22 review (model_manager.rs:161-262): reqwest
does not return Err on 4xx/5xx by default. The resume branch
validated 206/200 and errored on anything else, but the non-resume
branch skipped the status check entirely — a 404 or 500 body was
streamed into .part and atomically renamed over the destination as
if it were the model file. For models without a sha256 declared,
this failure mode was silent and catastrophic (the engine would
crash loading an HTML error page as GGML on next launch).

Adds an is_success() check in the non-resume branch: any non-2xx
returns KonError::DownloadFailed with the HTTP status in the
message, and (importantly) we return before File::create so no
.part file is left behind.

Test: spawn_500_server that responds 500 to any request; a fresh
(no .part, no sha256) download must Err with "HTTP 500" and leave
neither .part nor dest on disk.
2026-04-22 09:09:09 +01:00
b665754560 fix(cr-2026-04-22): read_wav surfaces sample decode errors
MAJOR from the 2026-04-22 review (wav.rs:135-145): read_wav used
filter_map(|s| s.ok()) on both integer and float sample iterators, so
any per-sample decode error (truncated payload, corrupted format
descriptor after a partial write) was silently discarded. Callers
received Ok with a short samples vec, losing audio without any signal
to investigate.

Switches to collect::<Result<Vec<f32>>>() with a map that converts
hound's per-sample errors into KonError::AudioDecodeFailed. First
error aborts the read rather than returning a partial vector.

Test fabricates the regression by writing a valid WAV and chopping
the last 10 bytes; the previous filter_map would have returned Ok
with a shortened vec, the new code returns Err.
2026-04-22 09:07:55 +01:00
6e9ed99b3a fix(cr-2026-04-22): recording_filename avoids same-second collisions
MAJOR from the 2026-04-22 review (audio.rs:236-257): filenames were
derived from SystemTime::now().as_secs(), so two recordings started
within the same second resolved to the same path — possible overwrite
or merge.

Extracts the filename generation into a private helper and appends
the sub-second nanosecond component. Format is now
`kon-<secs>-<nanos_in_sec>.wav`, e.g. `kon-1776828000-123456789.wav`,
which stays human-readable, sortable by timestamp, and effectively
uncollidable under any realistic live-capture pattern.

Two tests cover the regression:
- recording_filenames_are_unique_across_rapid_calls: 64 tight-loop
  calls must produce at least 32 unique names.
- recording_filename_has_expected_shape: prefix/suffix plus the
  zero-padded 9-digit nanos component.
2026-04-22 09:06:47 +01:00
a37caa2219 fix(cr-2026-04-22): paste_text_replacing snapshots and restores prior clipboard
MAJOR from the 2026-04-22 review (paste.rs:181-217): unlike
paste_text, the replace flow did not snapshot the user's clipboard
before writing the raw transcript. A successful revert left the raw
transcript on the clipboard and destroyed whatever the user had
copied before invoking it — inconsistent with paste_text's Handy-#921
contract (brief item #3).

Extracts the snapshot+restore pattern into two helpers shared
between paste_text and paste_text_replacing:

- snapshot_clipboard_text() -> Option<String>
- schedule_clipboard_restore(prior, transcript)

Both paste_text and paste_text_replacing now run the same
capture-before-stomp, restore-after-fire sequence. The restore-
guard (only restore if clipboard still holds the transcript we set)
is shared too, so a user who copies something new within the 300 ms
window is still respected.

DRY: removes ~15 lines of inline clipboard bookkeeping from
paste_text while making the replace flow identical.
2026-04-22 09:05:40 +01:00
0ea230fef4 fix(cr-2026-04-22 C2): VadChunker::flush returns Vec<VadChunk> and preserves mid-flush emissions
CRITICAL from the 2026-04-22 code review: RmsVadChunker::flush() was
calling consume_frame() on a zero-padded final frame via `let _ = ...`,
discarding any VadChunk the call emitted. If the padded frame triggered
end-of-utterance (silent tail + padding zeros push past
silence_close_samples) or max_chunk_samples (buffered speech + padding
push past the cap), the emitted chunk was lost; the outer state check
then either returned None or an empty closing chunk.

Changes the VadChunker trait flush signature from Option<VadChunk> to
Vec<VadChunk> so both the mid-flush emission (from consume_frame) and
the closing emission (from emit_active_chunk_and_close) can be
surfaced. Updates RmsVadChunker::flush to collect from both sites
and skip a zero-length closing emit when the hit_max continue variant
already cleared active_chunk.

Two regression tests land alongside:
- flush_preserves_hit_max_chunk_from_padded_final_frame: tight
  max_chunk, sub-frame speech tail; pre-fix dropped the chunk, post-fix
  emitted samples cover the full active-speech region.
- flush_preserves_end_of_utterance_chunk_from_padded_final_frame:
  silent tail near silence_close; padded zero frame closes the
  utterance inside consume_frame; pre-fix returned None.

No production callers yet — the VadChunker wiring in live.rs is a
deferred item from A.3. API change is clean within the repo.
2026-04-22 09:03:50 +01:00
e54f0404ce fix(A.4 #29): strip zero-width format chars in to_plain_text
Review feedback (MINOR): char::is_whitespace returns false for
zero-width format codepoints (U+200B ZWSP, U+200C ZWNJ, U+200D ZWJ,
U+2060 WORD JOINER, U+FEFF ZWNBSP / BOM). The original normalise
pass let them through to the LLM where they waste tokens without
contributing any natural-language content.

Makes the decision explicit: these chars STRIP entirely rather than
collapse to a space. Collapsing would silently insert a word break
where the source had none ("hello<FEFF>world" → "hello world"
would merge two words into a space-separated pair that the original
author did not intend). Stripping preserves the original token
boundaries and drops the invisible noise.

Three new tests:
- zero_width_format_chars_strip_entirely — exhaustive coverage of
  all five handled codepoints.
- zero_width_chars_do_not_break_adjacent_whitespace_collapsing —
  "hello <FEFF> world" still collapses to "hello world" (the
  strip does not leave behind an artefact that breaks the whitespace
  collapse pass).
- leading_bom_is_stripped — a BOM at segment start, the common
  artefact pattern when Whisper consumes an encoded file.
2026-04-22 08:37:43 +01:00
53fe848979 feat(A.4 #29): plain-text pre-formatter before LLM cleanup
New crates/ai-formatting/src/to_plain_text.rs module with one public
function: to_plain_text(&[Segment]) -> String.

Rules the function enforces:
- each segment's text is whitespace-normalised (any run of unicode
  whitespace collapses to a single ASCII space, so tabs, newlines,
  and NBSPs never reach the LLM),
- empty and whitespace-only segments are dropped,
- remaining segments are joined with a single ASCII space,
- the joined string is normalised again (so a segment ending in a
  space followed by one starting in a space does not produce a double
  space) and trimmed end-to-end.

pipeline.rs's inline join is replaced with this call. Whisper's
timestamp fields (Segment.start / .end) are carried separately and
never reach the LLM by construction — the "timestamps stripped"
half of brief item #29's acceptance falls out of using Segment.text
alone. The work the module actually adds is whitespace discipline
and the tested boundary (empty input, empty-only input, NBSPs,
pathological whitespace runs, idempotence, double-space at join
boundaries).

Source: Scriberr PR #288 — feeding raw Whisper JSON (with timestamps
and per-segment structure) degraded cleanup quality; plain-text
input raised it back.
2026-04-22 08:34:04 +01:00
4c1d368d05 fix(A.3 #25): guard sample_index_for_seconds against NaN and infinity
Review feedback (MINOR): the original <= 0.0 clamp caught negatives
and zero but not non-finite inputs. Rust's saturating float-to-int
cast turns f64::INFINITY into u64::MAX, which would park the capture
buffer origin beyond any reachable sample index and trim the whole
buffer forever if a future end_secs source ever produces infinity
(clock glitch, overflow upstream, corrupted timestamp in a pass).

Adds is_finite() check. NaN, +infinity, -infinity, and zero all
return 0, which downstream trim_buffer_to_commit_point treats as
no-op. Test covers all three non-finite cases.
2026-04-22 08:02:23 +01:00
ed90de3c93 fix(A.3 #21): preserve audio contiguity across max_chunk splits in RmsVadChunker
Review feedback (CRITICAL): when a chunk hit max_chunk_samples during
continuous speech, emit_active_chunk reset state to Idle. The next
1-2 loud frames of post-split continued speech went into onset_buffer
and were silently cleared if silence arrived before the 3-frame onset
threshold — 50-100ms of user audio lost at every max-chunk boundary
in long-continuous-speech scenarios.

Splits emit_active_chunk into two variants:

- emit_active_chunk_and_close: the existing behaviour. Used for
  end-of-utterance closes and end-of-session flush. Truncates trailing
  silence, resets state to Idle.
- emit_active_chunk_continue: mid-utterance split on max_chunk. Stays
  in State::InSpeech, clears active_chunk for continued accumulation,
  advances active_chunk_start by the emitted length so the next
  chunk's start_sample is contiguous with this one's end. No
  silence-trim (by definition still in speech — end-of-utterance
  takes priority).

Adds max_chunk_split_preserves_audio_contiguity test: feeds 17 frames
of continuous speech into a chunker with a 4-frame cap, asserts
(a) chunk[i+1].start_sample == chunk[i].start_sample + chunk[i].samples.len()
across every pair, and (b) the final emitted region reaches the end
of the fed speech with no sample loss.
2026-04-22 08:01:14 +01:00
4455e4d1b1 fix(A.3 #24): clamp LocalAgreement slices against latest.len() to prevent panic on shrinking passes
Review feedback (CRITICAL): LocalAgreement::push could panic with an
index OOB when a later pass arrived shorter than committed_count.
Concrete case: commit [a, b], next pass arrives [a] — lcp_len=1,
new_committed=max(1, 2)=2, then latest[2..] panicked because
latest.len()==1.

A Whisper re-transcription of an overlapping window can legitimately
collapse repeated segments, or the user can stop mid-utterance after
some tokens were already committed, both of which produce this
shape. The committed_count invariant still holds (non-shrinkage) —
it is the slicing that was unsafe.

Clamps every latest[..] slice against latest.len() before indexing.
committed_count stays at new_committed even when the pass is shorter:
non-shrinkage is relative to what we have already emitted, not to
the current pass length. newly_committed and tentative both return
empty when the shorter pass has nothing past the committed prefix.

Adds two regression tests:
- shorter_pass_after_commit_does_not_panic (commit 2, push 1)
- empty_pass_after_commit_does_not_panic (commit 1, push empty)
2026-04-22 07:59:27 +01:00
cea15c12c7 feat(A.3 #25): aggressive buffer trim tied to commit points
New streaming::buffer_trim module with two pure helpers:

- sample_index_for_seconds(end_secs, sample_rate) -> u64: converts
  LocalAgreement::last_committed_end_secs() into an absolute sample
  index. Defensive against negative end_secs (treats as 0) so a future
  clock-skewed timestamp cannot wrap to a huge u64.
- trim_buffer_to_commit_point(buffer, buffer_start_sample,
  commit_sample_index) -> new_buffer_start_sample: drains the prefix
  of the capture buffer that falls below the commit point and returns
  the new absolute-index origin.

Edge cases covered by tests:
- commit before buffer start → no drain
- commit equal to buffer start → no drain
- commit inside buffer → drain prefix, advance origin
- commit at buffer end → drain all, origin moves forward
- commit past buffer end → drain all, origin parks at commit (rare
  edge after a committer reset)
- sample_index_for_seconds rounds nearest, negatives clamp to 0
- integration with LocalAgreement::last_committed_end_secs

trim_bounds_buffer_over_long_session is the acceptance fixture for
the ufal #120/#102 failure mode: 100 cycles of 16_000 captured samples
with a 200-sample tentative tail per cycle, and the buffer stays below
2× the tentative envelope instead of growing to 1.6M samples.

Integration into src-tauri/src/commands/live.rs deferred to the
dogfood session that wires VadChunker and LocalAgreement end-to-end —
the trim is a one-line replacement at the maybe_dispatch_chunk drain
site once the committer is feeding it commit points.
2026-04-22 07:52:48 +01:00
da2340325f feat(A.3 #24): LocalAgreement-n commit policy
New streaming::commit_policy module implementing ufal's
LocalAgreement-n pattern: tokens emitted by the streaming ASR
pipeline stay tentative until N consecutive passes produce the same
prefix, at which point the agreed prefix commits.

Types:
- Token: text + absolute start/end seconds. PartialEq is text-only so
  identical words from overlapping Whisper windows compare equal even
  when their timestamps drift.
- CommitDecision { newly_committed, tentative }: the partition fed
  back to the live-session worker after each pass.
- CommitPolicy enum with LocalAgreement { n }. Default is n=2 (ufal).
- LocalAgreement: stateful committer with push/flush/reset and a
  last_committed_end_secs accessor. Brief item #25 uses the latter
  to compute the sample-index drain target for aggressive buffer trim.

Invariants exercised by tests:
- first pass is all tentative (need 2 passes to commit under n=2)
- two matching passes commit their common prefix
- divergent second pass commits nothing
- extending agreement commits only the newly-agreed tokens
- tentative tail tracks latest pass only (no stale guesses)
- committed prefix never shrinks, even if later passes contradict
- flush emits any tentative-but-not-committed tail at session end
- flush on empty history is a no-op
- reset clears all commit state
- n=3 requires three matching passes before anything commits
- CommitPolicy::default() is LocalAgreement { n: 2 }

Integration into src-tauri/src/commands/live.rs deferred — the
tentative/committed split needs the B-side 'tentative: bool' field on
LiveResultMessage.segments (workstream-B #24 UI contract) and
validation against real streaming captures before going live.
2026-04-22 07:50:18 +01:00
05eea41649 feat(A.3 #21): VadChunker trait + RMS backend (Silero deferred)
New crates/transcription/src/streaming/ module with:

- VadChunker trait: Send-bound, object-safe, push/flush/reset/
  next_sample_index. Same surface a future Silero backend will
  present, so live.rs wiring does not change when Silero drops in.
- VadChunk type: (start_sample: u64, samples: Vec<f32>) for
  commit-policy sample-offset bookkeeping in #24.
- RmsVadChunker: fallback backend the plan permits while the
  ort 2.0.0-rc.10 vs rc.12 ecosystem conflict blocks silero-vad-rust
  / voice_activity_detector. Tuned to match the existing
  evaluate_speech_gate behaviour (enter 0.003, exit 0.0014, 3-frame
  onset, 500 ms silence close, 2 s max chunk).

Key behavioural properties, each backed by a test:
- pure silence emits nothing
- samples between exit and enter thresholds never trigger onset
- a single loud frame does not start a chunk (sustained speech only)
- sustained speech followed by silence emits exactly one chunk
- hysteresis: a dip between enter and exit does not split a chunk
- max_chunk_samples caps continuous speech (Whisper never fed > 2 s)
- flush surfaces in-flight speech
- flush on an idle chunker emits nothing
- reset restores a clean state
- emitted chunk start_sample includes the onset buffer (Whisper sees
  the speech attack, not post-onset audio)

Open items tracked as follow-ups:
1. Silero backend via direct ort rc.12 bridge (Handy-style). Blocked
   on either ecosystem ort alignment or dedicated bridge session.
2. Integration into src-tauri/src/commands/live.rs. Deferred so
   threshold tuning can be validated against real microphone
   captures rather than synthetic constant-signal fixtures.
2026-04-22 07:47:30 +01:00
6f4adae56c fix(A.2 #19): only report audio_path when the WAV writer finalises cleanly
Review feedback: reported_audio_path was cached at writer-open time
and survived a mid-session writer drop. If an append error cleared
wav_writer (or hound's Drop ran instead of finalize), the Summary
still reported the path — risking StopLiveTranscriptionResponse
pointing at a file whose header did not reflect its data chunk.

Moves the decision to end-of-session. wav_writer.take() is inspected:
- writer present + finalize Ok → report the path,
- writer present + finalize Err → None, emit a Warning,
- writer absent (mid-session drop, or never opened) → None.

StopLiveTranscriptionResponse.audio_path now means "the recording is
known-good" rather than "a recording was attempted". Users can still
recover partial files via filesystem if needed; the warning toasts
already emitted by append_resampled_audio on write failure surface
that path implicitly.
2026-04-22 04:54:15 +01:00
e4adcc1832 fix(A.2 #13): propagate whisper feature from kon crate through to kon-transcription
Review feedback: src-tauri/src/commands/models.rs was still naming
load_whisper unconditionally, so a --no-default-features workspace
build (kon-transcription without the whisper feature) would have
compiled the transcription crate cleanly but failed in the kon crate
as soon as it tried to resolve the load_whisper symbol.

Adds a matching [features] section to src-tauri/Cargo.toml:
- default = ["whisper"]
- whisper = ["kon-transcription/whisper"]

and declares the kon-transcription dep with default-features = false so
the feature actually propagates rather than being forced-on by the
child crate's default. Cfg-gates the load_whisper import in models.rs
and adds a companion match arm that returns a runtime error when the
feature is off, keeping the API shape intact.

Verified with both cargo build -p kon and cargo build -p kon
--no-default-features.
2026-04-22 04:54:07 +01:00
f9b396a966 feat(A.2 #19): progressive WAV write during live capture
The Vec<f32> in-memory accumulator on run_live_session had three
failure modes: (a) a crash during transcription took the recording
with it, (b) RAM grew linearly with session length, (c) OOM killed
the capture thread silently.

New kon_audio::WavWriter wraps hound::WavWriter<BufWriter<File>> with
an append-friendly API and a 500 ms-granularity header flush. On any
abort after a flush the on-disk file is a valid, playable WAV. Unit
test (brief item #19 acceptance) simulates the abort with
std::mem::forget and asserts the pre-flush samples are recoverable.

Live capture now:
- resolves the destination path at start_live_transcription_session
  time via a new resolve_recording_path helper extracted from
  persist_audio_samples,
- opens a WavWriter before any samples arrive, sample rate taken from
  LocalEngine::capabilities() (#13 wiring) with 16 kHz fallback,
- feeds the resampler output through WavWriter::append inside
  append_resampled_audio — drops the writer with a user-visible
  warning if a write fails mid-session,
- calls flush() at stop (after resampler tail), finalise() on clean
  exit, and drops-to-last-flushed state on abort.

LiveSessionSummary.audio_samples → audio_path: the path is already
written by the time stop_live_transcription_session runs; no
post-session write step remains for live capture.
persist_audio_samples is kept for the offline save_audio command.
2026-04-22 04:39:44 +01:00
8b49d0fe9c feat(A.2 #13): replace SpeechBackend enum with Transcriber trait
New crates/transcription/src/transcriber.rs defines a Transcriber
trait (Send supertrait for spawn_blocking travel) with
TranscriberCapabilities (sample_rate, channels, supports_initial_prompt).
TranscriberCapabilities.sample_rate is load-bearing for the upcoming
progressive WAV writer (#19).

Concrete impls:
- SpeechModelAdapter wraps Box<dyn transcribe_rs::SpeechModel + Send>
  for Parakeet (and any future transcribe-rs-backed engine).
- WhisperRsBackend moves its transcribe_sync body into the impl,
  widening the signature from &self to &mut self so per-call
  WhisperState can be created cleanly through the trait object.

LocalEngine now holds Box<dyn Transcriber + Send>; dispatch in
transcribe_sync collapses from a match to a direct call. Adds
LocalEngine::capabilities() for the WAV-writer.

Cargo feature flag "whisper" (default on) makes whisper-rs, num_cpus,
and the whole whisper_rs_backend module optional. cargo check
--no-default-features -p kon-transcription now builds without pulling
whisper-rs-sys — the escape hatch brief item #6 / #13 called for on
Windows / non-AVX2 / cloud-only builds. load_whisper is cfg-gated
behind the same feature.

src-tauri/src/commands/models.rs load_model_from_disk returns
Box<dyn Transcriber + Send> instead of SpeechBackend; caller chain
(ensure_model_loaded, prewarm_default_model) is unchanged.

transcriber_trait_is_object_safe test lands alongside the trait as a
compile-time witness against future Self-returning / generic-method
additions.
2026-04-22 04:33:23 +01:00
dd98cb7994 fix(A.1 #8): make ResumeUnsupported test actually prove Range header was sent
Review feedback: the previous test would pass even if the Range-header
logic in download_file were deleted entirely, because File::create
truncates the stale .part regardless of which branch set
actually_resuming to false.

Tightens spawn_no_range_server to return HTTP 400 when the request
carries no Range header, and only return 200 + full body when Range is
present. A regression that stops sending Range now surfaces as a
download failure (empty body from 400, bytes != body assertion)
instead of silently passing through the truncation path.
2026-04-22 00:36:37 +01:00
6fd38932ce fix(A.1 #2): parse tauri.conf.json properly in CSP regression guard
Review feedback: the original guard substring-searched the whole file
after the first "csp" token, which (a) false-passes if any unrelated
JSON value elsewhere in the config happens to contain a localhost URL
and (b) false-fails if the CSP is ever re-serialised with escaped
forward slashes.

Switches to serde_json + a /app/security/csp pointer lookup, then
splits the CSP on ';', finds the connect-src directive, tokenises its
allow-list on whitespace, and requires an exact match for both
http://127.0.0.1:* and ws://127.0.0.1:*. The error now also includes
the current connect-src value so a developer who breaks it can see
exactly what needs restoring.
2026-04-22 00:35:33 +01:00
2371e73f18 test(A.1 #8): cover ResumeUnsupported restart path in transcription downloader
The downloader already handles servers that return 200 to a Range
request by falling through to a truncating File::create on the .part
path, discarding stale partial bytes. That branch had no dedicated
fixture test — the SHA mismatch and Range-honouring resume cases were
covered but the mirror / proxy that strips Range support was not.

Adds spawn_no_range_server (always 200, full body regardless of Range
header) and download_file_restarts_when_server_ignores_range. Writes 12
bytes of stale content to .part, kicks off a download, asserts the
final file matches the fresh body exactly (not stale-bytes-prefixed)
and the .part file is cleaned up.

Brings the transcription downloader to test-coverage parity with
crates/llm/src/model_manager.rs per brief item #8 ("test coverage
parity" acceptance).
2026-04-22 00:29:13 +01:00
f486ff4cbc feat(A.1 #2): build-time CSP regression guard for localhost LLM
Pins the connect-src CSP entries for http://127.0.0.1:* and
ws://127.0.0.1:* at build time. If a future edit to tauri.conf.json
strips the local-LLM permit, the kon crate fails to build rather than
shipping a binary whose webview fetch() silently 404s with an opaque
scope error (Vibe #438 / #487).

Closes item #2 of docs/whisper-ecosystem/brief.md — CSP widening itself
landed in an earlier commit; this is the regression-proofing the plan
calls for.
2026-04-22 00:26:15 +01:00
5c17544a63 fix(sounds): fall back to default volume on out-of-range input
resolveVolume previously clamped any value >=1 to full blast. If a
future settings change ever leaks a 0–100 scale through (instead of
0–1), the user gets jump-scared at max volume. Treat any v>1 as a
scale-drift bug and play at DEFAULT_VOLUME instead.

Also reject NaN / Infinity explicitly rather than relying on the
<=0 branch catching them.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 17:32:51 +01:00
59209bd181 ci(audit): add weekly cargo-audit + npm-audit workflow
Runs Mondays 06:00 UTC (plus workflow_dispatch) so any freshly
published advisory surfaces as its own failing run rather than
slipping into an unrelated PR's check.yml noise. npm audit is
gated to --audit-level=high to skip the low/moderate chatter that
doesn't warrant a bump.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 17:32:34 +01:00
697642fa4d ci(check): add svelte-check and workspace lib tests
svelte-check catches type/template errors Vite's build skips; cargo
test --workspace --lib runs our pure-unit suites (prompt contract,
hallucination filter, preset parsing) without GPU or runtime deps.
Test step is Linux-only so the Windows/macOS legs stay focused on
platform compile coverage.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 17:32:18 +01:00
ce2b4fdac6 feat(ai B.1 #15 + A.1 #28): cleanup presets and sequential-GPU guard
Some checks failed
check / cargo check (macos-latest) (push) Has been cancelled
check / cargo check (ubuntu-22.04) (push) Has been cancelled
check / cargo check (windows-latest) (push) Has been cancelled
check / svelte build + lint (push) Has been cancelled
Two new Settings → AI knobs that compose cleanly with what already
shipped (aiTier, LLM model, translator prompt framing).

**B.1 #15 — Named cleanup presets.** LlmPromptPreset enum
(Default / Email / Notes / Code) appends a short context hint onto
the CLEANUP_PROMPT just before generation. Presets shape tone and
structure ("email paragraph", "bulleted meeting notes", "preserve
technical terms") without licensing the content-editing the
translator-not-editor framing forbids. cleanup_transcript_text_cmd
now takes `preset: Option<String>` which runs through the new
LlmPromptPreset::parse (normalises aliases like "meeting-notes",
collapses unknown values to Default).

**A.1 #28 — Sequential-GPU guard.** New LocalEngine::unload drops
the backend + model_id so a subsequent load actually reclaims VRAM.
load_llm_model, load_model, and load_parakeet_model Tauri commands
grow an optional `concurrent: bool` argument. When concurrent is
Some(false), loading LLM first unloads whisper+parakeet, and vice
versa — prevents VRAM OOM on tight-VRAM setups. Default is the
previous parallel behaviour so nothing changes for multi-GB cards.
Transcribe-in-progress paths (transcribe_pcm, transcribe_file, live)
pass None, so mid-dictation model loads don't accidentally tear
down the LLM.

Settings UI (AI section):
- Cleanup preset segmented button + descriptive copy for each option.
- GPU concurrency segmented button with explicit trade-off text
  ("faster transitions vs fits in tight VRAM").

Frontend wiring:
- settings.llmPromptPreset flows from DictationPage's
  cleanupTranscriptIfEnabled into the Tauri command.
- settings.aiGpuConcurrency flows from both DictationPage (auto-load
  on record) and SettingsPage (manual load/unload buttons) as
  `concurrent: "parallel" === true` to the load commands.

Tests: three new preset cases in crates/ai-formatting/src/llm_client.rs
(parse aliases, suffix non-empty for non-default, default suffix
empty). All 139 existing lib tests still pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 17:12:48 +01:00
a57da0feb5 feat(llm B.1 #27): Test LLM button with classified error diagnostics
Some checks failed
check / cargo check (macos-latest) (push) Has been cancelled
check / cargo check (ubuntu-22.04) (push) Has been cancelled
check / cargo check (windows-latest) (push) Has been cancelled
check / svelte build + lint (push) Has been cancelled
The brief's pain point is opaque load failures: llama-cpp-2's errors
bubble up as raw C++ strings ("cudaMalloc failed: out of memory",
"invalid gguf magic"). A user seeing that has no path to recovery.

New backend command test_llm_model runs a staged diagnostic:
  1. Model not downloaded → `not-downloaded` + download hint.
  2. File size ≤90% of expected → `incomplete` (stalled download)
     + re-download hint. Matters because llama-cpp-2 can segfault
     on truncated GGUF rather than returning cleanly.
  3. Requested model already loaded → `ready`, no side effects.
  4. Otherwise attempt a real load. On failure, classify_llm_load_error
     maps the raw string to one of:
       - load-failed-vram         (OOM / cudaMalloc / allocation)
       - load-failed-corrupt      (GGUF magic / unsupported format)
       - load-failed-permission   (permission denied / access denied)
       - load-failed-other        (catch-all)
     Each category has a prewritten actionable hint pointing at the
     specific Settings surface (tier picker, re-download, file perms).

classify_llm_load_error is pure-string and unit-tested — 8 cases
covering the main categories plus edge cases (OOM alias, Windows
"Access is denied", unknown errors). Ordered narrow-to-broad so
overlap doesn't misclassify.

Settings UI gets a "Test" button in the AI section's action row,
visible whenever the model is downloaded (both downloaded-idle and
loaded states). Shows inline hint below the status line when the
test surfaces one. Refreshes both local and global LLM status after
the test since a successful test implicitly loads the model.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 17:04:11 +01:00
70b97c5273 feat(ui B.1 #20): sound cues on start / stop / complete via Web Audio
Some checks failed
check / cargo check (macos-latest) (push) Has been cancelled
check / cargo check (ubuntu-22.04) (push) Has been cancelled
check / cargo check (windows-latest) (push) Has been cancelled
check / svelte build + lint (push) Has been cancelled
Hands-off feedback for recording lifecycle: a short C5 pitch at
record start, a falling G4 at record stop, and a staggered C5–E5–G5
major third when the finalise flow completes. Synthesised at runtime
via the Web Audio API (OscillatorNode + linear-ramped GainNode
envelope) rather than shipping WAV assets — keeps the binary size
flat and lets us tweak timbre without touching bundled files.

Off by default. Settings → Output exposes the toggle with a volume
slider (0–100%, default 15%) and a "Test" button that plays the
completion cue so the user can confirm loudness without recording.

Hooked at three call sites in DictationPage:
- playStartCue after page.recording = true in startRecording
- playStopCue at the top of stopRecording
- playCompleteCue just before `saved = true` at the end of
  finaliseTranscription's transcript-present branch

All three no-op when settings.soundCues is false. The Web Audio
context is lazily constructed on first cue (most browsers suspend
it until a user gesture — Tauri's webview inherits that). If the
AudioContext can't be built we silently drop the cue rather than
throwing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 16:48:44 +01:00
1dd09e14ca feat(ai-formatting A.1 #26): detect prompt-loop repetition cascades
Some checks failed
check / cargo check (macos-latest) (push) Has been cancelled
check / cargo check (ubuntu-22.04) (push) Has been cancelled
check / cargo check (windows-latest) (push) Has been cancelled
check / svelte build + lint (push) Has been cancelled
ufal/whisper_streaming #161 documents the classic Whisper streaming
failure: on ambiguous audio the model falls into a prompt loop,
cascading a single token for 10+ words ("I I I I I I I I I I I…").
The chunk-boundary duplicate detector in live.rs doesn't catch
this — the repeat is within a single chunk, and the text is
technically novel so FTS is happy to keep it.

Fold the detection into is_hallucination as a third pass (after
HALLUCINATION_MARKERS substring-match and HALLUCINATION_TRAIL_PHRASES
exact-match). has_consecutive_repetition walks the token stream
(whitespace-split, lowercased) and returns true when any run of
≥REPETITION_RUN_THRESHOLD (4) identical tokens is found.

Threshold chosen deliberately: three consecutive matches appear in
normal speech ("no no no, that's wrong"), four almost never does.
Tests pin both sides — "I I I I I" detected, "no no no" allowed,
alternating patterns ("I am I am I am I am") allowed regardless of
length.

Phrase-level repetition ("thank you thank you thank you thank you")
is a documented companion failure mode but needs a sliding n-gram
matcher — deferred with a code comment flagging it.

No caller changes: post_process_segments already drops
is_hallucination hits when anti_hallucination is enabled.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 16:44:22 +01:00
f525004d05 feat(ai-formatting A.1 #22): expand hallucination blocklist for subtitle-training leakage
Some checks failed
check / cargo check (macos-latest) (push) Has been cancelled
check / cargo check (ubuntu-22.04) (push) Has been cancelled
check / cargo check (windows-latest) (push) Has been cancelled
check / svelte build + lint (push) Has been cancelled
Whisper was trained on subtitle corpora, so silence and room tone
trigger caption-style artefacts that the previous three-marker
blocklist ("[blank_audio]", "[music]", "[silence]") didn't catch:
"Thanks for watching!", "Please subscribe.", "ご視聴ありがとうござ
いました", "♪♪♪", etc. Documented in WhisperLive #185 / #246 and
ufal/whisper_streaming #121 as the top streaming-transcript-quality
issue after chunk-boundary repeats.

HALLUCINATION_MARKERS widens from 3 to 16 entries: all common
bracketed non-speech tags (applause / laughter / inaudible /
background noise / sounds), parens variants, and musical notation
(♪ / ♫). Still contains-match so the marker triggers even when
Whisper wraps it in other noise.

HALLUCINATION_TRAIL_PHRASES (renamed from AUTO_THANKS_PHRASES) jumps
from 4 to ~30 entries: YouTube sign-offs, subtitle-credit leakage,
and the two most common non-English variants (Japanese "thanks for
watching" + MBC Korean news sign-off). Stays exact-match so
legitimate dialogue containing "thanks" or "subscribe" mid-sentence
never gets dropped — a new regression test pins that invariant.

The <15-char length gate on trail phrases is removed; some of the
new entries (e.g. "please subscribe to our channel.") are longer.
Exact-match against a known list is safety enough.

No caller changes: post_process_segments already drops segments for
which is_hallucination returns true when anti_hallucination is on.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 16:41:55 +01:00
ad311d278f feat(sidebar B.1 #31): visible LLM status chip with live state
Some checks failed
check / cargo check (macos-latest) (push) Has been cancelled
check / cargo check (ubuntu-22.04) (push) Has been cancelled
check / cargo check (windows-latest) (push) Has been cancelled
check / svelte build + lint (push) Has been cancelled
The LLM runtime has been quiet since it shipped in Phase 3 — users
had no surface-level signal that cleanup was loaded, warming, or
actively generating. Settings has verbose status text internally,
but a dictation-flow user never opens Settings during a run.

New: a shared $state store drives a small chip in the sidebar that
reflects the true LLM state in ≤500 ms of any transition (brief
item #31 acceptance). Five states:

  off        → hidden (user has aiTier === "off")
  warming    → model download or first load in flight; amber pulse
  ready      → loaded + idle; green dot
  generating → cleanup_transcript_text_cmd or
               extract_tasks_from_transcript_cmd in flight; accent
               pulse with Sparkles icon
  error      → last operation failed; red dot with AlertTriangle

The store exposes three calls: refreshLlmStatus(aiTier) (polls the
backend), markGenerating(detail) / markGenerationDone(success).
DictationPage wraps its cleanup + extract calls in mark-generating
pairs. SettingsPage's LLM load / unload / delete / download paths
also refresh the global store so Settings-initiated transitions
surface in the sidebar immediately. The chip collapses to a
dot-only compact form when the sidebar is collapsed.

No backend changes — everything wires onto the existing
`get_llm_status` Tauri command.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 16:40:02 +01:00
ae4c1e3c6d feat(preview B.1 #17): raw-transcript revert button in preview overlay
Some checks failed
check / cargo check (macos-latest) (push) Has been cancelled
check / cargo check (ubuntu-22.04) (push) Has been cancelled
check / cargo check (windows-latest) (push) Has been cancelled
check / svelte build + lint (push) Has been cancelled
Kon's ideology rule: raw Whisper output is the source of truth; LLM
cleanup is additive, never destructive. The preview overlay already
tracks both rawText and finalText across the listening → live →
cleanup → final phases — but until now the user had no one-click path
from final to raw if cleanup changed their meaning.

Frontend: a context-aware "Use raw" / "Copy raw" button appears in
the preview overlay's final phase, only when rawText and finalText
actually differ (Raw format mode or LLM-off leaves the button hidden).
Two behaviours depending on how the transcript reached the target:

  - settings.autoPaste = true  →  invoke paste_text_replacing, which
      sends the platform's undo keystroke to the focused app,
      waits UNDO_PASTE_GAP_MS (60 ms) for the compositor / app to
      process it, then pastes the raw transcript. The preview hides
      itself beforehand so the keystroke doesn't race focus
      (existing Wayland-hardening path).
  - settings.autoPaste = false →  nothing was pasted in the first
      place, so just overwrite the clipboard with raw. User's own
      paste yields raw.

Backend: new paste_text_replacing Tauri command plus a mirror of the
paste-backend matrix for undo (wtype -M ctrl z / xdotool key ctrl+z /
ydotool keycodes 29:1 44:1 44:0 29:0 / osascript cmd+z / SendKeys '^z').
Reuses the pick_linux_backend_order Wayland-vs-X11 preference.
Registered in the Tauri command handler.

Acceptance per the brief: "after paste, Ctrl+Z within 5 s replaces
LLM output with raw transcript" — satisfied via the 4 s auto-hide
window on the preview's final phase. The click extends auto-hide so
the user actually sees the confirmation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 16:29:43 +01:00
e10f435eb1 feat(transcription A.1 #23): silent warm-up inference after Whisper model load
Some checks failed
check / cargo check (macos-latest) (push) Has been cancelled
check / cargo check (ubuntu-22.04) (push) Has been cancelled
check / cargo check (windows-latest) (push) Has been cancelled
check / svelte build + lint (push) Has been cancelled
prewarm_default_model loaded the model and returned. That moves the
model into RAM, but whisper.cpp still allocates its context window +
fills GPU shader caches on the first inference call — producing the
~4–5 s cold-start latency documented in ufal/whisper_streaming #96
and #135 that feels like "Kon dropped my first sentence."

Extend the pre-warm task: after engine.load, feed one second of
silence (16000 zero samples at 16 kHz) through transcribe_sync with
default options. Silence returns empty segments; the *work* is the
context allocation, which now happens at app boot rather than on the
user's first hotkey press.

Net: the user's first real dictation should complete within ~1.5× the
steady-state RTF they'll see on subsequent runs, satisfying the A.1
#23 acceptance criterion. No new public API; all inside the existing
spawn_blocking.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 16:25:09 +01:00
42ba18a274 feat(ai-formatting B.1 #16): reframe CLEANUP_PROMPT as translator, not editor
Some checks failed
check / cargo check (macos-latest) (push) Has been cancelled
check / cargo check (ubuntu-22.04) (push) Has been cancelled
check / cargo check (windows-latest) (push) Has been cancelled
check / svelte build + lint (push) Has been cancelled
The previous prompt led with "You are a transcript cleanup assistant"
and listed cleanup rules. That framing quietly licenses the LLM to
treat cleanup as content editing — rephrasing for clarity, summarising
long sentences, "improving" phrasing. That's precisely the failure
mode OpenWhispr / Scriberr / Whispering users complain about ("the
LLM changed my meaning").

New framing lifts Whispering's published baseline: "translator from
spoken to written form — not an editor trying to improve the content."
Adds an explicit rule: do NOT improve, summarise, expand, or rephrase;
faithful written-form translation only, never content editing.

Both load-bearing concerns are now regression-tested — the existing
prompt-injection hardening assertions stay, and a new test pins the
translator framing + explicit no-editing rule against drift during
future refactors.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 16:23:06 +01:00
3790fa0c91 docs(readme): add project README with architectural profile
Some checks failed
check / cargo check (macos-latest) (push) Has been cancelled
check / cargo check (ubuntu-22.04) (push) Has been cancelled
check / cargo check (windows-latest) (push) Has been cancelled
check / svelte build + lint (push) Has been cancelled
Previously the repo had no root README. Pitch + architecture + crate-level
breakdown + routes + runtime stack + roadmap all lived in dated HANDOVER
docs + docs/brief/ + memory. This pulls the canonical overview into the
single place a new contributor / investor / cursory browser will actually
land first.

Sections: design principles, what Kon does today (shipped capabilities),
architecture (3-layer: Rust workspace → Tauri commands → Svelte UI),
crate-by-crate responsibilities, Tauri command surface, frontend shape,
runtime stack with pinned versions, platform support matrix, build + dev
setup, testing, pointers into docs/, roadmap, contributing notes, licence
placeholder, contact.

All claims are grounded in current code state (136 tests, 9 crates, 18
Tauri command modules, Tauri 2.10.3, whisper-rs 0.16, llama-cpp-2
0.1.144, sqlx 0.8.6). No marketing puff; preserves the ideology-firm
stance from memory.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 16:11:16 +01:00
jake
e75f676fc1 feat(docs): add brief and brand reference docs to phase-2 branch
Some checks failed
check / cargo check (macos-latest) (push) Has been cancelled
check / cargo check (ubuntu-22.04) (push) Has been cancelled
check / cargo check (windows-latest) (push) Has been cancelled
check / svelte build + lint (push) Has been cancelled
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-21 16:03:49 +01:00
8ba5641451 feat: add design system handoff to feat/design-system branch
Adds colors_and_type.css token system, fonts (Lexend, Instrument Serif Italic,
JetBrains Mono, Atkinson Hyperlegible Next, OpenDyslexic), SVG assets (wordmark,
waveform mark, grain), HTML preview spec cards, UI kit, and SKILL.md reference
under src/design-system/. Foundation for applying the new Kon visual identity.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 16:03:49 +01:00
Cursor Agent
0338495a57 fix(vocab): dedupe bulk import case-insensitively within the paste
Some checks failed
check / cargo check (macos-latest) (push) Has been cancelled
check / cargo check (ubuntu-22.04) (push) Has been cancelled
check / cargo check (windows-latest) (push) Has been cancelled
check / svelte build + lint (push) Has been cancelled
Previously the bulk import ran new Set(...) on raw trimmed strings
before lowercasing, so 'ACME' and 'acme' both survived the first
dedupe pass. Neither existed in the store, so both got added —
defeating the commit message's claim that pasting the same block
twice with different casing is a no-op.

Collapse case variants at the initial dedupe step using a lowercase
seen-set, keeping the first occurrence's casing as written.

Co-authored-by: jars <jakejars@users.noreply.github.com>
2026-04-21 16:00:03 +01:00
Cursor Agent
74062f8381 fix(capabilities): cover transcription-preview window in default ACL
The preview window was missing from the default capability's window
list. Its frontend calls core:window:allow-hide (getCurrentWindow().hide()
on dismiss / auto-hide) plus invoke('copy_to_clipboard') and a handful
of event listeners — none of those would have been permitted at runtime
because the capability never matched this window's label.

Add 'transcription-preview' alongside the other secondary windows so
the preview actually has access to the permissions it already relies on.
Regenerate gen/schemas/capabilities.json to match.

Co-authored-by: jars <jakejars@users.noreply.github.com>
2026-04-21 16:00:03 +01:00
Cursor Agent
ded8811ca9 feat(B.1 #10): detect focused terminal and switch to clipboard-only paste
Some checks failed
check / cargo check (macos-latest) (push) Has been cancelled
check / cargo check (ubuntu-22.04) (push) Has been cancelled
check / cargo check (windows-latest) (push) Has been cancelled
check / svelte build + lint (push) Has been cancelled
Extends commands/paste.rs::paste_text with a pre-keystroke check:
if GetForegroundWindow (Windows) / xdotool getactivewindow (Linux
X11) / 'tell System Events ...' (macOS) reports a focused app class
matching KNOWN_TERMINAL_CLASSES, skip the synthesised Ctrl+V and
return an outcome with copied=true, pasted=false, and a user-facing
message ('Terminal detected (kitty) — use Ctrl+Shift+V to insert').

Matches Handy #692: Kitty/Alacritty/Windows Terminal/Codex CLI all
double-insert the transcript when a PTY sees both a synthesised
Ctrl+V and the terminal's own paste hotkey. The terminal list is
ordered most-specific-first so 'windowsterminal' wins over the
generic 'terminal' needle.

Adds classify_terminal() as a pure helper + seven unit tests. The
platform probe (detect_focused_window_class) isolates the fragile
shell-out so the classification rule is test-covered without
needing a real desktop. Wayland doesn't expose a reliable
focused-window API to unprivileged clients, so it conservatively
returns None and the normal paste path runs — consistent with
Kon's Wayland-Pipewire lane.

Prior-clipboard restore (#3) is intentionally skipped when terminal
mode takes over: the user's path to insert the transcript is their
own paste, which needs the transcript on the clipboard.

Co-authored-by: jars <jakejars@users.noreply.github.com>
2026-04-21 15:59:01 +01:00
Cursor Agent
df58d98adc feat(B.1 #5): per-OS hotkey capability matrix with inline rejection copy
Adds src/lib/utils/hotkeyValidity.ts with validateHotkey(combo, os)
and wires it into HotkeyRecorder.svelte. Rules:

  - X11/Wayland/Linux: reject single-key combos unless the trigger
    is F13..F24 (the conventional global-shortcut escape hatch).
  - Windows: reject combos whose only modifier is a right-hand
    variant (RCtrl/RAlt) — matches Handy #966's failure mode where
    RegisterHotKey silently ignores them.
  - macOS: reject Fn-only combos and bare-key combos (non-function
    keys).
  - unknown OS: pass through — better to ship a flawed combo than
    reject one we can't validate.

When validation fails, the recorder leaves the previous known-good
hotkey intact and surfaces an inline warning-coloured sentence
explaining why, with actionable copy ("add a modifier", "use the
left-hand equivalent", etc.). The save button disappears because
settings.globalHotkey is never written to — no state drift.

Matches Handy #917 / #1019 / #966 / #956, brief item #5.

Co-authored-by: jars <jakejars@users.noreply.github.com>
2026-04-21 15:59:01 +01:00
Cursor Agent
8e5e034df1 feat(B.1 #4 UX): debounce hotkey press events by 120ms
A rapid double-tap of the global hotkey, evdev autorepeat, or a
sticky-key compositor quirk (KDE's 'slow keys') can all deliver
the same press twice within ~100ms. Without a guard, the recording
toggles into and out of the same frame and the capture is lost.

Gates the evdev 'kon:hotkey-pressed' forwarder in +layout.svelte
behind a 120ms debounce (Date.now()-based; no timers, so no tail
latency for a legitimate single press). The debounce is intentionally
shorter than a deliberate double-press cadence but longer than any
autorepeat interval we've seen in the wild.

The audio-stream-warming half of brief item #4 (Handy #1143) lives
in Workstream A's Phase A.3 warm-up WAV; this covers the UX side.

Co-authored-by: jars <jakejars@users.noreply.github.com>
2026-04-21 15:59:01 +01:00
Cursor Agent
f3a0673eaa feat(B.1 #3): snapshot prior clipboard and restore 300 ms after paste
Extends commands/paste.rs so that when auto-paste fires we:
  1. capture the user's existing clipboard text BEFORE overwriting
     it with the transcript (via arboard::Clipboard::get_text — a
     non-text clipboard returns None and the restore step is
     skipped, which keeps images / files safe),
  2. after the paste keystroke lands, sleep 300 ms,
  3. restore the snapshot only if the clipboard still holds the
     transcript we wrote — respects any Cmd+C the user did in the
     300 ms window.

Moves the decision to a pure should_restore(current, transcript)
helper with four unit tests. The existing paste-matrix regression
tests are unchanged.

Matches Handy #921 (workstream-B brief item #3). Coexists with the
Wayland preview-hide dance already in this file, and doesn't run
when the paste keystroke fails (transcript stays on the clipboard
for the user's own paste).

Co-authored-by: jars <jakejars@users.noreply.github.com>
2026-04-21 15:59:01 +01:00
Cursor Agent
cc3bffa72c feat(B.1 #11): versioned settings schema with forward migration
Adds src/lib/utils/settingsMigrations.ts exposing
loadSettingsWithMigration() / saveSettingsWithVersion() around a
{version, data} envelope in localStorage["kon_settings"]. The
migration chain is indexed by destination version so adding a v2
is one MIGRATIONS[2] = (prev) => next entry away from working.

Legacy bare-object settings blobs are treated as v0 and folded into
v1 identically to before — no user-facing reset — but an unreadable
blob now surfaces a single Settings reset toast instead of silently
dropping data.

Covers Handy #602 ('settings reset on update') and unblocks the
other B.2/B.3 SettingsState additions listed in
docs/whisper-ecosystem/workstream-B.md: every subsequent field
lands behind a MIGRATIONS step, so older Kon builds stay readable.

Co-authored-by: jars <jakejars@users.noreply.github.com>
2026-04-21 15:59:01 +01:00
Cursor Agent
db9e119c1b docs(phase4-ux): execution plan for Workstream B
Sequences the 13 B-scope items from docs/whisper-ecosystem/brief.md
into three phases (pre-emptive UX, feature pinches, LLM layer) with
stop-for-review boundaries between each.

Enumerates the Settings sections touched per item (net: +2 toggles,
+2 sub-cards, nothing invisible becomes visible), the new
SettingsState fields with defaults, the schema migration bump
(version 1 -> 2), and the explicit Workstream A dependencies +
stubbed fallbacks for each (#14 list_gpus, #30 streaming cleanup,
#31 llm-state-change event).

Co-authored-by: jars <jakejars@users.noreply.github.com>
2026-04-21 15:59:01 +01:00