diff --git a/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenQuestionCardUiTest.kt b/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenQuestionCardUiTest.kt index 5cea6c1b4e..7a3dd99cbe 100644 --- a/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenQuestionCardUiTest.kt +++ b/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenQuestionCardUiTest.kt @@ -9,6 +9,11 @@ import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performTextInput import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.height +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import java.time.Instant import org.junit.Assert.assertEquals @@ -44,6 +49,37 @@ class AidenQuestionCardUiTest { canRespond = true ) + @Test + fun longQuestionnaireKeepsLastAnswerAndSubmitReachableInSmallWindow() { + var submitted: AidenQuestionRespondRequest? = null + val longPrompt = prompt().copy(questions = (0..3).map { index -> + AidenRemoteQuestion( + question = "Choose the timing for task ${index + 1}", + header = "Task ${index + 1}", multiSelect = false, + options = listOf(option("Morning ${index + 1}"), option("Evening ${index + 1}")) + ) + }) + compose.setContent { + AidenTheme { + Box(Modifier.height(240.dp)) { + AidenQuestionCard(prompt = longPrompt, enabled = true, onSubmit = { submitted = it }) + } + } + } + compose.onNodeWithText("Morning 1").performScrollTo().performClick() + compose.onNodeWithText("4. Task 4").performScrollTo().performClick() + compose.onNodeWithText("Morning 1").assertDoesNotExist() + compose.onNodeWithText("Evening 4").performScrollTo().performClick() + compose.onNodeWithText("1. Task 1").performScrollTo().performClick() + compose.onNodeWithText("Morning 1").assertIsOn() + compose.onNodeWithText("4. Task 4").performScrollTo().performClick() + compose.onNodeWithText("Submit").performScrollTo().performClick() + compose.runOnIdle { + assertEquals(listOf(AidenQuestionAnswer.Option(0, "Morning 1"), AidenQuestionAnswer.Option(3, "Evening 4")), submitted?.answers) + assertEquals(false, submitted?.cancelled) + } + } + @Test fun questionCardSubmitsSingleChoiceAnswer() { var submitted: AidenQuestionRespondRequest? = null diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatDetailScreen.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatDetailScreen.kt index db8d680a3f..92335bacec 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatDetailScreen.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatDetailScreen.kt @@ -803,8 +803,8 @@ fun AidenChatDetailScreen( ) } - // 1:1 Parity iOS Glass Composer - AidenComposerView( + // A pending question occupies the composer without discarding its draft. + if (pendingQuestion == null) AidenComposerView( draft = draft, onDraftChange = { viewModel.updateDraft(it) }, onSend = { diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenQuestionCard.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenQuestionCard.kt index 96fb140b36..1bed94a581 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenQuestionCard.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenQuestionCard.kt @@ -1,5 +1,7 @@ package sbtbiswas.AidenOnTheGo.features.chat +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.background import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement @@ -10,6 +12,9 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width @@ -38,6 +43,7 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.SolidColor @@ -60,7 +66,7 @@ import androidx.compose.ui.res.stringResource import sbtbiswas.AidenOnTheGo.R /** `ask_user_question` prompt card (iOS parity: AidenQuestionCard). All - * questions render stacked; a non-blank custom draft overrides that question's + * questions appear one at a time; a non-blank custom draft overrides that question's * option selections, and unaddressed questions are sent as skipped. */ @Composable fun AidenQuestionCard( @@ -69,6 +75,7 @@ fun AidenQuestionCard( onSubmit: (AidenQuestionRespondRequest) -> Unit ) { val palette = AidenTheme.palette + var activeIndex by remember(prompt.id) { mutableStateOf(0) } val customAnswerDescription = stringResource(R.string.chat_question_custom_answer_cd) val typeSomethingDescription = stringResource(R.string.chat_question_type_something_cd) var selections by remember(prompt.id) { mutableStateOf(mapOf>()) } @@ -89,7 +96,10 @@ fun AidenQuestionCard( colors = CardDefaults.cardColors(containerColor = palette.raised), shape = MaterialTheme.shapes.extraLarge ) { - Column(modifier = Modifier.padding(14.dp)) { + Column(modifier = Modifier + .heightIn(max = (LocalConfiguration.current.screenHeightDp * 0.55f).dp) + .verticalScroll(rememberScrollState()) + .padding(14.dp)) { Row(verticalAlignment = Alignment.CenterVertically) { Icon( Icons.Default.QuestionMark, @@ -116,7 +126,23 @@ fun AidenQuestionCard( ) } } - prompt.questions.forEachIndexed { index, question -> + Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).selectableGroup()) { + prompt.questions.forEachIndexed { index, question -> + Text( + text = "${index + 1}. ${question.header}", + style = MaterialTheme.typography.labelLarge, + color = if (index == activeIndex) palette.foreground else palette.secondary, + modifier = Modifier + .clip(RoundedCornerShape(12.dp)) + .background(if (index == activeIndex) palette.canvas else palette.raised) + .selectable(selected = index == activeIndex, enabled = enabled, role = Role.Tab, + onClick = { activeIndex = index }) + .padding(horizontal = 12.dp, vertical = 14.dp) + ) + } + } + prompt.questions.getOrNull(activeIndex)?.let { question -> + val index = activeIndex Spacer(modifier = Modifier.height(10.dp)) Row(verticalAlignment = Alignment.CenterVertically) { Text( @@ -293,9 +319,16 @@ fun AidenQuestionCard( ) Spacer(modifier = Modifier.width(10.dp)) AidenPrimaryButton( - text = stringResource(R.string.chat_question_submit), - onClick = { onSubmit(AidenQuestionRespondRequest(cancelled = false, answers = answers)) }, - enabled = enabled && answers.isNotEmpty() + text = if (activeIndex < prompt.questions.lastIndex) { + stringResource(R.string.chat_question_next) + } else { + stringResource(R.string.chat_question_submit) + }, + onClick = { + if (activeIndex < prompt.questions.lastIndex) activeIndex += 1 + else onSubmit(AidenQuestionRespondRequest(cancelled = false, answers = answers)) + }, + enabled = enabled && (activeIndex < prompt.questions.lastIndex || answers.isNotEmpty()) ) } } diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 02dc1312bc..e7da41db34 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -809,6 +809,7 @@ This paired device cannot respond to prompts. Skip Submit + Next Approve task diff --git a/docs/testing/scheduled-task-question-audit-2026-10-06.md b/docs/testing/scheduled-task-question-audit-2026-10-06.md new file mode 100644 index 0000000000..c7d6df5b49 --- /dev/null +++ b/docs/testing/scheduled-task-question-audit-2026-10-06.md @@ -0,0 +1,47 @@ +# Scheduled tasks and question composer audit — 2026-10-06 + +Scope: conversational task creation, approval and persistence, pending-question ownership and display, desktop question composer, and the existing iOS/Android chat consumers. Changes are in this checkout; no release, installation replacement, saved-task mutation, or live scheduled execution was performed. + +## Confirmed failures and fixes + +1. **Approved tasks failed before dispatch.** Standard scheduling approval attached a hidden Symbol property to the model arguments. Assistant automation approval did the same for exact MCP bindings. Pi hashes arguments after approval and rejects non-JSON properties, so approving the task could immediately fail with “Pi runtime effect arguments are not a plain object.” Approval metadata now lives in invocation-scoped WeakMaps. Canonical Assistant arguments also omit an absent workspace instead of containing `undefined`. Exact approved model, workspace, permissions, and connector bindings remain enforced. The existing tool suite now reproduces both paths through the real Pi tool-call runner and argument digest, then verifies the saved record. + +2. **Desktop could miss questions belonging to phone-started runs.** The desktop restored remote approvals but never fetched the pending question. Desktop now restores it through document-guarded Electron IPC and submits it through its original main-process owner. The service checks chat identity, prompt identity, expiry, and the real answer parser; resolution remains one-shot. A stale response cannot clear a newer displayed prompt. The network API and mobile protocol revision are unchanged. + +3. **Question presentation diverged across clients.** Desktop used a separate card treatment; native clients listed every question and left the normal composer available. The question UI now occupies the composer area, uses desktop composer/shared button primitives and the native composer surface, and exposes one question at a time with numbered tabs. Custom drafts and selections survive tab changes. Desktop offers explicit Next/Submit and keyboard tab navigation. Native drafts remain keyed to the prompt. Bounded scrolling keeps long prompts and answer actions reachable. Dismissing/resolving restores the message composer without sending its draft. + +4. **Schedule suggestions still opened a control-heavy editor.** Suggested tasks now seed editable natural-language requests in chat. The existing manual setup remains available. No task is created merely by choosing a suggestion. + +5. **Generic approval UI hid useful schedule detail.** The desktop approval now presents the actual instructions/script, model, workspace/connector scope, timezone, notifications, scheduler-disabled/paused state, and desktop-awake requirement. Claimed schedule payloads that fail validation cannot be approved from this card. + +## Reference comparison + +Reviewed the official [Codex automations guide](https://learn.chatgpt.com/docs/automations?surface=app): describe work and timing conversationally, review the unattended scope, and make the local execution requirement clear. Also inspected the public [Codex request-user-input handler](https://github.com/openai/codex/blob/main/codex-rs/core/src/tools/handlers/request_user_input.rs) and Aiden's existing desktop UI inspiration/specimen. Implementation uses Aiden's existing tool contracts and semantic styles; no upstream code was copied. + +## Validation + +- Scheduling and automation suites: 158 and 182 tests passed. +- Question parser, coordinator, and rendered component suite: 21 tests passed; final rendered tab semantics tests also passed. +- Main-process remote-question tests exercise cross-chat rejection, invalid answers, expiry, one-shot resolution, and the phone-visible resolved state. Local adapter tests ensure phone-owned answers use host authority. +- Electron behavioral coverage: suggestion-to-chat draft; actual question → approval → persisted task with pinned provider/model; small-window tabs/custom-draft retention/keyboard navigation; restoring and answering a phone-owned question. All three focused conversational scheduling/question scenarios passed on the final full-file run. After tightening the scroll layout, the small-window tab test passed again with explicit checks that Submit is in the viewport and the card stays outside the sidebar. +- Android: 10 rendered question/schedule tests passed on the API 36.1 emulator, including four-question tab navigation and retained answers inside a 240 dp viewport. All 93 focused Chat/Question/Scheduled unit tests and Android lint passed. +- iOS: all 272 focused Chat and ScheduledTask tests passed, including the new draft-retention test for tab changes and invalid navigation. Simulator: iPhone 17 Pro, iOS 27, Xcode beta, signing disabled. This is simulator evidence, not physical-device/release acceptance. +- Root/e2e TypeScript checks, ESLint, production build, and `git diff --check` passed. The combined final remote-stream/adapter/IPC/dock/render suite passed 95 tests. React Doctor reported one index-key warning on question tabs; this is a reviewed false positive because question indexes are the immutable wire identity within a prompt, and the composer remounts on prompt identity changes. No rule was suppressed. + +## Test-run limitation + +During one desktop run alongside native verification, the existing exploration test and the question/approval/save test completed their assertions but Electron shutdown exceeded the harness's 35-second bound. The new tab/remote-question tests passed. No timeouts, retries, or flaky-test enforcement were relaxed. Local evidence: `/tmp/aiden-task-e2e3.log`; test artifacts under `test-results/e2e/`. On the single follow-up full-file run, the question/approval/save test and both question-UI tests passed; the exploration test still exceeded the shutdown bound (`/tmp/aiden-task-e2e-final.log`). The full-file run is therefore **3 passed, 1 teardown failure**, not green. The final layout-only question test separately passed (`/tmp/aiden-task-tabs-final.log`). Hosted follow-up is tracked in [PR #369](https://github.com/sambitcreate/aiden-agent/pull/369); these remain the historical local results. + +## Scope decisions + +Reviewed both native consumers and the onboarding feature gallery. This repairs existing advertised scheduling/questions rather than adding a setup capability; no onboarding illustration, permission expansion, API revision, or plan-status transition is needed. Scheduled work still requires the desktop runtime to be available. Existing saved-task/history data was inspected read-only and was not rewritten or executed. + +## PR review follow-up — 2026-10-07 + +- Restored iOS run cancellation during a pending question by sharing the same Stop control between both composers. It uses the existing ownership/connection/read-only/stopping gates and calls run cancellation without submitting or skipping a question. A hosted question-card test exercises that action and verifies only the run-cancel request is sent. +- Moved one-shot dictation launch consumption into the chat model. Removing/restoring the composer cannot restart capture, and a launch encountered while streaming or read-only is consumed without starting the microphone. The regression test exercises launch, pending-question presentation, and restored composer startup. +- Fixed a remote-adapter test whose overridden mock did not record calls; it now independently verifies the session chat/prompt scope and one host dispatch. +- The initial [hosted Electron shard](https://github.com/sambitcreate/aiden-agent/actions/runs/37568961729/job/112623416000) reported the compact-window tab test as flaky: the card measured at x=257 while the sidebar ended at x=272, then passed the runner's retry. A local diagnostic reproduction traced this to `EnvironmentWorkbench`: its hidden overflow held `scrollLeft=88`, moving the entire chat beneath the sidebar. That outer boundary now uses non-scrollable clipping; the transcript and panels retain their own scrolling. Custom-answer focus also prevents ancestor scrolling, and the layout assertion waits for settled geometry while preserving the same no-overlap requirement. The [Linux x64 gate](https://github.com/sambitcreate/aiden-agent/actions/runs/37568961729/job/112623119730) reported the same narrow-window test failure. No timeout was raised and no retries or flaky-test enforcement were changed. +- Local follow-up: all 274 iOS Chat/ScheduledTask tests passed, including the new cancellation and dictation tests; all six adapter tests passed. The final five Electron compact-window/workbench-focus tests and 22 focused layout/state/adapter/question unit tests passed. Production build, TypeScript, ESLint, and diff checks passed. The original broad desktop shutdown failures remain documented above. + +The next hosted run exposed an old iOS shipping-inventory assertion tied to the literal composer-local voice guard. Replaced that assertion with coverage in the existing read-only fixture XCTest: a launch request must never start capture. The full iOS release-policy suite and focused read-only/dictation simulator tests pass. Both review bots found no new issues in the production follow-up. diff --git a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift index 6b667678c1..cf7a67ff3e 100644 --- a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift +++ b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift @@ -1188,6 +1188,7 @@ final class AidenChatViewModel { @ObservationIgnored private var suppressesDraftPersistence = false @ObservationIgnored private var draftGeneration: UInt64 = 0 @ObservationIgnored private var composerGeneration: UInt64 = 0 + @ObservationIgnored private var didConsumeVoiceLaunch = false @ObservationIgnored private var uploadTask: Task? @ObservationIgnored private var ownedUploadReferences: [String: (AidenAttachmentReference, AidenRemoteRequestContext, AidenRemoteClient)] = [:] @ObservationIgnored private var attachmentCleanupTasks: [String: Task] = [:] @@ -3023,6 +3024,15 @@ final class AidenChatViewModel { && installation.hasNegotiatedAccess(to: .botWrite)) } + /// A launch intent belongs to the chat lifetime, not a removable composer. + /// Consume before awaiting capture so remounts cannot replay it. + func startVoiceForLaunch(if requested: Bool, start: () async -> Void) async { + guard requested, !didConsumeVoiceLaunch else { return } + didConsumeVoiceLaunch = true + guard !isReadOnlyPresentation, !isRemoved, !isStreaming, pendingQuestion == nil else { return } + await start() + } + @discardableResult func stop() async -> Bool { if activeStreamID == nil, foreignRun != nil, !isRemoved { return await stopForeignRun() } @@ -4765,6 +4775,11 @@ struct AidenChatDetailView: View { .onChange(of: botPrimarySupportsImages, initial: true) { _, supportsImages in model.setBotPrimarySupportsImages(supportsImages) } + .onChange(of: model.pendingQuestion?.id) { _, id in + guard id != nil else { return } + composerIsFocused = false + attachmentPicker.dismiss() + } .onChange(of: model.isStreaming) { _, isStreaming in guard isStreaming else { return } attachmentPicker.dismiss() @@ -5076,16 +5091,34 @@ struct AidenChatDetailView: View { .padding(.horizontal, 4) .padding(.bottom, 6) } - AidenComposerView( - model: model, - autoStartVoice: autoStartVoice, - composerFocus: $composerIsFocused, - attachmentPicker: attachmentPicker, - motionNamespace: attachmentMotionNamespace, - canToggleAttachments: canToggleAttachmentPicker, - onToggleAttachmentPicker: toggleAttachmentPicker, - placeholder: botToolsModel?.bot.map { "Ask \($0.name)" } ?? "Message Aiden" - ) + if let question = model.pendingQuestion { + AidenQuestionCard( + model: model, + prompt: question, + onSubmit: { request in + Task { + await model.respondToQuestion( + request, + promptID: question.id, + idempotencyKey: UUID() + ) + } + } + ) + .disabled(!model.isConnected || model.isReadOnlyPresentation || model.isRespondingToQuestion || model.isStopping) + .id(question.id) + } else { + AidenComposerView( + model: model, + autoStartVoice: autoStartVoice, + composerFocus: $composerIsFocused, + attachmentPicker: attachmentPicker, + motionNamespace: attachmentMotionNamespace, + canToggleAttachments: canToggleAttachmentPicker, + onToggleAttachmentPicker: toggleAttachmentPicker, + placeholder: botToolsModel?.bot.map { "Ask \($0.name)" } ?? "Message Aiden" + ) + } } .disabled(model.isReadOnlyPresentation) .padding(.horizontal, 16) @@ -7010,23 +7043,6 @@ private struct AidenLiveResponseView: View { .id(approval.id) } - if let question = model.pendingQuestion { - AidenQuestionCard( - prompt: question, - onSubmit: { request in - Task { - await model.respondToQuestion( - request, - promptID: question.id, - idempotencyKey: UUID() - ) - } - } - ) - .disabled(!model.isConnected || model.isReadOnlyPresentation || model.isRespondingToQuestion || model.isStopping) - .id(question.id) - } - if chronologicalRows == nil && !visibleText.isEmpty { AidenMarkdownView(content: visibleText) .padding(presentationStyle == .botMessages ? 12 : 0) @@ -7232,205 +7248,218 @@ struct AidenQuestionCard: View { @Environment(\.aidenPalette) private var palette @Environment(\.aidenReduceMotion) private var reduceMotion + /// The workspace chat whose run the card can stop. Bot session questions have no run to stop. + var model: AidenChatViewModel? = nil let prompt: AidenPendingQuestion let onSubmit: (AidenQuestionRespondRequest) -> Void - @State private var selections: [Int: Set] = [:] - @State private var customDrafts: [Int: String] = [:] - @State private var customOpen: Set = [] + @State private var draft = AidenQuestionComposerDraft() - private let shape = RoundedRectangle(cornerRadius: 14, style: .continuous) + var stopButton: AidenChatStopButton? { model.map { AidenChatStopButton(model: $0) } } - private var answers: [AidenQuestionAnswer] { - AidenQuestionAnswerDraft.answers( - for: prompt.questions, - selections: selections, - customAnswers: customDrafts - ) - } - - private func toggle(_ label: String, questionIndex: Int, multiSelect: Bool) { - selections = AidenQuestionAnswerDraft.toggled( - selections: selections, - questionIndex: questionIndex, - label: label, - multiSelect: multiSelect - ) - } + private var answers: [AidenQuestionAnswer] { draft.answers(for: prompt.questions) } private func binding(for index: Int) -> Binding { Binding( - get: { customDrafts[index] ?? "" }, - set: { customDrafts[index] = $0.isEmpty ? nil : $0 } + get: { draft.customAnswers[index] ?? "" }, + set: { draft.customAnswers[index] = $0.isEmpty ? nil : $0 } ) } var body: some View { - VStack(alignment: .leading, spacing: 10) { - HStack(alignment: .top, spacing: 10) { - Image(systemName: "questionmark.bubble") - .font(.system(size: 15, weight: .semibold)) - .foregroundStyle(palette.accent) - .frame(width: 32, height: 32) - .background(palette.accent.opacity(0.12), in: Circle()) - .accessibilityHidden(true) + ScrollView { + VStack(alignment: .leading, spacing: 10) { + HStack(alignment: .top, spacing: 10) { + Image(systemName: "questionmark.bubble") + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(palette.accent) + .frame(width: 32, height: 32) + .background(palette.accent.opacity(0.12), in: Circle()) + .accessibilityHidden(true) - VStack(alignment: .leading, spacing: 2) { - Text("Aiden needs your input") - .font(.subheadline.weight(.semibold)) - .foregroundStyle(palette.foreground) + VStack(alignment: .leading, spacing: 2) { + Text("Aiden needs your input") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(palette.foreground) - Text(prompt.questions.count > 1 - ? String(localized: "Answer what you can — unanswered questions are skipped.") - : String(localized: "Choose an option or type your own answer.")) - .font(.caption) - .foregroundStyle(palette.secondary) - .fixedSize(horizontal: false, vertical: true) + Text(prompt.questions.count > 1 + ? String(localized: "Answer what you can — unanswered questions are skipped.") + : String(localized: "Choose an option or type your own answer.")) + .font(.caption) + .foregroundStyle(palette.secondary) + .fixedSize(horizontal: false, vertical: true) + } + Spacer(minLength: 0) + if let stopButton { stopButton } } - } - ForEach(Array(prompt.questions.enumerated()), id: \.offset) { index, question in - VStack(alignment: .leading, spacing: 8) { - HStack(spacing: 6) { - Text(question.header) - .font(.caption2.weight(.semibold)) - .foregroundStyle(palette.secondary) - .padding(.horizontal, 8) - .padding(.vertical, 3) - .background(palette.canvas, in: Capsule()) - if question.multiSelect { - Text("Select all that apply") - .font(.caption2) - .foregroundStyle(palette.secondary) + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 4) { + ForEach(Array(prompt.questions.enumerated()), id: \.offset) { index, question in + Button { draft.move(to: index, questions: prompt.questions) } label: { + Text("\(index + 1). \(question.header)") + .font(.caption.weight(.semibold)) + .foregroundStyle(index == draft.activeIndex ? palette.foreground : palette.secondary) + .padding(.horizontal, 12) + .frame(minHeight: 44) + .background(index == draft.activeIndex ? palette.canvas : .clear, + in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + } + .buttonStyle(.plain) + .accessibilityAddTraits(index == draft.activeIndex ? .isSelected : []) + .accessibilityLabel("Question \(index + 1) of \(prompt.questions.count), \(question.header)") } } - .accessibilityHidden(true) + } + ForEach(Array(prompt.questions.enumerated()).filter { $0.offset == draft.activeIndex }, id: \.offset) { index, question in + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 6) { + Text(question.header) + .font(.caption2.weight(.semibold)) + .foregroundStyle(palette.secondary) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background(palette.canvas, in: Capsule()) + if question.multiSelect { + Text("Select all that apply") + .font(.caption2) + .foregroundStyle(palette.secondary) + } + } + .accessibilityHidden(true) - Text(question.question) - .font(.callout.weight(.medium)) - .foregroundStyle(palette.foreground) - .fixedSize(horizontal: false, vertical: true) + Text(question.question) + .font(.callout.weight(.medium)) + .foregroundStyle(palette.foreground) + .fixedSize(horizontal: false, vertical: true) - ForEach(question.options, id: \.label) { option in - let selected = selections[index]?.contains(option.label) == true - Button { - withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.15)) { - toggle(option.label, questionIndex: index, multiSelect: question.multiSelect) - } - } label: { - HStack(alignment: .top, spacing: 10) { - Image(systemName: question.multiSelect - ? (selected ? "checkmark.square.fill" : "square") - : (selected ? "checkmark.circle.fill" : "circle")) - .font(.system(size: 16)) - .foregroundStyle(selected ? palette.accent : palette.secondary) - .frame(width: 20) - .accessibilityHidden(true) - VStack(alignment: .leading, spacing: 2) { - Text(option.label) - .font(.callout) - .foregroundStyle(palette.foreground) - Text(option.description) - .font(.caption) - .foregroundStyle(palette.secondary) - .fixedSize(horizontal: false, vertical: true) + ForEach(question.options, id: \.label) { option in + let selected = draft.selections[index]?.contains(option.label) == true + Button { + withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.15)) { + draft.toggle(option.label, questions: prompt.questions) } - Spacer(minLength: 0) + } label: { + HStack(alignment: .top, spacing: 10) { + Image(systemName: question.multiSelect + ? (selected ? "checkmark.square.fill" : "square") + : (selected ? "checkmark.circle.fill" : "circle")) + .font(.system(size: 16)) + .foregroundStyle(selected ? palette.accent : palette.secondary) + .frame(width: 20) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 2) { + Text(option.label) + .font(.callout) + .foregroundStyle(palette.foreground) + Text(option.description) + .font(.caption) + .foregroundStyle(palette.secondary) + .fixedSize(horizontal: false, vertical: true) + } + Spacer(minLength: 0) + } + .padding(.horizontal, 10) + .padding(.vertical, 8) + .contentShape(Rectangle()) } - .padding(.horizontal, 10) - .padding(.vertical, 8) - .contentShape(Rectangle()) + .buttonStyle(.plain) + .background( + selected ? palette.accent.opacity(0.10) : palette.canvas, + in: RoundedRectangle(cornerRadius: 10, style: .continuous) + ) + .accessibilityLabel(option.label) + .accessibilityValue(selected + ? String(localized: "Selected") + : String(localized: "Not selected")) + .accessibilityHint(option.description) + .accessibilityAddTraits(selected ? .isSelected : []) } - .buttonStyle(.plain) - .background( - selected ? palette.accent.opacity(0.10) : palette.canvas, - in: RoundedRectangle(cornerRadius: 10, style: .continuous) - ) - .accessibilityLabel(option.label) - .accessibilityValue(selected - ? String(localized: "Selected") - : String(localized: "Not selected")) - .accessibilityHint(option.description) - .accessibilityAddTraits(selected ? .isSelected : []) - } - if customOpen.contains(index) { - TextField( - String(localized: "Type your answer"), - text: binding(for: index), - axis: .vertical - ) - .font(.callout) - .lineLimit(1...4) - .padding(.horizontal, 10) - .padding(.vertical, 8) - .background(palette.canvas, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) - .accessibilityLabel(String(localized: "Custom answer")) - .accessibilityHint(String(localized: "Overrides the selected options for this question")) - } else { - Button { - customOpen.insert(index) - } label: { - Label("Type something.", systemImage: "text.cursor") - .font(.caption.weight(.medium)) - .foregroundStyle(palette.secondary) - .frame(maxWidth: .infinity, alignment: .leading) + if draft.customOpen.contains(index) { + TextField( + String(localized: "Type your answer"), + text: binding(for: index), + axis: .vertical + ) + .font(.callout) + .lineLimit(1...4) .padding(.horizontal, 10) .padding(.vertical, 8) - .contentShape(Rectangle()) + .background(palette.canvas, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + .accessibilityLabel(String(localized: "Custom answer")) + .accessibilityHint(String(localized: "Overrides the selected options for this question")) + } else { + Button { + draft.customOpen.insert(index) + } label: { + Label("Type something.", systemImage: "text.cursor") + .font(.caption.weight(.medium)) + .foregroundStyle(palette.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 10) + .padding(.vertical, 8) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityHint(String(localized: "Shows a field for a custom answer")) } - .buttonStyle(.plain) - .accessibilityHint(String(localized: "Shows a field for a custom answer")) } + .accessibilityElement(children: .contain) } - .accessibilityElement(children: .contain) - } - if !prompt.canRespond { - Label("This paired device cannot respond to prompts.", systemImage: "lock.fill") - .font(.caption) - .foregroundStyle(palette.secondary) - } else { - HStack(spacing: 8) { - Spacer(minLength: 0) + if !prompt.canRespond { + Label("This paired device cannot respond to prompts.", systemImage: "lock.fill") + .font(.caption) + .foregroundStyle(palette.secondary) + } else { + HStack(spacing: 8) { + Spacer(minLength: 0) - Button { - onSubmit(AidenQuestionRespondRequest(cancelled: true, answers: [])) - } label: { - Text("Skip") - .font(.caption.weight(.semibold)) - .foregroundStyle(palette.foreground) - .padding(.horizontal, 13) - .frame(height: 34) - .aidenApprovalActionGlass() - } - .buttonStyle(.plain) - .padding(.vertical, 5) - .accessibilityHint(String(localized: "Dismisses the prompt without answers")) + Button { + onSubmit(AidenQuestionRespondRequest(cancelled: true, answers: [])) + } label: { + Text("Skip") + .font(.caption.weight(.semibold)) + .foregroundStyle(palette.foreground) + .padding(.horizontal, 13) + .frame(height: 34) + .aidenApprovalActionGlass() + } + .buttonStyle(.plain) + .padding(.vertical, 5) + .accessibilityHint(String(localized: "Dismisses the prompt without answers")) - Button { - onSubmit(AidenQuestionRespondRequest(cancelled: false, answers: answers)) - } label: { - Text("Submit") - .font(.caption.weight(.semibold)) - .foregroundStyle(palette.canvas) - .padding(.horizontal, 13) - .frame(height: 34) - .aidenApprovalActionGlass(tint: palette.accent) + Button { + if draft.activeIndex < prompt.questions.count - 1 { + draft.move(to: draft.activeIndex + 1, questions: prompt.questions) + } else { + onSubmit(AidenQuestionRespondRequest(cancelled: false, answers: answers)) + } + } label: { + Text(draft.activeIndex < prompt.questions.count - 1 ? "Next" : "Submit") + .font(.caption.weight(.semibold)) + .foregroundStyle(palette.canvas) + .padding(.horizontal, 13) + .frame(height: 34) + .aidenApprovalActionGlass(tint: palette.accent) + } + .buttonStyle(.plain) + .padding(.vertical, 5) + .disabled(draft.activeIndex == prompt.questions.count - 1 && answers.isEmpty) + .opacity(draft.activeIndex == prompt.questions.count - 1 && answers.isEmpty ? 0.5 : 1) + .accessibilityHint(draft.activeIndex < prompt.questions.count - 1 + ? String(localized: "Moves to the next question and keeps your answers") + : answers.isEmpty + ? String(localized: "Select an option or type an answer first") + : String(localized: "Sends your answers to your Mac")) } - .buttonStyle(.plain) - .padding(.vertical, 5) - .disabled(answers.isEmpty) - .opacity(answers.isEmpty ? 0.5 : 1) - .accessibilityHint(answers.isEmpty - ? String(localized: "Select an option or type an answer first") - : String(localized: "Sends your answers to your Mac")) } } + .padding(12) } - .padding(12) - .background(palette.raised, in: shape) - .overlay(shape.stroke(palette.foreground.opacity(0.08), lineWidth: 0.5)) + .frame(maxHeight: 360) + .aidenComposerGlass() .shadow(color: palette.foreground.opacity(0.08), radius: 8, y: 3) .accessibilityElement(children: .contain) } @@ -7662,6 +7691,32 @@ private struct AidenToolActivityCard: View { } } +/// Shared by the message and question composers so cancellation remains reachable. +struct AidenChatStopButton: View { + @Environment(\.aidenPalette) private var palette + @Bindable var model: AidenChatViewModel + + var canStop: Bool { model.canControlCurrentRun && !model.isStopping } + + @discardableResult + func stop() async -> Bool { await model.stop() } + + var body: some View { + if model.isStreaming { + Button { Task { await stop() } } label: { + Image(systemName: "stop.fill") + .frame(width: 30, height: 30) + .background(palette.foreground, in: Circle()) + .foregroundStyle(palette.canvas) + .frame(width: 44, height: 44) + } + .buttonStyle(.plain) + .disabled(!canStop) + .accessibilityLabel(model.isStopping ? "Stopping response" : "Stop response") + } + } +} + private struct AidenComposerView: View { @Environment(\.colorScheme) private var colorScheme @Environment(\.aidenPalette) private var palette @@ -7676,7 +7731,6 @@ private struct AidenComposerView: View { let onToggleAttachmentPicker: () -> Void var placeholder = "Message Aiden" @State private var voiceInput = ComposerVoiceInputController() - @State private var didAutoStartVoice = false var body: some View { VStack(alignment: .leading, spacing: 6) { @@ -7927,16 +7981,7 @@ private struct AidenComposerView: View { if model.showsRunInputOptions { runInputPill } - Button { Task { await model.stop() } } label: { - Image(systemName: "stop.fill") - .frame(width: 30, height: 30) - .background(palette.foreground, in: Circle()) - .foregroundStyle(palette.canvas) - .frame(width: 44, height: 44) - } - .buttonStyle(.plain) - .disabled(!model.canControlCurrentRun || model.isStopping) - .accessibilityLabel(model.isStopping ? "Stopping response" : "Stop response") + AidenChatStopButton(model: model) } else { Button { voiceInput.stopBeforeSubmittingDraft() @@ -7983,14 +8028,14 @@ private struct AidenComposerView: View { value: visiblePendingAttachments.map(\.id) + attachmentPicker.committingAssets.map(\.localIdentifier) ) .task { - guard !model.isReadOnlyPresentation, autoStartVoice, !didAutoStartVoice else { return } - didAutoStartVoice = true - model.readAloud.stop() - await voiceInput.toggle( - currentDraft: model.draft, - updateDraft: { model.draft = $0 }, - macTranscriber: model.transcribeMacSpeech - ) + await model.startVoiceForLaunch(if: autoStartVoice) { + model.readAloud.stop() + await voiceInput.toggle( + currentDraft: model.draft, + updateDraft: { model.draft = $0 }, + macTranscriber: model.transcribeMacSpeech + ) + } } .onReceive(NotificationCenter.default.publisher(for: .aidenStopDictationForReadAloud)) { _ in voiceInput.cancelDiscardingRecording() diff --git a/ios/AidenOnTheGo/Models/AidenChat.swift b/ios/AidenOnTheGo/Models/AidenChat.swift index 33b7b64a40..7fb6ba31f4 100644 --- a/ios/AidenOnTheGo/Models/AidenChat.swift +++ b/ios/AidenOnTheGo/Models/AidenChat.swift @@ -2295,6 +2295,31 @@ enum AidenPendingQuestionResolution { } } +/// Owns all question drafts while the composer displays one page at a time. +struct AidenQuestionComposerDraft { + private(set) var activeIndex = 0 + var selections: [Int: Set] = [:] + var customAnswers: [Int: String] = [:] + var customOpen: Set = [] + + mutating func move(to index: Int, questions: [AidenRemoteQuestion]) { + guard questions.indices.contains(index) else { return } + activeIndex = index + } + + mutating func toggle(_ label: String, questions: [AidenRemoteQuestion]) { + guard questions.indices.contains(activeIndex) else { return } + selections = AidenQuestionAnswerDraft.toggled( + selections: selections, questionIndex: activeIndex, label: label, + multiSelect: questions[activeIndex].multiSelect + ) + } + + func answers(for questions: [AidenRemoteQuestion]) -> [AidenQuestionAnswer] { + AidenQuestionAnswerDraft.answers(for: questions, selections: selections, customAnswers: customAnswers) + } +} + /// Builds the wire answers from the card's selection state. A non-empty custom /// draft wins over option selections for that question; questions left /// unaddressed are omitted so the host records them as skipped. diff --git a/ios/AidenOnTheGoTests/AidenChatTests.swift b/ios/AidenOnTheGoTests/AidenChatTests.swift index 2c77ce39b0..f23fbe4576 100644 --- a/ios/AidenOnTheGoTests/AidenChatTests.swift +++ b/ios/AidenOnTheGoTests/AidenChatTests.swift @@ -744,6 +744,60 @@ final class AidenChatTests: XCTestCase { XCTAssertEqual(model.streamState, .waitingForApproval) } + @MainActor + func testQuestionComposerStopCancelsRunWithoutSubmittingAnAnswer() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-question-stop-\(UUID())") + defer { try? FileManager.default.removeItem(at: root); AidenChatProgressLifecycleURLProtocol.reset() } + let (model, _, _) = try await makeControlModel(mode: .questions, root: root) + try await waitUntil { model.pendingQuestion != nil } + let card = AidenQuestionCard(model: model, prompt: try XCTUnwrap(model.pendingQuestion)) { _ in + XCTFail("Stopping a run must not submit or skip the question") + } + let host = UIHostingController(rootView: card.frame(width: 320)) + host.loadViewIfNeeded() + XCTAssertGreaterThanOrEqual(host.sizeThatFits(in: CGSize(width: 320, height: 400)).height, 44) + let stopButton = try XCTUnwrap(card.stopButton) + XCTAssertTrue(stopButton.canStop) + let writesBeforeStop = AidenChatProgressLifecycleURLProtocol.postPaths + model.setAllowsMutations(false) + XCTAssertFalse(stopButton.canStop) + let denied = await stopButton.stop() + XCTAssertFalse(denied) + XCTAssertEqual(AidenChatProgressLifecycleURLProtocol.postPaths, writesBeforeStop) + model.setAllowsMutations(true) + let stopped = await stopButton.stop() + XCTAssertTrue(stopped) + XCTAssertEqual(model.streamState, .cancelled) + XCTAssertNil(model.pendingQuestion) + XCTAssertFalse(stopButton.canStop) + XCTAssertEqual(Array(AidenChatProgressLifecycleURLProtocol.postPaths.dropFirst(writesBeforeStop.count)), [ + "/api/aiden/v1/streams/stream-control/cancel" + ]) + } + + @MainActor + func testDictationLaunchCannotReplayAfterQuestionComposerReturns() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-question-voice-\(UUID())") + defer { try? FileManager.default.removeItem(at: root); AidenChatProgressLifecycleURLProtocol.reset() } + let cache = AidenChatCache(root: root) + let model = try await makeProgressLifecycleModel(mode: .questions, cache: cache) + var captureStarts = 0 + await model.startVoiceForLaunch(if: false) { captureStarts += 1 } + await model.startVoiceForLaunch(if: true) { captureStarts += 1 } + XCTAssertEqual(captureStarts, 1) + try await cache.saveActiveStream(.init(deviceId: "device-progress-lifecycle", streamId: "stream-control", turnId: "turn-control", lastSequence: 0), instanceId: "instance-progress-lifecycle", chatId: model.chat.id, chatWriteToken: cache.reserveChatWrite()) + await model.load(observeProgress: false) + try await waitUntil { model.pendingQuestion != nil } + await model.startVoiceForLaunch(if: true) { captureStarts += 1 } + let stopped = await model.stop() + XCTAssertTrue(stopped) + XCTAssertNil(model.pendingQuestion) + XCTAssertFalse(model.isStreaming) + // The restored composer's startup task sees the same launch flag. + await model.startVoiceForLaunch(if: true) { captureStarts += 1 } + XCTAssertEqual(captureStarts, 1) + } + @MainActor func testMismatchedApprovalReceiptCannotReplaceNewerRequest() async throws { try await exerciseControlResponse(stop: false, nextApproval: "approval-next", mode: .mismatchedApproval) @@ -7326,6 +7380,8 @@ final class AidenChatTests: XCTestCase { func testReadOnlyFixtureChatRejectsEveryLiveEntryPointWithoutMutatingItsChat() async { let chat = sampleChat() let model = AidenChatViewModel(readOnlyFixture: chat) + var captureStarts = 0 + await model.startVoiceForLaunch(if: true) { captureStarts += 1 } XCTAssertFalse(model.isConnected) XCTAssertFalse(model.canSend) @@ -7347,6 +7403,7 @@ final class AidenChatTests: XCTestCase { XCTAssertEqual(model.draft, "This must stay local") XCTAssertTrue(model.pendingAttachments.isEmpty) XCTAssertNil(model.presentedError) + XCTAssertEqual(captureStarts, 0, "A read-only chat cannot start microphone capture") } #endif @@ -7490,6 +7547,8 @@ private final class AidenChatProgressLifecycleURLProtocol: URLProtocol, @uncheck nonisolated(unsafe) private static var _approvalReadCount = 0 static var approvalReadCount: Int { lock.withLock { _approvalReadCount } } static var controlWriteCount: Int { lock.withLock { _controlWriteCount } } + nonisolated(unsafe) private static var _postPaths: [String] = [] + static var postPaths: [String] { lock.withLock { _postPaths } } static func setApprovalID(_ id: String) { lock.withLock { approvalID = id } } nonisolated(unsafe) private static var approvalResolved = false /// The Mac resolved the approval: later approval reads return none. @@ -7595,6 +7654,7 @@ private final class AidenChatProgressLifecycleURLProtocol: URLProtocol, @uncheck lock.lock() self.mode = mode _controlWriteCount = 0 + _postPaths = [] approvalID = "approval-current" approvalReadFails = false approvalResolved = false @@ -7622,6 +7682,7 @@ private final class AidenChatProgressLifecycleURLProtocol: URLProtocol, @uncheck return } let path = request.url?.path ?? "" + if request.httpMethod == "POST" { Self.lock.withLock { Self._postPaths.append(path) } } if path.contains("/attachments/"), request.httpMethod == "DELETE" { Self.lock.withLock { Self._attachmentDeleteCount += 1 } } if path.hasSuffix("/attachments"), request.httpMethod == "POST" { Self.lock.withLock { Self._uploadRequestCount += 1 } } if path.hasSuffix("/turns") { Self.lock.withLock { Self._turnRequestCount += 1 } } @@ -7689,7 +7750,9 @@ private final class AidenChatProgressLifecycleURLProtocol: URLProtocol, @uncheck """.utf8)) case "/api/aiden/v1/approvals/approval-current/respond", "/api/aiden/v1/streams/stream-control/cancel": Self.lock.withLock { Self._controlWriteCount += 1 } - if Self.lock.withLock({ Self.mode == .mismatchedApproval }) { + if Self.lock.withLock({ Self.mode == .questions }), path.hasSuffix("/cancel") { + result = Self.response(for: request, status: 202, contentType: "application/json", data: Data(#"{"streamId":"stream-control","chatId":"chat-progress-lifecycle","turnId":"turn-control","state":"cancelled","lastSequence":1,"updatedAt":"2026-09-22T12:00:01Z"}"#.utf8)) + } else if Self.lock.withLock({ Self.mode == .mismatchedApproval }) { result = Self.response(for: request, status: 200, contentType: "application/json", data: Data(#"{"approvalId":"approval-other","decision":"allow","resolvedAt":"2026-09-22T12:00:00Z"}"#.utf8)) } else if Self.lock.withLock({ Self.mode == .mismatchedStop }) { result = Self.response(for: request, status: 202, contentType: "application/json", data: Data(#"{"streamId":"stream-other","chatId":"chat-progress-lifecycle","turnId":"turn-control","state":"reconciling","lastSequence":0,"updatedAt":"2026-09-22T12:00:00Z"}"#.utf8)) @@ -9362,6 +9425,26 @@ extension AidenChatTests { ) } + func testQuestionTabsRetainCustomAndMultiSelectAnswersWhenRevisited() { + let questions = [questionFixture(), questionFixture(multiSelect: true)] + var draft = AidenQuestionComposerDraft() + draft.customOpen.insert(0) + draft.customAnswers[0] = " Make it 2 mm " + draft.move(to: 1, questions: questions) + draft.toggle("0.5 mm", questions: questions) + draft.toggle("1.0 mm", questions: questions) + draft.move(to: 0, questions: questions) + XCTAssertEqual(draft.activeIndex, 0) + XCTAssertTrue(draft.customOpen.contains(0)) + XCTAssertEqual(draft.customAnswers[0], " Make it 2 mm ") + draft.move(to: 7, questions: questions) + XCTAssertEqual(draft.activeIndex, 0) + XCTAssertEqual(draft.answers(for: questions), [ + .custom(questionIndex: 0, answer: "Make it 2 mm"), + .multi(questionIndex: 1, selected: ["0.5 mm", "1.0 mm"]), + ]) + } + func testQuestionAnswerDraftBuildsWireAnswersInOrder() { let questions = [questionFixture(), questionFixture(multiSelect: true)] let answers = AidenQuestionAnswerDraft.answers( diff --git a/main/handlers/aiden-remote.ts b/main/handlers/aiden-remote.ts index 5f9f23e380..dea42c8548 100644 --- a/main/handlers/aiden-remote.ts +++ b/main/handlers/aiden-remote.ts @@ -47,6 +47,27 @@ async function settingsSnapshot(): Promise { export function registerAidenRemoteHandlers(): void { ipcMain.handle("remote:get", settingsSnapshot); + ipcMain.handle("remote:getPendingQuestion", async (event, chatId: unknown) => { + const owner = rendererDocumentOwner(event, () => new Error("Questions require the active application document.")); + const question = (await getAidenRemoteRuntime()).pendingQuestionForChat( + parseAidenRemoteScopedIdentifier(chatId), + ); + if (owner.isDestroyed()) throw new Error("The renderer document is no longer active."); + return question ? { ...question, version: 1, source: "remote" } : null; + }); + + ipcMain.handle("remote:respondQuestionFromHost", async (event, chatId: unknown, promptId: unknown, response: unknown) => { + const owner = rendererDocumentOwner(event, () => new Error("Questions require the active application document.")); + const runtime = await getAidenRemoteRuntime(); + if (owner.isDestroyed()) throw new Error("The renderer document is no longer active."); + const resolved = runtime.respondQuestionFromHost( + parseAidenRemoteScopedIdentifier(chatId), + parseAidenRemoteScopedIdentifier(promptId), + response, + ); + return { status: resolved ? "answered" : "elsewhere" }; + }); + ipcMain.handle("remote:getPendingApproval", async (event, chatId: unknown) => { const owner = rendererDocumentOwner( event, diff --git a/main/services/aiden-remote-service-main.ts b/main/services/aiden-remote-service-main.ts index ab104baff5..c2a2412cd8 100644 --- a/main/services/aiden-remote-service-main.ts +++ b/main/services/aiden-remote-service-main.ts @@ -158,7 +158,7 @@ import { import { hostRunRegistry } from "./host-runs-main.js"; import { gitCachedRepositoryIdentity } from "./git.js"; import { projectAidenRemoteWorkspace } from "./aiden-remote-workspaces.js"; -import { aidenRemoteHostPlatform } from "./aiden-remote-protocol.js"; +import { aidenRemoteHostPlatform, type AidenRemotePendingQuestion } from "./aiden-remote-protocol.js"; import type { ToolApprovalScope } from "../../renderer/shared/tool-approval-scope.js"; const STATE_FILE = "aiden-remote-v1.json"; @@ -281,6 +281,8 @@ export interface AidenRemoteRuntime { approvedRoots: AidenRemoteApprovedRootService; revokeDevice(deviceId: string): Promise; pendingApprovalForChat(chatId: string): AidenRemotePendingApproval | null; + pendingQuestionForChat(chatId: string): AidenRemotePendingQuestion | null; + respondQuestionFromHost(chatId: string, promptId: string, response: unknown): boolean; respondApprovalFromHost( chatId: string, approvalId: string, @@ -1073,6 +1075,9 @@ async function createRuntime(): Promise { return revoked; }, pendingApprovalForChat: (chatId) => activeStreams?.pendingApprovalForChat(chatId) ?? null, + pendingQuestionForChat: (chatId) => activeStreams?.pendingQuestionForChat(chatId) ?? null, + respondQuestionFromHost: (chatId, promptId, response) => + activeStreams?.respondQuestionFromHost(chatId, promptId, response) ?? false, respondApprovalFromHost: (chatId, approvalId, decision, scope) => activeStreams?.respondApprovalFromHost(chatId, approvalId, decision, scope) ?? false, }; diff --git a/main/services/aiden-remote-streams.test.ts b/main/services/aiden-remote-streams.test.ts index 763f40d0c0..fbde1c3aa9 100644 --- a/main/services/aiden-remote-streams.test.ts +++ b/main/services/aiden-remote-streams.test.ts @@ -1678,6 +1678,35 @@ test("remote question prompts bind to their stream and resolve once", async () = ); }); +test("desktop can recover and answer a phone question without crossing chats or settling twice", async () => { + let answers = 0; + let now = 1_000; + const service = new AidenRemoteStreamService({ + now: () => now, cancel: () => true, approve: () => true, + respondQuestion: () => { answers += 1; return true; }, + }); + const owner = service.create("device-1", "stream-1", "chat-1", "turn-1"); + owner.owner.send("chat:questionnaire", QUESTION_PROMPT); + assert.equal(service.pendingQuestionForChat("unrelated"), null); + assert.equal(service.pendingQuestionForChat("chat-1")?.questions[0]?.question, QUESTION_PROMPT.questions[0]?.question); + const answer = { version: 1, promptId: "q-prompt-1", cancelled: false, answers: [{ questionIndex: 0, kind: "custom", answer: "Use 1 mm" }] }; + assert.equal(service.respondQuestionFromHost("unrelated", "q-prompt-1", answer), false); + assert.equal(service.respondQuestionFromHost("chat-1", "q-prompt-1", { ...answer, answers: [{ questionIndex: 0, kind: "option", answer: "Invented option" }] }), false); + assert.equal(answers, 0); + assert.ok(service.pendingQuestionForChat("chat-1")); + assert.equal(service.respondQuestionFromHost("chat-1", "q-prompt-1", answer), true); + assert.equal(service.pendingQuestionForChat("chat-1"), null); + assert.equal(service.pendingQuestion("device-1", "stream-1"), null); + assert.equal(service.status("device-1", "stream-1").state, "running"); + assert.equal(service.respondQuestionFromHost("chat-1", "q-prompt-1", answer), false); + assert.equal(answers, 1); + + owner.owner.send("chat:questionnaire", { ...QUESTION_PROMPT, promptId: "q-expired" }); + now += 300_001; + assert.equal(service.pendingQuestionForChat("chat-1"), null); + assert.equal(service.respondQuestionFromHost("chat-1", "q-expired", { ...answer, promptId: "q-expired" }), false); +}); + test("remote question responses are semantically validated against the stored prompt", async () => { const service = new AidenRemoteStreamService({ now: () => 1_000, diff --git a/main/services/aiden-remote-streams.ts b/main/services/aiden-remote-streams.ts index 5720b83126..50aa61df0a 100644 --- a/main/services/aiden-remote-streams.ts +++ b/main/services/aiden-remote-streams.ts @@ -1534,6 +1534,32 @@ export class AidenRemoteStreamService { return null; } + pendingQuestionForChat(chatId: string): AidenRemotePendingQuestion | null { + this.prune(); + for (const stream of this.streams.values()) { + if (stream.chatId !== chatId || terminal(stream.state)) continue; + const question = this.pendingQuestionForStream(stream.streamId); + if (question) return question; + } + return null; + } + + respondQuestionFromHost(chatId: string, promptId: string, value: unknown): boolean { + this.prune(); + const question = this.questions.get(promptId); + if (!question || question.chatId !== chatId || question.expiresAt <= this.options.now()) { + return false; + } + const response = parseAskUserQuestionResponse(value, { + version: ASK_USER_QUESTION_VERSION, + promptId, + streamId: question.streamId, + toolCallId: question.toolCallId, + questions: question.questions, + }); + return response ? this.resolveQuestion(promptId, response) : false; + } + respondApprovalFromHost( chatId: string, approvalId: string, diff --git a/main/services/llm-client.ts b/main/services/llm-client.ts index 540dcf2624..22e1677356 100644 --- a/main/services/llm-client.ts +++ b/main/services/llm-client.ts @@ -3187,7 +3187,8 @@ export const llmClient = { : await repairAssistantScheduleMcpTarget(context.args); if (createScheduleApproval) { const canonicalArgs = context.args as Record; - canonicalArgs.workspaceId = proposal.input.workspaceId; + if (proposal.input.workspaceId) canonicalArgs.workspaceId = proposal.input.workspaceId; + else delete canonicalArgs.workspaceId; canonicalArgs.permission = proposal.input.permission; canonicalArgs.mcpServerIds = proposal.input.mcpServerIds; } diff --git a/main/services/peer-remote-chat-control.test.ts b/main/services/peer-remote-chat-control.test.ts index 721c55b013..b50aa3c06c 100644 --- a/main/services/peer-remote-chat-control.test.ts +++ b/main/services/peer-remote-chat-control.test.ts @@ -406,6 +406,7 @@ test("the same session control drives a chat on this Mac and one on another Mac markRead: unused, answerQuestionnaire: unused, respondRemoteApproval: unused, + respondRemoteQuestion: unused, approve: async (approvalId, decision, options) => { local.approve({ runId: localRuns.runForPrompt(approvalId)!, chatId: "chat-1", approvalId, decision, scope: options?.scope }); }, diff --git a/main/services/schedule-tool.test.ts b/main/services/schedule-tool.test.ts index 749aa3fe6b..cc4806ff6b 100644 --- a/main/services/schedule-tool.test.ts +++ b/main/services/schedule-tool.test.ts @@ -1,6 +1,8 @@ import assert from "node:assert/strict"; import test from "node:test"; -import type { AgentToolResult } from "@earendil-works/pi-agent-core"; +import { runToolCall, type AgentToolResult } from "@earendil-works/pi-agent-core"; +import { fauxAssistantMessage } from "@earendil-works/pi-ai/providers/faux"; +import { digestPiRuntimeEffectArguments } from "./pi-runtime-effect-core.js"; import type { McpServer, ScheduledMcpServerBinding, @@ -195,6 +197,36 @@ function jsonResult(value: AgentToolResult): Record { return JSON.parse(block.text) as Record; } +for (const attended of [false, true]) { + test(`approved ${attended ? "Assistant" : "standard"} task reaches execution through the durable tool boundary`, async () => { + const fake = fakeDependencies(); + const tool = createScheduleTaskTool( + attended ? ATTENDED_ACCESS : { kind: "standard", modelSelection: ASSISTANT_MODEL_SELECTION }, + fake.dependencies, + ); + const outcome = await runToolCall({ + type: "toolCall", id: "create-approved", name: tool.name, + arguments: { action: "create", name: "Inbox brief", cron: "0 9 * * *", prompt: "Summarize unread email.", permission: "full", mcpServerIds: ["gmail"] }, + }, { + assistantMessage: fauxAssistantMessage("I’ll prepare your daily brief."), + tools: [tool], + context: { messages: [], tools: [tool] }, + beforeToolCall: async ({ args }) => { + if (attended) attachAssistantScheduleMcpApproval(args, [GMAIL_BINDING]); + else await prepareStandardScheduleApproval(args, ASSISTANT_MODEL_SELECTION, fake.dependencies); + // The managed runtime hashes arguments after approval and before dispatch. + digestPiRuntimeEffectArguments(args); + return undefined; + }, + }); + assert.equal(outcome.isError, false, JSON.stringify(outcome.result)); + assert.equal(fake.tasks.length, 1); + assert.equal(fake.tasks[0]?.providerId, "local-provider"); + assert.equal(fake.tasks[0]?.model, "local-model"); + assert.deepEqual(fake.tasks[0]?.mcpServerBindings, [GMAIL_BINDING]); + }); +} + test("schedule_task supports the full create/update/list/pause/resume/run/remove lifecycle", async () => { const fake = fakeDependencies(); const tool = createScheduleTaskTool( diff --git a/main/services/schedule-tool.ts b/main/services/schedule-tool.ts index a459e2c930..86e93bd16b 100644 --- a/main/services/schedule-tool.ts +++ b/main/services/schedule-tool.ts @@ -119,7 +119,10 @@ export interface AssistantScheduleProposal { >; } -const APPROVED_MCP_BINDINGS = Symbol("assistant-approved-mcp-bindings"); +// Approval state belongs to this invocation, not the model's JSON arguments. +// The runtime hashes those arguments after approval; hidden symbol properties +// make them invalid JSON and prevent an approved task from ever dispatching. +const approvedMcpByArguments = new WeakMap(); export function attachAssistantScheduleMcpApproval( args: unknown, @@ -128,12 +131,7 @@ export function attachAssistantScheduleMcpApproval( if (!args || typeof args !== "object" || Array.isArray(args)) { throw new Error("Automation approval arguments are invalid."); } - Object.defineProperty(args, APPROVED_MCP_BINDINGS, { - configurable: false, - enumerable: false, - writable: false, - value: structuredClone(bindings), - }); + approvedMcpByArguments.set(args, structuredClone([...bindings])); } function approvedMcpBindings( @@ -144,7 +142,7 @@ function approvedMcpBindings( const bindings = args && typeof args === "object" && !Array.isArray(args) ? validateScheduledMcpServerBindings( - (args as { [APPROVED_MCP_BINDINGS]?: unknown })[APPROVED_MCP_BINDINGS], + approvedMcpByArguments.get(args), ) : undefined; if ( @@ -598,7 +596,7 @@ export function canonicalizeAssistantScheduleToolArguments( cron: proposal.input.cron, timezone: proposal.input.timezone, prompt: proposal.input.prompt, - workspaceId: proposal.input.workspaceId, + ...(proposal.input.workspaceId ? { workspaceId: proposal.input.workspaceId } : {}), permission: proposal.input.permission, mcpServerIds: proposal.input.mcpServerIds, notify: proposal.input.notify, @@ -923,7 +921,7 @@ interface PreparedStandardScheduleApproval { details: ScheduledTaskApprovalDetails; } -const PREPARED_STANDARD_SCHEDULE = Symbol("prepared-standard-schedule"); +const preparedStandardByArguments = new WeakMap(); function sameIds(left: readonly string[] | undefined, right: readonly string[]): boolean { return (left?.length ?? 0) === right.length && right.every((id, index) => left?.[index] === id); @@ -1320,12 +1318,7 @@ export async function prepareStandardScheduleApproval( if (!value || typeof value !== "object" || Array.isArray(value)) { throw new Error("Scheduled task arguments are invalid."); } - Object.defineProperty(value, PREPARED_STANDARD_SCHEDULE, { - configurable: false, - enumerable: false, - writable: false, - value: structuredClone(prepared), - }); + preparedStandardByArguments.set(value, structuredClone(prepared)); return { summary: prepared.summary, details: prepared.details }; } @@ -1337,9 +1330,7 @@ async function standardScheduleApprovalForExecution( ): Promise { const attached = value && typeof value === "object" && !Array.isArray(value) - ? (value as { [PREPARED_STANDARD_SCHEDULE]?: PreparedStandardScheduleApproval })[ - PREPARED_STANDARD_SCHEDULE - ] + ? preparedStandardByArguments.get(value) : undefined; if (attached) return structuredClone(attached); return resolveStandardScheduleApproval(value, selection, dependencies, defaultWorkspaceId); diff --git a/renderer/components/ask-user-question-composer.test.ts b/renderer/components/ask-user-question-composer.test.ts index 7236d2388f..5c5912782b 100644 --- a/renderer/components/ask-user-question-composer.test.ts +++ b/renderer/components/ask-user-question-composer.test.ts @@ -1,32 +1,10 @@ import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; import test from "node:test"; import { createElement } from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { ASK_USER_QUESTION_VERSION, type AskUserQuestionPromptV1 } from "../shared/ask-user-question.js"; import { AskUserQuestionComposer } from "./ask-user-question-composer.js"; -function source(relativePath: string): string { - return readFileSync(new URL(relativePath, import.meta.url), "utf8"); -} - -test("structured questions fully replace the composer with the reference card", () => { - const pane = source("../main/chat-pane.tsx"); - const component = source("./ask-user-question-composer.tsx"); - const styles = source("../styles.css"); - assert.match( - pane, - /questionnaire \? \([\s\S]* { + const value = prompt(false); + value.questions.push({ ...value.questions[0]!, header: "Timing", question: "When should it run?" }); + const markup = renderToStaticMarkup(createElement(AskUserQuestionComposer, { prompt: value, onRespond: () => undefined })); + assert.equal((markup.match(/role="tab"/g) ?? []).length, 2); + assert.equal((markup.match(/role="tabpanel"/g) ?? []).length, 1); + assert.match(markup, /1. Database/); + assert.match(markup, /2. Timing/); + assert.doesNotMatch(markup, /When should it run\?/); +}); diff --git a/renderer/components/ask-user-question-composer.tsx b/renderer/components/ask-user-question-composer.tsx index 32b60499fa..b185ac1394 100644 --- a/renderer/components/ask-user-question-composer.tsx +++ b/renderer/components/ask-user-question-composer.tsx @@ -1,5 +1,6 @@ import * as React from "react"; -import { ArrowRight, Check, ChevronLeft, ChevronRight, Pencil, X } from "lucide-react"; +import { Check, Pencil, X } from "lucide-react"; +import { Button } from "./ui"; import { cn } from "../lib/ui-utils"; import { ASK_USER_QUESTION_VERSION, @@ -40,10 +41,10 @@ export function AskUserQuestionComposer({ React.useEffect(() => { const frame = requestAnimationFrame(() => { - (customOpen ? customRef.current : firstOptionRef.current)?.focus({ preventScroll: true }); + firstOptionRef.current?.focus({ preventScroll: true }); }); return () => cancelAnimationFrame(frame); - }, [activeIndex, customOpen]); + }, [prompt.promptId]); const response = React.useCallback( (cancelled: boolean, resolvedAnswers = answers) => @@ -63,10 +64,10 @@ export function AskUserQuestionComposer({ const moveTo = React.useCallback( (index: number) => { if (submitting || index < 0 || index >= prompt.questions.length) return; - setCustomOpen(false); + setCustomOpen(customDrafts.has(index)); setActiveIndex(index); }, - [prompt.questions.length, submitting], + [customDrafts, prompt.questions.length, submitting], ); const commit = React.useCallback( @@ -75,14 +76,14 @@ export function AskUserQuestionComposer({ if (nextAnswer) next.set(activeIndex, nextAnswer); else next.delete(activeIndex); setAnswers(next); - setCustomOpen(false); if (activeIndex < prompt.questions.length - 1) { + setCustomOpen(customDrafts.has(activeIndex + 1)); setActiveIndex(activeIndex + 1); } else { void onRespond(response(false, next)); } }, - [activeIndex, answers, onRespond, prompt.questions.length, response], + [activeIndex, answers, customDrafts, onRespond, prompt.questions.length, response], ); const commitCustom = React.useCallback(() => { @@ -106,6 +107,18 @@ export function AskUserQuestionComposer({ next.delete(activeIndex); } setAnswers(next); + const drafts = new Map(customDrafts); + drafts.delete(activeIndex); + setCustomDrafts(drafts); + setCustomOpen(false); + }; + + const selectOption = (label: string) => { + setAnswers(new Map(answers).set(activeIndex, { questionIndex: activeIndex, kind: "option", answer: label })); + const drafts = new Map(customDrafts); + drafts.delete(activeIndex); + setCustomDrafts(drafts); + setCustomOpen(false); }; const handleCardKeyDown = (event: React.KeyboardEvent) => { @@ -115,61 +128,58 @@ export function AskUserQuestionComposer({ if (!option) return; event.preventDefault(); if (question.multiSelect) toggleMulti(option.label); - else commit({ questionIndex: activeIndex, kind: "option", answer: option.label }); + else selectOption(option.label); } }; return ( -
+
-
-

