diff --git a/AGENTS.md b/AGENTS.md index b8541982..bd5f006f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1251,6 +1251,32 @@ Helpful, never a pile to clear (`BighelpNotificationGrouping`): Attention comes first; the payload holds five rows and a total count. A chat finishing cannot end another chat's card. The service aggregates scoped per-turn updates before sending to the shared native token (docs/LIVE_ACTIVITY_GROUPS.md). The finished card leaves about 30 seconds after all work ends, and opening the app clears it. +- The Dynamic Island opens by itself for news (#1050): a chat needs the person, finished or could not finish. + The notification service sees a row's phase change into `waiting`, `completed` or `failed`, and that one update + carries an `alert` (fixed words, no sound) and names the row in the state's `lead`, which the card shows first + (`BighelpActivitySession.shown`). A step never does. The open island then shows that chat + (`BighelpIslandMoment`): its bot, what happened, the words from the sealed detail and buttons. iOS takes an ended + card off the island at once, so the last chat's finish goes as an update and the end follows 30 s later. + The simulator gets no pushes: `-test-island-moment command|approval|question|done|failed` shows each one. +- A yes on the island needs the whole command on screen. The sealed detail says what waits + (`BighelpActivityDetail.Ask`, the plugin's `a`): only a command the computer sent whole, at most 90 characters, + that the card may show as text gets Deny and Approve (`BighelpActivityDecisionIntent`, a `LiveActivityIntent` + that runs in the app and needs the unlocked phone). Every other approval gets Review, a question Answer, a + finished reply Open chat and Reply (`chatURL(reply:)`, `ChatReplyRequest`: the chat opens with the keyboard up). + The intent carries the command the island showed, and the app answers only when that same command is the one + request that waits in the chat (`ChatOutsidePrompt.approval`: not expired, the choice allowed, the command + short). The island can stay on screen for minutes; a tap after the bot asked for something else answers + nothing and says so. +- Words typed on an alert go to its chat with the app closed (#1051, `BighelpAlertReply`): a reply's alert takes + the person's next message, a question's alert its answer. The notification service extension adds the field + from the alert's kind, never from the push, so an older build shows no field whose words it would drop. The + field needs the unlocked phone: saved chats can't be read while it is locked. +- Everything a person does to a chat from outside the app goes through `ChatOutsideActions`, on the Shortcuts + host path: the alert's words, the island's Approve and Deny. It never starts a chat, never moves a person who + is using the app to another computer, and says a failure in an alert on the phone with the words in it + (`ChatOutsideNotice`). Actions run one at a time and stop after 24 s, inside the time iOS gives one, so a + failure is always said. `BighelpShortcutWorkspace.sendFromOutside` is the one send, shared with Arriving and + leaving. - The card starts when the person taps Send (T3 Code's playbook, `BighelpManagedNativeActivityRuntime.arm`, a "Sending your message" row under the chat's own opaque ID): iOS starts a Live Activity only for an app in front, and a turn with a file starts once the file is up, often after the person left, so it got no card. A turn that diff --git a/Bighelp.xcodeproj/project.pbxproj b/Bighelp.xcodeproj/project.pbxproj index 5c56190d..fea31c71 100644 --- a/Bighelp.xcodeproj/project.pbxproj +++ b/Bighelp.xcodeproj/project.pbxproj @@ -51,6 +51,7 @@ 048F7A61F0CA0760D47A2BF2 /* DirectHermesAttachmentClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 81CABC4DD0A03C05A6531348 /* DirectHermesAttachmentClientTests.swift */; }; 0499789C48A13CFC46D6E128 /* DirectHermesGeneratedMediaClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80938D1DC3C8FD823A41A1E1 /* DirectHermesGeneratedMediaClient.swift */; }; 051146CA8DA17E3FF2A1F883 /* NativeWorkspaceLockedWakeLiveTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 117DF67A867B04D7F822E7D8 /* NativeWorkspaceLockedWakeLiveTests.swift */; }; + 051F55E3EC6657F82AFBB275 /* IslandMomentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B72C56885C1D313E00DA5D8 /* IslandMomentTests.swift */; }; 0537F66F671525DE97D570CE /* VoiceConfigurationStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335213208F41D9012118F4BD /* VoiceConfigurationStore.swift */; }; 053E66E5A37D5E8F24168EBC /* BighelpRealtimeAudioPeer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 918B96E497E5895E812E63C3 /* BighelpRealtimeAudioPeer.swift */; }; 053EB5E11B8F26BDA0FCDB09 /* PinnedModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F842CFD9DCD39F9FA5F5C67 /* PinnedModelTests.swift */; }; @@ -87,6 +88,7 @@ 095FEFD74A2FA1D648B59B6A /* SpacesStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8E5581E4759087BDC795DA7 /* SpacesStoreTests.swift */; }; 0963824B1C1CDB181BEBF365 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = EA02A54D78F51C5693D834C4 /* PrivacyInfo.xcprivacy */; }; 09651BA643D9557E64F410ED /* DashboardActivityDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCC640306666832EF7BEC2A0 /* DashboardActivityDetailView.swift */; }; + 096C9C082BDDE56DCC8335E7 /* BighelpIslandMoment.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1114608474A869B664B1723 /* BighelpIslandMoment.swift */; }; 097C03162CA1EBD2B7D40CA6 /* DirectHermesKanbanAdministrationClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0146AA0B6247AD289E1620B5 /* DirectHermesKanbanAdministrationClient.swift */; }; 097D67F2E01BD2916CF4A97E /* DirectHermesTransferBudgetTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95D917C06BD57494A90A5534 /* DirectHermesTransferBudgetTests.swift */; }; 098475E928DB8D2D64FCB6C6 /* BighelpPhysicalActivityTokenRegistrarTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC27A35B9A6557BD1E426506 /* BighelpPhysicalActivityTokenRegistrarTests.swift */; }; @@ -301,6 +303,7 @@ 248DAD8CB40DDDE24D1DF77D /* RootShellView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04C04136C11827E672449E5B /* RootShellView.swift */; }; 24A40737A11720660FEEA796 /* publish.json in Resources */ = {isa = PBXBuildFile; fileRef = 1B6B693ABB104DB929DE4072 /* publish.json */; }; 24C17081BD26E8CD41D28F4B /* DirectHermesSessionCatalogClient+Fork.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28193E2FCD079F5AB0F9F344 /* DirectHermesSessionCatalogClient+Fork.swift */; }; + 24D93F8CC1819D1B5A6179AD /* ChatOutsideActions.swift in Sources */ = {isa = PBXBuildFile; fileRef = C86554BC06175E4863F33254 /* ChatOutsideActions.swift */; }; 24E16857EE287D1D20F82814 /* ChatModelSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36E3B5F0213C68AE641282A2 /* ChatModelSummary.swift */; }; 24F2DA68D41BA5EEFD0A11F4 /* DirectHermesAgentAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D9949FF5F6338FC334250AF /* DirectHermesAgentAdapterTests.swift */; }; 250BC7C93473EBD7B9CEC42F /* ChatSessionFilesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3169FAF80070C715B4D2C9F /* ChatSessionFilesView.swift */; }; @@ -324,6 +327,7 @@ 26FA0DB95E90AC1A58B177ED /* SimpleBotsSwitcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = C6D5ABF5E4CE7FD36AF3820A /* SimpleBotsSwitcher.swift */; }; 27084531F50DE08A275E0B1C /* ChatCitationFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6EE5E11EF15659E52E927941 /* ChatCitationFixture.swift */; }; 27148CBB784CD22E4B829B12 /* DefaultModelUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E5CDB113F353D5523600CFB /* DefaultModelUITests.swift */; }; + 275A1A84B3CAF2442FBC1F31 /* BighelpAlertReply.swift in Sources */ = {isa = PBXBuildFile; fileRef = B25ED3C7FF7ACD0A9E03FDAA /* BighelpAlertReply.swift */; }; 278D4BD4933398E9E8A1CDDA /* HostHooksView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EBB614F75D0EEDA0B6D89CA /* HostHooksView.swift */; }; 27A49B69B97D32CD2A32E649 /* GitHubResource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 068D61A6A87AA9FEA4157D48 /* GitHubResource.swift */; }; 27B50136A7D03C9538027EBB /* VoiceShortcutUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60E050D2B298F1D866F2DFF1 /* VoiceShortcutUITests.swift */; }; @@ -424,6 +428,7 @@ 348AB2B95F565F4AE42D3649 /* ChatAttributionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5839EBC64D344E43871E5958 /* ChatAttributionTests.swift */; }; 34A0AF30BB214480FD668A0D /* ProviderLogoRepository.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42035E7783F34ECD1C61887F /* ProviderLogoRepository.swift */; }; 34A877ABA88E5CE239BF4C33 /* BotLookRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 224EF7C922F648595D119617 /* BotLookRenderer.swift */; }; + 34B81802B8A4F5168F6F2BEF /* IslandMomentPreview.swift in Sources */ = {isa = PBXBuildFile; fileRef = A191699C5E52C57BA6D32BC6 /* IslandMomentPreview.swift */; }; 34BB5D4D0ABBA53C4AB99418 /* GitHubCredentialVault.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1F3A6B164D214D21D79B91C /* GitHubCredentialVault.swift */; }; 34CDFC72CAD26CDBFA0751FB /* AvatarKitRenderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0284978EC9F5AD21700F6E31 /* AvatarKitRenderTests.swift */; }; 3523846944DD383A6D161D7D /* BotScreenStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BEF307512389C0729BDF539 /* BotScreenStateTests.swift */; }; @@ -477,6 +482,7 @@ 3A4C3BD63F9AD9122450E4A5 /* BighelpBoardWidgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E3F7BC4DE0D166012849DBB /* BighelpBoardWidgets.swift */; }; 3A557EDD8981195F9BE06451 /* SpaceDraftCardStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01ACA08D84DDE576D1756E14 /* SpaceDraftCardStateTests.swift */; }; 3A594C9B53EBF9F00712E1BE /* session-path.json in Resources */ = {isa = PBXBuildFile; fileRef = 172B7497F44AA26F893DD141 /* session-path.json */; }; + 3A749C2A4ED92C1D3F602211 /* AlertReplyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FCAEFB8B77DA001E3EDD520 /* AlertReplyTests.swift */; }; 3AA6E7EAA99FD6C034F8A654 /* BighelpFocusFilterState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 317F3D4090FD79701E7E1B7A /* BighelpFocusFilterState.swift */; }; 3AABEACF3DF7C6022828FB53 /* BighelpLinkPushEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE129246716CE44864F927A5 /* BighelpLinkPushEnvironment.swift */; }; 3AB6DDD20A75CEB013581D39 /* NativeWorkspaceSessionBridge+Prompts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5467FAB05B10A607ED9DBE3C /* NativeWorkspaceSessionBridge+Prompts.swift */; }; @@ -1575,6 +1581,7 @@ BAF77DEF5842A102D632C021 /* BighelpPushDisplay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CB641DD1ED71A94F5CEF61C /* BighelpPushDisplay.swift */; }; BB0E8A5C17D13AFDEE9EFEA4 /* ProjectsStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FB92C87FA3C2AEFE88CC27F /* ProjectsStore.swift */; }; BB0FEC14E7280C63BE65F1B7 /* DirectHermesHostImportTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F153F100B7A625AFD7145C9 /* DirectHermesHostImportTransport.swift */; }; + BB1675622CE87341BBD94728 /* BighelpAlertReply.swift in Sources */ = {isa = PBXBuildFile; fileRef = B25ED3C7FF7ACD0A9E03FDAA /* BighelpAlertReply.swift */; }; BB4C274C0588810261C7F7DE /* ShellFeatureStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9775DDC3330098E37AD98104 /* ShellFeatureStore.swift */; }; BB9CE1A084021E1CD9FFD1F5 /* WorkCards.swift in Sources */ = {isa = PBXBuildFile; fileRef = 407581F24811888F32AEF469 /* WorkCards.swift */; }; BBA132CACFBE9000296578AB /* CompanionReactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21796C5BE7BB0044774A8C36 /* CompanionReactionTests.swift */; }; @@ -1867,6 +1874,7 @@ DE066F0F3AD816A6ED5FF72C /* BighelpUsageWidgetViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F8D3EAA68D390EB783F6B71 /* BighelpUsageWidgetViews.swift */; }; DE205DF7F6F0287FD70D5DA5 /* GeneratedMediaProjectionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 458AECEE1D05EA55E6476DDE /* GeneratedMediaProjectionTests.swift */; }; DE2387F7053F01F406DC550D /* BighelpWatchApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 34735749BD48CA6C538D6B1D /* BighelpWatchApp.swift */; }; + DE2E797EEA5F52CC2637B2D3 /* BighelpActivityDecision.swift in Sources */ = {isa = PBXBuildFile; fileRef = B64D0E4C69A56D35D32B1E10 /* BighelpActivityDecision.swift */; }; DE5468478D84BDFC944E2CF5 /* WorkspacePresentationContinuity.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC21517744DE257F55DA956F /* WorkspacePresentationContinuity.swift */; }; DE5B4700D25B828CB4E201C2 /* ChatNativeMarkdownRendering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1CF64A930FF6C4F681D96FB3 /* ChatNativeMarkdownRendering.swift */; }; DE5C37183EF6C9461DA72BE4 /* ChatToolFolderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E5EA3FFBC65637A8AB769AF /* ChatToolFolderTests.swift */; }; @@ -1935,6 +1943,7 @@ E5988E36EF865BD472C30D46 /* DeviceToolCatalog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55A878E7D915D9578F8B6D1A /* DeviceToolCatalog.swift */; }; E5AE72FCAF0D598E265BF605 /* ProfileLifecycleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4B3EF4DE0B3F0D3F8FF8DA5 /* ProfileLifecycleView.swift */; }; E5ED0E414BA70426E622F483 /* HostAccessEditorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFE0A4000866389A931340CB /* HostAccessEditorView.swift */; }; + E5F1B9F3654CC6CF51626582 /* BighelpIslandMoment.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1114608474A869B664B1723 /* BighelpIslandMoment.swift */; }; 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 */; }; @@ -2003,6 +2012,7 @@ EE3C73C255647DBB8B73D65D /* DeviceAppearanceFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2271D36949B061D1891E546B /* DeviceAppearanceFixture.swift */; }; EE47A87EE0032BAEEBD18CF7 /* DirectHermesCapabilityManifest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EA3E1856CF21502D87D4216 /* DirectHermesCapabilityManifest.swift */; }; EE47C6D021C5C6B11DDDF885 /* BighelpCardEnvelope.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDD30D26F79A0E05511ADF5A /* BighelpCardEnvelope.swift */; }; + EE788BD9231A0AE90FB392DB /* BighelpActivityDecision.swift in Sources */ = {isa = PBXBuildFile; fileRef = B64D0E4C69A56D35D32B1E10 /* BighelpActivityDecision.swift */; }; EE985620CD35B9714C5DFAB9 /* WikiModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2E5AA247E3613B8E4EA02A0 /* WikiModels.swift */; }; EEBAB35D8F6844C744D7C38B /* DirectHermesConversationClient+Events.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86B6A908202EBEE1C0FA264F /* DirectHermesConversationClient+Events.swift */; }; EEEB50E2DBF4AE5BFD0254F5 /* list.json in Resources */ = {isa = PBXBuildFile; fileRef = F5AC35A79ACACE81F456243E /* list.json */; }; @@ -2624,6 +2634,7 @@ 2B2A93A6AF8DA5497A0408EB /* WatchPhone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchPhone.swift; sourceTree = ""; }; 2B40CF01292786E98BB37CE5 /* DirectHermesFileAttachments.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesFileAttachments.swift; sourceTree = ""; }; 2B44FC009700CCB1A5BEFF77 /* SessionCatalogReconciliation+Index.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SessionCatalogReconciliation+Index.swift"; sourceTree = ""; }; + 2B72C56885C1D313E00DA5D8 /* IslandMomentTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandMomentTests.swift; sourceTree = ""; }; 2B8B37EC9D882249EE83AE37 /* AgentBoard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentBoard.swift; sourceTree = ""; }; 2BD1CAE5DCBB420CB2ED2CE7 /* DeviceAccessCardsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAccessCardsTests.swift; sourceTree = ""; }; 2BD21A8FBBCA9AF95D546F15 /* FleetSettingsUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FleetSettingsUITests.swift; sourceTree = ""; }; @@ -2663,6 +2674,7 @@ 2F69DF4D8979ACD704171100 /* DirectHermesVoiceConfigurationClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesVoiceConfigurationClient.swift; sourceTree = ""; }; 2F84A337096DA59B68CAF506 /* ImageActionsSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageActionsSettings.swift; sourceTree = ""; }; 2FA73AFA26F8900D33EE46AF /* telemetry-v1.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "telemetry-v1.json"; sourceTree = ""; }; + 2FCAEFB8B77DA001E3EDD520 /* AlertReplyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AlertReplyTests.swift; sourceTree = ""; }; 2FE55A8596FE2BA8F810C73E /* HomeShellUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeShellUITests.swift; sourceTree = ""; }; 30032BB7A11575E32DECD170 /* BotChatActivityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotChatActivityTests.swift; sourceTree = ""; }; 301F7F2D182A2BEC6F9B21B1 /* BighelpLoaderGallery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpLoaderGallery.swift; sourceTree = ""; }; @@ -3627,6 +3639,7 @@ A165878C3209946E72E421B1 /* DirectHermesAchievementsClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesAchievementsClient.swift; sourceTree = ""; }; A1743EC57BBB9882E10B308F /* CodeBatchChatView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeBatchChatView.swift; sourceTree = ""; }; A190714D79AB52AA0A2AA7DA /* BighelpNotificationIdentityInstallationScopeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpNotificationIdentityInstallationScopeTests.swift; sourceTree = ""; }; + A191699C5E52C57BA6D32BC6 /* IslandMomentPreview.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandMomentPreview.swift; sourceTree = ""; }; A196AB02B4F486670EB8CBFB /* ChatComposer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatComposer.swift; sourceTree = ""; }; A1A136B4A7CA143CF46EFF26 /* GeneratedMediaView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeneratedMediaView.swift; sourceTree = ""; }; A1DE79294A568DC5DD50BBD6 /* AppsHubView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppsHubView.swift; sourceTree = ""; }; @@ -3755,6 +3768,7 @@ B2134123E3894BA3AE1CCD71 /* WorkflowRunStageSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkflowRunStageSheet.swift; sourceTree = ""; }; B21A4DAF16C06699A239D845 /* ChatReplyUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatReplyUITests.swift; sourceTree = ""; }; B22571E8F505DF1823F34C87 /* ChatMessageShareSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatMessageShareSheet.swift; sourceTree = ""; }; + B25ED3C7FF7ACD0A9E03FDAA /* BighelpAlertReply.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpAlertReply.swift; sourceTree = ""; }; B2959D3C5D33528BE75E28D0 /* ReminderLocationTriggerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReminderLocationTriggerTests.swift; sourceTree = ""; }; B2A0A50A767F97777ED5B33F /* AvatarFaceStudio.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvatarFaceStudio.swift; sourceTree = ""; }; B2A535EE66D55EF262F77F84 /* ConnectorLogoSVG.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectorLogoSVG.swift; sourceTree = ""; }; @@ -3791,6 +3805,7 @@ B626CC553921E60F230F7A70 /* ReferenceSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReferenceSnapshot.swift; sourceTree = ""; }; B63050DDDB07FF271C12047D /* BighelpShare.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = BighelpShare.entitlements; sourceTree = ""; }; B6429B1FDB55AEF47256F94B /* LinkPreviewStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LinkPreviewStore.swift; sourceTree = ""; }; + B64D0E4C69A56D35D32B1E10 /* BighelpActivityDecision.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpActivityDecision.swift; sourceTree = ""; }; B657E4B774D2DA98DB27151E /* ChatReactionBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatReactionBar.swift; sourceTree = ""; }; B6661D7BF22ADC5D3BD94B36 /* BighelpThemePresetPalettes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpThemePresetPalettes.swift; sourceTree = ""; }; B690494F7B38ED09DBF3EF95 /* DraftAttachmentRailUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DraftAttachmentRailUITests.swift; sourceTree = ""; }; @@ -3881,6 +3896,7 @@ C092C3BB9D2A2FEE279DC7CF /* valid-form.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "valid-form.json"; sourceTree = ""; }; C0AC1DBD645E9917893BC329 /* WorkspaceCapabilityWireModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceCapabilityWireModels.swift; sourceTree = ""; }; C0D3B38A3BDBBA33B939C4C1 /* BighelpWorkflowsWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpWorkflowsWidget.swift; sourceTree = ""; }; + C1114608474A869B664B1723 /* BighelpIslandMoment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpIslandMoment.swift; sourceTree = ""; }; C130A87556531870129AFB11 /* CatalogStorefrontUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CatalogStorefrontUITests.swift; sourceTree = ""; }; C1821BF710F8D5387ABCAB46 /* DeviceToolHandoff.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceToolHandoff.swift; sourceTree = ""; }; C1AEC5E55113E285DDB16191 /* GeminiLiveEchoGateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeminiLiveEchoGateTests.swift; sourceTree = ""; }; @@ -3940,6 +3956,7 @@ C7F0E6A28B2BDF60EFA57809 /* BighelpLandingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpLandingTests.swift; sourceTree = ""; }; C7F3009E78870A5880C0A883 /* ComposioSignInHostUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposioSignInHostUITests.swift; sourceTree = ""; }; C820C988D3FE3D2A125EA670 /* AgentDuplicateModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentDuplicateModelTests.swift; sourceTree = ""; }; + C86554BC06175E4863F33254 /* ChatOutsideActions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatOutsideActions.swift; sourceTree = ""; }; C8D36C2E6E629486BCF40734 /* ChatTurnFailure.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatTurnFailure.swift; sourceTree = ""; }; C8DBAFF188A8ED30640E5BE2 /* bighelp-lifter-error-dark.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "bighelp-lifter-error-dark.json"; sourceTree = ""; }; C8DDCF35895C5D425D298524 /* LiveVoiceCallContext.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveVoiceCallContext.swift; sourceTree = ""; }; @@ -4622,6 +4639,7 @@ 51D769A3504F32207EA002CF /* BighelpQuietHours.swift */, 901D2828E64091858D603134 /* BighelpScheduledAlertLinks.swift */, 76DECB1180E7EB7CD9EDDDF1 /* BighelpVisibleChats.swift */, + C86554BC06175E4863F33254 /* ChatOutsideActions.swift */, ); path = Notifications; sourceTree = ""; @@ -5407,6 +5425,7 @@ 8AE5A2AB78BBDB43F0291669 /* BighelpActivityShared */ = { isa = PBXGroup; children = ( + B64D0E4C69A56D35D32B1E10 /* BighelpActivityDecision.swift */, 4CF32CA404AC85688FA54FCF /* BighelpActivityDetail.swift */, B82073CABF9477908D2AF2A7 /* BighelpActivityHeroView.swift */, CD81C509ADE4E67B19BA9F6E /* BighelpActivityPose.swift */, @@ -5417,6 +5436,7 @@ 7E3F7BC4DE0D166012849DBB /* BighelpBoardWidgets.swift */, 00F2E8F0C9FD53FCF9A4CDD5 /* BighelpBotsWidget.swift */, 16B85BE01827FCFD38480171 /* BighelpHomeWidgets.swift */, + C1114608474A869B664B1723 /* BighelpIslandMoment.swift */, 8540B54D37AC7754A2D6B4AB /* BighelpKanbanWidget.swift */, F1FF50374D94C106E4CE34A4 /* BighelpPinnedAgentsWidget.swift */, 69316E6086691BDD2C164048 /* BighelpSessionActivityAttributes.swift */, @@ -5452,6 +5472,7 @@ 015D146A996F9F8372C8D7D5 /* BighelpLiveActivityProjection.swift */, D6C798268B143E4AAB61400C /* BighelpLiveActivityWorkReducer.swift */, D9BDE066016389C9FFF8D00F /* BighelpPhysicalActivityTokenRegistrar.swift */, + A191699C5E52C57BA6D32BC6 /* IslandMomentPreview.swift */, ); path = LiveActivity; sourceTree = ""; @@ -5662,6 +5683,7 @@ 07F358B0F3EFF0113D2718C2 /* AgentTodayDetailTests.swift */, A15863BCEAD74614DD39B039 /* AgentVoiceChoicesTests.swift */, B5B9F82EEB2541BEE9642460 /* AIDataConsentTests.swift */, + 2FCAEFB8B77DA001E3EDD520 /* AlertReplyTests.swift */, 568BD9C6A4BF6FE13070369B /* AppearanceChoicesTests.swift */, 97E85DBCBB8DDC592F728728 /* AppleDeviceToolServiceTests.swift */, 523FAEE099C696A0EB986626 /* ApprovalModelTests.swift */, @@ -5951,6 +5973,7 @@ 0833D7454B06F1305F80A2ED /* IMessageThemeContractTests.swift */, 5FA3C250CDD715840DD68725 /* IncomingChatLinkTests.swift */, 93BCA75E13D979E7977DE481 /* IndependentHostScopeTests.swift */, + 2B72C56885C1D313E00DA5D8 /* IslandMomentTests.swift */, BD70C77DE16F0C5CDD82DD3E /* KanbanAvailabilityTests.swift */, F1DB559BCA138130360AAB97 /* KanbanBoardModelTests.swift */, B471C653B70E1EF7F99BDB67 /* KanbanFailureTests.swift */, @@ -6441,6 +6464,7 @@ B157E21E0D86C4C23FB845C4 /* NotificationShared */ = { isa = PBXGroup; children = ( + B25ED3C7FF7ACD0A9E03FDAA /* BighelpAlertReply.swift */, 7B73DAC3DFA07E9D022CB02F /* BighelpDeliveryReceipts.swift */, 317F3D4090FD79701E7E1B7A /* BighelpFocusFilterState.swift */, 1B427CDEAC6F712A67C5AA1F /* BighelpNotificationDelivery.swift */, @@ -8100,6 +8124,7 @@ 45A1B9EFBC1874E4533590DB /* BigFileUploader.swift in Sources */, BA5D3D6B994FAFB24B41C1DB /* BighelpActionRow.swift in Sources */, C735199075D3BBC19A3DC669 /* BighelpActivityAvatarWriter.swift in Sources */, + DE2E797EEA5F52CC2637B2D3 /* BighelpActivityDecision.swift in Sources */, 55DFD8B1447208EC786FF539 /* BighelpActivityDetail.swift in Sources */, 39736130B7C4759EBD2AE919 /* BighelpActivityGroupDriver.swift in Sources */, 6D176BFE206362441C47FFAB /* BighelpActivityHeroView.swift in Sources */, @@ -8109,6 +8134,7 @@ 4122539152FD6C26ACEA61D2 /* BighelpActivitySession.swift in Sources */, F9EBB12A3071788BA831F1CC /* BighelpAgentWidget.swift in Sources */, F2E02C1A22EAC238986DFFC0 /* BighelpAlarmActivity.swift in Sources */, + 275A1A84B3CAF2442FBC1F31 /* BighelpAlertReply.swift in Sources */, A171D079DE792AA74DBF8719 /* BighelpApp.swift in Sources */, E8415FDA5F5475B0D6AEE296 /* BighelpAppBotsState.swift in Sources */, 740571327FB47B4F812C1992 /* BighelpAppComposition.swift in Sources */, @@ -8164,6 +8190,7 @@ 62E58EC17E3B0D20B42DFCE7 /* BighelpIncomingURLRoute.swift in Sources */, EA863FA5A7E38EBC70B27301 /* BighelpInlineModelChooser.swift in Sources */, A2764BB3B14DB368B13E03A8 /* BighelpInterfaceSize.swift in Sources */, + E5F1B9F3654CC6CF51626582 /* BighelpIslandMoment.swift in Sources */, 3F9B09435FB28A088F244847 /* BighelpJSONValue.swift in Sources */, BAC7A7264B21154E2BE3A626 /* BighelpKanbanWidget.swift in Sources */, BF1317AAEB15EF97C75FCF70 /* BighelpKeyboard.swift in Sources */, @@ -8431,6 +8458,7 @@ DE5B4700D25B828CB4E201C2 /* ChatNativeMarkdownRendering.swift in Sources */, 1510B5AFB84C82A2064A382F /* ChatNativeMarkdownTextView.swift in Sources */, E64170A092AE47599073DA7A /* ChatNewChatSlot.swift in Sources */, + 24D93F8CC1819D1B5A6179AD /* ChatOutsideActions.swift in Sources */, 6E58E9FB4DCCE110FA2FE5DB /* ChatPDFPagesDraft.swift in Sources */, 88D7FEFF96EAFC31CC02B57C /* ChatPendingCardView.swift in Sources */, 0799B9446E83D23984F3E275 /* ChatPerformanceProbe.swift in Sources */, @@ -8813,6 +8841,7 @@ CDB6A3B34919A1827792AE09 /* ImageDraftWriteFence.swift in Sources */, EBA983EFC7F728A8F947CAA0 /* ImageDraftsClient.swift in Sources */, AB37CC3BE76F45E6D345BD2F /* ImageDraftsFixture.swift in Sources */, + 34B81802B8A4F5168F6F2BEF /* IslandMomentPreview.swift in Sources */, 1210FA290293C238A6C1F377 /* IslandStage.swift in Sources */, 307E2A2936B6EB808B7E7C7B /* KanbanAdministrationModels.swift in Sources */, 486C974071404BED690FA982 /* KanbanAdministrationView.swift in Sources */, @@ -9316,6 +9345,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + BB1675622CE87341BBD94728 /* BighelpAlertReply.swift in Sources */, ED10D771E70A26E20EDEE0EA /* BighelpDeliveryReceipts.swift in Sources */, 3AA6E7EAA99FD6C034F8A654 /* BighelpFocusFilterState.swift in Sources */, 288E2E677E3BACBB2C12CF25 /* BighelpNotificationDelivery.swift in Sources */, @@ -9383,6 +9413,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + EE788BD9231A0AE90FB392DB /* BighelpActivityDecision.swift in Sources */, 8372672BD6FE98E203AC89DA /* BighelpActivityDetail.swift in Sources */, 7652995B7D6B0A649E0449BE /* BighelpActivityHeroView.swift in Sources */, 008C54331AC97F43C96F1AC4 /* BighelpActivityPose.swift in Sources */, @@ -9394,6 +9425,7 @@ CF5BBABB155B59EF0DD63373 /* BighelpBoardWidgets.swift in Sources */, 17A89C342173BE53DF58A8AB /* BighelpBotsWidget.swift in Sources */, B665E162FA1BACCA4168073B /* BighelpHomeWidgets.swift in Sources */, + 096C9C082BDDE56DCC8335E7 /* BighelpIslandMoment.swift in Sources */, A4C2A472F47C2ACFBAAFDC50 /* BighelpKanbanWidget.swift in Sources */, 1A315D6D7B38C1DED76F92FE /* BighelpLiveActivityBundle.swift in Sources */, 30B888ABB8A97DAE12A5DF65 /* BighelpPinnedAgentsWidget.swift in Sources */, @@ -9466,6 +9498,7 @@ 94143673BB126A24786419D0 /* AgentTodayDetailTests.swift in Sources */, C10B5B01C96C2D77B0842124 /* AgentVoiceChoicesTests.swift in Sources */, 334C431DA1A5A6AA749BF53A /* AgentsPresentationTests.swift in Sources */, + 3A749C2A4ED92C1D3F602211 /* AlertReplyTests.swift in Sources */, A929D78738AA73BFD2F5AF0B /* AppStateSyncTests.swift in Sources */, 5FD9F0F18BD763BC16E0B9D1 /* AppStateTests.swift in Sources */, 6840E53D10369DC672943D96 /* AppearanceChoicesTests.swift in Sources */, @@ -9755,6 +9788,7 @@ 94764A8C0B1F66F20798B9C4 /* ImageDraftsClientTests.swift in Sources */, E4F06C54D7E5C01E36870064 /* IncomingChatLinkTests.swift in Sources */, 2F46E2D89A7FE9EEB8068E01 /* IndependentHostScopeTests.swift in Sources */, + 051F55E3EC6657F82AFBB275 /* IslandMomentTests.swift in Sources */, 8A5B2DD7632882A15FAFD471 /* KanbanAvailabilityTests.swift in Sources */, E2B771B30C555C4A476D2426 /* KanbanBoardModelTests.swift in Sources */, 118E64EF7A92C0A500B827B6 /* KanbanFailureTests.swift in Sources */, diff --git a/Bighelp/App/AppState.swift b/Bighelp/App/AppState.swift index 91c12426..70327b47 100644 --- a/Bighelp/App/AppState.swift +++ b/Bighelp/App/AppState.swift @@ -41,6 +41,8 @@ final class AppState { /// because the person stepped out of its chat. var deviceToolConversationID: String? { activatedConversationID } private(set) var pendingVoiceConversationID: String? + /// The chat whose message box takes the keyboard as it opens (the island's Reply). + private(set) var pendingReplyConversationID: String? /// Text a board "Ask" or "Discuss" leaves in the next new chat's composer. var pendingComposerText: String? /// The open chat's agent and text when the app left, while that chat had sent nothing. @@ -180,6 +182,17 @@ final class AppState { pendingVoiceConversationID = conversationID } + func requestReply(in conversationID: String) { + pendingReplyConversationID = conversationID + } + + @discardableResult + func consumeReplyRequest(for conversationID: String) -> Bool { + guard pendingReplyConversationID == conversationID else { return false } + pendingReplyConversationID = nil + return true + } + /// Another computer: its pages close and the tab stays. The connections screen stays up while /// you switch computers from it. func resetForHostBoundary() { @@ -187,6 +200,7 @@ final class AppState { if !showsOnlyConnections { path.removeAll() } activatedConversationID = nil pendingVoiceConversationID = nil + pendingReplyConversationID = nil clearComposerText() dropPendingShare() } @@ -195,6 +209,7 @@ final class AppState { path.removeAll() activatedConversationID = nil pendingVoiceConversationID = nil + pendingReplyConversationID = nil clearComposerText() dropPendingShare() } @@ -301,3 +316,19 @@ struct PendingShareHandoff: Identifiable { /// No chat took it (a host or account change, or it waited too long); it's offered again. let onDropped: @MainActor (String) -> Void } + +/// "Reply" on the Dynamic Island opens a chat and asks for the keyboard. The link names a Live +/// Activity row, and the chat it stands for is known only once the shell opens it, so the request +/// waits here for that open. It is good for a short time: an open that comes later is another tap. +@MainActor +enum ChatReplyRequest { + private static var notedAt: Date? + + static func note(at date: Date = .now) { notedAt = date } + + static func take(at date: Date = .now) -> Bool { + defer { notedAt = nil } + guard let notedAt else { return false } + return date.timeIntervalSince(notedAt) >= 0 && date.timeIntervalSince(notedAt) < 10 + } +} diff --git a/Bighelp/App/BighelpApp.swift b/Bighelp/App/BighelpApp.swift index af55800a..69eda8fa 100644 --- a/Bighelp/App/BighelpApp.swift +++ b/Bighelp/App/BighelpApp.swift @@ -310,6 +310,8 @@ struct BighelpApp: App { registry: hostRegistry ) _notificationComposition = State(initialValue: notificationComposition) + Self.configureOutsideActions(composition.shortcutService, hostRegistry: hostRegistry, + notifications: notificationComposition) let priorNativeEvent = hostRegistry.onNativeEvent hostRegistry.onNativeEvent = { [weak nativeWorkspaces, weak notificationComposition] host, event in @@ -348,6 +350,9 @@ struct BighelpApp: App { shortcutService = composition.shortcutService #if DEBUG BighelpShortcutAskProbe.runIfRequested(composition.shortcutService) + #if os(iOS) && !targetEnvironment(macCatalyst) + IslandMomentPreview.runIfRequested() + #endif #endif _reflectiveVisionCamera = State(initialValue: ReflectiveVisionCamera()) usesDemoFixtures = composition.usesDemoFixtures @@ -435,6 +440,32 @@ struct BighelpApp: App { } #endif + /// A reply typed on an alert and the island's Approve and Deny reach the computer through the + /// same live host as Shortcuts, so they work with Bighelp closed. + private static func configureOutsideActions(_ shortcuts: BighelpShortcutService, hostRegistry: BighelpHostRegistry, + notifications: BighelpManagedNotificationComposition) { + var actions = ChatOutsideActions( + connect: { try await shortcuts.connectedWorkspace() }, + selectedHostID: { [weak hostRegistry] in hostRegistry?.selectedHostID }, + selectHost: { id in (try? shortcuts.useGateway(id)) != nil }) + // An action can be what started the app: the saved notification setup may load a moment later. + @MainActor func service() async -> BighelpManagedNotificationService? { + for _ in 0..<20 { + if let service = notifications.service { return service } + try? await Task.sleep(for: .milliseconds(250)) + } + return notifications.service + } + actions.alertTarget = { open in await service()?.outsideTarget(for: open) } + actions.rowTarget = { rowID in await service()?.outsideTarget(opaqueSessionID: rowID) } + ChatOutsideActions.shared = actions + #if os(iOS) && !targetEnvironment(macCatalyst) + BighelpActivityActions.decide = { rowID, approves, command in + await ChatOutsideActions.shared?.receiveDecision(rowID: rowID, approves: approves, command: command) + } + #endif + } + #if os(iOS) /// CarPlay's voice chat talks through the same live host as Shortcuts; /// demo runs use the local fixtures. diff --git a/Bighelp/App/BighelpIncomingURLRoute.swift b/Bighelp/App/BighelpIncomingURLRoute.swift index eb648497..ea1fce09 100644 --- a/Bighelp/App/BighelpIncomingURLRoute.swift +++ b/Bighelp/App/BighelpIncomingURLRoute.swift @@ -35,6 +35,13 @@ enum BighelpIncomingURLRoute: Equatable, Sendable { /// "loopdy://usage": Usage, from the Usage widget. case usage + /// The island's Reply: a chat link that also asks for the keyboard (`BighelpWidgetSnapshot.chatURL`). + static func asksForReply(_ url: URL) -> Bool { + guard case .chat? = parse(url) else { return false } + return URLComponents(url: url, resolvingAgainstBaseURL: false)? + .queryItems?.contains { $0.name == "reply" && $0.value == "1" } == true + } + static func parse(_ url: URL) -> BighelpIncomingURLRoute? { let scheme = url.scheme?.lowercased() guard scheme == "loopdy" || scheme == "app.loopdy.mobile" else { return nil } diff --git a/Bighelp/App/ChatDestinationView.swift b/Bighelp/App/ChatDestinationView.swift index f0b7eb1d..e0e111b0 100644 --- a/Bighelp/App/ChatDestinationView.swift +++ b/Bighelp/App/ChatDestinationView.swift @@ -709,6 +709,10 @@ struct ChatDestinationView: View { if pending.fillsBlanks, model.beginBlueprintDraft(pending.text) { return } model.draft = pending.text } + .task(id: appState.pendingReplyConversationID) { + guard appState.consumeReplyRequest(for: model.conversationID) else { return } + attachmentFlow.composerFocusRequest &+= 1 + } .task(id: appState.pendingVoiceConversationID) { // The request stays until voice can open, so withdrawing it (another computer, another // screen) cancels this wait. diff --git a/Bighelp/App/RootShellView.swift b/Bighelp/App/RootShellView.swift index 6f50a47b..9d8947c4 100644 --- a/Bighelp/App/RootShellView.swift +++ b/Bighelp/App/RootShellView.swift @@ -1153,6 +1153,7 @@ struct RootShellView: View { // approvals and questions now live in the bot's chat. openPrimaryBotChat() case .chat(let sessionID): + if BighelpIncomingURLRoute.asksForReply(url) { ChatReplyRequest.note() } openIncomingChat(sessionID: sessionID) case .agent(let tab, let agentID): // From the Watch and the widgets: that bot's Feed, Ideas or Goals over Today. The @@ -1489,6 +1490,8 @@ struct RootShellView: View { func openSession(_ session: SessionSummary) { let route = AppRoute.chat(conversationID: session.id) + // The island's Reply: this chat's message box takes the keyboard once it shows. + if ChatReplyRequest.take() { appState.requestReply(in: session.id) } let simpleBotsOpening = beginSimpleBotsChatOpening(session) defer { noteSimpleBotsChatOpened(simpleBotsOpening, route: route) } // On screen already (a notification or link about it): keep it as it is, any load it diff --git a/Bighelp/Link/BighelpLinkApplePush.swift b/Bighelp/Link/BighelpLinkApplePush.swift index 9fc1db91..59a194f7 100644 --- a/Bighelp/Link/BighelpLinkApplePush.swift +++ b/Bighelp/Link/BighelpLinkApplePush.swift @@ -303,14 +303,14 @@ final class BighelpLinkApplicationDelegate: NSObject, UIApplicationDelegate, ) -> Bool { let center = UNUserNotificationCenter.current() center.delegate = self - center.setNotificationCategories([ + center.setNotificationCategories(BighelpAlertReply.categories.union([ UNNotificationCategory( identifier: BighelpProactiveNotificationRequest.categoryIdentifier, actions: [], intentIdentifiers: [], options: [] ), - ]) + ])) // Configure only after bighelp installs its delegate so BuzzKit captures and // forwards to it. Missing injected configuration remains a truthful state. _ = BighelpBuzzKitRuntime.shared.configureIfPossible() @@ -353,6 +353,24 @@ final class BighelpLinkApplicationDelegate: NSObject, UIApplicationDelegate, if response.actionIdentifier == UNNotificationDefaultActionIdentifier { Telemetry.featureUsed(.notificationOpened) } + // Words typed on the alert go to its chat with the app still closed. iOS gets its answer + // once they are sent, which keeps the app running until then. + if response.actionIdentifier == BighelpAlertReply.actionID { + let content = response.notification.request.content + let text = (response as? UNTextInputNotificationResponse)?.userText ?? "" + let alert = BighelpProactiveNotificationOpen(userInfo: content.userInfo) + let agentName = content.title, thread = content.threadIdentifier + Task { @MainActor in + if let actions = ChatOutsideActions.shared { + await actions.receiveReply(text, alert: alert, agentName: agentName, thread: thread) + } else { + // Never drop the words without a word. + await ChatOutsideNotice.post(.unavailable, text: text, agentName: agentName, thread: thread) + } + completionHandler() + } + return + } // A question or approval alert opens its chat, where the request pops up. if response.actionIdentifier == UNNotificationDefaultActionIdentifier, let url = BighelpPromptAlertLink.url(in: response.notification.request.content.userInfo) { diff --git a/Bighelp/LiveActivity/IslandMomentPreview.swift b/Bighelp/LiveActivity/IslandMomentPreview.swift new file mode 100644 index 00000000..c955342e --- /dev/null +++ b/Bighelp/LiveActivity/IslandMomentPreview.swift @@ -0,0 +1,69 @@ +#if DEBUG && os(iOS) && !targetEnvironment(macCatalyst) +import ActivityKit +import CryptoKit +import UIKit + +/// `-test-island-moment command|approval|question|done|failed` (with the demo data): a card whose one +/// chat has news, and the alert that opens the Dynamic Island for it, for screenshots and for a look +/// on a phone. The real alert comes in a push from the notification service, which a simulator can't +/// receive; ActivityKit's own alert opens the island the same way. The update goes a few seconds +/// after launch, so there is time to leave the app: iOS hides an app's own card while it is in front. +@MainActor +enum IslandMomentPreview { + static let launchArgument = "-test-island-moment" + + private static let details: [String: (phase: LoopdySessionActivityAttributes.ContentState.Phase, detail: String, alert: String)] = [ + "command": (.waiting, #""q":"rm -rf build/cache","a":"c""#, "A chat needs you."), + "approval": (.waiting, #""q":"Deletes the old builds and their caches from three folders","a":"a""#, "A chat needs you."), + "question": (.waiting, #""q":"Can I delete the 14 old drafts in Notes, Archive?","a":"q""#, "A chat needs you."), + "done": (.completed, #""p":"Booked the 7:40 train to Leeds and put it in your calendar. The return is open until Friday.""#, "A chat finished."), + "failed": (.failed, #""p":"The airline site asked for a sign-in I don't have. Your search is saved.""#, "A chat could not finish."), + ] + + static func runIfRequested(arguments: [String] = ProcessInfo.processInfo.arguments) { + guard arguments.contains("-use-demo-fixtures"), let index = arguments.firstIndex(of: launchArgument), + arguments.indices.contains(index + 1), let moment = details[arguments[index + 1]] else { return } + let rowID = "native-" + String(repeating: "ab", count: 32) + let started = Int(Date.now.timeIntervalSince1970) + var attributes = LoopdySessionActivityAttributes(sessionID: rowID, sessionTitle: "Active chat", + agentID: "scout", agentName: "Scout") + BighelpActivitySessionInfo.save([rowID: .init(attributes: attributes, title: "Weekend trip")]) + attributes.cardKey = BighelpActivityCardKey.attributeKey() + let background = UIApplication.shared.beginBackgroundTask(withName: "Island moment preview") + let phase = moment.phase, detail = moment.detail, alert = moment.alert + Task.detached { + await play(rowID: rowID, started: started, attributes: attributes, phase: phase, detail: detail, alert: alert) + await MainActor.run { UIApplication.shared.endBackgroundTask(background) } + } + } + + /// Off the main actor: an `Activity` isn't sendable, so one task makes it and changes it. + nonisolated private static func play(rowID: String, started: Int, attributes: LoopdySessionActivityAttributes, + phase: LoopdySessionActivityAttributes.ContentState.Phase, + detail: String, alert: String) async { + let working = BighelpActivitySession.aggregate([.init(id: rowID, phase: .usingTool, timestamp: started)], timestamp: started) + guard let activity = try? Activity.request( + attributes: attributes, + content: ActivityContent(state: working, staleDate: Date(timeIntervalSince1970: TimeInterval(started + 120))), + pushType: nil) else { return } + try? await Task.sleep(for: .seconds(7)) + let timestamp = Int(Date.now.timeIntervalSince1970) + var row = BighelpActivitySession(id: rowID, phase: phase, timestamp: timestamp) + if let master = BighelpActivityCardKey.master(create: true), + let box = try? AES.GCM.seal(Data(#"{"v":1,"b":\#(started - 240),"s":9,\#(detail)}"#.utf8), + using: BighelpActivityCardKey.rowKey(rowID, master: master), + authenticating: Data("bighelp-card-v1|\(timestamp)".utf8)), + let combined = box.combined { + row.sealed = BighelpActivityDetail.encode(combined) + } + var state = BighelpActivitySession.aggregate([row], timestamp: timestamp) + state.sessions = [row] + state.lead = rowID + await activity.update( + ActivityContent(state: state, staleDate: Date(timeIntervalSince1970: TimeInterval(timestamp + 120))), + alertConfiguration: AlertConfiguration(title: "Bighelp", body: LocalizedStringResource(stringLiteral: alert), sound: .default)) + try? await Task.sleep(for: .seconds(40)) + await activity.end(nil, dismissalPolicy: .immediate) + } +} +#endif diff --git a/Bighelp/NotificationShared/BighelpAlertReply.swift b/Bighelp/NotificationShared/BighelpAlertReply.swift new file mode 100644 index 00000000..d016ed30 --- /dev/null +++ b/Bighelp/NotificationShared/BighelpAlertReply.swift @@ -0,0 +1,57 @@ +import Foundation +import UserNotifications + +/// A text field on an alert, the way a messaging app has one: touch and hold the alert, type, send. +/// A reply's alert takes the person's next message; a question's alert takes its answer. +/// +/// The phone adds the field itself, from the alert's kind. The push never asks for it, so an app from +/// before this never shows a field whose words it would drop. +enum BighelpAlertReply { + static let actionID = "bighelp.reply" + static let openActionID = "open" + static let replyCategory = "BIGHELP_REPLY" + static let answerCategory = "BIGHELP_ANSWER" + static let replyEvent = "session.completed" + static let questionEvent = "clarification.required" + + /// The category for an alert of this kind about one saved chat, or nil when it takes no words. + static func categoryID(for userInfo: [AnyHashable: Any]) -> String? { + // As the app reads an alert's chat (`BighelpProactiveNotificationOpen`): a grant, an event and a + // chat reference. Without them the app could not find the chat, and the field would only fail. + guard let loopdy = userInfo["loopdy"] as? [String: Any], + loopdy["grantId"] is String, loopdy["eventId"] is String, + let reference = loopdy["sessionReference"] as? String, + reference.range(of: "^[A-Za-z0-9_-]{43}$", options: .regularExpression) != nil else { return nil } + switch loopdy["eventType"] as? String { + case replyEvent: return replyCategory + case questionEvent: return answerCategory + default: return nil + } + } + + /// Both categories. The words are the person's own, so the phone must be unlocked to send them. + static var categories: Set { + func category(_ id: String, title: String, placeholder: String) -> UNNotificationCategory { + UNNotificationCategory( + identifier: id, + actions: [ + UNTextInputNotificationAction(identifier: actionID, title: title, options: [.authenticationRequired], + textInputButtonTitle: "Send", textInputPlaceholder: placeholder), + UNNotificationAction(identifier: openActionID, title: "Open chat", options: [.foreground]), + ], + intentIdentifiers: [], options: [.customDismissAction]) + } + return [category(replyCategory, title: "Reply", placeholder: "Message"), + category(answerCategory, title: "Answer", placeholder: "Your answer")] + } + + /// Puts the field on `content` when its alert takes words, registering the categories the first time. + static func add(to content: UNMutableNotificationContent, categories store: any BighelpNotificationCategoryStore) async { + guard let id = categoryID(for: content.userInfo) else { return } + content.categoryIdentifier = id + let existing = await store.categories() + let known = Set(existing.map(\.identifier)) + guard !categories.allSatisfy({ known.contains($0.identifier) }) else { return } + store.setCategories(existing.filter { $0.identifier != replyCategory && $0.identifier != answerCategory }.union(categories)) + } +} diff --git a/Bighelp/NotificationShared/BighelpNotificationProcessor.swift b/Bighelp/NotificationShared/BighelpNotificationProcessor.swift index 105321ac..ca4975b2 100644 --- a/Bighelp/NotificationShared/BighelpNotificationProcessor.swift +++ b/Bighelp/NotificationShared/BighelpNotificationProcessor.swift @@ -144,6 +144,8 @@ final class BighelpNotificationProcessor: @unchecked Sendable { let attached = await display.apply(to: content, categories: services.categories, download: services.download) { picture = attached } + // After the push's own buttons: a reply or a question takes the person's words instead. + await BighelpAlertReply.add(to: content, categories: services.categories) // A different content: until it is built, the held one stays ready to show. if let message = BighelpPushDisplay.communication(content, picture: picture) { delivery.replace(content: message) diff --git a/Bighelp/Notifications/BighelpManagedNotificationNavigation.swift b/Bighelp/Notifications/BighelpManagedNotificationNavigation.swift index 03271ec3..086485f4 100644 --- a/Bighelp/Notifications/BighelpManagedNotificationNavigation.swift +++ b/Bighelp/Notifications/BighelpManagedNotificationNavigation.swift @@ -12,6 +12,29 @@ extension EnvironmentValues { } extension BighelpManagedNotificationService { + /// The computer and chat an alert is about, for an answer given on the alert itself. Nil for an + /// alert that names no single saved chat (a scheduled run, an older alert). + @MainActor + func outsideTarget(for open: BighelpProactiveNotificationOpen) -> ChatOutsideTarget? { + guard let type = open.eventType, let reference = open.sessionReference, let profile = open.agentID, + let host = host(forEvent: open.eventID, eventType: type), + // The agent is the one this phone set alerts up for, not only the one the push names. + ledger.enrollments.contains(where: { + $0.enabled && !$0.revokePending && $0.grant?.grantId == open.hostGrantID && $0.profile == profile + }) else { return nil } + return ChatOutsideTarget(hostID: host.id, profileID: profile, chat: .reference(reference)) + } + + /// The computer and chat of a Live Activity row, for the island's buttons. + @MainActor + func outsideTarget(opaqueSessionID: String) -> ChatOutsideTarget? { + guard let owner = activityRuntime?.destination(opaqueSessionID: opaqueSessionID), + let host = registry.hosts.first(where: { + $0.hostConnectionID == owner.hostConnectionID && $0.notificationScope == owner.accountScope + }) else { return nil } + return ChatOutsideTarget(hostID: host.id, profileID: owner.profile, chat: .stored(owner.storedSessionID)) + } + /// Activity links identify a local scoped mapping, not a host supplied by URL. The tap hands /// the shell its computer, agent and exact chat; the shell opens it from its saved chats. /// Asking `session.list` first failed every Bot Chat (Hermes leaves them out) and so every diff --git a/Bighelp/Notifications/ChatOutsideActions.swift b/Bighelp/Notifications/ChatOutsideActions.swift new file mode 100644 index 00000000..45993ea2 --- /dev/null +++ b/Bighelp/Notifications/ChatOutsideActions.swift @@ -0,0 +1,311 @@ +import Foundation +import UIKit +import UserNotifications + +/// The chat an action from outside the app is for: a reply typed on an alert, or a button on the +/// Dynamic Island. It names its computer, so nothing meant for one computer's chat reaches another's. +struct ChatOutsideTarget: Equatable, Sendable { + enum Chat: Equatable, Sendable { + /// An alert's chat (`ManagedNotificationValidation.sessionReference`). + case reference(String) + /// A Live Activity row's chat, by Hermes' stored ID. + case stored(String) + } + let hostID: UUID + let profileID: String + let chat: Chat +} + +enum ChatOutsideFailure: Error, Equatable { + /// Bighelp isn't set up to do this (no computer, the AI data agreement not given, demo data). + case unavailable + /// The chat is on another computer, and the person is using the app on this one. + case otherComputerInUse + case chatGone + /// Nothing waits for an answer in the chat any more. + case nothingWaits + /// The request has to be read in the app before it gets a yes. + case mustReview + case notSent +} + +/// Picks the one request an answer from outside the app is for. +enum ChatOutsidePrompt { + /// The approval that waits in `chatID`, when it is the command the island showed (`shown`). The + /// island can stay on screen for minutes, and the bot can ask for something else meanwhile: an + /// answer is for the characters the person read, or for nothing. A yes also needs one request + /// only and a command the island shows whole. Anything else is decided in the app. + static func approval(in items: [DashboardAttentionItem], chatID: String, decision: ApprovalDecision, + shown: String, now: Date) -> Result { + let waiting = items.filter { item in + guard item.sessionID == chatID, case .approval(let request) = item.interaction else { return false } + return !request.isExpired(at: now) + } + guard let item = waiting.first else { return .failure(.nothingWaits) } + let command = item.title.trimmingCharacters(in: .whitespacesAndNewlines) + guard waiting.count == 1, case .approval(let request) = item.interaction, + request.allowedDecisions.contains(decision), + !shown.isEmpty, command == shown, + command.count <= BighelpIslandMoment.wholeCommandCharacters else { return .failure(.mustReview) } + return .success(item) + } + + /// The question that waits in `chatID`, when words alone can answer it. + static func question(in items: [DashboardAttentionItem], chatID: String, answer: String, + now: Date) -> Result { + let waiting = items.filter { item in + guard item.sessionID == chatID, case .clarification(let request) = item.interaction else { return false } + return !request.isExpired(at: now) + } + guard let item = waiting.first else { return .failure(.nothingWaits) } + guard waiting.count == 1, case .clarification(let request) = item.interaction, + request.questions.count == 1, !request.isMultiSelect, request.questions[0].lockedAnswer == nil, + request.allowsCustomResponse || request.choices.contains(answer) else { return .failure(.mustReview) } + return .success(item) + } +} + +/// Does what a person asked for from outside the app, through the Shortcuts host path, which +/// connects with Bighelp in the background. It never starts a chat, never moves a person who is +/// using the app to another computer, and never touches what they are typing. +@MainActor +struct ChatOutsideActions { + /// Set as the app starts. Nil in the Live Activity extension and in tests that don't need it. + static var shared: ChatOutsideActions? + + var connect: @MainActor () async throws -> BighelpShortcutWorkspace + var selectedHostID: @MainActor () -> UUID? + /// Makes a computer the one in use. False when it can't be. + var selectHost: @MainActor (UUID) -> Bool + var appIsActive: @MainActor () -> Bool = { UIApplication.shared.applicationState == .active } + var now: @MainActor () -> Date = { .now } + /// The chat an alert or a Live Activity row is about, from the phone's own notification setup. + /// They wait a little for that setup: an action can be the reason the app was started. + var alertTarget: @MainActor (BighelpProactiveNotificationOpen) async -> ChatOutsideTarget? = { _ in nil } + var rowTarget: @MainActor (String) async -> ChatOutsideTarget? = { _ in nil } + var notify: @MainActor (ChatOutsideFailure, _ text: String?, _ agentName: String?, _ thread: String) async -> Void = { + await ChatOutsideNotice.post($0, text: $1, agentName: $2, thread: $3) + } + /// iOS gives an action from outside the app about half a minute. The work stops before that, so + /// the person is told what didn't go instead of the app being ended with nothing said. + var limit: Duration = .seconds(24) + + /// Words typed on an alert: an answer to its question, or the person's next message in its chat. + /// Anything that doesn't go is said on the phone, with the words. + func receiveReply(_ text: String, alert: BighelpProactiveNotificationOpen?, agentName: String?, thread: String) async { + let words = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !words.isEmpty else { return } + let failure = await Self.inTurn(limit: limit) { + guard let alert, let target = await alertTarget(alert) else { throw ChatOutsideFailure.chatGone } + if alert.eventType == BighelpAlertReply.questionEvent { + try await answer(words, to: target) + } else { + try await reply(words, to: target) + } + } + if let failure { await notify(failure, words, agentName, thread) } + } + + /// Approve or Deny on the island, for the command it showed. + func receiveDecision(rowID: String, approves: Bool, command: String) async { + let failure = await Self.inTurn(limit: limit) { + guard let target = await rowTarget(rowID) else { throw ChatOutsideFailure.chatGone } + try await decide(approves: approves, command: command, in: target) + } + if let failure { await notify(failure, nil, nil, rowID) } + } + + /// iOS gives an alert's action about half a minute in all, so the wait for the reply to start is short. + private static let replyGrace = Duration.seconds(5) + + /// Sends `text` into the chat as the person's next message. A running turn takes it as a steer. + func reply(_ text: String, to target: ChatOutsideTarget) async throws { + try await holdingConnection { + let (workspace, chatID) = try await chat(target) + let agentID = workspace.catalog.session(id: chatID)?.agentIDs.first ?? target.profileID + guard try await workspace.sendFromOutside(text, chatID: chatID, agentID: agentID, replyGrace: Self.replyGrace) else { + throw ChatOutsideFailure.notSent + } + } + } + + /// Answers the question that waits in the chat. With no question waiting any more, the words go as a + /// message instead: the person still meant them for this chat. + func answer(_ text: String, to target: ChatOutsideTarget) async throws { + let answer = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !answer.isEmpty else { throw ChatOutsideFailure.notSent } + try await holdingConnection { + let (workspace, chatID) = try await chat(target) + let dashboard = workspace.featureStore.dashboardModel + await dashboard.refreshAfterExternalChange() + switch ChatOutsidePrompt.question(in: dashboard.snapshot?.attentionItems ?? [], chatID: chatID, + answer: answer, now: now()) { + case .success(let item): + await dashboard.respondToClarification(itemID: item.id, response: answer) + guard dashboard.snapshot?.attentionItems.contains(where: { $0.id == item.id }) != true else { + throw ChatOutsideFailure.notSent + } + case .failure(.nothingWaits): + let agentID = workspace.catalog.session(id: chatID)?.agentIDs.first ?? target.profileID + guard try await workspace.sendFromOutside(answer, chatID: chatID, agentID: agentID, replyGrace: Self.replyGrace) else { + throw ChatOutsideFailure.notSent + } + case .failure(let failure): + throw failure + } + } + } + + /// Approves once, or denies, the command that waits in the chat, when it is the one `command` names. + func decide(approves: Bool, command: String, in target: ChatOutsideTarget) async throws { + try await holdingConnection { + let (workspace, chatID) = try await chat(target) + let dashboard = workspace.featureStore.dashboardModel + await dashboard.refreshAfterExternalChange() + let decision: ApprovalDecision = approves ? .once : .deny + let item = try ChatOutsidePrompt.approval(in: dashboard.snapshot?.attentionItems ?? [], chatID: chatID, + decision: decision, shown: command, now: now()).get() + await dashboard.respondToApproval(itemID: item.id, decision: decision) + guard dashboard.snapshot?.attentionItems.contains(where: { $0.id == item.id }) != true else { + throw ChatOutsideFailure.notSent + } + } + } + + // MARK: One at a time, and not for ever + + private static var last: Task? + + /// The first answer wins: the work's own, or the time limit's. + private final class Once { + private var continuation: CheckedContinuation? + init(_ continuation: CheckedContinuation) { self.continuation = continuation } + func finish(_ failure: ChatOutsideFailure?) { + continuation?.resume(returning: failure) + continuation = nil + } + } + + /// Runs `work` after the action before it, and for `limit` at most. Two actions at once could each + /// change the computer in use under the other. Returns what went wrong, or nil. + private static func inTurn(limit: Duration, _ work: @escaping @MainActor () async throws -> Void) async -> ChatOutsideFailure? { + let before = last + let run = Task { @MainActor () -> ChatOutsideFailure? in + await before?.value + let job = Task { @MainActor () -> ChatOutsideFailure? in + do { try await work(); return nil } catch { return error as? ChatOutsideFailure ?? .notSent } + } + let outcome = await withCheckedContinuation { (continuation: CheckedContinuation) in + let once = Once(continuation) + Task { @MainActor in once.finish(await job.value) } + Task { @MainActor in + try? await Task.sleep(for: limit) + // Out of time: stop the work where it can stop, and say it didn't go. + job.cancel() + once.finish(.notSent) + } + } + return outcome + } + last = Task { @MainActor in _ = await run.value } + return await run.value + } + + private func holdingConnection(_ work: @MainActor () async throws -> Void) async throws { + // The host connection stays open while the answer goes, with Bighelp in the background. + try await BighelpShortcutService.holdingHostConnection(named: "Bighelp answer") { + // The answer may use another computer than the one in use. With the app closed it does, and + // the person's own computer is put back after, so the app opens where they left it. + let before = selectedHostID() + defer { + if let before, selectedHostID() != before, !appIsActive() { _ = selectHost(before) } + } + try await work() + } + } + + /// The target's computer, connected, and the app's ID for its chat. + private func chat(_ target: ChatOutsideTarget) async throws -> (BighelpShortcutWorkspace, String) { + if selectedHostID() != target.hostID { + // Switching under a person who is using the app would move them without asking. + guard !appIsActive() else { throw ChatOutsideFailure.otherComputerInUse } + guard selectHost(target.hostID), selectedHostID() == target.hostID else { throw ChatOutsideFailure.unavailable } + } + let workspace: BighelpShortcutWorkspace + do { workspace = try await connect() } catch { throw ChatOutsideFailure.unavailable } + guard selectedHostID() == target.hostID else { throw ChatOutsideFailure.otherComputerInUse } + // Never let a message meant for one chat start another. + switch target.chat { + case .reference(let reference): + guard let record = SessionRecord.matching(reference: reference, profileID: target.profileID, + in: workspace.catalog.records) else { throw ChatOutsideFailure.chatGone } + return (workspace, record.id) + case .stored(let storedID): + if let record = SessionRecord.matching(storedID: storedID, profileID: target.profileID, + in: workspace.catalog.records) { return (workspace, record.id) } + guard let record = try? await workspace.catalog.resolveStoredSession( + profileID: target.profileID, storedSessionID: storedID) else { throw ChatOutsideFailure.chatGone } + return (workspace, record.id) + } + } +} + +extension BighelpShortcutWorkspace { + /// Sends `message` into a chat this computer holds, as a message of its own: what the person is + /// typing there and any attachments they staged stay where they are, and a running turn takes it + /// as a steer. False when it didn't go. Used with Bighelp in the background, so it waits until the + /// message is really in the chat and a little longer (`replyGrace`) for the reply to start. + func sendFromOutside(_ message: String, chatID: String, agentID: String, + replyGrace: Duration = .seconds(20)) async throws -> Bool { + // `readyChat` makes a chat when it finds none. A message from outside is for this chat or for nothing. + guard catalog.session(id: chatID) != nil else { return false } + let (_, chat) = try await readyChat(agentID: agentID, reusing: chatID) + guard chat.acceptsCardReply(message) else { return false } + let known = Set(chat.items.map(\.id)) + var finished = false + Task { @MainActor in await chat.sendCardReply(message); finished = true } + let accepted = ContinuousClock.now + .seconds(15) + while ContinuousClock.now < accepted { + if chat.failureMessage != nil { break } + if chat.items.contains(where: { !known.contains($0.id) && $0.role == .human }) { break } + try await Task.sleep(for: .milliseconds(150)) + } + guard chat.failureMessage == nil, + chat.items.contains(where: { !known.contains($0.id) && $0.role == .human }) else { return false } + // The host answers on its own; stay connected a little for the reply to start. + let grace = ContinuousClock.now + replyGrace + while !finished, ContinuousClock.now < grace { try await Task.sleep(for: .milliseconds(150)) } + featureStore.flushChatPersistence() + return true + } +} + +/// Tells the person, with an alert on the phone, that something they did outside the app didn't go +/// through. Their words are in it, so nothing they typed is lost. +enum ChatOutsideNotice { + static func body(for failure: ChatOutsideFailure, text: String?) -> String { + let reason = switch failure { + case .unavailable, .notSent: "Bighelp couldn't reach the computer." + case .otherComputerInUse: "That chat is on another computer." + case .chatGone: "That chat isn't on this phone any more." + case .nothingWaits: "Nothing is waiting for an answer there now." + case .mustReview: "This one needs a look in Bighelp first." + } + guard let text = text?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty else { + return "\(reason) Open Bighelp to answer." + } + return "\(reason) Open Bighelp to send it: “\(String(text.prefix(300)))”" + } + + @MainActor + static func post(_ failure: ChatOutsideFailure, text: String?, agentName: String?, thread: String) async { + let content = UNMutableNotificationContent() + content.title = text == nil ? "Not answered" : "Not sent" + if let agentName, !agentName.isEmpty { content.subtitle = agentName } + content.body = body(for: failure, text: text) + content.threadIdentifier = thread + content.sound = .default + try? await UNUserNotificationCenter.current().add( + UNNotificationRequest(identifier: "bighelp.outside." + UUID().uuidString, content: content, trigger: nil)) + } +} diff --git a/Bighelp/Permissions/DeviceGeofenceLive.swift b/Bighelp/Permissions/DeviceGeofenceLive.swift index 50f92e72..3b28d92a 100644 --- a/Bighelp/Permissions/DeviceGeofenceLive.swift +++ b/Bighelp/Permissions/DeviceGeofenceLive.swift @@ -195,28 +195,11 @@ final class LiveDeviceGeofenceSender: DeviceGeofenceMessageSending { throw DeviceGeofenceDeliveryError.chatGone } let agentID = workspace.catalog.session(id: chatID)?.agentIDs.first ?? place.agentID - let (_, chat) = try await workspace.readyChat(agentID: agentID, reusing: chatID) - // Its own message, not the composer's: what the person is typing and any attachments they // staged stay where they are. A running turn takes it as a steer. - guard chat.acceptsCardReply(message) else { throw DeviceGeofenceDeliveryError.notSent } - let known = Set(chat.items.map(\.id)) - var finished = false - Task { @MainActor in await chat.sendCardReply(message); finished = true } - let accepted = ContinuousClock.now + .seconds(15) - while ContinuousClock.now < accepted { - if chat.failureMessage != nil { break } - if chat.items.contains(where: { !known.contains($0.id) && $0.role == .human }) { break } - try await Task.sleep(for: .milliseconds(150)) - } - guard chat.failureMessage == nil, - chat.items.contains(where: { !known.contains($0.id) && $0.role == .human }) else { + guard try await workspace.sendFromOutside(message, chatID: chatID, agentID: agentID) else { throw DeviceGeofenceDeliveryError.notSent } - // The host answers on its own; stay connected a little for the reply to start. - let grace = ContinuousClock.now + .seconds(20) - while !finished, ContinuousClock.now < grace { try await Task.sleep(for: .milliseconds(150)) } - workspace.featureStore.flushChatPersistence() } } diff --git a/BighelpActivityShared/BighelpActivityDecision.swift b/BighelpActivityShared/BighelpActivityDecision.swift new file mode 100644 index 00000000..68b59dfb --- /dev/null +++ b/BighelpActivityShared/BighelpActivityDecision.swift @@ -0,0 +1,48 @@ +// Live Activities are iPhone and iPad only, and so are their buttons. +#if os(iOS) && !targetEnvironment(macCatalyst) +import AppIntents +import Foundation + +/// What the island's Approve and Deny do. The app sets it as it starts; the Live Activity extension +/// never does, because iOS runs a Live Activity's intent in the app. +@MainActor +enum BighelpActivityActions { + static var decide: (@MainActor (_ rowID: String, _ approves: Bool, _ command: String) async -> Void)? + + static func run(rowID: String, approves: Bool, command: String) async { + await decide?(rowID, approves, command) + } +} + +/// Approve or Deny beside a command the island shows in full. It carries that command, so the answer +/// is for the characters on screen: the app refuses it when something else waits by then. It runs in +/// the app, which answers the computer over its own connection. `isDiscoverable` keeps it out of the +/// Shortcuts app, and the phone must be unlocked: a yes to a command is the person's own. +struct BighelpActivityDecisionIntent: LiveActivityIntent { + static let title: LocalizedStringResource = "Answer a request" + static let isDiscoverable = false + static let authenticationPolicy: IntentAuthenticationPolicy = .requiresAuthentication + + @Parameter(title: "Chat") + var rowID: String + + @Parameter(title: "Approve") + var approves: Bool + + @Parameter(title: "Command") + var command: String + + init() {} + + init(rowID: String, approves: Bool, command: String) { + self.rowID = rowID + self.approves = approves + self.command = command + } + + func perform() async throws -> some IntentResult { + await BighelpActivityActions.run(rowID: rowID, approves: approves, command: command) + return .result() + } +} +#endif diff --git a/BighelpActivityShared/BighelpActivityDetail.swift b/BighelpActivityShared/BighelpActivityDetail.swift index a4f037d3..b4ba8132 100644 --- a/BighelpActivityShared/BighelpActivityDetail.swift +++ b/BighelpActivityShared/BighelpActivityDetail.swift @@ -26,16 +26,27 @@ struct BighelpActivityDetail: Equatable, Sendable { var trail: [Step] = [] var say: String? var question: String? + /// What kind of answer `question` waits for. Nil from a computer that doesn't say. + var ask: Ask? var preview: String? var helperGoals: [String] = [] var contextUsed: Int? var contextWindow: Int? var model: String? + enum Ask: String, Equatable, Sendable { + /// A question the person answers in words. + case question = "q" + /// A command, and `question` is all of it: Approve and Deny may sit beside it. + case command = "c" + /// An approval whose command the card doesn't show in full: it is read in the app first. + case approval = "a" + } + private struct Wire: Decodable { struct Step: Decodable { var t: String?; var c: Int?; var n: String? } var b: Int?; var s: Int?; var t: String?; var n: String?; var tr: [Step]? - var say: String?; var q: String?; var p: String?; var h: [String]? + var say: String?; var q: String?; var a: String?; var p: String?; var h: [String]? var cu: Int?; var cm: Int?; var m: String? } @@ -57,6 +68,8 @@ struct BighelpActivityDetail: Equatable, Sendable { } say = Self.line(wire.say, 160) question = Self.line(wire.q, 200) + // A command counts as whole only as the computer wrote it: one line, nothing folded or cut. + ask = wire.a.flatMap(Ask.init(rawValue:)).map { $0 == .command && question != wire.q ? .approval : $0 } preview = Self.line(wire.p, 280) helperGoals = (wire.h ?? []).prefix(2).compactMap { Self.line($0, 60) } contextUsed = wire.cu.flatMap { $0 > 0 ? $0 : nil } diff --git a/BighelpActivityShared/BighelpActivityRowsView.swift b/BighelpActivityShared/BighelpActivityRowsView.swift index b911663d..f32657fb 100644 --- a/BighelpActivityShared/BighelpActivityRowsView.swift +++ b/BighelpActivityShared/BighelpActivityRowsView.swift @@ -19,9 +19,7 @@ struct BighelpActivityRowsView: View { @Environment(\.isLuminanceReduced) private var luminanceReduced @Environment(\.dynamicTypeSize) private var typeSize - private var ordered: [BighelpActivitySession] { - (state.sessions ?? []).filter { BighelpActivityText.coordinate($0.id, maximum: 128) != nil }.sorted { ($0.priority, $0.id) < ($1.priority, $1.id) } - } + private var ordered: [BighelpActivitySession] { BighelpActivitySession.shown(state) } private var limit: Int { typeSize.isAccessibilitySize ? min(maximumRows, 1) : maximumRows } private var activeCount: Int { max(0, state.activeCount ?? ordered.filter { !$0.phase.isTerminal }.count) } private var attentionCount: Int { ordered.filter { $0.phase == .waiting && !stale($0) }.count } diff --git a/BighelpActivityShared/BighelpActivitySession.swift b/BighelpActivityShared/BighelpActivitySession.swift index 058d667f..480c8b92 100644 --- a/BighelpActivityShared/BighelpActivitySession.swift +++ b/BighelpActivityShared/BighelpActivitySession.swift @@ -27,6 +27,13 @@ struct BighelpActivitySession: Codable, Hashable, Sendable, Identifiable { self.init(id: id, phase: state.phase, timestamp: state.timestamp, activeSubagentCount: state.activeSubagentCount, latestTool: state.latestTool) } + /// The card's rows in the order it shows them: the row with news first, then the ones that wait, + /// the ones that work and the finished ones. + static func shown(_ state: LoopdySessionActivityAttributes.ContentState) -> [Self] { + (state.sessions ?? []).filter { BighelpActivityText.coordinate($0.id, maximum: 128) != nil }.sorted { + ($0.id == state.lead ? 0 : 1, $0.priority, $0.id) < ($1.id == state.lead ? 0 : 1, $1.priority, $1.id) + } + } static func aggregate(_ rows: [Self], timestamp: Int) -> LoopdySessionActivityAttributes.ContentState { let ordered = rows.sorted { ($0.priority, $0.id) < ($1.priority, $1.id) } let running = ordered.filter { !$0.phase.isTerminal } diff --git a/BighelpActivityShared/BighelpIslandMoment.swift b/BighelpActivityShared/BighelpIslandMoment.swift new file mode 100644 index 00000000..14439e76 --- /dev/null +++ b/BighelpActivityShared/BighelpIslandMoment.swift @@ -0,0 +1,185 @@ +import SwiftUI + +/// What the open Dynamic Island shows when a chat has news: it needs the person, it finished or it +/// could not finish. The notification service opens the island for that update; a touch and hold +/// shows the same thing later. A chat that is only working keeps the plain rows. +struct BighelpIslandMoment: Equatable { + enum Kind: Equatable { case needsYou, done, failed } + + /// The buttons under the words. + enum Buttons: Equatable { + /// Deny and Approve, for a command the island shows in full. + case decide + /// An approval the person reads in the app first. + case review + /// A question, answered in the chat. + case answer + /// A finished reply: Open chat and Reply. + case reply + case open + } + + let row: BighelpActivitySession + let kind: Kind + let agentID: String + let agentName: String + /// The question, the command or the reply's first lines. Nil when the card may not show text. + let text: String? + /// The chat's title, shown when there is no text. + let title: String + let buttons: Buttons + + /// The most of a command the island shows whole, in three lines. The computer sends at most this much + /// as a whole command; the island checks again, because a yes here is a yes to what is on screen. + static let wholeCommandCharacters = 90 + + init?(state: LoopdySessionActivityAttributes.ContentState, isStale: Bool, asOf: Date = .now, + infos: [String: BighelpActivitySessionInfo], details: [String: BighelpActivityDetail]? = nil, + cardKey: String? = nil, level: BighelpActivityDetailLevel = .current) { + guard let row = BighelpActivitySession.shown(state).first else { return nil } + let kind: Kind + switch row.phase { + case .waiting: + // News that is two minutes old without a word from the computer is not news: the rows say Paused. + guard !isStale, asOf.timeIntervalSince1970 < Double(row.timestamp) + 120 else { return nil } + kind = .needsYou + case .completed: kind = .done + case .failed: kind = .failed + default: return nil + } + var detail: BighelpActivityDetail? + if level != .statusOnly { + if let details { detail = details[row.id] } else { detail = row.openDetail(cardKey: cardKey) } + } + let words = level == .stepsAndText ? (kind == .needsYou ? detail?.question : detail?.preview) : nil + let info = infos[row.id] + self.row = row + self.kind = kind + agentID = info?.attributes.agentID ?? "agent" + agentName = BighelpActivityText.personName(info?.attributes.agentName ?? "") ?? "Your bot" + title = info?.title ?? "Chat" + text = words + switch (kind, detail?.ask) { + case (.needsYou, .command?): + buttons = (words?.count ?? .max) <= Self.wholeCommandCharacters ? .decide : .review + case (.needsYou, .approval?): buttons = .review + case (.needsYou, .question?): buttons = .answer + case (.done, _): buttons = .reply + default: buttons = .open + } + } + + var status: String { + switch kind { + case .needsYou: "Needs you" + case .done: "Done" + case .failed: "Didn't finish" + } + } + + var symbolName: String { + switch kind { + case .needsYou: "questionmark.circle.fill" + case .done: "checkmark.circle.fill" + case .failed: "exclamationmark.circle.fill" + } + } + + var tint: Color { + switch kind { + case .needsYou: Color(uiColor: .systemOrange) + case .done: Color(uiColor: .systemGreen) + case .failed: Color(uiColor: .systemRed) + } + } + + var accessibilityLabel: String { + [agentName, status, text ?? title].joined(separator: ". ") + } +} + +/// The island's top row for a chat with news: whose it is, and what happened. +struct BighelpIslandMomentSender: View { + let moment: BighelpIslandMoment + + var body: some View { + HStack(spacing: 8) { + BighelpActivityAvatar(agentID: moment.agentID, name: moment.agentName, diameter: 28) + Text(moment.agentName).font(.subheadline.weight(.semibold)).lineLimit(1) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(moment.agentName) + } +} + +struct BighelpIslandMomentStatus: View { + let moment: BighelpIslandMoment + + var body: some View { + Label(moment.status, systemImage: moment.symbolName) + .font(.footnote.weight(.semibold)) + .foregroundStyle(moment.tint) + .lineLimit(1) + } +} + +/// The words and the buttons under the island's top row. The island is always black, so the colors +/// are fixed: they are the same in light and dark. +struct BighelpIslandMomentBody: View { + let moment: BighelpIslandMoment + + var body: some View { + VStack(alignment: .leading, spacing: 9) { + Link(destination: BighelpWidgetSnapshot.chatURL(moment.row.id)) { + Text(moment.text ?? moment.title) + .font(moment.buttons == .decide ? .system(.footnote, design: .monospaced) : .callout) + .foregroundStyle(moment.text == nil ? Color.secondary : Color.white) + // A command is on screen whole or Approve isn't offered, so it gets the lines it needs. + .lineLimit(moment.buttons == .decide ? 3 : 2) + .multilineTextAlignment(.leading) + .frame(maxWidth: .infinity, alignment: .leading) + } + .buttonStyle(.plain) + .accessibilityHint("Opens this conversation") + HStack(spacing: 8) { buttons } + } + // The island is about 160 points tall: text any larger than this pushes the buttons out of it. + .dynamicTypeSize(...DynamicTypeSize.xLarge) + } + + @ViewBuilder + private var buttons: some View { + switch moment.buttons { + case .decide: + #if os(iOS) && !targetEnvironment(macCatalyst) + Button(intent: BighelpActivityDecisionIntent(rowID: moment.row.id, approves: false, command: moment.text ?? "")) { label("Deny", filled: false) } + .buttonStyle(.plain) + Button(intent: BighelpActivityDecisionIntent(rowID: moment.row.id, approves: true, command: moment.text ?? "")) { label("Approve", filled: true) } + .buttonStyle(.plain) + #else + link("Review", filled: true) + #endif + case .review: link("Review", filled: true) + case .answer: link("Answer", filled: true) + case .reply: + link("Open chat", filled: false) + link("Reply", filled: true, reply: true) + case .open: link("Open chat", filled: true) + } + } + + private func link(_ title: String, filled: Bool, reply: Bool = false) -> some View { + Link(destination: BighelpWidgetSnapshot.chatURL(moment.row.id, reply: reply)) { label(title, filled: filled) } + .buttonStyle(.plain) + } + + private func label(_ title: String, filled: Bool) -> some View { + Text(title) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(filled ? Color.black : Color.white) + .lineLimit(1) + .frame(maxWidth: .infinity, minHeight: 36) + .background(filled ? AnyShapeStyle(moment.tint) : AnyShapeStyle(Color.white.opacity(0.17)), in: Capsule()) + .contentShape(Capsule()) + } +} diff --git a/BighelpActivityShared/BighelpSessionActivityAttributes.swift b/BighelpActivityShared/BighelpSessionActivityAttributes.swift index 4e81ccae..b3643329 100644 --- a/BighelpActivityShared/BighelpSessionActivityAttributes.swift +++ b/BighelpActivityShared/BighelpSessionActivityAttributes.swift @@ -33,6 +33,9 @@ struct LoopdySessionActivityAttributes: Codable, Hashable, Sendable { var sessions: [BighelpActivitySession]? = nil var activeCount: Int? = nil var activeRows: [String]? = nil + /// The row with news (it needs the person, finished or could not finish), named by the + /// notification service on the one update that opens the island for it. It is shown first. + var lead: String? = nil static func initial(agentName: String, timestamp: Int) -> ContentState { let name = BighelpActivityText.personName(agentName) ?? "Your bot" diff --git a/BighelpActivityShared/BighelpWidgetSnapshot.swift b/BighelpActivityShared/BighelpWidgetSnapshot.swift index 955c7278..995d3e17 100644 --- a/BighelpActivityShared/BighelpWidgetSnapshot.swift +++ b/BighelpActivityShared/BighelpWidgetSnapshot.swift @@ -206,9 +206,11 @@ struct BighelpWidgetSnapshot: Codable, Equatable, Sendable { } } - static func chatURL(_ sessionID: String) -> URL { + /// `reply` opens the chat with the keyboard up (the island's Reply). + static func chatURL(_ sessionID: String, reply: Bool = false) -> URL { var components = URLComponents() components.scheme = "loopdy"; components.host = "chat"; components.path = "/" + sessionID + if reply { components.queryItems = [URLQueryItem(name: "reply", value: "1")] } return components.url ?? URL(string: "loopdy://home")! } diff --git a/BighelpLiveActivity/BighelpSessionLiveActivity.swift b/BighelpLiveActivity/BighelpSessionLiveActivity.swift index 8f547756..045075b6 100644 --- a/BighelpLiveActivity/BighelpSessionLiveActivity.swift +++ b/BighelpLiveActivity/BighelpSessionLiveActivity.swift @@ -92,7 +92,10 @@ struct BighelpSessionLiveActivity: Widget { } private func sharedIsland(_ context: ActivityViewContext) -> DynamicIsland { - let rows = context.state.sessions ?? [] + let rows = BighelpActivitySession.shown(context.state) + // A chat with news takes the open island: who it is, what happened, and what to do about it. + let moment = BighelpIslandMoment(state: context.state, isStale: context.isStale, + infos: BighelpActivitySessionInfo.load(), cardKey: context.attributes.cardKey) let attention = !context.isStale && rows.contains { $0.phase == .waiting } let count = context.state.activeCount ?? rows.filter { !$0.phase.isTerminal }.count let symbol = context.isStale ? "pause.circle" : attention ? "questionmark.circle.fill" : count == 0 ? "checkmark.circle" : "circle.dashed" @@ -102,16 +105,30 @@ struct BighelpSessionLiveActivity: Widget { ? nil : rows.first.flatMap { $0.phase.isTerminal ? nil : $0.openDetail(cardKey: context.attributes.cardKey)?.tool }.map(BighelpActivityPose.init(tool:)) return DynamicIsland { DynamicIslandExpandedRegion(.leading) { - Text("Bighelp").font(.system(.caption, design: .rounded, weight: .bold)) + if let moment { + BighelpIslandMomentSender(moment: moment) + } else { + Text("Bighelp").font(.system(.caption, design: .rounded, weight: .bold)) + } } DynamicIslandExpandedRegion(.trailing) { - Text(context.isStale ? "Paused" : attention ? "Needs you" : "\(count) active") - .font(.caption.weight(.semibold)).foregroundStyle(attention ? .orange : .secondary) + if let moment { + BighelpIslandMomentStatus(moment: moment) + } else { + Text(context.isStale ? "Paused" : attention ? "Needs you" : "\(count) active") + .font(.caption.weight(.semibold)).foregroundStyle(attention ? .orange : .secondary) + } } DynamicIslandExpandedRegion(.bottom) { - BighelpActivityRowsView(state: context.state, isStale: context.isStale, maximumRows: 3, showsHeader: false, - cardKey: context.attributes.cardKey) - .padding(.vertical, 4) + if let moment { + BighelpIslandMomentBody(moment: moment) + .padding(.top, 4) + .accessibilityElement(children: .contain) + } else { + BighelpActivityRowsView(state: context.state, isStale: context.isStale, maximumRows: 3, showsHeader: false, + cardKey: context.attributes.cardKey) + .padding(.vertical, 4) + } } } compactLeading: { if let (_, info) = first { diff --git a/BighelpTests/AlertReplyTests.swift b/BighelpTests/AlertReplyTests.swift new file mode 100644 index 00000000..314058c3 --- /dev/null +++ b/BighelpTests/AlertReplyTests.swift @@ -0,0 +1,197 @@ +import Foundation +import Testing +import UserNotifications +@testable import Bighelp + +/// Which alerts take typed words, and how the field is put on them. +struct AlertReplyCategoryTests { + private final class Categories: BighelpNotificationCategoryStore, @unchecked Sendable { + private let lock = NSLock() + private var stored: Set + init(_ stored: Set = []) { self.stored = stored } + func categories() async -> Set { lock.withLock { stored } } + func setCategories(_ categories: Set) { lock.withLock { stored = categories } } + } + + private let reference = String(repeating: "r", count: 43) + + private func userInfo(_ eventType: String, reference: String? = nil) -> [AnyHashable: Any] { + var loopdy: [String: Any] = ["version": 2, "eventType": eventType, "grantId": "grant-1", "eventId": "grant-1:event"] + if let reference { loopdy["sessionReference"] = reference } + return ["loopdy": loopdy] + } + + @Test func aReplyAndAQuestionTakeWordsAndNothingElseDoes() { + #expect(BighelpAlertReply.categoryID(for: userInfo("session.completed", reference: reference)) == "BIGHELP_REPLY") + #expect(BighelpAlertReply.categoryID(for: userInfo("clarification.required", reference: reference)) == "BIGHELP_ANSWER") + #expect(BighelpAlertReply.categoryID(for: userInfo("approval.required", reference: reference)) == nil) + #expect(BighelpAlertReply.categoryID(for: userInfo("scheduled.completed", reference: reference)) == nil) + // An alert that names no chat has nowhere to send words, and a name that is no chat reference + // (an alert's stack) is not one the app could find. + #expect(BighelpAlertReply.categoryID(for: userInfo("session.completed")) == nil) + #expect(BighelpAlertReply.categoryID(for: userInfo("session.completed", reference: "scout")) == nil) + #expect(BighelpAlertReply.categoryID(for: ["loopdy": ["eventType": "session.completed", "sessionReference": reference]]) == nil) + #expect(BighelpAlertReply.categoryID(for: [:]) == nil) + } + + @Test func theAlertGetsATextFieldThatNeedsTheUnlockedPhone() async throws { + let old = UNNotificationCategory(identifier: "LOOPDY_AGENT_UPDATE", actions: [], intentIdentifiers: [], options: []) + let store = Categories([old]) + let content = UNMutableNotificationContent() + content.categoryIdentifier = "LOOPDY_AGENT_UPDATE" + content.userInfo = userInfo("session.completed", reference: reference) + await BighelpAlertReply.add(to: content, categories: store) + + #expect(content.categoryIdentifier == "BIGHELP_REPLY") + let registered = await store.categories() + #expect(registered.contains(old)) + let category = try #require(registered.first { $0.identifier == "BIGHELP_REPLY" }) + let field = try #require(category.actions.first as? UNTextInputNotificationAction) + #expect(field.identifier == BighelpAlertReply.actionID) + #expect(field.options.contains(.authenticationRequired)) + #expect(!field.options.contains(.foreground)) + #expect(category.actions.last?.options.contains(.foreground) == true) + #expect(registered.contains { $0.identifier == "BIGHELP_ANSWER" }) + + // Any other alert keeps the buttons its push brought. + let approval = UNMutableNotificationContent() + approval.categoryIdentifier = "LOOPDY_REVIEW" + approval.userInfo = userInfo("approval.required", reference: reference) + await BighelpAlertReply.add(to: approval, categories: store) + #expect(approval.categoryIdentifier == "LOOPDY_REVIEW") + } +} + +/// Words typed on an alert, and the island's Approve and Deny: which request they are for, and where they go. +@MainActor +struct AlertReplyTests { + private let reference = String(repeating: "r", count: 43) + + // MARK: Which request an answer is for + + private func approval(_ id: String, chat: String, command: String = "rm -rf build/cache", + allowed: [ApprovalDecision] = [.once, .session, .deny], + expires: Date = .distantFuture) -> DashboardAttentionItem { + DashboardAttentionItem(id: id, title: command, detail: "recursive delete", urgency: .important, + approvalID: id, sessionID: chat, agentID: "scout", + interaction: .approval(.init(eventID: id, approvalID: id, allowedDecisions: allowed, expiresAt: expires)), + createdAt: .distantPast) + } + + private func question(_ id: String, chat: String, choices: [String] = [], custom: Bool = true) -> DashboardAttentionItem { + DashboardAttentionItem(id: id, title: "Which fare?", detail: "", urgency: .needsReview, sessionID: chat, agentID: "scout", + interaction: .clarification(.init(eventID: id, requestID: id, sessionID: chat, question: "Which fare?", + choices: choices, allowsCustomResponse: custom, + isMultiSelect: false, expiresAt: nil)), + createdAt: .distantPast) + } + + @Test func aYesGoesOnlyToTheOneShortCommandThatWaitsInTheChat() throws { + let now = Date(timeIntervalSince1970: 1_800_000_000) + let shown = "rm -rf build/cache" + let mine = approval("a1", chat: "chat-1") + let elsewhere = approval("a2", chat: "chat-2") + func pick(_ items: [DashboardAttentionItem], _ decision: ApprovalDecision = .once, shown: String = shown) + -> Result { + ChatOutsidePrompt.approval(in: items, chatID: "chat-1", decision: decision, shown: shown, now: now) + } + #expect(try pick([elsewhere, mine]).get().id == "a1") + #expect(try pick([approval("a0", chat: "chat-1", command: " rm -rf build/cache\n")]).get().id == "a0") + #expect(pick([elsewhere]) == .failure(.nothingWaits)) + #expect(pick([approval("old", chat: "chat-1", expires: now)]) == .failure(.nothingWaits)) + // Two requests: a yes on the island could be for either. + #expect(pick([mine, approval("a3", chat: "chat-1")]) == .failure(.mustReview)) + #expect(pick([approval("a5", chat: "chat-1", allowed: [.deny])]) == .failure(.mustReview)) + // The island can stay up for minutes. If the bot asks for something else by then, a tap on the + // old buttons answers nothing: not a yes, and not a no either. + let next = approval("a6", chat: "chat-1", command: "git push --force") + #expect(pick([next]) == .failure(.mustReview)) + #expect(pick([next], .deny) == .failure(.mustReview)) + #expect(pick([approval("a7", chat: "chat-1", command: "Approval requested")]) == .failure(.mustReview)) + #expect(pick([mine], shown: "") == .failure(.mustReview)) + // A command longer than the island shows whole is read in the app, whatever the island said. + let long = String(repeating: "x", count: BighelpIslandMoment.wholeCommandCharacters + 1) + #expect(pick([approval("a4", chat: "chat-1", command: long)], shown: long) == .failure(.mustReview)) + #expect(try pick([mine], .deny).get().id == "a1") + } + + @Test func typedWordsAnswerAQuestionOnlyWhenWordsCanAnswerIt() throws { + let now = Date(timeIntervalSince1970: 1_800_000_000) + #expect(try ChatOutsidePrompt.question(in: [question("q1", chat: "chat-1")], chatID: "chat-1", answer: "The cheap one", now: now).get().id == "q1") + let picks = question("q2", chat: "chat-1", choices: ["Economy", "Flex"], custom: false) + #expect(try ChatOutsidePrompt.question(in: [picks], chatID: "chat-1", answer: "Flex", now: now).get().id == "q2") + #expect(ChatOutsidePrompt.question(in: [picks], chatID: "chat-1", answer: "First class", now: now) == .failure(.mustReview)) + #expect(ChatOutsidePrompt.question(in: [question("q3", chat: "chat-2")], chatID: "chat-1", answer: "Yes", now: now) == .failure(.nothingWaits)) + } + + // MARK: Where the words go + + private final class Log { var notices: [(ChatOutsideFailure, String?)] = []; var selected: [UUID] = []; var connects = 0 } + + private func actions(selected: UUID?, appIsActive: Bool, target: ChatOutsideTarget?, log: Log) -> ChatOutsideActions { + var actions = ChatOutsideActions( + connect: { log.connects += 1; throw BighelpShortcutServiceError.connectionUnavailable }, + selectedHostID: { log.selected.last ?? selected }, + selectHost: { log.selected.append($0); return true }) + actions.appIsActive = { appIsActive } + actions.alertTarget = { _ in target } + actions.rowTarget = { _ in target } + actions.limit = .seconds(5) + actions.notify = { failure, text, _, _ in log.notices.append((failure, text)) } + return actions + } + + private var alert: BighelpProactiveNotificationOpen? { + BighelpProactiveNotificationOpen(userInfo: ["loopdy_notification_version": "1", "loopdy_event_id": "event-1", + "loopdy_event_type": "session.completed", "loopdy_agent_id": "scout"]) + } + + @Test func wordsForAnotherComputersChatNeverMoveAPersonWhoIsUsingTheApp() async { + let here = UUID(), there = UUID(), log = Log() + let target = ChatOutsideTarget(hostID: there, profileID: "scout", chat: .reference(reference)) + await actions(selected: here, appIsActive: true, target: target, log: log) + .receiveReply("On my way", alert: alert, agentName: "Scout", thread: "scout") + #expect(log.selected.isEmpty) + #expect(log.connects == 0) + #expect(log.notices.map(\.0) == [.otherComputerInUse]) + // The words are in the notice, so they are not lost. + #expect(log.notices.first?.1 == "On my way") + } + + @Test func withTheAppClosedTheChatsComputerIsUsedAndAFailureIsSaid() async { + let here = UUID(), there = UUID(), log = Log() + let target = ChatOutsideTarget(hostID: there, profileID: "scout", chat: .reference(reference)) + await actions(selected: here, appIsActive: false, target: target, log: log) + .receiveReply(" On my way \n", alert: alert, agentName: "Scout", thread: "scout") + // The chat's computer is used, and the person's own is put back after. + #expect(log.selected == [there, here]) + #expect(log.connects == 1) + #expect(log.notices.map(\.0) == [.unavailable]) + #expect(log.notices.first?.1 == "On my way") + } + + @Test func workThatOutlastsTheTimeIosGivesIsStoppedAndSaid() async { + let here = UUID(), log = Log() + var slow = actions(selected: here, appIsActive: false, + target: ChatOutsideTarget(hostID: here, profileID: "scout", chat: .reference(reference)), log: log) + slow.connect = { try await Task.sleep(for: .seconds(30)); throw BighelpShortcutServiceError.connectionUnavailable } + slow.limit = .milliseconds(200) + let started = ContinuousClock.now + await slow.receiveReply("Hello", alert: alert, agentName: "Scout", thread: "scout") + #expect(ContinuousClock.now - started < .seconds(5)) + #expect(log.notices.map(\.0) == [.notSent]) + #expect(log.notices.first?.1 == "Hello") + } + + @Test func anAlertThatNamesNoChatAndEmptyWordsSendNothing() async { + let here = UUID(), log = Log() + let none = actions(selected: here, appIsActive: false, target: nil, log: log) + await none.receiveReply("Hello", alert: alert, agentName: nil, thread: "scout") + await none.receiveReply(" ", alert: alert, agentName: nil, thread: "scout") + await none.receiveDecision(rowID: "native-row", approves: true, command: "rm -rf build/cache") + #expect(log.connects == 0) + #expect(log.notices.map(\.0) == [.chatGone, .chatGone]) + #expect(ChatOutsideNotice.body(for: .notSent, text: "Hello").contains("“Hello”")) + #expect(!ChatOutsideNotice.body(for: .mustReview, text: nil).contains("“")) + } +} diff --git a/BighelpTests/IslandMomentTests.swift b/BighelpTests/IslandMomentTests.swift new file mode 100644 index 00000000..eaada7cf --- /dev/null +++ b/BighelpTests/IslandMomentTests.swift @@ -0,0 +1,170 @@ +import Foundation +import SwiftUI +import Testing +@testable import Bighelp + +/// The open Dynamic Island for a chat with news: which chat leads, what it says and which buttons +/// it offers. A yes to a command is offered only beside the whole command. +@MainActor +struct IslandMomentTests { + typealias State = LoopdySessionActivityAttributes.ContentState + private let working = "native-" + String(repeating: "aa", count: 32) + private let other = "native-" + String(repeating: "bb", count: 32) + private let now = Date(timeIntervalSince1970: 1_800_000_030) + + private func state(_ rows: [BighelpActivitySession], lead: String? = nil) -> State { + var state = BighelpActivitySession.aggregate(rows, timestamp: 1_800_000_000) + state.lead = lead + return state + } + + private func row(_ id: String, _ phase: State.Phase) -> BighelpActivitySession { + BighelpActivitySession(id: id, phase: phase, timestamp: 1_800_000_000) + } + + private func detail(_ json: String) throws -> BighelpActivityDetail { + try BighelpActivityDetail(json: Data(json.utf8)) + } + + private func moment(_ phase: State.Phase, _ json: String = #"{"v":1}"#, + level: BighelpActivityDetailLevel = .stepsAndText, isStale: Bool = false, + asOf: Date? = nil) throws -> BighelpIslandMoment? { + let info = BighelpActivitySessionInfo( + attributes: .init(sessionID: other, sessionTitle: "Active chat", agentID: "scout", agentName: "Scout"), + title: "Weekend trip") + return BighelpIslandMoment(state: state([row(other, phase)]), isStale: isStale, asOf: asOf ?? now, + infos: [other: info], details: [other: try detail(json)], level: level) + } + + @Test func theRowWithNewsIsShownFirst() { + let rows = [row(working, .usingTool), row(other, .completed)] + #expect(BighelpActivitySession.shown(state(rows)).map(\.id) == [working, other]) + #expect(BighelpActivitySession.shown(state(rows, lead: other)).map(\.id) == [other, working]) + // A lead that names no row on the card changes nothing. + #expect(BighelpActivitySession.shown(state(rows, lead: "native-gone")).map(\.id) == [working, other]) + } + + @Test func aCardStateFromThePushNamesItsLeadAndOlderOnesStillRead() throws { + let push = #"{"phase":"completed","currentAction":"","progress":0,"completedSteps":0,"activeSubagentCount":0,"latestTool":null,"timestamp":1800000000,"activeCount":0,"activeRows":[],"sessions":[],"lead":"native-x"}"# + #expect(try JSONDecoder().decode(State.self, from: Data(push.utf8)).lead == "native-x") + let older = push.replacingOccurrences(of: #","lead":"native-x""#, with: "") + #expect(try JSONDecoder().decode(State.self, from: Data(older.utf8)).lead == nil) + } + + @Test func theCardKnowsWhatKindOfAnswerWaits() throws { + #expect(try detail(#"{"v":1,"q":"rm -rf build/cache","a":"c"}"#).ask == .command) + #expect(try detail(#"{"v":1,"q":"deletes files","a":"a"}"#).ask == .approval) + #expect(try detail(#"{"v":1,"q":"Send the order?","a":"q"}"#).ask == .question) + #expect(try detail(#"{"v":1,"q":"Send the order?"}"#).ask == nil) + #expect(try detail(#"{"v":1,"q":"Send the order?","a":"later"}"#).ask == nil) + // A command the card would fold or cut is not the command a yes would run. + #expect(try detail(#"{"v":1,"q":"echo two spaces","a":"c"}"#).ask == .approval) + #expect(try detail(#"{"v":1,"q":"\#(String(repeating: "x", count: 220))","a":"c"}"#).ask == .approval) + } + + @Test func aShortCommandGetsApproveAndDenyBesideIt() throws { + let moment = try #require(try moment(.waiting, #"{"v":1,"q":"rm -rf build/cache","a":"c"}"#)) + #expect(moment.kind == .needsYou) + #expect(moment.text == "rm -rf build/cache") + #expect(moment.buttons == .decide) + #expect(moment.agentName == "Scout") + #expect(moment.status == "Needs you") + } + + @Test func aYesIsNeverOfferedWithoutTheWholeCommandOnScreen() throws { + // The computer says it must be read in the app. + #expect(try moment(.waiting, #"{"v":1,"q":"deletes files","a":"a"}"#)?.buttons == .review) + // Longer than the island shows whole. + let long = String(repeating: "x", count: BighelpIslandMoment.wholeCommandCharacters + 1) + #expect(try moment(.waiting, #"{"v":1,"q":"\#(long)","a":"c"}"#)?.buttons == .review) + // The person turned the card's text off, so the command isn't on screen. + let hidden = try #require(try moment(.waiting, #"{"v":1,"q":"rm -rf build/cache","a":"c"}"#, level: .steps)) + #expect(hidden.text == nil) + #expect(hidden.buttons == .review) + // A computer that doesn't say what waits gets a way into the chat, nothing more. + #expect(try moment(.waiting, #"{"v":1,"q":"rm -rf build/cache"}"#)?.buttons == .open) + #expect(try moment(.waiting, level: .statusOnly)?.buttons == .open) + } + + @Test func aQuestionAFinishedReplyAndAFailureEachGetTheirOwnButtons() throws { + #expect(try moment(.waiting, #"{"v":1,"q":"Send the order?","a":"q"}"#)?.buttons == .answer) + let done = try #require(try moment(.completed, #"{"v":1,"p":"Booked the 7:40 train."}"#)) + #expect(done.kind == .done) + #expect(done.text == "Booked the 7:40 train.") + #expect(done.buttons == .reply) + let failed = try #require(try moment(.failed)) + #expect(failed.kind == .failed) + #expect(failed.text == nil) + #expect(failed.title == "Weekend trip") + #expect(failed.buttons == .open) + } + + @Test func aChatThatOnlyWorksOrWentQuietKeepsThePlainRows() throws { + #expect(try moment(.usingTool) == nil) + #expect(try moment(.thinking) == nil) + #expect(try moment(.waiting, isStale: true) == nil) + #expect(try moment(.waiting, asOf: Date(timeIntervalSince1970: 1_800_000_121)) == nil) + // A finished chat stays news: it has nothing more to say. + #expect(try moment(.completed, asOf: Date(timeIntervalSince1970: 1_800_000_121)) != nil) + } + + @Test func replyOnTheIslandIsAChatLinkThatAsksForTheKeyboard() throws { + let reply = BighelpWidgetSnapshot.chatURL(other, reply: true) + #expect(BighelpIncomingURLRoute.parse(reply) == .chat(sessionID: other)) + #expect(BighelpIncomingURLRoute.asksForReply(reply)) + #expect(!BighelpIncomingURLRoute.asksForReply(BighelpWidgetSnapshot.chatURL(other))) + #expect(!BighelpIncomingURLRoute.asksForReply(try #require(URL(string: "loopdy://sessions?reply=1")))) + } + + @Test func aReplyRequestIsTakenOnceAndOnlySoonAfterTheTap() { + let tap = Date(timeIntervalSince1970: 1_800_000_000) + ChatReplyRequest.note(at: tap) + #expect(ChatReplyRequest.take(at: tap.addingTimeInterval(2))) + #expect(!ChatReplyRequest.take(at: tap.addingTimeInterval(3))) + ChatReplyRequest.note(at: tap) + #expect(!ChatReplyRequest.take(at: tap.addingTimeInterval(60))) + + let state = AppState() + state.requestReply(in: "chat-1") + #expect(!state.consumeReplyRequest(for: "chat-2")) + #expect(state.consumeReplyRequest(for: "chat-1")) + #expect(!state.consumeReplyRequest(for: "chat-1")) + } + + /// BIGHELP_EVIDENCE= (TEST_RUNNER_BIGHELP_EVIDENCE through xcodebuild) draws each moment's + /// own views into a black shape the size of the open island and saves it as a PNG. The system draws + /// the real island; a simulator's screenshots leave it out. + @Test func picturesOfEachMoment() throws { + guard let folder = ProcessInfo.processInfo.environment["BIGHELP_EVIDENCE"] else { return } + let moments: [(String, State.Phase, String)] = [ + ("command", .waiting, #"{"v":1,"q":"rm -rf build/cache","a":"c"}"#), + ("approval", .waiting, #"{"v":1,"q":"Deletes the old builds and their caches from three folders","a":"a"}"#), + ("question", .waiting, #"{"v":1,"q":"Can I delete the 14 old drafts in Notes, Archive?","a":"q"}"#), + ("done", .completed, #"{"v":1,"p":"Booked the 7:40 train to Leeds and put it in your calendar. The return is open until Friday."}"#), + ("failed", .failed, #"{"v":1,"p":"The airline site asked for a sign-in I don't have. Your search is saved."}"#), + ] + for (name, phase, json) in moments { + let moment = try #require(try moment(phase, json)) + let island = VStack(alignment: .leading, spacing: 0) { + HStack { + BighelpIslandMomentSender(moment: moment) + Spacer(minLength: 12) + BighelpIslandMomentStatus(moment: moment) + } + .frame(height: 40) + BighelpIslandMomentBody(moment: moment).padding(.top, 4) + } + .padding(.horizontal, 22).padding(.top, 12).padding(.bottom, 18) + .frame(width: 374) + .foregroundStyle(.white) + .background(.black, in: RoundedRectangle(cornerRadius: 44, style: .continuous)) + .environment(\.colorScheme, .dark) + for (look, page) in [("light", Color(white: 0.94)), ("dark", Color(white: 0.12))] { + let renderer = ImageRenderer(content: island.padding(14).background(page)) + renderer.scale = 3 + let image = try #require(renderer.uiImage) + try #require(image.pngData()).write(to: URL(fileURLWithPath: folder).appendingPathComponent("island-\(name)-\(look).png")) + } + } + } +} diff --git a/BighelpTests/NotificationProcessorTests.swift b/BighelpTests/NotificationProcessorTests.swift index 1bfad292..bda2ba21 100644 --- a/BighelpTests/NotificationProcessorTests.swift +++ b/BighelpTests/NotificationProcessorTests.swift @@ -178,6 +178,18 @@ import UserNotifications #expect(fakes.clearedEvents.count == 1) } + /// A reply about one saved chat takes the person's words (#1051), in place of the buttons its push brought. + @Test func aSealedReplyAboutAChatGetsATextField() async throws { + let (info, plaintext) = try Self.sealedPush() + let fakes = Fakes() + fakes.opened = plaintext + let (_, delivered) = run(fakes, Self.request(info, thread: String(repeating: "A", count: 43))) + let content = try #require(await delivered.settled().first) + #expect(content.categoryIdentifier == BighelpAlertReply.replyCategory) + let registered = await fakes.categories.categories() + #expect(registered.contains { $0.identifier == BighelpAlertReply.replyCategory }) + } + @Test func aSealedAlertShownLiveByTheAppIsQuiet() async throws { let (info, plaintext) = try Self.sealedPush() let fakes = Fakes() diff --git a/docs/LIVE_ACTIVITY_GROUPS.md b/docs/LIVE_ACTIVITY_GROUPS.md index 1e2c7162..7a8260bc 100644 --- a/docs/LIVE_ACTIVITY_GROUPS.md +++ b/docs/LIVE_ACTIVITY_GROUPS.md @@ -53,6 +53,40 @@ Registration must establish credential/grant authority before another row can fi The payload carries five visible rows, the total active count, and opaque membership suffixes for up to 64 active rows. Hidden rows are recovered only when that membership confirms them; local dismissal tombstones survive restoration. Physical token registration is serialized across all row owners and drains token rotations before releasing the queue. If a remote completion ends the physical card before a new row registers, still-running work gets a new physical card during an eligible live opportunity. All-finished cards dismiss after 30 seconds, or on the next app opening. Upgrade cleanup dismisses old per-chat native cards only after a shared start succeeds. +## News opens the island + +The Dynamic Island opens by itself when a chat has news: it needs the person, it finished or it could not finish. +An ordinary step never opens it. + +- **The moment.** The notification service keeps each row's last state. When a row's phase changes into `waiting`, + `completed` or `failed`, that one update is a moment. A host that sends the same state again makes no moment. + A moment stays with its row until a push for it is reserved, so a host's retry of an update that failed still + opens the island. +- **The alert.** The push for a moment carries `aps.alert` with fixed words and no sound: the title "Bighelp" and + "A chat needs you.", "A chat finished." or "A chat could not finish." The words never come from a chat. iOS + opens the island for a few seconds, or shows the card as a banner on a phone that has no island. +- **The row that leads.** The same push names the row in the state's `lead`. The service puts that row first, so + its sealed detail fits, and the card shows it first. Later updates carry no `lead`. +- **A finished card stays for a moment.** iOS takes an ended card off the island at once. When the last active row + finishes, the service sends an update with the alert and keeps a pending end for the group. Its alarm sends the + end 30 seconds later, with a dismissal date of that time, so the card leaves at once. The end goes through the + same send queue and the same authorization checks as every send, and a pending end holds only IDs and + revisions. It names no single row's activity: the row that finished is closed by then, and the group's grants + are checked again as the end is sent. No end is sent if a row became active again, if the group already ended or if the authority is + gone. A host that sends a finished row again during the wait gets a plain update. An end that fails is not + sent again: the card then ends with its lease or when the app opens. A group whose last row finished without + a moment has no pending end and ends as before, with a dismissal date 30 seconds ahead. +- **Priority.** A moment's push always goes at the normal priority. Only a new step alone goes at low priority. +- **What the open island shows.** The bot, what happened, the words from the row's sealed detail, and buttons: + Deny and Approve beside a short command, Review for every other approval, Answer for a question, Open chat and + Reply for a finished reply, Open chat for a failure. A chat that only works keeps the plain rows. +- **A yes needs the whole command.** The computer marks a waiting row's detail with what kind of answer waits. Only + a command it sent whole (one printable line of at most 90 characters) gets Approve, and only while the card may + show text. The button carries the command the island showed. The app answers the computer only when that same + command is the one request that waits in the chat, is not expired, and the choice is allowed. The buttons need the unlocked phone. +- **Older builds.** `lead` and the detail's new field are optional. An older app shows the same rows as before + when the island opens. + ## When the service refuses a card The service answers a phone's row DELETE for a card it never stored with 404 `notification_activity_unknown`, and a revision it doesn't expect with 409 `notification_activity_conflict` (both `{version, error: {code, message}}`). The host routes keep their own answers. The app treats the 404 as "already gone": it clears the saved revocation and does the same local cleanup a confirmed revoke does. A 409, a 5xx or any other answer stays pending and is retried at the next foreground. diff --git a/docs/SECURITY_AND_PRIVACY.md b/docs/SECURITY_AND_PRIVACY.md index 404ffd12..bb527c70 100644 --- a/docs/SECURITY_AND_PRIVACY.md +++ b/docs/SECURITY_AND_PRIVACY.md @@ -320,6 +320,8 @@ updates. | Alert title/body | Device after decryption | Encrypted payload | Created by the authorized source | | Live Activity state | ActivityKit | Bounded state, encrypted at rest but readable during relay delivery and by Apple | Created from agent activity | | Live Activity detail (steps, a waiting question, reply lines) | Device after decryption, in the Live Activity extension | Encrypted bytes for a key the relay never has | Created and encrypted by the authorized source | +| Live Activity alert (opens the Dynamic Island for news) | Shown by iOS; the open island draws from the state and the detail | Fixed words only ("A chat needs you.", "A chat finished.", "A chat could not finish."), readable by the relay and Apple | The relay adds it when a row's phase changes; no text from a chat | +| Words typed on an alert, and Approve or Deny on the island | Sent by the app over its own connection | Not sent | Plaintext, as a message or an answer in that chat | | Static Card document and embedded values | Local transcript cache | Not sent | Generated and validated on the authorized Hermes host | | Live Card source URL, response, and request metadata | Not accepted in build 3 | Not accepted in build 3 | Not accepted in build 3 | | Preferences | UserDefaults | Not uploaded as preferences | Not required | diff --git a/services/link/src/activity-group.ts b/services/link/src/activity-group.ts index 27ee5e4c..bff8e1cc 100644 --- a/services/link/src/activity-group.ts +++ b/services/link/src/activity-group.ts @@ -26,20 +26,46 @@ export function activityRowPriority(phase: string): number { return phase === "waiting" ? 0 : phase === "failed" ? 2 : phase === "completed" ? 3 : 1; } -export function aggregateActivityRows(rows: ActivityGroupRow[], timestamp: number) { +/** A row that just changed into a phase the person should hear about. */ +export type ActivityMomentKind = "waiting" | "completed" | "failed"; +export interface ActivityMoment { row: string; kind: ActivityMomentKind } + +/** The moment for a row's phase change, or none for a repeat of the same phase or any other phase. */ +export function activityMoment(old: ActivityGroupRow, state: ActivityGroupRow): ActivityMoment | null { + if (old.phase === state.phase) return null; + return state.phase === "waiting" || state.phase === "completed" || state.phase === "failed" + ? { row: state.id, kind: state.phase } : null; +} + +/** The alert a moment's push carries. Fixed text, never from a chat: this service cannot read one. */ +export function activityMomentAlert(kind: ActivityMomentKind): { title: string; body: string } { + return { title: "Bighelp", body: ACTIVITY_MOMENT_BODIES[kind] }; +} +const ACTIVITY_MOMENT_BODIES: Record = { + waiting: "A chat needs you.", completed: "A chat finished.", failed: "A chat could not finish.", +}; + +/** How long a finished group stays in the island after its last chat ends, before its deferred end. */ +export const ACTIVITY_END_DELAY_SECONDS = 30; + +/** `lead` is the row the push is about: it goes first, so the card and its sealed detail show it first. */ +export function aggregateActivityRows(rows: ActivityGroupRow[], timestamp: number, lead?: string) { const active = rows.filter((row) => row.phase !== "completed" && row.phase !== "failed"); const activeCount = active.length; // Opaque membership hints let the phone hide completed cached rows that do not // fit in sessions. These suffixes are never authority or routing identifiers. const activeRows = [...new Set(active.map((row) => row.id.slice(-16)))].sort().slice(0, 64); - const ordered = [...rows].sort((a, b) => activityRowPriority(a.phase) - activityRowPriority(b.phase) + const byPriority = [...rows].sort((a, b) => activityRowPriority(a.phase) - activityRowPriority(b.phase) || a.id.localeCompare(b.id)); const phase = activeCount === 0 ? (rows.some((row) => row.phase === "failed") ? "failed" : "completed") - : ordered.find((row) => row.phase !== "completed" && row.phase !== "failed")?.phase ?? "thinking"; + : byPriority.find((row) => row.phase !== "completed" && row.phase !== "failed")?.phase ?? "thinking"; + const led = lead !== undefined ? byPriority.find((row) => row.id === lead) : undefined; + const ordered = led ? [led, ...byPriority.filter((row) => row !== led)] : byPriority; const state = { phase, currentAction: "", progress: 0, completedSteps: 0, activeSubagentCount: 0, latestTool: null, timestamp, activeCount, activeRows, sessions: ordered.slice(0, 5).map(({ sealed: _, ...row }): ActivityGroupRow => row), + ...(led ? { lead: led.id } : {}), }; // Sealed detail goes to the rows in the order the card shows them, while the push still fits. let size = bytes(state); diff --git a/services/link/src/push-delivery.ts b/services/link/src/push-delivery.ts index 7b863ffa..eac9cf0d 100644 --- a/services/link/src/push-delivery.ts +++ b/services/link/src/push-delivery.ts @@ -61,6 +61,8 @@ export interface LiveActivityMessage { dismissalDate?: number; /** 10 when left out. 5 for an update that changes only a card's sealed detail. */ priority?: 5 | 10; + /** Makes the push open the Dynamic Island on its own. Fixed text; with no `sound`, it is silent. */ + alert?: { title: string; body: string }; } export interface ApnsRetryMessage { @@ -286,6 +288,7 @@ export function liveActivitySpec(live: LiveActivityMessage, nowSeconds: number): event: live.event, "content-state": live.contentState, "stale-date": live.staleDate, + ...(live.alert ? { alert: { title: live.alert.title, body: live.alert.body } } : {}), ...(live.event === "end" && live.dismissalDate !== undefined ? { "dismissal-date": live.dismissalDate } : {}), }, diff --git a/services/link/src/user-link-notifications.ts b/services/link/src/user-link-notifications.ts index 4836a887..2c43848b 100644 --- a/services/link/src/user-link-notifications.ts +++ b/services/link/src/user-link-notifications.ts @@ -1,4 +1,7 @@ -import { aggregateActivityRows, NATIVE_ROW_ID, type ActivityGroupRow } from "./activity-group.js"; +import { + activityMoment, aggregateActivityRows, NATIVE_ROW_ID, type ActivityGroupRow, type ActivityMoment, + type ActivityMomentKind, +} from "./activity-group.js"; import { LoopdyLinkError } from "./contracts.js"; import type { NotificationActivity, NotificationAsset, NotificationEgressSnapshot } from "./notification-grants.js"; import type { UserLinkAccount } from "./user-link-account.js"; @@ -28,6 +31,19 @@ const NOTIFICATION_ASSET_TYPES: string[] = ["image/png", "image/jpeg", "image/we // stays an hour longer. export const ACTIVITY_RECORD_GRACE_SECONDS = 3_600; +/** + * What the deferred end of a finished group needs to send: ids and revisions, never chat text. + * The authority names no single activity: the row that finished is closed by the time the end goes + * (`completeNotificationActivityUpdate`), and the end speaks for the whole group, whose grants are + * checked again when it is sent. + */ +export interface PendingActivityEnd { + ownerCoordinate: string; + activityId: string; + authority: Omit; + externalId: string; +} + export class UserLinkNotificationStore { constructor( private readonly storage: DurableObjectStorage, @@ -209,7 +225,8 @@ export class UserLinkNotificationStore { } : {}) }; } - updateActivityGroup(activityId: string, state: ActivityGroupRow, credentialId: string): void { + /** Stores the row's new state and reports the moment its phase change is, if any. */ + updateActivityGroup(activityId: string, state: ActivityGroupRow, credentialId: string): ActivityMoment | null { const group = this.groupRow(activityId); if (!group || group.row_id !== state.id || group.credential_id !== credentialId) { throw new LoopdyLinkError("notification_activity_conflict", "Activity row ownership changed"); @@ -224,9 +241,26 @@ export class UserLinkNotificationStore { } this.storage.sql.exec("UPDATE managed_activity_rows SET state_json=?,last_state_timestamp=? WHERE activity_id=?", JSON.stringify(state), state.timestamp, activityId); + // A moment stays with its row until a push for it is reserved. A host sends a failed update + // again with the same state: that retry must still open the island, and wait before the end. + const moment = activityMoment(old, state); + if (moment) { + this.storage.sql.exec(`INSERT INTO managed_activity_moments(activity_id,kind) VALUES(?,?) + ON CONFLICT(activity_id) DO UPDATE SET kind=excluded.kind`, activityId, moment.kind); + } else if (old.phase !== state.phase) this.clearActivityMoment(activityId); + const kept = this.storage.sql.exec<{ kind: string }>( + "SELECT kind FROM managed_activity_moments WHERE activity_id=?", activityId, + ).toArray()[0]; + return kept && kept.kind === state.phase ? { row: state.id, kind: kept.kind as ActivityMomentKind } : null; + } + + /** The moment's push is reserved: the same state sent again is no longer news. */ + clearActivityMoment(activityId: string): void { + this.storage.sql.exec("DELETE FROM managed_activity_moments WHERE activity_id=?", activityId); } - activityGroup(activityId: string, now: number, authority: NotificationEgressSnapshot) { + /** `moment` leads the aggregate only while its row is still in the phase it was a moment for. */ + activityGroup(activityId: string, now: number, authority: NotificationEgressSnapshot, moment?: ActivityMoment | null) { // This runs at the final egress boundary. Revocations are mirrored into this // owner before directory cleanup, so all included grants share that fence. this.authorizeNotificationEgress(authority); @@ -246,7 +280,8 @@ export class UserLinkNotificationStore { a.updated_at DESC, a.activity_id DESC LIMIT 69`, group.group_id, group.credential_id, authority.authorizationEpoch, authorizationNow, authorizationNow, ).toArray().map((row) => JSON.parse(row.state_json) as ActivityGroupRow); - return { ...aggregateActivityRows(rows, now), groupId: group.group_id }; + const lead = moment && rows.some((row) => row.id === moment.row && row.phase === moment.kind) ? moment.row : undefined; + return { ...aggregateActivityRows(rows, now, lead), groupId: group.group_id }; } activityGroupGrants(activityId: string): NonNullable[] { @@ -278,6 +313,46 @@ export class UserLinkNotificationStore { WHERE group_id=?`, timestamp, terminal ? 1 : 0, group.group_id); } + activityGroupEnded(activityId: string): boolean { + const group = this.groupRow(activityId); + if (!group) throw new LoopdyLinkError("notification_activity_invalid", "No activity group"); + return this.storage.sql.exec<{ ended: number }>( + "SELECT ended FROM managed_activity_groups WHERE group_id=?", group.group_id, + ).one().ended !== 0; + } + + /** Keeps a finished group's end for `dueAt` (Unix seconds); a newer finish moves it. */ + putPendingActivityEnd(groupId: string, dueAt: number, end: PendingActivityEnd): void { + this.storage.sql.exec(`INSERT INTO managed_activity_pending_ends(group_id,due_at,end_json) VALUES(?,?,?) + ON CONFLICT(group_id) DO UPDATE SET due_at=excluded.due_at,end_json=excluded.end_json`, + groupId, dueAt, JSON.stringify(end)); + } + + hasPendingActivityEnd(groupId: string): boolean { + return this.storage.sql.exec<{ count: number }>( + "SELECT COUNT(*) AS count FROM managed_activity_pending_ends WHERE group_id=?", groupId, + ).one().count > 0; + } + + clearPendingActivityEnd(groupId: string): void { + this.storage.sql.exec("DELETE FROM managed_activity_pending_ends WHERE group_id=?", groupId); + } + + /** Takes every end that is due out of the table: a failed end never repeats. */ + takeDueActivityEnds(now: number): PendingActivityEnd[] { + const due = this.storage.sql.exec<{ group_id: string; end_json: string }>( + "SELECT group_id,end_json FROM managed_activity_pending_ends WHERE due_at<=? ORDER BY due_at,group_id", now, + ).toArray(); + if (due.length > 0) this.storage.sql.exec("DELETE FROM managed_activity_pending_ends WHERE due_at<=?", now); + return due.map((row) => JSON.parse(row.end_json) as PendingActivityEnd); + } + + nextPendingActivityEnd(): number | null { + return this.storage.sql.exec<{ next: number | null }>( + "SELECT MIN(due_at) AS next FROM managed_activity_pending_ends", + ).one().next; + } + notificationActivity(input: { grantId: string; activityId: string; now: number; }): NotificationActivity { @@ -428,6 +503,8 @@ export class UserLinkNotificationStore { this.storage.sql.exec("DELETE FROM managed_activity_rows"); this.storage.sql.exec("DELETE FROM managed_activity_groups"); this.storage.sql.exec("DELETE FROM managed_activity_row_generations"); + this.storage.sql.exec("DELETE FROM managed_activity_pending_ends"); + this.storage.sql.exec("DELETE FROM managed_activity_moments"); }); } @@ -572,6 +649,8 @@ export class UserLinkNotificationStore { this.storage.sql.exec("DELETE FROM managed_activity_rows WHERE activity_id NOT IN (SELECT activity_id FROM managed_notification_activities)"); this.storage.sql.exec("DELETE FROM managed_activity_groups WHERE group_id NOT IN (SELECT group_id FROM managed_activity_rows)"); this.storage.sql.exec("DELETE FROM managed_activity_row_generations WHERE group_id NOT IN (SELECT group_id FROM managed_activity_groups)"); + this.storage.sql.exec("DELETE FROM managed_activity_pending_ends WHERE group_id NOT IN (SELECT group_id FROM managed_activity_groups)"); + this.storage.sql.exec("DELETE FROM managed_activity_moments WHERE activity_id NOT IN (SELECT activity_id FROM managed_activity_rows)"); const asset = this.storage.sql.exec<{ next: number | null }>( "SELECT MIN(expires_at) AS next FROM notification_assets", ).one().next; diff --git a/services/link/src/user-link-schema.ts b/services/link/src/user-link-schema.ts index 9463151e..bfacb9f7 100644 --- a/services/link/src/user-link-schema.ts +++ b/services/link/src/user-link-schema.ts @@ -118,6 +118,15 @@ export function initializeUserLinkStorage(storage: DurableObjectStorage): void { last_timestamp INTEGER NOT NULL DEFAULT 0, ended INTEGER NOT NULL DEFAULT 0 ); + CREATE TABLE IF NOT EXISTS managed_activity_moments ( + activity_id TEXT PRIMARY KEY, + kind TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS managed_activity_pending_ends ( + group_id TEXT PRIMARY KEY, + due_at INTEGER NOT NULL, + end_json TEXT NOT NULL + ); CREATE TABLE IF NOT EXISTS managed_notification_credentials ( credential_id TEXT PRIMARY KEY, authorization_epoch INTEGER NOT NULL CHECK (authorization_epoch > 0), diff --git a/services/link/src/user-link.ts b/services/link/src/user-link.ts index bc42c170..c59c2aa7 100644 --- a/services/link/src/user-link.ts +++ b/services/link/src/user-link.ts @@ -1,3 +1,4 @@ +import { ACTIVITY_END_DELAY_SECONDS, activityMomentAlert, type ActivityMoment } from "./activity-group.js"; import { requireNotificationGroupGrantEgressActive } from "./notification-grants.js"; import { UserLinkAccount } from "./user-link-account.js"; import { ACTIVITY_RECORD_GRACE_SECONDS, UserLinkNotificationStore } from "./user-link-notifications.js"; @@ -234,43 +235,94 @@ export class UserLink extends DurableObject { private activityDeliveryTail: Promise = Promise.resolve(); + /** Runs one physical send after the ones queued before it. The queue slot is taken before the first await. */ + private async inActivityDeliveryTail(run: () => Promise): Promise { + const before = this.activityDeliveryTail; + let release!: () => void; + this.activityDeliveryTail = new Promise((resolve) => { release = resolve; }); + try { + await before; + return await run(); + } finally { release(); } + } + async sendNotificationActivityGroup(input: { ownerCoordinate: string; activityId: string; state: import("./activity-group.js").ActivityGroupRow; authority: import("./notification-grants.js").NotificationEgressSnapshot; externalId: string; quiet?: boolean; }) { this.notificationState.authorizeNotificationEgress(input.authority); - this.notificationState.updateActivityGroup(input.activityId, input.state, input.authority.credentialId); - const before = this.activityDeliveryTail; - let release!: () => void; - this.activityDeliveryTail = new Promise((resolve) => { release = resolve; }); + const moment = this.notificationState.updateActivityGroup(input.activityId, input.state, input.authority.credentialId); + const receipt = await this.inActivityDeliveryTail(() => this.deliverActivityGroup({ ...input, moment, kind: "update" })); + // Only the deferred end can decide there is nothing to send. + if (!receipt) throw new LoopdyLinkError("notification_activity_conflict", "Activity group changed before delivery"); + return receipt; + } + + /** Sends the deferred end of every group whose wait is over. A failed end is dropped, never repeated. */ + private async sendDueActivityEnds(nowSeconds: number): Promise { + for (const end of this.notificationState.takeDueActivityEnds(nowSeconds)) { + try { + await this.inActivityDeliveryTail(() => this.deliverActivityGroup({ ...end, kind: "end" })); + } catch { /* Authorization lost or the push failed: the card ends with its lease. */ } + } + } + + /** + * One push of the group's aggregate. `kind: "update"` is a host's row update; `kind: "end"` is the + * deferred end, which sends nothing unless the group is still finished and has not ended. + */ + private async deliverActivityGroup(input: { + ownerCoordinate: string; activityId: string; + authority: import("./notification-grants.js").NotificationEgressSnapshot; externalId: string; + kind: "update" | "end"; quiet?: boolean; moment?: ActivityMoment | null; + }) { + const store = this.notificationState; + // APNs timestamps are whole seconds. Serialize sends and read the newest + // aggregate after waiting so reordered rows cannot overwrite newer work. + const delay = (store.activityDeliveryTimestamp(input.activityId) + 1) * 1_000 - Date.now(); + if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay)); + store.authorizeNotificationEgress(input.authority); + const now = Math.max(Math.floor(Date.now() / 1_000), store.activityDeliveryTimestamp(input.activityId) + 1); + const content = store.activityGroup(input.activityId, now, input.authority, input.moment); + const finished = content.activeCount === 0; + if (input.kind === "end" && (!finished || store.activityGroupEnded(input.activityId))) return null; + // A moment push carries an alert, and the row it is about leads the card. + const moment = input.moment && content.lead === input.moment.row ? input.moment : null; + // The last chat finishing is a moment too: the card stays in the island for a while, then ends. + const deferEnd = input.kind === "update" && finished && moment !== null; + const terminal = input.kind === "end" + || (finished && moment === null && !store.hasPendingActivityEnd(content.groupId)); + const authorize = async () => { + const grants = store.activityGroupGrants(input.activityId); + await requireNotificationGroupGrantEgressActive(this.env, input.ownerCoordinate, input.authority, grants); + const freshGrants = store.activityGroupGrants(input.activityId); + const fresh = store.activityGroup(input.activityId, now, input.authority, input.moment); + // No asynchronous work separates rebuilding the aggregate from reserving + // the physical send. A newly registered row must also prevent an end. + if (JSON.stringify(fresh) !== JSON.stringify(content) || JSON.stringify(freshGrants) !== JSON.stringify(grants)) { + throw new LoopdyLinkError("notification_activity_conflict", "Activity group changed before delivery"); + } + store.reserveActivityDelivery(input.activityId, now, terminal); + if (moment) store.clearActivityMoment(input.activityId); + // The end waits only while the group is finished: work that starts again, or the end itself, clears it. + if (deferEnd) { + // Without the finished row's own activity: it is closed before the end goes. + const { activity: _closed, ...authority } = input.authority; + store.putPendingActivityEnd(content.groupId, now + ACTIVITY_END_DELAY_SECONDS, { + ownerCoordinate: input.ownerCoordinate, activityId: input.activityId, + authority, externalId: input.externalId, + }); + } else if (!finished || terminal) store.clearPendingActivityEnd(content.groupId); + }; + const event = terminal ? "end" : "update"; + // The end of the deferred wait leaves at once; an end with no wait before it leaves 30 s later. + const dismissalDate = input.kind === "end" ? now : now + 30; + const alert = moment ? activityMomentAlert(moment.kind) : undefined; + // The physical card is addressed by its group ID, so that is the ID whose push token the + // phone registers for direct delivery too. The aggregate is rebuilt for every send, so a + // failed direct push is never queued for later: it goes through BuzzKit at once. try { - await before; - // APNs timestamps are whole seconds. Serialize sends and read the newest - // aggregate after waiting so reordered rows cannot overwrite newer work. - const delay = (this.notificationState.activityDeliveryTimestamp(input.activityId) + 1) * 1_000 - Date.now(); - if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay)); - this.notificationState.authorizeNotificationEgress(input.authority); - const now = Math.max(Math.floor(Date.now() / 1_000), - this.notificationState.activityDeliveryTimestamp(input.activityId) + 1); - const content = this.notificationState.activityGroup(input.activityId, now, input.authority); - const terminal = content.activeCount === 0; - const authorize = async () => { - const grants = this.notificationState.activityGroupGrants(input.activityId); - await requireNotificationGroupGrantEgressActive(this.env, input.ownerCoordinate, input.authority, grants); - const freshGrants = this.notificationState.activityGroupGrants(input.activityId); - const fresh = this.notificationState.activityGroup(input.activityId, now, input.authority); - // No asynchronous work separates rebuilding the aggregate from reserving - // the physical send. A newly registered row must also prevent an end. - if (JSON.stringify(fresh) !== JSON.stringify(content) || JSON.stringify(freshGrants) !== JSON.stringify(grants)) { - throw new LoopdyLinkError("notification_activity_conflict", "Activity group changed before delivery"); - } - this.notificationState.reserveActivityDelivery(input.activityId, now, terminal); - }; - const event = terminal ? "end" : "update"; - // The physical card is addressed by its group ID, so that is the ID whose push token the - // phone registers for direct delivery too. The aggregate is rebuilt for every send, so a - // failed direct push is never queued for later: it goes through BuzzKit at once. - const receipt = await deliverLiveActivity({ + return await deliverLiveActivity({ env: this.env as unknown as DeliveryEnv, ctx: this.ctx, owner: { kind: input.authority.ownerKind, coordinate: input.ownerCoordinate, @@ -279,20 +331,26 @@ export class UserLink extends DurableObject { grantId: input.authority.grant?.grantId ?? "", updateId: String(now), queueable: false, live: { event, activityId: content.groupId, contentState: content, timestamp: now, staleDate: now + 120, - ...(terminal ? { dismissalDate: now + 30 } : {}), + ...(terminal ? { dismissalDate } : {}), + ...(alert ? { alert } : {}), // A new step alone: Apple limits high-priority card updates, so these go at low priority. - ...(input.quiet === true && !terminal ? { priority: 5 as const } : {}), + // A moment is never one of them. + ...(input.quiet === true && !terminal && !moment ? { priority: 5 as const } : {}), }, authorize, sendViaBuzzKit: () => sendBuzzKitLiveActivity(this.env, { externalId: input.externalId, activityId: content.groupId, event, contentState: content, timestamp: now, staleDate: new Date((now + 120) * 1_000).toISOString(), - ...(terminal ? { dismissalDate: new Date((now + 30) * 1_000).toISOString() } : {}), + ...(terminal ? { dismissalDate: new Date(dismissalDate * 1_000).toISOString() } : {}), }, authorize), }); - return receipt; - } finally { release(); } + } finally { + // Stored when the send was reserved, even if the push then failed: the end still has to come. + if (deferEnd && store.hasPendingActivityEnd(content.groupId)) { + await this.scheduleNotificationPurge(now + ACTIVITY_END_DELAY_SECONDS); + } + } } registerNotificationActivity(input: Parameters[0]) { @@ -680,6 +738,8 @@ export class UserLink extends DurableObject { ) .toArray(); await this.coalescedBuzzKitWakeDrain(); + // Before the purge: an end needs its group's rows. + await this.sendDueActivityEnds(Math.floor(Date.now() / 1_000)); const purge = this.notificationState.purgeExpiredNotificationState(Math.floor(Date.now() / 1_000)); const recent = this.ctx.storage.sql.exec<{ next: number | null }>( "SELECT MIN(last_seen_bucket)+? AS next FROM devices WHERE lifecycle='active' AND connection_state='recent'", RECENT_SECONDS, @@ -687,7 +747,8 @@ export class UserLink extends DurableObject { const wake = this.ctx.storage.sql.exec<{ next: number | null }>( "SELECT MIN(next_attempt) AS next FROM buzzkit_wake_outbox", ).one().next; - const nextSeconds = [recent, wake, purge].filter((value): value is number => value !== null) + const end = this.notificationState.nextPendingActivityEnd(); + const nextSeconds = [recent, wake, purge, end].filter((value): value is number => value !== null) .reduce((selected, value) => selected === null ? value : Math.min(selected, value), null); if (nextSeconds !== null) { await this.ctx.storage.setAlarm(Math.max(Date.now() + 1_000, nextSeconds * 1_000)); diff --git a/services/link/test/activity-group-do.test.ts b/services/link/test/activity-group-do.test.ts index 7324ad05..528816ff 100644 --- a/services/link/test/activity-group-do.test.ts +++ b/services/link/test/activity-group-do.test.ts @@ -1,4 +1,4 @@ -import { env, evictDurableObject, runInDurableObject } from "cloudflare:test"; +import { env, evictDurableObject, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { UserLinkNotificationStore } from "../src/user-link-notifications.js"; import type { LinkEnv, UserLink } from "../src/user-link.js"; @@ -189,7 +189,8 @@ describe("shared activity owner integration", () => { await f.stub.revokeNotificationGrantAuthority({ grantId: b.activity.grantId, credentialId: f.credentialId, authorizationEpoch: 1, revision: 2 }); await pending; - expect(f.payloads.at(-1)).toMatchObject({ event: "end", contentState: { activeCount: 0 } }); + // The last chat finishing is a moment: the card updates now and ends after its wait. + expect(f.payloads.at(-1)).toMatchObject({ event: "update", contentState: { activeCount: 0 } }); expect(f.payloads.at(-1)!.contentState.sessions.map((r) => r.id)).not.toContain(rowId(2)); }); @@ -280,13 +281,18 @@ describe("shared activity owner integration", () => { await f.send(a, "completed"); await expect(f.send(a, "thinking", now() + 1)).rejects.toThrow(); await f.send(b, "completed"); - expect(f.payloads.at(-1)).toMatchObject({ event: "end", contentState: { activeCount: 0 } }); + expect(f.payloads.at(-1)).toMatchObject({ event: "update", contentState: { activeCount: 0 } }); }); it("refuses a new alias once a physical end has been dispatched", async () => { const f = await fixture(); const a = await f.register(1); await f.send(a, "completed"); + expect(f.payloads.at(-1)).toMatchObject({ event: "update" }); + // The end comes from the alarm once the wait is over. + const clock = vi.spyOn(Date, "now").mockReturnValue(Date.now() + 31_000); + try { await runDurableObjectAlarm(f.stub); } finally { clock.mockRestore(); } + expect(f.payloads.at(-1)).toMatchObject({ event: "end" }); await expect(f.register(2, a.activity.grantId)).rejects.toThrow(); }); }); diff --git a/services/link/test/activity-group.test.ts b/services/link/test/activity-group.test.ts index 75ee3252..32aa8425 100644 --- a/services/link/test/activity-group.test.ts +++ b/services/link/test/activity-group.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { aggregateActivityRows, NATIVE_ROW_ID } from "../src/activity-group.js"; +import { activityMoment, activityMomentAlert, aggregateActivityRows, NATIVE_ROW_ID } from "../src/activity-group.js"; describe("one Live Activity for several chats", () => { const row = (id: string, phase: string) => ({ id, phase, timestamp: 100, activeSubagentCount: 0 }); @@ -73,4 +73,59 @@ describe("one Live Activity for several chats", () => { it("ends only after every row is terminal", () => { expect(aggregateActivityRows([row("a", "completed"), row("b", "failed")], 101).phase).toBe("failed"); }); + + it("leaves the output as it was when no row leads", () => { + const result = aggregateActivityRows([row("a", "thinking")], 101); + const expected = { + phase: "thinking", currentAction: "", progress: 0, completedSteps: 0, activeSubagentCount: 0, + latestTool: null, timestamp: 101, activeCount: 1, activeRows: ["a"], + sessions: [{ id: "a", phase: "thinking", timestamp: 100, activeSubagentCount: 0 }], + }; + expect(JSON.stringify(result)).toBe(JSON.stringify(expected)); + expect(result).not.toHaveProperty("lead"); + // A lead that is not in the group changes nothing either. + expect(aggregateActivityRows([row("a", "thinking")], 101, "missing")).toEqual(expected); + }); + + it("puts the leading row first, finished or not, and names it", () => { + const result = aggregateActivityRows([row("a", "thinking"), row("b", "waiting"), row("c", "completed")], 101, "c"); + expect(result.lead).toBe("c"); + expect(result.sessions.map((value) => value.id)).toEqual(["c", "b", "a"]); + // Which phase the card shows still comes from the work that is left. + expect(result.phase).toBe("waiting"); + expect(result.activeCount).toBe(2); + }); + + it("keeps the leading row's sealed detail first when the push is tight", () => { + const appRow = (i: number) => `native-${i.toString(16).padStart(64, "0")}`; + const sealed = "s".repeat(1200); + const rows = Array.from({ length: 64 }, (_, i) => ({ + ...row(appRow(i), i === 9 ? "waiting" : "using_tool"), timestamp: 1792854000, activeSubagentCount: 99, sealed, + })); + const result = aggregateActivityRows(rows, 1792854000, appRow(40)); + expect(result.lead).toBe(appRow(40)); + expect(result.sessions[0]).toMatchObject({ id: appRow(40), sealed }); + expect(result.sessions[1]).toMatchObject({ id: appRow(9) }); + expect(result.sessions.filter((value) => value.sealed).length).toBeLessThan(5); + const apns = { aps: { timestamp: 1792854000, event: "update", "stale-date": 1792854120, + alert: activityMomentAlert("waiting"), "content-state": { ...result, groupId: `activity_${"g".repeat(43)}` } } }; + expect(new TextEncoder().encode(JSON.stringify(apns)).byteLength).toBeLessThanOrEqual(4000); + }); + + it("finds a moment only when a row changes into waiting, completed or failed", () => { + const state = (phase: string) => row("a", phase); + expect(activityMoment(state("thinking"), state("waiting"))).toEqual({ row: "a", kind: "waiting" }); + expect(activityMoment(state("using_tool"), state("completed"))).toEqual({ row: "a", kind: "completed" }); + expect(activityMoment(state("waiting"), state("failed"))).toEqual({ row: "a", kind: "failed" }); + expect(activityMoment(state("waiting"), state("waiting"))).toBeNull(); + expect(activityMoment(state("completed"), state("completed"))).toBeNull(); + expect(activityMoment(state("waiting"), state("thinking"))).toBeNull(); + expect(activityMoment(state("thinking"), state("responding"))).toBeNull(); + }); + + it("words each alert the same, and never from a chat", () => { + expect(activityMomentAlert("waiting")).toEqual({ title: "Bighelp", body: "A chat needs you." }); + expect(activityMomentAlert("completed")).toEqual({ title: "Bighelp", body: "A chat finished." }); + expect(activityMomentAlert("failed")).toEqual({ title: "Bighelp", body: "A chat could not finish." }); + }); }); diff --git a/services/link/test/apns-activity-group.test.ts b/services/link/test/apns-activity-group.test.ts index 2b0c3d81..9fca176f 100644 --- a/services/link/test/apns-activity-group.test.ts +++ b/services/link/test/apns-activity-group.test.ts @@ -1,6 +1,7 @@ -import { env, runInDurableObject } from "cloudflare:test"; +import { env, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { apnsIdFor, resetApnsTokenCache } from "../src/apns.js"; +import { ACTIVITY_END_DELAY_SECONDS, activityMomentAlert } from "../src/activity-group.js"; import { resetApnsBreaker } from "../src/push-delivery.js"; import { putPushTarget } from "../src/push-targets.js"; import type { NotificationActivity, NotificationEgressSnapshot } from "../src/notification-grants.js"; @@ -89,10 +90,11 @@ async function fixture(mode: "off" | "on") { await runInDurableObject(stub, async (instance) => { await instance.registerNotificationActivity(input); }); return { activity: input as NotificationActivity, authority }; }; - const send = (row: Awaited>, phase: string, more: { sealed?: string; quiet?: boolean } = {}) => + const send = (row: Awaited>, phase: string, + more: { sealed?: string; quiet?: boolean; timestamp?: number } = {}) => runInDurableObject(stub, async (instance) => instance.sendNotificationActivityGroup({ ownerCoordinate, activityId: row.activity.activityId, - state: { id: row.activity.rowId!, phase, timestamp: now(), activeSubagentCount: 0, + state: { id: row.activity.rowId!, phase, timestamp: more.timestamp ?? now(), activeSubagentCount: 0, ...(more.sealed ? { sealed: more.sealed } : {}) }, ...(more.quiet ? { quiet: true } : {}), externalId: "fixture-recipient", authority: { ...row.authority, activity: { @@ -100,7 +102,7 @@ async function fixture(mode: "off" | "on") { leaseExpires: row.activity.leaseExpires, } }, })); - return { groupId, credentialId, addTarget, register, send }; + return { stub, groupId, credentialId, addTarget, register, send }; } describe("direct delivery of the shared chat Live Activity", () => { @@ -142,14 +144,21 @@ describe("direct delivery of the shared chat Live Activity", () => { expect(rows.find((row) => row.id === rowId(2))).not.toHaveProperty("sealed"); }); - it("ends the card with a dismissal date only when no chat is left", async () => { + it("ends the card at once, with a dismissal date, when a chat that was already finished is resent last", async () => { + // A group whose last chat finished before moments existed has no pending end: it ends as it always did. const f = await fixture("on"); await f.addTarget(f.groupId); const a = await f.register(1); - await f.send(a, "completed"); + const timestamp = now(); + await runInDurableObject(f.stub, (_instance, state) => { + state.storage.sql.exec("UPDATE managed_activity_rows SET state_json=? WHERE activity_id=?", + JSON.stringify({ id: a.activity.rowId, phase: "completed", timestamp, activeSubagentCount: 0 }), a.activity.activityId); + }); + await f.send(a, "completed", { timestamp }); const aps = sent[0]!.body.aps; expect(aps).toMatchObject({ event: "end", "content-state": { activeCount: 0 } }); expect(aps["dismissal-date"]).toBe(aps.timestamp + 30); + expect(aps).not.toHaveProperty("alert"); }); it("ignores a token registered under a chat's own alias: the card is addressed by its group", async () => { @@ -201,3 +210,195 @@ describe("direct delivery of the shared chat Live Activity", () => { expect(await env.ACCOUNTS.prepare("SELECT COUNT(*) AS n FROM push_sends").first()).toEqual({ n: 0 }); }); }); + +// MARK: Moments + +describe("a chat's moment on the shared card", () => { + const apsOf = (index: number) => sent[index]!.body.aps; + const priorityOf = (index: number) => sent[index]!.headers.get("apns-priority"); + /** Moves the clock past the deferred end's wait, runs the Durable Object's alarm, then lets the clock go on. */ + const runAlarmAfterWait = async (stub: DurableObjectStub) => { + const clock = vi.spyOn(Date, "now").mockReturnValue(Date.now() + (ACTIVITY_END_DELAY_SECONDS + 1) * 1_000); + try { return await runDurableObjectAlarm(stub); } finally { clock.mockRestore(); } + }; + + it("pushes an alert, silent, with the waiting chat first, when a chat starts waiting", async () => { + const f = await fixture("on"); + await f.addTarget(f.groupId); + await f.register(1); + const b = await f.register(2); + await f.send(b, "waiting"); + expect(apsOf(0).event).toBe("update"); + expect(apsOf(0).alert).toEqual(activityMomentAlert("waiting")); + expect(apsOf(0).alert).toEqual({ title: "Bighelp", body: "A chat needs you." }); + expect(apsOf(0)).not.toHaveProperty("sound"); + expect(apsOf(0)["content-state"]).toMatchObject({ lead: rowId(2), activeCount: 2 }); + expect(apsOf(0)["content-state"].sessions[0].id).toBe(rowId(2)); + expect(priorityOf(0)).toBe("10"); + }); + + it("sends no alert when the host resends the same waiting state", async () => { + const f = await fixture("on"); + await f.addTarget(f.groupId); + const a = await f.register(1); + const timestamp = now(); + await f.send(a, "waiting", { timestamp }); + await f.send(a, "waiting", { timestamp: timestamp + 60 }); + expect(apsOf(0)).toHaveProperty("alert"); + expect(apsOf(1)).not.toHaveProperty("alert"); + expect(apsOf(1)["content-state"]).not.toHaveProperty("lead"); + }); + + it("sends no alert for a step, and says nothing about a chat that is not the news", async () => { + const f = await fixture("on"); + await f.addTarget(f.groupId); + const a = await f.register(1); + await f.send(a, "using_tool"); + await f.send(a, "responding"); + expect(sent.map((call) => call.body.aps)).toSatisfy((all: Array>) => + all.every((aps) => !("alert" in aps) && !("lead" in (aps["content-state"] as object)))); + }); + + it("names the chat that finished while another still works, and keeps the card up", async () => { + const f = await fixture("on"); + await f.addTarget(f.groupId); + const a = await f.register(1); + await f.register(2); + await f.send(a, "completed"); + expect(apsOf(0).event).toBe("update"); + expect(apsOf(0).alert).toEqual({ title: "Bighelp", body: "A chat finished." }); + expect(apsOf(0)["content-state"]).toMatchObject({ lead: rowId(1), activeCount: 1 }); + // Without the lead, the finished chat would sort after the one that still works. + expect(apsOf(0)["content-state"].sessions.map((row: { id: string }) => row.id)).toEqual([rowId(1), rowId(2)]); + await runAlarmAfterWait(f.stub); + expect(sent).toHaveLength(1); + }); + + it("says a chat could not finish", async () => { + const f = await fixture("on"); + await f.addTarget(f.groupId); + const a = await f.register(1); + await f.register(2); + await f.send(a, "failed"); + expect(apsOf(0).alert).toEqual({ title: "Bighelp", body: "A chat could not finish." }); + expect(apsOf(0)["content-state"]).toMatchObject({ lead: rowId(1) }); + }); + + it("keeps a moment at high priority even when the host marks the update quiet", async () => { + const f = await fixture("on"); + await f.addTarget(f.groupId); + const a = await f.register(1); + const b = await f.register(2); + await f.send(a, "waiting", { quiet: true }); + expect(priorityOf(0)).toBe("10"); + await f.send(b, "completed", { quiet: true }); + expect(priorityOf(1)).toBe("10"); + }); + + it("updates, then ends 30 seconds later and at once, when the last chat finishes", async () => { + const f = await fixture("on"); + await f.addTarget(f.groupId); + const a = await f.register(1); + await f.send(a, "completed"); + expect(apsOf(0).event).toBe("update"); + expect(apsOf(0)).not.toHaveProperty("dismissal-date"); + expect(apsOf(0).alert).toEqual({ title: "Bighelp", body: "A chat finished." }); + expect(apsOf(0)["content-state"]).toMatchObject({ activeCount: 0, lead: rowId(1) }); + expect(sent).toHaveLength(1); + // The alarm is set for the end, ahead of the hour-away lease purge registration set. + await runInDurableObject(f.stub, async (_instance, state) => { + expect(await state.storage.getAlarm()).toBeLessThanOrEqual(Date.now() + (ACTIVITY_END_DELAY_SECONDS + 2) * 1_000); + }); + + expect(await runAlarmAfterWait(f.stub)).toBe(true); + expect(sent).toHaveLength(2); + const end = apsOf(1); + expect(end).toMatchObject({ event: "end", "content-state": { activeCount: 0 } }); + expect(end).not.toHaveProperty("alert"); + expect(end.timestamp).toBeGreaterThanOrEqual(apsOf(0).timestamp + ACTIVITY_END_DELAY_SECONDS); + // The card leaves now, not 30 seconds from now. + expect(end["dismissal-date"]).toBeLessThanOrEqual(end.timestamp); + await runInDurableObject(f.stub, (_instance, state) => { + expect(state.storage.sql.exec("SELECT COUNT(*) AS count FROM managed_activity_pending_ends").one().count).toBe(0); + }); + // The group has ended: no chat can join it now. + await expect(f.register(2)).rejects.toThrow(); + }); + + it("still ends the card after the finished chat's own activity is closed, as the update route closes it", async () => { + const f = await fixture("on"); + await f.addTarget(f.groupId); + const a = await f.register(1); + await f.send(a, "thinking"); + await f.send(a, "completed"); + // The route marks a finished chat's activity ended as soon as its update is sent. + await runInDurableObject(f.stub, (_instance, state) => { + state.storage.sql.exec("UPDATE managed_notification_activities SET status='ended' WHERE activity_id=?", + a.activity.activityId); + }); + const before = sent.length; + await runAlarmAfterWait(f.stub); + expect(sent.length).toBe(before + 1); + expect(apsOf(before).event).toBe("end"); + }); + + it("keeps the moment for a host's retry when the first try never reached a push", async () => { + const f = await fixture("on"); + await f.addTarget(f.groupId); + const a = await f.register(1); + await f.send(a, "thinking"); + const timestamp = now() + 5; + const state = { id: a.activity.rowId!, phase: "completed", timestamp, activeSubagentCount: 0 }; + // The first try stored the row and then failed before any push was reserved. + await runInDurableObject(f.stub, (instance) => { + (instance as unknown as { notificationState: { updateActivityGroup(id: string, row: unknown, credential: string): unknown } }) + .notificationState.updateActivityGroup(a.activity.activityId, state, f.credentialId); + }); + const before = sent.length; + await f.send(a, "completed", { timestamp }); + // The retry is still news: the island opens, and the card stays for the wait. + expect(apsOf(before).event).toBe("update"); + expect(apsOf(before).alert).toEqual(activityMomentAlert("completed")); + await f.send(a, "completed", { timestamp }); + expect(apsOf(before + 1)).not.toHaveProperty("alert"); + }); + + it("does not end the card when a chat started working before the wait was over", async () => { + const f = await fixture("on"); + await f.addTarget(f.groupId); + const a = await f.register(1); + await f.send(a, "completed"); + await f.register(2); + expect(await runAlarmAfterWait(f.stub)).toBe(true); + expect(sent).toHaveLength(1); + expect(order).toEqual(["apns"]); + }); + + it("does not end the card early when the host resends the finished chat", async () => { + const f = await fixture("on"); + await f.addTarget(f.groupId); + const a = await f.register(1); + const timestamp = now(); + await f.send(a, "completed", { timestamp }); + await f.send(a, "completed", { timestamp }); + expect(apsOf(1).event).toBe("update"); + expect(apsOf(1)).not.toHaveProperty("alert"); + expect(apsOf(1)).not.toHaveProperty("dismissal-date"); + expect(await runAlarmAfterWait(f.stub)).toBe(true); + expect(sent).toHaveLength(3); + expect(apsOf(2).event).toBe("end"); + }); + + it("sends nothing for an end whose credential was revoked in the wait", async () => { + const f = await fixture("on"); + await f.addTarget(f.groupId); + const a = await f.register(1); + await f.send(a, "completed"); + await f.stub.revokeNotificationCredential({ credentialId: f.credentialId, authorizationEpoch: 2 }); + await runAlarmAfterWait(f.stub); + expect(sent).toHaveLength(1); + await runInDurableObject(f.stub, (_instance, state) => { + expect(state.storage.sql.exec("SELECT COUNT(*) AS count FROM managed_activity_pending_ends").one().count).toBe(0); + }); + }); +}); diff --git a/services/link/test/apns.test.ts b/services/link/test/apns.test.ts index 772255c6..5384f228 100644 --- a/services/link/test/apns.test.ts +++ b/services/link/test/apns.test.ts @@ -1515,6 +1515,19 @@ describe("Live Activity updates", () => { }); expect(spec.ttlSeconds).toBe(60); }); + + it("puts an alert in the payload only when one is given, and never a sound", () => { + const base = { event: "update" as const, activityId, contentState: { a: 1 }, timestamp: 10, staleDate: 20 }; + expect(liveActivitySpec(base, 10)!.payload).toEqual({ + aps: { timestamp: 10, event: "update", "content-state": { a: 1 }, "stale-date": 20 }, + }); + const spec = liveActivitySpec({ ...base, alert: { title: "Bighelp", body: "A chat needs you." } }, 10)!; + expect(spec.payload).toEqual({ + aps: { timestamp: 10, event: "update", "content-state": { a: 1 }, "stale-date": 20, + alert: { title: "Bighelp", body: "A chat needs you." } }, + }); + expect((spec.payload as { aps: object }).aps).not.toHaveProperty("sound"); + }); }); // MARK: Retry queue