From 95c6fe4c585c5e04c1369faf1fd0e3e9dc4f6a19 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:41:25 -0600 Subject: [PATCH] Let's do it sends the idea as a card, and Discuss attaches posts and goals as cards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Let's do it now sends "Let's do it!" at once with the idea attached as a card in the bubble, and the idea moves to Ideas › Completed. Discuss on a Feed post, goal or idea puts the item in the message box as a card above what the person types. The card travels as a block before the message in its own text, so the agent reads all of it and a reread draws it again. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 5 + Bighelp.xcodeproj/project.pbxproj | 12 + Bighelp/App/AppState.swift | 21 +- Bighelp/App/ChatDestinationView.swift | 9 + Bighelp/App/RootAgentHome.swift | 7 + Bighelp/App/RootSimpleBots.swift | 6 +- Bighelp/Board/AgentBoard.swift | 48 +++- Bighelp/Board/AgentBoardViews.swift | 207 ++++++++++++++---- Bighelp/Board/AgentGoalsView.swift | 2 +- Bighelp/Board/BoardDashboard.swift | 10 +- Bighelp/Board/BoardDashboardViews.swift | 14 +- Bighelp/Board/FeedPostFiles.swift | 2 +- Bighelp/Chat/ChatBoardCard.swift | 125 +++++++++++ Bighelp/Chat/ChatBoardCardViews.swift | 110 ++++++++++ Bighelp/Chat/ChatComposer.swift | 38 ++-- Bighelp/Chat/ChatModel+Attachments.swift | 1 + Bighelp/Chat/ChatModel+BigFiles.swift | 1 + Bighelp/Chat/ChatModel+BotMode.swift | 2 + Bighelp/Chat/ChatModel+References.swift | 1 + Bighelp/Chat/ChatModel+StagedSends.swift | 1 + Bighelp/Chat/ChatModel+Submission.swift | 10 + Bighelp/Chat/ChatModel.swift | 19 +- Bighelp/Chat/ChatReplyQuote.swift | 20 +- Bighelp/Chat/MessageBubble.swift | 162 ++++++++------ Bighelp/Chat/MessageViews.swift | 9 +- Bighelp/Driving/DriveOverlay.swift | 4 +- Bighelp/Fixtures/DemoAgentBoardClient.swift | 6 + Bighelp/Hermes/HermesUserMessageDisplay.swift | 4 +- Bighelp/SimpleBots/SimpleBotProfileView.swift | 4 +- BighelpTests/AgentBoardTests.swift | 39 +++- BighelpTests/ChatBoardCardTests.swift | 116 ++++++++++ 31 files changed, 841 insertions(+), 174 deletions(-) create mode 100644 Bighelp/Chat/ChatBoardCard.swift create mode 100644 Bighelp/Chat/ChatBoardCardViews.swift create mode 100644 BighelpTests/ChatBoardCardTests.swift diff --git a/AGENTS.md b/AGENTS.md index 8075f0c9..9cf8ddf9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,6 +78,11 @@ change in both repos. (`showComposerText`) and taken by the chat Hermes makes (`takeComposerText`). The canvas is thrown away when that chat arrives, and its draft doesn't always get across in time: text only the canvas took was lost about every other time. + - An idea, Feed post or goal goes to a chat as a card (`ChatBoardCard`): a block before the person's + words in the message's own text, so the agent reads all of it and a reread draws it in their bubble. + 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`). - Code mode is a second home, not a second app: ☰ gets a mode switch on top and Code's places while it's the home (`AppTab.code`, `appState.homeTab`). Chat stays the out-of-box home. - The modes are Bots, Chat and Code (`BighelpMode`; `settings.switchMode`). Settings › Modes has one picker diff --git a/Bighelp.xcodeproj/project.pbxproj b/Bighelp.xcodeproj/project.pbxproj index 73791d12..f9421423 100644 --- a/Bighelp.xcodeproj/project.pbxproj +++ b/Bighelp.xcodeproj/project.pbxproj @@ -61,6 +61,7 @@ 06306AA92F9CE0D334C1033C /* WorkspaceContracts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DBEA050720EFD509842B1C6 /* WorkspaceContracts.swift */; }; 068864D988E15F2B4CA8C773 /* ChatModel+BigFiles.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DC4E597FA288CBDD2DB0319 /* ChatModel+BigFiles.swift */; }; 0696F09D9FDBD8C418B03759 /* BighelpUsageWidgetLockScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 902E06ADA277EE9D8806B818 /* BighelpUsageWidgetLockScreen.swift */; }; + 06BB7A5FB7AAF542E44FCA86 /* ChatBoardCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = CDDE2652D6BECAC1152A81D3 /* ChatBoardCard.swift */; }; 06F99F6B3D43F9DB4D62BE05 /* CompanionEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = A719EC8CA6038F1E58FCA152 /* CompanionEnvironment.swift */; }; 070CD600683A27FFFF11BC55 /* WatchPhone.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B2A93A6AF8DA5497A0408EB /* WatchPhone.swift */; }; 0713CE767A50A04AE6334BD8 /* BighelpMacUpdates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52D7663820814CF769807B82 /* BighelpMacUpdates.swift */; }; @@ -717,6 +718,7 @@ 59D953650AB3262332C459D4 /* DeviceGeofenceTool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83409EC359A93949A1A1A2CB /* DeviceGeofenceTool.swift */; }; 5A03AFA13C6289B7BB80E8E9 /* HermesToolsList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25B42C0520EEAFCC064E8825 /* HermesToolsList.swift */; }; 5A044C9061C88CA10BBD96F6 /* HermesFacePlayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = B790E89E45A355459ABFB9FB /* HermesFacePlayer.swift */; }; + 5A06094B12516F4C88133FE8 /* ChatBoardCardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5EBC42DDD3A3EF941FC8F001 /* ChatBoardCardTests.swift */; }; 5A394E6D02D5BA8702A671C1 /* BighelpRailCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3839FB429704BEC09A1DF03 /* BighelpRailCard.swift */; }; 5A5C26429791A98EBF3DF089 /* PendingShareLedger.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBEB6BA3161F76CD081422A8 /* PendingShareLedger.swift */; }; 5A5E28837861B4344C9C4451 /* ChatToolCodeCellTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 955EF8DC3E8F0CC2CFB5D6C9 /* ChatToolCodeCellTests.swift */; }; @@ -1441,6 +1443,7 @@ B114F8B6C0F6E61915A7AB01 /* ZipArchiveExtractor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 687949CFACF582DCB8685E39 /* ZipArchiveExtractor.swift */; }; B11E653400EF8354295D41EF /* BighelpUsageWidgetParts.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEC8CA83E1771ACA442E7CBA /* BighelpUsageWidgetParts.swift */; }; B1214CC75367254984FD4565 /* BighelpCardValidator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 193FB3F79D5331CD5035BE1A /* BighelpCardValidator.swift */; }; + B12EF1DA1FE757C8BEEE9FE3 /* ChatBoardCardViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A0CAEF0ED1025A8195B7486 /* ChatBoardCardViews.swift */; }; B140375ABF770C6F5215857B /* OnDeviceVoiceLiveTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18E94A655AC6FD5808D8F386 /* OnDeviceVoiceLiveTests.swift */; }; B167522D81630E6BD2577047 /* SystemPageFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 880A1627E9A029C69713613D /* SystemPageFixture.swift */; }; B1A7F7D9B87F938E77192942 /* ReferenceDeliveryAcceptanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14785604C02D2E7707B79C3F /* ReferenceDeliveryAcceptanceTests.swift */; }; @@ -2301,6 +2304,7 @@ 09FE7AF3652707DEC52C692C /* FleetStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FleetStoreTests.swift; sourceTree = ""; }; 0A044AC6EE1343EDBF6F530F /* FocusedTextEditor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FocusedTextEditor.swift; sourceTree = ""; }; 0A08E4F2667799009DAF1479 /* CredentialVault.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CredentialVault.swift; sourceTree = ""; }; + 0A0CAEF0ED1025A8195B7486 /* ChatBoardCardViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatBoardCardViews.swift; sourceTree = ""; }; 0A26DC30FABB27D7EDEBDADE /* ComposioAccount.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposioAccount.swift; sourceTree = ""; }; 0A319B9E00DA53C7BB4B58F9 /* ReferenceHistoryView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReferenceHistoryView.swift; sourceTree = ""; }; 0A3F66FAB8AF9CF45DBC1D7C /* ChatModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatModel.swift; sourceTree = ""; }; @@ -2980,6 +2984,7 @@ 5E2E69C77E0356A64595B016 /* BotBodies.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = BotBodies.json; sourceTree = ""; }; 5E3A8F019E59F4BEE6DDF45E /* HomeWorkAcceptanceFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeWorkAcceptanceFixture.swift; sourceTree = ""; }; 5E45B7FBC8B435DDF94BAF6E /* DeviceToolEnvironment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceToolEnvironment.swift; sourceTree = ""; }; + 5EBC42DDD3A3EF941FC8F001 /* ChatBoardCardTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatBoardCardTests.swift; sourceTree = ""; }; 5ECA70B7C1A6646021728982 /* VoiceModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceModelTests.swift; sourceTree = ""; }; 5ED7AA71154BB0B11EE43FE7 /* soul-muse.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = "soul-muse.md"; sourceTree = ""; }; 5EEED5396B4A5CA08D8C5836 /* BotModeRoomStore+NativeEvents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BotModeRoomStore+NativeEvents.swift"; sourceTree = ""; }; @@ -3883,6 +3888,7 @@ CD8CEE35C3DA794958BBBB9B /* DirectHermesOwnedRPC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesOwnedRPC.swift; sourceTree = ""; }; CDA65FB5CDACAC184E55451B /* DirectHermesSessionCatalogRowTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesSessionCatalogRowTests.swift; sourceTree = ""; }; CDCFBB5C4E5985D8EC6C78FD /* AgentProfileSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentProfileSheet.swift; sourceTree = ""; }; + CDDE2652D6BECAC1152A81D3 /* ChatBoardCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatBoardCard.swift; sourceTree = ""; }; CDE853A92392551EBA916C0E /* WikiNavigation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WikiNavigation.swift; sourceTree = ""; }; CE0D46B41203E5ABB073CFB3 /* DeviceToolCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceToolCoordinator.swift; sourceTree = ""; }; CE11871CC7E3CE3213E44774 /* SimpleBotsHomeSections.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimpleBotsHomeSections.swift; sourceTree = ""; }; @@ -5608,6 +5614,7 @@ FF33B10BBB5C75516E3D7032 /* ChatAttentionTests.swift */, 5839EBC64D344E43871E5958 /* ChatAttributionTests.swift */, 827FB1BAC0E8E4C2F4FFE359 /* ChatBackgroundResultTests.swift */, + 5EBC42DDD3A3EF941FC8F001 /* ChatBoardCardTests.swift */, 86E766D96E35643FF00B36D1 /* ChatBotModeIntegrationTests.swift */, C563DE2C670A96AC2D4E48B2 /* ChatCanvasGeometryTests.swift */, DC3FE4EE90C9C2ABFF8CBE6D /* ChatCardMessageProjectionTests.swift */, @@ -7088,6 +7095,8 @@ 4FB152CCFD82E237A8543E00 /* ChatBackgroundResult.swift */, C554359955749145E7E3FFEB /* ChatBackgroundResultCard.swift */, 70E27D7C36503753B5BF5C26 /* ChatBlueprintDraft.swift */, + CDDE2652D6BECAC1152A81D3 /* ChatBoardCard.swift */, + 0A0CAEF0ED1025A8195B7486 /* ChatBoardCardViews.swift */, 346E60E2A592A84C62801324 /* ChatCameraPicker.swift */, ACFD343C02B210E5028EAECA /* ChatCapabilityControlSheet.swift */, 3FD7F747650F9C1AEB8642FF /* ChatCardImageCopy.swift */, @@ -8180,6 +8189,8 @@ B6C40DC2D80992F3CD7B405A /* ChatBackgroundResultCard.swift in Sources */, DCEAA98BEEBAAD8DBE293509 /* ChatBigFile.swift in Sources */, 7CC97AB51B2E888D2F9F5B4F /* ChatBlueprintDraft.swift in Sources */, + 06BB7A5FB7AAF542E44FCA86 /* ChatBoardCard.swift in Sources */, + B12EF1DA1FE757C8BEEE9FE3 /* ChatBoardCardViews.swift in Sources */, 9C275F3044E17BFF11E7CF52 /* ChatCameraPicker.swift in Sources */, FCA9EEBC3708BFEBBBA82FE5 /* ChatCapabilityControlSheet.swift in Sources */, A72D48948B447E5C97EE084F /* ChatCardImageCopy.swift in Sources */, @@ -9329,6 +9340,7 @@ B532598FCEB85F153DA7919C /* ChatAttentionTests.swift in Sources */, 348AB2B95F565F4AE42D3649 /* ChatAttributionTests.swift in Sources */, CF95DFCDD58FBA3A83DE41D5 /* ChatBackgroundResultTests.swift in Sources */, + 5A06094B12516F4C88133FE8 /* ChatBoardCardTests.swift in Sources */, 89055BA34023126D9C86613B /* ChatBotModeIntegrationTests.swift in Sources */, A5F1CA216DBB2489904CB112 /* ChatCanvasGeometryTests.swift in Sources */, 556808D1B218893EAC7C564B /* ChatCardMessageProjectionTests.swift in Sources */, diff --git a/Bighelp/App/AppState.swift b/Bighelp/App/AppState.swift index 9ffd3788..9b6b35e2 100644 --- a/Bighelp/App/AppState.swift +++ b/Bighelp/App/AppState.swift @@ -53,6 +53,9 @@ final class AppState { var suspendedChat: SuspendedChat? /// `pendingComposerText` is a blueprint: its `[blanks]` show as chips to fill in (`ChatBlueprintDraft`). var pendingComposerFillsBlanks = false + /// `pendingComposerText` is a message to send, not a draft (Let's do it): the chat that takes + /// it sends it and leaves its message box alone. + var pendingComposerSendsAtOnce = false /// The bot whose own chat may take `pendingComposerText` even though it has history: a bot's /// Dashboard opens that bot's Bot Chat, never a new one. Only an empty message box takes it. var pendingComposerAgentID: String? @@ -266,9 +269,12 @@ final class AppState { /// Leaves text for the next chat's message box. Each request replaces the last one whole, so /// an earlier bot or blueprint never sticks to new text. Only a blueprint sets `fillsBlanks`: /// brackets in anything else (a post's title, text the person typed) are just text. - func leaveComposerText(_ text: String, fillsBlanks: Bool = false, agentID: String? = nil, now: Date = .now) { + /// `sendsAtOnce`: the chat sends the text as a message of its own (Let's do it). + func leaveComposerText(_ text: String, fillsBlanks: Bool = false, sendsAtOnce: Bool = false, + agentID: String? = nil, now: Date = .now) { pendingComposerText = text pendingComposerFillsBlanks = fillsBlanks + pendingComposerSendsAtOnce = sendsAtOnce pendingComposerShown = false pendingComposerAgentID = agentID pendingComposerSince = now @@ -278,8 +284,10 @@ final class AppState { /// The canvas is thrown away when the chat arrives and its draft doesn't always get across in /// time, so the text stays here for that chat to take. func showComposerText(now: Date = .now) -> (text: String, fillsBlanks: Bool)? { - guard pendingComposerAgentID == nil, let text = pendingComposerText, let since = pendingComposerSince, - now.timeIntervalSince(since) <= Self.pendingComposerLifetime else { return nil } + // A message to send isn't a draft: the canvas leaves it for the chat that sends it. + guard pendingComposerAgentID == nil, !pendingComposerSendsAtOnce, let text = pendingComposerText, + let since = pendingComposerSince, now.timeIntervalSince(since) <= Self.pendingComposerLifetime + else { return nil } pendingComposerShown = true return (text, pendingComposerFillsBlanks) } @@ -287,15 +295,15 @@ final class AppState { /// The text, if this chat should take it: a new chat on top, or the named bot's own chat on top. /// `wasShown`: a blank canvas already showed it, so this chat may hold it (and what the person /// changed) from the canvas's draft. - func takeComposerText(isNewChat: Bool, isNamedBotChat: Bool, - now: Date = .now) -> (text: String, fillsBlanks: Bool, wasShown: Bool)? { + func takeComposerText(isNewChat: Bool, isNamedBotChat: Bool, now: Date = .now) + -> (text: String, fillsBlanks: Bool, sendsAtOnce: Bool, wasShown: Bool)? { guard let text = pendingComposerText else { return nil } guard let since = pendingComposerSince, now.timeIntervalSince(since) <= Self.pendingComposerLifetime else { clearComposerText() return nil } guard pendingComposerAgentID == nil ? isNewChat : isNamedBotChat else { return nil } - let taken = (text, pendingComposerFillsBlanks, pendingComposerShown) + let taken = (text, pendingComposerFillsBlanks, pendingComposerSendsAtOnce, pendingComposerShown) clearComposerText() return taken } @@ -303,6 +311,7 @@ final class AppState { private func clearComposerText() { pendingComposerText = nil pendingComposerFillsBlanks = false + pendingComposerSendsAtOnce = false pendingComposerShown = false pendingComposerAgentID = nil pendingComposerSince = nil diff --git a/Bighelp/App/ChatDestinationView.swift b/Bighelp/App/ChatDestinationView.swift index 45c39ee2..9b72715f 100644 --- a/Bighelp/App/ChatDestinationView.swift +++ b/Bighelp/App/ChatDestinationView.swift @@ -727,6 +727,15 @@ struct ChatDestinationView: View { let isNamedBotChat = isOnTop && appState.pendingComposerAgentID.map { model.memberIDs == [$0] } == true guard let pending = appState.takeComposerText(isNewChat: isOnTop && model.transcriptEntries.isEmpty, isNamedBotChat: isNamedBotChat) else { return } + if pending.sendsAtOnce { + // Let's do it: a message of its own, whatever the box holds. If it can't go, it + // waits in an empty box for Send. Taking the text restarts this task, so the send + // runs on its own. + Task { [model] in + if await !model.sendFromOutside(pending.text), model.draft.isEmpty { model.draft = pending.text } + } + return + } if pending.wasShown, !model.draft.isEmpty { // It came across from the canvas, with whatever the person changed there. Its chips // came too (`prepareNewChat`), unless the text is still as the blueprint wrote it. diff --git a/Bighelp/App/RootAgentHome.swift b/Bighelp/App/RootAgentHome.swift index 9d1aed7f..012f7ff4 100644 --- a/Bighelp/App/RootAgentHome.swift +++ b/Bighelp/App/RootAgentHome.swift @@ -293,6 +293,12 @@ extension RootShellView { startNewChat(explicitAgentID: homeAgent?.id) } + /// Let's do it: a new chat with this agent, the message sent at once. + func sendToAgent(_ text: String) { + appState.leaveComposerText(text, sendsAtOnce: true) + startNewChat(explicitAgentID: homeAgent?.id) + } + /// A blueprint: a new chat with it in the message box, its blanks as chips. Nothing is sent. func useBlueprint(_ text: String) { appState.leaveComposerText(text, fillsBlanks: true) @@ -500,6 +506,7 @@ extension RootShellView { onProfile: { profileAgentID = agent.id }, onSwitchAgent: { isAgentSwitcherPresented = true }, onAsk: askAgent, + onSend: sendToAgent, onBlueprint: useBlueprint, onMenu: { isHomeDrawerPresented.toggle() }, onNewChat: { startHomeChat(with: agent.id) }, diff --git a/Bighelp/App/RootSimpleBots.swift b/Bighelp/App/RootSimpleBots.swift index 8f5c46d0..2a32ce51 100644 --- a/Bighelp/App/RootSimpleBots.swift +++ b/Bighelp/App/RootSimpleBots.swift @@ -358,6 +358,7 @@ extension RootShellView { shellBoardKey: { agentBoardClientKey }, configureShellBoard: { await configureAgentBoard($0) }, onAsk: { id, text in askSimpleBot(id, text, fillsBlanks: false) }, + onSend: { id, text in askSimpleBot(id, text, fillsBlanks: false, sendsAtOnce: true) }, onBlueprint: { id, text in askSimpleBot(id, text, fillsBlanks: true) }) ) } @@ -381,8 +382,9 @@ extension RootShellView { /// The bot's own chat with the text in its message box (a Dashboard's Ask, Do it or template). /// It's the Bot Chat, history and all; only an empty message box takes the text. - func askSimpleBot(_ agentID: String, _ text: String, fillsBlanks: Bool) { - appState.leaveComposerText(text, fillsBlanks: fillsBlanks, agentID: agentID) + /// `sendsAtOnce`: Let's do it sends the text there instead, and the box stays as it was. + func askSimpleBot(_ agentID: String, _ text: String, fillsBlanks: Bool, sendsAtOnce: Bool = false) { + appState.leaveComposerText(text, fillsBlanks: fillsBlanks, sendsAtOnce: sendsAtOnce, agentID: agentID) openSimpleBotChat(agentID) } diff --git a/Bighelp/Board/AgentBoard.swift b/Bighelp/Board/AgentBoard.swift index 61d2426d..347b0f80 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 + /// 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. + var answeredAt: Date? var createdAt: Date var updatedAt: Date @@ -185,6 +189,8 @@ struct AgentBoardItem: Identifiable, Equatable, Sendable { var goalCategory: GoalCategory? { GoalCategory(stored: category) ?? (category.isEmpty ? GoalCategory.inferred(from: title, body, note) : nil) } + /// Let's do it was said to this idea (the plugin's `answer`); it shows under Completed. + var isCompleted: Bool { kind == .idea && answer == "yes" } var liked: Bool { rating == .up } var isDone: Bool { status == "done" } @@ -195,11 +201,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 = "", createdAt: Date = .now, updatedAt: Date? = nil) { + dismissed: Bool = false, category: 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.answer = answer; self.answeredAt = answeredAt self.createdAt = createdAt; self.updatedAt = updatedAt ?? createdAt } @@ -237,6 +245,8 @@ struct AgentBoardItem: Identifiable, Equatable, Sendable { reason: object["reason"]?.string ?? "", read: object["read"]?.boolean ?? true, dismissed: object["dismissed"]?.boolean ?? false, category: object["category"]?.string ?? "", + answer: object["answer"]?.string ?? "none", + answeredAt: (object["answeredAt"]?.integer).flatMap { $0 > 0 ? date("answeredAt") : nil }, createdAt: date("createdAt"), updatedAt: date("updatedAt")) } } @@ -484,10 +494,9 @@ struct AgentIdentityDocuments: Equatable, Sendable { } extension AgentBoardItem { - /// What Let's do it puts in the chat: the idea's title only. The host learns which idea from - /// `AgentBoardStore.accept`, so its ID never shows in the message box, the sent message or - /// the chat's history. Older plugins match this exact text to record the yes. - var letsDoItMessage: String { "Yes, go ahead with this idea: “\(title)”." } + /// What Let's do it sends: "Let's do it!" with the idea attached as a card. The host learns + /// which idea from `AgentBoardStore.accept`, so its ID never shows in the chat. + var letsDoItMessage: String { chatCard.prefixing("Let's do it!") } } // MARK: - Clients @@ -771,7 +780,13 @@ final class AgentBoardStore { /// Just deleted, for Undo. private(set) var recentlyHidden: AgentBoardItem? var feed: [AgentBoardItem] { items.filter { $0.kind == .feed && !$0.dismissed } } - var ideas: [AgentBoardItem] { items.filter { $0.kind == .idea && !$0.dismissed } } + /// Ideas still waiting for an answer. Ones the person said Let's do it to are `completedIdeas`. + var ideas: [AgentBoardItem] { items.filter { $0.kind == .idea && !$0.dismissed && !$0.isCompleted } } + /// Ideas the person said Let's do it to, newest yes first. + var completedIdeas: [AgentBoardItem] { + items.filter { $0.isCompleted && !$0.dismissed } + .sorted { ($0.answeredAt ?? $0.updatedAt) > ($1.answeredAt ?? $1.updatedAt) } + } var goals: [AgentBoardItem] { items.filter { $0.kind == .goal && !$0.dismissed } } /// A new client (host, account or plugin change) drops everything shown so far. @@ -981,9 +996,12 @@ final class AgentBoardStore { } /// Let's do it: tells the host which idea by its ID, before the chat opens. The ID goes - /// only here, never into the chat (`letsDoItMessage`). The idea stays on the board. - func accept(_ idea: AgentBoardItem) async -> AcceptOutcome { - guard let client, client.supportsAnswers else { return .notSupported } + /// only here, never into the chat (`letsDoItMessage`). The idea moves to Completed. + func accept(_ idea: AgentBoardItem, now: Date = .now) async -> AcceptOutcome { + guard let client, client.supportsAnswers else { + complete(idea.id, at: now) + return .notSupported + } guard idea.kind == .idea, let agentID, items.contains(where: { $0.id == idea.id && $0.kind == .idea }) else { return .failed } @@ -991,14 +1009,24 @@ final class AgentBoardStore { do { try await client.accept(agentID: agentID, itemID: idea.id) // A yes recorded by a connection that's gone may belong to another computer. - return generation == self.generation ? .recorded : .failed + guard generation == self.generation else { return .failed } + complete(idea.id, at: now) + return .recorded } catch WorkspaceClientError.unavailable(.unsupportedOperation) { + complete(idea.id, at: now) return .notSupported } catch { return .failed } } + /// Shows the idea under Completed at once, as the host now has it. + private func complete(_ id: String, at now: Date) { + guard let index = items.firstIndex(where: { $0.id == id && $0.kind == .idea }) else { return } + items[index].answer = "yes" + items[index].answeredAt = now + } + 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/AgentBoardViews.swift b/Bighelp/Board/AgentBoardViews.swift index cee80966..939cab55 100644 --- a/Bighelp/Board/AgentBoardViews.swift +++ b/Bighelp/Board/AgentBoardViews.swift @@ -13,6 +13,8 @@ struct AgentBoardContext { let onSwitchAgent: () -> Void /// Opens a chat with this agent with the text in its message box. let onAsk: (String) -> Void + /// Opens a chat with this agent and sends the text there (Let's do it). + let onSend: (String) -> Void /// Opens a chat with this agent with a blueprint in its message box, its blanks as chips. let onBlueprint: (String) -> Void /// The Chat tab's header controls, so every board has ☰, New chat and ⋯ too. @@ -194,10 +196,10 @@ enum BoardItemMenu { } } } - Button("Discuss", systemImage: "bubble.left") { context.onAsk("About “\(item.title)”: ") } + Button("Discuss", systemImage: "bubble.left") { context.onAsk(item.chatCard.block) } case .idea: Button("Start a chat about this", systemImage: "bubble.left") { - context.onAsk("About your idea “\(item.title)”: ") + context.onAsk(item.chatCard.block) } if store.supportsFeedback { Button("Turn into a goal", systemImage: "target") { Task { await store.promote(item) } } @@ -207,7 +209,7 @@ enum BoardItemMenu { systemImage: item.isDone ? "arrow.uturn.backward" : "checkmark") { Task { await store.setDone(item, !item.isDone) } } - Button("Discuss", systemImage: "bubble.left") { context.onAsk("About my goal “\(item.title)”: ") } + Button("Discuss", systemImage: "bubble.left") { context.onAsk(item.chatCard.block) } } if store.supportsFeedback { Button(item.read ? "Mark as unread" : "Mark as read", @@ -831,11 +833,15 @@ struct BoardPictureView: View { // MARK: - Ideas /// Ideas: chips for its sections, then a bento of pastel tiles. The newest idea is the tall one -/// with Let's do it; a tap on any idea opens it (`IdeaDetailSheet`). +/// with Let's do it; a tap on any idea opens it (`IdeaDetailSheet`). Ideas the person said Let's +/// do it to are listed under Completed at the end. struct AgentIdeasView: View { let context: AgentBoardContext @State private var selected: AgentBoardItem? @State private var showsBlueprints = false + @State private var hidesCompleted = false + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @BighelpThemeReader private var theme /// The chosen section chip; nil is All. @State private var section: String? @Environment(\.dynamicTypeSize) private var dynamicTypeSize @@ -894,6 +900,7 @@ struct AgentIdeasView: View { IdeaTile(idea: idea, context: context) { selected = idea } } } + completed(store.completedIdeas) } .boardBlueprints(isPresented: $showsBlueprints, kind: .idea, context: context) .bighelpSheet(item: $selected) { idea in @@ -904,6 +911,41 @@ struct AgentIdeasView: View { } } + /// "Completed · 2", then a card with a row for each, newest yes first. The heading folds it. + @ViewBuilder + private func completed(_ ideas: [AgentBoardItem]) -> some View { + if !ideas.isEmpty { + Button { + withAnimation(reduceMotion ? nil : .snappy) { hidesCompleted.toggle() } + } label: { + HStack(spacing: BighelpTokens.space8) { + Text("Completed · \(ideas.count)") + .font(.bighelp(.subheadline, weight: .semibold)) + Spacer(minLength: 0) + Image(systemName: hidesCompleted ? "chevron.right" : "chevron.down") + .font(.bighelp(.footnote, weight: .semibold)) + .accessibilityHidden(true) + } + .foregroundStyle(theme.secondaryText) + .frame(minHeight: BighelpTokens.hitTarget) + .contentShape(.rect) + } + .bighelpPlainButtonStyle() + .accessibilityAddTraits(.isHeader) + .accessibilityValue(hidesCompleted ? "Hidden" : "Shown") + .accessibilityIdentifier("board.ideas.completed") + .boardRow(top: BighelpTokens.space12, bottom: BighelpTokens.space4) + if !hidesCompleted { + ForEach(ideas) { idea in + CompletedIdeaRow(idea: idea) { selected = idea } + .boardCardSegment(isFirst: idea.id == ideas.first?.id, isLast: idea.id == ideas.last?.id, + separatorInset: CompletedIdeaRow.textInset) + .boardItemSwipe(idea, store: context.store) + } + } + } + } + private func chips(_ sections: [String], chosen: String?) -> some View { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: BighelpTokens.space8) { @@ -936,6 +978,62 @@ struct AgentIdeasView: View { } } +/// An idea the person said Let's do it to: a check, its title and when. A tap opens it. +private struct CompletedIdeaRow: View { + let idea: AgentBoardItem + let onOpen: () -> Void + + /// Where the row's text starts, for the hairline between rows. + static let textInset = BighelpTokens.space16 + 28 + BighelpTokens.space12 + + var body: some View { + Button(action: onOpen) { + HStack(spacing: BighelpTokens.space12) { + Image(systemName: "checkmark") + .font(.system(size: 13, weight: .bold)) + .foregroundStyle(.white) + .frame(width: 28, height: 28) + .background(theme.success, in: .circle) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 1) { + Text(idea.title) + .font(.bighelp(.subheadline, weight: .semibold)) + .foregroundStyle(theme.primaryText) + .multilineTextAlignment(.leading) + Text(IdeaCompletion.label(idea.answeredAt)) + .font(.bighelp(.footnote)) + .foregroundStyle(theme.secondaryText) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + .padding(.horizontal, BighelpTokens.space16) + .padding(.vertical, BighelpTokens.space12) + .frame(minHeight: BighelpTokens.hitTarget) + .contentShape(.rect) + } + .bighelpPlainButtonStyle() + .accessibilityElement(children: .combine) + .accessibilityHint("Opens the idea") + .accessibilityIdentifier("board.ideas.completed.\(idea.id)") + } + + @BighelpThemeReader private var theme +} + +/// "Started today", "Started Monday": when the person said Let's do it. +enum IdeaCompletion { + static func label(_ date: Date?, now: Date = .now, calendar: Calendar = .current) -> String { + guard let date else { return String(localized: "Completed") } + if calendar.isDateInToday(date) { return String(localized: "Started today") } + if calendar.isDateInYesterday(date) { return String(localized: "Started yesterday") } + let days = calendar.dateComponents([.day], from: calendar.startOfDay(for: date), + to: calendar.startOfDay(for: now)).day ?? .max + let day = days < 7 ? date.formatted(.dateTime.weekday(.wide)) + : date.formatted(.dateTime.month(.abbreviated).day()) + return String(localized: "Started \(day)") + } +} + /// An idea's words without Markdown's symbols, like a message preview. @MainActor private func ideaPreview(_ idea: AgentBoardItem) -> String { @@ -1040,7 +1138,7 @@ private struct IdeaHeroTile: View { isAccepting = false guard outcome != .failed else { acceptFailed = true; return } acceptFailed = false - context.onAsk(idea.letsDoItMessage) + context.onSend(idea.letsDoItMessage) } } @@ -1124,50 +1222,21 @@ struct IdeaDetailSheet: View { .foregroundStyle(theme.primaryText) .tint(theme.action) VStack(spacing: BighelpTokens.space8) { - Button { - Task { await letsDoIt() } - } label: { - Group { - if isAccepting { - BighelpNoodleView(motion: .loader, size: 20, tint: theme.actionForeground) - } else { - Text(acceptFailed ? "Try again" : "Let's do it") - } - } - .font(.bighelp(.body).weight(.semibold)) - .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget) - } - .bighelpProminentButtonStyle() - .buttonBorderShape(.capsule) - .tint(theme.action) - .foregroundStyle(theme.actionForeground) - .disabled(isAccepting) - .accessibilityIdentifier("board.idea.accept") - if acceptFailed { - Text("Couldn't tell \(context.agentName) yet. Check the connection and try again.") - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - .multilineTextAlignment(.center) - .accessibilityIdentifier("board.idea.accept.failed") - } - if context.store.supportsFeedback { - Button { - dismiss() - Task { await context.store.promote(idea) } - } label: { - Label("Make it a goal", systemImage: "target") - .font(.bighelp(.body).weight(.semibold)) - .foregroundStyle(theme.primaryText) - .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget) - } - .buttonStyle(.plain) - .accessibilityIdentifier("board.idea.promote") + if idea.isCompleted { + // Said yes to already: the chat has it. + Label(IdeaCompletion.label(idea.answeredAt), systemImage: "checkmark.circle.fill") + .font(.bighelp(.body).weight(.semibold)) + .foregroundStyle(theme.success) + .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget) + .accessibilityIdentifier("board.idea.completed") + } else { + acceptButtons } Button { dismiss() Task { await context.store.hide(idea) } } label: { - Text("Not now") + Text(idea.isCompleted ? "Remove" : "Not now") .font(.bighelp(.body).weight(.semibold)) .foregroundStyle(theme.secondaryText) .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget) @@ -1199,15 +1268,59 @@ struct IdeaDetailSheet: View { #endif } - /// The yes is recorded when the person taps, by the idea's ID; the chat that opens - /// gets only the readable text. Older plugins skip straight to the chat, as before. + /// Let's do it, and Make it a goal. + @ViewBuilder + private var acceptButtons: some View { + Button { + Task { await letsDoIt() } + } label: { + Group { + if isAccepting { + BighelpNoodleView(motion: .loader, size: 20, tint: theme.actionForeground) + } else { + Text(acceptFailed ? "Try again" : "Let's do it") + } + } + .font(.bighelp(.body).weight(.semibold)) + .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget) + } + .bighelpProminentButtonStyle() + .buttonBorderShape(.capsule) + .tint(theme.action) + .foregroundStyle(theme.actionForeground) + .disabled(isAccepting) + .accessibilityIdentifier("board.idea.accept") + if acceptFailed { + Text("Couldn't tell \(context.agentName) yet. Check the connection and try again.") + .font(.bighelp(.footnote)) + .foregroundStyle(theme.secondaryText) + .multilineTextAlignment(.center) + .accessibilityIdentifier("board.idea.accept.failed") + } + if context.store.supportsFeedback { + Button { + dismiss() + Task { await context.store.promote(idea) } + } label: { + Label("Make it a goal", systemImage: "target") + .font(.bighelp(.body).weight(.semibold)) + .foregroundStyle(theme.primaryText) + .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget) + } + .buttonStyle(.plain) + .accessibilityIdentifier("board.idea.promote") + } + } + + /// The yes is recorded when the person taps, by the idea's ID; then "Let's do it!" goes to + /// the chat with the idea as a card. Older plugins skip straight to the chat, as before. private func letsDoIt() async { isAccepting = true let outcome = await context.store.accept(idea) isAccepting = false guard outcome != .failed else { acceptFailed = true; return } dismiss() - context.onAsk(idea.letsDoItMessage) + context.onSend(idea.letsDoItMessage) } @BighelpThemeReader private var theme diff --git a/Bighelp/Board/AgentGoalsView.swift b/Bighelp/Board/AgentGoalsView.swift index 720b1cf3..403ae03a 100644 --- a/Bighelp/Board/AgentGoalsView.swift +++ b/Bighelp/Board/AgentGoalsView.swift @@ -359,7 +359,7 @@ private struct GoalMoreMenu: View { var body: some View { Menu { - Button("Discuss", systemImage: "bubble.left") { context.onAsk("About my goal “\(goal.title)”: ") } + Button("Discuss", systemImage: "bubble.left") { context.onAsk(goal.chatCard.block) } Button(goal.isDone ? "Mark not done" : "Mark done", systemImage: "checkmark") { Task { await context.store.setDone(goal, !goal.isDone) } } diff --git a/Bighelp/Board/BoardDashboard.swift b/Bighelp/Board/BoardDashboard.swift index da5ccc95..10a31fc9 100644 --- a/Bighelp/Board/BoardDashboard.swift +++ b/Bighelp/Board/BoardDashboard.swift @@ -33,11 +33,12 @@ enum DashboardSwipe { /// What a swipe on a Dashboard card does. Right acts on the card, left puts it away. enum DashboardCardAction: Equatable, Sendable { - /// Feed, right: the bot's chat with the post in the message box. Nothing is sent. + /// Feed, right: the bot's chat with the post as a card in the message box. Nothing is sent. case ask /// Feed, left: the post's Clear (the host's dismiss), with Undo. case clear - /// Ideas, right: Let's do it. The host records the yes, the chat opens with it in the box. + /// Ideas, right: Let's do it. The host records the yes, and "Let's do it!" goes to the chat + /// with the idea as a card. case doIt /// Ideas, left: the idea's Not now (the host's dismiss; the plugin remembers it), with Undo. case notNow @@ -78,7 +79,7 @@ enum DashboardCardAction: Equatable, Sendable { /// A short second line on the stamp, for the one swipe that leaves the page. var detail: String? { switch self { - // Let's do it opens the chat with the yes in the box; the stamp says where it goes. + // Let's do it sends the yes to the chat; the stamp says where it goes. case .doIt: String(localized: "To chat") default: nil } @@ -127,7 +128,8 @@ enum DashboardPiles { /// bot touched last first. Put away for now (`hidden`: snoozed goals, cards taken to the /// chat) are left out. static func cards(_ kind: AgentBoardItem.Kind, items: [AgentBoardItem], hidden: Set) -> [AgentBoardItem] { - let shown = items.filter { $0.kind == kind && !$0.dismissed && !hidden.contains($0.id) } + // An idea already said yes to waits under Completed, not on the pile. + let shown = items.filter { $0.kind == kind && !$0.dismissed && !$0.isCompleted && !hidden.contains($0.id) } switch kind { case .feed, .idea: return shown.sorted { $0.createdAt > $1.createdAt } diff --git a/Bighelp/Board/BoardDashboardViews.swift b/Bighelp/Board/BoardDashboardViews.swift index 346f0d26..1f33e218 100644 --- a/Bighelp/Board/BoardDashboardViews.swift +++ b/Bighelp/Board/BoardDashboardViews.swift @@ -98,19 +98,20 @@ final class BoardDashboardModel { /// A swipe (or its VoiceOver action, or the menu's) on a card. func swipe(_ item: AgentBoardItem, _ direction: DashboardSwipeDirection, botName: String, - onAsk: @escaping (String) -> Void) { + onAsk: @escaping (String) -> Void, onSend: @escaping (String) -> Void) { let action = DashboardCardAction.action(for: item.kind, direction) let message = action.undoMessage(for: item.title, botName: botName) switch action { case .ask: takenToChat.insert(item.id) undo = Undo(item: item, message: message, revert: .putBack) - onAsk("About “\(item.title)”: ") + onAsk(item.chatCard.block) case .clear, .notNow: undo = Undo(item: item, message: message, revert: .unhide) run(item) { await $0.store.dismiss(item) } case .doIt: - // Let's do it, as on Ideas: the host records the yes by the idea's ID before the chat opens. + // Let's do it, as on Ideas: the host records the yes by the idea's ID, then the chat + // gets "Let's do it!" with the idea. Sent, it can't be undone; the idea is Completed. inFlight.insert(item.id) Task { [weak self] in guard let self else { return } @@ -122,8 +123,8 @@ final class BoardDashboardModel { } guard isShown else { return } takenToChat.insert(item.id) - undo = Undo(item: item, message: message, revert: .putBack) - onAsk(item.letsDoItMessage) + undo = Undo(item: item, message: message, revert: nil) + onSend(item.letsDoItMessage) } case .markDone: undo = Undo(item: item, message: message, revert: .unmarkDone) @@ -407,6 +408,7 @@ struct BoardDashboardView: View { activity: context.activity, store: context.store, onProfile: { model.sheet = nil }, onSwitchAgent: {}, onAsk: { text in after { context.onAsk(text) } }, + onSend: { text in after { context.onSend(text) } }, onBlueprint: { text in after { context.onBlueprint(text) } }, onMenu: {}, onNewChat: { after { context.onNewChat() } }, onPickAgents: {}, tools: [], onBack: { model.sheet = nil }) @@ -512,7 +514,7 @@ private struct DashboardSection: View { let right = DashboardCardAction.action(for: kind, .right) let left = DashboardCardAction.action(for: kind, .left) let swipe: (DashboardSwipeDirection) -> Void = { direction in - model.swipe(item, direction, botName: context.agentName, onAsk: context.onAsk) + model.swipe(item, direction, botName: context.agentName, onAsk: context.onAsk, onSend: context.onSend) } return DashboardSwipeCard( right: right.stamp(botName: context.agentName), left: left.stamp(botName: context.agentName), diff --git a/Bighelp/Board/FeedPostFiles.swift b/Bighelp/Board/FeedPostFiles.swift index b7746a9b..e8b75e14 100644 --- a/Bighelp/Board/FeedPostFiles.swift +++ b/Bighelp/Board/FeedPostFiles.swift @@ -299,7 +299,7 @@ struct FeedPostDetailSheet: View { } Button { dismiss() - context.onAsk("About “\(item.title)”: ") + context.onAsk(item.chatCard.block) } label: { Label("Discuss", systemImage: "bubble.left") .font(.bighelp(.body).weight(.semibold)) diff --git a/Bighelp/Chat/ChatBoardCard.swift b/Bighelp/Chat/ChatBoardCard.swift new file mode 100644 index 00000000..c9516f46 --- /dev/null +++ b/Bighelp/Chat/ChatBoardCard.swift @@ -0,0 +1,125 @@ +import Foundation + +/// An idea, Feed post or goal attached to a message: Let's do it sends "Let's do it!" with the +/// idea, and Discuss puts the post or goal in the message box above what the person types. +/// +/// Like a reply (`ChatReplyQuote`), it travels in the message's own text, so the agent reads +/// all of it and a reloaded chat still draws the card: +/// +/// [Idea (Home): "Start a Sunday meal plan"] +/// Each Sunday I draft five dinners… +/// [End of idea] +/// +/// Let's do it! +/// +/// The block comes first, then a blank line, then the person's words. +struct ChatBoardCard: Equatable, Sendable { + enum Kind: String, CaseIterable, Sendable { + case idea = "Idea" + case feedPost = "Feed post" + case goal = "Goal" + + var closer: String { "[End of \(rawValue.lowercased())]" } + + var systemImage: String { + switch self { + case .idea: "lightbulb" + case .feedPost: "dot.radiowaves.up.forward" + case .goal: "target" + } + } + } + + static let maximumTitleLength = 200 + static let maximumDetailLength = 60 + /// The whole message still goes as one card reply (`ChatOutgoingMessage.maximumCardReplyBytes`). + static let maximumBodyBytes = 6_000 + + let kind: Kind + /// One line. + let title: String + /// Where it's filed: an idea's section, a goal's category. One line, may be empty. + let detail: String + /// The item's own text, as written. + let body: String + + init(kind: Kind, title: String, detail: String = "", body: String) { + self.kind = kind + self.title = Self.line(title, limit: Self.maximumTitleLength) + self.detail = Self.line(detail.filter { !"[]():\"".contains($0) }, limit: Self.maximumDetailLength) + self.body = Self.bounded(body.trimmingCharacters(in: .whitespacesAndNewlines) + // The body can't end the block early. + .replacingOccurrences(of: kind.closer, with: "(End of \(kind.rawValue.lowercased()))")) + } + + /// The block the agent reads. + var block: String { + let label = detail.isEmpty ? kind.rawValue : "\(kind.rawValue) (\(detail))" + let opener = "[\(label): \"\(title)\"]" + return body.isEmpty ? opener + "\n" + kind.closer : opener + "\n" + body + "\n" + kind.closer + } + + /// The text sent: the block, a blank line, then the message. + func prefixing(_ message: String) -> String { + message.isEmpty ? block : block + "\n\n" + message + } + + /// Reads a card back from a message's text. Nil when the text doesn't start with one. + static func split(_ text: String) -> (card: ChatBoardCard, body: String)? { + let source = text.drop(while: \.isNewline) + guard source.first == "[" else { return nil } + let lineEnd = source.firstIndex(where: \.isNewline) ?? source.endIndex + let line = source[.. String { + let line = text.split(whereSeparator: \.isWhitespace).joined(separator: " ") + guard line.count > limit else { return line } + return String(line.prefix(limit)).trimmingCharacters(in: .whitespaces) + "…" + } + + private static func bounded(_ text: String) -> String { + guard text.utf8.count > maximumBodyBytes else { return text } + var kept = Substring(text) + while kept.utf8.count > maximumBodyBytes - 3 { kept = kept.dropLast(max(1, (kept.utf8.count - maximumBodyBytes) / 4)) } + return kept.trimmingCharacters(in: .whitespacesAndNewlines) + "…" + } +} + +extension AgentBoardItem { + /// This item as a card on a message. + var chatCard: ChatBoardCard { + switch kind { + case .idea: + ChatBoardCard(kind: .idea, title: title, detail: section, body: body) + case .feed: + ChatBoardCard(kind: .feedPost, title: title, detail: source, body: body) + case .goal: + ChatBoardCard(kind: .goal, title: title, + detail: goalCategory.map { $0 == .other ? "" : $0.groupTitle } ?? "", + body: [body, note.isEmpty ? "" : "Latest: \(note)"].filter { !$0.isEmpty }.joined(separator: "\n\n")) + } + } +} diff --git a/Bighelp/Chat/ChatBoardCardViews.swift b/Bighelp/Chat/ChatBoardCardViews.swift new file mode 100644 index 00000000..7a7312c0 --- /dev/null +++ b/Bighelp/Chat/ChatBoardCardViews.swift @@ -0,0 +1,110 @@ +import SwiftUI + +extension ChatBoardCard { + /// The same pastel the item has on its page: an idea's section, a post's source, a goal's + /// category. + var blockColor: BighelpBlockColor { + BighelpBlockColor.pastel(for: detail.isEmpty ? title : detail.lowercased()) + } + + /// "Idea · Home", "Goal". + var label: String { + let kind = switch kind { + case .idea: String(localized: "Idea") + case .feedPost: String(localized: "Feed post") + case .goal: String(localized: "Goal") + } + return detail.isEmpty ? kind : "\(kind) · \(detail)" + } +} + +/// The idea, post or goal a sent message carries, inside the person's bubble above their words. +struct ChatBoardCardView: View { + let card: ChatBoardCard + + @BighelpThemeReader private var theme + + var body: some View { + let block = card.blockColor + VStack(alignment: .leading, spacing: BighelpTokens.space4) { + HStack(spacing: BighelpTokens.space8) { + Image(systemName: card.kind.systemImage) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(block.ink) + .frame(width: 24, height: 24) + .background(block.fill(dark: theme.isDarkPalette), + in: RoundedRectangle(cornerRadius: 7, style: .continuous)) + .accessibilityHidden(true) + Text(card.label) + .font(.bighelp(.caption, weight: .semibold)) + .foregroundStyle(theme.secondaryText) + .lineLimit(1) + } + Text(card.title) + .font(.bighelp(.body, weight: .bold)) + .foregroundStyle(theme.primaryText) + .fixedSize(horizontal: false, vertical: true) + if !card.body.isEmpty { + // One paragraph, as the Ideas tiles show it. + Text(MarkdownDocument(card.body).visiblePlainText + .split(whereSeparator: \.isNewline).joined(separator: " ")) + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + .lineLimit(4) + } + } + .padding(.horizontal, BighelpTokens.space12) + .padding(.vertical, BighelpTokens.space12) + .frame(maxWidth: .infinity, alignment: .leading) + // After dark the page's own black sets it apart from the bubble around it. + .background(theme.isDarkPalette ? theme.canvas : theme.raisedSurface, + in: RoundedRectangle(cornerRadius: 16, style: .continuous)) + .accessibilityElement(children: .combine) + .accessibilityIdentifier("chat.board-card") + } +} + +/// The idea, post or goal the draft is about, inside the message box above the text. ✕ takes +/// it off; the text stays. +struct ChatBoardCardDraftView: View { + let card: ChatBoardCard + let onRemove: () -> Void + + @BighelpThemeReader private var theme + + var body: some View { + let block = card.blockColor + HStack(spacing: BighelpTokens.space8) { + Image(systemName: card.kind.systemImage) + .font(.bighelp(.footnote).weight(.semibold)) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 0) { + Text(card.label) + .font(.bighelp(.caption2, weight: .semibold)) + .opacity(0.75) + Text(card.title) + .font(.bighelp(.subheadline, weight: .semibold)) + } + .lineLimit(1) + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityElement(children: .combine) + .accessibilityIdentifier("chat.board-card-draft.title") + Button(action: onRemove) { + Image(systemName: "xmark") + .font(.bighelp(.caption).weight(.bold)) + .frame(width: 26, height: 26) + .background(block.ink.opacity(0.12), in: .circle) + .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) + .contentShape(.rect) + } + .bighelpPlainButtonStyle(.circle) + .bighelpIconLabel(String(localized: "Remove \(card.title)")) + .accessibilityIdentifier("chat.board-card-draft.remove") + } + .foregroundStyle(block.ink) + .padding(.leading, BighelpTokens.space12) + .background(block.fill(dark: theme.isDarkPalette), in: RoundedRectangle(cornerRadius: 18, style: .continuous)) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("chat.board-card-draft") + } +} diff --git a/Bighelp/Chat/ChatComposer.swift b/Bighelp/Chat/ChatComposer.swift index 77417092..fc5b5710 100644 --- a/Bighelp/Chat/ChatComposer.swift +++ b/Bighelp/Chat/ChatComposer.swift @@ -204,6 +204,7 @@ struct ChatComposer: View, Equatable { .animation(reduceMotion ? nil : .easeInOut(duration: BighelpTokens.stateDuration), value: model.sessionContext) .animation(reduceMotion ? nil : .snappy(duration: BighelpTokens.stateDuration), value: model.compaction) .animation(reduceMotion ? nil : .easeInOut(duration: BighelpTokens.stateDuration), value: model.replyDraft) + .animation(reduceMotion ? nil : .easeInOut(duration: BighelpTokens.stateDuration), value: model.boardCardDraft) .modifier(ChatConnectionGrace(model: model)) .onChange(of: model.taskDrawer) { _, tasks in if tasks == nil, presentedStatus == .tasks { @@ -389,19 +390,30 @@ struct ChatComposer: View, Equatable { // undo state, keyboard ownership, and the exact draft owner. HStack(alignment: .center, spacing: BighelpTokens.space8) { attachmentButton - // Voice mode, Send and Stop sit inside the box, at its bottom as the draft grows. - HStack(alignment: .bottom, spacing: BighelpTokens.space4) { - composerInput - .bighelpFont(.body) - .foregroundStyle(theme.primaryText) - .frame(maxWidth: .infinity, alignment: .leading) - .frame(height: usesCompactEditingLayout ? max(44, compactDraftLineHeight) : nil) - .frame(minHeight: BighelpTokens.hitTarget) - .submitLabel(.send) - .disabled(model.isComposerInputDisabled) - .onSubmit { send() } - ComposerModelChip(model: model).equatable() - primaryAction + // An idea, post or goal the draft is about sits in the box above the text. The text + // row keeps its place in the column whether or not one shows, so the editor stays. + VStack(spacing: BighelpTokens.space4) { + if let card = model.boardCardDraft { + ChatBoardCardDraftView(card: card) { model.boardCardDraft = nil } + // The box's own padding is for the text; the card reaches nearer its edge. + .padding(.leading, BighelpTokens.space4 - ComposerFieldMetrics.leadingInset) + .padding(.top, BighelpTokens.space4) + .transition(.opacity) + } + // Voice mode, Send and Stop sit inside the box, at its bottom as the draft grows. + HStack(alignment: .bottom, spacing: BighelpTokens.space4) { + composerInput + .bighelpFont(.body) + .foregroundStyle(theme.primaryText) + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: usesCompactEditingLayout ? max(44, compactDraftLineHeight) : nil) + .frame(minHeight: BighelpTokens.hitTarget) + .submitLabel(.send) + .disabled(model.isComposerInputDisabled) + .onSubmit { send() } + ComposerModelChip(model: model).equatable() + primaryAction + } } // iMessage-style field: a fixed-radius continuous shape reads as a // pill on one line and keeps square-ish corners as the draft grows, diff --git a/Bighelp/Chat/ChatModel+Attachments.swift b/Bighelp/Chat/ChatModel+Attachments.swift index 3fcca2a1..bf55d1ef 100644 --- a/Bighelp/Chat/ChatModel+Attachments.swift +++ b/Bighelp/Chat/ChatModel+Attachments.swift @@ -291,6 +291,7 @@ extension ChatModel { orderedDraftAttachments == orderedAttachments { draft = "" replyDraft = nil + boardCardDraft = nil draftAttachments = [] orderedDraftAttachments = [] } diff --git a/Bighelp/Chat/ChatModel+BigFiles.swift b/Bighelp/Chat/ChatModel+BigFiles.swift index cb556cbf..18e71f7f 100644 --- a/Bighelp/Chat/ChatModel+BigFiles.swift +++ b/Bighelp/Chat/ChatModel+BigFiles.swift @@ -48,6 +48,7 @@ extension ChatModel { sharesLeaveBox(as: human.id, message: message, attachments: orderedAttachments) draft = "" replyDraft = nil + boardCardDraft = nil draftAttachments = [] orderedDraftAttachments = [] } diff --git a/Bighelp/Chat/ChatModel+BotMode.swift b/Bighelp/Chat/ChatModel+BotMode.swift index 81ceaa99..3de20689 100644 --- a/Bighelp/Chat/ChatModel+BotMode.swift +++ b/Bighelp/Chat/ChatModel+BotMode.swift @@ -59,6 +59,7 @@ extension ChatModel { } draft = "" replyDraft = nil + boardCardDraft = nil failureMessage = nil let outgoing = beginBotModeOutgoing(message) do { @@ -958,6 +959,7 @@ extension ChatModel { if outgoingDraftText.utf8.elementsEqual(recovery.message.utf8) { draft = "" replyDraft = nil + boardCardDraft = nil } nativeBotModeSendRecovery = nil } diff --git a/Bighelp/Chat/ChatModel+References.swift b/Bighelp/Chat/ChatModel+References.swift index b686d424..89d63734 100644 --- a/Bighelp/Chat/ChatModel+References.swift +++ b/Bighelp/Chat/ChatModel+References.swift @@ -59,6 +59,7 @@ extension ChatModel { isReplacingReferenceDraft = true draft = "" replyDraft = nil + boardCardDraft = nil draftAttachments = [] orderedDraftAttachments = [] referenceSelections = [] diff --git a/Bighelp/Chat/ChatModel+StagedSends.swift b/Bighelp/Chat/ChatModel+StagedSends.swift index 5e32898d..b2a4b3f7 100644 --- a/Bighelp/Chat/ChatModel+StagedSends.swift +++ b/Bighelp/Chat/ChatModel+StagedSends.swift @@ -79,6 +79,7 @@ extension ChatModel { failureMessage = nil draft = "" replyDraft = nil + boardCardDraft = nil draftAttachments = [] orderedDraftAttachments = [] drainStagedSendsIfNeeded() diff --git a/Bighelp/Chat/ChatModel+Submission.swift b/Bighelp/Chat/ChatModel+Submission.swift index 7e226d1c..f5afddf9 100644 --- a/Bighelp/Chat/ChatModel+Submission.swift +++ b/Bighelp/Chat/ChatModel+Submission.swift @@ -139,6 +139,14 @@ extension ChatModel { return true } + /// A message from outside the box (Let's do it on an idea): it goes once the chat can take + /// it, as Send would (waiting out a chat that's still opening or connecting), and whatever is + /// in the message box stays there. False when it couldn't go. + func sendFromOutside(_ text: String) async -> Bool { + guard await waitForConnection(until: { acceptsCardReply(text) }) else { return false } + return await sendCardReply(text) + } + func send(_ outgoing: ChatOutgoingMessage) async { let message = outgoing.message let slashSelection = outgoing.slashSelection @@ -209,6 +217,7 @@ extension ChatModel { } draft = "" replyDraft = nil + boardCardDraft = nil draftAttachments = [] orderedDraftAttachments = [] } @@ -565,6 +574,7 @@ extension ChatModel { if restoresDraft, outgoing.stagedItem == nil { draft = "" replyDraft = nil + boardCardDraft = nil draftAttachments = [] orderedDraftAttachments = [] } diff --git a/Bighelp/Chat/ChatModel.swift b/Bighelp/Chat/ChatModel.swift index 96d2ac5e..a1aa1d83 100644 --- a/Bighelp/Chat/ChatModel.swift +++ b/Bighelp/Chat/ChatModel.swift @@ -50,6 +50,10 @@ final class ChatModel { didSet { // A sent reply put back after a failure, or a saved draft, comes // back as its quote line plus text: show the reply again. + if !isReplacingReferenceDraft, let card = ChatBoardCard.split(draft) { + draft = card.body + boardCardDraft = card.card + } if !isReplacingReferenceDraft, let reply = ChatReplyQuote.split(draft) { draft = reply.body replyDraft = reply.quote @@ -97,6 +101,14 @@ final class ChatModel { persistSession() } } + /// The idea, Feed post or goal the draft is about (Discuss). It is sent, and saved with the + /// draft, as a block before the text (`ChatBoardCard`). + var boardCardDraft: ChatBoardCard? { + didSet { + guard oldValue != boardCardDraft, !isReplacingReferenceDraft else { return } + persistSession() + } + } /// A blueprint in the message box with its `[blanks]` as chips (`ChatBlueprintDraft`). `draft` /// always holds its text as filled in so far; changing the draft any other way ends it. private(set) var blueprintDraft: ChatBlueprintDraft? @@ -536,8 +548,11 @@ final class ChatModel { self.chosenActivityVisibility = chosenActivityVisibility activityVisibility = chosenActivityVisibility ?? initialActivityVisibility // A saved reply rides before an ordinary draft; reference drafts keep their exact bytes. - let savedReply = sourceSession?.referenceState == nil ? ChatReplyQuote.split(initialDraft) : nil - let initialDraft = savedReply?.body ?? initialDraft + let savedCard = sourceSession?.referenceState == nil ? ChatBoardCard.split(initialDraft) : nil + let draftAfterCard = savedCard?.body ?? initialDraft + boardCardDraft = savedCard?.card + let savedReply = sourceSession?.referenceState == nil ? ChatReplyQuote.split(draftAfterCard) : nil + let initialDraft = savedReply?.body ?? draftAfterCard replyDraft = savedReply?.quote let restoredReferences = ReferenceCanonicalState.restoredDraft(initialDraft, state: sourceSession?.referenceState) diff --git a/Bighelp/Chat/ChatReplyQuote.swift b/Bighelp/Chat/ChatReplyQuote.swift index 9f969e2a..21be8f8c 100644 --- a/Bighelp/Chat/ChatReplyQuote.swift +++ b/Bighelp/Chat/ChatReplyQuote.swift @@ -60,7 +60,7 @@ struct ChatReplyQuote: Equatable, Sendable { let words: String switch item.content { case .message(let text) where item.role == .human: - words = HermesUserMessageDisplay.preview(split(text)?.body ?? text, attachments: item.attachments) + words = HermesUserMessageDisplay.preview(text, attachments: item.attachments) case .message(let text): let prose = ReferenceCodec.decode( DirectHermesGeneratedMediaClient.pendingFiles(text, role: item.role).text).prose @@ -180,19 +180,21 @@ struct ChatReplyQuote: Equatable, Sendable { } extension ChatModel { - /// The composer's text as sent: a reply's quote line first. A command goes - /// out as typed, since a line before it would stop it from running. + /// The composer's text as sent: an idea, post or goal card first, then a reply's quote + /// line. A command goes out as typed, since a line before it would stop it from running. var outgoingDraftText: String { - guard let replyDraft, !draft.hasPrefix("/") else { return draft } - return replyDraft.prefixing(draft) + guard !draft.hasPrefix("/") else { return draft } + let replied = replyDraft?.prefixing(draft) ?? draft + return boardCardDraft?.prefixing(replied) ?? replied } - /// The draft as saved: the reply's quote line, then the text. A draft with - /// references keeps their exact bytes and saves without the reply. + /// The draft as saved: the card, the reply's quote line, then the text. A draft with + /// references keeps their exact bytes and saves without them. var persistedDraft: String { let canonical = canonicalReferenceDraft - guard let replyDraft, referenceSelections.isEmpty, referenceSubmission == nil else { return canonical } - return replyDraft.prefixing(canonical) + guard referenceSelections.isEmpty, referenceSubmission == nil else { return canonical } + let replied = replyDraft?.prefixing(canonical) ?? canonical + return boardCardDraft?.prefixing(replied) ?? replied } /// Long-press › Reply: the composer quotes this message until it's sent or cancelled. diff --git a/Bighelp/Chat/MessageBubble.swift b/Bighelp/Chat/MessageBubble.swift index 76c8b615..997dc503 100644 --- a/Bighelp/Chat/MessageBubble.swift +++ b/Bighelp/Chat/MessageBubble.swift @@ -61,6 +61,8 @@ final class ChatMessageContentCache { let source: String /// The message a person's message answers, drawn above it instead of its quote line. let reply: ChatReplyQuote? + /// The idea, post or goal a person's message carries, drawn in its bubble. + let boardCard: ChatBoardCard? let references: ReferenceDecodedMessage let document: MarkdownDocument let citationLinks: [Int: URL] @@ -73,9 +75,12 @@ final class ChatMessageContentCache { init(_ source: String, role: TimelineRole, isStreaming: Bool = false) { self.source = source - let reply = role == .human ? ChatReplyQuote.split(source) : nil + let card = role == .human ? ChatBoardCard.split(source) : nil + boardCard = card?.card + let afterCard = card?.body ?? source + let reply = role == .human ? ChatReplyQuote.split(afterCard) : nil self.reply = reply?.quote - references = ReferenceCodec.decode(reply?.body ?? source) + references = ReferenceCodec.decode(reply?.body ?? afterCard) document = MarkdownDocument(references.prose) citationLinks = role == .assistant && !isStreaming ? ChatCitationLinks.resolve(in: references.prose) : [:] @@ -198,6 +203,10 @@ struct MessageBubble: View { if let reply = projection.reply { ChatReplyQuoteView(quote: reply, agentName: replyAgentName, alignsTrailing: role == .human) } + if !uiV3Enabled, let card = projection.boardCard { + ChatBoardCardView(card: card) + .frame(maxWidth: ChatBubbleLayoutMetrics.maximumAbsoluteWidth) + } messageInteractionSurface( ChatBubbleWidthLayout( maximumWidthFraction: uiV3Enabled @@ -208,10 +217,11 @@ struct MessageBubble: View { ) : presentation.maximumWidthFraction, contentFitsWidth: uiV3Enabled - ? !projection.cardProjection.hasRichContent + ? !projection.cardProjection.hasRichContent && projection.boardCard == nil : presentation.contentFitsWidth ) { messageContent( + boardCard: projection.boardCard, cardProjection: projection.cardProjection, document: document, citationLinks: projection.citationLinks, @@ -453,6 +463,7 @@ struct MessageBubble: View { @ViewBuilder private func messageContent( + boardCard: ChatBoardCard?, cardProjection: ChatCardMessageProjection, document: MarkdownDocument, citationLinks: [Int: URL], @@ -490,71 +501,94 @@ struct MessageBubble: View { .padding(.vertical, BighelpTokens.space4) } } + } else if uiV3Enabled, let boardCard { + // A person's message with an idea, post or goal: the card above their words, in the + // bubble. A message's text never changes, so it never moves between these branches. + VStack(alignment: .leading, spacing: BighelpTokens.space8) { + ChatBoardCardView(card: boardCard) + .padding(.horizontal, -BighelpTokens.space8) + .padding(.top, -BighelpTokens.space4) + if !document.blocks.isEmpty { + messageText(document: document, interaction: interaction, citationLinks: citationLinks) + } + } + .modifier(BighelpV3MessageSurface(role: role, theme: theme, + increasedContrast: colorSchemeContrast == .increased)) } else if uiV3Enabled { // One text view for both looks: becoming interim restyles it in place. - NativeInlineSelectableMarkdownTextView( + messageText(document: document, interaction: interaction, citationLinks: citationLinks) + .modifier(BighelpV3MessageSurface( + role: role, + theme: theme, + increasedContrast: colorSchemeContrast == .increased, + isInterim: isInterimReply + )) + } else { + legacyContent(document: document, presentation: presentation) + } + } + + private func messageText(document: MarkdownDocument, interaction: ChatBubbleInteraction, + citationLinks: [Int: URL]) -> some View { + NativeInlineSelectableMarkdownTextView( + document: document, + speakerName: speakerName, + proseLineSpacing: role == .human ? 2 : isInterimReply ? 4 : 5, + primaryText: isInterimReply ? theme.secondaryText : nativePrimaryText, + secondaryText: role == .human ? nativePrimaryText.opacity(0.82) + : isInterimReply ? theme.tertiaryText : theme.secondaryText, + accent: role == .human ? nativePrimaryText : theme.action, + codeBackground: role == .human + ? nativePrimaryText.opacity(0.14) + : theme.primaryText.opacity(0.07), + openURL: openURL, + theme: theme, + copyActionLabel: copyActionLabel, + onCopy: { copyMessage(interaction) }, + onSelect: { isSelectingText = true }, + onFork: onFork, + reactions: reactionActions, + onReply: onReply, + onShare: { isSharing = true }, + textScale: (isInterimReply ? ChatInterimReplyStyle.textScale : 1) * chatTextSize.scale, + mentionIdentities: mentionIdentities, + menuAnchor: menuAnchor, + bubbleShape: bubbleShape, + citationLinks: citationLinks + ) + } + + @ViewBuilder + private func legacyContent(document: MarkdownDocument, presentation: ChatMessagePresentation) -> some View { + switch presentation.chrome { + case .accentBubble: + MarkdownMessageView( document: document, - speakerName: speakerName, - proseLineSpacing: role == .human ? 2 : isInterimReply ? 4 : 5, - primaryText: isInterimReply ? theme.secondaryText : nativePrimaryText, - secondaryText: role == .human ? nativePrimaryText.opacity(0.82) - : isInterimReply ? theme.tertiaryText : theme.secondaryText, - accent: role == .human ? nativePrimaryText : theme.action, - codeBackground: role == .human - ? nativePrimaryText.opacity(0.14) - : theme.primaryText.opacity(0.07), - openURL: openURL, - theme: theme, - copyActionLabel: copyActionLabel, - onCopy: { copyMessage(interaction) }, - onSelect: { isSelectingText = true }, - onFork: onFork, - reactions: reactionActions, - onReply: onReply, - onShare: { isSharing = true }, - textScale: (isInterimReply ? ChatInterimReplyStyle.textScale : 1) * chatTextSize.scale, - mentionIdentities: mentionIdentities, - menuAnchor: menuAnchor, - bubbleShape: bubbleShape, - citationLinks: citationLinks + proseLineSpacing: presentation.proseLineSpacing ) - .modifier(BighelpV3MessageSurface( - role: role, - theme: theme, - increasedContrast: colorSchemeContrast == .increased, - isInterim: isInterimReply - )) - } else { - switch presentation.chrome { - case .accentBubble: - MarkdownMessageView( - document: document, - proseLineSpacing: presentation.proseLineSpacing - ) - .foregroundStyle(isPendingSubmission ? theme.secondaryText : theme.primaryText) - .multilineTextAlignment(.leading) - .padding(.horizontal, BighelpTokens.space16) - .padding(.vertical, BighelpTokens.space12) - .bighelpSurface(.selected) - case .openProse where isInterimReply: - MarkdownMessageView( - document: document, - proseLineSpacing: presentation.proseLineSpacing - ) - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - .multilineTextAlignment(.leading) - .modifier(ChatInterimReplyStyle(theme: theme)) - case .openProse: - MarkdownMessageView( - document: document, - proseLineSpacing: presentation.proseLineSpacing - ) - .foregroundStyle(isPendingSubmission ? theme.secondaryText : theme.primaryText) - .multilineTextAlignment(.leading) - .padding(.horizontal, BighelpTokens.space4) - .padding(.vertical, BighelpTokens.space4) - } + .foregroundStyle(isPendingSubmission ? theme.secondaryText : theme.primaryText) + .multilineTextAlignment(.leading) + .padding(.horizontal, BighelpTokens.space16) + .padding(.vertical, BighelpTokens.space12) + .bighelpSurface(.selected) + case .openProse where isInterimReply: + MarkdownMessageView( + document: document, + proseLineSpacing: presentation.proseLineSpacing + ) + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + .multilineTextAlignment(.leading) + .modifier(ChatInterimReplyStyle(theme: theme)) + case .openProse: + MarkdownMessageView( + document: document, + proseLineSpacing: presentation.proseLineSpacing + ) + .foregroundStyle(isPendingSubmission ? theme.secondaryText : theme.primaryText) + .multilineTextAlignment(.leading) + .padding(.horizontal, BighelpTokens.space4) + .padding(.vertical, BighelpTokens.space4) } } diff --git a/Bighelp/Chat/MessageViews.swift b/Bighelp/Chat/MessageViews.swift index 83b48c4a..26266c1b 100644 --- a/Bighelp/Chat/MessageViews.swift +++ b/Bighelp/Chat/MessageViews.swift @@ -51,7 +51,14 @@ struct TimelineSenderResolver { func accessibilityDescription(for item: TimelineItem) -> String { let description: String if item.role == .human, case .message(let text) = item.content, - let reply = ChatReplyQuote.split(text) { + let attached = ChatBoardCard.split(text) { + // The card is read first, as it shows. + let card = attached.card + let words = Self.spokenSentFiles(ChatReplyQuote.split(attached.body)?.body ?? attached.body, + attachments: item.attachments) + description = [card.label + ": " + card.title, words].filter { !$0.isEmpty }.joined(separator: ". ") + } else if item.role == .human, case .message(let text) = item.content, + let reply = ChatReplyQuote.split(text) { // The quote above the bubble speaks for itself. description = Self.spokenSentFiles(reply.body, attachments: item.attachments) } else if item.role == .human, case .message(let text) = item.content { diff --git a/Bighelp/Driving/DriveOverlay.swift b/Bighelp/Driving/DriveOverlay.swift index f96cb1d0..ac961631 100644 --- a/Bighelp/Driving/DriveOverlay.swift +++ b/Bighelp/Driving/DriveOverlay.swift @@ -456,7 +456,9 @@ private struct DriveDockComposer: View { /// A reply quote or references go out only through the chat's own box, which knows how to send /// them; here Send waits for Return to chat. - private var sends: Bool { chat.canSend && chat.replyDraft == nil && chat.referenceSelections.isEmpty } + private var sends: Bool { + chat.canSend && chat.replyDraft == nil && chat.boardCardDraft == nil && chat.referenceSelections.isEmpty + } var body: some View { HStack(spacing: 8) { diff --git a/Bighelp/Fixtures/DemoAgentBoardClient.swift b/Bighelp/Fixtures/DemoAgentBoardClient.swift index 08bba843..ddfc9a05 100644 --- a/Bighelp/Fixtures/DemoAgentBoardClient.swift +++ b/Bighelp/Fixtures/DemoAgentBoardClient.swift @@ -74,6 +74,12 @@ final class DemoAgentBoardClient: AgentBoardClient { throw WorkspaceClientError.invalidRequest } accepted[agentID, default: []].insert(itemID) + // As the plugin does: the idea now carries the yes, and when. + if let index = itemsByAgent[agentID]?.firstIndex(where: { $0.id == itemID }), + itemsByAgent[agentID]?[index].answer != "yes" { + itemsByAgent[agentID]?[index].answer = "yes" + itemsByAgent[agentID]?[index].answeredAt = .now + } } func picture(agentID: String, itemID: String, index: Int) async throws -> Data { diff --git a/Bighelp/Hermes/HermesUserMessageDisplay.swift b/Bighelp/Hermes/HermesUserMessageDisplay.swift index 564e1c7e..f0fda629 100644 --- a/Bighelp/Hermes/HermesUserMessageDisplay.swift +++ b/Bighelp/Hermes/HermesUserMessageDisplay.swift @@ -54,7 +54,9 @@ enum HermesUserMessageDisplay { static func preview(_ raw: String, attachments: [ChatAttachment] = []) -> String { var photos = attachments.contains { $0.kind == .image } var files = !attachments.isEmpty - let shown = text(raw) + var shown = text(raw) + // An idea, post or goal the message carries shows as its card, not in the preview. + if let card = ChatBoardCard.split(shown) { shown = card.body.isEmpty ? card.card.title : card.body } let words = (ChatReplyQuote.split(shown)?.body ?? shown).components(separatedBy: "\n").filter { line in if line.hasPrefix("@image:") { photos = true; return false } if line.hasPrefix("@file:") { files = true; return false } diff --git a/Bighelp/SimpleBots/SimpleBotProfileView.swift b/Bighelp/SimpleBots/SimpleBotProfileView.swift index 1667d246..459d3e39 100644 --- a/Bighelp/SimpleBots/SimpleBotProfileView.swift +++ b/Bighelp/SimpleBots/SimpleBotProfileView.swift @@ -52,6 +52,8 @@ struct SimpleBotDashboardHooks { let configureShellBoard: @MainActor (RootShellView.AgentBoardClientKey) async -> Void /// Opens the bot's chat with the text in its message box (bot ID, text); nothing is sent. let onAsk: (String, String) -> Void + /// Opens the bot's chat and sends the text there (Let's do it). + let onSend: (String, String) -> Void /// Opens the bot's chat with a blueprint in its message box, its blanks as chips. let onBlueprint: (String, String) -> Void } @@ -991,7 +993,7 @@ struct SimpleBotProfileView: View { agentID: id, agentName: profile.name, imageURL: context.agents.avatarURL(for: profile), activity: .idle, store: store, onProfile: {}, onSwitchAgent: {}, - onAsk: { hooks.onAsk(id, $0) }, onBlueprint: { hooks.onBlueprint(id, $0) }, + onAsk: { hooks.onAsk(id, $0) }, onSend: { hooks.onSend(id, $0) }, onBlueprint: { hooks.onBlueprint(id, $0) }, onMenu: {}, onNewChat: { context.onOpenChat(id) }, onPickAgents: {}, tools: []) } diff --git a/BighelpTests/AgentBoardTests.swift b/BighelpTests/AgentBoardTests.swift index c55af662..6afa7b83 100644 --- a/BighelpTests/AgentBoardTests.swift +++ b/BighelpTests/AgentBoardTests.swift @@ -115,7 +115,7 @@ struct AgentBoardTests { #expect(store.goals.map(\.title) == ["Sleep by 11"]) } - /// Let's do it tells the host which idea by its ID, and the chat gets only the readable text. + /// Let's do it tells the host which idea by its ID, and the chat gets only the readable card. @Test func letsDoItNamesTheIdeaByIDAndKeepsTheIDOutOfTheChat() async throws { let client = FakeBoardClient(items: [ AgentBoardItem(id: "idea-7f3a91", kind: .idea, title: "Plan a trip"), @@ -129,9 +129,12 @@ struct AgentBoardTests { #expect(await store.accept(idea) == .recorded) #expect(client.accepted.map(\.itemID) == ["idea-0c2e44"], "Exactly the tapped idea, not its same-title twin") #expect(client.accepted.map(\.agentID) == ["default"]) - #expect(store.ideas.count == 2, "The idea stays on the board") + // It moves to Completed, with when. + #expect(store.ideas.map(\.id) == ["idea-7f3a91"]) + #expect(store.completedIdeas.map(\.id) == ["idea-0c2e44"]) + #expect(store.completedIdeas.first?.answeredAt != nil) let text = idea.letsDoItMessage - #expect(text == "Yes, go ahead with this idea: “Plan a trip”.") + #expect(ChatBoardCard.split(text)?.body == "Let's do it!") #expect(!text.contains(idea.id) && !text.contains("idea-")) } @@ -140,13 +143,16 @@ struct AgentBoardTests { let store = AgentBoardStore() store.configure(client: client) await store.load(agentID: "default") - #expect(await store.accept(store.ideas[0]) == .notSupported) + let idea = store.ideas[0] + #expect(await store.accept(idea) == .notSupported) #expect(client.accepted.isEmpty) + // Completed here too, until the board loads again. + #expect(store.completedIdeas.map(\.id) == ["i"]) // A plugin that stops listing the feature after the board loaded: still no error. client.supportsAnswers = true client.acceptError = WorkspaceClientError.unavailable(.unsupportedOperation) - #expect(await store.accept(store.ideas[0]) == .notSupported) + #expect(await store.accept(idea) == .notSupported) store.configure(client: nil) #expect(await store.accept(AgentBoardItem(id: "i", kind: .idea, title: "Plan a trip")) == .notSupported) @@ -160,11 +166,34 @@ struct AgentBoardTests { store.configure(client: client) await store.load(agentID: "default") #expect(await store.accept(store.ideas[0]) == .failed) + #expect(store.completedIdeas.isEmpty, "Not completed until the host has it") client.acceptError = nil #expect(await store.accept(store.ideas[0]) == .recorded) #expect(client.accepted.map(\.itemID) == ["i"]) } + /// The host's answer puts an idea under Completed, newest yes first, with when. + @Test func ideasTheHostSaysYesToAreCompleted() async throws { + let item = { (id: String, answer: String, at: Int) -> BighelpJSONValue in + .object(["id": .string(id), "kind": .string("idea"), "title": .string(id), + "answer": .string(answer), "answeredAt": .integer(at)]) + } + let items = try [item("older", "yes", 100), item("newer", "yes", 200), item("open", "none", 0), + item("goal", "goal", 300)].map(AgentBoardItem.init(json:)) + let store = AgentBoardStore() + store.configure(client: FakeBoardClient(items: items)) + await store.load(agentID: "default") + #expect(store.ideas.map(\.id).sorted() == ["goal", "open"]) + #expect(store.completedIdeas.map(\.id) == ["newer", "older"]) + #expect(store.completedIdeas.first?.answeredAt == Date(timeIntervalSince1970: 200)) + // Plugins before answeredAt: still Completed, without a day. + let bare = try AgentBoardItem(json: .object(["id": .string("x"), "kind": .string("idea"), + "title": .string("x"), "answer": .string("yes")])) + #expect(bare.isCompleted && bare.answeredAt == nil) + #expect(IdeaCompletion.label(nil) == "Completed") + #expect(IdeaCompletion.label(.now) == "Started today") + } + @Test func letsDoItIsNotRecordedAcrossAHostOrAgentChange() async { let client = FakeBoardClient(items: [AgentBoardItem(id: "i", kind: .idea, title: "Plan a trip")]) client.supportsAnswers = true diff --git a/BighelpTests/ChatBoardCardTests.swift b/BighelpTests/ChatBoardCardTests.swift new file mode 100644 index 00000000..6ec7b562 --- /dev/null +++ b/BighelpTests/ChatBoardCardTests.swift @@ -0,0 +1,116 @@ +import Foundation +import Testing +@testable import Bighelp + +/// An idea, Feed post or goal on a message: the block the agent reads, the draft it rides with, +/// Let's do it's own message, and the bubble a reloaded chat draws from the host's text. +@MainActor +struct ChatBoardCardTests { + @Test func everyKindRoundTripsThroughTheSentText() throws { + let bodies = ["Let's do it!", "Two lines\nof question", "", "Quote \"marks\"] and [brackets]"] + let cards = [ + ChatBoardCard(kind: .idea, title: "Start a \"Sunday\"] meal plan", detail: "Home", + body: "Five dinners.\n\n- A list\n- Reminders"), + ChatBoardCard(kind: .feedPost, title: "Your week in money", body: ""), + ChatBoardCard(kind: .goal, title: "Run a 10K", detail: "Health", body: "Three runs a week"), + ] + for card in cards { + for body in bodies { + let read = try #require(ChatBoardCard.split(card.prefixing(body)), "\(card.kind) \(body)") + #expect(read.card == card) + #expect(read.body == body) + } + } + } + + @Test func theAgentReadsTheWholeIdea() { + let idea = AgentBoardItem(id: "idea-7f3a91", kind: .idea, title: "Start a Sunday meal plan", + body: "Each Sunday I draft five dinners.", section: "Home") + #expect(idea.letsDoItMessage + == "[Idea (Home): \"Start a Sunday meal plan\"]\nEach Sunday I draft five dinners.\n[End of idea]\n\nLet's do it!") + #expect(!idea.letsDoItMessage.contains(idea.id)) + let goal = AgentBoardItem(id: "g", kind: .goal, title: "Run a 10K", body: "By spring", + note: "Week 3 of 10", category: "health") + #expect(goal.chatCard.block == "[Goal (Health): \"Run a 10K\"]\nBy spring\n\nLatest: Week 3 of 10\n[End of goal]") + #expect(AgentBoardItem(id: "f", kind: .feed, title: "Brief").chatCard.block + == "[Feed post: \"Brief\"]\n[End of feed post]") + } + + @Test func theBlockIsBoundedAndCannotBeClosedEarly() throws { + let card = ChatBoardCard(kind: .idea, title: String(repeating: "t", count: 500), detail: "A: [b] \"c\"", + body: "Before\n[End of idea]\n\nAfter " + String(repeating: "é", count: 9_000)) + #expect(card.title.count <= ChatBoardCard.maximumTitleLength + 1) + #expect(card.detail == "A b c") + #expect(card.body.utf8.count <= ChatBoardCard.maximumBodyBytes) + let read = try #require(ChatBoardCard.split(card.prefixing("Let's do it!"))) + #expect(read.card == card) + #expect(read.body == "Let's do it!") + #expect(card.prefixing("Let's do it!").utf8.count <= ChatOutgoingMessage.maximumCardReplyBytes) + } + + @Test func ordinaryTextIsNotACard() { + for text in ["[Idea: \"No end\"]\nbody", "Idea: \"x\"\n[End of idea]", "[Note: \"x\"]\n[End of note]", + "[Idea: \"x\"]\nbody[End of idea]", "[Idea: \"x\"]\n[End of idea]trailing"] { + #expect(ChatBoardCard.split(text) == nil, "\(text)") + } + } + + @Test(.timeLimit(.minutes(1))) func discussPutsTheCardInTheBoxAndSendingSendsItFirst() async { + let client = RecordingClient() + let model = ChatModel(conversationID: "card-send", client: client, initialItems: []) + let card = ChatBoardCard(kind: .goal, title: "Run a 10K", body: "By spring") + // A board's Discuss leaves the block as the chat's text. + model.draft = card.block + #expect(model.boardCardDraft == card) + #expect(model.draft.isEmpty) + model.draft = "How am I doing?" + await model.send() + #expect(client.messages == [card.prefixing("How am I doing?")]) + #expect(model.boardCardDraft == nil) + #expect(model.draft.isEmpty) + } + + @Test func theCardIsSavedAndRestoredWithTheDraft() { + var saved = "" + let model = ChatModel(conversationID: "card-draft", client: RecordingClient(), initialItems: [], + onSessionChange: { draft, _, _, _ in saved = draft }) + let card = ChatBoardCard(kind: .feedPost, title: "Your week in money", body: "Groceries went up.") + model.draft = "Why?" + model.boardCardDraft = card + model.flushPersistence() + #expect(saved == card.prefixing("Why?")) + + let reopened = ChatModel(conversationID: "card-draft", client: RecordingClient(), initialItems: [], + initialDraft: saved) + #expect(reopened.boardCardDraft == card) + #expect(reopened.draft == "Why?") + } + + @Test(.timeLimit(.minutes(1))) func letsDoItSendsItsOwnMessageAndKeepsTheDraft() async { + let client = RecordingClient() + let model = ChatModel(conversationID: "card-lets-do-it", client: client, initialItems: []) + model.draft = "Half-typed note" + let message = AgentBoardItem(id: "i", kind: .idea, title: "Plan a trip").letsDoItMessage + #expect(await model.sendFromOutside(message)) + #expect(client.messages == [message]) + #expect(model.draft == "Half-typed note") + #expect(model.boardCardDraft == nil) + } + + @Test func theChatListShowsTheWordsNotTheBlock() { + let card = ChatBoardCard(kind: .idea, title: "Plan a trip", body: "Three days in Lisbon.") + let hostText = card.prefixing("Let's do it!") + #expect(HermesUserMessageDisplay.preview(HermesUserMessageDisplay.text(hostText)) == "Let's do it!") + #expect(HermesUserMessageDisplay.preview(card.block) == "Plan a trip") + } +} + +@MainActor +private final class RecordingClient: ConversationFixtureClient { + private(set) var messages: [String] = [] + + override func send(message: String, conversationID: String) async throws -> ConversationResponse { + messages.append(message) + return try await super.send(message: message, conversationID: conversationID) + } +}