diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml index cf7116de..843c3b42 100644 --- a/.github/workflows/ios.yml +++ b/.github/workflows/ios.yml @@ -46,5 +46,14 @@ jobs: run: xcodebuild build -project ios/Hapi.xcodeproj -scheme Hapi -destination 'generic/platform=iOS Simulator' CODE_SIGNING_ALLOWED=NO - name: Transcript layout regression tests run: ios/scripts/test-transcript.sh + - name: iPad navigation and layout regression tests + env: + HAPI_TEST_DEVICE_TYPE: com.apple.CoreSimulator.SimDeviceType.iPad-Air-11-inch-M2 + run: >- + ios/scripts/test-transcript.sh + -only-testing:HapiTests/SessionNavigationTests + -only-testing:HapiTests/SessionSplitPresentationTests + -only-testing:HapiTests/TranscriptTypographyTests + -only-testing:HapiTests/TranscriptGeometryTests - name: Verify localization catalog was not rewritten run: git diff --exit-code -- ios/Hapi/Resources/Localizable.xcstrings diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index daf0eb48..09de87f9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,7 +15,7 @@ jobs: - run: bun install --frozen-lockfile - run: bun typecheck - run: bunx playwright install --with-deps chromium - - run: bun run test:e2e -- terminal-wrap-fidelity.spec.ts composer-copy.spec.ts session-list-scroll.spec.ts + - run: bun run test:e2e -- terminal-wrap-fidelity.spec.ts composer-copy.spec.ts session-list-scroll.spec.ts cold-initial-tail.spec.ts - run: bun run test # Serial runner-integration suite: starts real detached runner/session diff --git a/android/README.md b/android/README.md index 3c7afd78..a871412b 100644 --- a/android/README.md +++ b/android/README.md @@ -307,6 +307,15 @@ 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 hides that proposal’s action menu locally and focuses the composer, +preserving its draft and plan mode without sending a message. The plan document +remains readable, and a new proposal gets a fresh menu. 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 @@ -315,7 +324,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/build.gradle.kts b/android/app/build.gradle.kts index 8c8a2334..a7292fb5 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -80,7 +80,7 @@ android { value.toInt().also { require(it > 0) { "hapiVersionCode must be positive" } } }.orElse(1).get() // Tracks the hapi CLI/hub release train. - versionName = providers.gradleProperty("hapiVersionName").orElse("0.28.0").get() + versionName = providers.gradleProperty("hapiVersionName").orElse("0.30.7").get() testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } 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/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/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/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) 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..f7072071 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,14 @@ 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 continuedPlanIds: Set = emptySet(), + val errors: Map = emptyMap(), + ) + private val codexPlanOperations = MutableStateFlow(CodexPlanOperations()) private sealed interface CodexModels { data object Idle : CodexModels @@ -480,11 +490,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 +511,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 +1461,73 @@ 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 + && it !in operations.continuedPlanIds + }, + 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 + codexPlanOperations.update { + it.copy(continuedPlanIds = it.continuedPlanIds + planId, errors = it.errors - planId) + } + 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/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/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/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(可选) 添加备注… + 以上都不是 + 可在备注中补充说明(可选)。 打开此链接? @@ -573,4 +575,6 @@ 隐私政策 没有可打开此链接的应用。 已处理 + 执行计划 + 继续规划 diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 53cd3f7b..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? @@ -399,6 +401,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..53559e4a 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,127 @@ 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 dismisses actions and 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()) + assertFalse(harness.viewModel.codexPlanActions.value.forPlan("plan-1").isVisible) + harness.viewModel.continueCodexPlan("plan-1") + harness.viewModel.implementCodexPlan("plan-1") + harness.sessionStore.setDetail(planDetail()) + testScheduler.runCurrent() + assertEquals(1L, harness.viewModel.composer.value.focusRequest) + assertTrue(harness.api.planCalls.value.isEmpty()) + assertFalse(harness.viewModel.codexPlanActions.value.forPlan("plan-1").isVisible) + harness.sessionStore.setDetail(planDetail().copy(agentState = AgentState(codexPlanProposalId = "plan-2"))) + testScheduler.runCurrent() + assertTrue(harness.viewModel.codexPlanActions.value.forPlan("plan-2").canAct) + } + + @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/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/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/main/kotlin/app/hapi/data/store/MessageWindowStore.kt b/android/core/data/src/main/kotlin/app/hapi/data/store/MessageWindowStore.kt index f58057eb..66601ba1 100644 --- a/android/core/data/src/main/kotlin/app/hapi/data/store/MessageWindowStore.kt +++ b/android/core/data/src/main/kotlin/app/hapi/data/store/MessageWindowStore.kt @@ -9,6 +9,7 @@ import app.hapi.protocol.window.MessageWindowLogic import app.hapi.protocol.window.HISTORY_WINDOW_SIZE import app.hapi.protocol.window.MessageWindowState import app.hapi.protocol.window.OlderLoadOutcome +import app.hapi.protocol.window.INITIAL_PAGE_SIZE import app.hapi.protocol.window.PAGE_SIZE import app.hapi.protocol.window.WindowMessage import app.hapi.protocol.window.asWindowMessage @@ -206,7 +207,12 @@ class MessageWindowStore( if (!canIncrement) { val requestBaseline = baseline() - val response = api.getMessages(sessionId, MessagesQuery.Latest(limit = PAGE_SIZE)) + val latestPageSize = if (initial.requiresLatestReset || initialCursor != null) { + PAGE_SIZE + } else { + INITIAL_PAGE_SIZE + } + val response = api.getMessages(sessionId, MessagesQuery.Latest(limit = latestPageSize)) if (!isCurrentTailSync(generation)) return update { previous -> if (previous.syncGeneration != generation) return@update previous 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/data/src/test/kotlin/app/hapi/data/store/MessageWindowStoreTest.kt b/android/core/data/src/test/kotlin/app/hapi/data/store/MessageWindowStoreTest.kt index acb73144..86b22529 100644 --- a/android/core/data/src/test/kotlin/app/hapi/data/store/MessageWindowStoreTest.kt +++ b/android/core/data/src/test/kotlin/app/hapi/data/store/MessageWindowStoreTest.kt @@ -9,6 +9,8 @@ import app.hapi.protocol.window.MessageViewMode import app.hapi.protocol.window.MessagePosition import app.hapi.protocol.window.OlderLoadOutcome import app.hapi.protocol.window.PersistedMessageWindow +import app.hapi.protocol.window.INITIAL_PAGE_SIZE +import app.hapi.protocol.window.PAGE_SIZE import app.hapi.protocol.window.asWindowMessage import app.hapi.protocol.window.buildOptimisticMessage import app.hapi.protocol.wire.DecryptedMessage @@ -236,6 +238,37 @@ class MessageWindowStoreTest { assertEquals(false, store.state.value.isLoadingMore) } + @Test + fun `cold sync requests the initial page size`() = runTest { + val api = GatedMessagesApi() + val store = MessageWindowStore("s", api, backgroundScope) + + val sync = launch { store.syncTail() } + runCurrent() + assertEquals(1, api.requests.size) + assertTrue(api.requests.single() is MessagesQuery.Latest) + assertEquals(INITIAL_PAGE_SIZE, (api.requests.single() as MessagesQuery.Latest).limit) + + api.release(latestPage(listOf(agentRow("a-1", 1, 1000)), epoch = 0)) + sync.join() + } + + @Test + fun `reset sync keeps the full latest page size`() = runTest { + val api = GatedMessagesApi() + val initial = MessageWindowLogic.createState("s").copy(requiresLatestReset = true) + val store = MessageWindowStore("s", api, backgroundScope, initialState = initial) + + val sync = launch { store.syncTail() } + runCurrent() + assertEquals(1, api.requests.size) + assertTrue(api.requests.single() is MessagesQuery.Latest) + assertEquals(PAGE_SIZE, (api.requests.single() as MessagesQuery.Latest).limit) + + api.release(latestPage(listOf(agentRow("a-1", 1, 1000)), epoch = 1)) + sync.join() + } + @Test fun `concurrent syncTail calls coalesce into a single run`() = runTest { val api = GatedMessagesApi() diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/window/MessageWindowState.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/window/MessageWindowState.kt index 06df5ded..fd63ef1d 100644 --- a/android/core/protocol/src/main/kotlin/app/hapi/protocol/window/MessageWindowState.kt +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/window/MessageWindowState.kt @@ -16,6 +16,8 @@ const val HISTORY_WINDOW_SIZE: Int = 600 const val OLDER_LOAD_WINDOW_SIZE: Int = 800 const val AGENT_RUN_WINDOW_SIZE: Int = 800 const val PAGE_SIZE: Int = 200 +/** Request size for a genuinely cold latest page, prioritizing first paint. */ +const val INITIAL_PAGE_SIZE: Int = 20 enum class MessageViewMode(val wire: String) { /** Following the live bottom; trims from the top. */ 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/bun.lock b/bun.lock index ab88d7bb..ddfadeab 100644 --- a/bun.lock +++ b/bun.lock @@ -13,7 +13,7 @@ }, "cli": { "name": "@twsxtd/hapi", - "version": "0.30.3", + "version": "0.30.7", "bin": { "hapi": "bin/hapi.cjs", }, @@ -48,11 +48,11 @@ "vitest": "^4.0.16", }, "optionalDependencies": { - "@twsxtd/hapi-darwin-arm64": "0.30.3", - "@twsxtd/hapi-darwin-x64": "0.30.3", - "@twsxtd/hapi-linux-arm64": "0.30.3", - "@twsxtd/hapi-linux-x64": "0.30.3", - "@twsxtd/hapi-win32-x64": "0.30.3", + "@twsxtd/hapi-darwin-arm64": "0.30.7", + "@twsxtd/hapi-darwin-x64": "0.30.7", + "@twsxtd/hapi-linux-arm64": "0.30.7", + "@twsxtd/hapi-linux-x64": "0.30.7", + "@twsxtd/hapi-win32-x64": "0.30.7", }, }, "docs": { @@ -1111,15 +1111,15 @@ "@twsxtd/hapi": ["@twsxtd/hapi@workspace:cli"], - "@twsxtd/hapi-darwin-arm64": ["@twsxtd/hapi-darwin-arm64@0.30.3", "", { "os": "darwin", "cpu": "arm64", "bin": { "hapi": "bin/hapi" } }, "sha512-Z9gyucz1dIte3F/Q1iJeoU1HDDkTNihJugmXUGBivPV2snYfYewxnnUj7AwvN4wsGIrtx5WTi59TtY/Cp1ZLiA=="], + "@twsxtd/hapi-darwin-arm64": ["@twsxtd/hapi-darwin-arm64@0.30.7", "", { "os": "darwin", "cpu": "arm64", "bin": { "hapi": "bin/hapi" } }, "sha512-liXzQiIdNrEobPqlVRmbdIcN8r7W9e/7Vcc5gO34keJwzr6PZ4JZO4BM2PnNuw57WD2EeXb4aBR5PSOFhYi6Xw=="], - "@twsxtd/hapi-darwin-x64": ["@twsxtd/hapi-darwin-x64@0.30.3", "", { "os": "darwin", "cpu": "x64", "bin": { "hapi": "bin/hapi" } }, "sha512-oggYX9p08nPFAT9/bdb7kLTGm7As79+vvosO1kLzHoxNNE0c6M3QKm3CMPo5uTAUXBwzMqCUnnfc0HyWALxemg=="], + "@twsxtd/hapi-darwin-x64": ["@twsxtd/hapi-darwin-x64@0.30.7", "", { "os": "darwin", "cpu": "x64", "bin": { "hapi": "bin/hapi" } }, "sha512-GbakM5JycgyINRfsBfHwvUIqA/faq63Kzu28ARcFxXqyet4hrS8P0Xawrsbmawq6RibK3sI74kX5cRlFmtXpZw=="], - "@twsxtd/hapi-linux-arm64": ["@twsxtd/hapi-linux-arm64@0.30.3", "", { "os": "linux", "cpu": "arm64", "bin": { "hapi": "bin/hapi" } }, "sha512-OUYolzz1wj0AX5yysmEOnQoA2G7RqWr/rlJtYlp2shzvpjNI4mVTTNT44QlhGaqpY12+mJf5A0qKwjDhu59YEw=="], + "@twsxtd/hapi-linux-arm64": ["@twsxtd/hapi-linux-arm64@0.30.7", "", { "os": "linux", "cpu": "arm64", "bin": { "hapi": "bin/hapi" } }, "sha512-v3OQ7ZrsLLwcCGIBd9lCCp+5vNoR0u+g+oWUV2iIAWvi2nmGF6zHvYT0Bl4+G9rjk29wdR8XemrItSfQrc3kbg=="], - "@twsxtd/hapi-linux-x64": ["@twsxtd/hapi-linux-x64@0.30.3", "", { "os": "linux", "cpu": "x64", "bin": { "hapi": "bin/hapi" } }, "sha512-DTP5NFod54hYvSXW9gyGmbPg1IFuywfzaxeGq9HeLaXtt+38WBYurcWJ1yR9G66F6wnPBEdglS5UYBz0QXCOZQ=="], + "@twsxtd/hapi-linux-x64": ["@twsxtd/hapi-linux-x64@0.30.7", "", { "os": "linux", "cpu": "x64", "bin": { "hapi": "bin/hapi" } }, "sha512-/e712GKRzzeVD2SMO+ApIxd1/CkIHyKZRRzkEK1WWWvcie45Onres8z58V3liEA/JxbHUxaKaOPW7N0xQBVq1Q=="], - "@twsxtd/hapi-win32-x64": ["@twsxtd/hapi-win32-x64@0.30.3", "", { "os": "win32", "cpu": "x64", "bin": { "hapi": "bin/hapi.exe" } }, "sha512-3ZKhZx93CEYf8acT+2zWKgro2V0yt5mLLQZJ+C2YYnRFGtvBduopUj6mDVWNYJhfdPaOb3ahfAuhHlef6N6J4A=="], + "@twsxtd/hapi-win32-x64": ["@twsxtd/hapi-win32-x64@0.30.7", "", { "os": "win32", "cpu": "x64", "bin": { "hapi": "bin/hapi.exe" } }, "sha512-oO43ncEFZVEUIUxQjzwTNdr70ae1pc8TEYBBa+lGhIOpU5NQNWu+Fc0tKqwvIcRKhXYqsHHPaVLqp+gg5uHxeQ=="], "@types/aria-query": ["@types/aria-query@5.0.4", "", {}, "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw=="], diff --git a/cli/README.md b/cli/README.md index ec889e75..3d35e6eb 100644 --- a/cli/README.md +++ b/cli/README.md @@ -181,6 +181,15 @@ bun run build:single-exe - `src/ui/` - User interface and diagnostics. - `src/modules/` - Tool implementations (ripgrep, difftastic, git). +## Releasing + +From the repository root, `bun run release-all ` updates the CLI package, +shared app version, iOS `MARKETING_VERSION` (app and notification extension, all +configurations), and Android's default `versionName` before building and publishing. +Use `--dry-run` to preview without changing files or publishing. Native build +numbers (`CURRENT_PROJECT_VERSION` / `versionCode`) remain managed separately; +Android's `-PhapiVersionName` override is preserved. + ## Related docs - `../hub/README.md` diff --git a/cli/package.json b/cli/package.json index 91186e5e..e7f9a084 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "@twsxtd/hapi", - "version": "0.30.3", + "version": "0.30.7", "description": "App for agentic coding - access coding agent anywhere", "author": "Kirill Dubovitskiy & weishu", "license": "AGPL-3.0-only", @@ -26,11 +26,11 @@ } }, "optionalDependencies": { - "@twsxtd/hapi-darwin-arm64": "0.30.3", - "@twsxtd/hapi-darwin-x64": "0.30.3", - "@twsxtd/hapi-linux-arm64": "0.30.3", - "@twsxtd/hapi-linux-x64": "0.30.3", - "@twsxtd/hapi-win32-x64": "0.30.3" + "@twsxtd/hapi-darwin-arm64": "0.30.7", + "@twsxtd/hapi-darwin-x64": "0.30.7", + "@twsxtd/hapi-linux-arm64": "0.30.7", + "@twsxtd/hapi-linux-x64": "0.30.7", + "@twsxtd/hapi-win32-x64": "0.30.7" }, "scripts": { "postinstall": "node -e \"try{require('fs').chmodSync(require('path').join(__dirname,'bin','hapi.cjs'),0o755)}catch(e){}\"", diff --git a/cli/scripts/release-all.ts b/cli/scripts/release-all.ts index 5700dc26..4837150f 100644 --- a/cli/scripts/release-all.ts +++ b/cli/scripts/release-all.ts @@ -1,7 +1,7 @@ #!/usr/bin/env bun /** * Unified release script that handles the complete release flow: - * 1. Bump version + * 1. Bump CLI, shared, iOS, and Android versions * 2. Build binaries (with embedded web assets) * 3. Publish platform packages first (so lockfile can resolve them) * 4. Verify all platform packages are live on npm @@ -11,13 +11,12 @@ */ import { execSync } from 'node:child_process'; -import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; +import { updateReleaseVersions } from './release-version'; const scriptDir = import.meta.dir; const projectRoot = join(scriptDir, '..'); const repoRoot = join(projectRoot, '..'); -const buildInfoPath = join(repoRoot, 'shared', 'src', 'buildInfo.ts'); // 解析参数 const args = process.argv.slice(2); @@ -43,22 +42,6 @@ function run(cmd: string, cwd = projectRoot): void { } } -function updateBuildInfoVersion(nextVersion: string): void { - const content = readFileSync(buildInfoPath, 'utf-8'); - const updated = content.replace( - /export const APP_VERSION = ['"][^'"]+['"]/, - `export const APP_VERSION = '${nextVersion}'` - ); - - if (updated === content) { - throw new Error(`Could not update APP_VERSION in ${buildInfoPath}`); - } - - if (!dryRun) { - writeFileSync(buildInfoPath, updated); - } -} - async function waitForPlatformPackages(platforms: string[], expectedVersion: string): Promise { const timeoutMs = 10 * 60 * 1000; const intervalMs = 15_000; @@ -107,7 +90,7 @@ async function runWithTimeoutRetry(cmd: string, cwd = projectRoot): Promise { +async function main(version: string): Promise { const flags = [dryRun && 'dry-run', publishNpm && 'publish-npm', skipBuild && 'skip-build'].filter(Boolean); console.log(`\n🚀 Starting release v${version}${flags.length ? ` (${flags.join(', ')})` : ''}\n`); @@ -133,16 +116,9 @@ async function main(): Promise { console.log(' ✓ Skipping npm login check (dry-run)'); } - // Step 1: Update package.json version - console.log('📦 Step 1: Updating package.json version...'); - const pkgPath = join(projectRoot, 'package.json'); - const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')); - const oldVersion = pkg.version; - pkg.version = version; - if (!dryRun) { - writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n'); - } - updateBuildInfoVersion(version); + // Step 1: Update all release versions before building or publishing. + console.log('📦 Step 1: Updating CLI, shared, iOS, and Android versions...'); + const oldVersion = updateReleaseVersions(repoRoot, version, dryRun); console.log(` ${oldVersion} → ${version}`); // Step 2: Build all platform binaries (with embedded web assets) @@ -197,7 +173,7 @@ async function main(): Promise { console.log(`\n✅ Release v${version} completed!`); } -main().catch(err => { +main(version).catch(err => { console.error('Release failed:', err); process.exit(1); }); diff --git a/cli/scripts/release-version.test.ts b/cli/scripts/release-version.test.ts new file mode 100644 index 00000000..0a0eca1f --- /dev/null +++ b/cli/scripts/release-version.test.ts @@ -0,0 +1,106 @@ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { updateReleaseVersions } from './release-version'; + +const sourceRoot = fileURLToPath(new URL('../..', import.meta.url)); +const paths = { + cli: 'cli/package.json', + shared: 'shared/src/buildInfo.ts', + ios: 'ios/Hapi.xcodeproj/project.pbxproj', + android: 'android/app/build.gradle.kts', +}; + +describe('updateReleaseVersions', () => { + let repoRoot: string; + + function read(path: string): string { + return readFileSync(join(repoRoot, path), 'utf-8'); + } + + function write(path: string, content: string): void { + writeFileSync(join(repoRoot, path), content); + } + + function snapshot(): string[] { + return Object.values(paths).map(read); + } + + beforeEach(() => { + repoRoot = mkdtempSync(join(tmpdir(), 'hapi-release-version-')); + // Exercise the real project formats without ever modifying the checkout. + for (const path of Object.values(paths)) { + mkdirSync(dirname(join(repoRoot, path)), { recursive: true }); + write(path, readFileSync(join(sourceRoot, path), 'utf-8')); + } + }); + + afterEach(() => { + rmSync(repoRoot, { recursive: true, force: true }); + }); + + it('updates every release version while preserving other settings and native build numbers', () => { + const pkg = JSON.parse(read(paths.cli)); + const shared = read(paths.shared); + const ios = read(paths.ios); + const android = read(paths.android); + + expect(updateReleaseVersions(repoRoot, '1.2.3')).toBe(pkg.version); + + expect(JSON.parse(read(paths.cli))).toEqual({ ...pkg, version: '1.2.3' }); + expect(read(paths.shared)).toBe(shared.replace(/APP_VERSION = ['"][^'"]+['"]/, "APP_VERSION = '1.2.3'")); + expect(read(paths.ios)).toBe(ios.replace(/MARKETING_VERSION = [^;]+;/g, 'MARKETING_VERSION = 1.2.3;')); + // Both app and extension, Debug and Release, must stay in sync. + expect([...read(paths.ios).matchAll(/MARKETING_VERSION = ([^;]+);/g)].map(match => match[1])) + .toEqual(['1.2.3', '1.2.3', '1.2.3', '1.2.3']); + expect(read(paths.android)).toBe(android.replace( + /versionName = .*/, + 'versionName = providers.gradleProperty("hapiVersionName").orElse("1.2.3").get()' + )); + }); + + it('does not change any files in dry-run mode', () => { + const before = snapshot(); + + expect(updateReleaseVersions(repoRoot, '1.2.3', true)).toBe(JSON.parse(read(paths.cli)).version); + + expect(snapshot()).toEqual(before); + }); + + it('can retry the same version without failing or changing build numbers', () => { + updateReleaseVersions(repoRoot, '1.2.3'); + const before = snapshot(); + + expect(updateReleaseVersions(repoRoot, '1.2.3')).toBe('1.2.3'); + + expect(snapshot()).toEqual(before); + }); + + it('repairs stale native versions even when CLI and shared versions are already current', () => { + updateReleaseVersions(repoRoot, '1.2.3'); + const expected = snapshot(); + write(paths.ios, read(paths.ios).replaceAll('MARKETING_VERSION = 1.2.3;', 'MARKETING_VERSION = 0.0.1;')); + write(paths.android, read(paths.android).replace('orElse("1.2.3")', 'orElse("0.0.1")')); + + expect(updateReleaseVersions(repoRoot, '1.2.3')).toBe('1.2.3'); + + expect(snapshot()).toEqual(expected); + }); + + describe.each([false, true])('validation (dryRun: %s)', dryRun => { + it.each([ + [paths.shared, 'APP_VERSION'], + [paths.ios, 'MARKETING_VERSION'], + [paths.android, 'hapiVersionName'], + ])('rejects a missing version field in %s before writing any files', (path, field) => { + write(path, read(path).replaceAll(field, 'REMOVED_VERSION_FIELD')); + const before = snapshot(); + + expect(() => updateReleaseVersions(repoRoot, '1.2.3', dryRun)).toThrow(path); + + expect(snapshot()).toEqual(before); + }); + }); +}); diff --git a/cli/scripts/release-version.ts b/cli/scripts/release-version.ts new file mode 100644 index 00000000..4fcf39b2 --- /dev/null +++ b/cli/scripts/release-version.ts @@ -0,0 +1,50 @@ +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +/** Update release versions without changing native build numbers or Gradle overrides. */ +export function updateReleaseVersions(repoRoot: string, version: string, dryRun = false): string { + const pkgPath = join(repoRoot, 'cli', 'package.json'); + const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')); + const oldVersion: string = pkg.version; + pkg.version = version; + + function updateVersionFile(relativePath: string, pattern: RegExp): { path: string; content: string } { + const path = join(repoRoot, relativePath); + const content = readFileSync(path, 'utf-8'); + let matched = false; + const updated = content.replace(pattern, (_match, prefix: string, suffix: string) => { + matched = true; + return `${prefix}${version}${suffix}`; + }); + // An already-current version is valid (e.g. when retrying a release). + if (!matched) { + throw new Error(`Could not find release version in ${relativePath}`); + } + return { path, content: updated }; + } + + // Read and validate every version field before writing any files. + const updates = [ + { path: pkgPath, content: JSON.stringify(pkg, null, 2) + '\n' }, + updateVersionFile( + 'shared/src/buildInfo.ts', + /(export const APP_VERSION = ['"])[^'"\r\n]+(['"])/ + ), + // Includes Debug/Release for both Hapi and HapiNotificationService. + updateVersionFile( + 'ios/Hapi.xcodeproj/project.pbxproj', + /^([ \t]*MARKETING_VERSION\s*=\s*)[^;\r\n]+(;)/gm + ), + updateVersionFile( + 'android/app/build.gradle.kts', + /(versionName\s*=\s*providers\.gradleProperty\("hapiVersionName"\)\.orElse\(")[^"]+("\))/ + ), + ]; + + if (!dryRun) { + for (const update of updates) { + writeFileSync(update.path, update.content); + } + } + return oldVersion; +} diff --git a/cli/src/api/apiMachine.test.ts b/cli/src/api/apiMachine.test.ts index def544e6..80ea6fd2 100644 --- a/cli/src/api/apiMachine.test.ts +++ b/cli/src/api/apiMachine.test.ts @@ -765,6 +765,51 @@ describe('ApiMachineClient list-directory handler', () => { return entries.map((entry) => entry.name).sort() } + it('refuses browsing when no workspace roots are configured', async () => { + // Local deployment policy: a machine without --workspace-root keeps + // directory browsing disabled instead of exposing the runner account's + // whole filesystem to the web UI. + const machine = makeMachine('machine-ls-unrestricted') + const client = new ApiMachineClient('cli-token', machine) + try { + const result = await callListDirectory(client, machine.id, { path: workspaceRoot }) + expect(result).toMatchObject({ + success: false, + error: 'Workspace browsing is not enabled for this machine' + }) + } finally { + client.shutdown() + } + }) + + it('lists in-root directory links and rejects links escaping explicit workspace roots', async () => { + const outside = mkdtempSync(join(tmpdir(), 'hapi-machine-ls-outside-')) + mkdirSync(join(workspaceRoot, 'visible-dir', '.git')) + symlinkSync(join(workspaceRoot, 'visible-dir'), join(workspaceRoot, 'linked-repo'), 'dir') + symlinkSync(outside, join(workspaceRoot, 'escape'), 'dir') + const machine = makeMachine('machine-ls-links') + const client = new ApiMachineClient('cli-token', machine, [workspaceRoot]) + try { + const result = await callListDirectory(client, machine.id, { path: workspaceRoot }) + expect(result).toMatchObject({ + success: true, + entries: expect.arrayContaining([ + expect.objectContaining({ name: 'linked-repo', type: 'directory', isGitRepo: true }), + ]), + }) + expect(entryNames(result)).not.toContain('escape') + expect(await callListDirectory(client, machine.id, { path: join(workspaceRoot, 'escape') })) + .toEqual({ success: false, error: 'Path is outside workspace roots' }) + expect(await callListDirectory(client, machine.id, { path: join(workspaceRoot, '..') })) + .toEqual({ success: false, error: 'Path is outside workspace roots' }) + expect(await callListDirectory(client, machine.id, { path: join(workspaceRoot, 'linked-repo') })) + .toMatchObject({ success: true }) + } finally { + client.shutdown() + rmSync(outside, { recursive: true, force: true }) + } + }) + it('filters dot-prefixed entries by default', async () => { const machine = makeMachine('machine-ls-1') const client = new ApiMachineClient('cli-token', machine, [workspaceRoot]) diff --git a/cli/src/api/apiMachine.ts b/cli/src/api/apiMachine.ts index 99767cd5..bf5fc500 100644 --- a/cli/src/api/apiMachine.ts +++ b/cli/src/api/apiMachine.ts @@ -3,9 +3,8 @@ */ import { io, type Socket } from 'socket.io-client' -import { readdir, realpath, stat } from 'node:fs/promises' -import { realpathSync } from 'node:fs' -import { basename, dirname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path' +import { readdir, stat } from 'node:fs/promises' +import { join } from 'node:path' import { logger } from '@/ui/logger' import { configuration } from '@/configuration' import type { ClientToServerEvents, ServerToClientEvents, Update, UpdateMachineBody } from '@hapi/protocol' @@ -68,7 +67,9 @@ import { inspectCursorChatStore } from '@/cursor/cursorChatStoreStatus' import { homedir } from 'node:os' import type { CursorChatStoreStatus } from '@hapi/protocol/apiTypes' import { getAgentAvailabilityResponse } from '@/agent/agentAvailability' -import { MachinePathPolicy } from './machinePathPolicy' +import { MachinePathPolicy, normalizeWindowsDriveRoot } from './machinePathPolicy' + +export { normalizeWindowsDriveRoot } type MachineRpcHandlers = { spawnSession: (options: SpawnSessionOptions) => Promise @@ -91,30 +92,6 @@ interface CursorChatStoreStatusRequest { homeDir?: string } -export function normalizeWindowsDriveRoot(path: string): string { - return /^[A-Za-z]:$/.test(path) ? `${path}\\` : path -} - -function canonicalRealpathSync(path: string): string { - return normalizeWindowsDriveRoot(realpathSync.native(path)) -} - -function normalizeWorkspaceRoots(paths?: string[]): string[] | undefined { - if (!paths?.length) { - return undefined - } - - const normalized = Array.from(new Set(paths.map((path) => { - try { - return canonicalRealpathSync(path) - } catch { - return normalizeWindowsDriveRoot(resolvePath(path)) - } - }))) - - return normalized.length > 0 ? normalized : undefined -} - function workspaceRootsEqual(left?: string[], right?: string[]): boolean { const normalizedLeft = left ?? [] const normalizedRight = right ?? [] @@ -135,7 +112,6 @@ export class ApiMachineClient { private keepAliveStartTimeout: ReturnType | null = null private rpcHandlerManager: RpcHandlerManager - private readonly normalizedWorkspaceRoots: string[] | undefined private readonly pathPolicy: MachinePathPolicy constructor( @@ -143,13 +119,8 @@ export class ApiMachineClient { private readonly machine: Machine, private readonly workspaceRoots?: string[] ) { - // Realpath roots once so all subsequent comparisons are against - // canonical, symlink-resolved locations. Falls back to lexical - // resolution if realpath fails so we still get protection. - this.normalizedWorkspaceRoots = normalizeWorkspaceRoots(workspaceRoots) this.pathPolicy = new MachinePathPolicy({ workspaceRoots, - homeDirectory: this.machine.metadata?.homeDir ?? homedir(), }) this.rpcHandlerManager = new RpcHandlerManager({ @@ -196,7 +167,7 @@ export class ApiMachineClient { ) this.rpcHandlerManager.registerHandler(RPC_METHODS.ListMachineDirectory, async (params) => { - if (!this.normalizedWorkspaceRoots?.length) { + if (!this.pathPolicy.hasWorkspaceRoots()) { return { success: false, error: 'Workspace browsing is not enabled for this machine' } } @@ -207,8 +178,8 @@ export class ApiMachineClient { const includeHidden = params?.includeHidden === true - const targetPath = await this.resolveForWorkspaceCheck(rawPath) - if (!this.isWithinWorkspaceRoots(targetPath)) { + const targetPath = await this.pathPolicy.resolveForCheck(rawPath) + if (!this.pathPolicy.isWithinBrowseRoots(targetPath)) { return { success: false, error: 'Path is outside workspace roots' } } @@ -225,34 +196,27 @@ export class ApiMachineClient { if (!includeHidden && entry.name.startsWith('.')) return const fullPath = join(targetPath, entry.name) + const resolvedEntryPath = entry.isSymbolicLink() + ? await this.pathPolicy.resolveForCheck(fullPath) + : fullPath + if (!this.pathPolicy.isWithinBrowseRoots(resolvedEntryPath)) return + const stats = await stat(resolvedEntryPath).catch(() => undefined) let type: 'file' | 'directory' | 'other' = 'other' - let size: number | undefined - let modified: number | undefined let isGitRepo = false - if (entry.isDirectory()) { + if (entry.isDirectory() || stats?.isDirectory()) { type = 'directory' try { - const gitStat = await stat(join(fullPath, '.git')) + const gitStat = await stat(join(resolvedEntryPath, '.git')) isGitRepo = gitStat.isDirectory() || gitStat.isFile() } catch { // not a git repo } - } else if (entry.isFile()) { + } else if (entry.isFile() || stats?.isFile()) { type = 'file' } - if (!entry.isSymbolicLink()) { - try { - const stats = await stat(fullPath) - size = stats.size - modified = stats.mtime.getTime() - } catch { - // ignore stat errors - } - } - - entries.push({ name: entry.name, type, size, modified, isGitRepo }) + entries.push({ name: entry.name, type, size: stats?.size, modified: stats?.mtime.getTime(), isGitRepo }) })) entries.sort((a, b) => { @@ -469,50 +433,10 @@ export class ApiMachineClient { } private async isLocalSessionWithinWorkspaceRoots(session: { cwd?: string | null }): Promise { - if (!this.normalizedWorkspaceRoots?.length) return true + if (!this.pathPolicy.hasWorkspaceRoots()) return true const cwd = session.cwd?.trim() if (!cwd) return false - const resolvedCwd = await this.resolveForWorkspaceCheck(cwd) - return this.pathPolicy.isWithinSpawnRoots(resolvedCwd) - } - - private isWithinWorkspaceRoots(absolutePath: string): boolean { - if (!this.normalizedWorkspaceRoots?.length) return true - return this.normalizedWorkspaceRoots.some((workspaceRoot) => { - const rel = relative(workspaceRoot, absolutePath) - return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)) - }) - } - - /** - * Canonicalize a path for workspace-root containment checks. Resolves - * symlinks via realpath so a symlink such as `/safe/out -> /etc` cannot - * be used to escape the configured root with a lexical-only check. - * - * If the path doesn't exist (e.g. a session is being spawned in a - * directory we'll create), walks up to the nearest existing ancestor - * and realpaths *that*, joining the missing tail back on. This way the - * check still runs against the real on-disk location once any - * intermediate symlink in the parent chain has been resolved. - */ - private async resolveForWorkspaceCheck(path: string): Promise { - const absolute = resolvePath(path) - try { - return normalizeWindowsDriveRoot(await realpath(absolute)) - } catch { - const missing: string[] = [] - let cursor = absolute - while (cursor !== dirname(cursor)) { - missing.unshift(basename(cursor)) - cursor = dirname(cursor) - try { - return join(normalizeWindowsDriveRoot(await realpath(cursor)), ...missing) - } catch { - // keep walking to the nearest existing parent - } - } - return normalizeWindowsDriveRoot(absolute) - } + return this.pathPolicy.isWithinSpawnRoots(await this.pathPolicy.resolveForCheck(cwd)) } setRPCHandlers({ spawnSession, stopSession, requestShutdown }: MachineRpcHandlers): void { @@ -523,8 +447,8 @@ export class ApiMachineClient { throw new Error('Directory is required') } - const resolvedDirectory = await this.resolveForWorkspaceCheck(directory) - if (!this.isWithinWorkspaceRoots(resolvedDirectory)) { + const resolvedDirectory = await this.pathPolicy.resolveForCheck(directory) + if (!this.pathPolicy.isWithinSpawnRoots(resolvedDirectory)) { return { type: 'error', errorMessage: 'Directory is outside this machine\'s workspace roots' } } diff --git a/cli/src/api/machinePathPolicy.test.ts b/cli/src/api/machinePathPolicy.test.ts index 347beeb1..7d1bf020 100644 --- a/cli/src/api/machinePathPolicy.test.ts +++ b/cli/src/api/machinePathPolicy.test.ts @@ -16,6 +16,9 @@ describe('MachinePathPolicy', () => { expect(await policy.allowsSpawn(join(first, 'missing', 'child'))).toBe(true) expect(await policy.allowsSpawn(second)).toBe(true) expect(await policy.allowsSpawn(collision)).toBe(false) + expect(await policy.allowsBrowse(first)).toBe(true) + expect(await policy.allowsBrowse(collision)).toBe(false) + expect(await policy.allowsBrowse(join(first, '..project'))).toBe(true) }) it('resolves an existing symlink before checking a missing child', async () => { @@ -28,20 +31,21 @@ describe('MachinePathPolicy', () => { const policy = new MachinePathPolicy({ workspaceRoots: [root] }) expect(await policy.allowsSpawn(join(escape, 'missing'))).toBe(false) + expect(await policy.allowsBrowse(escape)).toBe(false) expect(await policy.resolveForCheck(join(escape, 'missing'))).toBe( join(await realpath(outside), 'missing') ) }) - it('keeps manual spawn unrestricted but scopes browsing to home without roots', async () => { + it('allows both browsing and spawning outside home without explicit roots', async () => { const base = await mkdtemp(join(tmpdir(), 'hapi-path-policy-')) const home = join(base, 'home') const outside = join(base, 'outside') await Promise.all([mkdir(home), mkdir(outside)]) - const policy = new MachinePathPolicy({ homeDirectory: home }) + const policy = new MachinePathPolicy() expect(await policy.allowsSpawn(outside)).toBe(true) expect(await policy.allowsBrowse(join(home, 'missing'))).toBe(true) - expect(await policy.allowsBrowse(outside)).toBe(false) + expect(await policy.allowsBrowse(outside)).toBe(true) }) }) diff --git a/cli/src/api/machinePathPolicy.ts b/cli/src/api/machinePathPolicy.ts index 7b8d8943..2c9de7b7 100644 --- a/cli/src/api/machinePathPolicy.ts +++ b/cli/src/api/machinePathPolicy.ts @@ -1,6 +1,5 @@ import { realpathSync } from 'node:fs' import { realpath } from 'node:fs/promises' -import { homedir } from 'node:os' import { basename, dirname, @@ -8,6 +7,7 @@ import { join, relative, resolve, + sep, } from 'node:path' export function normalizeWindowsDriveRoot(path: string): string { @@ -31,30 +31,24 @@ function normalizeRoots(paths: readonly string[]): string[] { function isPathWithinRoots(path: string, roots: readonly string[]): boolean { return roots.some((root) => { const child = relative(root, path) - return child === '' || (!child.startsWith('..') && !isAbsolute(child)) + return child !== '..' && !child.startsWith(`..${sep}`) && !isAbsolute(child) }) } /** * Single authority for machine-scoped path access. * - * Spawn paths are unrestricted when the runner has no configured workspace - * roots, preserving the legacy manual-entry contract. Browse paths instead - * fall back to the runner's home directory so native autocomplete/pickers can - * remain useful without exposing the whole filesystem. + * Browsing and spawning share the same boundaries. Without explicit workspace + * roots, both can access any path available to the runner's OS account; a + * client's initial directory is a navigation preference, not an access limit. */ export class MachinePathPolicy { readonly workspaceRoots: readonly string[] - readonly browseRoots: readonly string[] constructor(options: { workspaceRoots?: readonly string[] - homeDirectory?: string } = {}) { this.workspaceRoots = normalizeRoots(options.workspaceRoots ?? []) - this.browseRoots = this.workspaceRoots.length > 0 - ? this.workspaceRoots - : normalizeRoots([options.homeDirectory ?? homedir()]) } hasWorkspaceRoots(): boolean { @@ -66,7 +60,7 @@ export class MachinePathPolicy { } isWithinBrowseRoots(path: string): boolean { - return isPathWithinRoots(path, this.browseRoots) + return this.isWithinSpawnRoots(path) } async resolveForCheck(path: string): Promise { 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/shared/projection.title.test.ts b/cli/src/codex/shared/projection.title.test.ts new file mode 100644 index 00000000..dbe1e01c --- /dev/null +++ b/cli/src/codex/shared/projection.title.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { ApiSessionClient } from '@/api/apiSession'; +import type { Metadata } from '@/api/types'; +import { SharedCodexProjection } from './projection'; + +function fixture(parentThreadId?: string, deferWrites = false) { + let metadata: Metadata = { path: '/repo', host: 'test', flavor: 'codex', name: 'Manual name' }; + const queued: Array<(value: Metadata) => Metadata> = []; + const update = vi.fn((fn: (value: Metadata) => Metadata) => { + if (deferWrites) queued.push(fn); + else metadata = fn(metadata); + }); + const send = vi.fn(); + const committed = vi.fn(async (_id: string) => {}); + const session = { + getMetadata: () => metadata, updateMetadata: update, sendAgentMessage: send, + sendUserMessage() {} + } as unknown as ApiSessionClient; + return { + projection: new SharedCodexProjection(session, 'thread', committed, parentThreadId), + metadata: () => metadata, update, send, committed, + flush: () => { for (const fn of queued.splice(0)) metadata = fn(metadata); } + }; +} + +function titleItem(id: string, title: string) { + return { id, type: 'mcpToolCall', server: 'hapi', tool: 'change_title', arguments: { title }, + status: 'completed', result: { content: [{ type: 'text', text: 'Successfully changed chat title' }], isError: false } }; +} +function params(item: unknown, turnId = 'turn') { return { threadId: 'thread', turnId, item }; } +function history(...items: unknown[]) { return { turns: [{ id: 'turn', status: 'completed', items }] }; } + +describe('shared Codex titles', () => { + it('persists a successful root tool title while preserving the manual name and transcript', async () => { + const f = fixture(); + const item = titleItem('title', ' Remote title '); + await f.projection.notification('item/started', params(item)); + expect(f.update).not.toHaveBeenCalled(); + // Completion may omit the arguments already sent at start. + await f.projection.notification('item/completed', params({ ...item, arguments: undefined })); + expect(f.metadata()).toMatchObject({ name: 'Manual name', summary: { text: 'Remote title', updatedAt: expect.any(Number) } }); + expect(f.send.mock.calls.map(([body]) => body.type)).toEqual(['tool-call', 'tool-call-result']); + expect(f.update).toHaveBeenCalledTimes(1); + await f.projection.notification('item/completed', params(item)); + f.projection.reset(); + await f.projection.history(history(item)); + await f.projection.notification('item/completed', params(item)); + expect(f.update).toHaveBeenCalledTimes(1); + }); + + it('handles a complete item without a start and orders successive titles across deferred writes', async () => { + const f = fixture(undefined, true); + await f.projection.notification('item/completed', params(titleItem('first', 'First'))); + await f.projection.notification('item/completed', params(titleItem('second', 'Second'))); + f.flush(); + expect(f.metadata().summary?.text).toBe('Second'); + }); + + it.each([ + { status: 'failed' }, { status: 'cancelled' }, { status: 'inProgress' }, + { error: { message: 'failed' } }, { result: { Err: 'failed' } }, + { result: { isError: true } }, { result: { Ok: { isError: true } } }, + { result: null }, { arguments: { title: ' ' } }, + { server: 'other' }, { tool: 'other' } + ])('ignores unsuccessful or unrelated tools: %j', async overrides => { + const f = fixture(); + const item = { ...titleItem('title', 'Wrong'), ...overrides }; + await f.projection.notification('item/started', params(item)); + await f.projection.notification('item/completed', params(item)); + await f.projection.history(history(item)); + expect(f.update).not.toHaveBeenCalled(); + }); + + it('isolates child and sibling titles from the root metadata', async () => { + const child = fixture('parent'); + const item = titleItem('title', 'Child title'); + await child.projection.notification('item/started', params(item)); + await child.projection.notification('item/completed', params(item)); + await child.projection.history(history(item)); + expect(child.update).not.toHaveBeenCalled(); + expect(child.send.mock.calls[0][0].type).toBe('agent-run-trace'); + const root = fixture(); + await root.projection.notification('item/completed', { ...params(item), threadId: 'sibling' }); + expect(root.update).not.toHaveBeenCalled(); + }); + + it('restores only the last successful historical title and does not replay earlier names', async () => { + const f = fixture(); + const first = titleItem('first', 'First'); + const last = titleItem('last', 'Last'); + const snapshot = history(first, last, { ...titleItem('failed', 'Failed'), result: { isError: true } }); + await f.projection.history(snapshot); + expect(f.metadata().summary?.text).toBe('Last'); + expect(f.update).toHaveBeenCalledTimes(1); + f.projection.reset(); + await f.projection.history(snapshot); + await f.projection.notification('item/completed', params(first)); + expect(f.metadata().summary?.text).toBe('Last'); + expect(f.update).toHaveBeenCalledTimes(1); + }); + + it('never overwrites an existing summary during a cold history replay', async () => { + const f = fixture(); + f.update(metadata => ({ ...metadata, summary: { text: 'Existing', updatedAt: 123 } })); + f.update.mockClear(); + await f.projection.history(history(titleItem('old', 'Old'))); + expect(f.update).not.toHaveBeenCalled(); + expect(f.metadata().summary).toEqual({ text: 'Existing', updatedAt: 123 }); + }); + + it('keeps pending inputs from an active snapshot for a later argument-less completion', async () => { + const f = fixture(); + const item = { ...titleItem('title', 'Resumed'), status: 'inProgress', result: null }; + await f.projection.history({ turns: [{ id: 'turn', status: 'inProgress', items: [item] }] }); + expect(f.update).not.toHaveBeenCalled(); + await f.projection.notification('item/completed', params({ ...titleItem('title', 'unused'), arguments: undefined })); + expect(f.metadata().summary?.text).toBe('Resumed'); + }); + + it('does not roll back a live title when a suspended replay or queued metadata callback resumes', async () => { + const f = fixture(undefined, true); + let release!: () => void; + f.committed.mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); + const replay = f.projection.history(history( + { id: 'user', type: 'userMessage', content: [{ type: 'text', text: 'hello' }] }, + titleItem('old', 'Old') + )); + await vi.waitFor(() => expect(release).toBeTypeOf('function')); + await f.projection.notification('item/completed', params(titleItem('live', 'Live'), 'next')); + release(); await replay; + f.flush(); + expect(f.metadata().summary?.text).toBe('Live'); + + const queued = fixture(undefined, true); + await queued.projection.history(history(titleItem('old', 'Old'))); + await queued.projection.notification('item/completed', params(titleItem('live', 'Live'), 'next')); + queued.flush(); + expect(queued.metadata().summary?.text).toBe('Live'); + }); +}); diff --git a/cli/src/codex/shared/projection.ts b/cli/src/codex/shared/projection.ts index 68758bfc..c1e44e76 100644 --- a/cli/src/codex/shared/projection.ts +++ b/cli/src/codex/shared/projection.ts @@ -14,12 +14,29 @@ export function inputText(input: unknown): string { }).filter(Boolean).join('\n'); } +function requestedTitle(item: Record): string | undefined { + if (item.type !== 'mcpToolCall' || item.server !== 'hapi' || item.tool !== 'change_title') return; + return string(record(item.arguments).title)?.trim() || undefined; +} + +function successfulTitle(item: Record, pending?: string): string | undefined { + if (item.type !== 'mcpToolCall' || (item.status !== undefined && item.status !== 'completed') + || item.error != null || item.result == null) return; + const result = record(item.result); + if ('Err' in result || result.isError === true || record(result.Ok).isError === true) return; + return requestedTitle(item) ?? pending; +} + /** Canonical V2 stream only. Stable message IDs also deduplicate snapshot replay at the hub. */ export class SharedCodexProjection { private converter = new AppServerEventConverter(); private readonly emitted = new Set(); private readonly turns = new Map(); private readonly turnModels = new Map(); + // Unlike transcript emission, title side effects survive reset/replay. + private readonly pendingTitles = new Map(); + private readonly completedTitles = new Set(); + private titleRevision = 0; constructor(private readonly session: ApiSessionClient, readonly threadId: string, private readonly committed: (id: string) => Promise, private readonly parentThreadId?: string) { if (!parentThreadId) for (const [id, turn] of Object.entries(session.getMetadata()?.conversationHistoryTurns ?? {})) this.turns.set(id, turn); @@ -38,6 +55,30 @@ export class SharedCodexProjection { } async notification(method: string, params: unknown, modelAtReceipt?: string): Promise { + const p = record(params); + const item = record(p.item); + if (!this.parentThreadId && p.threadId === this.threadId && string(item.id)) { + const key = `${string(p.turnId) ?? 'thread'}:${item.id}`; + if (!this.completedTitles.has(key)) { + const title = requestedTitle(item); + if (method === 'item/started' && title) this.pendingTitles.set(key, title); + if (method === 'item/completed') { + const completedTitle = successfulTitle(item, this.pendingTitles.get(key)); + this.pendingTitles.delete(key); + if (completedTitle) { + this.completedTitles.add(key); + const revision = ++this.titleRevision; + this.session.updateMetadata(metadata => revision !== this.titleRevision ? metadata : { + ...metadata, summary: { text: completedTitle, updatedAt: Date.now() } + }); + } + } + } + } + await this.project(method, params, modelAtReceipt); + } + + private async project(method: string, params: unknown, modelAtReceipt?: string): Promise { if (method.startsWith('codex/event/')) return; const p = record(params); const item = record(p.item); @@ -126,18 +167,41 @@ export class SharedCodexProjection { async history(thread: unknown): Promise { const turns = record(thread).turns; if (!Array.isArray(turns)) return; + const titleRevision = this.titleRevision; + let latestTitle: string | undefined; for (const value of turns) { const turn = record(value); if (!Array.isArray(turn.items)) continue; for (const item of turn.items) { const params = { threadId: this.threadId, turnId: turn.id, item }; - await this.notification('item/started', params); + const titleKey = `${string(turn.id) ?? 'thread'}:${record(item).id}`; + const pendingTitle = requestedTitle(record(item)); + if (!this.parentThreadId && string(record(item).id) && pendingTitle && !this.completedTitles.has(titleKey)) { + this.pendingTitles.set(titleKey, pendingTitle); + } + await this.project('item/started', params); // Active snapshots can contain partial assistant text. Do not // settle it under the final stable id and suppress completion. if (turn.status !== 'inProgress' || record(item).status === 'completed' || record(item).type === 'userMessage') { - await this.notification('item/completed', params); + if (!this.parentThreadId) { + const title = successfulTitle(record(item)); + if (title && string(record(item).id)) { + latestTitle = title; + this.completedTitles.add(titleKey); + } + this.pendingTitles.delete(titleKey); + } + await this.project('item/completed', params); } } } + // Repair sessions created while remote title projection was missing. + // Recheck inside the metadata lock: live updates may still be queued, + // and a replay must never replace an existing or newer title. + if (latestTitle && titleRevision === this.titleRevision && !this.session.getMetadata()?.summary?.text?.trim()) { + const title = latestTitle; + this.session.updateMetadata(metadata => titleRevision !== this.titleRevision || metadata.summary?.text?.trim() + ? metadata : { ...metadata, summary: { text: title, updatedAt: Date.now() } }); + } } } diff --git a/cli/src/codex/shared/root.test.ts b/cli/src/codex/shared/root.test.ts index 4f996a23..392644ce 100644 --- a/cli/src/codex/shared/root.test.ts +++ b/cli/src/codex/shared/root.test.ts @@ -91,7 +91,7 @@ async function fixture(options: { deferHistory?: boolean } = {}) { notify(method: string, params: unknown): void; abandoned(): void; }; - return { root, native, rpc, send, state: () => state, updateState, reconnect: () => reconnect?.(), syncHistory: () => root.syncHistory(response) }; + return { root, native, rpc, send, metadata: () => metadata, state: () => state, updateState, reconnect: () => reconnect?.(), syncHistory: () => root.syncHistory(response) }; } async function completePlan(f: Awaited>, status = 'completed') { @@ -115,6 +115,19 @@ describe('shared plan actions', () => { expect(f.native.requests).toContain('thread/read'); }); + it('persists remote title tools while retaining native terminal rename events', async () => { + const f = await fixture(); + const item = { id: 'title', type: 'mcpToolCall', server: 'hapi', tool: 'change_title', + arguments: { title: 'Remote title' }, status: 'completed', result: { content: [], isError: false } }; + f.native.notify('item/completed', { threadId: 'thread', turnId: 'turn', item }); + await vi.waitFor(() => expect(f.metadata().summary?.text).toBe('Remote title')); + f.native.notify('thread/name/updated', { threadId: 'thread', threadName: 'Terminal title' }); + await vi.waitFor(() => expect(f.metadata().name).toBe('Terminal title')); + await f.root.refresh(); + expect(f.metadata().summary?.text).toBe('Remote title'); + expect(f.metadata().name).toBe('Terminal title'); + }); + it('preserves content while native turns, mode changes and disconnects withdraw controls', async () => { const f = await fixture(); const id = await completePlan(f); diff --git a/cli/src/codex/shared/root.ts b/cli/src/codex/shared/root.ts index 3e9d6972..8642fe42 100644 --- a/cli/src/codex/shared/root.ts +++ b/cli/src/codex/shared/root.ts @@ -143,6 +143,8 @@ export class SharedCodexRoot { } async prepare(): Promise { + // Descendants share this bridge. The projection applies successful + // root title calls so a child cannot rename the parent session. this.bridge = await buildHapiMcpBridge(this.session, { exportSessionEnv: false, emitTitleSummary: false, skillLookup: { workingDirectory: this.bootstrap.workingDirectory, flavor: 'codex' } }); await initializeSharedClient(this.client); 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/cli/vitest.config.ts b/cli/vitest.config.ts index 89c9432a..489daf46 100644 --- a/cli/vitest.config.ts +++ b/cli/vitest.config.ts @@ -5,7 +5,7 @@ export default defineConfig({ test: { globals: false, environment: 'node', - include: ['src/**/*.test.ts'], + include: ['src/**/*.test.ts', 'scripts/**/*.test.ts'], exclude: [ // Runner integration tests spawn real detached runner/session // process trees and must run serially through the dedicated diff --git a/docs/api/client-contract/pagination.md b/docs/api/client-contract/pagination.md index 03e0a721..f8f6e194 100644 --- a/docs/api/client-contract/pagination.md +++ b/docs/api/client-contract/pagination.md @@ -98,7 +98,10 @@ Client contract: Run after connect, after an SSE `resume: 'gap'` handshake, on session open, and when told to (`messages-invalidated`). Reference: `runTailSync` in `web/src/lib/message-window-store.ts`. -1. **No usable state** (no newest cursor, no cached epoch, or a reset is pending): `GET …/messages?limit=200` (latest), replace/merge into the window, store `page.epoch`, `nextBefore*` (older-page cursor) and `snapshotHead*` (newest cursor). Done. +1. **No usable state** (no newest cursor, no cached epoch, or a reset is pending): + - For a genuinely cold window with no cursor and no pending structural reset, request `GET …/messages?limit=20` (latest) so the newest usable conversation content can paint quickly. + - For a pending structural reset, request the normal full latest page with `limit=200`. + - Replace/merge into the window, store `page.epoch`, `nextBefore*` (older-page cursor) and `snapshotHead*` (newest cursor). Done. 2. **Have cursor + epoch**: loop - `GET …/messages?afterSeq&afterAt&epoch[&untilSeq&untilAt]&limit=200`, where `after` starts at your newest cursor and `until` is the `snapshotHead*` captured from the **first** response of the loop (fixes the target so the loop terminates). - `page.reset` or `direction: 'latest'` ⇒ replace the window with this page; stop. @@ -115,7 +118,8 @@ Constants from the web reference (`web/src/lib/message-window-store.ts`): | Constant | Value | Meaning | |---|---|---| -| `PAGE_SIZE` | 200 | Request size for every page fetch. | +| `INITIAL_PAGE_SIZE` | 20 | Request size for the cold latest page used to prioritize first paint. | +| `PAGE_SIZE` | 200 | Request size for ordinary latest/reset, forward, and older-page fetches. | | `VISIBLE_WINDOW_SIZE` | 400 | Max regular rows kept in **tail** mode (following live bottom). | | `HISTORY_WINDOW_SIZE` | 600 | Max regular rows kept in **history** mode (user scrolled back). | | `OLDER_LOAD_WINDOW_SIZE` | 800 | Temporary cap while an older page is being merged (prepend). | @@ -126,7 +130,7 @@ Rules: - **Tail mode** trims from the top (oldest dropped). Dropping rows ⇒ set `hasMore: true` and recompute the older-page cursor from the oldest kept row. - **History mode** trims from the bottom (newest dropped). Dropping newest rows means your window no longer reaches the tail ⇒ flag "latest reset required": on returning to tail mode, discard cursors and fetch a fresh latest page rather than trusting stale ones. - **Queued rows are never trimmed** (user messages with `invokedAt === null`, see below) — they are re-merged after every trim. -- Persist the window (messages + cursors + epoch) per session for instant cold-start rendering; on re-activation with a persisted cursor, still fetch a fresh latest page first (another client may have advanced the session by many pages) and reconcile. +- Persist the window (messages + cursors + epoch) per session for instant cold-start rendering; a genuinely cold window requests a small latest page for first paint, while structural resets and re-activation with a persisted cursor use the ordinary full latest page and reconcile. Another client may have advanced the session by many pages. --- diff --git a/docs/api/client-contract/rest.md b/docs/api/client-contract/rest.md index 0cb91383..247e63be 100644 --- a/docs/api/client-contract/rest.md +++ b/docs/api/client-contract/rest.md @@ -167,6 +167,16 @@ after the form-level query without requiring a duplicate client RPC. Availability checks executables and static runner configuration only; it does not execute the Agent or verify account/login state. +Directory listing and spawning use the same workspace-root policy. With no +`metadata.workspaceRoots`, paths are unrestricted beyond the runner account's +filesystem permissions; `metadata.homeDir` is only a suggested starting location. +Explicit roots restrict both operations, after canonical symlink resolution. +Listings classify allowed directory symlinks as directories and omit links +whose targets escape the configured roots. Dot-prefixed entries require +`includeHidden: true`. Autocomplete clients can suggest known workspace roots +from metadata while a user types their prefix, without listing a root's +out-of-bounds parent. + ### Git & files (RPC-wrapped) Source: `hub/src/web/routes/git.ts`. Git endpoints return the **raw command output** — `GitCommandResponse` `{success, stdout?, stderr?, exitCode?, error?}` — and the client parses `stdout` itself (reference parsers: `web/src/lib/gitParsers.ts`). diff --git a/docs/guide/installation.md b/docs/guide/installation.md index 08562e21..b90e27d6 100644 --- a/docs/guide/installation.md +++ b/docs/guide/installation.md @@ -332,10 +332,10 @@ Use `--workspace-root ` to restrict which directories the runner can brows hapi runner start --workspace-root ~/projects --workspace-root ~/work ``` -Without `--workspace-root`, manually entered spawn paths remain unrestricted. -Session directory autocomplete and native pickers browse only beneath the -runner's home directory; configuring roots makes both browsing and spawning -use those roots instead. +Without `--workspace-root`, directory browsing and spawning both accept paths +anywhere the runner's OS account can access. The iOS directory picker starts +at the home directory and can navigate above it. Configuring roots restricts +both browsing and spawning to those roots, including symlink targets. For running the hub and runner as persistent background services (pm2, launchd, systemd), see [Deployment](./deployment.md). Supervised installs should set `HAPI_RUNNER_SUPERVISED=1` on the runner process (systemd `Environment=` / pm2 `--env`) so the web **Restart** control can safely stop-runner knowing the supervisor will cold-start it. diff --git a/docs/guide/native-apps.md b/docs/guide/native-apps.md index ee452ae1..0a7f2ae3 100644 --- a/docs/guide/native-apps.md +++ b/docs/guide/native-apps.md @@ -34,7 +34,10 @@ you install; see [Notifications](#notifications). - **Open a pairing link:** `hapicompanion://bind` opens the app's pairing flow. Confirm the hub before pairing. - **Enter manually:** supply the hub URL and access token printed by the - hub. Use the hub address, not the web frontend address `app.hapi.run`. + hub. On iOS, enter just the domain/IP and optional port; the separate + protocol menu defaults to HTTPS. You can also paste a full address, or + paste a pairing link into either field to fill both values before tapping + **Pair**. Use the hub address, not the web frontend address `app.hapi.run`. 3. The app checks reachability and protocol compatibility, then authenticates and stores credentials for that hub. A namespaced token such as `your-token:team` opens that namespace's sessions. @@ -46,11 +49,12 @@ The network relay, an HTTPS reverse proxy, or Tailscale Serve can provide an endpoint; see [Deployment](./deployment.md). Android rejects HTTP URLs in manual entry, QR codes, deep links and saved hub -state, including debug builds. iOS accepts HTTP input and prefixes a manually -entered address without a scheme with `http://`; connection success still -depends on system network policy. The iOS project declares no ATS exceptions, -so HTTP input acceptance does not guarantee a working connection. Prefer an -explicit HTTPS URL on both platforms. +state, including debug builds. iOS manual entry defaults to HTTPS and accepts +HTTP only when explicitly selected or supplied in a full URL/pairing link. It +warns about unencrypted HTTP and never automatically downgrades HTTPS. HTTP +connection success still depends on system network policy. The iOS project +declares no ATS exceptions, so HTTP input acceptance does not guarantee a +working connection. Prefer HTTPS on both platforms. Camera pairing is optional. Use manual entry on an iOS Simulator or any device without a usable scanner. @@ -78,7 +82,7 @@ directory browsing and session creation. | Composer | Text, photos/camera/files, drafts, queued-message actions and steering when supported by the session. | | Session controls | Both support pin/archive, stopping a turn and sending to resume an inactive session. Android also exposes Rename, Delete and explicit Reopen actions; iOS currently has no corresponding UI for those three actions. | | Files and Git | Open **Session files** from the chat menu to browse/search files, inspect Git status and read diffs. | -| Scratchlist | Open **Scratchlist** from the chat menu to park text and attachments for later use in a session. | +| Scratchlist | On iOS, tap the tray beside the composer attachment button to enter **Save draft** mode; Android uses the chat menu. Text and attachments sync within the session. | | Dictation | Record audio, transcribe through a configured hub provider, then edit the inserted text before sending. | | Usage and storage | Available only to the hub owner (`default` namespace). | | Display | English/Simplified Chinese, theme preferences, system text scaling and machine filtering on the session list. | @@ -88,6 +92,18 @@ the message or save the Scratchlist entry. Removing it requests cleanup of unused uploads on a best-effort basis. See the [Privacy Policy](../privacy.md) for storage and provider data flows. +On iOS, Scratchlist opens as a compact drawer above the same input field. +**Save draft** keeps the content without sending it; closing the drawer with +× leaves unsaved input intact. The drawer shows one recent draft, or just its +header while typing. **Take draft** keeps the saved entry and restores its +text and attachments. If the input is nonempty, choose **Append to input** or +**Save input, then take draft**. **Add to send queue** in the draft's menu is an +explicit send and removes the draft only after acceptance. A failed removal +can be retried without sending again. Tap the drawer header for the full list +and pull down to search text or filenames. The same menu offers edit, copy and +delete; editing an original draft commits text and attachments together on **Save**. +Cancelling an edit leaves the original unchanged. + Dictation uses the first configured provider that supports standard transcription. The microphone stays hidden until provider discovery succeeds; grant microphone permission when first using it. Configure providers on the hub 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/e2e/cold-initial-tail.spec.ts b/e2e/cold-initial-tail.spec.ts new file mode 100644 index 00000000..41ee115a --- /dev/null +++ b/e2e/cold-initial-tail.spec.ts @@ -0,0 +1,32 @@ +import { expect, test } from '@playwright/test' + +test('cold sessions request a small latest page and keep older loads at 200', async ({ page }) => { + await page.goto('/e2e-fixtures/history-load-fixture.html?coldInitial=1') + const viewport = page.locator('.app-scroll-y') + await expect(viewport).toBeVisible() + + await expect.poll(async () => await page.evaluate(() => window.__probe.requests.length)).toBeGreaterThan(0) + await expect.poll(async () => await page.evaluate(() => ({ + direction: window.__probe.requests[0]?.direction ?? null, + limit: window.__probe.requests[0]?.limit ?? null, + childCount: document.querySelector('.happy-thread-messages')?.childElementCount ?? 0 + }))).toEqual({ + direction: 'latest', + limit: 20, + childCount: expect.any(Number) + }) + + await expect.poll(async () => await page.evaluate(() => window.__probe.windowState().messageCount)).toBe(20) + await expect(page.getByText('Fixture message 1200', { exact: true })).toBeVisible() + + // Call the same loadMore callback that the top sentinel invokes. The + // dedicated history-load suite covers pointer/scroll gesture detection; + // this regression should isolate the page-size contract without relying + // on IntersectionObserver timing. + await page.evaluate(() => window.__probe.loadMore()) + + await expect.poll(async () => await page.evaluate(() => { + const older = window.__probe.requests.filter((request) => request.direction === 'before') + return older[0]?.limit ?? null + })).toBe(200) +}) diff --git a/e2e/markdown-math.spec.ts b/e2e/markdown-math.spec.ts new file mode 100644 index 00000000..daed7743 --- /dev/null +++ b/e2e/markdown-math.spec.ts @@ -0,0 +1,29 @@ +import { expect, test } from '@playwright/test' + +for (const viewport of [ + { width: 1440, height: 900 }, + { width: 390, height: 844 }, +]) { + test(`renders TeX bracket delimiters and preserves code blocks at ${viewport.width}px`, async ({ page }) => { + const pageErrors: string[] = [] + page.on('pageerror', (error) => pageErrors.push(error.message)) + await page.setViewportSize(viewport) + + await page.goto('/e2e-fixtures/markdown-math-fixture.html') + + const fixture = page.getByTestId('markdown-math-fixture') + await expect(fixture).toBeVisible() + await expect(fixture.locator('.katex-display')).toHaveCount(1) + await expect(fixture.locator('.katex')).toHaveCount(2) + + const codeBody = fixture.locator('[data-hapi-code-body="true"]') + await expect(codeBody).toBeVisible() + await expect(codeBody).toContainText('\\[x^2\\]') + await expect(codeBody.locator('.katex')).toHaveCount(0) + const pageFitsViewport = await page.evaluate(() => ( + document.documentElement.scrollWidth <= window.innerWidth + )) + expect(pageFitsViewport).toBe(true) + expect(pageErrors).toEqual([]) + }) +} diff --git a/e2e/share-turn.spec.ts b/e2e/share-turn.spec.ts index 25fc702d..44b42792 100644 --- a/e2e/share-turn.spec.ts +++ b/e2e/share-turn.spec.ts @@ -31,9 +31,11 @@ for (const viewport of [ await expect(page.getByText('Complex response fixture')).toBeVisible() await expect(page.getByText('Excluded tool output')).toBeVisible() await expect(page.getByText(/type ExportResult/)).toBeVisible() + await expect(page.getByTestId('source-turn').locator('.katex')).toHaveCount(4) await page.getByTestId('source-turn').screenshot({ path: testInfo.outputPath(`source-${viewport.name}.png`) }) await page.getByRole('button', { name: 'Open share preview' }).click() await expect(page.getByRole('dialog')).toBeVisible() + await expect(page.getByRole('dialog').locator('.katex')).toHaveCount(4) await expect(page.getByRole('dialog').getByText('Excluded tool output')).toHaveCount(0) await expect(page.getByRole('dialog').locator('.happy-message-actions')).toHaveCount(0) await expect(page.getByRole('dialog').locator('.hapi-share-hidden-content-spacer')).toHaveCount(1) diff --git a/ios/Hapi.xcodeproj/project.pbxproj b/ios/Hapi.xcodeproj/project.pbxproj index 04cd1b68..489c1dd2 100644 --- a/ios/Hapi.xcodeproj/project.pbxproj +++ b/ios/Hapi.xcodeproj/project.pbxproj @@ -397,7 +397,7 @@ GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = Hapi/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = HAPI; - INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = NO; INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; INFOPLIST_KEY_UILaunchScreen_Generation = YES; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; @@ -407,7 +407,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 0.28.0; + MARKETING_VERSION = 0.30.7; PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = NO; @@ -428,7 +428,7 @@ GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = Hapi/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = HAPI; - INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = NO; INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; INFOPLIST_KEY_UILaunchScreen_Generation = YES; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; @@ -438,7 +438,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 0.28.0; + MARKETING_VERSION = 0.30.7; PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = NO; @@ -462,7 +462,7 @@ "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MARKETING_VERSION = 0.28.0; + MARKETING_VERSION = 0.30.7; PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app.HapiNotificationService; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; @@ -487,7 +487,7 @@ "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MARKETING_VERSION = 0.28.0; + MARKETING_VERSION = 0.30.7; PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app.HapiNotificationService; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; diff --git a/ios/Hapi/Features/Chat/Blocks/ChatActionButtonStyle.swift b/ios/Hapi/Features/Chat/Blocks/ChatActionButtonStyle.swift new file mode 100644 index 00000000..1f135531 --- /dev/null +++ b/ios/Hapi/Features/Chat/Blocks/ChatActionButtonStyle.swift @@ -0,0 +1,40 @@ +import HapiUI +import SwiftUI + +/// Inline chat actions own their outer size instead of adding system bordered- +/// button padding to an already-sized label. This is presentation only: plans, +/// approvals and answers keep their separate interaction paths. +struct ChatActionButtonStyle: ButtonStyle { + enum Emphasis { + case primary + case secondary + case destructive + } + + let emphasis: Emphasis + var fillsWidth = true + @Environment(\.hapiTheme) private var theme + @Environment(\.isEnabled) private var isEnabled + + private var foreground: Color { + switch emphasis { + case .primary: theme.background + case .secondary: theme.textPrimary + case .destructive: theme.danger + } + } + + func makeBody(configuration: Configuration) -> some View { + let shape = RoundedRectangle(cornerRadius: 10, style: .continuous) + configuration.label + .multilineTextAlignment(.center) + .padding(.horizontal, 12) + .padding(.vertical, 10) + .frame(minWidth: 44, maxWidth: fillsWidth ? .infinity : nil, minHeight: 44) + .foregroundStyle(foreground) + .background(emphasis == .primary ? theme.link : Color.clear, in: shape) + .overlay(shape.strokeBorder(emphasis == .primary ? Color.clear : theme.divider, lineWidth: 1)) + .contentShape(shape) + .opacity(isEnabled ? (configuration.isPressed ? 0.8 : 1) : 0.5) + } +} diff --git a/ios/Hapi/Features/Chat/Blocks/CodexPlanActionsView.swift b/ios/Hapi/Features/Chat/Blocks/CodexPlanActionsView.swift new file mode 100644 index 00000000..07c9fc00 --- /dev/null +++ b/ios/Hapi/Features/Chat/Blocks/CodexPlanActionsView.swift @@ -0,0 +1,66 @@ +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(\.hapiTheme) private var theme + @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(theme.danger) + .accessibilityIdentifier("plan-error-\(planId)") + } + if state.available || state.pending { + // Prefer one compact row, but never squeeze or truncate + // the labels to fit a narrow column or larger text size. + ViewThatFits(in: .horizontal) { + HStack(spacing: 8) { + buttons(state: state, horizontal: true) + } + VStack(spacing: 8) { + buttons(state: state, horizontal: false) + } + } + .font(typography.toolTitleFont) + .disabled(!state.canAct) + } + } + .padding(12) + } + } + + @ViewBuilder + private func buttons(state: CodexPlanActionState, horizontal: Bool) -> some View { + Button { interactions.implementCodexPlan(planId: planId) } label: { + HStack(spacing: 8) { + if state.pending { + ProgressView() + .controlSize(.small) + .tint(theme.background) + .accessibilityHidden(true) + } + Text("Implement plan") + } + .fixedSize(horizontal: horizontal, vertical: true) + } + .buttonStyle(ChatActionButtonStyle(emphasis: .primary)) + .accessibilityIdentifier("plan-implement-\(planId)") + + Button { interactions.continueCodexPlan(planId: planId) } label: { + Text("Continue planning") + .fixedSize(horizontal: horizontal, vertical: true) + } + .buttonStyle(ChatActionButtonStyle(emphasis: .secondary)) + .accessibilityIdentifier("plan-continue-\(planId)") + } +} diff --git a/ios/Hapi/Features/Chat/Blocks/PermissionActionViews.swift b/ios/Hapi/Features/Chat/Blocks/PermissionActionViews.swift index 575c3c27..14e59840 100644 --- a/ios/Hapi/Features/Chat/Blocks/PermissionActionViews.swift +++ b/ios/Hapi/Features/Chat/Blocks/PermissionActionViews.swift @@ -23,88 +23,194 @@ struct PendingPermissionFooter: View { ) } } else { - PermissionActionsRow(tool: tool, requestId: requestId, interactions: interactions) + PermissionApprovalView(tool: tool, requestId: requestId, interactions: interactions) } } } -/// Ordinary approvals retain their existing permission-specific controls. -struct PermissionActionsRow: View { +/// One approval surface in both the conversation and the process page. The +/// latter omits the input link because its full input is already on screen. +struct PermissionApprovalView: View { let tool: ChatToolCall let requestId: String let interactions: ChatInteractor - @Environment(\.dynamicTypeSize) private var dynamicTypeSize + var openInput: (() -> Void)? + @Environment(\.hapiTheme) private var theme + @Environment(\.hapiTypography) private var typography var body: some View { let override = interactions.permissionOverrides[requestId] - if override == .alreadyHandled { - AlreadyHandledLine() - } else { - let resolving = override == .resolving - let codex = isCodexPermissionUX(flavor: interactions.flavor, toolName: tool.name) - let canAllowForSession = !codex && !PermissionGates.hideAllowForSession.contains(tool.name) - let canAllowAllEdits = interactions.flavor == "claude" - && PermissionGates.editTools.contains(tool.name) - - let layout = dynamicTypeSize.isAccessibilitySize - ? AnyLayout(VStackLayout(alignment: .leading, spacing: 8)) - : AnyLayout(HStackLayout(spacing: 8)) - layout { - Button { - interactions.resolvePermission(requestId: requestId, action: .allow) - } label: { - Text("Allow") - .fixedSize(horizontal: false, vertical: true) - .frame(maxWidth: .infinity, minHeight: 44) - } - .buttonStyle(.bordered) - .tint(.green) - - Button { - interactions.resolvePermission(requestId: requestId, action: codex ? .abort : .deny) - } label: { - Text(codex ? String(localized: "Abort") : String(localized: "Deny")) - .fixedSize(horizontal: false, vertical: true) - .frame(maxWidth: .infinity, minHeight: 44) - } - .buttonStyle(.bordered) - .tint(.red) - - if resolving { - ProgressView() - .controlSize(.small) - } else if codex || canAllowForSession || canAllowAllEdits { - Menu { - if codex || canAllowForSession { - Button("Allow for this session") { - interactions.resolvePermission(requestId: requestId, action: .allowForSession) - } - } - if canAllowAllEdits { - Button("Allow all edits") { - interactions.resolvePermission(requestId: requestId, action: .allowAllEdits) - } - } - } label: { - Image(systemName: "ellipsis") - .frame(minWidth: 44, minHeight: 44) - .contentShape(Rectangle()) - } + VStack(alignment: .leading, spacing: 8) { + header(override: override) + .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading) + if override != .alreadyHandled { + PermissionActionsRow( + options: PermissionActionOptions(flavor: interactions.flavor, toolName: tool.name), + requestId: requestId, + resolving: override == .resolving + ) { action in + interactions.resolvePermission(requestId: requestId, action: action) } } - .disabled(resolving) - .padding(.horizontal, 10) - .padding(.vertical, 6) } + .padding(12) + .frame(maxWidth: .infinity, alignment: .leading) + .background(theme.surface, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + } + + private func header(override: PermissionRowOverride?) -> some View { + ViewThatFits(in: .horizontal) { + HStack(spacing: 8) { + status(override).fixedSize(horizontal: true, vertical: true) + Spacer(minLength: 0) + inputLink.fixedSize(horizontal: true, vertical: true) + } + VStack(alignment: .leading, spacing: 4) { + status(override) + inputLink + } + } + } + + private func status(_ override: PermissionRowOverride?) -> some View { + PermissionPendingStatus(override: override) + .accessibilityIdentifier("permission-status-\(requestId)") + } + + @ViewBuilder + private var inputLink: some View { + if let openInput { + Button(action: openInput) { + Label("View full input", systemImage: "arrow.up.right.square") + .font(typography.captionFont) + .fixedSize(horizontal: false, vertical: true) + .frame(minHeight: 44, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .foregroundStyle(theme.link) + .accessibilityIdentifier("permission-input-\(requestId)") + } + } +} + +/// UI projection of the existing flavor/tool gates, not a new permission policy. +struct PermissionActionOptions: Equatable { + let denyAction: PermissionAction + let canAllowForSession: Bool + let canAllowAllEdits: Bool + + var hasMore: Bool { canAllowForSession || canAllowAllEdits } + + init(flavor: String?, toolName: String) { + let codex = isCodexPermissionUX(flavor: flavor, toolName: toolName) + denyAction = codex ? .abort : .deny + canAllowForSession = codex || !PermissionGates.hideAllowForSession.contains(toolName) + canAllowAllEdits = flavor == "claude" && PermissionGates.editTools.contains(toolName) + } +} + +struct PermissionActionsRow: View { + let options: PermissionActionOptions + let requestId: String + let resolving: Bool + let submit: (PermissionAction) -> Void + @Environment(\.hapiTypography) private var typography + + var body: some View { + Group { + if typography.usesStackedToolLayout { + VStack(spacing: 8) { buttons(horizontal: false) } + } else { + ViewThatFits(in: .horizontal) { + HStack(spacing: 8) { buttons(horizontal: true) } + VStack(spacing: 8) { buttons(horizontal: false) } + } + } + } + .font(typography.toolTitleFont) + .disabled(resolving) + } + + @ViewBuilder + private func buttons(horizontal: Bool) -> some View { + Button { submit(.allow) } label: { + Text("Allow").fixedSize(horizontal: horizontal, vertical: true) + } + .buttonStyle(ChatActionButtonStyle(emphasis: .primary)) + .accessibilityIdentifier("permission-allow-\(requestId)") + + Button { submit(options.denyAction) } label: { + Text(options.denyAction == .abort ? LocalizedStringKey("Abort") : LocalizedStringKey("Deny")) + .fixedSize(horizontal: horizontal, vertical: true) + } + .buttonStyle(ChatActionButtonStyle(emphasis: .destructive)) + .accessibilityIdentifier("permission-deny-\(requestId)") + + if options.hasMore { + Menu { + if options.canAllowForSession { + Button("Allow for this session") { submit(.allowForSession) } + } + if options.canAllowAllEdits { + Button("Allow all edits") { submit(.allowAllEdits) } + } + } label: { + if horizontal { + Image(systemName: "ellipsis").frame(width: 20) + } else { + Label("More approval options", systemImage: "ellipsis") + .fixedSize(horizontal: false, vertical: true) + } + } + .buttonStyle(ChatActionButtonStyle(emphasis: .secondary, fillsWidth: !horizontal)) + .accessibilityLabel("More approval options") + .accessibilityIdentifier("permission-more-\(requestId)") + } + } +} + +/// Progress occupies the status icon's slot, never replaces the more menu or +/// changes the action widths. An already-handled request is no longer waiting. +struct PermissionPendingStatus: View { + var override: PermissionRowOverride? + @Environment(\.hapiTheme) private var theme + @Environment(\.hapiTypography) private var typography + + private var title: LocalizedStringKey { + switch override { + case .resolving: "Submitting approval…" + case .alreadyHandled: "Already handled elsewhere" + case nil: "Awaiting approval" + } + } + + var body: some View { + Label { + // The warning token is an accent, not a small-text color on the + // light surface. Keep the caption readable in every palette. + Text(title) + .foregroundStyle(theme.textSecondary) + .fixedSize(horizontal: false, vertical: true) + } icon: { + Group { + if override == .resolving { + ProgressView().controlSize(.small).tint(theme.textSecondary) + } else { + Image(systemName: override == .alreadyHandled ? "checkmark.circle" : "hourglass") + } + } + .frame(width: typography.captionSize, height: typography.captionSize) + .foregroundStyle(override == nil ? theme.warning : theme.textSecondary) + .accessibilityHidden(true) + } + .font(typography.captionFont) } } private struct AlreadyHandledLine: View { var body: some View { - Text("Already handled elsewhere") - .font(.caption) - .foregroundStyle(.secondary) - .padding(.horizontal, 10) - .padding(.vertical, 6) + PermissionPendingStatus(override: .alreadyHandled) + .padding(12) } } 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..dfb26934 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) @@ -284,17 +288,17 @@ struct QuestionAnswerFormView: View { } } label: { HStack(spacing: 8) { - if submitting { ProgressView().tint(.white).controlSize(.small) } + if submitting { + ProgressView().tint(theme.background).controlSize(.small) + .accessibilityHidden(true) + } Text(submitting ? String(localized: "Submitting answer…") : last ? String(localized: "Submit answer") : String(localized: "Next question")) .fixedSize(horizontal: false, vertical: true) } .font(typography.toolTitleFont) - .frame(maxWidth: fullWidth ? .infinity : nil, minHeight: 32) - .padding(.horizontal, 8) } - .buttonStyle(.borderedProminent) - .tint(theme.accent) + .buttonStyle(ChatActionButtonStyle(emphasis: .primary, fillsWidth: fullWidth)) .disabled(!enabled || submitting || (last ? draft.submission(in: form) == nil : !draft.isAnswered(at: index, in: form))) .accessibilityIdentifier(last ? "question-submit" : "question-next") } @@ -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/Features/Chat/Blocks/ToolCallBlockView.swift b/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift index 0ad8d401..ce5ea01d 100644 --- a/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift +++ b/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift @@ -31,10 +31,16 @@ 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 { - pendingApprovalSection(permission: permission, interactions: interactions) + PermissionApprovalView( + tool: block.tool, requestId: permission.id, interactions: interactions, + openInput: { openTool?(block) } + ) } else { PermissionStateRow(permission: permission) } @@ -59,36 +65,11 @@ struct ToolCallBlockView: View { .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) } - /// Pending permission with a live interaction engine: highlighted banner - /// plus the actionable footer (approve buttons / answer forms). - private func pendingApprovalSection( - permission: ToolPermission, - interactions: ChatInteractor - ) -> some View { - VStack(alignment: .leading, spacing: 0) { - Label("Awaiting approval", systemImage: "hourglass") - .font(.footnote.weight(.semibold)) - .foregroundStyle(.orange) - .padding(.horizontal, 10) - .padding(.top, 6) - Button { openTool?(block) } label: { - Label("View full input", systemImage: "arrow.up.right.square") - .font(typography.toolSubtitleFont) - .frame(minHeight: 44) - } - .padding(.horizontal, 10) - PermissionActionsRow( - tool: block.tool, - requestId: permission.id, - interactions: interactions - ) - } - .frame(maxWidth: .infinity, alignment: .leading) - .background(.orange.opacity(0.10)) - } - private func headerRow(_ presentation: ToolCardPresentation) -> some View { - ToolSummaryRow(presentation: presentation, state: block.tool.state) { openTool?(block) } + ToolSummaryRow( + presentation: presentation, state: block.tool.state, + showsStatus: block.tool.state != .pending || block.tool.permission?.status != .pending + ) { openTool?(block) } .accessibilityHint(opensToolProcess(block) ? String(localized: "View agent process") : String(localized: "View tool details")) .accessibilityIdentifier("tool-summary-\(block.id)") @@ -100,13 +81,17 @@ struct ToolCallBlockView: View { struct ToolSummaryRow: View { let presentation: ToolCardPresentation let state: ToolCallState + var showsStatus = true let action: () -> Void @Environment(\.hapiTheme) private var theme @Environment(\.hapiTypography) private var typography var body: some View { Button(action: action) { - let layout = typography.usesStackedToolLayout + // An approval owns its status below this summary. Without a + // status chip, keep the chevron beside the title, not on an orphan row. + let stacksStatus = typography.usesStackedToolLayout && showsStatus + let layout = stacksStatus ? AnyLayout(VStackLayout(alignment: .leading, spacing: 8)) : AnyLayout(HStackLayout(spacing: 8)) layout { @@ -133,9 +118,9 @@ struct ToolSummaryRow: View { } } } - if !typography.usesStackedToolLayout { Spacer(minLength: 8) } + if !stacksStatus { Spacer(minLength: 8) } HStack(spacing: 8) { - if state != .completed { + if showsStatus && state != .completed { ToolStatusIndicator(state: state) } Image(systemName: "chevron.right") @@ -193,46 +178,46 @@ private struct StatusChip: View { // MARK: - Permission (read-only) -/// Read-only permission verdict: highlighted banner while pending (shown only -/// without a `\.chatInteractions` engine — previews/tests; the live chat -/// renders `PendingPermissionFooter` instead), subdued line once decided. +/// Read-only verdict in the inspector or a non-interactive transcript. Live +/// approvals share the same quiet status treatment in PermissionApprovalView. struct PermissionStateRow: View { let permission: ToolPermission + var horizontalInset: CGFloat = 12 var body: some View { - switch permission.status { - case .pending: - Label("Awaiting approval", systemImage: "hourglass") - .font(.footnote.weight(.semibold)) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.horizontal, 10) - .padding(.vertical, 6) - .background(.orange.opacity(0.18)) - .foregroundStyle(.orange) - case .approved: - PermissionLine(text: String(localized: "✓ Approved") + (permission.mode.map { " · \($0)" } ?? "")) - case .denied: - PermissionLine( - text: String(localized: "✕ Denied") + (permission.reason.map { " · \($0)" } ?? ""), - isError: true - ) - case .resolved: - PermissionLine(text: String(localized: "Resolved in Codex")) - case .canceled: - PermissionLine(text: String(localized: "— Canceled")) + Group { + switch permission.status { + case .pending: + PermissionPendingStatus() + case .approved: + PermissionLine(text: String(localized: "✓ Approved") + (permission.mode.map { " · \($0)" } ?? "")) + case .denied: + PermissionLine( + text: String(localized: "✕ Denied") + (permission.reason.map { " · \($0)" } ?? ""), + isError: true + ) + case .resolved: + PermissionLine(text: String(localized: "Resolved in Codex")) + case .canceled: + PermissionLine(text: String(localized: "— Canceled")) + } } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, horizontalInset) + .padding(.vertical, 6) } } private struct PermissionLine: View { let text: String var isError = false + @Environment(\.hapiTheme) private var theme + @Environment(\.hapiTypography) private var typography var body: some View { Text(text) - .font(.footnote) - .foregroundStyle(isError ? AnyShapeStyle(.red) : AnyShapeStyle(.secondary)) - .padding(.horizontal, 10) - .padding(.bottom, 6) + .font(typography.captionFont) + .foregroundStyle(isError ? theme.danger : theme.textSecondary) + .fixedSize(horizontal: false, vertical: true) } } diff --git a/ios/Hapi/Features/Chat/ChatModel.swift b/ios/Hapi/Features/Chat/ChatModel.swift index 03682a02..265a6533 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() @@ -160,9 +158,12 @@ final class ChatModel { func releaseSurface(_ id: String) { visibleSurfaces.remove(id) - Task { [weak self] in + // Keep the model alive through the deferred teardown. A replaced + // split detail may otherwise deallocate before this task runs, leaving + // its SSE client running and the hub's open-chat marker stale. + Task { [self] in await Task.yield() - guard let self, self.visibleSurfaces.isEmpty else { return } + guard visibleSurfaces.isEmpty else { return } self.stop() } } @@ -172,9 +173,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) } @@ -202,7 +202,9 @@ final class ChatModel { case .sessionSuperseded(let sessionId): self.supersededSessionId = sessionId case .notice(let message): - self.showNotice(message) + // Scratchlist failures already have an inline banner with a + // retry action. A second toast obscures the same input area. + if message != self.interactor.scratchlistError { self.showNotice(message) } } } interactor.activate() @@ -289,7 +291,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 +420,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/Hapi/Features/Chat/ChatView.swift b/ios/Hapi/Features/Chat/ChatView.swift index e5d6e7dc..4a877e1e 100644 --- a/ios/Hapi/Features/Chat/ChatView.swift +++ b/ios/Hapi/Features/Chat/ChatView.swift @@ -3,7 +3,7 @@ import HapiProtocol import HapiUI import SwiftUI -/// The chat screen: `ScrollView + LazyVStack` over the reduced +/// The chat screen: an anchored UIKit transcript over the reduced /// `VisibleChatBlock`s, newest at the bottom (M2f), plus the A-M3ab /// interaction chrome — composer + queued bar (bottom inset), permission /// action footers (via `\.chatInteractions`), the session config sheet @@ -12,14 +12,16 @@ import SwiftUI /// Transcript layout and scroll intent live in `ChatTranscriptView`. struct ChatView: View { @State private var model: ChatModel - /// Session config sheet (toolbar gear). - @State private var configSheetOpen = false + /// Adaptive session settings (toolbar gear). + @State private var configOpen = false /// Files browser push (toolbar folder, A-M4a). @State private var filesOpen = false /// File viewer push for `hapi-file://` chat citations (A-M4a). @State private var viewerRoute: FileViewerRoute? - /// Scratchlist sheet (toolbar note icon, A-M4b). + /// Full inventory; the compact drawer lives with the composer below. @State private var scratchlistOpen = false + @State private var scratchlistEntry: ScratchlistEntry? + @State private var scratchlistStartsEditing = false /// Resume/reopen handed back a superseding session id — the host swaps /// its navigation entry (HomeView replaces the path element). @@ -34,9 +36,14 @@ struct ChatView: View { sessionId: String, onNavigateToSession: ((String) -> Void)? = nil ) { - _model = State(initialValue: ChatModel(session: session, sessionId: sessionId)) + self.init(session: session, model: ChatModel(session: session, sessionId: sessionId), + onNavigateToSession: onNavigateToSession) + } + + init(session: HubSession, model: ChatModel, onNavigateToSession: ((String) -> Void)? = nil) { + _model = State(initialValue: model) self.session = session - self.sessionId = sessionId + self.sessionId = model.sessionId self.onNavigateToSession = onNavigateToSession } @@ -69,7 +76,11 @@ struct ChatView: View { VStack(spacing: 0) { QueuedMessagesBarView(interactor: model.interactor) .hapiReadingColumn() - ChatComposerView(interactor: model.interactor, dictation: model.dictation) + ChatComposerView(interactor: model.interactor, dictation: model.dictation) { entry, editing in + scratchlistEntry = entry + scratchlistStartsEditing = editing + scratchlistOpen = true + } } } .toolbar { @@ -80,12 +91,9 @@ struct ChatView: View { // squeezed the title out): gear for the frequent config // switches, everything else behind one menu. ToolbarItem(placement: .topBarTrailing) { - Button { - configSheetOpen = true - } label: { - Image(systemName: "gearshape") + SessionConfigButton(isPresented: $configOpen) { + SessionConfigView(interactor: model.interactor, notice: model.notice) } - .accessibilityLabel("Session settings") } ToolbarItem(placement: .topBarTrailing) { Menu { @@ -95,7 +103,7 @@ struct ChatView: View { Label("Session files", systemImage: "folder") } Button { - scratchlistOpen = true + model.interactor.setComposerDestination(.scratchlist) } label: { let count = model.interactor.scratchlistCount if count > 0 { @@ -114,9 +122,6 @@ struct ChatView: View { } } .navigationBarTitleDisplayMode(.inline) - .sheet(isPresented: $configSheetOpen) { - SessionConfigView(interactor: model.interactor) - } .navigationDestination(isPresented: $filesOpen) { FilesView(session: session, sessionId: sessionId) } @@ -142,7 +147,9 @@ struct ChatView: View { store: model.scratchlist, sessionId: model.sessionId, attachments: model.scratchlistAttachments, - interactor: model.interactor + interactor: model.interactor, + initialEntry: scratchlistEntry, + initiallyEditing: scratchlistStartsEditing ) } .toolPresentations(model: model, session: session, owner: "chat") { path in diff --git a/ios/Hapi/Features/Chat/Composer/ChatComposerView.swift b/ios/Hapi/Features/Chat/Composer/ChatComposerView.swift index a90af76c..73b5e47b 100644 --- a/ios/Hapi/Features/Chat/Composer/ChatComposerView.swift +++ b/ios/Hapi/Features/Chat/Composer/ChatComposerView.swift @@ -1,5 +1,6 @@ import AVFAudio import HapiClient +import HapiProtocol import HapiUI import PhotosUI import SwiftUI @@ -16,6 +17,7 @@ struct ChatComposerView: View { let interactor: ChatInteractor /// nil ⇒ dictation unavailable (no controller wired) — mic button hidden. var dictation: DictationController? + var onOpenScratchlist: (ScratchlistEntry?, Bool) -> Void = { _, _ in } // Attachment pickers (the launchers live here; policy + upload live in // HapiKit — `AttachmentPreparer` / `ComposerAttachments`). @@ -24,6 +26,13 @@ struct ChatComposerView: View { @State private var photoSelection: [PhotosPickerItem] = [] @State private var cameraOpen = false @State private var filePickerOpen = false + @FocusState private var textFocused: Bool + @State private var preparingAttachment = false + + private var scratchlistMode: Bool { interactor.composerDestination == .scratchlist } + private var composerPrompt: LocalizedStringKey { + scratchlistMode ? "Keep an instruction for later…" : "Message the agent…" + } private var text: Binding { Binding( @@ -48,6 +57,16 @@ struct ChatComposerView: View { let attachments = interactor.attachments.items VStack(spacing: 0) { VStack(spacing: 0) { + if scratchlistMode, let store = interactor.scratchlist { + ScratchlistDrawerView(store: store, sessionId: interactor.sessionId, interactor: interactor, + keyboardFocused: textFocused, onOpen: onOpenScratchlist) + } + if let error = interactor.scratchlistError { + ScratchlistErrorBanner(message: error, + actionTitle: interactor.scratchlistErrorDestination == nil ? "Dismiss" : "Retry", + retry: interactor.retryScratchlistComposerOperation) + .padding(.horizontal, 12) + } if !attachments.isEmpty { attachmentsRow(attachments) .padding(.horizontal, 12) @@ -60,7 +79,8 @@ struct ChatComposerView: View { .padding(.horizontal, 12) .padding(.top, 8) } - TextField("Message the agent…", text: text, axis: .vertical) + TextField(composerPrompt, text: text, prompt: Text(composerPrompt).foregroundColor(.secondary), axis: .vertical) + .focused($textFocused) .font(typography.bodyFont) .lineLimit(1...6) .textFieldStyle(.plain) @@ -69,11 +89,18 @@ struct ChatComposerView: View { .padding(.bottom, 4) HStack(spacing: 2) { addAttachmentButton + if interactor.scratchlist != nil { scratchlistButton } Spacer() + if scratchlistMode, composer.canSteer { + Button { interactor.abortSession() } label: { + Image(systemName: "stop.fill").foregroundStyle(.red).frame(width: 44, height: 44) + }.accessibilityLabel("Stop the current turn") + } if let dictation, dictation.isAvailable { micButton(dictation) } - primaryActionButton(composer, attachments: attachments) + if scratchlistMode { parkButton } + else { primaryActionButton(composer, attachments: attachments) } } // 44 pt touch slot with a centered 38 pt circle: // 9 + 3 = the shared 12 pt visual inset. @@ -89,22 +116,12 @@ struct ChatComposerView: View { } .hapiReadingColumn() .padding(.vertical, 8) + .onChange(of: interactor.composerFocusRequest) { + textFocused = true + } .task(id: dictation.map { ObjectIdentifier($0) }) { await dictation?.refreshAvailability() } - .confirmationDialog("Attach", isPresented: $attachDialogOpen, titleVisibility: .visible) { - Button("Photo library") { - photosPickerOpen = true - } - if CameraCaptureView.isAvailable { - Button("Camera") { - cameraOpen = true - } - } - Button("Files") { - filePickerOpen = true - } - } .photosPicker( isPresented: $photosPickerOpen, selection: $photoSelection, @@ -159,7 +176,7 @@ struct ChatComposerView: View { } let result = await AttachmentPreparer.prepare(fileURL: movie.url) try? FileManager.default.removeItem(at: movie.url) - handle(result) + await handle(result) return } let naming = AttachmentPreparer.photoFilename(for: type) @@ -174,10 +191,25 @@ struct ChatComposerView: View { )) } - private func handle(_ result: PrepareResult) { + private func handle(_ result: PrepareResult) async { switch result { case .ready(let prepared): - interactor.attachments.add(prepared) + if scratchlistMode, let store = interactor.scratchlist { + preparingAttachment = true + defer { preparingAttachment = false } + let limits = await store.limits(sessionId: interactor.sessionId) + let existing = interactor.attachments.scratchlistBudget + let outcome = await Task.detached(priority: .userInitiated) { + ScratchlistAttachmentImport.prepare(data: prepared.bytes, filename: prepared.filename, + mimeType: prepared.mimeType, existing: existing, limits: limits) + }.value + switch outcome { + case .ready(let attachment): + interactor.attachments.add(PreparedAttachment(filename: attachment.filename, mimeType: attachment.mimeType, + bytes: attachment.data, previewBytes: prepared.previewBytes), toScratchlist: true) + case .rejected(let message): interactor.reportScratchlistError(message) + } + } else { interactor.attachments.add(prepared) } case .tooLarge(let filename, _): interactor.postNotice(String(format: String(localized: "%@ is over the 50 MB upload limit"), filename)) case .unreadable(let filename): @@ -196,6 +228,7 @@ struct ChatComposerView: View { onRetry: { interactor.attachments.retry(attachment.id) }, onRemove: { interactor.attachments.remove(attachment.id) } ) + .disabled(interactor.scratchlistBusy || interactor.isSending) } } } @@ -214,7 +247,63 @@ struct ChatComposerView: View { } } .buttonStyle(.plain) + .disabled(preparingAttachment || interactor.scratchlistBusy) .accessibilityLabel("Add attachment") + .accessibilityIdentifier("chat.add-attachment") + .confirmationDialog("Attach", isPresented: $attachDialogOpen, titleVisibility: .visible) { + Button("Photo library") { + photosPickerOpen = true + } + if CameraCaptureView.isAvailable { + Button("Camera") { + cameraOpen = true + } + } + Button("Files") { + filePickerOpen = true + } + } + } + + private var scratchlistButton: some View { + Button { + interactor.setComposerDestination(scratchlistMode ? .chat : .scratchlist) + } label: { + HStack(spacing: 3) { + Image(systemName: "tray") + if interactor.scratchlistCount > 0 { + Text(verbatim: interactor.scratchlistCount > 99 ? "99+" : "\(interactor.scratchlistCount)") + .font(.caption.weight(.medium)).monospacedDigit() + } + } + .foregroundStyle(scratchlistMode ? AnyShapeStyle(.orange) : AnyShapeStyle(.secondary)) + .padding(.horizontal, 6) + .frame(minWidth: 44, minHeight: 44) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(interactor.scratchlistBusy || interactor.isSending || preparingAttachment) + .accessibilityLabel(String(format: String(localized: "Scratchlist (%lld)"), Int64(interactor.scratchlistCount))) + .accessibilityValue(scratchlistMode ? String(localized: "Held — not sent") : String(localized: "Chat")) + .accessibilityIdentifier("scratchlist.toggle") + } + + private var parkButton: some View { + Button { interactor.parkComposerDraft() } label: { + HStack(spacing: 5) { + if interactor.scratchlistBusy { ProgressView().controlSize(.small) } + else { Image(systemName: "tray.and.arrow.down") } + Text("Save draft").font(.subheadline.weight(.semibold)) + } + .padding(.horizontal, 12) + .frame(minHeight: 38) + .background(.orange.opacity(0.16), in: Capsule()) + .frame(minHeight: 44) + } + .buttonStyle(.plain) + .disabled(!interactor.hasComposerDraft || interactor.scratchlistBusy || interactor.isSending + || interactor.attachments.hasUnsettled || preparingAttachment) + .accessibilityIdentifier("scratchlist.park") } // MARK: - Dictation diff --git a/ios/Hapi/Features/Chat/Composer/QueuedMessagesBarView.swift b/ios/Hapi/Features/Chat/Composer/QueuedMessagesBarView.swift index 5c8dc630..fd3ea862 100644 --- a/ios/Hapi/Features/Chat/Composer/QueuedMessagesBarView.swift +++ b/ios/Hapi/Features/Chat/Composer/QueuedMessagesBarView.swift @@ -1,4 +1,5 @@ import HapiClient +import HapiUI import SwiftUI /// Floating bar above the composer for queued (uninvoked) sends — the @@ -8,6 +9,8 @@ import SwiftUI /// actions disabled until the SSE echo lands. struct QueuedMessagesBarView: View { let interactor: ChatInteractor + @Environment(\.hapiTheme) private var theme + @Environment(\.hapiTypography) private var typography var body: some View { let rows = interactor.queuedRows @@ -16,8 +19,8 @@ struct QueuedMessagesBarView: View { Text(rows.count == 1 ? String(localized: "1 queued message") : String(format: String(localized: "%lld queued messages"), Int64(rows.count))) - .font(.caption2) - .foregroundStyle(.secondary) + .font(typography.captionFont) + .foregroundStyle(theme.textSecondary) .padding(.horizontal, 10) ScrollView { VStack(spacing: 4) { @@ -36,56 +39,89 @@ struct QueuedMessagesBarView: View { } } -private struct QueuedRowView: View { +struct QueuedRowView: View { let row: QueuedMessageRow let interactor: ChatInteractor + @Environment(\.hapiTheme) private var theme + @Environment(\.hapiTypography) private var typography var body: some View { - HStack(alignment: .center, spacing: 4) { - VStack(alignment: .leading, spacing: 1) { - Text(row.text.isEmpty ? row.attachmentNames.joined(separator: ", ") : row.text) - .font(.footnote) - .lineLimit(2) - if row.indeterminate { - Text("Delivery outcome unknown") - .font(.caption2) - .foregroundStyle(.red) - } - if let scheduledAt = row.scheduledAt { - Text("Scheduled · \(Self.timeLabel(scheduledAt))") - .font(.caption2) - .foregroundStyle(.secondary) + ViewThatFits(in: .horizontal) { + HStack(spacing: 8) { + preview.frame(minWidth: 120, alignment: .leading) + Spacer(minLength: 0) + HStack(spacing: 4) { actions(horizontal: true) } + .fixedSize(horizontal: true, vertical: true) + } + VStack(alignment: .leading, spacing: 4) { + preview.frame(maxWidth: .infinity, alignment: .leading) + ViewThatFits(in: .horizontal) { + HStack(spacing: 4) { actions(horizontal: true) } + VStack(spacing: 4) { actions(horizontal: false) } } } - Spacer(minLength: 8) - if row.indeterminate { - Button("Retry") { - interactor.retryIndeterminateMessage(row.id) - } - .font(.footnote.weight(.medium)) - .disabled(!row.canAct) - } else if row.canSteer { - Button("Steer") { - interactor.steerQueuedMessage(row.id) - } - .font(.footnote.weight(.medium)) - } - Button("Edit") { - interactor.editQueuedMessage(row.id) - } - .font(.footnote.weight(.medium)) - .disabled(!row.canAct) - Button("Cancel") { - interactor.cancelQueuedMessage(row.id) - } - .font(.footnote.weight(.medium)) - .tint(.red) - .disabled(!row.canAct) } - .buttonStyle(.borderless) .padding(.horizontal, 10) .padding(.vertical, 6) - .background(.fill.tertiary, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + .background(theme.surface, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + } + + private var preview: some View { + VStack(alignment: .leading, spacing: 1) { + Text(row.text.isEmpty ? row.attachmentNames.joined(separator: ", ") : row.text) + .font(typography.toolSubtitleFont) + .foregroundStyle(theme.textPrimary) + .lineLimit(2) + if row.indeterminate { + Text("Delivery outcome unknown") + .font(typography.captionFont) + .foregroundStyle(theme.danger) + } + if let scheduledAt = row.scheduledAt { + Text("Scheduled · \(Self.timeLabel(scheduledAt))") + .font(typography.captionFont) + .foregroundStyle(theme.textSecondary) + } + } + } + + @ViewBuilder + private func actions(horizontal: Bool) -> some View { + if row.indeterminate { + action("Retry", id: "retry", horizontal: horizontal) { + interactor.retryIndeterminateMessage(row.id) + } + } else if row.canSteer { + action("Steer", id: "steer", horizontal: horizontal) { + interactor.steerQueuedMessage(row.id) + } + } + action("Edit", id: "edit", horizontal: horizontal) { + interactor.editQueuedMessage(row.id) + } + action("Cancel", id: "cancel", horizontal: horizontal, destructive: true) { + interactor.cancelQueuedMessage(row.id) + } + } + + private func action( + _ title: LocalizedStringKey, id: String, horizontal: Bool, + destructive: Bool = false, perform: @escaping () -> Void + ) -> some View { + Button(action: perform) { + Text(title) + .font(typography.toolTitleFont) + .multilineTextAlignment(.center) + .fixedSize(horizontal: horizontal, vertical: true) + .padding(.horizontal, 8) + .frame(minWidth: 44, maxWidth: horizontal ? nil : .infinity, minHeight: 44) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .foregroundStyle(destructive ? theme.danger : theme.link) + .disabled(!row.canAct) + .opacity(row.canAct ? 1 : 0.5) + .accessibilityIdentifier("queued-\(id)-\(row.id)") } private static func timeLabel(_ epochMs: Int) -> String { diff --git a/ios/Hapi/Features/Chat/SessionConfigModel.swift b/ios/Hapi/Features/Chat/SessionConfigModel.swift new file mode 100644 index 00000000..1bdea6f9 --- /dev/null +++ b/ios/Hapi/Features/Chat/SessionConfigModel.swift @@ -0,0 +1,90 @@ +import HapiClient +import HapiProtocol +import Observation + +/// App-only selection state. The interactor remains the source of +/// truth, including optimistic updates, capability gates and server reloads. +@MainActor @Observable +final class SessionConfigModel { + let interactor: ChatInteractor + + init(interactor: ChatInteractor) { + self.interactor = interactor + } + + var config: SessionConfigState { interactor.config } + var isApplying: Bool { interactor.configOpPending } + var modelLoadFailed: Bool { interactor.codexModels == .failed } + var showsModel: Bool { config.modelOptions != nil || config.modelOptionsLoading } + var showsEffort: Bool { config.effortOptions?.isEmpty == false } + var showsCollaborationMode: Bool { config.flavor == "codex" } + var hasSettings: Bool { !config.permissionModes.isEmpty || showsModel || showsEffort || showsCollaborationMode } + + var permission: PermissionMode { config.permissionMode ?? .default } + var collaborationMode: CodexCollaborationMode { config.collaborationMode ?? .default } + + var currentModel: String? { + if config.flavor == "claude" { + return ModelCatalog.normalizeClaudeModel(config.model) + } + if config.flavor == "codex", config.model == nil, + case .loaded(let models) = interactor.codexModels { + return models.first(where: \.isDefault)?.id + } + return config.model + } + + var modelLabel: String { + config.modelOptions?.first { $0.value == currentModel }?.label + ?? currentModel ?? "Default" + } + + /// Give the menu a read-only matching tag, even when Codex has neither an + /// explicit selection nor a catalog default. Never imply its first model. + var unlistedModelOption: CatalogOption? { + guard config.modelOptions?.contains(where: { $0.value == currentModel }) != true else { return nil } + return CatalogOption(value: currentModel, label: modelLabel) + } + + var currentEffort: String? { + config.flavor == "claude" ? ModelCatalog.normalizeClaudeEffort(config.effort) : config.effort + } + + /// An obsolete effort can arrive via SSE or remain after a model switch. + /// Give Picker a matching, read-only tag without offering unsupported edits. + var effortOptions: [CatalogOption] { + guard var options = config.effortOptions, !options.isEmpty else { return [] } + if !options.contains(where: { $0.value == currentEffort }) { + options.insert(CatalogOption(value: currentEffort, label: currentEffort ?? "Default"), at: 0) + } + return options + } + + func canSelectEffort(_ value: String?) -> Bool { + config.effortOptions?.contains(where: { $0.value == value }) == true + } + + func selectPermission(_ mode: PermissionMode) { + guard !isApplying, config.permissionModes.contains(where: { $0.mode == mode }) else { return } + if mode != permission { interactor.setPermissionMode(mode) } + } + + func selectModel(_ value: String?) { + guard !isApplying, config.modelOptions?.contains(where: { $0.value == value }) == true else { return } + if value != currentModel { interactor.setModel(value) } + } + + func selectCollaborationMode(_ mode: CodexCollaborationMode) { + guard !isApplying, config.canChangeCollaborationMode, mode != collaborationMode else { return } + interactor.setCollaborationMode(mode) + } + + func selectEffort(_ value: String?) { + guard !isApplying, value != currentEffort, canSelectEffort(value) else { return } + interactor.setEffort(value) + } + + func loadModels() { + interactor.loadModelOptions() + } +} diff --git a/ios/Hapi/Features/Chat/SessionConfigView.swift b/ios/Hapi/Features/Chat/SessionConfigView.swift index 68e3c372..34391ab8 100644 --- a/ios/Hapi/Features/Chat/SessionConfigView.swift +++ b/ios/Hapi/Features/Chat/SessionConfigView.swift @@ -2,107 +2,259 @@ import HapiClient import HapiProtocol import SwiftUI -/// Session config sheet (A-M3b): permission mode / model / effort sections, -/// catalog-driven per flavor — the SwiftUI twin of the Android -/// `SessionConfigSheet`. Pickers apply optimistically through the interactor -/// (`setPermissionMode` & co., server truth reloaded on error); a flavor -/// without a known model catalog simply hides that section. -struct SessionConfigView: View { - let interactor: ChatInteractor +/// Attach to the gear, not the chat root: UIKit needs the actual toolbar +/// anchor to position an iPad popover. One presenter survives size adaptation. +struct SessionConfigButton: View { + @Binding var isPresented: Bool + @ViewBuilder let content: () -> Content + @Environment(\.horizontalSizeClass) private var horizontalSizeClass + @Environment(\.verticalSizeClass) private var verticalSizeClass + @Environment(\.dynamicTypeSize) private var dynamicTypeSize + private var prefersPopover: Bool { + horizontalSizeClass == .regular && verticalSizeClass != .compact + } + + var body: some View { + Button { + isPresented = true + } label: { + Image(systemName: "gearshape") + } + .accessibilityLabel("Session settings") + .accessibilityIdentifier("session-config-open") + .popover(isPresented: $isPresented, attachmentAnchor: .rect(.bounds), arrowEdge: .top) { + content() + // Preferred, not fixed: the system can constrain a small window. + // Read the host's traits; popover content has its own traits. + .frame( + idealWidth: prefersPopover ? 400 : nil, + maxWidth: prefersPopover ? 400 : nil, + idealHeight: prefersPopover ? popoverHeight : nil, + maxHeight: prefersPopover ? popoverHeight : nil + ) + .presentationCompactAdaptation(.sheet) + } + } + + private var popoverHeight: CGFloat { dynamicTypeSize.isAccessibilitySize ? 600 : 480 } +} + +/// Single-page, catalog-driven menus. Selecting applies immediately; Done +/// only dismisses. Presentation height is UI state, not configuration state. +struct SessionConfigView: View { + @State private var model: SessionConfigModel + @State private var detent: PresentationDetent = .medium + let notice: String? + @Environment(\.dismiss) private var dismiss + @Environment(\.dynamicTypeSize) private var dynamicTypeSize + + init(interactor: ChatInteractor, notice: String? = nil) { + self.init(model: SessionConfigModel(interactor: interactor), notice: notice) + } + + init(model: SessionConfigModel, notice: String? = nil) { + _model = State(initialValue: model) + self.notice = notice + } var body: some View { - let config = interactor.config NavigationStack { - List { - if !config.active { - notice("Session is offline — changes apply after it resumes or may be rejected.") - } else if config.controlledByUser { - notice("Session is controlled from the terminal — config changes will be rejected.") - } - - if !config.permissionModes.isEmpty { - Section("Permission mode") { - ForEach(config.permissionModes, id: \.mode) { option in - OptionRow( - label: option.label, - selected: option.mode == (config.permissionMode ?? .default), - tone: option.tone - ) { - interactor.setPermissionMode(option.mode) - } - } - } - } - - if config.modelOptions != nil || config.modelOptionsLoading { - Section("Model") { - modelSection(config) - } - } - - if let effortOptions = config.effortOptions { - Section("Effort") { - let current = normalizedCurrentEffort(config) - ForEach(effortOptions, id: \.self) { option in - OptionRow(label: option.label, selected: option.value == current) { - interactor.setEffort(option.value) - } - } - } - } - } - .navigationTitle("Session Settings") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .confirmationAction) { - Button("Done") { - dismiss() - } - } - } + settingsForm + .navigationTitle("Session Settings") + .navigationBarTitleDisplayMode(.inline) + .toolbar { doneButton } } - .presentationDetents([.medium, .large]) - .onAppear { - interactor.loadModelOptions() + .safeAreaInset(edge: .bottom, spacing: 0) { feedback } + .presentationDetents( + dynamicTypeSize.isAccessibilitySize ? [.large] : [.medium, .large], + selection: Binding( + get: { dynamicTypeSize.isAccessibilitySize ? .large : detent }, + set: { detent = $0 } + ) + ) + .onAppear { model.loadModels() } + } + + private var settingsForm: some View { + Form { + if !model.config.active { + statusNotice("Session is offline — changes apply after it resumes or may be rejected.") + } else if model.config.controlledByUser { + statusNotice("Session is controlled from the terminal — config changes will be rejected.") + } + + if model.showsModel || model.showsEffort { + Section { + if model.showsModel { modelRow } + if model.showsEffort { effortMenu } + } + .disabled(model.isApplying) + } + if !model.config.permissionModes.isEmpty || model.showsCollaborationMode { + Section { + if !model.config.permissionModes.isEmpty { permissionMenu } + if model.showsCollaborationMode { collaborationMenu } + } footer: { + if !model.config.permissionModes.isEmpty { + Text("Permission modes control how the agent requests approval. Behavior varies by agent.") + } + } + .disabled(model.isApplying) + } + if !model.hasSettings { + statusNotice("No settings available for this session.") + } } } - @ViewBuilder - private func modelSection(_ config: SessionConfigState) -> some View { - if config.modelOptionsLoading { - HStack(spacing: 8) { - ProgressView() - .controlSize(.small) - Text("Loading models…") - .font(.subheadline) + private var permissionMenu: some View { + SessionConfigMenu( + title: "Permission mode", value: Text(verbatim: model.permission.label), tone: model.permission.tone + ) { + Picker("Permission mode", selection: Binding( + get: { model.permission }, set: { model.selectPermission($0) } + )) { + if !model.config.permissionModes.contains(where: { $0.mode == model.permission }) { + permissionOption(PermissionModeOption(mode: model.permission)).disabled(true) + } + ForEach(model.config.permissionModes, id: \.mode) { option in + permissionOption(option) + } + } + .pickerStyle(.inline) + } + .accessibilityIdentifier("session-config-permission") + } + + private func permissionOption(_ option: PermissionModeOption) -> some View { + Group { + if option.tone == .danger { + Label { + Text(verbatim: option.label) + Text(verbatim: " · ") + Text("High risk") + } icon: { + Image(systemName: "exclamationmark.triangle") + } + } else { + Text(verbatim: option.label) + } + } + .tag(option.mode) + .accessibilityIdentifier("session-config-permission-\(option.mode.rawValue)") + } + + private var collaborationMenu: some View { + SessionConfigMenu( + title: "Collaboration Mode", value: Text(LocalizedStringKey(model.collaborationMode.label)) + ) { + Picker("Collaboration Mode", selection: Binding( + get: { model.collaborationMode }, set: { model.selectCollaborationMode($0) } + )) { + ForEach(CodexCollaborationMode.allCases, id: \.self) { mode in + Text(LocalizedStringKey(mode.label)).tag(mode) + } + } + .pickerStyle(.inline) + } + .disabled(!model.config.canChangeCollaborationMode) + .accessibilityIdentifier("session-config-collaboration") + } + + private var effortMenu: some View { + SessionConfigMenu( + title: "Effort", + value: Text(verbatim: model.effortOptions.first { $0.value == model.currentEffort }?.label ?? "Default") + ) { + Picker("Effort", selection: Binding( + get: { model.currentEffort }, set: { model.selectEffort($0) } + )) { + ForEach(model.effortOptions, id: \.value) { option in + Text(verbatim: option.label) + .tag(option.value) + .disabled(!model.canSelectEffort(option.value)) + } + } + .pickerStyle(.inline) + } + .accessibilityIdentifier("session-config-effort") + } + + private var modelRow: some View { + VStack(alignment: .leading, spacing: 8) { + SessionConfigMenu(title: "Model", value: Text(verbatim: model.modelLabel)) { + Picker("Model", selection: Binding( + get: { model.currentModel }, set: { model.selectModel($0) } + )) { + if let current = model.unlistedModelOption { + Text(verbatim: current.label).tag(current.value).disabled(true) + } + ForEach(model.config.modelOptions ?? [], id: \.value) { option in + Text(verbatim: option.label) + .tag(option.value) + .accessibilityIdentifier("session-config-model-\(option.value ?? "default")") + } + } + .pickerStyle(.inline) + } + .disabled(model.config.modelOptionsLoading || model.modelLoadFailed || model.config.modelOptions?.isEmpty != false) + .accessibilityIdentifier("session-config-model") + + if model.config.modelOptionsLoading { + ProgressView("Loading models…") + .accessibilityIdentifier("session-config-model-loading") + } else if model.modelLoadFailed { + Text("Failed to load models") .foregroundStyle(.secondary) - } - } else if config.modelOptions?.isEmpty != false { - Text("Model list unavailable for this session.") - .font(.subheadline) - .foregroundStyle(.secondary) - } else { - let current = normalizedCurrentModel(config) - ForEach(config.modelOptions ?? [], id: \.self) { option in - OptionRow(label: option.label, selected: option.value == current) { - interactor.setModel(option.value) - } + Button("Retry") { model.loadModels() } + .buttonStyle(.borderless) + .frame(minHeight: 44) + .accessibilityIdentifier("session-config-model-retry") + } else if model.config.modelOptions?.isEmpty != false { + Text("Model list unavailable for this session.") + .foregroundStyle(.secondary) + .accessibilityIdentifier("session-config-model-unavailable") } } } - /// Claude models normalize `auto`/`default` to the nil Default row. - private func normalizedCurrentModel(_ config: SessionConfigState) -> String? { - config.flavor == "claude" ? ModelCatalog.normalizeClaudeModel(config.model) : config.model + @ToolbarContentBuilder + private var doneButton: some ToolbarContent { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { dismiss() } + .accessibilityIdentifier("session-config-done") + } } - private func normalizedCurrentEffort(_ config: SessionConfigState) -> String? { - config.flavor == "claude" ? ModelCatalog.normalizeClaudeEffort(config.effort) : config.effort + /// ChatModel owns the event callback. Mirroring its notice here keeps + /// failures visible above the modal without stealing chat's event handler. + @ViewBuilder + private var feedback: some View { + if model.isApplying || notice != nil { + VStack(alignment: .leading, spacing: 8) { + if model.isApplying { + ProgressView("Applying changes…") + .accessibilityIdentifier("session-config-applying") + } + if let notice { + Label { + Text(verbatim: LocalizedNoticeMapper.map(notice)) + .fixedSize(horizontal: false, vertical: true) + } icon: { + Image(systemName: "info.circle") + } + .accessibilityElement(children: .combine) + .accessibilityIdentifier("session-config-notice") + } + } + .font(.footnote) + .frame(maxWidth: .infinity, alignment: .leading) + .padding() + .background(.regularMaterial) + } } - private func notice(_ text: LocalizedStringKey) -> some View { + private func statusNotice(_ text: LocalizedStringKey) -> some View { Section { Label(text, systemImage: "info.circle") .font(.footnote) @@ -111,32 +263,99 @@ struct SessionConfigView: View { } } -/// One catalog row: label + trailing checkmark, tinted by the mode's tone. -private struct OptionRow: View { - let label: String - let selected: Bool +/// Menu labels share adaptive summaries, including VoiceOver's current value. +/// A Picker inside Menu supplies native selection checkmarks without a push. +private struct SessionConfigMenu: View { + let title: LocalizedStringKey + let value: Text var tone: PermissionModeTone = .neutral - let onTap: () -> Void + @ViewBuilder let content: () -> Content var body: some View { - Button(action: onTap) { - HStack { - Text(label) - .foregroundStyle(toneColor) - Spacer() - if selected { - Image(systemName: "checkmark") - .font(.subheadline.weight(.semibold)) - .foregroundStyle(.tint) - } + Menu(content: content) { + HStack(spacing: 8) { + SessionConfigSummaryRow(title: title, value: value, tone: tone) + Image(systemName: "chevron.up.chevron.down") + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + .accessibilityHidden(true) } .contentShape(Rectangle()) } + .menuIndicator(.hidden) .buttonStyle(.plain) + .accessibilityLabel(title) + .accessibilityValue(tone == .danger ? value + Text(verbatim: ", ") + Text("High risk") : value) + } +} + +private struct SessionConfigSummaryRow: View { + let title: LocalizedStringKey + let value: Text + var tone: PermissionModeTone = .neutral + @Environment(\.dynamicTypeSize) private var dynamicTypeSize + + var body: some View { + Group { + if dynamicTypeSize.isAccessibilitySize { + stackedSummary + } else { + ViewThatFits(in: .horizontal) { + HStack(spacing: 16) { + Text(title).fixedSize() + Spacer(minLength: 0) + currentValue.fixedSize() + } + stackedSummary + } + } + } + .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading) + .accessibilityElement(children: .ignore) + .accessibilityLabel(title) + .accessibilityValue( + tone == .danger + ? value + Text(verbatim: ", ") + Text("High risk") + : value + ) } - private var toneColor: Color { - switch tone { + private var stackedSummary: some View { + VStack(alignment: .leading, spacing: 4) { + Text(title) + currentValue + } + .fixedSize(horizontal: false, vertical: true) + } + + private var currentValue: some View { + VStack(alignment: .leading, spacing: 2) { + value + .foregroundStyle(tone == .neutral || tone == .info ? .secondary : tone.color) + if tone == .danger { + SessionConfigRiskLabel() + } + } + } +} + +/// Explicit layout avoids Form's automatic Label style treating this subtitle +/// as a separate list-row label (which can clip or stretch its warning text). +private struct SessionConfigRiskLabel: View { + var body: some View { + HStack(spacing: 4) { + Image(systemName: "exclamationmark.triangle") + .accessibilityHidden(true) + Text("High risk") + } + .font(.caption) + .foregroundStyle(.red) + } +} + +private extension PermissionModeTone { + var color: Color { + switch self { case .danger: .red case .warning: .orange case .neutral, .info: .primary diff --git a/ios/Hapi/Features/Chat/ToolDetailView.swift b/ios/Hapi/Features/Chat/ToolDetailView.swift index 7ad8157c..2b286d25 100644 --- a/ios/Hapi/Features/Chat/ToolDetailView.swift +++ b/ios/Hapi/Features/Chat/ToolDetailView.swift @@ -246,7 +246,7 @@ private struct ToolInspectorDetail: View { } } -private struct ToolDetailHeader: View { +struct ToolDetailHeader: View { let block: ToolCallBlock let basePath: String? var openFile: ((String) -> Void)? @@ -263,12 +263,15 @@ private struct ToolDetailHeader: View { .font(.footnote) .foregroundStyle(state == .failed ? Color.red : .secondary) } else { - HStack(spacing: 8) { - ToolStatusIndicator(state: block.tool.state) - Text(statusLabel).font(.footnote).foregroundStyle(.secondary) + if block.tool.state != .pending || block.tool.permission?.status != .pending { + HStack(spacing: 8) { + ToolStatusIndicator(state: block.tool.state) + Text(statusLabel).font(.footnote).foregroundStyle(.secondary) + } } - if let permission = block.tool.permission { - PermissionStateRow(permission: permission) + if let permission = block.tool.permission, + !permissionActionsInline || permission.status != .pending { + PermissionStateRow(permission: permission, horizontalInset: 0) } } if block.tool.permission?.status == .pending && !permissionActionsInline { @@ -359,9 +362,14 @@ private struct ToolProcessView: View { ToolDetailHeader(block: block, basePath: model.basePath, openFile: { path in fileRoute = FileViewerRoute(sessionId: model.sessionId, path: path, mode: .file) }, permissionActionsInline: true) - if model.toolInspection.tools[snapshot.id] != nil, - let permission = block.tool.permission, permission.status == .pending { - PendingPermissionFooter(tool: block.tool, requestId: permission.id, interactions: model.interactor) + if let permission = block.tool.permission, permission.status == .pending { + if model.toolInspection.tools[snapshot.id] != nil { + PendingPermissionFooter(tool: block.tool, requestId: permission.id, interactions: model.interactor) + } else if !isQuestionDetailsTool(block.tool.name) { + // The header delegates pending status to this section. + // A stale process keeps the recorded verdict, never actions. + PermissionStateRow(permission: permission, horizontalInset: 0) + } } ToolCallBody(tool: block.tool, basePath: model.basePath) Text("Agent process").font(.headline) diff --git a/ios/Hapi/Features/DirectoryBrowser/RemoteDirectoryBrowserView.swift b/ios/Hapi/Features/DirectoryBrowser/RemoteDirectoryBrowserView.swift index 6da25ff4..e3acd424 100644 --- a/ios/Hapi/Features/DirectoryBrowser/RemoteDirectoryBrowserView.swift +++ b/ios/Hapi/Features/DirectoryBrowser/RemoteDirectoryBrowserView.swift @@ -59,7 +59,7 @@ struct RemoteDirectoryBrowserView: View { } } else if let error = model.error { VStack(alignment: .leading, spacing: 8) { - Text(error).foregroundStyle(.red) + Text(LocalizedNoticeMapper.map(error)).foregroundStyle(.red) Button("Retry") { model.refresh() } diff --git a/ios/Hapi/Features/Home/HomeView.swift b/ios/Hapi/Features/Home/HomeView.swift index f245b413..35b1f440 100644 --- a/ios/Hapi/Features/Home/HomeView.swift +++ b/ios/Hapi/Features/Home/HomeView.swift @@ -1,12 +1,13 @@ import HapiClient import SwiftUI +import UIKit /// Post-pairing home: the session list for the active hub, with the hub /// switcher (switch / add / settings / sign out), the "+" new-session sheet /// (A-M3c), the Settings sheet (A-M4e), and a unified session-filter menu. /// Degraded connections appear below navigation, not among its actions. -/// Tapping a row pushes the chat (M2f); a successful -/// spawn dismisses the sheet and pushes the new chat the same way. +/// iPhone pushes the chat; iPad selects a stable detail in a native split. +/// Spawn, notification and row selection share the same opening path. struct HomeView: View { let session: HubSession @@ -16,6 +17,9 @@ struct HomeView: View { @State private var showNewSession = false @State private var showSettings = false @State private var path: [String] = [] + @State private var tabletNavigation = SessionNavigationState() + + private var usesSplitNavigation: Bool { UIDevice.current.userInterfaceIdiom == .pad } init(session: HubSession) { self.session = session @@ -24,64 +28,21 @@ struct HomeView: View { var body: some View { @Bindable var model = model - NavigationStack(path: $path) { - VStack(spacing: 0) { - if let failedHub = model.authFailureNotice { - authFailureBanner(failedHub: failedHub) + Group { + if usesSplitNavigation { + SessionSplitView(navigation: tabletNavigation, onNewSession: { showNewSession = true }) { + sessionList + } detail: { sessionId in + chat(sessionId) } - SessionConnectionNotice( - state: session.connectionState, - showsCachedSessions: listModel.isOffline && listModel.hasLoaded - ) - SessionListView(model: listModel) { sessionId in - path.append(sessionId) + } else { + NavigationStack(path: $path) { + sessionList + .navigationDestination(for: String.self) { sessionId in + chat(sessionId) + } } } - .navigationDestination(for: String.self) { sessionId in - ChatView(session: session, sessionId: sessionId) { superseding in - // Resume returned a different session id (A-M3a): replace - // the current chat entry so back still pops to the list. - if let last = path.indices.last, path[last] == sessionId { - path[last] = superseding - } else { - path.append(superseding) - } - } - // A replaced path element must rebuild the screen's @State. - .id(sessionId) - } - .navigationTitle("Sessions") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .topBarLeading) { - hubMenu - } - if listModel.showsFilterMenu { - ToolbarItem(placement: .topBarTrailing) { - SessionFilterMenu(model: listModel) - } - } - ToolbarItem(placement: .topBarTrailing) { - Button { - showNewSession = true - } label: { - Label("New Session", systemImage: "plus") - .frame(minWidth: 44, minHeight: 44) - } - .accessibilityIdentifier("home.new-session") - } - } - .confirmationDialog( - "Sign out of \(HubDisplay.host(session.hubUrl))?", - isPresented: $confirmSignOut, - titleVisibility: .visible - ) { - Button("Sign Out", role: .destructive) { - model.signOut(hub: session.hubUrl) - } - } message: { - Text("Removes the stored access token for this hub. Pair again to reconnect.") - } } // Notification tap (P3): consume the pending target into this hub's // navigation path. `initial: true` covers a tap that cold-started @@ -89,9 +50,11 @@ struct HomeView: View { .onChange(of: model.pendingOpenSessionId, initial: true) { _, sessionId in guard let sessionId else { return } model.pendingOpenSessionId = nil - if path.last != sessionId { - path.append(sessionId) - } + openSession(sessionId) + } + .onChange(of: session.sessionRemoval) { _, removal in + guard usesSplitNavigation, let removal else { return } + tabletNavigation.remove(removal.sessionId) } .sheet(isPresented: $model.showAddHub) { PairingFlowView(context: .addHub) @@ -100,7 +63,7 @@ struct HomeView: View { NewSessionView(session: session) { sessionId in // Navigate-replace: drop the sheet, push the fresh chat. showNewSession = false - path.append(sessionId) + openSession(sessionId) } } .sheet(isPresented: $showSettings) { @@ -108,6 +71,60 @@ struct HomeView: View { } } + private var sessionList: some View { + VStack(spacing: 0) { + if let failedHub = model.authFailureNotice { + authFailureBanner(failedHub: failedHub) + } + SessionConnectionNotice( + state: session.connectionState, + showsCachedSessions: listModel.isOffline && listModel.hasLoaded + ) + SessionListView(model: listModel, selection: usesSplitNavigation ? Binding( + get: { tabletNavigation.selectedSessionId }, + // Native list deselection (e.g. a filter hides the row) is + // not an authoritative removal and must not close the chat. + set: { if let id = $0 { openSession(id) } } + ) : nil, onOpenSession: openSession) + } + .navigationTitle("Sessions") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarLeading) { hubMenu } + if listModel.showsFilterMenu { + ToolbarItem(placement: .topBarTrailing) { SessionFilterMenu(model: listModel) } + } + ToolbarItem(placement: .topBarTrailing) { + Button { showNewSession = true } label: { + Label("New Session", systemImage: "plus") + .frame(minWidth: 44, minHeight: 44) + } + .accessibilityIdentifier("home.new-session") + } + } + } + + private func openSession(_ sessionId: String) { + if usesSplitNavigation { + listModel.onSessionOpened(sessionId) + tabletNavigation.open(sessionId) + } else if path.last != sessionId { + path.append(sessionId) + } + } + + private func chat(_ sessionId: String) -> some View { + ChatView(session: session, sessionId: sessionId) { superseding in + if usesSplitNavigation { + tabletNavigation.supersede(sessionId, with: superseding) + } else if let last = path.indices.last, path[last] == sessionId { + path[last] = superseding + } + // A late response from a chat already left must not steal focus. + } + .id(sessionId) + } + // MARK: - Hub switcher private var hubMenu: some View { @@ -147,6 +164,15 @@ struct HomeView: View { } .accessibilityValue(HubDisplay.host(session.hubUrl)) .accessibilityIdentifier("home.hubs") + .confirmationDialog( + "Sign out of \(HubDisplay.host(session.hubUrl))?", + isPresented: $confirmSignOut, + titleVisibility: .visible + ) { + Button("Sign Out", role: .destructive) { model.signOut(hub: session.hubUrl) } + } message: { + Text("Removes the stored access token for this hub. Pair again to reconnect.") + } } private func authFailureBanner(failedHub: String) -> some View { diff --git a/ios/Hapi/Features/Home/SessionNavigationState.swift b/ios/Hapi/Features/Home/SessionNavigationState.swift new file mode 100644 index 00000000..10f4f4d6 --- /dev/null +++ b/ios/Hapi/Features/Home/SessionNavigationState.swift @@ -0,0 +1,34 @@ +import Observation +import SwiftUI + +/// In-memory navigation for one hub's iPad workspace. Window geometry never +/// owns selection: filtering, collapsing and reopening the sidebar must not +/// discard the selected chat or its nested file/process navigation. +@MainActor @Observable +final class SessionNavigationState { + private(set) var selectedSessionId: String? + var detailPath = NavigationPath() + var columnVisibility: NavigationSplitViewVisibility = .all + var preferredCompactColumn: NavigationSplitViewColumn = .sidebar + + func open(_ sessionId: String) { + if selectedSessionId != sessionId { + detailPath = NavigationPath() + selectedSessionId = sessionId + } + // Also works for notifications/new sessions not yet in the list. + preferredCompactColumn = .detail + } + + func supersede(_ sessionId: String, with replacement: String) { + guard selectedSessionId == sessionId else { return } + open(replacement) + } + + func remove(_ sessionId: String) { + guard selectedSessionId == sessionId else { return } + detailPath = NavigationPath() + selectedSessionId = nil + preferredCompactColumn = .sidebar + } +} diff --git a/ios/Hapi/Features/Home/SessionSplitView.swift b/ios/Hapi/Features/Home/SessionSplitView.swift new file mode 100644 index 00000000..597b8de9 --- /dev/null +++ b/ios/Hapi/Features/Home/SessionSplitView.swift @@ -0,0 +1,43 @@ +import SwiftUI + +/// Keep the same split/stack hierarchy across size-class changes. SwiftUI +/// moves the detail controller when collapsing instead of creating a second +/// ChatView (and a second interactor/SSE subscription). +struct SessionSplitView: View { + let navigation: SessionNavigationState + let onNewSession: () -> Void + @ViewBuilder var sidebar: () -> Sidebar + @ViewBuilder var detail: (String) -> Detail + + var body: some View { + @Bindable var navigation = navigation + NavigationSplitView( + columnVisibility: $navigation.columnVisibility, + preferredCompactColumn: $navigation.preferredCompactColumn + ) { + sidebar() + .navigationSplitViewColumnWidth(min: 280, ideal: 320, max: 360) + } detail: { + NavigationStack(path: $navigation.detailPath) { + if let sessionId = navigation.selectedSessionId { + detail(sessionId) + } else { + ContentUnavailableView { + Label("Select a session", systemImage: "bubble.left.and.bubble.right") + } description: { + Text("Choose a session from the sidebar, or start a new one.") + } actions: { + Button("New Session", action: onNewSession) + .buttonStyle(.borderedProminent) + } + .accessibilityIdentifier("home.no-selection") + } + } + // Switching sessions clears *all* destinations, including the + // existing Boolean/item-based file and tool presentations. + // No width, size class or column visibility participates in ID. + .id(navigation.selectedSessionId) + } + .navigationSplitViewStyle(.balanced) + } +} diff --git a/ios/Hapi/Features/NewSession/NewSessionModel.swift b/ios/Hapi/Features/NewSession/NewSessionModel.swift index 724f7865..668f879e 100644 --- a/ios/Hapi/Features/NewSession/NewSessionModel.swift +++ b/ios/Hapi/Features/NewSession/NewSessionModel.swift @@ -119,8 +119,6 @@ struct NewSessionPrefsStore { /// - `startingMode` stays unset → the runner spawns `'remote'` (pty deferred). @MainActor @Observable final class NewSessionModel { - static let debounce: Duration = .milliseconds(250) - static let msgWorktreeMissing = String(localized: "Worktree sessions require an existing repository directory.") static let msgDirectoryMissing = @@ -130,6 +128,8 @@ final class NewSessionModel { static let msgDirectoryOutsideWorkspaceRoots = String(localized: "Directory must be inside one of this machine's workspace roots.") static let msgDirectoryLookupFailed = String(localized: "Failed to browse directories") + static let msgDirectoryCheckFailed = String(localized: "Failed to check directory") + static let msgMachineOffline = String(localized: "Selected machine is offline. Choose an online machine.") static let msgAgentAvailabilityFailed = String(localized: "Failed to check installed Agents") static let msgRunnerUpgradeRequired = String(localized: "Upgrade and restart this machine's HAPI runner before creating sessions.") @@ -141,17 +141,14 @@ final class NewSessionModel { // MARK: Observable state private(set) var form = NewSessionForm() - private(set) var suggestions: [String] = [] + let directoryInput: NewSessionDirectoryModel + var suggestions: [String] { directoryInput.suggestions } private(set) var codexModels: CodexModelsState = .hidden private(set) var agentAvailability: AgentAvailabilityState = .loading private(set) var isSpawning = false private(set) var spawnError: String? private(set) var confirmCreateDirectoryArmed = false private(set) var machinesSettled = false - /// Probed existence per trimmed path (feeds the directory status hint). - private(set) var pathExistence: [String: Bool] = [:] - private(set) var outsideWorkspaceRoots: Set = [] - private(set) var directoryLookupError: String? private(set) var prefsData = NewSessionPrefsData() let directoryBrowser: RemoteDirectoryBrowserModel @@ -162,7 +159,6 @@ final class NewSessionModel { /// Fired once with the new session id — navigate-replace to the chat. private let onCreated: @MainActor (String) -> Void - @ObservationIgnored private var directoryTask: Task? @ObservationIgnored private var codexTask: Task? @ObservationIgnored private var availabilityTask: Task? @ObservationIgnored private var defaultDirectoryTask: Task? @@ -170,16 +166,23 @@ final class NewSessionModel { @ObservationIgnored private var availabilityFetchedForMachine: String? @ObservationIgnored private var suppressSuggestions = false @ObservationIgnored private var spawnInFlight = false - @ObservationIgnored private var directoryRequestVersion = 0 - /// Parent-listing cache: retyping within the same parent re-filters - /// locally instead of re-requesting. - @ObservationIgnored private var cachedListing: - (machineId: String, parent: String, entries: [MachineDirectoryEntry])? + @ObservationIgnored private var hasStarted = false + @ObservationIgnored private var directoryEdited = false + @ObservationIgnored private var directoryEditVersion = 0 - init(session: HubSession, onCreated: @escaping @MainActor (String) -> Void) { + init( + session: HubSession, + defaults: UserDefaults = .standard, + onCreated: @escaping @MainActor (String) -> Void + ) { self.session = session - self.prefsStore = NewSessionPrefsStore(hubUrl: session.hubUrl) + self.prefsStore = NewSessionPrefsStore(hubUrl: session.hubUrl, defaults: defaults) self.onCreated = onCreated + self.directoryInput = NewSessionDirectoryModel( + requester: session.api, + lookupError: Self.msgDirectoryLookupFailed, + checkError: Self.msgDirectoryCheckFailed + ) self.directoryBrowser = RemoteDirectoryBrowserModel( requester: session.api, fallbackError: Self.msgDirectoryLookupFailed @@ -191,15 +194,18 @@ final class NewSessionModel { /// Restore prefs + sanitized draft, preselect a machine, refresh the /// roster. Call once per presentation. func start() async { - prefsData = prefsStore.readPrefs() - let initial = prefsStore.readDraft().map(NewSessionLogic.sanitizeDraft) ?? NewSessionForm() - form = initial + if !hasStarted { + hasStarted = true + prefsData = prefsStore.readPrefs() + let draft = prefsStore.readDraft().map(NewSessionLogic.sanitizeDraft) + form = draft ?? NewSessionForm() + // A saved empty path can be intentional; never replace it on refresh. + directoryEdited = draft != nil + suppressSuggestions = true + } reconcileMachineSelection() refreshAgentAvailability() refreshCodexModelsIfNeeded() - // A restored directory should probe existence but not pop the - // autocomplete dropdown — suggestions belong to typing. - suppressSuggestions = true scheduleDirectoryWork() do { @@ -207,14 +213,43 @@ final class NewSessionModel { } catch { // Snapshot (if any) keeps serving; the picker shows what it has. } + guard !Task.isCancelled else { return } machinesSettled = true - reconcileMachineSelection() + machinesChanged() } - /// Machine roster changed (SSE / refresh) — re-run the preselection: - /// keep a still-online selection; otherwise last-used, else first. + /// Only an unselected form is auto-selected. Losing a machine must not + /// move the user's path or pending Create action onto a different host. func machinesChanged() { + guard hasStarted else { return } reconcileMachineSelection() + if selectedMachine == nil { + cancelDefaultDirectoryResolution() + directoryBrowser.close() + availabilityTask?.cancel() + codexTask?.cancel() + availabilityFetchedForMachine = nil + codexFetchedForMachine = nil + } else { + if directoryBrowser.isPresented, + directoryBrowser.roots != selectedMachine.map(RemoteDirectoryPath.browseRoots) { + directoryBrowser.close() + } + refreshAgentAvailability() + refreshCodexModelsIfNeeded() + } + scheduleDirectoryWork() + } + + func stopDirectoryWork() { + cancelDefaultDirectoryResolution() + directoryInput.stop() + } + + private func cancelDefaultDirectoryResolution() { + directoryEditVersion += 1 + defaultDirectoryTask?.cancel() + defaultDirectoryTask = nil } // MARK: - Derived state @@ -227,6 +262,14 @@ final class NewSessionModel { session.machineStore.machines.isEmpty && !machinesSettled } + var machineUnavailable: Bool { + machinesSettled && form.machineId != nil && selectedMachine == nil + } + + var normalizedDirectory: String { + RemoteDirectoryPath.expandHome(form.directory, homeDirectory: selectedMachine?.metadata?.homeDir) + } + /// `runnerState.lastSpawnError` of the selected machine, formatted /// (`web/src/utils/formatRunnerSpawnError.ts`). var runnerSpawnError: String? { @@ -252,8 +295,8 @@ final class NewSessionModel { isError: false ) } - if let directoryLookupError { - return DirectoryStatusUI(message: directoryLookupError, isError: true) + if let error = directoryInput.existenceError { + return DirectoryStatusUI(message: error, isError: true) } return nil } @@ -361,8 +404,8 @@ final class NewSessionModel { } var canCreate: Bool { - form.machineId != nil - && !form.trimmedDirectory.isEmpty + selectedMachine != nil + && !normalizedDirectory.isEmpty && !isSpawning && !missingWorktreeDirectory && !directoryOutsideWorkspaceRoots @@ -372,18 +415,15 @@ final class NewSessionModel { } private var selectedMachine: Machine? { - session.machineStore.machines.first { $0.id == form.machineId } + session.machineStore.machines.first { $0.id == form.machineId && $0.active } } private var directoryExists: Bool? { - let trimmed = form.trimmedDirectory - guard !trimmed.isEmpty else { return nil } - return pathExistence[trimmed] + directoryInput.exists } private var directoryOutsideWorkspaceRoots: Bool { - let trimmed = form.trimmedDirectory - return !trimmed.isEmpty && outsideWorkspaceRoots.contains(trimmed) + directoryInput.outsideWorkspaceRoots } private var missingWorktreeDirectory: Bool { @@ -418,11 +458,15 @@ final class NewSessionModel { // MARK: - Actions func setMachine(_ machineId: String) { - guard machineId != form.machineId else { return } + guard !isSpawning, machineId != form.machineId, + session.machineStore.machines.contains(where: { $0.id == machineId && $0.active }) + else { return } applyMachineSelection(machineId, resetDirectory: true) } func setDirectory(_ value: String) { + cancelDefaultDirectoryResolution() + directoryEdited = true suppressSuggestions = false confirmCreateDirectoryArmed = false form.directory = value @@ -443,7 +487,8 @@ final class NewSessionModel { directoryBrowser.open( machineId: machine.id, roots: RemoteDirectoryPath.browseRoots(for: machine), - initialPath: form.trimmedDirectory + initialPath: normalizedDirectory, + defaultPath: RemoteDirectoryPath.defaultDirectory(for: machine) ) } @@ -538,7 +583,10 @@ final class NewSessionModel { /// creates it. Success persists prefs, clears the draft, and hands the /// new session id to `onCreated`; failure lands in the inline error. func create() { - let current = form + guard canCreate, !spawnInFlight else { return } + cancelDefaultDirectoryResolution() + var current = form + current.directory = normalizedDirectory guard let machineId = current.machineId else { return } let directory = current.trimmedDirectory guard !directory.isEmpty, !spawnInFlight else { return } @@ -553,7 +601,7 @@ final class NewSessionModel { spawnInFlight = true isSpawning = true spawnError = nil - Task { [weak self] in + Task { [weak self, current] in defer { self?.spawnInFlight = false self?.isSpawning = false @@ -566,11 +614,11 @@ final class NewSessionModel { paths: [directory] ) let exists = pathResult.exists[directory] - if let exists { - self.pathExistence[directory] = exists + guard self.selectedMachine?.id == machineId else { + self.spawnError = Self.msgMachineOffline + return } - self.outsideWorkspaceRoots.remove(directory) - self.outsideWorkspaceRoots.formUnion(pathResult.outsideWorkspaceRoots ?? []) + self.directoryInput.acceptExistence(pathResult, machineId: machineId, path: directory) if pathResult.outsideWorkspaceRoots?.contains(directory) == true { self.spawnError = Self.msgDirectoryOutsideWorkspaceRoots return @@ -612,9 +660,10 @@ final class NewSessionModel { // MARK: - Internals private func pickPath(_ path: String) { + cancelDefaultDirectoryResolution() + directoryEdited = true suppressSuggestions = true confirmCreateDirectoryArmed = false - suggestions = [] form.directory = path persistDraft() scheduleDirectoryWork() @@ -625,26 +674,17 @@ final class NewSessionModel { } private func reconcileMachineSelection() { - let machines = session.machineStore.machines + guard form.machineId == nil else { return } + let machines = session.machineStore.machines.filter(\.active) guard !machines.isEmpty else { return } - if let current = form.machineId, machines.contains(where: { $0.id == current }) { - if form.trimmedDirectory.isEmpty { - applyMachineSelection(current, resetDirectory: true) - } - return - } let target = machines.first { $0.id == prefsData.lastMachineId } ?? machines[0] - applyMachineSelection(target.id, resetDirectory: form.trimmedDirectory.isEmpty) + applyMachineSelection(target.id, resetDirectory: !directoryEdited && form.trimmedDirectory.isEmpty) } private func applyMachineSelection(_ machineId: String, resetDirectory: Bool) { directoryBrowser.close() - defaultDirectoryTask?.cancel() - pathExistence = [:] - outsideWorkspaceRoots = [] - directoryLookupError = nil - suggestions = [] - cachedListing = nil + cancelDefaultDirectoryResolution() + directoryInput.stop() confirmCreateDirectoryArmed = false // The seeded recent path is a pick, not typing — no dropdown. suppressSuggestions = true @@ -652,7 +692,8 @@ final class NewSessionModel { form.model = "auto" if resetDirectory { let machine = session.machineStore.machines.first { $0.id == machineId } - form.directory = machine.flatMap { RemoteDirectoryPath.browseRoots(for: $0).first } ?? "" + directoryEdited = false + form.directory = machine.map(RemoteDirectoryPath.defaultDirectory) ?? "" } persistDraft() if resetDirectory { @@ -664,7 +705,9 @@ final class NewSessionModel { } private func resolveDefaultDirectory(machineId: String, fallback: String) { - defaultDirectoryTask?.cancel() + cancelDefaultDirectoryResolution() + let editVersion = directoryEditVersion + let roots = selectedMachine.map(RemoteDirectoryPath.browseRoots) let recent = recentPaths(for: machineId) guard !recent.isEmpty else { return } defaultDirectoryTask = Task { [weak self] in @@ -687,7 +730,10 @@ final class NewSessionModel { }) else { return } - guard self.form.machineId == machineId, self.form.directory == fallback else { return } + guard self.selectedMachine?.id == machineId, + self.selectedMachine.map(RemoteDirectoryPath.browseRoots) == roots, + self.directoryEditVersion == editVersion, + self.form.directory == fallback else { return } self.suppressSuggestions = true self.form.directory = valid self.persistDraft() @@ -695,106 +741,22 @@ final class NewSessionModel { } } - /// Debounced directory work: parent listing for autocomplete + exists - /// probe, both riding one 250 ms debounce like the Android reference. private func scheduleDirectoryWork() { - directoryTask?.cancel() - directoryRequestVersion += 1 - let requestVersion = directoryRequestVersion - guard let machineId = form.machineId else { - suggestions = [] - return - } - directoryTask = Task { [weak self] in - try? await Task.sleep(for: Self.debounce) - guard !Task.isCancelled, let self else { return } - guard self.directoryRequestVersion == requestVersion, - self.form.machineId == machineId - else { - return - } - await self.performDirectoryWork(machineId: machineId, requestVersion: requestVersion) - } - } - - private func performDirectoryWork(machineId: String, requestVersion: Int) async { - let text = form.directory - let trimmed = form.trimmedDirectory - let api = session.api - - let query = suppressSuggestions ? nil : NewSessionLogic.parentQuery(for: text) - if let query { - let cacheKey = (machineId, query.parent) - let entries: [MachineDirectoryEntry] - if let cached = cachedListing, (cached.machineId, cached.parent) == cacheKey { - entries = cached.entries - directoryLookupError = nil - } else { - do { - let response = try await api.listMachineDirectory( - machineId: machineId, - path: query.parent - ) - guard isCurrentDirectoryRequest(requestVersion, machineId: machineId) else { return } - if response.success { - entries = response.entries ?? [] - cachedListing = (machineId, query.parent, entries) - directoryLookupError = nil - } else { - entries = [] - directoryLookupError = response.error ?? Self.msgDirectoryLookupFailed - } - } catch is CancellationError { - return - } catch { - guard isCurrentDirectoryRequest(requestVersion, machineId: machineId) else { return } - directoryLookupError = (error as? LocalizedError)?.errorDescription - ?? Self.msgDirectoryLookupFailed - entries = [] - } - } - guard isCurrentDirectoryRequest(requestVersion, machineId: machineId) else { return } - // Never suggest the path already typed verbatim. - suggestions = NewSessionLogic.buildSuggestions(query: query, entries: entries) - .filter { $0 != trimmed } - } else { - suggestions = [] - directoryLookupError = nil - } - - if !trimmed.isEmpty { - // Unknown existence (request failed): no status hint, the spawn - // re-checks anyway. - do { - let result = try await api.machinePathsExist(machineId: machineId, paths: [trimmed]) - guard isCurrentDirectoryRequest(requestVersion, machineId: machineId) else { return } - pathExistence.merge(result.exists) { _, new in new } - outsideWorkspaceRoots.remove(trimmed) - outsideWorkspaceRoots.formUnion(result.outsideWorkspaceRoots ?? []) - } catch is CancellationError { - return - } catch { - // Unknown existence: no status hint, spawn re-checks anyway. - } - } - } - - private func isCurrentDirectoryRequest(_ requestVersion: Int, machineId: String) -> Bool { - !Task.isCancelled - && directoryRequestVersion == requestVersion - && form.machineId == machineId + directoryInput.update( + machine: selectedMachine, + path: form.directory, + showSuggestions: !suppressSuggestions + ) } private func refreshAgentAvailability(force: Bool = false) { - guard let machineId = form.machineId else { + guard let machineId = selectedMachine?.id else { availabilityTask?.cancel() availabilityFetchedForMachine = nil agentAvailability = .loading return } - if !force, - availabilityFetchedForMachine == machineId, - agentAvailability != .loading { + if !force, availabilityFetchedForMachine == machineId { return } availabilityTask?.cancel() @@ -838,7 +800,7 @@ final class NewSessionModel { codexModels = .hidden return } - guard let machineId = form.machineId else { + guard let machineId = selectedMachine?.id else { codexModels = .hidden return } diff --git a/ios/Hapi/Features/NewSession/NewSessionView.swift b/ios/Hapi/Features/NewSession/NewSessionView.swift index f69b161a..708714db 100644 --- a/ios/Hapi/Features/NewSession/NewSessionView.swift +++ b/ios/Hapi/Features/NewSession/NewSessionView.swift @@ -49,6 +49,9 @@ struct NewSessionView: View { onSelect: model.selectBrowsedDirectory ) } + .onDisappear { + model.stopDirectoryWork() + } } // MARK: - Machine @@ -62,6 +65,9 @@ struct NewSessionView: View { .foregroundStyle(.secondary) } else { Picker("Machine", selection: machineBinding) { + if model.machineUnavailable, let machineId = model.form.machineId { + Text("Selected machine is offline").tag(machineId) + } ForEach(model.machines) { machine in Text(machine.label).tag(machine.id) } @@ -72,6 +78,11 @@ struct NewSessionView: View { .foregroundStyle(.secondary) } } + if model.machineUnavailable { + Text(NewSessionModel.msgMachineOffline) + .font(.footnote) + .foregroundStyle(.red) + } if let error = model.runnerSpawnError { Text("Runner last spawn error: \(error)") .font(.footnote) @@ -112,8 +123,11 @@ struct NewSessionView: View { } .buttonStyle(.borderless) .accessibilityLabel("Browse") + .disabled(model.machineUnavailable || model.form.machineId == nil) } + directoryLookupStatus + // Server-side autocomplete (list-directory on the parent path). ForEach(model.suggestions, id: \.self) { suggestion in Button { @@ -146,14 +160,52 @@ struct NewSessionView: View { } header: { Text("Directory") } footer: { - if let status = model.directoryStatus { - Text(status.message) - .foregroundStyle(status.isError ? AnyShapeStyle(.red) : AnyShapeStyle(.secondary)) + if model.directoryInput.isCheckingExistence { + Text("Checking directory…") + } else if let status = model.directoryStatus { + HStack(alignment: .firstTextBaseline) { + Text(LocalizedNoticeMapper.map(status.message)) + .foregroundStyle(status.isError ? AnyShapeStyle(.red) : AnyShapeStyle(.secondary)) + if model.directoryInput.existenceError != nil { + Button("Retry") { model.directoryInput.retry() } + } + } } } .disabled(model.isSpawning) } + @ViewBuilder + private var directoryLookupStatus: some View { + switch model.directoryInput.lookupState { + case .idle: + EmptyView() + case .loading: + HStack(spacing: 8) { + ProgressView().controlSize(.small) + Text("Searching directories…").foregroundStyle(.secondary) + } + .font(.footnote) + case .loaded: + if model.suggestions.isEmpty { + Text("No matching directories") + .font(.footnote) + .foregroundStyle(.secondary) + } + case .outsideRoots: + Text(NewSessionModel.msgDirectoryOutsideWorkspaceRoots) + .font(.footnote) + .foregroundStyle(.red) + case .failed(let error): + HStack(alignment: .firstTextBaseline) { + Text(LocalizedNoticeMapper.map(error)).foregroundStyle(.red) + Spacer() + Button("Retry") { model.directoryInput.retry() } + } + .font(.footnote) + } + } + private var directoryBrowserPresented: Binding { Binding( get: { model.directoryBrowser.isPresented }, diff --git a/ios/Hapi/Features/Pairing/ManualEntryView.swift b/ios/Hapi/Features/Pairing/ManualEntryView.swift index 7a81c431..9cf10e39 100644 --- a/ios/Hapi/Features/Pairing/ManualEntryView.swift +++ b/ios/Hapi/Features/Pairing/ManualEntryView.swift @@ -1,5 +1,4 @@ import HapiClient -import HapiProtocol import SwiftUI /// Manual pairing path for hubs without `--relay` (nothing to scan): type or @@ -8,66 +7,14 @@ import SwiftUI struct ManualEntryView: View { @Environment(\.dismiss) private var dismiss @Environment(AppModel.self) private var model - @State private var hubUrl = "" - @State private var accessToken = "" @State private var attempt = PairingAttempt() - private var canPair: Bool { - !hubUrl.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - && !accessToken.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - } - var body: some View { NavigationStack { - Form { - Section { - TextField("http://192.168.1.20:3006", text: $hubUrl) - .keyboardType(.URL) - .textContentType(.URL) - .textInputAutocapitalization(.never) - .autocorrectionDisabled() - .disabled(attempt.isPairing) - } header: { - Text("Hub URL") - } footer: { - Text("The address the hub prints at startup — a LAN address like http://192.168.1.20:3006, or the public tunnel URL when running with --relay.") - } - - Section { - TextField("Access token", text: $accessToken) - .textInputAutocapitalization(.never) - .autocorrectionDisabled() - .monospaced() - .disabled(attempt.isPairing) - } header: { - Text("Access token") - } footer: { - Text("Printed by the hub at startup, and shown in the web app under Settings → Companion Pairing. Pasting a full pairing link into either field also works.") - } - - if let failure = attempt.failure { - Section { - PairingErrorView(failure: failure) - } - } - - Section { - Button { - pairNow() - } label: { - if attempt.isPairing { - HStack(spacing: 8) { - ProgressView() - Text("Pairing…") - } - .frame(maxWidth: .infinity) - } else { - Text(attempt.failure == nil ? String(localized: "Pair") : String(localized: "Try Again")) - .frame(maxWidth: .infinity) - } - } - .disabled((!canPair && parsePastedLink() == nil) || attempt.isPairing) - } + ManualPairingFormView(isPairing: attempt.isPairing, failure: attempt.failure) { + attempt.failure = nil + } onPair: { submission in + attempt.pair(model, hubUrl: submission.hubURL, accessToken: submission.accessToken) } .navigationTitle("Enter Hub Details") .navigationBarTitleDisplayMode(.inline) @@ -76,33 +23,174 @@ struct ManualEntryView: View { Button("Cancel") { dismiss() } + .disabled(attempt.isPairing) } } .interactiveDismissDisabled(attempt.isPairing) } } +} - /// Convenience: a whole pairing link pasted into either field carries - /// both values at once. - private func parsePastedLink() -> BindLink? { - BindLink.parse(hubUrl) ?? BindLink.parse(accessToken) +/// The production form also runs without AppModel in app-hosted interaction +/// tests. Only the explicit submit action can invoke onPair. +struct ManualPairingFormView: View { + let isPairing: Bool + let failure: PairingFailure? + var onEdit: () -> Void + var onPair: (ManualPairingForm.Submission) -> Void + + @Environment(\.dynamicTypeSize) private var typeSize + @Environment(\.locale) private var locale + @State private var form = ManualPairingForm() + @State private var focusedField: ManualPairingForm.Field? = .address + + var body: some View { + Form { + Section { + let layout = typeSize.isAccessibilitySize + ? AnyLayout(VStackLayout(alignment: .leading, spacing: 0)) + : AnyLayout(HStackLayout(spacing: 12)) + layout { + Menu { + Picker("Connection protocol", selection: Binding( + get: { form.scheme }, + set: { value in + guard !isPairing else { return } + form.selectScheme(value) + onEdit() + } + )) { + ForEach(ManualPairingForm.Scheme.allCases, id: \.self) { scheme in + Text(verbatim: scheme.prefix).tag(scheme) + } + } + } label: { + HStack(spacing: 4) { + Text(verbatim: form.scheme.prefix) + Image(systemName: "chevron.down").font(.caption) + } + .fixedSize() + .frame(minHeight: 44) + } + .accessibilityLabel("Connection protocol") + .accessibilityValue(form.scheme.prefix) + .accessibilityIdentifier("pairing.scheme") + .disabled(isPairing) + + input(.address) + } + inputError(for: .address) + } header: { + Text("Hub URL") + } footer: { + VStack(alignment: .leading, spacing: 8) { + Text("Enter your hub address without the protocol, or paste a full URL or pairing link.") + if form.scheme == .http { + Label("HTTP is unencrypted and may be restricted by iOS. HTTPS is recommended.", systemImage: "exclamationmark.triangle") + } + } + } + + Section { + input(.accessToken) + inputError(for: .accessToken) + } header: { + Text("Access token") + } footer: { + Text("Printed by the hub at startup, or available in web Settings → Companion Pairing. You can also paste a pairing link here.") + } + + if form.didImportLink { + Section { + Label("Pairing details filled in. Review them, then tap Pair.", systemImage: "checkmark.circle") + .foregroundStyle(.secondary) + .accessibilityIdentifier("pairing.imported") + } + } + + if let failure { + Section { PairingErrorView(failure: failure) } + } + + Section { + Button(action: pairNow) { + if isPairing { + HStack(spacing: 8) { + ProgressView() + .progressViewStyle(.circular) + Text("Pairing…") + } + .frame(maxWidth: .infinity) + } else { + Text(failure == nil ? LocalizedStringKey("Pair") : LocalizedStringKey("Try Again")) + .frame(maxWidth: .infinity) + } + } + .accessibilityIdentifier("pairing.submit") + .disabled(form.submission == nil || isPairing) + } + } + } + + private func input(_ field: ManualPairingForm.Field) -> some View { + PairingTextField( + text: Binding(get: { form.text(for: field) }, set: { value in + guard !isPairing else { return } + form.edit(value, in: field) + onEdit() + }), + focusedField: $focusedField, + field: field, + placeholder: field == .address + ? String(localized: LocalizedStringResource("Domain or IP address", locale: locale)) + : String(localized: LocalizedStringResource("Access token", locale: locale)), + accessibilityLabel: field == .address + ? String(localized: LocalizedStringResource("Hub URL", locale: locale)) + : String(localized: LocalizedStringResource("Access token", locale: locale)), + isEnabled: !isPairing, + onPaste: { raw in + guard !isPairing else { return false } + let handled = form.paste(raw, into: field) + if handled { onEdit() } + return handled + }, + onEndEditing: { + guard !isPairing else { return } + form.finishEditing(field) + }, + onReturn: { + guard !isPairing else { return } + if field == .address { + form.finishEditing(field) + focusedField = .accessToken + } else { + pairNow() + } + } + ) + } + + @ViewBuilder + private func inputError(for field: ManualPairingForm.Field) -> some View { + if let error = form.error(for: field) { + let message: LocalizedStringKey = switch error { + case .invalidAddress: "Enter a valid hub domain or IP address, with an optional port." + case .invalidLink: "This pairing link is invalid or incomplete. Copy the full link from your hub." + case .missingToken: "Enter the access token printed by your hub." + } + Label(message, systemImage: "exclamationmark.circle") + .font(.footnote) + .foregroundStyle(.red) + .accessibilityIdentifier(field == .address ? "pairing.addressError" : "pairing.tokenError") + } } private func pairNow() { - if let link = parsePastedLink() { - attempt.pair(model, hubUrl: link.hubUrl, accessToken: link.accessToken) - return - } - var address = hubUrl.trimmingCharacters(in: .whitespacesAndNewlines) - // Typing the scheme on a phone is annoying; local hubs serve plain - // HTTP. - if !address.isEmpty, !address.contains("://") { - address = "http://\(address)" - } - attempt.pair( - model, - hubUrl: address, - accessToken: accessToken.trimmingCharacters(in: .whitespacesAndNewlines) - ) + guard !isPairing else { return } + form.finishEditing(.address) + form.finishEditing(.accessToken) + guard let submission = form.submission else { return } + focusedField = nil + onPair(submission) } } diff --git a/ios/Hapi/Features/Pairing/ManualPairingForm.swift b/ios/Hapi/Features/Pairing/ManualPairingForm.swift new file mode 100644 index 00000000..4e98ee41 --- /dev/null +++ b/ios/Hapi/Features/Pairing/ManualPairingForm.swift @@ -0,0 +1,142 @@ +import Foundation +import HapiClient +import HapiProtocol + +/// UI-only input policy. The service still receives an absolute origin and +/// an opaque token; no clipboard access or networking happens in this model. +struct ManualPairingForm { + enum Field: Hashable { + case address, accessToken + } + + enum Scheme: String, CaseIterable { + case https, http + + var prefix: String { "\(rawValue)://" } + } + + enum InputError: Equatable { + case invalidAddress, invalidLink, missingToken + } + + struct Submission: Equatable { + let hubURL: String + let accessToken: String + } + + private(set) var scheme: Scheme = .https + private(set) var address = "" + private(set) var accessToken = "" + private(set) var didImportLink = false + private var validatedFields: Set = [] + + var submission: Submission? { + guard validationError(for: .address) == nil, + validationError(for: .accessToken) == nil, + let origin = normalizedAddress(address) else { return nil } + return Submission(hubURL: origin, accessToken: trimmed(accessToken)) + } + + func text(for field: Field) -> String { + field == .address ? address : accessToken + } + + func error(for field: Field) -> InputError? { + validatedFields.contains(field) ? validationError(for: field) : nil + } + + mutating func edit(_ text: String, in field: Field) { + if field == .address { address = text } else { accessToken = text } + didImportLink = false + } + + mutating func selectScheme(_ value: Scheme) { + // First consume a manually typed explicit scheme, then honor the menu + // choice. Otherwise an old "https://" in the draft could override it. + if !trimmed(address).isEmpty { finishEditing(.address) } + scheme = value + didImportLink = false + } + + /// Returns true only when the entire paste replaces a field (or the form). + /// Ordinary text is left to the text control's selection/insertion rules. + @discardableResult + mutating func paste(_ raw: String, into field: Field) -> Bool { + if Self.looksLikePairingLink(raw) { + edit(raw, in: field) + finishEditing(field) + return true + } + if field == .address, raw.contains("://") { + edit(raw, in: field) + finishEditing(field) + return true + } + return false + } + + mutating func finishEditing(_ field: Field) { + let raw = trimmed(text(for: field)) + validatedFields.insert(field) + if Self.looksLikePairingLink(raw) { + guard raw.removingPercentEncoding != nil, + let link = BindLink.parse(raw), + let origin = normalizedAddress(link.hubUrl) else { return } + applyOrigin(origin) + accessToken = trimmed(link.accessToken) + didImportLink = true + validatedFields = [.address, .accessToken] + } else if field == .address { + if let origin = normalizedAddress(raw) { applyOrigin(origin) } + } else { + accessToken = raw + } + } + + private func validationError(for field: Field) -> InputError? { + let raw = trimmed(text(for: field)) + // Never fall back to the web frontend origin for a broken pairing + // link, or send a pasted link verbatim as an access token. + if Self.looksLikePairingLink(raw) { return .invalidLink } + if field == .address { + return normalizedAddress(raw) == nil ? .invalidAddress : nil + } + return raw.isEmpty ? .missingToken : nil + } + + private func normalizedAddress(_ raw: String) -> String? { + let value = trimmed(raw) + guard !value.isEmpty, !value.contains(where: \.isWhitespace), + value.removingPercentEncoding != nil else { return nil } + let absolute = value.contains("://") ? value : scheme.prefix + value + guard let components = URLComponents(string: absolute), + components.user == nil, components.password == nil, + let host = components.host, !host.isEmpty, + !host.contains(where: \.isWhitespace) else { return nil } + if let port = components.port, !(1...65535).contains(port) { return nil } + return HubURLNormalization.normalize(absolute) + } + + private mutating func applyOrigin(_ origin: String) { + // Origins come exclusively from HubURLNormalization (http or https). + scheme = origin.hasPrefix(Scheme.http.prefix) ? .http : .https + address = String(origin.dropFirst(scheme.prefix.count)) + } + + private static func looksLikePairingLink(_ raw: String) -> Bool { + let value = raw.trimmingCharacters(in: .whitespacesAndNewlines) + if value.lowercased().hasPrefix("hapicompanion:") { return true } + guard value.contains("://") else { return false } + guard let queryStart = value.firstIndex(of: "?") else { return false } + let query = value[value.index(after: queryStart)...].prefix { $0 != "#" } + return query.split(separator: "&").contains { item in + let key = item.prefix { $0 != "=" } + let decoded = String(key).replacingOccurrences(of: "+", with: " ").removingPercentEncoding + return decoded == "hub" || decoded == "token" + } + } + + private func trimmed(_ value: String) -> String { + value.trimmingCharacters(in: .whitespacesAndNewlines) + } +} diff --git a/ios/Hapi/Features/Pairing/PairingConfirmView.swift b/ios/Hapi/Features/Pairing/PairingConfirmView.swift index 9179242e..62399272 100644 --- a/ios/Hapi/Features/Pairing/PairingConfirmView.swift +++ b/ios/Hapi/Features/Pairing/PairingConfirmView.swift @@ -111,7 +111,7 @@ struct PairingErrorView: View { private var message: String { switch failure { case .invalidHubURL: - String(localized: "Enter the hub's full address, e.g. http://192.168.1.20:3006.") + String(localized: "Check the hub address. HTTPS is recommended, for example https://hub.example.com.") case .unreachable: String(localized: "No HAPI hub answered at this address. Check that the hub is running and that this device can reach it (same network, or the relay tunnel is up).") case .protocolMismatch(let hubVersion, let supportedVersion): diff --git a/ios/Hapi/Features/Pairing/PairingFlowView.swift b/ios/Hapi/Features/Pairing/PairingFlowView.swift index 5a0a916a..3e5e0742 100644 --- a/ios/Hapi/Features/Pairing/PairingFlowView.swift +++ b/ios/Hapi/Features/Pairing/PairingFlowView.swift @@ -20,7 +20,7 @@ struct PairingFlowView: View { @State private var showScanner = false @State private var showManualEntry = false - private static let docsURL = URL(string: "https://app.hapi.run/docs/") + private static let docsURL = URL(string: "https://hapi.run/docs/guide/quick-start") var body: some View { NavigationStack { diff --git a/ios/Hapi/Features/Pairing/PairingTextField.swift b/ios/Hapi/Features/Pairing/PairingTextField.swift new file mode 100644 index 00000000..6183e92c --- /dev/null +++ b/ios/Hapi/Features/Pairing/PairingTextField.swift @@ -0,0 +1,144 @@ +import SwiftUI +import UIKit + +/// A narrow bridge for this form: distinguish a user-initiated system paste +/// from typing, without inspecting UIPasteboard or rewriting each keystroke. +struct PairingTextField: UIViewRepresentable { + @Binding var text: String + @Binding var focusedField: ManualPairingForm.Field? + let field: ManualPairingForm.Field + let placeholder: String + let accessibilityLabel: String + let isEnabled: Bool + var onPaste: (String) -> Bool + var onEndEditing: () -> Void + var onReturn: () -> Void + + @ScaledMetric(relativeTo: .body) private var fontSize = 17 + + func makeCoordinator() -> Coordinator { Coordinator(self) } + + func makeUIView(context: Context) -> NativeField { + let view = NativeField() + view.delegate = context.coordinator + view.pasteDelegate = context.coordinator + view.addTarget(context.coordinator, action: #selector(Coordinator.changed(_:)), for: .editingChanged) + view.autocapitalizationType = .none + view.autocorrectionType = .no + view.spellCheckingType = .no + view.smartQuotesType = .no + view.smartDashesType = .no + view.clearButtonMode = .whileEditing + view.setContentHuggingPriority(.defaultLow, for: .horizontal) + view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + return view + } + + func updateUIView(_ view: NativeField, context: Context) { + context.coordinator.owner = self + // Avoid resetting the selection/marked text on ordinary keystrokes. + if view.text != text { view.text = text } + view.placeholder = placeholder + view.accessibilityLabel = accessibilityLabel + view.accessibilityIdentifier = field == .address ? "pairing.address" : "pairing.accessToken" + view.font = field == .address + ? .systemFont(ofSize: fontSize) + : .monospacedSystemFont(ofSize: fontSize, weight: .regular) + view.keyboardType = field == .address ? .URL : .default + view.textContentType = field == .address ? .URL : nil + view.returnKeyType = field == .address ? .next : .go + view.allowsEditing = isEnabled + view.wantsFocus = focusedField == field && isEnabled + view.updateFocus() + } + + func sizeThatFits(_ proposal: ProposedViewSize, uiView: NativeField, context: Context) -> CGSize? { + CGSize(width: proposal.width ?? max(0, uiView.intrinsicContentSize.width), + height: max(44, uiView.intrinsicContentSize.height)) + } + + static func dismantleUIView(_ uiView: NativeField, coordinator: Coordinator) { + uiView.wantsFocus = false + uiView.delegate = nil + uiView.pasteDelegate = nil + } + + final class NativeField: UITextField { + var wantsFocus = false + var allowsEditing = true + + override func didMoveToWindow() { + super.didMoveToWindow() + updateFocus() + } + + func updateFocus() { + // Disabling/focusing a field can trigger UIKit layout and editing + // callbacks. Do that outside SwiftUI's updateUIView transaction. + DispatchQueue.main.async { [weak self] in + guard let self else { return } + if isEnabled != allowsEditing { isEnabled = allowsEditing } + if wantsFocus, isEnabled, window != nil, !isFirstResponder { + becomeFirstResponder() + } else if !wantsFocus, isFirstResponder { + resignFirstResponder() + } + } + } + } + + final class Coordinator: NSObject, UITextFieldDelegate, UITextPasteDelegate { + var owner: PairingTextField + + init(_ owner: PairingTextField) { self.owner = owner } + + @objc func changed(_ textField: UITextField) { + guard owner.isEnabled else { return } + owner.text = textField.text ?? "" + } + + func textFieldDidBeginEditing(_ textField: UITextField) { + if owner.focusedField != owner.field { owner.focusedField = owner.field } + } + + func textFieldDidEndEditing(_ textField: UITextField) { + // Disabling a focused UITextField can synchronously end editing + // inside updateUIView. Don't mutate SwiftUI state in that callback. + guard owner.isEnabled else { return } + if owner.focusedField == owner.field { owner.focusedField = nil } + owner.onEndEditing() + } + + func textFieldShouldReturn(_ textField: UITextField) -> Bool { + if owner.isEnabled { owner.onReturn() } + return false + } + + func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { + owner.isEnabled + } + + func textFieldShouldClear(_ textField: UITextField) -> Bool { + owner.isEnabled + } + + func textPasteConfigurationSupporting( + _ textPasteConfigurationSupporting: any UITextPasteConfigurationSupporting, + performPasteOf attributedString: NSAttributedString, + to textRange: UITextRange + ) -> UITextRange { + guard owner.isEnabled, + let textField = textPasteConfigurationSupporting as? UITextField, + textField.isEnabled else { return textRange } + if owner.onPaste(attributedString.string) { + textField.text = owner.text + textField.selectedTextRange = textField.textRange(from: textField.endOfDocument, to: textField.endOfDocument) + } else { + // Honor the system's replacement range for ordinary text. + textField.replace(textRange, withText: attributedString.string.trimmingCharacters(in: .whitespacesAndNewlines)) + changed(textField) + } + return textField.selectedTextRange ?? textRange + } + } +} diff --git a/ios/Hapi/Features/Scratchlist/ScratchlistDismissGuard.swift b/ios/Hapi/Features/Scratchlist/ScratchlistDismissGuard.swift new file mode 100644 index 00000000..9d9ab0b3 --- /dev/null +++ b/ios/Hapi/Features/Scratchlist/ScratchlistDismissGuard.swift @@ -0,0 +1,45 @@ +import SwiftUI +import UIKit + +/// SwiftUI's interactiveDismissDisabled blocks the gesture silently. Forward +/// presentation callbacks while offering the same discard choice as Cancel. +struct ScratchlistDismissGuard: UIViewControllerRepresentable { + let blocked: Bool + let onAttempt: () -> Void + + func makeCoordinator() -> Coordinator { Coordinator() } + func makeUIViewController(context: Context) -> UIViewController { UIViewController() } + func updateUIViewController(_ controller: UIViewController, context: Context) { + context.coordinator.blocked = blocked + context.coordinator.onAttempt = onAttempt + DispatchQueue.main.async { [weak controller, coordinator = context.coordinator] in + guard var root = controller else { return } + while let parent = root.parent { root = parent } + guard let presentation = root.presentationController else { return } + if presentation.delegate !== coordinator { + coordinator.previous = presentation.delegate + presentation.delegate = coordinator + } + } + } + + final class Coordinator: NSObject, UIAdaptivePresentationControllerDelegate { + var blocked = false + var onAttempt: (() -> Void)? + weak var previous: (any UIAdaptivePresentationControllerDelegate)? + + func presentationControllerShouldDismiss(_ controller: UIPresentationController) -> Bool { + !blocked && (previous?.presentationControllerShouldDismiss?(controller) ?? true) + } + func presentationControllerDidAttemptToDismiss(_ controller: UIPresentationController) { + if blocked { onAttempt?() } + else { previous?.presentationControllerDidAttemptToDismiss?(controller) } + } + func presentationControllerWillDismiss(_ controller: UIPresentationController) { + previous?.presentationControllerWillDismiss?(controller) + } + func presentationControllerDidDismiss(_ controller: UIPresentationController) { + previous?.presentationControllerDidDismiss?(controller) + } + } +} diff --git a/ios/Hapi/Features/Scratchlist/ScratchlistDrawerView.swift b/ios/Hapi/Features/Scratchlist/ScratchlistDrawerView.swift new file mode 100644 index 00000000..9b1ffc95 --- /dev/null +++ b/ios/Hapi/Features/Scratchlist/ScratchlistDrawerView.swift @@ -0,0 +1,77 @@ +import HapiClient +import HapiProtocol +import HapiUI +import SwiftUI + +/// One recent draft while browsing; just a header while typing. +struct ScratchlistDrawerView: View { + @State private var model: ScratchlistScreenModel + let interactor: ChatInteractor + let keyboardFocused: Bool + let onOpen: (ScratchlistEntry?, Bool) -> Void + @Environment(\.dynamicTypeSize) private var dynamicTypeSize + + init(store: any SessionScratchlistStoring, sessionId: String, interactor: ChatInteractor, + keyboardFocused: Bool, onOpen: @escaping (ScratchlistEntry?, Bool) -> Void) { + _model = State(initialValue: ScratchlistScreenModel(sessionId: sessionId, store: store)) + self.interactor = interactor + self.keyboardFocused = keyboardFocused + self.onOpen = onOpen + } + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + header + if model.state.loadFailed || model.state.refreshFailed { + ScratchlistErrorBanner(message: String(localized: model.state.loadFailed + ? "Couldn't load the scratchlist" : "Couldn't refresh — showing saved drafts")) { model.retry() } + } + if !keyboardFocused, !dynamicTypeSize.isAccessibilitySize, let entry = model.state.entries.first { + ScratchlistEntryRow(entry: entry, interactor: interactor, + onOpen: { onOpen(entry, false) }, onEdit: { onOpen(entry, true) }, + onDelete: { model.deleteEntry(entry.entryId) }, compact: true) + .padding(.bottom, 8) + .accessibilityIdentifier("scratchlist.recent") + } + Divider() + } + .padding(.horizontal, 12) + .padding(.top, 4) + .accessibilityIdentifier("scratchlist.drawer") + .onAppear { model.start() } + .onDisappear { model.stop() } + } + + private var header: some View { + HStack(spacing: 0) { + Button { onOpen(nil, false) } label: { + HStack(spacing: 6) { + Text("Scratchlist").font(.subheadline.weight(.semibold)) + if model.isLoading { + ProgressView().controlSize(.small) + } else if model.state.loaded { + Text(verbatim: "· \(model.state.entries.count)") + .font(.subheadline).foregroundStyle(.secondary) + } + Image(systemName: "chevron.right") + .font(.caption.weight(.semibold)).foregroundStyle(.secondary) + Spacer(minLength: 0) + } + .frame(minHeight: 44) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityHint("View all") + .accessibilityIdentifier("scratchlist.open") + Button { interactor.setComposerDestination(.chat) } label: { + Image(systemName: "xmark") + .font(.system(size: 15, weight: .medium)).foregroundStyle(.secondary) + .frame(width: 44, height: 44).contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("Back to chat") + .accessibilityIdentifier("scratchlist.close") + .disabled(interactor.scratchlistBusy || interactor.isSending) + } + } +} diff --git a/ios/Hapi/Features/Scratchlist/ScratchlistScreenModel.swift b/ios/Hapi/Features/Scratchlist/ScratchlistScreenModel.swift index cc8e9bd4..c49ccd00 100644 --- a/ios/Hapi/Features/Scratchlist/ScratchlistScreenModel.swift +++ b/ios/Hapi/Features/Scratchlist/ScratchlistScreenModel.swift @@ -3,57 +3,51 @@ import HapiClient import HapiProtocol import Observation import PhotosUI -// PhotosPickerItem lives in the `_PhotosUI_SwiftUI` cross-import overlay: -// it is only visible when SwiftUI is imported alongside PhotosUI. import SwiftUI import UniformTypeIdentifiers -/// Edit-sheet model; `entryId == nil` = drafting a brand-new entry. -struct ScratchlistEditorState: Equatable { +struct ScratchlistEditorState: Equatable, Identifiable { + let id = UUID() var entryId: String? var text = "" var attachments: [ScratchlistAttachment] = [] - /// A picked file is importing/uploading — spinner tile in the strip. + var originalText = "" + var originalAttachments: [ScratchlistAttachment] = [] + var uploaded: [ScratchlistAttachment] = [] var isUploading = false + var isSaving = false + var error: String? + var saveFailed = false + var failedUploadName: String? + + var isDirty: Bool { text != originalText || attachments != originalAttachments || isUploading || failedUploadName != nil } + var canSave: Bool { + !isUploading && !isSaving && failedUploadName == nil && text.utf16.count <= ScratchlistCaps.maxTextLength + && (!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachments.isEmpty) + } } -/// Per-session scratchlist workbench (A-M4b) — the iOS port of the Android -/// `ScratchlistViewModel`: the entries list rides -/// ``SessionScratchlistStoring``'s per-session cache (optimistic CRUD + -/// SSE-triggered refetch handled there); this model owns the edit-sheet draft -/// state and the attachment import→upload flow. -/// -/// Attachment writes: on an **existing** entry every strip change persists -/// immediately (upload → `PUT {attachments}` / remove → PUT minus the file, -/// then a best-effort attachment delete to free session bytes). On a **new** -/// entry uploads accumulate locally and travel with the create; dismissing -/// the draft best-effort deletes the now-orphaned uploads. +/// Transactional editor: text and attachment membership commit together. +/// Each opening has an identity, so a late upload cannot attach to a new editor. @MainActor @Observable final class ScratchlistScreenModel { let sessionId: String @ObservationIgnored private let store: any SessionScratchlistStoring - - /// Non-nil while the edit sheet is open. private(set) var editor: ScratchlistEditorState? - /// Transient failure/notice toast (the Android snackbar analogue). private(set) var notice: String? - @ObservationIgnored private var noticeTask: Task? + private(set) var deletingEntryId: String? @ObservationIgnored private var opened = false + @ObservationIgnored private var createId: String? + @ObservationIgnored private var retryUpload: PreparedAttachment? init(sessionId: String, store: any SessionScratchlistStoring) { self.sessionId = sessionId self.store = store } - // MARK: - List state (from the store) - var state: ScratchlistSessionState { store.state(sessionId) } - - /// First fetch still running, nothing cached yet. var isLoading: Bool { !state.loaded && !state.loadFailed } - // MARK: - Lifecycle (paired with the screen's appear/disappear) - func start() { guard !opened else { return } opened = true @@ -63,231 +57,190 @@ final class ScratchlistScreenModel { func stop() { guard opened else { return } opened = false - noticeTask?.cancel() store.release(sessionId) } - /// Error-state retry. - func retry() { - Task { [self] in - try? await store.refresh(sessionId) - } - } + func refresh() async { try? await store.refresh(sessionId) } + func retry() { Task { await refresh() } } + func clearNotice() { notice = nil } - // MARK: - Editor - - /// Card tap (existing) or the new-note button (`entry == nil`, new draft). func openEditor(_ entry: ScratchlistEntry?) { + guard editor == nil else { return } if entry == nil, state.atCap { - showNotice(String(localized: "Scratchlist is full (200 entries) — delete one first")) + notice = String(localized: "Scratchlist is full (200 entries)") return } - if let entry { - editor = ScratchlistEditorState( - entryId: entry.entryId, - text: entry.text, - attachments: entry.attachments - ) - } else { - editor = ScratchlistEditorState() - } + createId = "scratch-\(UUID().uuidString)" + editor = ScratchlistEditorState(entryId: entry?.entryId, text: entry?.text ?? "", + attachments: entry?.attachments ?? [], originalText: entry?.text ?? "", + originalAttachments: entry?.attachments ?? []) } - /// Sheet dismissed without saving; orphaned new-draft uploads are freed. func dismissEditor() { - guard let editor else { return } - self.editor = nil - if editor.entryId == nil, !editor.attachments.isEmpty { - Task { [self] in - for attachment in editor.attachments { - _ = await store.deleteAttachment(sessionId: sessionId, attachmentId: attachment.id) - } - } - } + guard let draft = editor, !draft.isSaving else { return } + editor = nil + createId = nil + retryUpload = nil + cleanup(draft.uploaded) } func setEditorText(_ text: String) { + guard editor?.isSaving == false else { return } editor?.text = text } - /// Save closes the sheet immediately (mutations are store-optimistic and - /// roll back with a notice on failure — web parity). + func reportEditorError(_ message: String) { + editor?.error = message + editor?.saveFailed = false + } + + var editorErrorIsRetryable: Bool { retryUpload != nil || editor?.saveFailed == true } + + func retryEditorOperation() { + if let prepared = retryUpload, let draft = editor, !draft.isUploading, !draft.isSaving { + editor?.isUploading = true + editor?.error = nil + Task { await uploadPrepared(prepared, draftId: draft.id) } + } else if editor?.saveFailed == true { saveEditor() } + else { editor?.error = nil } + } + + func removeFailedUpload() { + guard editor?.isUploading == false else { return } + retryUpload = nil + editor?.failedUploadName = nil + editor?.error = nil + } + func saveEditor() { - guard let editor else { return } - let text = editor.text.trimmingCharacters(in: .whitespacesAndNewlines) - if text.isEmpty, editor.attachments.isEmpty { - // Nothing to keep: a new draft just closes; an existing entry - // must keep text or attachments (hub 400s empty updates). - if editor.entryId == nil { - self.editor = nil + guard let draft = editor, draft.canSave else { return } + editor?.isSaving = true + editor?.error = nil + editor?.saveFailed = false + let createId = createId + Task { + let saved: Bool + let text = draft.text.trimmingCharacters(in: .whitespacesAndNewlines) + if let entryId = draft.entryId { + saved = await store.updateEntry(sessionId: sessionId, entryId: entryId, text: text, attachments: draft.attachments) } else { - showNotice("A note needs text or an attachment — use Delete to remove it") - } - return - } - self.editor = nil - Task { [self] in - if let entryId = editor.entryId { - let updated = await store.updateEntry( - sessionId: sessionId, - entryId: entryId, - text: text, - attachments: nil - ) - if !updated { - showNotice(String(localized: "Couldn't save the note — check the hub connection")) - } - } else { - switch await store.createEntry(sessionId: sessionId, text: text, attachments: editor.attachments) { - case .created: - break + switch await store.createEntry(sessionId: sessionId, text: text, attachments: draft.attachments, entryId: createId) { + case .created: saved = true case .atCap: - showNotice(String(localized: "Scratchlist is full (200 entries)")) - case .failed: - showNotice(String(localized: "Couldn't save the note — check the hub connection")) + saved = false + editor?.error = String(localized: "Scratchlist is full (200 entries)") + case .failed: saved = false + } + } + guard editor?.id == draft.id else { return } + if saved { + editor = nil + self.createId = nil + retryUpload = nil + let retained = Set(draft.attachments.map(\.id)) + cleanup((draft.originalAttachments + draft.uploaded).filter { !retained.contains($0.id) }) + } else { + editor?.isSaving = false + editor?.saveFailed = true + if editor?.error == nil { + editor?.error = String(localized: "Couldn't save the draft — your changes are kept here") } } } } - /// Sheet delete; optimistic with store rollback. func deleteEntry(_ entryId: String) { - if editor?.entryId == entryId { - editor = nil - } - Task { [self] in - let deleted = await store.deleteEntry(sessionId: sessionId, entryId: entryId) - if !deleted { - showNotice(String(localized: "Couldn't delete the note — check the hub connection")) + guard deletingEntryId == nil else { return } + deletingEntryId = entryId + notice = nil + Task { + defer { deletingEntryId = nil } + if !(await store.deleteEntry(sessionId: sessionId, entryId: entryId)) { + notice = String(localized: "Couldn't delete the note — check the hub connection") } } } - // MARK: - Attachments - - /// Photo-picker result → guard/downscale → upload → strip (and PUT for - /// existing entries). func addAttachment(_ item: PhotosPickerItem) { - guard let current = editor, !current.isUploading else { return } + guard let draft = editor, !draft.isUploading, !draft.isSaving, draft.failedUploadName == nil else { return } editor?.isUploading = true - Task { [weak self] in - guard let self else { return } - defer { self.editor?.isUploading = false } - let limits = await self.store.limits(sessionId: self.sessionId) - guard let existing = self.editor?.attachments else { return } + editor?.error = nil + Task { guard let data = try? await item.loadTransferable(type: Data.self), !data.isEmpty else { - self.showNotice(String(localized: "Couldn't read the selected photo")) + finishImport(id: draft.id, error: String(localized: "Couldn't read the selected photo")) return } - let contentType = item.supportedContentTypes.first - let mimeType = contentType?.preferredMIMEType ?? "application/octet-stream" - let filename = Self.pickedFilename(for: contentType) - // Guard + downscale are CPU work — keep them off the main actor. - let outcome = await Task.detached(priority: .userInitiated) { - ScratchlistAttachmentImport.prepare( - data: data, - filename: filename, - mimeType: mimeType, - existing: existing, - limits: limits - ) - }.value - switch outcome { - case .rejected(let message): - self.showNotice(message) - case .ready(let prepared): - let uploaded = await self.store.uploadAttachment( - sessionId: self.sessionId, - filename: prepared.filename, - data: prepared.data, - mimeType: prepared.mimeType - ) - switch uploaded { - case .failed(_, let code): - self.showNotice(Self.uploadFailureMessage(code: code)) - case .uploaded(let attachment): - await self.attachToEditor(attachment) - } + let type = item.supportedContentTypes.first + await importAttachment(data: data, filename: "photo-\(UUID().uuidString).\(type?.preferredFilenameExtension ?? "jpg")", + mimeType: type?.preferredMIMEType ?? "image/jpeg", draft: draft) + } + } + + func addPreparedAttachment(_ attachment: PreparedAttachment) { + guard let draft = editor, !draft.isUploading, !draft.isSaving, draft.failedUploadName == nil else { return } + editor?.isUploading = true + editor?.error = nil + Task { + await importAttachment(data: attachment.bytes, filename: attachment.filename, mimeType: attachment.mimeType, draft: draft) + } + } + + private func importAttachment(data: Data, filename: String, mimeType: String, draft: ScratchlistEditorState) async { + let limits = await store.limits(sessionId: sessionId) + guard editor?.id == draft.id else { return } + let outcome = await Task.detached(priority: .userInitiated) { + ScratchlistAttachmentImport.prepare(data: data, filename: filename, mimeType: mimeType, + existing: draft.attachments, limits: limits) + }.value + guard editor?.id == draft.id else { return } + switch outcome { + case .rejected(let message): finishImport(id: draft.id, error: message) + case .ready(let prepared): + await uploadPrepared(PreparedAttachment(filename: prepared.filename, mimeType: prepared.mimeType, bytes: prepared.data), draftId: draft.id) + } + } + + private func uploadPrepared(_ prepared: PreparedAttachment, draftId: UUID) async { + let result = await store.uploadAttachment(sessionId: sessionId, filename: prepared.filename, + data: prepared.bytes, mimeType: prepared.mimeType) + switch result { + case .uploaded(let attachment): + guard editor?.id == draftId else { + cleanup([attachment]) + return } + retryUpload = nil + editor?.failedUploadName = nil + editor?.attachments.append(attachment) + editor?.uploaded.append(attachment) + finishImport(id: draftId, error: nil) + case .failed: + guard editor?.id == draftId else { return } + retryUpload = prepared + editor?.failedUploadName = prepared.filename + finishImport(id: draftId, error: String(localized: "Upload failed — check the hub connection")) } } - private func attachToEditor(_ attachment: ScratchlistAttachment) async { - guard let editor else { - // Sheet closed mid-upload: don't leak the stored file. - _ = await store.deleteAttachment(sessionId: sessionId, attachmentId: attachment.id) - return - } - let next = editor.attachments + [attachment] - self.editor?.attachments = next - if let entryId = editor.entryId { - let updated = await store.updateEntry( - sessionId: sessionId, - entryId: entryId, - text: nil, - attachments: next - ) - if !updated { - rollbackEditorAttachments(entryId: entryId, to: editor.attachments) - _ = await store.deleteAttachment(sessionId: sessionId, attachmentId: attachment.id) - showNotice(String(localized: "Couldn't attach the file — check the hub connection")) - } - } + private func finishImport(id: UUID, error: String?) { + guard editor?.id == id else { return } + editor?.isUploading = false + editor?.error = error + editor?.saveFailed = false } - /// Restore the strip to `attachments` if the sheet still edits `entryId`. - private func rollbackEditorAttachments(entryId: String, to attachments: [ScratchlistAttachment]) { - guard editor?.entryId == entryId else { return } - editor?.attachments = attachments - } - - /// Strip ✕: detach (existing entries PUT immediately) and free the stored file. func removeAttachment(_ attachment: ScratchlistAttachment) { - guard let editor else { return } - let next = editor.attachments.filter { $0.id != attachment.id } - guard next.count != editor.attachments.count else { return } - self.editor?.attachments = next - Task { [self] in - if let entryId = editor.entryId { - let updated = await store.updateEntry( - sessionId: sessionId, - entryId: entryId, - text: nil, - attachments: next - ) - if !updated { - rollbackEditorAttachments(entryId: entryId, to: editor.attachments) - showNotice(String(localized: "Couldn't remove the attachment — check the hub connection")) - return - } + guard editor?.isSaving == false, editor?.isUploading == false else { return } + editor?.attachments.removeAll { $0.id == attachment.id } + // Even local uploads wait for Save/Cancel cleanup; a failed Save is retryable. + } + + private func cleanup(_ attachments: [ScratchlistAttachment]) { + guard !attachments.isEmpty else { return } + Task { + for attachment in attachments { + _ = await store.deleteAttachment(sessionId: sessionId, attachmentId: attachment.id) } - // Best-effort byte-budget cleanup; InUse just means another entry - // still references the file (fine to leave). - _ = await store.deleteAttachment(sessionId: sessionId, attachmentId: attachment.id) - } - } - - // MARK: - Internals - - private static func uploadFailureMessage(code: String?) -> String { - code == ScratchlistErrorCode.attachmentTooLarge - ? String(localized: "That file is over the hub's per-file size limit") - : String(localized: "Upload failed — check the hub connection") - } - - private static func pickedFilename(for contentType: UTType?) -> String { - let stamp = Int(Date().timeIntervalSince1970 * 1000) - let ext = contentType?.preferredFilenameExtension ?? "bin" - return "photo-\(stamp).\(ext)" - } - - private func showNotice(_ message: String) { - notice = message - noticeTask?.cancel() - noticeTask = Task { [weak self] in - try? await Task.sleep(for: .seconds(4)) - guard !Task.isCancelled else { return } - self?.notice = nil } } } diff --git a/ios/Hapi/Features/Scratchlist/ScratchlistView.swift b/ios/Hapi/Features/Scratchlist/ScratchlistView.swift index 7d5e7dfc..92f3dfa7 100644 --- a/ios/Hapi/Features/Scratchlist/ScratchlistView.swift +++ b/ios/Hapi/Features/Scratchlist/ScratchlistView.swift @@ -1,322 +1,477 @@ import HapiClient import HapiProtocol +import HapiUI import PhotosUI import SwiftUI -/// Per-session scratchlist workbench (A-M4b): notes/drafts parked until the -/// operator promotes them — presented as a sheet off the chat toolbar's note -/// icon. Entry cards (text preview, age, attachment thumbs) open an edit -/// sheet; the toolbar + drafts a new note; "To composer" inserts an entry's -/// text into the chat composer and closes the sheet. -/// -/// Placement divergence from Android (deliberate, A-M3f owns the composer -/// UI): "Park current draft" lives in this screen's header instead of the -/// composer bar. The seam itself (`ChatInteractor.parkComposerDraft`) matches -/// Android — the composer clears only after the hub accepts, and an at-cap or -/// failed park keeps the draft. +/// Full inventory and a single navigation stack for reading/editing drafts. struct ScratchlistView: View { @State private var model: ScratchlistScreenModel private let attachments: ScratchlistAttachmentLoader private let interactor: ChatInteractor? - + private let initialEntry: ScratchlistEntry? + private let initiallyEditing: Bool @Environment(\.dismiss) private var dismiss + @State private var query = "" + @State private var path: [String] = [] @State private var viewerAttachment: ScratchlistAttachment? + @State private var discardAndClose = false - init( - store: ScratchlistStore, - sessionId: String, - attachments: ScratchlistAttachmentLoader, - interactor: ChatInteractor? = nil - ) { + init(store: any SessionScratchlistStoring, sessionId: String, attachments: ScratchlistAttachmentLoader, + interactor: ChatInteractor? = nil, initialEntry: ScratchlistEntry? = nil, initiallyEditing: Bool = false) { _model = State(initialValue: ScratchlistScreenModel(sessionId: sessionId, store: store)) self.attachments = attachments self.interactor = interactor + self.initialEntry = initialEntry + self.initiallyEditing = initiallyEditing + } + + private var entries: [ScratchlistEntry] { + let query = query.trimmingCharacters(in: .whitespacesAndNewlines) + return model.state.entries.filter { + query.isEmpty || $0.text.localizedStandardContains(query) + || $0.attachments.contains { $0.filename.localizedStandardContains(query) } + } } var body: some View { - NavigationStack { - content + NavigationStack(path: $path) { + inventory + .navigationTitle("Scratchlist") .navigationBarTitleDisplayMode(.inline) + .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .automatic), prompt: "Search drafts") .toolbar { - ToolbarItem(placement: .topBarLeading) { - Button("Done") { - dismiss() - } - } - ToolbarItem(placement: .principal) { - VStack(spacing: 0) { - Text("Scratchlist") - .font(.headline) - Text(countLine) - .font(.caption2) - .foregroundStyle(.secondary) - } - } - if interactor != nil { - ToolbarItem(placement: .topBarTrailing) { - parkButton - } - } - ToolbarItem(placement: .topBarTrailing) { - Button { - model.openEditor(nil) - } label: { - Image(systemName: "plus") - } - .accessibilityLabel("New note") - } + ToolbarItem(placement: .topBarTrailing) { Button("Done") { dismiss() } } } - .overlay(alignment: .bottom) { - noticeToast + .navigationDestination(for: String.self) { entryId in + ScratchlistDetailView(model: model, entryId: entryId, loader: attachments, + interactor: interactor, onRestore: { dismiss() }, + onOpenAttachment: { viewerAttachment = $0 }) } } - .sheet(isPresented: editorPresented) { - ScratchlistEditorSheet( - model: model, - attachments: attachments, - onOpenAttachment: { viewerAttachment = $0 } - ) + .presentationDetents([.large]) + .presentationDragIndicator(.visible) + .background(ScratchlistDismissGuard(blocked: model.editor?.isDirty == true || model.editor?.isSaving == true) { + if model.editor?.isSaving != true { discardAndClose = true } + }) + .confirmationDialog("Discard your changes?", isPresented: $discardAndClose, titleVisibility: .visible) { + Button("Discard changes", role: .destructive) { model.dismissEditor(); dismiss() } + Button("Keep editing", role: .cancel) {} } .fullScreenCover(item: $viewerAttachment) { attachment in ScratchlistAttachmentViewer(attachment: attachment, loader: attachments) } .onAppear { model.start() + if path.isEmpty, let initialEntry { + path = [initialEntry.entryId] + if initiallyEditing { model.openEditor(initialEntry) } + } } .onDisappear { model.stop() + if viewerAttachment == nil { model.dismissEditor() } } } - // MARK: - Content states - @ViewBuilder - private var content: some View { - let state = model.state - VStack(spacing: 0) { - if !state.uploadsInFlight.isEmpty { - ProgressView() - .progressViewStyle(.linear) - } - if model.isLoading { - Spacer() - ProgressView() - Spacer() - } else if state.loadFailed { - loadFailedState - } else if state.entries.isEmpty { - emptyState - } else { - entryList(state.entries) - } - } - } - - private func entryList(_ entries: [ScratchlistEntry]) -> some View { - ScrollView { - LazyVStack(spacing: 10) { - ForEach(entries) { entry in - ScratchlistEntryCard( - entry: entry, - attachments: attachments, - onOpen: { model.openEditor(entry) }, - onSendToComposer: sendToComposerAction(entry), - onOpenAttachment: { viewerAttachment = $0 } - ) + private var inventory: some View { + if model.isLoading { + ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) + } else if model.state.loadFailed { + ContentUnavailableView { + Label("Couldn't load the scratchlist", systemImage: "wifi.slash") + } description: { + Text("Check the connection to your hub and try again.") + } actions: { Button("Retry") { model.retry() }.buttonStyle(.borderedProminent) } + } else { + List { + Section { + if let notice = model.notice { + ScratchlistErrorBanner(message: notice, actionTitle: "Dismiss") { model.clearNotice() } + } + if model.state.refreshFailed { + ScratchlistErrorBanner(message: String(localized: "Couldn't refresh — showing saved drafts")) { model.retry() } + } + if model.state.atCap { + Text("Scratchlist is full (200 entries)").font(.footnote).foregroundStyle(.secondary) + } + ForEach(entries) { entry in + ScratchlistEntryRow(entry: entry, interactor: interactor, + onOpen: { path.append(entry.entryId) }, + onEdit: { model.openEditor(entry); path.append(entry.entryId) }, + onDelete: { model.deleteEntry(entry.entryId) }, onRestore: { dismiss() }) + .disabled(model.deletingEntryId != nil) + } } } - .padding(.horizontal, 12) - .padding(.vertical, 10) - } - } - - /// "To composer": insert the entry's text into the chat composer and - /// close the sheet (the entry itself stays on the scratchlist). Nil when - /// no interactor is wired (previews) — the affordance is hidden. - private func sendToComposerAction(_ entry: ScratchlistEntry) -> (() -> Void)? { - guard let interactor else { return nil } - return { - interactor.insertComposerText(entry.text) - dismiss() - } - } - - private var loadFailedState: some View { - ContentUnavailableView { - Label("Couldn't load the scratchlist", systemImage: "wifi.slash") - } description: { - Text("Check the connection to your hub and try again.") - } actions: { - Button("Retry") { - model.retry() - } - .buttonStyle(.borderedProminent) - } - } - - private var emptyState: some View { - ContentUnavailableView { - Label("No notes yet", systemImage: "note.text") - } description: { - Text("Park drafts from the header, or tap + to jot a note for this session.") - } - } - - // MARK: - Chrome - - private var countLine: String { - let state = model.state - if !model.isLoading, state.entries.isEmpty { - return String(localized: "No notes") - } - return state.entries.count == 1 - ? String(localized: "1 note") - : String(format: String(localized: "%lld notes"), Int64(state.entries.count)) - } - - /// "Park current draft": the composer draft becomes an entry (disabled - /// while the composer is blank or the list is at cap; the new row appears - /// optimistically once the hub accepts). - @ViewBuilder - private var parkButton: some View { - if let interactor { - let blank = interactor.composer.text - .trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - Button { - interactor.parkComposerDraft() - } label: { - Image(systemName: "tray.and.arrow.down") - } - .disabled(blank || model.state.atCap) - .accessibilityLabel("Park current draft") - } - } - - @ViewBuilder - private var noticeToast: some View { - if let notice = model.notice { - Text(notice) - .font(.footnote) - .lineLimit(3) - .padding(.horizontal, 14) - .padding(.vertical, 8) - .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) - .shadow(radius: 4, y: 2) - .padding(.horizontal, 24) - .padding(.bottom, 8) - .transition(.move(edge: .bottom).combined(with: .opacity)) - } - } - - private var editorPresented: Binding { - Binding( - get: { model.editor != nil }, - set: { open in - if !open { - model.dismissEditor() + .listStyle(.insetGrouped) + .overlay { + if model.state.entries.isEmpty { + ContentUnavailableView { + Label("No drafts yet", systemImage: "tray") + } actions: { + if let interactor { + Button("Write draft") { + interactor.setComposerDestination(.scratchlist) + interactor.focusComposer() + dismiss() + }.buttonStyle(.borderedProminent) + } + } + } else if entries.isEmpty { + ContentUnavailableView.search(text: query) } } - ) + .refreshable { await model.refresh() } + } } } -// MARK: - Entry card - -/// One note: attachment strip, 4-line text preview, relative age, and the -/// optional "To composer" promote action. -private struct ScratchlistEntryCard: View { +/// Each affordance is a real button: tapping a row never also takes a draft. +struct ScratchlistEntryRow: View { + @Environment(\.hapiTypography) private var typography + @Environment(\.dynamicTypeSize) private var dynamicTypeSize let entry: ScratchlistEntry - let attachments: ScratchlistAttachmentLoader + let interactor: ChatInteractor? let onOpen: () -> Void - let onSendToComposer: (() -> Void)? - let onOpenAttachment: (ScratchlistAttachment) -> Void + let onEdit: () -> Void + let onDelete: () -> Void + var onRestore: () -> Void = {} + var compact = false + var showsPreview = true + var showsEditAction = true + @State private var confirmRestore = false + @State private var confirmDelete = false + @State private var restoreError: String? + + private var queued: Bool { interactor?.queuedScratchlistEntries.contains(entry.entryId) == true } + private var busy: Bool { interactor?.scratchlistBusy == true || interactor?.isSending == true } + // The compact row shares the composer's error banner. Do not repeat a + // failed park/restore there; the sheet needs its own local feedback. + private var error: String? { + (compact ? nil : restoreError) ?? interactor?.scratchlistEntryErrors[entry.entryId] + } var body: some View { VStack(alignment: .leading, spacing: 6) { - if !entry.attachments.isEmpty { - ScratchlistAttachmentStrip( - attachments: entry.attachments, - loader: attachments, - thumbSize: 64, - onOpen: onOpenAttachment, - onRemove: nil - ) - } - if entry.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - Text("Attachment only") - .font(.subheadline) - .italic() - .foregroundStyle(.secondary) + if dynamicTypeSize.isAccessibilitySize { + if showsPreview { preview } + actions.frame(maxWidth: .infinity, alignment: .trailing) } else { - Text(entry.text) - .font(.subheadline) - .lineLimit(4) - .frame(maxWidth: .infinity, alignment: .leading) - } - HStack { - Text(scratchlistRelativeAge( - nowMs: Int(Date().timeIntervalSince1970 * 1000), - thenMs: entry.updatedAt - )) - .font(.caption2) - .foregroundStyle(.tertiary) - Spacer() - if let onSendToComposer { - Button("To composer", action: onSendToComposer) - .font(.caption.weight(.medium)) - .buttonStyle(.borderless) + HStack(alignment: .center, spacing: 12) { + if showsPreview { preview } + else { Spacer(minLength: 0) } + actions } } + if let error { + Text(LocalizedNoticeMapper.map(error)).font(.footnote).foregroundStyle(.red) + } + } + .confirmationDialog("You already have a draft", isPresented: $confirmRestore, titleVisibility: .visible) { + Button("Append to input") { restore(.append) } + Button("Save input, then take draft") { restore(.parkCurrent) } + Button("Cancel", role: .cancel) {} + } + .confirmationDialog("Delete this draft?", isPresented: $confirmDelete, titleVisibility: .visible) { + Button("Delete", role: .destructive, action: onDelete) + Button("Cancel", role: .cancel) {} + } + } + + private var preview: some View { + Button(action: onOpen) { + VStack(alignment: .leading, spacing: 5) { + Text(entry.text.isEmpty ? String(localized: "Attachment only") : entry.text) + .font(typography.bodyFont) + .foregroundStyle(.primary) + .lineLimit(2) + .frame(maxWidth: .infinity, alignment: .leading) + if !compact, !entry.attachments.isEmpty { + Label { + Text(verbatim: "\(entry.attachments.count)") + } icon: { Image(systemName: "paperclip") } + .font(typography.captionFont).foregroundStyle(.secondary) + .accessibilityLabel(Text("\(entry.attachments.count) attachments")) + } + } + .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityHint("View the full draft") + .accessibilityIdentifier("scratchlist.preview.\(entry.entryId)") + } + + private var actions: some View { + HStack(spacing: 8) { + if let interactor { + Button { + if queued { queue() } + else if interactor.hasComposerDraft { confirmRestore = true } + else { restore(.append) } + } label: { + Text(queued ? "Retry removal" : "Take draft") + .font(.subheadline.weight(.medium)) + .frame(minWidth: 44, minHeight: 44) + .contentShape(Rectangle()) + } + .accessibilityIdentifier("scratchlist.take.\(entry.entryId)") + .disabled(busy) + } + if !compact { + Menu { + if interactor != nil, !queued { + Button("Add to send queue", systemImage: "text.line.first.and.arrowtriangle.forward", action: queue) + } + if showsEditAction { + Button("Edit", systemImage: "pencil", action: onEdit).disabled(queued) + } + Button("Copy text", systemImage: "doc.on.doc") { UIPasteboard.general.string = entry.text } + .disabled(entry.text.isEmpty) + Button("Delete", systemImage: "trash", role: .destructive) { confirmDelete = true }.disabled(queued) + } label: { + Image(systemName: "ellipsis") + .font(.system(size: 18, weight: .medium)) + .frame(width: 44, height: 44).contentShape(Rectangle()) + } + .accessibilityLabel("Draft actions") + .accessibilityIdentifier("scratchlist.actions.\(entry.entryId)") + .disabled(busy) + } + } + .buttonStyle(.plain) + .foregroundStyle(.tint) + } + + private func queue() { + guard let interactor else { return } + restoreError = nil + Task { if await interactor.queueScratchlistEntry(entry) { onRestore() } } + } + + private func restore(_ choice: ScratchlistRestoreChoice) { + guard let interactor else { return } + restoreError = nil + Task { + if await interactor.restoreScratchlistEntry(entry, choice: choice) { onRestore() } + else { restoreError = interactor.scratchlistError } } - .padding(.horizontal, 14) - .padding(.vertical, 10) - .frame(maxWidth: .infinity, alignment: .leading) - .background(Color(uiColor: .secondarySystemBackground), in: RoundedRectangle(cornerRadius: 14, style: .continuous)) - .contentShape(RoundedRectangle(cornerRadius: 14, style: .continuous)) - .onTapGesture(perform: onOpen) } } -/// Relative age like the session list's Android `formatRelativeAge`. -private func scratchlistRelativeAge(nowMs: Int, thenMs: Int) -> String { - let delta = nowMs - thenMs - if delta < 60_000 { return String(localized: "now") } - let minutes = delta / 60_000 - if minutes < 60 { return "\(minutes)m" } - let hours = minutes / 60 - if hours < 24 { return "\(hours)h" } - let days = hours / 24 - if days < 7 { return "\(days)d" } - let weeks = days / 7 - if weeks < 5 { return "\(weeks)w" } - let months = days / 30 - if months < 12 { return "\(months)mo" } - return "\(days / 365)y" +struct ScratchlistErrorBanner: View { + let message: String + var actionTitle: LocalizedStringKey = "Retry" + let retry: () -> Void + var body: some View { + HStack(alignment: .center, spacing: 8) { + Image(systemName: "exclamationmark.circle").foregroundStyle(.red) + Text(LocalizedNoticeMapper.map(message)).font(.footnote).frame(maxWidth: .infinity, alignment: .leading) + Button(action: retry) { + Text(actionTitle).frame(minHeight: 44).contentShape(Rectangle()) + } + } + .accessibilityElement(children: .contain) + } } +private struct ScratchlistAgeLabel: View { + let updatedAt: Int + @Environment(\.locale) private var locale + var body: some View { + TimelineView(.periodic(from: .now, by: 60)) { context in + Text(verbatim: age(relativeTo: context.date)) + } + } + private func age(relativeTo now: Date) -> String { + let formatter = RelativeDateTimeFormatter() + formatter.locale = locale + formatter.unitsStyle = .short + return formatter.localizedString(for: Date(timeIntervalSince1970: Double(updatedAt) / 1000), relativeTo: now) + } +} + +private struct ScratchlistDetailView: View { + let model: ScratchlistScreenModel + let entryId: String + let loader: ScratchlistAttachmentLoader + let interactor: ChatInteractor? + let onRestore: () -> Void + let onOpenAttachment: (ScratchlistAttachment) -> Void + @Environment(\.hapiTypography) private var typography + @State private var discardChanges = false + + private var entry: ScratchlistEntry? { model.state.entries.first { $0.entryId == entryId } } + + var body: some View { + Group { + if model.editor != nil { + ScratchlistEditorView(model: model, attachments: loader, onOpenAttachment: onOpenAttachment) + } else if let entry { + ScrollView { + VStack(alignment: .leading, spacing: 20) { + if let notice = model.notice { + ScratchlistErrorBanner(message: notice, actionTitle: "Dismiss") { model.clearNotice() } + } + Text(entry.text).font(typography.bodyFont).textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + if !entry.attachments.isEmpty { + ScratchlistAttachmentStrip(attachments: entry.attachments, loader: loader, + thumbSize: 88, onOpen: onOpenAttachment, onRemove: nil, showsFilenames: true) + } + ScratchlistAgeLabel(updatedAt: entry.updatedAt) + .font(typography.captionFont).foregroundStyle(.secondary) + ScratchlistEntryRow(entry: entry, interactor: interactor, onOpen: {}, + onEdit: { model.openEditor(entry) }, onDelete: { model.deleteEntry(entryId) }, onRestore: onRestore, + showsPreview: false, showsEditAction: false) + }.padding(16) + } + } else { + ContentUnavailableView("Draft no longer available", systemImage: "tray") + } + } + .navigationTitle(model.editor == nil ? "Draft" : "Edit draft") + .navigationBarTitleDisplayMode(.inline) + .navigationBarBackButtonHidden(model.editor != nil) + .toolbar { + if let editor = model.editor { + ToolbarItem(placement: .topBarLeading) { + Button("Cancel") { + if editor.isDirty { discardChanges = true } else { model.dismissEditor() } + }.disabled(editor.isSaving) + } + ToolbarItem(placement: .topBarTrailing) { + Button("Save") { model.saveEditor() }.disabled(!editor.canSave) + } + } else if let entry { + ToolbarItem(placement: .topBarTrailing) { + Button("Edit") { model.openEditor(entry) } + .disabled(interactor?.scratchlistBusy == true || interactor?.queuedScratchlistEntries.contains(entryId) == true) + } + } + } + .confirmationDialog("Discard your changes?", isPresented: $discardChanges, titleVisibility: .visible) { + Button("Discard changes", role: .destructive) { model.dismissEditor() } + Button("Keep editing", role: .cancel) {} + } + } +} + +private struct ScratchlistEditorView: View { + let model: ScratchlistScreenModel + let attachments: ScratchlistAttachmentLoader + let onOpenAttachment: (ScratchlistAttachment) -> Void + @Environment(\.hapiTypography) private var typography + @State private var pickedItem: PhotosPickerItem? + @State private var photosPickerOpen = false + @State private var filePickerOpen = false + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + if let editor = model.editor { + if editor.isSaving { ProgressView().frame(maxWidth: .infinity) } + if let error = editor.error { + ScratchlistErrorBanner(message: error, actionTitle: model.editorErrorIsRetryable ? "Retry" : "Dismiss", + retry: model.retryEditorOperation) + } + if editor.text.utf16.count > ScratchlistCaps.maxTextLength { + Text("Drafts can contain at most 10,000 characters — shorten the text before saving") + .font(.footnote).foregroundStyle(.red) + } + TextEditor(text: Binding(get: { model.editor?.text ?? "" }, set: model.setEditorText)) + .font(typography.bodyFont) + .accessibilityLabel("Draft text") + .disabled(editor.isSaving) + if !editor.attachments.isEmpty { + ScratchlistAttachmentStrip(attachments: editor.attachments, loader: attachments, thumbSize: 72, + onOpen: onOpenAttachment, onRemove: model.removeAttachment) + .frame(height: 78) + .disabled(editor.isSaving || editor.isUploading) + } + if let filename = editor.failedUploadName { + HStack { + Label(filename, systemImage: "exclamationmark.circle").font(.footnote).foregroundStyle(.red) + Spacer() + Button("Remove", role: .destructive) { model.removeFailedUpload() }.frame(minHeight: 44) + }.disabled(editor.isUploading) + } + HStack { + Menu { + Button("Photo library", systemImage: "photo") { photosPickerOpen = true } + Button("Files", systemImage: "doc") { filePickerOpen = true } + } label: { + Image(systemName: "plus") + .frame(width: 44, height: 44).contentShape(Rectangle()) + } + .accessibilityLabel("Add attachment") + .accessibilityIdentifier("scratchlist.editor.attach") + Spacer() + if editor.isUploading { ProgressView() } + } + .frame(minHeight: 44) + .disabled(editor.isSaving || editor.isUploading || editor.failedUploadName != nil) + } + } + .padding(16) + .photosPicker(isPresented: $photosPickerOpen, selection: $pickedItem, matching: .images) + .onChange(of: pickedItem) { + guard let item = pickedItem else { return } + pickedItem = nil + model.addAttachment(item) + } + .fileImporter(isPresented: $filePickerOpen, allowedContentTypes: [.item]) { result in + guard case .success(let url) = result else { return } + let editorId = model.editor?.id + Task { + let prepared = await AttachmentPreparer.prepare(fileURL: url) + guard model.editor?.id == editorId else { return } + switch prepared { + case .ready(let prepared): + model.addPreparedAttachment(prepared) + case .tooLarge(let filename, _): + model.reportEditorError(String(format: String(localized: "%@ is over the 50 MB upload limit"), filename)) + case .unreadable(let filename): + model.reportEditorError(String(format: String(localized: "Couldn't read %@"), filename)) + } + } + } + } +} // MARK: - Attachment strip /// Horizontal thumbnails: images render through the authed loader, other /// mime types (pdf/text) degrade to filename chips; an optional ✕ badge /// removes (editor strip). -private struct ScratchlistAttachmentStrip: View { +struct ScratchlistAttachmentStrip: View { let attachments: [ScratchlistAttachment] let loader: ScratchlistAttachmentLoader let thumbSize: CGFloat let onOpen: (ScratchlistAttachment) -> Void let onRemove: ((ScratchlistAttachment) -> Void)? + var showsFilenames = false var body: some View { ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: 6) { + HStack(alignment: .top, spacing: showsFilenames ? 12 : 6) { ForEach(attachments) { attachment in - ScratchlistAttachmentThumb( - attachment: attachment, - loader: loader, - size: thumbSize, - onOpen: { onOpen(attachment) }, - onRemove: removeAction(for: attachment) - ) + VStack(spacing: 6) { + ScratchlistAttachmentThumb( + attachment: attachment, + loader: loader, + size: thumbSize, + onOpen: { onOpen(attachment) }, + onRemove: removeAction(for: attachment), + showsFilename: !showsFilenames + ) + if showsFilenames { + Text(verbatim: attachment.filename) + .font(.caption).foregroundStyle(.secondary) + .frame(width: max(thumbSize, 140)) + .fixedSize(horizontal: false, vertical: true) + } + } } } } @@ -329,12 +484,13 @@ private struct ScratchlistAttachmentStrip: View { } /// One thumbnail (image via the authed loader, otherwise a filename chip). -private struct ScratchlistAttachmentThumb: View { +struct ScratchlistAttachmentThumb: View { let attachment: ScratchlistAttachment let loader: ScratchlistAttachmentLoader let size: CGFloat let onOpen: () -> Void let onRemove: (() -> Void)? + var showsFilename = true @State private var image: UIImage? @State private var failed = false @@ -349,6 +505,7 @@ private struct ScratchlistAttachmentThumb: View { tile } .buttonStyle(.plain) + .accessibilityLabel(attachment.filename) if let onRemove { Button(action: onRemove) { Image(systemName: "xmark.circle.fill") @@ -356,7 +513,7 @@ private struct ScratchlistAttachmentThumb: View { .foregroundStyle(.white, .black.opacity(0.6)) } .buttonStyle(.plain) - .padding(2) + .frame(minWidth: 44, minHeight: 44) .accessibilityLabel("Remove \(attachment.filename)") } } @@ -387,108 +544,29 @@ private struct ScratchlistAttachmentThumb: View { .background(Color(uiColor: .tertiarySystemFill)) .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) } else { - Text(verbatim: "📎 \(attachment.filename)") - .font(.caption2) - .lineLimit(3) - .multilineTextAlignment(.center) - .padding(4) - .frame(width: size, height: size) - .background(Color(uiColor: .tertiarySystemFill), in: RoundedRectangle(cornerRadius: 10, style: .continuous)) - } - } -} - -// MARK: - Editor sheet - -/// Edit sheet: text field + attachment strip (photo picker → guard → -/// downscale → upload spinner tile, remove) + Delete for existing entries + -/// Save. -private struct ScratchlistEditorSheet: View { - let model: ScratchlistScreenModel - let attachments: ScratchlistAttachmentLoader - let onOpenAttachment: (ScratchlistAttachment) -> Void - - @State private var pickedItem: PhotosPickerItem? - - var body: some View { - let editor = model.editor ?? ScratchlistEditorState() - VStack(alignment: .leading, spacing: 12) { - Text(editor.entryId == nil ? String(localized: "New note") : String(localized: "Edit note")) - .font(.headline) - TextField( - "Note, draft, parking-lot idea…", - text: Binding( - get: { model.editor?.text ?? "" }, - set: { model.setEditorText($0) } - ), - axis: .vertical - ) - .lineLimit(3...8) - .textFieldStyle(.roundedBorder) - attachmentRow(editor) - HStack { - if let entryId = editor.entryId { - Button("Delete", role: .destructive) { - model.deleteEntry(entryId) - } - } - Spacer() - Button("Cancel") { - model.dismissEditor() - } - Button("Save") { - model.saveEditor() - } - .buttonStyle(.borderedProminent) - .disabled(editor.isUploading) - } - Spacer(minLength: 0) - } - .padding(16) - .presentationDetents([.medium, .large]) - .presentationDragIndicator(.visible) - .onChange(of: pickedItem) { - guard let item = pickedItem else { return } - pickedItem = nil - model.addAttachment(item) - } - } - - private func attachmentRow(_ editor: ScratchlistEditorState) -> some View { - ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: 6) { - ForEach(editor.attachments) { attachment in - ScratchlistAttachmentThumb( - attachment: attachment, - loader: attachments, - size: 72, - onOpen: { onOpenAttachment(attachment) }, - onRemove: { model.removeAttachment(attachment) } - ) - } - if editor.isUploading { - ProgressView() - .frame(width: 72, height: 72) - .background(Color(uiColor: .tertiarySystemFill), in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + Group { + if showsFilename { + Text(verbatim: "📎 \(attachment.filename)") + .font(.caption2).lineLimit(3).multilineTextAlignment(.center) } else { - PhotosPicker(selection: $pickedItem, matching: .images) { - Image(systemName: "plus") - .frame(width: 72, height: 72) - .background(Color(uiColor: .tertiarySystemFill), in: RoundedRectangle(cornerRadius: 10, style: .continuous)) - } - .accessibilityLabel("Add photo") + Image(systemName: isImage ? "photo" : "doc") + .font(.title2).foregroundStyle(.secondary) } } + .padding(4) + .frame(width: size, height: size) + .background(Color(uiColor: .tertiarySystemFill), in: RoundedRectangle(cornerRadius: 10, style: .continuous)) } } } + // MARK: - Viewer /// Full-screen attachment viewer (the generated-image viewer pattern): dark /// backdrop, fit-scaled image via the authed loader, tap or the close button /// dismisses. Non-image attachments show a filename placeholder. -private struct ScratchlistAttachmentViewer: View { +struct ScratchlistAttachmentViewer: View { let attachment: ScratchlistAttachment let loader: ScratchlistAttachmentLoader diff --git a/ios/Hapi/Features/Sessions/SessionListModel.swift b/ios/Hapi/Features/Sessions/SessionListModel.swift index dbb83a4e..a1300058 100644 --- a/ios/Hapi/Features/Sessions/SessionListModel.swift +++ b/ios/Hapi/Features/Sessions/SessionListModel.swift @@ -11,20 +11,70 @@ struct SessionRowUI: Identifiable, Equatable { let summary: SessionSummary /// `getSessionTitle` port: name → summary text → path tail → id prefix. let title: String - /// Secondary line: summary text, only when it is not already the title. - let subtitle: String? - /// Single meta line, `project · worktree · machine`: project is the last - /// two segments of the worktree base path (session path fallback, the web - /// sidebar's group-name rule); the machine label is disambiguation only — - /// present only when several machines are known and no machine filter is - /// active. Full paths never render in the list (the session detail owns - /// them). - let meta: String? + /// Short project name only. Paths, machine/worktree details and the + /// conversation summary stay out of the compact home row. + let project: String? /// Raw flavor id (`claude`, `codex`, …); labels resolve via the catalog. let flavor: String? let unread: Bool var id: String { summary.id } + var status: SessionRowStatus? { SessionRowStatus(summary: summary) } +} + +/// Presentation only: request totals/kinds come from the hub, independently +/// of the capped request slice and the local read watermark. +enum SessionRowStatus: Equatable { + case needsReply(Int) + case needsApproval(Int) + case needsAttention(Int) + case running + + init?(summary: SessionSummary) { + let count = summary.pendingRequestsCount + if count > 0 { + let kinds = Set(summary.pendingRequestKinds) + if kinds == [.input] { + self = .needsReply(count) + } else if kinds == [.permission] { + self = .needsApproval(count) + } else { + self = .needsAttention(count) + } + } else if summary.active && summary.thinking { + self = .running + } else { + return nil + } + } + + /// Localize in the view so its locale also governs previews/specimens. + var titleKey: String { + switch self { + case .needsReply: return "Needs reply" + case .needsApproval: return "Needs approval" + case .needsAttention: return "Needs attention" + case .running: return "Running" + } + } + + var count: Int? { + switch self { + case .needsReply(let count), .needsApproval(let count), .needsAttention(let count): return count + case .running: return nil + } + } + + /// Unfilled attention symbols; running uses the native loading indicator. + /// Status wording/count remain available to VoiceOver in either case. + var symbolName: String? { + switch self { + case .needsReply: return "bubble.left" + case .needsApproval: return "hand.raised" + case .needsAttention: return "exclamationmark.bubble" + case .running: return nil + } + } } struct MachineFilterUI: Identifiable, Equatable { @@ -59,6 +109,7 @@ final class SessionListModel { /// Last refresh failed — show the offline state over snapshot data. private(set) var isOffline = false private(set) var hasRefreshedOnce = false + @ObservationIgnored private var hasAttemptedRefresh = false /// Transient pin/archive failure for an alert. var actionError: String? @@ -177,32 +228,11 @@ final class SessionListModel { guard let activeFilter else { return true } return (summary.metadata?.machineId ?? unknownMachineFilterId) == activeFilter } - // With one machine — or a machine filter active — every visible row - // shares the machine, so repeating it per row is noise. - let machines = machineFilters - let showMachine = machines.count >= 2 && activeFilter == nil - let labels = Dictionary(uniqueKeysWithValues: machines.map { ($0.id, $0.label) }) return visible.map { summary in - let title = Self.sessionTitle(summary) - let rawSummaryText = summary.metadata?.summary?.text - let isBlank = rawSummaryText?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true - let summaryText = isBlank ? nil : rawSummaryText - var metaParts: [String] = [] - if let project = Self.projectLabel(summary) { - metaParts.append(project) - } - if let tree = summary.metadata?.worktree { - let name = tree.name.trimmingCharacters(in: .whitespaces) - metaParts.append(name.isEmpty ? tree.branch : tree.name) - } - if showMachine, let machine = labels[summary.metadata?.machineId ?? unknownMachineFilterId] { - metaParts.append(machine) - } - return SessionRowUI( + SessionRowUI( summary: summary, - title: title, - subtitle: (summaryText != nil && summaryText != title) ? summaryText : nil, - meta: metaParts.isEmpty ? nil : metaParts.joined(separator: " · "), + title: Self.sessionTitle(summary), + project: Self.projectLabel(summary), flavor: summary.metadata?.flavor, unread: LastSeenStore.isUnread(summary, lastSeenAt: lastSeen[summary.id] ?? 0) ) @@ -215,25 +245,32 @@ final class SessionListModel { rows.prefix { $0.summary.globalPinned == true || $0.summary.pinned == true }.count } - /// Project identity for the meta line: last two segments of the worktree - /// base path, session path fallback — mirrors the web sidebar's - /// `getGroupDisplayName` rule (`SessionList.tsx`). + /// Use the worktree's owning project, not its temporary checkout name. + /// The home needs a scan key, not a repeated path or machine inventory. static func projectLabel(_ summary: SessionSummary) -> String? { - guard let path = summary.metadata?.worktree?.basePath ?? summary.metadata?.path, - !path.isEmpty else { return nil } - let parts = path.split(whereSeparator: { $0 == "/" || $0 == "\\" }).map(String.init) - if parts.isEmpty { return path } - if parts.count == 1 { return parts[0] } - return "\(parts[parts.count - 2])/\(parts[parts.count - 1])" + guard let path = summary.metadata?.worktree?.basePath ?? summary.metadata?.path else { return nil } + return path.split(whereSeparator: { $0 == "/" || $0 == "\\" }).last.map(String.init) } // MARK: - Actions + /// A split sidebar can disappear/reappear just because the window + /// collapses. Fetch once per home, not once per layout transition; + /// global SSE recovery and explicit pull-to-refresh still fetch normally. + func refreshOnFirstAppearance() async { + guard !hasAttemptedRefresh else { return } + hasAttemptedRefresh = true + // The sidebar's SwiftUI task is cancelled when it collapses. The + // initial fetch belongs to the model, not that transient presentation. + await Task { await self.refresh() }.value + } + /// Pull-to-refresh / initial load. Coalesces concurrent calls; the first /// successful list seeds the unread baseline so historical sessions do /// not all light up as unread. func refresh() async { guard !isRefreshing else { return } + hasAttemptedRefresh = true isRefreshing = true defer { isRefreshing = false } do { diff --git a/ios/Hapi/Features/Sessions/SessionListView.swift b/ios/Hapi/Features/Sessions/SessionListView.swift index 5d117e39..a06b4b1c 100644 --- a/ios/Hapi/Features/Sessions/SessionListView.swift +++ b/ios/Hapi/Features/Sessions/SessionListView.swift @@ -11,16 +11,16 @@ import SwiftUI /// home owns the filter menu and connection notice; /// - pinned section first (the sort already puts globalPinned/pinned rows on /// top; a header makes the boundary visible); -/// - per row: flavor brand icon + title, spinner while a turn is in flight, -/// summary line, `project · worktree · machine` meta line (machine only -/// when it disambiguates), relative `updatedAt`, pending-request badge, -/// todo-progress chip, unread dot; disconnected rows are dimmed — -/// connected is the resting state, so no presence dot (web parity); +/// - per row: flavor brand icon + title, trailing relative `updatedAt` and +/// an optional unread dot; a quiet second line has project left and a small status +/// indicator right. No preview, task progress, machine/path details or badges. +/// Disconnected titles/icons are secondary, without dimming attention; /// - long-press context menu → pin (none/project/global) + archive with /// optimistic store updates; failures land in an alert. struct SessionListView: View { @Environment(\.hapiTheme) private var theme let model: SessionListModel + var selection: Binding? = nil let onOpenSession: (String) -> Void var body: some View { @@ -40,7 +40,11 @@ struct SessionListView: View { .task { // Explicit fetch on entry: the snapshot may be stale and a // `resume: ok` handshake deliberately skips the REST resync. - await model.refresh() + if selection != nil { + await model.refreshOnFirstAppearance() + } else { + await model.refresh() + } } .refreshable { await model.refresh() @@ -69,7 +73,7 @@ struct SessionListView: View { private func sessionList(now: Date) -> some View { let rows = model.rows let pinnedCount = SessionListModel.pinnedCount(of: rows) - return List { + return List(selection: selection) { if pinnedCount > 0 { Section("Pinned") { ForEach(rows.prefix(pinnedCount)) { row in @@ -115,16 +119,23 @@ struct SessionListView: View { } private func rowCell(_ row: SessionRowUI, now: Date) -> some View { - Button { - model.onSessionOpened(row.id) - onOpenSession(row.id) - } label: { - SessionRowView(row: row, now: now) - .frame(maxWidth: .infinity, alignment: .leading) - // Plain buttons otherwise ignore the label's empty space. - .contentShape(Rectangle()) + Group { + if selection != nil { + NavigationLink(value: row.id) { + rowLabel(row, now: now) + } + .tag(row.id) + } else { + Button { + model.onSessionOpened(row.id) + onOpenSession(row.id) + } label: { + rowLabel(row, now: now) + } + .buttonStyle(.plain) + } } - .buttonStyle(.plain) + .listRowInsets(EdgeInsets(top: 12, leading: 16, bottom: 12, trailing: 16)) // Default separator color reads heavy against these rows; the theme // divider is the WeChat-style faint hairline. .listRowSeparatorTint(theme.divider) @@ -133,6 +144,12 @@ struct SessionListView: View { } } + private func rowLabel(_ row: SessionRowUI, now: Date) -> some View { + SessionRowView(row: row, now: now) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + @ViewBuilder private func contextMenuActions(_ row: SessionRowUI) -> some View { let summary = row.summary @@ -193,135 +210,114 @@ struct SessionListView: View { // MARK: - Row struct SessionRowView: View { + @Environment(\.hapiTheme) private var theme + @ScaledMetric(relativeTo: .footnote) private var statusSlotSize: CGFloat = 16 + let row: SessionRowUI let now: Date + // The agent owns the leading column; one quiet line of secondary text + // keeps the row focused on the title rather than a stack of indicators. + private let textInset: CGFloat = 24 + var body: some View { - VStack(alignment: .leading, spacing: 2) { + VStack(alignment: .leading, spacing: 4) { titleLine - // Summary directly under the title (its prose continuation); the - // `project · machine` meta closes the row as a footer. - if let subtitle = row.subtitle { - Text(subtitle) - .font(.footnote) - .foregroundStyle(.secondary) - .lineLimit(1) - } - metaLine - badgeLine + detailLine + .padding(.leading, textInset) } - .padding(.vertical, 2) - // Dimming expresses "disconnected" (web parity): connected is the - // resting state here, so only the exception gets marked — no - // per-row presence dot. - .opacity(row.summary.active ? 1 : 0.5) + .alignmentGuide(.listRowSeparatorLeading) { _ in textInset } .accessibilityElement(children: .combine) + .accessibilityIdentifier("home.session.\(row.id)") } private var titleLine: some View { - // Spinner/dot pinned to the trailing edge next to the timestamp - // (Android row order), so they don't drift with the title length. - HStack(spacing: 6) { + HStack(spacing: 8) { AgentFlavorIconView(flavor: row.flavor) - Text(row.title) + .foregroundStyle(row.summary.active ? theme.textPrimary : theme.textSecondary) + .opacity(row.summary.active ? 1 : 0.5) + Text(verbatim: row.title) .font(.body) .fontWeight(row.unread ? .semibold : .regular) + .foregroundStyle(row.summary.active ? theme.textPrimary : theme.textSecondary) .lineLimit(1) Spacer(minLength: 4) - if row.summary.active && row.summary.thinking { - ProgressView() - .scaleEffect(0.7) - .frame(width: 14, height: 14) - .tint(.green) - .accessibilityLabel("Thinking") - } - if row.unread { - Circle() - .fill(.tint) - .frame(width: 8, height: 8) - .accessibilityLabel("Unread") - } - Text(formatRelativeAge(now: now, thenEpochMs: row.summary.updatedAt)) - .font(.caption2) - .foregroundStyle(.secondary) - } - } - - // `project · worktree · machine`, composed in the model (machine only - // when it disambiguates) — the row just renders it. - @ViewBuilder - private var metaLine: some View { - if let meta = row.meta { - // Footnote, not caption: as the row's only secondary line the - // meta carries the project scan key (web keeps title/meta at - // 14/12; 17/13 is the same contrast). - Text(meta) - .font(.footnote) - .foregroundStyle(.secondary) - .lineLimit(1) - } - } - - @ViewBuilder - private var badgeLine: some View { - let summary = row.summary - if summary.pendingRequestsCount > 0 || summary.todoProgress != nil { HStack(spacing: 6) { - if summary.pendingRequestsCount > 0 { - PendingBadge( - count: summary.pendingRequestsCount, - kinds: summary.pendingRequestKinds, - requests: summary.pendingRequests - ) - } - if let progress = summary.todoProgress { - TodoChip(progress: progress) + Text(verbatim: formatRelativeAge(now: now, thenEpochMs: row.summary.updatedAt)) + .font(.caption2) + .foregroundStyle(theme.textSecondary) + .monospacedDigit() + .fixedSize() + // Unread dots always occupy the trailing edge. Read rows + // remove the slot so the timestamp itself aligns right. + if row.unread { + Circle() + .fill(theme.accent) + .frame(width: 8, height: 8) + .frame(width: 12) + .accessibilityLabel("Unread") } } - .padding(.top, 2) + .fixedSize() } } -} -/// Pending badge: authoritative `pendingRequestsCount` + kind wording; the -/// capped `pendingRequests` slice names the first tool. -struct PendingBadge: View { - let count: Int - let kinds: [PendingRequestKind] - let requests: [PendingRequest] - - var body: some View { - let needsInput = kinds.contains(.input) && !kinds.contains(.permission) - let label: String - if needsInput { - label = String(localized: "needs input") - } else if let first = requests.first { - label = String(format: String(localized: "approve %@"), first.tool) - } else { - label = String(localized: "pending") + @ViewBuilder + private var detailLine: some View { + if row.project != nil || row.status != nil { + HStack(alignment: .center, spacing: 0) { + // Keep the same text line height when metadata is missing, + // so the symbol does not jump vertically at large text sizes. + Text(verbatim: row.project ?? " ") + .lineLimit(1) + .accessibilityHidden(row.project == nil) + Spacer(minLength: 12) + if let status = row.status { + statusIndicator(status) + } + } + .font(.footnote) + .foregroundStyle(theme.textSecondary) } - let text = count > 1 ? "\(count) · \(label)" : label - return Text(text) - .font(.caption2) - .lineLimit(1) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(.orange.opacity(0.18), in: RoundedRectangle(cornerRadius: 6)) - .foregroundStyle(.orange) } -} -struct TodoChip: View { - let progress: TodoProgress + private func statusIndicator(_ status: SessionRowStatus) -> some View { + Group { + if let symbol = status.symbolName { + Image(systemName: symbol) + .symbolVariant(.none) + .symbolRenderingMode(.monochrome) + .foregroundStyle(attentionColor) + } else { + ProgressView() + // Native small loading already scales with Dynamic Type; + // an extra scaleEffect would overflow the shared slot. + .controlSize(.small) + .tint(theme.textSecondary) + } + } + // One shared slot keeps attention symbols and loading aligned. + // Footnote is 13pt at the default size and scales for AX. + .frame(width: statusSlotSize, height: statusSlotSize) + .fixedSize() + .layoutPriority(1) + .accessibilityLabel(statusAccessibilityText(status)) + } - var body: some View { - Label("\(progress.completed)/\(progress.total)", systemImage: "checklist") - .font(.caption2) - .lineLimit(1) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(Color.secondary.opacity(0.15), in: RoundedRectangle(cornerRadius: 6)) - .foregroundStyle(.secondary) + // Darker amber keeps thin strokes visible on white without a filled + // symbol, background badge or animation competing with the session title. + private var attentionColor: Color { + theme.isDark ? theme.warning : Color(hex: 0x9A6700) + } + + /// Keep the exact request count available to VoiceOver without adding + /// another visible number or badge to every waiting conversation. + private func statusAccessibilityText(_ status: SessionRowStatus) -> Text { + let title = Text(LocalizedStringKey(status.titleKey)) + if let count = status.count, count > 1 { + return Text("\(title) · \(count) requests") + } + return title } } diff --git a/ios/Hapi/Info.plist b/ios/Hapi/Info.plist index 80c17ed4..3846cffb 100644 --- a/ios/Hapi/Info.plist +++ b/ios/Hapi/Info.plist @@ -2,6 +2,13 @@ + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + ITSAppUsesNonExemptEncryption NSCameraUsageDescription diff --git a/ios/Hapi/Models/HubSession.swift b/ios/Hapi/Models/HubSession.swift index cee14991..3380fa6a 100644 --- a/ios/Hapi/Models/HubSession.swift +++ b/ios/Hapi/Models/HubSession.swift @@ -49,6 +49,13 @@ final class HubSession { /// the chat the user is looking at is pure noise. private(set) var openChatSessionId: String? + struct SessionRemoval: Equatable { + let sessionId: String + // Repeated removal of a reopened ID still notifies navigation. + private let occurrence = UUID() + } + private(set) var sessionRemoval: SessionRemoval? + /// Fired once when the hub terminally rejects the stored credentials /// (access token rotated/revoked). `AppModel` reacts by dropping the hub /// back to pairing with a banner. @@ -113,6 +120,9 @@ final class HubSession { try await api.setVisibility(subscriptionId: subscriptionId, visibility: visibility) }) self.router = SyncEventRouter(sessions: sessionStore, machines: machineStore) + sessionStore.onSessionRemoved = { [weak self] sessionId in + self?.sessionRemoval = SessionRemoval(sessionId: sessionId) + } } // MARK: - Per-chat sessions (M2f) @@ -214,6 +224,7 @@ final class HubSession { // Hub switch can outrun the chat view's disappear; stop is idempotent. activeChat?.stop() activeChat = nil + openChatSessionId = nil consumeTask?.cancel() consumeTask = nil if let sse { diff --git a/ios/Hapi/Models/LocalizedNoticeMapper.swift b/ios/Hapi/Models/LocalizedNoticeMapper.swift index 0e2cef95..fee60964 100644 --- a/ios/Hapi/Models/LocalizedNoticeMapper.swift +++ b/ios/Hapi/Models/LocalizedNoticeMapper.swift @@ -34,6 +34,13 @@ enum LocalizedNoticeMapper { "Draft parked to scratchlist", "Scratchlist is full (200 entries)", "Couldn't park the draft — check the hub connection", + "Drafts can contain at most 10,000 characters — shorten the text before saving", + "Couldn't prepare the attachments — retry or remove the failed files", + "The attachments exceed the scratchlist limits — remove a file or choose a smaller one", + "Your input changed — review it and try again", + "Couldn't queue the draft — retry", + "Draft added to the send queue", + "Already queued — couldn't remove the draft. Retry removal only.", // DictationController "Could not start recording", "Could not reach the hub", @@ -42,6 +49,7 @@ enum LocalizedNoticeMapper { "Transcription failed", // NewSessionLogic "Name needs at least one letter or digit", + "Path is outside workspace roots", // MessageWindowController (degraded-sync banner) "Failed to synchronize messages", "Failed to load older messages", diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index b496e7a0..489dfb56 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -89,6 +89,28 @@ } } }, + "%@ · %@ requests" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@ · %2$@ requests" + } + } + } + }, + "%@ · %lld requests" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ · %lld 项" + } + } + } + }, "%@, %lld sessions" : { "extractionState" : "manual", "localizations" : { @@ -140,6 +162,35 @@ } } }, + "%lld attachments" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld attachment" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld attachments" + } + } + } + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld 个附件" + } + } + } + }, "%lld chars" : { "extractionState" : "manual", "localizations" : { @@ -675,6 +726,17 @@ } } }, + "Add to send queue" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "加入发送队列" + } + } + } + }, "After" : { "extractionState" : "manual", "localizations" : { @@ -851,6 +913,17 @@ } } }, + "Already queued — couldn't remove the draft. Retry removal only." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已加入队列,但草稿移除失败。请重试移除,不会重复发送。" + } + } + } + }, "Answer every question first" : { "extractionState" : "manual", "localizations" : { @@ -928,6 +1001,17 @@ } } }, + "Append to input" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "追加到输入" + } + } + } + }, "Applies after the app is relaunched." : { "extractionState" : "manual", "localizations" : { @@ -950,6 +1034,17 @@ } } }, + "Applying changes…" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在应用更改…" + } + } + } + }, "Archive" : { "extractionState" : "manual", "localizations" : { @@ -1038,6 +1133,17 @@ } } }, + "Back to chat" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "返回聊天" + } + } + } + }, "Back to latest" : { "extractionState" : "manual", "localizations" : { @@ -1236,6 +1342,17 @@ } } }, + "Chat" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "聊天" + } + } + } + }, "Check the connection to your hub and try again." : { "extractionState" : "manual", "localizations" : { @@ -1247,6 +1364,28 @@ } } }, + "Check the hub address. HTTPS is recommended, for example https://hub.example.com." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "请检查 Hub 地址。建议使用 HTTPS,例如 https://hub.example.com。" + } + } + } + }, + "Checking directory…" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在检查目录…" + } + } + } + }, "Checking hub…" : { "extractionState" : "manual", "localizations" : { @@ -1269,6 +1408,17 @@ } } }, + "Choose a session from the sidebar, or start a new one." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "从侧栏选择一个会话,或新建会话。" + } + } + } + }, "Choose Directory" : { "extractionState" : "manual", "localizations" : { @@ -1379,6 +1529,17 @@ } } }, + "Connection protocol" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "连接协议" + } + } + } + }, "Connection: %@" : { "extractionState" : "manual", "localizations" : { @@ -1412,6 +1573,17 @@ } } }, + "Continue planning" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "继续规划" + } + } + } + }, "Copy" : { "extractionState" : "manual", "localizations" : { @@ -1478,6 +1650,17 @@ } } }, + "Copy text" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "复制文字" + } + } + } + }, "Could not load this dashboard." : { "extractionState" : "manual", "localizations" : { @@ -1610,6 +1793,28 @@ } } }, + "Couldn't prepare the attachments — retry or remove the failed files" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "附件准备失败,请重试或移除失败的附件" + } + } + } + }, + "Couldn't queue the draft — retry" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "草稿加入队列失败,请重试" + } + } + } + }, "Couldn't read %@" : { "extractionState" : "manual", "localizations" : { @@ -1643,6 +1848,17 @@ } } }, + "Couldn't refresh — showing saved drafts" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "刷新失败,正在显示已缓存的草稿" + } + } + } + }, "Couldn't remove the attachment — check the hub connection" : { "extractionState" : "manual", "localizations" : { @@ -1654,6 +1870,17 @@ } } }, + "Couldn't save the draft — your changes are kept here" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "保存失败,修改仍保留在这里,请重试" + } + } + } + }, "Couldn't save the note — check the hub connection" : { "extractionState" : "manual", "localizations" : { @@ -1775,6 +2002,17 @@ } } }, + "Default" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "默认" + } + } + } + }, "Delete" : { "extractionState" : "manual", "localizations" : { @@ -1797,6 +2035,17 @@ } } }, + "Delete this draft?" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "删除这条草稿?" + } + } + } + }, "Delivery outcome unknown" : { "extractionState" : "manual", "localizations" : { @@ -1918,6 +2167,28 @@ } } }, + "Discard changes" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "放弃修改" + } + } + } + }, + "Discard your changes?" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "放弃尚未保存的修改?" + } + } + } + }, "Disk footprint of the hub's SQLite database (database, write-ahead log, shared memory)." : { "extractionState" : "manual", "localizations" : { @@ -1929,6 +2200,28 @@ } } }, + "Dismiss" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "关闭" + } + } + } + }, + "Domain or IP address" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "域名或 IP 地址" + } + } + } + }, "Done" : { "extractionState" : "manual", "localizations" : { @@ -1940,6 +2233,50 @@ } } }, + "Draft" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "草稿" + } + } + } + }, + "Draft actions" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "草稿操作" + } + } + } + }, + "Draft added to the send queue" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "草稿已加入发送队列" + } + } + } + }, + "Draft no longer available" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "这条草稿已不存在" + } + } + } + }, "Draft parked to scratchlist" : { "extractionState" : "manual", "localizations" : { @@ -1951,6 +2288,28 @@ } } }, + "Draft text" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "草稿内容" + } + } + } + }, + "Drafts can contain at most 10,000 characters — shorten the text before saving" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "草稿最多支持 10,000 个字符,请缩短内容后再暂存" + } + } + } + }, "Earlier calls aren't loaded. Close this view and load older messages in the conversation." : { "extractionState" : "manual", "localizations" : { @@ -1984,6 +2343,17 @@ } } }, + "Edit draft" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "编辑草稿" + } + } + } + }, "Edit file" : { "extractionState" : "manual", "localizations" : { @@ -2072,13 +2442,35 @@ } } }, - "Enter the hub's full address, e.g. http://192.168.1.20:3006." : { + "Enter a valid hub domain or IP address, with an optional port." : { "extractionState" : "manual", "localizations" : { "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "请输入 Hub 的完整地址,例如 http://192.168.1.20:3006。" + "value" : "请输入有效的 Hub 域名或 IP 地址,可包含端口。" + } + } + } + }, + "Enter the access token printed by your hub." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "请输入 Hub 启动时显示的访问令牌。" + } + } + } + }, + "Enter your hub address without the protocol, or paste a full URL or pairing link." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "输入 Hub 地址,无需填写协议;也可粘贴完整地址或配对链接。" } } } @@ -2138,6 +2530,17 @@ } } }, + "Failed to check directory" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "无法检查目录" + } + } + } + }, "Failed to check installed Agents" : { "extractionState" : "manual", "localizations" : { @@ -2424,6 +2827,50 @@ } } }, + "HTTP is unencrypted and may be restricted by iOS. HTTPS is recommended." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "HTTP 不加密,且可能受 iOS 网络策略限制。建议使用 HTTPS。" + } + } + } + }, + "Held — not sent" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "暂存 · 未发送" + } + } + } + }, + "Hide note" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "收起备注" + } + } + } + }, + "High risk" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "高风险" + } + } + } + }, "Hub" : { "extractionState" : "manual", "localizations" : { @@ -2523,6 +2970,17 @@ } } }, + "Implement plan" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "执行计划" + } + } + } + }, "Inactive" : { "extractionState" : "manual", "localizations" : { @@ -2589,6 +3047,28 @@ } } }, + "Keep an instruction for later…" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "记下稍后要做的事…" + } + } + } + }, + "Keep editing" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "继续编辑" + } + } + } + }, "Language" : { "extractionState" : "manual", "localizations" : { @@ -2930,6 +3410,17 @@ } } }, + "More approval options" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "更多授权选项" + } + } + } + }, "Name needs at least one letter or digit" : { "extractionState" : "manual", "localizations" : { @@ -2941,6 +3432,39 @@ } } }, + "Needs approval" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "待批准" + } + } + } + }, + "Needs attention" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "待处理" + } + } + } + }, + "Needs reply" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "待回复" + } + } + } + }, "New Session" : { "extractionState" : "manual", "localizations" : { @@ -3051,6 +3575,17 @@ } } }, + "No drafts yet" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "暂无草稿" + } + } + } + }, "No files matched" : { "extractionState" : "manual", "localizations" : { @@ -3084,6 +3619,17 @@ } } }, + "No matching directories" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "没有匹配的目录" + } + } + } + }, "No messages yet" : { "extractionState" : "manual", "localizations" : { @@ -3139,6 +3685,17 @@ } } }, + "No settings available for this session." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此会话没有可用设置。" + } + } + } + }, "No storage data reported." : { "extractionState" : "manual", "localizations" : { @@ -3194,6 +3751,17 @@ } } }, + "None of the above" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "以上都不是" + } + } + } + }, "Not delivered" : { "extractionState" : "manual", "localizations" : { @@ -3370,6 +3938,17 @@ } } }, + "Optionally, add details in notes." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "可在备注中补充说明(可选)。" + } + } + } + }, "Options" : { "extractionState" : "manual", "localizations" : { @@ -3436,6 +4015,17 @@ } } }, + "Pairing details filled in. Review them, then tap Pair." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "配对信息已填入,请确认后点击「配对」。" + } + } + } + }, "Pairing succeeded but the credentials could not be stored on this device. Try again." : { "extractionState" : "manual", "localizations" : { @@ -3502,6 +4092,17 @@ } } }, + "Path is outside workspace roots" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "目录不在此机器允许的工作区内。" + } + } + } + }, "Paused" : { "extractionState" : "manual", "localizations" : { @@ -3535,6 +4136,17 @@ } } }, + "Permission modes control how the agent requests approval. Behavior varies by agent." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "权限模式控制代理请求审批的方式,具体行为因代理而异。" + } + } + } + }, "Permission request" : { "extractionState" : "manual", "localizations" : { @@ -3700,13 +4312,13 @@ } } }, - "Printed by the hub at startup, and shown in the web app under Settings → Companion Pairing. Pasting a full pairing link into either field also works." : { + "Printed by the hub at startup, or available in web Settings → Companion Pairing. You can also paste a pairing link here." : { "extractionState" : "manual", "localizations" : { "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "Hub 启动时打印,也显示在网页版「设置 → 伴侣应用配对」中。将完整配对链接粘贴到任一输入框同样有效。" + "value" : "可在 Hub 启动信息或网页版「设置 → 伴侣应用配对」中获取。也可在此粘贴配对链接。" } } } @@ -3986,6 +4598,17 @@ } } }, + "Remove" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "移除" + } + } + } + }, "Remove %@" : { "extractionState" : "manual", "localizations" : { @@ -4096,6 +4719,17 @@ } } }, + "Retry removal" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "重试移除" + } + } + } + }, "Run script" : { "extractionState" : "manual", "localizations" : { @@ -4162,6 +4796,28 @@ } } }, + "Save draft" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "暂存" + } + } + } + }, + "Save input, then take draft" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "先暂存,再取回" + } + } + } + }, "Scan Again" : { "extractionState" : "manual", "localizations" : { @@ -4283,6 +4939,17 @@ } } }, + "Search drafts" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "搜索草稿" + } + } + } + }, "Search files" : { "extractionState" : "manual", "localizations" : { @@ -4305,6 +4972,17 @@ } } }, + "Searching directories…" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在查找目录…" + } + } + } + }, "Section" : { "extractionState" : "manual", "localizations" : { @@ -4327,6 +5005,17 @@ } } }, + "Select a session" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "选择一个会话" + } + } + } + }, "Select all that apply" : { "extractionState" : "manual", "localizations" : { @@ -4349,6 +5038,28 @@ } } }, + "Selected machine is offline" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "所选机器已离线" + } + } + } + }, + "Selected machine is offline. Choose an online machine." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "所选机器已离线,请选择一台在线机器。" + } + } + } + }, "Send" : { "extractionState" : "manual", "localizations" : { @@ -4877,6 +5588,28 @@ } } }, + "Submitting approval…" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在提交授权…" + } + } + } + }, + "Take draft" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "取回" + } + } + } + }, "Team: %@" : { "extractionState" : "manual", "localizations" : { @@ -4943,17 +5676,6 @@ } } }, - "The address the hub prints at startup — a LAN address like http://192.168.1.20:3006, or the public tunnel URL when running with --relay." : { - "extractionState" : "manual", - "localizations" : { - "zh-Hans" : { - "stringUnit" : { - "state" : "translated", - "value" : "Hub 启动时打印的地址 — 局域网地址如 http://192.168.1.20:3006,或使用 --relay 时的公网隧道地址。" - } - } - } - }, "The app checks the hub is reachable, then exchanges the token for a session." : { "extractionState" : "manual", "localizations" : { @@ -4965,6 +5687,17 @@ } } }, + "The attachments exceed the scratchlist limits — remove a file or choose a smaller one" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "附件超出草稿夹限制,请移除附件或选择更小的文件" + } + } + } + }, "The hub answered unexpectedly (HTTP %lld). Try again in a moment." : { "extractionState" : "manual", "localizations" : { @@ -5119,6 +5852,17 @@ } } }, + "This pairing link is invalid or incomplete. Copy the full link from your hub." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "配对链接无效或不完整。请从 Hub 复制完整链接。" + } + } + } + }, "This question could not be displayed. Open details to inspect the request." : { "extractionState" : "manual", "localizations" : { @@ -5449,6 +6193,17 @@ } } }, + "View all" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "查看全部" + } + } + } + }, "View current file" : { "extractionState" : "manual", "localizations" : { @@ -5515,6 +6270,17 @@ } } }, + "View the full draft" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "查看草稿全文" + } + } + } + }, "View tool details" : { "extractionState" : "manual", "localizations" : { @@ -5636,6 +6402,17 @@ } } }, + "Write draft" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "写草稿" + } + } + } + }, "Write file" : { "extractionState" : "manual", "localizations" : { @@ -5658,6 +6435,17 @@ } } }, + "You already have a draft" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "输入框中已有内容" + } + } + } + }, "Your answer" : { "extractionState" : "manual", "localizations" : { @@ -5669,13 +6457,13 @@ } } }, - "approve %@" : { + "Your input changed — review it and try again" : { "extractionState" : "manual", "localizations" : { "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "批准 %@" + "value" : "输入内容已发生变化,请检查后重试" } } } @@ -5702,17 +6490,6 @@ } } }, - "needs input" : { - "extractionState" : "manual", - "localizations" : { - "zh-Hans" : { - "stringUnit" : { - "state" : "translated", - "value" : "需要输入" - } - } - } - }, "now" : { "extractionState" : "manual", "localizations" : { 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/CodexPlanActionPresentationTests.swift b/ios/HapiTests/CodexPlanActionPresentationTests.swift new file mode 100644 index 00000000..248125a5 --- /dev/null +++ b/ios/HapiTests/CodexPlanActionPresentationTests.swift @@ -0,0 +1,217 @@ +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 measuredSize( + _ view: V, width: CGFloat = 320, size: DynamicTypeSize = .large + ) -> CGSize { + UIHostingController(rootView: view.hapiTypography().environment(\.dynamicTypeSize, size)) + .sizeThatFits(in: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)) + } + + private func height(_ view: V, size: DynamicTypeSize = .large) -> CGFloat { + measuredSize(view, size: size).height + } + + func testActionsUseOneCompactRowAndStackWithoutClippingWhenNeeded() throws { + let driver = try Driver() + let actions = CodexPlanActionsView(planId: "proposal", interactions: driver.interactor) + .environment(\.locale, Locale(identifier: "en")) + for theme in [HapiTheme.light, .dark, .oled] { + for width: CGFloat in [320, 390, 720] { + let measured = measuredSize(actions.hapiTheme(theme), width: width) + XCTAssertEqual(measured.height, 44 + 24, accuracy: 1, + "One 44 pt row plus the card inset, without system button padding") + XCTAssertLessThanOrEqual(measured.width, width) + } + let narrow = measuredSize(actions.hapiTheme(theme), width: 220) + XCTAssertEqual(narrow.height, 2 * 44 + 8 + 24, accuracy: 1, + "Two full-width targets with an 8 pt gap") + XCTAssertLessThanOrEqual(narrow.width, 220) + let accessible = measuredSize(actions.hapiTheme(theme), size: .accessibility3) + XCTAssertGreaterThan(accessible.height, narrow.height, + "Large labels wrap and grow instead of truncating") + XCTAssertLessThanOrEqual(accessible.width, 320) + XCTAssertEqual(measuredSize(actions.hapiTheme(theme).disabled(true)).height, + measuredSize(actions.hapiTheme(theme)).height, + "Disabled styling must not shift the layout") + } + } + + 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 + 44, "A compact row of 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 - 44 } + 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") + } + + func testActionCardSpecimensInLightDarkOLEDAndLargeType() async throws { + let cases: [(String, HapiTheme, DynamicTypeSize, CGFloat)] = [ + ("light", .light, .large, 390), ("dark", .dark, .large, 390), + ("oled", .oled, .large, 390), ("narrow", .light, .large, 252), + ("large-type", .dark, .accessibility3, 390), + ] + for (name, theme, size, width) in cases { + let driver = try Driver() + let view = NavigationStack { + ScrollView { + MeasuredCard(driver: driver, block: block()) + .hapiReadingColumn() + .padding(.vertical, 16) + } + .background(theme.background) + .safeAreaInset(edge: .bottom, spacing: 0) { + ChatComposerView(interactor: driver.interactor) + } + .navigationTitle("Plan proposal") + .navigationBarTitleDisplayMode(.inline) + } + .hapiTypography().hapiTheme(theme) + .environment(\.dynamicTypeSize, size) + .environment(\.locale, Locale(identifier: "en")) + .preferredColorScheme(theme.isDark ? .dark : .light) + let window = try host(view, width: width) + defer { window.isHidden = true } + try await settle { driver.height > 100 } + try await Task.sleep(for: .milliseconds(150)) + guard let directory = ProcessInfo.processInfo.environment["HAPI_TOOL_CAPTURE"] else { continue } + let url = URL(fileURLWithPath: directory, isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + try XCTUnwrap(image.pngData()).write(to: url.appendingPathComponent("plan-actions-\(name).png")) + } + } + + private func host(_ view: V, width: CGFloat = 390) 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: width, 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/HapiTests/HomeFilterPresentationTests.swift b/ios/HapiTests/HomeFilterPresentationTests.swift index 6e806eef..a08df483 100644 --- a/ios/HapiTests/HomeFilterPresentationTests.swift +++ b/ios/HapiTests/HomeFilterPresentationTests.swift @@ -1,4 +1,5 @@ import HapiClient +import HapiProtocol import HapiUI import Observation import SwiftUI @@ -20,6 +21,7 @@ final class HomeFilterPresentationTests: XCTestCase { let navigation: Navigation var theme: HapiTheme = .light var size: DynamicTypeSize = .large + var locale = Locale(identifier: "en") var body: some View { @Bindable var navigation = navigation @@ -50,6 +52,7 @@ final class HomeFilterPresentationTests: XCTestCase { .hapiTypography() .hapiTheme(theme) .environment(\.dynamicTypeSize, size) + .environment(\.locale, locale) .environment(\.colorScheme, theme.isDark ? .dark : .light) .preferredColorScheme(theme.isDark ? .dark : .light) } @@ -117,10 +120,48 @@ final class HomeFilterPresentationTests: XCTestCase { XCTAssertTrue(model.showsFilterMenu) } + func testNativeListRowsKeepOnlyTitleAndProjectStatus() async throws { + let sessions = HomeFilterTestSessions((0..<3).map { index in + var summary = HomeFilterTestData.summary("row-\(index)", machine: nil) + summary.metadata?.summary = .init(text: "A short preview") + summary.pendingRequestsCount = index == 2 ? 0 : 1 + summary.pendingRequestKinds = [.input] + summary.thinking = index == 2 + if index > 0 { summary.todoProgress = .init(completed: 3, total: 5) } + return summary + }) + let model = HomeFilterTestData.model(sessions: sessions) + let window = try makeWindow(Harness(model: model, navigation: Navigation()), width: 390) + defer { window.isHidden = true } + try await settle() + let list = try XCTUnwrap(findCollection(window)) + let heights = try (0..<3).map { index in + try XCTUnwrap(list.layoutAttributesForItem(at: IndexPath(item: index, section: 0))).size.height + } + XCTAssertGreaterThanOrEqual(heights[0], 60) + XCTAssertLessThanOrEqual(heights[0], 70, "Two readable lines, with breathing room") + XCTAssertEqual(heights[0], heights[1], accuracy: 1, "Source progress must not add visible content") + XCTAssertEqual(heights[0], heights[2], accuracy: 1, "Activity shares the same quiet secondary line") + } + func testHomeLayoutSpecimens() async throws { - let sessions = HomeFilterTestSessions((0..<36).map { + let now = Int(Date.now.timeIntervalSince1970 * 1_000) + let sessions = HomeFilterTestSessions((0..<6).map { var row = HomeFilterTestData.summary("session-\($0)", machine: $0.isMultiple(of: 2) ? "mac" : "debian") - row.metadata?.name = ["Review session filtering", "检查离线状态与筛选反馈", "Keep the reading position"][($0 / 2) % 3] + let sample = $0 % 6 + row.metadata?.name = ["优化 iOS 首页", "Review database migration", "确认发布方案与执行权限", + "修复通知同步", "补齐离线恢复与回归测试", + "排查后台任务重试问题"][sample] + row.metadata?.flavor = sample.isMultiple(of: 2) ? "codex" : "claude" + row.metadata?.summary = .init(text: "已补齐重连逻辑和测试 · Recovery checks are ready") + row.updatedAt = now - [0, 59 * 60_000, 2 * 3_600_000, 4 * 3_600_000, 2 * 86_400_000, 330 * 86_400_000][sample] + row.pendingRequestsCount = [1, 2, 7, 0, 0, 1][sample] + row.pendingRequestKinds = sample == 1 ? [.permission] : (sample == 2 ? [.input, .permission] : [.input]) + row.thinking = sample == 0 || sample == 3 + row.active = sample != 5 + if sample == 0 || sample == 3 || sample == 4 { + row.todoProgress = .init(completed: sample == 4 ? 5 : 3, total: 5) + } return row }) let machines = HomeFilterTestMachines([ @@ -131,15 +172,20 @@ final class HomeFilterPresentationTests: XCTestCase { let cases: [(String, HapiTheme, DynamicTypeSize, CGFloat)] = [ ("light", .light, .large, 402), ("dark", .dark, .large, 402), ("compact", .light, .large, 320), ("large-text", .light, .accessibility3, 390), - ("wide", .light, .large, 768), + ("wide", .light, .large, 768), ("oled", .oled, .large, 390), + ("chinese", .light, .large, 390), ] for (name, theme, size, width) in cases { model.clearFilters() machines.machines[0].metadata?.displayName = name == "compact" || name == "large-text" ? "MacBook Pro · 上海开发环境 · very-long-machine-name.example.com" : nil - let window = try makeWindow(Harness(model: model, navigation: Navigation(), theme: theme, size: size), width: width) + let locale = Locale(identifier: name == "chinese" || name == "large-text" ? "zh-Hans" : "en") + let window = try makeWindow(Harness(model: model, navigation: Navigation(), theme: theme, size: size, locale: locale), width: width) defer { window.isHidden = true } try await settle() + // After the first-refresh baseline, mix read and unread rows. + for index in [0, 2, 4] { sessions.sessions[index].updatedAt += 1 } + try await settle() let all = try XCTUnwrap(findCollection(window)) let allTop = try firstRowTop(all, in: window) try capture(window, name: "\(name)-all") @@ -149,7 +195,7 @@ final class HomeFilterPresentationTests: XCTestCase { let filteredTop = try firstRowTop(filtered, in: window) XCTAssertGreaterThanOrEqual(filteredTop - allTop, 43, "Applied summary has a 44pt clear target") XCTAssertLessThanOrEqual(filtered.frame.width, width + 1) - XCTAssertEqual(model.rows.count, 18) + XCTAssertEqual(model.rows.count, 3) try capture(window, name: "\(name)-filtered") } } diff --git a/ios/HapiTests/ManualEntryPresentationTests.swift b/ios/HapiTests/ManualEntryPresentationTests.swift new file mode 100644 index 00000000..a4000cde --- /dev/null +++ b/ios/HapiTests/ManualEntryPresentationTests.swift @@ -0,0 +1,323 @@ +import HapiClient +import Observation +import SwiftUI +import UIKit +import XCTest +@testable import Hapi + +@MainActor +final class ManualEntryPresentationTests: XCTestCase { + @Observable + fileprivate final class Driver { + var isPairing = false + var failure: PairingFailure? + var submissions: [ManualPairingForm.Submission] = [] + var edits = 0 + } + + private struct Harness: View { + let driver: Driver + var locale = Locale(identifier: "en") + var typeSize: DynamicTypeSize = .large + + var body: some View { + NavigationStack { + ManualPairingFormView(isPairing: driver.isPairing, failure: driver.failure) { + driver.failure = nil + driver.edits += 1 + } onPair: { driver.submissions.append($0) } + .navigationTitle("Enter Hub Details") + .navigationBarTitleDisplayMode(.inline) + } + .environment(\.locale, locale) + .environment(\.dynamicTypeSize, typeSize) + } + } + + func testEmptyFieldsAndNextKeyThenExplicitSubmission() async throws { + let driver = Driver() + let window = try makeWindow(Harness(driver: driver)) + defer { window.isHidden = true } + try await settle() + let address = try field(.address, in: window) + let token = try field(.accessToken, in: window) + XCTAssertEqual(address.text, "") + XCTAssertEqual(token.text, "") + XCTAssertEqual(address.placeholder, "Domain or IP address") + XCTAssertEqual(address.accessibilityLabel, "Hub URL") + XCTAssertEqual(address.keyboardType, .URL) + XCTAssertEqual(address.autocapitalizationType, .none) + XCTAssertEqual(address.autocorrectionType, .no) + XCTAssertEqual(address.clearButtonMode, .whileEditing) + XCTAssertTrue(address.isFirstResponder) + + type("Hub.Example.com", into: address) + _ = address.delegate?.textFieldShouldReturn?(address) + try await settle() + XCTAssertTrue(token.isFirstResponder) + XCTAssertEqual(address.text, "hub.example.com") + type(" Secret+Value:team ", into: token) + try await settle() + XCTAssertTrue(driver.submissions.isEmpty) + _ = token.delegate?.textFieldShouldReturn?(token) + try await settle() + XCTAssertEqual(driver.submissions, [.init(hubURL: "https://hub.example.com", accessToken: "Secret+Value:team")]) + } + + func testBothSystemPasteLinkFormsFillEitherFieldWithoutSubmitting() async throws { + let links = [ + ("hapicompanion://bind?hub=https%3A%2F%2FHub.Example.com&code=Tok%2BValue%3Ateam", "hub.example.com"), + ("https://app.hapi.run/?hub=http%3A%2F%2F192.168.1.20%3A3006&token=Tok%2BValue%3Ateam", "192.168.1.20:3006"), + ] + for target in [ManualPairingForm.Field.address, .accessToken] { + let driver = Driver() + let window = try makeWindow(Harness(driver: driver)) + defer { window.isHidden = true } + try await settle() + let address = try field(.address, in: window) + let token = try field(.accessToken, in: window) + type("old.test", into: address) + type("old:namespace", into: token) + try await settle() + for (link, host) in links { + let input = target == .address ? address : token + // A complete link is an import even with a caret in old text. + let start = input.beginningOfDocument + let caret = try XCTUnwrap(input.textRange(from: start, to: start)) + try paste(link, into: input, range: caret) + try await settle() + XCTAssertEqual(address.text, host) + XCTAssertEqual(token.text, "Tok+Value:team") + XCTAssertTrue(driver.submissions.isEmpty, "Pasting never invokes the pairing callback") + } + } + } + + func testURLPasteChangesOnlyAddressAndLaterEditsWinAtSubmission() async throws { + let driver = Driver() + let window = try makeWindow(Harness(driver: driver)) + defer { window.isHidden = true } + try await settle() + let address = try field(.address, in: window) + let token = try field(.accessToken, in: window) + try paste("hapicompanion://bind?hub=https://old.test&code=old", into: address) + try await settle() + for _ in 0..<2 { + try paste(" HTTP://New.Test:3006/path?q=1#f \n", into: address) + try await settle() + XCTAssertEqual(address.text, "new.test:3006") + XCTAssertEqual(token.text, "old") + } + type("new:team", into: token) + try await settle() + _ = token.delegate?.textFieldShouldReturn?(token) + try await settle() + XCTAssertEqual(driver.submissions, [.init(hubURL: "http://new.test:3006", accessToken: "new:team")]) + } + + func testOrdinaryPasteHonorsSelectionAndDoesNotReadOrRewriteTheClipboard() async throws { + let driver = Driver() + let window = try makeWindow(Harness(driver: driver)) + defer { window.isHidden = true } + try await settle() + let address = try field(.address, in: window) + type("prefix.test", into: address) + try await settle() + let start = address.beginningOfDocument + let end = try XCTUnwrap(address.position(from: start, offset: 6)) + let range = try XCTUnwrap(address.textRange(from: start, to: end)) + try paste("hub", into: address, range: range) + try await settle() + XCTAssertEqual(address.text, "hub.test") + let token = try field(.accessToken, in: window) + try paste(" \nAbC+%2B:namespace\n ", into: token) + try await settle() + XCTAssertEqual(token.text, "AbC+%2B:namespace") + XCTAssertTrue(driver.submissions.isEmpty) + } + + func testSystemItemProvidersAcceptTextAndCopiedURLs() async throws { + let driver = Driver() + let window = try makeWindow(Harness(driver: driver)) + defer { window.isHidden = true } + try await settle() + let address = try field(.address, in: window) + let token = try field(.accessToken, in: window) + let link = "hapicompanion://bind?hub=https://provider.test&code=token:team" + for provider in [NSItemProvider(object: link as NSString), NSItemProvider(object: try XCTUnwrap(URL(string: link)) as NSURL)] { + type("", into: address) + type("", into: token) + try await settle() + XCTAssertTrue(address.canPaste([provider])) + address.paste(itemProviders: [provider]) + let clock = ContinuousClock() + let deadline = clock.now.advanced(by: .seconds(3)) + while token.text != "token:team", clock.now < deadline { + try await Task.sleep(for: .milliseconds(50)) + } + XCTAssertEqual(address.text, "provider.test") + XCTAssertEqual(token.text, "token:team") + XCTAssertTrue(driver.submissions.isEmpty) + } + } + + func testTypingPreservesSelectionAndClearingDoesNotRestoreTheImportedURL() async throws { + let driver = Driver() + let window = try makeWindow(Harness(driver: driver)) + defer { window.isHidden = true } + try await settle() + let address = try field(.address, in: window) + try paste("https://hub.example.com", into: address) + try await settle() + let position = try XCTUnwrap(address.position(from: address.beginningOfDocument, offset: 3)) + address.selectedTextRange = address.textRange(from: position, to: position) + address.sendActions(for: .editingChanged) + try await settle() + XCTAssertEqual(address.offset(from: address.beginningOfDocument, to: try XCTUnwrap(address.selectedTextRange).start), 3) + type("", into: address) + try await settle() + XCTAssertEqual(address.text, "") + let token = try field(.accessToken, in: window) + type("token", into: token) + try await settle() + _ = token.delegate?.textFieldShouldReturn?(token) + try await settle() + XCTAssertTrue(driver.submissions.isEmpty) + XCTAssertEqual(address.text, "") + } + + func testMalformedLinkStaysVisibleAndCannotSubmitAgainstExistingHub() async throws { + let driver = Driver() + let window = try makeWindow(Harness(driver: driver)) + defer { window.isHidden = true } + try await settle() + let address = try field(.address, in: window) + let token = try field(.accessToken, in: window) + type("original.test", into: address) + try await settle() + let broken = "https://app.hapi.run/?hub=https://new.test&token=" + try paste(broken, into: token) + try await settle() + XCTAssertEqual(address.text, "original.test") + XCTAssertEqual(token.text, broken) + _ = token.delegate?.textFieldShouldReturn?(token) + try await settle() + XCTAssertTrue(driver.submissions.isEmpty) + type("corrected:team", into: token) + try await settle() + _ = token.delegate?.textFieldShouldReturn?(token) + try await settle() + XCTAssertEqual(driver.submissions, [.init(hubURL: "https://original.test", accessToken: "corrected:team")]) + } + + func testEditsClearOldFailureAndBusyFormIgnoresLatePasteAndReturn() async throws { + let driver = Driver() + driver.failure = .invalidAccessToken + let window = try makeWindow(Harness(driver: driver)) + defer { window.isHidden = true } + try await settle() + let address = try field(.address, in: window) + let token = try field(.accessToken, in: window) + try paste("hapicompanion://bind?hub=https://hub.test&code=token", into: address) + try await settle() + XCTAssertNil(driver.failure) + driver.isPairing = true + try await settle() + XCTAssertFalse(address.isEnabled) + XCTAssertFalse(token.isEnabled) + XCTAssertEqual(address.delegate?.textField?(address, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: "late"), false) + XCTAssertEqual(token.delegate?.textFieldShouldClear?(token), false) + let edits = driver.edits + try paste("hapicompanion://bind?hub=http://wrong.test&code=wrong", into: address) + _ = token.delegate?.textFieldShouldReturn?(token) + try await settle() + XCTAssertEqual(address.text, "hub.test") + XCTAssertEqual(token.text, "token") + XCTAssertEqual(driver.edits, edits) + XCTAssertTrue(driver.submissions.isEmpty) + } + + func testSmallScreenAndLargeTypeKeepTheAddressReadable() async throws { + for (locale, typeSize, name) in [ + ("en", DynamicTypeSize.large, "empty-en"), + ("zh-Hans", .large, "empty-zh"), + ("en", .accessibility3, "large-en"), + ] { + let driver = Driver() + let window = try makeWindow(Harness(driver: driver, locale: Locale(identifier: locale), typeSize: typeSize), width: 320) + defer { window.isHidden = true } + try await settle() + let address = try field(.address, in: window) + let rect = address.convert(address.bounds, to: window) + XCTAssertGreaterThanOrEqual(rect.height, 44) + XCTAssertGreaterThan(rect.width, 130) + XCTAssertGreaterThanOrEqual(rect.minX, 0) + XCTAssertLessThanOrEqual(rect.maxX, window.bounds.width) + XCTAssertEqual(address.placeholder, locale == "zh-Hans" ? "域名或 IP 地址" : "Domain or IP address") + XCTAssertEqual(address.accessibilityLabel, locale == "zh-Hans" ? "Hub 地址" : "Hub URL") + if typeSize.isAccessibilitySize { + XCTAssertGreaterThan(try XCTUnwrap(address.font).pointSize, 25) + } + try capture(window, named: name) + } + } + + func testImportedHTTPDetailsAreVisibleForReview() async throws { + let driver = Driver() + let window = try makeWindow(Harness(driver: driver, locale: Locale(identifier: "zh-Hans"))) + defer { window.isHidden = true } + try await settle() + let address = try field(.address, in: window) + try paste("https://app.hapi.run/?hub=http%3A%2F%2F192.168.1.20%3A3006&token=demo%3Ateam", into: address) + try await settle() + XCTAssertEqual(address.text, "192.168.1.20:3006") + XCTAssertEqual(try field(.accessToken, in: window).text, "demo:team") + XCTAssertTrue(driver.submissions.isEmpty) + try capture(window, named: "imported-http-zh") + } + + private func field(_ field: ManualPairingForm.Field, in window: UIWindow) throws -> UITextField { + let identifier = field == .address ? "pairing.address" : "pairing.accessToken" + func find(_ view: UIView) -> UITextField? { + if let field = view as? UITextField, field.accessibilityIdentifier == identifier { return field } + return view.subviews.lazy.compactMap(find).first + } + return try XCTUnwrap(find(window), identifier) + } + + private func type(_ value: String, into field: UITextField) { + field.text = value + field.sendActions(for: .editingChanged) + } + + private func paste(_ value: String, into field: UITextField, range: UITextRange? = nil) throws { + let delegate = try XCTUnwrap(field.pasteDelegate) + let range = try XCTUnwrap(range ?? field.textRange(from: field.beginningOfDocument, to: field.endOfDocument)) + // Inject the system-delivered payload, never touch the user's clipboard. + _ = delegate.textPasteConfigurationSupporting?(field, performPasteOf: NSAttributedString(string: value), to: range) + } + + private func makeWindow(_ view: V, width: CGFloat = 390) 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: width, height: 900) + window.rootViewController = UIHostingController(rootView: view) + window.makeKeyAndVisible() + window.layoutIfNeeded() + return window + } + + private func settle() async throws { try await Task.sleep(for: .milliseconds(220)) } + + private func capture(_ window: UIWindow, named name: String) throws { + guard let path = ProcessInfo.processInfo.environment["HAPI_PAIRING_CAPTURE"] else { return } + let directory = URL(fileURLWithPath: path, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let format = UIGraphicsImageRendererFormat() + format.scale = 2 + let image = UIGraphicsImageRenderer(bounds: window.bounds, format: format).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + try XCTUnwrap(image.pngData()).write(to: directory.appendingPathComponent(name + ".png")) + } +} diff --git a/ios/HapiTests/ManualPairingFormTests.swift b/ios/HapiTests/ManualPairingFormTests.swift new file mode 100644 index 00000000..148ad81a --- /dev/null +++ b/ios/HapiTests/ManualPairingFormTests.swift @@ -0,0 +1,194 @@ +import XCTest +@testable import Hapi + +final class ManualPairingFormTests: XCTestCase { + private let companion = "hapicompanion://bind?hub=https%3A%2F%2FHub.Example.com%3A443%2F&code=Tok%2BValue%3Ateam" + private let web = "https://app.hapi.run/?hub=http%3A%2F%2F192.168.1.20%3A3006&token=Tok%2BValue%3Ateam" + + func testPristineFormHasNoExampleValuesOrErrors() { + var form = ManualPairingForm() + XCTAssertEqual(form.scheme, .https) + XCTAssertEqual(form.address, "") + XCTAssertEqual(form.accessToken, "") + XCTAssertNil(form.submission) + XCTAssertNil(form.error(for: .address)) + XCTAssertNil(form.error(for: .accessToken)) + form.selectScheme(.http) + XCTAssertEqual(form.address, "") + XCTAssertNil(form.error(for: .address), "Selecting a protocol must not validate an untouched empty address") + } + + func testTypingIsNotRewrittenUntilEditingEnds() { + var form = ManualPairingForm() + for input in ["h", "https:", "https://", " HTTPS://Hub.Example.com:443/path?q=1#f "] { + form.edit(input, in: .address) + XCTAssertEqual(form.address, input) + XCTAssertNil(form.error(for: .address)) + } + form.finishEditing(.address) + XCTAssertEqual(form.address, "hub.example.com") + XCTAssertEqual(form.scheme, .https) + XCTAssertNil(form.error(for: .address)) + } + + func testBareAddressesUseTheSelectedSchemeWithoutGuessing() throws { + for scheme in ManualPairingForm.Scheme.allCases { + for host in ["Hub.Example.com", "192.168.1.20:3006", "localhost:3006", "[::1]:3006"] { + var form = readyForm() + form.selectScheme(scheme) + form.edit(host, in: .address) + form.finishEditing(.address) + XCTAssertEqual(try XCTUnwrap(form.submission).hubURL, scheme.prefix + host.lowercased()) + } + } + } + + func testURLPastesReplaceAddressAndSynchronizeSchemeWithoutChangingToken() throws { + var form = readyForm() + for (url, origin, scheme) in [ + (" HTTP://192.168.1.20:3006/path\n", "http://192.168.1.20:3006", ManualPairingForm.Scheme.http), + ("https://Hub.Example.com:443/", "https://hub.example.com", .https), + ("http://hub.example.com:80/?q=1#f", "http://hub.example.com", .http), + ("https://[2001:db8::1]:8443/", "https://[2001:db8::1]:8443", .https), + ] { + for _ in 0..<2 { + XCTAssertTrue(form.paste(url, into: .address)) + XCTAssertEqual(form.scheme, scheme) + XCTAssertEqual(form.scheme.prefix + form.address, origin) + XCTAssertEqual(try XCTUnwrap(form.submission).hubURL, origin) + XCTAssertEqual(form.accessToken, "original:team") + XCTAssertFalse(form.didImportLink) + } + } + } + + func testMenuSelectionWinsOverAnExplicitSchemeStillBeingEdited() throws { + var form = readyForm() + form.edit("https://hub.example.com:8443", in: .address) + form.selectScheme(.http) + XCTAssertEqual(form.address, "hub.example.com:8443") + XCTAssertEqual(try XCTUnwrap(form.submission).hubURL, "http://hub.example.com:8443") + } + + func testBothLinkFormsImportFromEitherFieldAndReplaceTheWholeForm() throws { + for field in [ManualPairingForm.Field.address, .accessToken] { + for (link, origin) in [(companion, "https://hub.example.com"), (web, "http://192.168.1.20:3006")] { + var form = readyForm() + for _ in 0..<2 { + XCTAssertTrue(form.paste(" \n" + link + " \n", into: field)) + XCTAssertTrue(form.didImportLink) + XCTAssertEqual(form.scheme.prefix + form.address, origin) + XCTAssertEqual(form.accessToken, "Tok+Value:team") + XCTAssertEqual(try XCTUnwrap(form.submission), .init(hubURL: origin, accessToken: "Tok+Value:team")) + XCTAssertNil(form.error(for: .address)) + XCTAssertNil(form.error(for: .accessToken)) + } + } + } + } + + func testAHandTypedLinkIsOnlyImportedAtEndEditing() { + var form = ManualPairingForm() + for input in ["hapicompanion:", "hapicompanion://bind?hub=https://hub.test&code=t", companion] { + form.edit(input, in: .address) + XCTAssertEqual(form.address, input) + XCTAssertEqual(form.accessToken, "") + XCTAssertFalse(form.didImportLink) + XCTAssertNil(form.submission, "Raw links are never a hidden submit source") + } + form.finishEditing(.address) + XCTAssertEqual(form.address, "hub.example.com") + XCTAssertTrue(form.didImportLink) + XCTAssertNotNil(form.submission) + } + + func testEditsAfterImportAreTheOnlySubmissionSource() throws { + var form = ManualPairingForm() + form.paste(companion, into: .accessToken) + form.edit("new:namespace", in: .accessToken) + form.edit("different.example.com:8443", in: .address) + form.selectScheme(.http) + XCTAssertFalse(form.didImportLink) + XCTAssertEqual(try XCTUnwrap(form.submission), .init(hubURL: "http://different.example.com:8443", accessToken: "new:namespace")) + form.edit("", in: .address) + XCTAssertNil(form.submission) + form.edit("hub.test", in: .address) + form.edit(" \n ", in: .accessToken) + XCTAssertNil(form.submission) + } + + func testMalformedLinksStayVisibleAndNeverFallBackToTheWebHost() { + let invalidLinks = [ + "hapicompanion://bind?hub=https://hub.test", + "hapicompanion://pair?hub=https://hub.test&code=secret", + "https://app.hapi.run/?hub=https://hub.test", + "https://app.hapi.run/?token=secret", + "https://app.hapi.run/?hub=https://hub.test&token=", + "https://app.hapi.run/?hub=ftp://hub.test&token=secret", + "https://app.hapi.run/?hub=https://hub.test&token=%zz", + "https://app.hapi.run/?%68ub=https://hub.test&code=secret", + "hapicompanion://bind?hub=https://hub.test:99999&code=secret", + ] + for field in [ManualPairingForm.Field.address, .accessToken] { + for link in invalidLinks { + var form = readyForm() + XCTAssertTrue(form.paste(link, into: field)) + XCTAssertEqual(form.text(for: field), link) + XCTAssertEqual(form.error(for: field), .invalidLink, link) + XCTAssertEqual(form.scheme, .https) + XCTAssertEqual(field == .address ? form.accessToken : form.address, + field == .address ? "original:team" : "original.test") + XCTAssertFalse(form.didImportLink) + XCTAssertNil(form.submission) + } + } + } + + func testInvalidAddressesBlockSubmissionAndErrorsAppearAfterEditingEnds() { + for input in ["", " ", "https://", "ftp://hub.test", "file:///tmp/hub", "bad host", "https://user:pass@hub.test", "hub.test:99999", "hub.test:0", "https://hub.test/%zz", "::1"] { + var form = readyForm() + form.edit(input, in: .address) + XCTAssertNil(form.error(for: .address)) + XCTAssertNil(form.submission, input) + form.finishEditing(.address) + XCTAssertEqual(form.error(for: .address), .invalidAddress, input) + form.edit("valid.test", in: .address) + XCTAssertNil(form.error(for: .address)) + XCTAssertNotNil(form.submission) + } + } + + func testOrdinaryTextUsesTheTextControlsInsertionRules() { + var form = readyForm() + for field in [ManualPairingForm.Field.address, .accessToken] { + for text in ["hub.test", "secret:team", "segment", "\n"] { + XCTAssertFalse(form.paste(text, into: field)) + XCTAssertEqual(form.address, "original.test") + XCTAssertEqual(form.accessToken, "original:team") + } + } + XCTAssertFalse(form.paste("https://not-a-pairing-link.test", into: .accessToken)) + } + + func testTokenRemainsOpaqueExceptForSurroundingWhitespace() throws { + var form = readyForm() + for token in [" AbC+Def%2B:namespace ", "token?token=value", "a b:team", "https://an-opaque-token.test"] { + form.edit(token, in: .accessToken) + form.finishEditing(.accessToken) + let expected = token.trimmingCharacters(in: .whitespacesAndNewlines) + XCTAssertEqual(form.accessToken, expected) + XCTAssertEqual(try XCTUnwrap(form.submission).accessToken, expected) + } + form.edit("\n ", in: .accessToken) + form.finishEditing(.accessToken) + XCTAssertEqual(form.error(for: .accessToken), .missingToken) + XCTAssertNil(form.submission) + } + + private func readyForm() -> ManualPairingForm { + var form = ManualPairingForm() + form.edit("original.test", in: .address) + form.edit("original:team", in: .accessToken) + return form + } +} diff --git a/ios/HapiTests/NewSessionDirectoryTests.swift b/ios/HapiTests/NewSessionDirectoryTests.swift new file mode 100644 index 00000000..5921303b --- /dev/null +++ b/ios/HapiTests/NewSessionDirectoryTests.swift @@ -0,0 +1,214 @@ +import Foundation +import HapiClient +import HapiProtocol +import XCTest +@testable import Hapi + +@MainActor +final class NewSessionDirectoryTests: XCTestCase { + func testClearingDirectorySurvivesRosterRefreshWithoutResettingModel() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + await harness.model.start() + harness.model.setModel("opus") + harness.model.setDirectory("") + try await harness.session.machineStore.refresh() + harness.model.machinesChanged() + XCTAssertEqual(harness.model.form.directory, "") + XCTAssertEqual(harness.model.form.model, "opus") + XCTAssertFalse(harness.model.canCreate) + } + + func testRestoredEmptyDirectoryIsNotReseeded() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + harness.prefs.writeDraft(NewSessionForm(machineId: "m1", directory: "", model: "opus")) + await harness.model.start() + XCTAssertEqual(harness.model.form.directory, "") + XCTAssertEqual(harness.model.form.model, "opus") + } + + func testExplicitPickOfFallbackSurvivesLateRecentDirectoryResponse() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + harness.prefs.writePrefs(NewSessionPrefsData(lastMachineId: "m1", recentPaths: ["m1": ["/recent"]])) + await harness.http.holdPath("/recent") + await harness.model.start() + try await newSessionEventually { await harness.http.waitingPaths.contains("/recent") } + // Same text as the automatic fallback: string equality alone is insufficient. + harness.model.pickRecentPath("/home/m1") + await harness.http.releasePaths() + try await newSessionEventually { await harness.http.completedPaths.contains("/recent") } + XCTAssertEqual(harness.model.form.directory, "/home/m1") + XCTAssertEqual(harness.prefs.readDraft()?.directory, "/home/m1") + } + + func testOfflineSelectionRetainsItsPathAndExplicitSwitchUsesTheNewMachineDefault() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + await harness.model.start() + harness.model.setDirectory("/project/on/m1") + harness.session.machineStore.applyMachineEvent(machineId: "m1", data: .removed) + harness.model.machinesChanged() + XCTAssertEqual(harness.model.form.machineId, "m1") + XCTAssertEqual(harness.model.form.directory, "/project/on/m1") + XCTAssertTrue(harness.model.machineUnavailable) + XCTAssertFalse(harness.model.canCreate) + harness.model.create() + let spawns = await harness.http.spawns + XCTAssertTrue(spawns.isEmpty) + harness.model.setMachine("m2") + XCTAssertEqual(harness.model.form.machineId, "m2") + XCTAssertEqual(harness.model.form.directory, "/home/m2") + XCTAssertFalse(harness.model.machineUnavailable) + } + + func testHomeExpansionIsUsedForChecksSpawnAndRecentPaths() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + await harness.model.start() + harness.model.setDirectory("~/project") + try await newSessionEventually { harness.model.canCreate } + harness.model.create() + try await newSessionEventually { !harness.model.isSpawning } + let spawns = await harness.http.spawns + XCTAssertEqual(spawns.map(\.directory), ["/home/m1/project"]) + let paths = await harness.http.checkedPaths + XCTAssertTrue(paths.contains("/home/m1/project")) + XCTAssertFalse(paths.contains("~/project")) + XCTAssertEqual(harness.prefs.readPrefs().recentPaths["m1"], ["/home/m1/project"]) + XCTAssertNil(harness.prefs.readDraft()) + } + + func testMissingDirectoryRequiresSecondTapAndWorktreeRemainsBlocked() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + await harness.model.start() + harness.model.setDirectory("/missing") + try await newSessionEventually { harness.model.canCreate } + harness.model.create() + try await newSessionEventually { !harness.model.isSpawning } + XCTAssertTrue(harness.model.confirmCreateDirectory) + let firstSpawns = await harness.http.spawns + XCTAssertTrue(firstSpawns.isEmpty) + harness.model.create() + try await newSessionEventually { !harness.model.isSpawning } + let confirmedSpawns = await harness.http.spawns + XCTAssertEqual(confirmedSpawns.count, 1) + + harness.model.setDirectory("/missing-worktree") + harness.model.setSessionType(.worktree) + try await newSessionEventually { !harness.model.directoryInput.isCheckingExistence } + XCTAssertFalse(harness.model.canCreate) + harness.model.create() + let finalSpawns = await harness.http.spawns + XCTAssertEqual(finalSpawns.count, 1) + } + + func testMachineGoingOfflineDuringCreatePreflightDoesNotSpawnElsewhere() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + await harness.model.start() + harness.model.setDirectory("/project") + try await newSessionEventually { harness.model.canCreate && !harness.model.directoryInput.isCheckingExistence } + await harness.http.holdPath("/project") + harness.model.create() + try await newSessionEventually { await harness.http.waitingPaths.contains("/project") } + harness.session.machineStore.applyMachineEvent(machineId: "m1", data: .removed) + harness.model.machinesChanged() + await harness.http.releasePaths() + try await newSessionEventually { !harness.model.isSpawning } + let spawns = await harness.http.spawns + XCTAssertTrue(spawns.isEmpty) + XCTAssertEqual(harness.model.spawnError, NewSessionModel.msgMachineOffline) + XCTAssertEqual(harness.model.form.machineId, "m1") + } +} + +@MainActor +private func newSessionEventually(_ condition: @MainActor () async -> Bool) async throws { + let clock = ContinuousClock() + let deadline = clock.now.advanced(by: .seconds(4)) + while clock.now < deadline { + if await condition() { return } + try await Task.sleep(for: .milliseconds(5)) + } + XCTFail("New-session state did not settle") + throw URLError(.timedOut) +} + +@MainActor +private final class NewSessionDirectoryHarness { + let http = NewSessionDirectoryHTTP() + let session: HubSession + let model: NewSessionModel + let prefs: NewSessionPrefsStore + + init() throws { + let hubUrl = "https://directory-\(UUID().uuidString.lowercased()).test" + let credentials = InMemoryCredentialStore() + let payload = Data(#"{"uid":1,"exp":4102444800,"ns":"test"}"#.utf8).base64EncodedString() + try credentials.store(HubCredentials(hubUrl: hubUrl, accessToken: "test", jwt: "e30.\(payload).test")) + session = try XCTUnwrap(HubSession(hubUrl: hubUrl, credentialStore: credentials, performer: http)) + let defaults = try XCTUnwrap(UserDefaults(suiteName: UUID().uuidString)) + prefs = NewSessionPrefsStore(hubUrl: hubUrl, defaults: defaults) + model = NewSessionModel(session: session, defaults: defaults, onCreated: { _ in }) + } +} + +private actor NewSessionDirectoryHTTP: HTTPPerforming { + private(set) var spawns: [SpawnRequest] = [] + private(set) var checkedPaths: [String] = [] + private(set) var completedPaths: [String] = [] + private(set) var waitingPaths: Set = [] + private var heldPaths: Set = [] + private var waiters: [CheckedContinuation] = [] + + func holdPath(_ path: String) { heldPaths.insert(path) } + func releasePaths() { + heldPaths = [] + waitingPaths = [] + let pending = waiters + waiters = [] + for waiter in pending { waiter.resume() } + } + + func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + let url = try XCTUnwrap(request.url) + let data: Data + if url.path == "/api/machines" { + struct Roster: Encodable { let machines: [Machine] } + let machines = ["m1", "m2"].map { id in + Machine( + id: id, namespace: "test", seq: 1, createdAt: 0, updatedAt: 0, active: true, activeAt: 0, + metadata: MachineMetadata(host: id, platform: "linux", happyCliVersion: "test", homeDir: "/home/\(id)"), + metadataVersion: 1, runnerStateVersion: 0 + ) + } + data = try HapiJSON.encoder.encode(Roster(machines: machines)) + } else if url.path.hasSuffix("/agent-availability") { + data = Data(#"{"agents":[{"agent":"claude","available":true}]}"#.utf8) + } else if url.path.hasSuffix("/list-directory") { + data = Data(#"{"success":true,"entries":[]}"#.utf8) + } else if url.path.hasSuffix("/paths/exists") { + struct PathsRequest: Decodable { let paths: [String] } + let paths = try HapiJSON.decoder.decode(PathsRequest.self, from: XCTUnwrap(request.httpBody)).paths + checkedPaths += paths + if paths.contains(where: heldPaths.contains) { + waitingPaths.formUnion(paths) + await withCheckedContinuation { waiters.append($0) } + } + completedPaths += paths + data = try HapiJSON.encoder.encode(MachinePathsExistsResponse( + exists: Dictionary(uniqueKeysWithValues: paths.map { ($0, !$0.hasPrefix("/missing")) }) + )) + } else if url.path.hasSuffix("/spawn") { + spawns.append(try HapiJSON.decoder.decode(SpawnRequest.self, from: XCTUnwrap(request.httpBody))) + data = Data(#"{"type":"success","sessionId":"created"}"#.utf8) + } else { + XCTFail("Unexpected new-session request: \(url.path)") + throw URLError(.badURL) + } + return (data, try XCTUnwrap(HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil))) + } +} diff --git a/ios/HapiTests/PermissionActionPresentationTests.swift b/ios/HapiTests/PermissionActionPresentationTests.swift new file mode 100644 index 00000000..3e0b8bfe --- /dev/null +++ b/ios/HapiTests/PermissionActionPresentationTests.swift @@ -0,0 +1,460 @@ +import HapiClient +import HapiUI +import Observation +import SwiftUI +import UIKit +import XCTest +@testable import Hapi +@testable import HapiProtocol + +/// Actual approval cards over deterministic HTTP; never activates a real chat, +/// reads Keychain credentials, or sends a permission decision to a hub. +@MainActor +final class PermissionActionPresentationTests: XCTestCase { + @Observable @MainActor + final class Driver { + var tool: ChatToolCall + var notice: String? + let http: ApprovalHTTP + let store: SessionListStore + let interactor: ChatInteractor + @ObservationIgnored var height: CGFloat = 0 + @ObservationIgnored var appearances = 0 + + init(flavor: String = "claude", toolName: String = "Bash") async throws { + let input: JSONValue = .object(["command": .string("git diff -- ios/Hapi")]) + tool = ChatToolCall(id: "tool", name: toolName, state: .pending, input: input, + createdAt: 0, permission: ToolPermission(id: "approval", status: .pending)) + let session = Session( + id: "approval-test", namespace: "test", seq: 1, createdAt: 0, updatedAt: 0, + active: true, activeAt: 0, + metadata: SessionMetadata(path: "/workspace/hapi", host: "test", flavor: flavor), + metadataVersion: 1, + agentState: AgentState(requests: ["approval": AgentStateRequest(tool: toolName, arguments: input)]), + agentStateVersion: 1, thinking: false, thinkingAt: 0 + ) + http = ApprovalHTTP(session: session) + let url = try XCTUnwrap(URL(string: "http://127.0.0.1:1")) + let credentials = InMemoryCredentialStore() + let payload = Data(#"{"uid":1,"exp":4102444800,"ns":"test"}"#.utf8).base64EncodedString() + try credentials.store(HubCredentials(hubUrl: url.absoluteString, accessToken: "test", jwt: "e30.\(payload).test")) + let auth = AuthManager(baseURL: url, credentialStore: credentials, performer: http) + let api = APIClient(baseURL: url, authManager: auth, performer: http) + store = SessionListStore(api: api) + try await store.loadSessionDetail(session.id) + interactor = ChatInteractor(sessionId: session.id, api: api, sessionStore: store, + windows: MessageWindowControllers(provider: api)) + interactor.onEvent = { [weak self] event in + if case .notice(let notice) = event { self?.notice = notice } + } + } + + var block: ToolCallBlock { + ToolCallBlock(id: tool.id, localId: nil, createdAt: 0, invokedAt: nil, + durationMs: nil, usage: nil, model: nil, tool: tool, children: [], meta: nil) + } + + func settlePermission(_ status: ToolPermissionStatus) { + store.applySessionEvent(.sessionUpdated(namespace: nil, sessionId: "approval-test", data: .patch(SessionPatch( + agentState: VersionedValue(version: 2, value: AgentState(requests: [:])) + )))) + tool.permission = ToolPermission(id: "approval", status: status) + tool.state = .completed + } + } + + actor ApprovalHTTP: HTTPPerforming { + struct Post: Sendable { + let path: String + let body: String? + } + let session: Session + var status = 200 + var held = false + var waiters: [CheckedContinuation] = [] + private(set) var posts: [Post] = [] + + init(session: Session) { self.session = session } + func setStatus(_ value: Int) { status = value } + func hold() { held = true } + func release() { + held = false + let pending = waiters + waiters.removeAll() + pending.forEach { $0.resume() } + } + + func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + let url = try XCTUnwrap(request.url) + let data: Data + var responseStatus = 200 + if request.httpMethod == "POST", url.path.contains("/permissions/") { + posts.append(Post(path: url.path, body: request.httpBody.map { String(decoding: $0, as: UTF8.self) })) + if held { await withCheckedContinuation { waiters.append($0) } } + responseStatus = status + data = Data((status == 200 ? #"{"ok":true}"# : #"{"error":"Approval failed"}"#).utf8) + } else if request.httpMethod == "GET", url.path == "/api/sessions/approval-test" { + data = try HapiJSON.encoder.encode(SessionResponse(session: session)) + } else { + throw URLError(.unsupportedURL) + } + return (data, try XCTUnwrap(HTTPURLResponse(url: url, statusCode: responseStatus, httpVersion: nil, headerFields: nil))) + } + } + + private struct Card: View { + let driver: Driver + var body: some View { + ToolCallBlockView(block: driver.block, basePath: "/workspace/hapi") + .environment(\.chatInteractions, driver.interactor) + .background(GeometryReader { geometry in + Color.clear + .onAppear { driver.height = geometry.size.height; driver.appearances += 1 } + .onChange(of: geometry.size.height) { _, height in driver.height = height } + }) + .hapiReadingColumn() + } + } + + private struct Specimen: View { + let driver: Driver + var theme = HapiTheme.light + var size = DynamicTypeSize.large + var locale = Locale(identifier: "en") + var body: some View { + NavigationStack { + ScrollView { + VStack(alignment: .leading, spacing: 16) { + UserTextBlockView(block: UserTextBlock( + id: "user", localId: nil, createdAt: 0, invokedAt: nil, + text: "请检查一下 iOS 界面的改动。", attachments: nil, + status: nil, originalText: nil, meta: nil + )).hapiReadingColumn() + Card(driver: driver) + } + .padding(.vertical, 16) + } + .background(theme.background) + .safeAreaInset(edge: .bottom, spacing: 0) { + ChatComposerView(interactor: driver.interactor) + } + .navigationTitle("HAPI · Approval") + .navigationBarTitleDisplayMode(.inline) + } + .hapiTypography().hapiTheme(theme) + .environment(\.dynamicTypeSize, size) + .environment(\.locale, locale) + .preferredColorScheme(theme.isDark ? .dark : .light) + } + } + + func testFlavorAndToolGatesRetainTheirExistingPermissionSemantics() { + for (flavor, tool, deny, session, edits) in [ + ("claude", "Bash", PermissionAction.deny, true, false), + ("claude", "Edit", .deny, false, true), + ("claude", "ExitPlanMode", .deny, false, false), + ("codex", "exec_command", .abort, true, false), + ("codex", "Edit", .abort, true, false), + ("cursor", "CursorBash", .abort, true, false), + ("gemini", "GeminiBash", .abort, true, false), + ] { + let options = PermissionActionOptions(flavor: flavor, toolName: tool) + XCTAssertEqual(options.denyAction, deny, "\(flavor), \(tool)") + XCTAssertEqual(options.canAllowForSession, session) + XCTAssertEqual(options.canAllowAllEdits, edits) + XCTAssertEqual(options.hasMore, session || edits) + } + XCTAssertEqual(PermissionActionOptions(flavor: nil, toolName: "CodexPermission").denyAction, .abort) + for tool in PermissionGates.editTools { + XCTAssertTrue(PermissionActionOptions(flavor: "claude", toolName: tool).canAllowAllEdits) + } + } + + func testApprovalActionsHave44PointOuterTargetsAndNeverShiftWhenDisabled() { + for theme in [HapiTheme.light, .dark, .oled] { + for locale in ["en", "zh-Hans"] { + for tool in ["Bash", "Edit", "ExitPlanMode"] { + let options = PermissionActionOptions(flavor: "claude", toolName: tool) + let ready = PermissionActionsRow(options: options, requestId: "approval", resolving: false) { _ in } + .hapiTheme(theme).environment(\.locale, Locale(identifier: locale)) + let busy = PermissionActionsRow(options: options, requestId: "approval", resolving: true) { _ in } + .hapiTheme(theme).environment(\.locale, Locale(identifier: locale)) + for width: CGFloat in [288, 358, 720] { + let measured = measure(ready, width: width) + XCTAssertEqual(measured.height, 44, accuracy: 1, "The entire button, not just its label, is 44 pt") + XCTAssertLessThanOrEqual(measured.width, width) + XCTAssertEqual(measure(busy, width: width).height, measured.height, accuracy: 1) + } + for (width, size) in [(CGFloat(120), DynamicTypeSize.large), (288, .accessibility5)] { + let measured = measure(ready, width: width, size: size) + if options.hasMore || size.isAccessibilitySize { XCTAssertGreaterThan(measured.height, 44) } + if size.isAccessibilitySize { + XCTAssertGreaterThanOrEqual(measured.height, options.hasMore ? 3 * 44 + 16 : 2 * 44 + 8) + } + XCTAssertLessThanOrEqual(measured.width, width) + XCTAssertEqual(measure(busy, width: width, size: size).height, measured.height, accuracy: 1) + } + } + } + } + } + + func testSubmittingPreservesGeometryAndSendsOnlyOneDecisionUntilSSESettles() async throws { + let driver = try await Driver(flavor: "codex", toolName: "CodexBash") + let (window, _) = try host(Specimen(driver: driver)) + defer { window.isHidden = true } + try await eventually { driver.height > 100 } + let initial = driver.height + await driver.http.hold() + defer { Task { await driver.http.release() } } + driver.interactor.resolvePermission(requestId: "approval", action: .abort) + driver.interactor.resolvePermission(requestId: "approval", action: .allow) + try await eventually { await driver.http.posts.count == 1 } + try await layoutSettles() + XCTAssertEqual(driver.height, initial, accuracy: 1) + XCTAssertEqual(driver.interactor.permissionOverrides["approval"], .resolving) + let posts = await driver.http.posts + let post = try XCTUnwrap(posts.first) + XCTAssertTrue(post.path.hasSuffix("/approval/deny")) + XCTAssertEqual(post.body, #"{"decision":"abort"}"#) + try capture(window, name: "submitting") + await driver.http.release() + try await layoutSettles() + XCTAssertEqual(driver.interactor.permissionOverrides["approval"], .resolving, "HTTP success alone is not a verdict") + driver.settlePermission(.denied) + try await eventually { driver.height < initial - 44 } + XCTAssertNil(driver.interactor.permissionOverrides["approval"]) + try capture(window, name: "denied") + } + + func testAlreadyHandledResponsesRemoveTheActionArea() async throws { + for status in [404, 409] { + let driver = try await Driver() + let (window, _) = try host(Specimen(driver: driver)) + defer { window.isHidden = true } + try await eventually { driver.height > 100 } + let initial = driver.height + await driver.http.setStatus(status) + driver.interactor.resolvePermission(requestId: "approval", action: .allow) + try await eventually { driver.interactor.permissionOverrides["approval"] == .alreadyHandled && driver.height < initial - 40 } + try capture(window, name: "handled-\(status)") + } + } + + func testFailureRestoresActionsAndSessionApprovalKeepsItsExistingWireBody() async throws { + let driver = try await Driver() + let (window, _) = try host(Specimen(driver: driver)) + defer { window.isHidden = true } + try await eventually { driver.height > 100 } + let initial = driver.height + await driver.http.setStatus(500) + driver.interactor.resolvePermission(requestId: "approval", action: .allow) + try await eventually { driver.notice != nil } + XCTAssertNil(driver.interactor.permissionOverrides["approval"]) + try await layoutSettles() + XCTAssertEqual(driver.height, initial, accuracy: 1) + await driver.http.setStatus(200) + driver.interactor.resolvePermission(requestId: "approval", action: .allowForSession) + try await eventually { await driver.http.posts.count == 2 } + let posts = await driver.http.posts + let post = try XCTUnwrap(posts.last) + XCTAssertEqual(post.body, #"{"allowTools":["Bash(git diff -- ios/Hapi)"]}"#) + driver.settlePermission(.approved) + try await eventually { driver.height < initial - 44 } + } + + private struct Row: Identifiable, Equatable { + let index: Int + var id: String { String(index) } + } + + private struct Transcript: View { + let driver: Driver + var body: some View { + AnchoredTranscriptList( + items: (0..<40).map { Row(index: $0) }, historyVersion: 0, jumpToken: 0, + historyControlID: "-1", onViewport: { _ in }, onLayout: { _, _ in } + ) { row in + AnyView(Group { + if row.index == 10 { Card(driver: driver) } + else { Text("Message \(row.id)").frame(maxWidth: .infinity).frame(height: 100) } + }) + } + .hapiTypography() + } + } + + func testRecyclingRetainsSubmissionAndSettlementPreservesTheReadingAnchor() async throws { + let driver = try await Driver() + let (window, host) = try host(Transcript(driver: driver)) + defer { window.isHidden = true } + func find(_ view: UIView) -> UICollectionView? { + (view as? UICollectionView) ?? view.subviews.lazy.compactMap(find).first + } + let list = try XCTUnwrap(find(host.view)) + try await eventually { list.numberOfItems(inSection: 0) == 40 } + func browse(_ index: Int) async throws { + list.delegate?.scrollViewWillBeginDragging?(list) + list.scrollToItem(at: IndexPath(item: index, section: 0), at: .top, animated: false) + try await eventually { list.cellForItem(at: IndexPath(item: index, section: 0)) != nil } + try await layoutSettles() + } + try await browse(10) + let height = driver.height + let appearances = driver.appearances + await driver.http.hold() + defer { Task { await driver.http.release() } } + driver.interactor.resolvePermission(requestId: "approval", action: .allow) + try await eventually { await driver.http.posts.count == 1 } + try await browse(32) + try await browse(10) + XCTAssertGreaterThan(driver.appearances, appearances) + XCTAssertEqual(driver.interactor.permissionOverrides["approval"], .resolving) + XCTAssertEqual(driver.height, height, accuracy: 1) + let cell = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 10, section: 0))) + let offset = cell.frame.minY - list.contentOffset.y + await driver.http.release() + driver.settlePermission(.approved) + try await eventually { driver.height < height - 44 } + try await layoutSettles() + XCTAssertEqual(cell.frame.minY - list.contentOffset.y, offset, accuracy: 1) + } + + func testProcessAndReadOnlyApprovalsUseCompactStatusPresentation() async throws { + let driver = try await Driver() + let summary = toolSummaryPresentation(driver.tool, basePath: nil) + let approvalHeader = ToolSummaryRow(presentation: summary, state: .pending, showsStatus: false) {} + let genericHeader = ToolSummaryRow(presentation: summary, state: .pending) {} + XCTAssertLessThan(measure(approvalHeader, width: 320, size: .accessibility3).height, + measure(genericHeader, width: 320, size: .accessibility3).height) + let process = PendingPermissionFooter(tool: driver.tool, requestId: "approval", interactions: driver.interactor) + XCTAssertEqual(measure(process, width: 320).height, 44 + 8 + 44 + 24, accuracy: 1) + let readonly = PermissionStateRow(permission: try XCTUnwrap(driver.tool.permission)) + XCTAssertLessThan(measure(readonly, width: 320).height, 44) + let pendingHeader = measure(ToolDetailHeader(block: driver.block, basePath: nil), width: 320).height + for state in [ToolCallState.running, .error] { + var block = driver.block + block.tool.state = state + XCTAssertGreaterThan(measure(ToolDetailHeader(block: block, basePath: nil), width: 320).height, + pendingHeader + 16, "Only the duplicate pending marker is hidden, not running/errors") + } + for status in [ToolPermissionStatus.approved, .denied, .resolved, .canceled] { + let verdict = PermissionStateRow(permission: ToolPermission(id: "approval", status: status)) + XCTAssertLessThan(measure(verdict, width: 320).height, 44) + XCTAssertLessThanOrEqual(measure(verdict, width: 288, size: .accessibility5).width, 288) + } + } + + func testQueuedActionsFitSmallColumnsLargeTypeAndDisabledRows() async throws { + let driver = try await Driver() + func row(enabled: Bool = true, uncertain: Bool = false, scheduled: Bool = false) -> QueuedRowView { + QueuedRowView(row: QueuedMessageRow( + id: "queued", localId: "local", text: "Update", attachmentNames: [], + scheduledAt: scheduled ? 1_800_000_000_000 : nil, + canAct: enabled, canSteer: !uncertain && !scheduled, indeterminate: uncertain + ), interactor: driver.interactor) + } + for theme in [HapiTheme.light, .dark, .oled] { + XCTAssertEqual(measure(row().hapiTheme(theme), width: 358).height, 56, accuracy: 1) + for (width, size) in [(CGFloat(180), DynamicTypeSize.large), (288, .accessibility5), (720, .xxxLarge)] { + let enabled = measure(row().hapiTheme(theme), width: width, size: size) + XCTAssertLessThanOrEqual(enabled.width, width) + if width < 320 { XCTAssertGreaterThan(enabled.height, 56) } + XCTAssertEqual(measure(row(enabled: false).hapiTheme(theme), width: width, size: size).height, + enabled.height, accuracy: 1) + for specimen in [row(uncertain: true), row(scheduled: true)] { + XCTAssertLessThanOrEqual(measure(specimen.hapiTheme(theme), width: width, size: size).width, width) + } + } + } + for (name, theme, size) in [("queue", HapiTheme.light, DynamicTypeSize.large), + ("queue-large-type", .dark, .accessibility3)] { + let view = ScrollView { + VStack(alignment: .leading, spacing: 16) { + row() + row(uncertain: true) + row(scheduled: true) + } + .hapiReadingColumn().padding(.vertical, 24) + } + .background(theme.background) + .hapiTypography().hapiTheme(theme) + .environment(\.dynamicTypeSize, size) + .preferredColorScheme(theme.isDark ? .dark : .light) + let (window, _) = try host(view, width: 320) + defer { window.isHidden = true } + try await layoutSettles() + try capture(window, name: name) + } + } + + func testApprovalSpecimensInThemesLocalesAndAccessibleSizes() async throws { + let cases: [(String, HapiTheme, DynamicTypeSize, CGFloat, String)] = [ + ("light", .light, .large, 390, "en"), ("dark", .dark, .large, 390, "en"), + ("oled", .oled, .large, 390, "en"), ("small", .light, .large, 320, "en"), + ("chinese", .light, .large, 390, "zh-Hans"), + ("large-type", .dark, .accessibility3, 390, "en"), + ("largest-type", .light, .accessibility5, 390, "zh-Hans"), + ("ipad", .light, .large, 1024, "en"), + ] + for (name, theme, size, width, locale) in cases { + let driver = try await Driver() + let (window, host) = try host(Specimen(driver: driver, theme: theme, size: size, + locale: Locale(identifier: locale)), width: width) + defer { window.isHidden = true } + try await eventually { driver.height > 100 } + try await layoutSettles() + if size == .large { XCTAssertLessThan(driver.height, 200, "A short approval should remain compact") } + XCTAssertNil(host.presentedViewController, "Approvals stay inline") + try capture(window, name: name) + if size.isAccessibilitySize, let scroll = findScroll(host.view) { + scroll.setContentOffset(CGPoint(x: 0, y: max(-scroll.adjustedContentInset.top, + scroll.contentSize.height - scroll.bounds.height + scroll.adjustedContentInset.bottom)), animated: false) + try await layoutSettles() + try capture(window, name: name + "-bottom") + } + } + } + + private func measure(_ view: V, width: CGFloat, size: DynamicTypeSize = .large) -> CGSize { + UIHostingController(rootView: view.hapiTypography().environment(\.dynamicTypeSize, size)) + .sizeThatFits(in: CGSize(width: width, height: .greatestFiniteMagnitude)) + } + + private func host(_ view: V, width: CGFloat = 390) throws -> (UIWindow, UIHostingController) { + 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: width, height: 844) + let host = UIHostingController(rootView: view) + window.rootViewController = host + window.makeKeyAndVisible() + host.view.layoutIfNeeded() + return (window, host) + } + + private func findScroll(_ view: UIView) -> UIScrollView? { + (view as? UIScrollView) ?? view.subviews.lazy.compactMap(findScroll).first + } + + private func eventually(_ condition: () async -> Bool) async throws { + for _ in 0..<150 { + if await condition() { return } + try await Task.sleep(for: .milliseconds(20)) + } + XCTFail("Approval presentation did not settle") + } + + private func layoutSettles() async throws { + try await Task.sleep(for: .milliseconds(200)) + } + + private func capture(_ window: UIWindow, name: String) throws { + guard let path = ProcessInfo.processInfo.environment["HAPI_APPROVAL_CAPTURE"] else { return } + let directory = URL(fileURLWithPath: path, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + try XCTUnwrap(image.pngData()).write(to: directory.appendingPathComponent("approval-\(name).png")) + } +} 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/HapiTests/ScratchlistPresentationTests.swift b/ios/HapiTests/ScratchlistPresentationTests.swift new file mode 100644 index 00000000..7db4e908 --- /dev/null +++ b/ios/HapiTests/ScratchlistPresentationTests.swift @@ -0,0 +1,293 @@ +import HapiClient +import HapiProtocol +import HapiUI +import SwiftUI +import UIKit +import XCTest +@testable import Hapi + +private struct ScratchlistOfflineHTTP: HTTPPerforming { + func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { throw URLError(.notConnectedToInternet) } +} + +@MainActor +final class ScratchlistPresentationTests: XCTestCase { + private func interactor() -> ChatInteractor { + let url = URL(string: "https://scratchlist.invalid")! + let http = ScratchlistOfflineHTTP() + let auth = AuthManager(baseURL: url, credentialStore: InMemoryCredentialStore(), performer: http) + let api = APIClient(baseURL: url, authManager: auth, performer: http) + let interactor = ChatInteractor(sessionId: "preview", api: api, sessionStore: SessionListStore(api: api), windows: MessageWindowControllers(provider: api)) + let stamp = Int(Date().timeIntervalSince1970 * 1000) - 120_000 + interactor.scratchlist = ScratchlistTestStore(entries: [ + ScratchlistEntry(entryId: "first", text: "检查登录后偶发的白屏,先补回归测试,再修复根因。", createdAt: stamp, updatedAt: stamp), + ScratchlistEntry(entryId: "second", text: "主流程完成后,再补充深色模式和大字号的界面截图。", createdAt: stamp - 180_000, updatedAt: stamp - 180_000, + attachments: [ScratchlistAttachment(id: "reference", filename: "dark-mode-reference.png", mimeType: "image/png", size: 100, path: "hub-reference")]), + ScratchlistEntry(entryId: "third", text: "Review the release notes", createdAt: stamp - 600_000, updatedAt: stamp - 600_000), + ]) + interactor.setComposerDestination(.scratchlist) + return interactor + } + + private struct Harness: View { + let interactor: ChatInteractor + let size: DynamicTypeSize + let dark: Bool + var locale = "zh-Hans" + var body: some View { + NavigationStack { + ScrollView { + VStack(alignment: .leading, spacing: 18) { + Text("先梳理登录流程,修复问题后补上测试。") + .padding(14).background(.quaternary, in: RoundedRectangle(cornerRadius: 16)) + Text("正在检查会话恢复和登录状态切换。你可以先把后续想法暂存在草稿夹,不打断当前任务。") + .frame(maxWidth: .infinity, alignment: .leading) + }.padding(16) + } + .safeAreaInset(edge: .bottom, spacing: 0) { + ChatComposerView(interactor: interactor) + } + .navigationTitle("登录流程优化") + .navigationBarTitleDisplayMode(.inline) + } + .hapiTypography() + .environment(\.dynamicTypeSize, size) + .environment(\.locale, Locale(identifier: locale)) + .preferredColorScheme(dark ? .dark : .light) + } + } + + func testComposerRendersAtCompactRegularAndAccessibleSizes() async throws { + for (name, width, size, dark, locale) in [ + ("light", CGFloat(402), DynamicTypeSize.large, false, "zh-Hans"), + ("dark", CGFloat(402), DynamicTypeSize.large, true, "zh-Hans"), + ("compact", CGFloat(320), DynamicTypeSize.large, false, "zh-Hans"), + ("large-text", CGFloat(390), DynamicTypeSize.accessibility3, false, "zh-Hans"), + ("english", CGFloat(320), DynamicTypeSize.large, false, "en"), + ] { + 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: width, height: 874) + let interactor = interactor() + let host = UIHostingController(rootView: Harness(interactor: interactor, size: size, dark: dark, locale: locale)) + window.rootViewController = host + window.makeKeyAndVisible() + defer { window.isHidden = true } + try await Task.sleep(for: .milliseconds(350)) + window.layoutIfNeeded() + XCTAssertEqual(host.view.bounds.width, width, accuracy: 1) + XCTAssertEqual(interactor.composerDestination, .scratchlist) + XCTAssertEqual(interactor.scratchlistCount, 3) + let format = UIGraphicsImageRendererFormat() + format.scale = 2 + let image = UIGraphicsImageRenderer(bounds: window.bounds, format: format).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + let attachment = XCTAttachment(image: image) + attachment.name = "scratchlist-\(name)" + attachment.lifetime = .keepAlways + add(attachment) + let url = FileManager.default.temporaryDirectory.appendingPathComponent("scratchlist-\(name).png") + try XCTUnwrap(image.pngData()).write(to: url) + print("SCRATCHLIST_CAPTURE=\(url.path)") + } + } + + func testDrawerShowsOneRecentDraftAndOnlyHeaderWhenTypingOrUsingLargeText() throws { + let interactor = interactor() + let store = try XCTUnwrap(interactor.scratchlist as? ScratchlistTestStore) + let entries = store.session.entries + func measure(count: Int, focused: Bool, size: DynamicTypeSize, locale: String) -> CGSize { + store.session.entries = Array(entries.prefix(count)) + let view = ScratchlistDrawerView(store: store, sessionId: "preview", interactor: interactor, + keyboardFocused: focused, onOpen: { _, _ in }) + .hapiTypography().environment(\.dynamicTypeSize, size).environment(\.locale, Locale(identifier: locale)) + let host = UIHostingController(rootView: view) + return host.sizeThatFits(in: CGSize(width: 320, height: 2000)) + } + for locale in ["en", "zh-Hans"] { + let summary = measure(count: 3, focused: true, size: .large, locale: locale) + XCTAssertLessThan(summary.height, 70, "Typing should leave just one header, not a draft preview") + XCTAssertLessThanOrEqual(summary.width, 320) + XCTAssertEqual(measure(count: 0, focused: true, size: .large, locale: locale).height, summary.height, accuracy: 1) + let one = measure(count: 1, focused: false, size: .large, locale: locale) + XCTAssertGreaterThan(one.height, summary.height + 40) + XCTAssertLessThan(one.height, 150) + XCTAssertEqual(measure(count: 3, focused: false, size: .large, locale: locale).height, one.height, accuracy: 1) + for size in [DynamicTypeSize.accessibility3, .accessibility5] { + let empty = measure(count: 0, focused: false, size: size, locale: locale) + let populated = measure(count: 3, focused: false, size: size, locale: locale) + XCTAssertEqual(populated.height, empty.height, accuracy: 1, "Large text uses a summary even without the keyboard") + XCTAssertLessThanOrEqual(populated.width, 320) + XCTAssertLessThan(populated.height, 170) + } + } + } + + func testRowsRemainCompactAndAdaptActionsAtAccessibleSizes() throws { + let interactor = interactor() + let entry = try XCTUnwrap(interactor.scratchlist?.state("preview").entries[1]) + for locale in ["en", "zh-Hans"] { + for size in [DynamicTypeSize.large, .accessibility3, .accessibility5] { + for compact in [false, true] { + let row = ScratchlistEntryRow(entry: entry, interactor: interactor, + onOpen: {}, onEdit: {}, onDelete: {}, compact: compact) + .hapiTypography().environment(\.dynamicTypeSize, size) + .environment(\.locale, Locale(identifier: locale)) + let host = UIHostingController(rootView: row) + let fitting = host.sizeThatFits(in: CGSize(width: 256, height: 2000)) + XCTAssertLessThanOrEqual(fitting.width, 256) + XCTAssertGreaterThanOrEqual(fitting.height, 44) + if size == .large { XCTAssertLessThan(fitting.height, compact ? 70 : 100) } + } + } + } + } + + func testFocusingTheRealComposerCollapsesThePreviewWithoutChangingInput() async throws { + let interactor = interactor() + interactor.setComposerText("补充一条回归测试") + 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: ChatComposerView(interactor: interactor) + .hapiTypography().environment(\.locale, Locale(identifier: "zh-Hans"))) + window.rootViewController = host + window.makeKeyAndVisible() + defer { window.endEditing(true); window.isHidden = true } + try await Task.sleep(for: .milliseconds(250)) + let proposal = CGSize(width: 390, height: 2000) + let browsingHeight = host.sizeThatFits(in: proposal).height + interactor.focusComposer() + func hasFirstResponder(_ view: UIView) -> Bool { + view.isFirstResponder || view.subviews.contains(where: hasFirstResponder) + } + for _ in 0..<50 { + if hasFirstResponder(window) { break } + try await Task.sleep(for: .milliseconds(10)) + } + XCTAssertTrue(hasFirstResponder(window)) + try await Task.sleep(for: .milliseconds(250)) + XCTAssertLessThan(host.sizeThatFits(in: proposal).height, browsingHeight - 40) + XCTAssertEqual(interactor.composerText, "补充一条回归测试") + XCTAssertEqual(interactor.composerDestination, .scratchlist) + XCTAssertEqual(interactor.scratchlistCount, 3) + } + + func testInlineScratchlistErrorsDoNotAlsoProduceToasts() throws { + let hub = try XCTUnwrap(HubSession(hubUrl: "http://127.0.0.1:1/scratchlist-notices-\(UUID().uuidString)", + credentialStore: InMemoryCredentialStore(), performer: ScratchlistOfflineHTTP())) + let model = ChatModel(session: hub, sessionId: "preview") + defer { model.stop(); hub.shutdown() } + model.start() + let message = "Couldn't park the draft — check the hub connection" + model.interactor.reportScratchlistError(message) + model.interactor.onEvent?(.notice(message)) + XCTAssertNil(model.notice) + // Dismissing the inline error must not uncover a duplicate toast. + model.interactor.retryScratchlistComposerOperation() + XCTAssertNil(model.notice) + model.interactor.onEvent?(.notice("Draft parked to scratchlist")) + XCTAssertEqual(model.notice, "Draft parked to scratchlist") + model.interactor.onEvent?(.notice("An unrelated error")) + XCTAssertEqual(model.notice, "An unrelated error") + } +} + +extension ScratchlistPresentationTests { + private struct ScrollRow: Identifiable, Equatable { let id: String } + private struct ScrollHarness: View { + let interactor: ChatInteractor + let rows = (0..<100).map { ScrollRow(id: "message-\($0)") } + var body: some View { + AnchoredTranscriptList(items: rows, historyVersion: 0, jumpToken: 0, + historyControlID: "history", onViewport: { _ in }, onLayout: { _, _ in }) { row in + AnyView(Text(verbatim: row.id).frame(maxWidth: .infinity).frame(height: 90)) + } + .safeAreaInset(edge: .bottom, spacing: 0) { ChatComposerView(interactor: interactor) } + .hapiTypography() + } + } + + func testTogglingDrawerPreservesTranscriptIdentityAndReadingAnchor() async throws { + let interactor = interactor() + interactor.setComposerDestination(.chat) + 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: ScrollHarness(interactor: interactor)) + window.rootViewController = host + window.makeKeyAndVisible() + defer { window.isHidden = true } + try await Task.sleep(for: .milliseconds(250)) + func find(_ view: UIView) -> UICollectionView? { + if let collection = view as? UICollectionView { return collection } + return view.subviews.lazy.compactMap(find).first + } + let list = try XCTUnwrap(find(host.view)) + list.delegate?.scrollViewWillBeginDragging?(list) + list.scrollToItem(at: IndexPath(item: 25, section: 0), at: .top, animated: false) + list.contentOffset.y += 13 + list.delegate?.scrollViewDidEndDragging?(list, willDecelerate: false) + try await Task.sleep(for: .milliseconds(180)) + func anchor() -> (String, CGFloat)? { + list.visibleCells.filter { $0.frame.maxY > list.contentOffset.y } + .sorted { $0.frame.minY < $1.frame.minY }.first.map { + ($0.accessibilityIdentifier ?? "", $0.frame.minY - list.contentOffset.y) + } + } + let before = try XCTUnwrap(anchor()) + for mode in [ComposerDestination.scratchlist, .chat] { + interactor.setComposerDestination(mode) + try await Task.sleep(for: .milliseconds(250)) + XCTAssertTrue(find(host.view) === list) + let after = try XCTUnwrap(anchor()) + XCTAssertEqual(after.0, before.0) + XCTAssertEqual(after.1, before.1, accuracy: 1) + } + } + + func testInventoryAndSingleStackEditorRender() async throws { + let interactor = interactor() + let store = try XCTUnwrap(interactor.scratchlist) + let http = ScratchlistOfflineHTTP() + let url = URL(string: "https://scratchlist.invalid")! + let api = APIClient(baseURL: url, + authManager: AuthManager(baseURL: url, credentialStore: InMemoryCredentialStore(), performer: http), performer: http) + let loader = ScratchlistAttachmentLoader(api: api, sessionId: "preview") + for (name, detail, editing, width, size, dark) in [ + ("inventory", false, false, CGFloat(402), DynamicTypeSize.large, false), + ("inventory-dark", false, false, CGFloat(402), DynamicTypeSize.large, true), + ("inventory-compact", false, false, CGFloat(320), DynamicTypeSize.large, false), + ("inventory-large-text", false, false, CGFloat(390), DynamicTypeSize.accessibility3, false), + ("detail", true, false, CGFloat(402), DynamicTypeSize.large, false), + ("editor", true, true, CGFloat(402), DynamicTypeSize.large, false), + ("empty", false, false, CGFloat(402), DynamicTypeSize.large, false), + ] { + if name == "empty" { (store as? ScratchlistTestStore)?.session.entries = [] } + 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: width, height: 874) + let view = ScratchlistView(store: store, sessionId: "preview", attachments: loader, interactor: interactor, + initialEntry: detail ? store.state("preview").entries[1] : nil, initiallyEditing: editing) + .hapiTypography().environment(\.locale, Locale(identifier: "zh-Hans")) + .environment(\.dynamicTypeSize, size).preferredColorScheme(dark ? .dark : .light) + window.rootViewController = UIHostingController(rootView: view) + window.makeKeyAndVisible() + defer { window.isHidden = true } + try await Task.sleep(for: .milliseconds(350)) + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + let name = "scratchlist-\(name)" + let attachment = XCTAttachment(image: image) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + let file = FileManager.default.temporaryDirectory.appendingPathComponent("\(name).png") + try XCTUnwrap(image.pngData()).write(to: file) + print("SCRATCHLIST_CAPTURE=\(file.path)") + XCTAssertEqual(store.state("preview").entries.count, name == "scratchlist-empty" ? 0 : 3) + } + } +} diff --git a/ios/HapiTests/ScratchlistScreenModelTests.swift b/ios/HapiTests/ScratchlistScreenModelTests.swift new file mode 100644 index 00000000..47560f4a --- /dev/null +++ b/ios/HapiTests/ScratchlistScreenModelTests.swift @@ -0,0 +1,164 @@ +import HapiClient +import HapiProtocol +import Observation +import XCTest +@testable import Hapi + +@MainActor @Observable +final class ScratchlistTestStore: SessionScratchlistStoring { + var session = ScratchlistSessionState() + var updates: [(String?, [ScratchlistAttachment]?)] = [] + var deletedAttachments: [String] = [] + var updateSucceeds = true + var holdUpload = false + var uploadStarted = false + var uploadSucceeds = true + var uploadCount = 0 + @ObservationIgnored var uploadGate: CheckedContinuation? + let uploaded = ScratchlistAttachment(id: "new-photo", filename: "new.txt", mimeType: "text/plain", size: 4, path: "hapi-hub:scratchlist/test/new.txt") + + init(entries: [ScratchlistEntry] = []) { + session.loaded = true + session.entries = entries + } + func state(_ sessionId: String) -> ScratchlistSessionState { session } + func open(_ sessionId: String) {} + func release(_ sessionId: String) {} + func refresh(_ sessionId: String) async throws {} + func createEntry(sessionId: String, text: String, attachments: [ScratchlistAttachment], entryId: String?) async -> ScratchlistCreateResult { + let entry = ScratchlistEntry(entryId: entryId ?? "new", text: text, createdAt: 1, updatedAt: 1, attachments: attachments) + session.entries.insert(entry, at: 0) + return .created(entry) + } + func updateEntry(sessionId: String, entryId: String, text: String?, attachments: [ScratchlistAttachment]?) async -> Bool { + updates.append((text, attachments)) + return updateSucceeds + } + func deleteEntry(sessionId: String, entryId: String) async -> Bool { true } + func uploadAttachment(sessionId: String, filename: String, data: Data, mimeType: String) async -> ScratchlistUploadResult { + uploadStarted = true + uploadCount += 1 + if holdUpload { await withCheckedContinuation { uploadGate = $0 } } + return uploadSucceeds ? .uploaded(uploaded) : .failed(message: "offline", code: nil) + } + func deleteAttachment(sessionId: String, attachmentId: String) async -> ScratchlistAttachmentDeleteResult { + deletedAttachments.append(attachmentId) + return .removed + } + func limits(sessionId: String) async -> ScratchlistAttachmentLimits { .defaultLimits } +} + +@MainActor +final class ScratchlistScreenModelTests: XCTestCase { + private var original: ScratchlistEntry { + ScratchlistEntry(entryId: "original", text: "Original text", createdAt: 1, updatedAt: 2, + attachments: [ScratchlistAttachment(id: "old", filename: "reference.txt", mimeType: "text/plain", size: 5, path: "hub-path")]) + } + private func wait(_ condition: () -> Bool) async throws { + for _ in 0..<200 { + if condition() { return } + try await Task.sleep(for: .milliseconds(10)) + } + XCTFail("Timed out waiting for scratchlist state") + } + + func testCancelDoesNotPersistTextOrAttachmentChanges() async throws { + let store = ScratchlistTestStore(entries: [original]) + let model = ScratchlistScreenModel(sessionId: "session", store: store) + model.openEditor(original) + model.setEditorText("Changed") + model.removeAttachment(original.attachments[0]) + XCTAssertTrue(model.editor?.isDirty == true) + XCTAssertTrue(store.updates.isEmpty) + model.dismissEditor() + try await Task.sleep(for: .milliseconds(20)) + XCTAssertNil(model.editor) + XCTAssertTrue(store.updates.isEmpty) + XCTAssertTrue(store.deletedAttachments.isEmpty) + } + + func testSaveCommitsTextAndAttachmentsTogetherAndKeepsFailedDraft() async throws { + let store = ScratchlistTestStore(entries: [original]) + store.updateSucceeds = false + let model = ScratchlistScreenModel(sessionId: "session", store: store) + model.openEditor(original) + model.setEditorText("Changed") + model.removeAttachment(original.attachments[0]) + model.saveEditor() + try await wait { model.editor?.isSaving == false } + XCTAssertEqual(store.updates.count, 1) + XCTAssertEqual(store.updates[0].0, "Changed") + XCTAssertEqual(store.updates[0].1, []) + XCTAssertEqual(model.editor?.text, "Changed") + XCTAssertNotNil(model.editor?.error) + XCTAssertTrue(store.deletedAttachments.isEmpty) + store.updateSucceeds = true + model.saveEditor() + try await wait { model.editor == nil && store.deletedAttachments == ["old"] } + } + + func testLateUploadCannotWriteIntoAnotherEditor() async throws { + let store = ScratchlistTestStore(entries: [original]) + store.holdUpload = true + let model = ScratchlistScreenModel(sessionId: "session", store: store) + model.openEditor(original) + model.addPreparedAttachment(PreparedAttachment(filename: "new.txt", mimeType: "text/plain", bytes: Data("test".utf8))) + try await wait { store.uploadStarted } + model.dismissEditor() + model.openEditor(ScratchlistEntry(entryId: "another", text: "Another", createdAt: 2, updatedAt: 2)) + store.uploadGate?.resume() + store.uploadGate = nil + try await wait { store.deletedAttachments.contains("new-photo") } + XCTAssertEqual(model.editor?.entryId, "another") + XCTAssertEqual(model.editor?.attachments, []) + XCTAssertFalse(model.editor?.isUploading ?? true) + XCTAssertTrue(store.updates.isEmpty) + } + + func testCancellingUploadedAttachmentCleansOnlyTheNewFile() async throws { + let store = ScratchlistTestStore(entries: [original]) + let model = ScratchlistScreenModel(sessionId: "session", store: store) + model.openEditor(original) + model.addPreparedAttachment(PreparedAttachment(filename: "new.txt", mimeType: "text/plain", bytes: Data("test".utf8))) + try await wait { model.editor?.isUploading == false } + XCTAssertEqual(model.editor?.attachments.count, 2) + XCTAssertTrue(store.updates.isEmpty) + model.dismissEditor() + try await wait { store.deletedAttachments == ["new-photo"] } + } + + func testUTF16LimitAndAttachmentOnlyValidation() { + let store = ScratchlistTestStore(entries: [original]) + let model = ScratchlistScreenModel(sessionId: "session", store: store) + model.openEditor(original) + model.setEditorText("") + XCTAssertTrue(model.editor?.canSave == true) + model.removeAttachment(original.attachments[0]) + XCTAssertFalse(model.editor?.canSave ?? true) + model.setEditorText(String(repeating: "😀", count: 5001)) + XCTAssertFalse(model.editor?.canSave ?? true) + model.saveEditor() + XCTAssertTrue(store.updates.isEmpty) + XCTAssertEqual(model.editor?.text.utf16.count, 10_002) + } + + func testFailedUploadBlocksSaveAndRetryRetriesTheFileNotTheSave() async throws { + let store = ScratchlistTestStore(entries: [original]) + store.uploadSucceeds = false + let model = ScratchlistScreenModel(sessionId: "session", store: store) + model.openEditor(original) + model.addPreparedAttachment(PreparedAttachment(filename: "new.txt", mimeType: "text/plain", bytes: Data("test".utf8))) + try await wait { model.editor?.isUploading == false } + XCTAssertEqual(model.editor?.failedUploadName, "new.txt") + XCTAssertFalse(model.editor?.canSave ?? true) + model.saveEditor() + XCTAssertTrue(store.updates.isEmpty) + store.uploadSucceeds = true + model.retryEditorOperation() + try await wait { model.editor?.failedUploadName == nil } + XCTAssertEqual(store.uploadCount, 2) + XCTAssertEqual(model.editor?.attachments.count, 2) + XCTAssertTrue(store.updates.isEmpty, "Retry upload must not save or dismiss the editor") + XCTAssertTrue(model.editor?.canSave == true) + } +} diff --git a/ios/HapiTests/SessionConfigPresentationTests.swift b/ios/HapiTests/SessionConfigPresentationTests.swift new file mode 100644 index 00000000..fe0afbef --- /dev/null +++ b/ios/HapiTests/SessionConfigPresentationTests.swift @@ -0,0 +1,316 @@ +import HapiClient +import HapiProtocol +import Observation +import SwiftUI +import UIKit +import XCTest +@testable import Hapi + +/// The production toolbar presenter over the non-networked config harness. +/// Run on both iPhone and iPad; synthetic widths alone cannot test adaptation. +@MainActor +final class SessionConfigPresentationTests: XCTestCase { + @Observable + fileprivate final class Presentation { + let model: SessionConfigModel + var isPresented = false + var notice: String? + init(model: SessionConfigModel) { self.model = model } + } + + private struct Host: View { + let presentation: Presentation + var size: DynamicTypeSize = .large + var dark = false + var locale = Locale(identifier: "en") + + var body: some View { + @Bindable var presentation = presentation + NavigationStack { + Text("Session settings specimen") + .navigationTitle("HAPI") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + SessionConfigButton(isPresented: $presentation.isPresented) { + SessionConfigView(model: presentation.model, notice: presentation.notice) + .environment(\.dynamicTypeSize, size) + .environment(\.locale, locale) + } + .environment(\.dynamicTypeSize, size) + } + ToolbarItem(placement: .topBarTrailing) { + Image(systemName: "ellipsis.circle") + } + } + } + .environment(\.dynamicTypeSize, size) + .environment(\.locale, locale) + .preferredColorScheme(dark ? .dark : .light) + } + } + + func testMenusKeepTheSamePageAndSheetHeightWhenSelecting() async throws { + let harness = try await SessionConfigTestHarness(model: "sonnet") + let presentation = Presentation(model: harness.model) + let (window, host) = try await show(Host(presentation: presentation)) + defer { window.isHidden = true } + let sheet = try XCTUnwrap(host.presentedViewController) + let rootList = try XCTUnwrap(findList(sheet.view)) + XCTAssertEqual(itemCount(rootList), 3) + XCTAssertTrue(rootList.visibleCells.allSatisfy { $0.bounds.height >= 44 }) + let rootHeight = sheet.view.bounds.height + try capture(window, name: "root") + + harness.model.selectModel("sonnet") + harness.model.selectPermission(.default) + let initialPosts = await harness.http.posts + XCTAssertTrue(initialPosts.isEmpty, "Reselecting the current value is read-only") + harness.model.selectModel("opus") + try await configEventually { !harness.model.isApplying } + harness.model.selectEffort("high") + try await configEventually { !harness.model.isApplying } + harness.model.selectPermission(.bypassPermissions) + try await configEventually { !harness.model.isApplying } + try await settle() + XCTAssertTrue(host.presentedViewController === sheet) + XCTAssertNil(sheet.presentedViewController, "Selections must not open another modal") + XCTAssertTrue(findList(sheet.view) === rootList, "No detail page replaces the settings list") + XCTAssertEqual(itemCount(rootList), 3) + XCTAssertEqual(sheet.view.bounds.height, rootHeight, accuracy: 2) + XCTAssertEqual(harness.model.modelLabel, "Opus") + XCTAssertEqual(harness.model.permission, .bypassPermissions) + try capture(window, name: "selected") + presentation.isPresented = false + try await configEventually { host.presentedViewController == nil } + let posts = await harness.http.posts + XCTAssertEqual(posts.count, 3, "Dismissal does not apply or revert settings") + } + + func testCodexRootShowsCollaborationAlongsidePermissionsModelAndEffort() async throws { + let harness = try await SessionConfigTestHarness(flavor: "codex") + let presentation = Presentation(model: harness.model) + let (window, host) = try await show(Host(presentation: presentation, locale: Locale(identifier: "zh-Hans"))) + defer { window.isHidden = true } + try await configEventually { harness.model.showsEffort } + try await settle() + let sheet = try XCTUnwrap(host.presentedViewController) + let list = try XCTUnwrap(findList(sheet.view)) + XCTAssertEqual(itemCount(list), 4) + XCTAssertTrue(list.visibleCells.allSatisfy { $0.bounds.height >= 44 }) + harness.model.selectCollaborationMode(.plan) + try await settle() + XCTAssertTrue(host.presentedViewController === sheet) + XCTAssertEqual(harness.model.collaborationMode, .plan) + XCTAssertEqual(harness.model.permission, .default) + XCTAssertEqual(itemCount(list), 4) + } + + func testBusyAndFailureFeedbackRemainInsideTheOpenSheet() async throws { + let harness = try await SessionConfigTestHarness(model: "sonnet") + let presentation = Presentation(model: harness.model) + harness.interactor.onEvent = { + if case .notice(let message) = $0 { presentation.notice = message } + } + let (window, host) = try await show(Host(presentation: presentation)) + defer { window.isHidden = true } + let sheet = try XCTUnwrap(host.presentedViewController) + await harness.http.holdPosts() + await harness.http.rejectChanges() + defer { Task { await harness.http.releasePosts() } } + harness.model.selectModel("opus") + try await settle() + XCTAssertTrue(harness.model.isApplying) + XCTAssertTrue(host.presentedViewController === sheet) + try capture(window, name: "applying") + await harness.http.releasePosts() + try await configEventually { presentation.notice == "HTTP 409 (Config rejected)" && !harness.model.isApplying } + try await settle() + XCTAssertEqual(harness.model.modelLabel, "Sonnet") + XCTAssertTrue(host.presentedViewController === sheet) + try capture(window, name: "failure") + presentation.notice = nil + try await settle() + XCTAssertEqual(itemCount(try XCTUnwrap(findList(sheet.view))), 3) + } + + func testFailedCatalogCanRetryInlineWithoutLeavingSettings() async throws { + let harness = try await SessionConfigTestHarness(flavor: "codex") + await harness.http.setModelsFailure(true) + let presentation = Presentation(model: harness.model) + let (window, host) = try await show(Host(presentation: presentation)) + defer { window.isHidden = true } + try await configEventually { harness.model.modelLoadFailed } + try await settle() + let sheet = try XCTUnwrap(host.presentedViewController) + XCTAssertEqual(itemCount(try XCTUnwrap(findList(sheet.view))), 3, "Model status stays in its row beside the other settings") + try capture(window, name: "catalog-failure") + await harness.http.setModelsFailure(false) + harness.model.loadModels() + try await configEventually { !harness.model.config.modelOptionsLoading } + try await settle() + XCTAssertTrue(host.presentedViewController === sheet) + XCTAssertEqual(harness.model.currentModel, "deep") + XCTAssertEqual(itemCount(try XCTUnwrap(findList(sheet.view))), 4) + } + + func testLayoutSpecimensSupportNarrowWideDarkChineseAndLargeType() async throws { + let cases: [(String, CGSize, DynamicTypeSize, Bool, String)] = [ + ("compact", CGSize(width: 320, height: 667), .large, false, "en"), + ("dark", CGSize(width: 390, height: 844), .large, true, "en"), + ("chinese", CGSize(width: 390, height: 844), .large, false, "zh-Hans"), + ("large-type", CGSize(width: 390, height: 844), .accessibility3, false, "zh-Hans"), + ("wide", CGSize(width: 820, height: 1180), .large, false, "en"), + ("landscape", CGSize(width: 1180, height: 820), .large, false, "en"), + ("wide-large-type", CGSize(width: 820, height: 1180), .accessibility3, false, "zh-Hans"), + ] + for (name, dimensions, typeSize, dark, locale) in cases { + let shortModel = name == "compact" || name == "chinese" + let harness = try await SessionConfigTestHarness( + model: shortModel ? "sonnet" : "custom-model-with-a-very-long-name-用于长名称换行验证" + ) + harness.store.updateDetailLocal("config") { $0.permissionMode = .bypassPermissions } + let presentation = Presentation(model: harness.model) + let (window, host) = try await show( + Host(presentation: presentation, size: typeSize, dark: dark, locale: Locale(identifier: locale)), + dimensions: dimensions + ) + let sheet = try XCTUnwrap(host.presentedViewController) + let list = try XCTUnwrap(findList(sheet.view)) + XCTAssertEqual(itemCount(list), 3) + XCTAssertTrue(list.visibleCells.allSatisfy { $0.bounds.height >= 44 }) + if !typeSize.isAccessibilitySize { + XCTAssertLessThan( + try XCTUnwrap(list.cellForItem(at: IndexPath(item: 0, section: 1))).bounds.height, 120, + "The warning subtitle must not stretch into a separate Form row" + ) + } + if typeSize.isAccessibilitySize && host.traitCollection.horizontalSizeClass == .compact { + let controller = try XCTUnwrap(adaptiveSheet(of: sheet)) + XCTAssertEqual(controller.detents.count, 1, "Accessibility text uses a large sheet") + } + try capture(window, name: name) + presentation.isPresented = false + try await configEventually { host.presentedViewController == nil } + window.isHidden = true + } + } + + func testNativeDevicePresentationIsAnchoredOnIPadAndAdaptsOnIPhone() async throws { + let harness = try await SessionConfigTestHarness(model: "sonnet") + let presentation = Presentation(model: harness.model) + // No fake dimensions or trait overrides: this test needs a real iPad run. + let (window, host) = try await show(Host(presentation: presentation), dimensions: nil) + defer { window.isHidden = true } + // Optional pause for AXe-driven menu/Done interaction over this fake session. + if let value = ProcessInfo.processInfo.environment["HAPI_SESSION_CONFIG_INTERACTIVE_SECONDS"], + let seconds = Double(value), seconds > 0 { + try await Task.sleep(for: .seconds(min(seconds, 180))) + } + let panel = try XCTUnwrap(host.presentedViewController) + XCTAssertEqual(itemCount(try XCTUnwrap(findList(panel.view))), 3) + if host.traitCollection.horizontalSizeClass == .regular { + let popover = try XCTUnwrap(panel.presentationController as? UIPopoverPresentationController) + if popover.sourceItem != nil { + XCTAssertNotNil(popover.sourceItem as? UIBarButtonItem, "Toolbar anchors use a native bar item") + } else { + let source = try XCTUnwrap(popover.sourceView) + let rect = popover.sourceRect.isEmpty || popover.sourceRect.isNull ? source.bounds : popover.sourceRect + let anchor = source.convert(rect, to: window) + XCTAssertLessThan(anchor.width, 100, "Anchor must be the gear, not the page") + XCTAssertGreaterThan(anchor.midX, window.bounds.midX) + XCTAssertLessThan(anchor.maxY, window.bounds.height / 3) + } + let panelFrame = panel.view.convert(panel.view.bounds, to: window) + XCTAssertGreaterThan(panelFrame.midX, window.bounds.midX, "Popover belongs beside the toolbar, not in the center") + XCTAssertLessThan(panelFrame.minY, window.bounds.height / 3) + XCTAssertLessThanOrEqual(panel.view.bounds.width, 420) + } else { + let sheet = try XCTUnwrap(adaptiveSheet(of: panel)) + XCTAssertEqual(sheet.detents.count, 2) + } + try capture(window, name: "device-root") + harness.model.selectModel("opus") + try await configEventually { !harness.model.isApplying } + try await settle() + XCTAssertTrue(host.presentedViewController === panel) + XCTAssertEqual(itemCount(try XCTUnwrap(findList(panel.view))), 3) + } + + func testSizeClassAdaptationPreservesOpenConfigurationAndDoesNotResubmit() async throws { + let harness = try await SessionConfigTestHarness(flavor: "codex") + let presentation = Presentation(model: harness.model) + let (window, host) = try await show(Host(presentation: presentation), dimensions: CGSize(width: 820, height: 1180)) + defer { window.isHidden = true } + try await configEventually { harness.model.showsEffort } + harness.model.selectModel("fast") + try await configEventually { !harness.model.isApplying } + presentation.notice = "Config rejected" + for sizeClass in [UIUserInterfaceSizeClass.compact, .regular] { + host.traitOverrides.horizontalSizeClass = sizeClass + try await Task.sleep(for: .seconds(2)) + XCTAssertTrue(presentation.isPresented) + let panel = try XCTUnwrap(host.presentedViewController) + XCTAssertEqual(itemCount(try XCTUnwrap(findList(panel.view))), 4) + XCTAssertEqual(harness.model.currentModel, "fast") + XCTAssertEqual(presentation.notice, "Config rejected") + } + let posts = await harness.http.posts + XCTAssertEqual(posts.count, 1) + let requests = await harness.http.modelRequests + XCTAssertEqual(requests, 1, "Adaptation must not reload the catalog") + try capture(window, name: "adapted") + } + + private func show( + _ content: Host, dimensions: CGSize? = CGSize(width: 390, height: 844) + ) async throws -> (UIWindow, UIHostingController) { + let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + let window = UIWindow(windowScene: scene) + window.frame = CGRect(origin: .zero, size: dimensions ?? scene.coordinateSpace.bounds.size) + let host = UIHostingController(rootView: content) + if let dimensions { + host.traitOverrides.horizontalSizeClass = dimensions.width < 600 ? .compact : .regular + } + window.rootViewController = host + window.makeKeyAndVisible() + try await Task.sleep(for: .milliseconds(100)) + content.presentation.isPresented = true + try await configEventually { host.presentedViewController != nil } + try await settle() + return (window, host) + } + + private func adaptiveSheet(of controller: UIViewController) -> UISheetPresentationController? { + // An adapted popover keeps its UIPopoverPresentationController; the + // actual sheet configuration is exposed through the adaptive accessor. + controller.popoverPresentationController?.adaptiveSheetPresentationController + ?? controller.sheetPresentationController + } + + private func settle() async throws { + try await Task.sleep(for: .milliseconds(650)) + } + + private func findList(_ view: UIView) -> UICollectionView? { + if let list = view as? UICollectionView, list.window != nil, !list.isHidden { return list } + for child in view.subviews.reversed() { + if let list = findList(child) { return list } + } + return nil + } + + private func itemCount(_ list: UICollectionView) -> Int { + (0..] = [] + private(set) var posts: [Post] = [] + private(set) var modelRequests = 0 + + init(detail: Session) { self.detail = detail } + func setModelsFailure(_ value: Bool) { modelsFailure = value } + func setModels(_ values: [CodexModelSummary]) { models = values } + func rejectChanges() { changesRejected = true } + func holdPosts() { postsHeld = true } + func releasePosts() { + postsHeld = false + let waiters = postWaiters + postWaiters.removeAll() + for waiter in waiters { waiter.resume() } + } + + func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + let url = try XCTUnwrap(request.url) + let path = url.path + let data: Data + var status = 200 + if request.httpMethod == "POST" { + posts.append(Post(path: path, body: request.httpBody.map { String(decoding: $0, as: UTF8.self) })) + if postsHeld { await withCheckedContinuation { postWaiters.append($0) } } + status = changesRejected ? 409 : 200 + data = Data((changesRejected ? #"{"error":"Config rejected"}"# : #"{"ok":true}"#).utf8) + } else if path.hasSuffix("/codex-models") { + modelRequests += 1 + data = try HapiJSON.encoder.encode(CodexModelsResponse( + success: !modelsFailure, models: modelsFailure ? nil : models, + error: modelsFailure ? "Catalog unavailable" : nil + )) + } else if path == "/api/sessions/config" { + data = try HapiJSON.encoder.encode(SessionResponse(session: detail)) + } else { + throw URLError(.unsupportedURL) + } + return (data, try XCTUnwrap(HTTPURLResponse(url: url, statusCode: status, httpVersion: nil, headerFields: nil))) + } +} + +@MainActor +func configEventually( + file: StaticString = #filePath, line: UInt = #line, + _ condition: () async -> Bool +) async throws { + for _ in 0..<200 { + if await condition() { return } + try await Task.sleep(for: .milliseconds(10)) + } + XCTFail("Timed out waiting for session config state", file: file, line: line) +} diff --git a/ios/HapiTests/SessionListFilterTests.swift b/ios/HapiTests/SessionListFilterTests.swift index 51712f79..8204a568 100644 --- a/ios/HapiTests/SessionListFilterTests.swift +++ b/ios/HapiTests/SessionListFilterTests.swift @@ -6,6 +6,36 @@ import XCTest @MainActor final class SessionListFilterTests: XCTestCase { + func testSidebarAppearanceFetchesOnceButExplicitRetryStillRefreshes() async { + let sessions = HomeFilterTestSessions() + sessions.failRefresh = true + let model = HomeFilterTestData.model(sessions: sessions) + await model.refreshOnFirstAppearance() + await model.refreshOnFirstAppearance() + XCTAssertEqual(sessions.refreshCount, 1) + XCTAssertTrue(model.isOffline) + sessions.failRefresh = false + await model.refresh() + XCTAssertEqual(sessions.refreshCount, 2) + XCTAssertFalse(model.isOffline) + await model.refreshOnFirstAppearance() + XCTAssertEqual(sessions.refreshCount, 2) + } + + func testSidebarInitialRefreshOutlivesPresentationCancellation() async { + let sessions = HomeFilterTestSessions() + let model = HomeFilterTestData.model(sessions: sessions) + let presentation = Task { + await Task.yield() + await model.refreshOnFirstAppearance() + } + presentation.cancel() + await presentation.value + XCTAssertEqual(sessions.refreshCount, 1) + XCTAssertFalse(sessions.refreshWasCancelled) + XCTAssertTrue(model.hasRefreshedOnce) + } + func testEmptyAndSingleMachineHaveNoFilterAffordance() { let sessions = HomeFilterTestSessions() let model = HomeFilterTestData.model(sessions: sessions) @@ -17,7 +47,7 @@ final class SessionListFilterTests: XCTestCase { XCTAssertNil(model.activeMachineFilter) XCTAssertNil(model.filterSummary) XCTAssertEqual(model.rows.count, 1) - XCTAssertEqual(model.rows.first?.meta, "workspace/hapi") + XCTAssertEqual(model.rows.first?.project, "hapi") } func testNamesCountsAndStableOrderIncludeHistoricalMachines() { @@ -52,11 +82,11 @@ final class SessionListFilterTests: XCTestCase { ]) let model = HomeFilterTestData.model(sessions: sessions) let options = model.machineFilters - XCTAssertTrue(model.rows.allSatisfy { $0.meta?.contains(" · ") == true }) + XCTAssertTrue(model.rows.allSatisfy { $0.project == "hapi" }, "Machines remain in filters, not every row") model.selectMachine("mac") XCTAssertTrue(model.filters.isActive) XCTAssertEqual(model.rows.map(\.id), ["a"]) - XCTAssertEqual(model.rows.first?.meta, "workspace/hapi") + XCTAssertEqual(model.rows.first?.project, "hapi") XCTAssertEqual(model.filterSummary, "Machine: Machine · mac") model.selectMachine("mac") XCTAssertEqual(model.activeMachineFilter, "mac") @@ -153,10 +183,12 @@ final class SessionListFilterTests: XCTestCase { final class HomeFilterTestSessions: SessionListStoring { var sessions: [SessionSummary] var refreshCount = 0 + var refreshWasCancelled = false var failRefresh = false init(_ sessions: [SessionSummary] = []) { self.sessions = sessions } func refresh() async throws { refreshCount += 1 + refreshWasCancelled = Task.isCancelled if failRefresh { throw URLError(.notConnectedToInternet) } } func scheduleRefresh() {} diff --git a/ios/HapiTests/SessionNavigationTests.swift b/ios/HapiTests/SessionNavigationTests.swift new file mode 100644 index 00000000..54c128ba --- /dev/null +++ b/ios/HapiTests/SessionNavigationTests.swift @@ -0,0 +1,100 @@ +import HapiClient +import HapiProtocol +import SwiftUI +import XCTest +@testable import Hapi + +@MainActor +final class SessionNavigationTests: XCTestCase { + func testColdStartAndHubReplacementHaveNoSelection() { + let navigation = SessionNavigationState() + XCTAssertNil(navigation.selectedSessionId) + XCTAssertTrue(navigation.detailPath.isEmpty) + XCTAssertEqual(navigation.columnVisibility, .all) + XCTAssertEqual(navigation.preferredCompactColumn, .sidebar) + navigation.open("a") + XCTAssertNil(SessionNavigationState().selectedSessionId) + } + + func testOpenIsIdempotentAndNewSessionClearsNestedNavigation() { + let navigation = SessionNavigationState() + navigation.open("a") + navigation.detailPath.append("files") + navigation.open("a") + XCTAssertEqual(navigation.detailPath.count, 1) + navigation.open("created-before-list-refresh") + XCTAssertEqual(navigation.selectedSessionId, "created-before-list-refresh") + XCTAssertTrue(navigation.detailPath.isEmpty) + XCTAssertEqual(navigation.preferredCompactColumn, .detail) + } + + func testColumnChangesDoNotDiscardSelectionOrDetailPath() { + let navigation = SessionNavigationState() + navigation.open("a") + navigation.detailPath.append("file.swift") + navigation.columnVisibility = .detailOnly + navigation.preferredCompactColumn = .sidebar + XCTAssertEqual(navigation.selectedSessionId, "a") + XCTAssertEqual(navigation.detailPath.count, 1) + navigation.open("a") + navigation.columnVisibility = .all + XCTAssertEqual(navigation.preferredCompactColumn, .detail) + XCTAssertEqual(navigation.detailPath.count, 1) + } + + func testSupersedingAndRemovalCannotStealAnotherChatsFocus() { + let navigation = SessionNavigationState() + navigation.open("a") + navigation.open("b") + navigation.detailPath.append("files") + navigation.supersede("a", with: "a-resumed") + navigation.remove("a") + XCTAssertEqual(navigation.selectedSessionId, "b") + XCTAssertEqual(navigation.detailPath.count, 1) + navigation.supersede("b", with: "b-resumed") + XCTAssertEqual(navigation.selectedSessionId, "b-resumed") + XCTAssertTrue(navigation.detailPath.isEmpty) + navigation.remove("b-resumed") + XCTAssertNil(navigation.selectedSessionId) + XCTAssertEqual(navigation.preferredCompactColumn, .sidebar) + } + + func testHubPublishesExplicitRemovalsEvenForAnUnlistedSession() throws { + let hub = try XCTUnwrap(HubSession(hubUrl: "http://127.0.0.1:1/ipad-removal-\(UUID())", + credentialStore: InMemoryCredentialStore())) + defer { hub.shutdown() } + hub.sessionStore.applySessionEvent(.sessionRemoved(namespace: nil, sessionId: "a")) + let first = try XCTUnwrap(hub.sessionRemoval) + XCTAssertEqual(first.sessionId, "a") + hub.sessionStore.applySessionEvent(.sessionRemoved(namespace: nil, sessionId: "a")) + XCTAssertNotEqual(hub.sessionRemoval, first) + } + + func testAppUsesOneSceneWithoutRequiringFullScreen() { + let manifest = Bundle.main.object(forInfoDictionaryKey: "UIApplicationSceneManifest") as? [String: Any] + XCTAssertEqual(manifest?["UIApplicationSupportsMultipleScenes"] as? Bool, false) + XCTAssertNotEqual(Bundle.main.object(forInfoDictionaryKey: "UIRequiresFullScreen") as? Bool, true) + } + + func testLastSurfaceReleaseStopsTransportBeforeModelDeallocation() async throws { + let hub = try XCTUnwrap(HubSession(hubUrl: "http://127.0.0.1:1/ipad-release-\(UUID())", + credentialStore: InMemoryCredentialStore())) + defer { hub.shutdown() } + var model: ChatModel? = ChatModel(session: hub, sessionId: "a") + weak var released = model + model?.retainSurface("chat") + for _ in 0..<100 { + if hub.openChatSessionId == "a" { break } + try await Task.sleep(for: .milliseconds(20)) + } + XCTAssertEqual(hub.openChatSessionId, "a") + model?.releaseSurface("chat") + model = nil + for _ in 0..<100 { + if hub.openChatSessionId == nil && released == nil { break } + try await Task.sleep(for: .milliseconds(20)) + } + XCTAssertNil(hub.openChatSessionId, "Teardown must not depend on the view retaining its old model") + XCTAssertNil(released) + } +} diff --git a/ios/HapiTests/SessionRowPresentationTests.swift b/ios/HapiTests/SessionRowPresentationTests.swift new file mode 100644 index 00000000..40fcf04d --- /dev/null +++ b/ios/HapiTests/SessionRowPresentationTests.swift @@ -0,0 +1,297 @@ +import HapiProtocol +import HapiUI +import Observation +import SwiftUI +import UIKit +import XCTest +@testable import Hapi + +/// Render the production row, without pairing, network, or UI test hooks in +/// the app. Pixel bounds pin the actual unread dot, not just its container. +@MainActor +final class SessionRowPresentationTests: XCTestCase { + private static let now = Date(timeIntervalSince1970: 1_800_000_000) + + @MainActor @Observable + fileprivate final class Driver { + var summary = HomeFilterTestData.summary("row", machine: nil) + var unread = true + var typeSize = DynamicTypeSize.large + @ObservationIgnored var height: CGFloat = 0 + @ObservationIgnored var appearances = 0 + + var row: SessionRowUI { + SessionRowUI(summary: summary, title: summary.metadata?.name ?? "Session", + project: SessionListModel.projectLabel(summary), + flavor: "codex", unread: unread) + } + } + + private struct Harness: View { + let driver: Driver + var theme: HapiTheme = .light + var locale = Locale(identifier: "en") + + var body: some View { + VStack(spacing: 0) { + SessionRowView(row: driver.row, now: SessionRowPresentationTests.now) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 16) + .padding(.vertical, 12) + .background(GeometryReader { geometry in + Color.clear + .onAppear { driver.height = geometry.size.height; driver.appearances += 1 } + .onChange(of: geometry.size.height) { _, height in driver.height = height } + }) + Spacer(minLength: 0) + } + .background(theme.background) + .hapiTheme(theme) + .environment(\.locale, locale) + .environment(\.dynamicTypeSize, driver.typeSize) + .preferredColorScheme(theme.isDark ? .dark : .light) + .ignoresSafeArea() + } + } + + func testUnreadDotHasOneColumnAcrossTitlesAgesAndStates() async throws { + for width in [CGFloat(320), 390] { + let driver = Driver() + let window = try makeWindow(Harness(driver: driver), width: width) + defer { window.isHidden = true } + var firstCenter: CGPoint? + let cases: [(String, Int, Int, Bool)] = [ + ("Short", 0, 0, false), + ("很长的中文标题用于验证未读圆点不会随着标题移动", 59 * 60_000, 1, true), + ("A very long English title that must truncate before the time", 330 * 86_400_000, 7, true), + ("Running", 2 * 3_600_000, 0, true), + ] + for (title, age, pending, thinking) in cases { + driver.summary.metadata?.name = title + driver.summary.updatedAt = Int(Self.now.timeIntervalSince1970 * 1_000) - age + driver.summary.pendingRequestsCount = pending + driver.summary.pendingRequestKinds = [.input] + driver.summary.thinking = thinking + try await settle() + let dot = try XCTUnwrap(colorBounds(render(window))) + XCTAssertEqual(dot.midX, width - 16 - 6, accuracy: 0.6) + XCTAssertEqual(dot.width, 8, accuracy: 2) + if let firstCenter { + XCTAssertEqual(dot.midX, firstCenter.x, accuracy: 0.1) + XCTAssertEqual(dot.midY, firstCenter.y, accuracy: 0.1) + } else { + firstCenter = CGPoint(x: dot.midX, y: dot.midY) + } + } + let height = driver.height + let scale: CGFloat = 3 + // The final case has a short title; isolate the trailing region + // so antialiased title pixels cannot be mistaken for the time. + let timeBand = CGRect(x: (width - 100) * scale, y: 0, width: 100 * scale, height: (height - 12 - 16 - 4) * scale) + let unreadTime = try XCTUnwrap(colorBounds(render(window, scale: scale), matching: (82, 85, 94), within: timeBand)) + driver.unread = false + try await settle() + XCTAssertNil(try colorBounds(render(window)), "Read rows have no unread dot") + let readTime = try XCTUnwrap(colorBounds(render(window, scale: scale), matching: (82, 85, 94), within: timeBand)) + XCTAssertEqual(readTime.maxX / scale, width - 16, accuracy: 2, "Without a dot, the timestamp aligns to the right margin") + XCTAssertEqual((readTime.minX - unreadTime.minX) / scale, 18, accuracy: 1, "Remove both the 12pt dot slot and its 6pt gap") + XCTAssertEqual(driver.height, height, accuracy: 0.1) + XCTAssertEqual(driver.appearances, 1, "State updates must not rebuild the row") + } + } + + func testRowsStayTwoLinesAndOmitPreviewsAndProgress() async throws { + let driver = Driver() + driver.summary.updatedAt = Int(Self.now.timeIntervalSince1970 * 1_000) + let window = try makeWindow(Harness(driver: driver), width: 390) + defer { window.isHidden = true } + try await settle() + let restingHeight = driver.height + XCTAssertGreaterThanOrEqual(restingHeight, 60) + XCTAssertLessThanOrEqual(restingHeight, 70, "The normal row contains only title and project/status") + driver.summary.pendingRequestsCount = 7 + driver.summary.pendingRequestKinds = [.input, .permission] + driver.summary.todoProgress = .init(completed: 3, total: 5) + try await settle() + XCTAssertEqual(driver.height, restingHeight, accuracy: 1) + // Source progress and summary changes must have no visible effect. + let before = render(window).pngData() + driver.summary.todoProgress = .init(completed: 50, total: 100) + driver.summary.metadata?.summary = .init(text: "A long summary that should not appear in the home list") + try await settle() + XCTAssertEqual(render(window).pngData(), before) + driver.summary.active = false + try await settle() + XCTAssertNotNil(try colorBounds(render(window)), "Disconnecting must not dim the unread accent") + driver.summary.pendingRequestsCount = 0 + try await settle() + XCTAssertEqual(driver.height, restingHeight, accuracy: 1) + + driver.typeSize = .accessibility3 + driver.summary.pendingRequestsCount = 123 + try await settle() + XCTAssertGreaterThan(driver.height, restingHeight + 40, "Large text must grow naturally rather than shrink") + XCTAssertLessThan(driver.height, window.bounds.height) + let scaledImage = render(window, scale: 3) + XCTAssertNotNil(try colorBounds(scaledImage, matching: (154, 103, 0)), "Disconnected attention remains visible at large text sizes") + XCTAssertEqual(driver.appearances, 1) + } + + func testStatusIsACompactTrailingSymbolWithoutCrowdingTheProject() async throws { + let cases: [(HapiTheme, CGFloat, String, [PendingRequestKind])] = [ + (.light, 320, "en", [.input]), + (.light, 390, "zh-Hans", [.permission]), + (.dark, 320, "en", [.input, .permission]), + (.oled, 390, "zh-Hans", [.input]), + ] + for (theme, width, locale, kinds) in cases { + let driver = Driver() + driver.summary.pendingRequestsCount = 2 + driver.summary.pendingRequestKinds = kinds + driver.summary.metadata?.path = "/workspace/a-very-long-project-name-that-must-truncate-before-the-status" + let window = try makeWindow(Harness(driver: driver, theme: theme, locale: Locale(identifier: locale)), width: width) + defer { window.isHidden = true } + try await settle() + let scale: CGFloat = 3 + let amber = theme.isDark ? (210, 153, 34) : (154, 103, 0) + let secondary = theme.isDark ? (168, 173, 184) : (82, 85, 94) + let accent = theme.isDark ? (108, 158, 255) : (59, 130, 246) + let snapshot = render(window, scale: scale) + let status = try XCTUnwrap(colorBounds(snapshot, matching: amber)) + let dot = try XCTUnwrap(colorBounds(snapshot, matching: accent)) + XCTAssertEqual(status.midX / scale, width - 16 - 8, accuracy: 2, "Status symbols share one trailing slot") + XCTAssertLessThanOrEqual(status.width / scale, 18, "No visible status text or badge") + XCTAssertLessThanOrEqual(status.height / scale, 18) + XCTAssertGreaterThan(status.minY, dot.maxY, "Attention belongs to the second line, not the title") + let detailBand = CGRect(x: 0, y: (driver.height - 12 - 16) * scale, width: width * scale, height: 16 * scale) + let project = try XCTUnwrap(colorBounds(snapshot, matching: secondary, within: detailBand)) + XCTAssertEqual(project.minX / scale, 40, accuracy: 3) + XCTAssertLessThanOrEqual(project.maxX / scale + 12, status.minX / scale, "Project and status cannot overlap") + + driver.summary.metadata?.path = "" + try await settle() + let statusWithoutProject = try XCTUnwrap(colorBounds(render(window, scale: scale), matching: amber)) + assertSameSymbolBounds(statusWithoutProject, status) + + driver.typeSize = .accessibility3 + try await settle() + let largeStatus = try XCTUnwrap(colorBounds(render(window, scale: scale), matching: amber)) + XCTAssertGreaterThan(largeStatus.height, status.height, "Symbols scale with Dynamic Type") + XCTAssertLessThanOrEqual(largeStatus.maxX / scale, width - 14) + driver.summary.metadata?.path = "/workspace/another-very-long-project-name" + try await settle() + let largeStatusWithProject = try XCTUnwrap(colorBounds(render(window, scale: scale), matching: amber)) + assertSameSymbolBounds(largeStatusWithProject, largeStatus) + + driver.typeSize = .large + driver.summary.metadata?.path = "" + driver.summary.pendingRequestsCount = 0 + driver.summary.thinking = true + try await settle() + let runningImage = render(window, scale: scale) + XCTAssertNil(try colorBounds(runningImage, matching: amber), "Routine activity stays neutral") + let spinner = try XCTUnwrap(findActivityIndicator(window), "Running reuses native loading, not a static symbol") + XCTAssertTrue(spinner.isAnimating) + let running = spinner.convert(spinner.bounds, to: window) + XCTAssertEqual(running.midX, width - 16 - 8, accuracy: 1) + XCTAssertGreaterThan(running.minY, dot.maxY / scale, "Loading stays in the second line") + XCTAssertEqual(running.width, 14, accuracy: 1) + XCTAssertEqual(running.height, 14, accuracy: 1) + + driver.typeSize = .accessibility3 + try await settle() + let largeSpinner = try XCTUnwrap(findActivityIndicator(window)) + let largeRunning = largeSpinner.convert(largeSpinner.bounds, to: window) + XCTAssertGreaterThan(largeRunning.width, running.width) + XCTAssertLessThanOrEqual(largeRunning.maxX, width - 14, "Dynamic Type must not double-scale loading beyond its slot") + XCTAssertLessThanOrEqual(largeRunning.maxY, driver.height - 10, "Loading stays inside the row") + driver.typeSize = .large + driver.summary.pendingRequestsCount = 1 + try await settle() + XCTAssertNil(findActivityIndicator(window), "Pending attention replaces loading even while thinking remains true") + XCTAssertNotNil(try colorBounds(render(window, scale: scale), matching: amber)) + driver.summary.pendingRequestsCount = 0 + driver.summary.thinking = false + try await settle() + let idleImage = render(window, scale: scale) + XCTAssertNil(try colorBounds(idleImage, matching: amber)) + XCTAssertNil(try colorBounds(idleImage, matching: secondary, within: detailBand), "Idle sessions have no status symbol") + XCTAssertNil(findActivityIndicator(window)) + } + } + + func testStatusSymbolsAreAvailableAndDistinct() { + let statuses: [SessionRowStatus] = [.needsReply(1), .needsApproval(2), .needsAttention(3)] + let symbols = statuses.compactMap(\.symbolName) + XCTAssertEqual(symbols, ["bubble.left", "hand.raised", "exclamationmark.bubble"]) + for symbol in symbols { XCTAssertNotNil(UIImage(systemName: symbol)) } + XCTAssertNil(SessionRowStatus.running.symbolName, "Loading is not represented by a static SF Symbol") + } + + private func findActivityIndicator(_ view: UIView) -> UIActivityIndicatorView? { + if let spinner = view as? UIActivityIndicatorView { return spinner } + return view.subviews.lazy.compactMap(findActivityIndicator).first + } + + private func assertSameSymbolBounds(_ actual: CGRect, _ expected: CGRect, file: StaticString = #filePath, line: UInt = #line) { + // Allow one raster pixel of rounding, not compressed or moved symbols. + XCTAssertEqual(actual.minX, expected.minX, accuracy: 1, file: file, line: line) + XCTAssertEqual(actual.minY, expected.minY, accuracy: 1, file: file, line: line) + XCTAssertEqual(actual.width, expected.width, accuracy: 1, file: file, line: line) + XCTAssertEqual(actual.height, expected.height, accuracy: 1, file: file, line: line) + } + + private func makeWindow(_ view: V, width: CGFloat) 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: width, height: 800) + window.rootViewController = UIHostingController(rootView: view) + window.makeKeyAndVisible() + window.layoutIfNeeded() + return window + } + + private func settle() async throws { + try await Task.sleep(for: .milliseconds(180)) + } + + private func render(_ window: UIWindow, scale: CGFloat = 1) -> UIImage { + let format = UIGraphicsImageRendererFormat() + format.scale = scale + format.preferredRange = .standard + return UIGraphicsImageRenderer(bounds: window.bounds, format: format).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + } + + private func colorBounds(_ image: UIImage, matching rgb: (Int, Int, Int) = (59, 130, 246), within region: CGRect? = nil) throws -> CGRect? { + let source = try XCTUnwrap(image.cgImage) + let width = source.width + let height = source.height + var pixels = [UInt8](repeating: 0, count: width * height * 4) + try pixels.withUnsafeMutableBytes { buffer in + let context = try XCTUnwrap(CGContext( + data: buffer.baseAddress, width: width, height: height, + bitsPerComponent: 8, bytesPerRow: width * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue + )) + context.draw(source, in: CGRect(x: 0, y: 0, width: width, height: height)) + } + var bounds: CGRect? + for y in 0.. UIView { + let view = UIView() + view.accessibilityIdentifier = id + return view + } + func updateUIView(_ view: UIView, context: Context) { view.accessibilityIdentifier = id } + } + + private struct DetailProbe: View { + let sessionId: String + let probe: Probe + @State private var instance = UUID() + @State private var draft = "" + + var body: some View { + Form { + Text(verbatim: sessionId).accessibilityIdentifier("detail-\(sessionId)") + TextField("Draft", text: $draft) + NavigationLink("Files", value: Page.files) + } + .navigationTitle(Text(verbatim: sessionId)) + .overlay { Presence(id: "detail-\(sessionId)").frame(width: 1, height: 1).allowsHitTesting(false) } + .navigationDestination(for: Page.self) { _ in + Text("Files") + .overlay { Presence(id: "detail-files").frame(width: 1, height: 1).allowsHitTesting(false) } + } + .onAppear { probe.instances[sessionId] = instance } + } + } + + private struct Harness: View { + let navigation: SessionNavigationState + let list: SessionListModel + let probe: Probe + + var body: some View { + SessionSplitView(navigation: navigation, onNewSession: { navigation.open("created") }) { + SessionListView(model: list, selection: Binding( + get: { navigation.selectedSessionId }, + set: { if let id = $0 { navigation.open(id) } } + ), onOpenSession: navigation.open) + .navigationTitle("Sessions") + .overlay { Presence(id: "home.sessions").frame(width: 1, height: 1).allowsHitTesting(false) } + } detail: { id in + DetailProbe(sessionId: id, probe: probe) + } + .hapiTypography() + .hapiTheme(.light) + } + } + + func testWideSelectionSurvivesFilteringAndNestedNavigationAcrossCollapse() async throws { + try requireIPad() + let navigation = SessionNavigationState() + let probe = Probe() + let sessions = HomeFilterTestSessions([ + HomeFilterTestData.summary("a", machine: "mac"), + HomeFilterTestData.summary("b", machine: "debian"), + ]) + let list = HomeFilterTestData.model(sessions: sessions) + let (window, host) = try makeWindow(Harness(navigation: navigation, list: list, probe: probe), + width: 1194, height: 834) + defer { window.isHidden = true } + try await settle { list.hasRefreshedOnce } + XCTAssertTrue(probe.instances.isEmpty, "An empty detail must not start/mark a chat read") + let split = try XCTUnwrap(findController(UISplitViewController.self, in: host)) + XCTAssertFalse(split.isCollapsed) + + navigation.open("a") + try await settle { probe.instances["a"] != nil } + let identity = try XCTUnwrap(probe.instances["a"]) + let sidebar = try XCTUnwrap(split.viewController(for: .primary).flatMap { self.findCollection(in: $0.view) }) + XCTAssertGreaterThanOrEqual(sidebar.bounds.width, 280) + XCTAssertLessThanOrEqual(sidebar.bounds.width, 360) + + list.selectMachine("debian") + try await settle { list.rows.map(\.id) == ["b"] } + XCTAssertEqual(navigation.selectedSessionId, "a") + navigation.detailPath.append(Page.files) + try await settle { self.findView("detail-files", in: window) != nil } + resize(window, host: host, width: 390, height: 844, compact: true) + try await settle { split.isCollapsed } + XCTAssertEqual(navigation.selectedSessionId, "a") + XCTAssertEqual(navigation.detailPath.count, 1) + XCTAssertNotNil(findView("detail-files", in: window)) + + resize(window, host: host, width: 1194, height: 834, compact: false) + try await settle { !split.isCollapsed } + navigation.detailPath.removeLast() + try await settle { self.findView("detail-a", in: window) != nil } + XCTAssertEqual(probe.instances["a"], identity) + XCTAssertEqual(list.activeMachineFilter, "debian") + // Neither filtering nor geometry should refresh the sidebar again. + XCTAssertEqual(sessions.refreshCount, 1) + } + + func testCompactProgrammaticOpenAndBackAfterAFilePush() async throws { + try requireIPad() + let navigation = SessionNavigationState() + let probe = Probe() + let list = HomeFilterTestData.model(sessions: HomeFilterTestSessions([ + HomeFilterTestData.summary("a", machine: nil), HomeFilterTestData.summary("b", machine: nil), + ])) + let (window, host) = try makeWindow(Harness(navigation: navigation, list: list, probe: probe), + width: 390, height: 844, compact: true) + defer { window.isHidden = true } + let split = try XCTUnwrap(findController(UISplitViewController.self, in: host)) + try await settle { split.isCollapsed } + // A notification/new session need not have a matching sidebar row. + navigation.open("not-in-list") + try await settle { self.findView("detail-not-in-list", in: window) != nil } + navigation.detailPath.append(Page.files) + try await settle { self.findView("detail-files", in: window) != nil } + navigation.detailPath.removeLast() + try await settle { self.findView("detail-not-in-list", in: window) != nil } + try nativeBack(in: host) + try await settle { self.findView("home.sessions", in: window) != nil } + navigation.open("b") + try await settle { self.findView("detail-b", in: window) != nil } + XCTAssertEqual(navigation.selectedSessionId, "b") + XCTAssertTrue(navigation.detailPath.isEmpty) + navigation.remove("b") + try await settle { self.findView("home.sessions", in: window) != nil } + XCTAssertNil(navigation.selectedSessionId) + } + + private struct ChatHarness: View { + let navigation: SessionNavigationState + let list: SessionListModel + let hub: HubSession + let model: ChatModel + + var body: some View { + SessionSplitView(navigation: navigation, onNewSession: {}) { + SessionListView(model: list, selection: Binding( + get: { navigation.selectedSessionId }, + set: { if let id = $0 { navigation.open(id) } } + ), onOpenSession: navigation.open) + .navigationTitle("Sessions") + } detail: { _ in + ChatView(session: hub, model: model) + } + .hapiTypography() + .hapiTheme(.light) + } + } + + func testRootRoutesNotificationsRemovalsAndHubSwitches() async throws { + try requireIPad() + let suite = "ipad-root-\(UUID())" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let registry = HubRegistry(defaults: defaults) + let credentials = InMemoryCredentialStore() + let payload = Data(#"{"uid":1,"exp":4102444800,"ns":"test"}"#.utf8).base64EncodedString() + for url in ["http://127.0.0.1:1", "http://127.0.0.1:2"] { + registry.register(url) + try credentials.store(HubCredentials(hubUrl: url, accessToken: "test", jwt: "e30.\(payload).test")) + } + let model = AppModel(registry: registry, credentialStore: credentials, performer: SplitTestHTTP()) + let firstHub = try XCTUnwrap(model.session) + let (window, host) = try makeWindow(RootView().environment(model), width: 1194, height: 834) + defer { window.isHidden = true; model.session?.shutdown(); firstHub.shutdown() } + try await settle { firstHub.sessionStore.sessions.count == 2 } + XCTAssertNil(firstHub.openChatSessionId) + XCTAssertNil(findController(TranscriptCollectionController.self, in: host)) + model.pendingOpenSessionId = "a" + try await settle { firstHub.openChatSessionId == "a" && self.findController(TranscriptCollectionController.self, in: host) != nil } + XCTAssertNil(model.pendingOpenSessionId) + try capture(window, name: "ipad-home") + host.overrideUserInterfaceStyle = .dark + try await settle { host.traitCollection.userInterfaceStyle == .dark } + try capture(window, name: "ipad-home-dark") + + firstHub.sessionStore.applySessionEvent(.sessionRemoved(namespace: nil, sessionId: "b")) + try await Task.sleep(for: .milliseconds(250)) + XCTAssertEqual(firstHub.openChatSessionId, "a") + firstHub.sessionStore.applySessionEvent(.sessionRemoved(namespace: nil, sessionId: "a")) + try await settle { firstHub.openChatSessionId == nil } + XCTAssertNil(findController(TranscriptCollectionController.self, in: host)) + + model.switchHub(to: "http://127.0.0.1:2") + let secondHub = try XCTUnwrap(model.session) + try await settle { secondHub.sessionStore.sessions.count == 2 } + XCTAssertNil(secondHub.openChatSessionId) + model.pendingOpenSessionId = "b" + try await settle { secondHub.openChatSessionId == "b" } + XCTAssertNil(firstHub.openChatSessionId) + } + + func testRealChatResizePreservesTranscriptDraftAttachmentsAndSingleSurface() async throws { + try requireIPad() + 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 http = SplitTestHTTP() + let hub = try XCTUnwrap(HubSession(hubUrl: "http://127.0.0.1:1/ipad-chat-\(UUID())", + credentialStore: credentials, performer: http)) + let model = ChatModel(session: hub, sessionId: "a") + let navigation = SessionNavigationState() + navigation.open("a") + let sessions = HomeFilterTestSessions([ + HomeFilterTestData.summary("a", machine: "mac"), HomeFilterTestData.summary("b", machine: "debian"), + ]) + let list = HomeFilterTestData.model(sessions: sessions) + let (window, host) = try makeWindow(ChatHarness(navigation: navigation, list: list, hub: hub, model: model), + width: 1194, height: 834) + defer { window.isHidden = true; model.stop(); hub.shutdown() } + try await settle { !model.isInitialLoading && !model.blocks.isEmpty && !model.isSyncingTail } + let transcript = try XCTUnwrap(findController(TranscriptCollectionController.self, in: host)) + let collection = try XCTUnwrap(findCollection(in: transcript.view)) + model.interactor.setComposerText("检查 iPad 分栏与窗口缩放;这段草稿不能丢失。") + model.interactor.attachments.add(PreparedAttachment(filename: "layout.txt", mimeType: "text/plain", bytes: Data("iPad".utf8))) + try await settle { model.interactor.attachments.items.first?.status == .ready } + let attachment = try XCTUnwrap(model.interactor.attachments.items.first) + let requests = await http.messageRequests + try capture(window, name: "ipad-wide") + + collection.delegate?.scrollViewWillBeginDragging?(collection) + collection.scrollToItem(at: IndexPath(item: 20, section: 0), at: .top, animated: false) + try await settle { !model.followsTail } + let cell = try XCTUnwrap(collection.cellForItem(at: IndexPath(item: 20, section: 0))) + let anchorID = cell.accessibilityIdentifier + let anchorY = cell.frame.minY - collection.contentOffset.y + + for (width, height, compact) in [(820.0, 1180.0, false), (600, 900, false), (390, 844, true), (1194, 834, false)] { + resize(window, host: host, width: width, height: height, compact: compact) + try await settle { self.findController(TranscriptCollectionController.self, in: host) != nil } + XCTAssertTrue(findController(TranscriptCollectionController.self, in: host) === transcript) + let restored = try XCTUnwrap(collection.visibleCells.first { $0.accessibilityIdentifier == anchorID }) + XCTAssertEqual(restored.frame.minY - collection.contentOffset.y, anchorY, accuracy: 2) + XCTAssertEqual(model.interactor.composerText, "检查 iPad 分栏与窗口缩放;这段草稿不能丢失。") + XCTAssertEqual(model.interactor.attachments.items.first?.id, attachment.id) + XCTAssertEqual(model.visibleSurfaces, ["chat"]) + XCTAssertEqual(hub.openChatSessionId, "a") + let rowWidth = try XCTUnwrap(collection.layoutAttributesForItem(at: IndexPath(item: 20, section: 0))).size.width + XCTAssertLessThanOrEqual(rowWidth, 720) + if compact { try capture(window, name: "ipad-compact") } + } + navigation.columnVisibility = .detailOnly + try await settle { collection.bounds.width > 1000 } + navigation.columnVisibility = .all + try await settle { collection.bounds.width < 1000 } + XCTAssertTrue(findController(TranscriptCollectionController.self, in: host) === transcript) + let finalRequests = await http.messageRequests + XCTAssertEqual(finalRequests, requests, "Geometry must not cold-start the chat's message window") + XCTAssertEqual(sessions.refreshCount, 1) + + // A genuinely hidden chat must stop claiming visibility/marking read, + // unlike a detail that only moved during a window resize. + resize(window, host: host, width: 390, height: 844, compact: true) + try await settle { self.findController(UISplitViewController.self, in: host)?.isCollapsed == true } + try nativeBack(in: host) + try await settle { model.visibleSurfaces.isEmpty && hub.openChatSessionId == nil } + navigation.open("a") + try await settle { model.visibleSurfaces == ["chat"] && hub.openChatSessionId == "a" } + XCTAssertEqual(model.interactor.attachments.items.first?.id, attachment.id) + } + + private func requireIPad() throws { + try XCTSkipIf(UIDevice.current.userInterfaceIdiom != .pad, "Run with HAPI_TEST_DEVICE_TYPE=iPad-Air-11-inch-M2") + } + + private func makeWindow(_ view: V, width: CGFloat, height: CGFloat, compact: Bool = false) throws -> (UIWindow, UIHostingController) { + let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + let window = UIWindow(windowScene: scene) + let host = UIHostingController(rootView: view) + window.rootViewController = host + resize(window, host: host, width: width, height: height, compact: compact) + window.makeKeyAndVisible() + host.view.layoutIfNeeded() + return (window, host) + } + + private func resize(_ window: UIWindow, host: UIViewController, width: CGFloat, height: CGFloat, compact: Bool) { + host.traitOverrides.horizontalSizeClass = compact ? .compact : .regular + window.frame = CGRect(x: 0, y: 0, width: width, height: height) + window.layoutIfNeeded() + host.view.layoutIfNeeded() + } + + private func settle(_ condition: () -> Bool, file: StaticString = #filePath, line: UInt = #line) async throws { + for _ in 0..<150 { + try await Task.sleep(for: .milliseconds(20)) + if condition() { + try await Task.sleep(for: .milliseconds(350)) + return + } + } + XCTFail("iPad navigation/layout did not settle", file: file, line: line) + } + + private func findView(_ id: String, in view: UIView) -> UIView? { + guard !view.isHidden else { return nil } + if view.accessibilityIdentifier == id { return view } + return view.subviews.lazy.compactMap { self.findView(id, in: $0) }.first + } + + private func findCollection(in view: UIView) -> UICollectionView? { + if let result = view as? UICollectionView { return result } + return view.subviews.lazy.compactMap { self.findCollection(in: $0) }.first + } + + private func findController(_ type: T.Type, in controller: UIViewController) -> T? { + if let result = controller as? T { return result } + return controller.children.lazy.compactMap { self.findController(type, in: $0) }.first + } + + private func nativeBack(in controller: UIViewController) throws { + func navigations(_ parent: UIViewController) -> [UINavigationController] { + ((parent as? UINavigationController).map { [$0] } ?? []) + + parent.children.flatMap(navigations) + } + let navigation = try XCTUnwrap(navigations(controller).last { + $0.view.window != nil && $0.viewControllers.count > 1 + }) + XCTAssertNotNil(navigation.popViewController(animated: true)) + } + + private func capture(_ window: UIWindow, name: String) throws { + guard let path = ProcessInfo.processInfo.environment["HAPI_IPAD_CAPTURE"] else { return } + let directory = URL(fileURLWithPath: path, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + try XCTUnwrap(image.pngData()).write(to: directory.appendingPathComponent("\(name).png")) + } +} + +private actor SplitTestHTTP: HTTPPerforming { + private(set) var messageRequests = 0 + + func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + let url = try XCTUnwrap(request.url) + var status = 200 + let data: Data + switch url.lastPathComponent { + case "messages": + messageRequests += 1 + let rows = (1...80).map { index in + DecryptedMessage(id: "message-\(index)", seq: index, + content: ["role": "agent", "content": ["type": "codex", "data": [ + "type": "message", "message": .string("布局检查 \(index) · iPad workspace\n\n" + String(repeating: "Keep the conversation readable while resizing the window. ", count: 3)) + ]]], createdAt: index * 1000, invokedAt: index * 1000) + } + data = try JSONEncoder().encode(MessagesResponse(messages: rows, page: MessagesPage( + direction: .latest, limit: 200, epoch: 1, reset: false, + nextBeforeSeq: 1, nextBeforeAt: 1000, snapshotHeadSeq: 80, snapshotHeadAt: 80000, hasMore: false + ))) + case "a", "b": + data = try JSONEncoder().encode(["session": sample(url.lastPathComponent)]) + case "sessions": + data = try JSONEncoder().encode(["sessions": ["a", "b"].map { SummaryPatching.toSessionSummary(sample($0)) }]) + case "machines": + data = Data(#"{"machines":[]}"#.utf8) + case "upload": + data = Data(#"{"success":true,"path":"/tmp/layout.txt"}"#.utf8) + case "delete": + data = Data(#"{"success":true}"#.utf8) + default: + status = 404 + data = Data(#"{"error":"unused test endpoint"}"#.utf8) + } + return (data, try XCTUnwrap(HTTPURLResponse(url: url, statusCode: status, httpVersion: nil, headerFields: nil))) + } + + private func sample(_ id: String) -> Session { + Session(id: id, namespace: "test", seq: 1, createdAt: 0, updatedAt: Int(Date.now.timeIntervalSince1970 * 1000), + active: true, activeAt: 80000, + metadata: SessionMetadata(path: "/workspace/hapi", host: "Mac", name: id == "a" ? "iPad 布局适配" : "Review navigation tests", + machineId: id == "a" ? "mac" : "debian", flavor: "codex"), + metadataVersion: 1, agentStateVersion: 1, thinking: false, thinkingAt: 0) + } +} 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/HapiTests/TranscriptTypographyTests.swift b/ios/HapiTests/TranscriptTypographyTests.swift index bc0790ae..8fe42c0c 100644 --- a/ios/HapiTests/TranscriptTypographyTests.swift +++ b/ios/HapiTests/TranscriptTypographyTests.swift @@ -152,14 +152,18 @@ final class TranscriptTypographyTests: XCTestCase { defer { window.isHidden = true } await settle { driver.layouts.contains(0) } let cell = try await browse(view, index: 25) - view.contentOffset.y = cell.frame.minY + 350 + // Keep the anchor inside this measured row on iPad as well as iPhone. + // A fixed 350pt can already be in the next row with tablet metrics. + let deepOffset = min(350, cell.frame.height / 2) + XCTAssertGreaterThan(deepOffset, 100, "Exercise an offset beyond the unmeasured height estimate") + view.contentOffset.y = cell.frame.minY + deepOffset view.layoutIfNeeded() await settle() let previousSize = try XCTUnwrap(driver.typography).bodySize driver.size = .accessibility5 await settle { (driver.typography?.bodySize ?? 0) > previousSize } let grown = try XCTUnwrap(view.cellForItem(at: IndexPath(item: 25, section: 0))) - XCTAssertEqual(view.contentOffset.y - grown.frame.minY, 350, accuracy: 1) + XCTAssertEqual(view.contentOffset.y - grown.frame.minY, deepOffset, accuracy: 1) } func testReadingWidthAndBoldTextChangesKeepHistoryInPlace() async throws { diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Attachments/ComposerAttachments.swift b/ios/Packages/HapiKit/Sources/HapiClient/Attachments/ComposerAttachments.swift index fd41d6a8..043d055a 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Attachments/ComposerAttachments.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Attachments/ComposerAttachments.swift @@ -92,6 +92,9 @@ public protocol AttachmentUploading: Sendable { /// `POST /api/sessions/:id/upload/delete`. @discardableResult func deleteUpload(sessionId: String, path: String) async throws -> DeleteUploadResponse + + func uploadScratchlistAttachment(sessionId: String, filename: String, data: Data, mimeType: String) async throws -> ScratchlistUploadResponse + func deleteScratchlistAttachment(sessionId: String, attachmentId: String) async throws } extension APIClient: AttachmentUploading {} @@ -101,6 +104,11 @@ extension APIClient: AttachmentUploading {} /// `ComposerAttachments` (B-M3f), which itself mirrors the web /// `attachmentAdapter.ts` flow with mobile adjustments: /// +/// Scratchlist picks upload to the hub rather than the agent machine. Saved +/// references restored into the tray are borrowed (never deleted here) and +/// staged to chat storage only by an explicit send. The two ownership maps +/// separately track unsaved hub uploads and unconsumed chat uploads. +/// /// - ``add(_:)`` uploads immediately (`POST upload`, JSON + base64) and /// tracks the chip through ``ComposerAttachmentStatus``; failures keep the /// payload bytes for ``retry(_:)``, successes drop them (only the small @@ -134,6 +142,8 @@ public final class ComposerAttachments { var path: String? /// Upload payload, retained only until the upload succeeds (retry source). var bytes: Data? + var scratchlist: ScratchlistAttachment? + var uploadsToScratchlist = false } private var entries: [Entry] = [] @@ -143,6 +153,7 @@ public final class ComposerAttachments { /// Nonisolated shadow of the Ready chips' hub paths, so `deinit` (which /// cannot touch main-actor state) can schedule the orphan cleanup. private let uploadedPaths = UploadedPathBox() + private let ownedScratchlistIds = UploadedPathBox() public init(api: any AttachmentUploading, sessionId: String) { self.api = api @@ -155,8 +166,8 @@ public final class ComposerAttachments { // `discardAllDetached` from the holder's `onCleared`). Only Sendable // stored lets are touched here. let paths = uploadedPaths.drain() - guard !paths.isEmpty else { return } Self.deleteDetached(api: api, sessionId: sessionId, paths: paths) + Self.deleteScratchlistDetached(api: api, sessionId: sessionId, ids: ownedScratchlistIds.drain()) } // MARK: - Read surface @@ -176,10 +187,60 @@ public final class ComposerAttachments { entries.contains { $0.ui.status != .ready } } + public var snapshot: [ComposerAttachmentSnapshot] { + entries.compactMap { entry in + guard entry.ui.status == .ready else { return nil } + if let attachment = entry.scratchlist { + return ComposerAttachmentSnapshot(ui: entry.ui, source: .scratchlist(attachment)) + } + return entry.path.map { ComposerAttachmentSnapshot(ui: entry.ui, source: .chatUpload($0)) } + } + } + + public var hasScratchlistAttachments: Bool { entries.contains { $0.scratchlist != nil } } + + /// Budget projection includes pending picks, not just completed uploads. + public var scratchlistBudget: [ScratchlistAttachment] { + entries.map { entry in + entry.scratchlist ?? ScratchlistAttachment(id: entry.ui.id, filename: entry.ui.filename, + mimeType: entry.ui.mimeType, size: entry.ui.sizeBytes, path: "") + } + } + + /// Borrowed references stay in hub storage until an explicit chat send. + /// Removing these chips must never delete the original saved attachment. + public func restoreScratchlist(_ attachments: [ScratchlistAttachment]) { + for attachment in attachments { + guard !entries.contains(where: { $0.scratchlist?.id == attachment.id }) else { continue } + let ui = ComposerAttachmentUI(id: "restored-\(UUID().uuidString)", filename: attachment.filename, + mimeType: attachment.mimeType, sizeBytes: attachment.size, previewBytes: nil, status: .ready) + entries.append(Entry(ui: ui, path: nil, bytes: nil, scratchlist: attachment)) + } + } + + public func markScratchlistPersisted(_ attachments: [ScratchlistAttachment]) { + let ids = Set(attachments.map(\.id)) + for entry in entries where entry.scratchlist.map({ ids.contains($0.id) }) == true { + ownedScratchlistIds.forget(id: entry.ui.id) + } + } + + public func discard(_ snapshot: [ComposerAttachmentSnapshot]) { + for item in snapshot { remove(item.ui.id) } + } + + /// Staged chat uploads now belong to the optimistic message, not this tray. + public func consumePrepared(_ snapshot: [ComposerAttachmentSnapshot]) { + for item in snapshot { + uploadedPaths.forget(id: item.ui.id) + remove(item.ui.id) + } + } + // MARK: - Mutations /// Add a prepared pick to the tray and start its upload. - public func add(_ prepared: PreparedAttachment) { + public func add(_ prepared: PreparedAttachment, toScratchlist: Bool = false) { let ui = ComposerAttachmentUI( id: prepared.id, filename: prepared.filename, @@ -188,8 +249,12 @@ public final class ComposerAttachments { previewBytes: prepared.previewBytes, status: .uploading ) - entries.append(Entry(ui: ui, path: nil, bytes: prepared.bytes)) - upload(id: prepared.id, filename: prepared.filename, mimeType: prepared.mimeType, bytes: prepared.bytes) + entries.append(Entry(ui: ui, path: nil, bytes: prepared.bytes, uploadsToScratchlist: toScratchlist)) + if toScratchlist { + uploadScratchlist(id: prepared.id, filename: prepared.filename, mimeType: prepared.mimeType, bytes: prepared.bytes) + } else { + upload(id: prepared.id, filename: prepared.filename, mimeType: prepared.mimeType, bytes: prepared.bytes) + } } /// Failed chip tap: re-fire the upload with the retained bytes. @@ -200,6 +265,11 @@ public final class ComposerAttachments { return } let ui = entries[index].ui + if entries[index].uploadsToScratchlist { + entries[index].ui = ui.with(status: .uploading) + uploadScratchlist(id: id, filename: ui.filename, mimeType: ui.mimeType, bytes: bytes) + return + } entries[index] = Entry(ui: ui.with(status: .uploading), path: nil, bytes: bytes) upload(id: id, filename: ui.filename, mimeType: ui.mimeType, bytes: bytes) } @@ -209,8 +279,11 @@ public final class ComposerAttachments { public func remove(_ id: String) { guard let index = entries.firstIndex(where: { $0.ui.id == id }) else { return } let removed = entries.remove(at: index) - uploadedPaths.forget(id: id) - guard let path = removed.path else { return } + if let owned = ownedScratchlistIds.remove(id: id) { + Self.deleteScratchlistDetached(api: api, sessionId: sessionId, ids: [owned]) + } + let ownedPath = uploadedPaths.remove(id: id) + guard let path = ownedPath, removed.path != nil else { return } let api = api let sessionId = sessionId Task { @@ -218,11 +291,12 @@ public final class ComposerAttachments { } } - /// Take every Ready chip as send metadata, clearing them from the tray + /// Take Ready chat-upload chips as send metadata, clearing them from the tray /// (unsettled chips stay put — the interactor guards against calling with /// any pending, but a race can settle one to Failed in between). /// - /// - Returns: the metadata list, or nil when nothing was ready. + /// Hub-backed chips require staging followed by ``consumePrepared(_:)``. + /// - Returns: the metadata list, or nil when no chat upload was ready. public func consume() -> [AttachmentMetadata]? { var taken: [Entry] = [] entries.removeAll { entry in @@ -255,12 +329,39 @@ public final class ComposerAttachments { public func discardAllDetached() { entries = [] let paths = uploadedPaths.drain() - guard !paths.isEmpty else { return } Self.deleteDetached(api: api, sessionId: sessionId, paths: paths) + Self.deleteScratchlistDetached(api: api, sessionId: sessionId, ids: ownedScratchlistIds.drain()) } // MARK: - Internals + private func uploadScratchlist(id: String, filename: String, mimeType: String, bytes: Data) { + Task { + let attachment: ScratchlistAttachment? + do { + let result = try await api.uploadScratchlistAttachment(sessionId: sessionId, filename: filename, data: bytes, mimeType: mimeType) + attachment = result.success ? result.attachment : nil + } catch { attachment = nil } + guard let index = entries.firstIndex(where: { $0.ui.id == id }) else { + if let attachment { try? await api.deleteScratchlistAttachment(sessionId: sessionId, attachmentId: attachment.id) } + return + } + entries[index].ui = entries[index].ui.with(status: attachment == nil ? .failed : .ready) + entries[index].scratchlist = attachment + if let attachment { + entries[index].bytes = nil + ownedScratchlistIds.set(id: id, path: attachment.id) + } + } + } + + private nonisolated static func deleteScratchlistDetached(api: any AttachmentUploading, sessionId: String, ids: [String]) { + guard !ids.isEmpty else { return } + Task.detached { + for id in ids { try? await api.deleteScratchlistAttachment(sessionId: sessionId, attachmentId: id) } + } + } + private func upload(id: String, filename: String, mimeType: String, bytes: Data) { // Strong self on purpose: the upload finishes (and settles or deletes // its orphan) even while the screen is being dismantled — Android's @@ -313,6 +414,7 @@ public final class ComposerAttachments { sessionId: String, paths: [String] ) { + guard !paths.isEmpty else { return } Task.detached { for path in paths { _ = try? await api.deleteUpload(sessionId: sessionId, path: path) @@ -335,9 +437,13 @@ private final class UploadedPathBox: @unchecked Sendable { } func forget(id: String) { + _ = remove(id: id) + } + + func remove(id: String) -> String? { lock.lock() - paths.removeValue(forKey: id) - lock.unlock() + defer { lock.unlock() } + return paths.removeValue(forKey: id) } func drain() -> [String] { diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractionState.swift b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractionState.swift index c85a0b9e..90416e87 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. @@ -192,6 +204,9 @@ public struct SessionConfigState: Equatable, Sendable { public let permissionMode: PermissionMode? /// Catalog modes for this flavor; empty → hide the section (pi). public let permissionModes: [PermissionModeOption] + /// Codex collaboration is independent of its permission mode. + public let collaborationMode: CodexCollaborationMode? + public let canChangeCollaborationMode: Bool public let model: String? /// nil → hide the model section (flavor without a known catalog). public let modelOptions: [CatalogOption]? @@ -208,6 +223,8 @@ public struct SessionConfigState: Equatable, Sendable { controlledByUser: Bool, permissionMode: PermissionMode?, permissionModes: [PermissionModeOption], + collaborationMode: CodexCollaborationMode?, + canChangeCollaborationMode: Bool, model: String?, modelOptions: [CatalogOption]?, modelOptionsLoading: Bool, @@ -219,6 +236,8 @@ public struct SessionConfigState: Equatable, Sendable { self.controlledByUser = controlledByUser self.permissionMode = permissionMode self.permissionModes = permissionModes + self.collaborationMode = collaborationMode + self.canChangeCollaborationMode = canChangeCollaborationMode self.model = model self.modelOptions = modelOptions self.modelOptionsLoading = modelOptionsLoading @@ -235,6 +254,9 @@ public func buildSessionConfigState( codexModels: CodexModelsState ) -> SessionConfigState { let flavor = detail?.metadata?.flavor ?? summary?.metadata?.flavor + let active = detail?.active ?? summary?.active ?? false + let controlledByUser = detail?.agentState?.controlledByUser == true + && detail?.metadata?.capabilities?.concurrentClients != true let model = detail?.model var modelOptions: [CatalogOption]? var modelOptionsLoading = false @@ -275,12 +297,14 @@ public func buildSessionConfigState( return SessionConfigState( flavor: flavor, - active: detail?.active ?? summary?.active ?? false, - controlledByUser: detail?.agentState?.controlledByUser == true && detail?.metadata?.capabilities?.concurrentClients != true, + active: active, + controlledByUser: controlledByUser, permissionMode: detail?.permissionMode, permissionModes: permissionModeOptions(forFlavor: flavor).filter { detail?.metadata?.capabilities?.concurrentClients != true || $0.mode.rawValue != "safe-yolo" }, + collaborationMode: detail?.collaborationMode, + canChangeCollaborationMode: detail != nil && flavor == "codex" && active && !controlledByUser, model: model, modelOptions: modelOptions, modelOptionsLoading: modelOptionsLoading, diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift index b06717e6..947d9b7b 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift @@ -35,7 +35,7 @@ import Observation /// published ``permissionOverrides`` prunes rows whose request left /// `agentState.requests`); hub 404/409 → benign "already handled". /// - **Config** (``config``/``setPermissionMode(_:)``/``setModel(_:)``/ -/// ``setEffort(_:)``/``loadModelOptions()``): catalog pickers with +/// ``setEffort(_:)``/``setCollaborationMode(_:)``/``loadModelOptions()``): catalog pickers with /// optimistic detail updates, rolled forward to server truth on error; /// codex model catalog fetched per session. /// @@ -68,6 +68,29 @@ 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 + public private(set) var composerDestination: ComposerDestination = .chat + public private(set) var scratchlistBusy = false + public private(set) var scratchlistError: String? + public private(set) var scratchlistErrorDestination: ComposerDestination? + public private(set) var scratchlistEntryErrors: [String: String] = [:] + public private(set) var queuedScratchlistEntries: Set = [] + private var parkAttempt: (text: String, attachments: [ComposerAttachmentSnapshot], id: String)? + private struct ScratchlistQueueAttempt { + let entry: ScratchlistEntry + let localId: String + let target: String + let attachments: [AttachmentMetadata] + } + private var scratchlistQueueAttempts: [String: ScratchlistQueueAttempt] = [:] + private var scratchlistSendTarget: String? + // Screen-owned, not row-local: recycled plan cards retain operation state. + private var pendingCodexPlanId: String? + private var implementedCodexPlanIds: Set = [] + private var continuedCodexPlanIds: Set = [] + private var codexPlanErrors: [String: String] = [:] + private var queuedOpPending = false /// Raw override map; the published view prunes settled requests. private var overridesStore: [String: PermissionRowOverride] = [:] @@ -184,11 +207,19 @@ public final class ChatInteractor { /// an unsettled chip (uploading/failed) blocks the send with a notice. /// Text may be empty when attachments exist (wire: text OR attachments). public func sendMessage(steer: Bool = false) { - guard !isSending else { return } + guard !isSending, !scratchlistBusy else { return } + if composerDestination == .scratchlist { + parkComposerDraft() + return + } if attachments.hasUnsettled { emit(.notice("Attachments are still uploading — wait, or retry/remove the failed ones")) return } + if attachments.hasScratchlistAttachments { + sendComposerWithScratchlistAttachments(steer: steer) + return + } let text = composerText.trimmingCharacters(in: .whitespacesAndNewlines) let attachmentMetadata = attachments.consume() guard !text.isEmpty || attachmentMetadata != nil else { return } @@ -251,6 +282,10 @@ public final class ChatInteractor { /// same localId. A retry cannot prove the original turn is still live — /// steer degrades to queue (web `getRetryDeliveryMode`). public func retryFailedMessage(localId: String) { + if let attempt = scratchlistQueueAttempts.values.first(where: { $0.localId == localId }) { + Task { await queueScratchlistEntry(attempt.entry) } + return + } guard !isSending else { return } isSending = true Task { [weak self] in @@ -307,6 +342,7 @@ public final class ChatInteractor { return SendPayload(text: text, attachments: attachments) } + @discardableResult private func performSend( text: String, localId: String, @@ -314,10 +350,12 @@ public final class ChatInteractor { deliveryMode: MessageDeliveryMode, attachments: [AttachmentMetadata]?, scheduledAt: Int?, - isRetry: Bool - ) async { + isRetry: Bool, + targetSessionId: String? = nil + ) async -> String? { defer { isSending = false } - let store = await windowController() + let target = targetSessionId ?? sessionId + let store = target == sessionId ? await windowController() : await windows.open(sessionId: target) if isRetry { await store.updateStatus(localId: localId, status: .sending) } else { @@ -338,12 +376,14 @@ public final class ChatInteractor { deliveryMode: deliveryMode ) do { - try await api.sendMessage(sessionId: sessionId, request) + try await api.sendMessage(sessionId: target, request) await store.updateStatus(localId: localId, status: successStatus()) + return target } catch let error as APIError where error.status == 409 && error.code == "session_inactive" { - await resumeAndRetry(store: store, request: request, localId: localId) + return await resumeAndRetry(store: store, request: request, localId: localId, fromSessionId: target) } catch { await store.updateStatus(localId: localId, status: .failed) + return nil } } @@ -360,24 +400,25 @@ public final class ChatInteractor { private func resumeAndRetry( store: MessageWindowController, request: SendMessageRequest, - localId: String - ) async { + localId: String, + fromSessionId: String + ) async -> String? { let targetSessionId: String do { targetSessionId = try await api.resumeSession( - id: sessionId, - permissionMode: sessionStore.detail(for: sessionId)?.permissionMode + id: fromSessionId, + permissionMode: sessionStore.detail(for: fromSessionId)?.permissionMode ) } catch { await store.updateStatus(localId: localId, status: .failed) emit(.notice("Session is inactive and could not be resumed")) - return + return nil } let optimisticRow = await store.state.messages.first { $0.localId == localId } var targetStore = store - if targetSessionId != sessionId { - await windows.seed(fromSessionId: sessionId, toSessionId: targetSessionId) + if targetSessionId != fromSessionId { + await windows.seed(fromSessionId: fromSessionId, toSessionId: targetSessionId) targetStore = await windows.open(sessionId: targetSessionId) if let optimisticRow { // Seeding copies rows across, but make the hand-off explicit: @@ -385,22 +426,26 @@ public final class ChatInteractor { await targetStore.appendOptimistic(optimisticRow) await store.removeMessage(localIdOrId: localId) } - drafts?.move(fromSessionId: sessionId, toSessionId: targetSessionId) + drafts?.move(fromSessionId: fromSessionId, toSessionId: targetSessionId) } // Resume succeeded: reflect activity locally, refresh the list row. - sessionStore.updateDetailLocal(sessionId) { $0.active = true } + sessionStore.updateDetailLocal(fromSessionId) { $0.active = true } sessionStore.scheduleRefresh() + scratchlistSendTarget = targetSessionId + var accepted = false do { try await api.sendMessage(sessionId: targetSessionId, request) await targetStore.updateStatus(localId: localId, status: successStatus()) + accepted = true } catch { await targetStore.updateStatus(localId: localId, status: .failed) } if targetSessionId != sessionId { emit(.sessionSuperseded(sessionId: targetSessionId)) } + return accepted ? targetSessionId : nil } // MARK: - Queued bar @@ -684,6 +729,18 @@ public final class ChatInteractor { ) } + /// Codex `POST /collaboration-mode`; shared terminals can edit too. + public func setCollaborationMode(_ mode: CodexCollaborationMode) { + let config = config + guard config.canChangeCollaborationMode, mode != (config.collaborationMode ?? .default) else { return } + let api = api + let sessionId = sessionId + runConfigChange( + optimistic: { $0.collaborationMode = mode }, + call: { try await api.setCollaborationMode(sessionId: sessionId, mode: mode) } + ) + } + /// `POST /model` — nil clears back to the agent default. public func setModel(_ model: String?) { let api = api @@ -770,6 +827,60 @@ 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) + && !continuedCodexPlanIds.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 dismisses this proposal’s actions and focuses the 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 } + continuedCodexPlanIds.insert(planId) + codexPlanErrors[planId] = nil + composerFocusRequest += 1 + } + // MARK: - Internals private func windowController() async -> MessageWindowController { @@ -856,28 +967,218 @@ public final class ChatInteractor { } } - /// Scratchlist "Park current draft": the composer draft becomes a - /// scratchlist entry and the composer clears (store-optimistic; the - /// composer clears only after the hub accepts, so a failed park cannot - /// lose the draft). + public var hasComposerDraft: Bool { !Self.isBlank(composerText) || !attachments.items.isEmpty } + + public func setComposerDestination(_ destination: ComposerDestination) { + guard !scratchlistBusy, !isSending else { return } + composerDestination = destination + scratchlistError = nil + scratchlistErrorDestination = nil + } + + public func focusComposer() { composerFocusRequest += 1 } + + public func reportScratchlistError(_ message: String) { + scratchlistError = message + scratchlistErrorDestination = nil + } + + public func retryScratchlistComposerOperation() { + switch scratchlistErrorDestination { + case .scratchlist: parkComposerDraft() + case .chat: sendMessage() + case nil: scratchlistError = nil + } + } + + /// Capture both text and attachment identities; only clear the accepted + /// snapshot. A retry of the same draft uses the same hub entry id. public func parkComposerDraft() { - guard let scratchlist else { return } + guard scratchlist != nil, !scratchlistBusy, !isSending, hasComposerDraft else { return } + scratchlistBusy = true + Task { + defer { scratchlistBusy = false } + _ = await parkCurrentDraft() + } + } + + private func parkCurrentDraft() async -> Bool { + guard let scratchlist else { return false } let text = composerText - guard !Self.isBlank(text) else { return } - Task { [weak self] in - guard let self else { return } - switch await scratchlist.createEntry(sessionId: self.sessionId, text: text) { - case .created: - // Clear only when the draft is still what we parked (the - // operator may have kept typing while the POST ran). - if self.composerText == text { - self.setComposerText("") + scratchlistError = nil + guard text.utf16.count <= ScratchlistCaps.maxTextLength else { + return failPark("Drafts can contain at most 10,000 characters — shorten the text before saving") + } + guard !attachments.hasUnsettled else { + return failPark("Attachments are still uploading — wait, or retry/remove the failed ones") + } + let snapshot = attachments.snapshot + guard !Self.isBlank(text) || !snapshot.isEmpty else { return false } + if parkAttempt?.text != text || parkAttempt?.attachments != snapshot { + guard !scratchlist.state(sessionId).atCap else { return failPark("Scratchlist is full (200 entries)") } + parkAttempt = (text, snapshot, "scratch-\(UUID().uuidString)") + } + let id = parkAttempt!.id + let prepared: ScratchlistTransfer.Parked + do { + prepared = try await ScratchlistTransfer.preparePark(api: api, store: scratchlist, sessionId: sessionId, snapshot: snapshot) + } catch { return failPark(error.localizedDescription) } + guard composerText == text, attachments.snapshot == snapshot, !attachments.hasUnsettled else { + await ScratchlistTransfer.cleanupPark(store: scratchlist, sessionId: sessionId, attachments: prepared.uploaded) + return failPark("Your input changed — review it and try again") + } + switch await scratchlist.createEntry(sessionId: sessionId, text: text, attachments: prepared.attachments, entryId: id) { + case .created(let entry): + attachments.markScratchlistPersisted(entry.attachments) + if composerText == text, attachments.snapshot == snapshot, !attachments.hasUnsettled { + setComposerText("") + attachments.discard(snapshot) + } + parkAttempt = nil + // A retried POST can return the first accepted set of attachments. + let canonicalIds = Set(entry.attachments.map(\.id)) + await ScratchlistTransfer.cleanupPark(store: scratchlist, sessionId: sessionId, + attachments: prepared.uploaded.filter { !canonicalIds.contains($0.id) }) + emit(.notice("Draft parked to scratchlist")) + return true + case .atCap: + await ScratchlistTransfer.cleanupPark(store: scratchlist, sessionId: sessionId, attachments: prepared.uploaded) + return failPark("Scratchlist is full (200 entries)") + case .failed: + await ScratchlistTransfer.cleanupPark(store: scratchlist, sessionId: sessionId, attachments: prepared.uploaded) + return failPark("Couldn't park the draft — check the hub connection") + } + } + + private func failPark(_ message: String) -> Bool { + scratchlistError = message + scratchlistErrorDestination = .scratchlist + emit(.notice(message)) + return false + } + + /// The caller asks for a choice when there is an existing draft. Restoring + /// borrowed hub references is local and never resumes or sends a session. + @discardableResult + public func restoreScratchlistEntry(_ entry: ScratchlistEntry, choice: ScratchlistRestoreChoice = .append) async -> Bool { + guard !scratchlistBusy, !isSending, !queuedScratchlistEntries.contains(entry.entryId) else { return false } + scratchlistBusy = true + defer { scratchlistBusy = false } + scratchlistError = nil + if choice == .parkCurrent, hasComposerDraft { + guard await parkCurrentDraft() else { return false } + guard !hasComposerDraft else { return failPark("Your input changed — review it and try again") } + } + insertComposerText(entry.text) + attachments.restoreScratchlist(entry.attachments) + composerDestination = .chat + focusComposer() + return true + } + + /// Direct queue sends have their own immutable payload; they never consume + /// the visible composer. Failed retries reuse the exact localId/uploads. + @discardableResult + public func queueScratchlistEntry(_ entry: ScratchlistEntry) async -> Bool { + guard let scratchlist, !scratchlistBusy, !isSending else { return false } + scratchlistBusy = true + defer { scratchlistBusy = false } + scratchlistEntryErrors[entry.entryId] = nil + if queuedScratchlistEntries.contains(entry.entryId) { + return await finishScratchlistQueue(entryId: entry.entryId, store: scratchlist) + } + do { + let attempt: ScratchlistQueueAttempt + let isRetry = scratchlistQueueAttempts[entry.entryId] != nil + if let previous = scratchlistQueueAttempts[entry.entryId] { + attempt = previous + } else { + let target = try await resolveScratchlistSendTarget(needsUpload: !entry.attachments.isEmpty) + let staged = try await ScratchlistTransfer.prepareSend(api: api, sourceSessionId: target, + targetSessionId: target, snapshot: ScratchlistTransfer.snapshot(entry)) + // Stable across closing/reopening the chat and lost responses: + // the same saved version cannot be queued twice by a retry. + attempt = ScratchlistQueueAttempt(entry: entry, localId: "scratchlist-\(entry.entryId)-\(entry.updatedAt)", + target: target, attachments: staged) + scratchlistQueueAttempts[entry.entryId] = attempt + } + isSending = true + let acceptedTarget = await performSend(text: attempt.entry.text, localId: attempt.localId, createdAt: now(), + deliveryMode: .queue, attachments: attempt.attachments.isEmpty ? nil : attempt.attachments, + scheduledAt: nil, isRetry: isRetry, targetSessionId: attempt.target) + guard let acceptedTarget else { + scratchlistEntryErrors[entry.entryId] = "Couldn't queue the draft — retry" + return false + } + scratchlistSendTarget = acceptedTarget + queuedScratchlistEntries.insert(entry.entryId) + let removed = await finishScratchlistQueue(entryId: entry.entryId, store: scratchlist) + composerDestination = .chat + emit(.notice(removed ? "Draft added to the send queue" : "Already queued — couldn't remove the draft. Retry removal only.")) + navigateAfterScratchlistSend() + return removed + } catch { + scratchlistEntryErrors[entry.entryId] = "Couldn't prepare the attachments — retry or remove the failed files" + return false + } + } + + private func finishScratchlistQueue(entryId: String, store: any SessionScratchlistStoring) async -> Bool { + let removed = await store.deleteEntry(sessionId: scratchlistSendTarget ?? sessionId, entryId: entryId) + if removed { + scratchlistQueueAttempts[entryId] = nil + queuedScratchlistEntries.remove(entryId) + scratchlistEntryErrors[entryId] = nil + } else { + scratchlistEntryErrors[entryId] = "Already queued — couldn't remove the draft. Retry removal only." + } + return removed + } + + private func resolveScratchlistSendTarget(needsUpload: Bool) async throws -> String { + if let scratchlistSendTarget { return scratchlistSendTarget } + guard needsUpload, !currentSessionState().active else { return sessionId } + let target = try await api.resumeSession(id: sessionId, permissionMode: sessionStore.detail(for: sessionId)?.permissionMode) + scratchlistSendTarget = target + sessionStore.updateDetailLocal(sessionId) { $0.active = true } + sessionStore.scheduleRefresh() + if target != sessionId { + await windows.seed(fromSessionId: sessionId, toSessionId: target) + drafts?.move(fromSessionId: sessionId, toSessionId: target) + } + return target + } + + private func navigateAfterScratchlistSend() { + if let target = scratchlistSendTarget, target != sessionId { emit(.sessionSuperseded(sessionId: target)) } + } + + private func sendComposerWithScratchlistAttachments(steer: Bool) { + let text = composerText + let snapshot = attachments.snapshot + isSending = true + Task { + defer { isSending = false } + do { + let target = try await resolveScratchlistSendTarget(needsUpload: true) + let staged = try await ScratchlistTransfer.prepareSend(api: api, sourceSessionId: target, + targetSessionId: target, snapshot: snapshot) + guard composerText == text, attachments.snapshot == snapshot, !attachments.hasUnsettled else { + for (source, staged) in zip(snapshot, staged) { + if case .scratchlist = source.source { _ = try? await api.deleteUpload(sessionId: target, path: staged.path) } + } + scratchlistError = "Your input changed — review it and try again" + scratchlistErrorDestination = .chat + return } - self.emit(.notice("Draft parked to scratchlist")) - case .atCap: - self.emit(.notice("Scratchlist is full (200 entries)")) - case .failed: - self.emit(.notice("Couldn't park the draft — check the hub connection")) + setComposerText("") + attachments.consumePrepared(snapshot) + _ = await performSend(text: text, localId: makeLocalId(), createdAt: now(), deliveryMode: steer ? .steer : .queue, + attachments: staged, scheduledAt: nil, isRetry: false, targetSessionId: target) + navigateAfterScratchlistSend() + } catch { + scratchlistError = "Couldn't prepare the attachments — retry or remove the failed files" + scratchlistErrorDestination = .chat } } } 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/Sources/HapiClient/Chat/ScratchlistTransfer.swift b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ScratchlistTransfer.swift new file mode 100644 index 00000000..f0b13e4d --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ScratchlistTransfer.swift @@ -0,0 +1,119 @@ +import Foundation +import HapiProtocol + +public enum ComposerDestination: Equatable, Sendable { + case chat + case scratchlist +} + +public enum ScratchlistRestoreChoice: Sendable { + case append + case parkCurrent +} + +public struct ComposerAttachmentSnapshot: Equatable, Sendable { + public enum Source: Equatable, Sendable { + case chatUpload(String) + case scratchlist(ScratchlistAttachment) + } + public let ui: ComposerAttachmentUI + public let source: Source +} + +enum ScratchlistTransferError: Error, LocalizedError { + case attachment(String) + case limit + var errorDescription: String? { + switch self { + case .attachment: "Couldn't prepare the attachments — retry or remove the failed files" + case .limit: "The attachments exceed the scratchlist limits — remove a file or choose a smaller one" + } + } +} + +/// Storage conversion is explicit. Hub paths never travel in chat messages, +/// and chat paths never travel in scratchlist writes. Failed preparation +/// cleans up only newly created copies; the source always stays intact. +enum ScratchlistTransfer { + struct Parked { + var attachments: [ScratchlistAttachment] = [] + var uploaded: [ScratchlistAttachment] = [] + } + + @MainActor + static func preparePark(api: APIClient, store: any SessionScratchlistStoring, sessionId: String, + snapshot: [ComposerAttachmentSnapshot]) async throws -> Parked { + let limits = await store.limits(sessionId: sessionId) + guard snapshot.count <= limits.maxAttachmentsPerEntry, + snapshot.reduce(0, { $0 + $1.ui.sizeBytes }) <= limits.maxBytesPerEntry, + snapshot.allSatisfy({ limits.allowedMimeTypes.contains($0.ui.mimeType) && $0.ui.sizeBytes <= limits.maxBytesPerFile }) + else { throw ScratchlistTransferError.limit } + var result = Parked() + do { + for item in snapshot { + switch item.source { + case .scratchlist(let attachment): result.attachments.append(attachment) + case .chatUpload(let path): + let file = try await api.readSessionFile(sessionId: sessionId, path: path) + guard file.success, let content = file.content, let bytes = Data(base64Encoded: content) else { + throw ScratchlistTransferError.attachment(item.ui.filename) + } + switch await store.uploadAttachment(sessionId: sessionId, filename: item.ui.filename, data: bytes, mimeType: item.ui.mimeType) { + case .uploaded(let attachment): + result.uploaded.append(attachment) + result.attachments.append(attachment) + case .failed: throw ScratchlistTransferError.attachment(item.ui.filename) + } + } + } + return result + } catch { + await cleanupPark(store: store, sessionId: sessionId, attachments: result.uploaded) + throw error + } + } + + @MainActor + static func cleanupPark(store: any SessionScratchlistStoring, sessionId: String, attachments: [ScratchlistAttachment]) async { + for attachment in attachments { + _ = await store.deleteAttachment(sessionId: sessionId, attachmentId: attachment.id) + } + } + + static func prepareSend(api: APIClient, sourceSessionId: String, targetSessionId: String, + snapshot: [ComposerAttachmentSnapshot]) async throws -> [AttachmentMetadata] { + var result: [AttachmentMetadata] = [] + var createdPaths: [String] = [] + do { + for item in snapshot { + let path: String + switch item.source { + case .chatUpload(let existing): path = existing + case .scratchlist(let attachment): + let bytes = try await api.scratchlistAttachment(sessionId: sourceSessionId, attachmentId: attachment.id).data + let uploaded = try await api.uploadFile(sessionId: targetSessionId, filename: attachment.filename, + data: bytes, mimeType: attachment.mimeType) + guard uploaded.success, let uploadedPath = uploaded.path else { + throw ScratchlistTransferError.attachment(attachment.filename) + } + path = uploadedPath + createdPaths.append(path) + } + result.append(AttachmentMetadata(id: item.ui.id, filename: item.ui.filename, mimeType: item.ui.mimeType, + size: item.ui.sizeBytes, path: path, + previewUrl: item.ui.previewBytes.map { AttachmentPolicy.dataUrl(mimeType: "image/jpeg", bytes: $0) })) + } + return result + } catch { + for path in createdPaths { _ = try? await api.deleteUpload(sessionId: targetSessionId, path: path) } + throw error + } + } + + static func snapshot(_ entry: ScratchlistEntry) -> [ComposerAttachmentSnapshot] { + entry.attachments.map { + ComposerAttachmentSnapshot(ui: ComposerAttachmentUI(id: $0.id, filename: $0.filename, mimeType: $0.mimeType, + sizeBytes: $0.size, previewBytes: nil, status: .ready), source: .scratchlist($0)) + } + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/DirectoryBrowser/RemoteDirectoryBrowserModel.swift b/ios/Packages/HapiKit/Sources/HapiClient/DirectoryBrowser/RemoteDirectoryBrowserModel.swift index f638bc12..4ad574d2 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/DirectoryBrowser/RemoteDirectoryBrowserModel.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/DirectoryBrowser/RemoteDirectoryBrowserModel.swift @@ -25,18 +25,51 @@ public struct RemoteDirectoryBreadcrumb: Identifiable, Equatable, Sendable { /** Pure remote-path operations shared by directory-browser consumers. */ public enum RemoteDirectoryPath { + /// Empty roots mean unrestricted browsing, matching the runner's spawn policy. public static func browseRoots(for machine: Machine) -> [String] { - let workspaceRoots = unique( + unique( machine.metadata?.workspaceRoots? + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } ?? [] ) - if !workspaceRoots.isEmpty { return workspaceRoots } + } + + public static func defaultDirectory(for machine: Machine) -> String { + if let root = browseRoots(for: machine).first { return root } if let home = machine.metadata?.homeDir, !home.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - return [home] + return home.trimmingCharacters(in: .whitespacesAndNewlines) } - return [] + return machine.metadata?.platform == "win32" ? "" : "/" + } + + /// Expand against the runner's home, never the phone's local filesystem. + public static func expandHome(_ input: String, homeDirectory: String?) -> String { + let path = input.trimmingCharacters(in: .whitespacesAndNewlines) + guard let home = homeDirectory?.trimmingCharacters(in: .whitespacesAndNewlines), + !home.isEmpty else { return path } + if path == "~" { return home } + if path.hasPrefix("~/") || (home.contains("\\") && path.hasPrefix("~\\")) { + return join(parent: home, child: String(path.dropFirst(2))) + } + return path + } + + public static func filesystemRoot(_ path: String) -> String? { + if isDriveAbsolute(path) { return String(path.prefix(3)) } + if path.hasPrefix("\\\\") || path.hasPrefix("//") { + let parts = path.dropFirst(2).split(whereSeparator: isPathSeparator) + guard parts.count >= 2 else { return nil } + let separator = path.hasPrefix("\\") ? "\\" : "/" + return separator + separator + parts[0] + separator + parts[1] + } + return path.hasPrefix("/") ? "/" : nil + } + + public static func allowsBrowsing(path: String, roots: [String]) -> Bool { + filesystemRoot(path) != nil + && (roots.isEmpty || roots.contains { isWithinRoot(path: path, root: $0) }) } public static func join(parent: String, child: String) -> String { @@ -124,7 +157,8 @@ public enum RemoteDirectoryPath { * Reusable runner-backed directory navigation state machine. * * Consumers own presentation and selection handling. Navigation is lexically - * confined to ``roots``; the runner performs canonical symlink-aware checks. + * confined to explicit ``roots``; empty roots allow any absolute path. The + * runner performs canonical symlink-aware checks. */ @MainActor @Observable public final class RemoteDirectoryBrowserModel { @@ -152,17 +186,25 @@ public final class RemoteDirectoryBrowserModel { self.fallbackError = fallbackError } - public func open(machineId: String, roots: [String], initialPath: String? = nil) { + public func open( + machineId: String, + roots: [String], + initialPath: String? = nil, + defaultPath: String? = nil + ) { close() let usableRoots = unique(roots.filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) let selectedInitialPath = initialPath.flatMap { candidate in - usableRoots.contains { RemoteDirectoryPath.isWithinRoot(path: candidate, root: $0) } + RemoteDirectoryPath.allowsBrowsing(path: candidate, roots: usableRoots) ? candidate : nil } - guard let path = selectedInitialPath ?? usableRoots.first else { return } + let fallback = defaultPath.flatMap { + RemoteDirectoryPath.allowsBrowsing(path: $0, roots: usableRoots) ? $0 : nil + } + guard let path = selectedInitialPath ?? fallback ?? usableRoots.first else { return } self.machineId = machineId self.isPresented = true self.path = path @@ -187,7 +229,7 @@ public final class RemoteDirectoryBrowserModel { public func navigate(to path: String) { guard isPresented, - roots.contains(where: { RemoteDirectoryPath.isWithinRoot(path: path, root: $0) }) + RemoteDirectoryPath.allowsBrowsing(path: path, roots: roots) else { return } @@ -200,7 +242,7 @@ public final class RemoteDirectoryBrowserModel { public func navigateUp() { guard let parent = RemoteDirectoryPath.parent(path), - roots.contains(where: { RemoteDirectoryPath.isWithinRoot(path: parent, root: $0) }) + RemoteDirectoryPath.allowsBrowsing(path: parent, roots: roots) else { return } @@ -220,7 +262,7 @@ public final class RemoteDirectoryBrowserModel { private func load(_ path: String) { guard let machineId, isPresented, - roots.contains(where: { RemoteDirectoryPath.isWithinRoot(path: path, root: $0) }) + RemoteDirectoryPath.allowsBrowsing(path: path, roots: roots) else { return } @@ -235,7 +277,7 @@ public final class RemoteDirectoryBrowserModel { error = nil breadcrumbs = makeBreadcrumbs(path: path, roots: browseRoots) canGoUp = RemoteDirectoryPath.parent(path).map { parent in - browseRoots.contains { RemoteDirectoryPath.isWithinRoot(path: parent, root: $0) } + RemoteDirectoryPath.allowsBrowsing(path: parent, roots: browseRoots) } ?? false loadTask = Task { [weak self] in @@ -298,7 +340,8 @@ public final class RemoteDirectoryBrowserModel { } private func makeBreadcrumbs(path: String, roots: [String]) -> [RemoteDirectoryBreadcrumb] { - guard let root = roots + let breadcrumbRoots = roots.isEmpty ? [RemoteDirectoryPath.filesystemRoot(path)].compactMap { $0 } : roots + guard let root = breadcrumbRoots .filter({ RemoteDirectoryPath.isWithinRoot(path: path, root: $0) }) .max(by: { $0.count < $1.count }) else { 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/HapiClient/NewSession/NewSessionDirectoryModel.swift b/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionDirectoryModel.swift new file mode 100644 index 00000000..5b35238b --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionDirectoryModel.swift @@ -0,0 +1,189 @@ +import Foundation +import HapiProtocol +import Observation + +public protocol NewSessionDirectoryRequesting: MachineDirectoryRequesting { + func machinePathsExist(machineId: String, paths: [String]) async throws -> MachinePathsExistsResponse +} + +extension APIClient: NewSessionDirectoryRequesting {} + +public enum DirectoryLookupState: Equatable, Sendable { + case idle + case loading + case loaded + case outsideRoots + case failed(String) +} + +/// Directory queries for the create form. Listing and existence checks run +/// independently, so a slow/failed listing cannot hide the path's validation. +/// Every response belongs to one machine and input revision. +@MainActor @Observable +public final class NewSessionDirectoryModel { + public private(set) var suggestions: [String] = [] + public private(set) var lookupState: DirectoryLookupState = .idle + public private(set) var exists: Bool? + public private(set) var outsideWorkspaceRoots = false + public private(set) var isCheckingExistence = false + public private(set) var existenceError: String? + + private struct Input: Equatable { + let machineId: String? + let path: String + let roots: [String] + let showSuggestions: Bool + } + + private struct ListingKey: Equatable { + let machineId: String + let parent: String + let includeHidden: Bool + } + + @ObservationIgnored private let requester: any NewSessionDirectoryRequesting + @ObservationIgnored private let debounce: Duration + @ObservationIgnored private let lookupError: String + @ObservationIgnored private let checkError: String + @ObservationIgnored private var input: Input? + @ObservationIgnored private var requestVersion = 0 + @ObservationIgnored private var listingTask: Task? + @ObservationIgnored private var existenceTask: Task? + @ObservationIgnored private var cachedListing: (key: ListingKey, entries: [MachineDirectoryEntry])? + + public init( + requester: any NewSessionDirectoryRequesting, + debounce: Duration = .milliseconds(250), + lookupError: String = "Failed to browse directories", + checkError: String = "Failed to check directory" + ) { + self.requester = requester + self.debounce = debounce + self.lookupError = lookupError + self.checkError = checkError + } + + public func update(machine: Machine?, path: String, showSuggestions: Bool) { + schedule(Input( + machineId: machine?.id, + path: RemoteDirectoryPath.expandHome(path, homeDirectory: machine?.metadata?.homeDir), + roots: machine.map(RemoteDirectoryPath.browseRoots) ?? [], + showSuggestions: showSuggestions + )) + } + + public func retry() { + guard let input else { return } + cachedListing = nil + schedule(input, force: true) + } + + public func stop() { + listingTask?.cancel() + existenceTask?.cancel() + requestVersion += 1 + input = nil + suggestions = [] + lookupState = .idle + isCheckingExistence = false + exists = nil + outsideWorkspaceRoots = false + existenceError = nil + } + + /// The Create action's authoritative recheck supersedes the background probe. + public func acceptExistence( + _ result: MachinePathsExistsResponse, + machineId: String, + path: String + ) { + guard input?.machineId == machineId, input?.path == path else { return } + existenceTask?.cancel() + applyExistence(result, path: path) + } + + private func applyExistence(_ result: MachinePathsExistsResponse, path: String) { + exists = result.exists[path] + outsideWorkspaceRoots = result.outsideWorkspaceRoots?.contains(path) == true + isCheckingExistence = false + existenceError = nil + } + + private func schedule(_ next: Input, force: Bool = false) { + guard force || input != next else { return } + if input?.machineId != next.machineId || input?.roots != next.roots { + cachedListing = nil + } + stop() + input = next + let version = requestVersion + guard let machineId = next.machineId else { return } + + if !next.path.isEmpty { + isCheckingExistence = true + existenceTask = Task { [weak self, requester, debounce] in + do { + try await Task.sleep(for: debounce) + try Task.checkCancellation() + let result = try await requester.machinePathsExist(machineId: machineId, paths: [next.path]) + guard let self, self.isCurrent(version) else { return } + self.applyExistence(result, path: next.path) + } catch { + guard let self, self.isCurrent(version) else { return } + self.isCheckingExistence = false + self.existenceError = (error as? LocalizedError)?.errorDescription ?? self.checkError + } + } + } + + guard next.showSuggestions else { return } + switch NewSessionLogic.directoryAutocompleteQuery(path: next.path, roots: next.roots) { + case .none: + return + case .roots(let paths): + suggestions = paths + lookupState = .loaded + case .outsideRoots: + lookupState = .outsideRoots + case .directory(let query): + let key = ListingKey(machineId: machineId, parent: query.parent, includeHidden: query.includeHidden) + if let cachedListing, cachedListing.key == key { + applyListing(cachedListing.entries, query: query, path: next.path) + return + } + lookupState = .loading + listingTask = Task { [weak self, requester, debounce] in + do { + try await Task.sleep(for: debounce) + try Task.checkCancellation() + let response = try await requester.listMachineDirectory( + machineId: machineId, + path: query.parent, + includeHidden: query.includeHidden + ) + guard let self, self.isCurrent(version) else { return } + guard response.success else { + self.lookupState = .failed(response.error ?? self.lookupError) + return + } + let entries = response.entries ?? [] + self.cachedListing = (key, entries) + self.applyListing(entries, query: query, path: next.path) + } catch { + guard let self, self.isCurrent(version) else { return } + self.lookupState = .failed((error as? LocalizedError)?.errorDescription ?? self.lookupError) + } + } + } + } + + private func applyListing(_ entries: [MachineDirectoryEntry], query: NewSessionLogic.ParentQuery, path: String) { + suggestions = NewSessionLogic.buildSuggestions(query: query, entries: entries) + .filter { $0 != path } + lookupState = .loaded + } + + private func isCurrent(_ version: Int) -> Bool { + !Task.isCancelled && requestVersion == version + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift b/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift index 7529aaf5..cdffc144 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift @@ -207,6 +207,8 @@ public enum NewSessionLogic { /// Separator used by the typed path; suggestions preserve it. public let separator: String + public var includeHidden: Bool { prefix.hasPrefix(".") } + public init(parent: String, prefix: String, separator: String = "/") { self.parent = parent self.prefix = prefix @@ -214,6 +216,34 @@ public enum NewSessionLogic { } } + public enum DirectoryAutocompleteQuery: Equatable, Sendable { + case none + case roots([String]) + case directory(ParentQuery) + case outsideRoots + } + + /// Complete known roots without listing their forbidden ancestors. Once + /// inside a root, use the normal parent listing. `path` is home-expanded. + public static func directoryAutocompleteQuery( + path: String, + roots: [String] + ) -> DirectoryAutocompleteQuery { + if path.isEmpty { return roots.isEmpty ? .none : .roots(Array(roots.prefix(8))) } + guard let query = parentQuery(for: path) else { return .none } + if roots.contains(where: { + RemoteDirectoryPath.isWithinRoot(path: path, root: $0) + && RemoteDirectoryPath.isWithinRoot(path: $0, root: path) + }) { + return .directory(ParentQuery(parent: path, prefix: "", separator: query.separator)) + } + if RemoteDirectoryPath.allowsBrowsing(path: query.parent, roots: roots) { + return .directory(query) + } + let matchingRoots = roots.filter { $0.lowercased().hasPrefix(path.lowercased()) } + return matchingRoots.isEmpty ? .outsideRoots : .roots(Array(matchingRoots.prefix(8))) + } + /// Derives the list-directory request from the typed text: list the /// parent of the path segment being typed. Only absolute paths /// autocomplete (the hub lists runner-local absolute paths). diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift index c92d587c..fbddf6ab 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift @@ -242,9 +242,12 @@ public actor MessageWindowController { if !canIncrement { let requestBaseline = baseline() + let latestPageSize = initial.requiresLatestReset || initialCursor != nil + ? MessageWindowConstants.pageSize + : MessageWindowConstants.initialPageSize let response = try await provider.messages( sessionId: sessionId, - query: .latest(limit: MessageWindowConstants.pageSize) + query: .latest(limit: latestPageSize) ) guard isCurrentTailSync(generation) else { return } // A replay gap may have hidden messages-invalidated. Keep a diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/ScratchlistStore.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/ScratchlistStore.swift index 1eb7ea62..23a3720d 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Stores/ScratchlistStore.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/ScratchlistStore.swift @@ -11,6 +11,8 @@ public struct ScratchlistSessionState: Equatable, Sendable { public var isRefreshing = false /// No successful fetch yet and the last attempt failed → error state. public var loadFailed = false + /// A refresh failed; cached rows remain usable. + public var refreshFailed = false /// The session sits at the 200-entry cap (local count, or the hub's 409 /// `scratchlist_at_cap` verdict) — disable the add affordances. public var atCap = false @@ -46,6 +48,7 @@ public enum ScratchlistAttachmentDeleteResult: Sendable { public enum ScratchlistStoreError: Error, Equatable { /// A create with neither text nor attachments (the hub would 400 it). case emptyEntry + case textTooLong } /// The scratchlist surface UI layers depend on (``ScratchlistStore`` is the @@ -70,7 +73,8 @@ public protocol SessionScratchlistStoring: AnyObject { func createEntry( sessionId: String, text: String, - attachments: [ScratchlistAttachment] + attachments: [ScratchlistAttachment], + entryId: String? ) async -> ScratchlistCreateResult /// Optimistic update (nil = keep; `attachments = []` clears). Returns @@ -100,6 +104,9 @@ public protocol SessionScratchlistStoring: AnyObject { } extension SessionScratchlistStoring { + public func createEntry(sessionId: String, text: String, attachments: [ScratchlistAttachment]) async -> ScratchlistCreateResult { + await createEntry(sessionId: sessionId, text: text, attachments: attachments, entryId: nil) + } /// Text-only create convenience (protocol requirements cannot default arguments). public func createEntry(sessionId: String, text: String) async -> ScratchlistCreateResult { await createEntry(sessionId: sessionId, text: text, attachments: []) @@ -124,8 +131,7 @@ extension SessionScratchlistStoring { /// ``ScratchlistSessionState/atCap`` flag (recomputed from entry count on /// every entries change). /// -/// Text is trimmed and truncated to ``ScratchlistCaps/maxTextLength`` (web -/// truncates rather than rejects). Entries are memory-only: the hub is the +/// Overlong text is rejected, never silently truncated. Entries are memory-only: the hub is the /// durable store and every open refetches. @MainActor @Observable public final class ScratchlistStore: SessionScratchlistStoring { @@ -227,6 +233,7 @@ public final class ScratchlistStore: SessionScratchlistStoring { update(sessionId) { state in state.isRefreshing = false state.loadFailed = !state.loaded + state.refreshFailed = true } throw error } @@ -242,6 +249,7 @@ public final class ScratchlistStore: SessionScratchlistStoring { state.loaded = true state.isRefreshing = false state.loadFailed = false + state.refreshFailed = false } } @@ -255,27 +263,31 @@ public final class ScratchlistStore: SessionScratchlistStoring { public func createEntry( sessionId: String, text: String, - attachments: [ScratchlistAttachment] + attachments: [ScratchlistAttachment], + entryId: String? = nil ) async -> ScratchlistCreateResult { - let trimmed = Self.clampText(text) + guard text.utf16.count <= ScratchlistCaps.maxTextLength else { return .failed(ScratchlistStoreError.textTooLong) } + let trimmed = Self.trimText(text) if trimmed.isEmpty && attachments.isEmpty { return .failed(ScratchlistStoreError.emptyEntry) } - if state(sessionId).entries.count >= ScratchlistCaps.maxEntries { + // An explicit id may be a retry of an accepted POST with a lost reply. + // Let the hub apply its idempotency check, even when the local list is full. + if entryId == nil, state(sessionId).entries.count >= ScratchlistCaps.maxEntries { update(sessionId) { $0.atCap = true } return .atCap } let stamp = now() let optimistic = ScratchlistEntry( - entryId: makeEntryId(), + entryId: entryId ?? makeEntryId(), text: trimmed, createdAt: stamp, updatedAt: stamp, attachments: attachments ) pendingCreates.insert(optimistic.entryId) - setEntries(sessionId, [optimistic] + state(sessionId).entries) + setEntries(sessionId, [optimistic] + state(sessionId).entries.filter { $0.entryId != optimistic.entryId }) do { let response = try await api.createScratchlistEntry( @@ -323,7 +335,8 @@ public final class ScratchlistStore: SessionScratchlistStoring { text: String?, attachments: [ScratchlistAttachment]? ) async -> Bool { - let trimmed = text.map(Self.clampText) + if let text, text.utf16.count > ScratchlistCaps.maxTextLength { return false } + let trimmed = text.map(Self.trimText) if trimmed == nil && attachments == nil { return false } let previous = state(sessionId).entries.first { $0.entryId == entryId } if var optimistic = previous { @@ -470,20 +483,7 @@ public final class ScratchlistStore: SessionScratchlistStoring { states[sessionId] = state } - /// Trim, then truncate to the hub's UTF-16 length cap without splitting a - /// grapheme (the web slices JS strings, which count UTF-16 units). Pure — - /// `nonisolated` so it can be passed as an `Optional.map` transform. - nonisolated static func clampText(_ text: String) -> String { - let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) - guard trimmed.utf16.count > ScratchlistCaps.maxTextLength else { return trimmed } - var used = 0 - var end = trimmed.startIndex - for index in trimmed.indices { - let next = trimmed.index(after: index) - used += trimmed[index...index].utf16.count - if used > ScratchlistCaps.maxTextLength { break } - end = next - } - return String(trimmed[.. String { + text.trimmingCharacters(in: .whitespacesAndNewlines) } } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionListStore.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionListStore.swift index 33938319..ebe3b7f2 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionListStore.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionListStore.swift @@ -84,6 +84,11 @@ public final class SessionListStore: SessionListStoring { /// for the Android `SessionStore.scratchlistInvalidations` flow). @ObservationIgnored public var onScratchlistInvalidation: (@MainActor (String) -> Void)? + /// Authoritative removal only: SSE from either pipe, or a successful + /// archive. Optimistic list removal/rollback, filters and failed refreshes + /// must not dismiss a client's currently selected session. + @ObservationIgnored public var onSessionRemoved: (@MainActor (String) -> Void)? + @ObservationIgnored private let api: APIClient @ObservationIgnored private let snapshot: DiskCache<[SessionSummary]>? @ObservationIgnored private let refreshBatch: Duration @@ -189,6 +194,7 @@ public final class SessionListStore: SessionListStoring { if next.count != sessions.count { setSessions(next) } + onSessionRemoved?(sessionId) case .sessionEnded: // The reference has no session-ended cache branch: the state // change always arrives through the session-updated flow too. @@ -228,6 +234,7 @@ public final class SessionListStore: SessionListStoring { } do { try await api.archiveSession(id: sessionId) + onSessionRemoved?(sessionId) } catch { if let removed, !sessions.contains(where: { $0.id == sessionId }) { setSessions(sortSessionSummaries(sessions + [removed])) 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/Sources/HapiProtocol/Models/ScratchlistApi.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ScratchlistApi.swift index 548432a2..3b4852ec 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ScratchlistApi.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ScratchlistApi.swift @@ -16,9 +16,9 @@ public enum ScratchlistCaps { /// `SCRATCHLIST_MAX_ENTRIES` — POST past it → 409 `scratchlist_at_cap`. public static let maxEntries = 200 - /// `SCRATCHLIST_MAX_TEXT_LENGTH` — clients truncate (web behavior); the - /// hub 400s anything longer. The hub counts JS string length (UTF-16 - /// units), so clients must clamp on that measure, not Characters. + /// `SCRATCHLIST_MAX_TEXT_LENGTH` — web truncates; iOS rejects overlong + /// drafts without discarding text. The hub 400s anything longer. The hub counts JS string length (UTF-16 + /// units), so clients must validate that measure, not Characters. public static let maxTextLength = 10_000 } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowState.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowState.swift index 93dd9926..b3148d8b 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowState.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowState.swift @@ -19,8 +19,10 @@ public enum MessageWindowConstants { /// Separate trim bucket for codex `agent-run-*` rows so background-agent /// traces don't evict chat. public static let agentRunWindowSize = 800 - /// Request size for every page fetch. + /// Request size for ordinary latest/reset, forward, and older-page fetches. public static let pageSize = 200 + /// Request size for a genuinely cold latest page, prioritizing first paint. + public static let initialPageSize = 20 } public enum MessageViewMode: String, Sendable { diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorScratchlistTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorScratchlistTests.swift index 59fa3b16..da4e9243 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorScratchlistTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorScratchlistTests.swift @@ -18,6 +18,9 @@ private final class FakeScratchlist: SessionScratchlistStoring { /// When true, `createEntry` parks on a gate until `resumeCreates()`. var holdCreates = false private(set) var createCalls: [(sessionId: String, text: String, attachments: [ScratchlistAttachment])] = [] + private(set) var createIds: [String?] = [] + var deleteResult = true + private(set) var deleteCalls: [(String, String)] = [] private var gates: [CheckedContinuation] = [] func state(_ sessionId: String) -> ScratchlistSessionState { @@ -33,9 +36,11 @@ private final class FakeScratchlist: SessionScratchlistStoring { func createEntry( sessionId: String, text: String, - attachments: [ScratchlistAttachment] + attachments: [ScratchlistAttachment], + entryId: String? ) async -> ScratchlistCreateResult { createCalls.append((sessionId, text, attachments)) + createIds.append(entryId) if holdCreates { await withCheckedContinuation { gates.append($0) } } @@ -58,7 +63,8 @@ private final class FakeScratchlist: SessionScratchlistStoring { } func deleteEntry(sessionId: String, entryId: String) async -> Bool { - true + deleteCalls.append((sessionId, entryId)) + return deleteResult } func uploadAttachment( @@ -85,10 +91,12 @@ private final class FakeScratchlist: SessionScratchlistStoring { private final class ScratchlistSeamHarness { let scratchlist: FakeScratchlist let interactor: ChatInteractor + let performer: RoutingPerformer private(set) var events: [ChatInteractionEvent] = [] init(withStore: Bool = true) throws { - let api = try makeStoreAPIClient(performer: RoutingPerformer()) + performer = RoutingPerformer() + let api = try makeStoreAPIClient(performer: performer) scratchlist = FakeScratchlist() interactor = ChatInteractor( sessionId: "sess-1", @@ -243,3 +251,148 @@ struct ChatInteractorScratchlistTests { #expect(bare.interactor.scratchlistCount == 0) } } + +@Suite("Scratchlist composer workflow") +@MainActor +struct ScratchlistComposerWorkflowTests { + private var attachment: ScratchlistAttachment { + ScratchlistAttachment(id: "photo-1", filename: "screen.png", mimeType: "image/png", size: 4, + path: "hapi-hub:scratchlist/default/sess-1/photo-1.png") + } + private func entry(_ text: String = "Next task", attachments: [ScratchlistAttachment] = []) -> ScratchlistEntry { + ScratchlistEntry(entryId: "e1", text: text, createdAt: 1, updatedAt: 2, attachments: attachments) + } + + @Test func modeRoutesSubmitToParkAndStaysReadyForAnotherDraft() async throws { + let h = try ScratchlistSeamHarness() + h.scratchlist.createResult = .created(entry()) + h.interactor.setComposerText("Next task") + h.interactor.setComposerDestination(.scratchlist) + h.interactor.sendMessage(steer: true) + try await expectEventually { !h.interactor.scratchlistBusy } + #expect(h.interactor.composerText.isEmpty) + #expect(h.interactor.composerDestination == .scratchlist) + #expect(h.scratchlist.createCalls.count == 1) + #expect(await h.performer.requests.isEmpty) + } + + @Test func returningToChatKeepsDraftAndDoesNotSend() throws { + let h = try ScratchlistSeamHarness() + h.interactor.setComposerText("not ready") + h.interactor.setComposerDestination(.scratchlist) + h.interactor.setComposerDestination(.chat) + #expect(h.interactor.composerText == "not ready") + #expect(h.scratchlist.createCalls.isEmpty) + } + + @Test func attachmentOnlyRestoreIsLocalBorrowedAndExitsMode() async throws { + let h = try ScratchlistSeamHarness() + h.interactor.setComposerDestination(.scratchlist) + #expect(await h.interactor.restoreScratchlistEntry(entry("", attachments: [attachment]))) + #expect(h.interactor.composerDestination == .chat) + #expect(h.interactor.composerFocusRequest == 1) + #expect(h.interactor.attachments.items.count == 1) + #expect(h.interactor.attachments.allReady) + h.interactor.attachments.remove(h.interactor.attachments.items[0].id) + try await Task.sleep(for: .milliseconds(20)) + #expect(await h.performer.requests.isEmpty, "Borrowed attachments must not be uploaded, resumed, or deleted") + } + + @Test func appendKeepsCurrentTextAndAttachmentsAndDeduplicatesBorrowedFiles() async throws { + let h = try ScratchlistSeamHarness() + h.interactor.setComposerText("Existing") + h.interactor.attachments.restoreScratchlist([attachment]) + #expect(await h.interactor.restoreScratchlistEntry(entry(attachments: [attachment]), choice: .append)) + #expect(h.interactor.composerText == "Existing\nNext task") + #expect(h.interactor.attachments.items.count == 1) + } + + @Test func parkThenTakeIsAtomicOnFailureAndCopiesAttachmentsOnSuccess() async throws { + let h = try ScratchlistSeamHarness() + h.interactor.setComposerText("Existing") + h.interactor.attachments.restoreScratchlist([attachment]) + #expect(!(await h.interactor.restoreScratchlistEntry(entry(), choice: .parkCurrent))) + #expect(h.interactor.composerText == "Existing") + #expect(h.interactor.attachments.items.count == 1) + h.scratchlist.createResult = .created(entry("Existing", attachments: [attachment])) + #expect(await h.interactor.restoreScratchlistEntry(entry(), choice: .parkCurrent)) + #expect(h.scratchlist.createCalls.last?.attachments == [attachment]) + #expect(h.interactor.composerText == "Next task") + #expect(h.interactor.attachments.items.isEmpty) + #expect(h.scratchlist.createIds[0] == h.scratchlist.createIds[1]) + } + + @Test func duplicateParkClicksSubmitOnceAndProtectMidflightChanges() async throws { + let h = try ScratchlistSeamHarness() + h.scratchlist.holdCreates = true + h.scratchlist.createResult = .created(entry()) + h.interactor.setComposerText("Next task") + h.interactor.parkComposerDraft() + h.interactor.parkComposerDraft() + try await expectEventually { h.scratchlist.createCalls.count == 1 } + h.interactor.setComposerText("Still typing") + h.scratchlist.resumeCreates() + try await expectEventually { !h.interactor.scratchlistBusy } + #expect(h.interactor.composerText == "Still typing") + #expect(h.scratchlist.createCalls.count == 1) + } + + @Test func overlongAndUnsupportedDraftsNeverSendOrTruncate() async throws { + let h = try ScratchlistSeamHarness() + let long = String(repeating: "😀", count: 5_001) + h.interactor.setComposerText(long) + h.interactor.parkComposerDraft() + try await expectEventually { !h.interactor.scratchlistBusy } + #expect(h.interactor.composerText == long) + #expect(h.scratchlist.createCalls.isEmpty) + var video = attachment + video.mimeType = "video/mp4" + h.interactor.setComposerText("") + h.interactor.attachments.restoreScratchlist([video]) + h.interactor.setComposerDestination(.scratchlist) + h.interactor.sendMessage() + try await expectEventually { !h.interactor.scratchlistBusy } + #expect(h.interactor.scratchlistError != nil) + #expect(h.interactor.attachments.items.count == 1) + #expect(h.scratchlist.createCalls.isEmpty) + #expect(await h.performer.requests.isEmpty) + } + + @Test func directQueueDoesNotConsumeComposerAndRemovalRetryDoesNotSendAgain() async throws { + let h = try ScratchlistSeamHarness() + await h.performer.setRoutes([(pathPrefix: "/api/sessions/sess-1/messages", json: "{}")]) + h.interactor.setComposerText("Unrelated input") + h.scratchlist.deleteResult = false + #expect(!(await h.interactor.queueScratchlistEntry(entry()))) + #expect(h.interactor.composerText == "Unrelated input") + #expect(h.interactor.queuedScratchlistEntries.contains("e1")) + let before = await h.performer.requests.filter { $0.httpMethod == "POST" } + #expect(before.count == 1) + let body = try #require(before.first?.httpBody) + let json = try #require(JSONSerialization.jsonObject(with: body) as? [String: Any]) + #expect(json["deliveryMode"] as? String == "queue") + #expect(json["text"] as? String == "Next task") + h.scratchlist.deleteResult = true + #expect(await h.interactor.queueScratchlistEntry(entry())) + #expect(await h.performer.requests.filter { $0.httpMethod == "POST" }.count == 1) + #expect(h.scratchlist.deleteCalls.count == 2) + #expect(h.interactor.queuedScratchlistEntries.isEmpty) + } + + @Test func failedQueueKeepsEntryAndRetriesWithTheSameLocalId() async throws { + let h = try ScratchlistSeamHarness() + #expect(!(await h.interactor.queueScratchlistEntry(entry()))) + #expect(h.scratchlist.deleteCalls.isEmpty) + await h.performer.setRoutes([(pathPrefix: "/api/sessions/sess-1/messages", json: "{}")]) + #expect(await h.interactor.queueScratchlistEntry(entry())) + let posts = await h.performer.requests.filter { $0.httpMethod == "POST" } + #expect(posts.count == 2) + let ids = try posts.map { + let data = try #require($0.httpBody) + let json = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + return json["localId"] as? String + } + #expect(ids[0] == ids[1]) + #expect(h.scratchlist.deleteCalls.count == 1) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift index 2ae4746a..1800e0eb 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift @@ -809,6 +809,75 @@ struct ChatInteractorTests { // MARK: Config + @Test func collaborationModeSwitchesIndependentlyOfPermissionsAndSerializesChanges() async throws { + let harness = try await ChatInteractionHarness(detail: chatDetail(flavor: "codex"), activate: false) + let interactor = harness.interactor + #expect(interactor.config.collaborationMode == nil) + #expect(interactor.config.canChangeCollaborationMode) + interactor.setCollaborationMode(.default) + #expect(await harness.performer.count("POST", pathSuffix: "/collaboration-mode") == 0) + await harness.performer.gate("POST", pathSuffix: "/collaboration-mode") + defer { Task { await harness.performer.openGates() } } + interactor.setCollaborationMode(.plan) + #expect(interactor.config.collaborationMode == .plan) + #expect(interactor.config.permissionMode == .default) + #expect(interactor.configOpPending) + interactor.setCollaborationMode(.default) + interactor.setModel("other") + #expect(await eventually { await harness.performer.count("POST", pathSuffix: "/collaboration-mode") == 1 }) + #expect(await harness.performer.count("POST", pathSuffix: "/model") == 0) + await harness.performer.openGates() + #expect(await eventually { !interactor.configOpPending }) + interactor.setCollaborationMode(.plan) + interactor.setCollaborationMode(.default) + #expect(await eventually { !interactor.configOpPending }) + #expect(await harness.performer.bodies("POST", pathSuffix: "/collaboration-mode") == [#"{"mode":"plan"}"#, #"{"mode":"default"}"#]) + #expect(interactor.config.permissionMode == .default) + + harness.store.applySessionEvent(.sessionUpdated(namespace: nil, sessionId: chatSessionID, data: .patch(SessionPatch(collaborationMode: .plan)))) + #expect(interactor.config.collaborationMode == .plan) + #expect(await harness.performer.count("POST", pathSuffix: "/collaboration-mode") == 2) + } + + @Test func collaborationModeRejectsUnavailableSessionsButAllowsConcurrentTerminals() async throws { + let harness = try await ChatInteractionHarness(detail: chatDetail(flavor: "claude"), activate: false) + let interactor = harness.interactor + #expect(!interactor.config.canChangeCollaborationMode) + interactor.setCollaborationMode(.plan) + harness.store.updateDetailLocal(chatSessionID) { + $0.metadata?.flavor = "codex" + $0.active = false + } + #expect(!interactor.config.canChangeCollaborationMode) + interactor.setCollaborationMode(.plan) + harness.store.updateDetailLocal(chatSessionID) { + $0.active = true + $0.agentState = AgentState(controlledByUser: true) + } + #expect(!interactor.config.canChangeCollaborationMode) + interactor.setCollaborationMode(.plan) + #expect(await harness.performer.count("POST", pathSuffix: "/collaboration-mode") == 0) + harness.store.updateDetailLocal(chatSessionID) { + $0.metadata?.capabilities = SessionCapabilities(concurrentClients: true) + } + #expect(interactor.config.canChangeCollaborationMode) + interactor.setCollaborationMode(.plan) + #expect(await eventually { !interactor.configOpPending }) + #expect(await harness.performer.count("POST", pathSuffix: "/collaboration-mode") == 1) + harness.store.releaseDetail(chatSessionID) + #expect(!interactor.config.canChangeCollaborationMode) + } + + @Test func rejectedCollaborationModeReloadsServerTruthAndReportsFailure() async throws { + let harness = try await ChatInteractionHarness(detail: chatDetail(flavor: "codex"), activate: false) + await harness.performer.script("POST", "/api/sessions/sess-1/collaboration-mode", status: 409, json: #"{"error":"Config rejected"}"#) + harness.interactor.setCollaborationMode(.plan) + #expect(harness.interactor.config.collaborationMode == .plan) + #expect(await eventually { !harness.interactor.configOpPending }) + #expect(harness.interactor.config.collaborationMode == nil) + #expect(harness.events.contains { if case .notice = $0 { return true }; return false }) + } + @Test func permissionModeSwitchAppliesOptimisticallyAndRollsBackToServerTruthOnError() async throws { let harness = try await ChatInteractionHarness(detail: chatDetail(permissionMode: .default)) await harness.performer.script( @@ -896,6 +965,120 @@ 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 continuePlanningDismissesActionsAndPreservesDraftAndMode() 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) + #expect(!harness.interactor.codexPlanActions(planId: "plan-1").isVisible) + harness.interactor.continueCodexPlan(planId: "plan-1") + harness.interactor.implementCodexPlan(planId: "plan-1") + #expect(harness.interactor.composerFocusRequest == 1) + harness.store.updateDetailLocal(chatSessionID) { $0 = planSession() } + #expect(!harness.interactor.codexPlanActions(planId: "plan-1").isVisible) + harness.store.updateDetailLocal(chatSessionID) { + $0.agentState?.codexPlanProposalId = "plan-2" + } + #expect(harness.interactor.codexPlanActions(planId: "plan-2").canAct) + } + + @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/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/Packages/HapiKit/Tests/HapiClientTests/Chat/ScratchlistAttachmentFlowTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ScratchlistAttachmentFlowTests.swift new file mode 100644 index 00000000..4b534809 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ScratchlistAttachmentFlowTests.swift @@ -0,0 +1,171 @@ +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif +import HapiProtocol +import Testing +@testable import HapiClient + +private actor ScratchlistFlowHTTP: HTTPPerforming { + private(set) var requests: [URLRequest] = [] + var failUploadNumber: Int? + var failParkNumber: Int? + private var uploads = 0 + private var parks = 0 + private var resumes = 0 + private var expireAfterUpload = false + + func failChatUpload(_ number: Int) { failUploadNumber = number } + func failParkUpload(_ number: Int) { failParkNumber = number } + func expireStagedSession() { expireAfterUpload = true } + + func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + requests.append(request) + let path = request.url!.path + var status = 200 + let response: String + if path.hasSuffix("/scratchlist/upload") { + parks += 1 + if parks == failParkNumber { status = 500; response = "{}" } + else { + let attachment = ScratchlistAttachment(id: "park-\(parks)", filename: "photo.png", mimeType: "image/png", size: 4, + path: "hapi-hub:scratchlist/default/sess-1/park-\(parks).png") + response = try encodeJSON(ScratchlistUploadResponse(success: true, attachment: attachment)) + } + } else if path.hasSuffix("/upload") { + uploads += 1 + if uploads == failUploadNumber { status = 500; response = "{}" } + else { response = "{\"success\":true,\"path\":\"/tmp/chat-\(uploads).png\"}" } + } else if path.hasSuffix("/file") { + response = try encodeJSON(FileReadResponse(success: true, content: Data("test".utf8).base64EncodedString())) + } else if path.hasSuffix("/resume") { + resumes += 1 + response = resumes == 1 ? "{\"sessionId\":\"resumed\"}" : "{\"sessionId\":\"resumed-again\"}" + } + else if path.hasSuffix("/messages"), request.httpMethod == "POST", expireAfterUpload { + expireAfterUpload = false + status = 409 + response = "{\"error\":\"inactive\",\"code\":\"session_inactive\"}" + } + else if path.contains("/scratchlist/attachments/") { response = "test" } + else if path.hasSuffix("/messages"), request.httpMethod == "GET" { response = "{\"messages\":[],\"hasMore\":false}" } + else { response = "{}" } + return (Data(response.utf8), HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, + headerFields: ["Content-Type": "application/json"])!) + } +} + +@Suite("Scratchlist attachment ownership and transfer") +@MainActor +struct ScratchlistAttachmentFlowTests { + private func photo(_ id: String) -> ScratchlistAttachment { + ScratchlistAttachment(id: id, filename: "\(id).png", mimeType: "image/png", size: 4, path: "hapi-hub:scratchlist/default/sess-1/\(id).png") + } + private func pick(_ id: String) -> PreparedAttachment { + PreparedAttachment(id: id, filename: "photo.png", mimeType: "image/png", bytes: Data("test".utf8)) + } + + @Test func scratchlistPicksUploadToHubAndOnlyUnsavedOwnedFilesAreDeleted() async throws { + let http = ScratchlistFlowHTTP() + let api = try makeStoreAPIClient(performer: http) + let tray = ComposerAttachments(api: api, sessionId: "sess-1") + tray.add(pick("first"), toScratchlist: true) + try await expectEventually { tray.allReady } + let snapshot = tray.snapshot + guard case .scratchlist(let saved) = snapshot[0].source else { Issue.record("Expected hub storage"); return } + tray.markScratchlistPersisted([saved]) + tray.discard(snapshot) + tray.restoreScratchlist([saved]) + tray.discardAllDetached() + try await Task.sleep(for: .milliseconds(30)) + #expect(await http.requests.count == 1, "Neither saved nor borrowed files are owned by the composer") + tray.add(pick("second"), toScratchlist: true) + try await expectEventually { tray.allReady } + tray.discardAllDetached() + try await Task.sleep(for: .milliseconds(30)) + #expect(await http.requests.contains { $0.httpMethod == "DELETE" && $0.url!.path.hasSuffix("/park-2") }) + } + + @Test func chatToScratchlistMigrationLeavesTheSourceUntilCommit() async throws { + let http = ScratchlistFlowHTTP() + let api = try makeStoreAPIClient(performer: http) + let store = ScratchlistStore(api: api) + let tray = ComposerAttachments(api: api, sessionId: "sess-1") + tray.add(pick("first")) + try await expectEventually { tray.allReady } + let snapshot = tray.snapshot + let prepared = try await ScratchlistTransfer.preparePark(api: api, store: store, sessionId: "sess-1", snapshot: snapshot) + #expect(prepared.attachments.count == 1) + #expect(tray.snapshot == snapshot) + #expect(await http.requests.contains { $0.url!.path.hasSuffix("/file") }) + #expect(!(await http.requests.contains { $0.url!.path.hasSuffix("/upload/delete") })) + await ScratchlistTransfer.cleanupPark(store: store, sessionId: "sess-1", attachments: prepared.uploaded) + #expect(tray.snapshot == snapshot, "A rejected park leaves the original chat upload usable") + } + + @Test func partialParkFailureCleansOnlyNewHubCopies() async throws { + let http = ScratchlistFlowHTTP() + await http.failParkUpload(2) + let api = try makeStoreAPIClient(performer: http) + let store = ScratchlistStore(api: api) + let tray = ComposerAttachments(api: api, sessionId: "sess-1") + tray.add(pick("first")); tray.add(pick("second")) + try await expectEventually { tray.allReady } + do { + _ = try await ScratchlistTransfer.preparePark(api: api, store: store, sessionId: "sess-1", snapshot: tray.snapshot) + Issue.record("The second upload must fail") + } catch {} + #expect(tray.items.count == 2) + #expect(tray.allReady) + #expect(await http.requests.contains { $0.httpMethod == "DELETE" && $0.url!.path.hasSuffix("/park-1") }) + #expect(!(await http.requests.contains { $0.url!.path.hasSuffix("/upload/delete") })) + } + + @Test func partialSendPreparationCleansChatCopiesWithoutDeletingSavedFiles() async throws { + let http = ScratchlistFlowHTTP() + await http.failChatUpload(2) + let api = try makeStoreAPIClient(performer: http) + let entry = ScratchlistEntry(entryId: "entry", text: "", createdAt: 1, updatedAt: 1, attachments: [photo("one"), photo("two")]) + do { + _ = try await ScratchlistTransfer.prepareSend(api: api, sourceSessionId: "sess-1", targetSessionId: "sess-1", + snapshot: ScratchlistTransfer.snapshot(entry)) + Issue.record("The second upload must fail") + } catch {} + #expect(await http.requests.contains { $0.url!.path.hasSuffix("/upload/delete") }) + #expect(!(await http.requests.contains { $0.httpMethod == "DELETE" })) + } + + @Test func queueResumesBeforeStagingAndCleansEntryInTheEffectiveSession() async throws { + let http = ScratchlistFlowHTTP() + let api = try makeStoreAPIClient(performer: http) + let interactor = ChatInteractor(sessionId: "sess-1", api: api, sessionStore: SessionListStore(api: api), windows: MessageWindowControllers(provider: api)) + interactor.scratchlist = ScratchlistStore(api: api) + interactor.setComposerText("Keep this input") + let entry = ScratchlistEntry(entryId: "entry", text: "", createdAt: 1, updatedAt: 1, attachments: [photo("one")]) + #expect(await interactor.queueScratchlistEntry(entry)) + #expect(interactor.composerText == "Keep this input") + let requests = await http.requests + let resume = try #require(requests.firstIndex { $0.url!.path.hasSuffix("/resume") }) + let fetch = try #require(requests.firstIndex { $0.url!.path == "/api/sessions/resumed/scratchlist/attachments/one" }) + #expect(resume < fetch) + #expect(requests.contains { $0.httpMethod == "POST" && $0.url!.path == "/api/sessions/resumed/messages" }) + #expect(requests.contains { $0.httpMethod == "DELETE" && $0.url!.path == "/api/sessions/resumed/scratchlist/entry" }) + let message = try #require(requests.first { $0.httpMethod == "POST" && $0.url!.path.hasSuffix("/messages") }) + let body = try #require(message.httpBody) + #expect(!String(decoding: body, as: UTF8.self).contains("hapi-hub:")) + } + + @Test func expiryDuringStagingResumesTheEffectiveSessionRatherThanTheDeletedOriginal() async throws { + let http = ScratchlistFlowHTTP() + await http.expireStagedSession() + let api = try makeStoreAPIClient(performer: http) + let interactor = ChatInteractor(sessionId: "sess-1", api: api, sessionStore: SessionListStore(api: api), windows: MessageWindowControllers(provider: api)) + interactor.scratchlist = ScratchlistStore(api: api) + let entry = ScratchlistEntry(entryId: "entry", text: "next", createdAt: 1, updatedAt: 1, attachments: [photo("one")]) + #expect(await interactor.queueScratchlistEntry(entry)) + let requests = await http.requests + #expect(requests.filter { $0.url!.path.hasSuffix("/resume") }.map { $0.url!.path } + == ["/api/sessions/sess-1/resume", "/api/sessions/resumed/resume"]) + #expect(requests.contains { $0.httpMethod == "DELETE" && $0.url!.path == "/api/sessions/resumed-again/scratchlist/entry" }) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/DirectoryBrowser/RemoteDirectoryBrowserModelTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/DirectoryBrowser/RemoteDirectoryBrowserModelTests.swift index 8924686c..69c9287f 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/DirectoryBrowser/RemoteDirectoryBrowserModelTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/DirectoryBrowser/RemoteDirectoryBrowserModelTests.swift @@ -49,6 +49,62 @@ private func directoryBrowserEventually( @Suite("RemoteDirectoryBrowserModel") @MainActor struct RemoteDirectoryBrowserModelTests { + @Test func defaultDirectoryIsIndependentOfBrowseBoundaries() { + var machine = Machine( + id: "m", namespace: "test", seq: 1, createdAt: 0, updatedAt: 0, + active: true, activeAt: 0, + metadata: MachineMetadata(host: "m", platform: "linux", happyCliVersion: "test", homeDir: "/home/dev"), + metadataVersion: 1, runnerStateVersion: 0 + ) + #expect(RemoteDirectoryPath.browseRoots(for: machine).isEmpty) + #expect(RemoteDirectoryPath.defaultDirectory(for: machine) == "/home/dev") + machine.metadata?.workspaceRoots = ["/data", "/work"] + #expect(RemoteDirectoryPath.browseRoots(for: machine) == ["/data", "/work"]) + #expect(RemoteDirectoryPath.defaultDirectory(for: machine) == "/data") + #expect(RemoteDirectoryPath.expandHome("~/repo", homeDirectory: "/remote/home") == "/remote/home/repo") + #expect(RemoteDirectoryPath.expandHome("~", homeDirectory: "/remote/home") == "/remote/home") + #expect(RemoteDirectoryPath.expandHome("~\\repo", homeDirectory: "D:\\Users\\dev") == "D:\\Users\\dev\\repo") + #expect(RemoteDirectoryPath.filesystemRoot("D:\\Users\\dev") == "D:\\") + #expect(RemoteDirectoryPath.filesystemRoot("\\\\server\\share\\repo") == "\\\\server\\share") + #expect(!RemoteDirectoryPath.allowsBrowsing(path: "relative/path", roots: [])) + } + + @Test func unrestrictedBrowserPreservesExternalInputAndNavigatesAboveHome() async { + let requester = FakeMachineDirectoryRequester() + let model = RemoteDirectoryBrowserModel(requester: requester) + model.open(machineId: "m", roots: [], initialPath: "/data/github/hapi", defaultPath: "/home/dev") + #expect(await directoryBrowserEventually { !model.isLoading }) + #expect(model.path == "/data/github/hapi") + #expect(model.breadcrumbs.map(\.path) == ["/", "/data", "/data/github", "/data/github/hapi"]) + model.navigate(to: "/home/dev") + model.navigateUp() + #expect(await directoryBrowserEventually { !model.isLoading }) + #expect(model.path == "/home") + model.navigate(to: "/") + #expect(await directoryBrowserEventually { !model.isLoading }) + #expect(!model.canGoUp) + model.open(machineId: "m", roots: [], initialPath: "", defaultPath: "/home/dev") + #expect(model.path == "/home/dev") + model.close() + } + + @Test func configuredRootsRemainBoundariesAndSupportSwitchingRoots() async { + let requester = FakeMachineDirectoryRequester() + let model = RemoteDirectoryBrowserModel(requester: requester) + model.open(machineId: "m", roots: ["/data", "/work"], initialPath: "/home/dev", defaultPath: "/home/dev") + #expect(await directoryBrowserEventually { !model.isLoading }) + #expect(model.path == "/data") + #expect(!model.canGoUp) + model.navigate(to: "/work/repo") + #expect(await directoryBrowserEventually { !model.isLoading }) + #expect(model.breadcrumbs.map(\.path) == ["/work", "/work/repo"]) + model.navigateUp() + #expect(await directoryBrowserEventually { !model.isLoading }) + #expect(model.path == "/work") + #expect(!model.canGoUp) + model.close() + } + @Test func pathBoundariesSupportPosixDriveAndUNCPaths() { #expect(RemoteDirectoryPath.isWithinRoot(path: "/workspace/repo", root: "/workspace")) #expect(!RemoteDirectoryPath.isWithinRoot(path: "/workspace-other/repo", root: "/workspace")) 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/HapiClientTests/MessageWindowControllerTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift index 0e4ef84f..2587b2ac 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift @@ -81,6 +81,69 @@ struct MessageWindowControllerTests { // MARK: - Tail sync + @Test func coldSyncRequestsTheInitialPageSize() async { + let provider = GatedMessagesProvider() + let controller = MessageWindowController(sessionId: "s", provider: provider) + + let sync = Task { await controller.syncTail() } + await provider.waitForRequests(1) + + let requests = await provider.requests + guard case .latest(let limit) = requests[0] else { + Issue.record("cold sync should request the latest page, got \(requests[0])") + return + } + #expect(limit == MessageWindowConstants.initialPageSize) + + await provider.release(latestPage([agentRow(id: "a-1", seq: 1, at: 1000)], epoch: 0)) + await sync.value + } + + @Test func resetAndCachedCursorSyncsKeepTheFullPageSize() async { + let provider = GatedMessagesProvider() + + var resetState = MessageWindowState(sessionId: "reset") + resetState.requiresLatestReset = true + let resetController = MessageWindowController( + sessionId: "reset", + provider: provider, + initialState: resetState + ) + let resetSync = Task { await resetController.syncTail() } + await provider.waitForRequests(1) + let resetRequests = await provider.requests + guard case .latest(let resetLimit) = resetRequests[0] else { + Issue.record("reset sync should request the latest page, got \(resetRequests[0])") + return + } + #expect(resetLimit == MessageWindowConstants.pageSize) + await provider.release(latestPage([agentRow(id: "reset-1", seq: 1, at: 1000)], epoch: 1)) + await resetSync.value + + var cachedState = MessageWindowState(sessionId: "cached") + cachedState.messages = [WindowMessage(wire: agentRow(id: "cached-1", seq: 1, at: 1000))] + cachedState.hasMore = true + cachedState.epoch = 1 + cachedState.oldestPosition = MessagePosition(at: 1000, seq: 1) + cachedState.newestPosition = MessagePosition(at: 1000, seq: 1) + cachedState.preferLatestOnActivation = true + let cachedController = MessageWindowController( + sessionId: "cached", + provider: provider, + initialState: cachedState + ) + let cachedSync = Task { await cachedController.syncTail() } + await provider.waitForRequests(2) + let cachedRequests = await provider.requests + guard case .latest(let cachedLimit) = cachedRequests[1] else { + Issue.record("cached re-entry should request the latest page, got \(cachedRequests[1])") + return + } + #expect(cachedLimit == MessageWindowConstants.pageSize) + await provider.release(latestPage([agentRow(id: "cached-2", seq: 2, at: 2000)], epoch: 1)) + await cachedSync.value + } + @Test func cancellingHistoryDoesNotPublishAnOfflineWarning() async { let provider = GatedMessagesProvider() var initial = MessageWindowState(sessionId: "history") diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionDirectoryModelTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionDirectoryModelTests.swift new file mode 100644 index 00000000..1a2d962b --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionDirectoryModelTests.swift @@ -0,0 +1,266 @@ +import Foundation +import HapiClient +import HapiProtocol +import Testing + +private struct ListingCall: Hashable, Sendable { + let machineId: String + let path: String + var includeHidden = false +} + +private struct ExistenceCall: Hashable, Sendable { + let machineId: String + let path: String +} + +private actor DirectoryRequester: NewSessionDirectoryRequesting { + private(set) var listings: [ListingCall] = [] + private(set) var checks: [ExistenceCall] = [] + private(set) var completedListings: [ListingCall] = [] + private(set) var completedChecks: [ExistenceCall] = [] + private var heldListings: Set = [] + private var heldChecks: Set = [] + private var listingWaiters: [ListingCall: CheckedContinuation] = [:] + private var checkWaiters: [ExistenceCall: CheckedContinuation] = [:] + private var listingFailure = false + private var checkFailure = false + private var outside: Set = [] + + func holdListing(_ call: ListingCall) { heldListings.insert(call) } + func holdCheck(_ call: ExistenceCall) { heldChecks.insert(call) } + func setFailures(listing: Bool, check: Bool = false) { + listingFailure = listing + checkFailure = check + } + func setOutside(_ call: ExistenceCall) { outside.insert(call) } + func releaseListing(_ call: ListingCall) { + heldListings.remove(call) + listingWaiters.removeValue(forKey: call)?.resume() + } + func releaseCheck(_ call: ExistenceCall) { + heldChecks.remove(call) + checkWaiters.removeValue(forKey: call)?.resume() + } + + func listMachineDirectory(machineId: String, path: String, includeHidden: Bool) async throws -> MachineListDirectoryResponse { + let call = ListingCall(machineId: machineId, path: path, includeHidden: includeHidden) + listings.append(call) + let failed = listingFailure + // Intentionally ignore cancellation to exercise late transport responses. + if heldListings.contains(call) { + await withCheckedContinuation { listingWaiters[call] = $0 } + } + completedListings.append(call) + return MachineListDirectoryResponse( + success: !failed, + entries: ["github", "gists", ".git", "other"] + .filter { includeHidden || !$0.hasPrefix(".") } + .map { MachineDirectoryEntry(name: $0, type: .directory) }, + error: failed ? "Listing failed" : nil + ) + } + + func machinePathsExist(machineId: String, paths: [String]) async throws -> MachinePathsExistsResponse { + let path = paths[0] + let call = ExistenceCall(machineId: machineId, path: path) + checks.append(call) + let denied = outside.contains(call) + let failed = checkFailure + if heldChecks.contains(call) { + await withCheckedContinuation { checkWaiters[call] = $0 } + } + completedChecks.append(call) + if failed { throw URLError(.timedOut) } + return MachinePathsExistsResponse(exists: [path: false], outsideWorkspaceRoots: denied ? [path] : nil) + } +} + +private func directoryMachine(_ id: String = "m1", roots: [String]? = nil, home: String = "/home/dev") -> Machine { + Machine( + id: id, namespace: "test", seq: 1, createdAt: 0, updatedAt: 0, + active: true, activeAt: 0, + metadata: MachineMetadata(host: id, platform: "linux", happyCliVersion: "test", homeDir: home, workspaceRoots: roots), + metadataVersion: 1, runnerStateVersion: 0 + ) +} + +@MainActor +private func directoryEventually(_ condition: @MainActor () async -> Bool) async -> Bool { + let clock = ContinuousClock() + let deadline = clock.now.advanced(by: .seconds(3)) + while clock.now < deadline { + if await condition() { return true } + try? await Task.sleep(for: .milliseconds(2)) + } + return await condition() +} + +@Suite("NewSessionDirectoryModel") +@MainActor +struct NewSessionDirectoryModelTests { + @Test func completesOutsideHomeAndRefiltersCacheWhileClearingOldSuggestionsImmediately() async { + let requester = DirectoryRequester() + let model = NewSessionDirectoryModel(requester: requester, debounce: .milliseconds(10)) + model.update(machine: directoryMachine(), path: "/data/gi", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + #expect(model.suggestions == ["/data/github", "/data/gists"]) + #expect(await requester.listings == [ListingCall(machineId: "m1", path: "/data")]) + model.update(machine: directoryMachine(), path: "/data/gith", showSuggestions: true) + #expect(model.suggestions == ["/data/github"]) + #expect(await requester.listings.count == 1) + model.update(machine: directoryMachine(), path: "/elsewhere/g", showSuggestions: true) + #expect(model.suggestions.isEmpty) + #expect(model.lookupState == .loading) + model.update(machine: directoryMachine(), path: "", showSuggestions: true) + #expect(model.lookupState == .idle) + #expect(model.exists == nil) + #expect(!model.isCheckingExistence) + model.stop() + } + + @Test func knownRootsCompleteWithoutListingTheirAncestors() async { + let requester = DirectoryRequester() + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + let machine = directoryMachine(roots: ["/data/github", "/work"]) + model.update(machine: machine, path: "/data/gi", showSuggestions: true) + #expect(model.suggestions == ["/data/github"]) + #expect(await requester.listings.isEmpty) + model.update(machine: machine, path: "/data/github", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + #expect(await requester.listings == [ListingCall(machineId: "m1", path: "/data/github")]) + model.update(machine: machine, path: "/unrelated/g", showSuggestions: true) + #expect(model.lookupState == .outsideRoots) + #expect(model.suggestions.isEmpty) + model.stop() + } + + @Test func dotPrefixUsesASeparateHiddenDirectoryCache() async { + let requester = DirectoryRequester() + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(), path: "/data/g", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + model.update(machine: directoryMachine(), path: "/data/.", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + #expect(model.suggestions == ["/data/.git"]) + #expect(await requester.listings.map(\.includeHidden) == [false, true]) + model.update(machine: directoryMachine(), path: "/data/.g", showSuggestions: true) + #expect(model.suggestions == ["/data/.git"]) + #expect(await requester.listings.count == 2) + model.stop() + } + + @Test func slowListingDoesNotBlockExistenceAndCannotReplaceNewInput() async { + let requester = DirectoryRequester() + let held = ListingCall(machineId: "m1", path: "/old") + await requester.holdListing(held) + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(), path: "/old/gi", showSuggestions: true) + #expect(await directoryEventually { await requester.listings.contains(held) && model.exists == false }) + #expect(model.lookupState == .loading) + model.update(machine: directoryMachine(), path: "/new/gith", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + await requester.releaseListing(held) + #expect(await directoryEventually { await requester.completedListings.contains(held) }) + #expect(model.suggestions == ["/new/github"]) + model.stop() + } + + @Test func machineSwitchRejectsOldExistenceAndListingResponses() async { + let requester = DirectoryRequester() + let oldListing = ListingCall(machineId: "m1", path: "/data") + let oldCheck = ExistenceCall(machineId: "m1", path: "/data/gi") + await requester.holdListing(oldListing) + await requester.holdCheck(oldCheck) + await requester.setOutside(ExistenceCall(machineId: "m2", path: "/data/gi")) + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(), path: "/data/gi", showSuggestions: true) + #expect(await directoryEventually { + let checks = await requester.checks + let listings = await requester.listings + return checks.contains(oldCheck) && listings.contains(oldListing) + }) + model.update(machine: directoryMachine("m2", roots: ["/work"]), path: "/data/gi", showSuggestions: true) + #expect(await directoryEventually { model.outsideWorkspaceRoots }) + await requester.releaseListing(oldListing) + await requester.releaseCheck(oldCheck) + #expect(await directoryEventually { + let checks = await requester.completedChecks + let listings = await requester.completedListings + return checks.contains(oldCheck) && listings.contains(oldListing) + }) + #expect(model.outsideWorkspaceRoots) + #expect(model.lookupState == .outsideRoots) + #expect(model.suggestions.isEmpty) + model.stop() + } + + @Test func listingFailureAndMissingPathAreIndependentAndRetryRefreshesBoth() async { + let requester = DirectoryRequester() + await requester.setFailures(listing: true) + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(), path: "/data/gi", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .failed("Listing failed") && model.exists == false }) + await requester.setFailures(listing: false, check: true) + model.retry() + #expect(await directoryEventually { model.lookupState == .loaded && model.existenceError != nil }) + #expect(model.exists == nil) + #expect(model.suggestions == ["/data/github", "/data/gists"]) + await requester.setFailures(listing: false) + model.retry() + #expect(await directoryEventually { model.exists == false && model.lookupState == .loaded }) + #expect(model.existenceError == nil) + #expect(await requester.listings.count == 3) + model.stop() + } + + @Test func homeExpansionUsesTheRemoteMachineAndPickingSuppressesSuggestions() async { + let requester = DirectoryRequester() + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(home: "/remote/home"), path: "~/gi", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + #expect(model.suggestions == ["/remote/home/github", "/remote/home/gists"]) + #expect(await directoryEventually { await requester.checks.contains(ExistenceCall(machineId: "m1", path: "/remote/home/gi")) }) + model.update(machine: directoryMachine(home: "/remote/home"), path: "~/github", showSuggestions: false) + #expect(model.suggestions.isEmpty) + #expect(model.lookupState == .idle) + model.stop() + } + + @Test func createRecheckAndClosingSupersedeBackgroundProbes() async { + let requester = DirectoryRequester() + let check = ExistenceCall(machineId: "m1", path: "/data/gi") + await requester.holdCheck(check) + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(), path: check.path, showSuggestions: false) + #expect(await directoryEventually { await requester.checks.contains(check) }) + model.acceptExistence(MachinePathsExistsResponse(exists: [check.path: true]), machineId: "m1", path: check.path) + await requester.releaseCheck(check) + #expect(await directoryEventually { await requester.completedChecks.contains(check) }) + #expect(model.exists == true) + model.stop() + #expect(model.exists == nil) + #expect(model.lookupState == .idle) + } + + @Test func closingRejectsLateListingsAndSameMachineRootChangesInvalidateCache() async { + let requester = DirectoryRequester() + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(), path: "/data/gi", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + model.update(machine: directoryMachine(roots: ["/work"]), path: "/data/gi", showSuggestions: true) + #expect(model.lookupState == .outsideRoots) + #expect(model.suggestions.isEmpty) + + let held = ListingCall(machineId: "m1", path: "/work") + await requester.holdListing(held) + model.update(machine: directoryMachine(roots: ["/work"]), path: "/work/gi", showSuggestions: true) + #expect(await directoryEventually { await requester.listings.contains(held) }) + model.stop() + await requester.releaseListing(held) + #expect(await directoryEventually { await requester.completedListings.contains(held) }) + #expect(model.lookupState == .idle) + #expect(model.suggestions.isEmpty) + #expect(!model.isCheckingExistence) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift index a57508eb..1867549a 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift @@ -160,6 +160,12 @@ struct NewSessionLogicTests { } @Test func windowsDriveAndUNCAutocompletePreserveSeparators() { + #expect(NewSessionLogic.directoryAutocompleteQuery(path: "C:\\wo", roots: ["C:\\work"]) + == .roots(["C:\\work"])) + #expect(NewSessionLogic.directoryAutocompleteQuery(path: "\\\\server\\sh", roots: ["\\\\server\\share"]) + == .roots(["\\\\server\\share"])) + #expect(NewSessionLogic.directoryAutocompleteQuery(path: "C:\\work", roots: ["C:\\work"]) + == .directory(NewSessionLogic.ParentQuery(parent: "C:\\work", prefix: "", separator: "\\"))) #expect( NewSessionLogic.parentQuery(for: "C:\\Users\\pro") == NewSessionLogic.ParentQuery(parent: "C:\\Users", prefix: "pro", separator: "\\") diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/SessionListStoreTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/SessionListStoreTests.swift index fae38f91..cb252b7a 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/SessionListStoreTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/SessionListStoreTests.swift @@ -93,6 +93,23 @@ struct SessionListStoreTests { // MARK: - Event: patch + @Test func generatedTitlePatchUpdatesListAndDetailAndRejectsAnOlderTitle() async throws { + let (_, store) = try makeStore() + var initial = storeSession("remote", updatedAt: 100) + initial.metadata = SessionMetadata(path: "/repo", host: "test", flavor: "codex") + store.applySessionEvent(try sessionUpdatedEvent("remote", dataJSON: fullSessionJSON(initial))) + let revision = store.listRevision + let titlePatch = #"{"metadata":{"version":2,"value":{"path":"/repo","host":"test","flavor":"codex","summary":{"text":"Remote title","updatedAt":200}}}}"# + store.applySessionEvent(try sessionUpdatedEvent("remote", dataJSON: titlePatch)) + #expect(store.sessions.first?.metadata?.summary?.text == "Remote title") + #expect(store.detail(for: "remote")?.metadata?.summary?.text == "Remote title") + #expect(store.listRevision > revision) + store.applySessionEvent(try sessionUpdatedEvent("remote", dataJSON: titlePatch)) + store.applySessionEvent(try sessionUpdatedEvent("remote", dataJSON: #"{"metadata":{"version":1,"value":{"path":"/repo","host":"test"}}}"#)) + #expect(store.sessions.first?.metadata?.summary?.text == "Remote title") + #expect(store.detail(for: "remote")?.metadata?.summary?.text == "Remote title") + } + @Test func staleVersionedPatchLeavesDetailAndSummaryUntouched() async throws { let (performer, store) = try makeStore() await performer.enqueue(json: try sessionsResponseJSON( @@ -319,6 +336,34 @@ struct SessionListStoreTests { // MARK: - Snapshot + @Test func removalNotificationsIgnoreFailedArchivesAndListReplacement() async throws { + let (performer, store) = try makeStore() + var removals: [String] = [] + store.onSessionRemoved = { removals.append($0) } + await performer.enqueue(json: try sessionsResponseJSON(storeSummary("s1"), storeSummary("s2"))) + try await store.refresh() + await performer.enqueue(status: 409, json: #"{"error":"cannot archive"}"#) + do { + try await store.archiveSession(sessionId: "s1") + Issue.record("The archive should fail") + } catch {} + #expect(removals.isEmpty) + #expect(store.sessions.contains { $0.id == "s1" }) + + await performer.enqueue(json: #"{"ok":true}"#) + try await store.archiveSession(sessionId: "s1") + #expect(removals == ["s1"]) + await performer.enqueue(json: try sessionsResponseJSON()) + try await store.refresh() + #expect(removals == ["s1"], "A refreshed list is not an explicit removal event") + + // Removal still arrives when the ID is absent (new session/notification + // raced the list), including the same ID replayed on both SSE pipes. + store.applySessionEvent(try sessionRemovedEvent("s2")) + store.applySessionEvent(try sessionRemovedEvent("s2")) + #expect(removals == ["s1", "s2", "s2"]) + } + @Test func summariesRoundTripThroughTheSnapshotIntoAColdStore() async throws { let directory = makeTempDirectory() let (performer, store) = try makeStore(snapshotDirectory: directory) 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 3f8b620e..8cf2c7bd 100644 --- a/ios/README.md +++ b/ios/README.md @@ -13,7 +13,7 @@ keeps one active. Session lists support machine filtering, pinning and archive; sending to an inactive session can resume it and migrate the draft/navigation when the returned session ID changes. -Model and permission controls follow the session's agent/capabilities; +Model, permission and Codex collaboration controls follow the session's agent/capabilities; usage/storage require the owner namespace. Rename, Delete and explicit Reopen have API wrappers but no current iOS UI. See the [native app guide](../docs/guide/native-apps.md) for platform differences, web-only features and everyday use. @@ -95,15 +95,28 @@ presentation. When changing fixture inputs or generation, run hand-edit fixtures. See [fixture guidance](../shared/fixtures/README.md) and [UI development](#ui-development) for targeted app-hosted checks. +New-session directory regression checks: `ios/scripts/linux-test.sh --filter +'NewSession|RemoteDirectoryBrowser'` covers path queries and browser navigation; +`HapiTests/NewSessionDirectoryTests` covers the form's defaults, roster refresh, +offline machines and spawn validation. On a device, verify home → parent → a +project outside home, explicit workspace-root prefixes, `~/` and hidden-directory +completion, and clearing the input while machine health updates arrive. A +restored or selected offline machine stays selected until the user chooses an +online machine; its old path is never silently moved to another host. + ## Pairing The app supports multiple hubs with one active selection. See the [auth contract](../docs/api/client-contract/auth.md) for the wire rules. - **Manual entry:** start `hapi hub --relay`, then *Enter Manually* → HTTPS - hub origin and access token → *Pair*. For a source-tree `bun run dev` hub, - put an HTTPS reverse proxy or tunnel in front of `localhost:3006`; a - physical phone must reach that endpoint. The app checks `GET /health`, + hub address and access token → *Pair*. The address starts empty, with a + separate protocol menu defaulting to HTTPS; type the domain/IP and optional + port without a scheme. Pasting a full HTTP(S) URL updates that menu. A full + companion or web pairing link pasted into either field fills both values + for review — only submitting the form starts a connection. For a source-tree + `bun run dev` hub, put an HTTPS reverse proxy or tunnel in front of + `localhost:3006`; a physical phone must reach that endpoint. The app checks `GET /health`, requires `protocolVersion == ProtocolVersion.supported`, exchanges the token with `POST /api/auth` and stores credentials in the Keychain. - **QR scan:** the in-app scanner accepts both hub QR forms — @@ -119,16 +132,21 @@ The app supports multiple hubs with one active selection. See the issued JWT rejected again, triggers re-pairing. Temporary network/5xx refresh failures retain credentials. -The parser accepts HTTP URLs; manual addresses without a scheme receive an -`http://` prefix. This is input normalization, not a transport exemption. +The parser accepts HTTP URLs. Manual entry uses the selected protocol +(default HTTPS); HTTP must be selected explicitly or supplied in a full URL +or pairing link. The form warns that HTTP is unencrypted and may be restricted +by iOS. It never guesses HTTP for a local address or downgrades after a failed +HTTPS connection. Input acceptance is not a transport exemption. `Hapi/Info.plist` and the project build settings declare no ATS exceptions, -including no `NSAllowsLocalNetworking`. Use explicit HTTPS URLs for a reliable +including no `NSAllowsLocalNetworking`. Use HTTPS endpoints for a reliable pairing setup; HTTP behavior remains subject to system network policy. Manual app-layer acceptance: pair → kill/relaunch → background/foreground → pair a second hub and switch → sign out → scan both QR forms → open a deep link for unpaired/paired hubs. Also check that transient hub failures preserve -pairing, while a rejected rotated token shows the sign-out banner. Pure pairing +pairing, while a rejected rotated token shows the sign-out banner. +Manual-entry form and system-paste behavior is covered by app-hosted +`ManualPairingFormTests` and `ManualEntryPresentationTests`; pure pairing and auth behavior is covered by the package tests; this checklist is for the app wiring and platform interaction. @@ -237,6 +255,40 @@ uses `AnchoredTranscriptList` (`UICollectionView` with SwiftUI hosting) and prepares Markdown off the main thread; see [native transcript scrolling](../docs/native-chat-scrolling.md). +## Scratchlist workflow + +The composer tray toggles a session-local `chat` / `scratchlist` destination. +Scratchlist mode shows one recent draft, or just a header while the input is +focused or when using accessibility text sizes, and an explicitly labelled +**Save draft** action. Tap the header to open the full list, or × to return to +chat. Closing the drawer preserves input; taking a draft or accepting a queue +send returns to chat mode. The queue remains a +separate, automatically delivered surface. + +Text and attachments park as one snapshot. Failed saves retain input and +retry the same entry ID. Taking a saved attachment creates a borrowed hub +reference, without resuming the session; an explicit chat send stages it to +the active/resumed session's upload directory. Queue actions do not consume +the composer and use a stable local ID for the saved entry version. A failed +post-acceptance deletion retries removal only. The full inventory uses one +navigation stack for reading and transactional editing, with discard guards +and editor identities protecting against late uploads. + +Inventory rows show two lines of text, an attachment count, **Take draft** and +a menu for queueing, editing, copying and deleting. Pull down for search +(including attachment filenames); full filenames and relative timestamps live +in the detail view. The editor's + menu offers photos and files. Empty states +and routine chrome avoid explanatory paragraphs; failures stay inline with +their recovery action, without a duplicate toast. + +Regression suites: package `ScratchlistComposerWorkflowTests`, +`ScratchlistAttachmentFlowTests`, `ScratchlistStoreTests` and +`ComposerAttachmentsTests`; app-hosted `ScratchlistScreenModelTests` and +`ScratchlistPresentationTests` (including transcript-anchor preservation). +The presentation suite attaches light/dark, compact, accessibility, inventory +and editor renders. Manually check keyboard/VoiceOver, conflict choices, +photo/file retry, and inactive-session sending on a connected device. + ## UI development ### Localization catalog @@ -271,6 +323,53 @@ Xcode still synchronizes old extraction results, then rebuild/reopen and inspect the diff. Do not hide the file with `.gitignore`, `skip-worktree`, or restore it unconditionally: real translation edits must remain visible and committed. +### iPad navigation and resizing + +iPad uses a two-column `NavigationSplitView`: sessions in the sidebar and a +separate detail navigation stack for chat → files/viewer/process pages. The +sidebar requests 280–360pt (320pt ideal); the system collapses the same view +hierarchy in compact windows. iPhone keeps its single `NavigationStack`. +Cold starts and hub switches show **Select a session** until the user chooses +one; notifications and new sessions can open an ID before its list row arrives. +Selection and nested navigation are in memory, not restored across launches. + +`SessionNavigationState` owns selection, detail path and column visibility; +neither window geometry nor sidebar filters may clear them. Reopening the +selected session preserves its file page. A different/superseding session resets +the entire detail stack, but a late superseding callback cannot replace a chat +the user has since selected. Only explicit removal events or successful archive +operations clear the current selection, never optimistic list removal/rollback. + +The detail's identity is hub/session-based, so resizing preserves the existing +chat, draft, attachment tray and transcript anchor. Native menus/sheets remain +native; the hub sign-out and attachment dialogs are anchored to their buttons. +The explicit scene manifest disables additional HAPI windows, **not** Split +View/Stage Manager with other apps. Do not enable scene-manifest generation +(which generates multiple-scene support) or require full screen. Multiwindow, +third-column inspectors, keyboard shortcuts and drag/drop are not implemented. + +`SessionNavigationTests` covers navigation/removal policy and the built scene +manifest. `SessionSplitPresentationTests` runs on an actual iPad simulator and +uses the production split shell/list plus a real, non-networked chat specimen: +selection, compact programmatic opening, nested Back, filtering, resizing, +reading anchors, draft/attachment retention and surface/subscription lifetime. +CI keeps the iPhone suite and adds iPad Air 11-inch (M2). Run it locally with: + +```sh +HAPI_TEST_DEVICE_TYPE=com.apple.CoreSimulator.SimDeviceType.iPad-Air-11-inch-M2 \ + ios/scripts/test-transcript.sh \ + -only-testing:HapiTests/SessionNavigationTests \ + -only-testing:HapiTests/SessionSplitPresentationTests +``` + +Optional specimens: set `TEST_RUNNER_HAPI_IPAD_CAPTURE` to a **new temporary +directory**; these are synthetic test conversations, not release screenshots. +Before release, manually verify mini/11/13-inch portrait and landscape, +one-third/half-screen and Stage Manager resizing, keyboard docking/floating and +hardware-keyboard transitions, light/dark, Chinese/English, Dynamic Type and +VoiceOver. Check settings/new-session/Scratchlist/inspection sheets while +resizing, notification navigation, and background/foreground reconnection. + ### Reading typography `HapiUI` separates color palettes (`HapiTheme`) from resolved Dynamic Type @@ -307,12 +406,68 @@ TEST_RUNNER_HAPI_TYPOGRAPHY_CAPTURE=/tmp/hapi-typography-review \ ios/scripts/test-transcript.sh -only-testing:HapiTests/TypographySnapshotTests ``` +### Session settings + +The chat gear presents a single-page model/effort and permission/collaboration +form. All selections use native menus; permission explanations, high-risk +indicators, model-loading/retry states and update feedback remain in the form. +Changes apply immediately; Done only dismisses. On regular-width windows the +production toolbar button anchors an iPad popover; compact windows adapt that +same presenter to a medium/large sheet (large for accessibility text). + +Run the configuration and real-presentation tests on both phone and tablet: + +```sh +ios/scripts/test-transcript.sh \ + -only-testing:HapiTests/SessionConfigTests \ + -only-testing:HapiTests/SessionConfigPresentationTests + +# Pick a device type supported by your installed runtime: +# xcrun simctl list devicetypes +HAPI_TEST_DEVICE_TYPE=com.apple.CoreSimulator.SimDeviceType.iPad-Pro-11-inch-M5-12GB \ + ios/scripts/test-transcript.sh \ + -only-testing:HapiTests/SessionConfigTests \ + -only-testing:HapiTests/SessionConfigPresentationTests +``` + +The script creates and deletes an isolated simulator. Set +`TEST_RUNNER_HAPI_SESSION_CONFIG_CAPTURE` to a new temporary directory for +non-networked specimens (not App Store screenshots). A widened phone window +is not a substitute for the native iPad anchor test. For AXe-driven menu and +Done checks, run only +`SessionConfigPresentationTests/testNativeDevicePresentationIsAnchoredOnIPadAndAdaptsOnIPhone` +with `TEST_RUNNER_HAPI_SESSION_CONFIG_INTERACTIVE_SECONDS=180`; leave the panel +open when the pause ends. Manually check rotation and Split View/window resizing, +menu checkmarks and risk announcements, and that closing preserves the chat's +draft and reading position. + ### Tool inspection +Inline approvals use a neutral card with a quiet pending/submitting/handled +status, a full-input link, and adaptive action rows. `ChatActionButtonStyle` +owns the complete 44pt minimum target (10pt corners); do not add system bordered +button padding or another minimum label height. Approvals, question navigation +and plan actions share only this style, never their submission semantics. +Queued-message actions also keep 44pt targets and stack when the column is too +narrow. Native alerts, sheets and form controls retain their system styling. + +`PermissionActionPresentationTests` covers flavor gates, action geometry, busy +and already-handled states, failures, themes and large text. To capture isolated, +non-networked approval specimens, set `TEST_RUNNER_HAPI_APPROVAL_CAPTURE` to a +new temporary directory and run it through `ios/scripts/test-transcript.sh`. + 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 hides that proposal’s action menu locally and focuses the composer, +preserving its draft and plan mode without sending a message. The plan document +remains readable, and a new proposal gets a fresh menu. 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. @@ -345,6 +500,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. @@ -360,8 +520,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 diff --git a/ios/scripts/test-transcript.sh b/ios/scripts/test-transcript.sh index aefc73f2..0f42f1fa 100755 --- a/ios/scripts/test-transcript.sh +++ b/ios/scripts/test-transcript.sh @@ -8,7 +8,8 @@ import json, sys items = [x for x in json.load(sys.stdin)["runtimes"] if x.get("isAvailable") and x.get("name", "").startswith("iOS")] print(max(items, key=lambda x: tuple(map(int, x["version"].split("."))))["identifier"]) ') -device=$(xcrun simctl create "HAPI Transcript Tests" com.apple.CoreSimulator.SimDeviceType.iPhone-15 "$runtime") +device_type=${HAPI_TEST_DEVICE_TYPE:-com.apple.CoreSimulator.SimDeviceType.iPhone-15} +device=$(xcrun simctl create "HAPI Transcript Tests" "$device_type" "$runtime") trap 'xcrun simctl delete "$device" >/dev/null 2>&1 || true' EXIT xcodebuild test -project ios/Hapi.xcodeproj -scheme Hapi \ 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/shared/fixtures/pagination/cancel-too-late-ingests-invoked-row.json b/shared/fixtures/pagination/cancel-too-late-ingests-invoked-row.json index 93965dd0..fcc105ed 100644 --- a/shared/fixtures/pagination/cancel-too-late-ingests-invoked-row.json +++ b/shared/fixtures/pagination/cancel-too-late-ingests-invoked-row.json @@ -31,7 +31,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/fetch-older-before-cursor.json b/shared/fixtures/pagination/fetch-older-before-cursor.json index 2994a5a9..45e78fd6 100644 --- a/shared/fixtures/pagination/fetch-older-before-cursor.json +++ b/shared/fixtures/pagination/fetch-older-before-cursor.json @@ -39,7 +39,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/latest-page-then-sse-ingest.json b/shared/fixtures/pagination/latest-page-then-sse-ingest.json index 3293a500..17f4f2a7 100644 --- a/shared/fixtures/pagination/latest-page-then-sse-ingest.json +++ b/shared/fixtures/pagination/latest-page-then-sse-ingest.json @@ -48,7 +48,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/messages-consumed-stamps-invoked-at.json b/shared/fixtures/pagination/messages-consumed-stamps-invoked-at.json index 88afbe11..b3554e56 100644 --- a/shared/fixtures/pagination/messages-consumed-stamps-invoked-at.json +++ b/shared/fixtures/pagination/messages-consumed-stamps-invoked-at.json @@ -40,7 +40,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/older-page-epoch-mismatch-resets.json b/shared/fixtures/pagination/older-page-epoch-mismatch-resets.json index c9ceeef6..b8978f8e 100644 --- a/shared/fixtures/pagination/older-page-epoch-mismatch-resets.json +++ b/shared/fixtures/pagination/older-page-epoch-mismatch-resets.json @@ -30,7 +30,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/queued-state-reconciliation-drops-deleted.json b/shared/fixtures/pagination/queued-state-reconciliation-drops-deleted.json index 0c571ae9..c5666797 100644 --- a/shared/fixtures/pagination/queued-state-reconciliation-drops-deleted.json +++ b/shared/fixtures/pagination/queued-state-reconciliation-drops-deleted.json @@ -40,7 +40,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/reasoning-snapshots-collapse-to-newest.json b/shared/fixtures/pagination/reasoning-snapshots-collapse-to-newest.json index 1b9b20a5..26ce4562 100644 --- a/shared/fixtures/pagination/reasoning-snapshots-collapse-to-newest.json +++ b/shared/fixtures/pagination/reasoning-snapshots-collapse-to-newest.json @@ -66,7 +66,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/reset-latest-preserves-optimistic.json b/shared/fixtures/pagination/reset-latest-preserves-optimistic.json index 63fdd4b2..6146cf08 100644 --- a/shared/fixtures/pagination/reset-latest-preserves-optimistic.json +++ b/shared/fixtures/pagination/reset-latest-preserves-optimistic.json @@ -40,7 +40,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/sse-hidden-rows-advance-cursor-only.json b/shared/fixtures/pagination/sse-hidden-rows-advance-cursor-only.json index c50a3e08..689be3fc 100644 --- a/shared/fixtures/pagination/sse-hidden-rows-advance-cursor-only.json +++ b/shared/fixtures/pagination/sse-hidden-rows-advance-cursor-only.json @@ -39,7 +39,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/fixtures/pagination/trim-preserves-queued-and-recomputes-cursor.json b/shared/fixtures/pagination/trim-preserves-queued-and-recomputes-cursor.json index f6363cab..863895ad 100644 --- a/shared/fixtures/pagination/trim-preserves-queued-and-recomputes-cursor.json +++ b/shared/fixtures/pagination/trim-preserves-queued-and-recomputes-cursor.json @@ -3621,7 +3621,7 @@ { "expectedRequests": [ { - "limit": 200 + "limit": 20 } ], "op": "sync-tail", diff --git a/shared/src/buildInfo.ts b/shared/src/buildInfo.ts index 3063bc21..2eaf2c38 100644 --- a/shared/src/buildInfo.ts +++ b/shared/src/buildInfo.ts @@ -1 +1 @@ -export const APP_VERSION = '0.30.3' +export const APP_VERSION = '0.30.7' diff --git a/web/README.md b/web/README.md index d34742cc..4b65b18c 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. @@ -62,6 +66,10 @@ See `src/router.tsx` for route definitions. - Composer for sending messages. - Permission mode and model selection for supported agents. - Session abort and handoff controls. +- Codex **Continue planning** hides the current proposal's action menu locally + and focuses the composer without sending a message or replacing its draft. + The plan document remains readable; recycled cards stay dismissed and new + proposals get fresh action menus. - Context size display. - Per-session scratchlist (`src/components/AssistantChat/ScratchlistPanel.tsx`) - Workbench panel for held notes/drafts; **distinct from the queue**. diff --git a/web/e2e-fixtures/history-load-fixture.tsx b/web/e2e-fixtures/history-load-fixture.tsx index dccb7ba4..29379e3c 100644 --- a/web/e2e-fixtures/history-load-fixture.tsx +++ b/web/e2e-fixtures/history-load-fixture.tsx @@ -1,6 +1,7 @@ import { useMemo, useRef } from 'react' import ReactDOM from 'react-dom/client' import { AssistantRuntimeProvider } from '@assistant-ui/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import '../src/index.css' import type { ApiClient } from '../src/api/client' import type { DecryptedMessage, MessagesResponse, Session } from '../src/types/api' @@ -27,6 +28,7 @@ const BASE_AT = 1_700_000_000_000 type Probe = { requests: { direction: string; beforeSeq: number | null; limit: number | undefined; at: number }[] + loadMore: () => Promise refetch: () => Promise windowState: () => { messageCount: number; oldestSeq: number | null; newestSeq: number | null } } @@ -39,6 +41,7 @@ declare global { window.__probe = { requests: [], + loadMore: async () => {}, refetch: async () => {}, windowState: () => { const state = getMessageWindowState(SESSION_ID) @@ -62,6 +65,8 @@ window.__probe = { // - ?epochBump=1 — `before` responses carry a newer epoch than the tail, so // every older-page request hits the store's deliberate epoch-mismatch stop // (reset + tail resync, typed terminal stop). +// - ?coldInitial=1 — honor the production cold-open latest-page size instead +// of returning the legacy full 200-row page used by this fixture by default. // - ?slowBefore=1 — delay older-page responses long enough for a normal tail // synchronization to invalidate an in-flight request. const fixtureParams = new URLSearchParams(window.location.search) @@ -69,6 +74,7 @@ const shortPages = fixtureParams.has('shortPages') const failBeforeCount = Number(fixtureParams.get('failBefore') ?? '0') const filteredOlder = fixtureParams.has('filteredOlder') const epochBump = fixtureParams.has('epochBump') +const coldInitial = fixtureParams.has('coldInitial') const slowBefore = fixtureParams.has('slowBefore') let beforeAttempts = 0 @@ -118,10 +124,11 @@ const fakeApi = { afterAt?: number | null afterSeq?: number | null }): Promise => { - const limit = query.limit ?? 200 + const requestedLimit = query.limit ?? 200 let direction = 'latest' if (query.beforeSeq != null || query.beforeAt != null) direction = 'before' else if (query.afterSeq != null || query.afterAt != null) direction = 'after' + const limit = direction === 'latest' && !coldInitial ? 200 : requestedLimit window.__probe.requests.push({ direction, beforeSeq: query.beforeSeq ?? null, @@ -216,6 +223,7 @@ function FixtureThread() { setViewMode } = useMessages(fakeApi, SESSION_ID) + window.__probe.loadMore = loadMore window.__probe.refetch = refetch const blocksByIdRef = useRef>(new Map()) @@ -285,8 +293,16 @@ function FixtureThread() { ) } +const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false } + } +}) + ReactDOM.createRoot(document.getElementById('root')!).render( - - - + + + + + ) diff --git a/web/e2e-fixtures/markdown-math-fixture.html b/web/e2e-fixtures/markdown-math-fixture.html new file mode 100644 index 00000000..301be776 --- /dev/null +++ b/web/e2e-fixtures/markdown-math-fixture.html @@ -0,0 +1,12 @@ + + + + + + HAPI Markdown math fixture + + +
+ + + diff --git a/web/e2e-fixtures/markdown-math-fixture.tsx b/web/e2e-fixtures/markdown-math-fixture.tsx new file mode 100644 index 00000000..5cd0a488 --- /dev/null +++ b/web/e2e-fixtures/markdown-math-fixture.tsx @@ -0,0 +1,32 @@ +import React from 'react' +import ReactDOM from 'react-dom/client' +import '../src/index.css' +import { I18nProvider } from '../src/lib/i18n-context' +import { MarkdownRenderer } from '../src/components/MarkdownRenderer' + +const SAMPLE_MARKDOWN = [ + '# Markdown math fixture', + '', + String.raw`Inline: \(x^2 + y^2\)`, + '', + String.raw`\[`, + String.raw`\lim_{x\to 0}\frac{\sin x}{x}=1`, + String.raw`\]`, + '', + '```latex', + '\\[x^2\\]', + '```', +].join('\n') + +const rootEl = document.getElementById('root') +if (rootEl) { + ReactDOM.createRoot(rootEl).render( + + +
+ +
+
+
+ ) +} diff --git a/web/e2e-fixtures/share-turn-fixture.tsx b/web/e2e-fixtures/share-turn-fixture.tsx index 01acf032..17625756 100644 --- a/web/e2e-fixtures/share-turn-fixture.tsx +++ b/web/e2e-fixtures/share-turn-fixture.tsx @@ -62,6 +62,25 @@ Final paragraph after the divider. \`alist.techotaku39.top\` 已失效,5244 端口也不再监听。 请将 \`machine-status-widget/hapi-machine-status.user.js\` 全文覆盖到油猴脚本中,然后强制刷新页面。 + +### LaTeX + +Inline formula: \\(E=mc^2\\) + +\\[ +\\lim_{x\\to 0}\\frac{\\sin x}{x}=1 +\\] + +\\[ +\\prod_{i=1}^{n} x_i +\\] + +\\[ +\\begin{aligned} +f(x) &= x^2+2x+1 \\\\ + &= (x+1)^2 +\\end{aligned} +\\] ` if (new URLSearchParams(window.location.search).get('theme') === 'dark') { diff --git a/web/e2e/latex-bracket-math-session.spec.ts b/web/e2e/latex-bracket-math-session.spec.ts new file mode 100644 index 00000000..c26ca81a --- /dev/null +++ b/web/e2e/latex-bracket-math-session.spec.ts @@ -0,0 +1,79 @@ +import { expect, test } from '@playwright/test' +import { readFile } from 'node:fs/promises' +import { + getHapiBaseUrl, + installHapiAuth, + readCliAccessToken, +} from './helpers/hapi-live' + +const liveEnabled = process.env.HAPI_LIVE === '1' && Boolean(process.env.SESSION_ID?.trim()) + +test.describe('LaTeX bracket math (live HAPI session)', () => { + test.skip(!liveEnabled, 'Set HAPI_LIVE=1 and SESSION_ID to run against a real hub session') + + test('renders math and exports the share image', async ({ page }, testInfo) => { + const baseUrl = getHapiBaseUrl() + const sessionId = process.env.SESSION_ID?.trim() + if (!sessionId) throw new Error('SESSION_ID is required for the live LaTeX smoke') + await installHapiAuth(page, baseUrl, readCliAccessToken()) + if (process.env.HAPI_LIVE_MOBILE === '1') { + await page.addInitScript(() => { + Object.defineProperty(navigator, 'maxTouchPoints', { configurable: true, value: 5 }) + const nativeMatchMedia = window.matchMedia.bind(window) + window.matchMedia = (query: string) => { + if (query !== '(pointer: coarse)') return nativeMatchMedia(query) + return { + matches: true, + media: query, + onchange: null, + addListener: () => undefined, + removeListener: () => undefined, + addEventListener: () => undefined, + removeEventListener: () => undefined, + dispatchEvent: () => false, + } + } + }) + await page.setViewportSize({ width: 390, height: 844 }) + } + await page.goto(`${baseUrl}/sessions/${sessionId}`, { + waitUntil: 'domcontentloaded', + timeout: 60_000, + }) + await page.evaluate(() => { + document.documentElement.dataset.theme = 'dark' + }) + + const assistant = page.locator('[data-hapi-message-role="assistant"]').last() + await expect.poll(() => assistant.locator('.katex').count(), { timeout: 30_000 }).toBeGreaterThan(0) + const pageMathCount = await assistant.locator('.katex').count() + const pageDisplayMathCount = await assistant.locator('.katex-display').count() + // The synced seq=701 response contains 79 bracket-delimited display + // formulas. A small positive assertion would miss regressions where + // only the simplest formula still renders. + expect(pageMathCount).toBeGreaterThan(50) + expect(pageDisplayMathCount).toBeGreaterThan(50) + await expect.poll(() => assistant.locator('.katex').first().evaluate((element) => ( + getComputedStyle(element).fontFamily.includes('KaTeX') + ))).toBe(true) + + const mentionExplainer = page.getByRole('dialog', { name: 'New: @mention another session' }) + if (await mentionExplainer.count()) { + await mentionExplainer.getByRole('button', { name: 'Close explainer' }).click() + } + await assistant.locator('[data-hapi-share-action="true"]').click({ force: true }) + const dialog = page.getByRole('dialog', { name: /Share turn as image|将本轮对话分享为图片/ }) + await expect(dialog).toBeVisible() + await expect(dialog.locator('.katex')).toHaveCount(pageMathCount, { timeout: 30_000 }) + await expect(dialog.locator('.katex-display')).toHaveCount(pageDisplayMathCount) + + const downloadPromise = page.waitForEvent('download') + await dialog.getByRole('button', { name: /^(Download|下载)$/ }).click() + const download = await downloadPromise + const outputPath = testInfo.outputPath('live-latex-share.png') + await download.saveAs(outputPath) + const bytes = await readFile(outputPath) + expect(bytes.subarray(1, 4).toString()).toBe('PNG') + expect(bytes.length).toBeGreaterThan(80_000) + }) +}) diff --git a/web/playwright.live.config.ts b/web/playwright.live.config.ts index 73b93f45..b0f17a5f 100644 --- a/web/playwright.live.config.ts +++ b/web/playwright.live.config.ts @@ -5,7 +5,7 @@ const chromePath = process.env.PLAYWRIGHT_CHROME_PATH /** Live hub session tests — no Vite; hits HAPI_URL with HAPI_LIVE=1. */ export default defineConfig({ testDir: './e2e', - testMatch: 'mermaid-lightbox-session.spec.ts', + testMatch: ['mermaid-lightbox-session.spec.ts', 'latex-bracket-math-session.spec.ts'], timeout: 120_000, expect: { timeout: 20_000 }, fullyParallel: false, 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/AssistantChat/ShareTurnDialog.test.ts b/web/src/components/AssistantChat/ShareTurnDialog.test.ts new file mode 100644 index 00000000..3f73734e --- /dev/null +++ b/web/src/components/AssistantChat/ShareTurnDialog.test.ts @@ -0,0 +1,40 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { getKaTeXFontRequests } from './ShareTurnDialog' + +describe('getKaTeXFontRequests', () => { + afterEach(() => { + document.body.innerHTML = '' + }) + + it('returns only the KaTeX families and variants used by the formula', () => { + const root = document.createElement('div') + root.innerHTML = ` + + + + + + + ` + document.body.appendChild(root) + + root.querySelector('[data-font="main"]')!.setAttribute('style', 'font-family: "KaTeX_Main", serif') + root.querySelector('[data-font="math"]')!.setAttribute('style', 'font-family: "KaTeX_Math", serif; font-style: italic') + root.querySelector('[data-font="ams"]')!.setAttribute('style', 'font-family: "KaTeX_AMS", serif; font-weight: 700') + root.querySelector('[data-font="fallback"]')!.setAttribute('style', 'font-family: serif') + + expect(getKaTeXFontRequests(root)).toEqual([ + '16px "KaTeX_Main"', + 'italic 16px "KaTeX_Math"', + 'bold 16px "KaTeX_AMS"', + ]) + }) + + it('falls back to the main KaTeX font when computed styles are unavailable', () => { + const root = document.createElement('div') + root.innerHTML = '' + document.body.appendChild(root) + + expect(getKaTeXFontRequests(root)).toEqual(['16px "KaTeX_Main"']) + }) +}) diff --git a/web/src/components/AssistantChat/ShareTurnDialog.tsx b/web/src/components/AssistantChat/ShareTurnDialog.tsx index 019f3282..29b856bf 100644 --- a/web/src/components/AssistantChat/ShareTurnDialog.tsx +++ b/web/src/components/AssistantChat/ShareTurnDialog.tsx @@ -210,6 +210,13 @@ function prepareExportElement(element: HTMLElement, exportWidth: number, preserv shaped baseline. Zero spacing keeps each text run intact. */ letter-spacing: 0 !important; } + .hapi-share-export-root .katex, + .hapi-share-export-root .katex * { + letter-spacing: normal !important; + } + .hapi-share-export-root .katex { + line-height: 1.2 !important; + } .hapi-share-export-root :not(pre) > code { position: relative !important; /* html2canvas-pro paints an inline element's background using its @@ -303,6 +310,82 @@ function waitForStyleSheets(document: Document): Promise { })).then(() => undefined) } +const KATEX_FONT_FAMILIES = [ + 'KaTeX_Main', + 'KaTeX_Math', + 'KaTeX_AMS', + 'KaTeX_Caligraphic', + 'KaTeX_Fraktur', + 'KaTeX_SansSerif', + 'KaTeX_Script', + 'KaTeX_Size1', + 'KaTeX_Size2', + 'KaTeX_Size3', + 'KaTeX_Size4', + 'KaTeX_Typewriter', +] as const + +const loadedKaTeXFonts = new WeakMap>>() + +export function getKaTeXFontRequests(root: HTMLElement): string[] { + const requests = new Set() + const elements = [ + ...(root.matches('.katex') ? [root] : []), + ...Array.from(root.querySelectorAll('.katex, .katex *')), + ] + const getStyle = root.ownerDocument.defaultView?.getComputedStyle.bind(root.ownerDocument.defaultView) + + for (const element of elements) { + const style = getStyle?.(element) + if (!style) continue + const family = style.fontFamily + .split(',') + .map((value) => value.trim().replace(/^['"]|['"]$/g, '')) + .find((value): value is (typeof KATEX_FONT_FAMILIES)[number] => ( + KATEX_FONT_FAMILIES.includes(value as (typeof KATEX_FONT_FAMILIES)[number]) + )) + if (!family) continue + + const fontStyle = style.fontStyle === 'italic' ? 'italic' : 'normal' + const numericWeight = Number.parseInt(style.fontWeight, 10) + const fontWeight = style.fontWeight === 'bold' || numericWeight >= 600 ? 'bold' : 'normal' + const stylePrefix = fontStyle === 'italic' ? 'italic ' : '' + const weightPrefix = fontWeight === 'bold' ? 'bold ' : '' + requests.add(`${stylePrefix}${weightPrefix}16px "${family}"`) + } + + return requests.size > 0 ? [...requests] : ['16px "KaTeX_Main"'] +} + +function loadKaTeXFont(document: Document, request: string): Promise { + let documentFonts = loadedKaTeXFonts.get(document) + if (!documentFonts) { + documentFonts = new Map() + loadedKaTeXFonts.set(document, documentFonts) + } + + const existing = documentFonts.get(request) + if (existing) return existing + + const loading = document.fonts.load(request).catch(() => { + documentFonts?.delete(request) + return [] + }) + documentFonts.set(request, loading) + return loading +} + +async function waitForKaTeXFonts(root: HTMLElement): Promise { + const ownerDocument = root.ownerDocument + if (!ownerDocument.fonts) return + + // Loading every KaTeX family/style combination makes each export wait for + // fonts that are not present in the captured formula. The computed styles + // identify the small subset actually used by this turn. + const fontRequests = getKaTeXFontRequests(root) + await Promise.all(fontRequests.map((request) => loadKaTeXFont(ownerDocument, request))) +} + function appendTextFallback(target: DocumentFragment | HTMLElement, snapshot: ShareTurnSnapshot): void { if (snapshot.text.trim().length === 0) return const fallback = document.createElement('div') @@ -314,13 +397,14 @@ function appendTextFallback(target: DocumentFragment | HTMLElement, snapshot: Sh target.appendChild(fallback) } -function resolveCssUrls(cssText: string, styleSheetUrl: string | null): string { - if (!styleSheetUrl) return cssText +function resolveCssUrls(cssText: string, styleSheetUrl: string | null, fallbackBaseUrl: string): string { + const baseUrl = styleSheetUrl ?? fallbackBaseUrl + if (!baseUrl) return cssText return cssText.replace(/url\(\s*(['"]?)(.*?)\1\s*\)/gi, (match, quote: string, rawUrl: string) => { const url = rawUrl.trim() if (!url || /^(?:data:|blob:|#|[a-z][a-z\d+.-]*:|\/\/)/i.test(url)) return match try { - return `url(${quote}${new URL(url, styleSheetUrl).href}${quote})` + return `url(${quote}${new URL(url, baseUrl).href}${quote})` } catch { return match } @@ -339,7 +423,8 @@ function copyLoadedStyleSheets(source: Document, target: Document): void { try { const cssText = resolveCssUrls( Array.from(sheet.cssRules, (rule) => rule.cssText).join('\n'), - sheet.href + sheet.href, + source.baseURI ) if (!cssText) continue const style = target.createElement('style') @@ -386,7 +471,9 @@ async function waitForImages(root: HTMLElement): Promise { async function waitForExportReady(root: HTMLElement): Promise { const ownerDocument = root.ownerDocument await waitForStyleSheets(ownerDocument) - if (ownerDocument.fonts) { + if (root.querySelector('.katex')) { + await waitForKaTeXFonts(root) + } else if (ownerDocument.fonts) { await ownerDocument.fonts.ready.catch(() => undefined) } await waitForImages(root) @@ -458,10 +545,14 @@ async function elementToPngBlob( const maxScale = Math.sqrt(MAX_EXPORT_PIXELS / Math.max(1, captureWidth * captureHeight)) const scale = Math.min(SHARE_EXPORT_SCALE, maxScale) const backgroundColor = getComputedStyle(captureElement).backgroundColor || '#ffffff' + const containsKaTeX = captureElement.querySelector('.katex') !== null const { default: html2canvas } = await import('html2canvas-pro') canvas = await html2canvas(captureElement, { backgroundColor, - foreignObjectRendering: false, + // KaTeX relies on browser font metrics and nested CSS positioning + // for fractions, accents, delimiters, and aligned environments. + // Use Chromium's native foreignObject paint for those nodes. + foreignObjectRendering: containsKaTeX, imageTimeout: 15000, logging: false, removeContainer: true, diff --git a/web/src/components/AssistantChat/context.tsx b/web/src/components/AssistantChat/context.tsx index ee6cd74d..d3c2ddfd 100644 --- a/web/src/components/AssistantChat/context.tsx +++ b/web/src/components/AssistantChat/context.tsx @@ -1,5 +1,5 @@ import type { ReactNode } from 'react' -import { createContext, useContext } from 'react' +import { createContext, useContext, useState } from 'react' import type { ApiClient } from '@/api/client' import type { TerminalToolDisplayMode } from '@/hooks/useTerminalToolDisplayMode' import type { SessionMetadataSummary } from '@/types/api' @@ -16,7 +16,8 @@ export type HappyChatContextValue = { disabled: boolean onRefresh: () => void codexPlanProposalId?: string | null - onContinuePlan?: () => void + onContinuePlan?: (planId: string) => void + continuedPlanIds?: ReadonlySet onRetryMessage?: (localId: string) => void onRetryCodexTurn?: () => Promise | void /** Only the latest terminal Codex capacity error may expose Retry. */ @@ -40,8 +41,22 @@ export type HappyChatContextValue = { const HappyChatContext = createContext(null) export function HappyChatProvider(props: { value: HappyChatContextValue; children: ReactNode }) { + // Keep dismissal outside virtualized cards so recycling cannot revive a menu. + const [continued, setContinued] = useState<{ sessionId: string; ids: ReadonlySet }>({ + sessionId: props.value.sessionId, ids: new Set() + }) + const ids = continued.sessionId === props.value.sessionId ? continued.ids : new Set() + const value: HappyChatContextValue = { + ...props.value, + continuedPlanIds: ids, + onContinuePlan: props.value.onContinuePlan ? (planId) => { + if (props.value.disabled || props.value.codexPlanProposalId !== planId || ids.has(planId)) return + setContinued({ sessionId: props.value.sessionId, ids: new Set([...ids, planId]) }) + props.value.onContinuePlan?.(planId) + } : undefined + } return ( - + {props.children} ) diff --git a/web/src/components/MarkdownRenderer.test.tsx b/web/src/components/MarkdownRenderer.test.tsx index ed483499..01a65b18 100644 --- a/web/src/components/MarkdownRenderer.test.tsx +++ b/web/src/components/MarkdownRenderer.test.tsx @@ -28,4 +28,29 @@ describe('MarkdownRenderer', () => { expect(document.querySelector('.aui-md-codeblock')).toBeFalsy() expect(document.querySelector('.aui-md-code')).toBeTruthy() }) + + it('renders TeX bracket math in standalone mode', () => { + const { container } = render( + + + + ) + + expect(container.querySelector('.katex-display')).toBeTruthy() + expect(container.querySelector('.katex')).toBeTruthy() + expect(container.textContent).not.toContain('\\[') + }) + + it('renders TeX bracket math through the assistant-ui path', () => { + const { container } = render( + + + + ) + + expect(container.querySelector('.katex')).toBeTruthy() + expect(container.querySelector('.katex-display')).toBeFalsy() + }) }) diff --git a/web/src/components/SessionList.search-pin-divider.test.tsx b/web/src/components/SessionList.search-pin-divider.test.tsx new file mode 100644 index 00000000..7a79d84b --- /dev/null +++ b/web/src/components/SessionList.search-pin-divider.test.tsx @@ -0,0 +1,122 @@ +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { SessionSummary } from '@/types/api' +import { I18nProvider } from '@/lib/i18n-context' +import { ToastProvider } from '@/lib/toast-context' +import { SessionList } from './SessionList' + +const SEARCH_LABEL = 'Search sessions (title, path, Agent, machine name, ID, and more)' +const SEARCH_PLACEHOLDER = 'Search title/path/Agent/machine/ID…' +const PROJECT_PATH = '/work/proj' + +afterEach(() => { + cleanup() + localStorage.removeItem('hapi-session-preview-limit') + localStorage.removeItem('hapi-pin-in-progress-sessions') +}) + +function makeSession(overrides: Partial & { id: string }): SessionSummary { + return { + active: false, + thinking: false, + activeAt: 0, + updatedAt: 0, + metadata: null, + metadataVersion: 0, + agentStateVersion: 0, + todosUpdatedAt: 0, + todoProgress: null, + pendingRequestsCount: 0, + pendingRequestKinds: [], + pendingRequests: [], + backgroundTaskCount: 0, + futureScheduledMessageCount: 0, + nextScheduledAt: null, + model: null, + effort: null, + ...overrides, + } +} + +/** + * tiann #1842 repro: relevance sort interleaved pinned↔ordinary and the + * renderer drew a divider on every transition (two dividers in one group). + */ +function tiannPinDividerSessions(): SessionSummary[] { + return [ + makeSession({ + id: 'home-pinned', + pinned: true, + updatedAt: 400, + metadata: { path: PROJECT_PATH, name: 'Home pinned', flavor: 'codex' }, + }), + makeSession({ + id: 'home-ordinary', + updatedAt: 300, + metadata: { path: PROJECT_PATH, name: 'Home ordinary', flavor: 'codex' }, + }), + makeSession({ + id: 'homelab-pinned', + pinned: true, + updatedAt: 200, + metadata: { path: PROJECT_PATH, name: 'homelab pinned', flavor: 'codex' }, + }), + makeSession({ + id: 'homelab-ordinary', + updatedAt: 100, + metadata: { path: PROJECT_PATH, name: 'homelab ordinary', flavor: 'codex' }, + }), + ] +} + +function renderList(sessions: SessionSummary[]) { + return render( + + + + + + + + ) +} + +describe('SessionList search pin dividers', () => { + it('renders at most one pin divider in a group under relevance sort (tiann #1842)', () => { + renderList(tiannPinDividerSessions()) + + fireEvent.click(screen.getByRole('button', { name: SEARCH_LABEL })) + fireEvent.change(screen.getByPlaceholderText(SEARCH_PLACEHOLDER), { + target: { value: 'home' }, + }) + + // All four titles match; group stays open under search filtering. + expect(screen.getByRole('button', { name: /Home pinned/ })).toBeInTheDocument() + expect(screen.getByRole('button', { name: /Home ordinary/ })).toBeInTheDocument() + expect(screen.getByRole('button', { name: /homelab pinned/ })).toBeInTheDocument() + expect(screen.getByRole('button', { name: /homelab ordinary/ })).toBeInTheDocument() + + const projectHeader = screen.getByTitle(PROJECT_PATH) + const projectRoot = projectHeader.parentElement + expect(projectRoot).toBeTruthy() + const dividers = within(projectRoot as HTMLElement).getAllByTestId('session-pin-divider') + expect(dividers).toHaveLength(1) + }) +}) diff --git a/web/src/components/SessionList.tsx b/web/src/components/SessionList.tsx index bb5afac8..287a3b73 100644 --- a/web/src/components/SessionList.tsx +++ b/web/src/components/SessionList.tsx @@ -1,7 +1,13 @@ import { useEffect, useMemo, useRef, useState } from 'react' import type { SessionSummary } from '@/types/api' -import { isWildcardSearch, matchesSearchQuery } from '@hapi/protocol' import type { ApiClient } from '@/api/client' +import { + buildSessionSearchScoreIndex, + compareSessionsBySearchRelevance, + rankSessionGroupsBySearchRelevance, + sessionMatchesQuery, + sortSessionsBySearchRelevance, +} from '@/lib/sessionListSearch' import { useLongPress } from '@/hooks/useLongPress' import { usePlatform } from '@/hooks/usePlatform' import { useSessionActions } from '@/hooks/mutations/useSessionActions' @@ -550,32 +556,12 @@ function ToolbarCollapseIcon(props: { collapsed: boolean; className?: string }) } export { getSessionTitle } from '@/lib/sessionTitle' +export { sessionMatchesQuery } from '@/lib/sessionListSearch' export function normalizeSearch(value: string | null | undefined): string { return (value ?? '').trim().toLowerCase() } -export function sessionMatchesQuery(session: SessionSummary, query: string, machineLabel: string): boolean { - if (!query) return true - const searchableParts = [ - getSessionTitle(session), - getWorktreeSessionLabel(session), - session.id, - session.metadata?.path, - session.metadata?.worktree?.basePath, - session.metadata?.worktree?.worktreePath, - session.metadata?.name, - session.metadata?.summary?.text, - session.metadata?.flavor, - machineLabel, - ] - .filter((part): part is string => typeof part === 'string' && part.length > 0) - if (isWildcardSearch(query)) { - return searchableParts.some((part) => matchesSearchQuery(part, query)) - } - return searchableParts.join('\n').toLowerCase().includes(query) -} - export function getVisibleSessionPreview( sessions: SessionSummary[], @@ -1316,18 +1302,37 @@ export function SessionList(props: { () => new Set(allSessions.map(session => formatDateValue(new Date(session.updatedAt)))), [allSessions] ) + const hasTextQuery = normalizedQuery.length > 0 + const timeScopedSessions = useMemo( + () => timeRange === null + ? allSessions + : allSessions.filter(session => sessionMatchesTimeRange(session, timeRange)), + [allSessions, timeRange?.start, timeRange?.end] // eslint-disable-line react-hooks/exhaustive-deps + ) + const searchScoreIndex = useMemo( + () => hasTextQuery + ? buildSessionSearchScoreIndex(timeScopedSessions, normalizedQuery, resolveMachineLabel) + : null, + [hasTextQuery, timeScopedSessions, normalizedQuery, machineLabelsById] // eslint-disable-line react-hooks/exhaustive-deps + ) const visibleSessions = useMemo( - () => isFiltering - ? allSessions.filter(session => ( - sessionMatchesTimeRange(session, timeRange) - && sessionMatchesQuery( - session, - normalizedQuery, - resolveMachineLabel(session.metadata?.machineId ?? null) - ) - )) - : allSessions, - [allSessions, isFiltering, normalizedQuery, timeRange?.start, timeRange?.end, machineLabelsById] // eslint-disable-line react-hooks/exhaustive-deps + () => { + if (!isFiltering) return allSessions + const matched = hasTextQuery && searchScoreIndex + ? timeScopedSessions.filter(session => searchScoreIndex.matchedIds.has(session.id)) + : timeScopedSessions.filter(session => ( + sessionMatchesQuery( + session, + normalizedQuery, + resolveMachineLabel(session.metadata?.machineId ?? null) + ) + )) + if (hasTextQuery && searchScoreIndex) { + return sortSessionsBySearchRelevance(matched, searchScoreIndex) + } + return matched + }, + [allSessions, hasTextQuery, isFiltering, normalizedQuery, searchScoreIndex, timeScopedSessions, machineLabelsById] // eslint-disable-line react-hooks/exhaustive-deps ) const allGroups = useMemo( () => groupSessionsByDirectory(allSessions), @@ -1383,10 +1388,12 @@ export function SessionList(props: { [unreadFilteredSessions, activeMachineFilter] ) const globalPinnedSessions = useMemo(() => { - return machineFilteredSessions - .filter((session) => Boolean(session.globalPinned) && !personalPinnedSessionIds.has(session.id)) - .sort((a, b) => b.updatedAt - a.updatedAt) - }, [machineFilteredSessions, personalPinnedSessionIds]) + const pinned = machineFilteredSessions.filter((session) => Boolean(session.globalPinned) && !personalPinnedSessionIds.has(session.id)) + if (searchScoreIndex && hasTextQuery) { + return sortSessionsBySearchRelevance(pinned, searchScoreIndex) + } + return [...pinned].sort((a, b) => b.updatedAt - a.updatedAt) + }, [machineFilteredSessions, personalPinnedSessionIds, searchScoreIndex, hasTextQuery]) const personalPinnedSessions = useMemo(() => { return machineFilteredSessions .filter((session) => personalPinnedSessionIds.has(session.id)) @@ -1417,26 +1424,38 @@ export function SessionList(props: { } } const byRecent = (a: SessionSummary, b: SessionSummary) => b.updatedAt - a.updatedAt + const byRelevanceOrRecent = (a: SessionSummary, b: SessionSummary) => { + if (searchScoreIndex && hasTextQuery) { + return compareSessionsBySearchRelevance(a, b, searchScoreIndex) + } + return byRecent(a, b) + } for (const key of Object.keys(buckets) as RunningBucketKey[]) { - buckets[key].sort(byRecent) + buckets[key].sort(byRelevanceOrRecent) } return buckets - }, [machineFilteredSessions, pinActiveSessions, pinInProgressSessions, personalPinnedSessionIds]) + }, [machineFilteredSessions, pinActiveSessions, pinInProgressSessions, personalPinnedSessionIds, searchScoreIndex, hasTextQuery]) const runningSessionTotal = runningSessions.working.length + runningSessions.pending.length const activeSessionTotal = runningSessions.active.length const groups = useMemo( - () => groupSessionsByDirectory( - machineFilteredSessions.filter((session) => { - if (session.globalPinned || personalPinnedSessionIds.has(session.id)) return false - if (!session.pinned && ( - ((pinActiveSessions || pinInProgressSessions) && session.active) - || (pinInProgressSessions && isPinnedInProgressSession(session)) - )) return false - return true - }) - ), - [machineFilteredSessions, pinActiveSessions, pinInProgressSessions, personalPinnedSessionIds] + () => { + const grouped = groupSessionsByDirectory( + machineFilteredSessions.filter((session) => { + if (session.globalPinned || personalPinnedSessionIds.has(session.id)) return false + if (!session.pinned && ( + ((pinActiveSessions || pinInProgressSessions) && session.active) + || (pinInProgressSessions && isPinnedInProgressSession(session)) + )) return false + return true + }) + ) + if (searchScoreIndex && hasTextQuery) { + return rankSessionGroupsBySearchRelevance(grouped, searchScoreIndex) + } + return grouped + }, + [machineFilteredSessions, pinActiveSessions, pinInProgressSessions, personalPinnedSessionIds, searchScoreIndex, hasTextQuery] ) // Directory groups whose rows all floated to the pinned sections still // render an action-only header so copy-path / new-session-in-directory @@ -1733,6 +1752,7 @@ export function SessionList(props: {
{shouldShowPinnedDivider(visibleGroupSessions, index) ? (