From 92b90c0e13a787986255f148ea8fe7cb46f17d98 Mon Sep 17 00:00:00 2001 From: Jonathan van Rij Date: Fri, 23 Oct 2026 09:40:20 +0200 Subject: [PATCH] read text aloud --- Sources/HelderCore/Files/ContextActions.swift | 25 +++++- .../HelderCore/Markdown/MarkdownSpeech.swift | 62 ++++++++++++++ .../HelderServices/Speech/SpeechService.swift | 52 ++++++++++++ .../Overlays/ContextMenuOverlay.swift | 6 +- Sources/HelderUI/Shell/Command.swift | 5 ++ Sources/HelderUI/Shell/TitleBarView.swift | 10 ++- Sources/HelderUI/State/ReadAloudStore.swift | 32 +++++++ .../State/WorkspaceModel+ContextActions.swift | 21 +++++ .../State/WorkspaceModel+Lifecycle.swift | 3 +- Sources/HelderUI/State/WorkspaceModel.swift | 4 + .../HelderUI/State/WorkspaceServices.swift | 5 +- .../Files/ContextActionsTests.swift | 62 +++++++++++++- .../Markdown/MarkdownSpeechTests.swift | 39 +++++++++ .../State/WorkspaceModelTests.swift | 85 ++++++++++++++++++- .../Support/Fakes/FakeSpeech.swift | 13 +++ .../Support/WorkspaceHarness.swift | 5 +- docs/architecture.md | 8 +- docs/behaviour.md | 6 +- docs/guide/right-click-menu.md | 33 ++++++- docs/guide/title-bar.md | 13 +++ 20 files changed, 471 insertions(+), 18 deletions(-) create mode 100644 Sources/HelderCore/Markdown/MarkdownSpeech.swift create mode 100644 Sources/HelderServices/Speech/SpeechService.swift create mode 100644 Sources/HelderUI/State/ReadAloudStore.swift create mode 100644 Tests/HelderCoreTests/Markdown/MarkdownSpeechTests.swift create mode 100644 Tests/HelderUITests/Support/Fakes/FakeSpeech.swift diff --git a/Sources/HelderCore/Files/ContextActions.swift b/Sources/HelderCore/Files/ContextActions.swift index 8e179bc..4112c4c 100644 --- a/Sources/HelderCore/Files/ContextActions.swift +++ b/Sources/HelderCore/Files/ContextActions.swift @@ -41,8 +41,13 @@ public enum ContextAction: Sendable, Equatable { case delete(String, isDirectory: Bool) case copyTerminalSelection(TerminalKind) case pasteIntoTerminal(TerminalKind) + /// Inserts `/wait-what` with the pane's selection into the agent composer. + case waitWhat(TerminalKind) /// Inserts `/bouwen ` into the agent composer for an ontwikkeling folder. case bouwen(String) + /// Reads a Markdown file's prose aloud. + case readAloudFile(String) + case readAloudText(String) /// Destructive items read in amber-deep. public var isDestructive: Bool { @@ -81,14 +86,14 @@ public enum ContextActions { return [ .action(.passOnReference(ref, code: hasCode ? code : nil), label: hasCode ? "Pass on selection" : "Pass on reference"), .action(.copyReference(ref), label: "Copy reference"), - ] + showDiff + ] + (hasCode ? readAloudSelection(code ?? "", path: reference.path) : []) + showDiff case .projectRoot: return [ .action(.newFile(inDirectory: ""), label: "New file"), .action(.revealInFinder(""), label: "Show in Finder"), ] case let .file(path): - return fileHead(path) + [ + return fileHead(path) + readAloudFile(path) + [ .separator, .action(.rename(path, isDirectory: false), label: "Rename file"), .action(.revealInFinder(path), label: "Show in Finder"), @@ -109,10 +114,12 @@ public enum ContextActions { .action(.delete(path, isDirectory: true), label: "Delete folder"), ] case let .terminal(kind, hasSelection): + let waitWhat: [ContextMenuEntry] = hasSelection && kind == .agent + ? [.separator, .action(.waitWhat(kind), label: "Wait what?")] : [] return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : []) - + [.action(.pasteIntoTerminal(kind), label: "Paste")] + + [.action(.pasteIntoTerminal(kind), label: "Paste")] + waitWhat case let .gitRow(path, staged): - return fileHead(path) + [ + return fileHead(path) + readAloudFile(path) + [ .separator, staged ? .action(.unstage(path), label: "Unstage changes") : .action(.stage(path), label: "Stage changes"), .action(.openDiff(path), label: "Open diff"), @@ -128,6 +135,16 @@ public enum ContextActions { return String(parts[1]) } + private static func readAloudFile(_ path: String) -> [ContextMenuEntry] { + FileType.isMarkdown(path) ? [.separator, .action(.readAloudFile(path), label: "Read aloud")] : [] + } + + /// Selected Markdown is read as prose; a selection with no prose left, such as one code block, is read as it is. + private static func readAloudSelection(_ code: String, path: String) -> [ContextMenuEntry] { + let prose = FileType.isMarkdown(path) ? MarkdownSpeech.plainText(MarkdownParser.parse(code)) : "" + return [.separator, .action(.readAloudText(prose.isEmpty ? code : prose), label: "Read aloud selection")] + } + private static func fileHead(_ path: String) -> [ContextMenuEntry] { let name = PathUtils.basename(path) return [ diff --git a/Sources/HelderCore/Markdown/MarkdownSpeech.swift b/Sources/HelderCore/Markdown/MarkdownSpeech.swift new file mode 100644 index 0000000..cea5bca --- /dev/null +++ b/Sources/HelderCore/Markdown/MarkdownSpeech.swift @@ -0,0 +1,62 @@ +import Foundation + +public enum MarkdownSpeech { + /// The prose of a document for a voice to read: one sentence per line, markup, URLs, code blocks and rules left out. + /// A line without closing punctuation gets a full stop, so the voice pauses between blocks. + public static func plainText(_ blocks: [MarkdownBlock]) -> String { + lines(blocks).joined(separator: "\n") + } + + /// The text with each `$` that is not before a digit written as "dollar", so the voice does not say "dollar sign". + /// A `$` before a digit stays: the voice reads `$5` as "five dollars". + public static func spoken(_ text: String) -> String { + let characters = Array(text) + var result = "" + for (index, character) in characters.enumerated() { + let next = index + 1 < characters.count ? characters[index + 1] : nil + guard character == "$", !(next?.isNumber ?? false) else { + result.append(character) + continue + } + if let last = result.last, !last.isWhitespace { result.append(" ") } + result.append("dollar") + if let next, !next.isWhitespace { result.append(" ") } + } + return result + } + + private static func lines(_ blocks: [MarkdownBlock]) -> [String] { + blocks.flatMap { block -> [String] in + switch block { + case let .heading(_, content), let .paragraph(content): [sentence(content)] + case let .quote(inner): lines(inner) + case let .list(_, items): items.map(sentence) + case let .table(header, _, rows): + ([header] + rows).map { cells in sentence(cells.map(text).filter { !$0.isEmpty }.joined(separator: ", ")) } + case .code, .rule: [] + } + } + .filter { !$0.isEmpty } + } + + private static func sentence(_ inlines: [MarkdownInline]) -> String { + sentence(text(inlines)) + } + + private static func sentence(_ text: String) -> String { + let trimmed = text.split(whereSeparator: \.isWhitespace).joined(separator: " ") + guard let last = trimmed.last else { return "" } + return ".!?:;".contains(last) ? trimmed : trimmed + "." + } + + private static func text(_ inlines: [MarkdownInline]) -> String { + inlines.map { inline in + switch inline { + case let .text(text), let .code(text): text + case let .strong(inner), let .emphasis(inner), let .strikethrough(inner), let .link(inner, _, _): text(inner) + case let .image(alt, _, _): alt + } + } + .joined() + } +} diff --git a/Sources/HelderServices/Speech/SpeechService.swift b/Sources/HelderServices/Speech/SpeechService.swift new file mode 100644 index 0000000..d755ced --- /dev/null +++ b/Sources/HelderServices/Speech/SpeechService.swift @@ -0,0 +1,52 @@ +import AVFoundation +import Foundation + +@MainActor +public protocol SpeechServicing: AnyObject { + /// Called when the text was read to the end; never after `stop()`. + var onFinish: (() -> Void)? { get set } + /// Reads `text` aloud with the system voice, cutting off anything still being read. + func speak(_ text: String) + func stop() +} + +/// Speech through `AVSpeechSynthesizer`. +@MainActor +public final class SpeechService: NSObject, SpeechServicing { + public var onFinish: (() -> Void)? + private lazy var synthesizer: AVSpeechSynthesizer = { + let synthesizer = AVSpeechSynthesizer() + synthesizer.delegate = self + return synthesizer + }() + /// The utterance now being read; a late finish of a replaced one must not end the new one. + private var current: ObjectIdentifier? + + /// Nonisolated, so the shared `AppServices.live` can build it. + override public nonisolated init() { + super.init() + } + + public func speak(_ text: String) { + stop() + let utterance = AVSpeechUtterance(string: text) + current = ObjectIdentifier(utterance) + synthesizer.speak(utterance) + } + + public func stop() { + current = nil + synthesizer.stopSpeaking(at: .immediate) + } +} + +extension SpeechService: AVSpeechSynthesizerDelegate { + nonisolated public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { + let finished = ObjectIdentifier(utterance) + Task { @MainActor in + guard self.current == finished else { return } + self.current = nil + self.onFinish?() + } + } +} diff --git a/Sources/HelderUI/Overlays/ContextMenuOverlay.swift b/Sources/HelderUI/Overlays/ContextMenuOverlay.swift index c65ebeb..995b5b3 100644 --- a/Sources/HelderUI/Overlays/ContextMenuOverlay.swift +++ b/Sources/HelderUI/Overlays/ContextMenuOverlay.swift @@ -108,10 +108,10 @@ struct ContextMenuOverlay: View { nonisolated static func tint(for action: ContextAction) -> MenuIconTint { switch action { - case .copyReference, .copyTerminalSelection, .pasteIntoTerminal: .plain + case .copyReference, .copyTerminalSelection, .pasteIntoTerminal, .readAloudFile, .readAloudText: .plain case .newFile, .newFolder, .stage: .add case .copyFileName, .unstage, .revealInFinder: .modify - case .passOnReference, .passOnFileName, .bouwen, .openDiff, .showDiff, .rename: .rename + case .passOnReference, .passOnFileName, .bouwen, .waitWhat, .openDiff, .showDiff, .rename: .rename case .discard, .delete: .danger } } @@ -120,6 +120,8 @@ struct ContextMenuOverlay: View { switch action { case .passOnReference, .passOnFileName: ContextMenuRow.spark case .bouwen: "hammer" + case .waitWhat: "questionmark.bubble" + case .readAloudFile, .readAloudText: "speaker.wave.2" case .copyReference, .copyFileName, .copyTerminalSelection: "doc.on.doc" case .pasteIntoTerminal: "doc.on.clipboard" case .newFile: "doc.badge.plus" diff --git a/Sources/HelderUI/Shell/Command.swift b/Sources/HelderUI/Shell/Command.swift index b186eb7..f6033ed 100644 --- a/Sources/HelderUI/Shell/Command.swift +++ b/Sources/HelderUI/Shell/Command.swift @@ -129,6 +129,11 @@ public enum Command: Equatable, Sendable { /// The clean-copy popup's Copy and ⌘↩: copies its text and closes it. case copyCleanCopy + // MARK: Read aloud + + /// The title bar's Stop button. + case stopReading + // MARK: Project and window /// ⌘O diff --git a/Sources/HelderUI/Shell/TitleBarView.swift b/Sources/HelderUI/Shell/TitleBarView.swift index 371d776..500d40b 100644 --- a/Sources/HelderUI/Shell/TitleBarView.swift +++ b/Sources/HelderUI/Shell/TitleBarView.swift @@ -132,13 +132,14 @@ private struct PaneToggles: View { } /// Search ⌘F · Fluid ⌘L · Hidden ⌘. · Note ⌘N, then `?`. Search and Note are actions; Fluid and Hidden toggle. +/// While Helder reads aloud, a Stop toggle leads the group; switching it off stops the reading. private struct TitleToolbar: View { let model: WorkspaceModel var body: some View { let layout = model.layout HStack(spacing: Metrics.toolbarIconGap) { - ButtonGroup([ + ButtonGroup(stop + [ GroupItem("Search", keys: "⌘F", kind: .action, tip: Text("Search the open file, the project and the file names.")) { model.perform(.showSearch(seed: "")) }, GroupItem("Fluid", keys: "⌘L", kind: .toggle(isOn: layout.fluid), @@ -161,4 +162,11 @@ private struct TitleToolbar: View { } .fixedSize() } + + private var stop: [GroupItem] { + guard model.readAloud.isReading else { return [] } + return [GroupItem("Stop", kind: .toggle(isOn: true), tip: Tooltip.stated("Read aloud: ", "playing", ". Click to stop.")) { + model.perform(.stopReading) + }] + } } diff --git a/Sources/HelderUI/State/ReadAloudStore.swift b/Sources/HelderUI/State/ReadAloudStore.swift new file mode 100644 index 0000000..acea239 --- /dev/null +++ b/Sources/HelderUI/State/ReadAloudStore.swift @@ -0,0 +1,32 @@ +import Foundation +import HelderCore +import HelderServices +import Observation + +/// Read aloud: whether Helder is reading, for the title bar's Stop button. +@Observable +@MainActor +public final class ReadAloudStore { + public private(set) var isReading = false + + @ObservationIgnored private let speech: SpeechServicing + + public init(speech: SpeechServicing) { + self.speech = speech + speech.onFinish = { [weak self] in self?.isReading = false } + } + + /// Starts reading, replacing what is being read; false for blank text, which reads nothing. + @discardableResult + public func read(_ text: String) -> Bool { + guard !text.allSatisfy(\.isWhitespace) else { return false } + speech.speak(MarkdownSpeech.spoken(text)) + isReading = true + return true + } + + public func stop() { + speech.stop() + isReading = false + } +} diff --git a/Sources/HelderUI/State/WorkspaceModel+ContextActions.swift b/Sources/HelderUI/State/WorkspaceModel+ContextActions.swift index c57fd86..2237555 100644 --- a/Sources/HelderUI/State/WorkspaceModel+ContextActions.swift +++ b/Sources/HelderUI/State/WorkspaceModel+ContextActions.swift @@ -95,6 +95,14 @@ extension WorkspaceModel { overlay.present(.passOn(PassOnRequest(reference: name, anchor: anchor))) case let .bouwen(name): passToAgent("/bouwen \(name)", toast: "/bouwen \(name)") + case let .waitWhat(kind): + if let text = terminal.selection(kind)?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty { + passToAgent("/wait-what `\(text)`", toast: "/wait-what") + } + case let .readAloudText(text): + readAloud.read(text) + case let .readAloudFile(path): + readAloudFile(path) case let .newFile(directory): overlay.present(.namePrompt(NamePromptRequest(purpose: .newFile(inDirectory: directory), anchor: anchor))) case let .newFolder(directory): @@ -129,6 +137,19 @@ extension WorkspaceModel { } } + /// The open file is read from its buffer, unsaved edits included; any other file from disk. + private func readAloudFile(_ path: String) { + let live = editor.flatMap { $0.activePath == path && $0.isLoaded(path) ? $0.text(for: path) : nil } + let files = services?.files + track { + var text = live + if text == nil, case let .text(disk)? = try? await files?.readText(path) { text = disk } + guard !Task.isCancelled else { return } + let prose = MarkdownSpeech.plainText(MarkdownParser.parse(text ?? "")) + if !self.readAloud.read(prose) { self.toasts.show("Nothing to read", detail: path) } + } + } + func submitName(_ name: String) { guard case let .namePrompt(request) = overlay.current else { return } overlay.dismiss() diff --git a/Sources/HelderUI/State/WorkspaceModel+Lifecycle.swift b/Sources/HelderUI/State/WorkspaceModel+Lifecycle.swift index 2fe48e7..92c374d 100644 --- a/Sources/HelderUI/State/WorkspaceModel+Lifecycle.swift +++ b/Sources/HelderUI/State/WorkspaceModel+Lifecycle.swift @@ -115,7 +115,7 @@ extension WorkspaceModel { } /// Stops the watchers and polling, waits for the work still running against this project, - /// then saves the note and the session and ends the terminals. + /// then stops reading aloud, saves the note and the session and ends the terminals. func closeProject() async { watcher?.stop() watcher = nil @@ -132,6 +132,7 @@ extension WorkspaceModel { await refresh?.value await symbols?.value for task in running { await task.value } + readAloud.stop() await editor?.flushAutoSaves() await note?.save() await editor?.persist() diff --git a/Sources/HelderUI/State/WorkspaceModel.swift b/Sources/HelderUI/State/WorkspaceModel.swift index 7a57e51..2f1be43 100644 --- a/Sources/HelderUI/State/WorkspaceModel.swift +++ b/Sources/HelderUI/State/WorkspaceModel.swift @@ -79,6 +79,7 @@ public final class WorkspaceModel { public let layout: LayoutStore public let overlay: OverlayStore public let toasts: ToastStore + public let readAloud: ReadAloudStore public internal(set) var sourceControl: SourceControlStore? public internal(set) var explorer: ExplorerStore? public internal(set) var editor: EditorStore? @@ -114,6 +115,7 @@ public final class WorkspaceModel { layout = LayoutStore(session: app.session, persistence: app.layouts) overlay = OverlayStore() toasts = ToastStore() + readAloud = ReadAloudStore(speech: app.speech) terminal = TerminalStore() wireTerminal() overlay.onChange = { [weak self] old, new in self?.overlayChanged(from: old, to: new) } @@ -189,6 +191,8 @@ public final class WorkspaceModel { case .passNote: passNote() case .copyCleanCopy: copyCleanCopy() + case .stopReading: readAloud.stop() + case .openFolder: switchProject { guard let url = await self.app.system.chooseFolder() else { return } diff --git a/Sources/HelderUI/State/WorkspaceServices.swift b/Sources/HelderUI/State/WorkspaceServices.swift index d680bb1..36d2e40 100644 --- a/Sources/HelderUI/State/WorkspaceServices.swift +++ b/Sources/HelderUI/State/WorkspaceServices.swift @@ -46,17 +46,19 @@ public struct AppServices { public var layouts: LayoutPersisting /// Dialogs, pasteboard, Finder. public var system: SystemActing + public var speech: SpeechServicing /// Builds the services for a project folder. public var makeWorkspace: (URL) -> WorkspaceServices public var makeWatcher: () -> FileWatching /// Every store is passed in, so a test can never reach the user's real recents, sessions or layouts. public init(recentProjects: RecentProjectsStoring, session: SessionStoring, layouts: LayoutPersisting, system: SystemActing, - makeWorkspace: @escaping (URL) -> WorkspaceServices, makeWatcher: @escaping () -> FileWatching) { + speech: SpeechServicing, makeWorkspace: @escaping (URL) -> WorkspaceServices, makeWatcher: @escaping () -> FileWatching) { self.recentProjects = recentProjects self.session = session self.layouts = layouts self.system = system + self.speech = speech self.makeWorkspace = makeWorkspace self.makeWatcher = makeWatcher } @@ -66,6 +68,7 @@ public struct AppServices { session: SessionStore(), layouts: UserDefaultsLayoutStore(), system: LiveSystemActions(), + speech: SpeechService(), makeWorkspace: WorkspaceServices.live(root:), makeWatcher: { FSEventsWatcher() } ) diff --git a/Tests/HelderCoreTests/Files/ContextActionsTests.swift b/Tests/HelderCoreTests/Files/ContextActionsTests.swift index 3c20491..9e363d6 100644 --- a/Tests/HelderCoreTests/Files/ContextActionsTests.swift +++ b/Tests/HelderCoreTests/Files/ContextActionsTests.swift @@ -10,10 +10,15 @@ import Testing } @Test func copyAppearsOnlyWithASelection() { - #expect(labels(.terminal(.agent, hasSelection: true)) == ["Copy", "Paste"]) + #expect(labels(.terminal(.agent, hasSelection: true)) == ["Copy", "Paste", "Wait what?"]) #expect(labels(.terminal(.shell, hasSelection: false)) == ["Paste"]) } + @Test func waitWhatAppearsOnlyForASelectionInTheAgentPane() { + #expect(!labels(.terminal(.agent, hasSelection: false)).contains("Wait what?")) + #expect(!labels(.terminal(.shell, hasSelection: true)).contains("Wait what?")) + } + @Test func theActionsNameTheirPane() { #expect(ContextActions.entries(for: .terminal(.shell, hasSelection: true)) == [ .action(.copyTerminalSelection(.shell), label: "Copy"), @@ -83,3 +88,58 @@ import Testing #expect(!hasBouwen(.file(path: "ontwikkelingen/a"))) } } + +@Suite struct ReadAloudContextMenuTests { + private func readAloud(_ target: ContextTarget) -> [ContextMenuEntry] { + ContextActions.entries(for: target).filter { entry in + switch entry { + case .action(.readAloudFile, _), .action(.readAloudText, _): true + default: false + } + } + } + + @Test func aMarkdownFileCanBeReadAloud() { + let entries = ContextActions.entries(for: .file(path: "docs/guide.md")) + #expect(Array(entries[4...6]) == [ + .separator, + .action(.readAloudFile("docs/guide.md"), label: "Read aloud"), + .separator, + ]) + #expect(readAloud(.gitRow(path: "README.md", staged: true)) == [.action(.readAloudFile("README.md"), label: "Read aloud")]) + } + + @Test func otherFilesCannot() { + #expect(readAloud(.file(path: "src/app.php")).isEmpty) + #expect(readAloud(.gitRow(path: "src/app.php", staged: false)).isEmpty) + #expect(readAloud(.directory(path: "docs")).isEmpty) + } + + @Test func aSelectionCanBeReadAloudAfterCopyReference() { + let reference = AgentReference(path: "src/a.php", startLine: 3, endLine: 4) + #expect(ContextActions.entries(for: .editor(reference: reference, code: "$a = 1;", showDiffLine: 3)) == [ + .action(.passOnReference("src/a.php:3-4", code: "$a = 1;"), label: "Pass on selection"), + .action(.copyReference("src/a.php:3-4"), label: "Copy reference"), + .separator, + .action(.readAloudText("$a = 1;"), label: "Read aloud selection"), + .separator, + .action(.showDiff("src/a.php", line: 3), label: "Show diff"), + ]) + } + + @Test func noSelectionNoReadAloud() { + let reference = AgentReference(path: "README.md", startLine: 1) + #expect(readAloud(.editor(reference: reference, code: nil)).isEmpty) + #expect(readAloud(.editor(reference: reference, code: "")).isEmpty) + } + + @Test func selectedMarkdownIsReadAsProse() { + let reference = AgentReference(path: "README.md", startLine: 1) + #expect(readAloud(.editor(reference: reference, code: "## Setup\nRun **this**")) == [ + .action(.readAloudText("Setup.\nRun this."), label: "Read aloud selection"), + ]) + #expect(readAloud(.editor(reference: reference, code: "```\nls\n```")) == [ + .action(.readAloudText("```\nls\n```"), label: "Read aloud selection"), + ]) + } +} diff --git a/Tests/HelderCoreTests/Markdown/MarkdownSpeechTests.swift b/Tests/HelderCoreTests/Markdown/MarkdownSpeechTests.swift new file mode 100644 index 0000000..9158f5a --- /dev/null +++ b/Tests/HelderCoreTests/Markdown/MarkdownSpeechTests.swift @@ -0,0 +1,39 @@ +import Foundation +import HelderCore +import Testing + +@Suite struct MarkdownSpeechTests { + private func speech(_ markdown: String) -> String { + MarkdownSpeech.plainText(MarkdownParser.parse(markdown)) + } + + @Test func eachBlockIsItsOwnSentence() { + #expect(speech("# Title\n\nFirst paragraph\n\nSecond one!") == "Title.\nFirst paragraph.\nSecond one!") + } + + @Test func inlineMarkupIsStrippedAndLinksKeepTheirText() { + #expect(speech("Some **bold**, *soft*, ~~old~~ and `code` in [the docs](https://x.com).") + == "Some bold, soft, old and code in the docs.") + } + + @Test func listItemsQuotesAndTableRowsAreRead() { + #expect(speech("- one\n- two:\n\n> quoted") == "one.\ntwo:\nquoted.") + #expect(speech("| Name | Role |\n|---|---|\n| Ann | dev |") == "Name, Role.\nAnn, dev.") + } + + @Test func codeBlocksAndRulesAreSkipped() { + #expect(speech("Before\n\n```php\necho 1;\n```\n\n---\n\nAfter") == "Before.\nAfter.") + #expect(speech("```\nonly code\n```").isEmpty) + } + + @Test func aDollarSignIsSpokenAsDollar() { + #expect(MarkdownSpeech.spoken("echo $user") == "echo dollar user") + #expect(MarkdownSpeech.spoken("$ x") == "dollar x") + #expect(MarkdownSpeech.spoken("a$$") == "a dollar dollar") + } + + @Test func aDollarBeforeADigitAndTextWithoutDollarStay() { + #expect(MarkdownSpeech.spoken("It costs $5.") == "It costs $5.") + #expect(MarkdownSpeech.spoken("No money here.") == "No money here.") + } +} diff --git a/Tests/HelderUITests/State/WorkspaceModelTests.swift b/Tests/HelderUITests/State/WorkspaceModelTests.swift index 6f6dd04..85199fb 100644 --- a/Tests/HelderUITests/State/WorkspaceModelTests.swift +++ b/Tests/HelderUITests/State/WorkspaceModelTests.swift @@ -625,7 +625,7 @@ import Testing Issue.record("no context menu") return } - #expect(menuLabels(menu) == ["Copy", "Paste"]) + #expect(menuLabels(menu) == ["Copy", "Paste", "Wait what?"]) #expect(menu.header.isEmpty) #expect(menu.anchor == CGPoint(x: 900, y: 300)) } @@ -637,6 +637,14 @@ import Testing #expect(harness.system.copied == ["npm test"]) } + @Test func waitWhatInsertsTheSelectionAsAWaitWhatCommand() async { + let harness = WorkspaceHarness() + harness.agent.selectedText = " the reviewer was unsure\n" + await harness.perform(.context(.waitWhat(.agent))) + #expect(harness.agent.sent == [BracketedPaste.wrap("/wait-what `the reviewer was unsure`", composerHasText: false)]) + #expect(harness.toastTitles == ["Passed to agent"]) + } + @Test func pasteSendsThePasteboardToThatTerminal() async { let harness = WorkspaceHarness() let shell = FakeTerminal() @@ -662,3 +670,78 @@ import Testing } } + +@MainActor +@Suite struct ReadAloudModelTests { + @Test func aMarkdownFileIsReadAsPlainText() async { + let harness = WorkspaceHarness(contents: ["README.md": "# Hello\n\nSome **bold** [link](https://x.com)\n\n```\ncode\n```"]) + await harness.start() + await harness.perform(.context(.readAloudFile("README.md"))) + #expect(harness.speech.spoken == ["Hello.\nSome bold link."]) + #expect(harness.model.readAloud.isReading) + } + + @Test func theOpenFileIsReadWithItsUnsavedEdits() async { + let harness = WorkspaceHarness(contents: ["README.md": "On disk"]) + await harness.start() + harness.model.open("README.md") + await harness.model.settle() + harness.model.editor?.edit("Typed") + await harness.perform(.context(.readAloudFile("README.md"))) + #expect(harness.speech.spoken == ["Typed."]) + } + + @Test func aFileWithoutProseReadsNothingAndSaysSo() async { + let harness = WorkspaceHarness(contents: ["README.md": "```\nonly code\n```"]) + await harness.start() + await harness.perform(.context(.readAloudFile("README.md"))) + #expect(harness.speech.spoken.isEmpty) + #expect(!harness.model.readAloud.isReading) + #expect(harness.toastTitles == ["Nothing to read"]) + } + + @Test func aSelectionIsReadAsItIs() async { + let harness = WorkspaceHarness() + await harness.start() + await harness.perform(.context(.readAloudText("let a = 1"))) + #expect(harness.speech.spoken == ["let a = 1"]) + } + + @Test func aDollarSignIsReadAsDollar() async { + let harness = WorkspaceHarness() + await harness.start() + await harness.perform(.context(.readAloudText("echo $HOME costs $5"))) + #expect(harness.speech.spoken == ["echo dollar HOME costs $5"]) + } + + @Test func stopEndsTheReading() async { + let harness = WorkspaceHarness() + await harness.start() + await harness.perform(.context(.readAloudText("words"))) + await harness.perform(.stopReading) + #expect(harness.speech.stops == 1) + #expect(!harness.model.readAloud.isReading) + } + + @Test func readingToTheEndClearsTheState() async { + let harness = WorkspaceHarness() + await harness.start() + await harness.perform(.context(.readAloudText("words"))) + harness.speech.finish() + #expect(!harness.model.readAloud.isReading) + } + + @Test func aProjectSwitchStopsTheReading() async { + let harness = WorkspaceHarness() + await harness.start() + await harness.perform(.context(.readAloudText("words"))) + await harness.model.openProject(URL(fileURLWithPath: "/fake/other")) + #expect(!harness.model.readAloud.isReading) + #expect(harness.speech.stops == 1) + } + + @Test func readAloudUsesTheSpeakerIcon() { + #expect(ContextMenuOverlay.symbol(for: .readAloudFile("README.md")) == "speaker.wave.2") + #expect(ContextMenuOverlay.tint(for: .readAloudText("x")) == .plain) + } +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeSpeech.swift b/Tests/HelderUITests/Support/Fakes/FakeSpeech.swift new file mode 100644 index 0000000..4c1399f --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeSpeech.swift @@ -0,0 +1,13 @@ +import HelderServices + +/// Records what would have been read aloud; `finish()` plays the voice reaching the end. +@MainActor +final class FakeSpeech: SpeechServicing { + var onFinish: (() -> Void)? + private(set) var spoken: [String] = [] + private(set) var stops = 0 + + func speak(_ text: String) { spoken.append(text) } + func stop() { stops += 1 } + func finish() { onFinish?() } +} diff --git a/Tests/HelderUITests/Support/WorkspaceHarness.swift b/Tests/HelderUITests/Support/WorkspaceHarness.swift index 99b6328..5a02c98 100644 --- a/Tests/HelderUITests/Support/WorkspaceHarness.swift +++ b/Tests/HelderUITests/Support/WorkspaceHarness.swift @@ -18,6 +18,7 @@ struct WorkspaceHarness { let session: FakeSession let layouts: FakeLayouts let system: FakeSystem + let speech: FakeSpeech let watchers: WatcherBox let agent = FakeTerminal() @@ -38,9 +39,10 @@ struct WorkspaceHarness { let recentStore = FakeRecentProjects(recents) let layouts = FakeLayouts() let system = FakeSystem() + let speech = FakeSpeech() let watchers = WatcherBox() let app = AppServices( - recentProjects: recentStore, session: session, layouts: layouts, system: system, + recentProjects: recentStore, session: session, layouts: layouts, system: system, speech: speech, makeWorkspace: { _ in WorkspaceServices(git: git, files: files, search: FakeSearch(), symbols: symbols, config: config, notes: notes, recentFiles: recentFiles) @@ -63,6 +65,7 @@ struct WorkspaceHarness { self.session = session self.layouts = layouts self.system = system + self.speech = speech self.watchers = watchers model.terminal.attach(agent, as: .agent) } diff --git a/docs/architecture.md b/docs/architecture.md index b24ab8a..8ebb229 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -12,15 +12,16 @@ Helder (executable) → HelderUI → HelderServices → HelderCore | Target | May import | Rules | |---|---|---| | `HelderCore` | Foundation | Pure logic and value types, all `Sendable`. No AppKit, no SwiftUI, no disk, no processes. Swift 6 mode. | -| `HelderServices` | HelderCore, Foundation, CoreServices | Everything that touches disk or spawns `git`/`rg`, behind a protocol. Processes only through `ProcessRunning`. | +| `HelderServices` | HelderCore, Foundation, CoreServices, AVFoundation | Everything that touches disk or spawns `git`/`rg`, behind a protocol. Processes only through `ProcessRunning`. | | `HelderUI` | Core, Services, SwiftUI, AppKit, SwiftTerm | `@Observable @MainActor` stores plus views. Never runs a process or touches project files directly, only through the service protocols (the SwiftTerm terminals are the one exception). | | `Helder` | HelderUI | The `@main` app. Keep it tiny. | ## How a window works -- `WorkspaceModel` owns one window (`WorkspaceModel.swift`: state and `perform`; `+Commands`, `+ContextActions`, `+Lifecycle`, `+Refresh` hold the rest): the stores (`SourceControlStore`, `ExplorerStore`, `EditorStore`, `NoteStore`, `CleanCopyStore`, `TerminalStore`, `LayoutStore`, `OverlayStore`, `ToastStore`) and every action that spans more than one of them. A store never reaches into a sibling; `EditorStore` only reads the git state through a closure. +- `WorkspaceModel` owns one window (`WorkspaceModel.swift`: state and `perform`; `+Commands`, `+ContextActions`, `+Lifecycle`, `+Refresh` hold the rest): the stores (`SourceControlStore`, `ExplorerStore`, `EditorStore`, `NoteStore`, `CleanCopyStore`, `TerminalStore`, `LayoutStore`, `OverlayStore`, `ToastStore`, `ReadAloudStore`) and every action that spans more than one of them. A store never reaches into a sibling; `EditorStore` only reads the git state through a closure. - **One entry point.** Views, the menu bar and the key router all call `WorkspaceModel.perform(Command)` (`Shell/Command.swift`). Context-menu items arrive as `.context(ContextAction)`; the model asks `SourceControlStore.confirmation(for:)` / `ExplorerStore.confirmation(for:)` first and shows the confirm overlay, and `.confirmPending` runs the action. The name prompt submits with `.submitName`, the pass-on prompt with `.passToAgent`, the note's ⌘P with `.passNote`. - **Overlays never stack.** `OverlayStore.current` is one `Overlay` enum; only the model presents or dismisses it. `OverlayStore.onChange` lets the model run closing behaviour however an overlay went away (the note saves, the Diff gives back the mode it covered). `OverlayHost` draws the current overlay. `.launcher` is the ⇧⌘O "Open recent project" list; the bare window's launcher is part of the shell, not an overlay. The key router only sees `OverlayKind` (`none`, `note`, `diff(busy:)`, `other`): over the Diff the workspace keys keep working unless its own menu or prompt is open (`busy`). Toasts (`ToastStore`) may sit on top. The Diff draws its own right-click menu and pass-on prompt inside itself, so it stays open. +- **Read aloud.** `.readAloudFile` reads the open file's buffer (unsaved edits included) or the file from disk, turns it into prose with `MarkdownSpeech`, and hands it to `ReadAloudStore`; `.readAloudText` speaks the selection (selected Markdown as prose). `ReadAloudStore` lives as long as the window, like `ToastStore`; its `isReading` shows the title bar's Stop, which runs `.stopReading`. `closeProject()` stops the reading. - **Stores report, the model shows.** Stores raise toasts through `notify`/`showToast` hooks the model wires to `ToastStore`; the model never toasts a second time for the same action. - **Closing.** A window close, a project switch and ⌘Q all run `prepareToClose()` first: every unsaved file (at most the open one plus a vanished-file buffer) is asked about, and a cancel keeps everything open. Then `closeProject()` waits for running work, writes the note and session and ends the terminals. - **Lifecycle.** `start()`: recents → config (applied to every store and the terminals) → git, tree, note and the `.clean-copy` baseline in parallel → `editor.restore` → watcher → git polling (`git.refreshInterval`) → the PHP class list 1.5 s later. Watcher events: `.cleanCopy` (`.clean-copy` in the root, 150 ms debounce, fired besides `.project`) makes `CleanCopyStore` re-read the file and opens the `.cleanCopy` overlay for new non-blank text (the text found at load is the baseline; another open overlay makes it wait, keeping only the newest); `.project` re-reads git, the tree, the open file and every unsaved buffer (the edits kept), invalidates the symbol index and reloads the class list 2 s after the last change; `.git` re-reads git; `.config` re-resolves and re-applies the config. ⌘R re-reads git and the tree and lets the disk win in the open file. A project switch or window close saves the note and the session, stops the watcher and polling, and ends both terminals. @@ -40,7 +41,7 @@ Sources/HelderCore/ Files/ FileNode + FileTree, PathUtils, FileType (language, badge), limits + ignore rules, ContextActions (menus) Git/ GitStatus/Change/GitSnapshot, Porcelain parsing, GitDerivation (rows, grouping, commit text) Highlight/ SyntaxHighlighter and one grammar per language - Markdown/ block/inline tree and parser + Markdown/ block/inline tree and parser, MarkdownSpeech (the prose Read aloud speaks) Search/ result models, Fuzzy, InFileSearch, rg --json parsing Session/ SessionState, LayoutState, recents, ColumnLayout, Cursor/LineSelection/OpenOptions Symbols/ PHP symbol models and line parsers @@ -51,6 +52,7 @@ Sources/HelderServices/ Process/ ProcessRunner, ExecutableLocator, ChildReaper, InstanceLauncher Project/ ConfigService, NotesService, RecentStores, SessionStore, ProjectLocator Search/ SearchServicing + RipgrepSearchService, ProjectScanner (rg, or a Swift walk) + Speech/ SpeechServicing + SpeechService (AVSpeechSynthesizer, the system voice), shared by the window Symbols/ SymbolService Sources/HelderUI/ State/ WorkspaceModel (+ extension files), WorkspaceServices/AppServices, one file per store diff --git a/docs/behaviour.md b/docs/behaviour.md index 4f91798..82fc266 100644 --- a/docs/behaviour.md +++ b/docs/behaviour.md @@ -35,6 +35,7 @@ The top bar contains, left to right: - A breadcrumb showing the path to the active file, for example `console / src / Http / Controller / UserController.php`. The breadcrumb is **display only** for now. It is not clickable and does not navigate. - Centred on the window, the **pane toggles**: Git · Explorer · File · Claude, one per column, all on by default (see Pane toggles in section 9). The breadcrumb truncates before it reaches them. - On the right, the toolbar: **Search** (`Cmd+F`) and **Note** (`Cmd+N`) are actions; **Fluid** (`Cmd+L`) and **Hidden** (`Cmd+.`) are toggles. Then `?` for the keyboard shortcuts. +- While Helder reads aloud, a **Stop** toggle appears left of **Search**, in the same style and switched on. A click switches it off and stops the reading; the button then goes away. It also goes away when the reading reaches the end, and a project switch or window close stops the reading. --- @@ -107,6 +108,7 @@ The second column. A standard project file tree. - **Left-click** a file opens it in the editor. The selected file is highlighted. - The tree hides paths matched by `files.exclude` and, when `files.followGitignore` is on, paths ignored by git. - **Right-click** a file offers **Copy reference**, which copies the file's project-relative path to the clipboard (the file-level form of the editor's Copy reference). +- A Markdown file (`.md`) also offers **Read aloud**, in its own group after the pass-on and copy items, in the Explorer and on its git rows. Helder reads the text with the system voice: headings, paragraphs, list items, quotes and table cells, with the markup and link URLs left out and code blocks skipped. The open file is read as it stands in the editor, unsaved edits included. A file with nothing to read shows `Nothing to read`. A new Read aloud replaces the one that is playing. A `$` is read as "dollar", except before a digit (`$5` stays "five dollars"). --- @@ -152,7 +154,9 @@ Right-clicking inside the code area, with or without a selection, shows a contex 1. **Copy reference**: copies a reference to the clicked location to the clipboard. With no selection it is path plus single line, for example `src/Http/Controller/UserController.php:42`. With a selection it is path plus start and end line, for example `src/Http/Controller/UserController.php:42-58`. The path is project-relative. 2. **Pass on to Agent**: opens a small inline input popup anchored near the click or selection, with a single optional text field. On confirm (`Enter`), it composes one line, the typed text followed by the same reference, and inserts it into the agent pane's input. The insert does **not** submit. It lands as a new, unsubmitted line and the cursor sits on a fresh line, so the action can be repeated to stack several references before the user sends. `Esc` cancels with no insert. An empty field passes the bare reference. -On a marked line of the live file (any marked line, blank lines and the space after the text included), a separator and a third item follow: **Show diff**, which opens the Diff centred on that line. A new file, Preview and the Diff's own menu have no Show diff. +With a selection, a separator and **Read aloud selection** follow Copy reference. It reads the selected text with the system voice; in a Markdown file the selection is read as prose, the markup left out. The rendered Markdown preview has no Read aloud selection; its selection is not Helder's (use Read aloud on the file). + +On a marked line of the live file (any marked line, blank lines and the space after the text included), a separator and a last item follow: **Show diff**, which opens the Diff centred on that line. A new file, Preview and the Diff's own menu have no Show diff. ### File-state behavior in the views diff --git a/docs/guide/right-click-menu.md b/docs/guide/right-click-menu.md index 536147a..f33d936 100644 --- a/docs/guide/right-click-menu.md +++ b/docs/guide/right-click-menu.md @@ -26,7 +26,7 @@ Helder draws its own right-click menu, in the same dark style everywhere. This p 3. **Separator**: a thin line between groups of items. 4. **Destructive item**: Discard and Delete read in amber-deep, so they stand out. -Each item has a small icon. Add-type items (Stage, New file, New folder) have a teal icon. Copy file name, Unstage and Show in Finder have an amber icon. +Each item has a small icon. Add-type items (Stage, New file, New folder) have a teal icon. Copy file name, Unstage and Show in Finder have an amber icon. Read aloud has a speaker icon. ## Features @@ -56,6 +56,7 @@ These items show up in several menus. | **Pass on file name** | Opens the Pass on prompt with only the file name, without folders. | No | | **Copy file name** | Copies only the file name. A notification says `Copied`. | No | | **Show in Finder** | Opens a Finder window with the item selected. | No | +| **Read aloud** | Markdown files only. Reads the file aloud with the system voice. Stop it with **Stop** in the [title bar](title-bar.md#read-aloud). | No | ### Git rows @@ -119,6 +120,26 @@ Right-click a file in the [Explorer](explorer.md). The header is the file's path +----------------------------------------+ ``` +A Markdown file (`.md`), in the Explorer or on a git row, gets one extra group after the copy items: + +```text ++----------------------------------------+ +| docs/setup.md | +|----------------------------------------| +| * Pass on reference | +| # Copy reference | +| * Pass on file name | +| # Copy file name | +|----------------------------------------| +| )) Read aloud | +|----------------------------------------| +| / Rename file | +| ... | ++----------------------------------------+ +``` + +- **Read aloud**: reads the headings, paragraphs, list items, quotes and table cells aloud. Markup and link addresses are left out, and code blocks are skipped. The open file is read as it stands in the editor, unsaved edits included. A file with nothing to read shows `Nothing to read`. Reading another file stops the first one. + - **Rename file**: opens the [name prompt](dialogs.md#name-prompt) with the current name. Only the part before the extension is selected, so typing keeps the extension. - **Delete file**: always asks first; see [Dialogs](dialogs.md#delete-file-or-folder). The file is deleted for good, not moved to the Trash. @@ -200,6 +221,8 @@ With a selection: +----------------------------------------+ | * Pass on selection | | # Copy reference | +|----------------------------------------| +| )) Read aloud selection | +----------------------------------------+ ``` @@ -215,8 +238,9 @@ On a marked (teal) line of a changed file: ``` - **Pass on selection** passes the reference and the selected code. See [Pass on to Agent](pass-on-to-agent.md). +- **Read aloud selection** reads the selected text aloud. In a Markdown file the markup is left out. Stop it with **Stop** in the [title bar](title-bar.md#read-aloud). - **Show diff** opens the full-screen [Diff](file-view-diff.md) of the file, centred on the line you right-clicked. Every marked line counts, a blank one and the space after the text included. A new file, where every line is marked, has no Show diff. A left click on a marked line only places the caret. -- The same menu shows on the rendered [Markdown preview](file-view-markdown.md) and on an image. There it refers to the file's first line, for example `README.md:1`. +- The same menu shows on the rendered [Markdown preview](file-view-markdown.md) and on an image. There it refers to the file's first line, for example `README.md:1`, and has no Read aloud selection. To hear a previewed file, right-click it in the Explorer and choose **Read aloud**. - `Cmd+Right` with code selected opens the Pass on prompt straight away, without the menu. ### Diff @@ -244,9 +268,13 @@ With text selected in the pane: +----------------------------------------+ | # Copy | | # Paste | +|----------------------------------------| +| ? Wait what? | +----------------------------------------+ ``` +Wait what? shows only in the Claude Code pane, not in the Command line pane. + Without a selection: ```text @@ -257,6 +285,7 @@ Without a selection: - **Copy** (only with a selection): copies the selected terminal text. - **Paste**: types the clipboard text into that pane, as a normal paste would. With an empty clipboard nothing happens. +- **Wait what?** (Claude Code pane, only with a selection): inserts ``/wait-what `selected text` `` into the [Claude Code](claude-code.md) input, not sent. Spaces and blank lines around the selection are trimmed. A [notification](notifications.md) says `Passed to agent`. ## Keyboard diff --git a/docs/guide/title-bar.md b/docs/guide/title-bar.md index b2d3692..8dc9316 100644 --- a/docs/guide/title-bar.md +++ b/docs/guide/title-bar.md @@ -18,6 +18,12 @@ The title bar is the 44-point strip across the top of a project window. It tells The bar is one row in the app. It is drawn on two rows here to fit the page. +While Helder reads aloud, a **Stop** button leads the toolbar: + +```text +| [.Stop |Search |.Fluid |.Hidden |Note] [?] | +``` + 1. **Window buttons**: the macOS close, minimize and zoom buttons. 2. **Wordmark**: "Helder" with a blinking amber dot. 3. **Project name**: the project folder's name. Click it to open another folder. @@ -64,6 +70,12 @@ The toolbar sits on the right. Each button shows its shortcut next to its label. Fluid and Hidden carry a state dot like the pane toggles. Search and Note have no dot, because they are actions. Hover any button for a tooltip that explains its current state. +### Read aloud +- **Stop** shows only while Helder reads a file or a selection aloud. Start the reading from the [right-click menu](right-click-menu.md): **Read aloud** on a Markdown file, **Read aloud selection** in the code. +- It sits left of **Search**, in the same style, and its dot is on. The tooltip says "Read aloud: playing. Click to stop." +- Click it to switch it off: the reading stops and the button goes away. +- The button also goes away when the reading reaches the end. Switching projects or closing the window stops the reading. + ### Moving the window Drag an empty part of the title bar to move the window, as in any macOS app. @@ -87,3 +99,4 @@ Drag an empty part of the title bar to move the window, as in any macOS app. - [Keyboard shortcuts](keyboard-shortcuts.md): the overlay the `?` button opens. - [Recent projects](recent-projects.md): opening another folder. - [Status bar](status-bar.md): the matching bar at the bottom of the window. +- [Right-click menu](right-click-menu.md): where Read aloud starts.