A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Answer Claude questions from the notch (#165)
Louisc767db924969
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 01f5d21a..11d347e9 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -30,6 +30,9 @@ jobs:- name: Test plan gaugerun: bash scripts/test-plan-gauge.sh+ - name: Test ask question+ run: bash scripts/test-ask-question.sh+- name: Buildrun: |xcodebuild \diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxprojindex 94fd3635..273baf38 100644--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj@@ -49,6 +49,7 @@733FCC6A45DE963EF2024B4E /* ChatMarkdownView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFE88A53AEAA637F866D479D /* ChatMarkdownView.swift */; };78B3C6814431B2DD9D1F4949 /* SoundEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1BE21C2B315D37AA70ED45E9 /* SoundEngine.swift */; };78FCEDC8F78B683AB10E6529 /* NotionPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE03E03D1804B0B92C5C2DAD /* NotionPoller.swift */; };+ 7C75CCB3DC0116D8D3B12313 /* AskQuestion.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBB84A66045EB20CAC93A8A6 /* AskQuestion.swift */; };878924960FC0F2B3524D48AC /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 192844E7299DEED5C2372067 /* AppDelegate.swift */; };8A6B3688D6B3BF728D106D8B /* UserIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4A13AEE6E06F46CEC9D908C /* UserIdentity.swift */; };8C32A0C3EAF536D3836F61D5 /* GreetingCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */; };@@ -81,6 +82,7 @@E9C21D11BCB72C392436D19E /* ClaudePlanGauge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BF22817EC70748F2D1FB2E7 /* ClaudePlanGauge.swift */; };EB23ED9F1C12EA8B54A76A91 /* ResendPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61B5FDDE03F5F711146937E2 /* ResendPoller.swift */; };ECECA2F225E82B7C951658D7 /* UploadSequenceEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FD65943C32E150F1CD65C31 /* UploadSequenceEngine.swift */; };+ ED5D9A334DE08C0EB81DE322 /* AskQuestion.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBB84A66045EB20CAC93A8A6 /* AskQuestion.swift */; };F06EE0A97CB77096A337AA8B /* sounds in Resources */ = {isa = PBXBuildFile; fileRef = C066E2B991AA4F56B2724263 /* sounds */; };FAD78D74C6906D4EC8AA4101 /* UploadSequenceEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FD65943C32E150F1CD65C31 /* UploadSequenceEngine.swift */; };FBBC4CDE82B5886A83A27D7A /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 506824380E9C80B9BC6DCE72 /* Assets.xcassets */; };@@ -125,6 +127,7 @@D797CC384B5BC70D34F121BC /* ChatMarkdown.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatMarkdown.swift; sourceTree = "<group>"; };D8212018F09EA1E96FBD63CD /* IslandStateMachine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandStateMachine.swift; sourceTree = "<group>"; };E91B733ADC638E14E9BB6EFA /* WindowContextCapture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WindowContextCapture.swift; sourceTree = "<group>"; };+ EBB84A66045EB20CAC93A8A6 /* AskQuestion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AskQuestion.swift; sourceTree = "<group>"; };F1BD8F3CAA60CF37640759E1 /* NotchBuddyApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotchBuddyApp.swift; sourceTree = "<group>"; };F4263B550838CC5614569D13 /* ClaudePlanCardView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudePlanCardView.swift; sourceTree = "<group>"; };F4A13AEE6E06F46CEC9D908C /* UserIdentity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserIdentity.swift; sourceTree = "<group>"; };@@ -138,6 +141,7 @@192844E7299DEED5C2372067 /* AppDelegate.swift */,9F6D7015D6A77AA59323C0E7 /* AppLog.swift */,C2E4F18AA940EFF7E047B9F7 /* AppState.swift */,+ EBB84A66045EB20CAC93A8A6 /* AskQuestion.swift */,A29F4C0B02BE91654D02AA0C /* BotCanvasView.swift */,D4540F630F8BA04AFFFA3979 /* BotEngine.swift */,3104222B3F17BA5E8DEA5277 /* CalcomPoller.swift */,@@ -317,6 +321,7 @@C940B651C6CA952D99388E04 /* AppDelegate.swift in Sources */,4B6AC00F22EC75E90E0157D5 /* AppLog.swift in Sources */,1F11EC4E6F604C612A1ADAD1 /* AppState.swift in Sources */,+ 7C75CCB3DC0116D8D3B12313 /* AskQuestion.swift in Sources */,CD8DECA66B9E09C97E469DB9 /* BotCanvasView.swift in Sources */,C24D863967D8D32D828ED4B1 /* BotEngine.swift in Sources */,4F1E0B3C838DA3CD6F864BC0 /* CalcomPoller.swift in Sources */,@@ -361,6 +366,7 @@878924960FC0F2B3524D48AC /* AppDelegate.swift in Sources */,61CB7049490F61CFA1B36B64 /* AppLog.swift in Sources */,61F73B27A7E3AFF584B2CC22 /* AppState.swift in Sources */,+ ED5D9A334DE08C0EB81DE322 /* AskQuestion.swift in Sources */,651FA3F09608DE5D02D61CCE /* BotCanvasView.swift in Sources */,0E9CE475EC53C67DAB00F8E5 /* BotEngine.swift in Sources */,1969590AFEE6CB21404346F1 /* CalcomPoller.swift in Sources */,diff --git a/NotchBuddy/Sources/App/AppState.swift b/NotchBuddy/Sources/App/AppState.swiftindex 751ee930..48247158 100644--- a/NotchBuddy/Sources/App/AppState.swift+++ b/NotchBuddy/Sources/App/AppState.swift@@ -288,6 +288,9 @@ final class AppState: ObservableObject {// Pending approval request from Claude Code hook@Published var pendingApproval: ApprovalInfo? = nil+ // Pending AskUserQuestion from Claude Code hook+ @Published var pendingQuestion: AskQuestion? = nil+#if !APPSTORE@Published var musicPlaying: Bool = false@Published var musicAutomationDenied: Bool = falsediff --git a/NotchBuddy/Sources/App/AskQuestion.swift b/NotchBuddy/Sources/App/AskQuestion.swiftnew file mode 100644index 00000000..e3e7266f--- /dev/null+++ b/NotchBuddy/Sources/App/AskQuestion.swift@@ -0,0 +1,60 @@+import Foundation++// MARK: - AskUserQuestion model (Foundation-only, testable)++struct AskQuestionOption: Equatable {+ var label: String+ var description: String+}++struct AskQuestionItem: Equatable {+ var question: String // full question text+ var header: String // ≤12 chars; used as section label+ var options: [AskQuestionOption] // 2–4 choices+ var multiSelect: Bool+}++struct AskQuestion: Equatable {+ var questions: [AskQuestionItem] // 1–4 questions++ // MARK: - Parse from tool_input dict+ // Returns nil if the payload is malformed (fallback → Allow/Deny card).+ static func parse(toolInput: [String: Any]) -> AskQuestion? {+ guard let rawQs = toolInput["questions"] as? [[String: Any]],+ !rawQs.isEmpty, rawQs.count <= 4 else { return nil }+ var items: [AskQuestionItem] = []+ for raw in rawQs {+ guard let question = raw["question"] as? String, !question.isEmpty,+ let rawOpts = raw["options"] as? [[String: Any]],+ rawOpts.count >= 2, rawOpts.count <= 4 else { return nil }+ var opts: [AskQuestionOption] = []+ for opt in rawOpts {+ guard let label = opt["label"] as? String, !label.isEmpty else { return nil }+ let desc = opt["description"] as? String ?? ""+ opts.append(AskQuestionOption(label: label, description: desc))+ }+ let rawHeader = raw["header"] as? String ?? ""+ let header = String(rawHeader.prefix(12))+ let multi = raw["multiSelect"] as? Bool ?? false+ items.append(AskQuestionItem(question: question, header: header, options: opts, multiSelect: multi))+ }+ return AskQuestion(questions: items)+ }++ // MARK: - Build answers dict+ // selections[i] = list of labels selected for question[i].+ // Single-select / Other…: one label → String value (Claude Code 2.1.85+).+ // Multi-select: array of labels → [String] value (Claude Code 2.1.136+).+ static func buildAnswers(questions: [AskQuestionItem], selections: [[String]]) -> [String: Any] {+ var answers: [String: Any] = [:]+ for (i, item) in questions.enumerated() {+ guard i < selections.count, !selections[i].isEmpty else { continue }+ if item.multiSelect {+ answers[item.question] = selections[i] // array for multi-select+ } else {+ answers[item.question] = selections[i][0] // string for single-select+ }+ }+ return answers+ }+}diff --git a/NotchBuddy/Sources/App/HookServer.swift b/NotchBuddy/Sources/App/HookServer.swiftindex 7ba0d652..5f21d514 100644--- a/NotchBuddy/Sources/App/HookServer.swift+++ b/NotchBuddy/Sources/App/HookServer.swift@@ -40,6 +40,10 @@ final class HookServer: @unchecked Sendable {private var connectionCount = 0private var pendingApprovalFD: Int32 = -1 // held open while user decidesprivate var approvalFDSource: (any DispatchSourceRead)? = nil // monitors pendingApprovalFD+ private var pendingQuestionFD: Int32 = -1 // held open while user answers AskUserQuestion+ private var questionFDSource: (any DispatchSourceRead)? = nil // monitors pendingQuestionFD+ private var questionPillId: String = "" // pill that owns the pending question+ private var focusBeforeQuestion: String? = nil // saved focus to restore after questionprivate var activeSessionId: String? = nil // current Claude Code sessionprivate var focusBeforeApproval: String? = nil // saved focus to restore after approval@@ -81,6 +85,94 @@ final class HookServer: @unchecked Sendable {}}+ // MARK: - Question fd helpers++ @MainActor+ private func cancelQuestionFDSource() {+ questionFDSource?.cancel()+ questionFDSource = nil+ }++ @MainActor+ private func dismissQuestionCard(note: String) {+ cancelQuestionFDSource()+ pendingQuestionFD = -1+ let state = AppState.shared+ let pillId = questionPillId+ state.pendingQuestion = nil+ state.isPinned = false+ state.updateTask(id: pillId, state: .working)+ clearPillBadge(id: pillId)+ if let prev = focusBeforeQuestion {+ focusBeforeQuestion = nil+ if state.focusId == pillId, state.tasks.contains(where: { $0.id == prev }) {+ withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = prev }+ }+ }+ if !note.isEmpty {+ state.noteMessage = note+ state.view = .note+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) {+ NotificationCenter.default.post(name: .islandCollapse, object: nil)+ }+ } else {+ state.view = state.tasks.isEmpty ? .empty : .overview+ }+ }++ /// Called by QuestionView. Sends answers JSON and cleans up.+ @MainActor+ func sendQuestionAnswers(_ answers: [String: Any]) {+ let fd = pendingQuestionFD+ pendingQuestionFD = -1+ let source = questionFDSource+ questionFDSource = nil+ if fd >= 0, let data = try? JSONSerialization.data(withJSONObject: ["permissionDecision": "answer", "answers": answers], options: .withoutEscapingSlashes),+ let json = String(data: data, encoding: .utf8) {+ Task.detached { [weak self] in+ self?.sendLine(fd: fd, text: json)+ DispatchQueue.main.async { source?.cancel() }+ }+ } else {+ source?.cancel()+ }+ dismissQuestionCard(note: "")+ }++ /// Called by QuestionView.onDisappear — card left screen without an explicit answer.+ /// Sends "ask" immediately to unblock nb-hook; does NOT navigate (view already changed).+ @MainActor+ func releaseQuestionFD() {+ guard pendingQuestionFD >= 0 else { return }+ let fd = pendingQuestionFD+ pendingQuestionFD = -1+ let source = questionFDSource+ questionFDSource = nil+ AppState.shared.pendingQuestion = nil+ Task.detached { [weak self] in+ self?.sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)+ DispatchQueue.main.async { source?.cancel() }+ }+ }++ /// Called by QuestionView "Reply in terminal" button.+ @MainActor+ func sendQuestionAsk() {+ let fd = pendingQuestionFD+ pendingQuestionFD = -1+ let source = questionFDSource+ questionFDSource = nil+ if fd >= 0 {+ Task.detached { [weak self] in+ self?.sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)+ DispatchQueue.main.async { source?.cancel() }+ }+ } else {+ source?.cancel()+ }+ dismissQuestionCard(note: "")+ }+/// Returns the tool_input serialized as sorted-keys JSON, "" if absent or empty./// Same computation used in processPermissionRequest and processEvent to match PostToolUse.private static func approvalInputKey(_ input: [String: Any]) -> String {@@ -187,14 +279,29 @@ final class HookServer: @unchecked Sendable {return}+ let coucouKind = payload["coucou_kind"] as? String ?? ""+// statusline payloads are handled separately — no session, no reveal, no sound- if let kind = payload["coucou_kind"] as? String, kind == "statusline" {+ if coucouKind == "statusline" {Task { @MainActor in self.processStatusLine(payload: payload) }sendLine(fd: fd, text: #"{"ok":true}"#)close(fd)return}+ // AskUserQuestion via --ask PreToolUse hook — hold fd open like PermissionRequest+ if coucouKind == "ask_user_question" {+ let toolInput = payload["tool_input"] as? [String: Any] ?? [:]+ if let parsed = AskQuestion.parse(toolInput: toolInput) {+ Task { @MainActor in self.processQuestionRequest(fd: fd, parsed: parsed, payload: payload) }+ } else {+ // Malformed payload — fall back: send ask so Claude Code re-asks in terminal+ sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)+ close(fd)+ }+ return+ }+let eventName = payload["hook_event_name"] as? String ?? ""if eventName == "PermissionRequest" {@@ -322,9 +429,12 @@ final class HookServer: @unchecked Sendable {case "PreToolUse":activeSessionId = sessionId+ let tool = payload["tool_name"] as? String ?? "Tool"+ // AskUserQuestion is handled via the dedicated --ask hook.+ // Skip state/step update here to avoid flickering over the question card.+ guard tool != "AskUserQuestion" else { break }if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd) }state.updateTask(id: agentId, state: .working)- let tool = payload["tool_name"] as? String ?? "Tool"let input = payload["tool_input"] as? [String: Any] ?? [:]let step = frenchStep(tool: tool, input: input)appendStep(id: agentId, step: step)@@ -440,12 +550,12 @@ final class HookServer: @unchecked Sendable {let state = AppState.sharedlet isAlert: Boolswitch view {- case .approval, .finished, .error, .confused: isAlert = true+ case .approval, .question, .finished, .error, .confused: isAlert = truedefault: isAlert = false}if state.mode == .expanded {- // Approval always wins; other alerts are blocked while a card is showing- if view == .approval {+ // Approval and question always win; other alerts are blocked while a card is showing+ if view == .approval || view == .question {state.view = view} else if isAlert && state.pendingApproval == nil {state.view = view@@ -524,10 +634,22 @@ final class HookServer: @unchecked Sendable {let tool = payload["tool_name"] as? String ?? "Tool"let toolInput = payload["tool_input"] as? [String: Any] ?? [:]- var command = toolInput["command"] as? String ?? toollet inputKey = Self.approvalInputKey(toolInput)nbLog("PermissionRequest \(tool) [\(pillId)]")+ // AskUserQuestion is now handled via the dedicated --ask PreToolUse hook.+ // If it still arrives here as a PermissionRequest, reply "ask" so Claude Code+ // re-asks in the terminal — never show the question twice.+ if tool == "AskUserQuestion" {+ Task.detached { [weak self] in+ self?.sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)+ close(fd)+ }+ return+ }++ let command = toolInput["command"] as? String ?? tool+if pendingApprovalFD >= 0 {// Displace the previous request: write "ask" then cancel its source.// The cancel handler closes the old fd — never close it directly.@@ -633,6 +755,95 @@ final class HookServer: @unchecked Sendable {state.view = state.tasks.isEmpty ? .empty : .overview}+ // MARK: - Question request++ @MainActor+ private func processQuestionRequest(fd: Int32, parsed: AskQuestion, payload: [String: Any]) {+ let state = AppState.shared+ let sessionId = payload["session_id"] as? String+ ?? payload["conversation_id"] as? String+ ?? "unknown"+ let cwd = payload["cwd"] as? String ?? ""+ let rawName = URL(fileURLWithPath: cwd).lastPathComponent+ let projectName = aliasProjectName(rawName.isEmpty ? "Session" : rawName)++ let rawAgent = payload["coucou_agent"] as? String ?? ""+ let termProgram = payload["term_program"] as? String ?? ""+ let bundleId = payload["bundle_id"] as? String ?? ""+ let isCursorEditor = bundleId.lowercased() == "com.todesktop.230313mzl4w4u92"+ let isVSCodeEditor = !isCursorEditor && (+ termProgram.lowercased().contains("vscode") ||+ bundleId.lowercased().contains("vscode"))+ #if !APPSTORE+ let isCodexRequest = rawAgent == "codex"+ #else+ let isCodexRequest = false+ #endif+ let pillId: String+ if isCodexRequest {+ pillId = "agent_codex"+ } else if isCursorEditor {+ pillId = "agent_cursor"+ } else {+ pillId = "integration_claude"+ }+ guard isCodexRequest || isCursorEditor || isVSCodeEditor else {+ Task.detached { [weak self] in+ self?.sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)+ close(fd)+ }+ return+ }++ // Displace any previous question waiting for an answer.+ if pendingQuestionFD >= 0 {+ let old = pendingQuestionFD+ let oldSrc = questionFDSource+ questionFDSource = nil+ Task.detached { [weak self] in+ self?.sendLine(fd: old, text: #"{"permissionDecision":"ask"}"#)+ DispatchQueue.main.async { oldSrc?.cancel() }+ }+ }+ pendingQuestionFD = fd+ activeSessionId = sessionId+ questionPillId = pillId++ upsertWorkspaceTask(id: pillId, projectName: projectName, cwd: cwd)+ state.updateTask(id: pillId, state: .question)+ state.pendingQuestion = parsed+ state.isPinned = true+ SoundEngine.shared.play("approval")++ if focusBeforeQuestion == nil { focusBeforeQuestion = state.focusId }+ withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = pillId }+ expandIfNeeded(to: .question)++ let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: .main)+ source.setEventHandler { [weak self] in+ guard let self, self.pendingQuestionFD == fd else { return }+ self.dismissQuestionCard(note: "")+ }+ source.setCancelHandler { close(fd) }+ source.resume()+ questionFDSource = source++ let captured = fd+ DispatchQueue.main.asyncAfter(deadline: .now() + 120) { [weak self] in+ guard let self, self.pendingQuestionFD == captured else { return }+ // Send "ask" so nb-hook exits cleanly; Claude Code re-asks in terminal.+ let askFD = self.pendingQuestionFD+ self.pendingQuestionFD = -1+ let src = self.questionFDSource+ self.questionFDSource = nil+ Task.detached { [weak self] in+ self?.sendLine(fd: askFD, text: #"{"permissionDecision":"ask"}"#)+ DispatchQueue.main.async { src?.cancel() }+ }+ self.dismissQuestionCard(note: "")+ }+ }+/// Updates or transiently creates a workspace pill (VS Code or Cursor) task./// If the task already exists (persistent), just updates name/cwd./// If missing (transient), creates it and inserts after the main pill.@@ -819,28 +1030,46 @@ final class HookServer: @unchecked Sendable {// MARK: - Outdated hook detection- /// Returns true if settings.json has a Coucou PermissionRequest hook with timeout < 120s.+ /// Returns true if settings.json has a Coucou hook that needs updating:+ /// either a PermissionRequest hook with timeout < 120s, or the AskUserQuestion+ /// PreToolUse matcher is missing (requires Claude Code 2.1.85+).static func hooksNeedUpdate() -> Bool {let settingsURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".claude/settings.json")guard let data = try? Data(contentsOf: settingsURL),let settings = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let hooks = settings["hooks"] as? [String: Any],- let permReqHooks = hooks["PermissionRequest"] as? [[String: Any]] else {+ let hooks = settings["hooks"] as? [String: Any] else {return false}- for matcher in permReqHooks {- if let hookList = matcher["hooks"] as? [[String: Any]] {- for hook in hookList {- if let cmd = hook["command"] as? String,- (cmd.contains("NotchBuddy") || cmd.contains("coucou")),- let timeout = hook["timeout"] as? Int,- timeout < 120 {- return true+ // Track whether any Coucou hook is installed at all+ var hasCoucouHooks = false++ if let permReqHooks = hooks["PermissionRequest"] as? [[String: Any]] {+ for matcher in permReqHooks {+ if let hookList = matcher["hooks"] as? [[String: Any]] {+ for hook in hookList {+ if let cmd = hook["command"] as? String,+ cmd.contains("NotchBuddy") || cmd.contains("coucou") {+ hasCoucouHooks = true+ if let timeout = hook["timeout"] as? Int, timeout < 120 { return true }+ }}}}}++ // Check that the AskUserQuestion PreToolUse entry exists+ if hasCoucouHooks {+ let preToolHooks = hooks["PreToolUse"] as? [[String: Any]] ?? []+ let hasAskEntry = preToolHooks.contains { m in+ (m["matcher"] as? String) == "AskUserQuestion"+ && (m["hooks"] as? [[String: Any]])?.contains {+ let cmd = $0["command"] as? String ?? ""+ return cmd.contains("NotchBuddy") || cmd.contains("coucou")+ } ?? false+ }+ if !hasAskEntry { return true }+ }return false}@@ -904,6 +1133,13 @@ final class HookServer: @unchecked Sendable {existing.append(["hooks": [["type": "command", "command": quotedCmd, "timeout": timeout]]])hooks[event] = existing}+ // Dedicated AskUserQuestion PreToolUse hook (Claude Code 2.1.85+, timeout 130s)+ var preToolUse = hooks["PreToolUse"] as? [[String: Any]] ?? []+ preToolUse.append([+ "matcher": "AskUserQuestion",+ "hooks": [["type": "command", "command": "\(quotedCmd) --ask", "timeout": 130]],+ ])+ hooks["PreToolUse"] = preToolUsesettings["hooks"] = hooksreturn try JSONSerialization.data(withJSONObject: settings, options: [.prettyPrinted, .sortedKeys])}@@ -1148,6 +1384,13 @@ final class HookServer: @unchecked Sendable {existing.append(["hooks": [["type": "command", "command": quotedCmd, "timeout": timeout]]])hooks[event] = existing}+ // Dedicated AskUserQuestion PreToolUse hook (Claude Code 2.1.85+, timeout 130s)+ var preToolUse = hooks["PreToolUse"] as? [[String: Any]] ?? []+ preToolUse.append([+ "matcher": "AskUserQuestion",+ "hooks": [["type": "command", "command": "\(quotedCmd) --ask", "timeout": 130]],+ ])+ hooks["PreToolUse"] = preToolUsesettings["hooks"] = hooksreturn try JSONSerialization.data(withJSONObject: settings, options: [.prettyPrinted, .sortedKeys])}@@ -1674,6 +1917,56 @@ def main():passreturn+ # --ask mode: dedicated hook for AskUserQuestion via PreToolUse (Claude Code 2.1.85+)+ if '--ask' in sys.argv[1:]:+ tool = payload.get('tool_name', '')+ if tool != 'AskUserQuestion':+ return # Not an AskUserQuestion invocation — exit cleanly (no output)+ payload['coucou_kind'] = 'ask_user_question'+ env = os.environ+ payload.setdefault('term_program', env.get('TERM_PROGRAM', ''))+ payload.setdefault('iterm_session_id', env.get('ITERM_SESSION_ID', ''))+ payload.setdefault('term_session_id', env.get('TERM_SESSION_ID', ''))+ payload.setdefault('bundle_id', env.get('__CFBundleIdentifier', ''))+ if 'cwd' not in payload or not payload['cwd']:+ paths = payload.get('workspacePaths') or payload.get('workspace_roots', [])+ if isinstance(paths, list) and paths:+ payload['cwd'] = paths[0]+ else:+ payload['cwd'] = os.getcwd()+ try:+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ s.settimeout(125)+ s.connect(socket_path)+ s.sendall((json.dumps(payload) + '\\n').encode())+ chunks = []+ while True:+ chunk = s.recv(4096)+ if not chunk:+ break+ chunks.append(chunk)+ if b'\\n' in chunk:+ break+ s.close()+ response = b''.join(chunks).decode().strip()+ if response:+ try:+ resp_obj = json.loads(response)+ decision = resp_obj.get('permissionDecision', '')+ except Exception:+ decision = ''+ if decision == 'answer':+ answers = resp_obj.get('answers', {})+ questions = payload.get('tool_input', {}).get('questions', [])+ out = {'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'allow', 'updatedInput': {'questions': questions, 'answers': answers}}}+ sys.stdout.write(json.dumps(out) + '\\n')+ sys.stdout.flush()+ sys.exit(0)+ # 'ask' or unknown: fall through → no output → Claude Code asks in terminal+ except Exception:+ pass+ return+# Parse --agent <name> and optional positional event from argv.# --agent tags the payload with coucou_agent so the app routes to the right pill.# The positional arg is a fallback event name for agents that do not set hook_event_name.@@ -1763,6 +2056,14 @@ def main():sys.stdout.write(json.dumps(out) + '\\n')sys.stdout.flush()sys.exit(0)+ elif decision == 'answer':+ # AskUserQuestion answered from the notch+ answers = resp_obj.get('answers', {})+ questions = payload.get('tool_input', {}).get('questions', [])+ out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'allow', 'updatedInput': {'questions': questions, 'answers': answers}}}}+ sys.stdout.write(json.dumps(out) + '\\n')+ sys.stdout.flush()+ sys.exit(0)# 'ask' or unknown: fall through → no output → agent re-asksexcept Exception:pass@@ -1883,6 +2184,56 @@ def main():passreturn+ # --ask mode: dedicated hook for AskUserQuestion via PreToolUse (Claude Code 2.1.85+)+ if '--ask' in sys.argv[1:]:+ tool = payload.get('tool_name', '')+ if tool != 'AskUserQuestion':+ return # Not an AskUserQuestion invocation — exit cleanly (no output)+ payload['coucou_kind'] = 'ask_user_question'+ env = os.environ+ payload.setdefault('term_program', env.get('TERM_PROGRAM', ''))+ payload.setdefault('iterm_session_id', env.get('ITERM_SESSION_ID', ''))+ payload.setdefault('term_session_id', env.get('TERM_SESSION_ID', ''))+ payload.setdefault('bundle_id', env.get('__CFBundleIdentifier', ''))+ if 'cwd' not in payload or not payload['cwd']:+ paths = payload.get('workspacePaths') or payload.get('workspace_roots', [])+ if isinstance(paths, list) and paths:+ payload['cwd'] = paths[0]+ else:+ payload['cwd'] = os.getcwd()+ try:+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ s.settimeout(125)+ s.connect(socket_path)+ s.sendall((json.dumps(payload) + '\\n').encode())+ chunks = []+ while True:+ chunk = s.recv(4096)+ if not chunk:+ break+ chunks.append(chunk)+ if b'\\n' in chunk:+ break+ s.close()+ response = b''.join(chunks).decode().strip()+ if response:+ try:+ resp_obj = json.loads(response)+ decision = resp_obj.get('permissionDecision', '')+ except Exception:+ decision = ''+ if decision == 'answer':+ answers = resp_obj.get('answers', {})+ questions = payload.get('tool_input', {}).get('questions', [])+ out = {'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'allow', 'updatedInput': {'questions': questions, 'answers': answers}}}+ sys.stdout.write(json.dumps(out) + '\\n')+ sys.stdout.flush()+ sys.exit(0)+ # 'ask' or unknown: fall through → no output → Claude Code asks in terminal+ except Exception:+ pass+ return+# Parse --agent <name> and optional positional event from argv.# --agent tags the payload with coucou_agent so the app routes to the right pill.# The positional arg is a fallback event name for agents that do not set hook_event_name.@@ -1971,6 +2322,14 @@ def main():sys.stdout.write(json.dumps(out) + '\\n')sys.stdout.flush()sys.exit(0)+ elif decision == 'answer':+ # AskUserQuestion answered from the notch+ answers = resp_obj.get('answers', {})+ questions = payload.get('tool_input', {}).get('questions', [])+ out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'allow', 'updatedInput': {'questions': questions, 'answers': answers}}}}+ sys.stdout.write(json.dumps(out) + '\\n')+ sys.stdout.flush()+ sys.exit(0)# 'ask' or unknown: fall through → no output → agent re-asksexcept Exception:passdiff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swiftindex 7eb12456..12749de4 100644--- a/NotchBuddy/Sources/App/IslandViewContent.swift+++ b/NotchBuddy/Sources/App/IslandViewContent.swift@@ -298,25 +298,185 @@ struct ApprovalView: View {struct QuestionView: View {@ObservedObject var state: AppState+ @State private var questionIndex = 0+ // Per-question selected labels (empty = none chosen yet)+ @State private var selections: [[String]] = []+ // Per-question custom "Other…" text+ @State private var otherTexts: [String] = []+ // Per-question "Other…" mode active+ @State private var showOther: [Bool] = []+ @FocusState private var otherFieldFocused: Bool++ var question: AskQuestion? { state.pendingQuestion }var body: some View {ZStack {CardBackground(wash: .cyan)- VStack(alignment: .leading, spacing: 5) {- AgentWho(task: state.focusTask, label: "Claude Code is asking a question")- Text("Which search engine to use?")- .font(.system(size: 15, weight: .semibold))- HStack(spacing: 8) {- ForEach(["Postgres full-text", "Meilisearch", "Algolia"], id: \.self) { opt in- SecondaryButton(opt) { /* answer */ }+ if let q = question, !q.questions.isEmpty {+ let qi = min(questionIndex, q.questions.count - 1)+ let item = q.questions[qi]+ let isLast = qi == q.questions.count - 1+ let isMulti = item.multiSelect+ let curSel = qi < selections.count ? selections[qi] : []+ let curOther = qi < showOther.count ? showOther[qi] : false+ let curOtherText = qi < otherTexts.count ? otherTexts[qi] : ""+ let canProceed = !curSel.isEmpty || (curOther && !curOtherText.isEmpty)++ VStack(alignment: .leading, spacing: 4) {+ // Header row: agent name + question counter + "Reply in terminal" link+ HStack(spacing: 4) {+ AgentWho(task: nil, label: "Claude Code is asking")+ Spacer(minLength: 4)+ if q.questions.count > 1 {+ Text("\(qi + 1)/\(q.questions.count)")+ .font(.system(size: 10))+ .foregroundColor(Color(hex: "#6B7079"))+ }+ Button("Reply in terminal") { HookServer.shared.sendQuestionAsk() }+ .buttonStyle(.plain)+ .font(.system(size: 10))+ .foregroundColor(Color(hex: "#6B7079"))+ .underline()+ }+ // Optional short header label above question text+ if !item.header.isEmpty {+ Text(item.header)+ .font(.system(size: 10))+ .foregroundColor(Color(hex: "#6B7079"))+ }+ Text(item.question)+ .font(.system(size: 13, weight: .semibold))+ .foregroundColor(Color(hex: "#F5F6F8"))+ .lineLimit(2)+ // Options (wrapping) or "Other…" compact inline row+ if curOther {+ HStack(spacing: 6) {+ TextField("Your answer…", text: Binding(+ get: { qi < otherTexts.count ? otherTexts[qi] : "" },+ set: { v in if qi < otherTexts.count { otherTexts[qi] = v } }+ ))+ .textFieldStyle(.plain)+ .font(.system(size: 12))+ .foregroundColor(Color(hex: "#F5F6F8"))+ .focused($otherFieldFocused)+ .onAppear { otherFieldFocused = true }+ .onSubmit { commitOtherAndProceed(q: q, qi: qi, isLast: isLast) }+ .onExitCommand { if qi < showOther.count { showOther[qi] = false } }+ .padding(.horizontal, 8).padding(.vertical, 5)+ .background(Color.white.opacity(0.07))+ .clipShape(RoundedRectangle(cornerRadius: 8))+ Button(isLast ? "Send" : "Next") {+ commitOtherAndProceed(q: q, qi: qi, isLast: isLast)+ }+ .buttonStyle(.plain)+ .font(.system(size: 11, weight: .medium))+ .foregroundColor(curOtherText.isEmpty ? Color(hex: "#6B7079") : Color(hex: "#F5F6F8"))+ .padding(.horizontal, 8).padding(.vertical, 5)+ .background(Color.white.opacity(curOtherText.isEmpty ? 0.05 : 0.15))+ .clipShape(Capsule())+ .disabled(curOtherText.isEmpty)+ Button { if qi < showOther.count { showOther[qi] = false } } label: {+ Text("✕").font(.system(size: 9))+ }+ .buttonStyle(.plain)+ .foregroundColor(Color(hex: "#6B7079"))+ }+ } else {+ ChipFlowLayout(spacing: 6) {+ ForEach(Array(item.options.enumerated()), id: \.offset) { idx, opt in+ let isSelected = curSel.contains(opt.label)+ if isMulti {+ Button {+ toggleSelection(qi: qi, label: opt.label)+ } label: {+ Text(opt.label)+ .font(.system(size: 12, weight: .medium))+ .padding(.horizontal, 8).padding(.vertical, 4)+ .background(isSelected ? Color(hex: "#22D3EE").opacity(0.22) : Color.white.opacity(0.07))+ .foregroundColor(isSelected ? Color(hex: "#67E8F9") : Color(hex: "#C5C8CD"))+ .clipShape(RoundedRectangle(cornerRadius: 7))+ .overlay(RoundedRectangle(cornerRadius: 7).stroke(isSelected ? Color(hex: "#22D3EE").opacity(0.55) : Color.white.opacity(0.1), lineWidth: 1))+ }+ .buttonStyle(.plain)+ .keyboardShortcut(KeyEquivalent(Character(String(idx + 1))), modifiers: [])+ } else {+ SecondaryButton(opt.label) {+ selectAndProceed(q: q, qi: qi, label: opt.label, isLast: isLast)+ }+ .keyboardShortcut(KeyEquivalent(Character(String(idx + 1))), modifiers: [])+ }+ }+ // "Other…" implicit free-text option+ SecondaryButton("Other…") {+ if qi < showOther.count { showOther[qi] = true }+ }+ }+ }+ // Send/Next — only for multi-select (and not while "Other…" field is open)+ if isMulti && !curOther {+ PrimaryButton(isLast ? "Send" : "Next") {+ proceedFromQuestion(q: q, qi: qi, isLast: isLast)+ }+ .disabled(!canProceed)+ .opacity(canProceed ? 1 : 0.4)}}+ .padding(.leading, 116)+ .padding(.trailing, 16)+ .padding(.vertical, 4)+ .frame(maxWidth: .infinity, alignment: .leading)}- .padding(.leading, 116)- .padding(.trailing, 16)- .padding(.vertical, 4)- .frame(maxWidth: .infinity, alignment: .leading)}+ .onAppear { resetQuestionState() }+ .onChange(of: state.pendingQuestion) { _, _ in resetQuestionState() }+ .onDisappear { HookServer.shared.releaseQuestionFD() }+ }++ private func resetQuestionState() {+ questionIndex = 0+ let count = state.pendingQuestion?.questions.count ?? 0+ selections = Array(repeating: [], count: count)+ otherTexts = Array(repeating: "", count: count)+ showOther = Array(repeating: false, count: count)+ }++ private func toggleSelection(qi: Int, label: String) {+ guard qi < selections.count else { return }+ if let i = selections[qi].firstIndex(of: label) {+ selections[qi].remove(at: i)+ } else {+ selections[qi].append(label)+ }+ }++ // Single-select: pick a label and immediately advance/send+ private func selectAndProceed(q: AskQuestion, qi: Int, label: String, isLast: Bool) {+ guard qi < selections.count else { return }+ selections[qi] = [label]+ if isLast { sendAnswers(q: q) } else { withAnimation { questionIndex = qi + 1 } }+ }++ // Multi-select Send/Next button+ private func proceedFromQuestion(q: AskQuestion, qi: Int, isLast: Bool) {+ if isLast { sendAnswers(q: q) } else { withAnimation { questionIndex = qi + 1 } }+ }++ // "Other…" confirm+ private func commitOtherAndProceed(q: AskQuestion, qi: Int, isLast: Bool) {+ let text = qi < otherTexts.count ? otherTexts[qi] : ""+ guard !text.isEmpty else { return }+ if qi < selections.count { selections[qi] = [text] }+ if isLast {+ sendAnswers(q: q)+ } else {+ if qi < showOther.count { showOther[qi] = false }+ withAnimation { questionIndex = qi + 1 }+ }+ }++ private func sendAnswers(q: AskQuestion) {+ let answers = AskQuestion.buildAnswers(questions: q.questions, selections: selections)+ HookServer.shared.sendQuestionAnswers(answers)}}@@ -920,8 +1080,8 @@ struct PromptView: View {// MARK: - Model / provider picker-/// Wrapping horizontal flow layout for provider chips.-private struct ProviderChipFlow: Layout {+/// Wrapping horizontal flow layout — used by ModelPickerView and QuestionView.+struct ChipFlowLayout: Layout {var spacing: CGFloat = 6func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) -> CGSize {let r = rows(maxW: proposal.replacingUnspecifiedDimensions().width, subviews: subviews)@@ -960,7 +1120,7 @@ struct ModelPickerView: View {if p == .lmstudio { return !AppState.shared.lmstudioServerURL.isEmpty || state.chatProvider == .lmstudio }return true}- ProviderChipFlow(spacing: 6) {+ ChipFlowLayout(spacing: 6) {ForEach(visibleProviders, id: \.self) { provider inButton {guard provider != state.chatProvider else { return }diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swiftindex 21f0ff45..d3ea42ac 100644--- a/NotchBuddy/Sources/App/SettingsView.swift+++ b/NotchBuddy/Sources/App/SettingsView.swift@@ -330,7 +330,7 @@ struct SettingsView: View {HStack(spacing: 6) {Image(systemName: "exclamationmark.triangle.fill").foregroundColor(.orange)- Text("Hook timeout outdated — update to fix approvals")+ Text("Hooks outdated — update them to answer Claude's questions from the notch").font(.system(size: 11)).foregroundColor(.orange)}diff --git a/README.md b/README.mdindex d2e14637..59d88d36 100644--- a/README.md+++ b/README.md@@ -33,7 +33,7 @@ Meet **Mochi**: a soft little squircle with big eyes that pops out of your notch## Features- 🤖 **Claude Code, Cursor, Codex, Gemini CLI, Antigravity and other agents, live** — see every session in your notch: what it reads, edits and runs, step by step. Tag a hook payload with `coucou_agent` to give any agent its own pill (see [`docs/AGENTS.md`](docs/AGENTS.md)). Finished? Mochi does a happy little jump.-- ✅ **Approve from the notch** — Claude Code and Codex permission requests show up with **Allow / Deny** (and **Always** for Claude Code), in VS Code, Cursor's terminal, or Codex. One click, back to work.+- ✅ **Approve and answer from the notch** — Claude Code permission requests show up with **Allow / Deny / Always**; `AskUserQuestion` prompts show the choices right in the notch (single or multi-select, up to 4 questions). One click, or "Reply in terminal" to fall back to the CLI. Codex also gets Allow / Deny.- 🧑💻 **Jump to the right terminal** — open the exact terminal window of a session *(macOS)*.- 💬 **Chat with Claude, Gemini, OpenAI, or a local model (Ollama / LM Studio)** — click the model name above the chat box to switch provider and pick a model. Cloud providers use your own API key; local providers connect to a server running on your Mac. *(Gemini, OpenAI and local models: macOS)*- 📊 **Claude plan usage** *(macOS, GitHub build)* — a small pill in the notch header shows your 5-hour and weekly Claude plan limits. Enable it from Settings → Agents → Plan usage. Pro and Max plans only.diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.mdindex edbec867..4b1e58f5 100644--- a/docs/INTEGRATIONS.md+++ b/docs/INTEGRATIONS.md@@ -45,9 +45,17 @@ Vérifier dans la doc la liste exacte des événements et leurs champs.- « Toujours autoriser » : si la doc permet de renvoyer une règle de permission persistante, l'utiliser. Sinon l'app garde sa propre liste (projet + outil + motif de commande) et répond `allow` automatiquement ensuite. Liste visible et supprimable dans les réglages.- Raccourcis Y / N quand la vue `approval` est ouverte.-### Répondre aux questions-- Si Claude utilise l'outil de question (`AskUserQuestion`), l'intercepter en `PreToolUse` et afficher les options dans la vue `question`.-- Vérifier dans la doc si un hook peut fournir la réponse. Si oui : clic sur une option = réponse. **Si non** : la vue affiche la question et un bouton « Répondre dans le terminal » qui saute à la session. Ne pas bricoler de frappe clavier simulée.+### Répondre aux questions (`AskUserQuestion`)+- **Claude Code 2.1.85+** : `AskUserQuestion` arrive en `PreToolUse` (avec `matcher: "AskUserQuestion"`), non plus en `PermissionRequest`. Un hook dédié avec `--ask` et un timeout de 130 s est requis dans `settings.json`. Si ce hook manque, l'app affiche la bannière « Hooks outdated — update them to answer Claude's questions from the notch » dans les réglages et propose la mise à jour.+- `PermissionRequest` pour `AskUserQuestion` : l'app répond `{"permissionDecision":"ask"}` immédiatement (no-op) et n'affiche pas de carte.+- `PreToolUse` général pour `AskUserQuestion` : l'app ignore l'événement (pas de mise à jour de l'état `.working`).+- `tool_input.questions` : tableau de 1 à 4 questions, chacune avec `question` (texte), `header` (≤ 12 car.), `options` (2 à 4, chacune `label` + `description`), `multiSelect`.+- L'app parse en un modèle Foundation (`AskQuestion`) ; si le parse échoue, nb-hook.py n'émet rien → Claude Code re-pose la question dans le terminal.+- La vue `question` affiche une question à la fois (compteur 1/N), les options en grille fluide (`ChipFlowLayout`), un champ libre « Other… », et un lien « Reply in terminal » dans l'en-tête (envoie `ask`, aucune sortie).+- Single-select : clic = réponse immédiate (pas de bouton Send). Multi-select : toggles + bouton Send/Next, désactivé tant qu'aucun choix.+- Réponse via socket : `{"decision":"answer","answers":{"<question>":"<label>"}}`. Multi-select : valeur `[String]` (tableau, Claude Code 2.1.136+). Single-select et « Other… » : valeur `String`.+- nb-hook.py `--ask` : si `decision == 'answer'` → émet `hookSpecificOutput` avec `hookEventName: "PreToolUse"`, `permissionDecision: "allow"` et `updatedInput: {questions, answers}` — Claude Code reçoit les réponses et continue.+- Fallback : si l'app ne répond pas (absente, timeout 125 s) ou renvoie `ask`, nb-hook n'émet rien → Claude Code re-pose la question dans le terminal.### Sauter au terminal| Contexte capté | Action |diff --git a/docs/SPEC.md b/docs/SPEC.mdindex c9bd6aed..3a0a41dd 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -67,7 +67,7 @@ rouge `rgba(244,80,94,.55)`, vert `rgba(52,211,153,.5)`, rose `rgba(244,114,182,| `overview` | 196 | 64, 70 | carte gauche 322 de large : ligne agent + défilé de tâches ; carte droite : pastilles | 03 || `empty` | 150 | 70, 62 | « Rien ne tourne pour l'instant. » + bouton « Demander à Claude » | 16 || `approval` | 206 | 62, 56 | agent + « Claude Code veut lancer une commande », bloc code, Refuser (N), Toujours autoriser, Autoriser (Y) | 04 |-| `question` | 196 | 62, 56 | agent + question + options en boutons | 05 |+| `question` | 196 | 62, 56 | agent + question (1/N) + options en boutons (single-select ou multi-select) + « Reply in terminal » ; bouton Send/Next pour multi-select ou multi-questions ; « Other… » → saisie libre | 05 || `error` | 190 | 62, 58 | agent + outil, titre, détail en rouge `#FF8D97`, Relancer, Ouvrir dans n8n | 06 || `finished` | 170 | 62, 58 | agent + résumé, Voir le terminal, OK | 07 || `confused` | 160 | 76, 66 | « Trop de claques d'un coup. » | 08 |diff --git a/scripts/test-ask-question.sh b/scripts/test-ask-question.shnew file mode 100755index 00000000..c1c5aba6--- /dev/null+++ b/scripts/test-ask-question.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")/.."+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-ask-question.XXXXXX")"+trap 'rm -rf "$TEST_DIR"' EXIT+swiftc NotchBuddy/Sources/App/AskQuestion.swift \+ tests/AskQuestionTests.swift -o "$TEST_DIR/ask-question-tests"+"$TEST_DIR/ask-question-tests"diff --git a/tests/AskQuestionTests.swift b/tests/AskQuestionTests.swiftnew file mode 100644index 00000000..981b7242--- /dev/null+++ b/tests/AskQuestionTests.swift@@ -0,0 +1,121 @@+import Foundation++@main+enum AskQuestionTests {++ static var failures = 0++ static func check(_ label: String, _ got: String, _ expected: String) {+ if got == expected {+ print(" ✓ \(label)")+ } else {+ print(" ✗ \(label)")+ print(" got: \(got.debugDescription)")+ print(" expected: \(expected.debugDescription)")+ failures += 1+ }+ }++ static func checkTrue(_ label: String, _ value: Bool) {+ if value { print(" ✓ \(label)") }+ else { print(" ✗ \(label)"); failures += 1 }+ }++ static func main() {+ let opt1: [String: Any] = ["label": "Postgres", "description": "Full-text search"]+ let opt2: [String: Any] = ["label": "Meilisearch", "description": ""]+ let opt3: [String: Any] = ["label": "Algolia", "description": "Managed search"]++ // ── parse ──────────────────────────────────────────────────────────────+ print("AskQuestion.parse")++ let single: [String: Any] = ["questions": [+ ["question": "Which search engine?", "header": "Search", "options": [opt1, opt2, opt3], "multiSelect": false]+ ]]+ let parsed = AskQuestion.parse(toolInput: single)+ checkTrue("single question parses", parsed != nil)+ checkTrue("question text", parsed?.questions[0].question == "Which search engine?")+ checkTrue("header", parsed?.questions[0].header == "Search")+ checkTrue("3 options", parsed?.questions[0].options.count == 3)+ checkTrue("multiSelect false", parsed?.questions[0].multiSelect == false)+ checkTrue("option label", parsed?.questions[0].options[0].label == "Postgres")++ // header truncated at 12 chars+ let longHeader: [String: Any] = ["questions": [+ ["question": "Q?", "header": "This is a very long header", "options": [opt1, opt2], "multiSelect": false]+ ]]+ let lh = AskQuestion.parse(toolInput: longHeader)+ checkTrue("header truncated to 12", lh?.questions[0].header.count == 12)++ // multiSelect true+ let multi: [String: Any] = ["questions": [+ ["question": "Pick features", "header": "Features", "options": [opt1, opt2, opt3], "multiSelect": true]+ ]]+ let mParsed = AskQuestion.parse(toolInput: multi)+ checkTrue("multiSelect true", mParsed?.questions[0].multiSelect == true)++ // 4 questions (max)+ let q: [String: Any] = ["question": "Q?", "header": "", "options": [opt1, opt2], "multiSelect": false]+ let four: [String: Any] = ["questions": [q, q, q, q]]+ checkTrue("4 questions parses", AskQuestion.parse(toolInput: four) != nil)++ // 5 questions → nil (over max)+ let five: [String: Any] = ["questions": [q, q, q, q, q]]+ checkTrue("5 questions → nil", AskQuestion.parse(toolInput: five) == nil)++ // 1 option → nil (under min)+ let oneOpt: [String: Any] = ["questions": [+ ["question": "Q?", "header": "", "options": [opt1], "multiSelect": false]+ ]]+ checkTrue("1 option → nil", AskQuestion.parse(toolInput: oneOpt) == nil)++ // missing question text → nil+ let noQ: [String: Any] = ["questions": [+ ["header": "", "options": [opt1, opt2], "multiSelect": false]+ ]]+ checkTrue("missing question → nil", AskQuestion.parse(toolInput: noQ) == nil)++ // empty questions array → nil+ checkTrue("empty questions → nil", AskQuestion.parse(toolInput: ["questions": []]) == nil)++ // missing questions key → nil+ checkTrue("missing questions → nil", AskQuestion.parse(toolInput: [:]) == nil)++ // option with empty label → nil+ let emptyLabel: [String: Any] = ["questions": [+ ["question": "Q?", "header": "", "options": [["label": "", "description": ""], opt2], "multiSelect": false]+ ]]+ checkTrue("empty option label → nil", AskQuestion.parse(toolInput: emptyLabel) == nil)++ // ── buildAnswers ───────────────────────────────────────────────────────+ print("AskQuestion.buildAnswers")++ let items = AskQuestion.parse(toolInput: multi)!.questions+ + AskQuestion.parse(toolInput: single)!.questions++ // items[0] = "Pick features" (multiSelect: true), items[1] = "Which search engine?" (multiSelect: false)+ let sel1 = [["Postgres"], ["Meilisearch"]]+ let ans1 = AskQuestion.buildAnswers(questions: items, selections: sel1)+ checkTrue("multi-select single pick → [String]", (ans1["Pick features"] as? [String]) == ["Postgres"])+ checkTrue("single-select answer → String", (ans1["Which search engine?"] as? String) == "Meilisearch")++ // Multi-select with multiple picks → [String] array+ let sel2 = [["Postgres", "Algolia"], []]+ let ans2 = AskQuestion.buildAnswers(questions: items, selections: sel2)+ checkTrue("multi-select multiple picks → [String]", (ans2["Pick features"] as? [String]) == ["Postgres", "Algolia"])+ checkTrue("unanswered question omitted", ans2["Which search engine?"] == nil)++ // Empty selections → empty dict+ let ans3 = AskQuestion.buildAnswers(questions: items, selections: [[], []])+ checkTrue("all empty → empty dict", ans3.isEmpty)++ // ── finish ─────────────────────────────────────────────────────────────+ if failures == 0 {+ print("\nAll tests passed.")+ exit(0)+ } else {+ print("\n\(failures) test(s) failed.")+ exit(1)+ }+ }+}