From 7e7b16767bd2e5863571a6b0a394ec7f94c5f51d Mon Sep 17 00:00:00 2001 From: Ananovo Date: Sun, 13 Sep 2026 18:56:56 +0800 Subject: [PATCH 01/27] fix(android): stabilize tool group inspection on API 36 (#1843) --- .../feature/chat/InspectionReadersTest.kt | 31 ++++++++++++++++--- .../hapi/companion/feature/chat/ChatHost.kt | 12 +++++-- 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/InspectionReadersTest.kt b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/InspectionReadersTest.kt index f56ae53b..a85d84cb 100644 --- a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/InspectionReadersTest.kt +++ b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/InspectionReadersTest.kt @@ -75,23 +75,44 @@ class InspectionReadersTest { ToolGroupingOptions(hasMoreMessages = false), ).filterIsInstance().single() + // LazyColumn initial positioning and scroll-to-item can settle after a + // recomposition on API 36; do not race the semantics tree by one frame. + private fun waitForDisplayed(tag: String) { + try { + compose.waitUntil(10_000) { + try { + compose.onNodeWithTag(tag).assertIsDisplayed() + true + } catch (_: AssertionError) { + false + } + } + } catch (timeout: ComposeTimeoutException) { + val failure = AssertionError("Timed out waiting for displayed node <$tag>") + failure.initCause(timeout) + throw failure + } + } + @Test fun toolBrowserStartsAtLatestButDoesNotFollowUpdatesWhileReading() { val inspected = mutableStateOf(Inspected(group(200), false)) var selected: String? = null compose.setContent { HapiTheme { ToolGroupBrowser(inspected.value, "/repo", { selected = it }, {}, {}) } } - compose.onNodeWithTag("inspection-tool-tool-200").assertIsDisplayed() + waitForDisplayed("inspection-tool-tool-200") compose.onNodeWithTag("inspection-tools").performScrollToIndex(30) - compose.onNodeWithTag("inspection-tool-tool-31").assertIsDisplayed() + waitForDisplayed("inspection-tool-tool-31") compose.runOnIdle { inspected.value = Inspected(group(201), false) } - compose.onNodeWithTag("inspection-tool-tool-31").assertIsDisplayed().performClick() + waitForDisplayed("inspection-tool-tool-31") + compose.onNodeWithTag("inspection-tool-tool-31").performClick() compose.runOnIdle { assertEquals("tool-31", selected) } compose.onNodeWithTag("inspection-tool-tool-201").assertDoesNotExist() + waitForDisplayed("inspection-latest-tool") compose.onNodeWithTag("inspection-latest-tool").performClick() - compose.onNodeWithTag("inspection-tool-tool-201").assertIsDisplayed() + waitForDisplayed("inspection-tool-tool-201") compose.runOnIdle { inspected.value = inspected.value.copy(stale = true) } - compose.onNodeWithTag("inspection-notice").assertIsDisplayed() + waitForDisplayed("inspection-notice") } @Test fun fullContentUsesExactClipboardTextOrAReadableGrantedUri() { diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatHost.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatHost.kt index 572e59b9..2b7b9374 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatHost.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatHost.kt @@ -217,6 +217,9 @@ internal fun ToolGroupBrowser( val list = rememberLazyListState(initialFirstVisibleItemIndex = (group.tools.size - 1).coerceAtLeast(0)) val scope = rememberCoroutineScope() val resources = LocalContext.current.resources + LaunchedEffect(Unit) { + if (group.tools.isNotEmpty()) list.scrollToItem(group.tools.lastIndex) + } InspectionScaffold(stringResource(R.string.chat_group_tools_many, group.summary.totalTools), back, close, actions = { IconButton(onClick = { scope.launch { if (group.tools.isNotEmpty()) list.scrollToItem(group.tools.lastIndex) } }, @@ -225,10 +228,13 @@ internal fun ToolGroupBrowser( } }, ) { padding -> - ReadingColumn(Modifier.padding(padding)) { - Column { + ReadingColumn(Modifier.padding(padding).fillMaxSize()) { + Column(Modifier.fillMaxSize()) { InspectionNotice(inspected.stale, group.needsOlderHistory) - LazyColumn(state = list, modifier = Modifier.fillMaxSize().testTag("inspection-tools")) { + LazyColumn( + state = list, + modifier = Modifier.weight(1f).fillMaxWidth().testTag("inspection-tools"), + ) { items(group.tools, key = { it.id }, contentType = { "tool-summary" }) { block -> val presentation = remember(block.tool.name, block.tool.input, block.tool.description, basePath, resources) { toolSummaryPresentation(block.tool, basePath, resources) From 93d89c7cf4ea54d54ca171c729b8aa059843138d Mon Sep 17 00:00:00 2001 From: weishu Date: Sun, 13 Sep 2026 19:19:52 +0800 Subject: [PATCH 02/27] fix(ios): keep latest button hidden after tool inspection at bottom --- docs/native-chat-scrolling.md | 11 ++- ios/Hapi/Features/Chat/ChatModel.swift | 11 +-- ios/HapiTests/ChatHistoryPumpTests.swift | 21 +++-- .../ToolTranscriptPresentationTests.swift | 86 ++++++++++++++++++- ios/README.md | 6 +- 5 files changed, 112 insertions(+), 23 deletions(-) diff --git a/docs/native-chat-scrolling.md b/docs/native-chat-scrolling.md index 54deff86..6148a008 100644 --- a/docs/native-chat-scrolling.md +++ b/docs/native-chat-scrolling.md @@ -64,10 +64,13 @@ upward drags keep their reading offset without immediately showing the button. It appears at 80pt from the retained bottom and hides at 24pt, retaining its previous visibility between those thresholds. Hiding never resumes following; the actual-bottom tolerance remains 1pt. The collection reports a hysteretic -Boolean rather than publishing per-frame distances. A trimmed live tail, -in-flight latest navigation, or an inspection pause awaiting explicit resume -keeps the action available regardless of proximity. Failed catch-up retains -the retry action. Thresholds do not change history demand or retention. +Boolean rather than publishing per-frame distances. A trimmed live tail or +in-flight latest navigation keeps the action available regardless of proximity. +Inspection alone does not: opening/closing a sheet at bottom leaves the action +hidden, including output updates that do not resize transcript rows. New visible +content can reveal it through the same distance thresholds without moving the +reading anchor. Failed catch-up retains the retry action. Thresholds do not +change history demand or retention. Visible-rectangle queries binary-search the ordered frame array, then visit only intersecting rows (`O(log n + visible rows)`). Height changes update the diff --git a/ios/Hapi/Features/Chat/ChatModel.swift b/ios/Hapi/Features/Chat/ChatModel.swift index 03682a02..c072f968 100644 --- a/ios/Hapi/Features/Chat/ChatModel.swift +++ b/ios/Hapi/Features/Chat/ChatModel.swift @@ -61,10 +61,8 @@ final class ChatModel { private(set) var isJumpingToLatest = false private(set) var hasTrimmedTail = false private var isAwayFromBottom = false - private var resumeAfterInspection = false var showsJumpToLatest: Bool { - isJumpingToLatest || hasTrimmedTail - || (!followsTail && (isAwayFromBottom || resumeAfterInspection)) + isJumpingToLatest || hasTrimmedTail || (!followsTail && isAwayFromBottom) } let toolInspection = ToolInspectionState() private(set) var visibleSurfaces = Set() @@ -172,9 +170,8 @@ final class ChatModel { jumpTask?.cancel() jumpTask = nil isJumpingToLatest = false - // Closing an inspector must leave an explicit resume action even - // when no content has arrived and the reading anchor is at bottom. - resumeAfterInspection = true + // Pause following/paging without claiming the reader left the bottom. + // The latest action still depends on viewport distance or a trimmed tail. readingViewportChanged(followsTail: false, needsOlder: false, isAwayFromBottom: isAwayFromBottom) } @@ -289,7 +286,6 @@ final class ChatModel { let changedMode = self.followsTail != followsTail self.followsTail = followsTail self.isAwayFromBottom = !followsTail && isAwayFromBottom - if followsTail && !hasTrimmedTail { resumeAfterInspection = false } viewportNeedsOlder = needsOlder if changedMode, !isJumpingToLatest, let controller = chat.windowController { if followsTail && hasTrimmedTail { jumpToLatest(); return } @@ -419,7 +415,6 @@ final class ChatModel { guard !Task.isCancelled, self.chat === chat else { return } self.followsTail = true self.isAwayFromBottom = false - self.resumeAfterInspection = false self.jumpToLatestToken += 1 } } diff --git a/ios/HapiTests/ChatHistoryPumpTests.swift b/ios/HapiTests/ChatHistoryPumpTests.swift index e57c52e5..0da72798 100644 --- a/ios/HapiTests/ChatHistoryPumpTests.swift +++ b/ios/HapiTests/ChatHistoryPumpTests.swift @@ -63,7 +63,7 @@ final class ChatHistoryPumpTests: XCTestCase { await controller.syncTail(ensureAfterCurrent: true) let initialRevision = await controller.state.tailRevision model.beginContentInspection() - XCTAssertTrue(model.showsJumpToLatest, "Inspection keeps an explicit resume action even at bottom") + XCTAssertFalse(model.showsJumpToLatest, "Pausing inspection at bottom must not reveal the action") model.retainSurface("inspector:chat") model.retainSurface("inspector:chat") // Idempotent appearance. model.releaseSurface("chat") @@ -86,25 +86,27 @@ final class ChatHistoryPumpTests: XCTestCase { XCTAssertTrue(model.isInspectingContent) model.readingViewportChanged(followsTail: true, needsOlder: true, isAwayFromBottom: false) XCTAssertFalse(model.followsTail) - XCTAssertTrue(model.showsJumpToLatest) + XCTAssertFalse(model.showsJumpToLatest) try await Task.sleep(for: .milliseconds(30)) let olderRequests = await performer.beforeRequests XCTAssertEqual(olderRequests, 0) model.releaseSurface("message:chat") XCTAssertFalse(model.isInspectingContent) XCTAssertFalse(model.followsTail, "Closing the reader must not silently return to latest") - XCTAssertTrue(model.showsJumpToLatest, "Closing must not hide the only resume action") + XCTAssertFalse(model.showsJumpToLatest, "Closing at bottom must not create a resume action") + model.readingViewportChanged(followsTail: false, needsOlder: false, isAwayFromBottom: true) + XCTAssertTrue(model.showsJumpToLatest, "Real distance from bottom still provides a resume action") let jump = model.jumpToLatestToken model.jumpToLatest() try await eventually { model.jumpToLatestToken > jump && !model.isJumpingToLatest } XCTAssertTrue(model.followsTail) XCTAssertFalse(model.showsJumpToLatest) model.readingViewportChanged(followsTail: false, needsOlder: false, isAwayFromBottom: false) - XCTAssertFalse(model.showsJumpToLatest, "A completed jump must clear the inspection exception") + XCTAssertFalse(model.showsJumpToLatest) model.beginContentInspection() - XCTAssertTrue(model.showsJumpToLatest) + XCTAssertFalse(model.showsJumpToLatest, "Repeated inspection must not latch the action on") model.readingViewportChanged(followsTail: true, needsOlder: false, isAwayFromBottom: false) - XCTAssertFalse(model.showsJumpToLatest, "Manually reaching bottom also clears the inspection exception") + XCTAssertFalse(model.showsJumpToLatest) model.readingViewportChanged(followsTail: false, needsOlder: false, isAwayFromBottom: false) XCTAssertFalse(model.showsJumpToLatest) model.releaseSurface("chat") @@ -120,7 +122,7 @@ final class ChatHistoryPumpTests: XCTestCase { credentialStore: credentials, performer: performer)) let model = ChatModel(session: hub, sessionId: "latest-visibility") defer { model.stop(); hub.shutdown() } - model.start() + model.retainSurface("chat") try await eventually { !model.blocks.isEmpty && !model.isSyncingTail } let controller = await hub.windows.open(sessionId: model.sessionId) await controller.syncTail(ensureAfterCurrent: true) @@ -159,6 +161,11 @@ final class ChatHistoryPumpTests: XCTestCase { await controller.ingestSSEMessages(messages) try await eventually { model.hasTrimmedTail } XCTAssertTrue(model.showsJumpToLatest) + model.beginContentInspection() + model.retainSurface("inspector:chat") + model.readingViewportChanged(followsTail: true, needsOlder: false, isAwayFromBottom: false) + model.releaseSurface("inspector:chat") + XCTAssertTrue(model.showsJumpToLatest, "Inspection at a trimmed bottom must keep the recovery action") let retained = await controller.state.messages.map(\.id) let jump = model.jumpToLatestToken var requests = await performer.latestRequests diff --git a/ios/HapiTests/ToolTranscriptPresentationTests.swift b/ios/HapiTests/ToolTranscriptPresentationTests.swift index dc8b4dad..ce04f7f0 100644 --- a/ios/HapiTests/ToolTranscriptPresentationTests.swift +++ b/ios/HapiTests/ToolTranscriptPresentationTests.swift @@ -80,6 +80,7 @@ final class ToolTranscriptPresentationTests: XCTestCase { if size == .large { XCTAssertLessThanOrEqual(summary.frame.height, 100) } } try capture(window, name: name) + XCTAssertFalse(model.showsJumpToLatest) let cell = try XCTUnwrap(collection.visibleCells .filter { $0.accessibilityIdentifier != "chat-row-chat-history-control" } .sorted { $0.frame.minY < $1.frame.minY }.first) @@ -89,7 +90,7 @@ final class ToolTranscriptPresentationTests: XCTestCase { try await eventually { host.presentedViewController != nil && !model.followsTail } try await Task.sleep(for: .milliseconds(600)) XCTAssertTrue(model.isInspectingContent) - XCTAssertTrue(model.showsJumpToLatest, "Viewport proximity must not hide an inspection's resume action") + XCTAssertFalse(model.showsJumpToLatest, "Opening a sheet is not a departure from the bottom") XCTAssertNil(model.toolInspection.selection, "Group root must pause following without a selected tool") XCTAssertEqual(collection.numberOfItems(inSection: 0), 6) let presented = try XCTUnwrap(host.presentedViewController) @@ -126,11 +127,92 @@ final class ToolTranscriptPresentationTests: XCTestCase { let restored = try XCTUnwrap(collection.visibleCells.first { $0.accessibilityIdentifier == anchorID }) XCTAssertEqual(restored.frame.minY - collection.contentOffset.y, anchorY, accuracy: 1) XCTAssertFalse(model.followsTail) - XCTAssertTrue(model.showsJumpToLatest, "The real transcript must retain its resume action after dismissal") + XCTAssertFalse(model.showsJumpToLatest, "Output-only updates must not create a latest action at bottom") XCTAssertEqual(collection.numberOfItems(inSection: 0), 6) } } + func testToolSheetLatestVisibilityTracksActualBottomDistance() async throws { + let credentials = InMemoryCredentialStore() + let payload = Data(#"{"uid":1,"exp":4102444800,"ns":"test"}"#.utf8).base64EncodedString() + try credentials.store(HubCredentials(hubUrl: "http://127.0.0.1:1", accessToken: "test", jwt: "e30.\(payload).test")) + let hub = try XCTUnwrap(HubSession(hubUrl: "http://127.0.0.1:1/inspection-latest-\(UUID().uuidString)", + credentialStore: credentials, performer: ToolTranscriptHTTP())) + let model = ChatModel(session: hub, sessionId: "inspection-latest") + defer { model.stop(); hub.shutdown() } + model.start() + try await eventually { !model.blocks.isEmpty && !model.isSyncingTail } + let group = try XCTUnwrap(model.blocks.compactMap { block -> ToolGroupBlock? in + if case .toolGroup(let group) = block { return group } + return nil + }.last) + let tool = try XCTUnwrap(group.tools.first) + let controller = await hub.windows.open(sessionId: model.sessionId) + await controller.syncTail(ensureAfterCurrent: true) + let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + let window = UIWindow(windowScene: scene) + window.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + let host = UIHostingController(rootView: Harness(model: model, session: hub, theme: .light, size: .large)) + window.rootViewController = host + window.makeKeyAndVisible() + defer { window.isHidden = true } + host.view.layoutIfNeeded() + let collection = try XCTUnwrap(findCollection(host.view)) + try await eventually { collection.numberOfItems(inSection: 0) == 6 } + try await Task.sleep(for: .milliseconds(250)) + let bottomOffset = max(-collection.adjustedContentInset.top, + collection.contentSize.height - collection.bounds.height + collection.adjustedContentInset.bottom) + XCTAssertEqual(collection.contentOffset.y, bottomOffset, accuracy: 1) + XCTAssertFalse(model.showsJumpToLatest) + + // Repeated group and single-tool round trips with no arriving data. + for opensGroup in [true, false, true] { + let offset = collection.contentOffset.y + if opensGroup { + XCTAssertTrue(model.inspectToolGroup(group.id, owner: "chat")) + } else { + model.beginContentInspection() + model.retainSurface("inspector:chat") + model.toolInspection.open(tool, owner: "chat") + } + try await eventually { host.presentedViewController != nil && !model.followsTail } + XCTAssertFalse(model.showsJumpToLatest) + model.toolInspection.dismiss(owner: "chat") + try await eventually { host.presentedViewController == nil && !model.isInspectingContent } + XCTAssertEqual(collection.contentOffset.y, offset, accuracy: 1) + XCTAssertFalse(model.showsJumpToLatest, "Dismissal alone must not reveal Back to latest") + XCTAssertFalse(model.followsTail, "Hiding the action must not change reading intent") + } + + // New visible content, unlike inspection itself, creates real distance. + let offset = collection.contentOffset.y + XCTAssertTrue(model.inspectToolGroup(group.id, owner: "chat")) + try await eventually { host.presentedViewController != nil } + let seq = (await controller.state.newestSeq ?? 0) + 1 + let message = DecryptedMessage(id: "new-tail", seq: seq, + content: ["role": "agent", "content": ["type": "codex", "data": [ + "type": "message", "message": .string(String(repeating: "New visible tail content.\n\n", count: 20)), + ]]], createdAt: seq * 1000, invokedAt: seq * 1000) + await controller.onMessageEvent(.messageReceived(namespace: nil, sessionId: model.sessionId, message: message)) + try await eventually { collection.numberOfItems(inSection: 0) == 7 && model.showsJumpToLatest } + model.toolInspection.dismiss(owner: "chat") + try await eventually { host.presentedViewController == nil && !model.isInspectingContent } + XCTAssertEqual(collection.contentOffset.y, offset, accuracy: 1) + XCTAssertTrue(model.showsJumpToLatest) + XCTAssertFalse(model.followsTail) + + // Already browsing history: reopening the sheet retains the action. + XCTAssertTrue(model.inspectToolGroup(group.id, owner: "chat")) + try await eventually { host.presentedViewController != nil } + model.toolInspection.dismiss(owner: "chat") + try await eventually { host.presentedViewController == nil && !model.isInspectingContent } + XCTAssertEqual(collection.contentOffset.y, offset, accuracy: 1) + XCTAssertTrue(model.showsJumpToLatest) + let jump = model.jumpToLatestToken + model.jumpToLatest() + try await eventually { model.jumpToLatestToken > jump && model.followsTail && !model.showsJumpToLatest } + } + func testPlanPublicationUpdatesRecyclingAndInspectorPreserveTheDocumentAndAnchor() async throws { let plan = "# Initial proposal\n\nRead the document without opening the inspector." let credentials = InMemoryCredentialStore() diff --git a/ios/README.md b/ios/README.md index 3f8b620e..79758553 100644 --- a/ios/README.md +++ b/ios/README.md @@ -360,8 +360,10 @@ TEST_RUNNER_HAPI_QUESTION_CAPTURE=/tmp/hapi-question-review \ Inspection pauses transcript tail-following and hidden history paging, without opening another SSE subscription. Closing returns to the reading anchor; -**Back to latest** explicitly resumes following. Trimmed records remain visible -as labeled, read-only snapshots; missing groups retain their last membership, +opening/closing at bottom does not itself show **Back to latest**. The button +appears when the transcript is far enough from bottom (or the live tail has been +trimmed), and explicitly resumes following. Trimmed records remain visible as +labeled, read-only snapshots; missing groups retain their last membership, without switching to another group. Incomplete history is labeled and can be loaded from the conversation after closing the inspector. Large text is loaded in 20,000-character parts and can be copied in full; large diffs use paged source From a6880fe592271ac00540126b6cd6c7f38128e98c Mon Sep 17 00:00:00 2001 From: weishu Date: Sun, 13 Sep 2026 19:33:50 +0800 Subject: [PATCH 03/27] fix(native): add Codex plan proposal actions Add current-proposal decoding, dedicated implementation requests and composer-only continuation on iOS and Android. Keep pending/errors across row recycling, reject stale actions and prevent duplicate submissions. Include native regression tests and localized plan controls. --- android/README.md | 7 + .../feature/chat/CodexPlanActionsTest.kt | 111 +++++++++++++ .../feature/chat/ChatInteractions.kt | 3 + .../hapi/companion/feature/chat/ChatScreen.kt | 6 +- .../companion/feature/chat/ChatViewModel.kt | 83 +++++++++- .../feature/chat/CodexPlanActions.kt | 28 ++++ .../chat/blocks/CodexPlanActionsView.kt | 60 +++++++ .../feature/chat/blocks/ToolCallBlockView.kt | 6 + .../feature/chat/composer/ChatComposer.kt | 17 ++ .../src/main/res/values-zh-rCN/strings.xml | 2 + android/app/src/main/res/values/strings.xml | 2 + .../chat/ChatViewModelInteractionTest.kt | 121 ++++++++++++++ .../feature/chat/ChatViewModelTest.kt | 1 + .../app/hapi/data/api/ChatSessionApi.kt | 3 + .../main/kotlin/app/hapi/data/api/HapiApi.kt | 9 ++ .../kotlin/app/hapi/data/api/HapiApiTest.kt | 20 +++ .../app/hapi/protocol/wire/AgentState.kt | 2 + .../protocol/patch/SessionPatchingTest.kt | 20 +++ .../Chat/Blocks/CodexPlanActionsView.swift | 51 ++++++ .../Chat/Blocks/ToolCallBlockView.swift | 3 + .../Chat/Composer/ChatComposerView.swift | 5 + ios/Hapi/Resources/Localizable.xcstrings | 22 +++ .../CodexPlanActionPresentationTests.swift | 147 ++++++++++++++++++ .../Chat/ChatInteractionState.swift | 12 ++ .../HapiClient/Chat/ChatInteractor.swift | 58 +++++++ .../Endpoints/SessionEndpoints.swift | 15 ++ .../HapiProtocol/Models/AgentState.swift | 7 +- .../Chat/ChatInteractorTests.swift | 104 +++++++++++++ .../EndpointRequestTests.swift | 10 ++ .../SessionPatchingTests.swift | 27 ++++ ios/README.md | 6 + 31 files changed, 965 insertions(+), 3 deletions(-) create mode 100644 android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/CodexPlanActionsTest.kt create mode 100644 android/app/src/main/kotlin/app/hapi/companion/feature/chat/CodexPlanActions.kt create mode 100644 android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/CodexPlanActionsView.kt create mode 100644 ios/Hapi/Features/Chat/Blocks/CodexPlanActionsView.swift create mode 100644 ios/HapiTests/CodexPlanActionPresentationTests.swift diff --git a/android/README.md b/android/README.md index 3c7afd78..cdbe27e5 100644 --- a/android/README.md +++ b/android/README.md @@ -307,6 +307,13 @@ conversation, rendering the complete `input.plan` Markdown before approval controls. Tapping the header folds the card. Plan documents are prewarmed in the chat Markdown cache and do not use the ordinary tool-output paging budget; raw input/result remains under Source. +Shared Codex proposals also show **Implement plan** and **Continue planning** +when the active session's `agentState.codexPlanProposalId` matches the tool-call +id. Implementation uses the dedicated plan endpoint, not permission approval; +continue only focuses the composer, preserving its draft. The menu stays visible +when the document is folded; pending/error state survives row recycling. +Withdrawn, historical and child proposals remain read-only (an outstanding +operation/error can still be shown). Details recognize namespaced command/script/patch calls, unwrap common nested result envelopes, and keep command exit/status metadata visible. File diff --git a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/CodexPlanActionsTest.kt b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/CodexPlanActionsTest.kt new file mode 100644 index 00000000..0f38c839 --- /dev/null +++ b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/CodexPlanActionsTest.kt @@ -0,0 +1,111 @@ +package app.hapi.companion.feature.chat + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsFocused +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertIsNotFocused +import androidx.compose.ui.test.assertTextContains +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.unit.Density +import app.hapi.companion.feature.chat.blocks.ToolCallBlockView +import app.hapi.companion.feature.chat.blocks.previewToolCall +import app.hapi.companion.feature.chat.composer.ChatComposer +import app.hapi.companion.ui.theme.HapiTheme +import app.hapi.protocol.chat.ToolCallBlock +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test + +class CodexPlanActionsTest { + @get:Rule val compose = createComposeRule() + + private fun proposal(name: String = "ExitPlanMode"): ToolCallBlock { + val block = previewToolCall("message", name, input = mapOf("plan" to "# Plan document\n\nKeep the complete proposal.")) + return ToolCallBlock(id = block.id, localId = null, createdAt = 0, invokedAt = null, + tool = block.tool.copy(id = "proposal"), children = emptyList(), meta = null) + } + + @Test fun liveMenuUsesToolIdAndRetainsPendingAndErrorStateWithoutPermissions() { + val state = mutableStateOf(CodexPlanActions(proposalId = "proposal")) + val implemented = mutableListOf() + val continued = mutableListOf() + compose.setContent { + HapiTheme { + CompositionLocalProvider(LocalChatInteractions provides ChatInteractions( + flavor = "codex", permissionOverrides = emptyMap(), + resolvePermission = { _, _ -> error("Plan is not a permission") }, retryFailedMessage = {}, + codexPlanActions = state.value, + implementCodexPlan = { implemented += it; state.value = state.value.copy(pendingPlanId = it) }, + continueCodexPlan = { continued += it }, + )) { + Column(Modifier.verticalScroll(rememberScrollState())) { ToolCallBlockView(proposal(), null) } + } + } + } + compose.onNodeWithText("Plan document").assertIsDisplayed() + compose.onNodeWithText("Awaiting approval").assertDoesNotExist() + compose.onNodeWithTag("plan-implement-proposal").performScrollTo().assertIsEnabled() + compose.onNodeWithTag("plan-continue-proposal").performScrollTo().performClick() + compose.runOnIdle { assertEquals(listOf("proposal"), continued) } + // Folding a plan only hides its document, not its action/status footer. + compose.onNodeWithText("Plan proposal").performScrollTo().performClick() + compose.onNodeWithText("Plan document").assertDoesNotExist() + compose.onNodeWithTag("plan-implement-proposal").performScrollTo().performClick() + compose.onNodeWithTag("plan-implement-proposal").assertIsNotEnabled() + compose.onNodeWithTag("plan-continue-proposal").assertIsNotEnabled() + compose.runOnIdle { + assertEquals(listOf("proposal"), implemented) + state.value = state.value.copy(proposalId = null) + } + compose.onNodeWithTag("plan-implement-proposal").assertIsNotEnabled() + compose.runOnIdle { state.value = CodexPlanActions(errors = mapOf("proposal" to CodexPlanFailure("Not confirmed"))) } + compose.onNodeWithTag("plan-implement-proposal").assertDoesNotExist() + compose.onNodeWithText("Not confirmed").assertIsDisplayed() + compose.onNodeWithText("Plan proposal").performClick() + compose.onNodeWithText("Plan document").assertIsDisplayed() + compose.runOnIdle { state.value = CodexPlanActions(proposalId = "child-plan") } + compose.onNodeWithTag("plan-continue-proposal").assertDoesNotExist() + compose.onNodeWithText("Not confirmed").assertDoesNotExist() + compose.onNodeWithText("Plan document").assertIsDisplayed() + } + + @Test fun continueButtonFocusesTheComposerAndPreservesDraftAtLargeFontScale() { + val composer = mutableStateOf(ComposerUiState(text = "Refine step two", isSending = false, canSteer = false)) + compose.setContent { + HapiTheme(darkTheme = true, dynamicColor = false) { + CompositionLocalProvider( + LocalDensity provides Density(LocalDensity.current.density, fontScale = 2f), + LocalChatInteractions provides ChatInteractions( + flavor = "codex", permissionOverrides = emptyMap(), resolvePermission = { _, _ -> }, retryFailedMessage = {}, + codexPlanActions = CodexPlanActions(proposalId = "proposal"), + continueCodexPlan = { composer.value = composer.value.copy(focusRequest = composer.value.focusRequest + 1) }, + ), + ) { + Column(Modifier.fillMaxSize()) { + Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) { + ToolCallBlockView(proposal("exit_plan_mode"), null) + } + ChatComposer(state = composer.value, onTextChange = {}, onSend = {}, onSendSteer = {}, onAbort = {}) + } + } + } + } + compose.onNodeWithTag("chat-composer-input").assertIsNotFocused() + compose.onNodeWithTag("plan-continue-proposal").performScrollTo().assertIsDisplayed().performClick() + compose.onNodeWithTag("chat-composer-input").assertIsFocused().assertTextContains("Refine step two") + compose.runOnIdle { assertEquals("Refine step two", composer.value.text) } + } +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatInteractions.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatInteractions.kt index 634ee733..00910ea7 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatInteractions.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatInteractions.kt @@ -19,6 +19,9 @@ data class ChatInteractions( val permissionOverrides: Map, val resolvePermission: (requestId: String, action: PermissionAction) -> Unit, val retryFailedMessage: (localId: String) -> Unit, + val codexPlanActions: CodexPlanActions = CodexPlanActions(), + val implementCodexPlan: (planId: String) -> Unit = {}, + val continueCodexPlan: (planId: String) -> Unit = {}, ) /** Dynamic local: override churn invalidates readers only, not the whole tree. */ diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatScreen.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatScreen.kt index 31aa40a2..aaa78ace 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatScreen.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatScreen.kt @@ -117,6 +117,7 @@ internal fun ChatScreen( val jumpToken by viewModel.jumpToken.collectAsState() val jumpingLatest by viewModel.jumpingLatest.collectAsState() val composerState by viewModel.composer.collectAsState() + val codexPlanActions by viewModel.codexPlanActions.collectAsState() val queuedRows by viewModel.queuedRows.collectAsState() val configState by viewModel.config.collectAsState() val toolbarHeight = maxOf(64.dp, with(LocalDensity.current) { 24.sp.toDp() + 16.sp.toDp() } + 16.dp) @@ -257,12 +258,15 @@ internal fun ChatScreen( if (granted) launchCamera() else cameraPermissionLauncher.launch(Manifest.permission.CAMERA) } - val interactions = remember(state.flavor, state.permissionOverrides, viewModel) { + val interactions = remember(state.flavor, state.permissionOverrides, codexPlanActions, viewModel) { ChatInteractions( flavor = state.flavor, permissionOverrides = state.permissionOverrides, resolvePermission = viewModel::resolvePermission, retryFailedMessage = viewModel::retryFailedMessage, + codexPlanActions = codexPlanActions, + implementCodexPlan = viewModel::implementCodexPlan, + continueCodexPlan = viewModel::continueCodexPlan, ) } diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatViewModel.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatViewModel.kt index 64036b99..376822af 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatViewModel.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/ChatViewModel.kt @@ -155,6 +155,8 @@ data class ComposerUiState( val isSending: Boolean, /** A turn is active: long-press send offers Steer; an empty draft shows Stop. */ val canSteer: Boolean, + /** Local focus intent; does not replace or send the draft. */ + val focusRequest: Long = 0, ) /** One row of the queued-messages bar (uninvoked sends). */ @@ -409,6 +411,13 @@ class ChatViewModel( private val queuedOpPending = MutableStateFlow(false) private val permissionOverrides = MutableStateFlow>(emptyMap()) private val configOpPending = MutableStateFlow(false) + private val composerFocusRequest = MutableStateFlow(0L) + private data class CodexPlanOperations( + val pendingPlanId: String? = null, + val implementedPlanIds: Set = emptySet(), + val errors: Map = emptyMap(), + ) + private val codexPlanOperations = MutableStateFlow(CodexPlanOperations()) private sealed interface CodexModels { data object Idle : CodexModels @@ -480,11 +489,13 @@ class ChatViewModel( composerText, sendInFlight, sessionStateFlow(), - ) { text, sending, session -> + composerFocusRequest, + ) { text, sending, session, focusRequest -> ComposerUiState( text = text, isSending = sending, canSteer = session.thinking && session.active, + focusRequest = focusRequest, ) }.stateIn(scope, SharingStarted.Eagerly, ComposerUiState(text = "", isSending = false, canSteer = false)) @@ -499,6 +510,13 @@ class ChatViewModel( } .stateIn(scope, SharingStarted.Eagerly, emptyList()) + /** Plan availability updates independently of the transcript pipeline. */ + val codexPlanActions: StateFlow = combine( + sessionStore.sessionDetail(sessionId), codexPlanOperations, sendInFlight, configOpPending, + ) { detail, operations, sending, configuring -> + buildCodexPlanActions(detail, operations, sending || configuring) + }.stateIn(scope, SharingStarted.Eagerly, CodexPlanActions()) + /** Session config sheet model. */ val config: StateFlow = combine( sessionStore.sessionDetail(sessionId), @@ -1442,6 +1460,69 @@ class ChatViewModel( } } + // ---------------------------------------------------- Codex plan actions -- + + private fun buildCodexPlanActions( + detail: Session?, operations: CodexPlanOperations, busy: Boolean, + ): CodexPlanActions = CodexPlanActions( + proposalId = detail?.agentState?.codexPlanProposalId?.takeIf { + detail.active && detail.metadata?.flavor == "codex" + && detail.metadata?.capabilities?.concurrentClients == true + && it !in operations.implementedPlanIds + }, + pendingPlanId = operations.pendingPlanId, + disabled = busy || detail?.thinking == true, + errors = operations.errors, + ) + + // Re-read live inputs for callbacks; a combined StateFlow can lag a UI tap. + private fun currentCodexPlanActions() = buildCodexPlanActions( + sessionStore.currentDetail(sessionId), codexPlanOperations.value, + sendInFlight.value || configOpPending.value, + ) + + fun implementCodexPlan(planId: String) { + val previous = codexPlanOperations.value + if (!currentCodexPlanActions().forPlan(planId).canAct) return + if (!codexPlanOperations.compareAndSet(previous, previous.copy( + pendingPlanId = planId, errors = previous.errors - planId, + ))) return + scope.launch { + try { + try { + api.implementCodexPlan(sessionId, planId) + // Acceptance wins over a failed or temporarily stale refresh. + codexPlanOperations.update { it.copy(implementedPlanIds = it.implementedPlanIds + planId) } + } catch (cancellation: CancellationException) { + throw cancellation + } catch (error: Exception) { + val serverMessage = (error as? ApiError)?.body?.let { + runCatching { HapiJson.parseToJsonElement(it).objOrNull?.get("error").stringOrNull }.getOrNull() + } + codexPlanOperations.update { + it.copy(errors = it.errors + (planId to CodexPlanFailure(serverMessage ?: error.message))) + } + } + // Another client may have consumed/withdrawn the proposal, even + // after a failure. Refresh without resubmitting an uncertain POST. + try { + sessionStore.loadSessionDetail(sessionId) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + // Keep the last state; SSE/reconnection will refresh later. + } + } finally { + codexPlanOperations.update { it.copy(pendingPlanId = null) } + } + } + } + + fun continueCodexPlan(planId: String) { + if (!currentCodexPlanActions().forPlan(planId).canAct) return + composerFocusRequest.update { it + 1 } + } + // ---------------------------------------------------------------- config -- /** `POST /permission-mode` with an optimistic detail flip; server truth on error. */ diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/CodexPlanActions.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/CodexPlanActions.kt new file mode 100644 index 00000000..bfd24910 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/CodexPlanActions.kt @@ -0,0 +1,28 @@ +package app.hapi.companion.feature.chat + +/** A server/transport error; null detail uses the localized request-failed fallback. */ +data class CodexPlanFailure(val detail: String?) + +data class CodexPlanActionState( + val available: Boolean, + val pending: Boolean, + val canAct: Boolean, + val error: CodexPlanFailure?, +) { + val isVisible: Boolean get() = available || pending || error != null +} + +/** Screen-owned plan menus, independent of tool permissions and row recycling. */ +data class CodexPlanActions( + val proposalId: String? = null, + val pendingPlanId: String? = null, + val disabled: Boolean = false, + val errors: Map = emptyMap(), +) { + fun forPlan(planId: String): CodexPlanActionState = CodexPlanActionState( + available = proposalId == planId, + pending = pendingPlanId == planId, + canAct = proposalId == planId && pendingPlanId == null && !disabled, + error = errors[planId], + ) +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/CodexPlanActionsView.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/CodexPlanActionsView.kt new file mode 100644 index 00000000..77661276 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/CodexPlanActionsView.kt @@ -0,0 +1,60 @@ +package app.hapi.companion.feature.chat.blocks + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import app.hapi.companion.R +import app.hapi.companion.feature.chat.ChatInteractions + +/** Client actions, not permissions. Folding the document never discards operation state. */ +@Composable +internal fun CodexPlanActionsView(planId: String, interactions: ChatInteractions) { + val state = interactions.codexPlanActions.forPlan(planId) + if (!state.isVisible) return + Column(Modifier.fillMaxWidth().padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + state.error?.let { error -> + Text( + error.detail ?: stringResource(R.string.chat_notice_request_failed), + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.testTag("plan-error-$planId").semantics { liveRegion = LiveRegionMode.Polite }, + ) + } + if (state.available || state.pending) { + // Stacked, untruncated labels work on narrow phones and large fonts. + Button( + onClick = { interactions.implementCodexPlan(planId) }, enabled = state.canAct, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).testTag("plan-implement-$planId"), + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + if (state.pending) CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) + Text(stringResource(R.string.chat_plan_implement)) + } + } + OutlinedButton( + onClick = { interactions.continueCodexPlan(planId) }, enabled = state.canAct, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).testTag("plan-continue-$planId"), + ) { + Text(stringResource(R.string.chat_plan_continue)) + } + } + } +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/ToolCallBlockView.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/ToolCallBlockView.kt index 89228461..e3291e5f 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/ToolCallBlockView.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/ToolCallBlockView.kt @@ -79,6 +79,12 @@ fun ToolCallBlockView(block: ToolCallBlock, basePath: String?, modifier: Modifie ) } + if (planProposalMarkdown(tool) != null) { + LocalChatInteractions.current?.let { interactions -> + CodexPlanActionsView(planId = tool.id, interactions = interactions) + } + } + tool.permission?.let { permission -> val interactions = LocalChatInteractions.current if (permission.status == "pending" && interactions != null) { diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/composer/ChatComposer.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/composer/ChatComposer.kt index 5a8b4f3c..99a0a853 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/composer/ChatComposer.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/composer/ChatComposer.kt @@ -40,6 +40,10 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.platform.testTag import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale @@ -92,6 +96,17 @@ fun ChatComposer( onDictationToggle: () -> Unit = {}, onDictationCancel: () -> Unit = {}, ) { + val focusRequester = remember { FocusRequester() } + val keyboard = LocalSoftwareKeyboardController.current + // Do not replay an old focus intent when returning from an inspector. + var handledFocusRequest by remember { mutableLongStateOf(state.focusRequest) } + LaunchedEffect(state.focusRequest) { + if (state.focusRequest != handledFocusRequest) { + handledFocusRequest = state.focusRequest + focusRequester.requestFocus() + keyboard?.show() + } + } Surface(color = MaterialTheme.colorScheme.surface, modifier = modifier.fillMaxWidth()) { Column(modifier = Modifier.padding(vertical = 8.dp)) { if (slashSuggestions.isNotEmpty()) { @@ -143,6 +158,8 @@ fun ChatComposer( cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), maxLines = 6, modifier = Modifier + .focusRequester(focusRequester) + .testTag("chat-composer-input") .fillMaxWidth() .padding(start = 12.dp, end = 12.dp, top = 12.dp, bottom = 4.dp), decorationBox = { inner -> diff --git a/android/app/src/main/res/values-zh-rCN/strings.xml b/android/app/src/main/res/values-zh-rCN/strings.xml index e2e83edb..4e54fecd 100644 --- a/android/app/src/main/res/values-zh-rCN/strings.xml +++ b/android/app/src/main/res/values-zh-rCN/strings.xml @@ -573,4 +573,6 @@ 隐私政策 没有可打开此链接的应用。 已处理 + 执行计划 + 继续规划 diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 53cd3f7b..830ed38b 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -399,6 +399,8 @@ Todo list Plan Plan proposal + Implement plan + Continue planning Skill Skill: %1$s Reasoning diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelInteractionTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelInteractionTest.kt index 6cc997fc..2bd14186 100644 --- a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelInteractionTest.kt +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelInteractionTest.kt @@ -43,6 +43,7 @@ import app.hapi.protocol.wire.RetryIndeterminateMessageResponse import app.hapi.protocol.wire.SendMessageRequest import app.hapi.protocol.wire.Session import app.hapi.protocol.wire.SessionMetadata +import app.hapi.protocol.wire.SessionCapabilities import app.hapi.protocol.wire.SessionSummary import app.hapi.protocol.wire.SlashCommand import app.hapi.protocol.wire.SlashCommandsResponse @@ -51,6 +52,7 @@ import app.hapi.protocol.wire.SyncEvent import app.hapi.protocol.wire.UploadFileResponse import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotNull import kotlin.test.assertNull @@ -220,6 +222,15 @@ private class RecordingChatApi : ChatSessionApi { override suspend fun clearConversation(sessionId: String): ResumeSessionResponse = error("Unexpected clear") + val planCalls = MutableStateFlow>>(emptyList()) + var planGate: CompletableDeferred? = null + val planFailures = ArrayDeque() + override suspend fun implementCodexPlan(sessionId: String, planId: String) { + planCalls.value = planCalls.value + (sessionId to planId) + planGate?.await() + planFailures.removeFirstOrNull()?.let { throw it } + } + override suspend fun resumeSession(sessionId: String, permissionMode: String?): ResumeSessionResponse { resumeCalls.value = resumeCalls.value + (sessionId to permissionMode) return resumeResult ?: throw RuntimeException("resume not scripted") @@ -439,6 +450,116 @@ private class InteractionHarness( class ChatViewModelInteractionTest { + private fun planDetail(): Session = detail( + flavor = "codex", agentState = AgentState(codexPlanProposalId = "plan-1"), + ).copy( + metadata = SessionMetadata(path = "/repo", host = "host", flavor = "codex", + capabilities = SessionCapabilities(concurrentClients = true)), + collaborationMode = "plan", + ) + + @Test fun `only the active shared current Codex proposal is actionable`() = runTest { + val harness = InteractionHarness(this, planDetail()) + val vm = harness.viewModel + testScheduler.runCurrent() + assertTrue(vm.codexPlanActions.value.forPlan("plan-1").canAct) + assertFalse(vm.codexPlanActions.value.forPlan("history").isVisible) + assertFalse(vm.codexPlanActions.value.forPlan("child-plan").isVisible) + for (session in listOf( + planDetail().copy(active = false), + planDetail().copy(metadata = planDetail().metadata!!.copy(flavor = "claude")), + planDetail().copy(metadata = planDetail().metadata!!.copy(capabilities = null)), + planDetail().copy(agentState = AgentState()), + planDetail().copy(agentState = AgentState(codexPlanProposalId = "newer-plan")), + )) { + harness.sessionStore.setDetail(session) + // Even before the combined flow catches up, callbacks check live state. + vm.implementCodexPlan("plan-1") + vm.continueCodexPlan("plan-1") + testScheduler.runCurrent() + assertFalse(vm.codexPlanActions.value.forPlan("plan-1").isVisible) + } + assertTrue(harness.api.planCalls.value.isEmpty()) + assertEquals(0L, vm.composer.value.focusRequest) + } + + @Test fun `continue planning preserves the draft and mode without a request`() = runTest { + val harness = InteractionHarness(this, planDetail()) + harness.viewModel.setComposerText("Refine step two") + harness.viewModel.continueCodexPlan("plan-1") + testScheduler.runCurrent() + assertEquals(1L, harness.viewModel.composer.value.focusRequest) + assertEquals("Refine step two", harness.viewModel.composer.value.text) + assertEquals("plan", harness.sessionStore.currentDetail(IX_SESSION)?.collaborationMode) + assertTrue(harness.api.planCalls.value.isEmpty()) + assertTrue(harness.api.sendCalls.value.isEmpty()) + assertTrue(harness.api.approveCalls.value.isEmpty()) + assertTrue(harness.api.configCalls.value.isEmpty()) + } + + @Test fun `plan implementation is single flight and acceptance survives stale refresh`() = runTest { + val harness = InteractionHarness(this, planDetail()) + val vm = harness.viewModel + harness.api.planGate = CompletableDeferred() + vm.setComposerText("Keep this draft") + vm.implementCodexPlan("plan-1") + vm.implementCodexPlan("plan-1") + vm.continueCodexPlan("plan-1") + testScheduler.runCurrent() + assertTrue(vm.codexPlanActions.value.forPlan("plan-1").pending) + assertFalse(vm.codexPlanActions.value.forPlan("plan-1").canAct) + assertEquals(0L, vm.composer.value.focusRequest) + harness.sessionStore.setDetail(planDetail().copy(agentState = AgentState())) + testScheduler.runCurrent() + assertTrue(vm.codexPlanActions.value.forPlan("plan-1").pending) + assertFalse(vm.codexPlanActions.value.forPlan("plan-1").available) + harness.api.planGate!!.complete(Unit) + testScheduler.runCurrent() + // The refresh deliberately serves the old id: accepted actions stay hidden. + assertFalse(vm.codexPlanActions.value.forPlan("plan-1").isVisible) + vm.implementCodexPlan("plan-1") + testScheduler.runCurrent() + assertEquals(listOf(IX_SESSION to "plan-1"), harness.api.planCalls.value) + assertEquals(1, harness.sessionStore.calls.value.count { it == "loadDetail:$IX_SESSION" }) + assertEquals("Keep this draft", vm.composer.value.text) + assertTrue(harness.api.sendCalls.value.isEmpty()) + assertTrue(harness.api.approveCalls.value.isEmpty()) + assertTrue(harness.api.configCalls.value.isEmpty()) + } + + @Test fun `plan errors survive withdrawal and do not automatically resubmit`() = runTest { + for ((status, code) in listOf(409 to "stale_plan", 409 to "unavailable", 502 to "failed", 503 to "indeterminate")) { + val harness = InteractionHarness(this, planDetail()) + harness.api.planFailures.add(ApiError.from(status, """{"ok":false,"code":"$code","error":"Not confirmed"}""")) + harness.sessionStore.detailToLoad = planDetail().copy(agentState = AgentState()) + harness.viewModel.implementCodexPlan("plan-1") + testScheduler.runCurrent() + val state = harness.viewModel.codexPlanActions.value.forPlan("plan-1") + assertEquals("Not confirmed", state.error?.detail) + assertTrue(state.isVisible) + assertFalse(state.available || state.canAct || state.pending) + assertEquals(1, harness.api.planCalls.value.size) + assertEquals(1, harness.sessionStore.calls.value.count { it == "loadDetail:$IX_SESSION" }) + assertEquals("plan", harness.sessionStore.currentDetail(IX_SESSION)?.collaborationMode) + } + } + + @Test fun `confirmed failure allows an explicit retry and clears its error`() = runTest { + val harness = InteractionHarness(this, planDetail()) + harness.api.planFailures.add(ApiError.from(502, """{"code":"failed","error":"Try again"}""")) + harness.viewModel.implementCodexPlan("plan-1") + testScheduler.runCurrent() + assertTrue(harness.viewModel.codexPlanActions.value.forPlan("plan-1").canAct) + harness.api.planGate = CompletableDeferred() + harness.viewModel.implementCodexPlan("plan-1") + testScheduler.runCurrent() + assertNull(harness.viewModel.codexPlanActions.value.forPlan("plan-1").error) + harness.api.planGate!!.complete(Unit) + testScheduler.runCurrent() + assertFalse(harness.viewModel.codexPlanActions.value.forPlan("plan-1").isVisible) + assertEquals(2, harness.api.planCalls.value.size) + } + // ---------------------------------------------------------------- send -- @Test diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelTest.kt index 97a46aa9..9e1fa4ea 100644 --- a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelTest.kt +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelTest.kt @@ -181,6 +181,7 @@ private open class FakeMessagesApi : ChatSessionApi { SteerQueuedMessageResponse(status = "steered", localId = messageId) override suspend fun abortSession(sessionId: String) {} override suspend fun clearConversation(sessionId: String): ResumeSessionResponse = error("Unexpected clear") + override suspend fun implementCodexPlan(sessionId: String, planId: String) = error("Unexpected plan implementation") override suspend fun resumeSession(sessionId: String, permissionMode: String?): ResumeSessionResponse = ResumeSessionResponse(sessionId = sessionId) diff --git a/android/core/data/src/main/kotlin/app/hapi/data/api/ChatSessionApi.kt b/android/core/data/src/main/kotlin/app/hapi/data/api/ChatSessionApi.kt index 01784ec9..31e1867b 100644 --- a/android/core/data/src/main/kotlin/app/hapi/data/api/ChatSessionApi.kt +++ b/android/core/data/src/main/kotlin/app/hapi/data/api/ChatSessionApi.kt @@ -45,6 +45,9 @@ interface ChatSessionApi : MessagesApi, AttachmentUploadApi { /** Shared root creation; only the initiating client navigates. */ suspend fun clearConversation(sessionId: String): ResumeSessionResponse + /** Shared Codex client action, separate from permissions. Never auto-retry an unconfirmed result. */ + suspend fun implementCodexPlan(sessionId: String, planId: String) + /** `POST /api/sessions/:id/messages` — `{ok:true}`; the row arrives via SSE. */ suspend fun sendMessage(sessionId: String, message: SendMessageRequest) diff --git a/android/core/data/src/main/kotlin/app/hapi/data/api/HapiApi.kt b/android/core/data/src/main/kotlin/app/hapi/data/api/HapiApi.kt index b2c0a26c..b8e32425 100644 --- a/android/core/data/src/main/kotlin/app/hapi/data/api/HapiApi.kt +++ b/android/core/data/src/main/kotlin/app/hapi/data/api/HapiApi.kt @@ -284,6 +284,15 @@ class HapiApi internal constructor( override suspend fun clearConversation(sessionId: String): ResumeSessionResponse = request("POST", url("api", "sessions", sessionId, "clear").build(), EMPTY_JSON) + /** CLI validates the proposal, switches to Default, then queues implementation. */ + override suspend fun implementCodexPlan(sessionId: String, planId: String) { + request( + "POST", + url("api", "sessions", sessionId, "codex", "plan", "implement").build(), + jsonBody(buildJsonObject { put("planId", planId) }), + ) + } + /** `POST /api/sessions/:id/abort` — active sessions only. */ override suspend fun abortSession(sessionId: String) { request("POST", url("api", "sessions", sessionId, "abort").build(), EMPTY_JSON) diff --git a/android/core/data/src/test/kotlin/app/hapi/data/api/HapiApiTest.kt b/android/core/data/src/test/kotlin/app/hapi/data/api/HapiApiTest.kt index bf94167d..65bcefaa 100644 --- a/android/core/data/src/test/kotlin/app/hapi/data/api/HapiApiTest.kt +++ b/android/core/data/src/test/kotlin/app/hapi/data/api/HapiApiTest.kt @@ -117,6 +117,26 @@ class HapiApiTest { // ------------------------------------------------------ request shapes -- + @Test fun `Codex implementation uses a dedicated endpoint and exact plan id`() = runBlocking { + server.enqueue(ok("""{"ok":true}""")) + session.api.implementCodexPlan("session/1", "plan:thread:turn:item") + val request = server.takeRequest() + assertEquals("POST", request.method) + assertEquals("/api/sessions/session%2F1/codex/plan/implement", request.path) + assertEquals("Bearer $jwt", request.getHeader("Authorization")) + assertEquals("""{"planId":"plan:thread:turn:item"}""", request.body.readUtf8()) + } + + @Test fun `uncertain plan implementation reports its error without automatic resubmission`() = runBlocking { + for ((status, code) in listOf(409 to "stale_plan", 409 to "unavailable", 502 to "failed", 503 to "indeterminate")) { + server.enqueue(MockResponse().setResponseCode(status).setBody("""{"ok":false,"code":"$code","error":"Not confirmed"}""")) + val error = assertFailsWith { session.api.implementCodexPlan("session", "proposal") } + assertEquals(status, error.status) + assertEquals(code, error.code) + } + assertEquals(4, server.requestCount) + } + @Test fun `messages page sends compound cursor and epoch as query params`() { server.enqueue( diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/AgentState.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/AgentState.kt index 0083b11c..7bb533be 100644 --- a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/AgentState.kt +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/AgentState.kt @@ -22,6 +22,8 @@ data class AgentState( val requests: Map? = null, /** Resolved requests keyed by request id. */ val completedRequests: Map? = null, + /** Current actionable shared Codex proposal's tool-call id; null withdraws its menu. */ + val codexPlanProposalId: String? = null, ) /** A pending tool-permission / user-input request (`AgentStateRequestSchema`). */ diff --git a/android/core/protocol/src/test/kotlin/app/hapi/protocol/patch/SessionPatchingTest.kt b/android/core/protocol/src/test/kotlin/app/hapi/protocol/patch/SessionPatchingTest.kt index 0d768c5f..35b0b2ef 100644 --- a/android/core/protocol/src/test/kotlin/app/hapi/protocol/patch/SessionPatchingTest.kt +++ b/android/core/protocol/src/test/kotlin/app/hapi/protocol/patch/SessionPatchingTest.kt @@ -86,6 +86,26 @@ class SessionPatchingTest { // --- version gates in applySessionDetailPatch --- + @Test fun `Codex proposal id decodes and is withdrawn without stale SSE resurrection`() { + val state = HapiJson.decodeFromString("""{"codexPlanProposalId":"plan-1","requests":{}}""") + assertEquals("plan-1", state.codexPlanProposalId) + assertTrue(state.requests!!.isEmpty()) + assertEquals(state, HapiJson.decodeFromString(HapiJson.encodeToString(AgentState.serializer(), state))) + assertNull(HapiJson.decodeFromString("{}").codexPlanProposalId) + val session = makeSession(agentState = state, agentStateVersion = 3) + val clearedState = HapiJson.decodeFromString("""{"codexPlanProposalId":null}""") + val cleared = assertNotNull(applySessionDetailPatch(session, SessionPatch(agentState = VersionedValue(4, clearedState)))) + assertNull(cleared.agentState?.codexPlanProposalId) + assertEquals(4, cleared.agentStateVersion) + for (version in listOf(3L, 4L)) { + assertNull(applySessionDetailPatch(cleared, SessionPatch(agentState = VersionedValue(version, state)))) + } + val next = assertNotNull(applySessionDetailPatch(cleared, SessionPatch( + agentState = VersionedValue(5, AgentState(codexPlanProposalId = "plan-2")), + ))) + assertEquals("plan-2", next.agentState?.codexPlanProposalId) + } + @Test fun `stale metadata patch is dropped entirely`() { val session = makeSession(metadataVersion = 5, metadata = metadata("current")) diff --git a/ios/Hapi/Features/Chat/Blocks/CodexPlanActionsView.swift b/ios/Hapi/Features/Chat/Blocks/CodexPlanActionsView.swift new file mode 100644 index 00000000..31388748 --- /dev/null +++ b/ios/Hapi/Features/Chat/Blocks/CodexPlanActionsView.swift @@ -0,0 +1,51 @@ +import HapiClient +import HapiUI +import SwiftUI + +/// A plan menu, not an approval footer. The proposal remains readable after +/// its live id is withdrawn; only the current root proposal can be executed. +struct CodexPlanActionsView: View { + let planId: String + let interactions: ChatInteractor + @Environment(\.hapiTypography) private var typography + + var body: some View { + let state = interactions.codexPlanActions(planId: planId) + if state.isVisible { + VStack(alignment: .leading, spacing: 8) { + if let error = state.error { + Text(verbatim: LocalizedNoticeMapper.map(error)) + .font(typography.captionFont) + .foregroundStyle(.red) + .accessibilityIdentifier("plan-error-\(planId)") + } + if state.available || state.pending { + // Stack on narrow phones and at large Dynamic Type sizes; + // labels stay complete and every action has a 44 pt target. + VStack(alignment: .leading, spacing: 4) { + Button { interactions.implementCodexPlan(planId: planId) } label: { + HStack { + if state.pending { ProgressView().controlSize(.small) } + Text("Implement plan") + } + .frame(maxWidth: .infinity, minHeight: 44) + .contentShape(Rectangle()) + } + .buttonStyle(.borderedProminent) + .accessibilityIdentifier("plan-implement-\(planId)") + Button { interactions.continueCodexPlan(planId: planId) } label: { + Text("Continue planning") + .frame(maxWidth: .infinity, minHeight: 44) + .contentShape(Rectangle()) + } + .buttonStyle(.bordered) + .accessibilityIdentifier("plan-continue-\(planId)") + } + .font(typography.toolTitleFont) + .disabled(!state.canAct) + } + } + .padding(12) + } + } +} diff --git a/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift b/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift index 0ad8d401..1b9c02ab 100644 --- a/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift +++ b/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift @@ -31,6 +31,9 @@ struct ToolCallBlockView: View { PlanProposalContent(markdown: plan) .padding(12) .accessibilityIdentifier("plan-proposal-\(block.id)") + if let interactions { + CodexPlanActionsView(planId: block.tool.id, interactions: interactions) + } } if let permission = block.tool.permission { if permission.status == .pending, let interactions { diff --git a/ios/Hapi/Features/Chat/Composer/ChatComposerView.swift b/ios/Hapi/Features/Chat/Composer/ChatComposerView.swift index a90af76c..67f11855 100644 --- a/ios/Hapi/Features/Chat/Composer/ChatComposerView.swift +++ b/ios/Hapi/Features/Chat/Composer/ChatComposerView.swift @@ -24,6 +24,7 @@ struct ChatComposerView: View { @State private var photoSelection: [PhotosPickerItem] = [] @State private var cameraOpen = false @State private var filePickerOpen = false + @FocusState private var textFocused: Bool private var text: Binding { Binding( @@ -61,6 +62,7 @@ struct ChatComposerView: View { .padding(.top, 8) } TextField("Message the agent…", text: text, axis: .vertical) + .focused($textFocused) .font(typography.bodyFont) .lineLimit(1...6) .textFieldStyle(.plain) @@ -89,6 +91,9 @@ struct ChatComposerView: View { } .hapiReadingColumn() .padding(.vertical, 8) + .onChange(of: interactor.composerFocusRequest) { + textFocused = true + } .task(id: dictation.map { ObjectIdentifier($0) }) { await dictation?.refreshAvailability() } diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index b496e7a0..2feb700a 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -1412,6 +1412,17 @@ } } }, + "Continue planning" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "继续规划" + } + } + } + }, "Copy" : { "extractionState" : "manual", "localizations" : { @@ -2523,6 +2534,17 @@ } } }, + "Implement plan" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "执行计划" + } + } + } + }, "Inactive" : { "extractionState" : "manual", "localizations" : { diff --git a/ios/HapiTests/CodexPlanActionPresentationTests.swift b/ios/HapiTests/CodexPlanActionPresentationTests.swift new file mode 100644 index 00000000..444f8059 --- /dev/null +++ b/ios/HapiTests/CodexPlanActionPresentationTests.swift @@ -0,0 +1,147 @@ +import HapiClient +import HapiUI +import SwiftUI +import UIKit +import XCTest +@testable import Hapi +@testable import HapiProtocol + +@MainActor +final class CodexPlanActionPresentationTests: XCTestCase { + private struct NoHTTP: HTTPPerforming { + func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + throw URLError(.notConnectedToInternet) + } + } + + @MainActor + private final class Driver { + let store: SessionListStore + let interactor: ChatInteractor + var height: CGFloat = 0 + + init() throws { + let url = try XCTUnwrap(URL(string: "http://127.0.0.1:1")) + let auth = AuthManager(baseURL: url, credentialStore: InMemoryCredentialStore(), performer: NoHTTP()) + let api = APIClient(baseURL: url, authManager: auth, performer: NoHTTP()) + store = SessionListStore(api: api) + interactor = ChatInteractor(sessionId: "session", api: api, sessionStore: store, + windows: MessageWindowControllers(provider: api)) + let session = Session( + id: "session", namespace: "default", seq: 1, createdAt: 0, updatedAt: 0, + active: true, activeAt: 0, + metadata: SessionMetadata(path: "/repo", host: "host", flavor: "codex", + capabilities: SessionCapabilities(concurrentClients: true)), + metadataVersion: 1, agentState: AgentState(codexPlanProposalId: "proposal"), + agentStateVersion: 1, thinking: false, thinkingAt: 0, collaborationMode: .plan + ) + store.applySessionEvent(.sessionUpdated(namespace: nil, sessionId: "session", data: .session(session))) + } + + func publish(_ planId: String?, version: Int) { + store.applySessionEvent(.sessionUpdated(namespace: nil, sessionId: "session", data: .patch(SessionPatch( + agentState: VersionedValue(version: version, value: AgentState(codexPlanProposalId: planId)) + )))) + } + } + + private func block(_ name: String = "ExitPlanMode") -> ToolCallBlock { + // The wrapper id is intentionally different: the live id matches the + // native tool call, not the surrounding transcript message. + ToolCallBlock(id: "transcript-message", localId: nil, createdAt: 0, invokedAt: nil, + durationMs: nil, usage: nil, model: nil, + tool: ChatToolCall(id: "proposal", name: name, state: .completed, + input: .object(["plan": .string("# Plan\n\nImplement and verify. 中文计划")]), + createdAt: 0, result: .null), children: [], meta: nil) + } + + private func height(_ view: V, size: DynamicTypeSize = .large) -> CGFloat { + UIHostingController(rootView: view.hapiTypography().environment(\.dynamicTypeSize, size)) + .sizeThatFits(in: CGSize(width: 320, height: CGFloat.greatestFiniteMagnitude)).height + } + + func testCompletedProposalsHaveClientActionsWithoutInventingPermissions() throws { + let driver = try Driver() + for name in ["ExitPlanMode", "exit_plan_mode"] { + let block = block(name) + let readOnly = height(ToolCallBlockView(block: block, basePath: nil)) + let actionable = height(ToolCallBlockView(block: block, basePath: nil) + .environment(\.chatInteractions, driver.interactor)) + XCTAssertGreaterThan(actionable, readOnly + 88, "Two separate 44 pt action targets") + let large = height(ToolCallBlockView(block: block, basePath: nil) + .environment(\.chatInteractions, driver.interactor), size: .accessibility3) + XCTAssertGreaterThan(large, actionable) + XCTAssertNil(block.tool.permission) + // Inspectors remain read-only, even with live interactions nearby. + XCTAssertEqual(height(ToolCallBody(tool: block.tool, basePath: nil)), + height(ToolCallBody(tool: block.tool, basePath: nil) + .environment(\.chatInteractions, driver.interactor)), accuracy: 1) + } + } + + private struct MeasuredCard: View { + let driver: Driver + let block: ToolCallBlock + + var body: some View { + ToolCallBlockView(block: block, basePath: nil) + .environment(\.chatInteractions, driver.interactor) + .background(GeometryReader { geometry in + Color.clear + .onAppear { driver.height = geometry.size.height } + .onChange(of: geometry.size.height) { _, height in driver.height = height } + }) + } + } + + func testLiveStateAloneWithdrawsAndRestoresActionsWithoutChangingTheTool() async throws { + let driver = try Driver() + let window = try host(ScrollView { MeasuredCard(driver: driver, block: block()) }.hapiTypography()) + defer { window.isHidden = true } + try await settle { driver.height > 100 } + let actionable = driver.height + driver.publish(nil, version: 2) + try await settle { driver.height < actionable - 88 } + let readOnly = driver.height + driver.publish("proposal", version: 1) + try await Task.sleep(for: .milliseconds(100)) + XCTAssertEqual(driver.height, readOnly, accuracy: 1, "Stale SSE cannot restore the menu") + driver.publish("proposal", version: 3) + try await settle { abs(driver.height - actionable) < 1 } + driver.publish("child-plan", version: 4) + try await settle { abs(driver.height - readOnly) < 1 } + } + + func testContinuePlanningFocusesTheRealComposerWithoutReplacingItsText() async throws { + let driver = try Driver() + driver.interactor.setComposerText("Refine step two") + let window = try host(ChatComposerView(interactor: driver.interactor).hapiTypography()) + defer { window.isHidden = true } + try await Task.sleep(for: .milliseconds(150)) + XCTAssertFalse(hasFirstResponder(window)) + driver.interactor.continueCodexPlan(planId: "proposal") + try await settle { self.hasFirstResponder(window) } + XCTAssertEqual(driver.interactor.composerText, "Refine step two") + } + + private func host(_ view: V) throws -> UIWindow { + let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + let window = UIWindow(windowScene: scene) + window.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + window.rootViewController = UIHostingController(rootView: view) + window.makeKeyAndVisible() + return window + } + + private func hasFirstResponder(_ view: UIView) -> Bool { + view.isFirstResponder || view.subviews.contains { hasFirstResponder($0) } + } + + private func settle(_ condition: () -> Bool) async throws { + for _ in 0..<100 { + if condition() { return } + try await Task.sleep(for: .milliseconds(20)) + } + XCTFail("Plan presentation did not settle") + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractionState.swift b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractionState.swift index c85a0b9e..d1be1696 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractionState.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractionState.swift @@ -58,6 +58,18 @@ public struct QueuedMessageRow: Equatable, Sendable, Identifiable { } } +// MARK: - Codex plan client actions + +/// A shared Codex proposal's client-action footer, independent of permissions. +public struct CodexPlanActionState: Equatable, Sendable { + public let available: Bool + public let pending: Bool + public let canAct: Bool + public let error: String? + + public var isVisible: Bool { available || pending || error != nil } +} + // MARK: - Permissions /// Optimistic-permission UI state layered over the reduced blocks. diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift index b06717e6..5cbec19b 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift @@ -68,6 +68,13 @@ public final class ChatInteractor { /// `configOpPending`); exposed so the sheet can render a busy state. public private(set) var configOpPending = false + /// Local focus intent, observed by the composer without changing its draft. + public private(set) var composerFocusRequest = 0 + // Screen-owned, not row-local: recycled plan cards retain operation state. + private var pendingCodexPlanId: String? + private var implementedCodexPlanIds: Set = [] + private var codexPlanErrors: [String: String] = [:] + private var queuedOpPending = false /// Raw override map; the published view prunes settled requests. private var overridesStore: [String: PermissionRowOverride] = [:] @@ -770,6 +777,57 @@ public final class ChatInteractor { } } + // MARK: - Codex plan client actions + + public func codexPlanActions(planId: String) -> CodexPlanActionState { + let detail = sessionStore.detail(for: sessionId) + let available = detail?.active == true + && detail?.metadata?.flavor == "codex" + && detail?.metadata?.capabilities?.concurrentClients == true + && detail?.agentState?.codexPlanProposalId == planId + && !implementedCodexPlanIds.contains(planId) + return CodexPlanActionState( + available: available, + pending: pendingCodexPlanId == planId, + canAct: available && pendingCodexPlanId == nil && !isSending && !configOpPending + && detail?.thinking != true, + error: codexPlanErrors[planId] + ) + } + + /// One request at a time, with no optimistic message or mode switch. + /// Refresh even on failure: another client may have consumed the proposal. + public func implementCodexPlan(planId: String) { + guard codexPlanActions(planId: planId).canAct else { return } + pendingCodexPlanId = planId + codexPlanErrors[planId] = nil + Task { [weak self] in + guard let self else { return } + defer { self.pendingCodexPlanId = nil } + do { + try await self.api.implementCodexPlan(sessionId: self.sessionId, planId: planId) + // Do not re-enable an accepted plan if the detail refresh fails + // or briefly returns state from before the queue acceptance. + self.implementedCodexPlanIds.insert(planId) + } catch { + let serverMessage = (error as? APIError)?.body.flatMap { body in + (try? HapiJSON.decoder.decode(JSONValue.self, from: Data(body.utf8)))? + .objectValue?["error"]?.stringValue + } + self.codexPlanErrors[planId] = serverMessage + ?? Self.errorMessage(error, fallback: "Request failed") + } + _ = try? await self.sessionStore.loadSessionDetail(self.sessionId) + } + } + + /// Continue planning only focuses the existing composer; it neither sends + /// text nor resolves an approval nor changes the collaboration mode. + public func continueCodexPlan(planId: String) { + guard codexPlanActions(planId: planId).canAct else { return } + composerFocusRequest += 1 + } + // MARK: - Internals private func windowController() async -> MessageWindowController { diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift index 40d8649c..c373a96d 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift @@ -68,6 +68,21 @@ extension APIClient { try await request(.post, "/api/sessions/\(encodePathComponent(id))/clear", body: EmptyRequestBody()) } + /// Shared Codex client action, NOT a tool approval. The CLI + /// validates the proposal, switches to Default and queues implementation. + /// Never emulate this with separate config/message requests or auto-retry + /// an unconfirmed result. + public func implementCodexPlan(sessionId: String, planId: String) async throws { + struct ImplementPlanRequest: Encodable { + let planId: String + } + try await requestVoid( + .post, + "/api/sessions/\(encodePathComponent(sessionId))/codex/plan/implement", + body: ImplementPlanRequest(planId: planId) + ) + } + /// `POST /api/sessions/:id/abort` (active sessions only). public func abortSession(id: String) async throws { try await requestVoid( diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentState.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentState.swift index d8d70eba..b60fdab0 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentState.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentState.swift @@ -95,6 +95,9 @@ public struct AgentState: Codable, Equatable, Sendable { public var controlledByUser: Bool? /// Launch mode the session was started in (persisted for reopen/resume). public var startingMode: SessionStartingMode? + /// Current actionable shared Codex proposal's tool-call id. Nil withdraws + /// the plan menu; proposals are not entries in `requests`. + public var codexPlanProposalId: String? /// Pending requests keyed by request id. public var requests: [String: AgentStateRequest]? /// Resolved requests keyed by request id. @@ -104,10 +107,12 @@ public struct AgentState: Codable, Equatable, Sendable { controlledByUser: Bool? = nil, startingMode: SessionStartingMode? = nil, requests: [String: AgentStateRequest]? = nil, - completedRequests: [String: AgentStateCompletedRequest]? = nil + completedRequests: [String: AgentStateCompletedRequest]? = nil, + codexPlanProposalId: String? = nil ) { self.controlledByUser = controlledByUser self.startingMode = startingMode + self.codexPlanProposalId = codexPlanProposalId self.requests = requests self.completedRequests = completedRequests } diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift index 2ae4746a..763edde1 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift @@ -896,6 +896,110 @@ struct ChatInteractorTests { #expect(config.effortOptions?.map(\.value) == [nil, "low", "medium", "high"]) } + // MARK: Codex plans (client actions, not permissions) + + private func planSession() -> Session { + var detail = chatDetail(flavor: "codex", agentState: AgentState(codexPlanProposalId: "plan-1")) + detail.metadata?.capabilities = SessionCapabilities(concurrentClients: true) + detail.collaborationMode = .plan + return detail + } + + @Test func codexPlanActionsRequireCurrentSharedActiveCodexProposal() async throws { + let harness = try await ChatInteractionHarness(detail: planSession(), activate: false) + let interactor = harness.interactor + #expect(interactor.codexPlanActions(planId: "plan-1").canAct) + #expect(!interactor.codexPlanActions(planId: "historical").isVisible) + #expect(!interactor.codexPlanActions(planId: "child-plan").isVisible) + for modify: (inout Session) -> Void in [ + { $0.active = false }, + { $0.metadata?.flavor = "claude" }, + { $0.metadata?.capabilities = nil }, + { $0.agentState?.codexPlanProposalId = nil }, + { $0.agentState?.codexPlanProposalId = "newer-plan" }, + ] { + var detail = planSession() + modify(&detail) + harness.store.updateDetailLocal(chatSessionID) { $0 = detail } + #expect(!interactor.codexPlanActions(planId: "plan-1").isVisible) + interactor.implementCodexPlan(planId: "plan-1") + interactor.continueCodexPlan(planId: "plan-1") + } + #expect(interactor.composerFocusRequest == 0) + #expect(await harness.performer.count("POST", pathSuffix: "/codex/plan/implement") == 0) + } + + @Test func continuePlanningOnlyFocusesAndPreservesDraftAndMode() async throws { + let harness = try await ChatInteractionHarness(detail: planSession(), activate: false) + harness.interactor.setComposerText("Please refine step two") + harness.interactor.continueCodexPlan(planId: "plan-1") + #expect(harness.interactor.composerFocusRequest == 1) + #expect(harness.interactor.composerText == "Please refine step two") + #expect(harness.store.detail(for: chatSessionID)?.collaborationMode == .plan) + #expect(await harness.performer.exchanges.filter { $0.method == "POST" }.isEmpty) + } + + @Test func implementingPlanIsSingleFlightAndSurvivesWithdrawalAndStaleRefresh() async throws { + let harness = try await ChatInteractionHarness(detail: planSession(), activate: false) + let interactor = harness.interactor + await harness.performer.gate("POST", pathSuffix: "/codex/plan/implement") + interactor.setComposerText("Keep this draft") + interactor.implementCodexPlan(planId: "plan-1") + interactor.implementCodexPlan(planId: "plan-1") + interactor.continueCodexPlan(planId: "plan-1") + #expect(interactor.codexPlanActions(planId: "plan-1").pending) + #expect(!interactor.codexPlanActions(planId: "plan-1").canAct) + #expect(interactor.composerFocusRequest == 0) + #expect(await eventually { + await harness.performer.count("POST", pathSuffix: "/codex/plan/implement") == 1 + }) + harness.store.applySessionEvent(.sessionUpdated(namespace: nil, sessionId: chatSessionID, data: .patch(SessionPatch( + agentState: VersionedValue(version: 2, value: AgentState()) + )))) + #expect(!interactor.codexPlanActions(planId: "plan-1").available) + #expect(interactor.codexPlanActions(planId: "plan-1").pending) + await harness.performer.openGates() + #expect(await eventually { !interactor.codexPlanActions(planId: "plan-1").pending }) + // The GET deliberately still serves the old id; acceptance must win. + #expect(!interactor.codexPlanActions(planId: "plan-1").isVisible) + interactor.implementCodexPlan(planId: "plan-1") + #expect(await harness.performer.bodies("POST", pathSuffix: "/codex/plan/implement") == [#"{"planId":"plan-1"}"#]) + #expect(await harness.performer.exchanges.filter { $0.method == "POST" }.count == 1) + #expect(await harness.performer.count("GET", pathSuffix: "/api/sessions/sess-1") == 2) + #expect(interactor.composerText == "Keep this draft") + } + + @Test(arguments: [(409, "stale_plan"), (409, "unavailable"), (502, "failed"), (503, "indeterminate")]) + func planFailureRemainsVisibleAfterWithdrawalWithoutAutomaticResubmission(status: Int, code: String) async throws { + let harness = try await ChatInteractionHarness(detail: planSession(), activate: false) + await harness.performer.script("POST", "/api/sessions/sess-1/codex/plan/implement", status: status, + json: "{\"ok\":false,\"code\":\"\(code)\",\"error\":\"Plan was not confirmed\"}") + var next = planSession() + next.agentState?.codexPlanProposalId = nil + try await harness.serveDetail(next) + harness.interactor.implementCodexPlan(planId: "plan-1") + #expect(await eventually { !harness.interactor.codexPlanActions(planId: "plan-1").pending }) + let state = harness.interactor.codexPlanActions(planId: "plan-1") + #expect(state.error == "Plan was not confirmed") + #expect(state.isVisible && !state.available && !state.canAct) + #expect(await harness.performer.count("POST", pathSuffix: "/codex/plan/implement") == 1) + #expect(await harness.performer.count("GET", pathSuffix: "/api/sessions/sess-1") == 2) + #expect(harness.store.detail(for: chatSessionID)?.collaborationMode == .plan) + } + + @Test func confirmedPlanFailureCanBeRetriedExplicitly() async throws { + let harness = try await ChatInteractionHarness(detail: planSession(), activate: false) + await harness.performer.script("POST", "/api/sessions/sess-1/codex/plan/implement", status: 502, + json: #"{"ok":false,"code":"failed","error":"Try again"}"#) + harness.interactor.implementCodexPlan(planId: "plan-1") + #expect(await eventually { !harness.interactor.codexPlanActions(planId: "plan-1").pending }) + #expect(harness.interactor.codexPlanActions(planId: "plan-1").canAct) + harness.interactor.implementCodexPlan(planId: "plan-1") + #expect(harness.interactor.codexPlanActions(planId: "plan-1").error == nil) + #expect(await eventually { !harness.interactor.codexPlanActions(planId: "plan-1").isVisible }) + #expect(await harness.performer.count("POST", pathSuffix: "/codex/plan/implement") == 2) + } + // MARK: Misc @Test func draftPersistsOnTypingAndRestoresOnOpen() async throws { diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift index 5cc63fc1..b9ef87b2 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift @@ -88,6 +88,16 @@ struct EndpointRequestTests { #expect(bodyString(request) == "{\"answers\":{\"q1\":{\"answers\":[\"a\",\"b\"]}}}") } + @Test func implementCodexPlanUsesDedicatedEndpointAndExactPlanId() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue(json: "{\"ok\":true}") + try await harness.client.implementCodexPlan(sessionId: "session/1", planId: "plan:thread:turn:item") + let request = await harness.performer.requests.first + #expect(request?.url?.absoluteString == "\(testHubURLString)/api/sessions/session%2F1/codex/plan/implement") + #expect(request?.httpMethod == "POST") + #expect(bodyString(request) == #"{"planId":"plan:thread:turn:item"}"#) + } + @Test func approveWithFlatAnswersAndModeSwitch() async throws { let harness = try makeHarness(jwt: freshJWT()) await harness.performer.enqueue(json: "{\"ok\":true}") diff --git a/ios/Packages/HapiKit/Tests/HapiProtocolTests/SessionPatchingTests.swift b/ios/Packages/HapiKit/Tests/HapiProtocolTests/SessionPatchingTests.swift index b071c2a1..9848d0db 100644 --- a/ios/Packages/HapiKit/Tests/HapiProtocolTests/SessionPatchingTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiProtocolTests/SessionPatchingTests.swift @@ -96,6 +96,33 @@ struct SessionPatchingTests { // MARK: - Version gates + @Test func codexPlanProposalDecodesAndWithdrawsWithVersionedState() throws { + let state = try JSONDecoder().decode(AgentState.self, from: Data( + #"{"codexPlanProposalId":"plan-1","requests":{}}"#.utf8 + )) + #expect(state.codexPlanProposalId == "plan-1") + #expect(state.requests?.isEmpty == true) + #expect(try JSONDecoder().decode(AgentState.self, from: JSONEncoder().encode(state)) == state) + #expect(try JSONDecoder().decode(AgentState.self, from: Data("{}".utf8)).codexPlanProposalId == nil) + let session = makeSession(agentState: state, agentStateVersion: 3) + let patch = try JSONDecoder().decode(SessionPatch.self, from: Data( + #"{"agentState":{"version":4,"value":{"codexPlanProposalId":null}}}"#.utf8 + )) + let cleared = try #require(applySessionDetailPatch(session: session, patch: patch)) + #expect(cleared.agentState?.codexPlanProposalId == nil) + #expect(cleared.agentStateVersion == 4) + // Replayed SSE must not resurrect an executable historical proposal. + for version in [3, 4] { + #expect(applySessionDetailPatch(session: cleared, patch: SessionPatch( + agentState: VersionedValue(version: version, value: state) + )) == nil) + } + let next = try #require(applySessionDetailPatch(session: cleared, patch: SessionPatch( + agentState: VersionedValue(version: 5, value: AgentState(codexPlanProposalId: "plan-2")) + ))) + #expect(next.agentState?.codexPlanProposalId == "plan-2") + } + @Test func dropsStaleMetadataPatch() { let session = makeSession(metadataVersion: 5) let next = applySessionDetailPatch(session: session, patch: SessionPatch( diff --git a/ios/README.md b/ios/README.md index 79758553..4b1f9770 100644 --- a/ios/README.md +++ b/ios/README.md @@ -313,6 +313,12 @@ Plan proposals (`ExitPlanMode` / `exit_plan_mode`) are reading documents, not activity summaries: their complete `input.plan` Markdown stays visible in the conversation, before any approval controls. The same renderer is used in the inspector; null output does not show a misleading "No output" placeholder. +Shared Codex proposals expose **Implement plan** and **Continue planning** only +when the active session's `agentState.codexPlanProposalId` matches the tool-call +id. Implementation uses the dedicated plan endpoint, not permission approval; +continue only focuses the composer, preserving its draft. Pending/error state +survives row recycling. Withdrawn, historical and child proposals stay read-only +(an outstanding operation/error can still be shown). Plans are prewarmed in the chat Markdown cache and never use the ordinary tool-output preview/paging budget. The inspector retains raw fields under Source. From 0a9f15a9a7fd5d0b46b8a40e265776da77107cd7 Mon Sep 17 00:00:00 2001 From: weishu Date: Sun, 13 Sep 2026 19:35:09 +0800 Subject: [PATCH 04/27] fix: align request_user_input other answers across clients --- android/README.md | 7 +- .../feature/chat/QuestionDetailsTest.kt | 60 ++++ .../chat/blocks/PermissionActionViews.kt | 31 ++- .../chat/blocks/QuestionDetailsView.kt | 3 +- .../chat/blocks/QuestionToolPresentation.kt | 11 +- .../chat/permissions/PermissionInputs.kt | 21 +- .../src/main/res/values-zh-rCN/strings.xml | 2 + android/app/src/main/res/values/strings.xml | 2 + .../blocks/QuestionToolPresentationTest.kt | 29 ++ .../chat/permissions/RequestUserInputTest.kt | 48 ++++ cli/src/codex/shared/permissions.test.ts | 16 ++ .../utils/appServerPermissionAdapter.test.ts | 10 +- .../Chat/Blocks/QuestionAnswerDraft.swift | 19 +- .../Chat/Blocks/QuestionDetailsView.swift | 3 +- .../Chat/Blocks/QuestionToolCard.swift | 15 +- .../Blocks/QuestionToolPresentation.swift | 9 +- ios/Hapi/Resources/Localizable.xcstrings | 33 +++ ios/HapiTests/QuestionAnswerDraftTests.swift | 48 ++++ .../QuestionCardPresentationTests.swift | 34 +++ .../QuestionToolPresentationTests.swift | 32 +++ .../HapiClient/Chat/PermissionInputs.swift | 20 +- .../Chat/RequestUserInputTests.swift | 40 +++ ios/README.md | 5 + ...sion-request-user-input-other-pending.json | 185 +++++++++++++ ...on-request-user-input-other-with-note.json | 259 ++++++++++++++++++ ...request-user-input-other-without-note.json | 253 +++++++++++++++++ web/README.md | 4 + web/scripts/fixtures/cases/permissions.ts | 40 +++ .../ToolCard/RequestUserInputFooter.test.tsx | 80 +++++- .../ToolCard/RequestUserInputFooter.tsx | 27 +- .../ToolCard/requestUserInput.test.ts | 53 +++- .../components/ToolCard/requestUserInput.ts | 24 ++ .../views/RequestUserInputView.test.tsx | 65 +++++ .../ToolCard/views/RequestUserInputView.tsx | 21 +- web/src/lib/locales/en.ts | 2 + web/src/lib/locales/zh-CN.ts | 2 + 36 files changed, 1459 insertions(+), 54 deletions(-) create mode 100644 android/app/src/test/kotlin/app/hapi/companion/feature/chat/permissions/RequestUserInputTest.kt create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/Chat/RequestUserInputTests.swift create mode 100644 shared/fixtures/chat/permission-request-user-input-other-pending.json create mode 100644 shared/fixtures/chat/permission-request-user-input-other-with-note.json create mode 100644 shared/fixtures/chat/permission-request-user-input-other-without-note.json create mode 100644 web/src/components/ToolCard/views/RequestUserInputView.test.tsx diff --git a/android/README.md b/android/README.md index cdbe27e5..62f69551 100644 --- a/android/README.md +++ b/android/README.md @@ -322,7 +322,12 @@ reveals the original input/result, including fields omitted from the preview. Mixed text/media results stay JSON instead of dropping non-text blocks. Question details show recorded selections, custom answers and notes with -Markdown questions/options. `request_user_input` also restores answers from +Markdown questions/options. Codex choice questions with `isOther: true` add +**None of the above** and focus optional notes when selected; empty notes are +valid. Translations never change the submitted `None of the above` wire value. +Pi/MCP forms without `isOther` keep their existing choices. Recorded other +answers and notes are also shown in question details. +`request_user_input` also restores answers from historical results; live permission answers take precedence. Answered cards avoid duplicate results, but retain errors and the full input/result/answers under **Source**. Pending questions are answered in the conversation. diff --git a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/QuestionDetailsTest.kt b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/QuestionDetailsTest.kt index 26e8e5d4..75a806d0 100644 --- a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/QuestionDetailsTest.kt +++ b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/QuestionDetailsTest.kt @@ -10,14 +10,17 @@ import androidx.compose.ui.test.SemanticsMatcher import androidx.compose.ui.test.assert import androidx.compose.ui.test.assertHasNoClickAction import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsFocused import androidx.compose.ui.test.assertIsNotSelected import androidx.compose.ui.test.assertIsSelected import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.junit4.StateRestorationTester import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.test.performTextInput import app.hapi.companion.feature.chat.blocks.PendingPermissionFooter import app.hapi.companion.feature.chat.blocks.ToolCallBody import app.hapi.companion.ui.theme.HapiTheme @@ -35,6 +38,62 @@ class QuestionDetailsTest { private fun pending() = ChatToolCall(id = "question", name = "request_user_input", state = "running", input = input, createdAt = 0, description = null, permission = ToolPermission(id = "reply", status = "pending", presence = emptySet())) + private fun otherTool(multiple: Boolean = false) = pending().copy(input = HapiJson.parseToJsonElement( + """{"questions":[{"id":"target","question":"Choose","isOther":true,"multiple":$multiple,"options":[{"label":"Alpha"},{"label":"Beta"}]}]}""", + )) + + @Test fun otherChoiceFocusesOptionalNotesAndSubmitsWithoutAnyNote() { + val submitted = mutableListOf>() + compose.setContent { + HapiTheme { PendingPermissionFooter(tool = otherTool(), requestId = "reply", flavor = "codex", override = null, + onAction = { id, action -> submitted += id to action }) } + } + compose.onNodeWithTag("request-input-target-option-0").performClick() + compose.onNodeWithTag("request-input-target-option-2").performClick().assertIsSelected() + compose.onNodeWithTag("request-input-target-option-0").assertIsNotSelected() + compose.onNodeWithTag("request-input-target-note").assertIsFocused() + compose.runOnIdle { assertEquals(emptyList>(), submitted) } + compose.onNodeWithText("Submit").performClick() + compose.runOnIdle { + assertEquals(listOf("reply" to PermissionAction.NestedAnswers(mapOf("target" to listOf("None of the above")))), submitted) + } + } + + @Test fun otherChoiceIsExclusiveAndRestoresNotesWithoutChangingWireValues() { + val restoration = StateRestorationTester(compose) + var submitted: PermissionAction? = null + restoration.setContent { + HapiTheme { PendingPermissionFooter(tool = otherTool(multiple = true), requestId = "reply", flavor = "codex", override = null, + onAction = { _, action -> submitted = action }) } + } + compose.onNodeWithTag("request-input-target-option-0").performClick() + compose.onNodeWithTag("request-input-target-option-1").performClick() + compose.onNodeWithTag("request-input-target-option-2").performClick() + compose.onNodeWithTag("request-input-target-note").performTextInput(" 自定义\n说明 ") + compose.onNodeWithTag("request-input-target-option-1").performClick().assertIsSelected() + compose.onNodeWithTag("request-input-target-option-2").assertIsNotSelected().performClick() + compose.onNodeWithTag("request-input-target-option-0").assertIsNotSelected() + compose.onNodeWithTag("request-input-target-option-1").assertIsNotSelected() + restoration.emulateSavedInstanceStateRestore() + compose.onNodeWithTag("request-input-target-option-2").assertIsSelected() + compose.onNodeWithText("Submit").performClick() + compose.runOnIdle { + assertEquals(PermissionAction.NestedAnswers(mapOf("target" to listOf("None of the above", "user_note: 自定义\n说明"))), submitted) + } + } + + @Test fun recordedOtherAnswerIsSelectedReadOnlyAndKeepsItsNote() { + val tool = otherTool().copy(state = "completed", result = HapiJson.parseToJsonElement( + """{"answers":{"target":{"answers":["None of the above","user_note: recorded note"]}}}""", + )) + compose.setContent { + HapiTheme { Column(Modifier.verticalScroll(rememberScrollState())) { ToolCallBody(tool, basePath = null) } } + } + compose.waitUntil(10_000) { compose.onAllNodesWithText("None of the above").fetchSemanticsNodes().isNotEmpty() } + compose.onNodeWithTag("question-0-option-2").assertIsSelected().assertHasNoClickAction() + compose.onNodeWithText("recorded note").performScrollTo().assertIsDisplayed() + } + @Test fun detailsFollowLiveAnswersWithoutActionsAndKeepSourceAndErrorsAccessible() { val tool = mutableStateOf(pending()) compose.setContent { @@ -74,6 +133,7 @@ class QuestionDetailsTest { } } compose.onNodeWithText("staging").performClick() + compose.onNodeWithTag("request-input-target-option-2").assertDoesNotExist() compose.onNodeWithText("Submit").performClick() compose.runOnIdle { assertEquals("reply" to PermissionAction.NestedAnswers(mapOf("target" to listOf("staging", "user_note: production"))), resolved) diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/PermissionActionViews.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/PermissionActionViews.kt index db3d7437..9795f229 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/PermissionActionViews.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/PermissionActionViews.kt @@ -28,6 +28,9 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview @@ -41,6 +44,7 @@ import app.hapi.companion.feature.chat.permissions.isRequestUserInputAnswered import app.hapi.companion.feature.chat.permissions.parseAskUserQuestions import app.hapi.companion.feature.chat.permissions.parseRequestUserInputQuestions import app.hapi.companion.feature.chat.permissions.requestUserInputAnswerValues +import app.hapi.companion.feature.chat.permissions.selectRequestUserInputOption import app.hapi.companion.ui.theme.HapiTheme import app.hapi.companion.ui.theme.hapi import app.hapi.protocol.chat.ChatToolCall @@ -427,6 +431,7 @@ private fun RequestUserInputFooter( verticalArrangement = Arrangement.spacedBy(10.dp), ) { questions.forEach { question -> + val noteFocusRequester = remember(tool.id, question.id) { FocusRequester() } Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { if (question.question.isNotEmpty()) { Text( @@ -438,7 +443,8 @@ private fun RequestUserInputFooter( style = MaterialTheme.typography.bodyMedium, ) } - question.options.forEach { option -> + question.answerOptions.forEachIndexed { optionIndex, option -> + val isOther = question.isOtherOption(optionIndex) val checked = option.label in (selected.value[question.id] ?: emptySet()) Surface( shape = RoundedCornerShape(10.dp), @@ -451,15 +457,12 @@ private fun RequestUserInputFooter( .fillMaxWidth() .selectable(selected = checked, enabled = !resolving, onClick = { val current = selected.value[question.id] ?: emptySet() - val next = when { - question.multiple -> - if (option.label in current) current - option.label - else current + option.label - else -> setOf(option.label) - } + val next = selectRequestUserInputOption(question, current, optionIndex) selected.value = selected.value + (question.id to next) validationError = null - }), + if (isOther) noteFocusRequester.requestFocus() + }) + .testTag("request-input-${question.id}-option-$optionIndex"), ) { Row( modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp), @@ -471,8 +474,12 @@ private fun RequestUserInputFooter( RadioButton(selected = checked, onClick = null, enabled = !resolving) } Column(modifier = Modifier.padding(start = 6.dp)) { - Text(text = option.label, style = MaterialTheme.typography.bodyMedium) - option.description?.let { description -> + Text( + text = if (isOther) stringResource(R.string.chat_perm_none_of_the_above) else option.label, + style = MaterialTheme.typography.bodyMedium, + ) + val description = if (isOther) stringResource(R.string.chat_perm_other_note_optional) else option.description + description?.let { Text( text = description, style = MaterialTheme.typography.labelSmall, @@ -491,7 +498,9 @@ private fun RequestUserInputFooter( }, enabled = !resolving, placeholder = { Text(question.placeholder ?: stringResource(R.string.chat_perm_add_note)) }, - modifier = Modifier.fillMaxWidth(), + modifier = Modifier.fillMaxWidth() + .focusRequester(noteFocusRequester) + .testTag("request-input-${question.id}-note"), ) } } diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/QuestionDetailsView.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/QuestionDetailsView.kt index cd59c683..9da58541 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/QuestionDetailsView.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/QuestionDetailsView.kt @@ -39,7 +39,8 @@ internal fun QuestionDetailsView(questions: List) { } question.options.forEachIndexed { optionIndex, option -> QuestionAnswerCard( - text = option.label, description = option.description, markdown = true, + text = if (option.isOther) stringResource(R.string.chat_perm_none_of_the_above) else option.label, + description = option.description, markdown = true, isSelected = option.selected, multiple = question.multiple, showControl = question.hasAnswers, modifier = Modifier.testTag("question-$index-option-$optionIndex"), ) diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/QuestionToolPresentation.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/QuestionToolPresentation.kt index 23ab8aea..fa98599b 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/QuestionToolPresentation.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/blocks/QuestionToolPresentation.kt @@ -30,7 +30,9 @@ internal data class QuestionDetail( val hasAnswers: Boolean get() = options.any { it.selected } || otherAnswers.isNotEmpty() || note != null } -internal data class QuestionOptionDetail(val label: String, val description: String?, val selected: Boolean) +internal data class QuestionOptionDetail( + val label: String, val description: String?, val selected: Boolean, val isOther: Boolean = false, +) internal fun isQuestionDetailsTool(name: String): Boolean { val name = toolPresentationName(name) @@ -93,12 +95,13 @@ private fun questionAnswerMap(value: JsonElement?): Map> { private fun requestQuestionDetails( questions: List, answers: Map>, ): List = questions.map { question -> + val options = question.answerOptions val selected = mutableSetOf() val other = mutableListOf() var note: String? = null for (value in answers[question.id].orEmpty()) { val trimmed = value.trim() - val option = question.options.firstOrNull { it.label == trimmed } + val option = options.firstOrNull { it.label == trimmed } when { // An actual option named "user_note: ..." is not metadata. option != null -> selected += option.label @@ -112,7 +115,9 @@ private fun requestQuestionDetails( } QuestionDetail( header = null, question = question.question, multiple = question.multiple, - options = question.options.map { QuestionOptionDetail(it.label, it.description, it.label in selected) }, + options = options.mapIndexed { index, option -> + QuestionOptionDetail(option.label, option.description, option.label in selected, question.isOtherOption(index)) + }, otherAnswers = other, note = note, ) } diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/permissions/PermissionInputs.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/permissions/PermissionInputs.kt index 5141d4c5..4bbff39f 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/chat/permissions/PermissionInputs.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/chat/permissions/PermissionInputs.kt @@ -101,6 +101,9 @@ fun parseAskUserQuestions(input: JsonElement?, cursorDialect: Boolean): List + get() = if (isOther && options.isNotEmpty()) { + options + AskOption(id = null, label = REQUEST_USER_INPUT_OTHER, description = null) + } else options + + fun isOtherOption(index: Int): Boolean = isOther && options.isNotEmpty() && index == options.size +} + +fun selectRequestUserInputOption(question: RequestUserInputQuestion, selected: Set, index: Int): Set { + val option = question.answerOptions.getOrNull(index) ?: return selected + if (question.isOtherOption(index) || !question.multiple) return setOf(option.label) + val current = if (question.isOther) selected - REQUEST_USER_INPUT_OTHER else selected + return if (option.label in current) current - option.label else current + option.label +} /** `parseRequestUserInputInput` (the URL-confirmation flow is web-only). */ fun parseRequestUserInputQuestions(input: JsonElement?): List { @@ -144,6 +162,7 @@ fun parseRequestUserInputQuestions(input: JsonElement?): List其他… %1$s(可选) 添加备注… + 以上都不是 + 可在备注中补充说明(可选)。 打开此链接? diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 830ed38b..286f1547 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -359,6 +359,8 @@ Other… %1$s (optional) Add a note… + None of the above + Optionally, add details in notes. Open link? diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/blocks/QuestionToolPresentationTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/blocks/QuestionToolPresentationTest.kt index 7466c717..696bf0fe 100644 --- a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/blocks/QuestionToolPresentationTest.kt +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/blocks/QuestionToolPresentationTest.kt @@ -12,6 +12,35 @@ import kotlin.test.assertNull import kotlin.test.assertTrue class QuestionToolPresentationTest { + @Test fun otherAndNotesShowFromRecordedAnswersWithoutChangingRawInput() { + for (flag in listOf(""", "isOther":true""", "")) { + val input = """{"questions":[{"id":"choice"$flag,"options":[{"label":"A"}]}]}""" + for (note in listOf("", """, "user_note: 自定义\n说明"""")) { + val source = """{"answers":{"choice":{"answers":["None of the above"$note]}}}""" + for (result in listOf(json(source), JsonPrimitive(source))) { + val call = tool("request_user_input", input, result = result) + val details = questionToolDetails(call) + assertTrue(details.hasAnswers) + assertFalse(details.showResult) + if (flag.isEmpty()) assertEquals(listOf("None of the above"), details.questions[0].otherAnswers) + else { + assertEquals(listOf(false, true), details.questions[0].options.map { it.selected }) + assertTrue(details.questions[0].options[1].isOther) + assertEquals(emptyList(), details.questions[0].otherAnswers) + } + assertEquals(if (note.isEmpty()) null else "自定义\n说明", details.questions[0].note) + assertEquals(json(input), call.input) + } + } + } + val input = """{"questions":[{"id":"choice","isOther":true,"options":[{"label":"A"}]}]}""" + val call = tool("request_user_input", input, """{"choice":{"answers":["None of the above","user_note: live"]}}""", + json("""{"answers":{"choice":{"answers":["A","user_note: stale"]}}}""")) + assertEquals(listOf(false, true), questionToolDetails(call).questions[0].options.map { it.selected }) + assertEquals("live", questionToolDetails(call).questions[0].note) + assertFalse(questionToolDetails(tool("request_user_input", input, result = json("""{"status":"resolved"}"""))).hasAnswers) + } + private val askInput = """{"questions":[{"header":"Storage","question":"Choose **storage**","multiSelect":true,"options":[{"label":"SQLite","description":"Local file"},{"label":"Postgres"}]},{"question":"Anything else?","options":[]}]}""" private val requestInput = """{"questions":[{"id":"target","question":"Deploy where?","multiple":true,"options":[{"label":"staging","description":"Safe"},{"label":"production"}]},{"id":"comment","question":"Comment","prefill":"Not an answer"}]}""" private fun json(source: String) = HapiJson.parseToJsonElement(source) diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/permissions/RequestUserInputTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/permissions/RequestUserInputTest.kt new file mode 100644 index 00000000..53a0d202 --- /dev/null +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/permissions/RequestUserInputTest.kt @@ -0,0 +1,48 @@ +package app.hapi.companion.feature.chat.permissions + +import app.hapi.protocol.wire.HapiJson +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class RequestUserInputTest { + private fun question(fields: String): RequestUserInputQuestion = parseRequestUserInputQuestions( + HapiJson.parseToJsonElement("""{"questions":[{"id":"choice",$fields}]}"""), + ).single() + + @Test fun otherRequiresExplicitBooleanAndNonemptyOptions() { + for (flag in listOf("true", "false", "null", "\"true\"")) { + val question = question(""""isOther":$flag,"options":[{"label":"A"}]""") + assertEquals(flag == "true", question.isOther) + assertEquals(listOf("A"), question.options.map { it.label }) + assertEquals(if (flag == "true") listOf("A", "None of the above") else listOf("A"), question.answerOptions.map { it.label }) + assertFalse(question.isOtherOption(0)) + assertEquals(flag == "true", question.isOtherOption(1)) + } + val missing = question(""""options":[{"label":"A"}]""") + assertFalse(missing.isOther) + assertEquals(missing.options, missing.answerOptions) + val text = question(""""isOther":true,"options":[]""") + assertTrue(text.answerOptions.isEmpty()) + assertFalse(text.isOtherOption(0)) + assertFalse(isRequestUserInputAnswered(text, emptyList(), "")) + } + + @Test fun otherIsExclusiveAndNotesAreOptional() { + val question = question(""""isOther":true,"multiple":true,"options":[{"label":"A"},{"label":"B"}]""") + val other = selectRequestUserInputOption(question, setOf("A", "B"), 2) + assertEquals(setOf("None of the above"), other) + assertTrue(isRequestUserInputAnswered(question, other.toList(), "")) + assertFalse(isRequestUserInputAnswered(question, emptyList(), "custom answer")) + var selected = selectRequestUserInputOption(question, other, 0) + assertEquals(setOf("A"), selected) + selected = selectRequestUserInputOption(question, selected, 1) + assertEquals(setOf("A", "B"), selected) + assertEquals(setOf("B"), selectRequestUserInputOption(question, selected, 0)) + for (note in listOf("", " \n ", " 自定义\n说明 ")) { + assertEquals(listOf("None of the above") + (if (note.isBlank()) emptyList() else listOf("user_note: ${note.trim()}")), + requestUserInputAnswerValues(other.toList(), note)) + } + } +} diff --git a/cli/src/codex/shared/permissions.test.ts b/cli/src/codex/shared/permissions.test.ts index aba1d5a3..69e93e33 100644 --- a/cli/src/codex/shared/permissions.test.ts +++ b/cli/src/codex/shared/permissions.test.ts @@ -18,6 +18,22 @@ function fixture() { return { permissions, request, respond, handlers, send, state: () => state }; } describe('shared request arbitration', () => { + it.each([{ notes: [] }, { notes: ['user_note: custom answer'] }])('preserves isOther and canonical other answers (%j) without claiming a winner', async ({ notes }) => { + const f = fixture(); + const request = { ...f.request, params: { ...f.request.params, isBlocking: true, + questions: f.request.params.questions.map(question => ({ ...question, isOther: true })) } }; + f.permissions.receive(request); + const [id, pending] = Object.entries(f.state().requests ?? {})[0]!; + expect(pending.arguments).toEqual(request.params); + const answers = { choice: { answers: ['None of the above', ...notes] } }; + await f.handlers.get('permission')!({ id, approved: true, answers }); + await vi.waitFor(() => expect(f.respond).toHaveBeenCalledWith(1, { answers })); + expect(f.state().completedRequests).toBeUndefined(); + f.permissions.resolved('thread', request.id); + expect(f.state().completedRequests?.[id]).toMatchObject({ status: 'resolved' }); + expect(f.state().completedRequests?.[id]).not.toHaveProperty('answers'); + }); + it('withdrawal on disconnect is canceled, not a claim that a native answer won', () => { const f = fixture(); f.permissions.receive(f.request); f.permissions.close(); expect(Object.values(f.state().completedRequests ?? {})[0]?.status).toBe('canceled'); diff --git a/cli/src/codex/utils/appServerPermissionAdapter.test.ts b/cli/src/codex/utils/appServerPermissionAdapter.test.ts index 125b88b7..1044b5f2 100644 --- a/cli/src/codex/utils/appServerPermissionAdapter.test.ts +++ b/cli/src/codex/utils/appServerPermissionAdapter.test.ts @@ -25,13 +25,14 @@ describe('registerAppServerPermissionHandlers', () => { expect(id).toBe('tool-123'); expect(input).toEqual({ itemId: 'tool-123', - questions: [{ id: 'approve_nav', question: 'Approve app tool call?' }] + isBlocking: true, + questions: [{ id: 'approve_nav', question: 'Approve app tool call?', isOther: true }] }); return { decision: 'accept', answers: { approve_nav: { - answers: ['Allow'] + answers: ['None of the above', 'user_note: custom answer'] } } }; @@ -48,12 +49,13 @@ describe('registerAppServerPermissionHandlers', () => { await expect(handler?.({ itemId: 'tool-123', - questions: [{ id: 'approve_nav', question: 'Approve app tool call?' }] + isBlocking: true, + questions: [{ id: 'approve_nav', question: 'Approve app tool call?', isOther: true }] })).resolves.toEqual({ decision: 'accept', answers: { approve_nav: { - answers: ['Allow'] + answers: ['None of the above', 'user_note: custom answer'] } } }); diff --git a/ios/Hapi/Features/Chat/Blocks/QuestionAnswerDraft.swift b/ios/Hapi/Features/Chat/Blocks/QuestionAnswerDraft.swift index 2535371f..c76c349b 100644 --- a/ios/Hapi/Features/Chat/Blocks/QuestionAnswerDraft.swift +++ b/ios/Hapi/Features/Chat/Blocks/QuestionAnswerDraft.swift @@ -33,10 +33,15 @@ struct QuestionAnswerForm: Equatable { var options: [AskOption] { switch self { case .ask(let question, _, _): question.options - case .request(let question): question.options + case .request(let question): question.answerOptions } } + func isOtherOption(_ index: Int) -> Bool { + if case .request(let question) = self { return question.isOtherOption(at: index) } + return false + } + var multiple: Bool { switch self { case .ask(let question, _, _): question.multiSelect @@ -158,8 +163,12 @@ struct QuestionAnswerDraft: Equatable { guard index == currentPage(in: form), form.fields.indices.contains(index), form.fields[index].options.indices.contains(option) else { return } let field = form.fields[index] - if field.multiple { - var selected = selections[index] ?? [] + if field.isOtherOption(option) { + selections[index] = [option] + expanded[index] = true + // Unlike an ordinary single selection, leave time to add optional notes. + } else if field.multiple { + var selected = Set((selections[index] ?? []).filter { !field.isOtherOption($0) }) if selected.contains(option) { selected.remove(option) } else { selected.insert(option) } selections[index] = selected @@ -239,7 +248,9 @@ enum QuestionCardState: Equatable { } func questionAnswerSummary(_ question: QuestionDetail) -> String? { - let choices = question.options.filter(\.selected).map { QuestionOptionTitle($0.label).text } + let choices = question.options.filter(\.selected).map { + $0.isOther ? String(localized: "None of the above") : QuestionOptionTitle($0.label).text + } let values = choices + question.otherAnswers + (question.note.map { [$0.isEmpty ? String(localized: "(empty)") : $0] } ?? []) guard !values.isEmpty else { return nil } return chatTruncate(values.joined(separator: " · ").split(whereSeparator: \.isWhitespace).joined(separator: " "), 240) diff --git a/ios/Hapi/Features/Chat/Blocks/QuestionDetailsView.swift b/ios/Hapi/Features/Chat/Blocks/QuestionDetailsView.swift index ea35c622..f9f3a693 100644 --- a/ios/Hapi/Features/Chat/Blocks/QuestionDetailsView.swift +++ b/ios/Hapi/Features/Chat/Blocks/QuestionDetailsView.swift @@ -23,7 +23,8 @@ struct QuestionDetailsView: View { } ForEach(Array(question.options.enumerated()), id: \.offset) { optionIndex, option in QuestionAnswerCard( - text: option.label, description: option.description, markdown: true, + text: option.isOther ? String(localized: "None of the above") : option.label, + description: option.description, markdown: true, selected: option.selected, multiple: question.multiple, showControl: question.hasAnswers ) .accessibilityIdentifier("question-\(index)-option-\(optionIndex)") diff --git a/ios/Hapi/Features/Chat/Blocks/QuestionToolCard.swift b/ios/Hapi/Features/Chat/Blocks/QuestionToolCard.swift index a67bd8c8..d8fbc5a9 100644 --- a/ios/Hapi/Features/Chat/Blocks/QuestionToolCard.swift +++ b/ios/Hapi/Features/Chat/Blocks/QuestionToolCard.swift @@ -184,11 +184,13 @@ struct QuestionAnswerFormView: View { QuestionSelectionRow( option: field.options[optionIndex], selected: draft.selections[index]?.contains(optionIndex) == true, - multiple: field.multiple + multiple: field.multiple, + isOther: field.isOtherOption(optionIndex) ) { guard enabled, !submitting else { return } textFocused = false draft.select(optionIndex, at: index, in: form) + if field.isOtherOption(optionIndex) { textFocused = true } } .disabled(!enabled || submitting) .accessibilityIdentifier("question-\(index)-choice-\(optionIndex)") @@ -251,15 +253,17 @@ struct QuestionAnswerFormView: View { .accessibilityIdentifier("question-previous") } if !form.fields[index].options.isEmpty { + let expanded = draft.showsText(at: index, in: form) Button { draft.toggleText(at: index, in: form) textFocused = draft.showsText(at: index, in: form) } label: { Label { - Text(verbatim: textTitle(index: index)) + Text(verbatim: expanded && !form.fields[index].allowsCustomAnswer + ? String(localized: "Hide note") : textTitle(index: index)) .fixedSize(horizontal: false, vertical: true) } icon: { - Image(systemName: draft.showsText(at: index, in: form) ? "chevron.up" : "plus") + Image(systemName: expanded ? "chevron.up" : "plus") } .font(typography.captionFont) .frame(minHeight: 44) @@ -304,6 +308,7 @@ private struct QuestionSelectionRow: View { let option: AskOption let selected: Bool let multiple: Bool + let isOther: Bool let action: () -> Void @Environment(\.hapiTheme) private var theme @Environment(\.hapiTypography) private var typography @@ -318,8 +323,8 @@ private struct QuestionSelectionRow: View { .padding(.top, 2) .accessibilityHidden(true) VStack(alignment: .leading, spacing: 4) { - QuestionOptionLabel(label: option.label) - if let description = option.description { + QuestionOptionLabel(label: isOther ? String(localized: "None of the above") : option.label) + if let description = isOther ? String(localized: "Optionally, add details in notes.") : option.description { // Inline markdown keeps the caption metrics instead of // promoting supporting text to full-size body paragraphs. Text(.init(description)) diff --git a/ios/Hapi/Features/Chat/Blocks/QuestionToolPresentation.swift b/ios/Hapi/Features/Chat/Blocks/QuestionToolPresentation.swift index 749a3b2f..5b56639e 100644 --- a/ios/Hapi/Features/Chat/Blocks/QuestionToolPresentation.swift +++ b/ios/Hapi/Features/Chat/Blocks/QuestionToolPresentation.swift @@ -24,6 +24,7 @@ struct QuestionOptionDetail: Equatable, Sendable { let label: String let description: String? let selected: Bool + var isOther = false } func isQuestionDetailsTool(_ name: String) -> Bool { @@ -101,13 +102,14 @@ private func requestQuestionDetails( _ questions: [RequestUserInputQuestion], answers: [String: [String]] ) -> [QuestionDetail] { questions.map { question in + let options = question.answerOptions var selected: Set = [] var other: [String] = [] var note: String? for value in answers[question.id] ?? [] { let trimmed = trimQuestionAnswer(value) // An actual option named "user_note: ..." is not metadata. - if let option = question.options.first(where: { $0.label == trimmed }) { + if let option = options.first(where: { $0.label == trimmed }) { selected.insert(option.label) } else if value.hasPrefix("user_note: ") { let text = String(value.dropFirst("user_note: ".count)) @@ -124,8 +126,9 @@ private func requestQuestionDetails( } return QuestionDetail( header: question.header, question: question.question, multiple: question.multiple, - options: question.options.map { - QuestionOptionDetail(label: $0.label, description: $0.description, selected: selected.contains($0.label)) + options: options.enumerated().map { index, option in + QuestionOptionDetail(label: option.label, description: option.description, + selected: selected.contains(option.label), isOther: question.isOtherOption(at: index)) }, otherAnswers: other, note: note ) diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index 2feb700a..a28a9daf 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -2435,6 +2435,17 @@ } } }, + "Hide note" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "收起备注" + } + } + } + }, "Hub" : { "extractionState" : "manual", "localizations" : { @@ -3216,6 +3227,17 @@ } } }, + "None of the above" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "以上都不是" + } + } + } + }, "Not delivered" : { "extractionState" : "manual", "localizations" : { @@ -3392,6 +3414,17 @@ } } }, + "Optionally, add details in notes." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "可在备注中补充说明(可选)。" + } + } + } + }, "Options" : { "extractionState" : "manual", "localizations" : { diff --git a/ios/HapiTests/QuestionAnswerDraftTests.swift b/ios/HapiTests/QuestionAnswerDraftTests.swift index 8c73f35f..c40afa93 100644 --- a/ios/HapiTests/QuestionAnswerDraftTests.swift +++ b/ios/HapiTests/QuestionAnswerDraftTests.swift @@ -12,6 +12,54 @@ final class QuestionAnswerDraftTests: XCTestCase { private let choices = #"{"questions":[{"id":"first","header":"First","question":"Choose **one**","options":[{"label":"A (Recommended)"},{"label":"B"}]},{"id":"last","header":"Last","question":"Choose again","options":[{"label":"C"},{"label":"D"}]}]}"# + func testOtherOpensNotesWithoutAdvancingAndAllowsEmptyNotes() throws { + let input = choices.replacingOccurrences(of: "\"options\"", with: "\"isOther\":true,\"options\"") + let form = try QuestionAnswerForm(tool: tool(input)) + for note in ["", " \n ", " 自定义\n说明 "] { + var draft = QuestionAnswerDraft() + draft.select(0, at: 0, in: form) + XCTAssertEqual(draft.page, 1, "Ordinary choices still advance") + draft.previous(in: form) + draft.select(2, at: 0, in: form) + XCTAssertEqual(draft.page, 0, "Other must leave time to add a note") + XCTAssertEqual(draft.selections[0], [2]) + XCTAssertTrue(draft.showsText(at: 0, in: form)) + XCTAssertTrue(draft.isAnswered(at: 0, in: form), "Notes are optional") + draft.setText(note, at: 0, in: form) + let refreshed = try QuestionAnswerForm(tool: tool(input)) + XCTAssertEqual(draft.text(at: 0, in: refreshed), note) + draft.next(in: form) + XCTAssertEqual(draft.text(at: 1, in: form), "") + draft.select(0, at: 1, in: form) + let trimmed = note.trimmingCharacters(in: .whitespacesAndNewlines) + XCTAssertEqual(draft.submission(in: form), .nestedAnswers([ + "first": ["None of the above"] + (trimmed.isEmpty ? [] : ["user_note: \(trimmed)"]), "last": ["C"], + ])) + draft.previous(in: form) + XCTAssertEqual(draft.selections[0], [2]) + draft.select(1, at: 0, in: form) + XCTAssertEqual(draft.selections[0], [1]) + XCTAssertEqual(draft.text(at: 0, in: form), note, "Switching choices preserves notes") + } + } + + func testOtherIsExclusiveWithMultipleChoicesAndReopensCollapsedNotes() throws { + let form = try QuestionAnswerForm(tool: tool(#"{"questions":[{"id":"choice","isOther":true,"multiple":true,"options":[{"label":"A"},{"label":"B"}]}]}"#)) + var draft = QuestionAnswerDraft() + draft.select(0, at: 0, in: form) + draft.select(1, at: 0, in: form) + draft.select(2, at: 0, in: form) + XCTAssertEqual(draft.selections[0], [2]) + draft.setText("Keep", at: 0, in: form) + draft.toggleText(at: 0, in: form) + draft.select(2, at: 0, in: form) + XCTAssertTrue(draft.showsText(at: 0, in: form)) + draft.select(1, at: 0, in: form) + draft.select(0, at: 0, in: form) + XCTAssertEqual(draft.selections[0], [0, 1]) + XCTAssertEqual(draft.submission(in: form), .nestedAnswers(["choice": ["A", "B", "user_note: Keep"]])) + } + func testSingleSelectAdvancesOnlyOnExplicitSelectionAndLastRequiresSubmission() throws { let call = try tool(choices) let form = QuestionAnswerForm(tool: call) diff --git a/ios/HapiTests/QuestionCardPresentationTests.swift b/ios/HapiTests/QuestionCardPresentationTests.swift index 739ce6e1..da418c79 100644 --- a/ios/HapiTests/QuestionCardPresentationTests.swift +++ b/ios/HapiTests/QuestionCardPresentationTests.swift @@ -94,6 +94,40 @@ final class QuestionCardPresentationTests: XCTestCase { permission: ToolPermission(id: "reply", status: .pending)) } + func testOtherNotesStayOnTheCurrentQuestionAndRenderRecordedAnswers() async throws { + let source = #"{"questions":[{"id":"choice","header":"选择","question":"请选择一项","isOther":true,"options":[{"label":"Alpha"},{"label":"Beta"}]},{"id":"last","question":"Next question","options":[{"label":"Finish"}]}]}"# + for (name, theme, size, width) in [("light", HapiTheme.light, DynamicTypeSize.large, CGFloat(390)), + ("large-type", .dark, .accessibility3, 320)] { + let driver = Driver(tool: try makeTool(source)) + let (window, _) = try host(Specimen(driver: driver, theme: theme, typeSize: size), width: width) + defer { window.isHidden = true } + try await settle { driver.height > 100 } + let initialHeight = driver.height + let form = QuestionAnswerForm(tool: driver.tool) + driver.draft.select(2, at: 0, in: form) + XCTAssertEqual(driver.draft.page, 0) + XCTAssertTrue(driver.draft.isAnswered(at: 0, in: form)) + try await settle { driver.height > initialHeight } + driver.draft.setText("自定义\n说明", at: 0, in: form) + driver.tool.description = "Unrelated SSE update" + try await Task.sleep(for: .milliseconds(150)) + XCTAssertEqual(driver.draft.selections[0], [2]) + XCTAssertEqual(driver.draft.text(at: 0, in: form), "自定义\n说明") + XCTAssertFalse(questionToolDetails(driver.tool).hasAnswers) + try capture(window, name: "other-notes-\(name)") + driver.tool.state = .completed + driver.tool.permission = ToolPermission(id: "reply", status: .resolved) + XCTAssertFalse(questionToolDetails(driver.tool).hasAnswers, "Resolution does not prove which answer won") + driver.tool.result = .object(["answers": .object(["choice": .object([ + "answers": .array([.string("None of the above"), .string("user_note: 自定义\n说明")]), + ])])]) + try await settle { driver.height < initialHeight } + let details = questionToolDetails(driver.tool) + XCTAssertEqual(details.questions[0].options.map(\.selected), [false, false, true]) + XCTAssertEqual(details.questions[0].note, "自定义\n说明") + } + } + func testQuestionCardsFitThemesAndTypeSizesAndCollapseOnlyWithRecordedAnswers() async throws { for (name, theme, size, width) in [ ("light", HapiTheme.light, DynamicTypeSize.large, CGFloat(390)), diff --git a/ios/HapiTests/QuestionToolPresentationTests.swift b/ios/HapiTests/QuestionToolPresentationTests.swift index 17811522..82031bec 100644 --- a/ios/HapiTests/QuestionToolPresentationTests.swift +++ b/ios/HapiTests/QuestionToolPresentationTests.swift @@ -3,6 +3,38 @@ import XCTest import HapiProtocol final class QuestionToolPresentationTests: XCTestCase { + func testOtherAndNotesShowFromRecordedAnswersWithoutChangingRawInput() throws { + for flag in [#", "isOther":true"#, ""] { + let input = "{\"questions\":[{\"id\":\"choice\"\(flag),\"options\":[{\"label\":\"A\"}]}]}" + for note in ["", #", "user_note: 自定义\n说明""#] { + let source = "{\"answers\":{\"choice\":{\"answers\":[\"None of the above\"\(note)]}}}" + for result in [try json(source), JSONValue.string(source)] { + let call = try tool("request_user_input", input: input, result: result) + let details = questionToolDetails(call) + XCTAssertTrue(details.hasAnswers) + XCTAssertFalse(details.showResult) + if flag.isEmpty { + XCTAssertEqual(details.questions[0].otherAnswers, ["None of the above"]) + } else { + XCTAssertEqual(details.questions[0].options.map(\.selected), [false, true]) + XCTAssertTrue(details.questions[0].options[1].isOther) + XCTAssertEqual(details.questions[0].otherAnswers, []) + } + XCTAssertEqual(details.questions[0].note, note.isEmpty ? nil : "自定义\n说明") + XCTAssertEqual(call.input, try json(input)) + } + } + } + let input = #"{"questions":[{"id":"choice","isOther":true,"options":[{"label":"A"}]}]}"# + let call = try tool("request_user_input", input: input, + answers: #"{"choice":{"answers":["None of the above","user_note: live"]}}"#, + result: json(#"{"answers":{"choice":{"answers":["A","user_note: stale"]}}}"#)) + XCTAssertEqual(questionToolDetails(call).questions[0].options.map(\.selected), [false, true]) + XCTAssertEqual(questionToolDetails(call).questions[0].note, "live") + let resolved = try tool("request_user_input", input: input, result: json(#"{"status":"resolved"}"#)) + XCTAssertFalse(questionToolDetails(resolved).hasAnswers) + } + private let askInput = #"{"questions":[{"header":"Storage","question":"Choose **storage**","multiSelect":true,"options":[{"label":"SQLite","description":"Local file"},{"label":"Postgres"}]},{"question":"Anything else?","options":[]}]}"# private let requestInput = #"{"questions":[{"id":"target","question":"Deploy where?","multiple":true,"options":[{"label":"staging","description":"Safe"},{"label":"production"}]},{"id":"comment","question":"Comment","prefill":"Not an answer"}]}"# diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Chat/PermissionInputs.swift b/ios/Packages/HapiKit/Sources/HapiClient/Chat/PermissionInputs.swift index a3229584..9374715f 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Chat/PermissionInputs.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Chat/PermissionInputs.swift @@ -122,6 +122,9 @@ public func parseAskUserQuestions(_ input: JSONValue?, cursorDialect: Bool) -> [ return questions } +/// Codex wire value. Presentation may localize it; answer serialization must not. +public let requestUserInputOtherAnswer = "None of the above" + public struct RequestUserInputQuestion: Equatable, Sendable { public let id: String public let header: String? @@ -132,6 +135,16 @@ public struct RequestUserInputQuestion: Equatable, Sendable { public let placeholder: String? public let prefill: String? public let inputType: String? + public let isOther: Bool + + public var answerOptions: [AskOption] { + guard isOther, !options.isEmpty else { return options } + return options + [AskOption(id: nil, label: requestUserInputOtherAnswer, description: nil)] + } + + public func isOtherOption(at index: Int) -> Bool { + isOther && !options.isEmpty && index == options.count + } public init( id: String, @@ -142,7 +155,8 @@ public struct RequestUserInputQuestion: Equatable, Sendable { placeholder: String?, prefill: String?, inputType: String? = nil, - header: String? = nil + header: String? = nil, + isOther: Bool = false ) { self.id = id self.header = header @@ -153,6 +167,7 @@ public struct RequestUserInputQuestion: Equatable, Sendable { self.placeholder = placeholder self.prefill = prefill self.inputType = inputType + self.isOther = isOther } } @@ -190,7 +205,8 @@ public func parseRequestUserInputQuestions(_ input: JSONValue?) -> [RequestUserI placeholder: object["placeholder"]?.stringValue, prefill: object["prefill"]?.stringValue, inputType: object["inputType"]?.stringValue == "editor" ? "editor" : nil, - header: trimmedString(object["header"]).flatMap { $0.isEmpty ? nil : $0 } + header: trimmedString(object["header"]).flatMap { $0.isEmpty ? nil : $0 }, + isOther: object["isOther"]?.boolValue == true )) } return questions diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/RequestUserInputTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/RequestUserInputTests.swift new file mode 100644 index 00000000..cba227f0 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/RequestUserInputTests.swift @@ -0,0 +1,40 @@ +import Foundation +import HapiClient +import HapiProtocol +import Testing + +struct RequestUserInputTests { + private func question(_ fields: String) throws -> RequestUserInputQuestion { + let input = try JSONDecoder().decode(JSONValue.self, from: Data("{\"questions\":[{\"id\":\"choice\",\(fields)}]}".utf8)) + return try #require(parseRequestUserInputQuestions(input).first) + } + + @Test func otherRequiresExplicitBooleanAndNonemptyOptions() throws { + for flag in ["true", "false", "null", "\"true\""] { + let question = try question("\"isOther\":\(flag),\"options\":[{\"label\":\"A\"}]") + #expect(question.isOther == (flag == "true")) + #expect(question.options.map(\.label) == ["A"]) + #expect(question.answerOptions.map(\.label) == (flag == "true" ? ["A", "None of the above"] : ["A"])) + #expect(!question.isOtherOption(at: 0)) + #expect(question.isOtherOption(at: 1) == (flag == "true")) + } + let missing = try question(#""options":[{"label":"A"}]"#) + #expect(!missing.isOther) + #expect(missing.answerOptions == missing.options) + let text = try question(#""isOther":true,"options":[]"#) + #expect(text.answerOptions.isEmpty) + #expect(!text.isOtherOption(at: 0)) + #expect(!isRequestUserInputAnswered(text, selected: [], note: "")) + } + + @Test func optionalNoteKeepsCanonicalOtherValue() throws { + let question = try question(#""isOther":true,"options":[{"label":"A"}]"#) + #expect(isRequestUserInputAnswered(question, selected: [requestUserInputOtherAnswer], note: "")) + #expect(!isRequestUserInputAnswered(question, selected: [], note: "custom answer")) + for note in ["", " \n ", " 自定义\n说明 "] { + let trimmed = note.trimmingCharacters(in: .whitespacesAndNewlines) + #expect(requestUserInputAnswerValues(selected: [requestUserInputOtherAnswer], note: note) + == ["None of the above"] + (trimmed.isEmpty ? [] : ["user_note: \(trimmed)"])) + } + } +} diff --git a/ios/README.md b/ios/README.md index 4b1f9770..0b2afef6 100644 --- a/ios/README.md +++ b/ios/README.md @@ -351,6 +351,11 @@ question**. **Previous question** retains all choices and notes; the last step always requires **Submit answer**. Recommended labels are display-only badges, never default selections or rewritten wire values. Other-answer/note fields expand on demand; text-only questions and prefilled drafts show them immediately. +Codex choice questions with `isOther: true` also offer **None of the above**. +Selecting it stays on the current question and focuses optional notes; empty +notes are valid. Its wire value remains `None of the above` in every language, +and recorded answers/notes appear in summaries and details. Requests without +`isOther` (including Pi and MCP forms) keep their existing choices. All form state survives transcript-cell recycling for the retained request. Successful records collapse to answer summaries; missing recorded answers are shown as handled, not inferred from local drafts. Ordinary approvals retain their approval footer. diff --git a/shared/fixtures/chat/permission-request-user-input-other-pending.json b/shared/fixtures/chat/permission-request-user-input-other-pending.json new file mode 100644 index 00000000..10412805 --- /dev/null +++ b/shared/fixtures/chat/permission-request-user-input-other-pending.json @@ -0,0 +1,185 @@ +{ + "description": "Codex isOther survives the pipeline without modifying the original options or inventing an answer.", + "expected": { + "blocks": [ + { + "createdAt": 1755000000000, + "id": "shared-user", + "kind": "user-text", + "localId": null, + "text": "Choose an option." + }, + { + "createdAt": 1755000001000, + "id": "other-call", + "kind": "tool-call", + "localId": null, + "tool": { + "id": "other-call", + "input": { + "isBlocking": true, + "questions": [ + { + "header": "Choice", + "id": "choice", + "isOther": true, + "options": [ + { + "description": "First choice", + "label": "A" + }, + { + "description": "Second choice", + "label": "B" + } + ], + "question": "Which option?" + } + ] + }, + "name": "request_user_input", + "permission": { + "status": "pending" + }, + "state": "running" + } + } + ], + "hasReadyEvent": false, + "latestUsage": null, + "visibleBlocks": [ + { + "createdAt": 1755000000000, + "id": "shared-user", + "kind": "user-text", + "localId": null, + "text": "Choose an option." + }, + { + "createdAt": 1755000001000, + "id": "other-call", + "kind": "tool-call", + "localId": null, + "tool": { + "id": "other-call", + "input": { + "isBlocking": true, + "questions": [ + { + "header": "Choice", + "id": "choice", + "isOther": true, + "options": [ + { + "description": "First choice", + "label": "A" + }, + { + "description": "Second choice", + "label": "B" + } + ], + "question": "Which option?" + } + ] + }, + "name": "request_user_input", + "permission": { + "status": "pending" + }, + "state": "running" + } + } + ] + }, + "fixtureVersion": 1, + "input": { + "agentState": { + "requests": { + "other-request": { + "arguments": { + "isBlocking": true, + "questions": [ + { + "header": "Choice", + "id": "choice", + "isOther": true, + "options": [ + { + "description": "First choice", + "label": "A" + }, + { + "description": "Second choice", + "label": "B" + } + ], + "question": "Which option?" + } + ] + }, + "createdAt": 1755000001100, + "tool": "request_user_input", + "toolCallId": "other-call" + } + } + }, + "messages": [ + { + "content": { + "content": { + "text": "Choose an option.", + "type": "text" + }, + "role": "user" + }, + "createdAt": 1755000000000, + "id": "shared-user", + "localId": null, + "seq": 1 + }, + { + "content": { + "content": { + "data": { + "callId": "other-call", + "input": { + "isBlocking": true, + "questions": [ + { + "header": "Choice", + "id": "choice", + "isOther": true, + "options": [ + { + "description": "First choice", + "label": "A" + }, + { + "description": "Second choice", + "label": "B" + } + ], + "question": "Which option?" + } + ] + }, + "name": "request_user_input", + "type": "tool-call" + }, + "type": "codex" + }, + "role": "agent" + }, + "createdAt": 1755000001000, + "id": "other-question", + "localId": null, + "seq": 2 + } + ], + "options": { + "hasMoreMessages": false + } + }, + "name": "permission-request-user-input-other-pending" +} diff --git a/shared/fixtures/chat/permission-request-user-input-other-with-note.json b/shared/fixtures/chat/permission-request-user-input-other-with-note.json new file mode 100644 index 00000000..1f1da188 --- /dev/null +++ b/shared/fixtures/chat/permission-request-user-input-other-with-note.json @@ -0,0 +1,259 @@ +{ + "description": "Authoritatively recorded other answer, with an optional note; both result history and permission answers preserve canonical wire values. Not a locally inferred shared-session winner.", + "expected": { + "blocks": [ + { + "createdAt": 1755000000000, + "id": "shared-user", + "kind": "user-text", + "localId": null, + "text": "Choose an option." + }, + { + "createdAt": 1755000001000, + "id": "other-call", + "kind": "tool-call", + "localId": null, + "tool": { + "id": "other-call", + "input": { + "isBlocking": true, + "questions": [ + { + "header": "Choice", + "id": "choice", + "isOther": true, + "options": [ + { + "description": "First choice", + "label": "A" + }, + { + "description": "Second choice", + "label": "B" + } + ], + "question": "Which option?" + } + ] + }, + "name": "request_user_input", + "permission": { + "answers": { + "choice": { + "answers": [ + "None of the above", + "user_note: 自定义\n说明" + ] + } + }, + "status": "approved" + }, + "result": { + "answers": { + "choice": { + "answers": [ + "None of the above", + "user_note: 自定义\n说明" + ] + } + } + }, + "state": "completed" + } + } + ], + "hasReadyEvent": false, + "latestUsage": null, + "visibleBlocks": [ + { + "createdAt": 1755000000000, + "id": "shared-user", + "kind": "user-text", + "localId": null, + "text": "Choose an option." + }, + { + "createdAt": 1755000001000, + "id": "other-call", + "kind": "tool-call", + "localId": null, + "tool": { + "id": "other-call", + "input": { + "isBlocking": true, + "questions": [ + { + "header": "Choice", + "id": "choice", + "isOther": true, + "options": [ + { + "description": "First choice", + "label": "A" + }, + { + "description": "Second choice", + "label": "B" + } + ], + "question": "Which option?" + } + ] + }, + "name": "request_user_input", + "permission": { + "answers": { + "choice": { + "answers": [ + "None of the above", + "user_note: 自定义\n说明" + ] + } + }, + "status": "approved" + }, + "result": { + "answers": { + "choice": { + "answers": [ + "None of the above", + "user_note: 自定义\n说明" + ] + } + } + }, + "state": "completed" + } + } + ] + }, + "fixtureVersion": 1, + "input": { + "agentState": { + "completedRequests": { + "other-request": { + "answers": { + "choice": { + "answers": [ + "None of the above", + "user_note: 自定义\n说明" + ] + } + }, + "arguments": { + "isBlocking": true, + "questions": [ + { + "header": "Choice", + "id": "choice", + "isOther": true, + "options": [ + { + "description": "First choice", + "label": "A" + }, + { + "description": "Second choice", + "label": "B" + } + ], + "question": "Which option?" + } + ] + }, + "completedAt": 1755000005000, + "createdAt": 1755000001100, + "status": "approved", + "tool": "request_user_input", + "toolCallId": "other-call" + } + }, + "requests": {} + }, + "messages": [ + { + "content": { + "content": { + "text": "Choose an option.", + "type": "text" + }, + "role": "user" + }, + "createdAt": 1755000000000, + "id": "shared-user", + "localId": null, + "seq": 1 + }, + { + "content": { + "content": { + "data": { + "callId": "other-call", + "input": { + "isBlocking": true, + "questions": [ + { + "header": "Choice", + "id": "choice", + "isOther": true, + "options": [ + { + "description": "First choice", + "label": "A" + }, + { + "description": "Second choice", + "label": "B" + } + ], + "question": "Which option?" + } + ] + }, + "name": "request_user_input", + "type": "tool-call" + }, + "type": "codex" + }, + "role": "agent" + }, + "createdAt": 1755000001000, + "id": "other-question", + "localId": null, + "seq": 2 + }, + { + "content": { + "content": { + "data": { + "callId": "other-call", + "is_error": false, + "output": { + "answers": { + "choice": { + "answers": [ + "None of the above", + "user_note: 自定义\n说明" + ] + } + } + }, + "type": "tool-call-result" + }, + "type": "codex" + }, + "role": "agent" + }, + "createdAt": 1755000005000, + "id": "other-result", + "localId": null, + "seq": 3 + } + ], + "options": { + "hasMoreMessages": false + } + }, + "name": "permission-request-user-input-other-with-note" +} diff --git a/shared/fixtures/chat/permission-request-user-input-other-without-note.json b/shared/fixtures/chat/permission-request-user-input-other-without-note.json new file mode 100644 index 00000000..27192f53 --- /dev/null +++ b/shared/fixtures/chat/permission-request-user-input-other-without-note.json @@ -0,0 +1,253 @@ +{ + "description": "Authoritatively recorded other answer, with an optional note; both result history and permission answers preserve canonical wire values. Not a locally inferred shared-session winner.", + "expected": { + "blocks": [ + { + "createdAt": 1755000000000, + "id": "shared-user", + "kind": "user-text", + "localId": null, + "text": "Choose an option." + }, + { + "createdAt": 1755000001000, + "id": "other-call", + "kind": "tool-call", + "localId": null, + "tool": { + "id": "other-call", + "input": { + "isBlocking": true, + "questions": [ + { + "header": "Choice", + "id": "choice", + "isOther": true, + "options": [ + { + "description": "First choice", + "label": "A" + }, + { + "description": "Second choice", + "label": "B" + } + ], + "question": "Which option?" + } + ] + }, + "name": "request_user_input", + "permission": { + "answers": { + "choice": { + "answers": [ + "None of the above" + ] + } + }, + "status": "approved" + }, + "result": { + "answers": { + "choice": { + "answers": [ + "None of the above" + ] + } + } + }, + "state": "completed" + } + } + ], + "hasReadyEvent": false, + "latestUsage": null, + "visibleBlocks": [ + { + "createdAt": 1755000000000, + "id": "shared-user", + "kind": "user-text", + "localId": null, + "text": "Choose an option." + }, + { + "createdAt": 1755000001000, + "id": "other-call", + "kind": "tool-call", + "localId": null, + "tool": { + "id": "other-call", + "input": { + "isBlocking": true, + "questions": [ + { + "header": "Choice", + "id": "choice", + "isOther": true, + "options": [ + { + "description": "First choice", + "label": "A" + }, + { + "description": "Second choice", + "label": "B" + } + ], + "question": "Which option?" + } + ] + }, + "name": "request_user_input", + "permission": { + "answers": { + "choice": { + "answers": [ + "None of the above" + ] + } + }, + "status": "approved" + }, + "result": { + "answers": { + "choice": { + "answers": [ + "None of the above" + ] + } + } + }, + "state": "completed" + } + } + ] + }, + "fixtureVersion": 1, + "input": { + "agentState": { + "completedRequests": { + "other-request": { + "answers": { + "choice": { + "answers": [ + "None of the above" + ] + } + }, + "arguments": { + "isBlocking": true, + "questions": [ + { + "header": "Choice", + "id": "choice", + "isOther": true, + "options": [ + { + "description": "First choice", + "label": "A" + }, + { + "description": "Second choice", + "label": "B" + } + ], + "question": "Which option?" + } + ] + }, + "completedAt": 1755000005000, + "createdAt": 1755000001100, + "status": "approved", + "tool": "request_user_input", + "toolCallId": "other-call" + } + }, + "requests": {} + }, + "messages": [ + { + "content": { + "content": { + "text": "Choose an option.", + "type": "text" + }, + "role": "user" + }, + "createdAt": 1755000000000, + "id": "shared-user", + "localId": null, + "seq": 1 + }, + { + "content": { + "content": { + "data": { + "callId": "other-call", + "input": { + "isBlocking": true, + "questions": [ + { + "header": "Choice", + "id": "choice", + "isOther": true, + "options": [ + { + "description": "First choice", + "label": "A" + }, + { + "description": "Second choice", + "label": "B" + } + ], + "question": "Which option?" + } + ] + }, + "name": "request_user_input", + "type": "tool-call" + }, + "type": "codex" + }, + "role": "agent" + }, + "createdAt": 1755000001000, + "id": "other-question", + "localId": null, + "seq": 2 + }, + { + "content": { + "content": { + "data": { + "callId": "other-call", + "is_error": false, + "output": { + "answers": { + "choice": { + "answers": [ + "None of the above" + ] + } + } + }, + "type": "tool-call-result" + }, + "type": "codex" + }, + "role": "agent" + }, + "createdAt": 1755000005000, + "id": "other-result", + "localId": null, + "seq": 3 + } + ], + "options": { + "hasMoreMessages": false + } + }, + "name": "permission-request-user-input-other-without-note" +} diff --git a/web/README.md b/web/README.md index d34742cc..78c6fca2 100644 --- a/web/README.md +++ b/web/README.md @@ -7,6 +7,10 @@ React Mini App / PWA for monitoring and controlling hapi sessions. - Session list with status, pending approvals, todos, and summaries. - Chat view with streaming updates and message sending. - Permission approval and denial workflows. +- Codex `request_user_input` choices honor `isOther`: **None of the above** + focuses optional notes, supports empty notes, and preserves the canonical + wire value across languages. Recorded other answers and notes remain visible + in live and historical cards; Pi/MCP forms without the flag are unchanged. - Permission mode and model selection. - Machine list and remote session spawn. - File browser and git status/diff views. diff --git a/web/scripts/fixtures/cases/permissions.ts b/web/scripts/fixtures/cases/permissions.ts index 30218279..4d8349fe 100644 --- a/web/scripts/fixtures/cases/permissions.ts +++ b/web/scripts/fixtures/cases/permissions.ts @@ -45,6 +45,23 @@ const sharedQuestionResult = (status: 'resolved' | 'canceled') => wireMessage({ } }) +const otherQuestionInput = { + isBlocking: true, + questions: [{ id: 'choice', header: 'Choice', question: 'Which option?', isOther: true, options: [ + { label: 'A', description: 'First choice' }, { label: 'B', description: 'Second choice' } + ] }] +} +const otherQuestionMessage = wireMessage({ + id: 'other-question', seq: 2, createdAt: T0 + 1_000, content: { + role: 'agent', content: { type: 'codex', data: { + type: 'tool-call', name: 'request_user_input', callId: 'other-call', input: otherQuestionInput + } } + } +}) +const otherQuestionRequest = { + tool: 'request_user_input', toolCallId: 'other-call', arguments: otherQuestionInput, createdAt: T0 + 1_100 +} + /** * Permission requests are NOT messages: they live in session.agentState * (requests → completedRequests). A pending request whose tool_use message is @@ -54,6 +71,29 @@ const sharedQuestionResult = (status: 'resolved' | 'canceled') => wireMessage({ * the oldest loaded message (web/src/chat/reducer.ts). */ export const permissionCases: FixtureCase[] = [ + { + name: 'permission-request-user-input-other-pending', + description: 'Codex isOther survives the pipeline without modifying the original options or inventing an answer.', + messages: [sharedQuestionMessages[0]!, otherQuestionMessage], + agentState: { requests: { 'other-request': otherQuestionRequest } } + }, + ...[false, true].map((withNote): FixtureCase => { + const answers = { choice: { answers: ['None of the above', ...(withNote ? ['user_note: 自定义\n说明'] : [])] } } + return { + name: `permission-request-user-input-other-${withNote ? 'with-note' : 'without-note'}`, + description: 'Authoritatively recorded other answer, with an optional note; both result history and permission answers preserve canonical wire values. Not a locally inferred shared-session winner.', + messages: [sharedQuestionMessages[0]!, otherQuestionMessage, wireMessage({ + id: 'other-result', seq: 3, createdAt: T0 + 5_000, content: { + role: 'agent', content: { type: 'codex', data: { + type: 'tool-call-result', callId: 'other-call', output: { answers }, is_error: false + } } + } + })], + agentState: { requests: {}, completedRequests: { 'other-request': { + ...otherQuestionRequest, completedAt: T0 + 5_000, status: 'approved', answers + } } } + } + }), { name: 'permission-shared-pending', description: 'requestUserInput without a native transcript item: CLI persists one question, permission state attaches without duplicating it.', diff --git a/web/src/components/ToolCard/RequestUserInputFooter.test.tsx b/web/src/components/ToolCard/RequestUserInputFooter.test.tsx index 7dc9169a..a59fcc79 100644 --- a/web/src/components/ToolCard/RequestUserInputFooter.test.tsx +++ b/web/src/components/ToolCard/RequestUserInputFooter.test.tsx @@ -1,4 +1,4 @@ -import { render, screen } from '@testing-library/react' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { describe, expect, it, vi } from 'vitest' import type { ApiClient } from '@/api/client' import type { ChatToolCall } from '@/chat/types' @@ -13,11 +13,22 @@ vi.mock('@/hooks/usePlatform', () => ({ })) vi.mock('@/lib/use-translation', () => ({ - useTranslation: () => ({ t: (key: string) => key }) + useTranslation: () => ({ t: (key: string) => key === 'tool.requestUserInput.otherLabel' ? '以上都不是' : key }) })) import { RequestUserInputFooter } from './RequestUserInputFooter' +const choice = { id: 'choice', question: 'Choose', isOther: true, options: [{ label: 'Alpha' }, { label: 'Beta' }] } + +function renderFooter(input: unknown = { questions: [choice] }) { + const approvePermission = vi.fn().mockResolvedValue(undefined) + const props = { + api: { approvePermission } as unknown as ApiClient, + sessionId: 'session-1', tool: makeTool(input), disabled: false, onDone: vi.fn() + } + return { ...render(), props, approvePermission } +} + function makeTool(input: unknown): ChatToolCall { return { id: 'request-1', @@ -38,6 +49,71 @@ function makeTool(input: unknown): ChatToolCall { } describe('RequestUserInputFooter', () => { + it.each(['', ' \n ', ' 自定义\n说明 '])('focuses notes without submitting and posts canonical values (%j)', async (note) => { + const { approvePermission } = renderFooter() + fireEvent.click(screen.getByRole('button', { name: /Alpha/ })) + fireEvent.click(screen.getByRole('button', { name: /以上都不是/ })) + expect(screen.getByRole('textbox')).toHaveFocus() + expect(screen.getByRole('button', { name: /Alpha/ })).toHaveAttribute('aria-pressed', 'false') + expect(screen.getByRole('button', { name: /以上都不是/ })).toHaveAttribute('aria-pressed', 'true') + expect(approvePermission).not.toHaveBeenCalled() + fireEvent.change(screen.getByRole('textbox'), { target: { value: note } }) + fireEvent.click(screen.getByRole('button', { name: 'tool.submit' })) + await waitFor(() => expect(approvePermission).toHaveBeenCalledWith('session-1', 'permission-1', { + answers: { choice: { answers: ['None of the above', ...(note.trim() ? [`user_note: ${note.trim()}`] : [])] } } + })) + }) + + it('retains notes across choices, questions, and SSE rerenders without auto-advancing', async () => { + const { props, rerender, approvePermission } = renderFooter({ questions: [choice, { ...choice, id: 'second', question: 'Second' }] }) + fireEvent.click(screen.getByRole('button', { name: /以上都不是/ })) + fireEvent.change(screen.getByRole('textbox'), { target: { value: 'keep this note' } }) + fireEvent.click(screen.getByRole('button', { name: /Alpha/ })) + expect(screen.getByRole('button', { name: /以上都不是/ })).toHaveAttribute('aria-pressed', 'false') + expect(screen.getByRole('textbox')).toHaveValue('keep this note') + fireEvent.click(screen.getByRole('button', { name: /以上都不是/ })) + expect(screen.getByText('Choose')).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: 'tool.next' })) + expect(screen.getByRole('textbox')).toHaveValue('') + fireEvent.click(screen.getByRole('button', { name: /Beta/ })) + fireEvent.click(screen.getByRole('button', { name: 'tool.prev' })) + rerender() + expect(screen.getByRole('textbox')).toHaveValue('keep this note') + expect(screen.getByRole('button', { name: /以上都不是/ })).toHaveAttribute('aria-pressed', 'true') + fireEvent.click(screen.getByRole('button', { name: 'tool.next' })) + fireEvent.click(screen.getByRole('button', { name: 'tool.submit' })) + await waitFor(() => expect(approvePermission).toHaveBeenCalledWith('session-1', 'permission-1', { + answers: { choice: { answers: ['None of the above', 'user_note: keep this note'] }, second: { answers: ['Beta'] } } + })) + }) + + it('does not interpret a note alone as None of the above', () => { + const { approvePermission } = renderFooter() + fireEvent.change(screen.getByRole('textbox'), { target: { value: 'custom' } }) + fireEvent.click(screen.getByRole('button', { name: 'tool.submit' })) + expect(approvePermission).not.toHaveBeenCalled() + expect(screen.getByText('tool.selectOption')).toBeInTheDocument() + }) + + it.each([false, undefined])('does not add other to Pi or MCP choices (%s)', (isOther) => { + renderFooter({ questions: [{ ...choice, isOther }] }) + expect(screen.queryByRole('button', { name: /以上都不是/ })).not.toBeInTheDocument() + }) + + it('retains the answer on failure and removes controls when resolved elsewhere', async () => { + const { props, rerender, approvePermission } = renderFooter() + approvePermission.mockRejectedValueOnce(new Error('try again')) + fireEvent.click(screen.getByRole('button', { name: /以上都不是/ })) + fireEvent.change(screen.getByRole('textbox'), { target: { value: 'draft' } }) + fireEvent.click(screen.getByRole('button', { name: 'tool.submit' })) + await screen.findByText('try again') + expect(screen.getByRole('textbox')).toHaveValue('draft') + expect(screen.getByRole('button', { name: /以上都不是/ })).toHaveAttribute('aria-pressed', 'true') + rerender() + expect(screen.queryByRole('button', { name: 'tool.submit' })).not.toBeInTheDocument() + expect(approvePermission).toHaveBeenCalledTimes(1) + }) + it('uses a Pi extension pure-text placeholder and prefill when initializing the request', () => { render( @@ -82,6 +86,7 @@ export function RequestUserInputFooter(props: { const [loading, setLoading] = useState(false) const [error, setError] = useState(null) + const noteRef = useRef(null) useEffect(() => { setStep(0) @@ -166,19 +171,17 @@ export function RequestUserInputFooter(props: { setStep((s) => Math.max(s - 1, 0)) } - const selectOption = (question: RequestUserInputQuestion, optionLabel: string) => { + const selectOption = (question: RequestUserInputQuestion, option: RequestUserInputOption) => { haptic.selection() + setError(null) setStateByQuestion((prev) => ({ ...prev, [question.id]: { ...prev[question.id], - selected: question.multiple - ? prev[question.id]?.selected.includes(optionLabel) - ? prev[question.id].selected.filter((value) => value !== optionLabel) - : [...(prev[question.id]?.selected ?? []), optionLabel] - : [optionLabel] + selected: selectRequestUserInputOption(question, prev[question.id]?.selected ?? [], option) } })) + if (option.isOther) noteRef.current?.focus() } const updateUserNote = (questionId: string, value: string) => { @@ -236,16 +239,16 @@ export function RequestUserInputFooter(props: { // Question with options <>
- {currentQuestion.options.map((opt, optIdx) => { + {requestUserInputOptions(currentQuestion).map((opt, optIdx) => { const isSelected = currentState?.selected.includes(opt.label) ?? false return ( selectOption(currentQuestion, opt.label)} + title={opt.isOther ? t('tool.requestUserInput.otherLabel') : opt.label} + description={opt.isOther ? t('tool.requestUserInput.otherDescription') : opt.description} + onClick={() => selectOption(currentQuestion, opt)} /> ) })} @@ -257,6 +260,8 @@ export function RequestUserInputFooter(props: { {t('tool.requestUserInput.noteLabel')}