- {question.question} -

-
- - - {activeIndex + 1} of {prompt.questions.length} - - - +
+
+ {prompt.questions.map((item, index) => ( + + ))}
+
+
+

+ {question.question} +

+

{activeIndex + 1} of {prompt.questions.length}{question.multiSelect ? " · Select all that apply" : " · Choose an option or write an answer"}

{ if (question.multiSelect) toggleMulti(option.label); - else commit({ questionIndex: activeIndex, kind: "option", answer: option.label }); + else selectOption(option.label); }} > @@ -212,16 +220,14 @@ export function AskUserQuestionComposer({ {option.description} - {!question.multiSelect ? ( - - ) : null} - + ); })}
-
-
+
+
+
{customOpen ? (
@@ -238,6 +244,10 @@ export function AskUserQuestionComposer({ const next = new Map(customDrafts); next.set(activeIndex, event.target.value); setCustomDrafts(next); + const resolved = new Map(answers); + if (event.target.value.trim()) resolved.set(activeIndex, { questionIndex: activeIndex, kind: "custom", answer: event.target.value.trim() }); + else resolved.delete(activeIndex); + setAnswers(resolved); }} onKeyDown={(event) => { if (event.key === "Enter" && !event.shiftKey) { @@ -250,47 +260,50 @@ export function AskUserQuestionComposer({ } }} /> - +
) : ( - + )}
- {question.multiSelect && answer?.kind === "multi" && answer.selected.length > 0 ? ( - + ) : null} - +
diff --git a/renderer/components/chat-approval-card.tsx b/renderer/components/chat-approval-card.tsx index c092a9b034..f87252ae38 100644 --- a/renderer/components/chat-approval-card.tsx +++ b/renderer/components/chat-approval-card.tsx @@ -16,6 +16,8 @@ import { SubagentRunGrantApproval } from "./subagent-run-grant-approval"; import { FormFillApproval } from "./form-fill-approval"; import type { ApprovalPrompt } from "../lib/ipc"; import { + isAssistantAutomationApprovalDetails, + isScheduledTaskApprovalDetails, isFormFillBatchApprovalDetails, isSubagentMcpMutationApprovalDetails, isSubagentRunGrantApprovalDetails, @@ -88,6 +90,7 @@ export function ChatApprovalCard({ pendingCount?: number; }) { const details = pending.details as unknown; + const schedule = isScheduledTaskApprovalDetails(details) || isAssistantAutomationApprovalDetails(details) ? details : undefined; const pendingWorkspaceWrite = isSubagentWorkspaceWriteApprovalDetails(pending.details) ? pending.details : undefined; const pendingMcpMutation = isSubagentMcpMutationApprovalDetails(pending.details) ? pending.details : undefined; const pendingShell = isSubagentShellApprovalDetails(pending.details) ? pending.details : undefined; @@ -95,6 +98,8 @@ export function ChatApprovalCard({ const pendingFormFill = isFormFillBatchApprovalDetails(pending.details) ? pending.details : undefined; const pendingClassifier = classifierApprovalState(pending.toolName, details); const invalidPendingPrivilegedApproval = + (claimsKind(details, "scheduled-task") && !schedule) || + (claimsKind(details, "assistant-automation") && !schedule) || pendingClassifier.invalid || (claimsKind(details, "subagent-workspace-write") && pendingWorkspaceWrite === undefined) || (claimsKind(details, "subagent-mcp-mutation") && pendingMcpMutation === undefined) || @@ -169,6 +174,20 @@ export function ChatApprovalCard({ Aiden cannot safely authorize this action from this view. Deny it here or review the exact action on the device that owns this chat. + ) : schedule ? ( +
+

{schedule.name}

+

{pending.summary}

+ {schedule.mode === "llm" ?

Model: {schedule.providerName} / {schedule.modelName}

: null} +

Access: {schedule.permission === "full" ? "Full" : "Read-only"}{schedule.workspaceName ? ` · ${schedule.workspaceName} (${schedule.workspaceId})` : ""}{schedule.mcpServerIds.map((id, index) => ` · ${schedule.mcpServerNames[index]} (${id})`).join("")}

+
+

{schedule.mode === "script" ? "Script" : "Instructions"}

+

{schedule.prompt ?? ("script" in schedule ? schedule.script : "")}

+
+

Timezone: {schedule.timezone} · Notifications {schedule.notify ? "on" : "off"}

+ {!schedule.schedulerEnabled ?

Scheduling is off. This task will be saved but will not run automatically until you enable scheduling.

: schedule.enabled === false ?

This task stays paused.

: null} +

Scheduled work runs on your desktop while Aiden is open and the computer is awake.

+
) : pendingClassifier.details ? ( ) : pendingWorkspaceWrite ? ( diff --git a/renderer/components/environment-panel.tsx b/renderer/components/environment-panel.tsx index 0001971601..86b8d9ff66 100644 --- a/renderer/components/environment-panel.tsx +++ b/renderer/components/environment-panel.tsx @@ -1966,7 +1966,9 @@ export function EnvironmentWorkbench({ data-environment-surface-mode={panel.surfaceMode} data-quick-view-open={quickViewOpen ? "true" : "false"} data-environment-stacked={stacked ? "true" : "false"} - className="relative flex h-full min-h-0 w-full flex-1 overflow-hidden" + // Offscreen panels are clipped at the workbench boundary. A scrollport + // here lets focus/scrollIntoView pan the entire chat beneath the sidebar. + className="relative flex h-full min-h-0 w-full flex-1 overflow-clip" >
undefined, + cardRef: createRef(), denyRef: createRef(), + })); +} + +test("task approval discloses instructions, runtime, exact connectors and paused scheduling", () => { + const markup = renderApproval(approval); + for (const text of ["Summarize unread messages without sending replies.", "Local provider", "Brief model", "Email (mail-1)", "America/New_York", "will not run automatically"]) { + assert.ok(markup.includes(text), `Missing approval disclosure: ${text}`); + } + assert.ok(markup.includes("Allow once")); + assert.ok(!markup.includes("Remember this exact action")); +}); + +test("malformed schedule approval withholds Allow instead of presenting incomplete consent", () => { + const markup = renderApproval({ ...approval, providerName: undefined }); + assert.ok(markup.includes("Invalid privileged approval blocked")); + assert.ok(!markup.includes("Allow once")); +}); function source(relativePath: string): string { return readFileSync(new URL(relativePath, import.meta.url), "utf8"); @@ -71,4 +107,4 @@ test("the Model select stays bound to the helper's pinned model and never re-fil /current\.providerId === provider\.id \? current\.model : undefined/u, "a stale pinned model from another provider never leaks into the new provider", ); -}); \ No newline at end of file +}); diff --git a/renderer/components/scheduled-tasks-view.tsx b/renderer/components/scheduled-tasks-view.tsx index 353d79c72f..7e58edf855 100644 --- a/renderer/components/scheduled-tasks-view.tsx +++ b/renderer/components/scheduled-tasks-view.tsx @@ -133,7 +133,6 @@ function newTask( mcpServers: McpServer[], providers: Provider[] | undefined, hiddenModelsByProvider: HiddenModelsByProvider | undefined, - template?: (typeof TEMPLATES)[number], ): ScheduledTaskInput { const mode = settings?.defaultMode ?? "llm"; const permission = mode === "script" ? "full" : (settings?.defaultPermission ?? "read-only"); @@ -142,15 +141,15 @@ function newTask( ? scheduledTaskProviderPin(providers, readModelSelection(), hiddenModelsByProvider) : undefined; return { - name: template?.name ?? "", + name: "", enabled: true, mode, - cron: template?.cron ?? "0 9 * * 1-5", + cron: "0 9 * * 1-5", timezone: settings?.defaultTimezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? "UTC", workspaceId, ...(pinned ?? {}), - prompt: template?.prompt ?? "", + prompt: "", script: "", permission, mcpServerIds: @@ -757,18 +756,9 @@ export function ScheduledTasksView() { {index > 0 ? : null}