chore: initial commit of Vorleser kit
This commit is contained in:
commit
cf3f2678e1
62 files changed
+2350
No files matched your search
@@ -0,0 +1,547 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,96 @@
|
||||
# Audio pipeline
|
||||
|
||||
Module: `VorleserAudio`. It depends only on AVFoundation. It knows nothing about Ollama or text.
|
||||
|
||||
## Interface
|
||||
|
||||
```swift
|
||||
public struct AudioChunk: Sendable {
|
||||
public let epoch: UInt64
|
||||
public let segmentID: Int
|
||||
public let samples: [Float] // mono, 24 kHz, already converted from Int16
|
||||
public let isLastOfSegment: Bool
|
||||
}
|
||||
|
||||
public enum AudioEvent: Sendable {
|
||||
case segmentStarted(epoch: UInt64, segmentID: Int)
|
||||
case segmentFinished(epoch: UInt64, segmentID: Int)
|
||||
case starved(epoch: UInt64) // nothing left scheduled, not finished
|
||||
case routeChanged // engine reconfigured; session should re-seek
|
||||
case failed(String)
|
||||
}
|
||||
|
||||
public protocol AudioPlaying: AnyObject, Sendable {
|
||||
var events: AsyncStream<AudioEvent> { get }
|
||||
func schedule(_ chunk: AudioChunk)
|
||||
func play() throws
|
||||
func pause()
|
||||
func stopAndFlush() // drops everything scheduled
|
||||
func setRate(_ rate: Float) // 0.5 ... 2.0
|
||||
func elapsedInCurrentSegment() -> TimeInterval?
|
||||
}
|
||||
```
|
||||
|
||||
A `FakeAudioPlayer` that records calls and emits events on demand must exist in the test target from M3 onwards. `ReadingSession` tests run against it.
|
||||
|
||||
## Graph
|
||||
|
||||
```
|
||||
AVAudioPlayerNode ──▶ AVAudioUnitTimePitch ──▶ engine.mainMixerNode ──▶ outputNode
|
||||
format: Float32, 24_000 Hz, 1 ch, non-interleaved
|
||||
```
|
||||
|
||||
- Connect player → timePitch with the 24 kHz mono format. The mixer handles sample-rate conversion to the device rate.
|
||||
- `timePitch.rate = playbackRate` (0.5–2.0). `timePitch.pitch = 0`. Rate changes apply live without rescheduling.
|
||||
- `timePitch.overlap` default (8). If the speech sounds phasey at 1.5–2.0×, increase it and evaluate.
|
||||
|
||||
## PCM conversion
|
||||
|
||||
```swift
|
||||
// data: PCM16LE bytes, even length guaranteed by the client
|
||||
let count = data.count / 2
|
||||
var floats = [Float](repeating: 0, count: count)
|
||||
data.withUnsafeBytes { raw in
|
||||
let src = raw.bindMemory(to: Int16.self)
|
||||
for i in 0..<count { floats[i] = Float(Int16(littleEndian: src[i])) / 32768.0 }
|
||||
}
|
||||
```
|
||||
|
||||
Use `vDSP.convertElements` + `vDSP.multiply` (Accelerate) once the scalar version is covered by tests.
|
||||
|
||||
## Scheduling
|
||||
|
||||
- Wrap each chunk in an `AVAudioPCMBuffer` (`frameCapacity = samples.count`).
|
||||
- `player.scheduleBuffer(buf, completionCallbackType: .dataPlayedBack) { _ in … }`.
|
||||
- Keep a counter `scheduledFramesAhead` (incremented on schedule, decremented in callback). When it reaches 0 and the last callback was not `isLastOfSegment` of the final segment → emit `.starved`.
|
||||
- Emit `.segmentStarted` when the **first** chunk of a segment is scheduled while the player is idle, or when the preceding segment's last chunk finishes. Emit `.segmentFinished` on the `isLastOfSegment` callback.
|
||||
- Ignore callbacks whose `epoch` ≠ current epoch. `stopAndFlush()` triggers callbacks for dropped buffers, and these must not be reported as finished.
|
||||
|
||||
## Elapsed time
|
||||
|
||||
Track `segmentStartSampleTime` when a segment starts:
|
||||
|
||||
```swift
|
||||
guard let nodeTime = player.lastRenderTime,
|
||||
let t = player.playerTime(forNodeTime: nodeTime) else { return nil }
|
||||
return Double(t.sampleTime - segmentStartSampleTime) / t.sampleRate
|
||||
```
|
||||
|
||||
Note: `playerTime` is in the player's own timeline and is **not** affected by timePitch rate. The value represents content time. That is the right input for the "1.5 s → restart current sentence" rule.
|
||||
|
||||
## Engine lifecycle
|
||||
|
||||
- Create the engine once. Call `engine.prepare()` at launch. Call `start()` on the first `play()`.
|
||||
- Idle timer: 30 s after `stopAndFlush()` or finish → `engine.stop()`, which releases the device and lets the system sleep.
|
||||
- Observe `.AVAudioEngineConfigurationChange` → rebuild connections, `engine.start()`, emit `.routeChanged`. The session responds by seeking to the current segment start (cached PCM makes this instant).
|
||||
|
||||
## Edge cases to test
|
||||
|
||||
| Case | Expected |
|
||||
|---|---|
|
||||
| Pause during preparing | Stays paused when first audio arrives. Audio is scheduled but not played. |
|
||||
| Seek while a chunk callback is in flight | Old-epoch callback ignored, no spurious `segmentFinished` |
|
||||
| Rate change while paused | Applied on resume |
|
||||
| Headphones unplugged mid-sentence | `.routeChanged` → restart current segment |
|
||||
| Zero-length segment audio (server returned 0 bytes) | Treat as finished immediately. Log at `.error`. |
|
||||
| Very long segment (1,500 chars ≈ 90 s audio) | Streams. Memory bounded by chunk scheduling. |
|
||||
@@ -0,0 +1,42 @@
|
||||
# Coding standards
|
||||
|
||||
## Language and concurrency
|
||||
|
||||
- Swift 6 language mode, **complete** strict concurrency. Zero warnings policy: `-warnings-as-errors` in release CI.
|
||||
- Model shared mutable state as an `actor` (`SynthesisQueue`, `ReadingSession`). UI-facing types are `@MainActor`.
|
||||
- No `DispatchQueue.main.async` in new code. Use `@MainActor` / `MainActor.run`. Exception: AX calls run on a dedicated serial queue, bridged with `withCheckedThrowingContinuation`.
|
||||
- No `@unchecked Sendable` without a comment explaining the invariant. AVFoundation wrappers are the expected exception.
|
||||
- Never block an actor on I/O. Every network and AX call is async and cancellable.
|
||||
- Respect cancellation: check `Task.isCancelled` / `try Task.checkCancellation()` in loops over chunks/segments.
|
||||
|
||||
## Structure
|
||||
|
||||
- One primary type per file. The file name matches the type.
|
||||
- Protocols at module boundaries (`SpeechSynthesizing`, `SpeechModelCatalog`, `AudioPlaying`, `SelectionCapturing`, `PasteboardProtocol`, `AXClient`). Concrete types are `final class` or `struct`.
|
||||
- The composition root (`AppEnvironment`) is the only place that instantiates concrete implementations.
|
||||
- No singletons except Apple-provided ones (`NSWorkspace.shared`, `NSPasteboard.general`). Wrap even these behind protocols where tests need them.
|
||||
- `public` only for API used across modules.
|
||||
|
||||
## Errors and logging
|
||||
|
||||
- Throw `VorleserError` across module boundaries. Internal errors may be module-specific, but they are mapped at the boundary.
|
||||
- `Logger` per category (see ARCHITECTURE §16). Never interpolate selected text without `privacy: .private`; prefer counts.
|
||||
- `fatalError` / `preconditionFailure` only for programmer errors that tests would catch.
|
||||
|
||||
## UI
|
||||
|
||||
- SwiftUI for views; AppKit for `NSPanel`, services, the status item if needed.
|
||||
- Views have no logic beyond formatting. They bind to `SessionViewModel` / `SettingsViewModel`.
|
||||
- Every interactive control has an `accessibilityLabel` and a keyboard path.
|
||||
- Strings: use `String(localized:)` from the start. English is the base, with German (`de`) as a second localisation in M8.
|
||||
|
||||
## Style
|
||||
|
||||
- SwiftFormat default rules with 4-space indent and 120-column limit (`.swiftformat`).
|
||||
- SwiftLint with `.swiftlint.yml`. Warnings are fixed, not suppressed. A disable requires a reason comment.
|
||||
- Doc comments (`///`) on all public API.
|
||||
|
||||
## Git
|
||||
|
||||
- Small commits, one task per branch is optional. Conventional commit messages: `feat(ollama): stream PCM chunks (T1.4)`.
|
||||
- Never commit `Vorleser.xcodeproj`, `.build/`, `DerivedData/`, or audio files outside the test targets' `Fixtures/` folders.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Architecture decision records
|
||||
|
||||
Format: one section per ADR. Status: Proposed · Accepted · Superseded by ADR-n. Add new ADRs at the end with `/adr <title>`.
|
||||
|
||||
---
|
||||
|
||||
## ADR-001 — Ollama as the speech backend via `/v1/audio/speech`
|
||||
Status: Accepted
|
||||
|
||||
Context: The product's core value is local, private narration. Ollama ships Gradium Phonon with an OpenAI-compatible streaming speech endpoint on Apple Silicon.
|
||||
Decision: Use Ollama over HTTP. Do not embed MLX or the model in-process.
|
||||
Consequences: The user must install Ollama and pull a model, so onboarding must handle this. The app stays small and avoids redistributing CC BY-NC models. Swapping in another OpenAI-compatible TTS server later remains possible, but the speech client must not assume OpenAI-only parameters.
|
||||
|
||||
## ADR-002 — Raw PCM response format
|
||||
Status: Accepted
|
||||
|
||||
Context: The streaming WAV header from Ollama has max-value size fields, and AVFoundation file APIs expect complete files.
|
||||
Decision: Request `response_format: "pcm"` (16-bit LE, mono, 24 kHz) and schedule `AVAudioPCMBuffer`s ourselves.
|
||||
Consequences: Simple streaming with no header parsing. The format assumptions live in one place (`OllamaSpeechClient` + `PCMConverter`) and are covered by fixtures.
|
||||
|
||||
## ADR-003 — Non-sandboxed, Developer ID distribution
|
||||
Status: Accepted
|
||||
|
||||
Context: Reading another app's selection through `kAXSelectedTextAttribute` requires Accessibility trust, which App Sandbox does not allow for this use.
|
||||
Decision: Ship without App Sandbox, with Hardened Runtime, signed with Developer ID and notarised. No Mac App Store in v1.
|
||||
Consequences: Wider capability, and with it more responsibility. SECURITY_PRIVACY.md invariants are mandatory and checked in `make verify`. A future sandboxed "Services-only" edition remains possible.
|
||||
|
||||
## ADR-004 — Sentence as the synthesis and navigation unit
|
||||
Status: Accepted
|
||||
|
||||
Context: Users need precise replay/skip. Ollama provides no timestamps, so sub-request positions cannot be mapped.
|
||||
Decision: Synthesise one sentence (merged if < 25 chars, split if > 1,500 chars) per request.
|
||||
Consequences: Exact sentence navigation and low TTFA. Prosody may break slightly at sentence boundaries. Revisit in M9 with a paragraph-mode option (ADR candidate).
|
||||
|
||||
## ADR-005 — Playback speed in the audio layer
|
||||
Status: Accepted
|
||||
|
||||
Context: Ollama returns 400 for unsupported options such as `speed`.
|
||||
Decision: Apply speed via `AVAudioUnitTimePitch.rate` (pitch-preserving). Never send speed to the server.
|
||||
Consequences: Live speed changes, and cached audio stays valid across speeds.
|
||||
|
||||
## ADR-006 — XcodeGen + SwiftPM package for agent-friendly development
|
||||
Status: Accepted
|
||||
|
||||
Context: Coding agents edit `.pbxproj` files unreliably.
|
||||
Decision: All logic lives in a SwiftPM package (`swift build` / `swift test` from the CLI). The app target is defined in `project.yml` and generated with XcodeGen. `.xcodeproj` is git-ignored.
|
||||
Consequences: Agents can build and test without Xcode UI. Adding files needs no project edits.
|
||||
|
||||
## ADR-007 — Accessibility capture first, clipboard fallback opt-in
|
||||
Status: Accepted
|
||||
|
||||
Context: Simulating ⌘C works more broadly but mutates the user's clipboard and can trigger app-specific copy behaviour.
|
||||
Decision: The hotkey uses AX first. Clipboard fallback is off by default and, when enabled, always restores the pasteboard. The Services menu is a separate entry point.
|
||||
Consequences: Some apps (certain Electron/canvas views) will not work with the hotkey by default. The error message points to Services or to enabling the fallback.
|
||||
@@ -0,0 +1,110 @@
|
||||
# Implementation plan
|
||||
|
||||
Work milestone by milestone, task by task. Each task is sized for one OpenCode session, about 100–400 lines of change. A task is done only when its acceptance criteria pass **and** `make verify` is green. Track status in `docs/PROGRESS.md`.
|
||||
|
||||
Conventions: `T<milestone>.<n>`. "AC" = acceptance criteria. "Verify" = commands that must succeed.
|
||||
|
||||
---
|
||||
|
||||
## M0 — Scaffold and tooling
|
||||
|
||||
Goal: an empty but correctly configured project that builds, tests, and launches as a menu-bar agent.
|
||||
|
||||
| Task | Description | AC |
|
||||
|---|---|---|
|
||||
| T0.1 | The kit ships `Packages/VorleserKit/Package.swift` with placeholder sources and tests. Verify it resolves and builds, fix any toolchain issues, and replace placeholder enums as modules gain real types. | `swift build --package-path Packages/VorleserKit` and `make test` succeed. |
|
||||
| T0.2 | Complete the `App/` sources (stubs shipped): `VorleserApp` with a `MenuBarExtra` showing "Vorleser" + Quit; `AppDelegate` stub; `Info.plist` (LSUIElement, NSServices placeholder, ATS local networking); entitlements (no sandbox). | `make app` builds and the menu-bar icon appears, with no Dock icon. |
|
||||
| T0.3 | Validate the shipped `project.yml` (XcodeGen) and `make generate`; set your own bundle ID prefix. | `xcodegen generate` produces a project that builds in Xcode and via `xcodebuild`. |
|
||||
| T0.4 | Run the shipped `scripts/verify.sh`, `.swiftformat`, `.swiftlint.yml`; fix issues so the gate is green on the scaffold. | `make verify` runs end-to-end. |
|
||||
| T0.5 | Add `os.Logger` categories helper in `VorleserCore` (`Log.capture`, `Log.ollama`, …) and an `OSSignposter` wrapper. | Unit test compiles and uses it. |
|
||||
|
||||
## M1 — Ollama client
|
||||
|
||||
Goal: synthesise speech and discover models/voices headlessly.
|
||||
|
||||
| Task | Description | AC |
|
||||
|---|---|---|
|
||||
| T1.1 | Run `scripts/capture-fixtures.sh` against a local Ollama; commit `Packages/VorleserKit/Tests/VorleserOllamaTests/Fixtures/*`. Update `docs/OLLAMA_SPEECH_API.md` VERIFY items with observed shapes. | Fixtures exist. Doc updated. |
|
||||
| T1.2 | `OllamaHTTPClient`: base URL, JSON encode/decode, error body parsing, `EndpointPolicy` (SECURITY_PRIVACY SP-5). | `EndpointPolicyTests`, `ErrorMappingTests` green against fixtures. |
|
||||
| T1.3 | `OllamaCatalog: SpeechModelCatalog`: `/api/version`, `/api/tags`, `/api/show` (defensive voice decoding, `capabilities` contains `speech`), per-model cache. | Tests for both voice shapes, missing `voices` → `["default"]`, version comparison. |
|
||||
| T1.4 | `OllamaSpeechClient: SpeechSynthesizing` streaming PCM via `URLSession.bytes`, odd-byte carry, 100 ms chunking, idle timeout, cancellation propagation. | `URLProtocol` stub tests: chunk boundaries, odd bytes, cancel mid-stream cancels the task, 400 unknown voice mapping. |
|
||||
| T1.5 | `vorleser-cli`: `voices [--model]`, `models`, `speak --model --voice --text|--file --out file.pcm|--play`. `--play` uses `afplay` on a temp WAV that the CLI writes itself. | Manual: `swift run vorleser-cli speak --text "Hallo" --model phonon:40m-de --play` is audible. |
|
||||
|
||||
## M2 — Text pipeline
|
||||
|
||||
| Task | Description | AC |
|
||||
|---|---|---|
|
||||
| T2.1 | `TextNormaliser` implementing N1–N5 (ARCHITECTURE §6.1). | Table-driven tests including PDF hyphenation (DE + EN), soft hyphens, page-number paragraphs, single-newline joins. |
|
||||
| T2.2 | `Segmenter`: paragraphs → `NLTokenizer` sentences, 25-char merge, 1,500-char cap with the split order, `sourceRange`. | Tests: abbreviations ("z. B.", "e.g.", "Fig. 3"), decimals ("3.5 GHz"), very long sentence split, no word split, ranges map back to text. |
|
||||
| T2.3 | `LanguageDetector` + `ModelRouter` (routing table, fallback, `latest` normalisation). | Tests: EN, DE, mixed, short text → nil → fallback. |
|
||||
| T2.4 | `DocumentBuilder` composing T2.1–T2.3 into `ReadingDocument`. Add `vorleser-cli segment --file` to print segments. | Snapshot-style test on a sample article in `Packages/VorleserKit/Tests/VorleserTextTests/Fixtures/`. |
|
||||
|
||||
## M3 — Audio
|
||||
|
||||
| Task | Description | AC |
|
||||
|---|---|---|
|
||||
| T3.1 | `PCMConverter` (Int16LE → Float32), scalar + Accelerate path. | Tests: known sample values, endianness, empty input. |
|
||||
| T3.2 | `EngineAudioPlayer: AudioPlaying` (graph, scheduling, epochs, events, elapsed time, rate). | `vorleser-cli speak --play-engine` plays through the engine. Unit tests for the epoch-filter logic, factored into a pure `ScheduleLedger`. |
|
||||
| T3.3 | Engine lifecycle: lazy start, 30 s idle stop, configuration-change rebuild. | Manual test: unplug headphones mid-sentence → resumes. |
|
||||
| T3.4 | `FakeAudioPlayer` in a test-support target (`VorleserTestSupport`). | Used by M4 tests. |
|
||||
|
||||
## M4 — Synthesis queue and session
|
||||
|
||||
| Task | Description | AC |
|
||||
|---|---|---|
|
||||
| T4.1 | `PCMCache` (LRU by bytes, 64 MB cap, key `(segmentID, VoiceSelection)`). | Eviction tests. |
|
||||
| T4.2 | `SynthesisQueue` actor: serial, prefetch window, epoch cancellation, priority for the playhead segment. | Tests with a fake synthesiser with controllable latency: seek cancels in-flight work outside the window; no duplicate requests; cache hit → no request. |
|
||||
| T4.3 | `ReadingSession` actor implementing the state machine and commands (ARCHITECTURE §8.2) including the 1.5 s rule. | State-transition tests for every edge in the diagram, using fakes. |
|
||||
| T4.4 | `SessionViewModel` (`@MainActor @Observable`) mirroring state, progress, current sentence text. | Tests on the main actor. |
|
||||
| T4.5 | `vorleser-cli read --file` with interactive keys (space, ←/→, q) in raw TTY mode. | Manual: full navigation works headlessly. **This is the main integration checkpoint before UI work.** |
|
||||
|
||||
## M5 — App shell, settings, discovery
|
||||
|
||||
| Task | Description | AC |
|
||||
|---|---|---|
|
||||
| T5.1 | `AppSettings` model + `SettingsStore` (UserDefaults, versioned, migration hook). | Round-trip and default tests. |
|
||||
| T5.2 | Composition root `AppEnvironment` wiring client, catalog, queue, player, session. | App launches. `Read clipboard text` debug menu item reads the clipboard via the session. |
|
||||
| T5.3 | Settings scene: General / Speech / Capture / Privacy tabs. Speech tab lists installed speech models with licence badges and voices from discovery, plus a "Test voice" button. | Manual. Voice list matches `ollama show`. |
|
||||
| T5.4 | Model warm-up (`keepModelWarm`) and "Refresh models". | Signpost shows a lower TTFA on the first session after warm-up. |
|
||||
| T5.5 | Launch at login via `SMAppService.mainApp`. | Toggle reflects the real status. |
|
||||
|
||||
## M6 — Selection capture
|
||||
|
||||
| Task | Description | AC |
|
||||
|---|---|---|
|
||||
| T6.1 | `AccessibilityPermission` helper (trusted check, prompt, deep link). | Onboarding can show the status. |
|
||||
| T6.2 | `AXSelectionCapturer` per SELECTION_CAPTURE.md (focus, selected text, range fallback, parent walk, Electron flags, timeout, background queue). | Works in TextEdit, Safari, Preview (manual). Unit-test the pure parts behind an `AXClient` protocol. |
|
||||
| T6.3 | Global hotkeys with `KeyboardShortcuts` (Read selection ⌥⎋, Stop ⌥⇧⎋) + recorder in Settings. | Hotkey triggers capture → session. |
|
||||
| T6.4 | Services provider (`readSelection`) + Info.plist `NSServices`. | Right-click ▸ Services ▸ "Read with Vorleser" works in TextEdit and Safari. |
|
||||
| T6.5 | `ClipboardSelectionCapturer` (opt-in) with full pasteboard restore and transient type. `CaptureChain`. | Tests with an injected `PasteboardProtocol`. Manual test in VS Code. |
|
||||
| T6.6 | Menu-bar "Read selection" uses the previously frontmost app. | Works from the menu while Safari has the selection. |
|
||||
|
||||
## M7 — Controller panel
|
||||
|
||||
| Task | Description | AC |
|
||||
|---|---|---|
|
||||
| T7.1 | Non-activating floating `NSPanel` host (`ControllerPanel`), positioned near the top-right of the active screen, draggable, position remembered. | Source app keeps key focus while the panel is visible. |
|
||||
| T7.2 | SwiftUI `ControllerView`: transport buttons, speed slider, voice menu, progress, state/error line, current sentence (toggleable). | All controls work. VoiceOver labels present. |
|
||||
| T7.3 | Panel keyboard shortcuts (Space, ←/→, ⌥←/⌥→, −/=, Esc) when the panel is key. Clicking the panel makes it key without activating the app (`becomesKeyOnlyIfNeeded`). | Manual. |
|
||||
| T7.4 | HUD for transient messages. | `noSelection` shows a HUD and no panel. |
|
||||
| T7.5 | Menu-bar menu mirrors the session (Pause/Resume, Stop, current voice). | Manual. |
|
||||
|
||||
## M8 — Onboarding, errors, privacy
|
||||
|
||||
| Task | Description | AC |
|
||||
|---|---|---|
|
||||
| T8.1 | Onboarding window with three checks + fix actions (open Ollama download page, copy `ollama pull phonon`, open Accessibility settings, re-check). | Shown on first launch and from the menu. |
|
||||
| T8.2 | `VorleserError.userMessage` / `recoveryAction` for every case. Panel and HUD use them. | Exhaustive switch test. |
|
||||
| T8.3 | Optional disk cache (SP-7) with size cap and "Clear cache". | `DiskAudioCacheTests`. |
|
||||
| T8.4 | Remote endpoint toggle + HTTPS enforcement in the UI. | UI blocks invalid configurations. |
|
||||
| T8.5 | Privacy audit: grep checks for SP-1…SP-10 added to `scripts/verify.sh`. | `make verify` fails on violations. |
|
||||
|
||||
## M9 — Hardening and release
|
||||
|
||||
| Task | Description | AC |
|
||||
|---|---|---|
|
||||
| T9.1 | Fill the compatibility matrix in SELECTION_CAPTURE.md. Fix the top three failures. | Matrix complete. |
|
||||
| T9.2 | Performance pass against ARCHITECTURE §15 budgets using signposts. Record results in `docs/PERFORMANCE.md`. | Budgets met or ADR explaining the deviation. |
|
||||
| T9.3 | Diagnostics section (⌥-click in Settings). | Shows the listed fields, no text. |
|
||||
| T9.4 | `scripts/release.sh`: archive, Developer ID sign, notarise (`notarytool`), staple, DMG. | Notarised build launches on a clean Mac. |
|
||||
| T9.5 | README for end users: install, permissions, Services shortcut, troubleshooting (incl. `pbs -update`). | Reviewed. |
|
||||
@@ -0,0 +1,53 @@
|
||||
# Kickoff prompts for OpenCode
|
||||
|
||||
## First session (paste as-is)
|
||||
|
||||
```text
|
||||
You are building Vorleser, a macOS 14+ Apple Silicon menu-bar app that reads the user's current text
|
||||
selection aloud via a local Ollama speech model with sentence/paragraph playback control.
|
||||
|
||||
1. Read AGENTS.md, then docs/ARCHITECTURE.md (skim §1–§5 closely, the rest as an index),
|
||||
docs/IMPLEMENTATION_PLAN.md (M0 and M1), and docs/PROGRESS.md.
|
||||
2. Run `make verify` on the shipped scaffold and report the result. Fix toolchain or scaffold issues
|
||||
(T0.1–T0.4) without changing the architecture. If something in the scaffold contradicts the docs,
|
||||
tell me before changing either.
|
||||
3. Then propose your plan for M0 completion and T1.1–T1.2, using the @architect subagent.
|
||||
Do not start M1 implementation until I confirm the plan.
|
||||
```
|
||||
|
||||
## Every following session
|
||||
|
||||
```text
|
||||
/next
|
||||
```
|
||||
|
||||
or, to target a specific task:
|
||||
|
||||
```text
|
||||
/task T2.2
|
||||
```
|
||||
|
||||
## Integration checkpoint (after M4)
|
||||
|
||||
```text
|
||||
Run `swift run --package-path Packages/VorleserKit vorleser-cli read --file Packages/VorleserKit/Tests/VorleserTextTests/Fixtures/en-article.txt`
|
||||
and walk me through a manual test of: start, pause/resume, previous sentence within/after 1.5 s,
|
||||
next paragraph, speed change, stop. Then list any deviation from ARCHITECTURE §8.2.
|
||||
```
|
||||
|
||||
## Before UI work (M5+)
|
||||
|
||||
```text
|
||||
/status
|
||||
Then confirm that the headless CLI reader works end-to-end and that all M1–M4 acceptance criteria are met.
|
||||
List anything that would make the UI milestones harder if left as is.
|
||||
```
|
||||
|
||||
## When a macOS-only feature needs testing
|
||||
|
||||
```text
|
||||
/manual-test global hotkey capture in Safari, Preview and VS Code
|
||||
```
|
||||
|
||||
Report results back in the same session ("Safari ✅, Preview ⚠️ hyphenation not joined, VS Code ❌ no AX text").
|
||||
The agent updates the compatibility matrix and proposes fixes.
|
||||
@@ -0,0 +1,138 @@
|
||||
# Ollama speech API contract
|
||||
|
||||
Sources: Ollama speech documentation (https://docs.ollama.com/capabilities/speech), Ollama blog "Speech models" (https://ollama.com/blog/speech-models), Gradium Phonon voice catalogue.
|
||||
|
||||
This file is the contract `VorleserOllama` implements. Anything marked **VERIFY** is not fully specified in the public docs. Confirm it against a real server with `scripts/capture-fixtures.sh` before you rely on it, and update this file with the observed behaviour.
|
||||
|
||||
## Server requirements
|
||||
|
||||
- Ollama **≥ 0.40.9** (documented minimum for speech). Check with `GET /api/version` → `{"version":"0.40.x"}`. Compare it semantically and raise `ollamaTooOld` if it is lower.
|
||||
- Apple Silicon Mac. Linux/Windows support was announced as forthcoming.
|
||||
- Default base URL: `http://127.0.0.1:11434`.
|
||||
|
||||
## 1. Synthesize speech
|
||||
|
||||
`POST /v1/audio/speech` (OpenAI-compatible)
|
||||
|
||||
Request: send exactly these fields and nothing else.
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "phonon",
|
||||
"input": "Text to speak, at most 4096 characters.",
|
||||
"voice": "default",
|
||||
"response_format": "pcm"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Rule |
|
||||
|---|---|
|
||||
| `model` | Installed speech model tag, e.g. `phonon`, `phonon:40m-de`. |
|
||||
| `input` | ≤ 4,096 characters. Vorleser caps at 1,500 (see ARCHITECTURE §6.2). Must be non-empty after trimming. |
|
||||
| `voice` | A name from `/api/show` `voices`, or `default`. Case- and accent-insensitive. |
|
||||
| `response_format` | `pcm` (Vorleser default) or `wav`. Others → 400. |
|
||||
|
||||
Do **not** send `speed`, `instructions`, or other OpenAI fields. Unsupported options return **400**; the server does not ignore them.
|
||||
|
||||
Response (`200`):
|
||||
|
||||
| Format | Body |
|
||||
|---|---|
|
||||
| `pcm` | Raw signed 16-bit little-endian, mono, 24,000 Hz, no header. Streamed during generation. |
|
||||
| `wav` | 16-bit mono 24 kHz WAV. The header is written first with size fields set to their maximum value (length unknown), so you cannot trust RIFF/data sizes. |
|
||||
|
||||
Streaming: the body arrives incrementally. Playback can start on the first chunk. Consume it with `URLSession.bytes(for:)`.
|
||||
|
||||
Byte math: 24,000 samples/s × 2 bytes = **48,000 bytes/s**. A 100 ms chunk = 4,800 bytes.
|
||||
|
||||
### Text handling done by the server
|
||||
|
||||
- Prices, numbers, symbols, e-mail addresses, and URLs are spelled out (e.g. `$4.59` → "4 dollars and 59 cents").
|
||||
- Times and numeric dates are read as written. Write dates out for natural reading.
|
||||
- Emoji, bullet characters, and markdown markers (`*`, `#`) are skipped.
|
||||
|
||||
Consequence for Vorleser: do not pre-expand numbers/symbols. Keep the text faithful.
|
||||
|
||||
## 2. Model information and voices
|
||||
|
||||
`POST /api/show`
|
||||
|
||||
```json
|
||||
{ "model": "phonon" }
|
||||
```
|
||||
|
||||
Relevant response fields:
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `capabilities` | Array of strings. Speech models include `"speech"`. |
|
||||
| `voices` | Model-specific voice list. **VERIFY element shape**: it is either an array of strings or an array of objects with a `name` field. Decode both. |
|
||||
|
||||
Defensive decoding:
|
||||
|
||||
```swift
|
||||
enum VoiceEntry: Decodable {
|
||||
case name(String)
|
||||
case object(name: String)
|
||||
init(from d: Decoder) throws {
|
||||
let c = try d.singleValueContainer()
|
||||
if let s = try? c.decode(String.self) { self = .name(s); return }
|
||||
struct O: Decodable { let name: String }
|
||||
self = .object(name: try c.decode(O.self).name)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If `voices` is missing or empty, treat the list as `["default"]`.
|
||||
|
||||
CLI equivalent for humans: `ollama show phonon`.
|
||||
|
||||
## 3. Installed models
|
||||
|
||||
`GET /api/tags` → `{"models":[{"name":"phonon:latest", "model":"phonon:latest", …}]}`
|
||||
|
||||
Find the speech models: for each tag whose name starts with `phonon`, call `/api/show` and keep it if `capabilities` contains `speech`. Probing every installed model is expensive, so only probe others on "Refresh models" in Settings. Normalise `phonon:latest` ↔ `phonon` when you compare against routing settings.
|
||||
|
||||
## 4. Error classification
|
||||
|
||||
| Condition | HTTP / transport | Map to |
|
||||
|---|---|---|
|
||||
| Connection refused / host unreachable | `URLError.cannotConnectToHost`, `.cannotFindHost`, `.timedOut` (connect) | `ollamaUnreachable` |
|
||||
| Model not installed | **VERIFY**: typically `404` with body containing `not found` | `modelNotInstalled(model)` |
|
||||
| Unknown voice | `400`, body lists the available voices | `unknownVoice(voice, available)`. Parse names out of the message best-effort; fall back to re-querying `/api/show`. |
|
||||
| Model is not a speech model | `400` | `modelNotSpeech` (if body mentions speech/capability), else `badRequest` |
|
||||
| Unsupported option / format | `400` | `badRequest(message)`. This means a bug in Vorleser, so log at `.fault`. |
|
||||
| Other 4xx/5xx | status | `server(status, message)` |
|
||||
| Stream stalls > 15 s | idle timer | `server(status: 0, message: "stalled")`. Retry once. |
|
||||
| Task cancelled | `CancellationError` / `URLError.cancelled` | `cancelled`. This is **not** an error for UI purposes. |
|
||||
|
||||
Error bodies from Ollama are JSON `{"error":"…"}`. Fall back to the raw text.
|
||||
|
||||
## 5. Warm-up
|
||||
|
||||
To reduce the first-request latency, send a one-word synthesis (`"input": "Ready."`) with the routed model and discard the audio. Do this on app launch (if `keepModelWarm`) and when the routed model changes. Only for loopback endpoints.
|
||||
|
||||
## 6. Fixtures
|
||||
|
||||
`scripts/capture-fixtures.sh` records the following into `Packages/VorleserKit/Tests/VorleserOllamaTests/Fixtures/`:
|
||||
|
||||
- `version.json`, `tags.json`
|
||||
- `show-<model>.json` for each installed phonon model
|
||||
- `speech-<model>-short.pcm` (one sentence) and the HTTP status/headers
|
||||
- `error-unknown-voice.json`, `error-missing-model.json`, `error-unsupported-option.json`
|
||||
|
||||
Unit tests use these through a `URLProtocol` stub. Keep fixtures small (< 200 KB each).
|
||||
|
||||
## 7. Known models (for defaults and Settings hints only — never hard-code as "available")
|
||||
|
||||
| Tag | Language | Params | Licence |
|
||||
|---|---|---|---|
|
||||
| `phonon` / `phonon:31m-en` | English | 31M | Apache-2.0 |
|
||||
| `phonon:40m-en` | English | 40M | CC BY-NC 4.0 |
|
||||
| `phonon:40m-de` | German | 40M | CC BY-NC 4.0 |
|
||||
| `phonon:40m-fr` | French | 40M | CC BY-NC 4.0 |
|
||||
| `phonon:40m-es` | Spanish | 40M | CC BY-NC 4.0 |
|
||||
| `phonon:40m-pt` | Portuguese | 40M | CC BY-NC 4.0 |
|
||||
| `phonon:40m-multilingual` | en, de, fr, es, pt | 40M | CC BY-NC 4.0 |
|
||||
|
||||
The upstream Gradium catalogue contains 102 voices (EN-US, EN-UK, EN characters, DE, FR, ES-ES, ES-MX, PT-BR). What a given Ollama model exposes is defined **only** by its `/api/show` `voices` field.
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
# Vorleser — Product requirements (v1)
|
||||
|
||||
## Problem
|
||||
|
||||
Long technical texts such as papers, analyses, and documentation demand sustained attention. Research on reading while listening shows a small pooled benefit (Hedges' g ≈ 0.18). That benefit disappears when reading is self-paced and the reader has no control over the audio. Existing text-to-speech either requires copying text into a separate app, uses cloud services, or offers coarse control.
|
||||
|
||||
## Product statement
|
||||
|
||||
Select text anywhere on the Mac, press one shortcut, and hear it read aloud by a local Ollama speech model, with the controls a careful reader needs: pause, replay sentence, skip paragraph, adjust speed. The original document stays in front of you.
|
||||
|
||||
## Persona
|
||||
|
||||
A technical professional who reads demanding English and German material on an Apple Silicon Mac. They already run Ollama locally and care about privacy, fidelity, and keyboard-driven workflows.
|
||||
|
||||
## User stories and acceptance criteria
|
||||
|
||||
| ID | Story | Acceptance criteria |
|
||||
|---|---|---|
|
||||
| US-1 | As a reader, I select text in Safari and press ⌥⎋ to hear it. | Audio starts ≤ 1.0 s (warm model). Safari keeps focus. The controller panel appears without stealing focus. |
|
||||
| US-2 | As a reader, I pause to look at a figure and resume later. | Space in the panel, or the menu-bar Pause item, pauses within 100 ms. Resume continues from the exact sample. |
|
||||
| US-3 | As a reader, I replay a difficult sentence. | ← restarts the current sentence if > 1.5 s in, else goes to the previous one. Replay of a cached sentence starts ≤ 100 ms. |
|
||||
| US-4 | As a reader, I skip to the next paragraph. | ⌥→ jumps to the first sentence of the next paragraph. Pending synthesis for skipped sentences is cancelled. |
|
||||
| US-5 | As a reader, I change speed without changing pitch. | Speed 0.5–2.0× in 0.1 steps. The change applies live. The setting persists. |
|
||||
| US-6 | As a German reader, I select German text and hear a German voice. | Language is detected. The `de` route (`phonon:40m-de`) is used if installed. Otherwise the fallback model is used and a hint shows `ollama pull phonon:40m-de`. |
|
||||
| US-7 | As a reader, I choose a voice per model. | Settings lists only voices reported by `/api/show` for each installed speech model. The choice persists. |
|
||||
| US-8 | As a reader, I select new text while something is playing and press ⌥⎋. | The old session stops and the new session starts from the new selection. |
|
||||
| US-9 | As a reader, I use the right-click Services menu in an app where the hotkey does not work. | "Read with Vorleser" appears for text selections and starts a session. |
|
||||
| US-10 | As a first-time user, I am guided through setup. | Onboarding checks Ollama reachability and version, the speech model, and Accessibility trust. Each failing check offers a one-click fix or a copyable command. |
|
||||
| US-11 | As a privacy-conscious user, I know nothing leaves my Mac. | Default endpoint is loopback. A remote endpoint requires an explicit toggle and HTTPS. No logs contain text. No disk cache unless enabled. |
|
||||
| US-12 | As a reader, I see which sentence is being read. | The panel shows the current sentence and progress "n / N". This can be toggled off. |
|
||||
| US-13 | As a reader, I get a clear message when something fails. | Each `VorleserError` maps to a human message plus an action. No raw error strings. |
|
||||
| US-14 | As a reader, I want Vorleser available at login. | "Launch at login" toggle via `SMAppService`. |
|
||||
|
||||
## Out of scope (v1)
|
||||
|
||||
Word-level highlighting in the source app. Summarisation or rewriting. A document library. Export to MP3. Mac App Store distribution. Intel Macs.
|
||||
|
||||
## Candidate v2 features
|
||||
|
||||
- Export selection to an audio file (M4A) with metadata, for the Substack narration workflow.
|
||||
- Adapted-narration mode (LLM transforms tables/code into prose) with a visible "adapted" badge.
|
||||
- Paragraph-level synthesis option for smoother prosody.
|
||||
- Pronunciation dictionary (per-term replacements, e.g. "EuroHPC" → "Euro H P C").
|
||||
- Shortcuts.app / AppIntents: "Read text with Vorleser".
|
||||
@@ -0,0 +1,77 @@
|
||||
# Progress
|
||||
|
||||
The agent updates this file at the end of every task: check the box, add the date, add one line of notes (deviations, follow-ups). Do not delete history.
|
||||
|
||||
Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
|
||||
|
||||
## M0 — Scaffold and tooling
|
||||
- [ ] T0.1 Package.swift + module placeholders
|
||||
- [ ] T0.2 App sources, Info.plist, entitlements
|
||||
- [ ] T0.3 project.yml / XcodeGen
|
||||
- [ ] T0.4 verify script + format/lint
|
||||
- [ ] T0.5 Logging + signposts
|
||||
|
||||
## M1 — Ollama client
|
||||
- [ ] T1.1 Capture fixtures, resolve VERIFY items
|
||||
- [ ] T1.2 HTTP client, endpoint policy, error mapping
|
||||
- [ ] T1.3 Catalog (version, tags, show, voices)
|
||||
- [ ] T1.4 Streaming speech client
|
||||
- [ ] T1.5 vorleser-cli (models, voices, speak)
|
||||
|
||||
## M2 — Text pipeline
|
||||
- [ ] T2.1 Normaliser
|
||||
- [ ] T2.2 Segmenter
|
||||
- [ ] T2.3 Language detection + routing
|
||||
- [ ] T2.4 DocumentBuilder + `segment` CLI
|
||||
|
||||
## M3 — Audio
|
||||
- [ ] T3.1 PCM converter
|
||||
- [ ] T3.2 Engine player
|
||||
- [ ] T3.3 Engine lifecycle
|
||||
- [ ] T3.4 FakeAudioPlayer
|
||||
|
||||
## M4 — Queue and session
|
||||
- [ ] T4.1 PCM cache
|
||||
- [ ] T4.2 SynthesisQueue
|
||||
- [ ] T4.3 ReadingSession state machine
|
||||
- [ ] T4.4 SessionViewModel
|
||||
- [ ] T4.5 Interactive `read` CLI (integration checkpoint)
|
||||
|
||||
## M5 — App shell
|
||||
- [ ] T5.1 Settings model/store
|
||||
- [ ] T5.2 Composition root
|
||||
- [ ] T5.3 Settings UI
|
||||
- [ ] T5.4 Warm-up + refresh
|
||||
- [ ] T5.5 Launch at login
|
||||
|
||||
## M6 — Selection capture
|
||||
- [ ] T6.1 Accessibility permission helper
|
||||
- [ ] T6.2 AX capturer
|
||||
- [ ] T6.3 Global hotkeys
|
||||
- [ ] T6.4 Services provider
|
||||
- [ ] T6.5 Clipboard fallback + chain
|
||||
- [ ] T6.6 Menu-bar capture
|
||||
|
||||
## M7 — Controller panel
|
||||
- [ ] T7.1 Non-activating panel
|
||||
- [ ] T7.2 Controller view
|
||||
- [ ] T7.3 Panel shortcuts
|
||||
- [ ] T7.4 HUD
|
||||
- [ ] T7.5 Menu mirrors session
|
||||
|
||||
## M8 — Onboarding, errors, privacy
|
||||
- [ ] T8.1 Onboarding
|
||||
- [ ] T8.2 Error messages
|
||||
- [ ] T8.3 Disk cache
|
||||
- [ ] T8.4 Remote endpoint UI
|
||||
- [ ] T8.5 Privacy audit in verify
|
||||
|
||||
## M9 — Hardening and release
|
||||
- [ ] T9.1 Compatibility matrix
|
||||
- [ ] T9.2 Performance pass
|
||||
- [ ] T9.3 Diagnostics
|
||||
- [ ] T9.4 Release script
|
||||
- [ ] T9.5 End-user README
|
||||
|
||||
## Notes log
|
||||
<!-- YYYY-MM-DD · T#.# · note -->
|
||||
@@ -0,0 +1,42 @@
|
||||
# Security and privacy requirements
|
||||
|
||||
These are hard requirements. The `swift-reviewer` agent checks every change against this list.
|
||||
|
||||
## Data handling
|
||||
|
||||
| ID | Requirement | How to verify |
|
||||
|---|---|---|
|
||||
| SP-1 | Selected text is captured only after an explicit trigger (hotkey, Services, menu command). | No AX observers (`AXObserverCreate`) on other apps; no timers reading selections. Grep the code for `AXObserver`. |
|
||||
| SP-2 | Selected text never appears in logs. | All `Logger` interpolations of text use `privacy: .private`; prefer logging `text.count`. Grep for `\(text` / `\(segment.text` without `.private`. |
|
||||
| SP-3 | No telemetry, analytics, crash-reporting SDKs. | `Package.resolved` contains only allowed deps. |
|
||||
| SP-4 | Network requests only to the configured Ollama endpoint. | All networking goes through `OllamaHTTPClient`. Grep for `URLSession` usage outside `VorleserOllama`. |
|
||||
| SP-5 | Default endpoint is loopback. Non-loopback requires `allowRemoteEndpoint == true` and an `https` scheme. | Unit test `EndpointPolicyTests`. |
|
||||
| SP-6 | No disk persistence of text or audio by default. | Disk cache off by default; settings test. |
|
||||
| SP-7 | Disk cache (if enabled): stored under Caches, keyed by SHA-256, size-capped, user-clearable, no clear-text text. | `DiskAudioCacheTests` |
|
||||
| SP-8 | Clipboard fallback is off by default, disclosed in UI, and always restores the prior pasteboard (all items, all types). | `ClipboardCapturerTests` with an injected pasteboard abstraction |
|
||||
| SP-9 | The session's in-memory text and PCM are released on `stop` and on replacement by a new session. | Test that the cache count is 0 after stop |
|
||||
| SP-10 | The app never requests permissions it does not use: Accessibility only. No Input Monitoring, Screen Recording, Microphone. | Info.plist has no usage strings for unused permissions |
|
||||
|
||||
## Entitlements and runtime
|
||||
|
||||
- App Sandbox: **disabled** (ADR-003). Hardened Runtime: **enabled**.
|
||||
- No `com.apple.security.cs.allow-unsigned-executable-memory`, `disable-library-validation`, or other hardened-runtime exceptions.
|
||||
- ATS: `NSAllowsLocalNetworking = true` only. No `NSAllowsArbitraryLoads`.
|
||||
|
||||
## Endpoint policy (pseudo-code)
|
||||
|
||||
```swift
|
||||
func validate(_ url: URL, allowRemote: Bool) throws {
|
||||
let host = url.host?.lowercased() ?? ""
|
||||
let isLoopback = ["127.0.0.1", "localhost", "::1"].contains(host)
|
||||
if isLoopback { guard ["http", "https"].contains(url.scheme) else { throw … }; return }
|
||||
guard allowRemote else { throw EndpointError.remoteNotAllowed }
|
||||
guard url.scheme == "https" else { throw EndpointError.remoteRequiresHTTPS }
|
||||
}
|
||||
```
|
||||
|
||||
## Licensing notice (product, not code)
|
||||
|
||||
- Vorleser does not bundle or redistribute any model or voice.
|
||||
- Settings shows the licence per model: `phonon` (31M EN) Apache-2.0; `phonon:40m-*` CC BY-NC 4.0.
|
||||
- If Vorleser is ever distributed commercially, the default routing for non-English languages must be reviewed. Record the decision in an ADR.
|
||||
@@ -0,0 +1,131 @@
|
||||
# Selection capture
|
||||
|
||||
Module: `VorleserCapture`. This is the only module that may import `ApplicationServices` and use AX APIs.
|
||||
|
||||
## Principles
|
||||
|
||||
1. Capture only on an explicit user trigger.
|
||||
2. Capture before any Vorleser window is shown or activated. The controller is a non-activating panel.
|
||||
3. Return an immutable snapshot (`CapturedSelection`).
|
||||
4. Never read more than the selection: no full-document `kAXValueAttribute` reads as a fallback.
|
||||
5. When capture fails, the error names the method and app (`captureUnsupported(app:)`) so the user knows to use the Services menu or enable clipboard fallback.
|
||||
|
||||
## Entry points
|
||||
|
||||
| Entry point | Path into the app | Capture strategy |
|
||||
|---|---|---|
|
||||
| Global hotkey "Read selection" (default ⌥⎋) | `KeyboardShortcuts.onKeyUp` | `CaptureChain` (AX, then clipboard if enabled) |
|
||||
| Services menu "Read with Vorleser" | `NSApp.servicesProvider` → `readSelection(_:userData:error:)` | Pasteboard provided by the system |
|
||||
| Menu-bar "Read selection" | Menu item | Same as hotkey. **Note**: opening the menu-bar menu does not activate Vorleser, but capture still has to target the previously frontmost app. Record `NSWorkspace.shared.frontmostApplication` on `menuWillOpen`. |
|
||||
|
||||
## Strategy 1: Accessibility (`AXSelectionCapturer`)
|
||||
|
||||
Permission: Accessibility. Check with `AXIsProcessTrusted()`. Prompt with `AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt: true])` from onboarding only and never on the hotkey path. Deep-link: `x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility`.
|
||||
|
||||
Algorithm:
|
||||
|
||||
```text
|
||||
1. app = NSWorkspace.shared.frontmostApplication (skip if it is Vorleser itself)
|
||||
2. appElement = AXUIElementCreateApplication(app.pid)
|
||||
3. If app is Electron/Chromium-based (bundle ID list or presence of "AXManualAccessibility"):
|
||||
AXUIElementSetAttributeValue(appElement, "AXManualAccessibility", true)
|
||||
(Chromium: "AXEnhancedUserInterface" true is an alternative; set it only for the
|
||||
duration of the capture and then restore it, because it can affect window animations.)
|
||||
4. focused = AXUIElementCopyAttributeValue(systemWide, kAXFocusedUIElementAttribute)
|
||||
?? AXUIElementCopyAttributeValue(appElement, kAXFocusedUIElementAttribute)
|
||||
5. text = AXUIElementCopyAttributeValue(focused, kAXSelectedTextAttribute) as? String
|
||||
6. If text is nil/empty:
|
||||
range = kAXSelectedTextRangeAttribute → if non-empty, use
|
||||
kAXStringForRangeParameterizedAttribute(range) on focused element
|
||||
7. If still empty: walk up to 3 parents (kAXParentAttribute) repeating 5–6 (web areas often
|
||||
hold the selection on an ancestor "AXWebArea").
|
||||
8. Return text or throw .noSelection / .captureUnsupported(app.localizedName)
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- Messaging timeout: `AXUIElementSetMessagingTimeout(appElement, 0.25)`. Hung apps must not freeze the hotkey path.
|
||||
- Run AX calls off the main thread, on a dedicated serial `DispatchQueue` wrapped in an async function. AX is thread-safe per element.
|
||||
- Return `kAXErrorAPIDisabled` / `kAXErrorNotImplemented` / `kAXErrorCannotComplete` as `captureUnsupported`. `AXIsProcessTrusted() == false` → `accessibilityNotTrusted`.
|
||||
|
||||
## Strategy 2: Services (`ServicesSelectionReceiver`)
|
||||
|
||||
Info.plist (`NSServices`):
|
||||
|
||||
```xml
|
||||
<key>NSServices</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>NSMenuItem</key>
|
||||
<dict><key>default</key><string>Read with Vorleser</string></dict>
|
||||
<key>NSMessage</key><string>readSelection</string>
|
||||
<key>NSPortName</key><string>Vorleser</string>
|
||||
<key>NSSendTypes</key>
|
||||
<array><string>public.utf8-plain-text</string><string>NSStringPboardType</string></array>
|
||||
<key>NSRequiredContext</key><dict/>
|
||||
</dict>
|
||||
</array>
|
||||
```
|
||||
|
||||
AppDelegate:
|
||||
|
||||
```swift
|
||||
NSApp.servicesProvider = servicesHandler
|
||||
NSUpdateDynamicServices()
|
||||
|
||||
@objc func readSelection(_ pboard: NSPasteboard, userData: String?, error: AutoreleasingUnsafeMutablePointer<NSString?>) {
|
||||
guard let text = pboard.string(forType: .string), !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
|
||||
// build CapturedSelection(method: .service) and start session
|
||||
}
|
||||
```
|
||||
|
||||
Users can bind a shortcut under System Settings ▸ Keyboard ▸ Keyboard Shortcuts ▸ Services ▸ Text. Onboarding should mention this. Services may need a logout/login or `/System/Library/CoreServices/pbs -update` after first install. Document this under Troubleshooting.
|
||||
|
||||
## Strategy 3: Clipboard fallback (`ClipboardSelectionCapturer`, opt-in)
|
||||
|
||||
Disabled by default. Settings must disclose: "Vorleser will briefly copy your selection and then restore your clipboard."
|
||||
|
||||
```text
|
||||
1. snapshot = all items of NSPasteboard.general (all types, as Data), changeCount c0
|
||||
2. Post ⌘C via CGEvent (keyDown/keyUp with .maskCommand) to HID tap
|
||||
3. Poll changeCount every 10 ms up to 300 ms
|
||||
4. If changed → text = string(forType: .string)
|
||||
5. Restore snapshot (clearContents + write all items), regardless of success
|
||||
6. If unchanged → throw captureUnsupported
|
||||
```
|
||||
|
||||
Requires Accessibility trust to post events. Mark the restore with `NSPasteboard.general.setString("", forType: .init("org.nspasteboard.TransientType"))` so clipboard managers ignore the transient copy (nspasteboard.org convention).
|
||||
|
||||
## Capture chain
|
||||
|
||||
```swift
|
||||
public struct CaptureChain: SelectionCapturing {
|
||||
let strategies: [SelectionCapturing] // built from settings.captureOrder
|
||||
// Try in order. Stop at the first non-empty result.
|
||||
// Errors: if all fail, throw the most informative one
|
||||
// (accessibilityNotTrusted > captureUnsupported > noSelection).
|
||||
}
|
||||
```
|
||||
|
||||
## Compatibility matrix (fill in during M6/M9 testing)
|
||||
|
||||
Test each with: plain paragraph, multi-paragraph, selection containing a hyphenated line break (PDF), and an empty selection.
|
||||
|
||||
| App | Bundle ID | AX hotkey | Services | Clipboard | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| Safari | com.apple.Safari | ☐ | ☐ | ☐ | |
|
||||
| Google Chrome | com.google.Chrome | ☐ | ☐ | ☐ | AXEnhancedUserInterface |
|
||||
| Firefox | org.mozilla.firefox | ☐ | ☐ | ☐ | |
|
||||
| Preview (PDF) | com.apple.Preview | ☐ | ☐ | ☐ | Hyphenation join |
|
||||
| Adobe Acrobat | com.adobe.Acrobat.Pro | ☐ | ☐ | ☐ | |
|
||||
| Pages | com.apple.iWork.Pages | ☐ | ☐ | ☐ | |
|
||||
| Microsoft Word | com.microsoft.Word | ☐ | ☐ | ☐ | |
|
||||
| Mail | com.apple.mail | ☐ | ☐ | ☐ | |
|
||||
| Notes | com.apple.Notes | ☐ | ☐ | ☐ | |
|
||||
| TextEdit | com.apple.TextEdit | ☐ | ☐ | ☐ | Baseline |
|
||||
| Visual Studio Code | com.microsoft.VSCode | ☐ | ☐ | ☐ | Electron, AXManualAccessibility |
|
||||
| Obsidian | md.obsidian | ☐ | ☐ | ☐ | Electron |
|
||||
| Slack | com.tinyspeck.slackmacgap | ☐ | ☐ | ☐ | Electron |
|
||||
| Terminal | com.apple.Terminal | ☐ | ☐ | ☐ | |
|
||||
|
||||
Legend: ✅ works · ⚠️ partial (describe) · ❌ unsupported.
|
||||
@@ -0,0 +1,43 @@
|
||||
# Testing strategy
|
||||
|
||||
Framework: **Swift Testing** (`import Testing`, `@Test`, `#expect`) for all package tests. XCTest only where Swift Testing lacks support, e.g. performance `measure`.
|
||||
|
||||
## Layers
|
||||
|
||||
| Layer | Scope | Where | Runs in `make verify` |
|
||||
|---|---|---|---|
|
||||
| Unit | Pure logic: normaliser, segmenter, router, PCM conversion, schedule ledger, cache, endpoint policy, error mapping, settings | `Packages/VorleserKit/Tests/*Tests` | yes |
|
||||
| Contract | Ollama client against recorded fixtures through `URLProtocol` stubs | `Packages/VorleserKit/Tests/VorleserOllamaTests` | yes |
|
||||
| Component | `SynthesisQueue` + `ReadingSession` with `FakeSynthesizer` and `FakeAudioPlayer` (deterministic clocks) | `Packages/VorleserKit/Tests/VorleserCoreTests` | yes |
|
||||
| Live integration | Real Ollama on localhost, opt-in via `VORLESER_LIVE=1` | `Packages/VorleserKit/Tests/VorleserLiveTests` (tagged `.live`) | no; `make live-test` |
|
||||
| Manual | Capture compatibility matrix, audio routing, UI | checklists in `docs/SELECTION_CAPTURE.md` and below | no |
|
||||
|
||||
## Rules
|
||||
|
||||
- Every bug fix starts with a failing test, unless it is only reproducible manually. In that case, add a manual checklist item.
|
||||
- No test may depend on network, audio hardware, or Accessibility trust unless it is tagged `.live` or `.manual`.
|
||||
- Time-dependent logic (idle timeouts, the 1.5 s rule, starvation) takes an injected `Clock` (`any Clock<Duration>`). Tests use a manual test clock.
|
||||
- Fakes live in the `VorleserTestSupport` target: `FakeSynthesizer` (scripted chunks, latency, errors), `FakeAudioPlayer`, `FakeCatalog`, `FakePasteboard`, `FakeAXClient`.
|
||||
- Fixtures live inside their test target (SwiftPM resources must sit within the target): `Packages/VorleserKit/Tests/VorleserOllamaTests/Fixtures/` (recorded), `Packages/VorleserKit/Tests/VorleserTextTests/Fixtures/` (EN article and German PDF-copy samples with hyphenation). Load them with `Bundle.module`.
|
||||
|
||||
## Required test cases (minimum)
|
||||
|
||||
Segmenter:
|
||||
- `"z. B. die CPU"` is not split after "z." · `"3.5 GHz"` stays intact · `"Fig. 3 shows…"` merges · `"Infra-\nstruktur"` → `"Infrastruktur"` · `"Nord-\nSüd"` stays hyphenated (uppercase rule) · a 5,000-char sentence → segments ≤ 1,500 chars, no word split.
|
||||
|
||||
Ollama client:
|
||||
- Odd-length chunk boundary preserves samples · cancellation stops the URL task · 400 unknown voice → `unknownVoice` with a parsed list · connection refused → `ollamaUnreachable` · request body contains only the 4 allowed keys.
|
||||
|
||||
Session:
|
||||
- start → preparing → playing · pause during preparing remains paused when audio arrives · previousSentence at 0.8 s → previous segment, at 2.0 s → same segment · nextParagraph cancels in-flight synthesis for skipped segments · setVoice re-synthesises from the current segment · new start replaces the session and clears the cache · last segment finished → finished.
|
||||
|
||||
## Manual release checklist
|
||||
|
||||
- [ ] First launch: onboarding shows correct states with Ollama stopped, model missing, AX untrusted.
|
||||
- [ ] ⌥⎋ in Safari, Preview, and Word reads the selection. The source app keeps focus.
|
||||
- [ ] Services menu works in TextEdit.
|
||||
- [ ] Speed 0.5 / 1.0 / 2.0 sound correct (pitch preserved).
|
||||
- [ ] Headphone unplug/replug during playback.
|
||||
- [ ] A 10-minute read has no audible gaps (prefetch 2).
|
||||
- [ ] Console.app shows no selected text in Vorleser logs.
|
||||
- [ ] Quit during playback leaves no orphaned audio or network task.
|
||||
Reference in new issue
Block a user