Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 34 additions & 0 deletions Bighelp.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

31 changes: 31 additions & 0 deletions Bighelp/App/AppState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -180,13 +182,25 @@ 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() {
let showsOnlyConnections = !path.isEmpty && path.allSatisfy { $0 == .workspaceConnections }
if !showsOnlyConnections { path.removeAll() }
activatedConversationID = nil
pendingVoiceConversationID = nil
pendingReplyConversationID = nil
clearComposerText()
dropPendingShare()
}
Expand All @@ -195,6 +209,7 @@ final class AppState {
path.removeAll()
activatedConversationID = nil
pendingVoiceConversationID = nil
pendingReplyConversationID = nil
clearComposerText()
dropPendingShare()
}
Expand Down Expand Up @@ -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
}
}
31 changes: 31 additions & 0 deletions Bighelp/App/BighelpApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions Bighelp/App/BighelpIncomingURLRoute.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
4 changes: 4 additions & 0 deletions Bighelp/App/ChatDestinationView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 3 additions & 0 deletions Bighelp/App/RootShellView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
22 changes: 20 additions & 2 deletions Bighelp/Link/BighelpLinkApplePush.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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) {
Expand Down
69 changes: 69 additions & 0 deletions Bighelp/LiveActivity/IslandMomentPreview.swift
Original file line number Diff line number Diff line change
@@ -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
Loading