diff --git a/README.md b/README.md index 165af59c4..f044bf4ed 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ Reorder or hide panel sections, choose a compact layout, and export settings to - **Dynamic Island.** Keep music, notifications, calendars, timers, downloads and everyday controls around the camera cutout, or a simulated one on other Macs. Customize sections and shortcuts, with optional lyrics, a live equalizer, camera preview and file tools. - **AI agents.** Follow Claude, Codex, OpenCode and GitHub Copilot in the Dynamic Island: plan limits and when they reset where available, tokens, API value, models, projects and live work, with a notice when a long task finishes. Codex's banked resets can be used from there too, and each extra Codex account (`CODEX_HOME`) can have a limits card of its own. Copilot uses local CLI/app session logs; its token totals update when shutdown metrics arrive, and aggregate API-value estimates use base rates. -- **Claude Code sessions.** See every Claude Code session running on your Mac in the Dynamic Island: its folder and branch, whether it works, runs a tool, waits on you or is done, its latest tools, tasks, subagents and cost. Answer its permission prompts with the whole command in view, jump to its Terminal tab or Antigravity window, and type a reply that reaches it as if typed there. Enlarge a session's page to read the whole conversation at a text size you pick and write a longer reply. Permission prompts use opt-in Claude Code hooks; prompts and replies stay unread unless you turn on previews. +- **Claude Code sessions.** See every Claude Code session running on your Mac in the Dynamic Island: its folder and branch, whether it works, runs a tool, waits on you or is done, its latest tools, tasks, subagents and cost. Answer its permission prompts with the whole command in view, pick an answer to the questions Claude asks, or write your own, jump to its Terminal tab or Antigravity window, and type a reply that reaches it as if typed there. Enlarge a session's page to read the whole conversation at a text size you pick and write a longer reply. Permission prompts and questions use opt-in Claude Code hooks; prompts and replies stay unread unless you turn on previews. - **Command Bar.** Search apps, windows, files, clipboard history, snippets and app menu commands from one field. Calculate, convert units, find emoji or run saved scripts. - **Quick panel.** Open a floating palette of favorite tools with ⌃⌘V. - **Quick toggles.** Switch appearance, hide desktop icons, eject disks, empty the Trash, lock the screen and more. diff --git a/Sources/Vorssaint/Core/NotchClaudeSessionStrings.swift b/Sources/Vorssaint/Core/NotchClaudeSessionStrings.swift index 442b75fc9..c5f3fcbca 100644 --- a/Sources/Vorssaint/Core/NotchClaudeSessionStrings.swift +++ b/Sources/Vorssaint/Core/NotchClaudeSessionStrings.swift @@ -19,6 +19,12 @@ struct NotchClaudeSessionStrings { let alwaysAllow: String let deny: String let answerInTerminal: String + let question: String + let pickAny: String + let ownAnswer: String + let sendAnswer: String + let skip: String + let questionHint: String let open: String let enlarge: String let leftRunningFormat: String @@ -128,6 +134,12 @@ extension NotchClaudeSessionStrings { alwaysAllow: "Always", deny: "Deny", answerInTerminal: "Answer this one in the terminal.", + question: "Claude asks", + pickAny: "Pick any that apply", + ownAnswer: "Or write your own answer…", + sendAnswer: "Answer", + skip: "Skip", + questionHint: "Your answer goes straight to Claude. Return sends what you wrote, and ⌘N skips the question.", open: "Open", enlarge: "Enlarge", leftRunningFormat: "%d left running", @@ -167,7 +179,7 @@ extension NotchClaudeSessionStrings { contentPreview: "Show previews", contentPreviewHint: "Shows titles, commands, file names and the conversation. They stay in memory and are cleared when you turn this off.", hooksTitle: "Claude Code hooks", - hooksHint: "Hooks let the island show which tool runs and answer permission prompts. They’re added to ~/.claude/settings.json next to your own, with a backup first. Without the app running, Claude Code asks in the terminal as usual.", + hooksHint: "Hooks let the island show which tool runs, answer permission prompts and answer Claude’s questions. They’re added to ~/.claude/settings.json next to your own, with a backup first. Without the app running, Claude Code asks in the terminal as usual.", hooksInstalled: "Installed", hooksMissing: "Not installed", installHooks: "Install Hooks", diff --git a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeHookMessage.swift b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeHookMessage.swift index e25e0b61a..55b0f7be3 100644 --- a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeHookMessage.swift +++ b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeHookMessage.swift @@ -11,6 +11,8 @@ struct ClaudeHookMessage { /// The rules Claude Code offered to stop asking, handed back as they came /// when the person picks Always. let suggestions: Any? + /// The input of a question, handed back whole with the answers. + var questionInput: [String: Any]? = nil var isPermissionRequest: Bool { if case .permissionRequested = fact.event { return true } @@ -28,6 +30,7 @@ struct ClaudeHookMessage { let toolID = json["tool_use_id"] as? String ?? "" let agent = (json["agent_id"] as? String).flatMap { $0.isEmpty ? nil : $0 } var suggestions: Any? + var questionInput: [String: Any]? let event: ClaudeHookFact.Event // Subagent events name the subagent they are about; any other event // carrying an agent comes from inside that subagent. @@ -44,15 +47,24 @@ struct ClaudeHookMessage { case "PostToolUse", "PostToolUseFailure": guard !toolID.isEmpty else { return nil } event = .toolFinished(id: toolID, failed: name == "PostToolUseFailure") + case "PermissionRequest" where tool == ClaudeQuestion.tool && ClaudeQuestion.questions(in: input) == nil: + // A question the island cannot show is asked in the terminal, never + // allowed without its answers. + event = .other(name) case "PermissionRequest": let offered = json["permission_suggestions"] as? [Any] ?? [] suggestions = offered.isEmpty ? nil : offered + // A question Claude asks comes as a permission for its tool; the + // answers go back in the tool's input. + let questions = tool == ClaudeQuestion.tool ? ClaudeQuestion.questions(in: input) ?? [] : [] + if !questions.isEmpty { questionInput = input } event = .permissionRequested(ClaudePermission( requestID: requestID, tool: tool.isEmpty ? "Tool" : tool, - summary: ClaudeToolSummary.summary(name: tool, input: input), + summary: questions.first.map { ClaudeToolSummary.clip($0.question) } + ?? ClaudeToolSummary.summary(name: tool, input: input), detail: ClaudeToolSummary.permissionDetail(name: tool, input: input), - offersAlways: !offered.isEmpty, since: now, - inputKey: ClaudeToolSummary.inputKey(name: tool, input: input))) + offersAlways: !offered.isEmpty && questions.isEmpty, since: now, + inputKey: ClaudeToolSummary.inputKey(name: tool, input: input), questions: questions)) case "Notification": event = .notification(type: json["notification_type"] as? String ?? "") case "Stop": let text = policy.previews ? (json["last_assistant_message"] as? String).map(preview) : nil @@ -69,7 +81,7 @@ struct ClaudeHookMessage { } return ClaudeHookMessage( fact: ClaudeHookFact(sessionID: session, date: now, event: event, agentID: from), - transcript: json["transcript_path"] as? String, suggestions: suggestions) + transcript: json["transcript_path"] as? String, suggestions: suggestions, questionInput: questionInput) } private static func preview(_ text: String) -> String? { @@ -81,20 +93,30 @@ struct ClaudeHookMessage { enum Decision: Equatable { case allow, allowAlways, deny + /// What the person picked or typed for each question, by its text. + case answer([String: [String]]) } static let denyMessage = "Denied from the Dynamic Island." + static let skipMessage = "The user skipped the question from the Dynamic Island without answering." /// What the hook prints for Claude Code. Always adds the rules Claude Code - /// offered, so it stops asking for the same thing. - static func reply(_ decision: Decision, suggestions: Any?) -> Data { + /// offered, so it stops asking for the same thing. Answers go back in the + /// question's own input, unchanged but for them. + static func reply(_ decision: Decision, suggestions: Any?, input: [String: Any]? = nil) -> Data { var body: [String: Any] switch decision { case .allow: body = ["behavior": "allow"] case .allowAlways: body = ["behavior": "allow"] if let suggestions { body["updatedPermissions"] = suggestions } - case .deny: body = ["behavior": "deny", "message": denyMessage] + case .deny: body = ["behavior": "deny", "message": input == nil ? denyMessage : skipMessage] + case .answer(let answers): + guard var updated = input else { return Data() } + // One answer goes as text; several, for a question that takes + // more than one, as a list. + updated["answers"] = answers.mapValues { picked -> Any in picked.count == 1 ? picked[0] : picked } + body = ["behavior": "allow", "updatedInput": updated] } let output: [String: Any] = ["hookSpecificOutput": ["hookEventName": "PermissionRequest", "decision": body]] return (try? JSONSerialization.data(withJSONObject: output, options: [.sortedKeys])) ?? Data() diff --git a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionEngine.swift b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionEngine.swift index 40acc71ba..4a20cbc4d 100644 --- a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionEngine.swift +++ b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionEngine.swift @@ -220,7 +220,8 @@ final class ClaudeSessionEngine { /// The phase the rules above give one session. static func phase(record: ClaudeSessionRecord, activity entry: Activity, now: Date) -> ClaudeSessionPhase { - if !entry.permissions.isEmpty { return .waitingPermission } + // A question Claude asks waits on the person's answer, not a permission. + if let first = entry.permissions.first { return first.asksQuestions ? .waitingInput : .waitingPermission } if record.status == .waiting { guard record.waitingFor == ClaudeSessionRecord.dialogOpen else { return record.waitingFor == ClaudeSessionRecord.permissionPrompt ? .waitingPermission : .waitingInput diff --git a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionModels.swift b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionModels.swift index b1de4eb24..61260377b 100644 --- a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionModels.swift +++ b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionModels.swift @@ -117,9 +117,58 @@ struct ClaudePermission: Equatable { var toolID: String? = nil /// Matches the tool call whose input this is. var inputKey: Int? = nil + /// What Claude asks the person to choose, when the request is for a + /// question rather than a tool; it is answered, not allowed. + var questions: [ClaudeQuestion] = [] + + var asksQuestions: Bool { !questions.isEmpty } /// A request short enough to read whole on one line of the list. - var fitsOnALine: Bool { !detail.contains("\n") && detail.count <= ClaudeToolSummary.quickDecisionLimit } + var fitsOnALine: Bool { + !asksQuestions && !detail.contains("\n") && detail.count <= ClaudeToolSummary.quickDecisionLimit + } +} + +/// One question Claude asks through AskUserQuestion, with the answers it +/// wrote for it. Shown even with previews off, like a permission's detail: +/// nobody can answer what they cannot read. +struct ClaudeQuestion: Equatable { + struct Option: Equatable { + let label: String + var description: String? = nil + /// A mockup or snippet the option stands for, shown once it is picked. + var preview: String? = nil + } + + static let tool = "AskUserQuestion" + /// Claude Code takes at most four questions of four options each, and + /// refuses answers longer than 32,768 UTF-16 units in all; each answer + /// written by hand keeps to a share of that, leaving room for the choices. + static let ownAnswerLimit = 7_500 + + let question: String + var header: String? = nil + var options: [Option] = [] + var multiSelect = false + + /// The questions of the tool's input, or nil when it holds none that + /// can be shown. + static func questions(in input: [String: Any]) -> [ClaudeQuestion]? { + guard let list = input["questions"] as? [[String: Any]] else { return nil } + let questions = list.compactMap { item -> ClaudeQuestion? in + guard let text = item["question"] as? String, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + else { return nil } + let options = (item["options"] as? [[String: Any]] ?? []).compactMap { option -> Option? in + guard let label = option["label"] as? String, !label.isEmpty else { return nil } + return Option(label: label, description: (option["description"] as? String).flatMap { $0.isEmpty ? nil : $0 }, + preview: (option["preview"] as? String).flatMap { $0.isEmpty ? nil : $0 }) + } + return ClaudeQuestion(question: text, header: (item["header"] as? String).flatMap { $0.isEmpty ? nil : $0 }, + options: options, multiSelect: item["multiSelect"] as? Bool ?? false) + } + // Every question needs an answer Claude Code can match to it. + return questions.isEmpty || questions.count != list.count ? nil : questions + } } struct ClaudeSubagent: Equatable, Identifiable { diff --git a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionService.swift b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionService.swift index d2498385e..446148780 100644 --- a/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionService.swift +++ b/Sources/Vorssaint/Services/ClaudeSessions/ClaudeSessionService.swift @@ -71,7 +71,8 @@ final class ClaudeSessionService: ObservableObject { private var lastRecords: [Int32: ClaudeSessionRecord] = [:] private var server: ClaudeHookServer? /// Permission requests whose hook waits for the island's answer. - private var pending: [String: (connection: ClaudeHookServer.Connection, session: String, suggestions: Any?, since: Date)] = [:] + private var pending: [String: (connection: ClaudeHookServer.Connection, session: String, suggestions: Any?, + question: [String: Any]?, since: Date)] = [:] /// Claude Code gives up on a hook after its timeout; the island lets go first. private static let permissionDeadline: TimeInterval = TimeInterval(ClaudeHookInstaller.permissionTimeout - 10) @@ -198,8 +199,16 @@ final class ClaudeSessionService: ObservableObject { guard let shown = shownRequests[id], shown.request == request, Date().timeIntervalSince(shown.at) >= NotchClaudeSessionsSupport.settleDelay else { return } queue.async { [self] in - guard engine.holds(request, for: id), let waiting = pending.removeValue(forKey: request) else { return } - waiting.connection.finish(ClaudeHookMessage.reply(decision, suggestions: waiting.suggestions)) + guard engine.holds(request, for: id), let asked = pending[request] else { return } + // A question is answered or skipped, never allowed as it stands; + // answers go only to a question. + switch decision { + case .allow, .allowAlways: guard asked.question == nil else { return } + case .answer: guard asked.question != nil else { return } + case .deny: break + } + pending[request] = nil + asked.connection.finish(ClaudeHookMessage.reply(decision, suggestions: asked.suggestions, input: asked.question)) engine.resolvePermission(requestID: request) engine.acknowledge(id, now: Date()) publish(now: Date()) @@ -309,7 +318,7 @@ final class ClaudeSessionService: ObservableObject { } if let transcript = message.transcript, !transcript.isEmpty { transcripts[message.fact.sessionID] = transcript } if message.isPermissionRequest { - pending[request] = (connection, message.fact.sessionID, message.suggestions, now) + pending[request] = (connection, message.fact.sessionID, message.suggestions, message.questionInput, now) } else { connection.finish() } diff --git a/Sources/Vorssaint/Services/Notch/NotchClaudeSessionsSupport.swift b/Sources/Vorssaint/Services/Notch/NotchClaudeSessionsSupport.swift index 2df34c33a..97b7556a5 100644 --- a/Sources/Vorssaint/Services/Notch/NotchClaudeSessionsSupport.swift +++ b/Sources/Vorssaint/Services/Notch/NotchClaudeSessionsSupport.swift @@ -268,6 +268,39 @@ enum NotchClaudeSessionsSupport { } } + /// What goes back for Claude's questions: for each, the options picked, + /// in the order Claude wrote them, and the person's own words, which + /// take the place of a single choice. Nil until every question has an + /// answer. + static func answers(_ questions: [ClaudeQuestion], picked: [Int: Set], typed: [Int: String]) -> [String: [String]]? { + guard !questions.isEmpty else { return nil } + var answers: [String: [String]] = [:] + for (index, question) in questions.enumerated() { + var chosen = question.options.map(\.label).filter { picked[index]?.contains($0) == true } + let own = clipped((typed[index] ?? "").trimmingCharacters(in: .whitespacesAndNewlines), utf16: ClaudeQuestion.ownAnswerLimit) + if !own.isEmpty { chosen = question.multiSelect ? chosen + [own] : [own] } + if !question.multiSelect { chosen = Array(chosen.prefix(1)) } + guard !chosen.isEmpty else { return nil } + answers[question.question] = chosen + } + return answers + } + + /// The text cut to whole characters within a count of UTF-16 units, the + /// length Claude Code measures. + static func clipped(_ text: String, utf16 limit: Int) -> String { + guard text.utf16.count > limit else { return text } + var used = 0 + var end = text.startIndex + for index in text.indices { + let size = text[index].utf16.count + guard used + size <= limit else { break } + used += size + end = text.index(after: index) + } + return String(text[.. String? { let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) diff --git a/Sources/Vorssaint/Services/Notch/NotchService.swift b/Sources/Vorssaint/Services/Notch/NotchService.swift index 5eae419b6..8d9bfb76e 100644 --- a/Sources/Vorssaint/Services/Notch/NotchService.swift +++ b/Sources/Vorssaint/Services/Notch/NotchService.swift @@ -1875,7 +1875,8 @@ final class NotchService: ObservableObject { } /// ⌘Y allows and ⌘N denies the permission of the session whose page is - /// open, or of the first session waiting on one. + /// open, or of the first session waiting on one. A question is answered + /// on its card; ⌘N skips it only there, where it can be read. private func handleSessionKey(_ event: NSEvent) -> Bool { guard selected == .sessions, !showingAppPanel, !showingSections, selectedMetric == nil, let decision = NotchClaudeSessionsSupport.decision( @@ -1884,8 +1885,9 @@ final class NotchService: ObservableObject { else { return false } let sessions = ClaudeSessionService.shared let focused = sessions.focusedID.flatMap { id in sessions.sessions.first { $0.id == id } } - guard let target = focused ?? sessions.sessions.first(where: { $0.permission != nil }), - let permission = target.permission else { return false } + guard let target = focused ?? sessions.sessions.first(where: { $0.permission.map { !$0.asksQuestions } ?? false }), + let permission = target.permission, + !(permission.asksQuestions && decision != .deny) else { return false } sessions.decide(target.id, request: permission.requestID, decision) return true } @@ -4193,7 +4195,10 @@ final class NotchService: ObservableObject { .joined(separator: " · "), symbol: NotchClaudeSessionsSupport.symbol(.waitingPermission), agent: .claude, sessionID: id)) case .needsInput: - show(NotchNotice(event: .sessions, title: sessions.displayName(session), detail: text.inputNotice, + // A question Claude asks through the hooks is named in the notice. + let question = session.permission?.asksQuestions == true ? session.permission?.summary : nil + show(NotchNotice(event: .sessions, title: sessions.displayName(session), + detail: [text.inputNotice, question ?? ""].filter { !$0.isEmpty }.joined(separator: " · "), symbol: NotchClaudeSessionsSupport.symbol(.waitingInput), agent: .claude, sessionID: id)) case .finished(_, let duration): let locale = L10n.shared.language.formattingLocale() diff --git a/Sources/Vorssaint/UI/Notch/NotchClaudeSessionDetailView.swift b/Sources/Vorssaint/UI/Notch/NotchClaudeSessionDetailView.swift index 4ab8128a8..7a45f685e 100644 --- a/Sources/Vorssaint/UI/Notch/NotchClaudeSessionDetailView.swift +++ b/Sources/Vorssaint/UI/Notch/NotchClaudeSessionDetailView.swift @@ -323,49 +323,16 @@ struct NotchClaudeSessionPermissionCard: View { HStack(spacing: 6) { Image(systemName: NotchClaudeSessionsSupport.symbol(session.phase)) .font(.system(size: 11, weight: .semibold)) - Text(session.permission?.tool ?? session.currentTool?.name ?? session.waitingFor ?? text.phase(session.phase)) + Text(title) .font(.system(size: 12, weight: .semibold)) } .foregroundStyle(session.phase.tint) - if let detail = session.permission?.detail, !detail.isEmpty { - // The whole request, every line of it, so nothing is allowed unread. - ScrollView { - Text(detail) - .font(.system(size: 11, design: .monospaced)) - .foregroundStyle(.white.opacity(0.9)) - .textSelection(.enabled) - .frame(maxWidth: .infinity, alignment: .leading) - .fixedSize(horizontal: false, vertical: true) - } - .frame(maxHeight: 120) - .padding(8) - .background(.black.opacity(0.35), in: RoundedRectangle(cornerRadius: 8, style: .continuous)) - } - HStack(spacing: 6) { - if let permission = session.permission { - NotchClaudeDecisionButton(title: text.deny, symbol: "xmark", role: .deny) { - service.decide(session.id, request: permission.requestID, .deny) - } - .disabled(settling) - Spacer(minLength: 0) - if permission.offersAlways { - NotchClaudeDecisionButton(title: text.alwaysAllow, symbol: "checkmark.seal", role: .secondary) { - service.decide(session.id, request: permission.requestID, .allowAlways) - } - .disabled(settling) - } - NotchClaudeDecisionButton(title: text.allow, symbol: "checkmark", role: .allow) { - service.decide(session.id, request: permission.requestID, .allow) - } - .disabled(settling) - } else { - Text(text.answerInTerminal).font(.system(size: 10.5)).foregroundStyle(.secondary) - Spacer(minLength: 0) - NotchClaudeDecisionButton(title: text.open, symbol: "arrow.up.forward.app", role: .secondary, action: open) - } - } - if session.permission != nil { - Text(text.shortcutsHint).font(.system(size: 9.5)).foregroundStyle(.tertiary) + if let permission = session.permission, permission.asksQuestions { + NotchClaudeQuestionForm(session: session, permission: permission, text: text, settling: settling) + // Answers picked for one question never carry over to the next. + .id(permission.requestID) + } else { + request } } .padding(10) @@ -382,6 +349,228 @@ struct NotchClaudeSessionPermissionCard: View { .strokeBorder(session.phase.tint.opacity(0.35), lineWidth: 1) } } + + private var title: String { + if session.permission?.asksQuestions == true { return text.question } + return session.permission?.tool ?? session.currentTool?.name ?? session.waitingFor ?? text.phase(session.phase) + } + + /// A tool's request, read whole and allowed or denied. + @ViewBuilder private var request: some View { + if let detail = session.permission?.detail, !detail.isEmpty { + // The whole request, every line of it, so nothing is allowed unread. + ScrollView { + Text(detail) + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(.white.opacity(0.9)) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + } + .frame(maxHeight: 120) + .padding(8) + .background(.black.opacity(0.35), in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + } + HStack(spacing: 6) { + if let permission = session.permission { + NotchClaudeDecisionButton(title: text.deny, symbol: "xmark", role: .deny) { + service.decide(session.id, request: permission.requestID, .deny) + } + .disabled(settling) + Spacer(minLength: 0) + if permission.offersAlways { + NotchClaudeDecisionButton(title: text.alwaysAllow, symbol: "checkmark.seal", role: .secondary) { + service.decide(session.id, request: permission.requestID, .allowAlways) + } + .disabled(settling) + } + NotchClaudeDecisionButton(title: text.allow, symbol: "checkmark", role: .allow) { + service.decide(session.id, request: permission.requestID, .allow) + } + .disabled(settling) + } else { + Text(text.answerInTerminal).font(.system(size: 10.5)).foregroundStyle(.secondary) + Spacer(minLength: 0) + NotchClaudeDecisionButton(title: text.open, symbol: "arrow.up.forward.app", role: .secondary, action: open) + } + } + if session.permission != nil { + Text(text.shortcutsHint).font(.system(size: 9.5)).foregroundStyle(.tertiary) + } + } +} + +/// Claude's questions with the answers it wrote for them. One question with +/// a single choice is answered by clicking it, as in the terminal; otherwise +/// the person picks for each and sends them together. Their own words can +/// stand in for, or join, the choices. +struct NotchClaudeQuestionForm: View { + let session: ClaudeSession + let permission: ClaudePermission + let text: NotchClaudeSessionStrings + /// The request just appeared, so clicks wait a moment. + let settling: Bool + @ObservedObject private var service = ClaudeSessionService.shared + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @State private var picked: [Int: Set] = [:] + @State private var typed: [Int: String] = [:] + @State private var sent = false + + private var questions: [ClaudeQuestion] { permission.questions } + /// A click on an option answers at once, unless options carry previews + /// that the person picks to see. + private var answersOnClick: Bool { + questions.count == 1 && !questions[0].multiSelect && questions[0].options.allSatisfy { $0.preview == nil } + } + private var answers: [String: [String]]? { NotchClaudeSessionsSupport.answers(questions, picked: picked, typed: typed) } + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + ForEach(Array(questions.enumerated()), id: \.offset) { index, question in + questionView(question, index: index) + } + HStack(spacing: 6) { + NotchClaudeDecisionButton(title: text.skip, symbol: "forward", role: .deny) { + service.decide(session.id, request: permission.requestID, .deny) + } + Spacer(minLength: 0) + NotchClaudeDecisionButton(title: text.sendAnswer, symbol: "arrow.up", role: .allow, action: send) + .disabled(answers == nil) + } + .disabled(settling || sent) + Text(text.questionHint).font(.system(size: 9.5)).foregroundStyle(.tertiary) + } + .animation(reduceMotion ? nil : .easeOut(duration: 0.16), value: picked) + } + + private func questionView(_ question: ClaudeQuestion, index: Int) -> some View { + VStack(alignment: .leading, spacing: 6) { + if let header = question.header { + Text(header.uppercased()) + .font(.system(size: 9, weight: .semibold)) + .tracking(0.6) + .foregroundStyle(.white.opacity(0.55)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(.white.opacity(0.08), in: Capsule()) + } + Text(question.question) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(.white.opacity(0.95)) + .fixedSize(horizontal: false, vertical: true) + .textSelection(.enabled) + if question.multiSelect { + Text(text.pickAny).font(.system(size: 10)).foregroundStyle(.secondary) + } + VStack(spacing: 4) { + ForEach(Array(question.options.enumerated()), id: \.offset) { _, option in + optionRow(option, question: question, index: index) + } + } + if let preview = question.options.first(where: { picked[index]?.contains($0.label) == true })?.preview { + ScrollView { + Text(preview) + .font(.system(size: 10.5, design: .monospaced)) + .foregroundStyle(.white.opacity(0.85)) + .frame(maxWidth: .infinity, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + } + .frame(maxHeight: 140) + .padding(8) + .background(.black.opacity(0.35), in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + .transition(.opacity) + } + ownAnswer(question, index: index) + } + } + + private func optionRow(_ option: ClaudeQuestion.Option, question: ClaudeQuestion, index: Int) -> some View { + let selected = picked[index]?.contains(option.label) == true + let tint = session.phase.tint + return Button { + pick(option.label, in: question, index: index) + } label: { + HStack(alignment: .top, spacing: 8) { + marker(selected: selected, multiple: question.multiSelect) + .padding(.top, 1) + VStack(alignment: .leading, spacing: 2) { + Text(option.label) + .font(.system(size: 11.5, weight: .semibold)) + .foregroundStyle(.white.opacity(0.95)) + if let description = option.description { + Text(description) + .font(.system(size: 10.5)) + .foregroundStyle(.white.opacity(0.6)) + .lineLimit(3) + } + } + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 0) + } + .padding(.horizontal, 9) + .padding(.vertical, 7) + .frame(maxWidth: .infinity, minHeight: 32, alignment: .leading) + .background(selected ? tint.opacity(0.18) : .white.opacity(0.06), + in: RoundedRectangle(cornerRadius: 9, style: .continuous)) + .overlay { + RoundedRectangle(cornerRadius: 9, style: .continuous) + .strokeBorder(tint.opacity(selected ? 0.6 : 0), lineWidth: 1) + } + .contentShape(RoundedRectangle(cornerRadius: 9, style: .continuous)) + } + .buttonStyle(NotchButtonStyle(cornerRadius: 9, lifts: false)) + .disabled(settling || sent) + .accessibilityLabel([option.label, option.description].compactMap { $0 }.joined(separator: ", ")) + .accessibilityAddTraits(selected ? .isSelected : []) + } + + /// A box for one of many, a dot for one of a few. + private func marker(selected: Bool, multiple: Bool) -> some View { + Image(systemName: multiple ? (selected ? "checkmark.square.fill" : "square") + : (selected ? "largecircle.fill.circle" : "circle")) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(selected ? session.phase.tint : .white.opacity(0.45)) + .frame(width: 16, height: 16) + } + + private func ownAnswer(_ question: ClaudeQuestion, index: Int) -> some View { + let binding = Binding(get: { typed[index] ?? "" }, set: { value in + typed[index] = value + // A single choice is either picked or written, not both. + if !question.multiSelect, !value.trimmingCharacters(in: .whitespaces).isEmpty { picked[index] = nil } + }) + return TextField(question.options.isEmpty ? text.replyPlaceholder : text.ownAnswer, text: binding) + .textFieldStyle(.plain) + .font(.system(size: 11.5)) + .padding(.horizontal, 9) + .frame(height: 28) + .background(.white.opacity(0.06), in: RoundedRectangle(cornerRadius: 9, style: .continuous)) + .onSubmit(send) + .disabled(settling || sent) + .accessibilityLabel(text.ownAnswer) + } + + private func pick(_ label: String, in question: ClaudeQuestion, index: Int) { + var chosen = picked[index] ?? [] + if question.multiSelect { + if chosen.contains(label) { chosen.remove(label) } else { chosen.insert(label) } + } else { + chosen = [label] + typed[index] = nil + } + picked[index] = chosen.isEmpty ? nil : chosen + if answersOnClick { send() } + } + + private func send() { + guard !settling, !sent, let answers else { return } + sent = true + service.decide(session.id, request: permission.requestID, .answer(answers)) + // The question stays only if the answer did not land, as when it was + // just answered in the terminal; then it can be tried again. + DispatchQueue.main.asyncAfter(deadline: .now() + 2) { sent = false } + } } struct NotchClaudeDecisionButton: View { diff --git a/Sources/Vorssaint/UI/Notch/NotchClaudeSessionsView.swift b/Sources/Vorssaint/UI/Notch/NotchClaudeSessionsView.swift index a847cda36..a1feb305c 100644 --- a/Sources/Vorssaint/UI/Notch/NotchClaudeSessionsView.swift +++ b/Sources/Vorssaint/UI/Notch/NotchClaudeSessionsView.swift @@ -313,7 +313,13 @@ enum NotchClaudeSessionFormat { if let tool = session.currentTool { parts.append(tool.summary.map { "\(tool.name): \($0)" } ?? tool.name) } - case .waitingInput, .generating: + case .waitingInput: + if let permission = session.permission, permission.asksQuestions { + parts.append(permission.summary ?? "") + } else if showsTitle, let title = session.title { + parts.append(title) + } + case .generating: if showsTitle, let title = session.title { parts.append(title) } case .background: if let label = session.backgroundLabel { parts.append(label) } else if showsTitle, let title = session.title { parts.append(title) } diff --git a/Tests/ClaudeHookTests.swift b/Tests/ClaudeHookTests.swift index c3c7bff2b..8ee9f1f69 100644 --- a/Tests/ClaudeHookTests.swift +++ b/Tests/ClaudeHookTests.swift @@ -18,6 +18,67 @@ enum ClaudeHookTests { ClaudeHookMessage.decode(Data(json.utf8), requestID: "r1", now: now, policy: ClaudeContentPolicy(previews: previews)) } + // MARK: Questions + + static func questions(_ suite: TestSuite, base: String, json: (Data) -> [String: Any]) { + let input = #"{"questions":[{"question":"Which color?","header":"Color","options":[{"label":"Red","description":"Warm"},{"label":"Blue","description":"","preview":"[ blue ]"}],"multiSelect":false},{"question":"Which sizes?","header":"","options":[{"label":"S"},{"label":"M"},{"label":"L"}],"multiSelect":true}]}"# + let message = decode(#"{\#(base),"hook_event_name":"PermissionRequest","tool_name":"AskUserQuestion","tool_input":\#(input),"permission_suggestions":[{"type":"addRules"}]}"#) + guard case .permissionRequested(let ask)? = message?.fact.event else { return suite.expect(false, "a question decodes as a request") } + suite.expect(ask.asksQuestions && ask.questions.count == 2 && !ask.fitsOnALine && !ask.offersAlways, + "a question is a request answered on its card, never allowed for good") + suite.expect(ask.summary == "Which color?" && ask.questions[0].header == "Color" && ask.questions[1].header == nil + && ask.questions[0].options == [.init(label: "Red", description: "Warm"), .init(label: "Blue", preview: "[ blue ]")] + && ask.questions[1].multiSelect, + "its questions, options, descriptions and previews are read even with previews off") + suite.expect(message?.questionInput?["questions"] != nil, "the question's input is kept to hand back") + + let bash = decode(#"{\#(base),"hook_event_name":"PermissionRequest","tool_name":"Bash","tool_input":{"command":"ls"}}"#) + suite.expect(bash?.questionInput == nil, "a tool's request keeps no input") + let empty = decode(#"{\#(base),"hook_event_name":"PermissionRequest","tool_name":"AskUserQuestion","tool_input":{"questions":[{"header":"x"}]}}"#) + suite.expect(empty?.fact.event == .other("PermissionRequest") && empty?.isPermissionRequest == false + && empty?.questionInput == nil, + "a question that can't be read is left to the terminal, never allowed unanswered") + + let original = message?.questionInput ?? [:] + let answered = json(ClaudeHookMessage.reply(.answer(["Which color?": ["Blue"], "Which sizes?": ["S", "L"]]), + suggestions: nil, input: original)) + let decision = answered["decision"] as? [String: Any] ?? [:] + let updated = decision["updatedInput"] as? [String: Any] ?? [:] + let answers = updated["answers"] as? [String: Any] ?? [:] + suite.expect(decision["behavior"] as? String == "allow" && answers["Which color?"] as? String == "Blue" + && answers["Which sizes?"] as? [String] == ["S", "L"], + "answers go back by question, one as text and several as a list") + func canonical(_ value: Any?) -> Data? { + value.flatMap { try? JSONSerialization.data(withJSONObject: $0, options: [.sortedKeys]) } + } + suite.expect(canonical(updated["questions"]) != nil && canonical(updated["questions"]) == canonical(original["questions"]), + "the questions go back exactly as Claude asked them") + let skipped = json(ClaudeHookMessage.reply(.deny, suggestions: nil, input: original))["decision"] as? [String: Any] ?? [:] + suite.expect(skipped["behavior"] as? String == "deny" && skipped["message"] as? String == ClaudeHookMessage.skipMessage, + "skipping tells Claude the question went unanswered") + suite.expect(ClaudeHookMessage.reply(.answer(["x": ["y"]]), suggestions: nil).isEmpty, + "answers with no question to hand back leave the terminal to ask") + + let shown = ask.questions + suite.expect(NotchClaudeSessionsSupport.answers(shown, picked: [0: ["Blue"]], typed: [:]) == nil, + "nothing goes until every question has an answer") + suite.expect(NotchClaudeSessionsSupport.answers(shown, picked: [0: ["Blue"], 1: ["L", "S"]], typed: [:]) + == ["Which color?": ["Blue"], "Which sizes?": ["S", "L"]], + "choices keep the order Claude wrote them in") + suite.expect(NotchClaudeSessionsSupport.answers(shown, picked: [0: ["Red"], 1: ["M"]], typed: [0: " Green ", 1: "XL"]) + == ["Which color?": ["Green"], "Which sizes?": ["M", "XL"]], + "an answer written by hand replaces a single choice and joins several") + suite.expect(NotchClaudeSessionsSupport.answers(shown, picked: [0: ["Red", "Blue"], 1: ["M"]], typed: [1: " "]) + == ["Which color?": ["Red"], "Which sizes?": ["M"]], + "a single choice sends one answer, and blank words none") + suite.expect(NotchClaudeSessionsSupport.answers([], picked: [:], typed: [:]) == nil, "no questions, no answers") + let long = String(repeating: "😀", count: 6_000) + let clipped = NotchClaudeSessionsSupport.answers(shown, picked: [1: ["S"]], typed: [0: long, 1: long]) + let units = clipped?.values.flatMap { $0 }.map(\.utf16.count).reduce(0, +) ?? 0 + suite.expect(units > 0 && units <= 32_768 && clipped?["Which color?"]?.first?.unicodeScalars.allSatisfy { $0 == "😀" } == true, + "answers written by hand stay within what Claude Code takes in all, cut at whole characters") + } + // MARK: Messages static func messages(_ suite: TestSuite) { @@ -69,6 +130,8 @@ enum ClaudeHookTests { suite.expect((always["updatedPermissions"] as? [[String: Any]])?.first?["type"] as? String == "addRules", "always hands back the rules Claude Code offered") + questions(suite, base: base, json: json) + suite.expect(ClaudeHookMessage.isComplete(Data(#"{"a":{"b":1}} "#.utf8)), "a whole object is complete") suite.expect(!ClaudeHookMessage.isComplete(Data(#"{"a":{"b":1}"#.utf8)) && !ClaudeHookMessage.isComplete(Data(#"{"a":"}"#.utf8)), "a cut one is not") diff --git a/Tests/ClaudeSessionEngineTests.swift b/Tests/ClaudeSessionEngineTests.swift index 9e0290d52..1864b6a7f 100644 --- a/Tests/ClaudeSessionEngineTests.swift +++ b/Tests/ClaudeSessionEngineTests.swift @@ -310,6 +310,19 @@ enum ClaudeSessionEngineTests { engine.ingest(hook: hook(.stopped(lastText: nil), 9), now: at(9)) suite.expect(engine.permission(of: "s1") == nil, "a turn ending drops its request") + // A question Claude asks waits on an answer, not a permission. + let quiz = ClaudeSessionEngine() + quiz.ingest(records: [record(status: .busy, changed: 0)], now: at(0)) + _ = quiz.snapshot(now: at(1)) + let question = ClaudePermission(requestID: "q1", tool: ClaudeQuestion.tool, summary: "Which color?", offersAlways: false, + since: at(2), questions: [ClaudeQuestion(question: "Which color?", + options: [.init(label: "Red"), .init(label: "Blue")])]) + quiz.ingest(hook: hook(.permissionRequested(question), 2), now: at(2)) + let asked = quiz.snapshot(now: at(3)) + suite.expect(asked.sessions.first?.phase == .waitingInput && asked.events == [.needsInput(id: "s1")] + && asked.sessions.first?.permission?.asksQuestions == true, + "a question waits for the person's answer and says so once") + // Two calls of one tool run side by side: the request belongs to the // one whose input it carries, not the newest. let twin = ClaudeSessionEngine() diff --git a/docs/PERMISSIONS.md b/docs/PERMISSIONS.md index c76bad81f..5e2e3e442 100644 --- a/docs/PERMISSIONS.md +++ b/docs/PERMISSIONS.md @@ -155,7 +155,7 @@ Download monitoring watches only the folder you choose in the system picker. Fol - **Uninstaller**, which moves leftover files to the Trash. - **Empty the Trash** in Quick toggles, which asks Finder to empty it. The other quick toggles, dark mode included, need no permission. - **Homebrew manager**, which can open Terminal with the exact Homebrew install or setup command when the app should not collect a password itself. -- **Dynamic Island Sessions**, which finds the Terminal tab a Claude Code session runs in by its device, brings it forward when you press Open, and types the reply you send from the island into it. Nothing is typed while that session waits on a permission or a question. Sessions in Antigravity go through the extension the page installs instead, which needs no permission. Answering permission prompts from the island goes through Claude Code hooks, which are written to `~/.claude/settings.json` when you press Install Hooks and need no permission either. +- **Dynamic Island Sessions**, which finds the Terminal tab a Claude Code session runs in by its device, brings it forward when you press Open, and types the reply you send from the island into it. Nothing is typed while that session waits on a permission or a question. Sessions in Antigravity go through the extension the page installs instead, which needs no permission. Answering permission prompts and Claude's questions from the island goes through Claude Code hooks, which are written to `~/.claude/settings.json` when you press Install Hooks and need no permission either. - **Dynamic Island playback**, when a music app requires Automation to control its own playback while another app is active. Only playback commands declared by the selected app are used; an explicit button requests permission before a new action can be sent. The shuffle button on the music page reads and switches only the shuffle setting the app declares, and reads whether shuffle is available for what is playing when the app declares that too. Until the app is allowed, its first press only asks for this permission, even for an app whose playback controls work without it. **If you say no.** Those Finder or Terminal handoff steps will not go through, and replies to sessions in Terminal stay unsent; you can still answer in the session's own tab. Music stays visible, and you can open its player to control it there. You can switch Automation back on in System Settings, under Privacy and Security, Automation. diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index 4aa68c0a3..b7e4aca43 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -41,7 +41,7 @@ On new setups, AI Agents stays off until you enable it. Updates preserve your ex The Sessions page is off until you turn it on, and it rides on AI Agents being installed. While it is on, it reads the small records Claude Code keeps in `~/.claude/sessions` (or `~/.config/claude/sessions`) for each running session: the process, the session, the folder it works in, its name and whether it is busy or waiting on you. It checks that each record's process is the one that wrote it, then reads the new lines of that session's transcript under `~/.claude/projects`, its subagents' transcripts and the small description Claude Code keeps beside each, and the task list Claude Code keeps under `~/.claude/tasks`. From these it keeps, in memory only, times, tool names and the identifiers of tool calls, the git branch, the model, token counts and the cost computed as AI Agents computes it, how many tasks are done, and each subagent's type. Prompts, replies, titles, tool arguments, task names and what subagents were asked are not decoded unless you turn on Show previews, which is off by default; with it on they are kept in memory only, shortened (the conversation an enlarged page shows keeps a session's latest 150 prompts and replies), and cleared as soon as you turn it off. To tell which app shows a session, Vorssaint reads that session's terminal device and two variables of its environment, the bundle identifier of the app that started it and the port of the IDE connection, and keeps nothing else from that environment. For a session in Antigravity it also reads the folders the IDE's lock file under `~/.claude/ide` says that window has open, to bring the right window forward. Nothing the page reads is saved or sent. An image you paste or drop into a reply is used where it lies when it is a PNG, JPEG, GIF or WebP file; any other image is saved as a PNG in a folder of the app's own under the system's temporary folder, readable only by your account, so Claude Code can read it, and copies a day old are deleted. When an Antigravity window still runs an extension from before images, until it reloads, the reply names each image's file instead, and a copy goes into the folder Claude Code keeps for that session under `/private/tmp/claude-/`, where Claude reads it without asking. The app keeps an extension you added current by itself. -Permission prompts and live tool activity reach the page through Claude Code hooks, which are added only when you press Install Hooks. They go into `~/.claude/settings.json` next to your own entries, marked as Vorssaint's, after the file is copied aside as `settings.json.vorssaint-