Feature chore bug 005 #19
@@ -0,0 +1,543 @@
|
||||
# Memory — whispassist
|
||||
|
||||
> Generated: 2026-07-07 21:30:45
|
||||
> Total memories: **75**
|
||||
> Breakdown: fact: 3, decision: 10, goal: 1, preference: 1, context: 3, event: 1, learning: 24, observation: 2, artifact: 25, error: 5
|
||||
|
||||
---
|
||||
|
||||
## Instructions
|
||||
|
||||
*Standing rules, constraints, and guidelines to always follow.*
|
||||
|
||||
*No memories of this type.*
|
||||
|
||||
---
|
||||
|
||||
## Facts
|
||||
|
||||
*Verified information, project status, and established truths.*
|
||||
|
||||
### parakeet-rs (altunenes) DOES have a genuine increm...
|
||||
|
||||
parakeet-rs (altunenes) DOES have a genuine incremental streaming decode API for Parakeet-family models: ParakeetEOU and Nemotron structs thread real recurrent state between calls internally (EncoderCache: cache_last_channel/cache_last_time/cache_last_channel_len; decoder LSTM state_h/state_c; last_token) plus a 4s rolling audio ring buffer, so callers just feed sequential small chunks (160ms for EOU, 560ms for Nemotron) and get incremental partial text -- it is not naive re-chunking of a batch decoder. Source: github.com/altunenes/parakeet-rs src/parakeet_eou.rs and model_eou.rs, examples/streaming.rs (checked 2026-07-02).
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-02T20:09:27*
|
||||
|
||||
### WhispAssist app icon/branding: real logo provided ...
|
||||
|
||||
WhispAssist app icon/branding: real logo provided by user (paperclip mascot + purple speech-bubble-with-sparkles mark, WhispAssist wordmark). The app icon (title bar/taskbar/tray/installer) is cropped from just the small speech-bubble-with-sparkles mark, not the full marketing graphic or the paperclip mascot (too much fine detail to read at 16-32px). Updated twice: first a transparent-background crop, then a refined version on its own gradient purple background from a cleaner logo revision the user provided. Regenerated via ; that command generates iOS/Android/Appx/macOS outputs by default which must be deleted since WhispAssist is Windows-only (not referenced by tauri.conf.json). tray.png is a manual 32x32 export, not one of tauri icon's own output names.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-02T20:13:49*
|
||||
|
||||
### The EOU streaming variant used by parakeet-rs is a...
|
||||
|
||||
The EOU streaming variant used by parakeet-rs is a genuinely separate ONNX export, not a mode of the batch Parakeet TDT model: it's NVIDIA's own nvidia/parakeet_realtime_eou_120m-v1 (120M params, cache-aware FastConformer encoder + LSTM decoder, 80-160ms chunks, English-only, no punctuation/casing, emits <EOU> token). This is distinct from istupakov/parakeet-tdt-0.6b-v3-onnx (600M, the community ONNX conversion used for WhispAssist's originally-considered batch/full-file transcription path, which has the ~4-5min length limit). Both are downloaded separately; author's own code comment on reset_on_eou says 'I must admit that this is not work very well on my real world tests'.
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-02T20:09:30*
|
||||
|
||||
---
|
||||
|
||||
## Decisions
|
||||
|
||||
*Architectural choices, approach selections, and their rationale.*
|
||||
|
||||
### M4.4 (MS Graph calendar source, T8.9, FR-CAL-6) SH...
|
||||
|
||||
M4.4 (MS Graph calendar source, T8.9, FR-CAL-6) SHIPPED 2026-07-07 on branch feature_chore_bug_005 (commits 83cb30e..7df76df + 1cf0be1). This LIFTS the 2026-07-02 'T8.9 on hold' decision — user explicitly asked to build it in this session, overriding the earlier hold. Implementation: calendar::GraphSource implementing CalendarSource, reusing sync::oauth's provider-agnostic PKCE/loopback machinery (added a 'graph-calendar' OAuth provider entry, made sync::resolve_access_token pub(crate) for cross-module reuse) rather than building new OAuth plumbing. This completes all of milestone M4 (M4.1 chunked upload, M4.2 multi-language, M4.3 Dropbox/Box, M4.4 Graph calendar).
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-08T02:22:48*
|
||||
|
||||
### WhispAssist roadmap: T8.8 (at-rest encryption / va...
|
||||
|
||||
WhispAssist roadmap: T8.8 (at-rest encryption / vault) and T8.9 (Microsoft Graph calendar) are ON HOLD per user decision (2026-07-02). Consequence: Phase 9c (T9.12 client-side encryption before upload) is blocked since it depends on the T8.8 vault - skip 9c for now. Building Phase 9 (remote sync) starting with 9a (WebDAV).
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-03T01:01:49*
|
||||
|
||||
### WhispAssist GPU acceleration decision (2026-07): w...
|
||||
|
||||
WhispAssist GPU acceleration decision (2026-07): whisper.cpp GPU transcription via VULKAN as primary cross-vendor path — ONE binary covers NVIDIA+AMD+Intel (whisper-rs 'vulkan' feature). whisper-rs GPU features: cuda (NVIDIA-only, CUDA toolkit at build), vulkan (cross-vendor, Vulkan SDK at build + vulkan-1.dll loader shipping with every GPU driver), hipblas (AMD/ROCm LINUX-ONLY, unusable on Windows), metal (Apple). KEY: whisper.cpp GPU backends are COMPILE-TIME/static (cannot download runtime on-demand like the ort load-dynamic NPU path); binary must be built with the feature. Vulkan is default GPU build; CUDA is optional NVIDIA-only turbo variant LATER (user: 'we will do cuda later'). Vulkan degrades to CPU if no GPU present.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-05T22:03:34*
|
||||
|
||||
### WhispAssist roadmap: T8.8 (at-rest encryption/vaul...
|
||||
|
||||
WhispAssist roadmap: T8.8 (at-rest encryption/vault) and T8.9 (MS Graph calendar) ON HOLD per user (2026-07-02). Consequence: Phase 9c (T9.12 client-side encryption) blocked (needs T8.8 vault) - skip for now. Building Phase 9 remote sync starting with 9a WebDAV.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-03T01:02:11*
|
||||
|
||||
### In WhispAssist's calendar module, CalendarSource::...
|
||||
|
||||
In WhispAssist's calendar module, CalendarSource::import() is a synchronous trait method (matches PstSource's blocking subprocess call). GraphSource (MS Graph, async reqwest HTTP) bridges into that sync signature via tauri::async_runtime::block_on inside fetch_events, and callers run the whole import() call inside tauri::async_runtime::spawn_blocking (same pattern commands.rs already used for PstSource's readpst subprocess) — avoids making CalendarSource async just for one source. Kept a separate WA_GRAPH_CALENDAR_BASE_URL env var (distinct from sync's WA_GRAPH_BASE_URL used by OneDriveTarget) so calendar and sync tests never race on the same process-global env var in cargo test.
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-08T02:22:55*
|
||||
|
||||
### WhispAssist PST usability fixes (2026-07-06, commi...
|
||||
|
||||
WhispAssist PST usability fixes (2026-07-06, commits 00de9d3/9d757be/75ec24d): (1) calendar path is now remembered in Settings (pst_last_path field) so the user doesn't re-browse every launch; (2) added an opt-in 'auto-sync on launch' checkbox (pst_auto_sync) that re-imports the remembered path once at startup - deliberately a ONE-SHOT pass mirroring the existing sync-job-resume pattern in lib.rs, NOT a periodic timer, because NFR-RES-1 ('no polling timers when idle') is enforced consistently everywhere else in this codebase (every startup task has a comment noting this). User asked about a periodic 'read frequency' option too; I declined to build that specific piece and explained the NFR-RES-1 conflict rather than silently building or silently dropping it.
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-06T20:40:52*
|
||||
|
||||
### Completed a full UI/UX redesign of WhispAssist: se...
|
||||
|
||||
Completed a full UI/UX redesign of WhispAssist: semantic CSS design-token system (light/dark, WCAG AA verified), all emoji/Unicode icons replaced with @lucide/svelte SVG icons, segmented Monitor/Sun/Moon theme toggle defaulting to system preference, custom theme-aware scrollbars. Informed by researching Granola and Meetily's UIs; kept WhispAssist's 3-pane layout since diarization/speaker-naming already beats both competitors.
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-02T20:13:34*
|
||||
|
||||
### WhispAssist M1 feature-briefs decomposition (2026-...
|
||||
|
||||
WhispAssist M1 feature-briefs decomposition (2026-07-06, docs-only, branch feature_chore_bug_004). KEY INSIGHT: M1 is heavily scaffolded already, do NOT re-create — IPC types FeatureBrief/FeatureBriefInfo/ContextExcerpt (models.rs), api.ts bindings createFeatureBrief/listFeatureBriefs/getFeatureBrief/setBriefExposed, the 4 commands registered in lib.rs, DB tables feature_briefs + mcp_access_log (migrations/0003_ai_mcp.sql), the briefs/<id>.json schema (docs/03-data-model.md), and the FeatureBriefBuilder trait (docs/04-api-contracts.md) ALL EXIST; only the 4 command bodies return not_implemented(). REMAINING to build: (1) Store methods insert_feature_brief/list_feature_briefs/get_feature_brief_row/set_brief_exposed; (2) a new non-streaming LlmProvider::complete(system,user)->String primitive (mirrors suggest_tags; impl Ollama+OpenAiCompat, Anthropic later); (3) FeatureBriefBuilder in a new briefs module (strict '## Title/## Problem/## Desired Outcome/## Acceptance Criteria' prompt like RESPONSE_FORMAT_INSTRUCTIONS + parse_brief mirroring parse_summary); (4) the 4 command bodies (add state: State<AppState>, Tauri injects it, api.ts unchanged); (5) UI in SummaryPanel; (6) golden-transcript tests. KEY DESIGN DECISIONS: context_excerpts are VERBATIM transcript substrings (grounding invariant enforced by the golden test), selected by keyword overlap, NOT model paraphrase; the on-disk file is a sealed BriefFile envelope {schema,generated_at,provider,model,...fields,source} indexed by the feature_briefs table (file=truth, row=index); write file+row only AFTER a successful distill (no partial artifacts on LLM failure). Full implementation-ready checklist in docs/05-roadmap.md M1; JSON schema in docs/03-data-model.md; tests in docs/06-test-strategy.md P10.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-07T04:28:36*
|
||||
|
||||
### Decision: NOT pursuing NVIDIA Parakeet or DirectML...
|
||||
|
||||
Decision: NOT pursuing NVIDIA Parakeet or DirectML/NPU acceleration for WhispAssist transcription near-term, as of 2026-07-02. Researched achetronic/parakeet (Go, Linux-only, dead end) and altunenes/parakeet-rs (Rust, built on ort, has genuine streaming via a separate EOU 120M model with real internally-threaded encoder cache and LSTM decoder state). Reasons not to pursue now: (1) DirectML support for this model family is unproven - zero reports of anyone running it, and there is a live unresolved ONNX Runtime bug (microsoft/onnxruntime issue 19837) producing wrong output on DirectML for the exact LSTM+Einsum op combination these models use; (2) DirectML itself is now in Microsoft maintenance mode, with new NPU/GPU work moving to Windows ML instead, which calls WhispAssist's existing ADR-0004 (ort + DirectML for NPU) into question independent of Parakeet; (3) Parakeet streaming needs a continuous per-meeting state machine fed small sequential chunks, fundamentally incompatible with WhispAssist's current stateless independent 4-second-window architecture - a real rearchitecture, not a swap, and it would lose whisper.cpp's crash-recoverable-per-window property; (4) competitor Meetily does not actually do live Parakeet+hardware-acceleration either - they only use it for offline batch re-transcription. Recommended future path if revisited: CPU-only Parakeet-EOU streaming spike first to validate the rearchitecture and quality tradeoffs (EOU is English-only, no punctuation/capitalization), treat NPU acceleration as a separate track that should probably target Windows ML rather than raw DirectML.
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-02T20:14:37*
|
||||
|
||||
### WhispAssist CUDA + AMD-non-Vulkan acceleration PLA...
|
||||
|
||||
WhispAssist CUDA + AMD-non-Vulkan acceleration PLAN (2026-07-05): whisper.cpp bakes in exactly ONE GPU backend at compile time. Universal build=Vulkan (all vendors). NEW: NVIDIA-turbo installer variant = whisper.cpp CUDA (feature already declared Cargo.toml:94) — but a CUDA build has NO Vulkan, so AMD/Intel GPUs in that variant need a non-Vulkan accel path. DECISION (recommended, user was away/didn't confirm): AMD-non-Vulkan = DirectML via the EXISTING ort/ONNX NPU path (OnnxNpuTranscriber generalized to accept EP: OpenVINO-NPU vs DirectML-GPU+device_id). DirectML works on any DX12 GPU, load-dynamic (no new build toolchain), one binary, degrades to CPU. hipBLAS/ROCm DEFERRED (narrow gfx coverage, fragile on Windows, needs 3rd installer). CORE CODE CHANGE: add AccelPath enum {WhisperCuda,WhisperVulkan,WhisperCpu,OnnxOpenVino,OnnxDirectML} + resolver in hardware/mod.rs from (BackendId+cfg!(feature)+runtime readiness); transcriber factory switches on it. This also CLOSES the known detection-honesty gap (GPU marked available from DXGI regardless of compiled feature -> no-op GPU routing). PHASES: P0 detection-honesty+AccelPath (small, no hw, do first), P2 AMD/Intel DirectML (validate on Intel Arc iGPU locally), P1 CUDA (needs NVIDIA hw/CI). ort needs 'directml' feature + an onnxruntime.dll built with DML EP in the runtime bundle; DirectML.dll ships with Win10 1903+.
|
||||
|
||||
*Confidence: 0.85 | Status: active | Created: 2026-07-05T23:28:58*
|
||||
|
||||
---
|
||||
|
||||
## Goals
|
||||
|
||||
*Objectives, targets, and milestones to track progress.*
|
||||
|
||||
### WhispAssist NEXT STEPS — CPU transcription slownes...
|
||||
|
||||
WhispAssist NEXT STEPS — CPU transcription slowness testing round (open bug): the full transcribe_file path takes ~90s for a 6.3s clip on a 14-thread CPU with base.en (should be ~2-3s). This is PRE-EXISTING (predates Vulkan) and independent of the GPU work. To root-cause next: (a) verify whisper set_n_threads actually applies available_threads()=14 (log n_threads in run_full); (b) check whether the encoder pays full 1500 audio_ctx per 30s window even for a 6s clip in the non-streaming path (the streaming path fix in commit 8530a22 scaled audio_ctx by window length, but transcribe_file/run_full may not); (c) run stock whisper-cli directly on the same model+wav to isolate whether it's OUR run_full config vs whisper.cpp itself; (d) test greedy vs beam params and q5_1 vs f16 model; (e) confirm it's not thermal/throttle. The non-vulkan CPU baseline re-run (task, ~90s expected) was in progress to formally confirm parity with the vulkan build's CPU number.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-05T22:04:11*
|
||||
|
||||
---
|
||||
|
||||
## Commitments
|
||||
|
||||
*Promises, obligations, and TODOs that need follow-through.*
|
||||
|
||||
*No memories of this type.*
|
||||
|
||||
---
|
||||
|
||||
## Preferences
|
||||
|
||||
*User and entity preferences for personalization.*
|
||||
|
||||
### WhispAssist user working style (observed 2026-07-0...
|
||||
|
||||
WhispAssist user working style (observed 2026-07-06): (1) Demands EMPIRICAL PROOF over theory. When I attributed silent new recordings to the mic-not-in-WAV design, they pushed back ('the old file is also vault-sealed and plays fine, so it must be the 32->16bit change'). Resolving it required an actual real-hardware loopback capture test (play a known sound, read peak i16 from the WAV) to prove the 16-bit path records real audio — only then accept the diagnosis. HOW TO APPLY: when diagnosing a bug, verify the cause with a runnable test/measurement and show the evidence; don't just assert a root cause. (2) Highly protective of encryption-at-rest. They independently spotted that the decrypted audio.play.wav on disk and the browser 'download' button undermined the vault, and asked to switch playback to in-memory on-the-fly decryption. HOW TO APPLY: proactively avoid writing plaintext of vault-sealed data to disk and close off easy exfiltration paths (downloads, temp files).
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-07T01:05:30*
|
||||
|
||||
---
|
||||
|
||||
## Relationships
|
||||
|
||||
*Entity connections, team context, and collaboration patterns.*
|
||||
|
||||
*No memories of this type.*
|
||||
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
*Session summaries, status updates, and conversation state.*
|
||||
|
||||
### WhispAssist release/versioning process (as of v0.2...
|
||||
|
||||
WhispAssist release/versioning process (as of v0.2.0, 2026-07-06): the version string lives in THREE files that must be bumped together — package.json, src-tauri/tauri.conf.json, src-tauri/Cargo.toml (Cargo.lock updates on build). The shipped UNIVERSAL installer is built with: npm run tauri build -- --features vulkan --config src-tauri/tauri.vulkan.conf.json, with env VULKAN_SDK=C:\VulkanSDK\1.4.350.0, CMAKE_GENERATOR=Ninja, CARGO_TARGET_DIR=C:\wt, and vcvars64.bat loaded from 'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat'. Outputs land at C:\wt\release\bundle\msi\WhispAssist_<ver>_x64_en-US.msi and \nsis\WhispAssist_<ver>_x64-setup.exe (MSI ~44MB, NSIS ~9MB). The build does NOT create/push git tags — after merging to main, tag manually: git tag v<ver>; git push origin v<ver>. Last release before 0.2.0 was v0.1.6 (PR #15).
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-07T01:05:16*
|
||||
|
||||
### Project status as of 2026-07-02: Phase 8 tasks T8....
|
||||
|
||||
Project status as of 2026-07-02: Phase 8 tasks T8.7 (multi-language transcription + i18n scaffold) and T8.8 (at-rest encryption/vault, needs an ADR decision on SQLCipher vs file-level encryption first) remain deferred/pending. User paused them to do a full UI/UX redesign, then a transcription-latency investigation and fix, then Parakeet/NPU research. Both T8.7 and T8.8 are still the next planned work whenever the user returns to the Phase 8 roadmap.
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-02T20:14:43*
|
||||
|
||||
### WhispAssist remaining-work assessment + plan (2026...
|
||||
|
||||
WhispAssist remaining-work assessment + plan (2026-07-06, docs-only planning on branch feature_chore_bug_004, NOT built). As of v0.2.0, Phases 1-9 ship. The only real gap is Phase 10 (external AI + agent handoff, ADR-0011) plus a few polish items. STUBBED (commands return Err(not_implemented)): create/list/get_feature_brief, set_brief_exposed, mcp_status, set_mcp_enabled, set_mcp_scope, mcp_access_log, run_agent, create_issue_from_brief. SKELETON/ABSENT: mcp/mod.rs (trait + todo!() only), AnthropicProvider (returns 'not built yet'), MS Graph CalendarSource, multi-language transcription, DropboxTarget/BoxTarget (OAuth wired in sync/oauth.rs but no upload impl), chunked/resumable upload. BUILT already: OpenAiCompatProvider. The phased plan lives in docs/05-roadmap.md section 'Remaining work — post-v0.2.0 execution plan': M1 feature briefs (first; LLM-only, no egress) -> M2 MCP server (the differentiator; inbound loopback, zero added egress, FR-MCP-7 egress-unchanged is the merge gate) ; M3 hosted AI (parallel; finish Anthropic + hosted-key/banner/allowlist) ; M4 reliability/breadth (chunked upload is TOP item because recordings are now ~50-100MB and put() buffers whole file, OneDrive/Graph caps PUT at 250MB; then multi-language, Dropbox/Box) ; M5 push handoff (agent runner + issue tracker, Could-priority, last/optional). MS Graph calendar deferred (Could).
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-07T04:28:28*
|
||||
|
||||
---
|
||||
|
||||
## Events
|
||||
|
||||
*Important conversations, milestones, and temporal occurrences.*
|
||||
|
||||
### WhispAssist reached v0.2.0 (2026-07-06), supersedi...
|
||||
|
||||
WhispAssist reached v0.2.0 (2026-07-06), superseding v0.1.6. Additions since 0.1.6: microphone capture (records+transcribes the user's voice, mixed into transcript AND the saved recording at native quality via MicBridge), in-app recording playback with in-memory on-the-fly decryption (waaudio:// custom protocol, no plaintext on disk, download disabled), AI-generated tags + chip tag editor + tag filtering, meeting rename (editable title), notes single-pane Editor/Preview toggle, cancel-a-recording, 16-bit half-size recordings, live per-item sync upload progress, audio output + microphone device pickers, Outlook .pst recurring-event import/filtering + auto-sync-on-launch, and a SINGLE universal Vulkan installer (bundled vulkan-1.dll) replacing the separate CPU/NPU vs Vulkan builds. Built on branch feature_chore_bug_003 — still needs merge to main + tag v0.2.0. Installers already produced at C:\wt\release\bundle.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-07T01:05:36*
|
||||
|
||||
---
|
||||
|
||||
## Learnings
|
||||
|
||||
*Knowledge acquired from experience, corrections, and insights.*
|
||||
|
||||
### Real libpst quirk found via a real 7.2GB mailbox t...
|
||||
|
||||
Real libpst quirk found via a real 7.2GB mailbox test (2026-07-06): this readpst/libpst build joins a multi-value RRULE BYDAY with semicolons instead of RFC 5545's commas, e.g. 'RRULE:FREQ=WEEKLY;COUNT=10;BYDAY=MO;TU;WE;TH;FR' - so TU/WE/TH/FR appear as bare semicolon-separated tokens with no '='. A naive RRULE parser using '?' on split_once('=') silently bails out (returns None) for any event with more than one weekday, which is why the first version of expand_rrule worked for single-BYDAY series but silently dropped recurrence for multi-weekday ones. Fix: track the last-seen key and attribute a bare (no '=') token to it as a continuation value. This joins other already-documented libpst 0.6.63 quirks in ADR-0008 (no ORGANIZER/ATTENDEE emitted, no -8 flag support, wrong -t usage string).
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T20:40:50*
|
||||
|
||||
### WhispAssist WASAPI microphone finding (2026-07-06)...
|
||||
|
||||
WhispAssist WASAPI microphone finding (2026-07-06): unlike get_default_device(Render) which FAILS in cargo test on this dev machine, capturing the DEFAULT MIC (Direction::Capture) DOES work under cargo test AND delivers real frames (~3840 16kHz frames in 0.6s). Caveat: the FIRST COM activation of the mic can deliver 0 frames within the first ~600ms (cold start); a second run delivers normally. So a hardware mic smoke test should assert open+stop succeed (summary.sample_rate>0), not frames>0. Test: audio::tests::microphone_capture_opens_and_stops_cleanly (#[ignore], run with --ignored).
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-06T21:34:39*
|
||||
|
||||
### CONFIRMED FIX for WhispAssist release build crashe...
|
||||
|
||||
CONFIRMED FIX for WhispAssist release build crashes: Windows Defender real-time scanning of src-tauri/target was corrupting rustc.exe's compilation (random STATUS_STACK_BUFFER_OVERRUN crashes on different crates each run). Adding Defender exclusions (Add-MpPreference -ExclusionPath for target/, ~/.cargo, ~/.rustup, and -ExclusionProcess for rustc.exe/cargo.exe) fixed it completely -- full release build (whisper-rs, sherpa-rs native deps, MSI+NSIS bundling) now succeeds cleanly with the project's normal aggressive release profile (opt-level=z, codegen-units=1, lto=true). No toolchain reinstall or profile change was needed after all; those were red herrings from earlier in the debugging session. Also: a leftover running whispassist.exe instance can block cargo from overwriting the binary with 'Access is denied' -- close it before rebuilding.
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-01T21:09:24*
|
||||
|
||||
### Dark-mode bug pattern learned: CSS custom properti...
|
||||
|
||||
Dark-mode bug pattern learned: CSS custom properties don't cascade upward to ancestor elements. If data-theme (or similar theme attribute) is only set on an inner .app div, html/body keep the browser's default white background + 8px UA-stylesheet margin, invisible in light mode but a bright white border around the whole window in dark mode. Fix: mirror the theme attribute onto document.documentElement via an effect, and add a global html/body margin:0 + background:var(--bg) rule.
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-02T20:13:41*
|
||||
|
||||
### WhispAssist NPU spike (T3.4): Intel AI Boost NPU (...
|
||||
|
||||
WhispAssist NPU spike (T3.4): Intel AI Boost NPU (Core Ultra 5 135U, Meteor Lake, PCI VEN_8086&DEV_7D1D) runs the Whisper base.en ONNX encoder via ONNX Runtime OpenVINO EP (device_type=NPU) at ~66 ms/window vs ~236 ms/window on CPU = 3.58x faster, correct output shape (1,1500,512), full op coverage. Validates the plan: offload the fixed-shape Whisper encoder to the NPU, keep the dynamic decoder on CPU.
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-02T20:31:08*
|
||||
|
||||
### WhispAssist: an OAuth-linked calendar source (MS G...
|
||||
|
||||
WhispAssist: an OAuth-linked calendar source (MS Graph) is stored in Settings (settings.json: graph_calendar_enabled + graph_calendar_credential_ref) rather than as a sync_targets DB row, because it is not a SyncTarget/upload destination — reusing add_sync_target's OAuth flow would have wrongly surfaced it in the Sync UI and risked the upload pump trying to build a SyncTarget for it. begin_graph_calendar_link is a separate command from begin_oauth_link for this reason, duplicating ~60 lines of PKCE handshake rather than sharing it, since the two flows diverge in storage/eventing.
|
||||
|
||||
*Confidence: 0.85 | Status: active | Created: 2026-07-08T02:23:03*
|
||||
|
||||
### cargo fmt -- <specific files> does not scope forma...
|
||||
|
||||
cargo fmt -- <specific files> does not scope formatting to those files in the WhispAssist repo (src-tauri) — it reformats the entire crate regardless of file args passed after --, pulling in unrelated pre-existing drift in untouched files (observed: src/audio/mod.rs). After running cargo fmt scoped to touched files, always git status/diff to catch and git checkout -- any unrelated files it touched before committing. Also: memanto's on-prem backend (localhost:8080) needs Ollama (localhost:11434, embedding model nomic-embed-text) running for recall/export/sync to work, and the active agent session (memanto agent activate whispassist) can expire/drop mid-session — 'remember' can report success even when the write doesn't actually persist/index, so verify with 'memanto recall --recent' after a batch of remember calls rather than trusting the success message alone.
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-08T02:23:10*
|
||||
|
||||
### WhispAssist runtime bundle URLs CORRECTED to gitea...
|
||||
|
||||
WhispAssist runtime bundle URLs CORRECTED to gitea /media/ path (2026-07-06, commit 224aaf9): the .7z runtime bundles are hosted via Git LFS, and gitea's /raw/ endpoint returns the LFS POINTER (text) not the file, so the download URLs were changed from /raw/branch/main/ to /media/branch/main/ (gitea's media endpoint resolves LFS objects). Final URLs: NPU=https://git.dou.bet/iamdoubz/WhispAssist/media/branch/main/runtime/openvino.7z, DirectML=https://git.dou.bet/iamdoubz/WhispAssist/media/branch/main/runtime/directml.7z. SHAs unchanged (openvino ca0be9fc..., directml 34369222...). Files tracked via Git LFS (.gitattributes: runtime/*.7z filter=lfs). Still on branch chore_debug (no PR yet); URLs point at main so they resolve after merge. GOTCHA for future: GitHub raw.githubusercontent AND gitea /raw/ both serve LFS pointers not content — always use gitea /media/ (or GitHub media/LFS URL) for LFS-backed download targets.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T14:45:20*
|
||||
|
||||
### cargo test in WhispAssist src-tauri reliably crash...
|
||||
|
||||
cargo test in WhispAssist src-tauri reliably crashes at LINK time (rustc.exe exit 0xc0000409 STATUS_STACK_BUFFER_OVERRUN) when linking the full debug test binary against whisper.cpp+sherpa-onnx native libs with full debug info (debuginfo=2 default for test profile). This reproduces even from a clean target/debug, with reduced --jobs, regardless of Defender exclusions (which fixed the earlier release-build crashes but not this). FIX: set env var CARGO_PROFILE_TEST_DEBUG=0 (drop debug info) before cargo test -- this shrinks the PDB/link footprint enough to avoid the crash. Confirmed working: 'cargo test privacy_self_check' passed cleanly with CARGO_PROFILE_TEST_DEBUG=0 --jobs 4. Also noted: commands.rs is NOT feature-gated for cpu-transcription/diarization (unconditionally imports SherpaDiarizer/WhisperTranscriber/run_streaming_worker), so cargo test --no-default-features fails to compile -- can't lighten the native-link footprint that way, must use the debug-info trick instead.
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-01T22:01:31*
|
||||
|
||||
### WhispAssist dark-theme native-control gotcha (2026...
|
||||
|
||||
WhispAssist dark-theme native-control gotcha (2026-07-06, commits 4442f80/8038918): the app theme is a MANUAL toggle (data-theme on html + .app), independent of the OS prefers-color-scheme. Native form controls default to LIGHT and render bright-white in dark mode. Fixes applied: (1) added CSS 'color-scheme: light' on :global(:root) and 'color-scheme: dark' on :global([data-theme="dark"]) in App.svelte — this alone fixed unstyled controls. (2) A <textarea> was white because Settings.svelte's 'input, select { background:var(--bg); color:var(--fg) }' rule EXCLUDED textarea; fix = add textarea to that selector. (3) The header template <select> (.theme-select) options popup stayed WHITE even with color-scheme:dark because it had 'background: transparent' — an AUTHOR-styled select makes Chromium/WebView2 render its options popup in light unless the options carry their own colors. Fix = give .theme-select an explicit 'background: var(--bg-elevated)' AND style '.theme-select option { background: var(--bg-elevated); color: var(--fg) }'. LESSON: for dark-mode selects, set color-scheme on the root AND author the <option> background/color with theme tokens; don't rely on transparent backgrounds.
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-06T13:02:41*
|
||||
|
||||
### WhispAssist test-environment quirk found 2026-07-0...
|
||||
|
||||
WhispAssist test-environment quirk found 2026-07-06: wasapi::get_default_device(&Direction::Render) (and thus find_render_device(None)) FAILS when called from within 'cargo test' on this dev machine, even though the real desktop app (running as a normal foreground GUI process) resolves it fine. Enumeration itself (DeviceCollection) works fine in both contexts -- it's specifically the 'default device' role query that needs a real interactive audio session. Tests for this were written to assert consistency (find_render_device(None) vs a raw wasapi::get_default_device call, or unknown-id fallback vs None) rather than assuming a default device is resolvable, so they pass in both environments. Implication: don't trust 'cargo test' alone to validate anything touching wasapi's default-device APIs -- verify audio-device-selection behavior via the actual running app instead.
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-06T21:02:54*
|
||||
|
||||
### WhispAssist NPU Rust recipe (T3.4, validated): ort...
|
||||
|
||||
WhispAssist NPU Rust recipe (T3.4, validated): ort crate v2.0.0-rc.10 with features [load-dynamic, openvino] links against Intel's pip onnxruntime-openvino DLLs and runs the Whisper base.en encoder on the Intel NPU at 65 ms/window (matches Python; CPU is 236ms). Recipe: (1) ORT_DYLIB_PATH -> site-packages/onnxruntime/capi/onnxruntime.dll (the OpenVINO-enabled ORT build); (2) prepend BOTH openvino/libs AND onnxruntime/capi to PATH so dependent DLLs (openvino.dll, onnxruntime_providers_openvino.dll, onnxruntime_providers_shared.dll) resolve; (3) OpenVINOExecutionProvider::default().with_device_type("NPU").build().error_on_failure() to make a failed NPU registration LOUD instead of silently falling back to CPU; (4) Session::run needs &mut session. For shipping, bundle these DLLs with the Tauri app (resource/sidecar) instead of relying on pip. load-dynamic means no C++/OpenVINO build step in cargo.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-02T20:42:31*
|
||||
|
||||
### DirectML support in parakeet-rs for NVIDIA Parakee...
|
||||
|
||||
DirectML support in parakeet-rs for NVIDIA Parakeet/EOU/Nemotron models is purely theoretical/unvalidated, not a proven working combination. Evidence: (1) parakeet-rs's own Cargo.toml/execution.rs just forwards to ort's generic directml feature with zero model-specific notes -- contrast with its explicit CoreML warning ('CoreML EP currently runs slower than CPU for Sortformer/Parakeet models because the ONNX graphs have dynamic input shapes'); no equivalent DirectML note exists. (2) Searched all 113 issues in altunenes/parakeet-rs GitHub repo: zero mention DirectML. (3) microsoft/onnxruntime issue #19837 (opened 2024, still unresolved as of check) reports DirectML EP producing wrong numeric results on a model containing LSTM+Einsum ops -- root cause never found. (4) Microsoft's own microsoft/DirectML GitHub repo now carries a banner: DirectML is in maintenance/sustained-engineering mode, with new feature development moved to Windows ML (WinML); relevant since WhispAssist ADR-0004 specifies ort+DirectML for NPU accel. Recommend flagging ADR-0004 for review given this shift.
|
||||
|
||||
*Confidence: 0.85 | Status: active | Created: 2026-07-02T20:09:34*
|
||||
|
||||
### Rebuilding WhispAssist release binary after Phase ...
|
||||
|
||||
Rebuilding WhispAssist release binary after Phase 6: initial 'tauri build' failed with 'only metadata stub found for rlib dependency core' / cannot find crate for std,num_traits (whisper-rs-sys build script, atoi). Root cause: stale/corrupted 19GB target/ dir from a prior interrupted build. Fix: cargo clean in src-tauri, then rebuild clean. Always load vcvars64.bat (VS2022 BuildTools) before cargo/tauri build.
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-01T20:27:51*
|
||||
|
||||
### Root cause of WhispAssist release build crashes fo...
|
||||
|
||||
Root cause of WhispAssist release build crashes found: NOT toolchain corruption. rustc.exe crashes with STATUS_STACK_BUFFER_OVERRUN (0xc0000409) specifically compiling the windows-rs crate (v0.61.3) and pxfm crate, reproducible under both rustc 1.94.1 and 1.96.1. Root cause is the project's aggressive release profile in src-tauri/Cargo.toml: opt-level='z' + codegen-units=1 + lto=true triggers an LLVM/rustc codegen crash on these large generated crates. Confirmed fix: overriding just opt-level=2, codegen-units=16 via CARGO_PROFILE_RELEASE_OPT_LEVEL/CARGO_PROFILE_RELEASE_CODEGEN_UNITS env vars lets the windows crate compile cleanly in isolation. Earlier 'toolchain corruption' and 'cargo clean' theories were red herrings -- the missing-std/core-prelude errors seen on other crates were a cascade effect of cargo continuing after the crashed crate's .rlib was never written.
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-01T20:40:50*
|
||||
|
||||
### WhispAssist recording fix + diagnosis (2026-07-06,...
|
||||
|
||||
WhispAssist recording fix + diagnosis (2026-07-06, branch feature_chore_bug_003): User reported new recordings had 'no sound' while old ones played. DIAGNOSED: NOT the 32->16bit change. Proved via ignored hardware test loopback_16bit_wav_captures_played_audio (played Windows Alarm01.wav through default device, captured peak i16=11670) that 16-bit loopback capture records real audio fine. Root cause: the recorded WAV was loopback-only, so a mic-only moment (user talking, nothing playing through speakers) recorded as silence while their voice still reached the transcript. FIX (user chose native-quality): added audio::MicBridge (AtomicU32 rate + Mutex<VecDeque<f32>>, cap ~0.5s for clock-drift): loopback thread publishes its rate + pulls mic samples per-frame and mixes into every channel in write_wav_bytes(mic:&[f32]); mic thread resamples its audio to loopback rate (Resampler::new_to) and pushes to the bridge. New WasapiCapture::start_loopback_recording / start_microphone_recording; commands.rs uses them with a shared bridge when mic enabled. Recording is now native rate/stereo 16-bit WITH the user's voice. Verified by ignored test loopback_recording_with_mic_bridge_captures_played_audio (peak i16=22358). This SUPERSEDES the earlier 'mic transcript-only, not in WAV' limitation.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T23:27:12*
|
||||
|
||||
### WhispAssist T3.4 steps 1-3 DONE & validated end-to...
|
||||
|
||||
WhispAssist T3.4 steps 1-3 DONE & validated end-to-end: OnnxNpuTranscriber transcribes speech correctly on the Intel NPU. Pipeline: hand-rolled Whisper log-mel (transcription/mel.rs, matches HF WhisperFeatureExtractor) -> NPU encoder (OpenVINO EP) -> CPU greedy decoder (no KV cache, re-feeds prefix) -> hand-rolled byte-BPE detok from tokenizer.json (no tokenizers crate). Behind cargo feature 'npu' = [dep:ort, dep:rustfft]; renamed from the old empty 'directml' feature. Decode config from generation_config.json: decoder_start=50257, eos=50256, forced_decoder_ids=[[1,50362]] (notimestamps); mask token ids >=50257 (except eot) in argmax. TTS test: spoke 'testing one two three four, the quick brown fox...' got 'testing 1234 the quick brown fox jumps over the lazy dog.' All gates green first try (clippy -D, fmt, 69 default tests, 77 npu tests). NOT YET wired into commands.rs dispatch (that is step 6) — nothing routes to it in-app yet.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-02T21:14:31*
|
||||
|
||||
### WhispAssist NPU build gotcha: ort's default downlo...
|
||||
|
||||
WhispAssist NPU build gotcha: ort's default download-binaries do NOT include the OpenVINO execution provider. Must supply an ONNX Runtime built with OpenVINO (Intel's prebuilt onnxruntime-openvino) PLUS the OpenVINO runtime DLLs on the DLL path. HARD VERSION PIN: onnxruntime-openvino 1.24.1 requires openvino runtime 2025.4.1 EXACTLY. Version mismatch (e.g. openvino 2026.2) does NOT error loudly — it silently falls back to CPUExecutionProvider (Win Error 127 'procedure could not be found'). Pin the ort<->onnxruntime<->openvino version triple and assert the active provider is OpenVINOExecutionProvider at load, else the NPU is silently unused.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-02T20:31:10*
|
||||
|
||||
### CONFIRMED ROOT CAUSE (2026-07-02) of the WhispAssi...
|
||||
|
||||
CONFIRMED ROOT CAUSE (2026-07-02) of the WhispAssist whisper.cpp model-load crash: it is Trend Micro Security Agent (Worry-Free Business Security, corporate-managed -- services ntrtscan/TMBMServer/TmCCSF/tmlisten all running) injecting into whispassist.exe and hooking file I/O / MessageBox APIs. Live cdb attach to the process while the 'Debug Assertion Failed: _osfile(fh) & FOPEN' dialog was showing revealed 'tmmon64' (Trend Micro's monitoring module) sitting directly in the call stack between USER32!MessageBoxW and ucrtbased!__acrt_MessageBoxW, and the read path (whisper.cpp's std::ifstream -> xsgetn -> fread) resolves into ucrtbased.dll (debug CRT) even though whisper-rs-sys's CMakeCache.txt confirms /MD (release CRT) was used to build it -- i.e. Trend Micro's hook is corrupting the CRT call path, not a real build misconfiguration. Ruled out first: NOT a stack-size issue (tried 16MiB worker thread stack, crash identical), NOT stale/corrupted build artifacts (crash reproduces identically from a fully clean cargo clean --profile dev rebuild), NOT Windows Defender (already excluded target/ and C:\Users\dadous\AppData\Local\WhispAssist, crash persisted). Fix requires excluding whispassist.exe / the WhispAssist install and model directories from Trend Micro's real-time scan and behavior monitoring -- likely needs corporate IT/policy admin involvement since TMBMServer implies tamper-protected central management, not a self-service local exclusion like Defender. Tooling note: installed WinDbg Preview via 'winget install --id Microsoft.WinDbg' -- ships cdbX64.exe (classic command-line debugger) alongside the modern WinDbgX.exe GUI, usable for live process attach analysis without needing the full Visual Studio IDE debugger.
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-02T13:30:42*
|
||||
|
||||
### Fixed a real bug behind reported 30-65 second live...
|
||||
|
||||
Fixed a real bug behind reported 30-65 second live-transcription lag: whisper.cpp's encoder always runs over a full padded 30-second mel window (1500 encoder positions) unless audio_ctx is explicitly reduced via set_audio_ctx. WhispAssist's live-transcription streaming windows are only about 4 seconds each but were never setting audio_ctx, so every window paid the full 30-second-equivalent encode cost, serially, on one worker thread. Fixed in src-tauri/src/transcription/mod.rs (function audio_ctx_for_window) by scaling audio_ctx proportionally to the real window length (1500 positions = 30s, so a 4s window gets about 201). Committed as 8530a22. Verified about 30 percent faster in a controlled A/B benchmark, though that specific test ran under heavy CPU contention from Docker Desktop and other concurrent Claude Code sessions on this machine, which likely masks a larger real-world improvement since the fix targets the encoder O(n^2)-ish attention cost specifically.
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-02T20:14:23*
|
||||
|
||||
### WhispAssist dev/test workflow gotchas (2026-07-06)...
|
||||
|
||||
WhispAssist dev/test workflow gotchas (2026-07-06): (1) A running 'npm run tauri dev' / whispassist.exe holds the cargo build lock on its target dir — STOP it (Stop-Process -Name whispassist, plus kill the node/cargo/vite procs whose CommandLine matches tauri|whispassist|vite) BEFORE running cargo build/clippy/test or the build blocks on the lock. (2) 'npm run tauri dev' writes output to the Windows console handle, NOT the redirected background-task log file (which stays empty) — confirm the app actually launched via Get-Process whispassist, not by reading the log; it typically appears ~30s after launch. (3) The audio-device tests find_render_device_none_matches_get_default_device and find_render_device_unknown_id_falls_back_exactly_like_none are FLAKY under cargo test (the wasapi get_default_device(Render) COM quirk) — a rerun passes; do NOT chase them as regressions. Loopback/mic hardware smoke tests (loopback_16bit_wav_captures_played_audio, etc.) are #[ignore]'d and run with --ignored.
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-07T01:05:20*
|
||||
|
||||
### WhispAssist tooling FOOTGUN (2026-07-06): 'npm run...
|
||||
|
||||
WhispAssist tooling FOOTGUN (2026-07-06): 'npm run format' = 'prettier --write .' — it reformats the ENTIRE repo, not just changed files. Running it during a small change reformatted 120+ files (all docs/ADRs/.claude skills/CLAUDE.md/stores/etc) because the repo isn't uniformly prettier-clean, burying the real diff. RECOVERY that worked: git diff --name-only | grep out the intended KEEP files | xargs git checkout -- , then verify only intended files remain; the reformats were content+EOL noise (git diff -w showed EOL-only for many). LESSON: to format/verify only your touched files use 'npx prettier --write <files>' or just 'npm run check' (svelte-check) + 'npx eslint <files>' which don't write. ALSO: 'npm run lint' currently reports ~143 PRE-EXISTING errors (mostly 'console'/'process' is not defined no-undef in node-context files) unrelated to app code — don't be alarmed, they predate any given change. Repo has mixed LF/CRLF (git warns 'LF will be replaced by CRLF'); harmless line-ending churn.
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-06T12:48:15*
|
||||
|
||||
### WhispAssist dev-run finding (2026-07-06): 'npm run...
|
||||
|
||||
WhispAssist dev-run finding (2026-07-06): 'npm run tauri dev' builds the Rust with features audio,cpu-transcription,diarization,pst,sync,npu = the DEFAULT set MINUS vulkan and cuda. Consequence: the everyday dev/default build has NEITHER a whisper.cpp GPU backend NOR CUDA, so on the Intel Core Ultra + Arc iGPU dev machine the ONLY GPU accel path is DirectML (via the ort/npu feature) — and directml_would_help() returns TRUE there, so the DirectML Settings card is visible. To exercise the Vulkan path you must build with --features vulkan explicitly (see whispassist-vulkan-build-recipe). Incremental dev rebuild ~42s once whisper.cpp/deps are cached; debug binary at src-tauri/target/debug/whispassist.exe. Launch recipe: load vcvars64.bat (VS2022 BuildTools) then 'npm run tauri dev'; the WebView2 window opens on the user's desktop. Opening Settings does NOT trigger the debug-CRT Abort/Retry/Ignore assertion dialog (that only fires on the transcription file-read path), so a UI-only visual check on the debug build is safe.
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-06T12:27:54*
|
||||
|
||||
### Windows dev-loop gotchas confirmed again this sess...
|
||||
|
||||
Windows dev-loop gotchas confirmed again this session (2026-07-06): (1) Git Bash's quoting of 'cmd.exe /c "...vcvars64.bat" && cargo ...' silently no-ops (just opens/closes an interactive cmd shell) - must run that exact vcvars64.bat wrapper via the PowerShell tool instead, never Bash; (2) both 'cargo fmt' (no path args) and 'npm run format' (prettier --write .) reformat the ENTIRE repo/workspace, not just touched files - this touched unrelated pre-existing files (commands.rs WebDavTarget chain, all of docs/, .claude/skills/, package.json, CLAUDE.md, package-lock.json) and had to be reverted via targeted git checkout, keeping only the intended diff. Going forward: use 'rustfmt --edition 2021 <specific files>' and 'npx prettier --write <specific files>' instead of the whole-repo commands.
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-06T20:40:55*
|
||||
|
||||
---
|
||||
|
||||
## Observations
|
||||
|
||||
*Patterns noticed, behavioral notes, and recurring themes.*
|
||||
|
||||
### WhispAssist transcription benchmark (2026-07, rele...
|
||||
|
||||
WhispAssist transcription benchmark (2026-07, release 0.1.4, SAME 6.3s TTS clip 'Testing 1234 the quick brown fox...', base.en q5_1 model, full transcribe_file path, machine=Intel Core Ultra 14-thread + Arc iGPU): VULKAN on Intel Arc iGPU = load 274ms, infer ~4.5s (fastest, edges out NPU). NPU OpenVINO = load 1355ms, infer ~5.7s. CPU whisper.cpp = load ~190ms, infer 92-99s (PATHOLOGICAL, ~15x SLOWER than real-time). All three produce the correct transcript. CRITICAL FINDING (user-confirmed): CPU was ALREADY ~90s BEFORE Vulkan was added — so the Vulkan build did NOT regress the CPU path; the 0.1.4 Vulkan build is SAFE to ship (CPU fallback unchanged). The ~90s CPU is a PRE-EXISTING bug in the full transcribe_file path, NOT caused by Vulkan. Vulkan and NPU are ~16-20x faster than the broken CPU path. Note the STREAMING path was already fixed earlier (audio_ctx scaling, commit 8530a22); transcribe_file (single_segment=false, 30s-padded seek loop) is the still-slow one.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-05T22:04:09*
|
||||
|
||||
### Meetily (Zackriya-Solutions/meetily), the competit...
|
||||
|
||||
Meetily (Zackriya-Solutions/meetily), the competitor app cited as prior art for Parakeet integration, uses Parakeet only for BATCH/offline transcription via the transcribe-rs crate (built on istupakov's ONNX conversion, per meetily's own README credits) -- not live streaming. Its 'Import & Enhance' feature (post-hoc re-transcription) is the actual use case; no DirectML-specific hardware acceleration for Parakeet is documented in its backend README. A true streaming fork (Nemotron streaming ASR engine) exists only as a community fork (Amitsurya2000/transcribe-rs), not upstream. sherpa-onnx (k2-fsa) also lacks true streaming Parakeet TDT support as of its open issues #2918 and #3573. Checked 2026-07-02, informs WhispAssist NPU/Parakeet research.
|
||||
|
||||
*Confidence: 0.85 | Status: active | Created: 2026-07-02T20:09:37*
|
||||
|
||||
---
|
||||
|
||||
## Artifacts
|
||||
|
||||
*Tool outputs, files, reports, and external references.*
|
||||
|
||||
### M4.1 (chunked/resumable upload, T9.2 refinement, F...
|
||||
|
||||
M4.1 (chunked/resumable upload, T9.2 refinement, FR-SYNC-2/5) SHIPPED 2026-07-07 on branch feature_chore_bug_005 (commits be025bb, 2cc48c9), same day as M4.2/M4.3/M4.4 but a separate prior session. Recordings are now native-quality (~50-100 MB) and the old put() buffered the whole file into memory in one PUT; OneDrive/Graph also caps a single PUT at 250 MB. Fixed by streaming disk-to-network in fixed-size chunks on both sync backends: WebDavTarget::put and OneDriveTarget::put now use tokio::fs::File + BufReader (O(chunk) memory, not O(file size)) for every upload. Files at/below LARGE_FILE_THRESHOLD (8 MiB) still take a single streamed PUT — only large artifacts (.wav recordings) take the chunked path. WebDAV (Nextcloud/ownCloud) implements the chunking-v2 protocol; OneDrive uses Graph's upload-session API. Needed enabling tokio's io-util/net features for AsyncReadExt/AsyncSeekExt/BufReader (separate chore commit be025bb).
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-08T02:27:25*
|
||||
|
||||
### WhispAssist calendar/PST recurrence expansion (202...
|
||||
|
||||
WhispAssist calendar/PST recurrence expansion (2026-07-06, commits fa8a7f2/6f07f28): expand_rrule in calendar/mod.rs now parses RRULE (DAILY/WEEKLY/MONTHLY/YEARLY, INTERVAL/COUNT/UNTIL/BYDAY/BYMONTHDAY/BYMONTH) and expands each recurring PST event into its own stored row keyed by '{uid}@{ymd}' for dedup, instead of only storing the first occurrence. Rewritten on chrono::Local (promoted from transitive to direct dependency) instead of hand-rolled epoch-day math, because the first version had a real DST bug: it kept a fixed UTC time-of-day per occurrence, so a meeting created in winter (CST) drifted an hour once its weekly recurrence crossed into summer (CDT) - e.g. 16:30 UTC showed correctly as 10:30 in January but wrongly as 11:30 in July. Fix: convert dtstart to local wall-clock once, keep hour/min/sec fixed, re-resolve the UTC offset per occurrence date. Tests assert local wall-clock time is identical across all occurrences (would fail under the old code).
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T20:40:48*
|
||||
|
||||
### WhispAssist audio-device-selection feature (2026-0...
|
||||
|
||||
WhispAssist audio-device-selection feature (2026-07-06, commits bb1d173/8e3e22c/2759a0e/5b28153/1376059/38b9cb2/b8dc5fc): added Settings > Hardware > 'Audio Devices' picker overriding the default 'Default system audio' WASAPI loopback render device. Backend: AudioCapture::start now takes device_id: Option<&str> (Device::get_id() string) instead of always resolving wasapi::get_default_device(&Direction::Render); new find_render_device() enumerates via wasapi::DeviceCollection and falls back to system default if the configured device is gone (same degrade-gracefully spirit as the existing mid-recording reconnect, which now retries the SAME selection first instead of switching to whatever's currently default). New list_render_devices()/list_audio_devices command (wasapi crate already supported enumeration, just was unused until now). Settings.audio_output_device: Option<String>, #[serde(default)] for backward compat. This is playback/render-device-only (loopback capture) -- WhispAssist has no microphone capture path at all (FR-CAP-1), so there is no separate 'input device' setting.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T21:02:52*
|
||||
|
||||
### WhispAssist M3 (hosted AI providers) SHIPPED (2026...
|
||||
|
||||
WhispAssist M3 (hosted AI providers) SHIPPED (2026-07-07, branch feature_chore_bug_005, merge commit e966181, on top of M1+M2 merge 2582d89). Built by an agent in an isolated git worktree, but that worktree's base snapshot was stale (pre-dated M1/M2 - based on 3038b9d, not the then-current feature_chore_bug_005 HEAD) - a real limitation of this session's worktree isolation mechanism worth remembering: it can silently reuse an earlier repo snapshot rather than the live current branch when a new worktree agent is launched later in the same session. Concretely this meant the M3 agent never saw M1's LlmProvider::complete() trait method addition, so AnthropicProvider::complete() was left as M1's not-yet-implemented stub even though M3 finished summarize/suggest_tags/status for real. Caught this by grepping the worktree for 'fn complete' before merging (found nothing) rather than trusting the agent's done report, then implemented AnthropicProvider::complete_with_key (non-streaming POST to /v1/messages, mirrors suggest_tags_with_key) myself as part of merge reconciliation. Also resolved three merge conflicts: llm/mod.rs (the complete() gap above), and two lucide-icon-import-list conflicts in Settings.svelte/SummaryPanel.svelte (M2 and M3 each added their own icon imports at the same insertion point) - unioned both, verified every icon is actually used before committing. What M3 built: AnthropicProvider real implementation (x-api-key + anthropic-version headers, SSE streaming for summarize, non-streaming for tags/complete), set_llm_provider storing the Anthropic key only in the OS credential store (never settings.json/DB, tested) and adding api.anthropic.com to the egress allowlist only when actually configured, HostedAiBanner.svelte one-time third-party-egress acknowledgment component, active-provider indicator + per-use quick-switch in SummaryPanel. Verified independently end to end on the fully merged M1+M2+M3 tree: cargo test --features mcp = 165 passed/0 failed, clippy clean (default + --features mcp), cargo fmt clean (only the same pre-existing unrelated audio/mod.rs drift as before), svelte-check 0 errors. Lesson for future milestone builds in this repo: after any worktree-isolated agent finishes, grep for the specific trait methods/functions the previous milestone added before trusting 'this builds on M<n-1>' claims - isolation snapshots can silently drift stale mid-session.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-07T13:16:21*
|
||||
|
||||
### WhispAssist meeting title + tags features (2026-07...
|
||||
|
||||
WhispAssist meeting title + tags features (2026-07-06, commits 2efe295/e68e888 and 68c32ff/16fcb15): (1) meetings previously had NO way to rename from 'Untitled meeting' anywhere in the UI - added an inline-editable title header above the transcript/notes pane (TranscriptNotes.svelte) backed by a new rename_meeting command; (2) attach_meeting_to_event now also mirrors the linked calendar event's subject onto the meeting's title when it has one, so linking 'Jerry / Daniel - Weekly 1:1' auto-renames the meeting; (3) added a 'Generate tags' feature mirroring 'Generate summary' - new LlmProvider::suggest_tags trait method (implemented for Ollama/OpenAI-compatible/Anthropic-stub), reads the transcript via the same build_prompt assembly, non-streamed, returns 1-8 tags merged into (not replacing) the existing tag list; (4) replaced the old comma-separated text-input tags UI with GitHub-topics-style removable/clickable chips (new shared TagChip.svelte component using existing --accent/--accent-soft tokens) - clicking a chip's label calls meetings.filterByTag() which filters the sidebar meeting list, an 'x' removes it.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T20:40:53*
|
||||
|
||||
### WhispAssist Phase 9a increment 1 DONE (branch feat...
|
||||
|
||||
WhispAssist Phase 9a increment 1 DONE (branch feature_another_one): WebDAV target management + connection test, validated end-to-end against a live wsgidav server (file physically uploaded via PROPFIND->MKCOL->PUT->HEAD). Added: storage SyncTargetRow CRUD (sqlx FromRow); sync::WebDavTarget real impl; sync::credentials keyring wrapper (service 'WhispAssist-sync', secret keyed by credential_ref, never in DB); TLS enforcement (enforce_transport: https always, http only for LAN+opt-in); commands list/add/update/remove/test_sync_target + set_sync_enabled (take State now); privacy_self_check wired to real targets. Enabled 'sync' in default cargo features. Anonymous targets supported (basic_auth only sent when a secret exists). All gates green: clippy -D, fmt, 74 tests. Local test server: python -m wsgidav.server.server_cli --host 127.0.0.1 --port 8899 --root <dir> --auth anonymous; test env WA_WEBDAV_URL/USER/PASS, run 'cargo test webdav_round_trip -- --ignored'. STILL TODO increment 2: durable queue + pump/backoff + sync_meeting + finalize-hook enqueue + sync://job events + sync_status/retry_sync_job (currently still not_implemented) + Settings sync UI. Increment 3: 9b OAuth (OneDrive/Dropbox/Box). 9c encryption on hold (needs T8.8 vault).
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-03T01:17:19*
|
||||
|
||||
### M4.2 (multi-language transcription, T8.7, FR-TRX-4...
|
||||
|
||||
M4.2 (multi-language transcription, T8.7, FR-TRX-4) SHIPPED 2026-07-07 on branch feature_chore_bug_005 (large commit chain: 6bc0949 add multilingual/language fields to ModelInfo+Settings, 37a6dd1 multilingual model catalog entries, 7f88101 whisper language catalog for Settings dropdown, 496a8aa wire whisper language param through Transcriber trait, 66d9eff persist requested language at meeting creation, 75ca3df track resolved per-meeting language on RecordingSession, 7490ff5 wire language selection through recording/reprocess/recovery, 34fff3f register list_whisper_languages command, plus a full UI chain (4c00496/4892719/dc969df/e6e995e/7bff392/353d582) for a Settings language picker + per-meeting badge + reprocess override, and a same-day bugfix 40709b2 making resolve_language normalize case-insensitive 'en' matches so the English-only-model guard fires correctly). Delivers: multilingual model option, whisper language param (select/auto-detect), per-meeting language persisted, Settings dropdown + reprocess picker in the UI.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-08T02:27:34*
|
||||
|
||||
### WhispAssist Phase 9a increment 2 DONE: durable upl...
|
||||
|
||||
WhispAssist Phase 9a increment 2 DONE: durable upload queue (sync_jobs CRUD, pump w/ backoff, finalize hook, startup pump, sync://job events). 78 tests green. TODO: Upload-now UI. Increment 3: 9b OAuth; 9c on hold.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-03T02:57:46*
|
||||
|
||||
### WhispAssist in-memory recording playback (2026-07-...
|
||||
|
||||
WhispAssist in-memory recording playback (2026-07-06, branch feature_chore_bug_003): Replaced the file-based player (which decrypted vault-sealed audio.wav to a plaintext audio.play.wav on disk, weakening encryption-at-rest) with an in-memory custom Tauri protocol. commands::serve_recording backs a registered 'waaudio' uri scheme (URL http://waaudio.localhost/<meeting_id> on Windows): reads audio.wav, vault::open decrypts in RAM, streams audio/wav with Range support (parse_byte_range) for seeking; 404 no file, 403 sealed+locked, path-traversal guarded (id must be alnum/hyphen). recording_playback_path now returns that URL after a cheap sealed-prefix + is_unlocked precheck and deletes stale audio.play.wav. commands::cleanup_playback_temp() sweeps all meetings/*/audio.play.wav at startup (called in lib.rs setup). Removed assetProtocol config + tauri protocol-asset feature + convertFileSrc; CSP media-src now 'self' http://waaudio.localhost. UI <audio> has controlsList=nodownload noplaybackrate + oncontextmenu preventDefault so the decrypted audio can't be saved to disk. Verified: clippy clean, svelte-check clean, full build, startup sweep removed leftover play-temp files.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T23:41:52*
|
||||
|
||||
### WhispAssist runtime bundles switched to 7z from re...
|
||||
|
||||
WhispAssist runtime bundles switched to 7z from repo raw URLs (2026-07-06, branch chore_debug, commits 27ba4f9/e6f1916). The NPU (OpenVINO) and DirectML runtimes are now downloaded as .7z (LZMA2+BCJ) from gitea RAW paths: NPU=https://git.dou.bet/iamdoubz/WhispAssist/raw/branch/main/runtime/openvino.7z (SHA ca0be9fc52c78ee623b152f790450b3d4020c5a7ebe99d27736455b308782191), DirectML=https://git.dou.bet/iamdoubz/WhispAssist/raw/branch/main/runtime/directml.7z (SHA 34369222fcc1be2e72a957b868b1976a90150ba704a06c9e8992c34ee368926b). REPLACED the zip crate with sevenz-rust2 (pinned 0.7.0 — newer needs rustc>1.77 MSRV; optional + npu-gated). extract_zip_flat -> extract_7z_flat (uses decompress_file_with_extract_fn, flattens basenames — archives nest DLLs under directml/ and openvino/ folders). stage_directml_runtime now defaults to DIRECTML_RUNTIME_URL const (no longer requires WA_DIRECTML_RUNTIME_URL env). Env overrides WA_NPU_RUNTIME_URL / WA_DIRECTML_RUNTIME_URL still honored. sevenz-rust2 0.7.0 confirmed to decode LZMA2+BCJ (has src/bcj/x86.rs); validated by test extract_7z_flat_unpacks_the_directml_bundle (extracts ../runtime/directml.7z, asserts onnxruntime.dll == 17253408 bytes, flattened) — PASSES. clippy -D warnings clean on default/shipped build; 104+ tests green. NOTE: raw URLs point to branch/main, so they only resolve once runtime/openvino.7z + runtime/directml.7z are committed to MAIN. As of now those .7z files are UNTRACKED (left for the user to commit — plain git add vs Git LFS decision; ~27MB total). The old .zip package-registry URL (git.dou.bet/api/packages/.../npu-runtime/...) is retired. archives were created with 7z LZMA2:24m BCJ.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T13:26:14*
|
||||
|
||||
### WhispAssist M1 (feature briefs) + M2 (MCP server) ...
|
||||
|
||||
WhispAssist M1 (feature briefs) + M2 (MCP server) SHIPPED (2026-07-07, branch feature_chore_bug_005, merge commit 2582d89). Built in parallel by two agents in isolated git worktrees, then merged sequentially (M1 first, ff-merge; M2 second, conflict-merged). M1: Store methods for feature_briefs (insert/list/get_row/set_exposed), LlmProvider::complete() primitive (Ollama+OpenAI-compat), FeatureBriefBuilder distiller (briefs/mod.rs, keyword-overlap grounding), the 4 create/list/get_feature_brief+set_brief_exposed commands, SummaryPanel.svelte UI, golden-transcript tests. M2: mcp module on rmcp (loopback bind + token gate, Streamable HTTP + stdio adapter), 4 tools (list_recent_meetings/get_transcript/get_action_items/get_feature_brief), scope control (none|selected|all), mcp_status/set_mcp_enabled lifecycle (token in OS credential store), disclosure UI + mcp_access_log audit, privacy panel integration. Gated behind an optional mcp Cargo feature. Merge required resolving one real conflict (storage/mod.rs trait+impl interleaving) plus one real cross-branch integration bug: M2's handler.rs called commands::get_feature_brief(id) with the pre-M1 stub arity; fixed by extracting get_feature_brief_core(store, id) shared between the Tauri command and the MCP handler, and wired the previously-stubbed selected-scope exposed-flag check (scope::brief_visible) that M2 had left as a documented KNOWN GAP. Verified independently (not just trusting agent reports): cargo test --features mcp = 154 passed/0 failed, clippy clean (default + --features mcp), cargo fmt clean (only pre-existing unrelated audio/mod.rs drift), svelte-check 0 errors. Known environment gotcha hit repeatedly during verification: whisper-rs-sys native build intermittently fails with MSVC error C1056 'cannot update time date stamp' - Trend Micro AV interference, same class as the previously-recorded model-loading hang; resolved by retrying the build, not a code defect. Also: building in a deeply-nested git worktree path (.claude/worktrees/agent-id/...) can overflow Windows MAX_PATH during whisper.cpp's CMake TryCompile scratch dirs - work around with a short CARGO_TARGET_DIR (e.g. C:/wa-build-x) when testing worktrees directly. M2's one incomplete acceptance item: no compiled end-to-end MCP wire-protocol client test (blocked on an rmcp reqwest-0.13-vs-0.12 version conflict pulling in aws-lc-rs; agent reverted the attempt cleanly rather than leave it unverified) - unit-level loopback-bind-refusal and scope-enforcement tests substitute for now. Next: M3 (hosted AI providers, Anthropic) per user pre-authorization to skip the usage checkpoint and go straight to a scheduled resume.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-07T06:17:52*
|
||||
|
||||
### M4.3 (Dropbox/Box upload targets, T9.10, FR-SYNC-9...
|
||||
|
||||
M4.3 (Dropbox/Box upload targets, T9.10, FR-SYNC-9) SHIPPED 2026-07-07 on branch feature_chore_bug_005 (commit 6991c1d), same day as M4.1/M4.2/M4.4 but a separate prior session. Implements DropboxTarget and BoxTarget SyncTarget impls (OAuth PKCE was already wired for both providers). DropboxTarget: path-addressed like OneDrive/WebDAV; create_folder_v2 creates the whole intermediate path in one call; upload-session chunking above LARGE_FILE_THRESHOLD (start/append_v2/finish). BoxTarget: Box addresses items by numeric ID not path, so ensure_dir/exists/put all walk (and lazily create) the folder chain from root ('0') by listing each level's children; always uploads via Box's session API regardless of file size (its session API takes plain PUT bodies, consistent with every other target, needs no new reqwest feature, and Box computes/returns each part's digest so no local hashing needed). Both follow the same documented ceiling as OneDriveTarget's put_chunked (M4.1): the upload-session id lives only for one put() call, not persisted across process restarts — a crash mid-chunked-upload restarts that file's upload from scratch rather than resuming (unlike WebDAV's chunking-v2 which is genuinely resumable).
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-08T02:27:46*
|
||||
|
||||
### WhispAssist T3.4 NPU acceleration COMPLETE (steps ...
|
||||
|
||||
WhispAssist T3.4 NPU acceleration COMPLETE (steps 1-6, feature_npu branch). Dispatch: commands.rs load_transcriber() routes BackendId::Npu -> OnnxNpuTranscriber (onnx model dir), else whisper.cpp, with graceful CPU fall-through; used by streaming worker and batch reprocess. run_streaming_worker now takes &dyn Transcriber (T: ?Sized). hardware_status returns npu:{present,runtimeReady,modelInstalled}. download_npu_package command + npu://download progress events; startup auto-fetches ONNX model in background if NPU present && model missing. Settings>Hardware shows NPU detected + download indicator. All gates green first try: fmt, clippy default+npu -D warnings, 69 default tests, 77 npu tests, svelte-check 0 errors, eslint. Real NPU inference re-verified post-refactor. KNOWN GAP: OpenVINO runtime staging (stage_npu_runtime) copies DLLs from local dirs in env WA_NPU_RUNTIME_SRC (';'-separated) not a hosted download - no hosted runtime bundle URL yet. Upgrade path: host versioned ORT+OpenVINO bundle, download+unzip into paths::npu_runtime_dir(). Repo frontend NOT prettier-clean (117 files pre-existing); only touched files formatted.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-02T22:17:13*
|
||||
|
||||
### WhispAssist merged single installer (2026-07-06, b...
|
||||
|
||||
WhispAssist merged single installer (2026-07-06, branch feature_chore_bug_003): Combined the two installers (13MB default/NPU-DirectML at src-tauri/target vs 67MB Vulkan at C:\wt) into ONE universal Vulkan installer. Verified facts: default exe 13MB imports no vulkan-1.dll (runs anywhere, GPU via runtime DirectML); Vulkan exe 67MB imports vulkan-1.dll at LOAD time (dumpbin) so it won't launch without the loader. Fix (option A = bundle the loader): build.rs stage_vulkan_loader() runs when CARGO_FEATURE_VULKAN set — copies vulkan-1.dll from %VULKAN_SDK%\Bin (fallback C:\Windows\System32) next to the exe (OUT_DIR ancestors nth(3) = target/<profile>, correct under CARGO_TARGET_DIR=C:\wt) AND into src-tauri/ (gitignored) for bundling. New src-tauri/tauri.vulkan.conf.json overlay adds bundle.resources ['vulkan-1.dll']. Release build cmd: npm run tauri build -- --features vulkan --config src-tauri/tauri.vulkan.conf.json (needs VULKAN_SDK, CMAKE_GENERATOR=Ninja, CARGO_TARGET_DIR=C:\wt). VERIFIED end-to-end: built MSI+NSIS 0.1.6; WiX main.wxs shows vulkan-1.dll as a Component in the same install dir as whispassist.exe + sibling DLLs (onnxruntime/sherpa/whispassist_lib), so the loader finds it. DirectML stays hidden when vulkan compiled (directml_would_help returns false). STILL TO TEST BY USER: launch the merged installer on a clean VM with NO vulkan-1.dll / no GPU driver to confirm graceful CPU fallback before retiring the 13MB build.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-07T00:06:25*
|
||||
|
||||
### WhispAssist 5-feature batch (2026-07-06, branch fe...
|
||||
|
||||
WhispAssist 5-feature batch (2026-07-06, branch feature_chore_bug_003): (1) Notes single-pane Editor/Preview toggle in TranscriptNotes.svelte (one button flips label Preview<->Editor). (2) Recording playback FR-REC-5: command recording_playback_path decrypts vault-sealed wav to audio.play.wav; enabled tauri protocol-asset feature + assetProtocol scope [$LOCALDATA/WhispAssist/meetings/**] + media-src CSP; SummaryPanel <audio controls> via convertFileSrc. (3) Smaller wav FR-CAP-8: wav_spec_for now forces 16-bit Int at native rate; write_wav_bytes quantizes f32->i16 via f32_to_i16 (clamp*i16::MAX) — halves 205MB->~103MB. Kept native rate (48k), did NOT resample to 44.1k (marginal, needs multichannel resampler in hot path). (4) Cancel recording FR-CAP-9: cancel_recording command stops loopback+mic, joins worker, store.delete_meeting (row+folder), emits recording://state state:cancelled; App.svelte Cancel button with confirm. (5) Live sync progress FR-SYNC-11: sync put() streams body via futures_util::stream::unfold + reqwest wrap_stream + Content-Length, sends incremental (sent,total); upload_job drains on a std thread (throttled 250ms) calling on_progress; pump_sync emits live sync://job; SummaryPanel <progress> bar. All clippy-clean, svelte-check clean, vite+full cargo build pass.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T22:57:29*
|
||||
|
||||
### WhispAssist 0.1.6 release build (2026-07-06): Vulk...
|
||||
|
||||
WhispAssist 0.1.6 release build (2026-07-06): Vulkan build (npm run tauri build -- --features vulkan; VULKAN_SDK=C:\VulkanSDK\1.4.350.0, CMAKE_GENERATOR=Ninja, CARGO_TARGET_DIR=C:\wt, use QUOTED 'set "VAR=val"' to avoid trailing-space bug). Headline fix vs 0.1.5: keyring windows-native (OS credential store was a no-op mock; sync/AI creds never persisted). Artifacts in C:\wt\release\bundle\: msi\WhispAssist_0.1.6_x64_en-US.msi (27MB, SHA256 ffbe32d9b53f2feaaa4b8a6a858b2f283cc5520b7e77814bc5cf7a41e04b5301), nsis\WhispAssist_0.1.6_x64-setup.exe (8.8MB, SHA256 669147d9578b2644b0838de346dda9ce7edd2b614a18f63ca5f61ffd64c6b526). SHA256SUMS.txt written to C:\wt\release\bundle\. Upload the .msi + -setup.exe + SHA256SUMS.txt; NOT the .7z runtime bundles (hosted in-repo via Git LFS, pulled from /media/branch/main/runtime/). 27MB MSI confirms Vulkan (CPU-only=11MB). Commits since 0.1.5: keyring fix 33c0397, version bump 6a4b832, plus sync-target-edit, Nextcloud server-URL auto-build, dark-theme fixes, About page, 7z runtime download.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T18:14:30*
|
||||
|
||||
### WhispAssist 0.1.5 shipped (2026-07-06, branch chor...
|
||||
|
||||
WhispAssist 0.1.5 shipped (2026-07-06, branch chore_debug): two UI fixes + version bump, 6 commits (035abb9..0d62416). (1) Settings panel horizontal-scroll/close-button-cutoff FIXED: the tab <nav> in Settings.svelte didn't wrap inside the fixed-width panel (width:min(720px,92vw)), overflowing and pushing the .close (X) button off-edge + adding a horizontal scrollbar. Fix: nav { flex:1 1 auto; min-width:0; flex-wrap:wrap }, header align-items:flex-start, .close flex:0 0 auto. (2) New ABOUT page (Settings ▸ About, Info icon tab): shows version (env!(CARGO_PKG_VERSION)) + build commit hash + a source link to https://git.dou.bet/iamdoubz/WhispAssist. Commit hash baked at build time via build.rs (git rev-parse --short HEAD -> cargo:rustc-env=WA_GIT_HASH, rerun-if-changed=../.git/logs/HEAD). Two new Tauri commands: app_info()->{version,commit}, open_url(url) (validates http(s), Windows-only via 'explorer <url>' — no shell injection, reuses installed toolchain instead of adding tauri-plugin-opener). api.ts got AppInfo type + appInfo()/openUrl() bindings. NOTE the section {#if}/{:else if} chain in Settings.svelte: privacy was the catch-all {:else} — adding an About branch required converting privacy to {:else if section==="privacy"} because {:else if} can't follow {:else}. Version bumped 0.1.4->0.1.5 in package.json, src-tauri/Cargo.toml, src-tauri/tauri.conf.json, Cargo.lock (package-lock.json tracks app version as 0.0.0, untouched). clippy -D warnings + svelte-check + eslint(my files) all clean.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T12:48:09*
|
||||
|
||||
### WhispAssist P2 DirectML GREEN end-to-end (2026-07-...
|
||||
|
||||
WhispAssist P2 DirectML GREEN end-to-end (2026-07-05): staged Microsoft.ML.OnnxRuntime.DirectML v1.24.1 (EXACT match to the OpenVINO bundle's ORT 1.24.1, from nuget flat-container api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime.directml/1.24.1/...nupkg) into %LOCALAPPDATA%/WhispAssist/runtime/directml/ = onnxruntime.dll (17MB, DML EP baked in) + onnxruntime_providers_shared.dll. DirectML.dll NOT in the nuget — the Win11 System32 DirectML.dll (v1.15.5) satisfied it. Ran directml_transcribes_speech spike (no ORT_DYLIB_PATH; ensure_runtime_env pointed ort at runtime/directml/onnxruntime.dll + prepended its dir to PATH): backend=Intel (Arc iGPU via DirectMLExecutionProvider device_id 0), load=1222ms, infer=453ms, transcript='(gentle music)' (test wav was music; non-empty => PASS). So the full P0+P2 DirectML path is proven working on real GPU hardware, infer time on par with Vulkan/NPU. Repro: nuget version MUST be >= the ORT the OpenVINO bundle ships (1.24.x) for ABI/symbol match with ort rc.10. Older DirectML nugets (1.20-1.23) would risk GetProcAddress misses.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T02:30:59*
|
||||
|
||||
### WhispAssist sync-target EDIT feature added (2026-0...
|
||||
|
||||
WhispAssist sync-target EDIT feature added (2026-07-06, commits 149f2c9/45b2acb/496a337/fb79009). Root cause of the user's Nextcloud auth failure: the saved target's base_url was missing the /remote.php/dav/files/<user>/ path (they entered just the host) -> PROPFIND hit a non-DAV path -> 401. Credentials + app password were CORRECT (verified via curl PROPFIND returning 207 + X-User-Id). The app had NO way to edit a saved target — only add/delete/toggle-enabled — so they couldn't fix the URL. FIX: the backend update_sync_target command + store + api.updateSyncTarget ALREADY existed (was only used by the enable toggle); added the missing UI. Changes: (1) SyncTargetInfo (models.rs + api.ts) gained upload_transcript/notes/summary/recording, trigger_on_finalize, allow_plaintext_lan, encrypt_before_upload + row_to_info populates them (secret still never exposed, FR-SYNC-6); (2) settings.svelte.ts store.updateTarget(); (3) Settings.svelte: per-webdav-target Edit button -> startEdit() loads it into the add-form (secret blank), heading/submit become 'Edit target'/'Save changes', kind tabs hidden during edit, Cancel button. Password left blank on save = keep stored (update only rotates the credential when a non-empty secret is provided). Test-connection in edit mode tests the TYPED values (form has no id) so it needs the password re-entered; the simpler fix-and-save path preserves the secret. Correct Nextcloud WebDAV base_url = https://HOST/remote.php/dav/files/USERNAME/ . clippy + svelte-check + eslint all clean.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T15:41:28*
|
||||
|
||||
### WhispAssist 0.1.5 release build (2026-07-06, first...
|
||||
|
||||
WhispAssist 0.1.5 release build (2026-07-06, first public release): Vulkan build via 'npm run tauri build -- --features vulkan' with env VULKAN_SDK=C:\VulkanSDK\1.4.350.0, CMAKE_GENERATOR=Ninja (ninja 1.10.2 at C:\Tools\Standalone), CARGO_TARGET_DIR=C:\wt, vcvars64 loaded. GOTCHA that failed the first attempt: cmd 'set CARGO_TARGET_DIR=C:\wt && ...' captured a TRAILING SPACE (C:\wt ) -> 'failed to create directory C:\wt \release'; fix = quoted set: set "CARGO_TARGET_DIR=C:\wt". Artifacts in C:\wt\release\bundle\: msi\WhispAssist_0.1.5_x64_en-US.msi (27MB, SHA256 ed83ad0001c654221f3e5787088d922a1211d2722acbd5c2b4523f4f98c745e6), nsis\WhispAssist_0.1.5_x64-setup.exe (8.8MB, SHA256 dfa3a3acf7e9fdfe6d104527d55f660f0b9c0c1364da0cf665113aad60c61422). SHA256SUMS.txt written to C:\wt\release\bundle\. 27MB MSI size confirms Vulkan (CPU-only was 11MB). Release page should upload: the .msi, the -setup.exe, and SHA256SUMS.txt — NOT the .7z runtime bundles (those are hosted in-repo via Git LFS, pulled on-demand from /media/branch/main/runtime/).
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T15:03:01*
|
||||
|
||||
### WhispAssist microphone-capture feature FR-CAP-7 (2...
|
||||
|
||||
WhispAssist microphone-capture feature FR-CAP-7 (2026-07-06, branch feature_chore_bug_002): WA now optionally captures the user's mic alongside loopback and mixes both 16kHz-mono streams into the single transcription worker via audio::spawn_mixer (Mixer struct sums+clamps aligned samples, forwards survivor when one source stalls/ends). New: WasapiCapture::start_microphone (Direction::Capture, no WAV), audio::list_capture_devices, list_input_devices command, Settings.microphone_enabled(default true)+audio_input_device. capture_loop generalized: wav_path Option, direction param, emit_level only for loopback. RecordingSession.mic_capture Option; stop/pause/resume handle both. Settings>Hardware>Audio Devices got a Microphone picker (Off/Default/devices). Loopback WAV stays byte-accurate native; mic is transcript-only (not in WAV/diarization) - tracked ponytail limitation.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T21:34:29*
|
||||
|
||||
### WhispAssist P0+P2 GPU acceleration SHIPPED (2026-0...
|
||||
|
||||
WhispAssist P0+P2 GPU acceleration SHIPPED (2026-07-05, branch chore_debug). P0 (2 commits e9567b8,7fe0d87): AccelPath enum {WhisperCpu,WhisperVulkan,WhisperCuda,OnnxOpenVino,OnnxDirectML} + resolve_accel(_with) in hardware/mod.rs = single source of truth; BackendInfo.available now derived from it (DXGI + NPU), closing the no-op-GPU detection gap; load_transcriber drives engine choice from it. 3 new pure resolver unit tests, all green. P2 (DirectML for AMD/Intel non-Vulkan): ort gains 'directml' feature; OnnxNpuTranscriber RENAMED to OnnxTranscriber (file still npu.rs) — load() now picks OpenVINO(NPU) vs DirectML(Amd/Intel, device_id 0) EP by BackendId over the SAME onnx artifacts; ensure_runtime_env takes the runtime dll path; paths::directml_runtime_dir/dll/ready added (C:\Users\dadous\AppData\Local/WhispAssist/runtime/directml/onnxruntime.dll); download_and_extract_runtime parameterized (sha+ready) and reused by new stage_directml_runtime + download_directml_package command (registered in lib.rs); hardware_status reports a directml field. 104 lib tests + clippy -D warnings all green across feature sets. TESTED end-to-end: directml_transcribes_speech spike (ignored test in npu.rs, env WA_DML_MODEL_DIR/WA_DML_TEST_WAV/WA_DML_BACKEND) run with ORT_DYLIB_PATH=the existing OpenVINO onnxruntime.dll -> FAILED as expected with 'GetProcAddress OrtSessionOptionsAppendExecutionProvider_DML failed' = the OpenVINO ORT build has NO DirectML EP. This PROVES the DML dispatch path selects the EP and fails LOUDLY (error_on_failure) instead of silently. REMAINING for a GREEN GPU run: stage a real DirectML-EP onnxruntime.dll (Microsoft.ML.OnnxRuntime.DirectML) into runtime/directml/, VERSION-MATCHED to ort rc.10 / ORT ~1.24.x (OpenVINO bundle is ORT 1.24.1). No hosted DirectML bundle published yet; WA_DIRECTML_RUNTIME_URL env drives download, empty SHA. CUDA (P1) NOT done yet (needs NVIDIA hw/CI).
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-06T00:45:47*
|
||||
|
||||
### WhispAssist DirectML Settings toggle WIRED (2026-0...
|
||||
|
||||
WhispAssist DirectML Settings toggle WIRED (2026-07-06, branch chore_debug, 4 commits 281ccf0/ceb7e59/1b743da/1b74e0b). Backend: hardware::directml_would_help() (pub, in hardware/mod.rs) = cfg!(feature=npu) && !cfg!(feature=vulkan) && a present AMD/Intel GPU (or NVIDIA when !cfg!(cuda)) via dxgi::enumerate_gpus() presence — gates the card so it stays HIDDEN on the shipping Vulkan build (Vulkan already covers all GPUs) and only shows on CUDA/non-Vulkan builds where a GPU lacks coverage. hardware_status now returns directml:{applicable,runtimeReady,modelInstalled} (mirrors the npu:{} field). Frontend: api.ts HardwareStatus gained directml?:{applicable,runtimeReady,modelInstalled} + api.downloadDirectmlPackage(); Settings.svelte has a 'GPU acceleration (DirectML)' card mirroring the NPU package card (reuses .npu-package CSS), shown when directml.applicable, Ready badge when runtimeReady&&modelInstalled else a Download button -> downloadDirectmlPackage() -> loadHardware(). Progress is await-driven (busy flag), NO % listener — DirectML runtime/model progress still emits on the cosmetic npu://download channel (only 'done' on directml://download). It's a package-DOWNLOAD action, not a persistent on/off toggle; the real 'use this GPU' switch is the existing Preferred-backend dropdown (which now enables AMD/Intel once staged, via the P0 availability fix). clippy -D warnings + svelte-check both clean (fixed a needless_return in directml_would_help by using the cfg-block tail-expression pattern like npu_hardware_present).
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T12:27:50*
|
||||
|
||||
### WhispAssist release 0.1.4 = first Vulkan-enabled b...
|
||||
|
||||
WhispAssist release 0.1.4 = first Vulkan-enabled build. Artifacts: C:\wt\release\bundle\msi\WhispAssist_0.1.4_x64_en-US.msi (27MB), C:\wt\release\bundle\nsis\WhispAssist_0.1.4_x64-setup.exe (8.7MB), C:\wt\release\whispassist.exe (64MB) — sizes jumped from 11MB/4.1MB/13MB (0.1.3 CPU-only) because the Vulkan backend + embedded SPIR-V shaders are statically compiled in. Built via 'npm run tauri build -- --features vulkan' with the [[whispassist-vulkan-build-recipe]] env. REMAINING WIRING GAPS (not yet done): (1) detection-honesty gating — mark GPU backends 'available' only when a vulkan/cuda feature is compiled (cfg!(feature=...)), else best() routes to a no-op GPU; (2) make Vulkan the standing release build flag instead of manual --features vulkan; (3) preferred_backend UI so the user can force Intel GPU (currently best() picks NPU rank-0 over Intel rank-3 on this machine, so the app uses NPU not Vulkan unless overridden).
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-05T22:04:13*
|
||||
|
||||
### WhispAssist Nextcloud sync UX overhaul (2026-07-06...
|
||||
|
||||
WhispAssist Nextcloud sync UX overhaul (2026-07-06, commits 8f6e804/9c670f9). ROOT CAUSE of user's confusion (dwdoubet@box.dou.bet): they were editing with the password field BLANK. WebDavTarget.test() does PROPFIND on base_url+remote_base_path. Bare host https://box.dou.bet + blank pw -> PROPFIND https://box.dou.bet/WhispAssist = NON-DAV path -> 404 (no auth needed) -> test treats 404 as success -> FALSE 'Connected'. Full DAV URL + blank pw -> real DAV endpoint -> 401 -> 'auth failed'. So bare-host 'Connected' was a false positive. FIX 1: WebDavTarget gained provider_hint field; for nextcloud/owncloud, dav_root() derives origin (scheme+host+port) from base_url and builds {origin}/remote.php/dav/files/{username}/ — so users enter ONLY the server URL (https://box.dou.bet) and the app builds the canonical DAV path; a pasted full path is normalized via origin(). Other providers (seafile /seafdav, synology /dav, cloudreve, generic) still use base_url verbatim. url_for uses dav_root(). FIX 2: test_sync_target — for an EXISTING webdav target (id present), it now builds WebDavTarget from the stored row's credential_ref (STORED password) + applies form overrides (base_url/username/remote_base_path/provider_hint/allow_plaintext_lan), unless the user typed a NEW password (temp cred). So Test works after a URL fix WITHOUT re-entering the password. Frontend: davAutoPath derived (provider is nextcloud/owncloud) drives the Server URL placeholder/hint; testConnection passes id in edit mode. Test nextcloud_builds_dav_path_from_server_url added. Correct Nextcloud username here = dwdoubet, host box.dou.bet. NOTE: their existing saved target may just start working after this (url_for rebuilds path from origin+username) if provider_hint=nextcloud. clippy --all-targets + svelte-check + eslint clean; 13 sync tests pass.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T16:11:14*
|
||||
|
||||
---
|
||||
|
||||
## Errors
|
||||
|
||||
*Failure records, bugs, and lessons learned from mistakes.*
|
||||
|
||||
### WhispAssist crash to INVESTIGATE LATER (2026-07-06...
|
||||
|
||||
WhispAssist crash to INVESTIGATE LATER (2026-07-06, dev build, branch feature_chore_bug_002): app crashed with exit code 0x80000003 (STATUS_BREAKPOINT) around DirectML use on an Intel GPU. Repro sequence: NPU recording worked fine (mic capture confirmed working); user then switched to test DirectML, downloaded the DirectML components, then hit Record and it crashed — crash may have occurred DURING the component download or immediately after starting recording. Log evidence at crash: WARN 'ONNX engine load failed (model load failed: Error attempting to load symbol OrtSessionOptionsAppendExecutionProvider_DML from dynamic library: GetProcAddress failed); falling back to CPU', then whisper_model_load loading ggml-small.en-q5_1.bin, then process exited 0x80000003. CONFIRMED unrelated to the microphone/mixer feature (FR-CAP-7) — it's in the DirectML/ONNX + whisper model-load path. Suspect: DirectML runtime download/activation or DML EP symbol-load failure interacting with recording start. Next: reproduce by enabling DirectML on Intel GPU + start recording; check GetProcAddress DML symbol load and whether crash is during download vs whisper load.
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-06T21:59:37*
|
||||
|
||||
### WhispAssist build gotcha (cost ~1hr this session, ...
|
||||
|
||||
WhispAssist build gotcha (cost ~1hr this session, masqueraded as a Node 26 incompatibility): NEVER use PowerShell 'Set-Content -Encoding utf8' on package.json / tauri.conf.json / any JSON or TOML — Windows PowerShell 5.1 writes UTF-8 WITH a BOM. The BOM in package.json breaks vite (fails 'type:module' detection -> 'This package is ESM only but was loaded by require' for @sveltejs/vite-plugin-svelte) AND vitefu (JSON.parse chokes: 'Unexpected token, not valid JSON' -> 'Unable to read package.json'), which fails 'npm run build' / the whole tauri build. Fix: use the Edit tool, or sed, or [System.IO.File]::WriteAllText. Strip an existing BOM with: sed -i '1s/^\xef\xbb\xbf//' file. Node was v26.3.0 at C:\Tools\node but Node was NOT the cause.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-05T22:04:14*
|
||||
|
||||
### Critical recurring issue: WhispAssist debug (dev) ...
|
||||
|
||||
Critical recurring issue: WhispAssist debug (dev) builds hang/stall during whisper.cpp model loading on this machine, apparently due to Trend Micro AV behavior-monitoring interfering with ZwWriteVirtualMemory calls made during model load. Confirmed reproducible even in a bare standalone Rust example binary with zero Tauri/webview involvement, so it is specific to whisper.cpp model loading in a debug-profile binary, not the app shell. Release (optimized+stripped) builds do NOT hit this - confirmed by the user and by direct testing. Escalated to IT, unresolved as of 2026-07-02. Workaround: use release builds for real testing/spot-checking; expect dev-mode launches to sometimes hang at model load and need force-killing.
|
||||
|
||||
*Confidence: 0.9 | Status: active | Created: 2026-07-02T20:14:14*
|
||||
|
||||
### WhispAssist CRITICAL BUG FOUND + FIXED (2026-07-06...
|
||||
|
||||
WhispAssist CRITICAL BUG FOUND + FIXED (2026-07-06): the OS credential store was a NO-OP the entire time. keyring 3.x feature-gates its platform backends and they are OFF by default; 'keyring = { version = "3", optional = true }' had NO backend feature, so on Windows keyring silently used its MOCK keystore. The mock does NOT persist across keyring::Entry instances, so credentials::set (Entry A) appeared to succeed while credentials::get (a fresh Entry B, same service+name) always returned NoEntry -> has_secret=false -> no HTTP Basic auth sent -> 401. This broke ALL sync WebDAV auth, and would break MCP/hosted-AI keys + OAuth tokens too (anything via sync::credentials, SERVICE='WhispAssist-sync'). FIX: keyring = { version = "3", optional = true, features = ["windows-native"] } (pulls dep:windows-sys = real Windows Credential Manager). Confirmed: WA_SYNC_TEST_DIAG went from status=401 has_secret=false to status=207 has_secret=true. DIAGNOSIS JOURNEY (Nextcloud box.dou.bet user dwdoubet): symptom 'auth failed'; the user's credentials + full DAV URL were valid (curl PROPFIND 207). Red herrings: (a) earlier the Nextcloud base_url was missing /remote.php/dav/files/<user>/; (b) a bare-host test gave a FALSE 'Connected' because a non-DAV path 404 is treated as success; (c) blank password in edit test. Real root cause was keyring. TOOLING NOTE: diagnosed via temporary tracing::info! logs (WA_SYNC_CMD_DIAG in test_sync_target = has_id+secret_len; WA_SYNC_SET_DIAG in add branch; WA_SYNC_TEST_DIAG in WebDavTarget::test() = url+status+has_secret) read live from the 'npm run tauri dev' output (tracing filter is 'info' in lib.rs). Also learned keyring feature name = windows-native, and the app's tracing default level is info. These temp diagnostics MUST be removed before release.
|
||||
|
||||
*Confidence: 1.0 | Status: active | Created: 2026-07-06T18:06:13*
|
||||
|
||||
### WhispAssist debug-CRT assertion (found 2026-07 whi...
|
||||
|
||||
WhispAssist debug-CRT assertion (found 2026-07 while running the non-vulkan CPU baseline in DEBUG): the whispassist_lib debug test binary throws MSVC Debug Assertion 'Expression: _osfile(fh) & FOPEN' at ucrt read.cpp:381 = a read() on a CLOSED/invalid file handle. It pops a MODAL Abort/Retry/Ignore dialog that HANGS the test (this is what stalled the overnight non-vulkan baseline run for 8 hours). Only fires under the debug CRT (-MDd); the RELEASE 0.1.4 build does NOT assert (release CRT skips the check), so shipping is unaffected — but the underlying 'read on a closed handle' is latent UB worth root-causing. Likely in the transcription file-read path (whisper.cpp model load or our audio read_wav_mono_16k / vault::open passthrough). ADD to the CPU testing round: investigate this handle bug alongside the ~90s transcribe_file slowness (may or may not be related). Workaround to get a clean non-vulkan CPU number: run 'cargo test --release' (no debug CRT dialog), not plain 'cargo test'.
|
||||
|
||||
*Confidence: 0.95 | Status: active | Created: 2026-07-05T22:07:51*
|
||||
|
||||
---
|
||||
|
||||
*End of memory export.*
|
||||
@@ -320,11 +320,12 @@ segment (the M1 grounding invariant, asserted by the golden-transcript test).
|
||||
"consent_acknowledged": false, // set true after the one-time consent notice (FR-REC-2)
|
||||
},
|
||||
"llm": {
|
||||
"provider": "ollama", // ollama|custom|anthropic|openai|off (ADR-0007/0011)
|
||||
"provider": "ollama", // ollama|custom|anthropic|openai|off (ADR-0007/0011; "openai" not yet wired)
|
||||
"endpoint": "http://localhost:11434",
|
||||
"model": "llama3",
|
||||
"stream": true,
|
||||
// API keys for hosted providers (anthropic|openai) live in the OS credential store, not here.
|
||||
"hosted_ai_acknowledged": false, // one-time "data leaves your device" notice ack (T10.3, ADR-0011)
|
||||
},
|
||||
// Sync target rows live in wa.db (sync_targets); secrets live in the OS credential store.
|
||||
// settings.json only holds the global default. No credentials here (FR-SYNC-6).
|
||||
@@ -338,6 +339,10 @@ segment (the M1 grounding invariant, asserted by the golden-transcript test).
|
||||
"expose_recordings": false, // never serve .wav unless explicitly true (FR-MCP-3)
|
||||
},
|
||||
"privacy": { "encrypt_at_rest": false },
|
||||
// Optional MS Graph calendar source (M4.4, T8.9, FR-CAL-6). Opt-in, explicit consent via OAuth
|
||||
// PKCE — OFF by default. `credential_ref` points into the OS credential store; the token itself
|
||||
// is never written here (same invariant as sync credentials, FR-SYNC-6).
|
||||
"calendar": { "graph_enabled": false, "graph_credential_ref": null },
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -15,7 +15,11 @@ each command returns `Result<T, WaError>` where `WaError` carries a `kind` (mach
|
||||
// `record` (default false) controls audio RETENTION (ADR-0009). When false, working audio is
|
||||
// deleted on finalize and only the transcript/notes persist. It can be toggled mid-meeting.
|
||||
// templateId (Phase 8, T8.1, FR-NOTE-5) picks a NoteTemplate — see list_note_templates below.
|
||||
start_recording(input: { meetingTitle?: string; calendarEventId?: string; record?: boolean; templateId?: string }): MeetingId
|
||||
// language (T8.7, FR-TRX-4, M4.2): omitted/"auto" requests auto-detection; an ISO-639-1 code
|
||||
// (e.g. "es") forces that language. Falls back to Settings.whisper_language when omitted.
|
||||
// Only takes effect with a multilingual model loaded (ModelInfo.multilingual) — an English-only
|
||||
// model forces "en" regardless (see resolve_language in src-tauri/src/transcription/mod.rs).
|
||||
start_recording(input: { meetingTitle?: string; calendarEventId?: string; record?: boolean; templateId?: string; language?: string }): MeetingId
|
||||
stop_recording(input: { meetingId: MeetingId }): MeetingSummaryRef
|
||||
pause_recording(input: { meetingId: MeetingId }): void
|
||||
resume_recording(input: { meetingId: MeetingId }): void
|
||||
@@ -27,11 +31,17 @@ hardware_status(): { backends: BackendInfo[]; active: BackendId; modelSize: stri
|
||||
set_preferred_backend(input: { backend: BackendId | "auto" }): void
|
||||
|
||||
// ---- Transcription / models ----
|
||||
reprocess_transcript(input: { meetingId: MeetingId; model: string }): void // batch mode (FR-TRX-3)
|
||||
// language (T8.7, M4.2): omitted reuses the meeting's current language rather than resetting it.
|
||||
reprocess_transcript(input: { meetingId: MeetingId; model: string; language?: string }): void // batch mode (FR-TRX-3)
|
||||
// ModelInfo gained `multilingual: boolean` (T8.7, FR-TRX-4, M4.2) — false for `.en` (English-only)
|
||||
// ggml variants, true for the multilingual ones; gates the Settings language picker.
|
||||
list_models(): ModelInfo[]
|
||||
list_diarization_models(): ModelInfo[] // fixed seg+emb pair (T4.7, FR-MODEL-1)
|
||||
download_model(input: { kind: "whisper" | "diar-seg" | "diar-emb"; id: string }): void // emits progress events
|
||||
remove_model(input: { id: string }): void // disambiguated by id, not kind — ids never collide across catalogs
|
||||
// Static catalog of whisper.cpp-recognized ISO-639-1 codes for the Settings language dropdown
|
||||
// (T8.7, FR-TRX-4, M4.2); "Auto-detect" is a frontend-only addition, not in this list.
|
||||
list_whisper_languages(): { code: string; label: string }[]
|
||||
|
||||
// ---- Speakers ----
|
||||
rename_speaker(input: { meetingId: MeetingId; label: string; name: string }): void
|
||||
@@ -77,6 +87,13 @@ import_pst(input: { path: string; password?: string }): number // eventsImport
|
||||
list_calendar_events(input: { from?: number; to?: number }): CalendarEvent[]
|
||||
get_calendar_event(input: { eventId: string }): { event: CalendarEvent; participants: Participant[] } // pre-meeting panel + naming dropdown (FR-CAL-3, FR-SPK-4)
|
||||
attach_meeting_to_event(input: { meetingId: MeetingId; eventId: string }): void
|
||||
// Optional MS Graph calendar source (M4.4, T8.9, FR-CAL-6): opt-in, explicit consent (OAuth PKCE
|
||||
// + Microsoft's own consent screen), metadata-only (subject/organizer/start/end/attendees, never
|
||||
// the event body). Not a SyncTarget — begin_graph_calendar_link stores its token separately from
|
||||
// sync_targets and never appears in list_sync_targets.
|
||||
begin_graph_calendar_link(): { authUrl: string } // opens in browser; emits calendar://linked when done
|
||||
import_graph_calendar(input: { from?: number; to?: number }): number // eventsImported; emits calendar://progress
|
||||
disconnect_graph_calendar(): void // best-effort credential cleanup + settings reset
|
||||
|
||||
// ---- Sync / upload (ADR-0010) ---- secrets are passed to add/update but stored only in the OS
|
||||
// credential store; they are NEVER returned by list_sync_targets.
|
||||
@@ -106,6 +123,9 @@ run_agent(input: { briefId: string; tool: "claude" | "codex" | "opencode" | "cop
|
||||
create_issue_from_brief(input: { briefId: string; tracker: "github"; assignCopilot?: boolean }): { url: string } // FR-AGENT-2
|
||||
|
||||
// ---- Settings ----
|
||||
// Settings gained `whisper_language: string | null` (T8.7, FR-TRX-4, M4.2) — the default
|
||||
// transcription language applied at the next start_recording; null = auto-detect. Mirrors
|
||||
// this doc's settings.json `transcription.language` (03-data-model.md).
|
||||
get_settings(): Settings
|
||||
update_settings(input: Partial<Settings>): Settings
|
||||
// Reports the full egress allowlist so the UI can prove exactly what may leave the device (FR-SEC-2).
|
||||
@@ -135,6 +155,8 @@ privacy_self_check(): {
|
||||
"llm://done" { meetingId, summary: SummaryFile } // full summary.json contents, not just a pointer
|
||||
"model://progress" { id, receivedBytes, totalBytes }
|
||||
"pst://progress" { processed, total }
|
||||
"calendar://linked" { ok: boolean, error?: string } // MS Graph OAuth handshake settled (M4.4)
|
||||
"calendar://progress" { processed, total } // MS Graph import (M4.4)
|
||||
"hardware://changed" { active: BackendId, reason: string } // fallback occurred (FR-HW-4)
|
||||
"recording://retention" { meetingId, record: boolean } // retention toggled (FR-REC-1/3)
|
||||
"sync://job" { jobId, meetingId, targetId, artifact, status, bytesSent, bytesTotal } // FR-SYNC-5
|
||||
@@ -205,9 +227,12 @@ pub trait Diarizer: Send + Sync {
|
||||
}
|
||||
|
||||
// calendar/mod.rs
|
||||
// `attendees()` (a second, separate trait method in the original design) was dropped — every
|
||||
// source (PstSource, GraphSource) lists attendees inline per-appointment, so import() returns
|
||||
// them together (see ADR-0008's update). CalImport gained `from`/`to` (M4.4) for a source that
|
||||
// fetches by date range (Graph's calendarView); PstSource ignores them.
|
||||
pub trait CalendarSource: Send + Sync {
|
||||
fn import(&self, input: CalImport) -> Result<Vec<CalendarEvent>, CalError>; // pst|graph|ics
|
||||
fn attendees(&self, event_id: &str) -> Result<Vec<Participant>, CalError>;
|
||||
fn import(&self, input: CalImport) -> Result<Vec<ImportedEvent>, CalError>; // pst|graph|ics
|
||||
}
|
||||
|
||||
// notes/mod.rs
|
||||
|
||||
+6
-5
@@ -251,13 +251,14 @@ Traits/contracts for all of this already exist in `04-api-contracts.md` (`Featur
|
||||
`06-test-strategy.md` (P10 + the cross-cutting egress gate).
|
||||
|
||||
**Status snapshot (what's actually in the tree):**
|
||||
- **Built:** Phases 1–9; `OpenAiCompatProvider` (used as the Phase 5 "custom" endpoint).
|
||||
- **Built:** Phases 1–9; `OpenAiCompatProvider` (used as the Phase 5 "custom" endpoint); chunked/
|
||||
resumable upload (M4.1); multi-language transcription (M4.2); `DropboxTarget`/`BoxTarget` (M4.3);
|
||||
MS Graph `CalendarSource` (`GraphSource`, M4.4).
|
||||
- **Stubbed** (commands return `Err(not_implemented(...))`): `create/list/get_feature_brief`,
|
||||
`set_brief_exposed`, `mcp_status`, `set_mcp_enabled`, `set_mcp_scope`, `mcp_access_log`,
|
||||
`run_agent`, `create_issue_from_brief`.
|
||||
- **Skeleton/absent:** `mcp/mod.rs` (trait + `todo!()` only); `AnthropicProvider` (returns
|
||||
"isn't built yet"); MS Graph `CalendarSource`; multi-language selection; `DropboxTarget`/
|
||||
`BoxTarget` (OAuth wired in `sync/oauth.rs`, upload impl missing); chunked/resumable upload.
|
||||
"isn't built yet").
|
||||
|
||||
**Sequence:** M1 → M2 (briefs are the MCP payload); **M3 can run in parallel** with M1/M2; M4 is
|
||||
opportunistic; **M5 is last and optional**.
|
||||
@@ -367,8 +368,8 @@ M1 (a brief can be distilled by a hosted model). Adds allowlisted egress **by de
|
||||
(select/auto); persist per-meeting `language`; UI localization scaffold. **M** → FR-TRX-4
|
||||
- `[M4.3]` Dropbox/Box upload targets (T9.10): implement `DropboxTarget`/`BoxTarget` `SyncTarget`
|
||||
impls (OAuth is already wired). **M** → FR-SYNC-9
|
||||
- `[M4.4]` *(Defer)* MS Graph calendar source (T8.9) behind `CalendarSource`, consented,
|
||||
metadata-only. **L** → FR-CAL-6 (Could)
|
||||
- `[M4.4]` MS Graph calendar source (T8.9) behind `CalendarSource` (`GraphSource`), consented
|
||||
(OAuth PKCE), metadata-only. **L** → FR-CAL-6 (Could) — **shipped**.
|
||||
|
||||
### M5 — Push handoff (Layer 3, last & optional) → FR-AGENT-1/2 (Could) (T10.10/10.11)
|
||||
Only on demand — the MCP handoff (M2) already covers the agent use case (agents *pull* context).
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "whispassist",
|
||||
"private": true,
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.0",
|
||||
"type": "module",
|
||||
"description": "Privacy-first, fully local Windows meeting assistant.",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
|
||||
Generated
+82
-7
@@ -71,7 +71,7 @@ checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"blake2",
|
||||
"cpufeatures",
|
||||
"cpufeatures 0.2.17",
|
||||
"password-hash",
|
||||
]
|
||||
|
||||
@@ -475,7 +475,18 @@ checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cpufeatures",
|
||||
"cpufeatures 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chacha20"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.0",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -485,7 +496,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
|
||||
dependencies = [
|
||||
"aead",
|
||||
"chacha20",
|
||||
"chacha20 0.9.1",
|
||||
"cipher",
|
||||
"poly1305",
|
||||
"zeroize",
|
||||
@@ -626,6 +637,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc"
|
||||
version = "3.4.0"
|
||||
@@ -1492,6 +1512,7 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi 6.0.0",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1795,6 +1816,12 @@ version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "httpdate"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.10.1"
|
||||
@@ -1808,6 +1835,7 @@ dependencies = [
|
||||
"http",
|
||||
"http-body",
|
||||
"httparse",
|
||||
"httpdate",
|
||||
"itoa",
|
||||
"pin-project-lite",
|
||||
"smallvec 1.15.2",
|
||||
@@ -3140,7 +3168,7 @@ version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
|
||||
dependencies = [
|
||||
"cpufeatures",
|
||||
"cpufeatures 0.2.17",
|
||||
"opaque-debug",
|
||||
"universal-hash",
|
||||
]
|
||||
@@ -3439,6 +3467,17 @@ dependencies = [
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
|
||||
dependencies = [
|
||||
"chacha20 0.10.1",
|
||||
"getrandom 0.4.3",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.3.1"
|
||||
@@ -3477,6 +3516,12 @@ dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
|
||||
|
||||
[[package]]
|
||||
name = "raw-window-handle"
|
||||
version = "0.6.2"
|
||||
@@ -3699,18 +3744,28 @@ checksum = "cc4c9c94680f75470ee8083a0667988b5d7b5beb70b9f998a8e51de7c682ce60"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"futures",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"pastey",
|
||||
"pin-project-lite",
|
||||
"rand 0.10.2",
|
||||
"reqwest 0.13.4",
|
||||
"rmcp-macros",
|
||||
"schemars 1.2.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sse-stream",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tokio-util",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4158,7 +4213,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
]
|
||||
|
||||
@@ -4169,7 +4224,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
]
|
||||
|
||||
@@ -4545,6 +4600,19 @@ dependencies = [
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sse-stream"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f3962b63f038885f15bce2c6e02c0e7925c072f1ac86bb60fd44c5c6b762fb72"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-util",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
@@ -5975,16 +6043,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "whispassist"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"chacha20poly1305",
|
||||
"chrono",
|
||||
"docx-rs",
|
||||
"futures-util",
|
||||
"getrandom 0.2.17",
|
||||
"hound",
|
||||
"http",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"keyring",
|
||||
"ort",
|
||||
"printpdf",
|
||||
@@ -6003,6 +6076,8 @@ dependencies = [
|
||||
"tauri-plugin-dialog",
|
||||
"thiserror 1.0.69",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
|
||||
+27
-4
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "whispassist"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
description = "Privacy-first, fully local Windows meeting assistant"
|
||||
authors = ["WhispAssist contributors"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
@@ -23,7 +23,7 @@ serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "1"
|
||||
async-trait = "0.1"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "fs"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "fs", "io-util", "net"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
@@ -47,7 +47,26 @@ chacha20poly1305 = "0.10"
|
||||
getrandom = "0.2"
|
||||
zeroize = "1" # wipe key material from memory on lock
|
||||
keyring = { version = "3", optional = true, features = ["windows-native"] } # OS credential store (sync + AI creds); windows-native = real Credential Manager (else keyring 3.x uses a no-op mock store)
|
||||
rmcp = { version = "0.16", optional = true, features = ["server"] } # MCP server (ADR-0011)
|
||||
# MCP server (ADR-0011). `client`/`transport-streamable-http-client-reqwest`
|
||||
# are only ever constructed by this crate's own in-process tests (an actual
|
||||
# MCP client talking to our loopback server) -- WA never opens an outbound
|
||||
# MCP connection at runtime, so this adds no egress (FR-MCP-7).
|
||||
rmcp = { version = "0.16", optional = true, features = [
|
||||
"server", "transport-streamable-http-server", "transport-io",
|
||||
"client", "transport-streamable-http-client-reqwest",
|
||||
] }
|
||||
# Low-level HTTP glue for the Streamable HTTP transport: `rmcp`'s
|
||||
# `StreamableHttpService` is a bare `tower_service::Service`, so something has
|
||||
# to actually accept TCP connections and run HTTP/1 on top of it. All four
|
||||
# versions are already in Cargo.lock transitively (via reqwest/tauri), so this
|
||||
# just promotes them to direct deps -- no new crates.
|
||||
hyper = { version = "1", optional = true, features = ["server", "http1"] }
|
||||
hyper-util = { version = "0.1", optional = true, features = ["tokio"] }
|
||||
http-body-util = { version = "0.1", optional = true }
|
||||
http = { version = "1", optional = true }
|
||||
bytes = { version = "1", optional = true }
|
||||
tower-service = { version = "0.3", optional = true }
|
||||
tokio-util = { version = "0.7", optional = true }
|
||||
|
||||
# audio / transcription / diarization / calendar are integrated per-phase and are
|
||||
# feature-gated so the CPU-only build always compiles (NFR-MNT-4).
|
||||
@@ -106,7 +125,11 @@ pst = [] # shells out to readpst (libpst) — no cra
|
||||
# Phase 9
|
||||
sync = ["dep:keyring"] # remote upload (WebDAV + OAuth providers)
|
||||
# Phase 10
|
||||
mcp = ["dep:rmcp", "dep:keyring"] # WhispAssist as an MCP server + hosted-AI creds
|
||||
mcp = [
|
||||
"dep:rmcp", "dep:keyring", "dep:hyper", "dep:hyper-util",
|
||||
"dep:http-body-util", "dep:http", "dep:bytes", "dep:tower-service",
|
||||
"dep:tokio-util",
|
||||
] # WhispAssist as an MCP server + hosted-AI creds
|
||||
|
||||
[profile.release]
|
||||
opt-level = "z" # optimize for size — keep the binary small (NFR-RES-1)
|
||||
|
||||
@@ -0,0 +1,574 @@
|
||||
//! Feature-brief distiller (Phase 10 M1, ADR-0011, FR-MCP-4/T10.6). Turns a
|
||||
//! finished meeting's transcript into an agent-ready spec via the configured
|
||||
//! `LlmProvider` — no new egress, no new dependency: it's the same provider
|
||||
//! `generate_summary` already talks to.
|
||||
//!
|
||||
//! The distillation itself (`distill`) is a plain function over an
|
||||
//! `LlmProvider` + transcript data, independent of `Store` — that's what lets
|
||||
//! the golden-transcript test exercise it with a `MockLlmProvider` and no
|
||||
//! database at all. `LlmFeatureBriefBuilder` is the thin `Store`-aware
|
||||
//! adapter the `FeatureBriefBuilder` trait (`docs/04-api-contracts.md`)
|
||||
//! describes, used by `commands::create_feature_brief`.
|
||||
|
||||
use crate::llm::{bullet_text, LlmError, LlmProvider};
|
||||
use crate::models::{ContextExcerpt, FeatureBrief, MeetingId, SpeakerInfo, TranscriptSegment};
|
||||
use crate::storage::{Store, StoreError};
|
||||
use async_trait::async_trait;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum BriefError {
|
||||
#[error("storage error: {0}")]
|
||||
Store(#[from] StoreError),
|
||||
#[error("llm error: {0}")]
|
||||
Llm(#[from] LlmError),
|
||||
}
|
||||
|
||||
/// Builds the agent-ready spec from a transcript via the configured
|
||||
/// `LlmProvider` (`docs/04-api-contracts.md`).
|
||||
#[async_trait]
|
||||
pub trait FeatureBriefBuilder: Send + Sync {
|
||||
async fn build(
|
||||
&self,
|
||||
meeting_id: &MeetingId,
|
||||
target_repo: Option<&str>,
|
||||
) -> Result<FeatureBrief, BriefError>;
|
||||
}
|
||||
|
||||
/// System prompt contract (mirrors `llm::RESPONSE_FORMAT_INSTRUCTIONS`):
|
||||
/// exactly four sections, in order, nothing invented beyond the transcript.
|
||||
const BRIEF_INSTRUCTIONS: &str = "Distill this transcript into an implementation brief for a \
|
||||
coding agent. Respond in Markdown with exactly, in order: \"## Title\" (one line), \
|
||||
\"## Problem\", \"## Desired Outcome\", \"## Acceptance Criteria\" (a \"- \" bullet list, one \
|
||||
testable criterion per line). Be concrete and terse; invent nothing not in the transcript; no \
|
||||
other sections.";
|
||||
|
||||
/// Parsed reply, before assembly into the IPC/file shapes.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct BriefFields {
|
||||
pub title: String,
|
||||
pub problem: String,
|
||||
pub desired_outcome: String,
|
||||
pub acceptance_criteria: Vec<String>,
|
||||
}
|
||||
|
||||
/// Assembles the (system, user) prompt pair — metadata + optional
|
||||
/// `target_repo` hint + the transcript, mirroring `commands::build_prompt`'s
|
||||
/// shape for `summarize`.
|
||||
fn build_brief_messages(
|
||||
meeting_title: &str,
|
||||
participants: &[String],
|
||||
target_repo: Option<&str>,
|
||||
transcript: &str,
|
||||
) -> (String, String) {
|
||||
let mut user = format!("Meeting: {meeting_title}\n");
|
||||
if !participants.is_empty() {
|
||||
user.push_str(&format!("Participants: {}\n", participants.join(", ")));
|
||||
}
|
||||
if let Some(repo) = target_repo {
|
||||
user.push_str(&format!("Target repo: {repo}\n"));
|
||||
}
|
||||
user.push_str("\nTranscript:\n");
|
||||
user.push_str(transcript);
|
||||
(BRIEF_INSTRUCTIONS.to_string(), user)
|
||||
}
|
||||
|
||||
/// Splits a "## Title / ## Problem / ## Desired Outcome / ## Acceptance
|
||||
/// Criteria" Markdown reply (see `BRIEF_INSTRUCTIONS`) into `BriefFields` —
|
||||
/// mirrors `llm::parse_summary`. A missing/malformed section never panics:
|
||||
/// `title`/`problem`/`desired_outcome` fall back to `""` (title falls back
|
||||
/// further, to `meeting_title`, since a brief with no title at all is
|
||||
/// unusable), and `acceptance_criteria` falls back to `[]`.
|
||||
pub fn parse_brief(md: &str, meeting_title: &str) -> BriefFields {
|
||||
let mut title = String::new();
|
||||
let mut problem = String::new();
|
||||
let mut desired_outcome = String::new();
|
||||
let mut acceptance_criteria = Vec::new();
|
||||
let mut section = -1i8; // 0 title, 1 problem, 2 desired outcome, 3 acceptance criteria, -1 other/unknown
|
||||
|
||||
for line in md.lines() {
|
||||
let lower = line.trim().to_ascii_lowercase();
|
||||
if lower.starts_with("## title") {
|
||||
section = 0;
|
||||
continue;
|
||||
}
|
||||
if lower.starts_with("## problem") {
|
||||
section = 1;
|
||||
continue;
|
||||
}
|
||||
if lower.starts_with("## desired outcome") {
|
||||
section = 2;
|
||||
continue;
|
||||
}
|
||||
if lower.starts_with("## acceptance criteria") {
|
||||
section = 3;
|
||||
continue;
|
||||
}
|
||||
if line.trim_start().starts_with('#') {
|
||||
section = -1;
|
||||
continue;
|
||||
}
|
||||
match section {
|
||||
0 => {
|
||||
let text = line.trim();
|
||||
if !text.is_empty() {
|
||||
if !title.is_empty() {
|
||||
title.push(' ');
|
||||
}
|
||||
title.push_str(text);
|
||||
}
|
||||
}
|
||||
1 => {
|
||||
problem.push_str(line);
|
||||
problem.push('\n');
|
||||
}
|
||||
2 => {
|
||||
desired_outcome.push_str(line);
|
||||
desired_outcome.push('\n');
|
||||
}
|
||||
3 => {
|
||||
if let Some(item) = bullet_text(line) {
|
||||
acceptance_criteria.push(item);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let title = title.trim().to_string();
|
||||
BriefFields {
|
||||
title: if title.is_empty() {
|
||||
meeting_title.to_string()
|
||||
} else {
|
||||
title
|
||||
},
|
||||
problem: problem.trim().to_string(),
|
||||
desired_outcome: desired_outcome.trim().to_string(),
|
||||
acceptance_criteria,
|
||||
}
|
||||
}
|
||||
|
||||
/// Lowercased alphanumeric words of length >= 3 — short enough to skip
|
||||
/// common stopwords ("the", "to", "we") without a stopword list, long enough
|
||||
/// to still catch meaningful terms.
|
||||
fn keywords(text: &str) -> HashSet<String> {
|
||||
text.split(|c: char| !c.is_alphanumeric())
|
||||
.filter(|w| w.len() >= 3)
|
||||
.map(|w| w.to_ascii_lowercase())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn display_name(label: &str, speakers: &[SpeakerInfo]) -> String {
|
||||
speakers
|
||||
.iter()
|
||||
.find(|s| s.label == label)
|
||||
.and_then(|s| s.display_name.clone())
|
||||
.unwrap_or_else(|| label.to_string())
|
||||
}
|
||||
|
||||
const MIN_EXCERPT_LEN: usize = 40;
|
||||
const MAX_EXCERPTS: usize = 5;
|
||||
const FALLBACK_EXCERPTS: usize = 3;
|
||||
|
||||
/// Selects grounding excerpts for a brief (the M1 grounding invariant: every
|
||||
/// returned `text` is copied verbatim from a transcript segment — never
|
||||
/// model paraphrase). Scores each substantive segment (>= ~40 chars) by
|
||||
/// keyword overlap with `problem` + `acceptance_criteria`, taking the top
|
||||
/// <= 5; falls back to the first 3 substantive segments if nothing scores
|
||||
/// (e.g. a terse reply with too few keywords, or a transcript that just
|
||||
/// doesn't share vocabulary with the drafted brief).
|
||||
// ponytail: keyword-overlap select; upgrade to embedding similarity if excerpts feel off
|
||||
fn context_excerpts(
|
||||
fields: &BriefFields,
|
||||
segments: &[TranscriptSegment],
|
||||
speakers: &[SpeakerInfo],
|
||||
) -> Vec<ContextExcerpt> {
|
||||
let mut query = keywords(&fields.problem);
|
||||
query.extend(keywords(&fields.acceptance_criteria.join(" ")));
|
||||
|
||||
let substantive: Vec<&TranscriptSegment> = segments
|
||||
.iter()
|
||||
.filter(|s| s.text.trim().len() >= MIN_EXCERPT_LEN)
|
||||
.collect();
|
||||
|
||||
if !query.is_empty() {
|
||||
let mut scored: Vec<(usize, &TranscriptSegment)> = substantive
|
||||
.iter()
|
||||
.map(|&s| (keywords(&s.text).intersection(&query).count(), s))
|
||||
.filter(|(overlap, _)| *overlap > 0)
|
||||
.collect();
|
||||
if !scored.is_empty() {
|
||||
// Stable sort keeps original (chronological) order among ties.
|
||||
scored.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
return scored
|
||||
.into_iter()
|
||||
.take(MAX_EXCERPTS)
|
||||
.map(|(_, s)| ContextExcerpt {
|
||||
speaker: display_name(&s.speaker, speakers),
|
||||
text: s.text.clone(),
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
|
||||
substantive
|
||||
.into_iter()
|
||||
.take(FALLBACK_EXCERPTS)
|
||||
.map(|s| ContextExcerpt {
|
||||
speaker: display_name(&s.speaker, speakers),
|
||||
text: s.text.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Transcript-derived inputs `distill` needs — bundled into one struct so the
|
||||
/// function stays under clippy's argument-count lint rather than taking each
|
||||
/// field positionally.
|
||||
struct MeetingContext<'a> {
|
||||
title: &'a str,
|
||||
participants: &'a [String],
|
||||
transcript_md: &'a str,
|
||||
segments: &'a [TranscriptSegment],
|
||||
speakers: &'a [SpeakerInfo],
|
||||
}
|
||||
|
||||
/// Core distillation: prompt -> LLM round trip -> parse -> ground. Takes
|
||||
/// transcript data directly rather than a `MeetingId`, so it needs no
|
||||
/// `Store` — `LlmFeatureBriefBuilder::build` below is the `Store`-aware
|
||||
/// wrapper that looks the meeting up first.
|
||||
async fn distill(
|
||||
llm: &dyn LlmProvider,
|
||||
meeting_id: &MeetingId,
|
||||
target_repo: Option<&str>,
|
||||
ctx: &MeetingContext<'_>,
|
||||
) -> Result<FeatureBrief, BriefError> {
|
||||
let (system, user) =
|
||||
build_brief_messages(ctx.title, ctx.participants, target_repo, ctx.transcript_md);
|
||||
let reply = llm.complete(&system, &user).await?;
|
||||
let fields = parse_brief(&reply, ctx.title);
|
||||
let context_excerpts = context_excerpts(&fields, ctx.segments, ctx.speakers);
|
||||
Ok(FeatureBrief {
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
meeting_id: meeting_id.clone(),
|
||||
title: fields.title,
|
||||
problem: fields.problem,
|
||||
desired_outcome: fields.desired_outcome,
|
||||
acceptance_criteria: fields.acceptance_criteria,
|
||||
target_repo: target_repo.map(str::to_string),
|
||||
context_excerpts,
|
||||
})
|
||||
}
|
||||
|
||||
/// `FeatureBriefBuilder` impl used by `commands::create_feature_brief`:
|
||||
/// loads the meeting via `store`, then distills it with `llm`.
|
||||
pub struct LlmFeatureBriefBuilder {
|
||||
pub store: Arc<dyn Store>,
|
||||
pub llm: Box<dyn LlmProvider>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl FeatureBriefBuilder for LlmFeatureBriefBuilder {
|
||||
async fn build(
|
||||
&self,
|
||||
meeting_id: &MeetingId,
|
||||
target_repo: Option<&str>,
|
||||
) -> Result<FeatureBrief, BriefError> {
|
||||
let meeting = self.store.get_meeting(meeting_id).await?;
|
||||
let participants: Vec<String> = meeting
|
||||
.speakers
|
||||
.iter()
|
||||
.map(|s| s.display_name.clone().unwrap_or_else(|| s.label.clone()))
|
||||
.collect();
|
||||
let ctx = MeetingContext {
|
||||
title: &meeting.title,
|
||||
participants: &participants,
|
||||
transcript_md: &meeting.notes_markdown,
|
||||
segments: &meeting.segments,
|
||||
speakers: &meeting.speakers,
|
||||
};
|
||||
distill(self.llm.as_ref(), meeting_id, target_repo, &ctx).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::llm::{LlmStatus, Prompt, Summary, TokenSink};
|
||||
|
||||
/// No-network stand-in for a real provider (T10.6 test — the golden-
|
||||
/// transcript builder test must never touch a socket). Only `complete`
|
||||
/// is exercised by `distill`; the rest are unused stubs.
|
||||
struct MockLlmProvider {
|
||||
reply: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl LlmProvider for MockLlmProvider {
|
||||
async fn status(&self) -> LlmStatus {
|
||||
LlmStatus {
|
||||
provider: "mock".to_string(),
|
||||
reachable: true,
|
||||
is_local: true,
|
||||
models: Vec::new(),
|
||||
}
|
||||
}
|
||||
async fn summarize(&self, _prompt: Prompt, _out: TokenSink) -> Result<Summary, LlmError> {
|
||||
unimplemented!("not exercised by the brief-builder test")
|
||||
}
|
||||
async fn suggest_tags(&self, _transcript: &str) -> Result<Vec<String>, LlmError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
async fn complete(&self, _system: &str, _user: &str) -> Result<String, LlmError> {
|
||||
Ok(self.reply.clone())
|
||||
}
|
||||
fn is_local(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
const GOLDEN_REPLY: &str = "## Title\n\
|
||||
Bulk CSV export for the reporting view\n\n\
|
||||
## Problem\n\
|
||||
Customers can't get their filtered report data out for offline analysis.\n\n\
|
||||
## Desired Outcome\n\
|
||||
One-click CSV export of the current filtered report.\n\n\
|
||||
## Acceptance Criteria\n\
|
||||
- Export button on the report toolbar\n\
|
||||
- Respects active filters and column order\n\
|
||||
- Streams large exports without blocking the UI\n";
|
||||
|
||||
fn seg(id: u64, speaker: &str, text: &str) -> TranscriptSegment {
|
||||
TranscriptSegment {
|
||||
id,
|
||||
start_ms: id * 1000,
|
||||
end_ms: id * 1000 + 900,
|
||||
speaker: speaker.to_string(),
|
||||
text: text.to_string(),
|
||||
confidence: Some(0.9),
|
||||
interim: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn golden_segments() -> Vec<TranscriptSegment> {
|
||||
vec![
|
||||
seg(0, "S1", "Let's start with the reporting view."),
|
||||
seg(
|
||||
1,
|
||||
"S2",
|
||||
"We really need to pull this filtered report into our own spreadsheets for offline analysis.",
|
||||
),
|
||||
seg(2, "S1", "Makes sense — what would the export button need to respect?"),
|
||||
seg(
|
||||
3,
|
||||
"S2",
|
||||
"It has to respect the active filters and the column order we've already set up.",
|
||||
),
|
||||
seg(4, "S1", "And it can't block the UI while a large export streams out."),
|
||||
seg(5, "S2", "Right, exactly."),
|
||||
]
|
||||
}
|
||||
|
||||
fn golden_speakers() -> Vec<SpeakerInfo> {
|
||||
vec![
|
||||
SpeakerInfo {
|
||||
label: "S1".to_string(),
|
||||
display_name: Some("Alex".to_string()),
|
||||
participant_id: None,
|
||||
},
|
||||
SpeakerInfo {
|
||||
label: "S2".to_string(),
|
||||
display_name: Some("Customer".to_string()),
|
||||
participant_id: None,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
// ---- parse_brief ----
|
||||
|
||||
#[test]
|
||||
fn parse_brief_splits_the_four_requested_sections() {
|
||||
let fields = parse_brief(GOLDEN_REPLY, "fallback title");
|
||||
assert_eq!(fields.title, "Bulk CSV export for the reporting view");
|
||||
assert_eq!(
|
||||
fields.problem,
|
||||
"Customers can't get their filtered report data out for offline analysis."
|
||||
);
|
||||
assert_eq!(
|
||||
fields.desired_outcome,
|
||||
"One-click CSV export of the current filtered report."
|
||||
);
|
||||
assert_eq!(
|
||||
fields.acceptance_criteria,
|
||||
vec![
|
||||
"Export button on the report toolbar",
|
||||
"Respects active filters and column order",
|
||||
"Streams large exports without blocking the UI",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_brief_falls_back_to_the_meeting_title_when_no_title_section() {
|
||||
let text = "## Problem\nSomething broke.\n";
|
||||
let fields = parse_brief(text, "Sprint planning");
|
||||
assert_eq!(fields.title, "Sprint planning");
|
||||
assert_eq!(fields.problem, "Something broke.");
|
||||
assert_eq!(fields.desired_outcome, "");
|
||||
assert!(fields.acceptance_criteria.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_brief_of_empty_or_malformed_input_is_empty_and_does_not_panic() {
|
||||
let fields = parse_brief("", "Meeting title");
|
||||
assert_eq!(fields.title, "Meeting title");
|
||||
assert_eq!(fields.problem, "");
|
||||
assert_eq!(fields.desired_outcome, "");
|
||||
assert!(fields.acceptance_criteria.is_empty());
|
||||
|
||||
// No recognized headings at all — everything before the first `#`
|
||||
// (there is none) is just unattributed prose, so nothing is captured.
|
||||
let fields = parse_brief("just some prose with no headings", "Meeting title");
|
||||
assert_eq!(fields.title, "Meeting title");
|
||||
assert!(fields.problem.is_empty());
|
||||
assert!(fields.acceptance_criteria.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_brief_ignores_unrecognized_extra_sections() {
|
||||
let text = "## Title\nFix the thing\n\n## Notes\nirrelevant chatter\n\n\
|
||||
## Acceptance Criteria\n- It works\n";
|
||||
let fields = parse_brief(text, "fallback");
|
||||
assert_eq!(fields.title, "Fix the thing");
|
||||
assert_eq!(fields.acceptance_criteria, vec!["It works"]);
|
||||
}
|
||||
|
||||
// ---- context_excerpts / grounding invariant ----
|
||||
|
||||
#[test]
|
||||
fn context_excerpts_are_verbatim_substrings_of_a_transcript_segment() {
|
||||
let fields = parse_brief(GOLDEN_REPLY, "fallback");
|
||||
let segments = golden_segments();
|
||||
let speakers = golden_speakers();
|
||||
let excerpts = context_excerpts(&fields, &segments, &speakers);
|
||||
assert!(!excerpts.is_empty());
|
||||
for excerpt in &excerpts {
|
||||
assert!(
|
||||
segments.iter().any(|s| s.text.contains(&excerpt.text)),
|
||||
"excerpt {:?} is not a verbatim substring of any transcript segment",
|
||||
excerpt.text
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_excerpts_resolve_speaker_display_names() {
|
||||
let fields = parse_brief(GOLDEN_REPLY, "fallback");
|
||||
let segments = golden_segments();
|
||||
let speakers = golden_speakers();
|
||||
let excerpts = context_excerpts(&fields, &segments, &speakers);
|
||||
assert!(excerpts.iter().any(|e| e.speaker == "Customer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_excerpts_falls_back_to_first_substantive_segments_with_no_keyword_overlap() {
|
||||
let fields = BriefFields {
|
||||
title: "t".to_string(),
|
||||
problem: "zzzzz qqqqq".to_string(), // shares no vocabulary with the transcript
|
||||
desired_outcome: String::new(),
|
||||
acceptance_criteria: vec!["wwwww".to_string()],
|
||||
};
|
||||
let segments = golden_segments();
|
||||
let excerpts = context_excerpts(&fields, &segments, &golden_speakers());
|
||||
assert_eq!(excerpts.len(), FALLBACK_EXCERPTS);
|
||||
for excerpt in &excerpts {
|
||||
assert!(segments.iter().any(|s| s.text.contains(&excerpt.text)));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- distill (the FeatureBriefBuilder golden-transcript test) ----
|
||||
|
||||
#[tokio::test]
|
||||
async fn distill_over_a_golden_transcript_yields_grounded_non_empty_criteria() {
|
||||
let llm = MockLlmProvider {
|
||||
reply: GOLDEN_REPLY.to_string(),
|
||||
};
|
||||
let segments = golden_segments();
|
||||
let speakers = golden_speakers();
|
||||
let participants: Vec<String> = speakers
|
||||
.iter()
|
||||
.map(|s| s.display_name.clone().unwrap())
|
||||
.collect();
|
||||
let transcript_md = segments
|
||||
.iter()
|
||||
.map(|s| format!("**{}:** {}", s.speaker, s.text))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
let ctx = MeetingContext {
|
||||
title: "Reporting sync",
|
||||
participants: &participants,
|
||||
transcript_md: &transcript_md,
|
||||
segments: &segments,
|
||||
speakers: &speakers,
|
||||
};
|
||||
let brief = distill(&llm, &"m1".to_string(), Some("acme/reporting-web"), &ctx)
|
||||
.await
|
||||
.expect("distill should succeed against the mock provider");
|
||||
|
||||
assert_eq!(brief.meeting_id, "m1");
|
||||
assert_eq!(brief.title, "Bulk CSV export for the reporting view");
|
||||
assert!(!brief.acceptance_criteria.is_empty());
|
||||
assert_eq!(brief.target_repo.as_deref(), Some("acme/reporting-web"));
|
||||
assert!(!brief.context_excerpts.is_empty());
|
||||
for excerpt in &brief.context_excerpts {
|
||||
assert!(
|
||||
segments.iter().any(|s| s.text.contains(&excerpt.text)),
|
||||
"grounding invariant violated: {:?}",
|
||||
excerpt.text
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn distill_propagates_an_llm_error_without_panicking() {
|
||||
struct FailingProvider;
|
||||
#[async_trait]
|
||||
impl LlmProvider for FailingProvider {
|
||||
async fn status(&self) -> LlmStatus {
|
||||
LlmStatus {
|
||||
provider: "mock".to_string(),
|
||||
reachable: false,
|
||||
is_local: true,
|
||||
models: Vec::new(),
|
||||
}
|
||||
}
|
||||
async fn summarize(
|
||||
&self,
|
||||
_prompt: Prompt,
|
||||
_out: TokenSink,
|
||||
) -> Result<Summary, LlmError> {
|
||||
unimplemented!()
|
||||
}
|
||||
async fn suggest_tags(&self, _transcript: &str) -> Result<Vec<String>, LlmError> {
|
||||
unimplemented!()
|
||||
}
|
||||
async fn complete(&self, _system: &str, _user: &str) -> Result<String, LlmError> {
|
||||
Err(LlmError::Unreachable("connection refused".to_string()))
|
||||
}
|
||||
fn is_local(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
let ctx = MeetingContext {
|
||||
title: "Meeting",
|
||||
participants: &[],
|
||||
transcript_md: "transcript",
|
||||
segments: &[],
|
||||
speakers: &[],
|
||||
};
|
||||
let result = distill(&FailingProvider, &"m1".to_string(), None, &ctx).await;
|
||||
assert!(matches!(result, Err(BriefError::Llm(_))));
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
use crate::models::{AttendeeInfo, CalendarEvent, ImportedEvent};
|
||||
use chrono::{Datelike, Duration, Local, NaiveDate, TimeZone, Timelike, Utc};
|
||||
use serde::Deserialize;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
@@ -23,11 +24,18 @@ pub enum CalError {
|
||||
Password,
|
||||
#[error("readpst isn't installed — install libpst and ensure readpst is on PATH")]
|
||||
ToolMissing,
|
||||
#[error("network request failed: {0}")]
|
||||
Network(String),
|
||||
}
|
||||
|
||||
pub struct CalImport {
|
||||
pub path: String,
|
||||
pub password: Option<String>,
|
||||
/// Date-range window (unix seconds) for a source that fetches by range
|
||||
/// (Graph's `calendarView`, M4.4); ignored by file-based sources like
|
||||
/// `PstSource`, which import everything a `.pst` contains.
|
||||
pub from: Option<i64>,
|
||||
pub to: Option<i64>,
|
||||
}
|
||||
|
||||
pub trait CalendarSource: Send + Sync {
|
||||
@@ -121,6 +129,205 @@ fn collect_ics_files(dir: &Path, out: &mut Vec<ImportedEvent>) -> Result<(), Cal
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- Microsoft Graph calendar source (M4.4, T8.9, FR-CAL-6) ----
|
||||
//
|
||||
// Opt-in, explicit-consent (OAuth 2.0 PKCE via `sync::oauth` — same identity
|
||||
// platform and token-set shape as the OneDrive sync target, ADR-0010) and
|
||||
// metadata-only per ADR-0008: subject, organizer, start/end, attendees —
|
||||
// never the event body. Uses Graph's `calendarView` endpoint, which expands
|
||||
// recurring series into concrete occurrences server-side, so unlike
|
||||
// `PstSource` there's no local RRULE expansion to do.
|
||||
#[cfg(feature = "sync")]
|
||||
pub struct GraphSource {
|
||||
pub credential_ref: String,
|
||||
}
|
||||
|
||||
// ponytail: one page (no `@odata.nextLink` follow) — plenty for a personal
|
||||
// calendar's near-term window; add pagination if a real user's date range
|
||||
// ever needs more than this in one import.
|
||||
#[cfg(feature = "sync")]
|
||||
const GRAPH_EVENTS_PAGE_SIZE: u32 = 250;
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
impl GraphSource {
|
||||
/// Graph API base — overridable via `WA_GRAPH_CALENDAR_BASE_URL` so tests
|
||||
/// can point this at a local mock. Kept distinct from sync's
|
||||
/// `WA_GRAPH_BASE_URL` (used by `OneDriveTarget`) so calendar and sync
|
||||
/// tests never race on the same process-global env var.
|
||||
fn graph_base() -> String {
|
||||
std::env::var("WA_GRAPH_CALENDAR_BASE_URL")
|
||||
.ok()
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or_else(|| "https://graph.microsoft.com/v1.0".to_string())
|
||||
}
|
||||
|
||||
async fn fetch_events(&self, from: i64, to: i64) -> Result<Vec<ImportedEvent>, CalError> {
|
||||
let token = crate::sync::resolve_access_token("graph-calendar", &self.credential_ref)
|
||||
.await
|
||||
.map_err(|e| CalError::Network(e.to_string()))?;
|
||||
let url = format!(
|
||||
"{}/me/calendarView?startDateTime={}&endDateTime={}&$select=id,subject,organizer,start,end,attendees&$top={}",
|
||||
Self::graph_base(),
|
||||
iso_datetime(from),
|
||||
iso_datetime(to),
|
||||
GRAPH_EVENTS_PAGE_SIZE,
|
||||
);
|
||||
let resp = reqwest::Client::new()
|
||||
.get(&url)
|
||||
// Ask Graph to return every dateTime already normalized to UTC —
|
||||
// avoids needing a timezone database (same tradeoff PST parsing
|
||||
// makes: see `parse_ics_datetime`'s doc comment).
|
||||
.header("Prefer", r#"outlook.timezone="UTC""#)
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| CalError::Network(e.to_string()))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(CalError::Network(format!(
|
||||
"graph calendarView returned {}",
|
||||
resp.status()
|
||||
)));
|
||||
}
|
||||
let body: GraphEventsResponse = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| CalError::Parse(e.to_string()))?;
|
||||
Ok(body
|
||||
.value
|
||||
.into_iter()
|
||||
.map(graph_event_to_imported)
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
impl CalendarSource for GraphSource {
|
||||
/// Sync per the trait — bridges to the async Graph call via
|
||||
/// `tauri::async_runtime::block_on`. Callers (the `import_graph_calendar`
|
||||
/// command) run this inside `spawn_blocking`, exactly like `PstSource`'s
|
||||
/// blocking subprocess call.
|
||||
fn import(&self, input: CalImport) -> Result<Vec<ImportedEvent>, CalError> {
|
||||
let now = Utc::now().timestamp();
|
||||
let from = input.from.unwrap_or(now - 30 * 86_400);
|
||||
let to = input.to.unwrap_or(now + 90 * 86_400);
|
||||
tauri::async_runtime::block_on(self.fetch_events(from, to))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
#[derive(Deserialize)]
|
||||
struct GraphEventsResponse {
|
||||
value: Vec<GraphEvent>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
#[derive(Deserialize)]
|
||||
struct GraphEvent {
|
||||
id: String,
|
||||
subject: Option<String>,
|
||||
organizer: Option<GraphOrganizer>,
|
||||
start: Option<GraphDateTime>,
|
||||
end: Option<GraphDateTime>,
|
||||
attendees: Option<Vec<GraphAttendee>>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
#[derive(Deserialize)]
|
||||
struct GraphOrganizer {
|
||||
#[serde(rename = "emailAddress")]
|
||||
email_address: GraphEmailAddress,
|
||||
}
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
#[derive(Deserialize)]
|
||||
struct GraphEmailAddress {
|
||||
name: Option<String>,
|
||||
address: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
#[derive(Deserialize)]
|
||||
struct GraphDateTime {
|
||||
#[serde(rename = "dateTime")]
|
||||
date_time: String,
|
||||
}
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
#[derive(Deserialize)]
|
||||
struct GraphAttendee {
|
||||
#[serde(rename = "emailAddress")]
|
||||
email_address: GraphEmailAddress,
|
||||
// required|optional|resource, passed through as-is (Graph's own vocabulary
|
||||
// is a superset of the organizer|required|optional convention the rest of
|
||||
// WA uses for attendee role).
|
||||
#[serde(rename = "type")]
|
||||
kind: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
fn graph_event_to_imported(e: GraphEvent) -> ImportedEvent {
|
||||
let attendees = e
|
||||
.attendees
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|a| {
|
||||
let name = a
|
||||
.email_address
|
||||
.name
|
||||
.or_else(|| a.email_address.address.clone())?;
|
||||
Some(AttendeeInfo {
|
||||
name,
|
||||
email: a.email_address.address,
|
||||
role: a.kind,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let organizer = e
|
||||
.organizer
|
||||
.and_then(|o| o.email_address.name.or(o.email_address.address));
|
||||
ImportedEvent {
|
||||
event: CalendarEvent {
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
source: "graph".to_string(),
|
||||
subject: e.subject,
|
||||
organizer,
|
||||
starts_at: e.start.and_then(|s| parse_graph_datetime(&s.date_time)),
|
||||
ends_at: e.end.and_then(|s| parse_graph_datetime(&s.date_time)),
|
||||
description: None, // metadata only (FR-CAL-6) — the event body is never fetched
|
||||
raw_uid: Some(e.id),
|
||||
},
|
||||
attendees,
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats a unix timestamp as the `YYYY-MM-DDTHH:MM:SS` Graph's
|
||||
/// `calendarView` query params expect.
|
||||
#[cfg(feature = "sync")]
|
||||
fn iso_datetime(unix_secs: i64) -> String {
|
||||
Utc.timestamp_opt(unix_secs, 0)
|
||||
.single()
|
||||
.map(|dt| dt.format("%Y-%m-%dT%H:%M:%S").to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Parses a Graph `dateTime` value (`"2026-07-01T09:00:00.0000000"`, already
|
||||
/// normalized to UTC by the `Prefer: outlook.timezone="UTC"` request header)
|
||||
/// to a unix epoch. Fixed-width slicing, not a general datetime parser — the
|
||||
/// fractional-second suffix (if any) is simply ignored.
|
||||
#[cfg(feature = "sync")]
|
||||
fn parse_graph_datetime(value: &str) -> Option<i64> {
|
||||
if value.len() < 19 {
|
||||
return None;
|
||||
}
|
||||
let year: i64 = value.get(0..4)?.parse().ok()?;
|
||||
let month: u32 = value.get(5..7)?.parse().ok()?;
|
||||
let day: u32 = value.get(8..10)?.parse().ok()?;
|
||||
let hour: u32 = value.get(11..13)?.parse().ok()?;
|
||||
let min: u32 = value.get(14..16)?.parse().ok()?;
|
||||
let sec: u32 = value.get(17..19)?.parse().ok()?;
|
||||
Some(ymd_hms_to_unix(year, month, day, hour, min, sec))
|
||||
}
|
||||
|
||||
// ---- iCalendar (RFC 5545) VEVENT parsing — pure, no I/O ----
|
||||
|
||||
fn unfold_lines(text: &str) -> Vec<String> {
|
||||
@@ -600,6 +807,70 @@ fn ymd_hms_to_unix(year: i64, month: u32, day: u32, hour: u32, min: u32, sec: u3
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
#[test]
|
||||
fn parse_graph_datetime_ignores_fractional_seconds() {
|
||||
assert_eq!(
|
||||
parse_graph_datetime("2026-07-01T09:00:00.0000000"),
|
||||
Some(ymd_hms_to_unix(2026, 7, 1, 9, 0, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_graph_datetime("2026-07-01T09:00:00"),
|
||||
Some(ymd_hms_to_unix(2026, 7, 1, 9, 0, 0))
|
||||
);
|
||||
assert_eq!(parse_graph_datetime("not-a-date"), None);
|
||||
}
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
#[test]
|
||||
fn iso_datetime_formats_for_graph_query_params() {
|
||||
assert_eq!(
|
||||
iso_datetime(ymd_hms_to_unix(2026, 7, 1, 9, 0, 0)),
|
||||
"2026-07-01T09:00:00"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "sync")]
|
||||
#[test]
|
||||
fn graph_event_to_imported_extracts_metadata_only_no_body() {
|
||||
let event = GraphEvent {
|
||||
id: "AAMk...".to_string(),
|
||||
subject: Some("Sprint planning".to_string()),
|
||||
organizer: Some(GraphOrganizer {
|
||||
email_address: GraphEmailAddress {
|
||||
name: Some("Jordan Lee".to_string()),
|
||||
address: Some("jordan@example.com".to_string()),
|
||||
},
|
||||
}),
|
||||
start: Some(GraphDateTime {
|
||||
date_time: "2026-07-01T09:00:00.0000000".to_string(),
|
||||
}),
|
||||
end: Some(GraphDateTime {
|
||||
date_time: "2026-07-01T10:00:00.0000000".to_string(),
|
||||
}),
|
||||
attendees: Some(vec![GraphAttendee {
|
||||
email_address: GraphEmailAddress {
|
||||
name: Some("Alex Kim".to_string()),
|
||||
address: Some("alex@example.com".to_string()),
|
||||
},
|
||||
kind: Some("required".to_string()),
|
||||
}]),
|
||||
};
|
||||
let imported = graph_event_to_imported(event);
|
||||
assert_eq!(imported.event.source, "graph");
|
||||
assert_eq!(imported.event.raw_uid.as_deref(), Some("AAMk..."));
|
||||
assert_eq!(imported.event.subject.as_deref(), Some("Sprint planning"));
|
||||
assert_eq!(imported.event.organizer.as_deref(), Some("Jordan Lee"));
|
||||
assert_eq!(imported.event.description, None);
|
||||
assert_eq!(
|
||||
imported.event.starts_at,
|
||||
Some(ymd_hms_to_unix(2026, 7, 1, 9, 0, 0))
|
||||
);
|
||||
assert_eq!(imported.attendees.len(), 1);
|
||||
assert_eq!(imported.attendees[0].name, "Alex Kim");
|
||||
assert_eq!(imported.attendees[0].role.as_deref(), Some("required"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ymd_hms_to_unix_matches_known_epoch_values() {
|
||||
assert_eq!(ymd_hms_to_unix(1970, 1, 1, 0, 0, 0), 0);
|
||||
@@ -695,6 +966,8 @@ END:VCALENDAR\r\n";
|
||||
let result = PstSource.import(CalImport {
|
||||
path: "Z:\\no\\such\\file.pst".to_string(),
|
||||
password: None,
|
||||
from: None,
|
||||
to: None,
|
||||
});
|
||||
assert!(matches!(result, Err(CalError::Open(_))));
|
||||
}
|
||||
|
||||
+810
-67
File diff suppressed because it is too large
Load Diff
@@ -52,6 +52,9 @@ pub fn list() -> Vec<ModelInfo> {
|
||||
// Both models are always "active" once installed — diarization
|
||||
// has no interchangeable-size picker like whisper's (yet).
|
||||
active: true,
|
||||
// Not a whisper model — the language picker (T8.7) never applies
|
||||
// to diarization's segmentation/embedding pair.
|
||||
multilingual: false,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
pub mod agent;
|
||||
pub mod audio;
|
||||
pub mod briefs;
|
||||
pub mod calendar;
|
||||
pub mod commands;
|
||||
pub mod diarization;
|
||||
@@ -62,6 +63,13 @@ pub struct RecordingSession {
|
||||
/// can pick a different model than `Settings.whisper_model`).
|
||||
pub active_backend: Arc<StdMutex<models::BackendId>>,
|
||||
pub model_id: String,
|
||||
/// Resolved transcription language (T8.7, FR-TRX-4): `None` = auto.
|
||||
/// Set by the transcription worker once the engine loads (to the
|
||||
/// request resolved against model capability, e.g. forced "en" for an
|
||||
/// English-only model) and updated after every decode to whatever was
|
||||
/// actually used/detected — `stop_recording` reads the final value to
|
||||
/// persist on the meeting record.
|
||||
pub language: Arc<StdMutex<Option<String>>>,
|
||||
/// `None` when diarization models aren't installed yet (T4.7) — live
|
||||
/// provisional turns and the final post-stop pass are both skipped, same
|
||||
/// graceful-degradation treatment as a missing hardware backend (T4.3).
|
||||
@@ -210,6 +218,7 @@ pub fn run() {
|
||||
commands::list_input_devices,
|
||||
commands::set_preferred_backend,
|
||||
commands::list_models,
|
||||
commands::list_whisper_languages,
|
||||
commands::download_npu_package,
|
||||
commands::download_directml_package,
|
||||
commands::list_diarization_models,
|
||||
@@ -240,6 +249,9 @@ pub fn run() {
|
||||
commands::list_calendar_events,
|
||||
commands::get_calendar_event,
|
||||
commands::attach_meeting_to_event,
|
||||
commands::begin_graph_calendar_link,
|
||||
commands::import_graph_calendar,
|
||||
commands::disconnect_graph_calendar,
|
||||
commands::rename_meeting,
|
||||
commands::list_sync_targets,
|
||||
commands::add_sync_target,
|
||||
@@ -280,3 +292,49 @@ pub(crate) fn update_tray_tooltip(app: &tauri::AppHandle, text: &str) {
|
||||
let _ = tray.0.set_tooltip(Some(text));
|
||||
}
|
||||
}
|
||||
|
||||
/// Entry point for `whispassist.exe --mcp-stdio` (FR-MCP-6): serves one MCP
|
||||
/// session over this process's own stdin/stdout instead of showing a window,
|
||||
/// against the same `wa.db` the GUI instance uses. There is no Tauri
|
||||
/// `AppHandle` in this mode, so `mcp://access` events have nowhere to go —
|
||||
/// the `mcp_access_log` DB row is still written regardless (FR-MCP-5).
|
||||
pub fn run_mcp_stdio() {
|
||||
#[cfg(feature = "mcp")]
|
||||
{
|
||||
// stderr, not stdout: stdout is the MCP JSON-RPC channel.
|
||||
let _ = tracing_subscriber::fmt()
|
||||
.with_env_filter("info")
|
||||
.with_writer(std::io::stderr)
|
||||
.try_init();
|
||||
let rt = match tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
{
|
||||
Ok(rt) => rt,
|
||||
Err(e) => {
|
||||
eprintln!("whispassist --mcp-stdio: failed to start a runtime: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
rt.block_on(async {
|
||||
let store: std::sync::Arc<dyn storage::Store> =
|
||||
match storage::SqliteStore::connect().await {
|
||||
Ok(s) => std::sync::Arc::new(s),
|
||||
Err(e) => {
|
||||
eprintln!("whispassist --mcp-stdio: failed to open wa.db: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let handler = mcp::handler::WaMcpHandler::new(store, None);
|
||||
if let Err(e) = mcp::stdio_transport::serve_once(handler).await {
|
||||
eprintln!("whispassist --mcp-stdio: session ended with an error: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
});
|
||||
}
|
||||
#[cfg(not(feature = "mcp"))]
|
||||
{
|
||||
eprintln!("this build was compiled without MCP support (the `mcp` cargo feature is off)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
+732
-25
@@ -46,6 +46,12 @@ pub trait LlmProvider: Send + Sync {
|
||||
/// Non-streaming — the reply is short enough that a single round trip is
|
||||
/// simpler than wiring up another token-stream event for it.
|
||||
async fn suggest_tags(&self, transcript: &str) -> Result<Vec<String>, LlmError>;
|
||||
/// One-shot, non-streaming completion (T10.6, ADR-0011): a caller-supplied
|
||||
/// system prompt + user message, one full reply back — no output-format
|
||||
/// contract of its own (unlike `summarize`'s three fixed sections), since
|
||||
/// callers like `briefs::FeatureBriefBuilder` define their own. Mirrors
|
||||
/// `suggest_tags`'s single-round-trip shape.
|
||||
async fn complete(&self, system: &str, user: &str) -> Result<String, LlmError>;
|
||||
/// True if the endpoint resolves to loopback/local (FR-LLM-6, FR-SEC-1).
|
||||
fn is_local(&self) -> bool;
|
||||
}
|
||||
@@ -61,7 +67,12 @@ const RESPONSE_FORMAT_INSTRUCTIONS: &str = "Respond in Markdown with exactly thr
|
||||
are bullet lists (each line starting with \"- \"); write \"- None\" if a section has nothing \
|
||||
to report. Do not add any other top-level sections.";
|
||||
|
||||
fn build_messages(prompt: &Prompt, user_system: Option<&str>) -> Vec<serde_json::Value> {
|
||||
/// Splits the assembled prompt into its `(system, user)` halves. Shared by
|
||||
/// every provider: OpenAI-shaped chat APIs (Ollama, OpenAI-compat) fold both
|
||||
/// into a `messages` array via `build_messages` below; Anthropic's Messages
|
||||
/// API (ADR-0011) takes `system` as its own top-level field instead, so it
|
||||
/// calls this directly.
|
||||
fn build_system_and_user(prompt: &Prompt, user_system: Option<&str>) -> (String, String) {
|
||||
let mut user = String::new();
|
||||
if !prompt.metadata.is_empty() {
|
||||
user.push_str(&prompt.metadata);
|
||||
@@ -84,6 +95,11 @@ fn build_messages(prompt: &Prompt, user_system: Option<&str>) -> Vec<serde_json:
|
||||
}
|
||||
system.push_str(RESPONSE_FORMAT_INSTRUCTIONS);
|
||||
|
||||
(system, user)
|
||||
}
|
||||
|
||||
fn build_messages(prompt: &Prompt, user_system: Option<&str>) -> Vec<serde_json::Value> {
|
||||
let (system, user) = build_system_and_user(prompt, user_system);
|
||||
vec![
|
||||
serde_json::json!({ "role": "system", "content": system }),
|
||||
serde_json::json!({ "role": "user", "content": user }),
|
||||
@@ -154,8 +170,10 @@ fn parse_summary(text: &str) -> Summary {
|
||||
}
|
||||
|
||||
/// `- text` / `* text` -> `Some("text")`; skips empty bullets and the
|
||||
/// placeholder "- None" the prompt asks for when a section is empty.
|
||||
fn bullet_text(line: &str) -> Option<String> {
|
||||
/// placeholder "- None" the prompt asks for when a section is empty. Shared
|
||||
/// with `briefs::parse_brief` — its "Acceptance Criteria" section is the same
|
||||
/// bullet-list shape as `summarize`'s Decisions/Action Items.
|
||||
pub(crate) fn bullet_text(line: &str) -> Option<String> {
|
||||
let trimmed = line.trim();
|
||||
let stripped = trimmed
|
||||
.strip_prefix("- ")
|
||||
@@ -175,10 +193,20 @@ const TAG_INSTRUCTIONS: &str = "You generate short topical tags for a meeting tr
|
||||
explanation, no quotes. Each tag: lowercase, 1-3 words, hyphenated instead of spaces (e.g. \
|
||||
\"budget-review\" not \"budget review\").";
|
||||
|
||||
/// `(system, user)` halves for the tag-suggestion prompt — see
|
||||
/// `build_system_and_user` above for why Anthropic needs these split out.
|
||||
fn tag_system_and_user(transcript: &str) -> (String, String) {
|
||||
(
|
||||
TAG_INSTRUCTIONS.to_string(),
|
||||
format!("Transcript:\n{transcript}"),
|
||||
)
|
||||
}
|
||||
|
||||
fn build_tag_messages(transcript: &str) -> Vec<serde_json::Value> {
|
||||
let (system, user) = tag_system_and_user(transcript);
|
||||
vec![
|
||||
serde_json::json!({ "role": "system", "content": TAG_INSTRUCTIONS }),
|
||||
serde_json::json!({ "role": "user", "content": format!("Transcript:\n{transcript}") }),
|
||||
serde_json::json!({ "role": "system", "content": system }),
|
||||
serde_json::json!({ "role": "user", "content": user }),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -438,11 +466,84 @@ impl LlmProvider for OllamaProvider {
|
||||
))
|
||||
}
|
||||
|
||||
/// One-shot completion (T10.6) — same non-streaming `/api/chat` shape as
|
||||
/// `suggest_tags`, just with a caller-supplied system/user pair instead of
|
||||
/// the fixed tag-list prompt.
|
||||
async fn complete(&self, system: &str, user: &str) -> Result<String, LlmError> {
|
||||
let body = serde_json::json!({
|
||||
"model": self.model,
|
||||
"messages": [
|
||||
{ "role": "system", "content": system },
|
||||
{ "role": "user", "content": user },
|
||||
],
|
||||
"stream": false,
|
||||
});
|
||||
let resp = reqwest::Client::new()
|
||||
.post(format!("{}/api/chat", self.base()))
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| LlmError::Unreachable(e.to_string()))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(LlmError::Request(format!("HTTP {}", resp.status())));
|
||||
}
|
||||
let chunk: OllamaChatChunk = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| LlmError::Request(e.to_string()))?;
|
||||
Ok(chunk.message.map(|m| m.content).unwrap_or_default())
|
||||
}
|
||||
|
||||
fn is_local(&self) -> bool {
|
||||
is_local_endpoint(&self.endpoint)
|
||||
}
|
||||
}
|
||||
|
||||
/// Hosted-provider API keys (Anthropic, and a hosted OpenAI-compatible
|
||||
/// gateway once `credential_ref` is set on `OpenAiCompatProvider`) live in
|
||||
/// the OS credential store, keyed by `credential_ref` — never in
|
||||
/// settings.json/wa.db/logs (ADR-0011, FR-SEC-1). Mirrors
|
||||
/// `sync::credentials`, with its own service name so LLM keys and sync
|
||||
/// secrets don't share a keyring namespace.
|
||||
#[cfg(feature = "sync")]
|
||||
pub mod credentials {
|
||||
use super::LlmError;
|
||||
|
||||
const SERVICE: &str = "WhispAssist-llm";
|
||||
|
||||
fn entry(credential_ref: &str) -> Result<keyring::Entry, LlmError> {
|
||||
keyring::Entry::new(SERVICE, credential_ref)
|
||||
.map_err(|e| LlmError::Unreachable(format!("credential store: {e}")))
|
||||
}
|
||||
|
||||
pub fn set(credential_ref: &str, secret: &str) -> Result<(), LlmError> {
|
||||
entry(credential_ref)?
|
||||
.set_password(secret)
|
||||
.map_err(|e| LlmError::Unreachable(format!("credential store: {e}")))
|
||||
}
|
||||
|
||||
pub fn get(credential_ref: &str) -> Result<String, LlmError> {
|
||||
entry(credential_ref)?
|
||||
.get_password()
|
||||
.map_err(|e| LlmError::Unreachable(format!("credential store: {e}")))
|
||||
}
|
||||
|
||||
pub fn delete(credential_ref: &str) -> Result<(), LlmError> {
|
||||
// Missing entry is fine — deletion is best-effort cleanup.
|
||||
match entry(credential_ref)?.delete_credential() {
|
||||
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
|
||||
Err(e) => Err(LlmError::Unreachable(format!("credential store: {e}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fixed credential-store key for the Anthropic API key (ADR-0011). Only one
|
||||
/// hosted Anthropic configuration is supported at a time (single `llm_*`
|
||||
/// settings fields, like every other provider here), so a deterministic ref —
|
||||
/// rather than a per-target uuid like sync's — is enough; nothing to
|
||||
/// disambiguate.
|
||||
pub const ANTHROPIC_CREDENTIAL_REF: &str = "wa-llm-anthropic";
|
||||
|
||||
// ---- OpenAI-compatible endpoint (Phase 5's "custom" option; Phase 10a reuses ----
|
||||
// this for hosted providers by setting `credential_ref`, ADR-0011.)
|
||||
|
||||
@@ -491,10 +592,16 @@ impl OpenAiCompatProvider {
|
||||
}
|
||||
|
||||
/// Reads the API key from the OS credential store (never settings/DB —
|
||||
/// FR-SEC-1). `None` for local, unauthenticated custom endpoints.
|
||||
/// FR-SEC-1). `None` for local, unauthenticated custom endpoints (no
|
||||
/// `credential_ref` at all) or if the store lookup fails.
|
||||
#[cfg(feature = "sync")]
|
||||
fn api_key(&self) -> Option<String> {
|
||||
self.credential_ref
|
||||
.as_deref()
|
||||
.and_then(|r| credentials::get(r).ok())
|
||||
}
|
||||
#[cfg(not(feature = "sync"))]
|
||||
fn api_key(&self) -> Option<String> {
|
||||
// T10a.2: `keyring` lookup by `credential_ref` lands with hosted
|
||||
// providers; a local custom endpoint has no `credential_ref` at all.
|
||||
None
|
||||
}
|
||||
|
||||
@@ -627,6 +734,55 @@ impl LlmProvider for OpenAiCompatProvider {
|
||||
Ok(parse_tags(&full_text))
|
||||
}
|
||||
|
||||
/// One-shot completion (T10.6) — reuses `suggest_tags`'s SSE-accumulate
|
||||
/// path (this API has no simpler non-streaming reply shape) with a
|
||||
/// caller-supplied system/user pair instead of the fixed tag prompt.
|
||||
async fn complete(&self, system: &str, user: &str) -> Result<String, LlmError> {
|
||||
let body = serde_json::json!({
|
||||
"model": self.model,
|
||||
"messages": [
|
||||
{ "role": "system", "content": system },
|
||||
{ "role": "user", "content": user },
|
||||
],
|
||||
"stream": true,
|
||||
});
|
||||
let req = self.auth(
|
||||
reqwest::Client::new()
|
||||
.post(format!("{}/v1/chat/completions", self.base()))
|
||||
.json(&body),
|
||||
);
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| LlmError::Unreachable(e.to_string()))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(LlmError::Request(format!("HTTP {}", resp.status())));
|
||||
}
|
||||
|
||||
let mut full_text = String::new();
|
||||
stream_lines(resp, |line| {
|
||||
let Some(payload) = line.strip_prefix("data:") else {
|
||||
return true;
|
||||
};
|
||||
let payload = payload.trim();
|
||||
if payload == "[DONE]" {
|
||||
return false;
|
||||
}
|
||||
let Ok(chunk) = serde_json::from_str::<OpenAiChatChunk>(payload) else {
|
||||
return true;
|
||||
};
|
||||
for choice in chunk.choices {
|
||||
if let Some(content) = choice.delta.content {
|
||||
full_text.push_str(&content);
|
||||
}
|
||||
}
|
||||
true
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(full_text)
|
||||
}
|
||||
|
||||
fn is_local(&self) -> bool {
|
||||
self.credential_ref.is_none() && is_local_endpoint(&self.endpoint)
|
||||
}
|
||||
@@ -727,34 +883,297 @@ pub async fn pull_model(
|
||||
.await
|
||||
}
|
||||
|
||||
/// Anthropic Messages API (`/v1/messages`) — native shape, NOT OpenAI-compatible.
|
||||
/// Anthropic Messages API version header (ADR-0011) — Anthropic's REST API is
|
||||
/// versioned by header, not URL path.
|
||||
const ANTHROPIC_VERSION: &str = "2023-06-01";
|
||||
|
||||
/// `max_tokens` is required by the Messages API and WA has no per-meeting
|
||||
/// tuning surface for it yet; a fixed generous cap is enough for a summary or
|
||||
/// a short tag list (T10a.1 — revisit if a real need for a larger cap shows up).
|
||||
const ANTHROPIC_MAX_TOKENS: u32 = 4096;
|
||||
|
||||
/// Anthropic Messages API (`/v1/messages`) — native shape, NOT OpenAI-
|
||||
/// compatible (ADR-0011): `system` is a top-level field rather than a
|
||||
/// `messages[0]` entry, auth is `x-api-key` (not `Authorization: Bearer`),
|
||||
/// and it needs the `anthropic-version` header. Always hosted — `is_local()`
|
||||
/// is unconditionally `false` (unlike `OpenAiCompatProvider`, there is no
|
||||
/// unauthenticated/local mode for this API).
|
||||
pub struct AnthropicProvider {
|
||||
pub model: String,
|
||||
pub credential_ref: String,
|
||||
/// `https://api.anthropic.com` in production; overridable so tests can
|
||||
/// point this at a local mock server.
|
||||
pub endpoint: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AnthropicModelsResponse {
|
||||
#[serde(default)]
|
||||
data: Vec<AnthropicModel>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AnthropicModel {
|
||||
id: String,
|
||||
}
|
||||
|
||||
/// One line of a Messages API SSE stream, e.g.
|
||||
/// `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hi"}}`.
|
||||
/// Only `content_block_delta` events carry text; every other event type
|
||||
/// (`message_start`, `content_block_start/stop`, `message_delta`,
|
||||
/// `message_stop`, `ping`) is ignored except to detect the stream's end.
|
||||
#[derive(Deserialize)]
|
||||
struct AnthropicStreamEvent {
|
||||
#[serde(rename = "type")]
|
||||
kind: String,
|
||||
#[serde(default)]
|
||||
delta: Option<AnthropicDelta>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
struct AnthropicDelta {
|
||||
#[serde(default)]
|
||||
text: Option<String>,
|
||||
}
|
||||
|
||||
/// Non-streaming Messages API reply (used for `suggest_tags`, whose short
|
||||
/// reply doesn't need token-by-token streaming — same call shape Ollama uses).
|
||||
#[derive(Deserialize)]
|
||||
struct AnthropicMessageResponse {
|
||||
#[serde(default)]
|
||||
content: Vec<AnthropicContentBlock>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AnthropicContentBlock {
|
||||
#[serde(default)]
|
||||
text: Option<String>,
|
||||
}
|
||||
|
||||
impl AnthropicProvider {
|
||||
fn base(&self) -> &str {
|
||||
self.endpoint.trim_end_matches('/')
|
||||
}
|
||||
|
||||
/// Reads the API key from the OS credential store (never settings/DB —
|
||||
/// FR-SEC-1, ADR-0011). Unlike `OpenAiCompatProvider` this always fails
|
||||
/// closed (`Err`, not a silent `None`) — Anthropic has no unauthenticated
|
||||
/// mode, so a missing key means the request simply cannot be made.
|
||||
#[cfg(feature = "sync")]
|
||||
fn api_key(&self) -> Result<String, LlmError> {
|
||||
credentials::get(&self.credential_ref)
|
||||
}
|
||||
#[cfg(not(feature = "sync"))]
|
||||
fn api_key(&self) -> Result<String, LlmError> {
|
||||
Err(LlmError::Unreachable(
|
||||
"credential store unavailable (built without the \"sync\" feature)".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
fn auth(&self, req: reqwest::RequestBuilder, key: &str) -> reqwest::RequestBuilder {
|
||||
req.header("x-api-key", key)
|
||||
.header("anthropic-version", ANTHROPIC_VERSION)
|
||||
}
|
||||
|
||||
/// `status()`'s actual HTTP call, taking an already-resolved key — split
|
||||
/// out so tests can exercise the request/response shape against a mock
|
||||
/// server with a fixed key, without needing that key to actually exist
|
||||
/// in the real OS credential store (the store lookup itself is a thin,
|
||||
/// already-trusted `keyring` wrapper — see `credentials` above — not
|
||||
/// worth re-proving with an HTTP mock).
|
||||
async fn status_with_key(&self, key: &str) -> LlmStatus {
|
||||
let req = self.auth(
|
||||
reqwest::Client::new().get(format!("{}/v1/models", self.base())),
|
||||
key,
|
||||
);
|
||||
let models = match req.send().await {
|
||||
Ok(resp) if resp.status().is_success() => resp
|
||||
.json::<AnthropicModelsResponse>()
|
||||
.await
|
||||
.map(|r| r.data.into_iter().map(|m| m.id).collect())
|
||||
.unwrap_or_default(),
|
||||
_ => {
|
||||
return LlmStatus {
|
||||
provider: "anthropic".to_string(),
|
||||
reachable: false,
|
||||
is_local: false,
|
||||
models: Vec::new(),
|
||||
}
|
||||
}
|
||||
};
|
||||
LlmStatus {
|
||||
provider: "anthropic".to_string(),
|
||||
reachable: true,
|
||||
is_local: false,
|
||||
models,
|
||||
}
|
||||
}
|
||||
|
||||
/// `summarize()`'s actual HTTP call — see `status_with_key`.
|
||||
async fn summarize_with_key(
|
||||
&self,
|
||||
key: &str,
|
||||
prompt: Prompt,
|
||||
out: TokenSink,
|
||||
) -> Result<Summary, LlmError> {
|
||||
let (system, user) = build_system_and_user(&prompt, None);
|
||||
let body = serde_json::json!({
|
||||
"model": self.model,
|
||||
"max_tokens": ANTHROPIC_MAX_TOKENS,
|
||||
"system": system,
|
||||
"messages": [{ "role": "user", "content": user }],
|
||||
"stream": true,
|
||||
});
|
||||
let req = self.auth(
|
||||
reqwest::Client::new()
|
||||
.post(format!("{}/v1/messages", self.base()))
|
||||
.json(&body),
|
||||
key,
|
||||
);
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| LlmError::Unreachable(e.to_string()))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(LlmError::Request(format!("HTTP {}", resp.status())));
|
||||
}
|
||||
|
||||
let mut full_text = String::new();
|
||||
stream_lines(resp, |line| {
|
||||
let Some(payload) = line.strip_prefix("data:") else {
|
||||
return true; // "event: ..." lines and blanks — not JSON, skip
|
||||
};
|
||||
let payload = payload.trim();
|
||||
let Ok(evt) = serde_json::from_str::<AnthropicStreamEvent>(payload) else {
|
||||
return true; // ignore an unparseable line, keep reading
|
||||
};
|
||||
if evt.kind == "content_block_delta" {
|
||||
if let Some(text) = evt.delta.and_then(|d| d.text) {
|
||||
if !text.is_empty() {
|
||||
full_text.push_str(&text);
|
||||
let _ = out.send(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
evt.kind != "message_stop"
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(parse_summary(&full_text))
|
||||
}
|
||||
|
||||
/// `suggest_tags()`'s actual HTTP call — see `status_with_key`.
|
||||
async fn suggest_tags_with_key(
|
||||
&self,
|
||||
key: &str,
|
||||
transcript: &str,
|
||||
) -> Result<Vec<String>, LlmError> {
|
||||
let (system, user) = tag_system_and_user(transcript);
|
||||
let body = serde_json::json!({
|
||||
"model": self.model,
|
||||
"max_tokens": ANTHROPIC_MAX_TOKENS,
|
||||
"system": system,
|
||||
"messages": [{ "role": "user", "content": user }],
|
||||
"stream": false,
|
||||
});
|
||||
let req = self.auth(
|
||||
reqwest::Client::new()
|
||||
.post(format!("{}/v1/messages", self.base()))
|
||||
.json(&body),
|
||||
key,
|
||||
);
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| LlmError::Unreachable(e.to_string()))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(LlmError::Request(format!("HTTP {}", resp.status())));
|
||||
}
|
||||
let parsed: AnthropicMessageResponse = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| LlmError::Request(e.to_string()))?;
|
||||
let text: String = parsed
|
||||
.content
|
||||
.into_iter()
|
||||
.filter_map(|b| b.text)
|
||||
.collect::<Vec<_>>()
|
||||
.join("");
|
||||
Ok(parse_tags(&text))
|
||||
}
|
||||
|
||||
/// `complete()`'s actual HTTP call — see `status_with_key`. Unlike
|
||||
/// `summarize`/`suggest_tags`, `system`/`user` arrive pre-assembled
|
||||
/// (`FeatureBriefBuilder`'s prompt contract, M1) rather than a `Prompt`,
|
||||
/// so this skips `build_system_and_user` and posts them directly.
|
||||
async fn complete_with_key(
|
||||
&self,
|
||||
key: &str,
|
||||
system: &str,
|
||||
user: &str,
|
||||
) -> Result<String, LlmError> {
|
||||
let body = serde_json::json!({
|
||||
"model": self.model,
|
||||
"max_tokens": ANTHROPIC_MAX_TOKENS,
|
||||
"system": system,
|
||||
"messages": [{ "role": "user", "content": user }],
|
||||
"stream": false,
|
||||
});
|
||||
let req = self.auth(
|
||||
reqwest::Client::new()
|
||||
.post(format!("{}/v1/messages", self.base()))
|
||||
.json(&body),
|
||||
key,
|
||||
);
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| LlmError::Unreachable(e.to_string()))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(LlmError::Request(format!("HTTP {}", resp.status())));
|
||||
}
|
||||
let parsed: AnthropicMessageResponse = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| LlmError::Request(e.to_string()))?;
|
||||
Ok(parsed
|
||||
.content
|
||||
.into_iter()
|
||||
.filter_map(|b| b.text)
|
||||
.collect::<Vec<_>>()
|
||||
.join(""))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl LlmProvider for AnthropicProvider {
|
||||
async fn status(&self) -> LlmStatus {
|
||||
// Not built yet (Phase 10a) and not reachable today: `set_llm_provider`
|
||||
// rejects "anthropic" before settings could ever select this provider.
|
||||
LlmStatus {
|
||||
provider: "anthropic".to_string(),
|
||||
reachable: false,
|
||||
is_local: false,
|
||||
models: Vec::new(),
|
||||
}
|
||||
let Ok(key) = self.api_key() else {
|
||||
return LlmStatus {
|
||||
provider: "anthropic".to_string(),
|
||||
reachable: false,
|
||||
is_local: false,
|
||||
models: Vec::new(),
|
||||
};
|
||||
};
|
||||
self.status_with_key(&key).await
|
||||
}
|
||||
async fn summarize(&self, _prompt: Prompt, _out: TokenSink) -> Result<Summary, LlmError> {
|
||||
Err(LlmError::Request(
|
||||
"Anthropic provider isn't built yet (Phase 10a)".to_string(),
|
||||
))
|
||||
|
||||
async fn summarize(&self, prompt: Prompt, out: TokenSink) -> Result<Summary, LlmError> {
|
||||
let key = self.api_key()?;
|
||||
self.summarize_with_key(&key, prompt, out).await
|
||||
}
|
||||
async fn suggest_tags(&self, _transcript: &str) -> Result<Vec<String>, LlmError> {
|
||||
Err(LlmError::Request(
|
||||
"Anthropic provider isn't built yet (Phase 10a)".to_string(),
|
||||
))
|
||||
|
||||
async fn suggest_tags(&self, transcript: &str) -> Result<Vec<String>, LlmError> {
|
||||
let key = self.api_key()?;
|
||||
self.suggest_tags_with_key(&key, transcript).await
|
||||
}
|
||||
|
||||
async fn complete(&self, system: &str, user: &str) -> Result<String, LlmError> {
|
||||
let key = self.api_key()?;
|
||||
self.complete_with_key(&key, system, user).await
|
||||
}
|
||||
|
||||
fn is_local(&self) -> bool {
|
||||
false
|
||||
}
|
||||
@@ -764,6 +1183,294 @@ impl LlmProvider for AnthropicProvider {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Minimal single-request HTTP mock: binds loopback on an OS-chosen port,
|
||||
/// accepts one connection on a background thread, hands the raw request
|
||||
/// bytes back over a channel, and writes `response` (a full raw
|
||||
/// `"HTTP/1.1 ..."` response) to the socket. Mirrors the blocking-loopback
|
||||
/// pattern `sync::oauth::LoopbackRedirect` already uses for a similar
|
||||
/// reason (no HTTP mocking crate in the dependency tree) — good enough
|
||||
/// for "one provider call, one reply" test shapes, which is all
|
||||
/// `summarize`/`suggest_tags`/`status` ever do.
|
||||
struct MockServer {
|
||||
port: u16,
|
||||
captured: std::sync::mpsc::Receiver<String>,
|
||||
}
|
||||
|
||||
impl MockServer {
|
||||
fn start(response: &'static str) -> Self {
|
||||
let listener =
|
||||
std::net::TcpListener::bind("127.0.0.1:0").expect("bind a loopback test port");
|
||||
let port = listener.local_addr().expect("local_addr").port();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
use std::io::{Read, Write};
|
||||
if let Ok((mut stream, _)) = listener.accept() {
|
||||
// A POST's headers and JSON body aren't guaranteed to
|
||||
// arrive in a single `read()` (separate writev calls can
|
||||
// land as separate TCP segments even on loopback), so
|
||||
// accumulate reads until the client goes quiet rather
|
||||
// than trusting one read to have the whole request.
|
||||
let _ = stream.set_read_timeout(Some(std::time::Duration::from_millis(300)));
|
||||
let mut request = Vec::new();
|
||||
let mut buf = [0u8; 4096];
|
||||
loop {
|
||||
match stream.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break, // EOF or read-timeout: client is done sending
|
||||
Ok(n) => request.extend_from_slice(&buf[..n]),
|
||||
}
|
||||
}
|
||||
let _ = tx.send(String::from_utf8_lossy(&request).to_string());
|
||||
let _ = stream.write_all(response.as_bytes());
|
||||
let _ = stream.flush();
|
||||
}
|
||||
});
|
||||
Self { port, captured: rx }
|
||||
}
|
||||
|
||||
fn base_url(&self) -> String {
|
||||
format!("http://127.0.0.1:{}", self.port)
|
||||
}
|
||||
|
||||
/// The raw request the mock received (headers + body), for asserting
|
||||
/// shape (path, auth header, JSON body fields).
|
||||
fn request(&self) -> String {
|
||||
self.captured
|
||||
.recv_timeout(std::time::Duration::from_secs(5))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
fn http_ok(content_type: &str, body: &str) -> String {
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
}
|
||||
|
||||
fn drain_tokens(rx: &std::sync::mpsc::Receiver<String>) -> String {
|
||||
let mut out = String::new();
|
||||
while let Ok(tok) = rx.try_recv() {
|
||||
out.push_str(&tok);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ---- AnthropicProvider (M3.1/M3.2, ADR-0011) ----
|
||||
|
||||
fn anthropic_provider(endpoint: String) -> AnthropicProvider {
|
||||
AnthropicProvider {
|
||||
model: "claude-3-5-sonnet-latest".to_string(),
|
||||
credential_ref: "test-anthropic-key".to_string(),
|
||||
endpoint,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn anthropic_summarize_streams_tokens_and_hits_v1_messages_with_auth_headers() {
|
||||
let sse = "event: message_start\n\
|
||||
data: {\"type\":\"message_start\"}\n\n\
|
||||
event: content_block_delta\n\
|
||||
data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"## Summary\\n\"}}\n\n\
|
||||
event: content_block_delta\n\
|
||||
data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"Shipped M3.\\n\\n## Decisions\\n- None\\n\\n## Action Items\\n- None\\n\"}}\n\n\
|
||||
event: message_stop\n\
|
||||
data: {\"type\":\"message_stop\"}\n\n";
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||
sse.len(),
|
||||
sse
|
||||
);
|
||||
let response: &'static str = Box::leak(response.into_boxed_str());
|
||||
let server = MockServer::start(response);
|
||||
let provider = anthropic_provider(server.base_url());
|
||||
|
||||
let (tx, rx) = std::sync::mpsc::channel::<String>();
|
||||
let prompt = Prompt {
|
||||
transcript: "Alice: let's ship it.".to_string(),
|
||||
metadata: "Meeting: M3 review".to_string(),
|
||||
template: None,
|
||||
};
|
||||
let summary = provider
|
||||
.summarize_with_key("test-anthropic-key", prompt, tx)
|
||||
.await
|
||||
.expect("summarize should succeed against the mock");
|
||||
|
||||
let request = server.request();
|
||||
assert!(request.starts_with("POST /v1/messages"), "{request}");
|
||||
assert!(
|
||||
request.contains("x-api-key: test-anthropic-key"),
|
||||
"{request}"
|
||||
);
|
||||
assert!(
|
||||
request.contains(&format!("anthropic-version: {ANTHROPIC_VERSION}")),
|
||||
"{request}"
|
||||
);
|
||||
assert!(
|
||||
request.contains("\"model\":\"claude-3-5-sonnet-latest\""),
|
||||
"{request}"
|
||||
);
|
||||
assert!(request.contains("\"stream\":true"), "{request}");
|
||||
// Anthropic's own shape: system is a top-level field, not messages[0].
|
||||
assert!(request.contains("\"system\":"), "{request}");
|
||||
assert!(!request.contains("\"role\":\"system\""), "{request}");
|
||||
|
||||
assert_eq!(summary.summary_md, "Shipped M3.");
|
||||
assert_eq!(
|
||||
drain_tokens(&rx),
|
||||
"## Summary\nShipped M3.\n\n## Decisions\n- None\n\n## Action Items\n- None\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn anthropic_suggest_tags_parses_the_non_streaming_reply() {
|
||||
let body = r#"{"id":"msg_1","type":"message","role":"assistant","content":[{"type":"text","text":"golang, webrtc, dtls"}],"model":"claude-3-5-sonnet-latest","stop_reason":"end_turn"}"#;
|
||||
let response = http_ok("application/json", body);
|
||||
let response: &'static str = Box::leak(response.into_boxed_str());
|
||||
let server = MockServer::start(response);
|
||||
let provider = anthropic_provider(server.base_url());
|
||||
|
||||
let tags = provider
|
||||
.suggest_tags_with_key(
|
||||
"test-anthropic-key",
|
||||
"Alice: let's talk webrtc and dtls in golang.",
|
||||
)
|
||||
.await
|
||||
.expect("suggest_tags should succeed against the mock");
|
||||
|
||||
let request = server.request();
|
||||
assert!(request.starts_with("POST /v1/messages"), "{request}");
|
||||
assert!(request.contains("\"stream\":false"), "{request}");
|
||||
assert_eq!(tags, vec!["golang", "webrtc", "dtls"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn anthropic_status_reports_reachable_and_models_from_v1_models() {
|
||||
let body = r#"{"data":[{"type":"model","id":"claude-3-5-sonnet-latest","display_name":"Claude 3.5 Sonnet"}],"has_more":false}"#;
|
||||
let response = http_ok("application/json", body);
|
||||
let response: &'static str = Box::leak(response.into_boxed_str());
|
||||
let server = MockServer::start(response);
|
||||
let provider = anthropic_provider(server.base_url());
|
||||
|
||||
let status = provider.status_with_key("test-anthropic-key").await;
|
||||
let request = server.request();
|
||||
assert!(request.starts_with("GET /v1/models"), "{request}");
|
||||
assert!(
|
||||
request.contains("x-api-key: test-anthropic-key"),
|
||||
"{request}"
|
||||
);
|
||||
assert!(status.reachable);
|
||||
assert!(!status.is_local);
|
||||
assert_eq!(status.provider, "anthropic");
|
||||
assert_eq!(status.models, vec!["claude-3-5-sonnet-latest"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anthropic_provider_is_never_local() {
|
||||
// Unlike OpenAiCompatProvider (which is local until a credential_ref
|
||||
// is set), Anthropic has no unauthenticated/local mode at all.
|
||||
let provider = anthropic_provider("http://127.0.0.1:1".to_string());
|
||||
assert!(!provider.is_local());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn anthropic_status_fails_closed_when_no_credential_is_stored() {
|
||||
// Exercises the real trait-level status() (not status_with_key), i.e.
|
||||
// the actual credential-store lookup path — a fresh/unused
|
||||
// credential_ref should never be present, so this proves the "no key
|
||||
// => unreachable, no request attempted" behavior without needing to
|
||||
// seed the real OS credential store from a test.
|
||||
let provider = AnthropicProvider {
|
||||
model: "claude-3-5-sonnet-latest".to_string(),
|
||||
credential_ref: "wa-llm-anthropic-test-missing-credential-do-not-create".to_string(),
|
||||
endpoint: "http://127.0.0.1:1".to_string(), // would refuse the connection if ever hit
|
||||
};
|
||||
let status = provider.status().await;
|
||||
assert!(!status.reachable);
|
||||
assert!(!status.is_local);
|
||||
assert!(status.models.is_empty());
|
||||
}
|
||||
|
||||
// ---- OpenAiCompatProvider (already-scaffolded reference; adding the ----
|
||||
// mock-server coverage M3's acceptance criteria calls for, which didn't
|
||||
// exist yet — see openai_compat_provider_is_not_local_once_a_credential_is_set
|
||||
// above for the pre-existing pure-logic test.)
|
||||
|
||||
#[tokio::test]
|
||||
async fn openai_compat_summarize_streams_sse_tokens_from_v1_chat_completions() {
|
||||
let sse = "data: {\"choices\":[{\"delta\":{\"content\":\"## Summary\\n\"}}]}\n\n\
|
||||
data: {\"choices\":[{\"delta\":{\"content\":\"All good.\\n\\n## Decisions\\n- None\\n\\n## Action Items\\n- None\\n\"}}]}\n\n\
|
||||
data: [DONE]\n\n";
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||
sse.len(),
|
||||
sse
|
||||
);
|
||||
let response: &'static str = Box::leak(response.into_boxed_str());
|
||||
let server = MockServer::start(response);
|
||||
let provider = OpenAiCompatProvider {
|
||||
endpoint: server.base_url(),
|
||||
model: "gpt-4o-mini".to_string(),
|
||||
credential_ref: None,
|
||||
};
|
||||
|
||||
let (tx, rx) = std::sync::mpsc::channel::<String>();
|
||||
let prompt = Prompt {
|
||||
transcript: "Alice: let's ship it.".to_string(),
|
||||
metadata: "Meeting: M3 review".to_string(),
|
||||
template: None,
|
||||
};
|
||||
let summary = provider
|
||||
.summarize(prompt, tx)
|
||||
.await
|
||||
.expect("summarize should succeed against the mock");
|
||||
|
||||
let request = server.request();
|
||||
assert!(
|
||||
request.starts_with("POST /v1/chat/completions"),
|
||||
"{request}"
|
||||
);
|
||||
assert!(request.contains("\"model\":\"gpt-4o-mini\""), "{request}");
|
||||
assert!(request.contains("\"role\":\"system\""), "{request}"); // OpenAI shape: system IS a message
|
||||
assert_eq!(summary.summary_md, "All good.");
|
||||
assert_eq!(
|
||||
drain_tokens(&rx),
|
||||
"## Summary\nAll good.\n\n## Decisions\n- None\n\n## Action Items\n- None\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn openai_compat_provider_with_unset_credential_sends_no_auth_header() {
|
||||
let sse = "data: [DONE]\n\n";
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||
sse.len(),
|
||||
sse
|
||||
);
|
||||
let response: &'static str = Box::leak(response.into_boxed_str());
|
||||
let server = MockServer::start(response);
|
||||
// `credential_ref: None` is the local/unauthenticated custom-endpoint
|
||||
// case (ADR-0007) — no lookup happens at all, so this asserts the
|
||||
// request truly carries no Authorization header, unlike the
|
||||
// `Some(ref)` hosted case above.
|
||||
let provider = OpenAiCompatProvider {
|
||||
endpoint: server.base_url(),
|
||||
model: "gpt-4o-mini".to_string(),
|
||||
credential_ref: None,
|
||||
};
|
||||
assert!(provider.is_local());
|
||||
|
||||
let _ = provider.suggest_tags("hello").await;
|
||||
let request = server.request();
|
||||
assert!(
|
||||
request.starts_with("POST /v1/chat/completions"),
|
||||
"{request}"
|
||||
);
|
||||
assert!(
|
||||
!request.to_lowercase().contains("authorization:"),
|
||||
"{request}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_summary_splits_the_three_requested_sections() {
|
||||
let text = "## Summary\nWe discussed the roadmap.\nIt went well.\n\n\
|
||||
|
||||
@@ -3,5 +3,14 @@
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
// `whispassist.exe --mcp-stdio` (FR-MCP-6): the stdio "adapter the agent
|
||||
// spawns" is this same binary, in headless mode -- it serves one MCP
|
||||
// session over its own stdin/stdout and exits, instead of opening the
|
||||
// GUI window. A coding agent's MCP client config spawns this exact
|
||||
// command line (see `mcp_status`/`set_mcp_enabled`'s returned endpoint).
|
||||
if std::env::args().any(|a| a == "--mcp-stdio") {
|
||||
whispassist_lib::run_mcp_stdio();
|
||||
return;
|
||||
}
|
||||
whispassist_lib::run();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
//! `rmcp::ServerHandler` implementation — the tools-first surface (FR-MCP-2)
|
||||
//! that a connected coding agent actually calls. Every tool handler:
|
||||
//! 1. Reads the *current* scope from `Settings` (not a snapshot taken at
|
||||
//! server start) so `set_mcp_scope` takes effect immediately.
|
||||
//! 2. Logs the read (FR-MCP-5) — even when the read is denied, so the audit
|
||||
//! trail reflects what an agent *asked for*.
|
||||
//! 3. Independently re-checks scope + the recordings gate (FR-MCP-3) — there
|
||||
//! is deliberately no single choke point upstream of this file.
|
||||
|
||||
use crate::mcp::{scope, ExposeScope};
|
||||
use crate::models::MeetingId;
|
||||
use crate::storage::{MeetingFilter, Store};
|
||||
use rmcp::model::{
|
||||
CallToolRequestParams, CallToolResult, Implementation, JsonObject, ListToolsResult,
|
||||
PaginatedRequestParams, ServerCapabilities, ServerInfo, Tool,
|
||||
};
|
||||
use rmcp::service::{RequestContext, RoleServer};
|
||||
use rmcp::{ErrorData as McpProtoError, ServerHandler};
|
||||
use serde_json::{json, Value};
|
||||
use std::sync::Arc;
|
||||
use tauri::{AppHandle, Emitter};
|
||||
|
||||
/// Shared handle the HTTP/stdio transports build a fresh `rmcp` service
|
||||
/// around per-connection (`ServerHandler` methods take `&self`, so this just
|
||||
/// needs to be `Clone` + cheap — it's an `Arc<Store>` and an `AppHandle`).
|
||||
/// `app` is `None` in `--mcp-stdio` mode (a separate process with no Tauri
|
||||
/// window to emit events to, see `mcp::stdio_transport`/`main.rs`) — the
|
||||
/// `mcp_access_log` row is still written either way (FR-MCP-5), only the
|
||||
/// live `"mcp://access"` event has nowhere to go.
|
||||
#[derive(Clone)]
|
||||
pub struct WaMcpHandler {
|
||||
store: Arc<dyn Store>,
|
||||
app: Option<AppHandle>,
|
||||
}
|
||||
|
||||
impl WaMcpHandler {
|
||||
pub fn new(store: Arc<dyn Store>, app: Option<AppHandle>) -> Self {
|
||||
Self { store, app }
|
||||
}
|
||||
|
||||
/// Live scope read (not cached) so `set_mcp_scope` applies without a
|
||||
/// server restart.
|
||||
fn current_scope(&self) -> (ExposeScope, bool) {
|
||||
let settings = crate::commands::load_settings();
|
||||
(
|
||||
ExposeScope::parse(&settings.mcp_expose),
|
||||
settings.mcp_expose_recordings,
|
||||
)
|
||||
}
|
||||
|
||||
async fn log_access(&self, tool: &str, meeting_id: Option<&MeetingId>, client: Option<&str>) {
|
||||
if let Err(e) = self.store.record_mcp_access(tool, meeting_id, client).await {
|
||||
tracing::warn!("failed to record mcp access log row: {e}");
|
||||
}
|
||||
if let Some(app) = &self.app {
|
||||
let _ = app.emit(
|
||||
"mcp://access",
|
||||
json!({
|
||||
"at": now_ms(),
|
||||
"tool": tool,
|
||||
"meetingId": meeting_id,
|
||||
"client": client,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn client_name(context: &RequestContext<RoleServer>) -> Option<String> {
|
||||
context
|
||||
.peer
|
||||
.peer_info()
|
||||
.map(|info| info.client_info.name.clone())
|
||||
}
|
||||
|
||||
async fn tool_list_recent_meetings(
|
||||
&self,
|
||||
args: &Option<JsonObject>,
|
||||
client: Option<&str>,
|
||||
) -> Result<CallToolResult, McpProtoError> {
|
||||
self.log_access("list_recent_meetings", None, client).await;
|
||||
let (scope_val, expose_recordings) = self.current_scope();
|
||||
if !scope::meetings_visible(scope_val) {
|
||||
return Ok(CallToolResult::structured(json!({ "meetings": [] })));
|
||||
}
|
||||
let limit = arg_u64(args, "limit").unwrap_or(20).clamp(1, 100) as usize;
|
||||
let items = self
|
||||
.store
|
||||
.list_meetings(MeetingFilter::default())
|
||||
.await
|
||||
.map_err(store_err)?;
|
||||
let mut out = Vec::with_capacity(limit);
|
||||
for item in items {
|
||||
if out.len() >= limit {
|
||||
break;
|
||||
}
|
||||
let Ok(full) = self.store.get_meeting(&item.id).await else {
|
||||
continue;
|
||||
};
|
||||
if !scope::recording_gate_ok(expose_recordings, full.recorded) {
|
||||
continue;
|
||||
}
|
||||
out.push(json!({
|
||||
"id": item.id,
|
||||
"title": item.title,
|
||||
"startedAt": item.started_at,
|
||||
"durationSecs": item.duration_secs,
|
||||
"status": item.status.as_str(),
|
||||
"tags": item.tags,
|
||||
}));
|
||||
}
|
||||
Ok(CallToolResult::structured(json!({ "meetings": out })))
|
||||
}
|
||||
|
||||
async fn tool_get_transcript(
|
||||
&self,
|
||||
args: &Option<JsonObject>,
|
||||
client: Option<&str>,
|
||||
) -> Result<CallToolResult, McpProtoError> {
|
||||
let meeting_id = arg_str(args, "meetingId")
|
||||
.ok_or_else(|| McpProtoError::invalid_params("meetingId is required", None))?;
|
||||
self.log_access("get_transcript", Some(&meeting_id), client)
|
||||
.await;
|
||||
let (scope_val, expose_recordings) = self.current_scope();
|
||||
if !scope::meetings_visible(scope_val) {
|
||||
return Ok(denied("get_transcript scope is not `all`"));
|
||||
}
|
||||
let meeting = self
|
||||
.store
|
||||
.get_meeting(&meeting_id)
|
||||
.await
|
||||
.map_err(store_err)?;
|
||||
if !scope::recording_gate_ok(expose_recordings, meeting.recorded) {
|
||||
return Ok(denied(
|
||||
"this meeting retained its recording; expose_recordings is off",
|
||||
));
|
||||
}
|
||||
Ok(CallToolResult::structured(json!({
|
||||
"meetingId": meeting.id,
|
||||
"title": meeting.title,
|
||||
"segments": meeting.segments,
|
||||
})))
|
||||
}
|
||||
|
||||
async fn tool_get_action_items(
|
||||
&self,
|
||||
args: &Option<JsonObject>,
|
||||
client: Option<&str>,
|
||||
) -> Result<CallToolResult, McpProtoError> {
|
||||
let meeting_id = arg_str(args, "meetingId")
|
||||
.ok_or_else(|| McpProtoError::invalid_params("meetingId is required", None))?;
|
||||
self.log_access("get_action_items", Some(&meeting_id), client)
|
||||
.await;
|
||||
let (scope_val, expose_recordings) = self.current_scope();
|
||||
if !scope::meetings_visible(scope_val) {
|
||||
return Ok(denied("get_action_items scope is not `all`"));
|
||||
}
|
||||
let meeting = self
|
||||
.store
|
||||
.get_meeting(&meeting_id)
|
||||
.await
|
||||
.map_err(store_err)?;
|
||||
if !scope::recording_gate_ok(expose_recordings, meeting.recorded) {
|
||||
return Ok(denied(
|
||||
"this meeting retained its recording; expose_recordings is off",
|
||||
));
|
||||
}
|
||||
let items = self
|
||||
.store
|
||||
.list_action_items(&meeting_id)
|
||||
.await
|
||||
.map_err(store_err)?;
|
||||
Ok(CallToolResult::structured(json!({
|
||||
"meetingId": meeting_id,
|
||||
"items": items,
|
||||
})))
|
||||
}
|
||||
|
||||
async fn tool_get_feature_brief(
|
||||
&self,
|
||||
args: &Option<JsonObject>,
|
||||
client: Option<&str>,
|
||||
) -> Result<CallToolResult, McpProtoError> {
|
||||
let id = arg_str(args, "id")
|
||||
.ok_or_else(|| McpProtoError::invalid_params("id is required", None))?;
|
||||
self.log_access("get_feature_brief", None, client).await;
|
||||
let (scope_val, _expose_recordings) = self.current_scope();
|
||||
if matches!(scope_val, ExposeScope::None) {
|
||||
return Ok(denied("MCP scope is `none`; no briefs are exposed"));
|
||||
}
|
||||
let row = match self.store.get_feature_brief_row(&id).await {
|
||||
Ok(row) => row,
|
||||
Err(e) => {
|
||||
return Ok(CallToolResult::structured_error(json!({
|
||||
"error": "storage",
|
||||
"message": e.to_string(),
|
||||
})))
|
||||
}
|
||||
};
|
||||
if !scope::brief_visible(scope_val, row.exposed) {
|
||||
return Ok(denied(
|
||||
"this brief is not exposed (toggle it on via set_brief_exposed, or set scope to `all`)",
|
||||
));
|
||||
}
|
||||
match crate::commands::get_feature_brief_core(&self.store, &id).await {
|
||||
Ok(brief) => Ok(CallToolResult::structured(
|
||||
serde_json::to_value(brief)
|
||||
.map_err(|e| McpProtoError::internal_error(e.to_string(), None))?,
|
||||
)),
|
||||
Err(e) => Ok(CallToolResult::structured_error(json!({
|
||||
"error": e.kind,
|
||||
"message": e.message,
|
||||
}))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerHandler for WaMcpHandler {
|
||||
fn get_info(&self) -> ServerInfo {
|
||||
ServerInfo {
|
||||
capabilities: ServerCapabilities::builder().enable_tools().build(),
|
||||
server_info: Implementation {
|
||||
name: "whispassist".into(),
|
||||
title: Some("WhispAssist".into()),
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
description: None,
|
||||
icons: None,
|
||||
website_url: None,
|
||||
},
|
||||
instructions: Some(
|
||||
"WhispAssist meeting-assistant tools. Served data may be forwarded by this \
|
||||
agent to its own model provider outside WhispAssist's control -- WA discloses \
|
||||
this in its UI and logs every read (FR-MCP-5). Recordings (.wav) are never \
|
||||
served by any tool here."
|
||||
.into(),
|
||||
),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
async fn list_tools(
|
||||
&self,
|
||||
_request: Option<PaginatedRequestParams>,
|
||||
_context: RequestContext<RoleServer>,
|
||||
) -> Result<ListToolsResult, McpProtoError> {
|
||||
let tools = vec![
|
||||
Tool::new(
|
||||
"list_recent_meetings",
|
||||
"Recent meetings, most recent first (scoped by the user's MCP settings).",
|
||||
obj_schema(json!({
|
||||
"type": "object",
|
||||
"properties": { "limit": { "type": "integer", "minimum": 1, "maximum": 100 } },
|
||||
"additionalProperties": false,
|
||||
})),
|
||||
),
|
||||
Tool::new(
|
||||
"get_transcript",
|
||||
"Full transcript (speaker-labeled segments) for one meeting.",
|
||||
obj_schema(json!({
|
||||
"type": "object",
|
||||
"properties": { "meetingId": { "type": "string" } },
|
||||
"required": ["meetingId"],
|
||||
"additionalProperties": false,
|
||||
})),
|
||||
),
|
||||
Tool::new(
|
||||
"get_action_items",
|
||||
"Confirmed action items for one meeting.",
|
||||
obj_schema(json!({
|
||||
"type": "object",
|
||||
"properties": { "meetingId": { "type": "string" } },
|
||||
"required": ["meetingId"],
|
||||
"additionalProperties": false,
|
||||
})),
|
||||
),
|
||||
Tool::new(
|
||||
"get_feature_brief",
|
||||
"Agent-ready spec (problem/outcome/acceptance criteria) distilled from a meeting.",
|
||||
obj_schema(json!({
|
||||
"type": "object",
|
||||
"properties": { "id": { "type": "string" } },
|
||||
"required": ["id"],
|
||||
"additionalProperties": false,
|
||||
})),
|
||||
),
|
||||
];
|
||||
Ok(ListToolsResult::with_all_items(tools))
|
||||
}
|
||||
|
||||
async fn call_tool(
|
||||
&self,
|
||||
request: CallToolRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, McpProtoError> {
|
||||
let client = Self::client_name(&context);
|
||||
match request.name.as_ref() {
|
||||
"list_recent_meetings" => {
|
||||
self.tool_list_recent_meetings(&request.arguments, client.as_deref())
|
||||
.await
|
||||
}
|
||||
"get_transcript" => {
|
||||
self.tool_get_transcript(&request.arguments, client.as_deref())
|
||||
.await
|
||||
}
|
||||
"get_action_items" => {
|
||||
self.tool_get_action_items(&request.arguments, client.as_deref())
|
||||
.await
|
||||
}
|
||||
"get_feature_brief" => {
|
||||
self.tool_get_feature_brief(&request.arguments, client.as_deref())
|
||||
.await
|
||||
}
|
||||
other => Err(McpProtoError::invalid_params(
|
||||
format!("unknown tool: {other}"),
|
||||
None,
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn obj_schema(value: Value) -> Arc<JsonObject> {
|
||||
Arc::new(value.as_object().cloned().unwrap_or_default())
|
||||
}
|
||||
|
||||
fn arg_str(args: &Option<JsonObject>, key: &str) -> Option<String> {
|
||||
args.as_ref()?.get(key)?.as_str().map(str::to_string)
|
||||
}
|
||||
|
||||
fn arg_u64(args: &Option<JsonObject>, key: &str) -> Option<u64> {
|
||||
args.as_ref()?.get(key)?.as_u64()
|
||||
}
|
||||
|
||||
fn store_err(e: crate::storage::StoreError) -> McpProtoError {
|
||||
McpProtoError::internal_error(e.to_string(), None)
|
||||
}
|
||||
|
||||
fn denied(reason: &str) -> CallToolResult {
|
||||
CallToolResult::structured_error(json!({ "error": "scope_denied", "message": reason }))
|
||||
}
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as i64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//! Streamable HTTP transport (FR-MCP-6): loopback-only bind + a bearer-token
|
||||
//! gate that runs in front of every connection, before a single byte reaches
|
||||
//! the MCP service. `rmcp`'s `StreamableHttpService` is a bare
|
||||
//! `tower_service::Service` (not an axum app), so this module supplies the
|
||||
//! actual TCP accept loop + HTTP/1 framing via `hyper`.
|
||||
|
||||
use crate::mcp::handler::WaMcpHandler;
|
||||
use crate::mcp::{token, McpError};
|
||||
use bytes::Bytes;
|
||||
use http_body_util::{combinators::BoxBody, BodyExt, Full};
|
||||
use hyper::body::Incoming;
|
||||
use hyper::service::service_fn;
|
||||
use hyper::{Request, Response, StatusCode};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
|
||||
use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
|
||||
use std::convert::Infallible;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// Binds `host:port`, refusing anything that doesn't resolve to a loopback
|
||||
/// address (127.0.0.0/8 or ::1) -- the only way this crate ever opens a
|
||||
/// listening socket for MCP (FR-MCP-1, NFR-SEC-5). Kept generic over `host`
|
||||
/// purely so the refusal path is directly unit-testable; the only production
|
||||
/// caller (`mcp::server`) always passes `"127.0.0.1"`.
|
||||
pub(crate) async fn bind_loopback(host: &str, port: u16) -> Result<TcpListener, McpError> {
|
||||
let ip: IpAddr = host.parse().map_err(|_| McpError::NonLoopback)?;
|
||||
if !ip.is_loopback() {
|
||||
return Err(McpError::NonLoopback);
|
||||
}
|
||||
TcpListener::bind(SocketAddr::new(ip, port))
|
||||
.await
|
||||
.map_err(|e| McpError::Server(e.to_string()))
|
||||
}
|
||||
|
||||
/// A running HTTP server; `stop()` cancels the accept loop and all live
|
||||
/// connections and waits for cleanup.
|
||||
pub(crate) struct HttpServerHandle {
|
||||
pub local_addr: SocketAddr,
|
||||
shutdown: CancellationToken,
|
||||
join: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl HttpServerHandle {
|
||||
pub async fn stop(self) {
|
||||
self.shutdown.cancel();
|
||||
let _ = self.join.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Serves the MCP Streamable HTTP endpoint (`/mcp`, per the config's session
|
||||
/// routing) on an already-bound loopback listener. Every request must present
|
||||
/// `Authorization: Bearer <token>` matching the stored token (constant-time
|
||||
/// compare, `mcp::token::verify`) or it never reaches `rmcp`.
|
||||
pub(crate) fn serve(
|
||||
listener: TcpListener,
|
||||
expected_token: String,
|
||||
handler: WaMcpHandler,
|
||||
) -> HttpServerHandle {
|
||||
let local_addr = listener
|
||||
.local_addr()
|
||||
.expect("a just-bound TcpListener has a local addr");
|
||||
let shutdown = CancellationToken::new();
|
||||
|
||||
let config = StreamableHttpServerConfig {
|
||||
stateful_mode: true,
|
||||
..Default::default()
|
||||
};
|
||||
let session_manager = Arc::new(LocalSessionManager::default());
|
||||
let service = StreamableHttpService::new(move || Ok(handler.clone()), session_manager, config);
|
||||
|
||||
let accept_ct = shutdown.clone();
|
||||
let join = tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = accept_ct.cancelled() => break,
|
||||
accepted = listener.accept() => {
|
||||
let Ok((stream, _peer)) = accepted else { continue };
|
||||
let io = TokioIo::new(stream);
|
||||
let svc = service.clone();
|
||||
let token = expected_token.clone();
|
||||
let conn_ct = accept_ct.clone();
|
||||
tokio::spawn(async move {
|
||||
let guarded = service_fn(move |req: Request<Incoming>| {
|
||||
let mut svc = svc.clone();
|
||||
let token = token.clone();
|
||||
async move { Ok::<_, Infallible>(handle_request(req, &mut svc, &token).await) }
|
||||
});
|
||||
let conn = hyper::server::conn::http1::Builder::new().serve_connection(io, guarded);
|
||||
tokio::select! {
|
||||
_ = conn_ct.cancelled() => {}
|
||||
_ = conn => {}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
HttpServerHandle {
|
||||
local_addr,
|
||||
shutdown,
|
||||
join,
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_request(
|
||||
req: Request<Incoming>,
|
||||
svc: &mut StreamableHttpService<WaMcpHandler>,
|
||||
expected_token: &str,
|
||||
) -> Response<BoxBody<Bytes, Infallible>> {
|
||||
if !is_authorized(&req, expected_token) {
|
||||
return unauthorized_response();
|
||||
}
|
||||
let (parts, body) = req.into_parts();
|
||||
let req = Request::from_parts(parts, body.boxed());
|
||||
tower_service::Service::call(svc, req)
|
||||
.await
|
||||
.unwrap_or_else(|never: Infallible| match never {})
|
||||
}
|
||||
|
||||
fn is_authorized(req: &Request<Incoming>, expected_token: &str) -> bool {
|
||||
let Some(header) = req.headers().get(hyper::header::AUTHORIZATION) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(header) = header.to_str() else {
|
||||
return false;
|
||||
};
|
||||
let Some(presented) = header.strip_prefix("Bearer ") else {
|
||||
return false;
|
||||
};
|
||||
token::verify(presented, expected_token)
|
||||
}
|
||||
|
||||
fn unauthorized_response() -> Response<BoxBody<Bytes, Infallible>> {
|
||||
Response::builder()
|
||||
.status(StatusCode::UNAUTHORIZED)
|
||||
.header(hyper::header::CONTENT_TYPE, "application/json")
|
||||
.body(Full::new(Bytes::from_static(b"{\"error\":\"unauthorized\"}")).boxed())
|
||||
.expect("valid response")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_a_non_loopback_bind() {
|
||||
// A real routable address is never allowed regardless of port
|
||||
// availability -- the check happens before any socket syscall.
|
||||
let err = bind_loopback("8.8.8.8", 0).await.unwrap_err();
|
||||
assert!(matches!(err, McpError::NonLoopback));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_an_unparseable_host() {
|
||||
let err = bind_loopback("not-an-ip", 0).await.unwrap_err();
|
||||
assert!(matches!(err, McpError::NonLoopback));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn binds_127_0_0_1_on_an_os_assigned_port() {
|
||||
let listener = bind_loopback("127.0.0.1", 0).await.expect("loopback bind");
|
||||
assert!(listener.local_addr().unwrap().ip().is_loopback());
|
||||
}
|
||||
}
|
||||
+81
-40
@@ -14,10 +14,28 @@
|
||||
use crate::models::{FeatureBrief, MeetingId};
|
||||
use async_trait::async_trait;
|
||||
|
||||
pub mod scope;
|
||||
|
||||
#[cfg(feature = "mcp")]
|
||||
pub mod handler;
|
||||
#[cfg(feature = "mcp")]
|
||||
pub mod http_transport;
|
||||
#[cfg(feature = "mcp")]
|
||||
pub mod server;
|
||||
#[cfg(feature = "mcp")]
|
||||
pub mod stdio_transport;
|
||||
#[cfg(feature = "mcp")]
|
||||
pub mod token;
|
||||
|
||||
#[cfg(feature = "mcp")]
|
||||
pub use server::RmcpServer;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum McpError {
|
||||
#[error("refusing to bind non-loopback address")]
|
||||
NonLoopback,
|
||||
#[error("unauthorized: missing or invalid token")]
|
||||
Unauthorized,
|
||||
#[error("server error: {0}")]
|
||||
Server(String),
|
||||
}
|
||||
@@ -38,7 +56,7 @@ pub struct McpConfig {
|
||||
pub expose_recordings: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum McpTransport {
|
||||
/// Streamable HTTP on http://127.0.0.1:<port>/mcp (loopback only).
|
||||
Http,
|
||||
@@ -46,24 +64,85 @@ pub enum McpTransport {
|
||||
Stdio,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
impl McpTransport {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
McpTransport::Http => "http",
|
||||
McpTransport::Stdio => "stdio",
|
||||
}
|
||||
}
|
||||
|
||||
/// Unknown/missing values fall back to `Http` — the safer default to
|
||||
/// document to the user (stdio requires a client that spawns a process).
|
||||
pub fn parse(s: &str) -> Self {
|
||||
match s {
|
||||
"stdio" => McpTransport::Stdio,
|
||||
_ => McpTransport::Http,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ExposeScope {
|
||||
None,
|
||||
Selected,
|
||||
All,
|
||||
}
|
||||
|
||||
impl ExposeScope {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ExposeScope::None => "none",
|
||||
ExposeScope::Selected => "selected",
|
||||
ExposeScope::All => "all",
|
||||
}
|
||||
}
|
||||
|
||||
/// Unknown values fall back to `None` — scope-control is a privacy
|
||||
/// control, so an unparsed value must never silently become permissive.
|
||||
pub fn parse(s: &str) -> Self {
|
||||
match s {
|
||||
"selected" => ExposeScope::Selected,
|
||||
"all" => ExposeScope::All,
|
||||
_ => ExposeScope::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returned on start: where to point the agent + the token it must present.
|
||||
pub struct McpHandle {
|
||||
pub endpoint: String,
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct McpToolDescriptor {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
}
|
||||
|
||||
/// The four tools-first-surface descriptors (FR-MCP-2), shared by the trait's
|
||||
/// default listing and anything else that needs to enumerate them without a
|
||||
/// running server (e.g. the settings/privacy UI).
|
||||
pub const TOOL_DESCRIPTORS: [McpToolDescriptor; 4] = [
|
||||
McpToolDescriptor {
|
||||
name: "list_recent_meetings",
|
||||
description: "Recent meetings (scoped).",
|
||||
},
|
||||
McpToolDescriptor {
|
||||
name: "get_transcript",
|
||||
description: "Transcript for a meeting (scoped).",
|
||||
},
|
||||
McpToolDescriptor {
|
||||
name: "get_action_items",
|
||||
description: "Action items for a meeting.",
|
||||
},
|
||||
McpToolDescriptor {
|
||||
name: "get_feature_brief",
|
||||
description: "Agent-ready spec distilled from a meeting.",
|
||||
},
|
||||
];
|
||||
|
||||
/// The MCP server. Built on the official Rust SDK (`rmcp`, feature `mcp`).
|
||||
#[async_trait]
|
||||
pub trait McpServer: Send + Sync {
|
||||
@@ -82,41 +161,3 @@ pub trait FeatureBriefBuilder: Send + Sync {
|
||||
target_repo: Option<&str>,
|
||||
) -> Result<FeatureBrief, BriefError>;
|
||||
}
|
||||
|
||||
/// Default rmcp-backed server (feature `mcp`).
|
||||
#[cfg(feature = "mcp")]
|
||||
pub struct RmcpServer;
|
||||
|
||||
#[cfg(feature = "mcp")]
|
||||
#[async_trait]
|
||||
impl McpServer for RmcpServer {
|
||||
async fn start(&self, _cfg: McpConfig) -> Result<McpHandle, McpError> {
|
||||
// T10.4: bind loopback ONLY (reject non-loopback), mint a token, register tools,
|
||||
// serve over Streamable HTTP (/mcp) or stdio. Never opens an outbound socket.
|
||||
todo!("Phase 10b — start MCP server (loopback, token)")
|
||||
}
|
||||
async fn stop(&self, _handle: McpHandle) -> Result<(), McpError> {
|
||||
todo!("Phase 10b — stop MCP server")
|
||||
}
|
||||
fn tools(&self) -> Vec<McpToolDescriptor> {
|
||||
// T10.5: the tools an agent can call. Tools-first for Copilot compatibility.
|
||||
vec![
|
||||
McpToolDescriptor {
|
||||
name: "list_recent_meetings",
|
||||
description: "Recent meetings (scoped).",
|
||||
},
|
||||
McpToolDescriptor {
|
||||
name: "get_transcript",
|
||||
description: "Transcript for a meeting (scoped).",
|
||||
},
|
||||
McpToolDescriptor {
|
||||
name: "get_action_items",
|
||||
description: "Action items for a meeting.",
|
||||
},
|
||||
McpToolDescriptor {
|
||||
name: "get_feature_brief",
|
||||
description: "Agent-ready spec distilled from a meeting.",
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Pure scope-control logic (FR-MCP-3), split out from `mcp/mod.rs` so it's
|
||||
//! unit-testable without a DB, a running server, or the `mcp` cargo feature.
|
||||
//!
|
||||
//! Design note (documented here because the schema doesn't (yet) carry a
|
||||
//! per-meeting "expose this meeting" flag -- only `feature_briefs.exposed`
|
||||
//! does, per `docs/03-data-model.md`): with `ExposeScope::Selected`, meetings/
|
||||
//! transcripts/action-items have no selection mechanism to key off in this
|
||||
//! milestone, so they are treated the same as `None` (deny) rather than the
|
||||
//! same as `All` (allow) -- a privacy-conservative default consistent with
|
||||
//! every other WA default (recording/sync/hosted-AI/MCP itself all default
|
||||
//! OFF). Only `get_feature_brief` has real per-item selection today, via the
|
||||
//! brief's own `exposed` flag (M1). A future "select meetings" UI/schema
|
||||
//! addition should upgrade `Selected` for the other three tools without
|
||||
//! changing this function's callers.
|
||||
|
||||
use crate::mcp::ExposeScope;
|
||||
|
||||
/// Whether `list_recent_meetings`/`get_transcript`/`get_action_items` may see
|
||||
/// meetings at all under the current scope. `Selected` has no per-meeting
|
||||
/// selection mechanism yet (see module docs) so it is conservatively treated
|
||||
/// like `None`.
|
||||
pub fn meetings_visible(scope: ExposeScope) -> bool {
|
||||
matches!(scope, ExposeScope::All)
|
||||
}
|
||||
|
||||
/// Whether a specific feature brief may be served. `exposed` is the brief's
|
||||
/// own per-item flag (`feature_briefs.exposed`, set via `set_brief_exposed`).
|
||||
pub fn brief_visible(scope: ExposeScope, exposed: bool) -> bool {
|
||||
match scope {
|
||||
ExposeScope::None => false,
|
||||
ExposeScope::Selected => exposed,
|
||||
ExposeScope::All => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Recordings (`.wav`) are never exposed unless explicitly allowed (FR-MCP-3),
|
||||
/// independent of `ExposeScope`. None of the four MCP tools serve raw audio
|
||||
/// bytes today, but a meeting that retained its recording (ADR-0009) is
|
||||
/// treated as more sensitive-by-association: its transcript/action items are
|
||||
/// also withheld unless the user opted into `expose_recordings`. Every tool
|
||||
/// handler must call this for each candidate meeting -- there is no central
|
||||
/// choke point (FR-MCP-3 "enforce in every tool handler").
|
||||
pub fn recording_gate_ok(expose_recordings: bool, meeting_recorded: bool) -> bool {
|
||||
expose_recordings || !meeting_recorded
|
||||
}
|
||||
|
||||
/// Combined check a tool handler runs before including one meeting's data.
|
||||
pub fn meeting_allowed(
|
||||
scope: ExposeScope,
|
||||
expose_recordings: bool,
|
||||
meeting_recorded: bool,
|
||||
) -> bool {
|
||||
meetings_visible(scope) && recording_gate_ok(expose_recordings, meeting_recorded)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn none_hides_all_meetings() {
|
||||
assert!(!meetings_visible(ExposeScope::None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_hides_meetings_pending_a_selection_mechanism() {
|
||||
// Documented conservative choice -- see module docs.
|
||||
assert!(!meetings_visible(ExposeScope::Selected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_shows_meetings() {
|
||||
assert!(meetings_visible(ExposeScope::All));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brief_visibility_follows_the_exposed_flag_only_under_selected() {
|
||||
assert!(!brief_visible(ExposeScope::None, true));
|
||||
assert!(!brief_visible(ExposeScope::Selected, false));
|
||||
assert!(brief_visible(ExposeScope::Selected, true));
|
||||
assert!(brief_visible(ExposeScope::All, false));
|
||||
assert!(brief_visible(ExposeScope::All, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recordings_never_served_unless_explicitly_allowed() {
|
||||
assert!(!recording_gate_ok(false, true));
|
||||
assert!(recording_gate_ok(false, false));
|
||||
assert!(recording_gate_ok(true, true));
|
||||
assert!(recording_gate_ok(true, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn meeting_allowed_requires_both_scope_and_recording_gate() {
|
||||
assert!(!meeting_allowed(ExposeScope::All, false, true)); // recorded, not opted-in
|
||||
assert!(meeting_allowed(ExposeScope::All, false, false)); // not recorded
|
||||
assert!(meeting_allowed(ExposeScope::All, true, true)); // opted-in
|
||||
assert!(!meeting_allowed(ExposeScope::None, true, false)); // scope still wins
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! `RmcpServer` — the concrete `McpServer` implementation (T10.4). Owns the
|
||||
//! one running transport (HTTP listener, if any) so `stop()` can tear it
|
||||
//! down; a process-wide singleton (`instance`) is what `commands.rs` reaches
|
||||
//! for, since Tauri command handlers are separate calls with no shared state
|
||||
//! of their own beyond `AppState`.
|
||||
|
||||
use crate::mcp::handler::WaMcpHandler;
|
||||
use crate::mcp::{
|
||||
http_transport, token, McpConfig, McpError, McpHandle, McpServer, McpToolDescriptor,
|
||||
McpTransport,
|
||||
};
|
||||
use crate::storage::Store;
|
||||
use async_trait::async_trait;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use tauri::AppHandle;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
enum Running {
|
||||
Http(http_transport::HttpServerHandle),
|
||||
/// stdio has nothing running *in this process* — the agent spawns its
|
||||
/// own `--mcp-stdio` child (see `mcp::stdio_transport`); this variant
|
||||
/// just records "enabled" for `mcp_status`.
|
||||
Stdio,
|
||||
}
|
||||
|
||||
pub struct RmcpServer {
|
||||
store: Arc<dyn Store>,
|
||||
app: AppHandle,
|
||||
running: Mutex<Option<Running>>,
|
||||
}
|
||||
|
||||
impl RmcpServer {
|
||||
pub fn new(store: Arc<dyn Store>, app: AppHandle) -> Self {
|
||||
Self {
|
||||
store,
|
||||
app,
|
||||
running: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
async fn stop_running(&self) {
|
||||
if let Some(Running::Http(handle)) = self.running.lock().await.take() {
|
||||
handle.stop().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` once a `start()` has actually taken effect (HTTP listener bound
|
||||
/// or stdio mode recorded) — used by `mcp_status`.
|
||||
pub async fn is_running(&self) -> bool {
|
||||
self.running.lock().await.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl McpServer for RmcpServer {
|
||||
async fn start(&self, cfg: McpConfig) -> Result<McpHandle, McpError> {
|
||||
// Re-enabling (or switching transport/port) replaces whatever was running.
|
||||
self.stop_running().await;
|
||||
let auth_token = token::mint_and_store()?;
|
||||
|
||||
match cfg.transport {
|
||||
McpTransport::Http => {
|
||||
let listener = http_transport::bind_loopback("127.0.0.1", cfg.port).await?;
|
||||
let handler = WaMcpHandler::new(self.store.clone(), Some(self.app.clone()));
|
||||
let handle = http_transport::serve(listener, auth_token.clone(), handler);
|
||||
let endpoint = format!("http://{}/mcp", handle.local_addr);
|
||||
*self.running.lock().await = Some(Running::Http(handle));
|
||||
Ok(McpHandle {
|
||||
endpoint,
|
||||
token: auth_token,
|
||||
})
|
||||
}
|
||||
McpTransport::Stdio => {
|
||||
*self.running.lock().await = Some(Running::Stdio);
|
||||
let exe = std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|p| p.to_str().map(str::to_string))
|
||||
.unwrap_or_else(|| "whispassist.exe".to_string());
|
||||
Ok(McpHandle {
|
||||
endpoint: format!("{exe} --mcp-stdio"),
|
||||
token: auth_token,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn stop(&self, _handle: McpHandle) -> Result<(), McpError> {
|
||||
self.stop_running().await;
|
||||
token::delete();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn tools(&self) -> Vec<McpToolDescriptor> {
|
||||
crate::mcp::TOOL_DESCRIPTORS.to_vec()
|
||||
}
|
||||
}
|
||||
|
||||
static INSTANCE: OnceLock<Arc<RmcpServer>> = OnceLock::new();
|
||||
|
||||
/// The process-wide `RmcpServer`. `store`/`app` are only used on the first
|
||||
/// call (they're the same `AppState`/`AppHandle` for the process's whole
|
||||
/// life); later calls just return the existing instance.
|
||||
pub fn instance(store: Arc<dyn Store>, app: AppHandle) -> Arc<RmcpServer> {
|
||||
INSTANCE
|
||||
.get_or_init(|| Arc::new(RmcpServer::new(store, app)))
|
||||
.clone()
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! stdio transport (FR-MCP-6) — "a thin adapter the agent spawns". A coding
|
||||
//! agent's MCP client config spawns `whispassist.exe --mcp-stdio` and talks
|
||||
//! JSON-RPC over that child process's stdin/stdout; `main.rs` checks for that
|
||||
//! flag before building the Tauri window and calls `serve_once` here instead.
|
||||
//!
|
||||
//! There is no bearer-token header to check here (unlike HTTP): the ability
|
||||
//! to spawn this process at all already requires the same OS-level privilege
|
||||
//! as running any other local command as the signed-in user, so process-spawn
|
||||
//! capability is the trust boundary for stdio, same as other local-only MCP
|
||||
//! servers. `set_mcp_enabled` still mints/stores a token (`mcp::token`) for
|
||||
//! parity with the HTTP transport and in case a future stdio client wants to
|
||||
//! pass it, but this transport does not require presenting it.
|
||||
|
||||
use crate::mcp::handler::WaMcpHandler;
|
||||
use crate::mcp::McpError;
|
||||
use rmcp::ServiceExt;
|
||||
|
||||
/// Serves one MCP session over the current process's stdin/stdout until the
|
||||
/// peer disconnects, then returns.
|
||||
pub async fn serve_once(handler: WaMcpHandler) -> Result<(), McpError> {
|
||||
let transport = rmcp::transport::io::stdio();
|
||||
let running = handler
|
||||
.serve(transport)
|
||||
.await
|
||||
.map_err(|e| McpError::Server(e.to_string()))?;
|
||||
running
|
||||
.waiting()
|
||||
.await
|
||||
.map_err(|e| McpError::Server(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! MCP auth-token storage (FR-MCP-1/6). The token itself is **never** written
|
||||
//! to `settings.json`/`wa.db`/logs — only the OS credential store, exactly
|
||||
//! like sync secrets (`sync::credentials`) and hosted-AI API keys.
|
||||
|
||||
use crate::mcp::McpError;
|
||||
|
||||
const SERVICE: &str = "WhispAssist-mcp";
|
||||
const ACCOUNT: &str = "token";
|
||||
const TOKEN_BYTES: usize = 32;
|
||||
|
||||
fn entry() -> Result<keyring::Entry, McpError> {
|
||||
keyring::Entry::new(SERVICE, ACCOUNT).map_err(|e| McpError::Server(e.to_string()))
|
||||
}
|
||||
|
||||
/// Generates a fresh random token (hex-encoded, 64 chars) and persists it,
|
||||
/// replacing whatever was there before (each `set_mcp_enabled` mints a new
|
||||
/// one — there is no "reveal the existing token" path, same treatment as a
|
||||
/// password).
|
||||
pub fn mint_and_store() -> Result<String, McpError> {
|
||||
let mut buf = [0u8; TOKEN_BYTES];
|
||||
getrandom::getrandom(&mut buf).map_err(|e| McpError::Server(e.to_string()))?;
|
||||
let token = hex_encode(&buf);
|
||||
entry()?
|
||||
.set_password(&token)
|
||||
.map_err(|e| McpError::Server(e.to_string()))?;
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
/// Best-effort read for `mcp_status`'s `tokenSet` flag — never returned to
|
||||
/// the frontend as a value, only whether one exists.
|
||||
pub fn is_set() -> bool {
|
||||
entry()
|
||||
.and_then(|e| {
|
||||
e.get_password()
|
||||
.map_err(|e| McpError::Server(e.to_string()))
|
||||
})
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
pub fn get() -> Result<String, McpError> {
|
||||
entry()?
|
||||
.get_password()
|
||||
.map_err(|e| McpError::Server(e.to_string()))
|
||||
}
|
||||
|
||||
/// Best-effort cleanup on disable — a missing entry is not an error.
|
||||
pub fn delete() {
|
||||
if let Ok(e) = entry() {
|
||||
match e.delete_credential() {
|
||||
Ok(()) | Err(keyring::Error::NoEntry) => {}
|
||||
Err(err) => tracing::warn!("failed to delete MCP token: {err}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Constant-time comparison so token checking doesn't leak timing
|
||||
/// information about how many leading bytes matched (NFR-SEC-5).
|
||||
pub fn verify(presented: &str, expected: &str) -> bool {
|
||||
let a = presented.as_bytes();
|
||||
let b = expected.as_bytes();
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
let mut diff = 0u8;
|
||||
for (x, y) in a.iter().zip(b.iter()) {
|
||||
diff |= x ^ y;
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
|
||||
fn hex_encode(bytes: &[u8]) -> String {
|
||||
let mut s = String::with_capacity(bytes.len() * 2);
|
||||
for b in bytes {
|
||||
s.push_str(&format!("{b:02x}"));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn verify_requires_exact_match() {
|
||||
assert!(verify("abc123", "abc123"));
|
||||
assert!(!verify("abc123", "abc124"));
|
||||
assert!(!verify("abc12", "abc123"));
|
||||
assert!(!verify("", "abc123"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_encode_is_lowercase_and_fixed_width() {
|
||||
assert_eq!(hex_encode(&[0, 255, 16]), "00ff10");
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,19 @@ pub struct ModelInfo {
|
||||
pub size_mb: u32, // approximate download size
|
||||
pub installed: bool,
|
||||
pub active: bool,
|
||||
/// `false` for the `.en` (English-only) ggml variants; `true` for the
|
||||
/// multilingual variants (no `.en` suffix, T8.7/FR-TRX-4/M4.2) — gates
|
||||
/// whether the Settings language picker is enabled for this model.
|
||||
pub multilingual: bool,
|
||||
}
|
||||
|
||||
/// One selectable transcription language (T8.7, FR-TRX-4) — ISO-639-1 code
|
||||
/// (as accepted by `whisper_rs::FullParams::set_language`) plus a display
|
||||
/// label for the Settings dropdown.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LanguageOption {
|
||||
pub code: String,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
@@ -198,10 +211,26 @@ pub struct Settings {
|
||||
pub llm_advanced: serde_json::Value,
|
||||
pub preferred_backend: String, // auto|npu|nvidia|amd|intel|cpu
|
||||
pub whisper_model: String, // ModelInfo.id, e.g. "base.en-q5_1"
|
||||
/// Global default transcription language (T8.7, FR-TRX-4): `None`/`"auto"`
|
||||
/// lets whisper.cpp auto-detect; an ISO-639-1 code (e.g. "es") forces
|
||||
/// that language. Only takes effect with a multilingual model loaded —
|
||||
/// an English-only (`.en`) model always decodes English regardless of
|
||||
/// this setting (see `transcription::resolve_language`). Each meeting
|
||||
/// persists whatever was actually used at `Meeting.language`, so this is
|
||||
/// just the default applied at the next `start_recording`.
|
||||
#[serde(default)]
|
||||
pub whisper_language: Option<String>,
|
||||
pub low_overhead: bool,
|
||||
// Recording retention (ADR-0009). Default OFF.
|
||||
pub default_record: bool,
|
||||
pub consent_acknowledged: bool,
|
||||
/// One-time "data leaves your device" acknowledgment for hosted
|
||||
/// (non-local) AI providers — Anthropic, or a hosted OpenAI-compatible
|
||||
/// gateway (ADR-0011, T10.3/M3.3). Shown once before first hosted use;
|
||||
/// this flag is what makes it not nag every time. Independent of
|
||||
/// `consent_acknowledged` (that one's specifically about recording law).
|
||||
#[serde(default)]
|
||||
pub hosted_ai_acknowledged: bool,
|
||||
// Sync master switch (ADR-0010). Default OFF. Target rows live in the DB; secrets in OS keychain.
|
||||
pub sync_enabled: bool,
|
||||
// Storage retention policy (FR-STORE-2). None = no cap on that dimension.
|
||||
@@ -213,6 +242,13 @@ pub struct Settings {
|
||||
pub pst_last_path: Option<String>,
|
||||
#[serde(default)]
|
||||
pub pst_auto_sync: bool,
|
||||
// Microsoft Graph calendar source (M4.4, T8.9, ADR-0008, FR-CAL-6). Opt-in,
|
||||
// explicit consent via OAuth PKCE — off by default. The credential ref
|
||||
// points into the OS credential store; the token itself never lives here.
|
||||
#[serde(default)]
|
||||
pub graph_calendar_enabled: bool,
|
||||
#[serde(default)]
|
||||
pub graph_calendar_credential_ref: Option<String>,
|
||||
// Audio capture device override (FR-CAP-1). `Device::get_id()` string;
|
||||
// None = system default render device (loopback / system audio).
|
||||
#[serde(default)]
|
||||
@@ -226,6 +262,33 @@ pub struct Settings {
|
||||
// default capture device.
|
||||
#[serde(default)]
|
||||
pub audio_input_device: Option<String>,
|
||||
// Local MCP server (Phase 10b, ADR-0011, FR-MCP-1). OFF by default; the
|
||||
// auth token itself is NEVER stored here — only in the OS credential
|
||||
// store (see `mcp::token`). `mcp_expose` is one of none|selected|all;
|
||||
// `mcp_expose_recordings` gates access to meetings with retained audio
|
||||
// (ADR-0009) regardless of `mcp_expose` (FR-MCP-3).
|
||||
#[serde(default)]
|
||||
pub mcp_enabled: bool,
|
||||
#[serde(default = "default_mcp_transport")]
|
||||
pub mcp_transport: String, // http|stdio
|
||||
#[serde(default = "default_mcp_port")]
|
||||
pub mcp_port: u16,
|
||||
#[serde(default = "default_mcp_expose")]
|
||||
pub mcp_expose: String, // none|selected|all
|
||||
#[serde(default)]
|
||||
pub mcp_expose_recordings: bool,
|
||||
}
|
||||
|
||||
fn default_mcp_transport() -> String {
|
||||
"http".into()
|
||||
}
|
||||
|
||||
fn default_mcp_port() -> u16 {
|
||||
4849
|
||||
}
|
||||
|
||||
fn default_mcp_expose() -> String {
|
||||
"none".into()
|
||||
}
|
||||
|
||||
/// serde default for a `bool` field that should be `true` when absent from an
|
||||
|
||||
@@ -5,8 +5,9 @@
|
||||
//! summary) are regenerable; retention never touches an in-progress meeting.
|
||||
|
||||
use crate::models::{
|
||||
ActionItem, CalendarEvent, ImportedEvent, MeetingId, MeetingListItem, MeetingStatus,
|
||||
Participant, SearchHit, SpeakerInfo, TranscriptSegment,
|
||||
ActionItem, CalendarEvent, ContextExcerpt, FeatureBriefInfo, ImportedEvent, McpAccessEntry,
|
||||
MeetingId, MeetingListItem, MeetingStatus, Participant, SearchHit, SpeakerInfo,
|
||||
TranscriptSegment,
|
||||
};
|
||||
use crate::paths;
|
||||
use async_trait::async_trait;
|
||||
@@ -41,6 +42,12 @@ pub struct NewMeeting {
|
||||
/// re-rendering notes.md on reprocess/resume reapplies the same
|
||||
/// section structure instead of losing it.
|
||||
pub template_id: Option<String>,
|
||||
/// Transcription language requested at recording start (T8.7, FR-TRX-4):
|
||||
/// `None` means auto-detect. Recorded immediately (not just at
|
||||
/// `finalize_meeting`) so a crash-recovered `recovering` meeting still
|
||||
/// knows what was asked for; `finalize_meeting`'s `language` overwrites
|
||||
/// this with whatever whisper.cpp actually resolved/detected.
|
||||
pub language: Option<String>,
|
||||
}
|
||||
|
||||
/// `list_meetings` filters (Phase 8, FR-SEARCH-2). All fields are ANDed
|
||||
@@ -128,6 +135,64 @@ pub struct Retention {
|
||||
pub max_size_gb: Option<u32>,
|
||||
}
|
||||
|
||||
/// A feature brief distilled from a meeting (ADR-0011, M1). Holds only a
|
||||
/// `credential_ref`-style pointer (`path`) into the meeting's `briefs/`
|
||||
/// folder — the JSON body is the source of truth; this row is the index
|
||||
/// `list_feature_briefs`/the MCP scope check reads. Maps 1:1 to the
|
||||
/// `feature_briefs` table.
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct FeatureBriefRow {
|
||||
pub id: String,
|
||||
pub meeting_id: MeetingId,
|
||||
pub title: String,
|
||||
pub target_repo: Option<String>,
|
||||
pub path: String, // briefs/<id>.json, relative to the meeting's folder
|
||||
pub exposed: bool,
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
impl From<FeatureBriefRow> for FeatureBriefInfo {
|
||||
fn from(row: FeatureBriefRow) -> Self {
|
||||
FeatureBriefInfo {
|
||||
id: row.id,
|
||||
meeting_id: row.meeting_id,
|
||||
title: row.title,
|
||||
target_repo: row.target_repo,
|
||||
exposed: row.exposed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On-disk shape of `briefs/<id>.json` (`docs/03-data-model.md`, ADR-0011) —
|
||||
/// the schema/provenance envelope around the same fields as the IPC
|
||||
/// `FeatureBrief` (`models.rs`). Written by `create_feature_brief` (M1.4),
|
||||
/// sealed at rest with the vault when unlocked, exactly like `summary.json`.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct BriefFile {
|
||||
pub schema: u32,
|
||||
pub id: String,
|
||||
pub meeting_id: MeetingId,
|
||||
pub generated_at: i64,
|
||||
pub provider: String,
|
||||
pub model: String,
|
||||
pub title: String,
|
||||
pub problem: String,
|
||||
pub desired_outcome: String,
|
||||
pub acceptance_criteria: Vec<String>,
|
||||
pub target_repo: Option<String>,
|
||||
pub context_excerpts: Vec<ContextExcerpt>,
|
||||
pub source: BriefSource,
|
||||
}
|
||||
|
||||
/// `schema`-envelope companion recording which meeting this brief came from,
|
||||
/// by name and time — distinct from the FK `meeting_id`, which can outlive a
|
||||
/// renamed/retitled meeting.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct BriefSource {
|
||||
pub meeting_title: String,
|
||||
pub at: i64,
|
||||
}
|
||||
|
||||
/// A configured upload destination as stored in the DB (ADR-0010). Holds only a
|
||||
/// `credential_ref` into the OS credential store — never the secret itself
|
||||
/// (FR-SYNC-6). Maps 1:1 to the `sync_targets` table.
|
||||
@@ -297,6 +362,48 @@ pub trait Store: Send + Sync {
|
||||
&self,
|
||||
meeting_id: Option<&MeetingId>,
|
||||
) -> Result<Vec<SyncJobRow>, StoreError>;
|
||||
|
||||
// ---- Feature briefs (Phase 10 M1, ADR-0011) ----
|
||||
/// Indexes a brief already sealed to disk by `create_feature_brief`
|
||||
/// (M1.4). Deletion cascades via the meeting FK — `delete_meeting`
|
||||
/// already drops the row (and its folder) with the rest of the meeting.
|
||||
async fn insert_feature_brief(&self, row: FeatureBriefRow) -> Result<(), StoreError>;
|
||||
/// Newest first; `None` lists across all meetings (the MCP "recent
|
||||
/// briefs" surface and the frontend's per-meeting list share this call).
|
||||
async fn list_feature_briefs(
|
||||
&self,
|
||||
meeting_id: Option<&MeetingId>,
|
||||
) -> Result<Vec<FeatureBriefInfo>, StoreError>;
|
||||
/// The full row (incl. `path`) so a caller can resolve and read the
|
||||
/// sealed JSON file itself (`get_feature_brief`, MCP `get_feature_brief`
|
||||
/// tool).
|
||||
async fn get_feature_brief_row(&self, id: &str) -> Result<FeatureBriefRow, StoreError>;
|
||||
/// Scope control: include/exclude a brief from the MCP server (FR-MCP-3).
|
||||
async fn set_brief_exposed(&self, id: &str, exposed: bool) -> Result<(), StoreError>;
|
||||
|
||||
// ---- MCP server (Phase 10b, ADR-0011) ----
|
||||
/// Confirmed action items for a meeting (FR-MCP-2 `get_action_items`) —
|
||||
/// distinct from `list_pending_reminders` (which is filtered to
|
||||
/// unfired-reminder rows across *all* meetings for the startup reconcile).
|
||||
async fn list_action_items(
|
||||
&self,
|
||||
meeting_id: &MeetingId,
|
||||
) -> Result<Vec<ActionItem>, StoreError>;
|
||||
/// Appends one row to the audit log (FR-MCP-5). Every MCP tool read calls
|
||||
/// this, regardless of whether the read was actually allowed to see
|
||||
/// anything — the audit trail is "what an agent asked for", not just
|
||||
/// "what it received".
|
||||
async fn record_mcp_access(
|
||||
&self,
|
||||
tool: &str,
|
||||
meeting_id: Option<&MeetingId>,
|
||||
client: Option<&str>,
|
||||
) -> Result<(), StoreError>;
|
||||
/// Most recent audit rows first, optionally capped (`mcp_access_log` command).
|
||||
async fn list_mcp_access_log(
|
||||
&self,
|
||||
limit: Option<u32>,
|
||||
) -> Result<Vec<McpAccessEntry>, StoreError>;
|
||||
}
|
||||
|
||||
/// SQLite-backed store. Migrations live in `migrations/` (`sqlx::migrate!`).
|
||||
@@ -602,8 +709,8 @@ impl Store for SqliteStore {
|
||||
let audio_path = folder.join("audio.wav");
|
||||
let now = now_unix();
|
||||
sqlx::query(
|
||||
"INSERT INTO meetings (id, title, started_at, folder_path, audio_path, status, calendar_event_id, template_id, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, 'recording', ?, ?, ?, ?)",
|
||||
"INSERT INTO meetings (id, title, started_at, folder_path, audio_path, status, calendar_event_id, template_id, language, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, 'recording', ?, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(&id)
|
||||
.bind(&m.title)
|
||||
@@ -612,6 +719,7 @@ impl Store for SqliteStore {
|
||||
.bind(audio_path.display().to_string())
|
||||
.bind(&m.calendar_event_id)
|
||||
.bind(&m.template_id)
|
||||
.bind(&m.language)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.execute(&self.pool)
|
||||
@@ -1484,6 +1592,131 @@ impl Store for SqliteStore {
|
||||
};
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
async fn insert_feature_brief(&self, row: FeatureBriefRow) -> Result<(), StoreError> {
|
||||
sqlx::query(
|
||||
"INSERT INTO feature_briefs (id, meeting_id, title, target_repo, path, exposed, created_at) \
|
||||
VALUES (?,?,?,?,?,?,?)",
|
||||
)
|
||||
.bind(&row.id)
|
||||
.bind(&row.meeting_id)
|
||||
.bind(&row.title)
|
||||
.bind(&row.target_repo)
|
||||
.bind(&row.path)
|
||||
.bind(row.exposed)
|
||||
.bind(row.created_at)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list_feature_briefs(
|
||||
&self,
|
||||
meeting_id: Option<&MeetingId>,
|
||||
) -> Result<Vec<FeatureBriefInfo>, StoreError> {
|
||||
let rows =
|
||||
match meeting_id {
|
||||
Some(m) => sqlx::query_as::<_, FeatureBriefRow>(
|
||||
"SELECT * FROM feature_briefs WHERE meeting_id = ? ORDER BY created_at DESC",
|
||||
)
|
||||
.bind(m)
|
||||
.fetch_all(&self.pool)
|
||||
.await?,
|
||||
None => {
|
||||
sqlx::query_as::<_, FeatureBriefRow>(
|
||||
"SELECT * FROM feature_briefs ORDER BY created_at DESC",
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?
|
||||
}
|
||||
};
|
||||
Ok(rows.into_iter().map(FeatureBriefInfo::from).collect())
|
||||
}
|
||||
|
||||
async fn get_feature_brief_row(&self, id: &str) -> Result<FeatureBriefRow, StoreError> {
|
||||
sqlx::query_as::<_, FeatureBriefRow>("SELECT * FROM feature_briefs WHERE id = ?")
|
||||
.bind(id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?
|
||||
.ok_or_else(|| StoreError::NotFound(format!("feature brief {id}")))
|
||||
}
|
||||
|
||||
async fn set_brief_exposed(&self, id: &str, exposed: bool) -> Result<(), StoreError> {
|
||||
let res = sqlx::query("UPDATE feature_briefs SET exposed = ? WHERE id = ?")
|
||||
.bind(exposed)
|
||||
.bind(id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
if res.rows_affected() == 0 {
|
||||
return Err(StoreError::NotFound(format!("feature brief {id}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list_action_items(
|
||||
&self,
|
||||
meeting_id: &MeetingId,
|
||||
) -> Result<Vec<ActionItem>, StoreError> {
|
||||
let rows = sqlx::query(
|
||||
"SELECT id, text, owner, due_at, confirmed, reminder_set FROM action_items \
|
||||
WHERE meeting_id = ? ORDER BY created_at ASC",
|
||||
)
|
||||
.bind(meeting_id)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.iter()
|
||||
.map(|r| ActionItem {
|
||||
id: Some(r.get("id")),
|
||||
text: r.get("text"),
|
||||
owner: r.get("owner"),
|
||||
due_at: r.get("due_at"),
|
||||
confirmed: r.get::<i64, _>("confirmed") != 0,
|
||||
reminder_set: r.get::<i64, _>("reminder_set") != 0,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn record_mcp_access(
|
||||
&self,
|
||||
tool: &str,
|
||||
meeting_id: Option<&MeetingId>,
|
||||
client: Option<&str>,
|
||||
) -> Result<(), StoreError> {
|
||||
sqlx::query(
|
||||
"INSERT INTO mcp_access_log (id, at, tool, meeting_id, client) VALUES (?,?,?,?,?)",
|
||||
)
|
||||
.bind(uuid::Uuid::new_v4().to_string())
|
||||
.bind(now_unix())
|
||||
.bind(tool)
|
||||
.bind(meeting_id)
|
||||
.bind(client)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list_mcp_access_log(
|
||||
&self,
|
||||
limit: Option<u32>,
|
||||
) -> Result<Vec<McpAccessEntry>, StoreError> {
|
||||
let cap: i64 = limit.map(i64::from).unwrap_or(200).max(1);
|
||||
let rows = sqlx::query(
|
||||
"SELECT at, tool, meeting_id, client FROM mcp_access_log ORDER BY at DESC LIMIT ?",
|
||||
)
|
||||
.bind(cap)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.iter()
|
||||
.map(|r| McpAccessEntry {
|
||||
at: r.get("at"),
|
||||
tool: r.get("tool"),
|
||||
meeting_id: r.get("meeting_id"),
|
||||
client: r.get("client"),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a derived artifact, transparently decrypting it if the vault sealed it
|
||||
@@ -1559,6 +1792,60 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// T8.7/FR-TRX-4: the language requested at `create_meeting` is visible
|
||||
/// immediately (not just after `finalize_meeting`) — a crash-recovered
|
||||
/// `recovering` meeting still knows what was asked for.
|
||||
#[tokio::test]
|
||||
async fn create_meeting_persists_the_requested_language_immediately() {
|
||||
let store = SqliteStore::connect_in_memory().await.unwrap();
|
||||
let id = store
|
||||
.create_meeting(NewMeeting {
|
||||
title: "Reunión semanal".to_string(),
|
||||
calendar_event_id: None,
|
||||
template_id: None,
|
||||
language: Some("es".to_string()),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let meeting = store.get_meeting(&id).await.unwrap();
|
||||
assert_eq!(meeting.language.as_deref(), Some("es"));
|
||||
}
|
||||
|
||||
/// `finalize_meeting` overwrites whatever `create_meeting` stored with
|
||||
/// the language whisper.cpp actually resolved/detected (T8.7, FR-TRX-4)
|
||||
/// — e.g. "auto" mode's detected result, or an English-only model's
|
||||
/// forced "en".
|
||||
#[tokio::test]
|
||||
async fn finalize_meeting_overwrites_the_requested_language_with_the_resolved_one() {
|
||||
let store = SqliteStore::connect_in_memory().await.unwrap();
|
||||
let id = store
|
||||
.create_meeting(NewMeeting {
|
||||
title: "Auto-detect meeting".to_string(),
|
||||
calendar_event_id: None,
|
||||
template_id: None,
|
||||
language: None, // requested "auto"
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
store
|
||||
.finalize_meeting(
|
||||
&id,
|
||||
FinalizeMeeting {
|
||||
segments: Vec::new(),
|
||||
speakers: Vec::new(),
|
||||
duration_secs: 42,
|
||||
recorded: false,
|
||||
language: Some("fr".to_string()), // what auto-detect resolved to
|
||||
backend_used: Some("cpu".to_string()),
|
||||
model_used: Some("small-q5_1".to_string()),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let meeting = store.get_meeting(&id).await.unwrap();
|
||||
assert_eq!(meeting.language.as_deref(), Some("fr"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rename_meeting_updates_the_title() {
|
||||
let store = SqliteStore::connect_in_memory().await.unwrap();
|
||||
@@ -1567,6 +1854,7 @@ mod tests {
|
||||
title: "Untitled meeting".to_string(),
|
||||
calendar_event_id: None,
|
||||
template_id: None,
|
||||
language: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1592,6 +1880,7 @@ mod tests {
|
||||
title: "Untitled meeting".to_string(),
|
||||
calendar_event_id: None,
|
||||
template_id: None,
|
||||
language: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1636,6 +1925,7 @@ mod tests {
|
||||
title: "Untitled meeting".to_string(),
|
||||
calendar_event_id: None,
|
||||
template_id: None,
|
||||
language: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
+2065
-41
File diff suppressed because it is too large
Load Diff
@@ -46,6 +46,15 @@ pub fn provider_for(kind: &str) -> Option<OAuthProvider> {
|
||||
scopes: &["root_readwrite"],
|
||||
client_id_env: "WA_OAUTH_BOX_CLIENT_ID",
|
||||
}),
|
||||
// Same identity platform as "onedrive", read-only calendar scope only
|
||||
// (M4.4, T8.9, FR-CAL-6) — WA never requests file/mail access here.
|
||||
"graph-calendar" => Some(OAuthProvider {
|
||||
kind: "graph-calendar",
|
||||
auth_endpoint: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
|
||||
token_endpoint: "https://login.microsoftonline.com/common/oauth2/v2.0/token",
|
||||
scopes: &["offline_access", "Calendars.Read", "User.Read"],
|
||||
client_id_env: "WA_OAUTH_GRAPH_CALENDAR_CLIENT_ID",
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Selectable transcription languages (T8.7, FR-TRX-4, M4.2) — the Settings
|
||||
//! language dropdown shown when a multilingual model is active.
|
||||
//!
|
||||
//! ponytail: a fixed table, not a runtime query against whisper.cpp's
|
||||
//! `whisper_lang_str`/`whisper_lang_max_id` — the ~100-language set whisper.cpp
|
||||
//! ships is effectively static (OpenAI's Whisper `tokenizer.py` LANGUAGES
|
||||
//! table), and hardcoding it here means the list is available to the UI even
|
||||
//! before any model is loaded (no `cpu-transcription` feature dependency).
|
||||
|
||||
use crate::models::LanguageOption;
|
||||
|
||||
/// `(ISO-639-1 code, display label)`, exactly the codes whisper.cpp accepts
|
||||
/// via `whisper_full_params.language`.
|
||||
const LANGUAGES: &[(&str, &str)] = &[
|
||||
("en", "English"),
|
||||
("zh", "Chinese"),
|
||||
("de", "German"),
|
||||
("es", "Spanish"),
|
||||
("ru", "Russian"),
|
||||
("ko", "Korean"),
|
||||
("fr", "French"),
|
||||
("ja", "Japanese"),
|
||||
("pt", "Portuguese"),
|
||||
("tr", "Turkish"),
|
||||
("pl", "Polish"),
|
||||
("ca", "Catalan"),
|
||||
("nl", "Dutch"),
|
||||
("ar", "Arabic"),
|
||||
("sv", "Swedish"),
|
||||
("it", "Italian"),
|
||||
("id", "Indonesian"),
|
||||
("hi", "Hindi"),
|
||||
("fi", "Finnish"),
|
||||
("vi", "Vietnamese"),
|
||||
("he", "Hebrew"),
|
||||
("uk", "Ukrainian"),
|
||||
("el", "Greek"),
|
||||
("ms", "Malay"),
|
||||
("cs", "Czech"),
|
||||
("ro", "Romanian"),
|
||||
("da", "Danish"),
|
||||
("hu", "Hungarian"),
|
||||
("ta", "Tamil"),
|
||||
("no", "Norwegian"),
|
||||
("th", "Thai"),
|
||||
("ur", "Urdu"),
|
||||
("hr", "Croatian"),
|
||||
("bg", "Bulgarian"),
|
||||
("lt", "Lithuanian"),
|
||||
("la", "Latin"),
|
||||
("mi", "Maori"),
|
||||
("ml", "Malayalam"),
|
||||
("cy", "Welsh"),
|
||||
("sk", "Slovak"),
|
||||
("te", "Telugu"),
|
||||
("fa", "Persian"),
|
||||
("lv", "Latvian"),
|
||||
("bn", "Bengali"),
|
||||
("sr", "Serbian"),
|
||||
("az", "Azerbaijani"),
|
||||
("sl", "Slovenian"),
|
||||
("kn", "Kannada"),
|
||||
("et", "Estonian"),
|
||||
("mk", "Macedonian"),
|
||||
("br", "Breton"),
|
||||
("eu", "Basque"),
|
||||
("is", "Icelandic"),
|
||||
("hy", "Armenian"),
|
||||
("ne", "Nepali"),
|
||||
("mn", "Mongolian"),
|
||||
("bs", "Bosnian"),
|
||||
("kk", "Kazakh"),
|
||||
("sq", "Albanian"),
|
||||
("sw", "Swahili"),
|
||||
("gl", "Galician"),
|
||||
("mr", "Marathi"),
|
||||
("pa", "Punjabi"),
|
||||
("si", "Sinhala"),
|
||||
("km", "Khmer"),
|
||||
("sn", "Shona"),
|
||||
("yo", "Yoruba"),
|
||||
("so", "Somali"),
|
||||
("af", "Afrikaans"),
|
||||
("oc", "Occitan"),
|
||||
("ka", "Georgian"),
|
||||
("be", "Belarusian"),
|
||||
("tg", "Tajik"),
|
||||
("sd", "Sindhi"),
|
||||
("gu", "Gujarati"),
|
||||
("am", "Amharic"),
|
||||
("yi", "Yiddish"),
|
||||
("lo", "Lao"),
|
||||
("uz", "Uzbek"),
|
||||
("fo", "Faroese"),
|
||||
("ht", "Haitian Creole"),
|
||||
("ps", "Pashto"),
|
||||
("tk", "Turkmen"),
|
||||
("nn", "Nynorsk"),
|
||||
("mt", "Maltese"),
|
||||
("sa", "Sanskrit"),
|
||||
("lb", "Luxembourgish"),
|
||||
("my", "Myanmar"),
|
||||
("bo", "Tibetan"),
|
||||
("tl", "Tagalog"),
|
||||
("mg", "Malagasy"),
|
||||
("as", "Assamese"),
|
||||
("tt", "Tatar"),
|
||||
("haw", "Hawaiian"),
|
||||
("ln", "Lingala"),
|
||||
("ha", "Hausa"),
|
||||
("ba", "Bashkir"),
|
||||
("jw", "Javanese"),
|
||||
("su", "Sundanese"),
|
||||
("yue", "Cantonese"),
|
||||
];
|
||||
|
||||
/// The dropdown's contents (`list_whisper_languages` command) — "Auto-detect"
|
||||
/// itself is not in this list; the frontend prepends it (maps to `None`/no
|
||||
/// `language` argument).
|
||||
pub fn list() -> Vec<LanguageOption> {
|
||||
LANGUAGES
|
||||
.iter()
|
||||
.map(|(code, label)| LanguageOption {
|
||||
code: code.to_string(),
|
||||
label: label.to_string(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `code` is a known whisper.cpp language code (case-insensitive).
|
||||
/// Used to validate an explicit selection before it's forced into
|
||||
/// `FullParams::set_language` — an unrecognized code is still passed through
|
||||
/// to whisper.cpp (it may support codes we haven't listed), but callers use
|
||||
/// this to warn rather than silently accept a typo.
|
||||
pub fn is_known(code: &str) -> bool {
|
||||
LANGUAGES.iter().any(|(c, _)| c.eq_ignore_ascii_case(code))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn list_includes_english_and_common_languages() {
|
||||
let langs = list();
|
||||
assert!(langs.iter().any(|l| l.code == "en" && l.label == "English"));
|
||||
assert!(langs.iter().any(|l| l.code == "es"));
|
||||
assert!(langs.iter().any(|l| l.code == "fr"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codes_are_unique() {
|
||||
let mut codes: Vec<&str> = LANGUAGES.iter().map(|(c, _)| *c).collect();
|
||||
let before = codes.len();
|
||||
codes.sort_unstable();
|
||||
codes.dedup();
|
||||
assert_eq!(before, codes.len(), "duplicate language code in catalog");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_known_is_case_insensitive() {
|
||||
assert!(is_known("en"));
|
||||
assert!(is_known("ES"));
|
||||
assert!(!is_known("xx-not-a-real-code"));
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use crate::models::{BackendId, TranscriptSegment};
|
||||
use std::path::Path;
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
|
||||
pub mod languages;
|
||||
pub mod models;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -29,7 +30,13 @@ pub struct AudioWindow {
|
||||
pub type SegmentSink = Sender<TranscriptSegment>;
|
||||
|
||||
pub trait Transcriber: Send + Sync {
|
||||
fn load(model: &Path, backend: BackendId) -> Result<Self, TrxError>
|
||||
/// `language` (T8.7, FR-TRX-4): `None` or `Some("auto")` requests
|
||||
/// auto-detection; an explicit ISO-639-1 code (e.g. `"es"`) forces that
|
||||
/// language. Engines that can't honor a request (an English-only model,
|
||||
/// or an engine with no language selection at all, like the NPU/ONNX
|
||||
/// path) resolve it against their own capability at load time rather
|
||||
/// than erroring — see `resolve_language` and `effective_language`.
|
||||
fn load(model: &Path, backend: BackendId, language: Option<&str>) -> Result<Self, TrxError>
|
||||
where
|
||||
Self: Sized;
|
||||
/// Streaming: emit interim + final segments for a window (FR-TRX-2).
|
||||
@@ -37,6 +44,47 @@ pub trait Transcriber: Send + Sync {
|
||||
/// Batch: one-shot over a whole file, higher accuracy — also the crash-recovery
|
||||
/// path (FR-TRX-3, T2.8): re-run over the working `audio.wav` from scratch.
|
||||
fn transcribe_file(&self, wav: &Path) -> Result<Vec<TranscriptSegment>, TrxError>;
|
||||
|
||||
/// The language this engine is actually configured to decode, resolved
|
||||
/// against model capability at `load` time — `None` means auto-detect.
|
||||
/// Default: engines with no language selection of their own (the
|
||||
/// NPU/ONNX path, whose ONNX artifacts are exported English-only) always
|
||||
/// decode English.
|
||||
fn effective_language(&self) -> Option<String> {
|
||||
Some("en".to_string())
|
||||
}
|
||||
|
||||
/// The language actually used/detected on the most recent decode, if the
|
||||
/// engine surfaces one (whisper.cpp does, via `full_lang_id_from_state`).
|
||||
/// `None` until at least one decode has completed, or if the engine
|
||||
/// doesn't support detection reporting at all.
|
||||
fn detected_language(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a requested language against model capability: an English-only
|
||||
/// (`.en`) whisper.cpp model can only ever decode English, so an explicit
|
||||
/// non-English request is forced to `"en"` (with a warning) rather than
|
||||
/// being silently honored into a garbage transcript — the T8.7/FR-TRX-4
|
||||
/// "no silent footgun" requirement. `None`/`"auto"` always means
|
||||
/// auto-detect, regardless of model, since that's harmless either way
|
||||
/// (whisper.cpp itself forces English internally for a non-multilingual
|
||||
/// model even when `language` is unset).
|
||||
#[cfg(feature = "cpu-transcription")]
|
||||
fn resolve_language(requested: Option<&str>, multilingual: bool) -> Option<String> {
|
||||
match requested {
|
||||
None => None,
|
||||
Some(l) if l.eq_ignore_ascii_case("auto") => None,
|
||||
Some(l) if l.eq_ignore_ascii_case("en") => Some("en".to_string()),
|
||||
Some(l) if !multilingual => {
|
||||
tracing::warn!(
|
||||
"language '{l}' requested but the loaded model is English-only; forcing 'en'"
|
||||
);
|
||||
Some("en".to_string())
|
||||
}
|
||||
Some(l) => Some(l.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// whisper.cpp-backed transcriber (CPU baseline; GPU via Cargo features).
|
||||
@@ -44,6 +92,14 @@ pub trait Transcriber: Send + Sync {
|
||||
pub struct WhisperTranscriber {
|
||||
ctx: whisper_rs::WhisperContext,
|
||||
next_id: std::sync::atomic::AtomicU64,
|
||||
/// What gets passed to `FullParams::set_language` on every decode —
|
||||
/// resolved once at `load` (see `resolve_language`), not re-resolved per
|
||||
/// window/file, since a whole recording session uses one language.
|
||||
configured_language: Option<String>,
|
||||
/// The language whisper.cpp actually used on the most recent `full()`
|
||||
/// call (`whisper_full_lang_id_from_state`), updated after every decode
|
||||
/// so "auto" mode has something concrete to persist (T8.7, FR-TRX-4).
|
||||
last_detected_language: std::sync::Mutex<Option<String>>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "cpu-transcription")]
|
||||
@@ -85,6 +141,9 @@ impl WhisperTranscriber {
|
||||
params.set_print_timestamps(false);
|
||||
params.set_suppress_blank(true);
|
||||
params.set_single_segment(single_segment);
|
||||
// T8.7/FR-TRX-4: `None` here means auto-detect, matching
|
||||
// `configured_language`'s resolved meaning (see `resolve_language`).
|
||||
params.set_language(self.configured_language.as_deref());
|
||||
|
||||
if single_segment {
|
||||
// whisper.cpp's encoder always runs over a full, padded 30s mel
|
||||
@@ -100,6 +159,18 @@ impl WhisperTranscriber {
|
||||
.full(params, samples)
|
||||
.map_err(|e| TrxError::Inference(e.to_string()))?;
|
||||
|
||||
// T8.7/FR-TRX-4: record whatever language whisper.cpp actually used
|
||||
// for this decode (explicit request or auto-detected) so "auto" mode
|
||||
// has a concrete value to persist per meeting. Best-effort — an
|
||||
// unrecognized lang id (or a poisoned mutex) just leaves the last
|
||||
// known value in place rather than failing the transcription.
|
||||
let lang_id = state.full_lang_id_from_state();
|
||||
if let Some(code) = whisper_rs::get_lang_str(lang_id) {
|
||||
if let Ok(mut last) = self.last_detected_language.lock() {
|
||||
*last = Some(code.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// A forced single_segment's reported end_timestamp() reflects
|
||||
// whisper.cpp's internal 30s-padded mel frame, not the real window
|
||||
// length — confirmed even with `duration_ms` set, so don't trust it.
|
||||
@@ -145,16 +216,19 @@ impl Transcriber for WhisperTranscriber {
|
||||
/// so `use_gpu` on a CPU-only build is a harmless no-op — this stays a
|
||||
/// single code path either way rather than branching on which features
|
||||
/// were compiled in.
|
||||
fn load(model: &Path, backend: BackendId) -> Result<Self, TrxError> {
|
||||
fn load(model: &Path, backend: BackendId, language: Option<&str>) -> Result<Self, TrxError> {
|
||||
let params = whisper_rs::WhisperContextParameters {
|
||||
use_gpu: !matches!(backend, BackendId::Cpu),
|
||||
..Default::default()
|
||||
};
|
||||
let ctx = whisper_rs::WhisperContext::new_with_params(model, params)
|
||||
.map_err(|e| TrxError::Load(e.to_string()))?;
|
||||
let configured_language = resolve_language(language, ctx.is_multilingual());
|
||||
Ok(Self {
|
||||
ctx,
|
||||
next_id: std::sync::atomic::AtomicU64::new(0),
|
||||
configured_language,
|
||||
last_detected_language: std::sync::Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -178,6 +252,17 @@ impl Transcriber for WhisperTranscriber {
|
||||
crate::audio::read_wav_mono_16k(wav).map_err(|e| TrxError::Load(e.to_string()))?;
|
||||
self.run_full(&samples, 0, false)
|
||||
}
|
||||
|
||||
fn effective_language(&self) -> Option<String> {
|
||||
self.configured_language.clone()
|
||||
}
|
||||
|
||||
fn detected_language(&self) -> Option<String> {
|
||||
self.last_detected_language
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|g| g.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "cpu-transcription")]
|
||||
@@ -315,7 +400,7 @@ mod tests {
|
||||
_ => BackendId::Intel, // use_gpu = true for any non-CPU backend
|
||||
};
|
||||
let t0 = std::time::Instant::now();
|
||||
let transcriber = WhisperTranscriber::load(Path::new(&model), backend).expect("load");
|
||||
let transcriber = WhisperTranscriber::load(Path::new(&model), backend, None).expect("load");
|
||||
let load_ms = t0.elapsed().as_millis();
|
||||
let t1 = std::time::Instant::now();
|
||||
let segments = transcriber
|
||||
@@ -330,4 +415,95 @@ mod tests {
|
||||
eprintln!("[spike] backend={backend:?} load={load_ms}ms infer={infer_ms}ms text={text:?}");
|
||||
assert!(!text.trim().is_empty(), "transcript was empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_language_auto_and_none_both_mean_auto_detect() {
|
||||
assert_eq!(resolve_language(None, true), None);
|
||||
assert_eq!(resolve_language(Some("auto"), true), None);
|
||||
assert_eq!(resolve_language(Some("AUTO"), true), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_language_explicit_on_multilingual_model_passes_through() {
|
||||
assert_eq!(resolve_language(Some("es"), true), Some("es".to_string()));
|
||||
assert_eq!(resolve_language(Some("fr"), true), Some("fr".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_language_forces_english_on_english_only_model() {
|
||||
// The footgun guard (T8.7/FR-TRX-4): an English-only model can't
|
||||
// honor a non-English request, so it's forced to "en" rather than
|
||||
// silently producing garbage.
|
||||
assert_eq!(resolve_language(Some("es"), false), Some("en".to_string()));
|
||||
assert_eq!(resolve_language(Some("EN"), false), Some("en".to_string()));
|
||||
// Auto is still allowed on an English-only model — harmless, since
|
||||
// whisper.cpp forces English internally for it either way.
|
||||
assert_eq!(resolve_language(None, false), None);
|
||||
assert_eq!(resolve_language(Some("auto"), false), None);
|
||||
}
|
||||
|
||||
/// Multilingual decode acceptance spike (opt-in, mirrors
|
||||
/// `gpu_transcribes_and_times`): loads a *multilingual* model with an
|
||||
/// explicit non-English `language` and confirms it decodes non-empty
|
||||
/// text without being forced to English. Needs a real multilingual ggml
|
||||
/// model + a non-English wav, neither of which are fetched by CI/this
|
||||
/// sandbox — run manually:
|
||||
/// WA_WHISPER_MODEL=…ggml-small-q5_1.bin WA_TEST_WAV=…spanish.wav \
|
||||
/// WA_TEST_LANGUAGE=es cargo test multilingual_model_decodes_requested_language \
|
||||
/// -- --ignored --nocapture
|
||||
#[test]
|
||||
#[ignore = "requires a multilingual whisper model + non-English wav; run manually"]
|
||||
fn multilingual_model_decodes_requested_language() {
|
||||
let model = std::env::var("WA_WHISPER_MODEL").expect("set WA_WHISPER_MODEL");
|
||||
let wav = std::env::var("WA_TEST_WAV").expect("set WA_TEST_WAV");
|
||||
let language = std::env::var("WA_TEST_LANGUAGE").unwrap_or_else(|_| "es".to_string());
|
||||
|
||||
let transcriber =
|
||||
WhisperTranscriber::load(Path::new(&model), BackendId::Cpu, Some(&language))
|
||||
.expect("load multilingual model");
|
||||
assert_eq!(transcriber.effective_language(), Some(language.clone()));
|
||||
|
||||
let segments = transcriber
|
||||
.transcribe_file(Path::new(&wav))
|
||||
.expect("transcribe");
|
||||
let text = segments
|
||||
.iter()
|
||||
.map(|s| s.text.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
eprintln!("[spike] language={language} text={text:?}");
|
||||
assert!(!text.trim().is_empty(), "transcript was empty");
|
||||
// whisper.cpp reports back whichever language it actually decoded in.
|
||||
assert_eq!(
|
||||
transcriber.detected_language().as_deref(),
|
||||
Some(language.as_str())
|
||||
);
|
||||
}
|
||||
|
||||
/// "Auto" acceptance spike (opt-in): confirms auto-detection actually
|
||||
/// runs (no `language` forced) and surfaces a detected language after
|
||||
/// decode. Same manual-only posture as the spike above.
|
||||
#[test]
|
||||
#[ignore = "requires a multilingual whisper model + wav; run manually"]
|
||||
fn auto_mode_detects_a_language() {
|
||||
let model = std::env::var("WA_WHISPER_MODEL").expect("set WA_WHISPER_MODEL");
|
||||
let wav = std::env::var("WA_TEST_WAV").expect("set WA_TEST_WAV");
|
||||
|
||||
let transcriber = WhisperTranscriber::load(Path::new(&model), BackendId::Cpu, None)
|
||||
.expect("load multilingual model");
|
||||
assert_eq!(
|
||||
transcriber.effective_language(),
|
||||
None,
|
||||
"auto should stay unset"
|
||||
);
|
||||
assert_eq!(transcriber.detected_language(), None, "nothing decoded yet");
|
||||
|
||||
transcriber
|
||||
.transcribe_file(Path::new(&wav))
|
||||
.expect("transcribe");
|
||||
assert!(
|
||||
transcriber.detected_language().is_some(),
|
||||
"auto mode should report a detected language after a decode"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,12 @@ struct Catalog {
|
||||
id: &'static str,
|
||||
label: &'static str,
|
||||
size_mb: u32,
|
||||
/// `false` for the `.en` (English-only) ggml variants; `true` for the
|
||||
/// multilingual variants, which whisper.cpp ships as the same filename
|
||||
/// minus the `.en` infix (e.g. `ggml-base.bin` vs `ggml-base.en.bin`) —
|
||||
/// same download/install machinery, just a different id/URL (T8.7,
|
||||
/// FR-TRX-4, M4.2).
|
||||
multilingual: bool,
|
||||
}
|
||||
|
||||
const CATALOG: &[Catalog] = &[
|
||||
@@ -19,21 +25,49 @@ const CATALOG: &[Catalog] = &[
|
||||
id: "tiny.en-q5_1",
|
||||
label: "Tiny (English, quantized) — fastest, least accurate",
|
||||
size_mb: 32,
|
||||
multilingual: false,
|
||||
},
|
||||
Catalog {
|
||||
id: "base.en-q5_1",
|
||||
label: "Base (English, quantized) — balanced default",
|
||||
size_mb: 60,
|
||||
multilingual: false,
|
||||
},
|
||||
Catalog {
|
||||
id: "small.en-q5_1",
|
||||
label: "Small (English, quantized) — more accurate, slower",
|
||||
size_mb: 190,
|
||||
multilingual: false,
|
||||
},
|
||||
Catalog {
|
||||
id: "medium.en-q5_1",
|
||||
label: "Medium (English, quantized) — best accuracy, slowest",
|
||||
size_mb: 540,
|
||||
multilingual: false,
|
||||
},
|
||||
Catalog {
|
||||
id: "tiny-q5_1",
|
||||
label: "Tiny (multilingual, quantized) — fastest, least accurate",
|
||||
size_mb: 32,
|
||||
multilingual: true,
|
||||
},
|
||||
Catalog {
|
||||
id: "base-q5_1",
|
||||
label: "Base (multilingual, quantized) — balanced default",
|
||||
size_mb: 60,
|
||||
multilingual: true,
|
||||
},
|
||||
Catalog {
|
||||
id: "small-q5_1",
|
||||
label: "Small (multilingual, quantized) — more accurate, slower",
|
||||
size_mb: 190,
|
||||
multilingual: true,
|
||||
},
|
||||
Catalog {
|
||||
id: "medium-q5_1",
|
||||
label: "Medium (multilingual, quantized) — best accuracy, slowest",
|
||||
size_mb: 540,
|
||||
multilingual: true,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -50,10 +84,19 @@ pub fn list(active_id: &str) -> Vec<ModelInfo> {
|
||||
size_mb: m.size_mb,
|
||||
installed: whisper_model_file(m.id).exists(),
|
||||
active: m.id == active_id,
|
||||
multilingual: m.multilingual,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `id` names a multilingual (non-`.en`) catalog model — an unknown
|
||||
/// id (shouldn't happen; callers validate against the catalog first) is
|
||||
/// conservatively treated as English-only rather than granting language
|
||||
/// selection it can't honor.
|
||||
pub fn is_multilingual(id: &str) -> bool {
|
||||
CATALOG.iter().any(|m| m.id == id && m.multilingual)
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ModelError {
|
||||
#[error("unknown model id: {0}")]
|
||||
@@ -147,4 +190,38 @@ mod tests {
|
||||
let err = remove(active, active).unwrap_err();
|
||||
assert!(matches!(err, ModelError::Invalid(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_has_a_multilingual_counterpart_for_every_english_only_size() {
|
||||
// T8.7/M4.2: every `.en` model must have a same-size multilingual
|
||||
// sibling so the Settings picker always has a language-capable
|
||||
// option at whatever accuracy/speed tier the user already chose.
|
||||
let en_only: Vec<_> = CATALOG.iter().filter(|m| !m.multilingual).collect();
|
||||
let multilingual: Vec<_> = CATALOG.iter().filter(|m| m.multilingual).collect();
|
||||
assert_eq!(en_only.len(), multilingual.len());
|
||||
for en in &en_only {
|
||||
assert!(
|
||||
multilingual.iter().any(|m| m.size_mb == en.size_mb),
|
||||
"no multilingual sibling for {}",
|
||||
en.id
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_multilingual_matches_the_catalog_flag() {
|
||||
assert!(!is_multilingual("base.en-q5_1"));
|
||||
assert!(is_multilingual("base-q5_1"));
|
||||
// Unknown ids are conservatively English-only (no model to check).
|
||||
assert!(!is_multilingual("nonexistent-id"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_reports_multilingual_flag_per_model() {
|
||||
let models = list("base.en-q5_1");
|
||||
let base_en = models.iter().find(|m| m.id == "base.en-q5_1").unwrap();
|
||||
let base_multi = models.iter().find(|m| m.id == "base-q5_1").unwrap();
|
||||
assert!(!base_en.multilingual);
|
||||
assert!(base_multi.multilingual);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,7 +202,24 @@ impl Transcriber for OnnxTranscriber {
|
||||
/// `Npu` → OpenVINO EP; `Amd`/`Intel` → DirectML EP (the non-Vulkan GPU
|
||||
/// path). Any other value is rejected so the dispatcher can fall back to
|
||||
/// whisper.cpp rather than us guessing.
|
||||
fn load(model: &Path, backend: BackendId) -> Result<Self, TrxError> {
|
||||
///
|
||||
/// `language` (T8.7, FR-TRX-4): the exported ONNX model's
|
||||
/// `forced_decoder_ids` bakes its language in at export time — this
|
||||
/// engine has no per-inference language selection to apply, unlike
|
||||
/// whisper.cpp's `FullParams::set_language`. A non-English, non-auto
|
||||
/// request is logged (not silently dropped) so a user picking a language
|
||||
/// on the NPU/DirectML path finds out it didn't take, rather than
|
||||
/// getting a quietly-wrong transcript; `effective_language`/
|
||||
/// `detected_language` fall back to the trait's English-only defaults.
|
||||
fn load(model: &Path, backend: BackendId, language: Option<&str>) -> Result<Self, TrxError> {
|
||||
if let Some(lang) = language {
|
||||
if !lang.eq_ignore_ascii_case("auto") && !lang.eq_ignore_ascii_case("en") {
|
||||
tracing::warn!(
|
||||
"language '{lang}' requested but the NPU/DirectML engine's ONNX model is \
|
||||
English-only (language is fixed at export time); ignoring the request"
|
||||
);
|
||||
}
|
||||
}
|
||||
// Pick the runtime bundle + encoder EP for the requested accelerator.
|
||||
// error_on_failure makes a failed accelerator registration LOUD (Err)
|
||||
// instead of a silent CPU fallback, so the dispatcher can cleanly drop
|
||||
@@ -465,7 +482,7 @@ mod tests {
|
||||
};
|
||||
let wav = std::env::var("WA_NPU_TEST_WAV").expect("set WA_NPU_TEST_WAV");
|
||||
let t0 = std::time::Instant::now();
|
||||
let t = OnnxTranscriber::load(Path::new(&model_dir), BackendId::Npu)
|
||||
let t = OnnxTranscriber::load(Path::new(&model_dir), BackendId::Npu, None)
|
||||
.expect("load NPU transcriber");
|
||||
let load_ms = t0.elapsed().as_millis();
|
||||
let t1 = std::time::Instant::now();
|
||||
@@ -507,7 +524,7 @@ mod tests {
|
||||
_ => BackendId::Intel,
|
||||
};
|
||||
let t0 = std::time::Instant::now();
|
||||
let t = OnnxTranscriber::load(Path::new(&model_dir), backend).expect("load DirectML");
|
||||
let t = OnnxTranscriber::load(Path::new(&model_dir), backend, None).expect("load DirectML");
|
||||
let load_ms = t0.elapsed().as_millis();
|
||||
let t1 = std::time::Instant::now();
|
||||
let segs = t.transcribe_file(Path::new(&wav)).expect("transcribe");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "WhispAssist",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.0",
|
||||
"identifier": "bet.dou.whispassist",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
|
||||
@@ -54,6 +54,7 @@ async fn attach_meeting_to_event_and_map_speaker_to_participant_round_trip() {
|
||||
title: "Test meeting".to_string(),
|
||||
calendar_event_id: None,
|
||||
template_id: None,
|
||||
language: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
+52
-7
@@ -57,7 +57,7 @@ export interface AudioDeviceInfo {
|
||||
}
|
||||
|
||||
export interface LlmStatus {
|
||||
provider: string; // ollama|custom|off (Phase 10a adds anthropic|openai)
|
||||
provider: string; // ollama|custom|anthropic|off (ADR-0011; "openai" not yet wired)
|
||||
reachable: boolean;
|
||||
isLocal: boolean;
|
||||
models: string[];
|
||||
@@ -69,6 +69,16 @@ export interface ModelInfo {
|
||||
size_mb: number;
|
||||
installed: boolean;
|
||||
active: boolean;
|
||||
/** `false` for `.en` (English-only) ggml variants; `true` for multilingual
|
||||
* ones — gates the Settings language picker (T8.7, FR-TRX-4, M4.2). */
|
||||
multilingual: boolean;
|
||||
}
|
||||
|
||||
// One selectable transcription language (T8.7, FR-TRX-4) — ISO-639-1 code
|
||||
// as accepted by whisper.cpp, plus a display label.
|
||||
export interface LanguageOption {
|
||||
code: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export type MeetingStatus = "recording" | "transcribing" | "ready" | "recovering" | "error";
|
||||
@@ -152,6 +162,9 @@ export interface Meeting {
|
||||
duration_secs: number | null;
|
||||
status: MeetingStatus;
|
||||
recorded: boolean;
|
||||
// Transcription language actually used/selected for this meeting (T8.7,
|
||||
// FR-TRX-4) — an ISO-639-1 code, or null if never resolved (e.g. no audio
|
||||
// was ever decoded).
|
||||
language: string | null;
|
||||
backend_used: string | null;
|
||||
model_used: string | null;
|
||||
@@ -284,11 +297,23 @@ export interface AppSettings {
|
||||
} | null;
|
||||
preferred_backend: string;
|
||||
whisper_model: string;
|
||||
/** Default transcription language (T8.7, FR-TRX-4): `null` = auto-detect,
|
||||
* an ISO-639-1 code forces that language. Only takes effect with a
|
||||
* multilingual model — see `ModelInfo.multilingual`. */
|
||||
whisper_language: string | null;
|
||||
low_overhead: boolean;
|
||||
default_record: boolean;
|
||||
consent_acknowledged: boolean;
|
||||
/** One-time "data leaves your device" ack for hosted (non-local) AI
|
||||
* providers — Anthropic today (ADR-0011, T10.3). Independent of
|
||||
* consent_acknowledged (that one's about recording law). */
|
||||
hosted_ai_acknowledged: boolean;
|
||||
sync_enabled: boolean;
|
||||
mcp_enabled: boolean;
|
||||
mcp_transport: string; // http|stdio
|
||||
mcp_port: number;
|
||||
mcp_expose: string; // none|selected|all
|
||||
mcp_expose_recordings: boolean;
|
||||
retention_max_age_days: number | null;
|
||||
retention_max_size_gb: number | null;
|
||||
pst_last_path: string | null;
|
||||
@@ -325,17 +350,29 @@ export interface McpAccessEntry {
|
||||
client: string | null;
|
||||
}
|
||||
|
||||
// mcp_status() response (FR-MCP-1/6). `endpoint` is empty while disabled.
|
||||
export interface McpStatus {
|
||||
enabled: boolean;
|
||||
transport: "http" | "stdio";
|
||||
endpoint: string;
|
||||
tokenSet: boolean;
|
||||
exposeScope: "none" | "selected" | "all";
|
||||
}
|
||||
|
||||
// ---- Commands ----
|
||||
export const api = {
|
||||
// `record` controls audio RETENTION (default false / off — ADR-0009).
|
||||
// `language` (T8.7, FR-TRX-4): omit/undefined falls back to
|
||||
// Settings.whisper_language; "auto" or omitted both mean auto-detect.
|
||||
startRecording: (
|
||||
meetingTitle?: string,
|
||||
calendarEventId?: string,
|
||||
record = false,
|
||||
templateId?: string,
|
||||
language?: string,
|
||||
) =>
|
||||
invoke<MeetingId>("start_recording", {
|
||||
args: { meetingTitle, calendarEventId, record, templateId },
|
||||
args: { meetingTitle, calendarEventId, record, templateId, language },
|
||||
}),
|
||||
listNoteTemplates: () => invoke<NoteTemplate[]>("list_note_templates"),
|
||||
stopRecording: (meetingId: MeetingId) => invoke<void>("stop_recording", { meetingId }),
|
||||
@@ -360,11 +397,16 @@ export const api = {
|
||||
downloadNpuPackage: () => invoke<void>("download_npu_package"),
|
||||
downloadDirectmlPackage: () => invoke<void>("download_directml_package"),
|
||||
listModels: () => invoke<ModelInfo[]>("list_models"),
|
||||
// T8.7/FR-TRX-4: static catalog of whisper.cpp-recognized language codes
|
||||
// for the Settings dropdown; "Auto-detect" is a frontend-only addition.
|
||||
listWhisperLanguages: () => invoke<LanguageOption[]>("list_whisper_languages"),
|
||||
downloadModel: (id: string, kind: "whisper" = "whisper") =>
|
||||
invoke<void>("download_model", { args: { kind, id } }),
|
||||
removeModel: (id: string) => invoke<void>("remove_model", { id }),
|
||||
reprocessTranscript: (meetingId: MeetingId, model: string) =>
|
||||
invoke<void>("reprocess_transcript", { meetingId, model }),
|
||||
// `language` (T8.7): omit/undefined reuses whatever language the meeting
|
||||
// already had rather than resetting it to auto.
|
||||
reprocessTranscript: (meetingId: MeetingId, model: string, language?: string) =>
|
||||
invoke<void>("reprocess_transcript", { meetingId, model, language }),
|
||||
resumeTranscription: (meetingId: MeetingId) =>
|
||||
invoke<void>("resume_transcription", { meetingId }),
|
||||
listMeetings: (filter?: MeetingFilter) =>
|
||||
@@ -455,7 +497,7 @@ export const api = {
|
||||
getFeatureBrief: (id: string) => invoke<FeatureBrief>("get_feature_brief", { id }),
|
||||
setBriefExposed: (id: string, exposed: boolean) =>
|
||||
invoke<void>("set_brief_exposed", { id, exposed }),
|
||||
mcpStatus: () => invoke("mcp_status"),
|
||||
mcpStatus: () => invoke<McpStatus>("mcp_status"),
|
||||
setMcpEnabled: (enabled: boolean, transport?: "http" | "stdio", port?: number) =>
|
||||
invoke<{ endpoint: string; token: string }>("set_mcp_enabled", { enabled, transport, port }),
|
||||
setMcpScope: (expose: "none" | "selected" | "all", exposeRecordings?: boolean) =>
|
||||
@@ -538,8 +580,11 @@ export const events = {
|
||||
onSyncLinked: (
|
||||
cb: (p: { ok: boolean; kind: string; error?: string }) => void,
|
||||
): Promise<UnlistenFn> => listen("sync://linked", (e) => cb(e.payload as never)),
|
||||
onMcpAccess: (cb: (p: McpAccessEntry & { client?: string }) => void): Promise<UnlistenFn> =>
|
||||
listen("mcp://access", (e) => cb(e.payload as never)),
|
||||
// Live tail of the FR-MCP-5 audit log (camelCase on the wire, unlike the
|
||||
// snake_case McpAccessEntry rows `mcpAccessLog()` returns).
|
||||
onMcpAccess: (
|
||||
cb: (p: { at: number; tool: string; meetingId?: MeetingId; client?: string }) => void,
|
||||
): Promise<UnlistenFn> => listen("mcp://access", (e) => cb(e.payload as never)),
|
||||
onAgentProgress: (
|
||||
cb: (p: { briefId: string; tool: string; line: string }) => void,
|
||||
): Promise<UnlistenFn> => listen("agent://progress", (e) => cb(e.payload as never)),
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
<script lang="ts">
|
||||
// One-time third-party "data leaves your device" notice (ADR-0011, T10.3/
|
||||
// M3.3), shown before the first use of any hosted (non-local) AI provider —
|
||||
// Anthropic today, a hosted OpenAI-compatible gateway once wired the same
|
||||
// way. Same shared-copy/shared-acknowledgment pattern as ConsentNotice.svelte
|
||||
// (recording consent, ADR-0009): both gate a single Settings toggle AND a
|
||||
// second use-time trigger point on the same one-time flag.
|
||||
import { Globe } from "@lucide/svelte";
|
||||
let {
|
||||
providerLabel,
|
||||
onAccept,
|
||||
onCancel,
|
||||
}: { providerLabel: string; onAccept: () => void; onCancel: () => void } = $props();
|
||||
</script>
|
||||
|
||||
<div class="banner" role="alertdialog" aria-labelledby="hosted-ai-heading">
|
||||
<div class="heading">
|
||||
<Globe size={18} aria-hidden="true" />
|
||||
<strong id="hosted-ai-heading">Before using {providerLabel}</strong>
|
||||
</div>
|
||||
<p>
|
||||
Generating with <strong>{providerLabel}</strong> sends this meeting's transcript to their servers
|
||||
— it leaves this device and is subject to their privacy policy. WhispAssist has no control over data
|
||||
handling once it leaves your device. This is off by default; you're choosing it now.
|
||||
</p>
|
||||
<div class="actions">
|
||||
<button class="primary" onclick={onAccept}>I understand — continue</button>
|
||||
<button class="ghost" onclick={onCancel}>Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.banner {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: var(--shadow-lg);
|
||||
padding: 1rem 1.1rem;
|
||||
background: var(--bg-elevated);
|
||||
color: var(--fg);
|
||||
max-width: 420px;
|
||||
}
|
||||
.heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
color: var(--warning);
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
.heading strong {
|
||||
color: var(--fg);
|
||||
}
|
||||
p {
|
||||
margin: 0;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.5;
|
||||
color: var(--muted);
|
||||
}
|
||||
p strong {
|
||||
color: var(--fg);
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 0.8rem;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
button.primary {
|
||||
background: var(--accent);
|
||||
color: var(--accent-fg);
|
||||
border: 1px solid transparent;
|
||||
padding: 0.4rem 0.8rem;
|
||||
border-radius: var(--radius-sm);
|
||||
font-weight: 600;
|
||||
}
|
||||
button.primary:hover {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
button.ghost {
|
||||
background: none;
|
||||
border: 1px solid var(--border);
|
||||
padding: 0.4rem 0.8rem;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--fg);
|
||||
}
|
||||
button.ghost:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
</style>
|
||||
@@ -218,9 +218,11 @@ class MeetingsStore {
|
||||
if (this.selectedId === id) await this.select(id);
|
||||
}
|
||||
|
||||
/** Batch re-transcribe with a different (typically larger) model (T3.8). */
|
||||
async reprocess(id: MeetingId, model: string) {
|
||||
await api.reprocessTranscript(id, model);
|
||||
/** Batch re-transcribe with a different (typically larger) model (T3.8).
|
||||
* `language` (T8.7, FR-TRX-4): omitted reuses the meeting's current
|
||||
* language rather than resetting it to auto. */
|
||||
async reprocess(id: MeetingId, model: string, language?: string) {
|
||||
await api.reprocessTranscript(id, model, language);
|
||||
await this.load();
|
||||
if (this.selectedId === id) await this.select(id);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Subscribes to recording/transcript events and exposes reactive state.
|
||||
|
||||
import { api, events, type TranscriptSegment, type MeetingId } from "../api";
|
||||
import { settings } from "./settings.svelte";
|
||||
|
||||
class RecordingStore {
|
||||
meetingId = $state<MeetingId | null>(null);
|
||||
@@ -52,7 +53,10 @@ class RecordingStore {
|
||||
this.segments = [];
|
||||
this.retention = record;
|
||||
this.deviceNotice = null;
|
||||
this.meetingId = await api.startRecording(title, undefined, record, templateId);
|
||||
// T8.7/FR-TRX-4: whatever language is currently configured in Settings
|
||||
// becomes this meeting's requested language, persisted on its record.
|
||||
const language = settings.settings.whisper_language ?? undefined;
|
||||
this.meetingId = await api.startRecording(title, undefined, record, templateId, language);
|
||||
this.state = "recording";
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,10 @@ import {
|
||||
type HardwareStatus,
|
||||
type LlmStatus,
|
||||
type ModelInfo,
|
||||
type LanguageOption,
|
||||
type PrivacySelfCheck,
|
||||
type McpStatus,
|
||||
type McpAccessEntry,
|
||||
} from "../api";
|
||||
|
||||
const DEFAULT_SETTINGS: AppSettings = {
|
||||
@@ -25,11 +28,17 @@ const DEFAULT_SETTINGS: AppSettings = {
|
||||
llm_model: "llama3",
|
||||
preferred_backend: "auto",
|
||||
whisper_model: "base.en-q5_1",
|
||||
whisper_language: null, // auto-detect by default (T8.7, FR-TRX-4)
|
||||
low_overhead: false,
|
||||
default_record: false, // recording OFF by default (ADR-0009)
|
||||
consent_acknowledged: false,
|
||||
hosted_ai_acknowledged: false, // hosted-AI "leaves your device" notice (ADR-0011)
|
||||
sync_enabled: false, // sync OFF by default (ADR-0010)
|
||||
mcp_enabled: false, // MCP server OFF by default (ADR-0011)
|
||||
mcp_transport: "http",
|
||||
mcp_port: 4849,
|
||||
mcp_expose: "none", // scope OFF by default (FR-MCP-3)
|
||||
mcp_expose_recordings: false,
|
||||
retention_max_age_days: null, // no cap by default (FR-STORE-2)
|
||||
retention_max_size_gb: null,
|
||||
pst_last_path: null,
|
||||
@@ -51,6 +60,8 @@ class SettingsStore {
|
||||
// Hardware + model management (Phase 3, T3.6/T3.7).
|
||||
hardware = $state<HardwareStatus | null>(null);
|
||||
models = $state<ModelInfo[]>([]);
|
||||
// Transcription language catalog for the Settings dropdown (T8.7, FR-TRX-4).
|
||||
languages = $state<LanguageOption[]>([]);
|
||||
audioDevices = $state<AudioDeviceInfo[]>([]);
|
||||
inputDevices = $state<AudioDeviceInfo[]>([]);
|
||||
downloadProgress = $state<Record<string, { received: number; total: number | null }>>({});
|
||||
@@ -58,6 +69,15 @@ class SettingsStore {
|
||||
// Privacy self-check (T7.6, FR-SEC-2).
|
||||
privacy = $state<PrivacySelfCheck | null>(null);
|
||||
|
||||
// MCP server (Phase 10b, ADR-0011).
|
||||
mcpStatus = $state<McpStatus | null>(null);
|
||||
mcpAccessLog = $state<McpAccessEntry[]>([]);
|
||||
mcpSaving = $state(false);
|
||||
/** The freshly-minted token from the last `setMcpEnabled(true)` call —
|
||||
* shown exactly once (it is never re-readable afterwards, same as any
|
||||
* other newly-issued secret). Cleared on disable or when the panel closes. */
|
||||
mcpLastToken = $state<string | null>(null);
|
||||
|
||||
// LLM provider status (T5.2, FR-LLM-1).
|
||||
llmStatus = $state<LlmStatus | null>(null);
|
||||
llmSaving = $state(false);
|
||||
@@ -80,8 +100,19 @@ class SettingsStore {
|
||||
await this.loadAudioDevices();
|
||||
await this.loadInputDevices();
|
||||
await this.loadModels();
|
||||
await this.loadLanguages();
|
||||
await this.loadPrivacy();
|
||||
await this.loadLlmStatus();
|
||||
await this.loadMcpStatus();
|
||||
await this.loadMcpAccessLog();
|
||||
// Live tail of the FR-MCP-5 audit log — every tool read an agent makes
|
||||
// while the panel is open shows up immediately, not just on refresh.
|
||||
await events.onMcpAccess(({ at, tool, meetingId, client }) => {
|
||||
this.mcpAccessLog = [
|
||||
{ at, tool, meeting_id: meetingId ?? null, client: client ?? null },
|
||||
...this.mcpAccessLog,
|
||||
].slice(0, 50);
|
||||
});
|
||||
await events.onHardwareChanged(({ active }) => {
|
||||
if (this.hardware) this.hardware.active = active;
|
||||
});
|
||||
@@ -167,6 +198,21 @@ class SettingsStore {
|
||||
}
|
||||
}
|
||||
|
||||
async loadLanguages() {
|
||||
try {
|
||||
this.languages = await api.listWhisperLanguages();
|
||||
} catch {
|
||||
this.languages = [];
|
||||
}
|
||||
}
|
||||
|
||||
/** `null` = auto-detect (T8.7, FR-TRX-4). Only meaningful when the active
|
||||
* model is multilingual — the Settings UI disables/hides this control
|
||||
* otherwise, and the backend forces "en" regardless if it's set anyway. */
|
||||
async setWhisperLanguage(code: string | null) {
|
||||
await this.patch({ whisper_language: code });
|
||||
}
|
||||
|
||||
async loadPrivacy() {
|
||||
try {
|
||||
this.privacy = await api.privacySelfCheck();
|
||||
@@ -175,6 +221,49 @@ class SettingsStore {
|
||||
}
|
||||
}
|
||||
|
||||
async loadMcpStatus() {
|
||||
try {
|
||||
this.mcpStatus = await api.mcpStatus();
|
||||
} catch {
|
||||
this.mcpStatus = null;
|
||||
}
|
||||
}
|
||||
|
||||
async loadMcpAccessLog(limit = 50) {
|
||||
try {
|
||||
this.mcpAccessLog = await api.mcpAccessLog(limit);
|
||||
} catch {
|
||||
this.mcpAccessLog = [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Enable/disable the loopback MCP server (FR-MCP-1/6). On enable, the
|
||||
* returned token is stashed in `mcpLastToken` for the one-time reveal. */
|
||||
async setMcpEnabled(enabled: boolean, transport?: "http" | "stdio", port?: number) {
|
||||
this.mcpSaving = true;
|
||||
try {
|
||||
const res = await api.setMcpEnabled(enabled, transport, port);
|
||||
this.mcpLastToken = enabled ? res.token : null;
|
||||
} catch {
|
||||
this.backendStub = true;
|
||||
} finally {
|
||||
this.mcpSaving = false;
|
||||
}
|
||||
await this.loadMcpStatus();
|
||||
await this.loadPrivacy();
|
||||
}
|
||||
|
||||
/** Scope control (FR-MCP-3) — takes effect immediately, no restart needed. */
|
||||
async setMcpScope(expose: "none" | "selected" | "all", exposeRecordings?: boolean) {
|
||||
try {
|
||||
await api.setMcpScope(expose, exposeRecordings);
|
||||
} catch {
|
||||
this.backendStub = true;
|
||||
}
|
||||
await this.loadMcpStatus();
|
||||
await this.loadPrivacy();
|
||||
}
|
||||
|
||||
async loadLlmStatus() {
|
||||
try {
|
||||
this.llmStatus = await api.llmStatus();
|
||||
@@ -183,8 +272,16 @@ class SettingsStore {
|
||||
}
|
||||
}
|
||||
|
||||
/** Persist the LLM provider/endpoint/model and refresh status (T5.2). */
|
||||
async setLlmProvider(config: { provider: string; endpoint?: string; model?: string }) {
|
||||
/** Persist the LLM provider/endpoint/model (+ hosted apiKey, ADR-0011) and
|
||||
* refresh status (T5.2/T10.2). The key is only ever sent to the backend
|
||||
* command (which stores it in the OS credential store) — never held here
|
||||
* beyond this call, and never merged into `this.settings`. */
|
||||
async setLlmProvider(config: {
|
||||
provider: string;
|
||||
endpoint?: string;
|
||||
model?: string;
|
||||
apiKey?: string;
|
||||
}) {
|
||||
this.llmSaving = true;
|
||||
// Optimistic local update so the form reflects the change immediately.
|
||||
this.settings = {
|
||||
@@ -202,6 +299,13 @@ class SettingsStore {
|
||||
}
|
||||
}
|
||||
|
||||
/** Persist the one-time hosted-AI "leaves your device" acknowledgment
|
||||
* (ADR-0011, T10.3) — same generic patch() every other boolean setting
|
||||
* here uses (see setDefaultRecord below). */
|
||||
acknowledgeHostedAi() {
|
||||
return this.patch({ hosted_ai_acknowledged: true });
|
||||
}
|
||||
|
||||
async setPreferredBackend(backend: AppSettings["preferred_backend"]) {
|
||||
await this.patch({ preferred_backend: backend });
|
||||
await this.loadHardware();
|
||||
|
||||
+389
-14
@@ -6,6 +6,7 @@
|
||||
import { settings } from "../stores/settings.svelte";
|
||||
import { calendar } from "../stores/calendar.svelte";
|
||||
import ConsentNotice from "../components/ConsentNotice.svelte";
|
||||
import HostedAiBanner from "../components/HostedAiBanner.svelte";
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { api, errorMessage, events } from "../api";
|
||||
import type { BackendId, SyncKind, SyncTargetConfig, SyncTargetInfo } from "../api";
|
||||
@@ -25,6 +26,12 @@
|
||||
ChevronRight,
|
||||
RotateCcw,
|
||||
Info,
|
||||
Bot,
|
||||
Copy,
|
||||
KeyRound,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Globe,
|
||||
} from "@lucide/svelte";
|
||||
import {
|
||||
OLLAMA_OPTIONS,
|
||||
@@ -37,29 +44,68 @@
|
||||
let { onClose }: { onClose: () => void } = $props();
|
||||
|
||||
let section = $state<
|
||||
"recording" | "hardware" | "storage" | "calendar" | "sync" | "ai" | "privacy" | "about"
|
||||
"recording" | "hardware" | "storage" | "calendar" | "sync" | "ai" | "mcp" | "privacy" | "about"
|
||||
>("recording");
|
||||
|
||||
// The currently active whisper model (T8.7, FR-TRX-4) — gates the
|
||||
// language picker below (multilingual model required).
|
||||
let activeModel = $derived(settings.models.find((m) => m.active));
|
||||
|
||||
// ---- About (version + build commit + source) ----
|
||||
const SOURCE_URL = "https://git.dou.bet/iamdoubz/WhispAssist";
|
||||
let appInfo = $state<{ version: string; commit: string } | null>(null);
|
||||
|
||||
// ---- AI summary provider (T5.2, FR-LLM-1) ----
|
||||
// ---- AI summary provider (T5.2/T10.1/T10.2, FR-LLM-1, ADR-0011) ----
|
||||
let llmProvider = $state(settings.settings.llm_provider);
|
||||
let llmEndpoint = $state(settings.settings.llm_endpoint);
|
||||
let llmModel = $state(settings.settings.llm_model);
|
||||
// Hosted (Anthropic) API key — never read back from the backend (it's
|
||||
// never returned by llm_status/get_settings, FR-SEC-1); this is a
|
||||
// write-only field that's blank unless the user is actively (re)typing
|
||||
// one, and is dropped from memory the moment saveLlm() sends it.
|
||||
let llmApiKey = $state("");
|
||||
let showApiKey = $state(false);
|
||||
$effect(() => {
|
||||
// Re-sync the form when settings (re)load or are saved elsewhere.
|
||||
llmProvider = settings.settings.llm_provider;
|
||||
llmEndpoint = settings.settings.llm_endpoint;
|
||||
llmModel = settings.settings.llm_model;
|
||||
});
|
||||
|
||||
const HOSTED_PROVIDER_LABELS: Record<string, string> = { anthropic: "Anthropic (Claude)" };
|
||||
|
||||
/** True when the *currently selected* provider is hosted (leaves the
|
||||
* device): Anthropic always is; "custom" is hosted only once its endpoint
|
||||
* resolves off-network — mirrors the live warning already shown below. */
|
||||
function isHostedProviderSelection(): boolean {
|
||||
if (llmProvider === "anthropic") return true;
|
||||
if (llmProvider === "custom" && llmEndpoint) return !endpointIsLocalOrLan(llmEndpoint);
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- Hosted-AI "leaves your device" one-time banner (T10.3/M3.3) ----
|
||||
let showHostedBanner = $state(false);
|
||||
function onSaveLlmClick() {
|
||||
if (isHostedProviderSelection() && !settings.settings.hosted_ai_acknowledged) {
|
||||
showHostedBanner = true;
|
||||
return;
|
||||
}
|
||||
saveLlm();
|
||||
}
|
||||
async function acceptHostedBannerAndSave() {
|
||||
await settings.acknowledgeHostedAi();
|
||||
showHostedBanner = false;
|
||||
await saveLlm();
|
||||
}
|
||||
|
||||
async function saveLlm() {
|
||||
await settings.setLlmProvider({
|
||||
provider: llmProvider,
|
||||
endpoint: llmEndpoint || undefined,
|
||||
endpoint: llmProvider === "anthropic" ? undefined : llmEndpoint || undefined,
|
||||
model: llmModel || undefined,
|
||||
apiKey: llmApiKey.trim() || undefined,
|
||||
});
|
||||
llmApiKey = ""; // never linger in memory once sent
|
||||
}
|
||||
/** Client-side mirror of the backend's loopback+private-LAN check, for a live
|
||||
* "leaves your network" hint while typing. */
|
||||
@@ -83,6 +129,49 @@
|
||||
}
|
||||
}
|
||||
|
||||
// ---- MCP server (Phase 10b, ADR-0011) ----
|
||||
let mcpTransport = $state<"http" | "stdio">(
|
||||
settings.settings.mcp_transport === "stdio" ? "stdio" : "http",
|
||||
);
|
||||
let mcpPort = $state(settings.settings.mcp_port);
|
||||
let mcpExpose = $state<"none" | "selected" | "all">(
|
||||
(settings.settings.mcp_expose as "none" | "selected" | "all") ?? "none",
|
||||
);
|
||||
let mcpExposeRecordings = $state(settings.settings.mcp_expose_recordings);
|
||||
let mcpCopied = $state<"endpoint" | "token" | null>(null);
|
||||
$effect(() => {
|
||||
// Re-sync the form when settings (re)load, same pattern as the LLM form above.
|
||||
mcpTransport = settings.settings.mcp_transport === "stdio" ? "stdio" : "http";
|
||||
mcpPort = settings.settings.mcp_port;
|
||||
mcpExpose = (settings.settings.mcp_expose as "none" | "selected" | "all") ?? "none";
|
||||
mcpExposeRecordings = settings.settings.mcp_expose_recordings;
|
||||
});
|
||||
async function toggleMcpEnabled(enabled: boolean) {
|
||||
await settings.setMcpEnabled(enabled, mcpTransport, mcpPort);
|
||||
}
|
||||
async function saveMcpScope() {
|
||||
await settings.setMcpScope(mcpExpose, mcpExposeRecordings);
|
||||
}
|
||||
async function copyToClipboard(text: string, what: "endpoint" | "token") {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
mcpCopied = what;
|
||||
setTimeout(() => {
|
||||
if (mcpCopied === what) mcpCopied = null;
|
||||
}, 2000);
|
||||
} catch {
|
||||
/* clipboard API unavailable — the value is still selectable/copyable by hand */
|
||||
}
|
||||
}
|
||||
function relativeTime(atMs: number): string {
|
||||
const diffSec = Math.round((Date.now() - atMs) / 1000);
|
||||
if (diffSec < 5) return "just now";
|
||||
if (diffSec < 60) return `${diffSec}s ago`;
|
||||
if (diffSec < 3600) return `${Math.round(diffSec / 60)}m ago`;
|
||||
if (diffSec < 86400) return `${Math.round(diffSec / 3600)}h ago`;
|
||||
return new Date(atMs).toLocaleString();
|
||||
}
|
||||
|
||||
// ---- Advanced Ollama configuration (sparse; only overrides are stored) ----
|
||||
const OPTION_GROUPS: OllamaGroup[] = ["sampling", "repetition", "mirostat", "context"];
|
||||
type OptVal = number | boolean | string[];
|
||||
@@ -489,6 +578,9 @@
|
||||
<button class:active={section === "ai"} onclick={() => (section = "ai")}>
|
||||
<Sparkles size={14} aria-hidden="true" /> AI
|
||||
</button>
|
||||
<button class:active={section === "mcp"} onclick={() => (section = "mcp")}>
|
||||
<Bot size={14} aria-hidden="true" /> MCP server
|
||||
</button>
|
||||
<button class:active={section === "privacy"} onclick={() => (section = "privacy")}>
|
||||
<ShieldCheck size={14} aria-hidden="true" /> Privacy
|
||||
</button>
|
||||
@@ -708,6 +800,41 @@
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
<h4>Transcription Language</h4>
|
||||
{#if activeModel?.multilingual}
|
||||
<label
|
||||
>Language
|
||||
<select
|
||||
value={settings.settings.whisper_language ?? ""}
|
||||
onchange={(e) => {
|
||||
const v = (e.target as HTMLSelectElement).value;
|
||||
settings.setWhisperLanguage(v || null);
|
||||
}}
|
||||
>
|
||||
<option value="">Auto-detect</option>
|
||||
{#each settings.languages as l (l.code)}
|
||||
<option value={l.code}>{l.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
<p class="muted">
|
||||
Applies to the next recording. The language actually used is shown on each meeting
|
||||
afterward.
|
||||
</p>
|
||||
{:else}
|
||||
<label
|
||||
>Language
|
||||
<select disabled aria-describedby="language-disabled-hint">
|
||||
<option>English only</option>
|
||||
</select>
|
||||
</label>
|
||||
<p class="muted" id="language-disabled-hint">
|
||||
{activeModel
|
||||
? `"${activeModel.label}" is English-only.`
|
||||
: "No model selected."} Switch to a multilingual model above to choose a language.
|
||||
</p>
|
||||
{/if}
|
||||
</section>
|
||||
{:else if section === "storage"}
|
||||
<section>
|
||||
@@ -986,8 +1113,10 @@
|
||||
<section>
|
||||
<h3>AI summary provider</h3>
|
||||
<p class="muted">
|
||||
Summaries run on a local LLM. Point this at Ollama on this PC or another machine on your
|
||||
LAN (e.g. <code>192.168.0.x</code>) — both count as local, so nothing leaves your network.
|
||||
Summaries run on a local LLM by default. Point this at Ollama on this PC or another
|
||||
machine on your LAN (e.g. <code>192.168.0.x</code>) — both count as local, so nothing
|
||||
leaves your network. Hosted providers (Anthropic) are optional, off by default, and send
|
||||
the transcript to a third party once you turn one on.
|
||||
</p>
|
||||
<label
|
||||
>Provider
|
||||
@@ -995,32 +1124,76 @@
|
||||
<option value="off">Off</option>
|
||||
<option value="ollama">Ollama (local / LAN)</option>
|
||||
<option value="custom">Custom (OpenAI-compatible)</option>
|
||||
<option value="anthropic">Anthropic (Claude) — hosted, leaves this device</option>
|
||||
</select>
|
||||
</label>
|
||||
{#if llmProvider !== "off"}
|
||||
<div class="grid">
|
||||
<label class="wide"
|
||||
>Endpoint<input
|
||||
bind:value={llmEndpoint}
|
||||
placeholder="http://192.168.0.42:11434"
|
||||
/></label
|
||||
>
|
||||
<label>Model<input bind:value={llmModel} placeholder="llama3.1" /></label>
|
||||
{#if llmProvider !== "anthropic"}
|
||||
<label class="wide"
|
||||
>Endpoint<input
|
||||
bind:value={llmEndpoint}
|
||||
placeholder="http://192.168.0.42:11434"
|
||||
/></label
|
||||
>
|
||||
<label>Model<input bind:value={llmModel} placeholder="llama3.1" /></label>
|
||||
{:else}
|
||||
<label class="wide"
|
||||
>Model<input bind:value={llmModel} placeholder="claude-3-5-sonnet-latest" /></label
|
||||
>
|
||||
<label class="wide"
|
||||
>API key
|
||||
<div class="key-input">
|
||||
<input
|
||||
type={showApiKey ? "text" : "password"}
|
||||
autocomplete="off"
|
||||
bind:value={llmApiKey}
|
||||
placeholder={settings.llmStatus?.provider === "anthropic"
|
||||
? "•••••••••••••••• (already set — leave blank to keep it)"
|
||||
: "sk-ant-…"}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="icon-toggle"
|
||||
onclick={() => (showApiKey = !showApiKey)}
|
||||
aria-label={showApiKey ? "Hide API key" : "Show API key"}
|
||||
>
|
||||
{#if showApiKey}<EyeOff size={14} aria-hidden="true" />{:else}<Eye
|
||||
size={14}
|
||||
aria-hidden="true"
|
||||
/>{/if}
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
{/if}
|
||||
</div>
|
||||
{#if llmEndpoint && !endpointIsLocalOrLan(llmEndpoint)}
|
||||
{#if llmProvider === "anthropic"}
|
||||
<div class="banner hosted">
|
||||
<Globe size={14} aria-hidden="true" />
|
||||
Anthropic is a hosted, third-party service — this meeting's transcript leaves your device
|
||||
when you generate a summary.
|
||||
</div>
|
||||
{:else if llmEndpoint && !endpointIsLocalOrLan(llmEndpoint)}
|
||||
<div class="banner">
|
||||
<AlertTriangle size={14} aria-hidden="true" />
|
||||
This endpoint isn't on your machine or LAN — your transcript would leave your network.
|
||||
</div>
|
||||
{/if}
|
||||
<div class="actions">
|
||||
<button class="primary" onclick={saveLlm} disabled={settings.llmSaving}>
|
||||
<button class="primary" onclick={onSaveLlmClick} disabled={settings.llmSaving}>
|
||||
{settings.llmSaving ? "Saving…" : "Save"}
|
||||
</button>
|
||||
<button class="ghost" onclick={() => settings.loadLlmStatus()}>
|
||||
<RefreshCw size={14} aria-hidden="true" /> Test connection
|
||||
</button>
|
||||
</div>
|
||||
{#if showHostedBanner}
|
||||
<HostedAiBanner
|
||||
providerLabel={HOSTED_PROVIDER_LABELS[llmProvider] ?? "this hosted provider"}
|
||||
onAccept={acceptHostedBannerAndSave}
|
||||
onCancel={() => (showHostedBanner = false)}
|
||||
/>
|
||||
{/if}
|
||||
{#if settings.llmStatus}
|
||||
{@const s = settings.llmStatus}
|
||||
<div class="status-card">
|
||||
@@ -1191,6 +1364,146 @@
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
{:else if section === "mcp"}
|
||||
<section>
|
||||
<h3>MCP server</h3>
|
||||
<div class="banner">
|
||||
<AlertTriangle size={14} aria-hidden="true" />
|
||||
<span>
|
||||
This lets your own coding agent (Claude Code, Codex, Copilot, OpenCode, …) pull meeting
|
||||
context on your local machine. Once connected, <strong>that agent</strong> may forward
|
||||
what it reads to its own model provider's cloud — outside WhispAssist's control.
|
||||
WhispAssist itself never sends this data anywhere; the server only listens on this
|
||||
device (<code>127.0.0.1</code>) and every read is logged below.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<label class="row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={settings.mcpStatus?.enabled ?? false}
|
||||
disabled={settings.mcpSaving}
|
||||
onchange={(e) => toggleMcpEnabled((e.target as HTMLInputElement).checked)}
|
||||
/>
|
||||
<span>Enable the MCP server</span>
|
||||
</label>
|
||||
<p class="muted">
|
||||
Off by default. Loopback-only, token-gated — nothing is reachable from the network.
|
||||
</p>
|
||||
|
||||
<div class="grid">
|
||||
<label
|
||||
>Transport
|
||||
<select bind:value={mcpTransport} disabled={settings.mcpStatus?.enabled}>
|
||||
<option value="http">Streamable HTTP</option>
|
||||
<option value="stdio">stdio (agent spawns a process)</option>
|
||||
</select>
|
||||
</label>
|
||||
{#if mcpTransport === "http"}
|
||||
<label
|
||||
>Port<input
|
||||
type="number"
|
||||
min="1"
|
||||
max="65535"
|
||||
bind:value={mcpPort}
|
||||
disabled={settings.mcpStatus?.enabled}
|
||||
/></label
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
{#if settings.mcpStatus?.enabled}
|
||||
<p class="muted small">
|
||||
To change transport/port, turn the server off first, then back on.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<h4>Scope</h4>
|
||||
<div class="grid">
|
||||
<label
|
||||
>Expose
|
||||
<select bind:value={mcpExpose} onchange={saveMcpScope}>
|
||||
<option value="none">None — nothing is shared</option>
|
||||
<option value="selected">Selected — only feature briefs you've marked shared</option>
|
||||
<option value="all"
|
||||
>All — meetings, transcripts, action items, and shared briefs</option
|
||||
>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<label class="row small">
|
||||
<input
|
||||
type="checkbox"
|
||||
bind:checked={mcpExposeRecordings}
|
||||
disabled={mcpExpose === "none"}
|
||||
onchange={saveMcpScope}
|
||||
/>
|
||||
<span
|
||||
>Also allow meetings with a saved recording (off by default — a recorded meeting's
|
||||
transcript is withheld even in "All" scope until this is on)</span
|
||||
>
|
||||
</label>
|
||||
|
||||
{#if settings.mcpLastToken}
|
||||
<div class="mcp-token" aria-live="polite">
|
||||
<div class="row">
|
||||
<KeyRound size={14} aria-hidden="true" />
|
||||
<strong>New auth token — shown once, copy it now</strong>
|
||||
</div>
|
||||
<p class="muted small">
|
||||
This won't be shown again. It's stored in your OS credential store; if you lose it,
|
||||
turn the server off and back on to mint a new one.
|
||||
</p>
|
||||
<div class="row">
|
||||
<code>{settings.mcpLastToken}</code>
|
||||
<button
|
||||
class="link"
|
||||
onclick={() => copyToClipboard(settings.mcpLastToken ?? "", "token")}
|
||||
>
|
||||
<Copy size={13} aria-hidden="true" />
|
||||
{mcpCopied === "token" ? "Copied" : "Copy"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if settings.mcpStatus?.enabled}
|
||||
<div class="row">
|
||||
Endpoint<code>{settings.mcpStatus.endpoint}</code>
|
||||
<button
|
||||
class="link"
|
||||
onclick={() => copyToClipboard(settings.mcpStatus?.endpoint ?? "", "endpoint")}
|
||||
>
|
||||
<Copy size={13} aria-hidden="true" />
|
||||
{mcpCopied === "endpoint" ? "Copied" : "Copy"}
|
||||
</button>
|
||||
</div>
|
||||
<p class="muted small">
|
||||
Point your agent's MCP client config at this
|
||||
{settings.mcpStatus.transport === "stdio" ? "command" : "URL"}, with the token above as
|
||||
a bearer credential.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<h4>Access log</h4>
|
||||
<p class="muted">Every tool read an agent makes, allowed or denied (FR-MCP-5).</p>
|
||||
{#if settings.mcpAccessLog.length === 0}
|
||||
<p class="muted">No agent has read anything yet.</p>
|
||||
{:else}
|
||||
<ul class="events">
|
||||
{#each settings.mcpAccessLog as entry, i (entry.at + "-" + i)}
|
||||
<li>
|
||||
<code>{entry.tool}</code>
|
||||
{#if entry.meeting_id}<span class="host"
|
||||
>meeting {entry.meeting_id.slice(0, 8)}</span
|
||||
>{/if}
|
||||
{#if entry.client}<span class="badge">{entry.client}</span>{/if}
|
||||
<span class="host">{relativeTime(entry.at)}</span>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
<button class="link" onclick={() => settings.loadMcpAccessLog()}>Refresh</button>
|
||||
{/if}
|
||||
</section>
|
||||
{:else if section === "privacy"}
|
||||
<section>
|
||||
<h3>Privacy</h3>
|
||||
@@ -1210,6 +1523,18 @@
|
||||
{settings.privacy.syncEnabled ? "enabled" : "off"}
|
||||
</span>
|
||||
</div>
|
||||
<div class="row">
|
||||
MCP server<span class="badge" class:busy={settings.mcpStatus?.enabled}>
|
||||
{settings.mcpStatus?.enabled ? `on · ${settings.mcpStatus.exposeScope}` : "off"}
|
||||
</span>
|
||||
</div>
|
||||
{#if settings.mcpStatus?.enabled}
|
||||
<p class="muted confirm">
|
||||
<Check size={14} aria-hidden="true" />
|
||||
Inbound on loopback only — it adds nothing to the egress list above. A connected agent may
|
||||
still forward what it reads to its own model provider; see the MCP server tab.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<h4>Egress allowlist</h4>
|
||||
{#if settings.privacy.allowlistedHosts.length === 0}
|
||||
@@ -1489,6 +1814,12 @@
|
||||
border-radius: 5px;
|
||||
padding: 0.35rem;
|
||||
}
|
||||
input:disabled,
|
||||
select:disabled,
|
||||
textarea:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.artifacts {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
@@ -1518,6 +1849,38 @@
|
||||
margin-top: 0.15rem;
|
||||
color: var(--warning);
|
||||
}
|
||||
/* Informational (not a warning-severity) variant for "this is hosted, by
|
||||
your own choice" notices — Anthropic's fixed endpoint (ADR-0011). */
|
||||
.banner.hosted {
|
||||
background: color-mix(in srgb, var(--accent) 12%, var(--bg));
|
||||
}
|
||||
.banner.hosted :global(svg) {
|
||||
color: var(--accent);
|
||||
}
|
||||
.key-input {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
.key-input input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.icon-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: none;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 5px;
|
||||
padding: 0.35rem;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
.icon-toggle:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--fg);
|
||||
}
|
||||
ul.targets,
|
||||
ul.models,
|
||||
ul.events {
|
||||
@@ -1660,6 +2023,18 @@
|
||||
ul.hosts li {
|
||||
padding: 0.2rem 0;
|
||||
}
|
||||
.mcp-token {
|
||||
margin: 0.6rem 0;
|
||||
padding: 0.6rem 0.75rem;
|
||||
border: 1px solid var(--warning, #d97706);
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
.mcp-token code {
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
/* ---- AI provider: status + advanced config ---- */
|
||||
.ghost {
|
||||
|
||||
@@ -9,10 +9,13 @@
|
||||
errorMessage,
|
||||
type ActionItem,
|
||||
type CalendarEventDetail,
|
||||
type FeatureBrief,
|
||||
type FeatureBriefInfo,
|
||||
type LlmStatus,
|
||||
} from "../api";
|
||||
import { renderMarkdown } from "../markdown";
|
||||
import TagChip from "../components/TagChip.svelte";
|
||||
import HostedAiBanner from "../components/HostedAiBanner.svelte";
|
||||
import {
|
||||
Tags,
|
||||
Sparkles,
|
||||
@@ -22,6 +25,11 @@
|
||||
Mic2,
|
||||
Bell,
|
||||
UploadCloud,
|
||||
FileText,
|
||||
Copy,
|
||||
Check,
|
||||
Cpu,
|
||||
Globe,
|
||||
} from "@lucide/svelte";
|
||||
|
||||
onMount(() => calendar.load());
|
||||
@@ -48,19 +56,93 @@
|
||||
|
||||
// ---- Summary + action items (T5.4/T5.5/T5.6, FR-LLM-2/3/4) ----
|
||||
let llmStatus = $state<LlmStatus | null>(null);
|
||||
onMount(async () => {
|
||||
async function refreshLlmStatus() {
|
||||
try {
|
||||
llmStatus = await api.llmStatus();
|
||||
} catch {
|
||||
llmStatus = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
onMount(refreshLlmStatus);
|
||||
|
||||
function generateSummary() {
|
||||
const m = meetings.selected;
|
||||
if (m) meetings.generateSummary(m.id);
|
||||
}
|
||||
|
||||
// ---- Active provider indicator + per-use quick switch (T10.3/M3.3) ----
|
||||
// Same four providers Settings' AI section offers; switching here reuses
|
||||
// the exact same set_llm_provider command (and hence the same "anthropic's
|
||||
// endpoint is fixed" / "switching away resets a stale hosted endpoint"
|
||||
// guarantees — see apply_llm_provider_args in commands.rs).
|
||||
const PROVIDER_LABELS: Record<string, string> = {
|
||||
off: "Off",
|
||||
ollama: "Ollama",
|
||||
custom: "Custom",
|
||||
anthropic: "Anthropic (Claude)",
|
||||
};
|
||||
function isHostedStatus(status: LlmStatus | null): boolean {
|
||||
return !!status && status.provider !== "off" && !status.isLocal;
|
||||
}
|
||||
let switchingProvider = $state(false);
|
||||
|
||||
// ---- Hosted-AI "leaves your device" one-time gate (T10.3/M3.3) — shared
|
||||
// by the quick switch (switching TO Anthropic) and Generate/Regenerate
|
||||
// (the actual point a transcript would leave the device, so this is the
|
||||
// gate that matters even if the quick switch's own check is skipped, e.g.
|
||||
// "custom" resolving to a hosted endpoint that was configured elsewhere).
|
||||
let showHostedBanner = $state(false);
|
||||
let hostedBannerLabel = $state("this hosted provider");
|
||||
let pendingHostedAction = $state<(() => void) | null>(null);
|
||||
function requireHostedAck(providerLabel: string, action: () => void) {
|
||||
if (!settings.settings.hosted_ai_acknowledged) {
|
||||
hostedBannerLabel = providerLabel;
|
||||
pendingHostedAction = action;
|
||||
showHostedBanner = true;
|
||||
return;
|
||||
}
|
||||
action();
|
||||
}
|
||||
async function acceptHostedBanner() {
|
||||
await settings.acknowledgeHostedAi();
|
||||
showHostedBanner = false;
|
||||
const action = pendingHostedAction;
|
||||
pendingHostedAction = null;
|
||||
action?.();
|
||||
}
|
||||
function cancelHostedBanner() {
|
||||
showHostedBanner = false;
|
||||
pendingHostedAction = null;
|
||||
}
|
||||
|
||||
async function switchProvider(provider: string) {
|
||||
switchingProvider = true;
|
||||
try {
|
||||
await settings.setLlmProvider({ provider });
|
||||
await refreshLlmStatus();
|
||||
} finally {
|
||||
switchingProvider = false;
|
||||
}
|
||||
}
|
||||
function onProviderChange(e: Event) {
|
||||
const next = (e.target as HTMLSelectElement).value;
|
||||
if (next === "anthropic") {
|
||||
// Deterministically hosted — worth confirming before even switching to
|
||||
// it, not just before the next generate.
|
||||
requireHostedAck(PROVIDER_LABELS[next], () => void switchProvider(next));
|
||||
} else {
|
||||
void switchProvider(next);
|
||||
}
|
||||
}
|
||||
function onGenerateClick() {
|
||||
const label = llmStatus ? (PROVIDER_LABELS[llmStatus.provider] ?? llmStatus.provider) : "";
|
||||
if (isHostedStatus(llmStatus)) {
|
||||
requireHostedAck(label, generateSummary);
|
||||
} else {
|
||||
generateSummary();
|
||||
}
|
||||
}
|
||||
|
||||
// Editable copy so toggling a checkbox doesn't persist until "Save" is
|
||||
// pressed; recomputes whenever a different meeting (or a freshly generated
|
||||
// summary) comes in. bind:checked mutates each item in place, which a plain
|
||||
@@ -250,13 +332,128 @@
|
||||
generatingTags = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Feature briefs (Phase 10 M1, ADR-0011, FR-MCP-4) ----
|
||||
// Agent-ready specs distilled from the meeting via the configured LLM
|
||||
// provider. `exposed` (MCP scope control, FR-MCP-3) lives only on the list
|
||||
// row (FeatureBriefInfo) — the full brief the viewer shows doesn't carry it.
|
||||
let briefs = $state<FeatureBriefInfo[]>([]);
|
||||
let selectedBriefId = $state<string | null>(null);
|
||||
let selectedBrief = $state<FeatureBrief | null>(null);
|
||||
let briefTargetRepo = $state("");
|
||||
let creatingBrief = $state(false);
|
||||
let briefError = $state<string | null>(null);
|
||||
let loadingBriefsForId: string | null = null;
|
||||
|
||||
$effect(() => {
|
||||
const m = meetings.selected;
|
||||
if (!m) {
|
||||
briefs = [];
|
||||
selectedBriefId = null;
|
||||
selectedBrief = null;
|
||||
loadingBriefsForId = null;
|
||||
return;
|
||||
}
|
||||
if (m.id === loadingBriefsForId) return;
|
||||
loadingBriefsForId = m.id;
|
||||
selectedBriefId = null;
|
||||
selectedBrief = null;
|
||||
api
|
||||
.listFeatureBriefs(m.id)
|
||||
.then((list) => (briefs = list))
|
||||
.catch(() => (briefs = []));
|
||||
});
|
||||
|
||||
async function createBrief() {
|
||||
const m = meetings.selected;
|
||||
if (!m) return;
|
||||
creatingBrief = true;
|
||||
briefError = null;
|
||||
try {
|
||||
const brief = await api.createFeatureBrief(m.id, briefTargetRepo.trim() || undefined);
|
||||
briefs = [
|
||||
{
|
||||
id: brief.id,
|
||||
meeting_id: brief.meeting_id,
|
||||
title: brief.title,
|
||||
target_repo: brief.target_repo,
|
||||
exposed: false,
|
||||
},
|
||||
...briefs,
|
||||
];
|
||||
selectedBriefId = brief.id;
|
||||
selectedBrief = brief;
|
||||
briefTargetRepo = "";
|
||||
} catch (e) {
|
||||
briefError = errorMessage(e);
|
||||
} finally {
|
||||
creatingBrief = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function openBrief(id: string) {
|
||||
selectedBriefId = id;
|
||||
briefError = null;
|
||||
try {
|
||||
selectedBrief = await api.getFeatureBrief(id);
|
||||
} catch (e) {
|
||||
selectedBrief = null;
|
||||
briefError = errorMessage(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleBriefExposed(brief: FeatureBriefInfo) {
|
||||
const next = !brief.exposed;
|
||||
try {
|
||||
await api.setBriefExposed(brief.id, next);
|
||||
briefs = briefs.map((b) => (b.id === brief.id ? { ...b, exposed: next } : b));
|
||||
} catch (e) {
|
||||
briefError = errorMessage(e);
|
||||
}
|
||||
}
|
||||
|
||||
function briefAsMarkdown(b: FeatureBrief): string {
|
||||
const criteria = b.acceptance_criteria.length
|
||||
? b.acceptance_criteria.map((c) => `- ${c}`).join("\n")
|
||||
: "- None";
|
||||
let md =
|
||||
`## Title\n${b.title}\n\n` +
|
||||
`## Problem\n${b.problem}\n\n` +
|
||||
`## Desired Outcome\n${b.desired_outcome}\n\n` +
|
||||
`## Acceptance Criteria\n${criteria}`;
|
||||
if (b.context_excerpts.length) {
|
||||
md += `\n\n## Context\n${b.context_excerpts.map((e) => `> **${e.speaker}:** ${e.text}`).join("\n\n")}`;
|
||||
}
|
||||
return md;
|
||||
}
|
||||
|
||||
// Brief copy feedback (T10.6, M1.5): a transient checkmark rather than a
|
||||
// toast — consistent with this panel having no toast system elsewhere.
|
||||
let copiedFormat = $state<"md" | "json" | null>(null);
|
||||
let copiedTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
function flashCopied(format: "md" | "json") {
|
||||
copiedFormat = format;
|
||||
clearTimeout(copiedTimer);
|
||||
copiedTimer = setTimeout(() => (copiedFormat = null), 1500);
|
||||
}
|
||||
async function copyBriefMarkdown() {
|
||||
if (!selectedBrief) return;
|
||||
await navigator.clipboard.writeText(briefAsMarkdown(selectedBrief));
|
||||
flashCopied("md");
|
||||
}
|
||||
async function copyBriefJson() {
|
||||
if (!selectedBrief) return;
|
||||
await navigator.clipboard.writeText(JSON.stringify(selectedBrief, null, 2));
|
||||
flashCopied("json");
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="wrap">
|
||||
{#if meetings.selected?.recorded}
|
||||
<h3><Mic2 size={14} aria-hidden="true" /> Recording</h3>
|
||||
{#if audioSrc}
|
||||
<!-- svelte-ignore a11y_media_has_caption -- a meeting recording has no caption track -->
|
||||
<!-- a meeting recording has no caption track — no svelte-ignore needed,
|
||||
the current eslint-plugin-svelte doesn't flag this element. -->
|
||||
<!-- controlsList/contextmenu: no download affordance — the decrypted audio
|
||||
must not be savable to disk (would undermine encryption at rest). -->
|
||||
<audio
|
||||
@@ -356,6 +553,38 @@
|
||||
{/if}
|
||||
|
||||
<h3><Sparkles size={14} aria-hidden="true" /> Summary</h3>
|
||||
|
||||
<div class="provider-row">
|
||||
<label class="provider-select">
|
||||
<span class="sr-only">AI provider</span>
|
||||
<select
|
||||
value={llmStatus?.provider ?? settings.settings.llm_provider}
|
||||
onchange={onProviderChange}
|
||||
disabled={switchingProvider}
|
||||
>
|
||||
{#each Object.entries(PROVIDER_LABELS) as [id, label] (id)}
|
||||
<option value={id}>{label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
{#if llmStatus && llmStatus.provider !== "off"}
|
||||
<span class="provider-badge" class:hosted={!llmStatus.isLocal}>
|
||||
{#if llmStatus.isLocal}<Cpu size={12} aria-hidden="true" />{:else}<Globe
|
||||
size={12}
|
||||
aria-hidden="true"
|
||||
/>{/if}
|
||||
{llmStatus.isLocal ? "local" : "leaves this device"}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
{#if showHostedBanner}
|
||||
<HostedAiBanner
|
||||
providerLabel={hostedBannerLabel}
|
||||
onAccept={acceptHostedBanner}
|
||||
onCancel={cancelHostedBanner}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if !meetings.selected}
|
||||
<p class="muted">Select a meeting to generate a summary.</p>
|
||||
{:else if meetings.summarizingId === meetings.selected.id}
|
||||
@@ -375,13 +604,13 @@
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
<button class="link" onclick={generateSummary}>Regenerate</button>
|
||||
<button class="link" onclick={onGenerateClick}>Regenerate</button>
|
||||
{:else}
|
||||
<p class="muted">Generated locally after the meeting (requires a local LLM provider).</p>
|
||||
{#if llmStatus && llmStatus.provider === "off"}
|
||||
<p class="muted small">No local LLM provider configured — enable one in Settings.</p>
|
||||
<p class="muted small">No AI provider configured — enable one in Settings.</p>
|
||||
{:else}
|
||||
<button class="primary" onclick={generateSummary}>
|
||||
<button class="primary" onclick={onGenerateClick}>
|
||||
<Sparkles size={14} aria-hidden="true" />
|
||||
Generate summary
|
||||
</button>
|
||||
@@ -391,6 +620,91 @@
|
||||
<p class="error">{meetings.summaryError}</p>
|
||||
{/if}
|
||||
|
||||
<h3><FileText size={14} aria-hidden="true" /> Feature briefs</h3>
|
||||
{#if !meetings.selected}
|
||||
<p class="muted">Select a meeting to create or view feature briefs.</p>
|
||||
{:else}
|
||||
<p class="muted small">
|
||||
Distills this meeting into an agent-ready spec (requires a local LLM provider) — hand it to a
|
||||
coding agent, or serve it over the MCP server once that's on.
|
||||
</p>
|
||||
<div class="brief-create">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Target repo (optional), e.g. acme/reporting-web"
|
||||
bind:value={briefTargetRepo}
|
||||
disabled={creatingBrief}
|
||||
/>
|
||||
<button class="primary" onclick={createBrief} disabled={creatingBrief}>
|
||||
<Sparkles size={14} aria-hidden="true" />
|
||||
{creatingBrief ? "Distilling…" : "Create feature brief"}
|
||||
</button>
|
||||
</div>
|
||||
{#if briefError}
|
||||
<p class="error">{briefError}</p>
|
||||
{/if}
|
||||
|
||||
{#if briefs.length > 0}
|
||||
<ul class="briefs">
|
||||
{#each briefs as b (b.id)}
|
||||
<li class:active={b.id === selectedBriefId}>
|
||||
<button class="brief-title" onclick={() => openBrief(b.id)}>
|
||||
{b.title}
|
||||
{#if b.target_repo}<span class="muted small">{b.target_repo}</span>{/if}
|
||||
</button>
|
||||
<label class="expose" title="Available when the MCP server is on">
|
||||
<input type="checkbox" checked={b.exposed} onchange={() => toggleBriefExposed(b)} />
|
||||
<span class="muted small">MCP</span>
|
||||
</label>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
|
||||
{#if selectedBrief}
|
||||
<div class="brief-viewer">
|
||||
<div class="brief-actions">
|
||||
<button class="link" onclick={copyBriefMarkdown}>
|
||||
{#if copiedFormat === "md"}
|
||||
<Check size={13} aria-hidden="true" /> Copied
|
||||
{:else}
|
||||
<Copy size={13} aria-hidden="true" /> Copy as Markdown
|
||||
{/if}
|
||||
</button>
|
||||
<button class="link" onclick={copyBriefJson}>
|
||||
{#if copiedFormat === "json"}
|
||||
<Check size={13} aria-hidden="true" /> Copied
|
||||
{:else}
|
||||
<Copy size={13} aria-hidden="true" /> Copy as JSON
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
<h4>Problem</h4>
|
||||
<p class="brief-text">{selectedBrief.problem}</p>
|
||||
<h4>Desired outcome</h4>
|
||||
<p class="brief-text">{selectedBrief.desired_outcome}</p>
|
||||
<h4>Acceptance criteria</h4>
|
||||
{#if selectedBrief.acceptance_criteria.length}
|
||||
<ul class="decisions">
|
||||
{#each selectedBrief.acceptance_criteria as c, i (i)}
|
||||
<li>{c}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{:else}
|
||||
<p class="muted small">None captured.</p>
|
||||
{/if}
|
||||
{#if selectedBrief.context_excerpts.length}
|
||||
<h4>Context</h4>
|
||||
<ul class="excerpts">
|
||||
{#each selectedBrief.context_excerpts as e, i (i)}
|
||||
<li><span class="speaker">{e.speaker}:</span> "{e.text}"</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
<h3><ListTodo size={14} aria-hidden="true" /> Action items</h3>
|
||||
{#if !meetings.selected}
|
||||
<p class="muted">Select a meeting to see its action items.</p>
|
||||
@@ -538,6 +852,40 @@
|
||||
padding-top: 0;
|
||||
border-top: none;
|
||||
}
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.provider-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin: -0.3rem 0 0.6rem;
|
||||
}
|
||||
.provider-select select {
|
||||
font-size: 0.78rem;
|
||||
padding: 0.25rem 0.4rem;
|
||||
}
|
||||
.provider-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
font-size: 0.72rem;
|
||||
color: var(--muted);
|
||||
padding: 0.15rem 0.5rem;
|
||||
border-radius: var(--radius-full, 999px);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
.provider-badge.hosted {
|
||||
color: var(--accent);
|
||||
border-color: color-mix(in srgb, var(--accent) 40%, var(--border));
|
||||
}
|
||||
button.primary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -761,4 +1109,96 @@
|
||||
.err {
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
/* ---- Feature briefs (Phase 10 M1, ADR-0011) ---- */
|
||||
.brief-create {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
margin: 0.3rem 0;
|
||||
}
|
||||
.brief-create input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
ul.briefs {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0.4rem 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
}
|
||||
ul.briefs li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
ul.briefs li.active {
|
||||
border-color: var(--accent);
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
.brief-title {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 0.1rem;
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
padding: 0.35rem 0.4rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--fg);
|
||||
}
|
||||
.expose {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
padding: 0 0.4rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.brief-viewer {
|
||||
margin-top: 0.5rem;
|
||||
padding: 0.6rem 0.7rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
.brief-actions {
|
||||
display: flex;
|
||||
gap: 0.9rem;
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
.brief-actions .link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
.brief-text {
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.5;
|
||||
margin: 0.2rem 0 0.4rem;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
ul.excerpts {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0.2rem 0;
|
||||
font-size: 0.82rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
ul.excerpts li {
|
||||
padding: 0.2rem 0;
|
||||
font-style: italic;
|
||||
}
|
||||
ul.excerpts .speaker {
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
color: var(--fg);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -29,6 +29,14 @@
|
||||
return speakers.find((s) => s.label === label)?.display_name ?? label;
|
||||
}
|
||||
|
||||
// T8.7/FR-TRX-4: the meeting view shows the language actually used, not
|
||||
// just the raw ISO code — falls back to the code itself if it's not in
|
||||
// the (curated) catalog, and to "auto-detecting…" before any is known.
|
||||
function languageLabel(code: string | null): string {
|
||||
if (!code) return "auto-detecting…";
|
||||
return settings.languages.find((l) => l.code === code)?.label ?? code;
|
||||
}
|
||||
|
||||
let notesText = $state("");
|
||||
// Notes is a single pane: raw markdown ("Editor") or the rendered result
|
||||
// ("Preview"), toggled by one button whose label flips to the other mode.
|
||||
@@ -130,13 +138,16 @@
|
||||
}
|
||||
|
||||
let reprocessModel = $state("");
|
||||
// T8.7/FR-TRX-4: "" reuses the meeting's current language (backend default
|
||||
// when `language` is omitted) rather than resetting it to auto.
|
||||
let reprocessLanguage = $state("");
|
||||
let reprocessing = $state(false);
|
||||
async function reprocess() {
|
||||
const m = meetings.selected;
|
||||
if (!m || !reprocessModel) return;
|
||||
reprocessing = true;
|
||||
try {
|
||||
await meetings.reprocess(m.id, reprocessModel);
|
||||
await meetings.reprocess(m.id, reprocessModel, reprocessLanguage || undefined);
|
||||
} finally {
|
||||
reprocessing = false;
|
||||
}
|
||||
@@ -154,8 +165,13 @@
|
||||
/>
|
||||
<div class="split">
|
||||
<div class="pane transcript">
|
||||
<h4><MessageSquareText size={14} aria-hidden="true" /> Transcript</h4>
|
||||
<h4>
|
||||
<MessageSquareText size={14} aria-hidden="true" /> Transcript
|
||||
<span class="badge lang" title="Transcription language">{languageLabel(m.language)}</span
|
||||
>
|
||||
</h4>
|
||||
{#if m.recorded && settings.models.some((mo) => mo.installed)}
|
||||
{@const reprocessModelInfo = settings.models.find((mo) => mo.id === reprocessModel)}
|
||||
<div class="reprocess">
|
||||
<select bind:value={reprocessModel}>
|
||||
<option value="">Re-transcribe with…</option>
|
||||
@@ -163,6 +179,15 @@
|
||||
<option value={mo.id}>{mo.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{#if reprocessModelInfo?.multilingual}
|
||||
<select bind:value={reprocessLanguage} aria-label="Reprocess language">
|
||||
<option value="">Keep current language</option>
|
||||
<option value="auto">Auto-detect</option>
|
||||
{#each settings.languages as l (l.code)}
|
||||
<option value={l.code}>{l.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{/if}
|
||||
<button disabled={!reprocessModel || reprocessing} onclick={reprocess}>
|
||||
<RefreshCw size={13} aria-hidden="true" class={reprocessing ? "spin" : ""} />
|
||||
{reprocessing ? "Re-transcribing…" : "Go"}
|
||||
@@ -328,6 +353,20 @@
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--muted);
|
||||
}
|
||||
/* Transcription language (T8.7, FR-TRX-4) — a quiet pill, not a status
|
||||
color, since "which language" isn't a good/bad state to flag. */
|
||||
.badge.lang {
|
||||
margin-left: auto;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 500;
|
||||
text-transform: none;
|
||||
letter-spacing: normal;
|
||||
color: var(--muted);
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 0.1rem 0.45rem;
|
||||
}
|
||||
.reprocess {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
|
||||
Reference in New Issue
Block a user