548 lines
27 KiB
Markdown
548 lines
27 KiB
Markdown
# Vorleser — Architecture
|
||
|
||
Status: Draft v1.0 · Target: macOS 14+ on Apple Silicon · Language: Swift 6
|
||
|
||
Vorleser is a lightweight macOS menu-bar companion. The user selects text in any application and triggers a command. Vorleser then reads that selection aloud using a local Ollama speech model (Gradium Phonon), with sentence-level and paragraph-level control. It is not a document reader: the source application remains the user's workspace, and Vorleser only provides the narration and its controls.
|
||
|
||
This document is the authoritative technical reference. If code and this document disagree, fix one of them in the same change and record the decision in `docs/DECISIONS.md`.
|
||
|
||
---
|
||
|
||
## 1. Goals and non-goals
|
||
|
||
### Goals
|
||
|
||
| ID | Goal |
|
||
|---|---|
|
||
| G1 | Read the **current selection** from the frontmost app after an explicit user action (hotkey, Services menu, or menu-bar command). |
|
||
| G2 | Give the reader control: play/pause, previous/next sentence, previous/next paragraph, restart, stop, playback speed. |
|
||
| G3 | Start audio quickly. Target time-to-first-audio (TTFA) is ≤ 1.0 s on an M-series Mac, measured on a warm model. |
|
||
| G4 | Local-first: default endpoint is `http://127.0.0.1:11434`. No text leaves the machine unless the user configures a remote endpoint. |
|
||
| G5 | Faithful reading: speak the selected text, not a summary or rewrite. |
|
||
| G6 | Support every installed Phonon model and its voices through runtime discovery. Do not hard-code the voice list. |
|
||
| G7 | Fail visibly and in a way the user can act on, e.g. "Ollama is not running", "Model not installed", "No text selected", "Accessibility permission required". |
|
||
|
||
### Non-goals (v1)
|
||
|
||
- No document library, persistence of articles, or a full-text reading view.
|
||
- No word-level highlighting inside the source application. Ollama provides no timestamps (see §9).
|
||
- No LLM rewriting or summarisation. A possible "adapted narration" mode is out of scope for v1.
|
||
- No Intel Macs, Linux, or Windows. Phonon in Ollama currently requires Apple Silicon.
|
||
- No Mac App Store distribution in v1. The Accessibility-based capture requires a non-sandboxed app (see ADR-003).
|
||
|
||
---
|
||
|
||
## 2. System context
|
||
|
||
```mermaid
|
||
flowchart LR
|
||
User((Reader))
|
||
Src[Source app<br/>Safari · Chrome · Preview · Word · …]
|
||
V[Vorleser.app<br/>menu-bar agent]
|
||
O[Ollama server<br/>127.0.0.1:11434]
|
||
P[Phonon model<br/>phonon / phonon:40m-*]
|
||
AX[(macOS Accessibility API)]
|
||
SV[(macOS Services / Pasteboard)]
|
||
CA[(Core Audio)]
|
||
|
||
User -- selects text --> Src
|
||
User -- hotkey / Services / menu --> V
|
||
V -- AXSelectedText --> AX --> Src
|
||
Src -- NSServices pasteboard --> SV --> V
|
||
V -- POST /v1/audio/speech --> O --> P
|
||
V -- POST /api/show, GET /api/tags --> O
|
||
V -- PCM buffers --> CA
|
||
```
|
||
|
||
### External contracts
|
||
|
||
| Dependency | Contract | Doc |
|
||
|---|---|---|
|
||
| Ollama ≥ 0.40.9 | `/v1/audio/speech`, `/api/show`, `/api/tags`, `/api/version` | `docs/OLLAMA_SPEECH_API.md` |
|
||
| macOS Accessibility | `AXUIElementCreateSystemWide`, `kAXFocusedUIElementAttribute`, `kAXSelectedTextAttribute` | `docs/SELECTION_CAPTURE.md` |
|
||
| macOS Services | `NSServices` in Info.plist, `NSApp.servicesProvider` | `docs/SELECTION_CAPTURE.md` |
|
||
| AVFoundation | `AVAudioEngine`, `AVAudioPlayerNode`, `AVAudioUnitTimePitch` | `docs/AUDIO_PIPELINE.md` |
|
||
| NaturalLanguage | `NLTokenizer(.sentence)`, `NLLanguageRecognizer` | §6 |
|
||
|
||
---
|
||
|
||
## 3. Module structure
|
||
|
||
The code is split into a **SwiftPM package (`VorleserKit`)** that holds all logic and is testable with `swift test`, a thin **app target** generated by XcodeGen, and a **CLI harness** for headless end-to-end testing.
|
||
|
||
```
|
||
Vorleser/
|
||
├── AGENTS.md · opencode.json · .opencode/ # OpenCode instructions, agents, commands
|
||
├── project.yml # XcodeGen spec → Vorleser.xcodeproj (generated, git-ignored)
|
||
├── Makefile · scripts/ # bootstrap, verify, privacy-check, capture-fixtures, smoke-ollama
|
||
├── App/ # macOS app target (SwiftUI + AppKit glue only)
|
||
│ ├── VorleserApp.swift
|
||
│ ├── AppDelegate.swift # Services provider, hotkey registration, lifecycle
|
||
│ ├── MenuBar/
|
||
│ ├── Controller/ # Floating NSPanel + SwiftUI controller view
|
||
│ ├── Settings/
|
||
│ ├── Onboarding/ # Accessibility + Ollama checks
|
||
│ ├── Info.plist
|
||
│ └── Vorleser.entitlements
|
||
├── Packages/VorleserKit/ # SwiftPM package — all testable logic
|
||
│ ├── Package.swift
|
||
│ ├── Sources/
|
||
│ │ ├── VorleserCore/ # Domain types, ReadingSession state machine, settings model
|
||
│ │ ├── VorleserOllama/ # HTTP client, model/voice discovery, streaming PCM
|
||
│ │ ├── VorleserText/ # Normalisation, segmentation, language detection
|
||
│ │ ├── VorleserAudio/ # AVAudioEngine playback, speed, position tracking
|
||
│ │ ├── VorleserCapture/ # Selection capture strategies (AX, Services, clipboard)
|
||
│ │ ├── VorleserTestSupport/# Fakes shared by tests
|
||
│ │ └── vorleser-cli/ # `vorleser-cli speak --file x.txt` for headless testing
|
||
│ └── Tests/
|
||
│ ├── VorleserCoreTests/
|
||
│ ├── VorleserOllamaTests/ # URLProtocol stubs + Fixtures/ (recorded by scripts/capture-fixtures.sh)
|
||
│ ├── VorleserTextTests/ # + Fixtures/ (sample EN/DE texts)
|
||
│ ├── VorleserAudioTests/
|
||
│ ├── VorleserCaptureTests/
|
||
│ └── VorleserLiveTests/ # opt-in, real Ollama (VORLESER_LIVE=1)
|
||
└── docs/
|
||
```
|
||
|
||
The local package lives in a subfolder rather than the repository root, so Xcode does not treat the whole repository as a package when it opens the generated project.
|
||
|
||
### Dependency rules (enforced by package target dependencies)
|
||
|
||
```mermaid
|
||
flowchart TD
|
||
App --> VorleserCore
|
||
App --> VorleserCapture
|
||
CLI[vorleser-cli] --> VorleserCore
|
||
VorleserCore --> VorleserOllama
|
||
VorleserCore --> VorleserText
|
||
VorleserCore --> VorleserAudio
|
||
VorleserCapture -.no deps on.-> VorleserOllama
|
||
```
|
||
|
||
- `VorleserText`, `VorleserOllama`, and `VorleserAudio` must not depend on each other.
|
||
- `VorleserCore` composes them through **protocols** so each can be faked in tests.
|
||
- `VorleserCapture` depends on AppKit and ApplicationServices only. It is the only module that touches Accessibility APIs.
|
||
- The `App` target holds no business logic. Anything with a branch worth testing belongs in a package module.
|
||
|
||
### Third-party dependencies
|
||
|
||
Keep this minimal. Allowed:
|
||
|
||
| Package | Purpose | Note |
|
||
|---|---|---|
|
||
| `sindresorhus/KeyboardShortcuts` | User-configurable global hotkey + SwiftUI recorder (app target only) | Wraps Carbon `RegisterEventHotKey`. It does not require Input Monitoring. |
|
||
| `apple/swift-argument-parser` | `vorleser-cli` argument parsing (CLI target only) | Never linked into the app. |
|
||
|
||
All other functionality uses Apple frameworks. Adding a dependency requires an ADR.
|
||
|
||
---
|
||
|
||
## 4. Core domain model
|
||
|
||
```swift
|
||
// VorleserCore
|
||
|
||
public struct CapturedSelection: Sendable, Equatable {
|
||
public let text: String
|
||
public let sourceBundleID: String? // e.g. "com.apple.Safari"
|
||
public let sourceAppName: String?
|
||
public let method: CaptureMethod // .accessibility, .service, .clipboard
|
||
public let capturedAt: Date
|
||
}
|
||
|
||
public struct Segment: Sendable, Identifiable, Equatable {
|
||
public let id: Int // dense, 0-based, playback order
|
||
public let paragraphIndex: Int
|
||
public let sentenceIndexInParagraph: Int
|
||
public let text: String // text sent to TTS (normalised)
|
||
public let sourceRange: Range<String.Index> // into the normalised snapshot
|
||
}
|
||
|
||
public struct ReadingDocument: Sendable {
|
||
public let selection: CapturedSelection
|
||
public let normalisedText: String
|
||
public let segments: [Segment]
|
||
public let paragraphStarts: [Int] // segment ids where paragraphs begin
|
||
public let detectedLanguage: SpeechLanguage?
|
||
}
|
||
|
||
public enum SpeechLanguage: String, Sendable, CaseIterable {
|
||
case en, de, fr, es, pt
|
||
}
|
||
|
||
public struct VoiceSelection: Sendable, Hashable, Codable {
|
||
public let model: String // "phonon", "phonon:40m-de", …
|
||
public let voice: String // "default", "Zoey", "Anton", …
|
||
}
|
||
|
||
public enum PlaybackState: Sendable, Equatable {
|
||
case idle
|
||
case preparing(segmentID: Int) // waiting for first audio
|
||
case playing(segmentID: Int)
|
||
case paused(segmentID: Int)
|
||
case buffering(segmentID: Int) // playback starved, waiting for synthesis
|
||
case finished
|
||
case failed(VorleserError)
|
||
}
|
||
```
|
||
|
||
### Error taxonomy
|
||
|
||
```swift
|
||
public enum VorleserError: Error, Sendable, Equatable {
|
||
case noSelection // capture succeeded but text empty/whitespace
|
||
case captureUnsupported(app: String?) // AX returned no selected-text attribute
|
||
case accessibilityNotTrusted
|
||
case ollamaUnreachable(url: URL)
|
||
case ollamaTooOld(found: String, required: String)
|
||
case modelNotInstalled(model: String)
|
||
case modelNotSpeech(model: String)
|
||
case unknownVoice(voice: String, available: [String])
|
||
case badRequest(message: String) // 400 not otherwise classified
|
||
case server(status: Int, message: String)
|
||
case audioEngine(message: String)
|
||
case cancelled
|
||
}
|
||
```
|
||
|
||
Each error has a `userMessage` and an optional `recoveryAction` (e.g. "Open Accessibility Settings", "Copy `ollama pull phonon`", "Start Ollama"). The UI must only show these strings and never raw `localizedDescription`.
|
||
|
||
---
|
||
|
||
## 5. Runtime flow
|
||
|
||
### 5.1 Read selection: end-to-end sequence
|
||
|
||
```mermaid
|
||
sequenceDiagram
|
||
autonumber
|
||
actor U as User
|
||
participant H as Trigger (Hotkey/Service/Menu)
|
||
participant C as SelectionCapturer
|
||
participant S as ReadingSession (actor)
|
||
participant T as TextPipeline
|
||
participant Q as SynthesisQueue (actor)
|
||
participant O as OllamaSpeechClient
|
||
participant A as AudioPlayer
|
||
participant UI as ControllerPanel
|
||
|
||
U->>H: ⌥⎋ (default) / Services ▸ Read with Vorleser
|
||
H->>C: capture(frontmostApp)
|
||
C-->>H: CapturedSelection
|
||
H->>S: start(selection, voiceSelection)
|
||
S->>T: makeDocument(selection)
|
||
T-->>S: ReadingDocument (segments)
|
||
S->>UI: show(document), state = preparing(0)
|
||
S->>Q: enqueue(segments[0...prefetch])
|
||
Q->>O: POST /v1/audio/speech (pcm, stream)
|
||
O-->>Q: PCM chunks (streamed)
|
||
Q-->>A: schedule(chunk, segmentID: 0)
|
||
A-->>S: didStart(segmentID: 0)
|
||
S->>UI: state = playing(0)
|
||
A-->>S: didFinish(segmentID: 0)
|
||
S->>Q: enqueue(next beyond window)
|
||
Note over S,Q: Repeat until last segment → finished
|
||
```
|
||
|
||
### 5.2 Trigger capture rules
|
||
|
||
1. Capture **synchronously at trigger time**, before Vorleser shows any window. The controller panel is a non-activating `NSPanel`, so the source app keeps focus and its selection.
|
||
2. The captured text becomes an immutable **snapshot**. Later selection changes in the source app never affect the running session.
|
||
3. A new trigger while a session is active **replaces** the session. The old session is cancelled, its queue drained, and its audio stopped. Then the new one starts.
|
||
4. If capture yields empty text, show `noSelection` in a transient HUD and do not open the controller.
|
||
|
||
---
|
||
|
||
## 6. Text pipeline (`VorleserText`)
|
||
|
||
Input: `CapturedSelection.text`. Output: `ReadingDocument`.
|
||
|
||
### 6.1 Normalisation (faithful)
|
||
|
||
These are purely mechanical transformations. None of them changes wording.
|
||
|
||
| Step | Rule | Why |
|
||
|---|---|---|
|
||
| N1 | Normalise line endings to `\n`; strip `\u{00AD}` (soft hyphen), zero-width spaces, BOM. | PDF and web artefacts |
|
||
| N2 | Join PDF hyphenation: `([a-zäöüß])-\n([a-zäöüß])` → `$1$2` (drop the hyphen). Before an uppercase letter, keep the hyphen and drop only the newline: `-\n([A-ZÄÖÜ])` → `-$1`. Runs before N3. | "Infra-\nstruktur" → "Infrastruktur"; "Nord-\nSüd" → "Nord-Süd" |
|
||
| N3 | Paragraph boundary = `\n\s*\n`. Single `\n` inside a paragraph → space. | PDF line wrapping |
|
||
| N4 | Collapse runs of whitespace to one space; trim. | |
|
||
| N5 | Drop paragraphs that consist only of bullets, digits (page numbers), or markdown markers. | Ollama skips `*`, `#`, bullets anyway |
|
||
| N6 | Optional, setting `expandNumericDates` (default **off**): rewrite `10/23` style dates. Off by default because it alters text. | Ollama reads numeric dates as written |
|
||
|
||
### 6.2 Segmentation
|
||
|
||
- Paragraphs come from N3. Sentences come from `NLTokenizer(unit: .sentence)` with `setLanguage` when detection is confident.
|
||
- **Synthesis unit = one sentence.** It is the navigation unit as well, which keeps "previous/next sentence" exact.
|
||
- Sentence merge: a sentence shorter than 25 characters is merged with the next sentence in the same paragraph. This avoids very short requests with poor prosody, e.g. "Fig. 3." Navigation then treats the merged unit as one sentence.
|
||
- Hard limit: Ollama accepts ≤ 4,096 characters per request. Use a safety cap of **1,500 characters** per segment, which also improves TTFA. Split oversize sentences in this order: `;` `:` `—` `–` `,` and then whitespace. Never split inside a word.
|
||
- Every `Segment` keeps `sourceRange` into `normalisedText` so the controller can show the current sentence.
|
||
|
||
### 6.3 Language detection and model routing
|
||
|
||
- `NLLanguageRecognizer` on the first ~1,000 characters → `SpeechLanguage?` if confidence ≥ 0.6.
|
||
- Model routing (user-editable in Settings):
|
||
|
||
| Language | Default model | Licence |
|
||
|---|---|---|
|
||
| en | `phonon` (31M) | Apache-2.0 |
|
||
| de | `phonon:40m-de` | CC BY-NC 4.0 |
|
||
| fr | `phonon:40m-fr` | CC BY-NC 4.0 |
|
||
| es | `phonon:40m-es` | CC BY-NC 4.0 |
|
||
| pt | `phonon:40m-pt` | CC BY-NC 4.0 |
|
||
| unknown/mixed | user fallback (default `phonon`) | — |
|
||
|
||
- If the routed model is not installed, fall back to the user's fallback model and show a one-time hint with the `ollama pull` command.
|
||
- The controller shows a language/voice menu, so the user can override routing for the current session (this restarts from the current segment).
|
||
|
||
---
|
||
|
||
## 7. Ollama integration (`VorleserOllama`)
|
||
|
||
Full contract: `docs/OLLAMA_SPEECH_API.md`.
|
||
|
||
```swift
|
||
public protocol SpeechSynthesizing: Sendable {
|
||
/// Streams raw PCM16LE mono 24 kHz for one segment.
|
||
func synthesize(text: String, voice: VoiceSelection) -> AsyncThrowingStream<Data, Error>
|
||
}
|
||
|
||
public protocol SpeechModelCatalog: Sendable {
|
||
func serverVersion() async throws -> String
|
||
func installedSpeechModels() async throws -> [SpeechModelInfo] // /api/tags + /api/show capabilities
|
||
func voices(for model: String) async throws -> [String] // /api/show .voices
|
||
}
|
||
```
|
||
|
||
Implementation rules:
|
||
|
||
- Use `URLSession.bytes(for:)` and forward the bytes in chunks of ~4,800 bytes (100 ms of audio). Do not buffer the whole response.
|
||
- Request `response_format: "pcm"`, which avoids parsing the streaming WAV header whose size fields are set to max. Send **only** `model`, `input`, `voice`, `response_format`. Ollama returns 400 for unsupported options such as `speed` and `instructions`.
|
||
- PCM16 framing: a chunk boundary may split a sample. Carry an odd trailing byte over to the next chunk.
|
||
- Cancellation: cancelling the consuming `Task` must cancel the URLSession task (`onTermination` → `task.cancel()`).
|
||
- Timeouts: connect timeout 3 s; no total timeout on streaming bodies; the idle-gap timeout is 15 s without bytes.
|
||
- Map responses to `VorleserError` (see the API doc for the classification table).
|
||
- Cache `/api/show` results per model for the app lifetime. Invalidate them on "Refresh models".
|
||
|
||
---
|
||
|
||
## 8. Synthesis queue and reading session (`VorleserCore`)
|
||
|
||
### 8.1 SynthesisQueue (actor)
|
||
|
||
- **Serial**: one synthesis request at a time. Ollama runs one speech generation per model in practice, so parallel requests only add latency to the segment the user is waiting for.
|
||
- **Prefetch window**: the current segment plus `prefetchAhead` segments (default 2, range 0–5).
|
||
- **Epoch-based cancellation**: every navigation event increments `epoch`. Results tagged with an old epoch are discarded. The in-flight request is cancelled when its segment falls outside the new window.
|
||
- **In-memory PCM cache** keyed by `(segmentID, VoiceSelection)` with an LRU cap of 64 MB. A replay of a recent sentence therefore costs no synthesis. The cache is cleared when the session ends. Disk caching is off by default (§11).
|
||
- Priority: the segment the playhead needs now always pre-empts prefetch work.
|
||
|
||
### 8.2 ReadingSession (actor, `@MainActor`-observable façade)
|
||
|
||
State machine:
|
||
|
||
```mermaid
|
||
stateDiagram-v2
|
||
[*] --> idle
|
||
idle --> preparing: start(selection)
|
||
preparing --> playing: firstAudioScheduled
|
||
preparing --> failed: error
|
||
playing --> paused: pause
|
||
paused --> playing: resume
|
||
playing --> buffering: playerStarved
|
||
buffering --> playing: audioAvailable
|
||
playing --> preparing: seek(segment) [not cached]
|
||
playing --> playing: seek(segment) [cached]
|
||
paused --> paused: seek(segment) (moves cursor, stays paused)
|
||
playing --> finished: lastSegmentDone
|
||
finished --> preparing: restart / seek
|
||
preparing --> idle: stop
|
||
playing --> idle: stop
|
||
paused --> idle: stop
|
||
buffering --> idle: stop
|
||
failed --> idle: dismiss
|
||
failed --> preparing: retry
|
||
```
|
||
|
||
Commands (all idempotent and safe in any state):
|
||
|
||
| Command | Behaviour |
|
||
|---|---|
|
||
| `start(selection)` | Build document, route model, begin at segment 0. Replaces any existing session. |
|
||
| `togglePause` | Pause/resume `AVAudioPlayerNode`. Synthesis prefetch continues while paused. |
|
||
| `previousSentence` | If > 1.5 s into the current segment → restart the current segment, else go to the previous one. (Same convention as music players.) |
|
||
| `nextSentence` | Jump to segment + 1. |
|
||
| `previousParagraph` / `nextParagraph` | Jump to the start of the current/previous paragraph or the next paragraph. Uses the same 1.5 s rule. |
|
||
| `restart` | Segment 0. |
|
||
| `setRate(Float)` | 0.5–2.0, steps of 0.1. Applied live via `AVAudioUnitTimePitch.rate` (pitch preserved). Never sent to Ollama. |
|
||
| `setVoice(VoiceSelection)` | Invalidate cache for the new voice, re-synthesise from the current segment. |
|
||
| `stop` | Cancel all, clear audio, close panel, state = idle. |
|
||
|
||
The UI observes a `@MainActor @Observable final class SessionViewModel`, which mirrors session state and exposes the commands. The actor is the single source of truth.
|
||
|
||
---
|
||
|
||
## 9. Audio pipeline (`VorleserAudio`)
|
||
|
||
Full detail: `docs/AUDIO_PIPELINE.md`.
|
||
|
||
```
|
||
PCM16LE chunks ─▶ Int16→Float32 convert ─▶ AVAudioPCMBuffer (24 kHz mono)
|
||
─▶ AVAudioPlayerNode ─▶ AVAudioUnitTimePitch ─▶ mainMixerNode ─▶ output
|
||
```
|
||
|
||
- One `AVAudioEngine` for the app lifetime. Start it lazily and stop it after 30 s idle to release the audio device.
|
||
- Schedule buffers with `scheduleBuffer(_:completionCallbackType: .dataPlayedBack)`, tagging each with `(epoch, segmentID, isLastChunkOfSegment)`. The last-chunk callback drives `didFinish(segmentID)`.
|
||
- Seek = `playerNode.stop()` (drops scheduled buffers) → bump epoch → schedule from the target segment.
|
||
- Starvation detection: if the last scheduled buffer plays back and the next segment has no audio yet → `buffering`.
|
||
- Position: `playerNode.playerTime(forNodeTime: lastRenderTime)` minus the segment's start sample gives elapsed time in the segment (used for the 1.5 s rule).
|
||
- Handle `AVAudioEngineConfigurationChange` (headphones unplugged, device switch): rebuild the graph and resume from the current segment start.
|
||
|
||
**No word-level sync.** Ollama returns audio only, without timestamps. The controller highlights the *current sentence* in its own text preview. It never touches the source app's UI.
|
||
|
||
---
|
||
|
||
## 10. Selection capture (`VorleserCapture`)
|
||
|
||
Full detail and compatibility matrix: `docs/SELECTION_CAPTURE.md`.
|
||
|
||
```swift
|
||
public protocol SelectionCapturing: Sendable {
|
||
var method: CaptureMethod { get }
|
||
func capture() async throws -> CapturedSelection
|
||
}
|
||
```
|
||
|
||
Three strategies, tried in the order the user configures:
|
||
|
||
| Strategy | Trigger | Permission | Notes |
|
||
|---|---|---|---|
|
||
| **Services** | Services menu / right-click ▸ Services ▸ "Read with Vorleser" (user may bind a shortcut in System Settings) | none | Most robust in Cocoa apps. The app receives the text via pasteboard. It is a separate entry point and does not belong to the hotkey chain. |
|
||
| **Accessibility** (default for hotkey) | Global hotkey | Accessibility | `kAXFocusedUIElementAttribute` → `kAXSelectedTextAttribute`. Set `AXManualAccessibility` on Electron apps. |
|
||
| **Clipboard fallback** (opt-in, default **off**) | Global hotkey, after AX fails | Accessibility (to post events) | Snapshot pasteboard → post ⌘C → wait ≤ 300 ms for `changeCount` → read → **restore** the original pasteboard contents. Disclosed in Settings. |
|
||
|
||
---
|
||
|
||
## 11. Security, privacy, and permissions
|
||
|
||
Full detail: `docs/SECURITY_PRIVACY.md`. Summary of invariants that code review must verify:
|
||
|
||
1. Text is captured **only** in response to an explicit trigger. No polling, no observers on the source application's selection.
|
||
2. Selected text is **never logged**. `os.Logger` messages use `privacy: .private` for any text and log lengths/counts only.
|
||
3. Default endpoint is loopback. A non-loopback endpoint requires the "Allow remote Ollama server" toggle **and** `https://`. Plain `http://` is only accepted for `127.0.0.1`, `localhost`, `::1`.
|
||
4. No disk cache by default. If enabled, the cache lives in `~/Library/Caches/<bundle-id>/audio/` with a size cap and a "Clear cache" button. Keys are SHA-256 of `(model, voice, text)`. Text is not stored in clear.
|
||
5. No telemetry, no network calls other than the configured Ollama endpoint.
|
||
6. Clipboard fallback restores the user's pasteboard and is off by default.
|
||
|
||
---
|
||
|
||
## 12. User interface
|
||
|
||
| Surface | Implementation | Contents |
|
||
|---|---|---|
|
||
| Menu-bar extra | `MenuBarExtra` (`.menu` style) | Read selection, Pause/Resume, Stop, current voice, Settings…, Quit |
|
||
| Controller panel | `NSPanel` with `.nonactivatingPanel`, `.hudWindow`, `level = .floating`, hosting a SwiftUI view | Transport buttons (⏮¶ ⏮ ⏯ ⏭ ⏭¶ ⏹), speed slider, voice menu, current-sentence preview, progress "12 / 48", state/error line |
|
||
| Settings | SwiftUI `Settings` scene with tabs | General (hotkey, launch at login), Speech (endpoint, model routing, voices, speed, prefetch), Capture (strategy order, clipboard fallback), Privacy (cache, remote endpoint) |
|
||
| Onboarding | First-run window | Checks: Ollama reachable + version, speech model installed, Accessibility trusted. Each check has a fix button. |
|
||
| HUD | Transient panel, 1.5 s | "No text selected", "Ollama not running", … |
|
||
|
||
Panel keyboard shortcuts (active when the panel is key; global hotkeys only for start/stop):
|
||
|
||
| Key | Action |
|
||
|---|---|
|
||
| Space | Play/Pause |
|
||
| ← / → | Previous / next sentence |
|
||
| ⌥← / ⌥→ | Previous / next paragraph |
|
||
| − / = | Speed −0.1 / +0.1 |
|
||
| Esc | Stop and close |
|
||
|
||
Default global hotkeys (user-configurable): **⌥⎋ Read selection**, **⌥⇧⎋ Stop**.
|
||
|
||
Accessibility of Vorleser itself: all controls have `accessibilityLabel`s, VoiceOver can operate the panel, and the panel respects Reduce Motion and Increase Contrast.
|
||
|
||
---
|
||
|
||
## 13. Configuration
|
||
|
||
`AppSettings` (Codable, stored in `UserDefaults` under a single key, versioned):
|
||
|
||
| Key | Type | Default |
|
||
|---|---|---|
|
||
| `endpoint` | URL | `http://127.0.0.1:11434` |
|
||
| `allowRemoteEndpoint` | Bool | false |
|
||
| `modelRouting` | `[SpeechLanguage: String]` | table in §6.3 |
|
||
| `fallbackModel` | String | `phonon` |
|
||
| `voicePerModel` | `[String: String]` | `["phonon": "default"]` |
|
||
| `playbackRate` | Float | 1.0 |
|
||
| `prefetchAhead` | Int | 2 |
|
||
| `captureOrder` | `[CaptureMethod]` | `[.accessibility, .clipboard]` |
|
||
| `clipboardFallbackEnabled` | Bool | false |
|
||
| `diskCacheEnabled` | Bool | false |
|
||
| `diskCacheLimitMB` | Int | 256 |
|
||
| `showCurrentSentence` | Bool | true |
|
||
| `expandNumericDates` | Bool | false |
|
||
| `keepModelWarm` | Bool | true (local endpoint only) |
|
||
| `settingsVersion` | Int | 1 |
|
||
|
||
---
|
||
|
||
## 14. Build, distribution, and platform
|
||
|
||
| Item | Decision |
|
||
|---|---|
|
||
| Minimum OS | macOS 14.0 (Sonoma) — `@Observable`, `MenuBarExtra`, `SMAppService` |
|
||
| Architecture | arm64 only |
|
||
| Toolchain | Xcode 16+ / Swift 6 language mode, strict concurrency |
|
||
| Project generation | XcodeGen from `project.yml`; `.xcodeproj` is generated and git-ignored |
|
||
| App type | Agent app (`LSUIElement = YES`), no Dock icon |
|
||
| Sandbox | **Off**. Accessibility capture of other apps' selections is incompatible with App Sandbox (ADR-003). |
|
||
| Hardened runtime | On |
|
||
| Signing | Development: "Sign to Run Locally". Release: Developer ID + notarisation (`scripts/release.sh`, milestone M9). |
|
||
| ATS | `NSAllowsLocalNetworking = YES` (permits `http://localhost`); remote endpoints must be HTTPS. |
|
||
| Launch at login | `SMAppService.mainApp` |
|
||
|
||
---
|
||
|
||
## 15. Performance budgets
|
||
|
||
| Metric | Budget | How measured |
|
||
|---|---|---|
|
||
| Trigger → captured text | ≤ 50 ms (AX), ≤ 350 ms (clipboard fallback) | `os_signpost` interval `capture` |
|
||
| Trigger → first audible sample (warm model) | ≤ 1.0 s | signpost `ttfa` |
|
||
| Seek to cached segment | ≤ 100 ms | signpost `seek` |
|
||
| Seek to uncached segment | ≤ TTFA | signpost `seek` |
|
||
| Playback gaps between segments | 0 underruns in a 10-minute read (prefetch 2) | starvation counter |
|
||
| Idle CPU | ~0% · Idle RSS ≤ 60 MB | Activity Monitor / `footprint` |
|
||
| Memory during session | ≤ 64 MB PCM cache + overhead | LRU cap |
|
||
|
||
Segment 0 of a session is requested **before** the controller panel finishes appearing.
|
||
|
||
---
|
||
|
||
## 16. Observability
|
||
|
||
- `os.Logger(subsystem: "<bundle-id>", category: …)` with categories `capture`, `ollama`, `queue`, `audio`, `session`, `ui`.
|
||
- `OSSignposter` intervals for `capture`, `ttfa`, `synthesis(segment)`, `seek`.
|
||
- A hidden "Diagnostics" section in Settings (⌥-click) shows: Ollama version, installed speech models, last 20 error codes (no text), TTFA of the last 10 sessions, AX trust status, frontmost app bundle ID at last capture.
|
||
|
||
---
|
||
|
||
## 17. Risks and mitigations
|
||
|
||
| Risk | Impact | Mitigation |
|
||
|---|---|---|
|
||
| Apps that do not expose `AXSelectedText` (some Electron, Java, canvas-based editors, some PDF views) | Hotkey fails in those apps | Services entry point; opt-in clipboard fallback; documented compatibility matrix; clear `captureUnsupported` message naming the app |
|
||
| `/api/show` voice schema is undocumented in detail | Discovery breaks | Defensive decoder (strings or objects with `name`); fixtures captured from the real server; fall back to `["default"]` |
|
||
| 40M models are CC BY-NC 4.0 | Commercial distribution restrictions | Show the licence next to each model in Settings; default English route uses Apache-2.0 `phonon`; no models are bundled with the app |
|
||
| Phonon/Ollama API changes (new release line) | Breakage | All HTTP in one module; contract tests against fixtures; `scripts/smoke-ollama.sh` before each release |
|
||
| Prosody discontinuities at sentence boundaries | Less natural audio | 25-char merge rule; evaluate a paragraph-level synthesis option in M9 (ADR candidate) |
|
||
| Ollama keeps model unloaded → slow first request | TTFA miss | On app launch and on session start, issue a 1-word warm-up request with the routed model when the user enables "Keep model warm" (default on, local endpoint only) |
|
||
|
||
---
|
||
|
||
## 18. Glossary
|
||
|
||
- **Segment**: the unit for synthesis and navigation (≈ one sentence).
|
||
- **Epoch**: monotonic counter, bumped on every navigation/voice change, used to discard stale audio.
|
||
- **TTFA**: time to first audio.
|
||
- **Routing**: mapping detected language → Ollama model tag.
|