Files
hapi/ios/Hapi/Features/Chat/PendingRequests.swift
d0b0fde6cb 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 <noreply@hapi.run>
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-12-01 06:47:01 +08:00

201 lines
8.7 KiB
Swift

import HapiClient
import HapiProtocol
import HapiUI
import SwiftUI
/// One live request from `agentState.requests`, flattened for presentation.
/// Kept independent of the paginated transcript: an old question stays
/// reachable after its card scrolls out of the loaded window.
struct ChatPendingRequest: Identifiable, Equatable {
let id: String
let tool: String
let toolCallId: String?
let arguments: JSONValue?
let createdAt: Int
let kind: PendingRequestKind
var isAsyncQuestion: Bool {
guard isRequestUserInputToolName(tool),
let object = arguments?.chatObject,
case .bool(false) = object["isBlocking"] else { return false }
return true
}
/// One-line secondary text in the pending menu.
var detailText: String {
let args = arguments?.chatObject
if kind == .input {
if let questions = args?["questions"]?.chatArray,
let first = questions.first?.chatObject {
if let text = first["question"]?.chatString, !text.isEmpty { return text }
if let text = first["prompt"]?.chatString, !text.isEmpty { return text }
if let text = first["header"]?.chatString, !text.isEmpty { return text }
}
if let text = args?["question"]?.chatString, !text.isEmpty { return text }
if let text = args?["prompt"]?.chatString, !text.isEmpty { return text }
}
if let text = args?["command"]?.chatString, !text.isEmpty { return text }
if let text = args?["description"]?.chatString, !text.isEmpty { return text }
if let text = args?["path"]?.chatString, !text.isEmpty { return text }
if let text = args?["file_path"]?.chatString, !text.isEmpty { return text }
return tool
}
}
/// 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 {
ChatToolCall(
id: request.id,
name: request.tool,
state: .pending,
input: request.arguments,
createdAt: request.createdAt,
permission: ToolPermission(id: request.id, status: .pending)
)
}
/// Collapsible "Awaiting your reply" section above the composer. Mirrors the
/// web AsyncQuestionsPanel: non-blocking `request_user_input` questions stay
/// answerable even when their transcript card is not loaded.
struct PendingQuestionsPanel: View {
let interactor: ChatInteractor
let requests: [ChatPendingRequest]
let enabled: Bool
let targetRequestID: String?
let targetToken: Int
var onTargetConsumed: (() -> Void)? = nil
@Environment(\.hapiTheme) private var theme
@Environment(\.hapiTypography) private var typography
@State private var expanded = false
@State private var highlightedRequestID: String?
@State private var highlightTask: Task<Void, Never>?
var body: some View {
if !requests.isEmpty {
VStack(spacing: 0) {
Button {
withAnimation(.snappy(duration: 0.2)) { expanded.toggle() }
} label: {
HStack(spacing: 8) {
Image(systemName: expanded ? "chevron.down" : "chevron.right")
.font(typography.captionFont)
.foregroundStyle(theme.textSecondary)
.accessibilityHidden(true)
Text("Awaiting your reply")
.font(typography.toolTitleFont)
.foregroundStyle(theme.textPrimary)
Spacer(minLength: 8)
Text("\(requests.count)")
.font(typography.captionFont.monospacedDigit())
.padding(.horizontal, 7)
.padding(.vertical, 2)
.background(theme.surface, in: Capsule())
.foregroundStyle(theme.textSecondary)
}
.padding(.horizontal, 12)
.frame(minHeight: 44)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityIdentifier("pending-questions-toggle")
if expanded {
ScrollViewReader { proxy in
ScrollView {
VStack(alignment: .leading, spacing: 8) {
Text("These questions do not block the agent. Answer here, or leave the ones you no longer need.")
.font(typography.captionFont)
.foregroundStyle(theme.textSecondary)
.padding(.horizontal, 12)
ForEach(requests) { request in
VStack(alignment: .leading, spacing: 0) {
QuestionAnswerFormView(
tool: pendingRequestTool(request),
requestId: request.id,
enabled: enabled,
submitting: interactor.permissionOverrides[request.id] == .resolving,
openDetails: nil,
submit: { action in
interactor.resolvePermission(requestId: request.id, action: action)
}
)
}
.background(theme.surface, in: RoundedRectangle(cornerRadius: 14, style: .continuous))
.overlay {
if highlightedRequestID == request.id {
RoundedRectangle(cornerRadius: 14, style: .continuous)
.stroke(theme.warning, lineWidth: 2)
}
}
.id(request.id)
}
}
.padding(.horizontal, 8)
.padding(.bottom, 10)
}
.frame(maxHeight: 300)
.onChange(of: targetToken) { _, _ in
revealTarget(with: proxy)
}
.onAppear {
if targetRequestID != nil { revealTarget(with: proxy) }
}
}
}
}
.background(theme.background, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
.overlay {
RoundedRectangle(cornerRadius: 16, style: .continuous)
.stroke(theme.divider, lineWidth: 0.5)
}
.hapiReadingColumn()
.padding(.horizontal, 8)
.padding(.bottom, 6)
.onChange(of: targetToken) { _, _ in
guard targetRequestID != nil else { return }
expanded = true
}
.onDisappear { highlightTask?.cancel() }
}
}
private func revealTarget(with proxy: ScrollViewProxy) {
guard let targetRequestID,
requests.contains(where: { $0.id == targetRequestID }) else { return }
expanded = true
highlightedRequestID = targetRequestID
DispatchQueue.main.async {
withAnimation(.snappy(duration: 0.2)) {
proxy.scrollTo(targetRequestID, anchor: .center)
}
onTargetConsumed?()
}
highlightTask?.cancel()
highlightTask = Task {
try? await Task.sleep(for: .seconds(1.8))
guard !Task.isCancelled else { return }
highlightedRequestID = nil
}
}
}