From d0b0fde6cb90f2dfebf1d8d96fcc31c65c4d8bca Mon Sep 17 00:00:00 2001 From: wusumac <736139669@qq.com> Date: Tue, 1 Dec 2026 06:47:01 +0800 Subject: [PATCH] feat(ios): jump notifications and session rows to the pending request Complete the pending-request center's entry points: - Push payloads already carry the request id for permission and input pushes; the notification tap now passes it through AppModel into the home screen instead of only the session id. - Opening a session row whose summary still has pending requests lands on the first wait (async questions first, since they live in the collapsible bottom panel; approvals scroll to their tool row). - ChatModel queues the jump until the detail's request dictionary arrives, so a cold notification start does not drop the target and a blocking target waits for the transcript to settle before scrolling. - A focus token lets the split detail re-fire for the session that is already open. Routing and pending-target presentation tests cover the new request id. via [HAPI](https://hapi.run) Co-Authored-By: HAPI Co-Authored-By: Claude Code --- ios/Hapi/Features/Chat/ChatModel.swift | 43 +++++++++++++ ios/Hapi/Features/Chat/ChatView.swift | 42 ++++++++++-- ios/Hapi/Features/Chat/PendingRequests.swift | 18 ++++++ ios/Hapi/Features/Home/HomeView.swift | 64 +++++++++++++++---- ios/Hapi/Models/AppModel.swift | 20 +++++- ios/Hapi/Models/PushCoordinator.swift | 13 ++-- ios/HapiTests/LiveActivityRoutingTests.swift | 1 + ios/HapiTests/NotificationRoutingTests.swift | 4 +- .../PendingRequestPresentationTests.swift | 15 ++++- 9 files changed, 194 insertions(+), 26 deletions(-) diff --git a/ios/Hapi/Features/Chat/ChatModel.swift b/ios/Hapi/Features/Chat/ChatModel.swift index ac17a297..ea193944 100644 --- a/ios/Hapi/Features/Chat/ChatModel.swift +++ b/ios/Hapi/Features/Chat/ChatModel.swift @@ -234,9 +234,14 @@ final class ChatModel { /// Transient row highlight after a pending-request jump. private(set) var highlightedRowID: String? @ObservationIgnored private var highlightTask: Task? + /// Jump requested by a notification tap or session-row attention icon + /// before the detail (and its request dictionary) was loaded. + @ObservationIgnored private var deferredPendingFocus: ChatPendingFocus? /// Route a pending-request selection to the bottom panel (async input) or /// to its correlated transcript row (blocking permission / inline question). + /// A target that is not live yet waits for the next detail application + /// instead of being dropped (cold notification start). func focusPendingRequest(_ id: String) { guard let request = pendingRequests.first(where: { $0.id == id }) else { return } if request.isAsyncQuestion { @@ -253,6 +258,42 @@ final class ChatModel { flashRow(rowID) } + /// Queue a pending-request jump; resolves immediately when the detail is + /// already loaded, otherwise on the next `apply` that carries it. + func requestPendingFocus(_ focus: ChatPendingFocus) { + deferredPendingFocus = focus + resolveDeferredPendingFocus(hasDetail: hub.sessionStore.detail(for: sessionId) != nil) + } + + private func resolveDeferredPendingFocus(hasDetail: Bool) { + guard let focus = deferredPendingFocus else { return } + // Summary requests carry no arguments: whether a request is an async + // question is only knowable from detail. A failed detail load falls + // back to the summary (blocking treatment only). + guard hasDetail || detailLoadFailed else { return } + switch focus { + case .request(let id): + guard let request = pendingRequests.first(where: { $0.id == id }) else { + // Detail is authoritative: an absent request was answered or + // expired elsewhere; opening the chat is still correct. + if hasDetail { deferredPendingFocus = nil } + return + } + // A blocking request needs its row; wait until the transcript + // settles so a cold start does not report "outside history". + guard request.isAsyncQuestion || !isInitialLoading else { return } + deferredPendingFocus = nil + focusPendingRequest(id) + case .firstAvailable: + let hasAsync = pendingRequests.contains(where: \.isAsyncQuestion) + guard hasAsync || !isInitialLoading else { return } + deferredPendingFocus = nil + if let target = pendingRequests.firstFocusTarget { + focusPendingRequest(target.id) + } + } + } + func clearPendingQuestionTarget() { pendingQuestionTargetID = nil } @@ -851,6 +892,8 @@ final class ChatModel { readThroughRevision = window.readThroughRevision renderedReadState = SessionReadState.merge(detail?.readState, summary?.readState) + // After isInitialLoading settles: a blocking target waits for rows. + resolveDeferredPendingFocus(hasDetail: detail != nil) } // MARK: - Header derivation (Android `buildHeader` port) diff --git a/ios/Hapi/Features/Chat/ChatView.swift b/ios/Hapi/Features/Chat/ChatView.swift index f9234e4f..8b88b2aa 100644 --- a/ios/Hapi/Features/Chat/ChatView.swift +++ b/ios/Hapi/Features/Chat/ChatView.swift @@ -40,6 +40,12 @@ struct ChatView: View { /// Resume/reopen handed back a superseding session id — the host swaps /// its navigation entry (HomeView replaces the path element). private let onNavigateToSession: ((String) -> Void)? + /// Pending-request jump carried in by a notification tap or a session-row + /// attention icon. `token` re-fires when the same session is already open + /// in a split view; the host clears the request after consumption. + private let pendingFocus: ChatPendingFocus? + private let pendingFocusToken: UUID? + private let onPendingFocusConsumed: (() -> Void)? /// Kept for the files/viewer pushes (the model owns its own reference). private let session: HubSession @@ -63,18 +69,37 @@ struct ChatView: View { init( session: HubSession, sessionId: String, - onNavigateToSession: ((String) -> Void)? = nil + onNavigateToSession: ((String) -> Void)? = nil, + pendingFocus: ChatPendingFocus? = nil, + pendingFocusToken: UUID? = nil, + onPendingFocusConsumed: (() -> Void)? = nil ) { - self.init(session: session, model: ChatModel(session: session, sessionId: sessionId), - onNavigateToSession: onNavigateToSession) + self.init( + session: session, + model: ChatModel(session: session, sessionId: sessionId), + onNavigateToSession: onNavigateToSession, + pendingFocus: pendingFocus, + pendingFocusToken: pendingFocusToken, + onPendingFocusConsumed: onPendingFocusConsumed + ) } - init(session: HubSession, model: ChatModel, onNavigateToSession: ((String) -> Void)? = nil) { + init( + session: HubSession, + model: ChatModel, + onNavigateToSession: ((String) -> Void)? = nil, + pendingFocus: ChatPendingFocus? = nil, + pendingFocusToken: UUID? = nil, + onPendingFocusConsumed: (() -> Void)? = nil + ) { _model = State(initialValue: model) _configModel = State(initialValue: SessionConfigModel(interactor: model.interactor)) self.session = session self.sessionId = model.sessionId self.onNavigateToSession = onNavigateToSession + self.pendingFocus = pendingFocus + self.pendingFocusToken = pendingFocusToken + self.onPendingFocusConsumed = onPendingFocusConsumed } private var content: some View { @@ -94,6 +119,15 @@ struct ChatView: View { ChatTranscriptView(model: model) } } + // A notification tap or row attention icon can target this chat + // before its detail loads; the model keeps the jump queued until the + // request dictionary arrives. `token` covers the same session already + // being open in a split view. + .task(id: pendingFocusToken) { + guard let pendingFocus else { return } + model.requestPendingFocus(pendingFocus) + onPendingFocusConsumed?() + } } var body: some View { diff --git a/ios/Hapi/Features/Chat/PendingRequests.swift b/ios/Hapi/Features/Chat/PendingRequests.swift index a60b30c5..0f1d82f5 100644 --- a/ios/Hapi/Features/Chat/PendingRequests.swift +++ b/ios/Hapi/Features/Chat/PendingRequests.swift @@ -42,6 +42,24 @@ struct ChatPendingRequest: Identifiable, Equatable { } } +/// A pending-request jump requested before the chat's detail (and therefore +/// the request dictionary) has loaded — a notification tap or a session-row +/// attention icon. Resolved once per arriving detail, then discarded. +enum ChatPendingFocus: Equatable { + /// The list row only carries counts/kinds: land on the first wait, with + /// async questions ahead of blocking approvals (they live in the + /// always-available bottom panel). + case firstAvailable + /// A notification names the exact request. + case request(String) +} + +extension Array where Element == ChatPendingRequest { + var firstFocusTarget: ChatPendingRequest? { + first(where: \.isAsyncQuestion) ?? first + } +} + /// Build the synthetic tool call the existing question form expects. The /// request dictionary key (not the correlated tool id) is the reply target. func pendingRequestTool(_ request: ChatPendingRequest) -> ChatToolCall { diff --git a/ios/Hapi/Features/Home/HomeView.swift b/ios/Hapi/Features/Home/HomeView.swift index 012eb3a5..df8372d3 100644 --- a/ios/Hapi/Features/Home/HomeView.swift +++ b/ios/Hapi/Features/Home/HomeView.swift @@ -15,6 +15,14 @@ private struct NewSessionSeed: Identifiable { let directory: String } +/// One-shot pending-request jump handed to a chat. `token` makes a repeat +/// request for the session already open in the split detail fire again. +private struct ChatOpenFocus: Equatable { + let sessionId: String + let target: ChatPendingFocus + let token: UUID +} + struct HomeView: View { let session: HubSession @@ -26,6 +34,9 @@ struct HomeView: View { @State private var showSettings = false @State private var path: [String] = [] @State private var tabletNavigation = SessionNavigationState() + /// Pending request to reveal when the chat appears (notification tap or + /// row attention icon). Cleared by the chat after it hands it to its model. + @State private var chatOpenFocus: ChatOpenFocus? /// Transient connection states show only after `connectionRevealDelay`: /// a foreground reconnect usually finishes first (Telegram-style). @State private var connectionStatusRevealed = false @@ -86,8 +97,10 @@ struct HomeView: View { // the app before this view existed. .onChange(of: model.pendingOpenSessionId, initial: true) { _, sessionId in guard let sessionId else { return } + let requestId = model.pendingOpenRequestId model.pendingOpenSessionId = nil - openSession(sessionId) + model.pendingOpenRequestId = nil + openSession(sessionId, focus: requestId.map(ChatPendingFocus.request)) } .onChange(of: session.sessionRemoval) { _, removal in guard let removal else { return } @@ -163,7 +176,7 @@ struct HomeView: View { // not an authoritative removal and must not close the chat. set: { if let id = $0 { openSession(id) } } ) : nil, - onOpenSession: openSession, + onOpenSession: { openSession($0) }, onNewSessionInDirectory: { machineId, directory in presentNewSession(NewSessionSeed(machineId: machineId, directory: directory)) } @@ -287,10 +300,17 @@ struct HomeView: View { listModel.searchQuery = "" } - private func openSession(_ sessionId: String) { + /// Opening a row that still has a pending request lands on it. The + /// attention icon is part of the row, so a tap there follows the same + /// path; an explicit `focus` (notification request id) wins. + private func openSession(_ sessionId: String, focus: ChatPendingFocus? = nil) { if searchOpen { closeSearch() } + let target = focus ?? pendingFocusForRow(sessionId) + chatOpenFocus = target.map { + ChatOpenFocus(sessionId: sessionId, target: $0, token: UUID()) + } if usesSplitNavigation { tabletNavigation.open(sessionId) } else if path.last != sessionId { @@ -298,15 +318,37 @@ struct HomeView: View { } } - private func chat(_ sessionId: String) -> some View { - ChatView(session: session, sessionId: sessionId) { superseding in - if usesSplitNavigation { - tabletNavigation.supersede(sessionId, with: superseding) - } else if let last = path.indices.last, path[last] == sessionId { - path[last] = superseding - } - // A late response from a chat already left must not steal focus. + /// The row summary knows only counts/kinds; the chat resolves the exact + /// request once its detail arrives. + private func pendingFocusForRow(_ sessionId: String) -> ChatPendingFocus? { + guard listModel.rows.first(where: { $0.id == sessionId })?.status != nil else { + return nil } + return .firstAvailable + } + + private func chat(_ sessionId: String) -> some View { + let focus = chatOpenFocus?.sessionId == sessionId ? chatOpenFocus : nil + return ChatView( + session: session, + sessionId: sessionId, + onNavigateToSession: { superseding in + if usesSplitNavigation { + tabletNavigation.supersede(sessionId, with: superseding) + } else if let last = path.indices.last, path[last] == sessionId { + path[last] = superseding + } + // A late response from a chat already left must not steal focus. + }, + pendingFocus: focus?.target, + pendingFocusToken: focus?.token, + onPendingFocusConsumed: { + // A newer request (possibly for another session) is not ours. + if chatOpenFocus?.token == focus?.token { + chatOpenFocus = nil + } + } + ) .id(sessionId) } diff --git a/ios/Hapi/Models/AppModel.swift b/ios/Hapi/Models/AppModel.swift index 77acb994..a557aa88 100644 --- a/ios/Hapi/Models/AppModel.swift +++ b/ios/Hapi/Models/AppModel.swift @@ -49,6 +49,10 @@ final class AppModel { /// navigation path against the active hub (switched to the owner first, /// see ``openNotificationTarget(sessionId:hubUrl:)``). var pendingOpenSessionId: String? + /// Specific pending request carried by the same notification tap + /// (`requestId`); nil for a plain ready/tap-to-open push, where the chat + /// opens at the first live request when the session has one. + var pendingOpenRequestId: String? /// Incremented by `hapicompanion://sessions`; HomeView pops to the list. private(set) var sessionListRequest = 0 @@ -97,8 +101,12 @@ final class AppModel { activeHubKnowsSession: { [weak self] sessionId in self?.session?.sessionStore.sessions.contains { $0.id == sessionId } ?? false }, - openSession: { [weak self] sessionId, hubUrl in - self?.openNotificationTarget(sessionId: sessionId, hubUrl: hubUrl) + openSession: { [weak self] sessionId, hubUrl, requestId in + self?.openNotificationTarget( + sessionId: sessionId, + hubUrl: hubUrl, + requestId: requestId + ) } )) } @@ -197,10 +205,15 @@ final class AppModel { /// Notification tap: a located owning hub becomes active first, so the /// new home screen consumes the target (`HomeView` is keyed by hub). - func openNotificationTarget(sessionId: String, hubUrl: String?) { + func openNotificationTarget( + sessionId: String, + hubUrl: String?, + requestId: String? = nil + ) { if let hubUrl, registry.hubs.contains(hubUrl), hasCredentials(for: hubUrl) { switchHub(to: hubUrl) } + pendingOpenRequestId = requestId pendingOpenSessionId = sessionId } @@ -249,6 +262,7 @@ final class AppModel { /// hub instead of opening whichever session happened to be first. func openSessionList() { pendingOpenSessionId = nil + pendingOpenRequestId = nil sessionListRequest += 1 } diff --git a/ios/Hapi/Models/PushCoordinator.swift b/ios/Hapi/Models/PushCoordinator.swift index 6d3c6f9a..1b903e3a 100644 --- a/ios/Hapi/Models/PushCoordinator.swift +++ b/ios/Hapi/Models/PushCoordinator.swift @@ -97,8 +97,9 @@ final class PushCoordinator: NSObject { let activeHubKnowsSession: @MainActor (String) -> Bool /// Tap-through navigation: switch to the owning hub when one was /// located (nil = stay on the active hub), then stash the target - /// session for the home screen (Android `pendingOpenSessionId`). - let openSession: @MainActor (_ sessionId: String, _ hubUrl: String?) -> Void + /// session (and the exact pending request, when the push names one) + /// for the home screen (Android `pendingOpenSessionId`). + let openSession: @MainActor (_ sessionId: String, _ hubUrl: String?, _ requestId: String?) -> Void } // MARK: - Observable state (Settings row) @@ -375,7 +376,9 @@ extension PushCoordinator: UNUserNotificationCenterDelegate { } switch response.actionIdentifier { case UNNotificationDefaultActionIdentifier: - await openSession(payload.sessionId) + // Permission and input pushes both carry the request id; a plain + // ready push has none and the chat falls back to its first wait. + await openSession(payload.sessionId, requestId: payload.requestId) case ActionID.allow: guard payload.type == .permissionRequest, payload.supportsActions, let requestId = payload.requestId else { return } @@ -412,14 +415,14 @@ extension PushCoordinator: UNUserNotificationCenterDelegate { /// a session the active list does not know is located first (active hub /// first, like the actions). A miss or an unreachable owner falls back /// to the active hub. - private func openSession(_ sessionId: String) async { + private func openSession(_ sessionId: String, requestId: String?) async { guard let environment else { return } var owner: String? if hubsActiveFirst().count > 1, !environment.activeHubKnowsSession(sessionId), case .success(let hubUrl) = await actionRunner().locate(sessionId: sessionId) { owner = hubUrl } - environment.openSession(sessionId, owner) + environment.openSession(sessionId, owner, requestId) } private func actionRunner() -> PushActionRunner { diff --git a/ios/HapiTests/LiveActivityRoutingTests.swift b/ios/HapiTests/LiveActivityRoutingTests.swift index 49afcac7..f575a98e 100644 --- a/ios/HapiTests/LiveActivityRoutingTests.swift +++ b/ios/HapiTests/LiveActivityRoutingTests.swift @@ -27,6 +27,7 @@ final class LiveActivityRoutingTests: XCTestCase { )) XCTAssertEqual(model.pendingOpenSessionId, "sess-1") + XCTAssertNil(model.pendingOpenRequestId) XCTAssertEqual(model.state, .unpaired) } diff --git a/ios/HapiTests/NotificationRoutingTests.swift b/ios/HapiTests/NotificationRoutingTests.swift index 0825a1e9..a93ee689 100644 --- a/ios/HapiTests/NotificationRoutingTests.swift +++ b/ios/HapiTests/NotificationRoutingTests.swift @@ -81,12 +81,14 @@ final class NotificationRoutingTests: XCTestCase { let model = AppModel(registry: registry, credentialStore: try credentials([hubA, hubB]), performer: OwnerHTTP()) XCTAssertEqual(model.state, .paired(activeHub: hubA)) - model.openNotificationTarget(sessionId: "s-b", hubUrl: hubB) + model.openNotificationTarget(sessionId: "s-b", hubUrl: hubB, requestId: "req-9") XCTAssertEqual(model.state, .paired(activeHub: hubB)) XCTAssertEqual(model.pendingOpenSessionId, "s-b") + XCTAssertEqual(model.pendingOpenRequestId, "req-9") // No located owner (or an unpaired one): stay on the active hub. model.openNotificationTarget(sessionId: "s-x", hubUrl: nil) + XCTAssertNil(model.pendingOpenRequestId, "a plain push clears an earlier request id") model.openNotificationTarget(sessionId: "s-y", hubUrl: "https://unpaired.example.com") XCTAssertEqual(model.state, .paired(activeHub: hubB)) XCTAssertEqual(model.pendingOpenSessionId, "s-y") diff --git a/ios/HapiTests/PendingRequestPresentationTests.swift b/ios/HapiTests/PendingRequestPresentationTests.swift index 7f07a033..15f9e7c6 100644 --- a/ios/HapiTests/PendingRequestPresentationTests.swift +++ b/ios/HapiTests/PendingRequestPresentationTests.swift @@ -6,10 +6,11 @@ final class PendingRequestPresentationTests: XCTestCase { private func request( _ tool: String, _ arguments: JSONValue?, - kind: PendingRequestKind = .input + kind: PendingRequestKind = .input, + id: String = "req-1" ) -> ChatPendingRequest { ChatPendingRequest( - id: "req-1", + id: id, tool: tool, toolCallId: "call-1", arguments: arguments, @@ -47,6 +48,16 @@ final class PendingRequestPresentationTests: XCTestCase { XCTAssertEqual(request("Bash", nil, kind: .permission).detailText, "Bash") } + func testFirstFocusTargetPrefersAnAsyncQuestion() { + let permission = request("Bash", nil, kind: .permission, id: "approval") + let async = request("request_user_input", .object([ + "isBlocking": .bool(false) + ]), id: "question") + XCTAssertEqual([permission, async].firstFocusTarget, async) + XCTAssertEqual([permission].firstFocusTarget, permission) + XCTAssertNil([ChatPendingRequest]().firstFocusTarget) + } + func testSyntheticToolUsesTheRequestKeyAsTheReplyTarget() { let tool = pendingRequestTool(request("request_user_input", .object([ "isBlocking": .bool(false)