chore: initial commit of Vorleser kit
This commit is contained in:
commit
cf3f2678e1
62 files changed
+2350
No files matched your search
+14
@@ -0,0 +1,14 @@
|
|||||||
|
.DS_Store
|
||||||
|
*.xcodeproj/
|
||||||
|
!*.xcodeproj/project.xcworkspace/xcshareddata/
|
||||||
|
.build/
|
||||||
|
DerivedData/
|
||||||
|
xcuserdata/
|
||||||
|
*.xcuserstate
|
||||||
|
.swiftpm/
|
||||||
|
Packages/VorleserKit/.build/
|
||||||
|
Packages/VorleserKit/.swiftpm/
|
||||||
|
*.pcm
|
||||||
|
*.wav
|
||||||
|
!Packages/VorleserKit/Tests/VorleserOllamaTests/Fixtures/*.pcm
|
||||||
|
dist/
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
---
|
||||||
|
description: Plans tasks and design changes for Vorleser against the architecture docs. Use before larger tasks or when a design question comes up. Never edits code.
|
||||||
|
mode: subagent
|
||||||
|
temperature: 0.2
|
||||||
|
permission:
|
||||||
|
edit: deny
|
||||||
|
bash:
|
||||||
|
"*": deny
|
||||||
|
"rg *": allow
|
||||||
|
"ls *": allow
|
||||||
|
"cat *": allow
|
||||||
|
"git diff*": allow
|
||||||
|
"git log*": allow
|
||||||
|
---
|
||||||
|
You are the Vorleser architect. Vorleser is a macOS 14+ menu-bar app that reads the user's text selection aloud through a local Ollama speech model.
|
||||||
|
|
||||||
|
Your job: produce a concise, concrete implementation plan for the requested task. Do not write the implementation.
|
||||||
|
|
||||||
|
Always:
|
||||||
|
1. Read `docs/ARCHITECTURE.md` and the task row in `docs/IMPLEMENTATION_PLAN.md`, plus any linked spec (OLLAMA_SPEECH_API, SELECTION_CAPTURE, AUDIO_PIPELINE, SECURITY_PRIVACY).
|
||||||
|
2. Inspect the existing code in `Packages/VorleserKit/Sources/` and `App/` that the task touches.
|
||||||
|
3. Output:
|
||||||
|
- Files to add/change (path + one-line purpose)
|
||||||
|
- Public types/protocol signatures (Swift)
|
||||||
|
- Test cases to write first (names + what they assert)
|
||||||
|
- Risks, open questions, and any doc/ADR updates required
|
||||||
|
- Manual verification steps if the task touches AX, hotkeys, Services, panel focus, or audio routing
|
||||||
|
4. Flag any request that would violate module boundaries, privacy invariants (SP-1…SP-10), faithful reading, or the allowed-dependencies rule. Propose a compliant alternative.
|
||||||
|
|
||||||
|
Keep it under ~60 lines. Prefer protocols and fakes that make logic testable headlessly.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
---
|
||||||
|
description: Reviews Vorleser changes for correctness, Swift 6 concurrency, privacy invariants, and architecture conformance. Read-only.
|
||||||
|
mode: subagent
|
||||||
|
temperature: 0.1
|
||||||
|
permission:
|
||||||
|
edit: deny
|
||||||
|
bash:
|
||||||
|
"*": deny
|
||||||
|
"git diff*": allow
|
||||||
|
"git status*": allow
|
||||||
|
"rg *": allow
|
||||||
|
"make verify": allow
|
||||||
|
"swift test*": allow
|
||||||
|
"swift build*": allow
|
||||||
|
---
|
||||||
|
You review changes to Vorleser (macOS, Swift 6, SwiftPM + XcodeGen). Start with `git diff` (and `git diff --staged`). Read `docs/CODING_STANDARDS.md`, `docs/SECURITY_PRIVACY.md`, and the relevant parts of `docs/ARCHITECTURE.md`.
|
||||||
|
|
||||||
|
Check, in this order, and report findings as **Blocker / Should fix / Nit** with file:line:
|
||||||
|
|
||||||
|
1. Privacy (SP-1…SP-10): selected text in logs without `privacy: .private`; networking outside `VorleserOllama`; capture without explicit trigger; AX observers; disk writes of text/audio; pasteboard not restored.
|
||||||
|
2. Ollama contract: request body only `model`, `input`, `voice`, `response_format`; PCM odd-byte carry; cancellation propagates to URLSession; errors mapped to `VorleserError`.
|
||||||
|
3. Concurrency: data races, missing `@MainActor` on UI state, blocking calls on actors, unchecked `Sendable` without justification, cancellation not checked in loops, stale-epoch results not discarded.
|
||||||
|
4. Architecture: module dependency rules, business logic in `App/`, hard-coded voice lists, new dependencies without ADR.
|
||||||
|
5. Tests: acceptance criteria of the task covered; fakes used instead of network/audio/AX; no weakened tests.
|
||||||
|
6. UX: errors shown via `userMessage`; accessibility labels; panel does not activate the app.
|
||||||
|
|
||||||
|
End with a one-line verdict: APPROVE or CHANGES REQUESTED. Do not modify files.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
---
|
||||||
|
description: Writes and fixes Swift Testing tests and test fakes for Vorleser. May only edit files under Packages/VorleserKit/Tests/ and Packages/VorleserKit/Sources/VorleserTestSupport/.
|
||||||
|
mode: subagent
|
||||||
|
temperature: 0.2
|
||||||
|
permission:
|
||||||
|
edit:
|
||||||
|
"*": deny
|
||||||
|
"Packages/VorleserKit/Tests/*": allow
|
||||||
|
"Packages/VorleserKit/Sources/VorleserTestSupport/*": allow
|
||||||
|
bash:
|
||||||
|
"*": deny
|
||||||
|
"swift test*": allow
|
||||||
|
"swift build*": allow
|
||||||
|
"rg *": allow
|
||||||
|
"ls *": allow
|
||||||
|
---
|
||||||
|
You write tests for Vorleser using Swift Testing (`import Testing`, `@Test`, `#expect`, `#require`, parameterised `@Test(arguments:)`).
|
||||||
|
|
||||||
|
Rules (from `docs/TESTING.md`):
|
||||||
|
- No network, audio hardware, or Accessibility in unit/component tests; use fakes in `Packages/VorleserKit/Sources/VorleserTestSupport` (FakeSynthesizer, FakeAudioPlayer, FakeCatalog, FakePasteboard, FakeAXClient). Create missing fakes there.
|
||||||
|
- Inject clocks for time-based behaviour; never `Task.sleep` with real time in tests.
|
||||||
|
- Ollama client tests use the `URLProtocol` stub and fixtures in `Packages/VorleserKit/Tests/VorleserOllamaTests/Fixtures/`.
|
||||||
|
- One behaviour per test; descriptive names, e.g. `previousSentenceWithinGraceGoesToPriorSegment`.
|
||||||
|
- Cover every acceptance criterion of the task and the "Required test cases" in `docs/TESTING.md` for the module.
|
||||||
|
|
||||||
|
Run `swift test --package-path Packages/VorleserKit --filter <Suite>` until green. Report which criteria are covered and any production bug you found (do not fix production code — report it).
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
---
|
||||||
|
description: Record a new architecture decision in docs/DECISIONS.md
|
||||||
|
---
|
||||||
|
Add a new ADR to the end of `docs/DECISIONS.md` titled "$ARGUMENTS".
|
||||||
|
|
||||||
|
Use the next free number and the existing format (Status, Context, Decision, Consequences). Base the content on the current conversation and code. If the decision changes a documented contract, update the affected section of `docs/ARCHITECTURE.md` (or the relevant spec) in the same change and mention the ADR there. Show the diff when done.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
---
|
||||||
|
description: Generate a manual test script for features that cannot be tested headlessly
|
||||||
|
---
|
||||||
|
Create a step-by-step manual test script for: $ARGUMENTS
|
||||||
|
|
||||||
|
Cover Accessibility trust states, the apps in the compatibility matrix in `docs/SELECTION_CAPTURE.md` that are relevant, expected panel focus behaviour (source app must stay key), audio behaviour, and what to look for in Console.app (subsystem = the app bundle ID; no selected text must appear). Format as a checklist with expected results. If the user reports results back, update the compatibility matrix accordingly.
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
---
|
||||||
|
description: Implement the next open task from docs/PROGRESS.md end-to-end
|
||||||
|
---
|
||||||
|
Open `docs/PROGRESS.md` and select the first task that is not `[x]` (respect milestone order; if one is `[~]`, continue it).
|
||||||
|
|
||||||
|
Then follow the "Workflow for every task" in AGENTS.md exactly:
|
||||||
|
1. Read the task row in `docs/IMPLEMENTATION_PLAN.md` and the referenced docs sections.
|
||||||
|
2. For tasks in M4 or later, or any task touching more than 3 files, first ask the @architect subagent for a plan and follow it.
|
||||||
|
3. Write tests first (delegate to @test-engineer where helpful), then implement.
|
||||||
|
4. Run `make verify` until green.
|
||||||
|
5. Ask @swift-reviewer to review the diff; address all Blockers and Should-fix items.
|
||||||
|
6. Update `docs/PROGRESS.md` and any affected docs/ADRs.
|
||||||
|
7. Report: task ID, summary, verification output, manual test steps (if any), follow-ups.
|
||||||
|
|
||||||
|
Additional instructions from the user (may be empty): $ARGUMENTS
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
description: Get an implementation plan for a task or feature without writing code
|
||||||
|
agent: architect
|
||||||
|
---
|
||||||
|
Produce an implementation plan for: $ARGUMENTS
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
description: Review current uncommitted changes with the swift-reviewer agent
|
||||||
|
agent: swift-reviewer
|
||||||
|
---
|
||||||
|
Review the current working-tree changes (`git diff` and `git diff --staged`) for Vorleser according to your checklist. Focus area (optional): $ARGUMENTS
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
---
|
||||||
|
description: Summarise project progress and the next three tasks
|
||||||
|
---
|
||||||
|
Read `docs/PROGRESS.md`, `git log --oneline -15`, and `git status`. Report:
|
||||||
|
- Milestone completion (done/total per milestone)
|
||||||
|
- Tasks in progress or blocked, with reasons
|
||||||
|
- Next three tasks with one-line scope each
|
||||||
|
- Any doc/code drift you notice (e.g. ARCHITECTURE describes something not implemented or vice versa)
|
||||||
|
Do not modify files.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
---
|
||||||
|
description: Implement a specific task by ID, e.g. /task T1.4
|
||||||
|
---
|
||||||
|
Implement task **$ARGUMENTS** from `docs/IMPLEMENTATION_PLAN.md`.
|
||||||
|
|
||||||
|
Before starting, confirm in `docs/PROGRESS.md` that all tasks it depends on (earlier tasks in the same milestone and all earlier milestones) are done. If not, list the missing ones and ask whether to proceed anyway.
|
||||||
|
|
||||||
|
Then follow the "Workflow for every task" in AGENTS.md: plan (use @architect for non-trivial tasks), tests first, implement, `make verify`, @swift-reviewer review, update PROGRESS.md and docs, report with manual test steps where the task touches Accessibility, hotkeys, Services, panel focus, or audio routing.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
---
|
||||||
|
description: Run the full verification suite and fix failures
|
||||||
|
---
|
||||||
|
Run `make verify`. If it fails:
|
||||||
|
- Classify each failure (format, lint, build, test, privacy-check).
|
||||||
|
- Fix the root cause in production code or tests — never disable a rule, delete a test, or weaken an assertion to get green. If a test is genuinely wrong, explain why before changing it.
|
||||||
|
- Re-run until green.
|
||||||
|
|
||||||
|
Report the final result and a short list of what you changed. $ARGUMENTS
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
--swiftversion 6.0
|
||||||
|
--indent 4
|
||||||
|
--maxwidth 120
|
||||||
|
--wraparguments before-first
|
||||||
|
--wrapparameters before-first
|
||||||
|
--wrapcollections before-first
|
||||||
|
--self remove
|
||||||
|
--importgrouping testable-bottom
|
||||||
|
--stripunusedargs closure-only
|
||||||
|
--exclude .build,Packages/VorleserKit/.build,Vorleser.xcodeproj
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
included:
|
||||||
|
- App
|
||||||
|
- Packages/VorleserKit/Sources
|
||||||
|
- Packages/VorleserKit/Tests
|
||||||
|
excluded:
|
||||||
|
- .build
|
||||||
|
- Packages/VorleserKit/.build
|
||||||
|
- Vorleser.xcodeproj
|
||||||
|
disabled_rules:
|
||||||
|
- trailing_comma # handled by swiftformat
|
||||||
|
- todo # TODOs reference task IDs during development
|
||||||
|
opt_in_rules:
|
||||||
|
- force_unwrapping
|
||||||
|
- implicitly_unwrapped_optional
|
||||||
|
- fatal_error_message
|
||||||
|
- empty_count
|
||||||
|
- first_where
|
||||||
|
- sorted_first_last
|
||||||
|
- unowned_variable_capture
|
||||||
|
line_length:
|
||||||
|
warning: 120
|
||||||
|
error: 160
|
||||||
|
type_body_length:
|
||||||
|
warning: 300
|
||||||
|
file_length:
|
||||||
|
warning: 500
|
||||||
|
identifier_name:
|
||||||
|
excluded: [id, i, t, x, y, ok, to]
|
||||||
|
custom_rules:
|
||||||
|
no_print_in_app:
|
||||||
|
included: "App/.*\\.swift"
|
||||||
|
regex: "\\bprint\\("
|
||||||
|
message: "Use os.Logger instead of print in the app target."
|
||||||
|
severity: error
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# AGENTS.md — Vorleser
|
||||||
|
|
||||||
|
Vorleser is a macOS 14+ (Apple Silicon) menu-bar app. It reads the user's **current text selection** in any app aloud through a **local Ollama speech model** (Gradium Phonon) and gives sentence- and paragraph-level playback control. Swift 6, SwiftUI + AppKit, SwiftPM package + XcodeGen app target.
|
||||||
|
|
||||||
|
## Source of truth — read on demand, not all at once
|
||||||
|
|
||||||
|
| When you work on… | Read first |
|
||||||
|
|---|---|
|
||||||
|
| Anything (overview, modules, state machine, budgets) | `docs/ARCHITECTURE.md` |
|
||||||
|
| What to build next / task scope / acceptance criteria | `docs/IMPLEMENTATION_PLAN.md`, `docs/PROGRESS.md` |
|
||||||
|
| Ollama HTTP, voices, errors, fixtures | `docs/OLLAMA_SPEECH_API.md` |
|
||||||
|
| Selection capture, Accessibility, Services, clipboard | `docs/SELECTION_CAPTURE.md` |
|
||||||
|
| AVAudioEngine, PCM, speed, events | `docs/AUDIO_PIPELINE.md` |
|
||||||
|
| Logging, network, permissions, caching | `docs/SECURITY_PRIVACY.md` (hard requirements) |
|
||||||
|
| Tests | `docs/TESTING.md` |
|
||||||
|
| Why something is the way it is | `docs/DECISIONS.md` |
|
||||||
|
| Product intent and user stories | `docs/PRD.md` |
|
||||||
|
|
||||||
|
`docs/CODING_STANDARDS.md` is always loaded through `opencode.json`. Follow it.
|
||||||
|
|
||||||
|
When you load a referenced file, treat its content as mandatory instructions. If two documents conflict, `ARCHITECTURE.md` wins. Raise the conflict to the user and fix the documents.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make bootstrap # install xcodegen/swiftformat/swiftlint via Homebrew if missing
|
||||||
|
make generate # xcodegen generate → Vorleser.xcodeproj (git-ignored)
|
||||||
|
make build # swift build (package) + xcodebuild app (Debug)
|
||||||
|
make test # swift test (unit, contract, component)
|
||||||
|
make verify # format check + lint + build + test + privacy grep checks ← must be green before "done"
|
||||||
|
make app # build and launch Vorleser.app (Debug)
|
||||||
|
make live-test # tests against a real local Ollama (VORLESER_LIVE=1)
|
||||||
|
make fixtures # scripts/capture-fixtures.sh → Packages/VorleserKit/Tests/VorleserOllamaTests/Fixtures
|
||||||
|
swift run --package-path Packages/VorleserKit vorleser-cli --help # headless harness: models, voices, speak, segment, read
|
||||||
|
```
|
||||||
|
|
||||||
|
The package (`Packages/VorleserKit/` — `Sources/`, `Tests/`) builds and tests without Xcode UI. Prefer `swift build` / `swift test` for fast feedback. Use `xcodebuild` only for the `App/` target.
|
||||||
|
|
||||||
|
## Workflow for every task
|
||||||
|
|
||||||
|
1. Read `docs/PROGRESS.md`, then pick the task (`T<m>.<n>`) the user named or the next open one in order. Do not skip milestones; M4 (headless CLI reading) must work before UI milestones.
|
||||||
|
2. Read the task row in `docs/IMPLEMENTATION_PLAN.md` and the relevant section of the referenced docs.
|
||||||
|
3. Plan briefly: files to add or change, protocols touched, tests to write.
|
||||||
|
4. Write tests first for logic: Swift Testing, using fakes from `VorleserTestSupport`.
|
||||||
|
5. Implement the smallest change that meets the acceptance criteria.
|
||||||
|
6. Run `make verify`. Fix until green. Never weaken or delete a test to make it pass.
|
||||||
|
7. Update `docs/PROGRESS.md` (checkbox, date, one-line note). If you changed a contract or made a design choice, update the relevant doc and/or add an ADR to `docs/DECISIONS.md`.
|
||||||
|
8. Summarise: what changed, how it was verified, open follow-ups.
|
||||||
|
|
||||||
|
## Non-negotiables
|
||||||
|
|
||||||
|
- **Privacy**: never log selected text, except with `privacy: .private`; prefer counts. No telemetry. Networking only in `VorleserOllama`. Loopback endpoint by default. See SP-1…SP-10.
|
||||||
|
- **Faithful reading**: never summarise, rewrite, or "improve" the user's text. Only the mechanical normalisation N1–N5.
|
||||||
|
- **Ollama request body** = exactly `model`, `input`, `voice`, `response_format`. Never send `speed` or `instructions` (the server returns 400).
|
||||||
|
- **Never hard-code voice lists.** Discover them via `/api/show`.
|
||||||
|
- **Capture only on explicit trigger.** No AX observers on other apps.
|
||||||
|
- **Module boundaries** per ARCHITECTURE §3. `App/` holds no business logic.
|
||||||
|
- **Swift 6 strict concurrency**, zero warnings.
|
||||||
|
- **Dependencies**: only `KeyboardShortcuts` (app) and `swift-argument-parser` (CLI only). Anything else needs an ADR and user approval.
|
||||||
|
- **Do not edit** `Vorleser.xcodeproj` (generated). Edit `project.yml`.
|
||||||
|
- Do not run `git push`, change signing identities, or touch notarisation credentials without the user's explicit request.
|
||||||
|
|
||||||
|
## Environment facts
|
||||||
|
|
||||||
|
- Ollama ≥ 0.40.9 at `http://127.0.0.1:11434`. Speech models: `phonon` (EN, Apache-2.0), `phonon:40m-{en,de,fr,es,pt,multilingual}` (CC BY-NC 4.0).
|
||||||
|
- Audio from Ollama: PCM16LE, mono, 24 kHz, streamed. 48,000 bytes/s.
|
||||||
|
- Max 4,096 chars per request; Vorleser caps segments at 1,500.
|
||||||
|
- Things you cannot test headlessly: Accessibility capture, global hotkeys, the Services menu, the panel's focus behaviour, and audio route changes. For these, write the code behind protocols, unit-test the logic, and give the user a precise manual test script.
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import AppKit
|
||||||
|
|
||||||
|
/// Lifecycle glue: composition root (T5.2), Services provider (T6.4), hotkeys (T6.3).
|
||||||
|
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||||
|
func applicationDidFinishLaunching(_ notification: Notification) {
|
||||||
|
// T5.2: build AppEnvironment here.
|
||||||
|
// T6.4: NSApp.servicesProvider = servicesHandler; NSUpdateDynamicServices()
|
||||||
|
// T6.3: register KeyboardShortcuts handlers.
|
||||||
|
}
|
||||||
|
|
||||||
|
func applicationWillTerminate(_ notification: Notification) {
|
||||||
|
// T4.x: stop session, cancel synthesis, stop audio engine.
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Created in milestone tasks — see docs/IMPLEMENTATION_PLAN.md.
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>CFBundleDevelopmentRegion</key>
|
||||||
|
<string>en</string>
|
||||||
|
<key>CFBundleDisplayName</key>
|
||||||
|
<string>Vorleser</string>
|
||||||
|
<key>CFBundleExecutable</key>
|
||||||
|
<string>$(EXECUTABLE_NAME)</string>
|
||||||
|
<key>CFBundleIdentifier</key>
|
||||||
|
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||||
|
<key>CFBundleInfoDictionaryVersion</key>
|
||||||
|
<string>6.0</string>
|
||||||
|
<key>CFBundleName</key>
|
||||||
|
<string>$(PRODUCT_NAME)</string>
|
||||||
|
<key>CFBundlePackageType</key>
|
||||||
|
<string>APPL</string>
|
||||||
|
<key>CFBundleShortVersionString</key>
|
||||||
|
<string>$(MARKETING_VERSION)</string>
|
||||||
|
<key>CFBundleVersion</key>
|
||||||
|
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||||
|
<key>LSMinimumSystemVersion</key>
|
||||||
|
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
||||||
|
<key>LSApplicationCategoryType</key>
|
||||||
|
<string>public.app-category.productivity</string>
|
||||||
|
|
||||||
|
<!-- Menu-bar agent: no Dock icon, no main menu. -->
|
||||||
|
<key>LSUIElement</key>
|
||||||
|
<true/>
|
||||||
|
|
||||||
|
<!-- Permits http:// to localhost / 127.0.0.1 only. Remote endpoints must use HTTPS (SP-5). -->
|
||||||
|
<key>NSAppTransportSecurity</key>
|
||||||
|
<dict>
|
||||||
|
<key>NSAllowsLocalNetworking</key>
|
||||||
|
<true/>
|
||||||
|
</dict>
|
||||||
|
|
||||||
|
<!-- Services menu entry point (docs/SELECTION_CAPTURE.md, Strategy 2). -->
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<!-- Intentionally NO usage-description keys for microphone, camera, screen recording,
|
||||||
|
input monitoring etc. (SP-10). Accessibility has no Info.plist key. -->
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Created in milestone tasks — see docs/IMPLEMENTATION_PLAN.md.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Created in milestone tasks — see docs/IMPLEMENTATION_PLAN.md.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Created in milestone tasks — see docs/IMPLEMENTATION_PLAN.md.
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<!-- ADR-003: App Sandbox is disabled because reading other apps' selections via
|
||||||
|
kAXSelectedTextAttribute requires Accessibility trust. Hardened Runtime is enabled
|
||||||
|
via ENABLE_HARDENED_RUNTIME in project.yml. No hardened-runtime exceptions. -->
|
||||||
|
<key>com.apple.security.app-sandbox</key>
|
||||||
|
<false/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// Entry point. Keep this file thin: scenes only, no business logic (ARCHITECTURE §3).
|
||||||
|
@main
|
||||||
|
struct VorleserApp: App {
|
||||||
|
@NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
|
||||||
|
|
||||||
|
var body: some Scene {
|
||||||
|
MenuBarExtra("Vorleser", systemImage: "text.bubble") {
|
||||||
|
// Replaced by MenuBar/StatusMenu.swift in T7.5.
|
||||||
|
Text("Vorleser")
|
||||||
|
Divider()
|
||||||
|
Button("Quit Vorleser") { NSApplication.shared.terminate(nil) }
|
||||||
|
.keyboardShortcut("q")
|
||||||
|
}
|
||||||
|
.menuBarExtraStyle(.menu)
|
||||||
|
|
||||||
|
Settings {
|
||||||
|
// Replaced by Settings/SettingsView.swift in T5.3.
|
||||||
|
Text("Settings")
|
||||||
|
.padding()
|
||||||
|
.frame(width: 420, height: 240)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Vorleser — developer entry points. See AGENTS.md.
|
||||||
|
PKG := Packages/VorleserKit
|
||||||
|
PROJECT := Vorleser.xcodeproj
|
||||||
|
SCHEME := Vorleser
|
||||||
|
DERIVED := .build/xcode
|
||||||
|
APP_PATH := $(DERIVED)/Build/Products/Debug/Vorleser.app
|
||||||
|
|
||||||
|
.PHONY: bootstrap generate build build-pkg build-app test live-test verify app fixtures smoke privacy-check format clean
|
||||||
|
|
||||||
|
bootstrap:
|
||||||
|
@scripts/bootstrap.sh
|
||||||
|
|
||||||
|
generate:
|
||||||
|
xcodegen generate --spec project.yml
|
||||||
|
|
||||||
|
build: build-pkg build-app
|
||||||
|
|
||||||
|
build-pkg:
|
||||||
|
swift build --package-path $(PKG)
|
||||||
|
|
||||||
|
build-app: generate
|
||||||
|
xcodebuild -project $(PROJECT) -scheme $(SCHEME) -configuration Debug \
|
||||||
|
-derivedDataPath $(DERIVED) -destination 'platform=macOS,arch=arm64' -quiet build
|
||||||
|
|
||||||
|
test:
|
||||||
|
swift test --package-path $(PKG) --skip VorleserLiveTests
|
||||||
|
|
||||||
|
live-test:
|
||||||
|
VORLESER_LIVE=1 swift test --package-path $(PKG) --filter VorleserLiveTests
|
||||||
|
|
||||||
|
verify:
|
||||||
|
@scripts/verify.sh
|
||||||
|
|
||||||
|
app: build-app
|
||||||
|
@pkill -x Vorleser 2>/dev/null || true
|
||||||
|
open "$(APP_PATH)"
|
||||||
|
|
||||||
|
fixtures:
|
||||||
|
@scripts/capture-fixtures.sh
|
||||||
|
|
||||||
|
smoke:
|
||||||
|
@scripts/smoke-ollama.sh
|
||||||
|
|
||||||
|
privacy-check:
|
||||||
|
@scripts/privacy-check.sh
|
||||||
|
|
||||||
|
format:
|
||||||
|
@command -v swiftformat >/dev/null && swiftformat App $(PKG) || echo "swiftformat not installed (make bootstrap)"
|
||||||
|
|
||||||
|
clean:
|
||||||
|
rm -rf .build $(PKG)/.build $(PROJECT)
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// swift-tools-version: 6.0
|
||||||
|
// VorleserKit — all testable logic for Vorleser. The macOS app target (App/) is generated by XcodeGen
|
||||||
|
// from project.yml and links the library products below. See docs/ARCHITECTURE.md §3.
|
||||||
|
|
||||||
|
import PackageDescription
|
||||||
|
|
||||||
|
let strictSettings: [SwiftSetting] = [
|
||||||
|
.enableUpcomingFeature("ExistentialAny"),
|
||||||
|
]
|
||||||
|
|
||||||
|
let package = Package(
|
||||||
|
name: "VorleserKit",
|
||||||
|
platforms: [.macOS(.v14)],
|
||||||
|
products: [
|
||||||
|
.library(name: "VorleserCore", targets: ["VorleserCore"]),
|
||||||
|
.library(name: "VorleserCapture", targets: ["VorleserCapture"]),
|
||||||
|
.executable(name: "vorleser-cli", targets: ["vorleser-cli"]),
|
||||||
|
],
|
||||||
|
dependencies: [
|
||||||
|
// CLI harness only (ADR-006). The app target must not depend on it.
|
||||||
|
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
|
||||||
|
],
|
||||||
|
targets: [
|
||||||
|
// Leaf modules — must not depend on each other.
|
||||||
|
.target(name: "VorleserText", swiftSettings: strictSettings),
|
||||||
|
.target(name: "VorleserOllama", swiftSettings: strictSettings),
|
||||||
|
.target(name: "VorleserAudio", swiftSettings: strictSettings),
|
||||||
|
|
||||||
|
// Composition of leaf modules via protocols.
|
||||||
|
.target(
|
||||||
|
name: "VorleserCore",
|
||||||
|
dependencies: ["VorleserText", "VorleserOllama", "VorleserAudio"],
|
||||||
|
swiftSettings: strictSettings
|
||||||
|
),
|
||||||
|
|
||||||
|
// Only module allowed to use Accessibility / ApplicationServices.
|
||||||
|
.target(name: "VorleserCapture", dependencies: ["VorleserCore"], swiftSettings: strictSettings),
|
||||||
|
|
||||||
|
// Fakes shared by tests (FakeSynthesizer, FakeAudioPlayer, FakeCatalog, FakePasteboard, FakeAXClient).
|
||||||
|
.target(
|
||||||
|
name: "VorleserTestSupport",
|
||||||
|
dependencies: ["VorleserCore", "VorleserCapture"],
|
||||||
|
swiftSettings: strictSettings
|
||||||
|
),
|
||||||
|
|
||||||
|
.executableTarget(
|
||||||
|
name: "vorleser-cli",
|
||||||
|
dependencies: [
|
||||||
|
"VorleserCore",
|
||||||
|
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||||
|
],
|
||||||
|
swiftSettings: strictSettings
|
||||||
|
),
|
||||||
|
|
||||||
|
.testTarget(name: "VorleserTextTests", dependencies: ["VorleserText"],
|
||||||
|
resources: [.copy("Fixtures")]),
|
||||||
|
.testTarget(name: "VorleserOllamaTests", dependencies: ["VorleserOllama"],
|
||||||
|
resources: [.copy("Fixtures")]),
|
||||||
|
.testTarget(name: "VorleserAudioTests", dependencies: ["VorleserAudio"]),
|
||||||
|
.testTarget(name: "VorleserCoreTests", dependencies: ["VorleserCore", "VorleserTestSupport"]),
|
||||||
|
.testTarget(name: "VorleserCaptureTests", dependencies: ["VorleserCapture", "VorleserTestSupport"]),
|
||||||
|
// Opt-in tests against a real local Ollama: VORLESER_LIVE=1 swift test --filter VorleserLiveTests
|
||||||
|
.testTarget(name: "VorleserLiveTests", dependencies: ["VorleserCore"]),
|
||||||
|
]
|
||||||
|
)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// Placeholder so the target compiles. Replace during T0.1+ (see docs/IMPLEMENTATION_PLAN.md).
|
||||||
|
|
||||||
|
/// Namespace for the VorleserAudio module.
|
||||||
|
public enum VorleserAudioModule {
|
||||||
|
public static let moduleName = "VorleserAudio"
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// Placeholder so the target compiles. Replace during T0.1+ (see docs/IMPLEMENTATION_PLAN.md).
|
||||||
|
|
||||||
|
/// Namespace for the VorleserCapture module.
|
||||||
|
public enum VorleserCaptureModule {
|
||||||
|
public static let moduleName = "VorleserCapture"
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// Placeholder so the target compiles. Replace during T0.1+ (see docs/IMPLEMENTATION_PLAN.md).
|
||||||
|
|
||||||
|
/// Namespace for the VorleserCore module.
|
||||||
|
public enum VorleserCoreModule {
|
||||||
|
public static let moduleName = "VorleserCore"
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// Placeholder so the target compiles. Replace during T0.1+ (see docs/IMPLEMENTATION_PLAN.md).
|
||||||
|
|
||||||
|
/// Namespace for the VorleserOllama module.
|
||||||
|
public enum VorleserOllamaModule {
|
||||||
|
public static let moduleName = "VorleserOllama"
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// Placeholder so the target compiles. Replace during T0.1+ (see docs/IMPLEMENTATION_PLAN.md).
|
||||||
|
|
||||||
|
/// Namespace for the VorleserTestSupport module.
|
||||||
|
public enum VorleserTestSupportModule {
|
||||||
|
public static let moduleName = "VorleserTestSupport"
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// Placeholder so the target compiles. Replace during T0.1+ (see docs/IMPLEMENTATION_PLAN.md).
|
||||||
|
|
||||||
|
/// Namespace for the VorleserText module.
|
||||||
|
public enum VorleserTextModule {
|
||||||
|
public static let moduleName = "VorleserText"
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import ArgumentParser
|
||||||
|
import VorleserCore
|
||||||
|
|
||||||
|
/// Headless harness for Vorleser. Subcommands are added in T1.5 (models, voices, speak),
|
||||||
|
/// T2.4 (segment) and T4.5 (read). See docs/IMPLEMENTATION_PLAN.md.
|
||||||
|
@main
|
||||||
|
struct VorleserCLI: ParsableCommand {
|
||||||
|
static let configuration = CommandConfiguration(
|
||||||
|
commandName: "vorleser-cli",
|
||||||
|
abstract: "Headless test harness for Vorleser.",
|
||||||
|
subcommands: []
|
||||||
|
)
|
||||||
|
|
||||||
|
func run() throws {
|
||||||
|
print("vorleser-cli: no subcommands implemented yet (\(VorleserCoreModule.moduleName))")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import Testing
|
||||||
|
@testable import VorleserAudio
|
||||||
|
|
||||||
|
@Test func moduleLinks() {
|
||||||
|
#expect(VorleserAudioModule.moduleName == "VorleserAudio")
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import Testing
|
||||||
|
@testable import VorleserCapture
|
||||||
|
|
||||||
|
@Test func moduleLinks() {
|
||||||
|
#expect(VorleserCaptureModule.moduleName == "VorleserCapture")
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import Testing
|
||||||
|
@testable import VorleserCore
|
||||||
|
|
||||||
|
@Test func moduleLinks() {
|
||||||
|
#expect(VorleserCoreModule.moduleName == "VorleserCore")
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import Testing
|
||||||
|
@testable import VorleserCore
|
||||||
|
|
||||||
|
@Test func moduleLinks() {
|
||||||
|
#expect(VorleserCoreModule.moduleName == "VorleserCore")
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Recorded by scripts/capture-fixtures.sh (T1.1). Do not edit by hand. Keep each file < 200 KB.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import Testing
|
||||||
|
@testable import VorleserOllama
|
||||||
|
|
||||||
|
@Test func moduleLinks() {
|
||||||
|
#expect(VorleserOllamaModule.moduleName == "VorleserOllama")
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
Sample inputs for normaliser/segmenter tests (T2.1–T2.4).
|
||||||
|
|
||||||
|
- en-article.txt: abbreviations (e.g., Fig. 3), decimals (3.5 TB/s), a page-number paragraph ("12"), em dash.
|
||||||
|
- de-pdf-copy.txt: PDF line wraps, lowercase hyphenation joins ("Infra-\nstruktur" → "Infrastruktur",
|
||||||
|
"Unter-\nschiede" → "Unterschiede"), uppercase continuation that must stay hyphenated ("Nord-\nSüd"),
|
||||||
|
German abbreviations ("z. B.", "d. h."), decimal comma, page-number paragraph ("– 14 –").
|
||||||
|
|
||||||
|
Expected outputs belong in the tests themselves, not in these files.
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
Die europäische KI-Infra-
|
||||||
|
struktur tritt in eine neue Phase ein. Die neuen Systeme kombinieren z. B. Beschleuniger
|
||||||
|
mit Hochbandbreitenspeicher, d. h. die Speicherbandbreite steigt auf 3,5 TB/s.
|
||||||
|
|
||||||
|
Der Nord-
|
||||||
|
Süd-Vergleich zeigt jedoch deutliche Unter-
|
||||||
|
schiede bei der Energieversorgung.
|
||||||
|
|
||||||
|
– 14 –
|
||||||
|
|
||||||
|
Ob damit die Lücke zu den USA und China geschlossen wird, bleibt offen.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
Europe's AI infrastructure is entering a new phase. The EuroHPC Joint Undertaking has selected new AI factories, e.g. in Germany and Finland, with a combined budget of more than 2.1 billion euros.
|
||||||
|
|
||||||
|
The systems combine accelerators with high-bandwidth memory. Fig. 3 shows the topology. Each node delivers 3.5 TB/s of memory bandwidth; the interconnect, however, remains the limiting factor for large-scale training — especially for mixture-of-experts models with frequent all-to-all communication.
|
||||||
|
|
||||||
|
12
|
||||||
|
|
||||||
|
Whether this closes the gap to the United States and China is an open question.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import Testing
|
||||||
|
@testable import VorleserText
|
||||||
|
|
||||||
|
@Test func moduleLinks() {
|
||||||
|
#expect(VorleserTextModule.moduleName == "VorleserText")
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# Vorleser: OpenCode starter kit
|
||||||
|
|
||||||
|
Vorleser is a macOS menu-bar app. Select text in any app, press **⌥⎋**, and a local Ollama speech model (Gradium Phonon) reads it aloud. You get sentence- and paragraph-level control, pitch-preserving speed, and no text leaving your Mac.
|
||||||
|
|
||||||
|
This repository is the development kit for building the app with **OpenCode**. It contains the architecture, specifications, a task plan, OpenCode agents and commands, and a compilable scaffold.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
| Requirement | Version |
|
||||||
|
|---|---|
|
||||||
|
| Apple Silicon Mac | macOS 14 Sonoma or later |
|
||||||
|
| Xcode | 16 or later (Swift 6) |
|
||||||
|
| Ollama | ≥ 0.40.9, with `ollama pull phonon` (optionally `phonon:40m-de`) |
|
||||||
|
| Homebrew | for `xcodegen`, `swiftformat`, `swiftlint`, `xcbeautify`, `ripgrep` |
|
||||||
|
| OpenCode | current release, with a strong coding model configured |
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git init && git add -A && git commit -m "chore: Vorleser OpenCode kit"
|
||||||
|
make bootstrap # installs xcodegen, swiftformat, swiftlint
|
||||||
|
ollama pull phonon # English, Apache-2.0
|
||||||
|
make smoke # plays one sentence per installed phonon model
|
||||||
|
make verify # the scaffold should already build and test
|
||||||
|
opencode # start OpenCode in the repo root
|
||||||
|
```
|
||||||
|
|
||||||
|
Then paste the prompt from `docs/KICKOFF.md` into OpenCode, or simply run:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/next
|
||||||
|
```
|
||||||
|
|
||||||
|
## What's inside
|
||||||
|
|
||||||
|
| Path | Purpose |
|
||||||
|
|---|---|
|
||||||
|
| `AGENTS.md` | Project rules OpenCode loads automatically: commands, workflow, non-negotiables, doc map |
|
||||||
|
| `opencode.json` | Loads `docs/CODING_STANDARDS.md` every session. It also sets permissions: build, test, and read-only git commands run freely; `git push`, `rm -rf`, and edits to the generated `.xcodeproj` are blocked. |
|
||||||
|
| `.opencode/agents/` | `architect` (plans, read-only), `swift-reviewer` (reviews, read-only), `test-engineer` (may only edit tests and fakes) |
|
||||||
|
| `.opencode/commands/` | `/next`, `/task T1.4`, `/plan …`, `/verify`, `/review`, `/adr …`, `/status`, `/manual-test …` |
|
||||||
|
| `docs/ARCHITECTURE.md` | Authoritative design: modules, state machine, pipelines, budgets, risks |
|
||||||
|
| `docs/PRD.md` | User stories and acceptance criteria |
|
||||||
|
| `docs/IMPLEMENTATION_PLAN.md` | 10 milestones (M0–M9), 49 tasks, each with acceptance criteria |
|
||||||
|
| `docs/KICKOFF.md` | Ready-to-paste prompts for the first session and checkpoints |
|
||||||
|
| `docs/PROGRESS.md` | Checklist the agent updates after each task |
|
||||||
|
| `docs/OLLAMA_SPEECH_API.md` | HTTP contract, error mapping, fixture plan |
|
||||||
|
| `docs/SELECTION_CAPTURE.md` | Accessibility, Services, clipboard strategies + compatibility matrix |
|
||||||
|
| `docs/AUDIO_PIPELINE.md` | AVAudioEngine graph, PCM conversion, epochs, events |
|
||||||
|
| `docs/SECURITY_PRIVACY.md` | Privacy invariants SP-1…SP-10 (checked by `scripts/privacy-check.sh`) |
|
||||||
|
| `docs/TESTING.md` | Test layers, required cases, manual release checklist |
|
||||||
|
| `docs/DECISIONS.md` | ADR-001…007 |
|
||||||
|
| `docs/CODING_STANDARDS.md` | Swift 6 concurrency, structure, logging, UI, style |
|
||||||
|
| `project.yml` | XcodeGen spec for the app target |
|
||||||
|
| `Packages/VorleserKit/` | SwiftPM package with module placeholders, test targets, and text fixtures |
|
||||||
|
| `App/` | App target stubs, `Info.plist` (LSUIElement, NSServices, ATS), entitlements |
|
||||||
|
| `scripts/` | `bootstrap`, `verify`, `privacy-check`, `capture-fixtures`, `smoke-ollama` |
|
||||||
|
|
||||||
|
## Recommended way to work with OpenCode
|
||||||
|
|
||||||
|
1. **One task per session.** `/task T1.4` keeps context small and focused. Start a new session per task.
|
||||||
|
2. **Headless first.** M1–M4 build everything that can be tested without UI: Ollama client, text pipeline, audio, and session. T4.5 gives you an interactive terminal reader (`vorleser-cli read --file article.txt`). Only then move to UI and Accessibility (M5–M7).
|
||||||
|
3. **Capture real fixtures early (T1.1).** Some `/api/show` and error-response details are marked **VERIFY** in the API doc. Recording them from your Ollama stops the agent from guessing.
|
||||||
|
4. **You are the test rig for macOS-only behaviour.** Accessibility, hotkeys, the Services menu, panel focus, and audio routing need a human. Use `/manual-test <feature>` and report results back so the agent can update the compatibility matrix.
|
||||||
|
5. **Review gate.** `/next` already calls `@swift-reviewer`. Run `/review` yourself before committing larger changes.
|
||||||
|
6. **Record decisions.** When you deviate from the architecture, run `/adr <title>` so the docs stay true.
|
||||||
|
|
||||||
|
## Placeholders to change
|
||||||
|
|
||||||
|
- Bundle ID prefix `de.schihei` in `project.yml`.
|
||||||
|
- App name "Vorleser" if you prefer another. Search the repo for `Vorleser` (it also appears in the Services menu title in `Info.plist`).
|
||||||
|
|
||||||
|
## Licensing note
|
||||||
|
|
||||||
|
Vorleser bundles no models or voices. `phonon` (31M English) is Apache-2.0. The `phonon:40m-*` checkpoints (incl. German) are **CC BY-NC 4.0**, so check this before any commercial distribution.
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"instructions": [
|
||||||
|
"docs/CODING_STANDARDS.md"
|
||||||
|
],
|
||||||
|
"permission": {
|
||||||
|
"edit": {
|
||||||
|
"*": "allow",
|
||||||
|
"Vorleser.xcodeproj/*": "deny",
|
||||||
|
"Packages/VorleserKit/Tests/VorleserOllamaTests/Fixtures/*": "ask"
|
||||||
|
},
|
||||||
|
"bash": {
|
||||||
|
"*": "ask",
|
||||||
|
"make *": "allow",
|
||||||
|
"swift build*": "allow",
|
||||||
|
"swift test*": "allow",
|
||||||
|
"swift run vorleser-cli*": "allow",
|
||||||
|
"swift run --package-path Packages/VorleserKit vorleser-cli*": "allow",
|
||||||
|
"swift package resolve*": "allow",
|
||||||
|
"swift package describe*": "allow",
|
||||||
|
"xcodegen*": "allow",
|
||||||
|
"xcodebuild *": "allow",
|
||||||
|
"swiftformat *": "allow",
|
||||||
|
"swiftlint *": "allow",
|
||||||
|
"ollama list*": "allow",
|
||||||
|
"ollama show *": "allow",
|
||||||
|
"ollama --version": "allow",
|
||||||
|
"curl -s http://127.0.0.1:11434/*": "allow",
|
||||||
|
"curl -sS http://127.0.0.1:11434/*": "allow",
|
||||||
|
"git status*": "allow",
|
||||||
|
"git diff*": "allow",
|
||||||
|
"git log*": "allow",
|
||||||
|
"git add *": "allow",
|
||||||
|
"git commit *": "ask",
|
||||||
|
"git push*": "deny",
|
||||||
|
"rm -rf *": "deny",
|
||||||
|
"ls *": "allow",
|
||||||
|
"cat *": "allow",
|
||||||
|
"rg *": "allow",
|
||||||
|
"grep *": "allow",
|
||||||
|
"find *": "allow"
|
||||||
|
},
|
||||||
|
"webfetch": "ask",
|
||||||
|
"external_directory": "ask"
|
||||||
|
}
|
||||||
|
}
|
||||||
+71
@@ -0,0 +1,71 @@
|
|||||||
|
# XcodeGen spec (ADR-006). Generate with `make generate`. Vorleser.xcodeproj is git-ignored — never edit it.
|
||||||
|
name: Vorleser
|
||||||
|
|
||||||
|
options:
|
||||||
|
bundleIdPrefix: de.schihei # placeholder — change to your own reverse-DNS prefix
|
||||||
|
deploymentTarget:
|
||||||
|
macOS: "14.0"
|
||||||
|
createIntermediateGroups: true
|
||||||
|
developmentLanguage: en
|
||||||
|
|
||||||
|
settings:
|
||||||
|
base:
|
||||||
|
SWIFT_VERSION: "6.0"
|
||||||
|
SWIFT_STRICT_CONCURRENCY: complete
|
||||||
|
ARCHS: arm64
|
||||||
|
ONLY_ACTIVE_ARCH: YES
|
||||||
|
MACOSX_DEPLOYMENT_TARGET: "14.0"
|
||||||
|
ENABLE_HARDENED_RUNTIME: YES
|
||||||
|
MARKETING_VERSION: "0.1.0"
|
||||||
|
CURRENT_PROJECT_VERSION: "1"
|
||||||
|
configs:
|
||||||
|
Release:
|
||||||
|
SWIFT_TREAT_WARNINGS_AS_ERRORS: YES
|
||||||
|
GCC_TREAT_WARNINGS_AS_ERRORS: YES
|
||||||
|
|
||||||
|
packages:
|
||||||
|
VorleserKit:
|
||||||
|
path: Packages/VorleserKit
|
||||||
|
KeyboardShortcuts:
|
||||||
|
url: https://github.com/sindresorhus/KeyboardShortcuts
|
||||||
|
from: "2.0.0"
|
||||||
|
|
||||||
|
targets:
|
||||||
|
Vorleser:
|
||||||
|
type: application
|
||||||
|
platform: macOS
|
||||||
|
sources:
|
||||||
|
- path: App
|
||||||
|
excludes:
|
||||||
|
- "**/README.md"
|
||||||
|
- "Info.plist"
|
||||||
|
- "Vorleser.entitlements"
|
||||||
|
# Do NOT use XcodeGen's `info:` / `entitlements:` keys: they regenerate (overwrite) the files.
|
||||||
|
# The hand-maintained files are referenced via INFOPLIST_FILE / CODE_SIGN_ENTITLEMENTS below.
|
||||||
|
settings:
|
||||||
|
base:
|
||||||
|
PRODUCT_NAME: Vorleser
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER: de.schihei.vorleser # placeholder
|
||||||
|
GENERATE_INFOPLIST_FILE: NO
|
||||||
|
INFOPLIST_FILE: App/Info.plist
|
||||||
|
CODE_SIGN_ENTITLEMENTS: App/Vorleser.entitlements
|
||||||
|
CODE_SIGN_STYLE: Automatic
|
||||||
|
CODE_SIGN_IDENTITY: "-" # "Sign to Run Locally" for development
|
||||||
|
ENABLE_APP_SANDBOX: NO
|
||||||
|
COMBINE_HIDPI_IMAGES: YES
|
||||||
|
dependencies:
|
||||||
|
- package: VorleserKit
|
||||||
|
product: VorleserCore
|
||||||
|
- package: VorleserKit
|
||||||
|
product: VorleserCapture
|
||||||
|
- package: KeyboardShortcuts
|
||||||
|
|
||||||
|
schemes:
|
||||||
|
Vorleser:
|
||||||
|
build:
|
||||||
|
targets:
|
||||||
|
Vorleser: all
|
||||||
|
run:
|
||||||
|
config: Debug
|
||||||
|
archive:
|
||||||
|
config: Release
|
||||||
Executable
+25
@@ -0,0 +1,25 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Installs developer tools if missing. Safe to re-run.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
[[ "$(uname -s)" == "Darwin" && "$(uname -m)" == "arm64" ]] || { echo "Vorleser requires an Apple Silicon Mac." >&2; exit 1; }
|
||||||
|
xcode-select -p >/dev/null 2>&1 || { echo "Install Xcode 16+ and run: xcode-select --install" >&2; exit 1; }
|
||||||
|
|
||||||
|
if ! command -v brew >/dev/null; then
|
||||||
|
echo "Homebrew not found — install from https://brew.sh or install xcodegen/swiftformat/swiftlint manually." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
for tool in xcodegen swiftformat swiftlint xcbeautify ripgrep; do
|
||||||
|
bin=$tool; [[ $tool == ripgrep ]] && bin=rg
|
||||||
|
if command -v "$bin" >/dev/null; then echo "✓ $tool"; else echo "→ installing $tool"; brew install "$tool"; fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if command -v ollama >/dev/null; then
|
||||||
|
echo "✓ ollama $(ollama --version 2>/dev/null | awk '{print $NF}')"
|
||||||
|
else
|
||||||
|
echo "! ollama not found — install from https://ollama.com/download (≥ 0.40.9 for speech)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
swift --version | head -1
|
||||||
|
echo "Bootstrap complete. Next: make generate && make verify"
|
||||||
Executable
+40
@@ -0,0 +1,40 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Records real Ollama responses into test fixtures (T1.1). Requires a running Ollama ≥ 0.40.9.
|
||||||
|
# Usage: scripts/capture-fixtures.sh [base_url]
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
BASE="${1:-http://127.0.0.1:11434}"
|
||||||
|
OUT="Packages/VorleserKit/Tests/VorleserOllamaTests/Fixtures"
|
||||||
|
mkdir -p "$OUT"
|
||||||
|
j() { curl -sS -H 'Content-Type: application/json' "$@"; }
|
||||||
|
|
||||||
|
echo "→ version / tags"
|
||||||
|
j "$BASE/api/version" | tee "$OUT/version.json" | jq -c .
|
||||||
|
j "$BASE/api/tags" > "$OUT/tags.json"
|
||||||
|
|
||||||
|
models=$(jq -r '.models[].name' "$OUT/tags.json" | grep -E '^phonon' || true)
|
||||||
|
[[ -z "$models" ]] && { echo "No phonon models installed. Run: ollama pull phonon" >&2; exit 1; }
|
||||||
|
|
||||||
|
for m in $models; do
|
||||||
|
safe=${m//[:\/]/_}
|
||||||
|
echo "→ show $m"
|
||||||
|
j -X POST "$BASE/api/show" -d "{\"model\":\"$m\"}" \
|
||||||
|
| jq '{capabilities, voices, details, model_info: (.model_info // {} | with_entries(select(.key|test("general\\."))))}' \
|
||||||
|
> "$OUT/show-$safe.json"
|
||||||
|
echo " voices: $(jq -c '.voices' "$OUT/show-$safe.json" | cut -c1-160)"
|
||||||
|
echo "→ speech $m"
|
||||||
|
curl -sS -D "$OUT/speech-$safe-short.headers" -o "$OUT/speech-$safe-short.pcm" \
|
||||||
|
-H 'Content-Type: application/json' "$BASE/v1/audio/speech" \
|
||||||
|
-d "{\"model\":\"$m\",\"input\":\"Ready.\",\"voice\":\"default\",\"response_format\":\"pcm\"}"
|
||||||
|
echo " bytes: $(wc -c < "$OUT/speech-$safe-short.pcm")"
|
||||||
|
done
|
||||||
|
|
||||||
|
first=$(echo "$models" | head -1)
|
||||||
|
echo "→ error cases"
|
||||||
|
status() { curl -sS -o "$2" -w '%{http_code}' -H 'Content-Type: application/json' "$BASE/v1/audio/speech" -d "$1"; }
|
||||||
|
echo " unknown voice: $(status "{\"model\":\"$first\",\"input\":\"x\",\"voice\":\"NoSuchVoice\",\"response_format\":\"pcm\"}" "$OUT/error-unknown-voice.json")"
|
||||||
|
echo " missing model: $(status '{"model":"phonon:does-not-exist","input":"x","voice":"default","response_format":"pcm"}' "$OUT/error-missing-model.json")"
|
||||||
|
echo " unsupported option: $(status "{\"model\":\"$first\",\"input\":\"x\",\"voice\":\"default\",\"speed\":1.5}" "$OUT/error-unsupported-option.json")"
|
||||||
|
echo " unsupported format: $(status "{\"model\":\"$first\",\"input\":\"x\",\"response_format\":\"mp3\"}" "$OUT/error-unsupported-format.json")"
|
||||||
|
|
||||||
|
echo "Done. Review $OUT, then update the VERIFY items in docs/OLLAMA_SPEECH_API.md (status codes printed above)."
|
||||||
Executable
+36
@@ -0,0 +1,36 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Static checks for docs/SECURITY_PRIVACY.md invariants. Extended in T8.5.
|
||||||
|
set -uo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
SRC="Packages/VorleserKit/Sources App"
|
||||||
|
fail=0
|
||||||
|
if ! command -v rg >/dev/null; then echo "warning: ripgrep (rg) not installed — privacy checks skipped (brew install ripgrep)"; exit 0; fi
|
||||||
|
report() { echo "✗ $1"; fail=1; }
|
||||||
|
|
||||||
|
# SP-1: no AX observers on other apps
|
||||||
|
if rg -n 'AXObserverCreate' $SRC >/dev/null 2>&1; then report "SP-1: AXObserverCreate found"; rg -n 'AXObserverCreate' $SRC; fi
|
||||||
|
|
||||||
|
# SP-4: networking only in VorleserOllama
|
||||||
|
hits=$(rg -n 'URLSession|URLRequest\(' $SRC -g '!**/VorleserOllama/**' -g '!**/VorleserTestSupport/**' 2>/dev/null || true)
|
||||||
|
[[ -n "$hits" ]] && { report "SP-4: networking outside VorleserOllama"; echo "$hits"; }
|
||||||
|
|
||||||
|
# SP-2: logger interpolation of text-like values without privacy: .private
|
||||||
|
hits=$(rg -n 'Log(ger)?\.[a-z]+.*\\\((text|selection\.text|segment\.text|input)[^)]*\)' $SRC 2>/dev/null | rg -v 'privacy: *\.private|\.count' || true)
|
||||||
|
[[ -n "$hits" ]] && { report "SP-2: possible text logging without privacy: .private"; echo "$hits"; }
|
||||||
|
|
||||||
|
# AX APIs only in VorleserCapture
|
||||||
|
hits=$(rg -n 'AXUIElement|kAXSelectedText' $SRC -g '!**/VorleserCapture/**' -g '!**/VorleserTestSupport/**' 2>/dev/null || true)
|
||||||
|
[[ -n "$hits" ]] && { report "Boundary: Accessibility APIs outside VorleserCapture"; echo "$hits"; }
|
||||||
|
|
||||||
|
# Ollama contract: never send speed/instructions
|
||||||
|
hits=$(rg -n '"(speed|instructions)"' Packages/VorleserKit/Sources/VorleserOllama 2>/dev/null || true)
|
||||||
|
[[ -n "$hits" ]] && { report "Contract: unsupported speech option in request"; echo "$hits"; }
|
||||||
|
|
||||||
|
# SP-10: no unused permission usage strings
|
||||||
|
if rg -n 'NS(Microphone|Camera|ScreenCapture|AppleEvents)UsageDescription' App/Info.plist >/dev/null 2>&1; then report "SP-10: unexpected usage description in Info.plist"; fi
|
||||||
|
|
||||||
|
# ATS
|
||||||
|
if rg -n 'NSAllowsArbitraryLoads' App/Info.plist >/dev/null 2>&1; then report "SP-5: NSAllowsArbitraryLoads present"; fi
|
||||||
|
|
||||||
|
[[ $fail -eq 0 ]] && echo "✓ privacy checks passed"
|
||||||
|
exit $fail
|
||||||
Executable
+24
@@ -0,0 +1,24 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Quick end-to-end check that Ollama speech works on this Mac. Plays one sentence per installed phonon model.
|
||||||
|
set -euo pipefail
|
||||||
|
BASE="${OLLAMA_BASE:-http://127.0.0.1:11434}"
|
||||||
|
ver=$(curl -fsS "$BASE/api/version" | jq -r .version) || { echo "✗ Ollama not reachable at $BASE"; exit 1; }
|
||||||
|
echo "✓ Ollama $ver"
|
||||||
|
models=$(curl -fsS "$BASE/api/tags" | jq -r '.models[].name' | grep -E '^phonon' || true)
|
||||||
|
[[ -z "$models" ]] && { echo "✗ no phonon model — run: ollama pull phonon"; exit 1; }
|
||||||
|
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
|
||||||
|
for m in $models; do
|
||||||
|
case "$m" in
|
||||||
|
*-de*) text="Dies ist ein kurzer Test der deutschen Sprachausgabe." ;;
|
||||||
|
*-fr*) text="Ceci est un court test de synthèse vocale." ;;
|
||||||
|
*-es*) text="Esta es una breve prueba de síntesis de voz." ;;
|
||||||
|
*-pt*) text="Este é um breve teste de síntese de voz." ;;
|
||||||
|
*) text="This is a short test of local speech synthesis." ;;
|
||||||
|
esac
|
||||||
|
start=$(python3 -c 'import time;print(time.time())')
|
||||||
|
curl -fsS "$BASE/v1/audio/speech" -H 'Content-Type: application/json' \
|
||||||
|
-d "$(jq -nc --arg m "$m" --arg t "$text" '{model:$m,input:$t,voice:"default",response_format:"wav"}')" -o "$tmp/out.wav"
|
||||||
|
end=$(python3 -c 'import time;print(time.time())')
|
||||||
|
printf '✓ %-28s %6d bytes %.2fs total\n' "$m" "$(wc -c < "$tmp/out.wav")" "$(python3 -c "print($end-$start)")"
|
||||||
|
afplay "$tmp/out.wav"
|
||||||
|
done
|
||||||
Executable
+33
@@ -0,0 +1,33 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Full verification gate. Must be green before a task is marked done (AGENTS.md).
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
PKG=Packages/VorleserKit
|
||||||
|
|
||||||
|
step() { printf '\n\033[1m▶ %s\033[0m\n' "$*"; }
|
||||||
|
|
||||||
|
step "Format check"
|
||||||
|
if command -v swiftformat >/dev/null; then swiftformat --lint App "$PKG"; else echo "skip: swiftformat not installed"; fi
|
||||||
|
|
||||||
|
step "Lint"
|
||||||
|
if command -v swiftlint >/dev/null; then swiftlint lint --strict --quiet App "$PKG/Sources"; else echo "skip: swiftlint not installed"; fi
|
||||||
|
|
||||||
|
step "Privacy checks"
|
||||||
|
scripts/privacy-check.sh
|
||||||
|
|
||||||
|
step "Package build"
|
||||||
|
swift build --package-path "$PKG"
|
||||||
|
|
||||||
|
step "Package tests"
|
||||||
|
swift test --package-path "$PKG" --skip VorleserLiveTests
|
||||||
|
|
||||||
|
step "App build"
|
||||||
|
if command -v xcodegen >/dev/null; then
|
||||||
|
xcodegen generate --spec project.yml --quiet
|
||||||
|
xcodebuild -project Vorleser.xcodeproj -scheme Vorleser -configuration Debug \
|
||||||
|
-derivedDataPath .build/xcode -destination 'platform=macOS,arch=arm64' -quiet build
|
||||||
|
else
|
||||||
|
echo "skip: xcodegen not installed (make bootstrap)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf '\n\033[32m✔ verify passed\033[0m\n'
|
||||||
Reference in new issue
Block a user