diff --git a/ios/Hapi/Features/Chat/ChatModel.swift b/ios/Hapi/Features/Chat/ChatModel.swift index 336a3c80..ac17a297 100644 --- a/ios/Hapi/Features/Chat/ChatModel.swift +++ b/ios/Hapi/Features/Chat/ChatModel.swift @@ -175,6 +175,129 @@ final class ChatModel { showNotice(String(localized: "Reference copied")) } + // MARK: Pending requests + + /// Live `agentState.requests`, newest assumptions first: detail is + /// authoritative; the list summary is only a cold-start fallback (it + /// omits arguments, so the async panel waits for detail). + var pendingRequests: [ChatPendingRequest] { + let detail = hub.sessionStore.detail(for: sessionId) + let source = detail?.agentState?.requests + let requests: [ChatPendingRequest] + if let source { + requests = source.map { id, request in + ChatPendingRequest( + id: id, + tool: request.tool, + toolCallId: request.toolCallId, + arguments: request.arguments, + createdAt: request.createdAt ?? 0, + kind: pendingRequestKind(tool: request.tool) + ) + } + } else { + let summary = hub.sessionStore.sessions.first { $0.id == sessionId } + requests = (summary?.pendingRequests ?? []).map { request in + ChatPendingRequest( + id: request.id, + tool: request.tool, + toolCallId: nil, + arguments: nil, + createdAt: request.since, + kind: request.kind + ) + } + } + return requests.sorted { + $0.createdAt == $1.createdAt ? $0.id < $1.id : $0.createdAt < $1.createdAt + } + } + + /// Non-blocking request_user_input questions for the bottom panel. + var asyncPendingQuestions: [ChatPendingRequest] { + pendingRequests.filter(\.isAsyncQuestion) + } + + var canAnswerPendingRequests: Bool { + guard let detail = hub.sessionStore.detail(for: sessionId) else { return false } + let controlledByUser = detail.agentState?.controlledByUser == true + && detail.metadata?.capabilities?.concurrentClients != true + return detail.active && !controlledByUser + } + + /// Set when a pending request should reveal its async question panel. + private(set) var pendingQuestionTargetID: String? + private(set) var pendingQuestionTargetToken = 0 + /// Set when a pending request should scroll the transcript to a tool row. + private(set) var scrollTargetRowID: String? + private(set) var scrollTargetToken = 0 + /// Transient row highlight after a pending-request jump. + private(set) var highlightedRowID: String? + @ObservationIgnored private var highlightTask: Task? + + /// Route a pending-request selection to the bottom panel (async input) or + /// to its correlated transcript row (blocking permission / inline question). + func focusPendingRequest(_ id: String) { + guard let request = pendingRequests.first(where: { $0.id == id }) else { return } + if request.isAsyncQuestion { + pendingQuestionTargetID = id + pendingQuestionTargetToken += 1 + return + } + guard let rowID = rowID(for: request) else { + showNotice(String(localized: "This request is outside the loaded conversation. Scroll up to load it.")) + return + } + scrollTargetRowID = rowID + scrollTargetToken += 1 + flashRow(rowID) + } + + func clearPendingQuestionTarget() { + pendingQuestionTargetID = nil + } + + private func rowID(for request: ChatPendingRequest) -> String? { + let ids = Set([request.toolCallId, request.id].compactMap { $0 }) + for visible in blocks { + switch visible { + case .block(.toolCall(let block)): + if ids.contains(block.tool.id) || ids.contains(block.id) + || block.localId.map(ids.contains) == true { + return block.id + } + case .toolGroup(let group): + if group.tools.contains(where: { tool in + ids.contains(tool.tool.id) || ids.contains(tool.id) + || tool.localId.map(ids.contains) == true + }) { + return group.id + } + default: + continue + } + } + return nil + } + + private func flashRow(_ id: String) { + highlightedRowID = id + highlightTask?.cancel() + highlightTask = Task { [weak self] in + try? await Task.sleep(for: .seconds(1.8)) + guard !Task.isCancelled else { return } + self?.highlightedRowID = nil + } + } + + private func pendingRequestKind(tool: String) -> PendingRequestKind { + let inputTools: Set = [ + "AskUserQuestion", "ask_user_question", "CursorAskQuestion", + "ExitPlanMode", "exit_plan_mode", "request_user_input" + ] + return inputTools.contains(tool) ? .input : .permission + } + /// Loaded user messages with a native fork/rewind point, newest first. var historyPointMessages: [UserTextBlock] { blocks.reversed().compactMap { visible in diff --git a/ios/Hapi/Features/Chat/ChatTranscriptView.swift b/ios/Hapi/Features/Chat/ChatTranscriptView.swift index 91fed72d..7a1a0454 100644 --- a/ios/Hapi/Features/Chat/ChatTranscriptView.swift +++ b/ios/Hapi/Features/Chat/ChatTranscriptView.swift @@ -35,6 +35,7 @@ enum TranscriptRow: Identifiable, Equatable { struct ChatTranscriptView: View { @Environment(\.scenePhase) private var scenePhase + @Environment(\.hapiTheme) private var theme let model: ChatModel private var rows: [TranscriptRow] { @@ -58,6 +59,8 @@ struct ChatTranscriptView: View { jumpToken: model.jumpToLatestToken, historyControlID: TranscriptRow.historyID, isInspectionPresented: model.isInspectingContent, + scrollTargetID: model.scrollTargetRowID, + scrollTargetToken: model.scrollTargetToken, onViewport: { viewport in model.readingViewportChanged( followsTail: viewport.followsTail, needsOlder: viewport.needsOlder, @@ -71,7 +74,17 @@ struct ChatTranscriptView: View { spacingBefore: { previous, row in row.spacing(after: previous) } ) { row in // The list bridges the current environment into its hosting roots. - AnyView(rowView(row)) + AnyView( + rowView(row) + .overlay { + if model.highlightedRowID == row.id { + RoundedRectangle(cornerRadius: 12, style: .continuous) + .stroke(theme.warning, lineWidth: 2) + .padding(2) + .allowsHitTesting(false) + } + } + ) } .overlay(alignment: .bottomTrailing) { if model.showsJumpToLatest { diff --git a/ios/Hapi/Features/Chat/ChatView.swift b/ios/Hapi/Features/Chat/ChatView.swift index 45db1d98..f9234e4f 100644 --- a/ios/Hapi/Features/Chat/ChatView.swift +++ b/ios/Hapi/Features/Chat/ChatView.swift @@ -126,6 +126,14 @@ struct ChatView: View { } .safeAreaInset(edge: .bottom, spacing: 0) { VStack(spacing: 0) { + PendingQuestionsPanel( + interactor: model.interactor, + requests: model.asyncPendingQuestions, + enabled: model.canAnswerPendingRequests, + targetRequestID: model.pendingQuestionTargetID, + targetToken: model.pendingQuestionTargetToken, + onTargetConsumed: { model.clearPendingQuestionTarget() } + ) QueuedMessagesBarView(interactor: model.interactor) ChatComposerStatusBar(model: model) ChatComposerView( diff --git a/ios/Hapi/Features/Chat/Composer/ChatComposerStatusBar.swift b/ios/Hapi/Features/Chat/Composer/ChatComposerStatusBar.swift index 6914b983..9d3f0abc 100644 --- a/ios/Hapi/Features/Chat/Composer/ChatComposerStatusBar.swift +++ b/ios/Hapi/Features/Chat/Composer/ChatComposerStatusBar.swift @@ -24,6 +24,17 @@ struct ChatComposerStatusBar: View { model.interactor.config } + private var pendingLabel: String? { + let requests = model.pendingRequests + guard !requests.isEmpty else { return nil } + if requests.count > 1 { + return String(format: String(localized: "%lld pending requests"), Int64(requests.count)) + } + return requests[0].kind == .input + ? String(localized: "Needs reply") + : String(localized: "Approval required") + } + private var modelLabel: String? { // The transcript is more truthful than session.model for local Claude // sessions whose provider maps an alias to a different backend model. @@ -47,14 +58,18 @@ struct ChatComposerStatusBar: View { var body: some View { HStack(spacing: 8) { - HStack(spacing: 5) { - Circle() - .fill(status.color) - .frame(width: 6, height: 6) - Text(status.label) - .foregroundStyle(status.color) + if let pendingLabel { + pendingRequestControl(label: pendingLabel) + } else { + HStack(spacing: 5) { + Circle() + .fill(status.color) + .frame(width: 6, height: 6) + Text(status.label) + .foregroundStyle(status.color) + } + .lineLimit(1) } - .lineLimit(1) Spacer(minLength: 8) @@ -106,6 +121,51 @@ struct ChatComposerStatusBar: View { .accessibilityElement(children: .combine) } + /// Pending requests outrank the ordinary connection state, matching the + /// web status bar: one request is a direct jump, several open a menu. + @ViewBuilder + private func pendingRequestControl(label: String) -> some View { + let requests = model.pendingRequests + if requests.count == 1, let request = requests.first { + Button { + model.focusPendingRequest(request.id) + } label: { + pendingPill(label) + } + .buttonStyle(.plain) + .accessibilityIdentifier("pending-request-status") + } else { + Menu { + ForEach(requests) { request in + Button { + model.focusPendingRequest(request.id) + } label: { + Text(verbatim: "\(request.kind == .input ? String(localized: "Needs reply") : String(localized: "Approval required")) · \(request.detailText)") + } + } + } label: { + pendingPill(label) + } + .menuStyle(.borderlessButton) + .accessibilityIdentifier("pending-request-status") + } + } + + private func pendingPill(_ label: String) -> some View { + HStack(spacing: 5) { + Circle() + .fill(theme.warning) + .frame(width: 6, height: 6) + Text(verbatim: label) + .foregroundStyle(theme.warning) + .lineLimit(1) + Image(systemName: "chevron.up") + .font(.system(size: 8, weight: .semibold)) + .foregroundStyle(theme.warning) + } + .contentShape(Rectangle()) + } + /// Background-task count chip; tap opens the running task list instead of /// leaving a number with no explanation. private func backgroundTasksChip(count: Int, tasks: [HapiProtocol.BackgroundTask]?) -> some View { diff --git a/ios/Hapi/Features/Chat/PendingRequests.swift b/ios/Hapi/Features/Chat/PendingRequests.swift new file mode 100644 index 00000000..a60b30c5 --- /dev/null +++ b/ios/Hapi/Features/Chat/PendingRequests.swift @@ -0,0 +1,182 @@ +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 + } +} + +/// 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? + + 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 + } + } +} diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index 59c9e5aa..0dcdfc34 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -7135,6 +7135,61 @@ } } }, + "%lld pending requests" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld 项待处理" + } + } + } + }, + "Approval required" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "待批准" + } + } + } + }, + "Awaiting your reply" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "待回复" + } + } + } + }, + "These questions do not block the agent. Answer here, or leave the ones you no longer need." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "这些问题不会阻塞 Agent。可以在这里回复,或忽略不再需要的问题。" + } + } + } + }, + "This request is outside the loaded conversation. Scroll up to load it." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "这个请求不在已加载的会话中,请向上滚动加载。" + } + } + } + }, "New note" : { "extractionState" : "manual", "localizations" : { diff --git a/ios/HapiTests/PendingRequestPresentationTests.swift b/ios/HapiTests/PendingRequestPresentationTests.swift new file mode 100644 index 00000000..7f07a033 --- /dev/null +++ b/ios/HapiTests/PendingRequestPresentationTests.swift @@ -0,0 +1,58 @@ +import XCTest +@testable import Hapi +import HapiProtocol + +final class PendingRequestPresentationTests: XCTestCase { + private func request( + _ tool: String, + _ arguments: JSONValue?, + kind: PendingRequestKind = .input + ) -> ChatPendingRequest { + ChatPendingRequest( + id: "req-1", + tool: tool, + toolCallId: "call-1", + arguments: arguments, + createdAt: 1, + kind: kind + ) + } + + func testAsyncQuestionRequiresNonBlockingRequestUserInput() { + let async = request("request_user_input", .object([ + "isBlocking": .bool(false), + "questions": .array([ + .object(["id": .string("q1"), "question": .string("Pick a branch")]) + ]) + ])) + XCTAssertTrue(async.isAsyncQuestion) + XCTAssertEqual(async.detailText, "Pick a branch") + + let blocking = request("request_user_input", .object(["isBlocking": .bool(true)])) + XCTAssertFalse(blocking.isAsyncQuestion) + + let ask = request("AskUserQuestion", .object(["isBlocking": .bool(false)])) + XCTAssertFalse(ask.isAsyncQuestion) + } + + func testPermissionDetailFallsBackFromCommandToTool() { + XCTAssertEqual( + request("Bash", .object(["command": .string("rm -rf build")]), kind: .permission).detailText, + "rm -rf build" + ) + XCTAssertEqual( + request("Read", .object(["file_path": .string("/tmp/a.txt")]), kind: .permission).detailText, + "/tmp/a.txt" + ) + XCTAssertEqual(request("Bash", nil, kind: .permission).detailText, "Bash") + } + + func testSyntheticToolUsesTheRequestKeyAsTheReplyTarget() { + let tool = pendingRequestTool(request("request_user_input", .object([ + "isBlocking": .bool(false) + ]))) + XCTAssertEqual(tool.id, "req-1") + XCTAssertEqual(tool.permission?.id, "req-1") + XCTAssertEqual(tool.state, .pending) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Chat/AnchoredTranscriptList.swift b/ios/Packages/HapiKit/Sources/HapiUI/Chat/AnchoredTranscriptList.swift index f60c3ed0..d8c1345e 100644 --- a/ios/Packages/HapiKit/Sources/HapiUI/Chat/AnchoredTranscriptList.swift +++ b/ios/Packages/HapiKit/Sources/HapiUI/Chat/AnchoredTranscriptList.swift @@ -20,6 +20,10 @@ public struct AnchoredTranscriptList: UIViewCont public var jumpToken: Int public var historyControlID: String public var isInspectionPresented: Bool + /// Row to reveal after a pending-request/notification jump. The token + /// makes repeated jumps to the same row distinct. + public var scrollTargetID: String? + public var scrollTargetToken: Int public var onViewport: (TranscriptViewport) -> Void public var onLayout: (Int, Bool) -> Void public var onTailDisplayed: () -> Void @@ -29,6 +33,8 @@ public struct AnchoredTranscriptList: UIViewCont public init(items: [Item], historyVersion: Int, jumpToken: Int, historyControlID: String, isInspectionPresented: Bool = false, + scrollTargetID: String? = nil, + scrollTargetToken: Int = 0, onViewport: @escaping (TranscriptViewport) -> Void, onLayout: @escaping (Int, Bool) -> Void, onTailDisplayed: @escaping () -> Void = {}, @@ -39,6 +45,8 @@ public struct AnchoredTranscriptList: UIViewCont self.jumpToken = jumpToken self.historyControlID = historyControlID self.isInspectionPresented = isInspectionPresented + self.scrollTargetID = scrollTargetID + self.scrollTargetToken = scrollTargetToken self.onViewport = onViewport self.onLayout = onLayout self.onTailDisplayed = onTailDisplayed @@ -338,6 +346,7 @@ public final class TranscriptCollectionController oldHeight + 1 self.acknowledgeLayout(version: next.historyVersion, madeProgress: addedRows || grew) @@ -512,6 +523,22 @@ public final class TranscriptCollectionController, animated: Bool) { + guard next.scrollTargetToken != lastScrollTargetToken, + let targetID = next.scrollTargetID, + let index = items.firstIndex(where: { $0.id == targetID }) else { return } + lastScrollTargetToken = next.scrollTargetToken + layout.followsTail = false + layout.anchorForUpdate = nil + collection.scrollToItem( + at: IndexPath(item: index, section: 0), + at: .centeredVertically, + animated: animated + ) + } + private func acknowledgeLayout(version: Int, madeProgress: Bool) { guard version != renderedHistoryVersion else { return } renderedHistoryVersion = version