From a7fd106fb61f4a1e98a6ee7280074e3ee06a4a28 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:57:37 -0600 Subject: [PATCH 1/4] Live voice saves what was said into the chat it continues Each finished line of a call (the person's or the voice model's, a cut-off reply marked as interrupted) goes to the plugin's voice/transcript route and becomes an ordinary message in the chat, so typing afterwards carries on the same conversation. LiveVoiceSpokenTurns keeps one journal per computer, agent and chat, sends lines in order until the chat takes them (a running turn answers voice_chat_busy), over whatever connection to that computer is current. A new call saves what the last one left before the plugin reads the chat, and the words before a request go in before its turn. Needs plugin feature native-voice-history-v1. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 8 + Bighelp.xcodeproj/project.pbxproj | 8 + Bighelp/App/NativeWorkspaceRuntime.swift | 36 +++- .../DirectHermesNativeContext.swift | 3 + Bighelp/Voice/LiveVoiceSpokenTurns.swift | 162 ++++++++++++++++++ Bighelp/Voice/NativeLiveVoiceSession.swift | 23 ++- Bighelp/Workspace/WorkspaceOperation.swift | 2 + BighelpTests/LiveVoiceSpokenTurnsTests.swift | 108 ++++++++++++ BighelpTests/NativeLiveVoiceTests.swift | 79 ++++++++- docs/DIRECT_STREAMING_AND_LIVE_VOICE.md | 13 ++ 10 files changed, 439 insertions(+), 3 deletions(-) create mode 100644 Bighelp/Voice/LiveVoiceSpokenTurns.swift create mode 100644 BighelpTests/LiveVoiceSpokenTurnsTests.swift diff --git a/AGENTS.md b/AGENTS.md index 8cea49d8..4d01ae62 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -420,6 +420,14 @@ change in both repos. the chat when it's free; one made while the chat works runs at once as a Hermes background task for it (`ChatModel.runNativeVoiceRequest`, `prompt.background`) and answers the call on its own. Background tasks can't reach the phone's tools. +- **A call continues its chat, both ways** (plugin `native-voice-history-v1`): the plugin reads the chat the + offer names (its newest messages with their roles, its compaction summary, the request still running) into + every provider's instructions before the voice model listens. Each finished line of the call (person or + voice model, a cut-off reply marked `interrupted`) goes back into the chat as an ordinary message through + `voice/transcript` (`LiveVoiceSpokenTurns`), which runs nothing and saves each line once. The plugin writes + only while no turn runs (`voice_chat_busy`), so the journal sends the same lines again until the chat takes + them, over whatever connection to that computer is current. One journal per computer, agent and chat: a new + call's offer waits for an earlier call's lines, and the lines before a request go before its turn. - **On-device voices** (`Bighelp/Voice/OnDevice/`): Phonon speaks on the iPhone or iPad instead of the computer. It's chosen per agent in Voice settings and kept on the device (`OnDeviceVoiceChoices`, by computer and agent); the agent's `tts.*` on the computer never changes. `OnDeviceVoiceSettingsClient` adds it to the diff --git a/Bighelp.xcodeproj/project.pbxproj b/Bighelp.xcodeproj/project.pbxproj index 7c3b7099..3a8e36fe 100644 --- a/Bighelp.xcodeproj/project.pbxproj +++ b/Bighelp.xcodeproj/project.pbxproj @@ -232,6 +232,7 @@ 1C2BB4E83D031A33B376321C /* BighelpShortcutService+Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19D7160AE9C689BF3CA8ECC8 /* BighelpShortcutService+Actions.swift */; }; 1C583C9DF419F0654D7CDC02 /* DevFactoryStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0434D211AF76E67D497A6E46 /* DevFactoryStore.swift */; }; 1C763567CD9CCE8F93EA60F8 /* HostSignInMatrixUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37C85FB08FD771ED53292DB4 /* HostSignInMatrixUITests.swift */; }; + 1C9D4B5D6383FA47982722F7 /* LiveVoiceSpokenTurns.swift in Sources */ = {isa = PBXBuildFile; fileRef = 743E14DEEDCC37C613D31F30 /* LiveVoiceSpokenTurns.swift */; }; 1CAD3F56F34703C56D4795E1 /* DirectHermesProjectClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2F8FB47038C2E9A1EE89696 /* DirectHermesProjectClientTests.swift */; }; 1CBBCA37E4825CA82FAB683F /* SimpleBotProfileExtras.swift in Sources */ = {isa = PBXBuildFile; fileRef = D51BF68C15E152807C58243B /* SimpleBotProfileExtras.swift */; }; 1CBFD9B876E36D5544E7129A /* ChatsInboxView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA031A13A7DDB2CCF96B99A3 /* ChatsInboxView.swift */; }; @@ -1941,6 +1942,7 @@ E631FB670F611061813B80C9 /* ModelNameCatalogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06E0752CDEB93F69DFC3661C /* ModelNameCatalogTests.swift */; }; E64170A092AE47599073DA7A /* ChatNewChatSlot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 49C6C5B621D594D25819458C /* ChatNewChatSlot.swift */; }; E64E2686D7C3C64D3E3E529A /* VoiceOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 558FB53391D183473F14A43A /* VoiceOptions.swift */; }; + E6619435B9EA0C05882CB280 /* LiveVoiceSpokenTurnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32C416483341AB26D7091D6B /* LiveVoiceSpokenTurnsTests.swift */; }; E67563B3E12A73308A799A38 /* AgentTemplateBrowser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B51E351013BB3D09F5BF96A /* AgentTemplateBrowser.swift */; }; E6B5DA183CBCD546DCAABD9B /* ChatLayoutPreferencesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F26A9153E01384FF3334E701 /* ChatLayoutPreferencesTests.swift */; }; E6BE2C3667CEEEBA7A13FB3A /* RichDraftRecoveryStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9341CEE698D541FD92FE8E4B /* RichDraftRecoveryStore.swift */; }; @@ -2691,6 +2693,7 @@ 32935F0C3FF3C44EDE17455D /* BighelpInterfaceSize.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpInterfaceSize.swift; sourceTree = ""; }; 32A8093F2FE15DF1627DCB77 /* ChatStreamingAnchorUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatStreamingAnchorUITests.swift; sourceTree = ""; }; 32C3489FFED4C0F54190BB0F /* BighelpCardCatalogView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpCardCatalogView.swift; sourceTree = ""; }; + 32C416483341AB26D7091D6B /* LiveVoiceSpokenTurnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveVoiceSpokenTurnsTests.swift; sourceTree = ""; }; 32CB21AAA8E67876D78BC09D /* ThinkingLadder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThinkingLadder.swift; sourceTree = ""; }; 32E521E0B53082AC36D71775 /* HermesBlobEditsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HermesBlobEditsTests.swift; sourceTree = ""; }; 33254D4EC0561796677A14F8 /* ClipboardAttachmentTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClipboardAttachmentTests.swift; sourceTree = ""; }; @@ -3235,6 +3238,7 @@ 73FA2398602D858EDB43E766 /* DeviceFocusToolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceFocusToolTests.swift; sourceTree = ""; }; 7437B65BFB4AFEE0CCB68086 /* BighelpActivityAvatarWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpActivityAvatarWriter.swift; sourceTree = ""; }; 743A8422BB20CF6C30B55B4B /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = ""; }; + 743E14DEEDCC37C613D31F30 /* LiveVoiceSpokenTurns.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveVoiceSpokenTurns.swift; sourceTree = ""; }; 7445286B80C4CA76D5634B40 /* PermissionsViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PermissionsViews.swift; sourceTree = ""; }; 7459CDC081DDB6A14E0C9F21 /* ChatCompactionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatCompactionTests.swift; sourceTree = ""; }; 74707D0902600D341422EDD9 /* SessionEditorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionEditorTests.swift; sourceTree = ""; }; @@ -5963,6 +5967,7 @@ 426C42D8F875320110D6639E /* LiveVoiceDebugTests.swift */, 930BE7C3699C14551E96C567 /* LiveVoiceFailureRecoveryTests.swift */, F50CA5FA31F95111A047BE14 /* LiveVoiceReadinessTests.swift */, + 32C416483341AB26D7091D6B /* LiveVoiceSpokenTurnsTests.swift */, 8AE3F5EF033F2E51AC96DFFA /* LiveVoiceUnavailableTests.swift */, A24F8EDFED2D47FDF964F65C /* LocalizationTests.swift */, 8B9BFECF9345E2D8DC72595E /* LongTextEditorTests.swift */, @@ -6600,6 +6605,7 @@ E2733FF4EBE31845361EA75E /* LiveVoiceControlClient.swift */, 109F04DFB422C0BB43066B7A /* LiveVoiceDebug.swift */, 6BFBFE60217D0F9676F7FD23 /* LiveVoiceModel.swift */, + 743E14DEEDCC37C613D31F30 /* LiveVoiceSpokenTurns.swift */, C060C8B5BD2262CCDADA50B1 /* LiveVoiceUnavailable.swift */, 3DE2AFF1D5FD9181A8FD5C0C /* LiveVoiceView.swift */, F83C6C89073925B7B902D076 /* NativeLiveVoiceSession.swift */, @@ -8846,6 +8852,7 @@ FA331C57EB24656B155C52F3 /* LiveVoiceControlClient.swift in Sources */, 2D5C56C4141E0E2AE210CCC1 /* LiveVoiceDebug.swift in Sources */, B98024B47619F441AB7EE964 /* LiveVoiceModel.swift in Sources */, + 1C9D4B5D6383FA47982722F7 /* LiveVoiceSpokenTurns.swift in Sources */, C8AD5F30F3BF6451299274CB /* LiveVoiceUnavailable.swift in Sources */, 798AB46934955192680B3C22 /* LiveVoiceView.swift in Sources */, 1D0ED381C419538DC3C37394 /* LocalModelsStore.swift in Sources */, @@ -9772,6 +9779,7 @@ B31182743F5AB3DE1031179C /* LiveVoiceDebugTests.swift in Sources */, D2C62A26D889E650BD2ECBE4 /* LiveVoiceFailureRecoveryTests.swift in Sources */, C5C7D6DF90F63E17E68BD8F9 /* LiveVoiceReadinessTests.swift in Sources */, + E6619435B9EA0C05882CB280 /* LiveVoiceSpokenTurnsTests.swift in Sources */, BD93F85CEA873C499CE14AEE /* LiveVoiceUnavailableTests.swift in Sources */, 18D4DFDDC85C7D8F532A22BA /* LocalizationTests.swift in Sources */, 0245FA2481F1D25284A33027 /* LongTextEditorTests.swift in Sources */, diff --git a/Bighelp/App/NativeWorkspaceRuntime.swift b/Bighelp/App/NativeWorkspaceRuntime.swift index 80bfebc8..46176ca7 100644 --- a/Bighelp/App/NativeWorkspaceRuntime.swift +++ b/Bighelp/App/NativeWorkspaceRuntime.swift @@ -466,6 +466,8 @@ final class NativeWorkspaceRuntime { let context = LiveVoiceCallContext.offerContext( features: workspace.nativeContext?.features ?? [], agentName: agent?.name, personName: { [weak userIdentity] in userIdentity?.identity.name }, place: .shared) + let spoken = Self.spokenTurns(for: voiceOwner, features: workspace.nativeContext?.features ?? [], + connections: connections, authority: authority, chat: chat) let voice = NativeLiveVoiceSession(owner: voiceOwner, operation: { operation, payload in try await workspace.perform(operation, payload: payload, owner: owner) }, isCurrent: { [weak connections] in connections?.owner == owner }, @@ -476,7 +478,7 @@ final class NativeWorkspaceRuntime { }, submit: { [weak chat] text in guard let chat else { throw LiveVoiceControlError.wrongOwner } return try await chat.runNativeVoiceRequest(text) - }, context: context) + }, context: context, spoken: spoken) return .success(voice.makeModel(agentName: agent?.name ?? "Hermes")) } // Native creation already captures the verified selected cwd before @@ -1085,3 +1087,35 @@ private final class ReplyVoiceCache { return output } } + +extension NativeWorkspaceRuntime { + /// The journal of what calls say in this chat, for a computer whose plugin saves it there. Each send takes + /// the connection to this computer that is current then, so lines a call left still go in after a + /// reconnect; the chat reads what was saved, so the lines show in it. + static func spokenTurns(for owner: LiveVoiceOwner, features: Set, connections: WorkspaceConnectionStore, + authority: WorkspaceAuthority, chat: ChatModel) -> LiveVoiceSpokenTurns? { + guard features.contains(LiveVoiceSpokenTurns.feature) else { return nil } + let journal = LiveVoiceSpokenTurns.shared(hostID: owner.hostID, agentID: owner.agentID, sessionID: owner.sessionID) + journal.send = { [weak connections] voiceID, lines in + guard let connections, let current = connections.owner, current.authority == authority, + let workspace = connections.workspace, + workspace.nativeContext?.features.contains(LiveVoiceSpokenTurns.feature) == true else { return .wait } + do { + _ = try await workspace.perform(.nativeVoiceTranscript, payload: [ + "agentId": .string(owner.agentID), "sessionId": .string(owner.sessionID), + "voiceId": .string(voiceID), "items": .array(lines), + ], owner: current) + return .saved + } catch WorkspaceClientError.rejected(let code, _) { + // A running turn holds the chat; anything else it refused, it will refuse again. + return code == "voice_chat_busy" || code == "context_changed" ? .wait : .refused + } catch WorkspaceClientError.unavailable { + return .refused + } catch { + return .wait + } + } + journal.onSaved = { [weak chat] in chat?.refreshFromHostSoon() } + return journal + } +} diff --git a/Bighelp/DirectHermes/DirectHermesNativeContext.swift b/Bighelp/DirectHermes/DirectHermesNativeContext.swift index 894920c9..049696e7 100644 --- a/Bighelp/DirectHermes/DirectHermesNativeContext.swift +++ b/Bighelp/DirectHermes/DirectHermesNativeContext.swift @@ -327,6 +327,9 @@ final class DirectHermesNativePluginClient { case .nativeVoiceGeminiOffer: return Route(path: "voice/offer", feature: "native-voice-gemini-v1", isMutation: true, maximumResponseBytes: 196_608) + case .nativeVoiceTranscript: + return Route(path: "voice/transcript", feature: LiveVoiceSpokenTurns.feature, isMutation: true, + maximumResponseBytes: 65_536) case .projectsGitCapabilities: return Route(path: "projects/git/capabilities", feature: "native-project-git-read-v1", isMutation: false, maximumResponseBytes: 196_608) diff --git a/Bighelp/Voice/LiveVoiceSpokenTurns.swift b/Bighelp/Voice/LiveVoiceSpokenTurns.swift new file mode 100644 index 00000000..896c1713 --- /dev/null +++ b/Bighelp/Voice/LiveVoiceSpokenTurns.swift @@ -0,0 +1,162 @@ +import Foundation +import os + +/// The finished lines of live voice calls on their way into the chat each call opened in (plugin +/// `native-voice-history-v1`), so typing afterwards carries on the same conversation. +/// +/// A line goes once it ends: what the person said, or what the voice model said back, cut where the person +/// interrupted it. The plugin appends each as an ordinary message without running anything, only while no turn +/// runs in the chat (`voice_chat_busy` otherwise), and at most once per call and line, so lines are sent in +/// order until the chat takes them, however often a send is repeated. Delegated work is already its own turn +/// in the chat; nothing here sends it again. +/// +/// One journal serves one chat on one computer (`shared(hostID:agentID:sessionID:)`): a call opened again in +/// the chat goes on with what an earlier call still holds, and its offer waits for those lines first, so the +/// chat it reads already has them. Lines outlive their call and its connection: `send` takes whatever +/// connection to the computer is current, and a journal stays alive while it has lines to try again. +@MainActor +final class LiveVoiceSpokenTurns { + struct Line: Equatable { + let voiceID: String + let id: String + let role: String + let text: String + let interrupted: Bool + let at: Date + + var wire: BighelpJSONValue { + .object(["id": .string(id), "role": .string(role), "text": .string(text), + "interrupted": .boolean(interrupted), "at": .number(at.timeIntervalSince1970)]) + } + } + + enum Outcome: Equatable, Sendable { + /// The chat holds them now (or held them already). + case saved + /// A turn runs in the chat, or the computer didn't answer: try again later. + case wait + /// The chat will never take them: not this agent's, gone, or a plugin without the route. + case refused + } + + typealias Send = @MainActor (_ voiceID: String, _ lines: [BighelpJSONValue]) async -> Outcome + + static let feature = "native-voice-history-v1" + static let maximumLines = 256 + static let maximumBatch = 32 + static let maximumTextLength = 4_000 + /// Waits between tries while the chat is busy or the computer is away; the last repeats until `giveUpAfter`. + static let retryWaits: [Duration] = [.seconds(1), .seconds(2), .seconds(4), .seconds(8), .seconds(15), .seconds(30)] + /// A delegated turn can run a long time. Lines that waited this long without a save are let go. + static let giveUpAfter: Duration = .seconds(30 * 60) + + private(set) var pending: [Line] = [] + /// The newest call's way to the computer; a call opened later in the same chat replaces it. + var send: Send? + /// Lines reached the chat: it reads what the computer saved. + var onSaved: (@MainActor () -> Void)? + private var round: Task? + private var retry: Task? + private var failures = 0 + private var waited: Duration = .zero + private var lineCount = 0 + private let retryWaits: [Duration] + private let giveUpAfter: Duration + private let now: () -> Date + + private static let logger = Logger(subsystem: "app.loopdy.mobile", category: "LiveVoice") + private static var journals: [String: WeakJournal] = [:] + + init(retryWaits: [Duration] = LiveVoiceSpokenTurns.retryWaits, giveUpAfter: Duration = LiveVoiceSpokenTurns.giveUpAfter, + now: @escaping () -> Date = Date.init) { + self.retryWaits = retryWaits.isEmpty ? Self.retryWaits : retryWaits + self.giveUpAfter = giveUpAfter + self.now = now + } + + /// The journal of one chat on one computer: the same object for every call in it while one is alive. + static func shared(hostID: String, agentID: String, sessionID: String) -> LiveVoiceSpokenTurns { + let key = [hostID, agentID, sessionID].joined(separator: "\u{1F}") + journals = journals.filter { $0.value.journal != nil } + if let journal = journals[key]?.journal { return journal } + let journal = LiveVoiceSpokenTurns() + journals[key] = WeakJournal(journal: journal) + return journal + } + + /// One finished line of call `voiceID`. Empty lines and anything past the bounds are left out. + func add(voiceID: String, role: String, text: String, interrupted: Bool = false) { + let text = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard role == "user" || role == "assistant", !text.isEmpty, pending.count < Self.maximumLines else { return } + lineCount += 1 + pending.append(Line(voiceID: voiceID, id: "\(role.prefix(1))\(lineCount)", role: role, + text: String(text.prefix(Self.maximumTextLength)), interrupted: interrupted, at: now())) + startRound() + } + + /// Sends what waits and returns when this try ends, saved or not; a busy chat gets more tries later. + func flush() async { + await startRound().value + } + + /// As `flush`, but returns after `seconds` at most, so a call or a request never waits long on it. The + /// send itself goes on. + func flush(waitingAtMost seconds: Double) async { + guard !pending.isEmpty else { return } + let round = startRound() + _ = try? await DeviceLocationDeadline.run(seconds: seconds) { await round.value } + } + + @discardableResult + private func startRound() -> Task { + if let round { return round } + let next = Task { [self] in + await sendPending() + round = nil + } + round = next + return next + } + + private func sendPending() async { + while let first = pending.first { + guard let send else { return scheduleRetry() } + let batch = Array(pending.prefix(Self.maximumBatch).prefix { $0.voiceID == first.voiceID }) + switch await send(first.voiceID, batch.map(\.wire)) { + case .saved: + pending.removeFirst(batch.count) + (failures, waited) = (0, .zero) + onSaved?() + case .refused: + // Nothing will take them; keeping them would hold up every later line. + Self.logger.notice("Live voice lines refused by the chat: \(batch.count, privacy: .public)") + pending.removeFirst(batch.count) + case .wait: + return scheduleRetry() + } + } + } + + private func scheduleRetry() { + guard retry == nil, !pending.isEmpty else { return } + guard waited < giveUpAfter else { + Self.logger.notice("Live voice lines let go after waiting: \(self.pending.count, privacy: .public)") + pending.removeAll() + (failures, waited) = (0, .zero) + return + } + let wait = retryWaits[min(failures, retryWaits.count - 1)] + failures += 1 + waited += wait + // The task holds the journal, so lines still waiting outlive the call that said them. + retry = Task { [self] in + try? await Task.sleep(for: wait) + retry = nil + startRound() + } + } + + private struct WeakJournal { + weak var journal: LiveVoiceSpokenTurns? + } +} diff --git a/Bighelp/Voice/NativeLiveVoiceSession.swift b/Bighelp/Voice/NativeLiveVoiceSession.swift index 7a8e3709..82c7348e 100644 --- a/Bighelp/Voice/NativeLiveVoiceSession.swift +++ b/Bighelp/Voice/NativeLiveVoiceSession.swift @@ -8,6 +8,11 @@ import Foundation /// GPT-Live's events come from the host's feed (`poll`) and its results go back /// through the host. A Gemini call's events come from the phone's own connection /// (`LiveVoiceLocalSession`), and its results go back to it as `UPDATE` text. +/// +/// A call continues its chat both ways: the plugin reads the chat into the offer, and +/// each finished line of the call goes back into it (`spoken`). Lines an earlier call in +/// the chat still holds go first, before the offer reads the chat, and the lines before a +/// request go before the request's own turn, so the chat keeps the order they were said in. @MainActor final class NativeLiveVoiceSession { typealias Operation = @MainActor (WorkspaceOperation, [String: BighelpJSONValue]) async throws -> [String: BighelpJSONValue] @@ -30,6 +35,8 @@ final class NativeLiveVoiceSession { var seen: [String: String] = [:] var pending: [String: Task] = [:] var transcripts: [(Int, String)] = [] + /// The provider dropped the reply's audio: the person cut it off, and its line ends there. + var audioCleared = false var contextOffset = -1 var contextIncomplete = false var closeCleanup: (@MainActor () async -> Void)? @@ -47,6 +54,8 @@ final class NativeLiveVoiceSession { private let closeCleanupFactory: CloseCleanupFactory? private let submit: Submit private let context: Context? + /// The chat's journal of spoken lines, on a computer that lists `native-voice-history-v1`. + private let spoken: LiveVoiceSpokenTurns? private var call: Call? private var pollTask: Task? private weak var model: LiveVoiceModel? @@ -57,13 +66,15 @@ final class NativeLiveVoiceSession { isCurrent: @escaping @MainActor () -> Bool, closeCleanupFactory: CloseCleanupFactory? = nil, submit: @escaping Submit, - context: Context? = nil) { + context: Context? = nil, + spoken: LiveVoiceSpokenTurns? = nil) { self.owner = owner self.operation = operation self.isCurrent = isCurrent self.closeCleanupFactory = closeCleanupFactory self.submit = submit self.context = context + self.spoken = spoken } func makeModel( @@ -105,6 +116,8 @@ final class NativeLiveVoiceSession { // The phone's context rides in the offer; the offer's own fields win. var fields = fields if let context { fields.merge(await context()) { own, _ in own } } + // What an earlier call said here goes in first, so the chat the offer reads has it. + await spoken?.flush(waitingAtMost: 2) guard call === next else { throw LiveVoiceControlError.wrongOwner } let result = try await request(local ? .nativeVoiceGeminiOffer : .nativeVoiceOffer, fields) guard call === next else { throw LiveVoiceControlError.wrongOwner } @@ -182,6 +195,12 @@ final class NativeLiveVoiceSession { if removed.0 > call.contextOffset { call.contextIncomplete = true } } } + if kind == "audio_cleared" { call.audioCleared = true } + if kind == "transcript_done", let role = event["role"]?.string, let text = event["text"]?.string { + let interrupted = role == "assistant" && call.audioCleared + if role == "assistant" { call.audioCleared = false } + spoken?.add(voiceID: call.id, role: role, text: text, interrupted: interrupted) + } guard kind == "delegation" || kind == "delegation_context_required" else { emit(event, voiceID: voiceID) return @@ -209,6 +228,8 @@ final class NativeLiveVoiceSession { guard !retired, isCurrent() else { return Outcome(text: "The host connection changed. Check the chat before resending.", confirmed: false) } + // The words that led here go into the chat before the request's own turn does. + await spoken?.flush(waitingAtMost: 1.5) do { return Outcome(text: Self.boundedResult(try await submit(text))) } catch { return Outcome(text: "This request was not confirmed. Check the chat and its pending approvals before requesting it again.", diff --git a/Bighelp/Workspace/WorkspaceOperation.swift b/Bighelp/Workspace/WorkspaceOperation.swift index 386caaf1..528a7f17 100644 --- a/Bighelp/Workspace/WorkspaceOperation.swift +++ b/Bighelp/Workspace/WorkspaceOperation.swift @@ -147,6 +147,8 @@ enum WorkspaceOperation: String, CaseIterable, Sendable { case nativeVoicePoll = "native.voice.poll" case nativeVoiceResult = "native.voice.result" case nativeVoiceClose = "native.voice.close" + /// A call's finished lines, saved into its chat: only on plugins that list `native-voice-history-v1`. + case nativeVoiceTranscript = "native.voice.transcript" /// The same routes, for Gemini Live: only on plugins that list `native-voice-gemini-v1`. case nativeVoiceGeminiStatus = "native.voice.gemini.status" case nativeVoiceGeminiOffer = "native.voice.gemini.offer" diff --git a/BighelpTests/LiveVoiceSpokenTurnsTests.swift b/BighelpTests/LiveVoiceSpokenTurnsTests.swift new file mode 100644 index 00000000..aa17001a --- /dev/null +++ b/BighelpTests/LiveVoiceSpokenTurnsTests.swift @@ -0,0 +1,108 @@ +import Foundation +import Testing +@testable import Bighelp + +/// A call's finished lines go into its chat in the order they were said, once the chat can take them. +@MainActor +struct LiveVoiceSpokenTurnsTests { + /// Stands in for the plugin's `voice/transcript`: answers each send from `outcomes`, then saves. + @MainActor final class Chat { + var outcomes: [LiveVoiceSpokenTurns.Outcome] = [] + var sends: [(voiceID: String, lines: [BighelpJSONValue])] = [] + var saved: [String] = [] + + func send(_ voiceID: String, _ lines: [BighelpJSONValue]) async -> LiveVoiceSpokenTurns.Outcome { + sends.append((voiceID, lines)) + let outcome = outcomes.isEmpty ? .saved : outcomes.removeFirst() + if outcome == .saved { saved += lines.compactMap { $0.object?["text"]?.string } } + return outcome + } + } + + private func journal(_ chat: Chat) -> LiveVoiceSpokenTurns { + let journal = LiveVoiceSpokenTurns(retryWaits: [.milliseconds(5)], giveUpAfter: .milliseconds(200)) + journal.send = { [chat] voiceID, lines in await chat.send(voiceID, lines) } + return journal + } + + private func settle(_ journal: LiveVoiceSpokenTurns) async { + for _ in 0..<400 where !journal.pending.isEmpty { try? await Task.sleep(for: .milliseconds(2)) } + } + + @Test func linesGoInTheOrderTheyWereSaidWithTheirRoles() async { + let chat = Chat() + let journal = journal(chat) + var refreshes = 0 + journal.onSaved = { refreshes += 1 } + journal.add(voiceID: "voice-one", role: "user", text: " My bike is blue. ") + journal.add(voiceID: "voice-one", role: "assistant", text: "Noted, a blue", interrupted: true) + await journal.flush() + await settle(journal) + #expect(chat.saved == ["My bike is blue.", "Noted, a blue"]) + let lines = chat.sends.flatMap(\.lines).compactMap(\.object) + #expect(lines.map { $0["role"]?.string } == ["user", "assistant"]) + #expect(lines.map { $0["interrupted"]?.boolean } == [false, true]) + #expect(Set(lines.compactMap { $0["id"]?.string }).count == 2, "Each line has its own ID") + #expect(refreshes >= 1, "The chat reads what was saved") + } + + @Test func aBusyChatGetsTheSameLinesAgainUntilItTakesThem() async { + let chat = Chat() + chat.outcomes = [.wait, .wait] + let journal = journal(chat) + journal.add(voiceID: "voice-one", role: "user", text: "Remind me at six.") + await settle(journal) + #expect(chat.saved == ["Remind me at six."]) + #expect(chat.sends.count == 3) + let ids = chat.sends.map { $0.lines.compactMap { $0.object?["id"]?.string } } + #expect(Set(ids.map { $0.joined() }).count == 1, "A retry sends the same line ID, so the plugin saves it once") + } + + @Test func eachCallsLinesGoUnderTheirOwnCall() async { + let chat = Chat() + chat.outcomes = [.wait] + let journal = journal(chat) + journal.add(voiceID: "voice-one", role: "user", text: "First call.") + journal.add(voiceID: "voice-two", role: "user", text: "Second call.") + await settle(journal) + #expect(chat.saved == ["First call.", "Second call."]) + #expect(chat.sends.last?.voiceID == "voice-two") + } + + @Test func aChatThatRefusesNeverHoldsUpLaterLines() async { + let chat = Chat() + chat.outcomes = [.refused] + let journal = journal(chat) + journal.add(voiceID: "voice-one", role: "user", text: "Lost.") + await journal.flush() + journal.add(voiceID: "voice-one", role: "user", text: "Kept.") + await settle(journal) + #expect(chat.saved == ["Kept."]) + } + + @Test func linesAChatNeverTakesAreLetGoInTheEnd() async { + let chat = Chat() + chat.outcomes = Array(repeating: .wait, count: 1_000) + let journal = journal(chat) + journal.add(voiceID: "voice-one", role: "user", text: "Waiting.") + await settle(journal) + #expect(journal.pending.isEmpty) + #expect(chat.saved.isEmpty) + } + + @Test func emptyLinesAndOtherRolesAreLeftOut() { + let journal = LiveVoiceSpokenTurns() + journal.add(voiceID: "voice-one", role: "user", text: " ") + journal.add(voiceID: "voice-one", role: "system", text: "Be brief.") + #expect(journal.pending.isEmpty) + } + + @Test func eachChatOnEachComputerHasItsOwnJournal() { + let one = LiveVoiceSpokenTurns.shared(hostID: "computer-a", agentID: "nova", sessionID: "chat-1") + #expect(LiveVoiceSpokenTurns.shared(hostID: "computer-a", agentID: "nova", sessionID: "chat-1") === one) + for (host, agent, session) in [("computer-b", "nova", "chat-1"), ("computer-a", "miso", "chat-1"), + ("computer-a", "nova", "chat-2")] { + #expect(LiveVoiceSpokenTurns.shared(hostID: host, agentID: agent, sessionID: session) !== one) + } + } +} diff --git a/BighelpTests/NativeLiveVoiceTests.swift b/BighelpTests/NativeLiveVoiceTests.swift index 488b9e49..27cb8b60 100644 --- a/BighelpTests/NativeLiveVoiceTests.swift +++ b/BighelpTests/NativeLiveVoiceTests.swift @@ -427,9 +427,86 @@ struct NativeLiveVoiceTests { return (model, peer) } + // A call continues its chat: what was said goes back into it, in order. + + private final class Order { + var steps: [String] = [] + } + + private func spokenSession(_ order: Order, journal: LiveVoiceSpokenTurns) -> NativeLiveVoiceSession { + NativeLiveVoiceSession(owner: .init(hostID: "native", authorizationID: "auth", agentID: "default", sessionID: "stored"), + operation: { operation, payload in + switch operation { + case .nativeVoiceOffer: + order.steps.append("offer") + return ["voiceId": payload["voiceId"]!, "sdp": .string(NativeVoicePeer.sdp)] + case .nativeVoicePoll: + return ["voiceId": payload["voiceId"]!, "events": .array([]), "next": payload["after"]!, "closed": .boolean(false)] + case .nativeVoiceResult: return ["appended": .boolean(true)] + case .nativeVoiceClose: return ["closed": .boolean(true)] + default: throw LiveVoiceControlError.unavailable + } + }, isCurrent: { true }, submit: { text in + order.steps.append("submit: " + text) + return "Tomorrow is clear." + }, spoken: journal) + } + + private func line(_ role: String, _ text: String) -> [String: BighelpJSONValue] { + ["kind": .string("transcript_done"), "role": .string(role), "text": .string(text)] + } + + @Test func theWordsBeforeARequestReachTheChatBeforeItsTurn() async throws { + let order = Order() + var interrupted: [Bool] = [] + let journal = LiveVoiceSpokenTurns(retryWaits: [.milliseconds(5)]) + journal.send = { _, lines in + for line in lines.compactMap(\.object) { + order.steps.append("saved: " + (line["text"]?.string ?? "")) + interrupted.append(line["interrupted"]?.boolean ?? false) + } + return .saved + } + let voice = spokenSession(order, journal: journal) + _ = try await voice.perform("voice.live.offer", fields: ["voiceId": .string("voice-one")]) + voice.receiveEvent(line("assistant", "Hi, picking up where we"), voiceID: "voice-one") + voice.receiveEvent(["kind": .string("audio_cleared")], voiceID: "voice-one") + voice.receiveEvent(line("assistant", "Hi, picking up where we"), voiceID: "voice-one") + voice.receiveEvent(line("user", "Check my calendar for tomorrow."), voiceID: "voice-one") + voice.receiveEvent(line("assistant", "On it."), voiceID: "voice-one") + voice.receiveEvent(["kind": .string("delegation"), "id": .string("call-1"), + "text": .string("Check the calendar for tomorrow")], voiceID: "voice-one") + for _ in 0..<500 where !order.steps.contains(where: { $0.hasPrefix("submit") }) { await Task.yield() } + #expect(order.steps == ["offer", "saved: Hi, picking up where we", "saved: Hi, picking up where we", + "saved: Check my calendar for tomorrow.", "saved: On it.", + "submit: Check the calendar for tomorrow"]) + #expect(interrupted == [false, true, false, false], "Only the reply the person cut off ends early") + _ = try await voice.perform("voice.live.close", fields: ["voiceId": .string("voice-one")]) + } + + @Test func aNewCallSavesWhatTheLastOneLeftBeforeItReadsTheChat() async throws { + let order = Order() + var answers: [LiveVoiceSpokenTurns.Outcome] = [.wait] + // The retry is far off: only the new call's offer sends the line again. + let journal = LiveVoiceSpokenTurns(retryWaits: [.seconds(60)]) + journal.send = { _, lines in + let outcome = answers.isEmpty ? .saved : answers.removeFirst() + if outcome == .saved { order.steps += lines.compactMap { "saved: " + ($0.object?["text"]?.string ?? "") } } + return outcome + } + journal.add(voiceID: "voice-one", role: "user", text: "My locker is 4417.") + await journal.flush() + #expect(order.steps.isEmpty, "The chat was busy") + let voice = spokenSession(order, journal: journal) + _ = try await voice.perform("voice.live.offer", fields: ["voiceId": .string("voice-two")]) + #expect(order.steps == ["saved: My locker is 4417.", "offer"]) + _ = try await voice.perform("voice.live.close", fields: ["voiceId": .string("voice-two")]) + } + @Test func nativeVoiceOperationsHaveNativePluginRoutes() { for operation in [WorkspaceOperation.nativeVoiceStatus, .nativeVoiceOffer, .nativeVoicePoll, - .nativeVoiceResult, .nativeVoiceClose, .nativeVoiceGeminiStatus, .nativeVoiceGeminiOffer] { + .nativeVoiceResult, .nativeVoiceClose, .nativeVoiceGeminiStatus, .nativeVoiceGeminiOffer, + .nativeVoiceTranscript] { #expect(DirectHermesNativePluginClient.supports(operation)) } } diff --git a/docs/DIRECT_STREAMING_AND_LIVE_VOICE.md b/docs/DIRECT_STREAMING_AND_LIVE_VOICE.md index 2e3719cd..7e84d950 100644 --- a/docs/DIRECT_STREAMING_AND_LIVE_VOICE.md +++ b/docs/DIRECT_STREAMING_AND_LIVE_VOICE.md @@ -30,6 +30,19 @@ edits the defaults. The voice button starts the call at once, in both voice type The voice model is the agent itself: the plugin builds its brief from the agent's name and `SOUL.md`, so it speaks in the first person and never says "your agent" or "Hermes". +A call continues the chat it opens in, both ways (plugin `native-voice-history-v1`). The plugin reads that chat +before the voice model listens: its newest messages with their roles, the summary of its compacted part and the +request a turn still works on, the same for Gemini and both GPT-Live options. The model answers from it and +doesn't greet or repeat as if the conversation were new. What is said on the call comes back into the chat: +each finished line, the person's or the voice model's, goes to the plugin's `voice/transcript` route +(`LiveVoiceSpokenTurns`) and becomes an ordinary message, so typing afterwards knows it. A reply the person cut +off ends where they cut in. Saving runs nothing, and requests the model handed over are already turns in the +chat. The plugin writes only while no turn runs in the chat, so the app sends the same lines again until the +chat takes them, and each line is saved once. Lines stay with their computer, agent and chat: a call opened +again in the chat saves what the last one left before the plugin reads the chat, and they go over whatever +connection to that computer is current, so a reconnect doesn't lose them. They wait in memory only: lines +the chat hasn't taken after 30 minutes, or when the app quits, are lost. + ### GPT-Live GPT-Live defaults to **Codex subscription** (`gpt-live-1-codex`). The plugin uses Hermes-managed subscription credentials; the phone receives no bearer token. The phone's WebRTC peer (`BighelpRealtimeAudioPeer`) carries audio directly to the provider. Setup, captions and job controls go through the plugin's `voice/status`, `voice/offer`, `voice/poll`, `voice/result` and `voice/close` routes (feature `native-voice-v1`) on the signed-in host connection. The provider sideband is connected before the answer SDP is returned. From 99bc22b15f7a62630a609d853b3061c3512eabb3 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:38:47 -0600 Subject: [PATCH 2/4] A call's last words reach the chat, and a cut-off marks only the reply it cut Review findings on the voice journal: - Cleared audio with no words of a reply yet marked the next whole reply as cut off. The mark now needs words of that reply. - On Gemini, a hang-up saves what the person said last and the reply it cut. - A line is cut to the plugin's length in Unicode scalars, and one send stays under the plugin's size for a request. - A route that is unavailable for a moment after a reconnect is tried again, not dropped. Co-Authored-By: Claude Fable 5.2 --- Bighelp/App/NativeWorkspaceRuntime.swift | 4 +++- Bighelp/Voice/GeminiLiveAudioPeer.swift | 2 ++ Bighelp/Voice/GeminiLiveWire.swift | 12 ++++++++++++ Bighelp/Voice/LiveVoiceSpokenTurns.swift | 12 ++++++++++-- Bighelp/Voice/NativeLiveVoiceSession.swift | 9 +++++++-- BighelpTests/GeminiLiveWireTests.swift | 15 +++++++++++++++ BighelpTests/LiveVoiceSpokenTurnsTests.swift | 16 ++++++++++++++++ BighelpTests/NativeLiveVoiceTests.swift | 5 +++++ 8 files changed, 70 insertions(+), 5 deletions(-) diff --git a/Bighelp/App/NativeWorkspaceRuntime.swift b/Bighelp/App/NativeWorkspaceRuntime.swift index 46176ca7..746bba4c 100644 --- a/Bighelp/App/NativeWorkspaceRuntime.swift +++ b/Bighelp/App/NativeWorkspaceRuntime.swift @@ -1109,9 +1109,11 @@ extension NativeWorkspaceRuntime { } catch WorkspaceClientError.rejected(let code, _) { // A running turn holds the chat; anything else it refused, it will refuse again. return code == "voice_chat_busy" || code == "context_changed" ? .wait : .refused - } catch WorkspaceClientError.unavailable { + } catch WorkspaceClientError.capacityExceeded { return .refused } catch { + // Also "unavailable": right after a reconnect the features can be unknown for a moment, + // and that is never "this computer can't save them". return .wait } } diff --git a/Bighelp/Voice/GeminiLiveAudioPeer.swift b/Bighelp/Voice/GeminiLiveAudioPeer.swift index 029f4a22..f1ec8680 100644 --- a/Bighelp/Voice/GeminiLiveAudioPeer.swift +++ b/Bighelp/Voice/GeminiLiveAudioPeer.swift @@ -257,6 +257,8 @@ final class GeminiLiveAudioPeer: LiveVoiceAudioPeer, LiveVoiceLocalSession, Live func close() { guard !closed else { return } + // The words still coming in when the call ends go to the chat as far as they got. + for case .event(let event) in translator.hangUp() { onEvent?(event) } closed = true diagnostics.event("call closed") reportLog?.cancel() diff --git a/Bighelp/Voice/GeminiLiveWire.swift b/Bighelp/Voice/GeminiLiveWire.swift index 1c72a4e6..3af493c2 100644 --- a/Bighelp/Voice/GeminiLiveWire.swift +++ b/Bighelp/Voice/GeminiLiveWire.swift @@ -190,6 +190,18 @@ struct GeminiLiveTranslator { /// Muted, Gemini hears nothing more and may never send the end of the person's speech. mutating func personStoppedSpeaking() { isUserSpeaking = false } + /// The call ends: what the person said last and the reply cut off by the hang-up end here, so + /// they still reach the chat. + mutating func hangUp() -> [Output] { + var outputs = finishUser() + if !assistant.isEmpty { + outputs += [.event(["kind": .string("audio_cleared")]), transcript("transcript_done", role: "assistant", assistant)] + } + assistant = "" + turnHasOutput = false + return outputs + } + private mutating func finishUser() -> [Output] { guard !user.isEmpty else { return [] } defer { user = "" } diff --git a/Bighelp/Voice/LiveVoiceSpokenTurns.swift b/Bighelp/Voice/LiveVoiceSpokenTurns.swift index 896c1713..79522569 100644 --- a/Bighelp/Voice/LiveVoiceSpokenTurns.swift +++ b/Bighelp/Voice/LiveVoiceSpokenTurns.swift @@ -44,7 +44,10 @@ final class LiveVoiceSpokenTurns { static let feature = "native-voice-history-v1" static let maximumLines = 256 static let maximumBatch = 32 + /// In Unicode scalars, as the plugin counts a line's length. static let maximumTextLength = 4_000 + /// One send's lines together, in UTF-8 bytes: under the plugin's limit for a request. + static let maximumBatchBytes = 120_000 /// Waits between tries while the chat is busy or the computer is away; the last repeats until `giveUpAfter`. static let retryWaits: [Duration] = [.seconds(1), .seconds(2), .seconds(4), .seconds(8), .seconds(15), .seconds(30)] /// A delegated turn can run a long time. Lines that waited this long without a save are let go. @@ -90,7 +93,8 @@ final class LiveVoiceSpokenTurns { guard role == "user" || role == "assistant", !text.isEmpty, pending.count < Self.maximumLines else { return } lineCount += 1 pending.append(Line(voiceID: voiceID, id: "\(role.prefix(1))\(lineCount)", role: role, - text: String(text.prefix(Self.maximumTextLength)), interrupted: interrupted, at: now())) + text: String(String.UnicodeScalarView(text.unicodeScalars.prefix(Self.maximumTextLength))), + interrupted: interrupted, at: now())) startRound() } @@ -121,7 +125,11 @@ final class LiveVoiceSpokenTurns { private func sendPending() async { while let first = pending.first { guard let send else { return scheduleRetry() } - let batch = Array(pending.prefix(Self.maximumBatch).prefix { $0.voiceID == first.voiceID }) + var bytes = 0 + let batch = Array(pending.prefix(Self.maximumBatch).prefix { line in + bytes += line.text.utf8.count + return line.voiceID == first.voiceID && (bytes <= Self.maximumBatchBytes || line == first) + }) switch await send(first.voiceID, batch.map(\.wire)) { case .saved: pending.removeFirst(batch.count) diff --git a/Bighelp/Voice/NativeLiveVoiceSession.swift b/Bighelp/Voice/NativeLiveVoiceSession.swift index 82c7348e..785a854e 100644 --- a/Bighelp/Voice/NativeLiveVoiceSession.swift +++ b/Bighelp/Voice/NativeLiveVoiceSession.swift @@ -37,6 +37,8 @@ final class NativeLiveVoiceSession { var transcripts: [(Int, String)] = [] /// The provider dropped the reply's audio: the person cut it off, and its line ends there. var audioCleared = false + /// Words of the reply being said have come in since the last finished reply. + var replyHasWords = false var contextOffset = -1 var contextIncomplete = false var closeCleanup: (@MainActor () async -> Void)? @@ -195,10 +197,13 @@ final class NativeLiveVoiceSession { if removed.0 > call.contextOffset { call.contextIncomplete = true } } } - if kind == "audio_cleared" { call.audioCleared = true } + // A cut-off marks only the reply whose words were coming in: cleared audio with no words yet + // has no line to mark, and must not mark the next whole reply. + if kind == "transcript_delta", event["role"]?.string == "assistant" { call.replyHasWords = true } + if kind == "audio_cleared" { call.audioCleared = call.replyHasWords } if kind == "transcript_done", let role = event["role"]?.string, let text = event["text"]?.string { let interrupted = role == "assistant" && call.audioCleared - if role == "assistant" { call.audioCleared = false } + if role == "assistant" { (call.audioCleared, call.replyHasWords) = (false, false) } spoken?.add(voiceID: call.id, role: role, text: text, interrupted: interrupted) } guard kind == "delegation" || kind == "delegation_context_required" else { diff --git a/BighelpTests/GeminiLiveWireTests.swift b/BighelpTests/GeminiLiveWireTests.swift index 2aea7cc9..5dddbf0c 100644 --- a/BighelpTests/GeminiLiveWireTests.swift +++ b/BighelpTests/GeminiLiveWireTests.swift @@ -93,6 +93,21 @@ struct GeminiLiveWireTests { "kind": .string("transcript_done"), "role": .string("assistant"), "text": .string("I need your approval.")])]) } + /// The chat keeps a call's last words: what the person said and the reply the hang-up cut off. + @Test func aHangUpEndsWhatWasStillBeingSaid() { + var translator = GeminiLiveTranslator() + _ = translator.outputs(for: .userText("My bike is teal.")) + #expect(translator.hangUp() == [.event([ + "kind": .string("transcript_done"), "role": .string("user"), "text": .string("My bike is teal.")])]) + // The reply's first words already ended the person's line. + _ = translator.outputs(for: .userText("And it has a bell.")) + _ = translator.outputs(for: .assistantText("A teal bike with")) + #expect(translator.hangUp() == [ + .event(["kind": .string("audio_cleared")]), + .event(["kind": .string("transcript_done"), "role": .string("assistant"), "text": .string("A teal bike with")])]) + #expect(translator.hangUp().isEmpty, "Nothing is said twice") + } + @Test func startWorkIsAnsweredAtOnceAndBecomesADelegation() { var translator = GeminiLiveTranslator() let call = GeminiLiveWire.FunctionCall(id: "c1", name: "start_work", arguments: ["request": .string(" Tidy Downloads ")]) diff --git a/BighelpTests/LiveVoiceSpokenTurnsTests.swift b/BighelpTests/LiveVoiceSpokenTurnsTests.swift index aa17001a..18fa51b6 100644 --- a/BighelpTests/LiveVoiceSpokenTurnsTests.swift +++ b/BighelpTests/LiveVoiceSpokenTurnsTests.swift @@ -90,6 +90,22 @@ struct LiveVoiceSpokenTurnsTests { #expect(chat.saved.isEmpty) } + @Test func longLinesGoInSendsTheComputerTakes() async { + let chat = Chat() + let journal = journal(chat) + // Four bytes a character, 16,000 a line: nine lines are over one send's size. + let long = String(repeating: "🌱", count: LiveVoiceSpokenTurns.maximumTextLength + 50) + for _ in 0..<9 { journal.add(voiceID: "voice-one", role: "user", text: long) } + await settle(journal) + #expect(chat.saved.count == 9) + #expect(chat.saved.allSatisfy { $0.unicodeScalars.count == LiveVoiceSpokenTurns.maximumTextLength }) + #expect(chat.sends.count >= 2, "No send is over the computer's limit") + #expect(chat.sends.allSatisfy { send in + send.lines.count == 1 || send.lines.compactMap { $0.object?["text"]?.string?.utf8.count }.reduce(0, +) + <= LiveVoiceSpokenTurns.maximumBatchBytes + }) + } + @Test func emptyLinesAndOtherRolesAreLeftOut() { let journal = LiveVoiceSpokenTurns() journal.add(voiceID: "voice-one", role: "user", text: " ") diff --git a/BighelpTests/NativeLiveVoiceTests.swift b/BighelpTests/NativeLiveVoiceTests.swift index 27cb8b60..32f4cdbe 100644 --- a/BighelpTests/NativeLiveVoiceTests.swift +++ b/BighelpTests/NativeLiveVoiceTests.swift @@ -470,8 +470,13 @@ struct NativeLiveVoiceTests { let voice = spokenSession(order, journal: journal) _ = try await voice.perform("voice.live.offer", fields: ["voiceId": .string("voice-one")]) voice.receiveEvent(line("assistant", "Hi, picking up where we"), voiceID: "voice-one") + voice.receiveEvent(["kind": .string("transcript_delta"), "role": .string("assistant"), "text": .string("Hi, ")], + voiceID: "voice-one") voice.receiveEvent(["kind": .string("audio_cleared")], voiceID: "voice-one") voice.receiveEvent(line("assistant", "Hi, picking up where we"), voiceID: "voice-one") + // Cut off before any word of the reply came in: there is no line to mark, and the next + // whole reply must not take the mark. + voice.receiveEvent(["kind": .string("audio_cleared")], voiceID: "voice-one") voice.receiveEvent(line("user", "Check my calendar for tomorrow."), voiceID: "voice-one") voice.receiveEvent(line("assistant", "On it."), voiceID: "voice-one") voice.receiveEvent(["kind": .string("delegation"), "id": .string("call-1"), From 2e7b0a3471e3b647e5c3b2c8dee849597dbe6759 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:38:47 -0600 Subject: [PATCH 3/4] Goals: add, rename and delete the goal categories of a computer Goals had seven fixed categories. Each computer now keeps its own list for all its bots (plugin native-goal-categories-v1). Edit categories under the Create a goal list opens a sheet that adds, renames and deletes them. A deleted category's goals show under Other, and a renamed one keeps its goals. Today, a bot's Dashboard and a goal's chat card show the category name and emoji that the computer sent. With an older plugin, Goals is as before. Closes #1064 Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 13 +- Bighelp.xcodeproj/project.pbxproj | 8 + Bighelp/Board/AgentBoard.swift | 94 +++++-- Bighelp/Board/AgentGoalsView.swift | 78 ++++-- Bighelp/Board/BoardDashboardViews.swift | 6 +- Bighelp/Board/GoalCategories.swift | 124 +++++++++ Bighelp/Board/GoalCategoriesSheet.swift | 261 ++++++++++++++++++ Bighelp/Chat/ChatBoardCard.swift | 2 +- .../DirectHermesNativeContext.swift | 3 + Bighelp/Fixtures/DemoAgentBoardClient.swift | 56 +++- Bighelp/Workspace/WorkspaceOperation.swift | 2 + .../BoardBlueprintAndGoalCategoryTests.swift | 128 ++++++++- .../BoardSwipeBlueprintsUITests.swift | 77 ++++++ DESIGN.md | 5 + 14 files changed, 799 insertions(+), 58 deletions(-) create mode 100644 Bighelp/Board/GoalCategories.swift create mode 100644 Bighelp/Board/GoalCategoriesSheet.swift diff --git a/AGENTS.md b/AGENTS.md index 4d01ae62..5b13dcf9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,6 +131,14 @@ change in both repos. Discuss puts it in the message box (`ChatModel.boardCardDraft`). Let's do it sends "Let's do it!" with the idea at once (`leaveComposerText(sendsAtOnce:)`, `ChatModel.sendFromOutside`), never touching the box, and the idea moves to Ideas › Completed (the plugin's `answer`, `answeredAt`). + - Goal categories belong to the computer, not the app (plugin `native-goal-categories-v1`, + `GoalCategoryInfo`): one list for every bot on it, the built-in seven until someone changes it. + `board/list` sends it with the goals, and each goal says where it shows now (`categoryName`, + `categoryIcon`), so Today and a chat card need no list. Goals › Edit categories + (`GoalCategoriesSheet`) adds, renames and deletes through `board/categories`; the bot does the same + with its board tool. A category's `id` never changes, so a rename keeps its goals. A deleted + category's goals show under Other, which is always last and never changes. `GoalCategory` is only + the built-in seven (symbols, blueprints, the words for a goal with no category). - New chat is the new chat's own screen, drawn by the ordinary chat (`ChatNewChatSlot`, handed only to the chat whose ID is `NewChatSession.conversationID`, never decided from its messages; from the first message on, staged, sending or sent, it's an ordinary chat). Under Back and ⋯ a To row (`NewChatToRow`) holds the picked bots as @@ -427,7 +435,10 @@ change in both repos. `voice/transcript` (`LiveVoiceSpokenTurns`), which runs nothing and saves each line once. The plugin writes only while no turn runs (`voice_chat_busy`), so the journal sends the same lines again until the chat takes them, over whatever connection to that computer is current. One journal per computer, agent and chat: a new - call's offer waits for an earlier call's lines, and the lines before a request go before its turn. + call's offer waits for an earlier call's lines (2 s at most), and a request waits for the lines before it + (1.5 s at most), so they usually go in first. A cut-off marks only a reply whose words were coming in. On + Gemini a hang-up saves what was still being said (`GeminiLiveTranslator.hangUp`); GPT-Live's last words can + be lost if their event hasn't come when the call closes. - **On-device voices** (`Bighelp/Voice/OnDevice/`): Phonon speaks on the iPhone or iPad instead of the computer. It's chosen per agent in Voice settings and kept on the device (`OnDeviceVoiceChoices`, by computer and agent); the agent's `tts.*` on the computer never changes. `OnDeviceVoiceSettingsClient` adds it to the diff --git a/Bighelp.xcodeproj/project.pbxproj b/Bighelp.xcodeproj/project.pbxproj index 3a8e36fe..68e8d1db 100644 --- a/Bighelp.xcodeproj/project.pbxproj +++ b/Bighelp.xcodeproj/project.pbxproj @@ -1151,6 +1151,7 @@ 86828616C0652504329CA63E /* AgentDeletionUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD268648AC84425AD755C76C /* AgentDeletionUITests.swift */; }; 86ED398D440A6A5D23CAD0B9 /* UsageStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = D04DCAF7F90EF8190BB0B2A2 /* UsageStore.swift */; }; 873627A0788894E370CA1D86 /* NeedsYouBlueprintsModesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CC87D2B2C1511FADA193002 /* NeedsYouBlueprintsModesTests.swift */; }; + 875482724CAF36C8C2C38163 /* GoalCategories.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB2E925280D6719953ECDF47 /* GoalCategories.swift */; }; 879E33489356FF40A206B326 /* CapabilitiesManagementView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12D93519128F8E3A35F264D0 /* CapabilitiesManagementView.swift */; }; 879F26B5861D37C7F19A5099 /* SubagentCanvasTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9853597BF6721C1FFA38C43 /* SubagentCanvasTests.swift */; }; 8807CDF7B4E669D5B8F7BE38 /* ReferenceGitHubAdapterSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB4F78E4AFF7D918C452079F /* ReferenceGitHubAdapterSnapshot.swift */; }; @@ -1559,6 +1560,7 @@ B95546BA653AA08075DAAEEB /* SessionContentRepository.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76C2C6940B458C1D6DF15854 /* SessionContentRepository.swift */; }; B96A047D8C3F72D4485B2129 /* ChatReactionBarTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 538EA16267AB77E69A6E9D28 /* ChatReactionBarTests.swift */; }; B98024B47619F441AB7EE964 /* LiveVoiceModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6BFBFE60217D0F9676F7FD23 /* LiveVoiceModel.swift */; }; + B99CD603DFAE116B404580FA /* GoalCategoriesSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B586517490B176E94948F05 /* GoalCategoriesSheet.swift */; }; B99CEBCB5650C88D5BA59020 /* OnDeviceVoiceRouting.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1BCC47FB209680A0EF2AAFB /* OnDeviceVoiceRouting.swift */; }; B9A9975B875DC065472E8F68 /* AgentBoardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC5B91C5A272DC8DA6E437DE /* AgentBoardTests.swift */; }; B9B06D7B27668CF35396371D /* AgentHeroHeaderLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65BD4C0208441BB886FDB670 /* AgentHeroHeaderLayoutTests.swift */; }; @@ -3173,6 +3175,7 @@ 6AC7DF2F678C14DF3F82F320 /* SessionSubagentPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionSubagentPresentation.swift; sourceTree = ""; }; 6ADD22141655C8ECEAAAFF20 /* FixtureWorkspaceManagementClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FixtureWorkspaceManagementClient.swift; sourceTree = ""; }; 6B51E351013BB3D09F5BF96A /* AgentTemplateBrowser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentTemplateBrowser.swift; sourceTree = ""; }; + 6B586517490B176E94948F05 /* GoalCategoriesSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GoalCategoriesSheet.swift; sourceTree = ""; }; 6B7A896B2C3D652785254B28 /* SystemPageUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SystemPageUITests.swift; sourceTree = ""; }; 6BAB935FB2C454D6B7A963BB /* NewChatCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewChatCoordinator.swift; sourceTree = ""; }; 6BBEA79EA71E6E0E9A00BE02 /* draft-save-code.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "draft-save-code.json"; sourceTree = ""; }; @@ -4105,6 +4108,7 @@ DAED33EFE39C435EEECF5599 /* BighelpPersonID.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpPersonID.swift; sourceTree = ""; }; DB0C6B1B426629EDA96C7ACC /* BighelpLiveActivityLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpLiveActivityLog.swift; sourceTree = ""; }; DB11B9CD72BA82F3CF4FC06E /* BotLook.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotLook.swift; sourceTree = ""; }; + DB2E925280D6719953ECDF47 /* GoalCategories.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GoalCategories.swift; sourceTree = ""; }; DB2FF592B8A04DEEFD7B17AF /* AgentMediaTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentMediaTests.swift; sourceTree = ""; }; DB640E443FE6AB3A381C1FFD /* AgentStudioCaption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentStudioCaption.swift; sourceTree = ""; }; DB83B642C9FCC3341B0169D4 /* BighelpSkeleton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpSkeleton.swift; sourceTree = ""; }; @@ -4797,6 +4801,8 @@ FCC640306666832EF7BEC2A0 /* DashboardActivityDetailView.swift */, 37D2DE1F0AF4478D40FD0E25 /* DashboardTodaySection.swift */, 14791450B5A4D6CE103EC937 /* FeedPostFiles.swift */, + DB2E925280D6719953ECDF47 /* GoalCategories.swift */, + 6B586517490B176E94948F05 /* GoalCategoriesSheet.swift */, D927E9C5B53DDE1797A520AD /* IslandStage.swift */, A44223CB9667024350A9D441 /* TemplateCatalogStore.swift */, CF9F2674039531137409B7D7 /* TemplateCategories.swift */, @@ -8743,6 +8749,8 @@ 27A49B69B97D32CD2A32E649 /* GitHubResource.swift in Sources */, 3DD0EFF0CB0B8EBF4DA5FFDD /* GitHubResourceProvider.swift in Sources */, B85A12A0BC8811D8CAE73C52 /* GitHubTransport.swift in Sources */, + 875482724CAF36C8C2C38163 /* GoalCategories.swift in Sources */, + B99CD603DFAE116B404580FA /* GoalCategoriesSheet.swift in Sources */, E0E26CC2702BC633B82814BB /* GroupSettingsDemoClient.swift in Sources */, 9D746590A066AA6E8FBAFD33 /* GroupSettingsView.swift in Sources */, 8D1EC9D53AE48FDCEC962091 /* HTMLAppCardView.swift in Sources */, diff --git a/Bighelp/Board/AgentBoard.swift b/Bighelp/Board/AgentBoard.swift index 3e8e30c3..e2a1ed9c 100644 --- a/Bighelp/Board/AgentBoard.swift +++ b/Bighelp/Board/AgentBoard.swift @@ -174,6 +174,10 @@ struct AgentBoardItem: Identifiable, Equatable, Sendable { var dismissed: Bool /// A goal's category as the plugin stored it; empty for none (plugins before 3.5). var category: String + /// The category's name and emoji on its computer (`native-goal-categories-v1`); empty from + /// plugins before that. Read them through `goalCategoryInfo`. + var categoryName: String + var categoryIcon: String /// How the person answered an idea: "yes" for Let's do it, "goal", or "none". var answer: String /// When they answered; nil for plugins that don't say. @@ -201,12 +205,13 @@ struct AgentBoardItem: Identifiable, Equatable, Sendable { init(id: String, kind: Kind, title: String, body: String = "", icon: String = "", section: String = "", status: String = "", note: String = "", links: [Link] = [], pictures: [Picture] = [], files: [File] = [], source: String = "", rating: Rating = .none, reason: String = "", read: Bool = true, - dismissed: Bool = false, category: String = "", answer: String = "none", answeredAt: Date? = nil, - createdAt: Date = .now, updatedAt: Date? = nil) { + dismissed: Bool = false, category: String = "", categoryName: String = "", categoryIcon: String = "", + answer: String = "none", answeredAt: Date? = nil, createdAt: Date = .now, updatedAt: Date? = nil) { self.id = id; self.kind = kind; self.title = title; self.body = body; self.icon = icon self.section = section; self.status = status; self.note = note; self.links = links self.pictures = pictures; self.files = files; self.source = source; self.rating = rating; self.reason = reason self.read = read; self.dismissed = dismissed; self.category = category + self.categoryName = categoryName; self.categoryIcon = categoryIcon self.answer = answer; self.answeredAt = answeredAt self.createdAt = createdAt; self.updatedAt = updatedAt ?? createdAt } @@ -245,14 +250,17 @@ struct AgentBoardItem: Identifiable, Equatable, Sendable { reason: object["reason"]?.string ?? "", read: object["read"]?.boolean ?? true, dismissed: object["dismissed"]?.boolean ?? false, category: object["category"]?.string ?? "", + categoryName: String((object["categoryName"]?.string ?? "").prefix(GoalCategoryInfo.maximumNameLength)), + categoryIcon: String((object["categoryIcon"]?.string ?? "").prefix(GoalCategoryInfo.maximumIconLength)), answer: object["answer"]?.string ?? "none", answeredAt: (object["answeredAt"]?.integer).flatMap { $0 > 0 ? date("answeredAt") : nil }, createdAt: date("createdAt"), updatedAt: date("updatedAt")) } } -/// What a goal is about. The plugin keeps the same fixed list -/// (`native-agent-board-goal-categories-v1`); "Something else" is stored as `other`. +/// The built-in goal categories (`native-agent-board-goal-categories-v1`): what every computer starts +/// with, and what blueprints are filed by. "Something else" is stored as `other`. A computer's own +/// list, which can rename, drop and add to these, is `GoalCategoryInfo`. enum GoalCategory: String, CaseIterable, Identifiable, Sendable { case health, relationships, finance, career, interests, productivity, other @@ -354,15 +362,6 @@ enum GoalCategory: String, CaseIterable, Identifiable, Sendable { let place = self == .other ? "my Goals" : "my Goals under \(groupTitle)" return "I'd like to set \(goal). \(ask) and add it to \(place)." } - - /// Goals by category in the list's order, keeping their order within each. Goals without a - /// category (or with one this build doesn't know) go under Other. - static func grouped(_ goals: [AgentBoardItem]) -> [(category: GoalCategory, items: [AgentBoardItem])] { - let byCategory = Dictionary(grouping: goals) { $0.goalCategory ?? .other } - return allCases.compactMap { category in - byCategory[category].map { (category, $0) } - } - } } /// Swipe left on a Feed, Ideas or Goals item, and the last action in its long-press menu. @@ -517,6 +516,11 @@ protocol AgentBoardClient: AnyObject { var supportsFeedback: Bool { get } /// Goals carry a category (`native-agent-board-goal-categories-v1`). var supportsGoalCategories: Bool { get } + /// The computer's own goal categories as its last `items` read gave them + /// (`native-goal-categories-v1`); nil before a read, and from a plugin that keeps only the built-in ones. + var goalCategories: [GoalCategoryInfo]? { get } + /// Adds, renames or removes one of the computer's goal categories, and returns the list as it is now. + func changeGoalCategories(agentID: String, _ change: GoalCategoryChange) async throws -> [GoalCategoryInfo] func items(agentID: String) async throws -> [AgentBoardItem] func update(agentID: String, itemID: String, change: AgentBoardChange) async throws -> AgentBoardItem func markRead(agentID: String, itemIDs: [String]) async throws @@ -544,6 +548,7 @@ protocol AgentBoardClient: AnyObject { extension AgentBoardClient { var supportsGoalCategories: Bool { false } + var goalCategories: [GoalCategoryInfo]? { nil } var supportsFiles: Bool { false } var supportsAnswers: Bool { false } var supportsToday: Bool { false } @@ -561,6 +566,10 @@ extension AgentBoardClient { throw WorkspaceClientError.unavailable(.unsupportedOperation) } + func changeGoalCategories(agentID: String, _ change: GoalCategoryChange) async throws -> [GoalCategoryInfo] { + throw WorkspaceClientError.unavailable(.unsupportedOperation) + } + func file(agentID: String, itemID: String, file: AgentBoardItem.File) async throws -> ChatAttachment { throw WorkspaceClientError.unavailable(.unsupportedOperation) } @@ -579,6 +588,7 @@ final class DirectHermesAgentBoardClient: AgentBoardClient { /// Chat's attachment client: the same chunked download, checks and cache. Only /// given when the plugin serves posts' files. private let files: DirectHermesGeneratedMediaClient? + private(set) var goalCategories: [GoalCategoryInfo]? init(workspace: any WorkspaceOperationPerforming, owner: WorkspaceOwner, supportsFeedback: Bool, supportsGoalCategories: Bool = false, supportsAnswers: Bool = false, supportsToday: Bool = false, @@ -615,12 +625,26 @@ final class DirectHermesAgentBoardClient: AgentBoardClient { } } - /// The plugin can answer 412 after making these: a second try could make a second goal. - private static let notRepeatable: Set = [.boardPromote, .boardAccept] + /// The plugin can answer 412 after making these: a second try could make a second goal, or + /// add a category twice under two names. + private static let notRepeatable: Set = [.boardPromote, .boardAccept, .boardCategories] func items(agentID: String) async throws -> [AgentBoardItem] { let result = try await perform(.boardList, ["agentId": .string(agentID), "limit": .integer(200)]) - return try (result["items"]?.array ?? []).map(AgentBoardItem.init(json:)) + let items = try (result["items"]?.array ?? []).map(AgentBoardItem.init(json:)) + // The list is the computer's, the same for every bot on it. + goalCategories = GoalCategoryInfo.list(json: result["goalCategories"]) + return items + } + + func changeGoalCategories(agentID: String, _ change: GoalCategoryChange) async throws -> [GoalCategoryInfo] { + guard goalCategories != nil else { throw WorkspaceClientError.unavailable(.unsupportedOperation) } + let result = try await perform(.boardCategories, change.payload.merging(["agentId": .string(agentID)]) { $1 }) + guard let categories = GoalCategoryInfo.list(json: result["goalCategories"]) else { + throw WorkspaceClientError.invalidResponse + } + goalCategories = categories + return categories } func update(agentID: String, itemID: String, change: AgentBoardChange) async throws -> AgentBoardItem { @@ -778,6 +802,10 @@ final class AgentBoardStore { var supportsFiles: Bool { client?.supportsFiles ?? false } /// Without it goals have no category and the page says to update the plugin. var supportsGoalCategories: Bool { client?.supportsGoalCategories ?? false } + /// The computer's goal categories, in its order: the built-in ones until a read says otherwise. + private(set) var goalCategories = GoalCategoryInfo.builtIn + /// The computer keeps a list of its own that Goals › Categories can change. + private(set) var canEditGoalCategories = false /// Just deleted, for Undo. private(set) var recentlyHidden: AgentBoardItem? var feed: [AgentBoardItem] { items.filter { $0.kind == .feed && !$0.dismissed } } @@ -799,6 +827,7 @@ final class AgentBoardStore { generation &+= 1 pendingReads = [:] items = []; activity = []; approvals = []; pictures = [:]; identity = nil; recentlyHidden = nil + goalCategories = GoalCategoryInfo.builtIn; canEditGoalCategories = false fileStates = [:]; fileThumbnails = [:]; pendingThumbnails = []; openingFile = nil state = client == nil ? .unavailable : .idle logState = state @@ -865,6 +894,7 @@ final class AgentBoardStore { for index in loaded.indices where pending.contains(loaded[index].id) { loaded[index].read = true } } items = loaded + takeGoalCategories(client.goalCategories) state = .loaded await sendPendingReads(agentID: agentID) } catch is CancellationError { @@ -1028,6 +1058,38 @@ final class AgentBoardStore { items[index].answeredAt = now } + private func takeGoalCategories(_ categories: [GoalCategoryInfo]?) { + let next = categories ?? GoalCategoryInfo.builtIn + if goalCategories != next { goalCategories = next } + if canEditGoalCategories != (categories != nil) { canEditGoalCategories = categories != nil } + } + + /// Goals › Categories: add, rename or remove one of the computer's categories. Nil when the + /// computer took it, else why not, in words for the person. The goals are read again, because a + /// change moves them: a renamed category's goals take its new name, a removed one's go to Other. + func changeGoalCategories(_ change: GoalCategoryChange) async -> String? { + guard let client, let agentID, canEditGoalCategories else { + return String(localized: "This computer isn't connected. Try again in a moment.") + } + let generation = generation + do { + let categories = try await client.changeGoalCategories(agentID: agentID, change) + guard generation == self.generation else { return nil } + takeGoalCategories(categories) + await load(agentID: agentID) + return nil + } catch let WorkspaceClientError.rejected(code, _) { + if code == "category_not_found" { await load(agentID: agentID) } + return GoalCategoryChange.refusal(code) + } catch { + // No answer, or the page that asked went away: the computer may have made the change, so + // read what it has now. + // In a task of its own: the one that asked may be cancelled already. + if generation == self.generation { Task { [weak self] in await self?.load(agentID: agentID) } } + return GoalCategoryChange.refusal(nil) + } + } + func setDone(_ item: AgentBoardItem, _ done: Bool) async { await mutate(item) { $0.status = done ? "done" : "active" } send: { client, agent in try await client.update(agentID: agent, itemID: item.id, change: .init(status: done ? "done" : "active")) diff --git a/Bighelp/Board/AgentGoalsView.swift b/Bighelp/Board/AgentGoalsView.swift index d914c12f..2e9b06c9 100644 --- a/Bighelp/Board/AgentGoalsView.swift +++ b/Bighelp/Board/AgentGoalsView.swift @@ -3,16 +3,18 @@ import SwiftUI /// Goals: what the agent is tracking (the latest one in a block of its category's color, the /// rest by category in a card), then done ones, then Create a goal by category. Every goal is /// a List row of its own (`BoardScroll`), so goals swipe left to remove. Goals have no progress -/// number, so nothing here draws one. +/// number, so nothing here draws one. The categories are the computer's own +/// (`AgentBoardStore.goalCategories`); Edit categories under the list changes them. struct AgentGoalsView: View { let context: AgentBoardContext @State private var showsDone = false @State private var showsBlueprints = false + @State private var showsCategories = false /// One row of the Tracking or Done card: a category's heading or a goal. private struct CardEntry: Identifiable { let id: String - var category: GoalCategory? + var category: GoalCategoryInfo? var goal: AgentBoardItem? } @@ -23,9 +25,10 @@ struct AgentGoalsView: View { let isLoaded = store.state == .loaded // The one the agent touched last leads. let hero = active.max { $0.updatedAt < $1.updatedAt } - let groups = GoalCategory.grouped(active.filter { $0.id != hero?.id }) + let categories = store.goalCategories + let groups = GoalCategoryInfo.grouped(active.filter { $0.id != hero?.id }, in: categories) let tracking: [CardEntry] = groups.flatMap { group -> [CardEntry] in - [CardEntry(id: "category.\(group.category.rawValue)", category: group.category)] + [CardEntry(id: "category.\(group.category.id)", category: group.category)] + group.items.map { CardEntry(id: $0.id, goal: $0) } } BoardScroll(context: context, title: "Goals", identifier: "board.goals", seen: goals, @@ -43,12 +46,12 @@ struct AgentGoalsView: View { .boardRow() } if let hero { - let category = hero.goalCategory ?? .other + let category = shown(hero, in: categories) // The category's heading carries its name for tests and VoiceOver; with no // other goals in it, the block's pill does. - GoalHeroBlock(goal: hero, context: context, - categoryIdentifier: groups.contains { $0.category == category } - ? "board.goals.hero.category" : "board.goals.category.\(category.rawValue)") + GoalHeroBlock(goal: hero, category: category, context: context, + categoryIdentifier: groups.contains { $0.category.id == category.id } + ? "board.goals.hero.category" : "board.goals.category.\(category.id)") .boardRow() .boardItemSwipe(hero, store: store) } @@ -60,6 +63,10 @@ struct AgentGoalsView: View { .boardRow(top: BighelpTokens.space16, bottom: BighelpTokens.space4) createList .boardRow() + if store.canEditGoalCategories { + editCategories + .boardRow(top: 0) + } if !store.supportsGoalCategories { categoriesNeedUpdate .boardRow() @@ -67,6 +74,29 @@ struct AgentGoalsView: View { } } .boardBlueprints(isPresented: $showsBlueprints, kind: .goal, context: context) + .bighelpSheet(isPresented: $showsCategories) { GoalCategoriesSheet(context: context) } + } + + /// The goal's category as the computer lists it now; one that left the list is Other. + private func shown(_ goal: AgentBoardItem, in categories: [GoalCategoryInfo]) -> GoalCategoryInfo { + let id = goal.goalCategoryInfo.id + return categories.first { $0.id == id } ?? categories.first(where: \.isOther) ?? .other + } + + /// Under the Create a goal list: opens the computer's categories to add, rename and delete. + private var editCategories: some View { + Button { + showsCategories = true + } label: { + // The whole row takes the tap, not only its words. + Label("Edit categories", systemImage: "slider.horizontal.3") + .font(.bighelp(.subheadline).weight(.semibold)) + .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) + .contentShape(.rect) + } + .buttonStyle(.borderless) + .tint(theme.action) + .accessibilityIdentifier("board.goals.categories.edit") } /// A bordered card a row at a time: headings and goals, each goal swiping on its own. @@ -87,15 +117,15 @@ struct AgentGoalsView: View { } } - private func categoryHeader(_ category: GoalCategory) -> some View { - Text(category.groupTitle) + private func categoryHeader(_ category: GoalCategoryInfo) -> some View { + Text(category.name) .font(.bighelp(.footnote, weight: .bold)) .foregroundStyle(theme.secondaryText) .padding(.horizontal, BighelpTokens.space16) .padding(.top, BighelpTokens.space12) .padding(.bottom, BighelpTokens.space4) .accessibilityAddTraits(.isHeader) - .accessibilityIdentifier("board.goals.category.\(category.rawValue)") + .accessibilityIdentifier("board.goals.category.\(category.id)") } @ViewBuilder @@ -148,7 +178,7 @@ struct AgentGoalsView: View { /// message box; touch and hold starts from one of its blueprints instead. private var createList: some View { VStack(spacing: 0) { - ForEach(Array(GoalCategory.allCases.enumerated()), id: \.element) { index, category in + ForEach(Array(context.store.goalCategories.enumerated()), id: \.element.id) { index, category in if index > 0 { Rectangle() .fill(theme.separator) @@ -167,9 +197,10 @@ struct AgentGoalsView: View { } @ViewBuilder - private func createRow(_ category: GoalCategory) -> some View { - let blueprints = BoardBlueprintCatalog.shared.blueprints(for: category) - // Seven rows share one List row, and a List row shows only its first context menu: + private func createRow(_ category: GoalCategoryInfo) -> some View { + // Blueprints are filed by the built-in categories. + let blueprints = category.builtInCategory.map(BoardBlueprintCatalog.shared.blueprints(for:)) ?? [] + // The rows share one List row, and a List row shows only its first context menu: // each row carries its own Menu instead. Group { if blueprints.isEmpty { @@ -192,11 +223,11 @@ struct AgentGoalsView: View { } } } - .accessibilityLabel(category == .other ? "Create a goal: something else" : "Create a \(category.title) goal") - .accessibilityIdentifier("board.goals.create.\(category.rawValue)") + .accessibilityLabel(category.isOther ? "Create a goal: something else" : "Create a \(category.title) goal") + .accessibilityIdentifier("board.goals.create.\(category.id)") } - private func createLabel(_ category: GoalCategory) -> some View { + private func createLabel(_ category: GoalCategoryInfo) -> some View { HStack(spacing: BighelpTokens.space12) { CategoryBadge(category: category, size: 34) Text(category.title) @@ -242,7 +273,7 @@ struct AgentGoalsView: View { /// A goal in the card: its category's tile, title and the agent's note, then done and ⋯. private func goalRow(_ goal: AgentBoardItem) -> some View { HStack(alignment: .center, spacing: BighelpTokens.space12) { - CategoryBadge(category: goal.goalCategory ?? .other, size: 36) + CategoryBadge(category: shown(goal, in: context.store.goalCategories), size: 36) VStack(alignment: .leading, spacing: 2) { Text(goal.title) .font(.bighelp(.subheadline, weight: .semibold)) @@ -280,15 +311,15 @@ struct AgentGoalsView: View { /// title and the agent's latest note, with Mark done. private struct GoalHeroBlock: View { let goal: AgentBoardItem + let category: GoalCategoryInfo let context: AgentBoardContext let categoryIdentifier: String var body: some View { - let category = goal.goalCategory ?? .other let block = BighelpBlockColor.goal(category) VStack(alignment: .leading, spacing: BighelpTokens.space12) { HStack(alignment: .center, spacing: BighelpTokens.space8) { - BoardOutlinePill(title: category.groupTitle, systemImage: category.systemImage, ink: block.ink) + BoardOutlinePill(title: category.pillTitle, systemImage: category.pillSystemImage, ink: block.ink) .accessibilityAddTraits(.isHeader) .accessibilityIdentifier(categoryIdentifier) Spacer(minLength: 0) @@ -381,10 +412,11 @@ private struct GoalMoreMenu: View { /// A category's symbol on a small square of its block color: content, not a control. private struct CategoryBadge: View { - let category: GoalCategory + let category: GoalCategoryInfo let size: CGFloat var body: some View { - BoardIconTile(icon: "", fallback: category.systemImage, color: BighelpBlockColor.goal(category), size: size) + BoardIconTile(icon: category.icon, fallback: category.systemImage, color: BighelpBlockColor.goal(category), + size: size) } } diff --git a/Bighelp/Board/BoardDashboardViews.swift b/Bighelp/Board/BoardDashboardViews.swift index d25d15fc..a56e80a1 100644 --- a/Bighelp/Board/BoardDashboardViews.swift +++ b/Bighelp/Board/BoardDashboardViews.swift @@ -505,7 +505,7 @@ private struct DashboardSection: View { // What's new gets the Feed's deep green, as its "new today" block does. case .feed: context.store.supportsFeedback && !item.read ? .forest : .feed(item) case .idea: .idea(item) - case .goal: .goal(item.goalCategory ?? .other) + case .goal: .goal(item.goalCategoryInfo) } } @@ -750,7 +750,7 @@ private struct DashboardItemFace: View, Equatable { let section = item.section.trimmingCharacters(in: .whitespaces) return section.isEmpty ? String(localized: "Idea") : section case .goal: - return (item.goalCategory ?? .other).groupTitle + return item.goalCategoryInfo.pillTitle } } @@ -758,7 +758,7 @@ private struct DashboardItemFace: View, Equatable { switch item.kind { case .feed: isNew ? "circle.fill" : nil case .idea: nil - case .goal: (item.goalCategory ?? .other).systemImage + case .goal: item.goalCategoryInfo.pillSystemImage } } diff --git a/Bighelp/Board/GoalCategories.swift b/Bighelp/Board/GoalCategories.swift new file mode 100644 index 00000000..ec0325a7 --- /dev/null +++ b/Bighelp/Board/GoalCategories.swift @@ -0,0 +1,124 @@ +import Foundation + +/// One of a computer's goal categories (plugin `native-goal-categories-v1`). Each computer keeps its +/// own list for every bot on it: the built-in seven until someone changes it in Goals › Categories or +/// asks a bot to. Its `id` never changes, so a renamed category keeps its goals. Other is always +/// there and last; goals whose category left the list show under it. +struct GoalCategoryInfo: Hashable, Identifiable, Sendable { + let id: String + var name: String + /// One emoji, or empty: then the built-in category's symbol, else a tag. + var icon: String + + static let maximumNameLength = 40 + static let maximumIconLength = 16 + static let maximumCount = 24 + /// What a computer has until its list changes, and what a plugin without the feature has. + static let builtIn = GoalCategory.allCases.map { GoalCategoryInfo($0) } + static let other = GoalCategoryInfo(.other) + + init(id: String, name: String, icon: String = "") { + self.id = id + self.name = name + self.icon = icon + } + + init(_ category: GoalCategory) { + self.init(id: category.rawValue, name: category.groupTitle) + } + + /// Lenient, bounded: a row without an ID or a name is skipped by `list(json:)`. + init?(json value: BighelpJSONValue) { + guard let object = value.object, + let id = object["id"]?.string, !id.isEmpty, id.count <= 64, + let name = object["name"]?.string?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty + else { return nil } + self.init(id: id, name: String(name.prefix(Self.maximumNameLength)), + icon: String((object["icon"]?.string ?? "").prefix(Self.maximumIconLength))) + } + + /// The computer's list as `board/list` and `board/categories` send it; nil when the plugin sends none. + static func list(json value: BighelpJSONValue?) -> [GoalCategoryInfo]? { + guard let rows = value?.array else { return nil } + var seen: Set = [] + let categories = rows.prefix(maximumCount).compactMap(GoalCategoryInfo.init(json:)).filter { seen.insert($0.id).inserted } + return categories.isEmpty ? nil : categories + } + + /// The built-in category with this ID, for its symbol, blueprints and wording. + var builtInCategory: GoalCategory? { GoalCategory(rawValue: id) } + var isOther: Bool { id == GoalCategory.other.rawValue } + /// In the Create a goal list. + var title: String { isOther ? GoalCategory.other.title : name } + var systemImage: String { builtInCategory?.systemImage ?? "tag" } + /// A pill's words: the emoji leads when there is one. + var pillTitle: String { icon.isEmpty ? name : "\(icon) \(name)" } + var pillSystemImage: String? { icon.isEmpty ? systemImage : nil } + + /// What Create a goal puts in the message box. It names the category so the bot files the goal there. + var prompt: String { + if let builtInCategory, name == builtInCategory.groupTitle { return builtInCategory.prompt } + return "I'd like to set a goal. Ask me a few quick questions about what I'm after, then make a plan " + + "and add it to my Goals under \(name)." + } + + /// Goals by category in the computer's order, keeping their order within each. A goal whose + /// category isn't on the list goes under Other. + static func grouped(_ goals: [AgentBoardItem], in list: [GoalCategoryInfo]) + -> [(category: GoalCategoryInfo, items: [AgentBoardItem])] { + let listed = Set(list.map(\.id)) + let byCategory = Dictionary(grouping: goals) { goal -> String in + let id = goal.goalCategoryInfo.id + return listed.contains(id) ? id : GoalCategory.other.rawValue + } + let order = list.contains(where: \.isOther) ? list : list + [.other] + return order.compactMap { category in byCategory[category.id].map { (category, $0) } } + } +} + +/// One change to a computer's goal categories, from Goals › Categories. +enum GoalCategoryChange: Equatable, Sendable { + case add(name: String, icon: String) + case update(id: String, name: String, icon: String) + case delete(id: String) + + var payload: [String: BighelpJSONValue] { + switch self { + case let .add(name, icon): + ["action": .string("add"), "name": .string(name), "icon": .string(icon)] + case let .update(id, name, icon): + ["action": .string("update"), "id": .string(id), "name": .string(name), "icon": .string(icon)] + case let .delete(id): + ["action": .string("delete"), "id": .string(id)] + } + } + + /// Why the computer didn't take a change, by the plugin's code. + static func refusal(_ code: String?) -> String { + switch code { + case "category_exists": String(localized: "There's already a category with that name.") + case "too_many_categories": + String(localized: "This computer has as many categories as it can keep. Delete one first.") + case "invalid_category": String(localized: "Use a short name, and one emoji for the icon.") + case "category_fixed": String(localized: "Other can't be renamed or deleted.") + case "category_not_found": String(localized: "That category isn't on this computer any more.") + default: String(localized: "The computer didn't save that. Try again.") + } + } +} + +extension AgentBoardItem { + /// Where a goal shows. The computer says (`categoryName`); a plugin from before that sends only a + /// built-in name, and a goal without one goes where its words point. + var goalCategoryInfo: GoalCategoryInfo { + if !categoryName.isEmpty, !category.isEmpty { + return GoalCategoryInfo(id: category, name: categoryName, icon: categoryIcon) + } + return GoalCategoryInfo(goalCategory ?? .other) + } +} + +extension BighelpBlockColor { + /// A category keeps its color through a rename: it goes by the ID. + static func goal(_ category: GoalCategoryInfo) -> BighelpBlockColor { pastel(for: category.id) } +} diff --git a/Bighelp/Board/GoalCategoriesSheet.swift b/Bighelp/Board/GoalCategoriesSheet.swift new file mode 100644 index 00000000..db7d49c3 --- /dev/null +++ b/Bighelp/Board/GoalCategoriesSheet.swift @@ -0,0 +1,261 @@ +import SwiftUI + +/// Goals › Edit categories: the computer's own goal categories, for every bot on it. A row opens +/// its name and emoji; a swipe, the row's menu or the editor deletes it. Each change goes to the +/// computer first (`AgentBoardStore.changeGoalCategories`) and shows once it took it; a refusal +/// stays on the page in plain words. Other is listed, and never changes. +struct GoalCategoriesSheet: View { + let context: AgentBoardContext + + /// What the editor is open on: a category, or a new one. + struct Draft: Identifiable, Hashable { + /// Nil for a new category. + var categoryID: String? + var name = "" + var icon = "" + + var id: String { categoryID ?? "new" } + } + + private struct Request: Equatable { + let change: GoalCategoryChange + let attempt = UUID() + } + + @Environment(\.dismiss) private var dismiss + @State private var draft: Draft? + @State private var deleting: GoalCategoryInfo? + @State private var request: Request? + @State private var failure: String? + + var body: some View { + let categories = context.store.goalCategories + NavigationStack { + List { + Section { + // One change at a time: a second one would cancel the first while the computer works on it. + ForEach(categories) { row($0).disabled(request != nil) } + } footer: { + if let failure, draft == nil { + Text(failure) + .foregroundStyle(theme.danger) + .accessibilityIdentifier("board.goals.categories.error") + } else { + Text("Every bot on this computer uses these. When you delete a category, its goals move to Other.") + } + } + .listRowBackground(theme.surface) + if categories.count < GoalCategoryInfo.maximumCount { + Section { + Button { + failure = nil + draft = Draft() + } label: { + Label("Add category", systemImage: "plus") + .font(.bighelp(.body).weight(.medium)) + .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) + .contentShape(.rect) + } + .bighelpPlainButtonStyle() + .foregroundStyle(theme.action) + .disabled(request != nil) + .accessibilityIdentifier("board.goals.categories.add") + } + .listRowBackground(theme.surface) + } + } + .scrollContentBackground(.hidden) + .background(theme.canvas.ignoresSafeArea()) + .navigationTitle("Categories") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { dismiss() } + .accessibilityIdentifier("board.goals.categories.done") + } + } + .navigationDestination(item: $draft) { draft in + GoalCategoryEditor(draft: draft, isBusy: request != nil, failure: failure) { change in + request = Request(change: change) + } + } + } + .confirmationDialog(deleting.map { String(localized: "Delete \($0.name)?") } ?? "", + isPresented: Binding { deleting != nil } set: { if !$0 { deleting = nil } }, + titleVisibility: .visible, presenting: deleting) { category in + Button("Delete category", role: .destructive) { request = Request(change: .delete(id: category.id)) } + Button("Cancel", role: .cancel) {} + } message: { _ in + Text("Its goals move to Other.") + } + // A refusal belongs to the page that asked: leaving the editor leaves it behind. + .onChange(of: draft) { old, new in + if old != nil, new == nil, request == nil { failure = nil } + } + .task(id: request) { + guard let request else { return } + let refusal = await context.store.changeGoalCategories(request.change) + guard !Task.isCancelled, self.request == request else { return } + failure = refusal + self.request = nil + // The editor closes on a change the computer took; a refusal stays there to fix. + if failure == nil { draft = nil } + } + .bighelpSheetSize(.standard) + .accessibilityIdentifier("board.goals.categories") + } + + @ViewBuilder + private func row(_ category: GoalCategoryInfo) -> some View { + let label = HStack(spacing: BighelpTokens.space12) { + BoardIconTile(icon: category.icon, fallback: category.systemImage, color: .goal(category), size: 34) + VStack(alignment: .leading, spacing: 2) { + Text(category.name) + .font(.bighelp(.body).weight(.medium)) + .foregroundStyle(theme.primaryText) + if category.isOther { + Text("For goals in no category") + .font(.bighelp(.footnote)) + .foregroundStyle(theme.secondaryText) + } + } + Spacer(minLength: BighelpTokens.space8) + if !category.isOther { + Image(systemName: "chevron.right") + .font(.bighelp(.footnote).weight(.semibold)) + .foregroundStyle(theme.tertiaryText) + .accessibilityHidden(true) + } + } + .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) + .contentShape(.rect) + if category.isOther { + label + .accessibilityElement(children: .combine) + .accessibilityIdentifier("board.goals.categories.row.\(category.id)") + } else { + Button { + failure = nil + draft = Draft(categoryID: category.id, name: category.name, icon: category.icon) + } label: { + label + } + .bighelpPlainButtonStyle() + .accessibilityHint("Changes its name and emoji") + .accessibilityIdentifier("board.goals.categories.row.\(category.id)") + .swipeActions(edge: .trailing, allowsFullSwipe: false) { + Button("Delete", systemImage: "trash", role: .destructive) { deleting = category } + } + // The Mac has no swipe: a right-click offers the same. + .contextMenu { + Button("Delete", systemImage: "trash", role: .destructive) { deleting = category } + } + } + } + + @BighelpThemeReader private var theme +} + +/// One category's name and emoji. Save sends the change; the sheet closes this page once the +/// computer took it. +private struct GoalCategoryEditor: View { + let draft: GoalCategoriesSheet.Draft + let isBusy: Bool + let failure: String? + let onChange: (GoalCategoryChange) -> Void + + @State private var name = "" + @State private var icon = "" + @State private var confirmsDelete = false + @FocusState private var nameIsFocused: Bool + + private var trimmedName: String { name.trimmingCharacters(in: .whitespacesAndNewlines) } + private var canSave: Bool { + !isBusy && !trimmedName.isEmpty && (draft.categoryID == nil || trimmedName != draft.name || icon != draft.icon) + } + + var body: some View { + Form { + Section { + TextField("Name", text: $name, prompt: Text("Name").bighelpFieldHint(theme)) + .focused($nameIsFocused) + .submitLabel(.done) + .onSubmit { if canSave { save() } } + .onChange(of: name) { _, value in + if value.count > GoalCategoryInfo.maximumNameLength { + name = String(value.prefix(GoalCategoryInfo.maximumNameLength)) + } + } + .accessibilityIdentifier("board.goals.categories.name") + TextField("Emoji", text: $icon, prompt: Text("Emoji (optional)").bighelpFieldHint(theme)) + .onChange(of: icon) { _, value in + let kept = Self.emoji(in: value) + if kept != value { icon = kept } + } + .accessibilityIdentifier("board.goals.categories.icon") + } footer: { + if let failure { + Text(failure) + .foregroundStyle(theme.danger) + .accessibilityIdentifier("board.goals.categories.error") + } else if draft.categoryID != nil { + Text("A new name keeps its goals.") + } + } + .listRowBackground(theme.surface) + if draft.categoryID != nil { + Section { + Button("Delete category", role: .destructive) { confirmsDelete = true } + .disabled(isBusy) + .accessibilityIdentifier("board.goals.categories.delete") + } + .listRowBackground(theme.surface) + } + } + .scrollContentBackground(.hidden) + .background(theme.canvas.ignoresSafeArea()) + .navigationTitle(draft.categoryID == nil ? "New category" : "Edit category") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Save") { save() } + .disabled(!canSave) + .accessibilityIdentifier("board.goals.categories.save") + } + } + .confirmationDialog(String(localized: "Delete \(draft.name)?"), isPresented: $confirmsDelete, + titleVisibility: .visible) { + Button("Delete category", role: .destructive) { + if let id = draft.categoryID { onChange(.delete(id: id)) } + } + Button("Cancel", role: .cancel) {} + } message: { + Text("Its goals move to Other.") + } + .onAppear { + name = draft.name + icon = draft.icon + if draft.categoryID == nil { nameIsFocused = true } + } + } + + private func save() { + if let id = draft.categoryID { + onChange(.update(id: id, name: trimmedName, icon: icon)) + } else { + onChange(.add(name: trimmedName, icon: icon)) + } + } + + /// The last emoji typed, or nothing: the computer takes one emoji and no letters. + static func emoji(in text: String) -> String { + guard let last = text.last(where: { character in + // A keycap ("1️⃣") starts with a digit, which the computer refuses. + guard let scalar = character.unicodeScalars.first, !scalar.isASCII else { return false } + return scalar.properties.isEmojiPresentation || (scalar.properties.isEmoji && character.unicodeScalars.count > 1) + }) else { return "" } + return String(last) + } + + @BighelpThemeReader private var theme +} diff --git a/Bighelp/Chat/ChatBoardCard.swift b/Bighelp/Chat/ChatBoardCard.swift index c9516f46..02ffca71 100644 --- a/Bighelp/Chat/ChatBoardCard.swift +++ b/Bighelp/Chat/ChatBoardCard.swift @@ -118,7 +118,7 @@ extension AgentBoardItem { ChatBoardCard(kind: .feedPost, title: title, detail: source, body: body) case .goal: ChatBoardCard(kind: .goal, title: title, - detail: goalCategory.map { $0 == .other ? "" : $0.groupTitle } ?? "", + detail: goalCategoryInfo.isOther ? "" : goalCategoryInfo.name, body: [body, note.isEmpty ? "" : "Latest: \(note)"].filter { !$0.isEmpty }.joined(separator: "\n\n")) } } diff --git a/Bighelp/DirectHermes/DirectHermesNativeContext.swift b/Bighelp/DirectHermes/DirectHermesNativeContext.swift index 049696e7..696b3923 100644 --- a/Bighelp/DirectHermes/DirectHermesNativeContext.swift +++ b/Bighelp/DirectHermes/DirectHermesNativeContext.swift @@ -590,6 +590,9 @@ final class DirectHermesNativePluginClient { case .boardAccept: return Route(path: "board/accept", feature: "native-agent-board-answers-v1", isMutation: true, maximumResponseBytes: 196_608) + case .boardCategories: + return Route(path: "board/categories", feature: "native-goal-categories-v1", isMutation: true, + maximumResponseBytes: 65_536) case .workflowsStatus, .workflowsList, .workflowsGet, .workflowsDraftSave, .workflowsValidate, .workflowsPublish, .workflowsBind, .workflowsArchive, .workflowsRunsStart, .workflowsRunsList, .workflowsRunsGet, .workflowsRunsEvents, .workflowsRunsControl, .workflowsRunsSignoff, diff --git a/Bighelp/Fixtures/DemoAgentBoardClient.swift b/Bighelp/Fixtures/DemoAgentBoardClient.swift index ddfc9a05..c292aee5 100644 --- a/Bighelp/Fixtures/DemoAgentBoardClient.swift +++ b/Bighelp/Fixtures/DemoAgentBoardClient.swift @@ -26,15 +26,63 @@ final class DemoAgentBoardClient: AgentBoardClient { agentID == "home" || UUID(uuidString: agentID) != nil } + /// The demo computer's own categories, changed in Goals › Categories as on a real one. + private var categories = GoalCategoryInfo.builtIn + var goalCategories: [GoalCategoryInfo]? { categories } + func items(agentID: String) async throws -> [AgentBoardItem] { + try await stored(agentID: agentID).map(shown) + } + + /// The items as kept: a goal keeps its category's ID through any change to the list. + private func stored(agentID: String) async throws -> [AgentBoardItem] { if let items = itemsByAgent[agentID] { return items } let items = Self.startsEmpty(agentID) ? [] : seed() itemsByAgent[agentID] = items return items } + /// As the plugin does: each goal says where it shows now. + private func shown(_ item: AgentBoardItem) -> AgentBoardItem { + guard item.kind == .goal else { return item } + var item = item + let category = categories.first { $0.id == item.category } ?? .other + (item.category, item.categoryName, item.categoryIcon) = (category.id, category.name, category.icon) + return item + } + + func changeGoalCategories(agentID: String, _ change: GoalCategoryChange) async throws -> [GoalCategoryInfo] { + func isTaken(_ name: String, except id: String? = nil) -> Bool { + categories.contains { $0.id != id && $0.name.caseInsensitiveCompare(name) == .orderedSame } + } + switch change { + case let .add(name, icon): + guard !isTaken(name) else { throw WorkspaceClientError.rejected(code: "category_exists") } + guard categories.count < GoalCategoryInfo.maximumCount else { + throw WorkspaceClientError.rejected(code: "too_many_categories") + } + let id = name.lowercased().split { !($0.isLetter || $0.isNumber) }.joined(separator: "-") + categories.insert(GoalCategoryInfo(id: id.isEmpty ? UUID().uuidString.lowercased() : id, name: name, icon: icon), + at: max(categories.count - 1, 0)) + case let .update(id, name, icon): + guard let index = categories.firstIndex(where: { $0.id == id }) else { + throw WorkspaceClientError.rejected(code: "category_not_found") + } + guard !isTaken(name, except: id) else { throw WorkspaceClientError.rejected(code: "category_exists") } + guard !categories[index].isOther || name == categories[index].name else { + throw WorkspaceClientError.rejected(code: "category_fixed") + } + categories[index].name = name + categories[index].icon = icon + case let .delete(id): + guard id != GoalCategory.other.rawValue else { throw WorkspaceClientError.rejected(code: "category_fixed") } + categories.removeAll { $0.id == id } + } + return categories + } + func update(agentID: String, itemID: String, change: AgentBoardChange) async throws -> AgentBoardItem { - var items = try await self.items(agentID: agentID) + var items = try await stored(agentID: agentID) guard let index = items.firstIndex(where: { $0.id == itemID }) else { throw WorkspaceClientError.invalidRequest } if let rating = change.rating { items[index].rating = rating @@ -44,17 +92,17 @@ final class DemoAgentBoardClient: AgentBoardClient { if let dismissed = change.dismissed { items[index].dismissed = dismissed } if let status = change.status { items[index].status = status } itemsByAgent[agentID] = items - return items[index] + return shown(items[index]) } func markRead(agentID: String, itemIDs: [String]) async throws { - var items = try await self.items(agentID: agentID) + var items = try await stored(agentID: agentID) for index in items.indices where itemIDs.contains(items[index].id) { items[index].read = true } itemsByAgent[agentID] = items } func promote(agentID: String, itemID: String) async throws -> AgentBoardItem { - var items = try await self.items(agentID: agentID) + var items = try await stored(agentID: agentID) guard let index = items.firstIndex(where: { $0.id == itemID && $0.kind == .idea }) else { throw WorkspaceClientError.invalidRequest } diff --git a/Bighelp/Workspace/WorkspaceOperation.swift b/Bighelp/Workspace/WorkspaceOperation.swift index 528a7f17..47fccd96 100644 --- a/Bighelp/Workspace/WorkspaceOperation.swift +++ b/Bighelp/Workspace/WorkspaceOperation.swift @@ -180,6 +180,8 @@ enum WorkspaceOperation: String, CaseIterable, Sendable { case boardPromote = "board.promote" /// Let's do it on an idea, by its ID (plugin `native-agent-board-answers-v1`). case boardAccept = "board.accept" + /// Adds, renames or removes one of the computer's goal categories (plugin `native-goal-categories-v1`). + case boardCategories = "board.categories" case usageList = "usage.list" /// Hours of the day, messages and models per day for the Usage page (plugin, `native-usage-activity-v1`). case usageActivity = "usage.activity" diff --git a/BighelpTests/BoardBlueprintAndGoalCategoryTests.swift b/BighelpTests/BoardBlueprintAndGoalCategoryTests.swift index e7f58baa..15d17904 100644 --- a/BighelpTests/BoardBlueprintAndGoalCategoryTests.swift +++ b/BighelpTests/BoardBlueprintAndGoalCategoryTests.swift @@ -160,11 +160,11 @@ struct BoardBlueprintAndGoalCategoryTests { #expect(GoalCategory.inferred(from: "Inbox under 20 every Friday") == .productivity) #expect(GoalCategory.inferred(from: "Something nice") == nil) #expect(GoalCategory.inferred(from: "Workout budget") == nil, "A tie is no category") - let groups = GoalCategory.grouped([ + let groups = GoalCategoryInfo.grouped([ AgentBoardItem(id: "a", kind: .goal, title: "Health goal", body: "Walk 8,000 steps a day"), AgentBoardItem(id: "b", kind: .goal, title: "Something nice"), - ]) - #expect(groups.map(\.category) == [.health, .other]) + ], in: GoalCategoryInfo.builtIn) + #expect(groups.map(\.category.id) == ["health", "other"]) } @Test func goalsGroupByCategoryInTheListsOrderWithUncategorizedUnderOther() { @@ -176,14 +176,116 @@ struct BoardBlueprintAndGoalCategoryTests { AgentBoardItem(id: "e", kind: .goal, title: "Walk", category: "health"), AgentBoardItem(id: "f", kind: .goal, title: "Else", category: "other"), ] - let groups = GoalCategory.grouped(goals) - #expect(groups.map(\.category) == [.health, .finance, .other]) + let groups = GoalCategoryInfo.grouped(goals, in: GoalCategoryInfo.builtIn) + #expect(groups.map(\.category.id) == ["health", "finance", "other"]) #expect(groups.map { $0.items.map(\.id) } == [["c", "e"], ["a"], ["b", "d", "f"]]) - #expect(GoalCategory.grouped([]).isEmpty) + #expect(GoalCategoryInfo.grouped([], in: GoalCategoryInfo.builtIn).isEmpty) // An older plugin: goals go where their words point, the rest under Other; nothing is lost. - let legacy = GoalCategory.grouped([AgentBoardItem(id: "x", kind: .goal, title: "Sleep"), - AgentBoardItem(id: "y", kind: .goal, title: "Old goal")]) - #expect(legacy.map(\.category) == [.health, .other] && legacy.allSatisfy { $0.items.count == 1 }) + let legacy = GoalCategoryInfo.grouped([AgentBoardItem(id: "x", kind: .goal, title: "Sleep"), + AgentBoardItem(id: "y", kind: .goal, title: "Old goal")], + in: GoalCategoryInfo.builtIn) + #expect(legacy.map(\.category.id) == ["health", "other"] && legacy.allSatisfy { $0.items.count == 1 }) + } + + // MARK: A computer's own categories + + private static let homeLab = GoalCategoryInfo(id: "home-lab", name: "Home lab", icon: "🖥️") + + @Test func aGoalShowsInItsComputersCategoryByItsNameAndEmoji() throws { + let goal = try AgentBoardItem(json: .object([ + "id": .string("keys"), "kind": .string("goal"), "title": .string("Audit the SSH keys"), + "category": .string("home-lab"), "categoryName": .string("Home lab"), "categoryIcon": .string("🖥️"), + ])) + #expect(goal.goalCategoryInfo == Self.homeLab) + #expect(goal.goalCategoryInfo.pillTitle == "🖥️ Home lab" && goal.goalCategoryInfo.pillSystemImage == nil) + #expect(goal.chatCard.detail == "Home lab") + // A built-in category someone renamed keeps its symbol and takes the new name. + let renamed = AgentBoardItem(id: "m", kind: .goal, title: "Save", category: "finance", categoryName: "Money") + #expect(renamed.goalCategoryInfo.name == "Money" && renamed.goalCategoryInfo.systemImage == "dollarsign") + #expect(renamed.goalCategoryInfo.prompt.contains("under Money")) + #expect(GoalCategoryInfo(.finance).prompt == GoalCategory.finance.prompt) + // A plugin from before the list sends only the built-in name. + #expect(AgentBoardItem(id: "o", kind: .goal, title: "Save", category: "finance").goalCategoryInfo + == GoalCategoryInfo(.finance)) + } + + @Test func goalsGroupInTheComputersOrderAndOnesOffTheListGoUnderOther() { + let list = [GoalCategoryInfo(.health), Self.homeLab, .other] + let goals = [ + AgentBoardItem(id: "a", kind: .goal, title: "Audit", category: "home-lab", categoryName: "Home lab"), + AgentBoardItem(id: "b", kind: .goal, title: "Save", category: "finance", categoryName: "Finance"), + AgentBoardItem(id: "c", kind: .goal, title: "Run", category: "health", categoryName: "Health"), + ] + let groups = GoalCategoryInfo.grouped(goals, in: list) + #expect(groups.map(\.category.id) == ["health", "home-lab", "other"]) + #expect(groups.map { $0.items.map(\.id) } == [["c"], ["a"], ["b"]], "Finance left the list") + } + + @Test func theComputersListIsReadLeniently() { + let rows: [BighelpJSONValue] = [ + .object(["id": .string("health"), "name": .string("Health"), "icon": .string("")]), + .object(["id": .string("home-lab"), "name": .string(" Home lab "), "icon": .string("🖥️"), + "later": .boolean(true)]), + .object(["id": .string("home-lab"), "name": .string("Twice")]), + .object(["name": .string("No ID")]), + .string("nonsense"), + .object(["id": .string("other"), "name": .string("Other")]), + ] + #expect(GoalCategoryInfo.list(json: .array(rows))?.map(\.id) == ["health", "home-lab", "other"]) + #expect(GoalCategoryInfo.list(json: .array(rows))?[1] == Self.homeLab) + #expect(GoalCategoryInfo.list(json: nil) == nil, "A plugin from before the list") + #expect(GoalCategoryInfo.list(json: .array([])) == nil) + } + + @Test func theGoalsPageChangesTheComputersCategories() async throws { + let client = DemoAgentBoardClient() + let store = AgentBoardStore() + store.configure(client: client) + #expect(store.goalCategories == GoalCategoryInfo.builtIn && !store.canEditGoalCategories) + await store.load(agentID: "nova") + #expect(store.canEditGoalCategories) + + #expect(await store.changeGoalCategories(.add(name: "Home lab", icon: "🖥️")) == nil) + #expect(store.goalCategories.map(\.id).suffix(2) == ["home-lab", "other"], "Other stays last") + #expect(await store.changeGoalCategories(.add(name: "home LAB", icon: "")) + == GoalCategoryChange.refusal("category_exists")) + #expect(await store.changeGoalCategories(.update(id: "health", name: "Fitness", icon: "")) == nil) + let health = try #require(store.goals.first { $0.category == "health" }) + #expect(health.goalCategoryInfo.name == "Fitness", "Its goals are read again under the new name") + #expect(await store.changeGoalCategories(.delete(id: "health")) == nil) + #expect(!store.goalCategories.contains { $0.id == "health" }) + #expect(store.goals.first { $0.id == health.id }?.goalCategoryInfo.isOther == true) + #expect(await store.changeGoalCategories(.delete(id: "other")) == GoalCategoryChange.refusal("category_fixed")) + } + + @Test func theComputerSendsItsCategoriesWithTheBoardAndTakesChanges() async throws { + let owner = WorkspaceOwner(authority: try .fixture(id: "categories"), authenticationGeneration: UUID(), + connectionGeneration: UUID()) + let performer = CategoryPerformer(owner: owner) + let listed: BighelpJSONValue = .array([ + .object(["id": .string("home-lab"), "name": .string("Home lab"), "icon": .string("🖥️")]), + .object(["id": .string("other"), "name": .string("Other"), "icon": .string("")]), + ]) + let client = DirectHermesAgentBoardClient(workspace: performer, owner: owner, supportsFeedback: true, + supportsGoalCategories: true) + // A plugin from before the list: nothing to edit. + _ = try await client.items(agentID: "nova") + #expect(client.goalCategories == nil) + await #expect(throws: WorkspaceClientError.unavailable(.unsupportedOperation)) { + _ = try await client.changeGoalCategories(agentID: "nova", .delete(id: "home-lab")) + } + performer.results[.boardList] = ["items": .array([]), "goalCategories": listed] + performer.results[.boardCategories] = ["goalCategories": .array([ + .object(["id": .string("other"), "name": .string("Other"), "icon": .string("")]), + ])] + _ = try await client.items(agentID: "nova") + #expect(client.goalCategories == [Self.homeLab, .other]) + let after = try await client.changeGoalCategories(agentID: "nova", .delete(id: "home-lab")) + #expect(after == [.other]) + #expect(performer.calls.last?.operation == .boardCategories) + #expect(performer.calls.last?.payload == ["agentId": .string("nova"), "action": .string("delete"), + "id": .string("home-lab")]) + #expect(DirectHermesNativePluginClient.supports(.boardCategories)) } @Test func everyCategoryStartsAChatThatNamesIt() { @@ -247,8 +349,14 @@ private final class CategoryPerformer: WorkspaceOperationPerforming { var owner: WorkspaceOwner? var capabilities: WorkspaceCapabilities { .init(owner: owner) } + var results: [WorkspaceOperation: [String: BighelpJSONValue]] = [:] + private(set) var calls: [(operation: WorkspaceOperation, payload: [String: BighelpJSONValue])] = [] + init(owner: WorkspaceOwner) { self.owner = owner } func perform(_ operation: WorkspaceOperation, payload: [String: BighelpJSONValue], owner: WorkspaceOwner) async throws - -> [String: BighelpJSONValue] { [:] } + -> [String: BighelpJSONValue] { + calls.append((operation, payload)) + return results[operation] ?? [:] + } } diff --git a/BighelpUITests/BoardSwipeBlueprintsUITests.swift b/BighelpUITests/BoardSwipeBlueprintsUITests.swift index a97d0f42..77c4f521 100644 --- a/BighelpUITests/BoardSwipeBlueprintsUITests.swift +++ b/BighelpUITests/BoardSwipeBlueprintsUITests.swift @@ -191,6 +191,83 @@ final class BoardSwipeBlueprintsUITests: BighelpUITestCase { } } + /// Goals › Edit categories: the computer's own list (the demo board stands in for it). A new + /// category joins the Create a goal list, a new name shows over its goals, and a deleted + /// category's goals move to Other. + @MainActor + func testEditCategoriesAddsRenamesAndDeletes() throws { + for appearance in ["light", "dark"] { + let app = launch(appearance: appearance) + openBoard("tab.goals", in: app) + let edit = app.buttons["board.goals.categories.edit"] + scroll(app, until: edit) + edit.tap() + let add = app.buttons["board.goals.categories.add"] + XCTAssertTrue(app.buttons["board.goals.categories.row.health"].waitForExistence(timeout: 10)) + XCTAssertFalse(app.buttons["board.goals.categories.row.other"].exists, "Other can't be opened") + save("board-goals-category-list-\(appearance)", app) + scroll(app, until: add) + add.tap() + let name = app.textFields["board.goals.categories.name"] + XCTAssertTrue(name.waitForExistence(timeout: 5)) + name.tap() + name.typeText("Garden") + save("board-goals-category-new-\(appearance)", app) + app.buttons["board.goals.categories.save"].tap() + XCTAssertTrue(app.buttons["board.goals.categories.row.garden"].waitForExistence(timeout: 10), + "The new category is on the list") + + // A name that is taken stays in the editor with the reason. + for _ in 0..<3 where !(add.exists && add.isHittable) { app.swipeUp() } + add.tap() + XCTAssertTrue(name.waitForExistence(timeout: 5)) + name.tap() + name.typeText("garden") + app.buttons["board.goals.categories.save"].tap() + XCTAssertTrue(app.staticTexts["board.goals.categories.error"].waitForExistence(timeout: 10)) + app.navigationBars.buttons.element(boundBy: 0).tap() + + // Health gets a new name, and its goals take it. + let health = app.buttons["board.goals.categories.row.health"] + for _ in 0..<3 where !(health.exists && health.isHittable) { app.swipeDown() } + health.tap() + XCTAssertTrue(name.waitForExistence(timeout: 5)) + name.tap() + name.typeText(" and fitness") + app.buttons["board.goals.categories.save"].tap() + XCTAssertTrue(health.waitForExistence(timeout: 10)) + XCTAssertTrue(health.label.contains("Health and fitness"), health.label) + + // Finance goes: its goals move to Other. + app.buttons["board.goals.categories.row.finance"].tap() + let delete = app.buttons["board.goals.categories.delete"] + XCTAssertTrue(delete.waitForExistence(timeout: 5)) + delete.tap() + // The question's button has the same words as the page's; it is the later one. + let confirm = app.buttons.matching(NSPredicate(format: "label == %@", "Delete category")) + let asked = Date().addingTimeInterval(5) + while confirm.count < 2, Date() < asked { Thread.sleep(forTimeInterval: 0.2) } + XCTAssertEqual(confirm.count, 2, "Deleting asks first") + confirm.element(boundBy: 1).tap() + XCTAssertTrue(app.buttons["board.goals.categories.row.finance"].waitForNonExistence(timeout: 10)) + app.buttons["board.goals.categories.done"].tap() + + // The page read its goals again, so the list may stand anywhere. + let created = app.buttons["board.goals.create.garden"] + scroll(app, until: created) + XCTAssertTrue(created.waitForExistence(timeout: 10), "Create a goal offers the new category") + XCTAssertFalse(app.buttons["board.goals.create.finance"].exists) + for _ in 0..<6 { app.swipeDown() } + let renamed = app.descendants(matching: .any)["board.goals.category.health"] + scroll(app, until: renamed) + XCTAssertTrue(renamed.label.contains("Health and fitness"), renamed.label) + XCTAssertFalse(app.descendants(matching: .any)["board.goals.category.finance"].exists, + "Its goals are under Other now") + save("board-goals-category-after-\(appearance)", app) + app.terminate() + } + } + /// Let's do it records the idea by its ID (the demo board stands in for the host) and opens /// the bot's chat to send the idea as a card: the ID never reaches the message box. @MainActor diff --git a/DESIGN.md b/DESIGN.md index e564f6c3..3cbe743a 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -347,6 +347,11 @@ Productivity, Other; "Nothing is being tracked yet" when empty), Done, then **Cr category with a +, which starts a chat asking the agent to plan a goal in that category (touch and hold for that category's blueprints). Goals carry the category in the plugin (`native-agent-board-goal-categories-v1`); without it every goal shows under Other and the page says to update the plugin. +The categories are the computer's own (`native-goal-categories-v1`): those seven until someone changes them. +**Edit categories**, under the Create a goal list, opens a sheet that lists them. A row opens its name and emoji, +a swipe or the editor deletes it (after a question, since its goals move to Other), and Add category makes a new +one. Other is listed, always last, and can't be changed. A category with no emoji shows its built-in symbol, or a +tag. **Projects** (Work › Projects) are Hermes projects shown the way Claude shows them: cards with the project's emoji and color, description and recent use; a project page with **New chat in this project**, its chats and its From 644d7a6d764db5115858473a7c4050304ff115d0 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:48:53 -0600 Subject: [PATCH 4/4] test(plugins): wait for the saved list itself, not for a file in its folder An atomic write puts a temporary file in the folder first. The test took that for the saved copy, opened the next launch with no copy, and then waited for a computer it holds back until its time limit. It showed when the test ran beside other suites. Co-Authored-By: Claude Fable 5.2 --- BighelpTests/PluginChangeSpeedTests.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/BighelpTests/PluginChangeSpeedTests.swift b/BighelpTests/PluginChangeSpeedTests.swift index a03666a2..669cc408 100644 --- a/BighelpTests/PluginChangeSpeedTests.swift +++ b/BighelpTests/PluginChangeSpeedTests.swift @@ -90,8 +90,10 @@ struct PluginListReadTests { let saved = CapabilitiesSavedLists(folder: folder) let host = PluginHost() await PluginLifecycleManagementModel(client: host.client(), keptCopies: CapabilitiesKeptCopies(saved: saved)).load() - // The copy is written off the main actor. - while (try? FileManager.default.contentsOfDirectory(atPath: folder.path(percentEncoded: false)))?.isEmpty != false { + // The copy is written off the main actor. Wait until it reads back: an atomic write puts a + // temporary file in the folder first, so "the folder isn't empty" came true before the copy was there. + let key = "plugins\n\(host.client().owner.cacheScopeID)" + while await saved.read(PluginSnapshot.self, key: key) == nil { try await Task.sleep(for: .milliseconds(10)) }