From 731e295ea1dc1bbc7fbf941bf849b00621df61cb Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Wed, 4 Nov 2026 22:34:02 -0800 Subject: [PATCH 1/8] =?UTF-8?q?feat(core):=20#1662=20=E8=BD=A6=E9=81=93=20?= =?UTF-8?q?F=20=E5=91=BD=E4=BB=A4=E6=B3=A8=E5=86=8C=E4=B8=8E=E5=85=B1?= =?UTF-8?q?=E4=BA=AB=E5=A5=91=E7=BA=A6=EF=BC=88=E8=BF=BD=E5=8A=A0=E5=BC=8F?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 注册 ai.configuration.*、ai.pullRequest.*、ai.inlineEdit.*、agent.edits.reversePlan、agent.hooks.validateDraft、mcp.librarySnapshot/validateDraft/batchPlan,更新 rust-core-api.md、i18n 词条与生成结果。 Co-Authored-By: Claude Opus 5.5 --- macos/Resources/en.lproj/Localizable.strings | 23 + .../zh-Hans.lproj/Localizable.strings | 23 + .../AI/MacClaudeConfigurationSource.swift | 162 ------- .../AI/MacCodexConfigurationSource.swift | 164 ------- .../AgentConversationFeatureModelTests.swift | 88 ++-- rust/lithe-agent-host/src/lib.rs | 75 ++- rust/lithe-core/src/agent/mod.rs | 1 + rust/lithe-core/src/ai/mod.rs | 24 +- rust/lithe-core/src/protocol/command.rs | 36 +- rust/lithe-core/src/runtime/dispatcher.rs | 40 +- rust/lithe-core/src/tests/agent.rs | 42 ++ shared/contracts/rust-core-api.md | 161 +++++-- shared/fixtures/agent/acp-events-v1.json | 23 +- .../agent/provider-configuration-v1.json | 147 ------ shared/i18n/locales/en-US.json | 30 ++ shared/i18n/locales/zh-CN.json | 30 ++ shared/i18n/messages.json | 426 ++++++++++++++++-- windows/tauri/src-tauri/src/ai_commit.rs | 146 +++--- windows/tauri/src/i18n/shared.generated.ts | 72 +++ 19 files changed, 1047 insertions(+), 666 deletions(-) delete mode 100644 macos/Sources/Lithe/Platform/MacOS/AI/MacClaudeConfigurationSource.swift delete mode 100644 macos/Sources/Lithe/Platform/MacOS/AI/MacCodexConfigurationSource.swift delete mode 100644 shared/fixtures/agent/provider-configuration-v1.json diff --git a/macos/Resources/en.lproj/Localizable.strings b/macos/Resources/en.lproj/Localizable.strings index f0152bc30a..e9c69f3061 100644 --- a/macos/Resources/en.lproj/Localizable.strings +++ b/macos/Resources/en.lproj/Localizable.strings @@ -5088,6 +5088,29 @@ "agent.history.provider" = "Conversation provider"; "agent.history.providerHint" = "Try another search or provider filter."; "agent.history.unknownProvider" = "Unknown provider"; +"agent.hooks.draft.agents.duplicate" = "Each Agent can be selected only once."; +"agent.hooks.draft.agents.required" = "Select at least one Agent."; +"agent.hooks.draft.agents.unsupported" = "Only Codex and Claude Code support Hooks."; +"agent.hooks.draft.command.containsNul" = "The command cannot contain a NUL character."; +"agent.hooks.draft.command.contains_nul" = "The command cannot contain a NUL character."; +"agent.hooks.draft.command.required" = "Enter a command."; +"agent.hooks.draft.command.tooLong" = "The command can have at most 32768 bytes."; +"agent.hooks.draft.command.too_long" = "The command can have at most 32768 bytes."; +"agent.hooks.draft.description.tooLong" = "The description can have at most 200 characters."; +"agent.hooks.draft.description.too_long" = "The description can have at most 200 characters."; +"agent.hooks.draft.id.invalid" = "This Hook draft has an invalid identifier. Close the editor and try again."; +"agent.hooks.draft.matcher.incompatibleEvent" = "Tool filters apply only to tool events."; +"agent.hooks.draft.matcher.incompatible_event" = "Tool filters apply only to tool events."; +"agent.hooks.draft.name.duplicate" = "A Hook with this name already exists."; +"agent.hooks.draft.name.invalidCharacters" = "Use only letters, digits, hyphens or underscores in the Hook name."; +"agent.hooks.draft.name.invalid_characters" = "Use only letters, digits, hyphens or underscores in the Hook name."; +"agent.hooks.draft.name.required" = "Enter a Hook name."; +"agent.hooks.draft.name.tooLong" = "Hook names can have at most 80 characters."; +"agent.hooks.draft.name.too_long" = "Hook names can have at most 80 characters."; +"agent.hooks.draft.timeout.notInteger" = "Enter the timeout as a whole number of seconds, or leave it empty."; +"agent.hooks.draft.timeout.not_integer" = "Enter the timeout as a whole number of seconds, or leave it empty."; +"agent.hooks.draft.timeout.outOfRange" = "The timeout must be from 1 to 86400 seconds."; +"agent.hooks.draft.timeout.out_of_range" = "The timeout must be from 1 to 86400 seconds."; "agent.settings.enableSubscription" = "Enable"; "agent.stop" = "Stop"; "ai.add" = "Add"; diff --git a/macos/Resources/zh-Hans.lproj/Localizable.strings b/macos/Resources/zh-Hans.lproj/Localizable.strings index 9b769f68ae..088a1f17f2 100644 --- a/macos/Resources/zh-Hans.lproj/Localizable.strings +++ b/macos/Resources/zh-Hans.lproj/Localizable.strings @@ -5088,6 +5088,29 @@ "agent.history.provider" = "对话供应商"; "agent.history.providerHint" = "试试其他搜索条件或供应商筛选。"; "agent.history.unknownProvider" = "未知供应商"; +"agent.hooks.draft.agents.duplicate" = "每个 Agent 只能选择一次。"; +"agent.hooks.draft.agents.required" = "请至少选择一个 Agent。"; +"agent.hooks.draft.agents.unsupported" = "只有 Codex 和 Claude Code 支持 Hook。"; +"agent.hooks.draft.command.containsNul" = "命令不能包含 NUL 字符。"; +"agent.hooks.draft.command.contains_nul" = "命令不能包含 NUL 字符。"; +"agent.hooks.draft.command.required" = "请输入命令。"; +"agent.hooks.draft.command.tooLong" = "命令最多 32768 字节。"; +"agent.hooks.draft.command.too_long" = "命令最多 32768 字节。"; +"agent.hooks.draft.description.tooLong" = "描述最多 200 个字符。"; +"agent.hooks.draft.description.too_long" = "描述最多 200 个字符。"; +"agent.hooks.draft.id.invalid" = "此 Hook 草稿的标识无效,请关闭编辑器后重试。"; +"agent.hooks.draft.matcher.incompatibleEvent" = "工具筛选只适用于工具相关的事件。"; +"agent.hooks.draft.matcher.incompatible_event" = "工具筛选只适用于工具相关的事件。"; +"agent.hooks.draft.name.duplicate" = "已存在同名的 Hook。"; +"agent.hooks.draft.name.invalidCharacters" = "Hook 名称只能包含字母、数字、连字符或下划线。"; +"agent.hooks.draft.name.invalid_characters" = "Hook 名称只能包含字母、数字、连字符或下划线。"; +"agent.hooks.draft.name.required" = "请输入 Hook 名称。"; +"agent.hooks.draft.name.tooLong" = "Hook 名称最多 80 个字符。"; +"agent.hooks.draft.name.too_long" = "Hook 名称最多 80 个字符。"; +"agent.hooks.draft.timeout.notInteger" = "超时请填写整数秒,或留空。"; +"agent.hooks.draft.timeout.not_integer" = "超时请填写整数秒,或留空。"; +"agent.hooks.draft.timeout.outOfRange" = "超时必须在 1 到 86400 秒之间。"; +"agent.hooks.draft.timeout.out_of_range" = "超时必须在 1 到 86400 秒之间。"; "agent.settings.enableSubscription" = "启用"; "agent.stop" = "停止"; "ai.add" = "添加"; diff --git a/macos/Sources/Lithe/Platform/MacOS/AI/MacClaudeConfigurationSource.swift b/macos/Sources/Lithe/Platform/MacOS/AI/MacClaudeConfigurationSource.swift deleted file mode 100644 index bec406b1ec..0000000000 --- a/macos/Sources/Lithe/Platform/MacOS/AI/MacClaudeConfigurationSource.swift +++ /dev/null @@ -1,162 +0,0 @@ -import Foundation -import LitheCoreContracts - -final class MacClaudeConfigurationSource: ClaudeConfigurationSource, @unchecked Sendable { - private let fileManager: FileManager - - init(fileManager: FileManager = .default) { - self.fileManager = fileManager - } - - func load() -> AIConfigurationSnapshot? { - let home = fileManager.homeDirectoryForCurrentUser - let claudeDirectory = home.appendingPathComponent(".claude", isDirectory: true) - let settingsURL = claudeDirectory.appendingPathComponent("settings.json") - let credentialsURL = claudeDirectory.appendingPathComponent(".credentials.json") - let claudeConfigURL = home.appendingPathComponent(".claude.json") - - return MacClaudeConfigurationParser.parse( - settingsData: try? Data(contentsOf: settingsURL), - credentialsData: try? Data(contentsOf: credentialsURL), - rootConfigData: try? Data(contentsOf: claudeConfigURL), - environment: ProcessInfo.processInfo.environment - ) - } -} - -enum MacClaudeConfigurationParser { - static func parse( - settingsData: Data?, - credentialsData: Data?, - rootConfigData: Data?, - environment: [String: String] - ) -> AIConfigurationSnapshot? { - let settings = decodeObject(settingsData) - let credentials = decodeObject(credentialsData) - let rootConfig = decodeObject(rootConfigData) - let settingsEnvironment = stringDictionary(settings?["env"]) - let combinedEnvironment = environment.merging(settingsEnvironment) { _, settingsValue in - settingsValue - } - - let apiKey = firstNonEmpty([ - settingsEnvironment["ANTHROPIC_API_KEY"], - stringValue(settings?["apiKey"]), - stringValue(rootConfig?["apiKey"]), - stringValue(credentials?["apiKey"]), - environment["ANTHROPIC_API_KEY"] - ]) - let authToken = firstNonEmpty([ - settingsEnvironment["ANTHROPIC_AUTH_TOKEN"], - stringValue(settings?["authToken"]), - stringValue(rootConfig?["authToken"]), - environment["ANTHROPIC_AUTH_TOKEN"] - ]) - let credential = apiKey ?? authToken - let authentication: AIProviderAuthentication = apiKey == nil ? .bearer : .apiKey - let endpoint = firstNonEmpty([ - settingsEnvironment["ANTHROPIC_BASE_URL"], - settingsEnvironment["ANTHROPIC_API_URL"], - stringValue(settings?["apiBaseUrl"]), - stringValue(rootConfig?["apiBaseUrl"]), - environment["ANTHROPIC_BASE_URL"], - "https://api.anthropic.com/v1" - ]) ?? "https://api.anthropic.com/v1" - let configuredModel = firstNonEmpty([ - settingsEnvironment["ANTHROPIC_MODEL"], - stringValue(settings?["model"]), - stringValue(rootConfig?["model"]), - environment["ANTHROPIC_MODEL"], - "claude-sonnet-4-5" - ]) ?? "claude-sonnet-4-5" - let model = resolveModelAlias(configuredModel, environment: combinedEnvironment) - - let hasConfiguration = settings != nil - || credentials != nil - || rootConfig != nil - || credential != nil - || environment["ANTHROPIC_BASE_URL"] != nil - || environment["ANTHROPIC_API_KEY"] != nil - || environment["ANTHROPIC_AUTH_TOKEN"] != nil - guard hasConfiguration else { return nil } - - return AIConfigurationSnapshot( - source: .claude, - providerName: "Claude", - endpoint: endpoint, - model: model, - apiProtocol: .anthropicMessages, - authentication: authentication, - reasoningEffort: nil, - requiresAPIKey: true, - apiKey: credential - ) - } - - private static func decodeObject(_ data: Data?) -> [String: Any]? { - guard let data, - let object = try? JSONSerialization.jsonObject(with: data), - let dictionary = object as? [String: Any] else { - return nil - } - return dictionary - } - - private static func stringDictionary(_ value: Any?) -> [String: String] { - guard let dictionary = value as? [String: Any] else { return [:] } - return dictionary.reduce(into: [:]) { result, entry in - if let value = entry.value as? String, !value.isEmpty { - result[entry.key] = value - } - } - } - - private static func stringValue(_ value: Any?) -> String? { - value as? String - } - - private static func resolveModelAlias( - _ model: String, - environment: [String: String] - ) -> String { - switch model.lowercased() { - case "opus": - return firstNonEmpty([ - environment["ANTHROPIC_DEFAULT_OPUS_MODEL"], - environment["ANTHROPIC_DEFAULT_OPUS_MODEL_NAME"], - model - ]) ?? model - case "sonnet": - return firstNonEmpty([ - environment["ANTHROPIC_DEFAULT_SONNET_MODEL"], - environment["ANTHROPIC_DEFAULT_SONNET_MODEL_NAME"], - model - ]) ?? model - case "haiku": - return firstNonEmpty([ - environment["ANTHROPIC_DEFAULT_HAIKU_MODEL"], - environment["ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME"], - model - ]) ?? model - case "fable": - return firstNonEmpty([ - environment["ANTHROPIC_DEFAULT_FABLE_MODEL"], - environment["ANTHROPIC_DEFAULT_FABLE_MODEL_NAME"], - model - ]) ?? model - default: - return model - } - } - - private static func firstNonEmpty(_ values: [String?]) -> String? { - for value in values { - guard let value else { continue } - let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) - if !trimmed.isEmpty { - return trimmed - } - } - return nil - } -} diff --git a/macos/Sources/Lithe/Platform/MacOS/AI/MacCodexConfigurationSource.swift b/macos/Sources/Lithe/Platform/MacOS/AI/MacCodexConfigurationSource.swift deleted file mode 100644 index 52cd280cf2..0000000000 --- a/macos/Sources/Lithe/Platform/MacOS/AI/MacCodexConfigurationSource.swift +++ /dev/null @@ -1,164 +0,0 @@ -import Foundation -import LitheCoreContracts - -final class MacCodexConfigurationSource: CodexConfigurationSource, @unchecked Sendable { - private let fileManager: FileManager - - init(fileManager: FileManager = .default) { - self.fileManager = fileManager - } - - func loadModel() -> AIConfigurationModel? { - let configURL = fileManager.homeDirectoryForCurrentUser - .appendingPathComponent(".codex", isDirectory: true) - .appendingPathComponent("config.toml") - guard let config = try? String(contentsOf: configURL, encoding: .utf8) else { return nil } - return AIConfigurationModel(source: .codex, model: MacCodexConfigurationParser.parseModel(config: config)) - } - - func load() -> CodexConfigurationSnapshot? { - let home = fileManager.homeDirectoryForCurrentUser - let configURL = home - .appendingPathComponent(".codex", isDirectory: true) - .appendingPathComponent("config.toml") - let authURL = home - .appendingPathComponent(".codex", isDirectory: true) - .appendingPathComponent("auth.json") - - guard let config = try? String(contentsOf: configURL, encoding: .utf8) else { - return nil - } - let authData = try? Data(contentsOf: authURL) - guard let snapshot = MacCodexConfigurationParser.parse(config: config, authData: authData) else { - return nil - } - guard !snapshot.hasAPIKey, - let environmentKey = ProcessInfo.processInfo.environment["OPENAI_API_KEY"], - !environmentKey.isEmpty else { - return snapshot - } - return CodexConfigurationSnapshot( - source: .codex, - providerName: snapshot.providerName, - endpoint: snapshot.endpoint, - model: snapshot.model, - apiProtocol: snapshot.apiProtocol, - reasoningEffort: snapshot.reasoningEffort, - requiresAPIKey: snapshot.requiresAPIKey, - apiKey: environmentKey - ) - } -} - -enum MacCodexConfigurationParser { - static func parse(config: String, authData: Data?) -> CodexConfigurationSnapshot? { - let (topLevel, providerValues) = parseValues(config: config) - let providerName = topLevel["model_provider"] ?? "custom" - guard let provider = providerValues[providerName], - let endpoint = provider["base_url"], - let model = topLevel["model"], - !endpoint.isEmpty, - !model.isEmpty else { - return nil - } - - let apiProtocol: CommitMessageAPIProtocol = provider["wire_api"] == "responses" - ? .responses - : .chatCompletions - let reasoningEffort = topLevel["model_reasoning_effort"].flatMap { - CommitMessageReasoningEffort(rawValue: $0) - } - let requiresAPIKey = provider["requires_openai_auth"] == "true" - let apiKey = decodeAPIKey(from: authData) - - return CodexConfigurationSnapshot( - source: .codex, - providerName: providerName, - endpoint: endpoint, - model: model, - apiProtocol: apiProtocol, - reasoningEffort: reasoningEffort, - requiresAPIKey: requiresAPIKey, - apiKey: apiKey - ) - } - - static func parseModel(config: String) -> String { - // A present config without a top-level model uses the CLI's default. - parseValues(config: config).topLevel["model"] ?? "" - } - - private static func parseValues(config: String) -> ( - topLevel: [String: String], providerValues: [String: [String: String]] - ) { - var topLevel: [String: String] = [:] - var providerValues: [String: [String: String]] = [:] - var currentProvider: String? - var isTopLevel = true - - for rawLine in config.split(whereSeparator: { $0.isNewline }) { - let line = stripComment(String(rawLine)).trimmingCharacters(in: .whitespacesAndNewlines) - guard !line.isEmpty else { continue } - - if line.hasPrefix("[") && line.hasSuffix("]") { - isTopLevel = false - let section = String(line.dropFirst().dropLast()) - if section.hasPrefix("model_providers.") { - currentProvider = String(section.dropFirst("model_providers.".count)) - providerValues[currentProvider!, default: [:]] = [:] - } else { - currentProvider = nil - } - continue - } - - let parts = line.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false) - guard parts.count == 2 else { continue } - let key = parts[0].trimmingCharacters(in: .whitespacesAndNewlines) - let value = parseValue(String(parts[1])) - if let currentProvider { - providerValues[currentProvider, default: [:]][key] = value - } else if isTopLevel { - topLevel[key] = value - } - } - return (topLevel, providerValues) - } - - private static func parseValue(_ rawValue: String) -> String { - let value = rawValue.trimmingCharacters(in: .whitespacesAndNewlines) - guard value.count >= 2, - value.first == "\"", - value.last == "\"" else { - return value - } - return String(value.dropFirst().dropLast()) - } - - private static func stripComment(_ line: String) -> String { - var isInsideString = false - var escaped = false - for (index, character) in line.enumerated() { - if character == "\\", isInsideString { - escaped.toggle() - continue - } - if character == "\"", !escaped { - isInsideString.toggle() - } - if character == "#", !isInsideString { - return String(line.prefix(index)) - } - escaped = false - } - return line - } - - private static func decodeAPIKey(from data: Data?) -> String? { - guard let data, - let values = try? JSONDecoder().decode([String: String].self, from: data) else { - return nil - } - return values["OPENAI_API_KEY"] ?? values["api_key"] - } -} diff --git a/macos/Tests/LitheTests/AgentConversationFeatureModelTests.swift b/macos/Tests/LitheTests/AgentConversationFeatureModelTests.swift index de54b3f395..a1fc498f72 100644 --- a/macos/Tests/LitheTests/AgentConversationFeatureModelTests.swift +++ b/macos/Tests/LitheTests/AgentConversationFeatureModelTests.swift @@ -2321,8 +2321,8 @@ struct AgentConversationFeatureModelTests { } private func receiveEdit(_ feature: AgentConnectionModel, id: String, old: String, new: String) throws { - let update: [String: Any] = ["sessionUpdate": "tool_call", "toolCallId": id, "kind": "edit", - "status": "completed", "content": [["type": "diff", "path": "a.txt", "oldText": old, "newText": new]]] + let update = (["sessionUpdate": "tool_call", "toolCallId": id, "kind": "edit", "status": "completed"] as [String: Any]) + .merging(AgentEditEvidenceTestSupport.diffContent(path: "a.txt", old: old, new: new)) { $1 } try feature.receive(event("toolCall", ["update": update])) } @@ -2440,43 +2440,35 @@ struct AgentConversationFeatureModelTests { #expect(conversation.modelCalls.callsWithUsage == 1) } + /// The Host decides what each call contributes; these totals only add the + /// shared fixture's contributions and must reach its shared totals. @Test - func contextCompositionFollowsMainRequestsWithAndWithoutTools() throws { - // Agents that never send tools refresh the composition on every request. - var toolless = AgentModelCallTotals() - toolless.record(try modelCall(context: context(messages: 1000, tools: 0))) - toolless.record(try modelCall(context: context(messages: 5000, tools: 0))) - #expect(toolless.latestContext?.messageTokens == 5000) - // Once tools are sent, tool-less auxiliary requests do not replace it. - var main = AgentModelCallTotals() - main.record(try modelCall(context: context(messages: 1000, tools: 0))) - main.record(try modelCall(context: context(messages: 8000, tools: 12))) - main.record(try modelCall(context: context(messages: 40, tools: 0))) - #expect(main.latestContext?.messageTokens == 8000) - main.record(try modelCall(context: context(messages: 9000, tools: 12))) - #expect(main.latestContext?.messageTokens == 9000) - } - - @Test - func auxiliaryRequestsSpendTokensButAreNotConversationSteps() throws { - var totals = AgentModelCallTotals() - let usage: [String: Any] = ["inputTokens": 10, "cacheReadTokens": 0, "cacheWriteTokens": 0, "outputTokens": 16] - // Claude Code names the session with a request of its own. - totals.record(try modelCall(usage: usage, context: context(messages: 300, tools: 0), auxiliary: true)) - #expect(totals.callCount == 0) - #expect(totals.duration == 0) - #expect(totals.averageFirstToken == nil) - #expect(totals.latestContext == nil) - #expect(totals.outputTokens == 16) - #expect(totals.callsWithUsage == 1) - #expect(totals.requestCount == 1) - #expect(totals.callsMissingUsage == 0) - totals.record(try modelCall(usage: usage, context: context(messages: 4000, tools: 11))) - #expect(totals.callCount == 1) - #expect(totals.outputTokens == 32) - #expect(totals.latestContext?.toolCount == 11) - #expect(totals.requestCount == 2) - #expect(totals.callsMissingUsage == 0) + func hostContributionsSumToTheSharedTotals() throws { + let root = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + let data = try Data(contentsOf: root.appendingPathComponent("shared/fixtures/agent/model-call-statistics-v1.json")) + let fixture = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + for entry in try #require(fixture["cases"] as? [[String: Any]]) { + var totals = AgentModelCallTotals() + for event in try #require(entry["events"] as? [[String: Any]]) { + totals.record(try #require(AgentModelCall.parse(event["statistics"]))) + } + let expected = try #require(AgentModelCall.parse(entry["total"])) + #expect(totals.requestCount == expected.requests) + #expect(totals.callCount == expected.steps) + #expect(totals.failedCount == expected.failedSteps) + #expect(totals.nonStreamingCount == expected.nonStreamingSteps) + #expect(abs(totals.duration - Double(expected.durationMs) / 1000) < 0.000_001) + #expect(totals.inputTokens == expected.inputTokens) + #expect(totals.cacheReadTokens == expected.cacheReadTokens) + #expect(totals.outputTokens == expected.outputTokens) + #expect(totals.reasoningTokens == expected.reasoningTokens) + #expect(totals.callsWithUsage == expected.callsWithUsage) + #expect(totals.latestContext == expected.context) + #expect(totals.averageFirstToken == (expected.firstTokenCount == 0 ? nil + : Double(expected.firstTokenMs) / 1000 / Double(expected.firstTokenCount))) + } } @Test(arguments: [false, true]) @@ -2539,18 +2531,18 @@ struct AgentConversationFeatureModelTests { #expect(auxiliary.callsMissingUsage == 0) } + /// The Host contribution of one streamed call without a first token. private func modelCall(usage: [String: Any]? = nil, context: [String: Any]? = nil, auxiliary: Bool = false) throws -> AgentModelCall { - var call: [String: Any] = ["api": "anthropicMessages", "status": 200, "streaming": true, "durationMs": 1000] - if auxiliary { call["auxiliary"] = true } - if let usage { call["usage"] = usage } - if let context { call["context"] = context } - return try #require(AgentModelCall.parse(call)) - } - - private func context(messages: Int, tools: Int) -> [String: Any] { - ["systemPromptTokens": 100, "toolTokens": tools * 100, "mcpToolTokens": 0, "messageTokens": messages, - "toolCount": tools, "mcpToolCount": 0, "scaledToUsage": false] + var statistics: [String: Any] = [ + "requests": 1, "steps": auxiliary ? 0 : 1, "failedSteps": 0, "nonStreamingSteps": 0, + "durationMs": auxiliary ? 0 : 1000, "callsWithUsage": usage == nil ? 0 : 1, + "firstTokenMs": 0, "firstTokenCount": 0, "generationMs": 0, "generatedTokens": 0] + for key in ["inputTokens", "cacheReadTokens", "cacheWriteTokens", "outputTokens"] { + statistics[key] = usage?[key] ?? 0 + } + if let context, !auxiliary { statistics["context"] = context } + return try #require(AgentModelCall.parse(statistics)) } @Test diff --git a/rust/lithe-agent-host/src/lib.rs b/rust/lithe-agent-host/src/lib.rs index e94f273bff..a788a48d8d 100644 --- a/rust/lithe-agent-host/src/lib.rs +++ b/rust/lithe-agent-host/src/lib.rs @@ -13,6 +13,7 @@ mod claude_desktop; mod claude_earlier_history; mod claude_subscription; pub mod cli_update; +pub mod edit_review; mod codex_context; mod codex_history; mod codex_retry; @@ -21,7 +22,9 @@ pub mod hooks; pub mod install; pub mod instructions; pub mod mcp_probe; +mod model_call_statistics; mod model_calls; +pub mod next_turn_config; mod model_proxy; mod prompt; mod prompt_retry; @@ -35,6 +38,7 @@ mod subscription; mod workspace_context; pub use catalog::{ModelDelivery, ProviderProtocol}; +pub use model_call_statistics::ModelCallStatistics; pub use model_calls::{ContextComposition, ModelApi, ModelCall, ModelCallUsage}; pub use prompt::PromptFile; @@ -538,6 +542,15 @@ pub enum AgentCommand { config_id: String, value: String, }, + /// Applies the choices a user made while a turn was running, after it + /// ended, as one ordered and confirmed sequence. See [`next_turn_config`]. + ApplyNextTurnConfiguration { + token: String, + session_id: String, + /// The product's latest confirmed catalog of the session. + catalog: Vec, + choices: Vec, + }, Permission { request_id: String, option_id: Option, @@ -628,6 +641,21 @@ pub enum AgentEvent { session_id: String, config_options: Vec, }, + /// Result of `applyNextTurnConfiguration`. `config_options` is the latest + /// catalog the Agent returned, present once any request succeeded, so the + /// product shows confirmed settings even when a later choice failed. + NextTurnConfigured { + token: String, + session_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + config_options: Option>, + /// Absent when every choice was applied. + #[serde(skip_serializing_if = "Option::is_none")] + failure: Option, + /// Upstream diagnostics of a failed request; never localized. + #[serde(skip_serializing_if = "Option::is_none")] + message: Option, + }, TurnCancelling { session_id: String, }, @@ -685,6 +713,9 @@ pub enum AgentEvent { #[serde(skip_serializing_if = "std::ops::Not::not")] after_turn_finished: bool, call: model_calls::ModelCall, + /// This call's contribution to turn and session statistics. Products + /// merge contributions; they never reinterpret `call` for accounting. + statistics: ModelCallStatistics, }, /// The agent acknowledged the prompt's completion, including cancellation. TurnFinished { @@ -1057,12 +1088,15 @@ async fn run_agent( let session: model_proxy::SessionResolver = Arc::new(move || sole_running_session(&running)); let calls = emit.clone(); + let tracker = model_call_statistics::StatisticsTracker::default(); let sink: model_proxy::CallSink = Arc::new(move |session_id, after_turn_finished, call| { + let statistics = tracker.contribution(session_id.as_deref(), &call); calls(AgentEvent::ModelCall { session_id, after_turn_finished, call, + statistics, }) }); // Statistics are optional. A proxy that cannot start leaves the @@ -1514,7 +1548,9 @@ where return Ok(()); }; let presented = update_desktop.lock().map_err(|_| internal("Replay presentation is unavailable"))?.present(&session_id, update); - for update in presented { + for mut update in presented { + // One evidence normalization for both products' edit review. + edit_review::annotate(&mut update); if update["sessionUpdate"] == "usage_update" { if let Some(recovery) = &context_updates { recovery.prefer_upstream_report(&session_id); } } @@ -1833,7 +1869,8 @@ where Ok(mut desktop) => updates.into_iter().flat_map(|u| desktop.present(&session_id, u)).collect(), Err(_) => updates, }; - for update in updates { + for mut update in updates { + edit_review::annotate(&mut update); emit(AgentEvent::Update { session_id: session_id.clone(), update }); } } @@ -1919,6 +1956,40 @@ where }); }); } + AgentCommand::ApplyNextTurnConfiguration { token, session_id, catalog, choices } => { + if turns.lock().is_ok_and(|turns| turns.contains_key(&session_id)) { + emit(failed(Some(token), Some(session_id), "Wait for the current turn before changing configuration".into())); + continue; + } + let connection = connection.clone(); + let emit = emit.clone(); + tasks.spawn(async move { + let mut plan = next_turn_config::NextTurnPlan::new(catalog, choices); + let mut latest = None; + let (failure, message) = loop { + let choice = match plan.next() { + next_turn_config::Step::Done => break (None, None), + next_turn_config::Step::Failed(failure) => break (Some(failure), None), + next_turn_config::Step::Send(choice) => choice, + }; + let result = request_with_timeout( + SESSION_REQUEST_TIMEOUT, + connection.send_request(SetSessionConfigOptionRequest::new( + session_id.clone(), choice.config_id, choice.value.as_str(), + )).block_task(), + ).await; + match result { + Ok(response) => { + let confirmed = plan.confirm(next_turn_config::catalog(&response.config_options)); + latest = Some(response.config_options); + if let Err(failure) = confirmed { break (Some(failure), None); } + } + Err(message) => break (Some(next_turn_config::ConfigFailure::RequestFailed), Some(message)), + } + }; + emit(AgentEvent::NextTurnConfigured { token, session_id, config_options: latest, failure, message }); + }); + } AgentCommand::Steer { token, session_id, text, files } => { let reject = |message: &str| emit(AgentEvent::SteeringResult { token: token.clone(), session_id: session_id.clone(), diff --git a/rust/lithe-core/src/agent/mod.rs b/rust/lithe-core/src/agent/mod.rs index 43173cc838..046e0ee711 100644 --- a/rust/lithe-core/src/agent/mod.rs +++ b/rust/lithe-core/src/agent/mod.rs @@ -5,6 +5,7 @@ use std::path::PathBuf; +pub(crate) mod edits; pub(crate) mod hooks; pub(crate) mod instructions; diff --git a/rust/lithe-core/src/ai/mod.rs b/rust/lithe-core/src/ai/mod.rs index 5bb446bd63..5582a6315c 100644 --- a/rust/lithe-core/src/ai/mod.rs +++ b/rust/lithe-core/src/ai/mod.rs @@ -1,23 +1,39 @@ -//! Portable AI commit configuration parsing and HTTP request planning; hosts own I/O and secrets. +//! Portable AI CLI configuration parsing and HTTP request planning; hosts own I/O and secrets. mod agent_configuration; mod commands; mod configuration; mod generation; +mod inline_edit; +mod provider_request; +mod pull_request; pub(crate) use generation::{ commit_input_budget, plan_commit_bounded, sensitive_path as is_sensitive_commit_path, }; -pub use agent_configuration::parse_provider_configuration; -pub use configuration::{parse_claude, parse_codex, DetectedConfiguration}; +pub use agent_configuration::{configuration_sources_command, parse_configuration_command}; +pub use configuration::{ + configuration_sources, detect, is_configured, parse_claude, parse_codex, ConfigurationFile, + ConfigurationFiles, ConfigurationSourceFile, CredentialLocator, DetectedConfiguration, +}; pub use generation::{ decode_message, plan_commit, ChatTokenLimitField, CommitFile, CommitOptions, CommitRequestPlan, Provider, }; +pub use pull_request::{ + decode_pull_request, plan_pull_request, PullRequestComparison, PullRequestDescription, + PullRequestOptions, +}; +#[cfg(test)] +mod request_tests; #[cfg(test)] mod tests; pub(crate) use commands::{ - commit_input_budget_command, decode_commit_command, plan_commit_command, + commit_input_budget_command, decode_commit_command, decode_pull_request_command, + plan_commit_command, plan_pull_request_command, +}; +pub(crate) use inline_edit::{ + decode_command as decode_inline_edit_command, plan_command as plan_inline_edit_command, }; diff --git a/rust/lithe-core/src/protocol/command.rs b/rust/lithe-core/src/protocol/command.rs index fbb7abd4bd..738ada51ec 100644 --- a/rust/lithe-core/src/protocol/command.rs +++ b/rust/lithe-core/src/protocol/command.rs @@ -75,14 +75,28 @@ pub enum CoreCommand { AgentUninstall, /// Installs or updates an agent's CLI through its installation owner (`agent.installCli`). AgentInstallCli, - /// Parses credential-free Agent provider metadata (`agent.parseProviderConfiguration`). - AgentParseProviderConfiguration, + /// Plans a rollback of one file's Agent edits from evidence and disk text (`agent.edits.reversePlan`). + AgentEditsReversePlan, + /// Validates an unsaved Hook draft field by field (`agent.hooks.validateDraft`). + AgentHooksValidateDraft, /// Budgets diff prefixes before crossing the native boundary (`ai.commitInputBudget`). AiCommitInputBudget, /// Plans a credential-free commit message request (`ai.planCommit`). AiPlanCommit, /// Decodes a provider commit message response (`ai.decodeCommitMessage`). AiDecodeCommitMessage, + /// Names the native files of one AI CLI configuration source (`ai.configuration.sources`). + AiConfigurationSources, + /// Parses AI CLI configuration into credential-free metadata (`ai.configuration.parse`). + AiConfigurationParse, + /// Plans a credential-free pull request description request (`ai.pullRequest.plan`). + AiPullRequestPlan, + /// Decodes a strict pull request title and description (`ai.pullRequest.decode`). + AiPullRequestDecode, + /// Plans a credential-free inline edit request (`ai.inlineEdit.plan`). + AiInlineEditPlan, + /// Decodes the replacement text of an inline edit response (`ai.inlineEdit.decode`). + AiInlineEditDecode, /// Parses one Agent MCP configuration file into normalized servers (`mcp.parseConfiguration`). McpParseConfiguration, /// Normalizes a public Registry response into discoverable server drafts (`mcp.parseRegistry`). @@ -97,6 +111,12 @@ pub enum CoreCommand { McpToolPolicy, /// Round-trips a quoted command line into exact argv boundaries. McpCommandLine, + /// Merges discovered MCP sources into library rows with ownership (`mcp.librarySnapshot`). + McpLibrarySnapshot, + /// Returns field-level issues for an MCP server editor draft (`mcp.validateDraft`). + McpValidateDraft, + /// Plans an all-or-nothing multi-file MCP library edit (`mcp.batchPlan`). + McpBatchPlan, /// Validates and normalizes a declarative plugin manifest (`plugins.declarative.validate`). PluginsDeclarativeValidate, /// Validates native plugin UI data with declaration identity and node budgets. @@ -806,10 +826,17 @@ impl CoreCommand { "agent.install" => Some(Self::AgentInstall), "agent.uninstall" => Some(Self::AgentUninstall), "agent.installCli" => Some(Self::AgentInstallCli), - "agent.parseProviderConfiguration" => Some(Self::AgentParseProviderConfiguration), + "agent.edits.reversePlan" => Some(Self::AgentEditsReversePlan), + "agent.hooks.validateDraft" => Some(Self::AgentHooksValidateDraft), "ai.commitInputBudget" => Some(Self::AiCommitInputBudget), "ai.planCommit" => Some(Self::AiPlanCommit), "ai.decodeCommitMessage" => Some(Self::AiDecodeCommitMessage), + "ai.configuration.sources" => Some(Self::AiConfigurationSources), + "ai.configuration.parse" => Some(Self::AiConfigurationParse), + "ai.pullRequest.plan" => Some(Self::AiPullRequestPlan), + "ai.pullRequest.decode" => Some(Self::AiPullRequestDecode), + "ai.inlineEdit.plan" => Some(Self::AiInlineEditPlan), + "ai.inlineEdit.decode" => Some(Self::AiInlineEditDecode), "mcp.parseConfiguration" => Some(Self::McpParseConfiguration), "mcp.parseRegistry" => Some(Self::McpParseRegistry), "mcp.featuredRegistry" => Some(Self::McpFeaturedRegistry), @@ -817,6 +844,9 @@ impl CoreCommand { "mcp.probe" => Some(Self::McpProbe), "mcp.toolPolicy" => Some(Self::McpToolPolicy), "mcp.commandLine" => Some(Self::McpCommandLine), + "mcp.librarySnapshot" => Some(Self::McpLibrarySnapshot), + "mcp.validateDraft" => Some(Self::McpValidateDraft), + "mcp.batchPlan" => Some(Self::McpBatchPlan), "plugins.declarative.validate" => Some(Self::PluginsDeclarativeValidate), "plugins.nativeUI.validateData" => Some(Self::PluginsNativeUIValidateData), "plugins.declarative.runPlan" => Some(Self::PluginsDeclarativeRunPlan), diff --git a/rust/lithe-core/src/runtime/dispatcher.rs b/rust/lithe-core/src/runtime/dispatcher.rs index 9983c9d2ff..6a0cb8c491 100644 --- a/rust/lithe-core/src/runtime/dispatcher.rs +++ b/rust/lithe-core/src/runtime/dispatcher.rs @@ -211,6 +211,9 @@ fn execute_parsed(mut parsed: CoreRequest) -> CoreResponse { } CoreCommand::AgentSkills => agent_response(id, parsed.payload, crate::agent::skills), CoreCommand::AgentHooks => agent_response(id, parsed.payload, crate::agent::hooks::execute), + CoreCommand::AgentEditsReversePlan => { + agent_response(id, parsed.payload, crate::agent::edits::reverse_plan) + } CoreCommand::AiCommitInputBudget => { plugin_response(id, parsed.payload, crate::ai::commit_input_budget_command) } @@ -220,11 +223,26 @@ fn execute_parsed(mut parsed: CoreRequest) -> CoreResponse { CoreCommand::AiDecodeCommitMessage => { plugin_response(id, parsed.payload, crate::ai::decode_commit_command) } - CoreCommand::AgentParseProviderConfiguration => { - match crate::ai::parse_provider_configuration(parsed.payload) { - Ok(data) => CoreResponse::success(id, data), - Err(error) => CoreResponse::failure(id, error), - } + CoreCommand::AiConfigurationSources => { + plugin_response(id, parsed.payload, crate::ai::configuration_sources_command) + } + CoreCommand::AiConfigurationParse => { + plugin_response(id, parsed.payload, crate::ai::parse_configuration_command) + } + CoreCommand::AiPullRequestPlan => { + plugin_response(id, parsed.payload, crate::ai::plan_pull_request_command) + } + CoreCommand::AiPullRequestDecode => { + plugin_response(id, parsed.payload, crate::ai::decode_pull_request_command) + } + CoreCommand::AiInlineEditPlan => { + plugin_response(id, parsed.payload, crate::ai::plan_inline_edit_command) + } + CoreCommand::AiInlineEditDecode => { + plugin_response(id, parsed.payload, crate::ai::decode_inline_edit_command) + } + CoreCommand::AgentHooksValidateDraft => { + agent_response(id, parsed.payload, crate::agent::hooks::validate_draft) } CoreCommand::McpParseConfiguration => { match crate::mcp::parse_configuration(parsed.payload) { @@ -253,6 +271,18 @@ fn execute_parsed(mut parsed: CoreRequest) -> CoreResponse { Ok(data) => CoreResponse::success(id, data), Err(error) => CoreResponse::failure(id, error), }, + CoreCommand::McpLibrarySnapshot => match crate::mcp::library_snapshot(parsed.payload) { + Ok(data) => CoreResponse::success(id, data), + Err(error) => CoreResponse::failure(id, error), + }, + CoreCommand::McpValidateDraft => match crate::mcp::validate_draft(parsed.payload) { + Ok(data) => CoreResponse::success(id, data), + Err(error) => CoreResponse::failure(id, error), + }, + CoreCommand::McpBatchPlan => match crate::mcp::batch_plan(parsed.payload) { + Ok(data) => CoreResponse::success(id, data), + Err(error) => CoreResponse::failure(id, error), + }, CoreCommand::PluginsNativeUIValidateData => plugin_response( id, parsed.payload, diff --git a/rust/lithe-core/src/tests/agent.rs b/rust/lithe-core/src/tests/agent.rs index 8a358d9e8d..fb221be0d0 100644 --- a/rust/lithe-core/src/tests/agent.rs +++ b/rust/lithe-core/src/tests/agent.rs @@ -228,3 +228,45 @@ fn cli_update_outcome_fixture_preserves_verified_version_and_warning() { assert_eq!(actual, fixture()["responses"][name]); } } + +#[test] +fn edit_reverse_plan_dispatches_shared_fixture_and_rejects_malformed_payloads() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../shared/fixtures/agent/edit-review-v1.json" + )) + .unwrap(); + assert!(crate::protocol::CoreCommand::parse("agent.edits.reversePlan").is_some()); + for case in fixture["reversePlan"].as_array().unwrap() { + // Reverse plan cases use literal text only; generators belong to evidence cases. + let response = run("agent.edits.reversePlan", case["request"].clone()); + assert_eq!(response["ok"], true, "{}", case["name"]); + assert_eq!(response["data"], case["expected"], "{}", case["name"]); + } + let response = run( + "agent.edits.reversePlan", + json!({"diffs": [{"oldText": "a", "truncated": false}], "disk": "a"}), + ); + assert_eq!(response["error"]["code"], "invalid_request"); + let response = run( + "agent.edits.reversePlan", + json!({"diffs": [], "disk": null, "workspace": "/arbitrary"}), + ); + assert_eq!(response["error"]["code"], "invalid_request"); +} + +/// Both editors call this command; the dispatcher must return the fixture verdicts. +#[test] +fn hook_draft_validation_dispatch_returns_the_shared_field_codes() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../shared/fixtures/agent/hook-draft-validation-v1.json" + )) + .unwrap(); + let command = fixture["command"].as_str().unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let response = run(command, case["request"].clone()); + assert_eq!(response["ok"], true, "{response}"); + assert_eq!(response["data"], case["expected"], "{}", case["name"]); + } + let response = run(command, json!({"hook": {"name": "x"}})); + assert_eq!(response["error"]["code"], "invalid_request", "{response}"); +} diff --git a/shared/contracts/rust-core-api.md b/shared/contracts/rust-core-api.md index a25d058964..5856125107 100644 --- a/shared/contracts/rust-core-api.md +++ b/shared/contracts/rust-core-api.md @@ -369,10 +369,10 @@ is green through 60%, yellow above 60% through 90%, and red above 90%; unknown or stale data remains gray. Window duration and missing values are never invented. `lithe_agent_send_json` queues one command: `newSession`, `loadSession`, -`listSessions`, `setConfigOption`, `prompt`, `steer`, `cancel`, `permission`, `authenticate`, +`listSessions`, `setConfigOption`, `applyNextTurnConfiguration`, `prompt`, `steer`, `cancel`, `permission`, `authenticate`, or `refreshQuota`. Results arrive as events: `ready`, `sessionCreated`, `sessionLoaded`, `sessions`, `update`, `permission`, -`sessionConfigured`, `steeringResult`, `turnRetrying`, `turnActivity`, `turnCancelling`, `turnFinished`, `requestFailed`, `stopped`, +`sessionConfigured`, `nextTurnConfigured`, `modelCall`, `steeringResult`, `turnRetrying`, `turnActivity`, `turnCancelling`, `turnFinished`, `requestFailed`, `stopped`, `authenticationRequired`, `authenticating`, `account`, `quota`, and `quotaFailed`. Commands and events, including their camel-case field names, are fixed by `shared/fixtures/agent/acp-events-v1.json`; `token` values are echoed so a caller @@ -491,13 +491,24 @@ full option list arrives as `sessionConfigured`. Consumers also accept ACP values remain authoritative; unsupported controls are not synthesized. Configuration failure echoes the token and does not finish a prompt. Native clients may stage next-turn choices while a prompt is active, without sending configuration commands or replacing the -Agent-confirmed values. The macOS conversation model keeps that intent per -session and submits it only after a terminal turn event, model first and then -one acknowledged choice at a time against the latest option list. Rejection, -unconfirmed values, or removed choices clear the remaining intent and surface a -configuration error; disconnect clears it as well. The next prompt remains -blocked until configuration requests finish. This does not change the Host's -busy-session rejection or the command/event shape. +Agent-confirmed values. Both products keep that intent per session and, after a +terminal turn event (including a failed turn), send one +`applyNextTurnConfiguration` command with `token`, `sessionId`, the product's +latest `catalog` (`id`, optional `category`, `currentValue`, `choices` value +IDs) and `choices` (`configId`, `value`). The Host owns the order and +validation: model options first, then the rest in catalog order; each remaining +choice is revalidated against the latest catalog the Agent returned, skipped +when already current, and must be confirmed by the Agent's reported value. It +answers with one `nextTurnConfigured` event (`token`, `sessionId`, optional +`configOptions` = latest Agent catalog once any request succeeded, optional +`failure` = `unsupported` | `notConfirmed` | `requestFailed`, and for a failed +request the upstream `message`). Products localize the failure code, clear the +remaining intent, keep confirmed settings, and fail a deferred supplement +instead of sending it; disconnect clears the intent as well. A deferred +supplement after a failed turn is failed with that turn's error, never replayed. +The next prompt remains blocked until the command finishes. The Host still +rejects the command while the session's prompt is running. Shape and cases: +`shared/fixtures/agent/next-turn-configuration-v1.json`. For a new session, the host also preserves the adapter's optional legacy model catalog while decoding the ACP response and negotiates only the versioned @@ -674,7 +685,18 @@ exactly one non-cancelling prompt was running when the request started; consumer drop unattributed calls instead of guessing. The host waits up to two seconds for a turn's attributed calls to report before emitting its `turnFinished`, so they arrive first. A call still open after that bound carries `afterTurnFinished: true` -and counts for the session only, never for a later turn. The launch accepts `contextLimits` (`windowTokens`, `autoCompactTokens`, both optional; +and counts for the session only, never for a later turn. Each `modelCall` also carries +`statistics`, the Host's accounting contribution of that call (`requests`, +`steps`, `failedSteps`, `nonStreamingSteps` for successful non-streamed steps +only, `durationMs`, the four token buckets, optional `reasoningTokens`, +`callsWithUsage`, `firstTokenMs`/`firstTokenCount` and +`generationMs`/`generatedTokens` of streamed steps, and optional `context` when +the call describes the current prompt: auxiliary requests never do, and once a +session's main requests carry tools, tool-less ones no longer do). Products +merge contributions in event order (counters add, `reasoningTokens` adds over +calls that report it, a present `context` replaces the previous one) and never +reinterpret `call` for accounting. Cases: +`shared/fixtures/agent/model-call-statistics-v1.json`. The launch accepts `contextLimits` (`windowTokens`, `autoCompactTokens`, both optional; zero means unset). Codex receives them as `model_context_window` and `model_auto_compact_token_limit` in its session configuration. Claude Code has a single switch, so the threshold (else the context length) is exported as @@ -766,6 +788,9 @@ configuration parsing, and response decoding. macOS uses `ai.commitInputBudget`, `ai.planCommit`, and `ai.decodeCommitMessage` over the existing JSON C ABI; Windows uses the typed API. The [AI commit contract](ai-commit.md) defines the bounded diff prefixes, payloads, errors and platform-owned I/O. +`ai.pullRequest.plan` / `ai.pullRequest.decode` and `ai.inlineEdit.plan` / +`ai.inlineEdit.decode` share that provider request model; see +[AI generation requests](ai-generation-requests.md). Every request has this shape: @@ -956,27 +981,89 @@ unknown fields. Unchanged set plans also return the current entry's hashes; removal can return the old definition hash for filter retention; absence has no entry hashes. Hashes sent on the draft server are never trusted as write output or persisted into Agent configuration. +The MCP server library is planned by three Core commands; hosts only discover +paths, read and atomically write files, persist the ledger and localize codes. +Each takes `files: LibraryFile[]` (at most 16, unique `id`), where a file is +`{ id, source: "codex" | "claude", scope, projectPath?, path, content?: string | +null, owned: LedgerEntry[] }`. `id` is the host's opaque ledger key and `path` +the native path that keys retained tool filters. A ledger entry is `{ name, +definitionHash, sourceHash?, toolFilters?: { : {enabledTools?, +disabledTools?} } }`; it never contains env/header values. + +`mcp.librarySnapshot` accepts `{ files }` and returns `{ rows, failures }`. Rows +merge every parsed server by `name#definitionHash` (`id`), carry the definition +from the first source in host file order, `sources: [{ file, definitionHash, +sourceHash, ownedByLithe }]`, `hasDefinitionConflict` (another global entry +with the same name has a different definition) and `projectOnly`. A source is +owned when a ledger entry records its name and complete `sourceHash`. Rows are +ordered by natural, case-insensitive name (digit runs compare numerically, bytes +break ties), then global before project-only, then definition hash. A file that +fails to parse contributes no rows and appears in `failures: [{ file, code, +message }]` without echoing content; hosts report their own read failures. + +`mcp.validateDraft` accepts `{ draft: { name, transport, command, url, +arguments, env, headers, enabledAgents, setup? } }` and returns `{ issues: +[{ field, code }], definition }`. Issues are ordered by display priority: +`name`/`nameRequired` or `nameInvalid` (`^[A-Za-z0-9][A-Za-z0-9._-]*$` after +trimming), `enabledAgents`/`agentsRequired`, `env` or `headers`/`duplicateKeys` +(active transport only, blank keys ignored), `command`/`commandRequired`, +`url`/`urlInvalid` (an absolute URL with a host), then featured setup: +`headers`/`bearerTokenRequired` (one `Authorization: Bearer ` value, +scheme case-insensitive) or `arguments`/`allowedDirectoriesRequired` (at least +one POSIX, drive or UNC absolute folder after the two fixed arguments). +`definition` is the normalized server a save writes — trimmed name, command or +URL, only the active transport's fields, blank keys dropped, entries sorted by +key — or `null` while issues remain. Values are never echoed in issues. + +`mcp.batchPlan` accepts `{ files, intent }`, with `intent` one of: +`{ kind: "save", draft, original?: { name, sources: [{ file, sourceHash?, +ownedByLithe }] } }`, `{ kind: "setAgent", definition: McpServer, agent, +enabled }` or `{ kind: "delete", name, files: string[] }`. `save` validates the +draft as above, removes the captured original from every global source whose +Agent is no longer enabled (requiring the captured `sourceHash` and a ledger +entry with that exact hash), and sets the definition in every global file whose +`source` is enabled, passing the captured hash as `expectedHash` and renaming +from the original name where the original existed. `setAgent` targets the first +global file of `agent`; `delete` removes the name from the listed files. Each +file's operations are planned in order with `mcp.planWrite` rules against the +previous output and the evolving ledger. The response is `{ status: "invalid", +issues }`, `{ status: "rejected", rejection: { code, name, file } }` with code +`notOwned`, `externallyModified` or `agentHasNoGlobalConfiguration` (`file` is +the conflicting file, or `null` for draft-level checks), or `{ status: "ready", +changes: [{ file, changed, content?, owned, renames: [{ from, to }] }] }` in +host file order. `content` is present only when changed; `owned` is the file's +next ledger (unchanged files return their input ledger). Hosts write every +changed file as one rollback batch and publish ledgers and renames only after +the whole batch succeeds. `shared/fixtures/mcp/library-v1.json` holds the shared +cases; its `{{sourceHash::}}` placeholders are resolved from the +parsed fixture files. + ### Agent adapters -`agent.parseProviderConfiguration` takes `{source, configuration}` with `source` -equal to `codex` (TOML) or `claude` (JSON). It reuses the typed AI configuration -parsers with an empty environment and returns provider metadata only, without -credentials or credential-presence flags. Configuration text is limited to -64 KiB UTF-8. Invalid source, malformed text and oversized input return -`invalid_request` without raw input or parser diagnostics. The fixture is -`shared/fixtures/agent/provider-configuration-v1.json`. Hosts extract explicit -API keys, validate Agent protocol compatibility, and persist credentials in their -native vault. This operation does not discover or write local CLI files. - -The optional `allowIncomplete: true` is for switching an editor draft back to -form fields. It accepts syntactically valid incomplete or blank input, preserves -missing endpoint/model fields as empty strings, and does not inject CLI defaults. -Claude metadata uses `apiKey` authentication when no credential is present; -an explicit auth token still uses `bearer`. Credential extraction remains -host-owned and may return an empty key only in this draft mode. Malformed text -and the 64 KiB limit still fail with redacted errors. Omitting this flag keeps -the existing parser behavior; saving still requires all fields, a compatible -protocol and explicit consent for HTTP. +`ai.configuration.sources` takes `{source, home, environment}` (`source` is +`codex` or `claude`, `home` an absolute path, `environment` only the directory +overrides `CODEX_HOME` / `CLAUDE_CONFIG_DIR`) and returns `{files}`: the native +files `{file, path}` the platform should read. `ai.configuration.parse` takes +`{source, files, environment, allowIncomplete}` with the file texts keyed +`config`, `auth`, `settings`, `credentials` and `root`, each at most 1 MiB, and +returns `null` when nothing is configured, otherwise `{model, provider, issue, +reasoningEffort, hasCredential, credential, unsupportedAuthentication}`. The +response never contains a secret: `credential` is a locator +(`{kind: "environment", name}` or `{kind: "file", file, path}`) that the host +resolves natively against the same text or environment. Malformed input returns +`invalid_request` with a fixed code (`AI_COMMIT_INVALID_CONFIG`, +`AI_CONFIGURATION_INVALID_AUTHENTICATION`, `AI_CONFIGURATION_SMART_QUOTES`, +`AI_CONFIGURATION_TOO_LARGE`) and never echoes input. `allowIncomplete: true` is +for editor drafts: it ignores the environment, accepts blank or partial text and +keeps missing endpoint/model fields empty. The shared cases are in +`shared/fixtures/ai/cli-configuration-v1.json`. It replaces the former +`agent.parseProviderConfiguration`. + +`agent.edits.reversePlan` takes `{diffs, disk}` (normalized edit evidence plus the +current file text, or `null` when the file is missing) and returns the rollback +plan or a conflict; it never touches the file system. Path containment, encoding, +guarded writes and Trash stay with the platform. Cases are in +`shared/fixtures/agent/edit-review-v1.json`. `agent.instructions.read` takes `{agentId}` (`codex-acp` or `claude-acp`) and returns `{agentId, path, content, exists, revision}`. It does not create files. @@ -1061,6 +1148,22 @@ does not claim execution. Source, ownership journal, lock and temporary siblings are user state outside installed resources and cannot be reused across worktrees. The shared fixture is `shared/fixtures/agent/hooks-management-v1.json`. +`agent.hooks.validateDraft` validates an unsaved editor draft without reading or +writing files, using the same rules `save` enforces in Agent Host. The payload is +`{hook, existingHooks}`: `hook` has `id`, `name`, `description`, `event`, `matcher`, +`command`, `agents` and the raw `timeoutText` of the timeout field (empty inherits +the native default; only ASCII digits are integers), and `existingHooks` lists +library rows as `{id, name}` for the case-insensitive unique-name rule. The result is +`{valid, issues, timeoutSeconds}`: `issues` holds at most one `{field, code}` per +field in editor order, and `timeoutSeconds` is the parsed value platforms store when +saving (null when empty or rejected). Fields and codes: `id` `invalid`; `name` +`required`, `too_long`, `invalid_characters`, `duplicate`; `description` `too_long`; +`matcher` `incompatible_event`; `command` `required`, `too_long`, `contains_nul`; +`timeout` `not_integer`, `out_of_range`; `agents` `required`, `unsupported`, +`duplicate`. Platforms localize `agent.hooks.draft..` and enable saving +only when `valid`. A malformed payload fails with `invalid_request`. The fixture is +`shared/fixtures/agent/hook-draft-validation-v1.json`. + `agent.status`, `agent.install`, `agent.uninstall`, and `agent.installCli` manage ACP adapters in `/agents/`, using the Node.js and npm the user installed. Lithe never installs Node.js or npm; the agents' own command-line tools are installed only through `agent.installCli` on an explicit user action. `agent.status` diff --git a/shared/fixtures/agent/acp-events-v1.json b/shared/fixtures/agent/acp-events-v1.json index e72dc048ac..2e95d83d1f 100644 --- a/shared/fixtures/agent/acp-events-v1.json +++ b/shared/fixtures/agent/acp-events-v1.json @@ -209,15 +209,15 @@ }, "fileEdit": { "kind": "update", "sessionId": "session-1", - "update": { "sessionUpdate": "tool_call", "toolCallId": "edit-1", "title": "Edit sample.txt", "kind": "edit", "status": "completed", "content": [{ "type": "diff", "path": "sample.txt", "oldText": "before\n", "newText": "after\n", "_meta": { "kind": "update", "jetbrains": { "air": { "version": 1, "diffStats": { "version": 1, "added": 1, "removed": 1 } } } } }] } + "update": { "sessionUpdate": "tool_call", "toolCallId": "edit-1", "title": "Edit sample.txt", "kind": "edit", "status": "completed", "content": [{ "type": "diff", "path": "sample.txt", "oldText": "before\n", "newText": "after\n", "_meta": { "kind": "update", "jetbrains": { "air": { "version": 1, "diffStats": { "version": 1, "added": 1, "removed": 1 } } } } }], "_meta": { "lithe": { "diffs": [{ "path": "sample.txt", "oldText": "before\n", "newText": "after\n", "operation": "update", "additions": 1, "deletions": 1, "truncated": false, "revertible": true }] } } } }, "claudeFileCreated": { "kind": "update", "sessionId": "session-1", - "update": { "sessionUpdate": "tool_call_update", "toolCallId": "write-create", "kind": "edit", "status": "completed", "content": [{ "type": "diff", "path": "created.txt", "newText": "created" }], "_meta": { "claudeCode": { "toolName": "Write", "toolResponse": { "type": "create", "filePath": "created.txt", "content": "created\n", "originalFile": null, "structuredPatch": [] } } } } + "update": { "sessionUpdate": "tool_call_update", "toolCallId": "write-create", "kind": "edit", "status": "completed", "content": [{ "type": "diff", "path": "created.txt", "newText": "created" }], "_meta": { "claudeCode": { "toolName": "Write", "toolResponse": { "type": "create", "filePath": "created.txt", "content": "created\n", "originalFile": null, "structuredPatch": [] } }, "lithe": { "diffs": [{ "path": "created.txt", "oldText": null, "newText": "created\n", "operation": "add", "additions": null, "deletions": null, "truncated": false, "revertible": true }] } } } }, "claudeFileWriteUpdated": { "kind": "update", "sessionId": "session-1", - "update": { "sessionUpdate": "tool_call_update", "toolCallId": "write-update", "kind": "edit", "status": "completed", "content": [{ "type": "diff", "path": "updated.txt", "oldText": "before", "newText": "after" }], "_meta": { "claudeCode": { "toolName": "Write", "toolResponse": { "type": "update", "filePath": "updated.txt", "content": "after\n", "originalFile": "before\n", "structuredPatch": [] } } } } + "update": { "sessionUpdate": "tool_call_update", "toolCallId": "write-update", "kind": "edit", "status": "completed", "content": [{ "type": "diff", "path": "updated.txt", "oldText": "before", "newText": "after" }], "_meta": { "claudeCode": { "toolName": "Write", "toolResponse": { "type": "update", "filePath": "updated.txt", "content": "after\n", "originalFile": "before\n", "structuredPatch": [] } }, "lithe": { "diffs": [{ "path": "updated.txt", "oldText": "before\n", "newText": "after\n", "operation": "update", "additions": null, "deletions": null, "truncated": false, "revertible": true }] } } } }, "codexRetry": { "kind": "update", "sessionId": "session-1", @@ -259,6 +259,12 @@ "firstTokenMs": 820, "durationMs": 6400, "usage": { "inputTokens": 1200, "cacheReadTokens": 42000, "cacheWriteTokens": 800, "outputTokens": 640 }, "context": { "systemPromptTokens": 4500, "toolTokens": 3500, "mcpToolTokens": 14000, "messageTokens": 22000, "toolCount": 18, "mcpToolCount": 40, "scaledToUsage": true } + }, + "statistics": { + "requests": 1, "steps": 1, "failedSteps": 0, "nonStreamingSteps": 0, "durationMs": 6400, + "inputTokens": 1200, "cacheReadTokens": 42000, "cacheWriteTokens": 800, "outputTokens": 640, "callsWithUsage": 1, + "firstTokenMs": 820, "firstTokenCount": 1, "generationMs": 5580, "generatedTokens": 640, + "context": { "systemPromptTokens": 4500, "toolTokens": 3500, "mcpToolTokens": 14000, "messageTokens": 22000, "toolCount": 18, "mcpToolCount": 40, "scaledToUsage": true } } }, "modelCallAfterTurn": { @@ -270,6 +276,12 @@ "firstTokenMs": 820, "durationMs": 6400, "usage": { "inputTokens": 1200, "cacheReadTokens": 42000, "cacheWriteTokens": 800, "outputTokens": 640 }, "context": { "systemPromptTokens": 4500, "toolTokens": 3500, "mcpToolTokens": 14000, "messageTokens": 22000, "toolCount": 18, "mcpToolCount": 40, "scaledToUsage": true } + }, + "statistics": { + "requests": 1, "steps": 1, "failedSteps": 0, "nonStreamingSteps": 0, "durationMs": 6400, + "inputTokens": 1200, "cacheReadTokens": 42000, "cacheWriteTokens": 800, "outputTokens": 640, "callsWithUsage": 1, + "firstTokenMs": 820, "firstTokenCount": 1, "generationMs": 5580, "generatedTokens": 640, + "context": { "systemPromptTokens": 4500, "toolTokens": 3500, "mcpToolTokens": 14000, "messageTokens": 22000, "toolCount": 18, "mcpToolCount": 40, "scaledToUsage": true } } }, "modelCallNonStreaming": { @@ -278,6 +290,11 @@ "call": { "api": "responses", "status": 200, "streaming": false, "durationMs": 3000, "usage": { "inputTokens": 500, "cacheReadTokens": 0, "cacheWriteTokens": 0, "outputTokens": 300, "reasoningTokens": 100 } + }, + "statistics": { + "requests": 1, "steps": 1, "failedSteps": 0, "nonStreamingSteps": 1, "durationMs": 3000, + "inputTokens": 500, "cacheReadTokens": 0, "cacheWriteTokens": 0, "outputTokens": 300, "reasoningTokens": 100, "callsWithUsage": 1, + "firstTokenMs": 0, "firstTokenCount": 0, "generationMs": 0, "generatedTokens": 0 } }, "turnFinished": { "kind": "turnFinished", "sessionId": "session-1", "stopReason": "end_turn" }, diff --git a/shared/fixtures/agent/provider-configuration-v1.json b/shared/fixtures/agent/provider-configuration-v1.json deleted file mode 100644 index 6a4a0f03c8..0000000000 --- a/shared/fixtures/agent/provider-configuration-v1.json +++ /dev/null @@ -1,147 +0,0 @@ -{ - "schemaVersion": 1, - "cases": [ - { - "source": "codex", - "configuration": "model = 'unused'\nprofile = 'work'\n[profiles.work]\nmodel = 'fixture-model'\nmodel_provider = 'gateway'\n[model_providers.gateway]\nbase_url = 'https://example.test/v1'\nwire_api = 'responses'\nrequires_openai_auth = true\n", - "expected": { - "endpoint": "https://example.test/v1", - "model": "fixture-model", - "apiProtocol": "responses" - } - }, - { - "source": "claude", - "configuration": "{\"env\":{\"ANTHROPIC_BASE_URL\":\"https://example.test/v1\",\"ANTHROPIC_MODEL\":\"sonnet\",\"ANTHROPIC_DEFAULT_SONNET_MODEL\":\"fixture-model\",\"ANTHROPIC_API_KEY\":\"fixture-secret\"}}", - "expected": { - "endpoint": "https://example.test/v1", - "model": "fixture-model", - "apiProtocol": "anthropicMessages" - } - } - ], - "draftCases": [ - { - "id": "codex-empty", - "source": "codex", - "configuration": "", - "expected": { - "endpoint": "", - "model": "", - "apiProtocol": "responses", - "authentication": "bearer" - } - }, - { - "id": "codex-model-only", - "source": "codex", - "configuration": "model = 'draft-model'", - "expected": { - "endpoint": "", - "model": "draft-model", - "apiProtocol": "responses", - "authentication": "bearer" - } - }, - { - "id": "codex-endpoint-only", - "source": "codex", - "configuration": "model_provider = 'custom'\n[model_providers.custom]\nbase_url = 'https://example.test/v1'", - "expected": { - "endpoint": "https://example.test/v1", - "model": "", - "apiProtocol": "responses", - "authentication": "bearer" - } - }, - { - "id": "claude-blank", - "source": "claude", - "configuration": "", - "expected": { - "endpoint": "", - "model": "", - "apiProtocol": "anthropicMessages", - "authentication": "apiKey" - } - }, - { - "id": "claude-empty", - "source": "claude", - "configuration": "{}", - "expected": { - "endpoint": "", - "model": "", - "apiProtocol": "anthropicMessages", - "authentication": "apiKey" - } - }, - { - "id": "claude-empty-template", - "source": "claude", - "configuration": "{\"env\":{\"ANTHROPIC_BASE_URL\":\"\",\"ANTHROPIC_MODEL\":\"\",\"ANTHROPIC_API_KEY\":\"\"}}", - "expected": { - "endpoint": "", - "model": "", - "apiProtocol": "anthropicMessages", - "authentication": "apiKey" - } - }, - { - "id": "claude-model-only", - "source": "claude", - "configuration": "{\"env\":{\"ANTHROPIC_MODEL\":\"draft-model\"}}", - "expected": { - "endpoint": "", - "model": "draft-model", - "apiProtocol": "anthropicMessages", - "authentication": "apiKey" - } - }, - { - "id": "claude-key-only", - "source": "claude", - "configuration": "{\"env\":{\"ANTHROPIC_API_KEY\":\"fixture-secret\"}}", - "expected": { - "endpoint": "", - "model": "", - "apiProtocol": "anthropicMessages", - "authentication": "apiKey" - }, - "expectedAPIKey": "fixture-secret" - }, - { - "id": "claude-alias", - "source": "claude", - "configuration": "{\"env\":{\"ANTHROPIC_MODEL\":\"sonnet\",\"ANTHROPIC_DEFAULT_SONNET_MODEL\":\"alias-model\"}}", - "expected": { - "endpoint": "", - "model": "alias-model", - "apiProtocol": "anthropicMessages", - "authentication": "apiKey" - } - }, - { - "id": "codex-whitespace", - "source": "codex", - "configuration": " \n\t ", - "expected": { - "endpoint": "", - "model": "", - "apiProtocol": "responses", - "authentication": "bearer" - } - }, - { - "id": "claude-whitespace", - "source": "claude", - "configuration": " \n\t ", - "expected": { - "endpoint": "", - "model": "", - "apiProtocol": "anthropicMessages", - "authentication": "apiKey" - } - } - ] -} diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 6a6e656f5a..52e2d023b2 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -154,6 +154,22 @@ "agent.history.tool": "Tool", "agent.history.unknownProvider": "Unknown provider", "agent.history.you": "You", + "agent.hooks.draft.agents.duplicate": "Each Agent can be selected only once.", + "agent.hooks.draft.agents.required": "Select at least one Agent.", + "agent.hooks.draft.agents.unsupported": "Only Codex and Claude Code support Hooks.", + "agent.hooks.draft.command.containsNul": "The command cannot contain a NUL character.", + "agent.hooks.draft.command.required": "Enter a command.", + "agent.hooks.draft.command.tooLong": "The command can have at most 32768 bytes.", + "agent.hooks.draft.description.tooLong": "The description can have at most 200 characters.", + "agent.hooks.draft.id.invalid": "This Hook draft has an invalid identifier. Close the editor and try again.", + "agent.hooks.draft.matcher.incompatibleEvent": "Tool filters apply only to tool events.", + "agent.hooks.draft.name.duplicate": "A Hook with this name already exists.", + "agent.hooks.draft.name.invalidCharacters": "Use only letters, digits, hyphens or underscores in the Hook name.", + "agent.hooks.draft.name.required": "Enter a Hook name.", + "agent.hooks.draft.name.tooLong": "Hook names can have at most 80 characters.", + "agent.hooks.draft.responseInvalid": "The Hook draft validation response was not recognised.", + "agent.hooks.draft.timeout.notInteger": "Enter the timeout as a whole number of seconds, or leave it empty.", + "agent.hooks.draft.timeout.outOfRange": "The timeout must be from 1 to 86400 seconds.", "agent.notice.dismiss": "Dismiss notification", "agent.permission.deny": "Deny", "agent.permission.dismiss": "Not now", @@ -3154,6 +3170,20 @@ "indexing.workspaceUnavailable": "The project folder is unavailable. Restore it, then retry.", "indexing.writeFailed": "Could not save project indexing settings. Your previous settings remain unchanged.", "inlineEdit.addApiKey": "Add API key", + "inlineEdit.aiINLINEEDITENDPOINTMISSING": "Custom provider base URL is required. Add one in Settings > AI.", + "inlineEdit.aiINLINEEDITFAILED": "Inline edit failed. Please try again.", + "inlineEdit.aiINLINEEDITHTTP": "The AI provider returned HTTP {status}. Check your key and model.", + "inlineEdit.aiINLINEEDITINSECUREENDPOINT": "This provider requires HTTPS.", + "inlineEdit.aiINLINEEDITINVALIDENDPOINT": "The provider URL is invalid. Use an HTTP(S) URL without credentials, query or fragment.", + "inlineEdit.aiINLINEEDITINVALIDREQUEST": "The selection or its context is too large for inline edit.", + "inlineEdit.aiINLINEEDITINVALIDRESPONSE": "The AI provider returned an unexpected response.", + "inlineEdit.aiINLINEEDITMISSINGKEY": "An API key is required for inline edit. Add one in Settings > AI.", + "inlineEdit.aiINLINEEDITMODELMISSING": "No inline edit model selected.", + "inlineEdit.aiINLINEEDITMODELNOTFOUND": "The selected model is not offered by this provider. Refresh the model list or choose another model.", + "inlineEdit.aiINLINEEDITNETWORKERROR": "Could not reach the AI provider. Check your network and provider URL.", + "inlineEdit.aiINLINEEDITOUTPUTLIMIT": "The model reached its output limit before finishing. Select less text and try again.", + "inlineEdit.aiINLINEEDITPROVIDERNOTFOUND": "The selected AI provider is not available. Choose another provider in Settings > AI.", + "inlineEdit.aiINLINEEDITUNSUPPORTEDPROVIDER": "This AI provider does not support inline edit.", "inlineEdit.apiKeyRequired": "{provider} API key is required for inline edit.", "inlineEdit.applied": "Inline edit applied.", "inlineEdit.apply": "Apply inline edit", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 720817ad0e..d5038fcc95 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -154,6 +154,22 @@ "agent.history.tool": "工具", "agent.history.unknownProvider": "未知供应商", "agent.history.you": "你", + "agent.hooks.draft.agents.duplicate": "每个 Agent 只能选择一次。", + "agent.hooks.draft.agents.required": "请至少选择一个 Agent。", + "agent.hooks.draft.agents.unsupported": "只有 Codex 和 Claude Code 支持 Hook。", + "agent.hooks.draft.command.containsNul": "命令不能包含 NUL 字符。", + "agent.hooks.draft.command.required": "请输入命令。", + "agent.hooks.draft.command.tooLong": "命令最多 32768 字节。", + "agent.hooks.draft.description.tooLong": "描述最多 200 个字符。", + "agent.hooks.draft.id.invalid": "此 Hook 草稿的标识无效,请关闭编辑器后重试。", + "agent.hooks.draft.matcher.incompatibleEvent": "工具筛选只适用于工具相关的事件。", + "agent.hooks.draft.name.duplicate": "已存在同名的 Hook。", + "agent.hooks.draft.name.invalidCharacters": "Hook 名称只能包含字母、数字、连字符或下划线。", + "agent.hooks.draft.name.required": "请输入 Hook 名称。", + "agent.hooks.draft.name.tooLong": "Hook 名称最多 80 个字符。", + "agent.hooks.draft.responseInvalid": "无法识别 Hook 草稿校验结果。", + "agent.hooks.draft.timeout.notInteger": "超时请填写整数秒,或留空。", + "agent.hooks.draft.timeout.outOfRange": "超时必须在 1 到 86400 秒之间。", "agent.notice.dismiss": "关闭通知", "agent.permission.deny": "拒绝", "agent.permission.dismiss": "暂不处理", @@ -3154,6 +3170,20 @@ "indexing.workspaceUnavailable": "项目目录不可用。请恢复目录后重试。", "indexing.writeFailed": "无法保存项目索引设置,原有设置未改变。", "inlineEdit.addApiKey": "添加 API 密钥", + "inlineEdit.aiINLINEEDITENDPOINTMISSING": "需要自定义服务商的 Base URL,请在“设置 > AI”中添加。", + "inlineEdit.aiINLINEEDITFAILED": "行内编辑失败,请重试。", + "inlineEdit.aiINLINEEDITHTTP": "AI 服务商返回 HTTP {status},请检查密钥和模型。", + "inlineEdit.aiINLINEEDITINSECUREENDPOINT": "该服务商要求使用 HTTPS。", + "inlineEdit.aiINLINEEDITINVALIDENDPOINT": "服务商 URL 无效,请使用不含凭据、查询参数或片段的 HTTP(S) 地址。", + "inlineEdit.aiINLINEEDITINVALIDREQUEST": "选区或其上下文过大,无法进行行内编辑。", + "inlineEdit.aiINLINEEDITINVALIDRESPONSE": "AI 服务商返回了无法识别的响应。", + "inlineEdit.aiINLINEEDITMISSINGKEY": "行内编辑需要 API 密钥,请在“设置 > AI”中添加。", + "inlineEdit.aiINLINEEDITMODELMISSING": "尚未选择行内编辑模型。", + "inlineEdit.aiINLINEEDITMODELNOTFOUND": "该服务商未提供所选模型,请刷新模型列表或选择其他模型。", + "inlineEdit.aiINLINEEDITNETWORKERROR": "无法连接 AI 服务商,请检查网络和服务商地址。", + "inlineEdit.aiINLINEEDITOUTPUTLIMIT": "模型在完成前达到输出上限,请缩小选区后重试。", + "inlineEdit.aiINLINEEDITPROVIDERNOTFOUND": "所选 AI 服务商不可用,请在“设置 > AI”中选择其他服务商。", + "inlineEdit.aiINLINEEDITUNSUPPORTEDPROVIDER": "该 AI 服务商不支持行内编辑。", "inlineEdit.apiKeyRequired": "行内编辑需要 {provider} API 密钥。", "inlineEdit.applied": "行内编辑已应用。", "inlineEdit.apply": "应用行内编辑", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 384460d88a..61a6892d19 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -1159,6 +1159,192 @@ "windows" ] }, + { + "id": "agent.hooks.draft.agents.duplicate", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (agents: duplicate)", + "platforms": [ + "macos", + "windows" + ] + }, + { + "id": "agent.hooks.draft.agents.required", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (agents: required)", + "platforms": [ + "macos", + "windows" + ] + }, + { + "id": "agent.hooks.draft.agents.unsupported", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (agents: unsupported)", + "platforms": [ + "macos", + "windows" + ] + }, + { + "id": "agent.hooks.draft.command.containsNul", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (command: contains_nul)", + "platforms": [ + "macos", + "windows" + ], + "macos": { + "key": "agent.hooks.draft.command.contains_nul", + "arguments": [] + }, + "windows": { + "key": "agent.hooks.draft.command.contains_nul" + } + }, + { + "id": "agent.hooks.draft.command.required", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (command: required)", + "platforms": [ + "macos", + "windows" + ] + }, + { + "id": "agent.hooks.draft.command.tooLong", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (command: too_long)", + "platforms": [ + "macos", + "windows" + ], + "macos": { + "key": "agent.hooks.draft.command.too_long", + "arguments": [] + }, + "windows": { + "key": "agent.hooks.draft.command.too_long" + } + }, + { + "id": "agent.hooks.draft.description.tooLong", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (description: too_long)", + "platforms": [ + "macos", + "windows" + ], + "macos": { + "key": "agent.hooks.draft.description.too_long", + "arguments": [] + }, + "windows": { + "key": "agent.hooks.draft.description.too_long" + } + }, + { + "id": "agent.hooks.draft.id.invalid", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (id: invalid)", + "platforms": [ + "macos", + "windows" + ] + }, + { + "id": "agent.hooks.draft.matcher.incompatibleEvent", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (matcher: incompatible_event)", + "platforms": [ + "macos", + "windows" + ], + "macos": { + "key": "agent.hooks.draft.matcher.incompatible_event", + "arguments": [] + }, + "windows": { + "key": "agent.hooks.draft.matcher.incompatible_event" + } + }, + { + "id": "agent.hooks.draft.name.duplicate", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (name: duplicate)", + "platforms": [ + "macos", + "windows" + ] + }, + { + "id": "agent.hooks.draft.name.invalidCharacters", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (name: invalid_characters)", + "platforms": [ + "macos", + "windows" + ], + "macos": { + "key": "agent.hooks.draft.name.invalid_characters", + "arguments": [] + }, + "windows": { + "key": "agent.hooks.draft.name.invalid_characters" + } + }, + { + "id": "agent.hooks.draft.name.required", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (name: required)", + "platforms": [ + "macos", + "windows" + ] + }, + { + "id": "agent.hooks.draft.name.tooLong", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (name: too_long)", + "platforms": [ + "macos", + "windows" + ], + "macos": { + "key": "agent.hooks.draft.name.too_long", + "arguments": [] + }, + "windows": { + "key": "agent.hooks.draft.name.too_long" + } + }, + { + "id": "agent.hooks.draft.responseInvalid", + "description": "Windows UI: Core returned an unrecognised Hook draft validation response", + "platforms": [ + "windows" + ], + "windows": { + "key": "The Hook draft validation response was not recognised." + } + }, + { + "id": "agent.hooks.draft.timeout.notInteger", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (timeout: not_integer)", + "platforms": [ + "macos", + "windows" + ], + "macos": { + "key": "agent.hooks.draft.timeout.not_integer", + "arguments": [] + }, + "windows": { + "key": "agent.hooks.draft.timeout.not_integer" + } + }, + { + "id": "agent.hooks.draft.timeout.outOfRange", + "description": "Hook editor field issue from Core agent.hooks.validateDraft (timeout: out_of_range)", + "platforms": [ + "macos", + "windows" + ], + "macos": { + "key": "agent.hooks.draft.timeout.out_of_range", + "arguments": [] + }, + "windows": { + "key": "agent.hooks.draft.timeout.out_of_range" + } + }, { "id": "agent.notice.dismiss", "description": "Windows UI: agent.notice.dismiss", @@ -11426,6 +11612,30 @@ "windows" ] }, + { + "id": "editor.workspaceEditOutsideWorkspace", + "description": "Workspace edit rejected because a target is outside the workspace.", + "platforms": [ + "windows" + ] + }, + { + "id": "editor.workspaceEditReadOnlyDocument", + "description": "Workspace edit rejected because a target document is read-only.", + "platforms": [ + "windows" + ] + }, + { + "id": "editor.workspaceEditRollbackFailed", + "description": "Workspace edit failed and some files could not be restored.", + "platforms": [ + "windows" + ], + "parameters": { + "paths": "string" + } + }, { "id": "editor.workspaceEditStale", "description": "Workspace edit rejected after document or workspace changes.", @@ -24872,6 +25082,149 @@ "windows" ] }, + { + "id": "inlineEdit.aiINLINEEDITENDPOINTMISSING", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_ENDPOINT_MISSING", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_ENDPOINT_MISSING" + } + }, + { + "id": "inlineEdit.aiINLINEEDITFAILED", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_FAILED", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_FAILED" + } + }, + { + "id": "inlineEdit.aiINLINEEDITHTTP", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_HTTP", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_HTTP" + }, + "parameters": { + "status": "integer" + } + }, + { + "id": "inlineEdit.aiINLINEEDITINSECUREENDPOINT", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_INSECURE_ENDPOINT", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_INSECURE_ENDPOINT" + } + }, + { + "id": "inlineEdit.aiINLINEEDITINVALIDENDPOINT", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_INVALID_ENDPOINT", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_INVALID_ENDPOINT" + } + }, + { + "id": "inlineEdit.aiINLINEEDITINVALIDREQUEST", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_INVALID_REQUEST", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_INVALID_REQUEST" + } + }, + { + "id": "inlineEdit.aiINLINEEDITINVALIDRESPONSE", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_INVALID_RESPONSE", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_INVALID_RESPONSE" + } + }, + { + "id": "inlineEdit.aiINLINEEDITMISSINGKEY", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_MISSING_KEY", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_MISSING_KEY" + } + }, + { + "id": "inlineEdit.aiINLINEEDITMODELMISSING", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_MODEL_MISSING", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_MODEL_MISSING" + } + }, + { + "id": "inlineEdit.aiINLINEEDITMODELNOTFOUND", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_MODEL_NOT_FOUND", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_MODEL_NOT_FOUND" + } + }, + { + "id": "inlineEdit.aiINLINEEDITNETWORKERROR", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_NETWORK_ERROR", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_NETWORK_ERROR" + } + }, + { + "id": "inlineEdit.aiINLINEEDITOUTPUTLIMIT", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_OUTPUT_LIMIT", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_OUTPUT_LIMIT" + } + }, + { + "id": "inlineEdit.aiINLINEEDITPROVIDERNOTFOUND", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_PROVIDER_NOT_FOUND", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_PROVIDER_NOT_FOUND" + } + }, + { + "id": "inlineEdit.aiINLINEEDITUNSUPPORTEDPROVIDER", + "description": "Windows UI: inline edit failure AI_INLINE_EDIT_UNSUPPORTED_PROVIDER", + "platforms": [ + "windows" + ], + "windows": { + "key": "inlineEdit.AI_INLINE_EDIT_UNSUPPORTED_PROVIDER" + } + }, { "id": "inlineEdit.apiKeyRequired", "description": "Windows UI: inlineEdit.apiKeyRequired", @@ -52041,6 +52394,17 @@ "arguments": [] } }, + { + "id": "native.languageEditCouldNotBePlanned", + "description": "Native UI: Language edit could not be planned.", + "platforms": [ + "macos" + ], + "macos": { + "key": "Language edit could not be planned.", + "arguments": [] + } + }, { "id": "native.languageEditTargetsAFileOutsideTheWorkspace", "description": "Native UI: Language edit targets a file outside the workspace.", @@ -74676,11 +75040,15 @@ "id": "native.theAIProviderReturnedAnEmptyPullRequestDescription", "description": "Native UI: The AI provider returned an empty pull request description.", "platforms": [ - "macos" + "macos", + "windows" ], "macos": { "key": "The AI provider returned an empty pull request description.", "arguments": [] + }, + "windows": { + "key": "aiCommit.AI_PULL_REQUEST_EMPTY_RESPONSE" } }, { @@ -74698,11 +75066,15 @@ "id": "native.theAIProviderReturnedAnUnexpectedPullRequestDescription", "description": "Native UI: The AI provider returned an unexpected pull request description.", "platforms": [ - "macos" + "macos", + "windows" ], "macos": { "key": "The AI provider returned an unexpected pull request description.", "arguments": [] + }, + "windows": { + "key": "aiCommit.AI_PULL_REQUEST_INVALID_RESPONSE" } }, { @@ -74890,7 +75262,8 @@ "id": "native.theAgentDidNotConfirmTheSelectedSessionSetting", "description": "Native UI: The Agent did not confirm the selected session setting.", "platforms": [ - "macos" + "macos", + "windows" ], "macos": { "key": "The Agent did not confirm the selected session setting.", @@ -74989,7 +75362,8 @@ "id": "native.theAgentNoLongerSupportsTheSelectedSessionSetting", "description": "Native UI: The Agent no longer supports the selected session setting.", "platforms": [ - "macos" + "macos", + "windows" ], "macos": { "key": "The Agent no longer supports the selected session setting.", @@ -75022,7 +75396,8 @@ "id": "native.theAgentRequestFailed", "description": "Native UI: The Agent request failed.", "platforms": [ - "macos" + "macos", + "windows" ], "macos": { "key": "The Agent request failed.", @@ -77744,11 +78119,15 @@ "id": "native.theSelectedBranchesHaveNoTextualChangesToSummarize", "description": "Native UI: The selected branches have no textual changes to summarize.", "platforms": [ - "macos" + "macos", + "windows" ], "macos": { "key": "The selected branches have no textual changes to summarize.", "arguments": [] + }, + "windows": { + "key": "aiCommit.AI_PULL_REQUEST_EMPTY_COMPARISON" } }, { @@ -98305,41 +98684,6 @@ "windows" ] }, - { - "id": "editor.workspaceEditOutsideWorkspace", - "description": "Workspace edit rejected because a target is outside the workspace.", - "platforms": [ - "windows" - ] - }, - { - "id": "editor.workspaceEditReadOnlyDocument", - "description": "Workspace edit rejected because a target document is read-only.", - "platforms": [ - "windows" - ] - }, - { - "id": "editor.workspaceEditRollbackFailed", - "description": "Workspace edit failed and some files could not be restored.", - "platforms": [ - "windows" - ], - "parameters": { - "paths": "string" - } - }, - { - "id": "native.languageEditCouldNotBePlanned", - "description": "Native UI: Language edit could not be planned.", - "platforms": [ - "macos" - ], - "macos": { - "key": "Language edit could not be planned.", - "arguments": [] - } - }, { "id": "workspace.appStore", "description": "Native project file Open With menu", diff --git a/windows/tauri/src-tauri/src/ai_commit.rs b/windows/tauri/src-tauri/src/ai_commit.rs index 5745f1ec72..50d5fc5410 100644 --- a/windows/tauri/src-tauri/src/ai_commit.rs +++ b/windows/tauri/src-tauri/src/ai_commit.rs @@ -1,6 +1,9 @@ // Note: .agents/notes/implemented/feature/2026-09-22-windows-ai-commit-design.md // Native configuration, credential, cancellation and HTTP boundary. Core owns pure rules. -use lithe_core::ai::{self, CommitFile, CommitOptions, DetectedConfiguration, Provider}; +use lithe_core::ai::{ + self, CommitFile, CommitOptions, CommitRequestPlan, ConfigurationFile, ConfigurationFiles, + DetectedConfiguration, Provider, PullRequestComparison, PullRequestOptions, +}; use serde::Deserialize; use serde_json::{json, Value}; use std::collections::{BTreeMap, HashMap}; @@ -54,50 +57,29 @@ fn read_optional(path: &Path) -> Result { Ok(text) } -fn load_source(app: &AppHandle, source: &str) -> Result, String> { +/// Reads the files Core names for one CLI source and applies the shared rules. +/// The credential stays in this host process; callers never return it to the UI. +pub(crate) fn load_source( + app: &AppHandle, + source: &str, +) -> Result, String> { let home = app .path() .home_dir() .map_err(|_| "AI_COMMIT_CONFIG_READ_FAILED")?; let environment: BTreeMap = std::env::vars().collect(); - match source { - "codex" => { - let directory = environment - .get("CODEX_HOME") - .filter(|s| !s.trim().is_empty()) - .map(std::path::PathBuf::from) - .unwrap_or_else(|| home.join(".codex")); - let config = read_optional(&directory.join("config.toml"))?; - if config.is_empty() { - return Ok(None); - } - let auth = read_optional(&directory.join("auth.json"))?; - ai::parse_codex(&config, &auth, &environment) - .map(Some) - .map_err(str::to_owned) - } - "claude" => { - let directory = environment - .get("CLAUDE_CONFIG_DIR") - .filter(|s| !s.trim().is_empty()) - .map(std::path::PathBuf::from) - .unwrap_or_else(|| home.join(".claude")); - let settings = read_optional(&directory.join("settings.json"))?; - let credentials = read_optional(&directory.join(".credentials.json"))?; - let root = read_optional(&home.join(".claude.json"))?; - if settings.is_empty() - && credentials.is_empty() - && root.is_empty() - && !environment.keys().any(|key| key.starts_with("ANTHROPIC_")) - { - return Ok(None); - } - ai::parse_claude(&settings, &credentials, &root, &environment) - .map(Some) - .map_err(str::to_owned) + let mut files = ConfigurationFiles::default(); + for entry in ai::configuration_sources(source, &home, &environment).map_err(str::to_owned)? { + let text = read_optional(&entry.path)?; + match entry.file { + ConfigurationFile::Config => files.config = text, + ConfigurationFile::Auth => files.auth = text, + ConfigurationFile::Settings => files.settings = text, + ConfigurationFile::Credentials => files.credentials = text, + ConfigurationFile::Root => files.root = text, } - _ => Err("AI_COMMIT_INVALID_PROVIDER".into()), } + ai::detect(source, &files, &environment).map_err(str::to_owned) } fn secret_key(id: &str) -> Result { @@ -119,6 +101,33 @@ struct GenerateArgs { files: Vec, } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct PullRequestArgs { + operation_id: String, + provider: Provider, + options: PullRequestOptions, + comparison: PullRequestComparison, +} + +/// Registers a cancellable request; the guard removes it when the request ends. +fn begin_operation( + operation_id: &str, +) -> Result<(Operation, tokio::sync::watch::Receiver), String> { + if operation_id.is_empty() || operation_id.len() > 128 { + return Err("AI_COMMIT_INVALID_OPTIONS".into()); + } + let (sender, receiver) = tokio::sync::watch::channel(false); + let mut operations = cancellations() + .lock() + .map_err(|_| "AI_COMMIT_INTERNAL_ERROR")?; + if operations.len() >= 4 || operations.contains_key(operation_id) { + return Err("AI_COMMIT_BUSY".into()); + } + operations.insert(operation_id.to_owned(), sender); + Ok((Operation(operation_id.to_owned()), receiver)) +} + pub async fn dispatch(app: AppHandle, command: &str, args: Value) -> Result { match command { "ai_commit_detect" => tauri::async_runtime::spawn_blocking(move || { @@ -179,32 +188,48 @@ pub async fn dispatch(app: AppHandle, command: &str, args: Value) -> Result { let args: GenerateArgs = serde_json::from_value(args).map_err(|_| "AI_COMMIT_INVALID_OPTIONS")?; - if args.operation_id.is_empty() || args.operation_id.len() > 128 { - return Err("AI_COMMIT_INVALID_OPTIONS".into()); - } - let (sender, mut receiver) = tokio::sync::watch::channel(false); - { - let mut operations = cancellations() - .lock() - .map_err(|_| "AI_COMMIT_INTERNAL_ERROR")?; - if operations.len() >= 4 || operations.contains_key(&args.operation_id) { - return Err("AI_COMMIT_BUSY".into()); - } - operations.insert(args.operation_id.clone(), sender); - } - let _operation = Operation(args.operation_id.clone()); + let (_operation, mut receiver) = begin_operation(&args.operation_id)?; tokio::select! { _ = receiver.changed() => Err("AI_COMMIT_CANCELLED".into()), result = tokio::time::timeout(Duration::from_secs(45), generate(app, args)) => result.map_err(|_| "AI_COMMIT_TIMEOUT")?, } } + "ai_commit_pull_request" => { + let args: PullRequestArgs = + serde_json::from_value(args).map_err(|_| "AI_COMMIT_INVALID_OPTIONS")?; + let (_operation, mut receiver) = begin_operation(&args.operation_id)?; + tokio::select! { + _ = receiver.changed() => Err("AI_COMMIT_CANCELLED".into()), + result = tokio::time::timeout(Duration::from_secs(45), generate_pull_request(app, args)) => result.map_err(|_| "AI_COMMIT_TIMEOUT")?, + } + } _ => Err("AI_COMMIT_INVALID_OPTIONS".into()), } } async fn generate(app: AppHandle, args: GenerateArgs) -> Result { + let (provider, credential) = resolve_provider(app, args.provider).await?; + let plan = ai::plan_commit(&provider, &args.options, &args.files)?; + let response = send(&provider, credential, plan).await?; + let message = ai::decode_message(&provider.api_protocol, &response, args.options.include_body)?; + Ok(json!({"message":message})) +} + +async fn generate_pull_request(app: AppHandle, args: PullRequestArgs) -> Result { + let (provider, credential) = resolve_provider(app, args.provider).await?; + let plan = ai::plan_pull_request(&provider, &args.options, &args.comparison)?; + let response = send(&provider, credential, plan).await?; + let description = ai::decode_pull_request(&provider.api_protocol, &response)?; + serde_json::to_value(description).map_err(|_| "AI_COMMIT_INTERNAL_ERROR".into()) +} + +/// Refreshes imported profiles from their source and reads the credential natively. +async fn resolve_provider( + app: AppHandle, + provider: Provider, +) -> Result<(Provider, Option), String> { let (provider, credential) = tauri::async_runtime::spawn_blocking(move || { - let mut provider = args.provider; + let mut provider = provider; let credential = if provider.source == "local" { crate::secure_storage::get_secure_secret(app, secret_key(&provider.id)?) .map_err(|_| "AI_COMMIT_KEY_FAILED")? @@ -222,7 +247,15 @@ async fn generate(app: AppHandle, args: GenerateArgs) -> Result { .await .map_err(|_| "AI_COMMIT_INTERNAL_ERROR")??; validate_credential_requirement(&provider, credential.as_deref()).map_err(str::to_owned)?; - let plan = ai::plan_commit(&provider, &args.options, &args.files)?; + Ok((provider, credential)) +} + +/// Sends a Core-planned request and returns the bounded JSON response. +async fn send( + provider: &Provider, + credential: Option, + plan: CommitRequestPlan, +) -> Result { // Never follow a redirect carrying credentials to a different server. let client = reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) @@ -264,10 +297,7 @@ async fn generate(app: AppHandle, args: GenerateArgs) -> Result { } bytes.extend_from_slice(&chunk); } - let response: Value = - serde_json::from_slice(&bytes).map_err(|_| "AI_COMMIT_INVALID_RESPONSE")?; - let message = ai::decode_message(&provider.api_protocol, &response, args.options.include_body)?; - Ok(json!({"message":message})) + serde_json::from_slice(&bytes).map_err(|_| "AI_COMMIT_INVALID_RESPONSE".into()) } #[cfg(test)] diff --git a/windows/tauri/src/i18n/shared.generated.ts b/windows/tauri/src/i18n/shared.generated.ts index df62945b13..e4e6e115ce 100644 --- a/windows/tauri/src/i18n/shared.generated.ts +++ b/windows/tauri/src/i18n/shared.generated.ts @@ -171,6 +171,22 @@ export const sharedCatalogs = { "agent.history.tool": "Tool", "agent.history.unknownProvider": "Unknown provider", "agent.history.you": "You", + "agent.hooks.draft.agents.duplicate": "Each Agent can be selected only once.", + "agent.hooks.draft.agents.required": "Select at least one Agent.", + "agent.hooks.draft.agents.unsupported": "Only Codex and Claude Code support Hooks.", + "agent.hooks.draft.command.contains_nul": "The command cannot contain a NUL character.", + "agent.hooks.draft.command.required": "Enter a command.", + "agent.hooks.draft.command.too_long": "The command can have at most 32768 bytes.", + "agent.hooks.draft.description.too_long": "The description can have at most 200 characters.", + "agent.hooks.draft.id.invalid": "This Hook draft has an invalid identifier. Close the editor and try again.", + "agent.hooks.draft.matcher.incompatible_event": "Tool filters apply only to tool events.", + "agent.hooks.draft.name.duplicate": "A Hook with this name already exists.", + "agent.hooks.draft.name.invalid_characters": "Use only letters, digits, hyphens or underscores in the Hook name.", + "agent.hooks.draft.name.required": "Enter a Hook name.", + "agent.hooks.draft.name.too_long": "Hook names can have at most 80 characters.", + "The Hook draft validation response was not recognised.": "The Hook draft validation response was not recognised.", + "agent.hooks.draft.timeout.not_integer": "Enter the timeout as a whole number of seconds, or leave it empty.", + "agent.hooks.draft.timeout.out_of_range": "The timeout must be from 1 to 86400 seconds.", "agent.notice.dismiss": "Dismiss notification", "agent.permission.deny": "Deny", "agent.permission.dismiss": "Not now", @@ -3045,6 +3061,20 @@ export const sharedCatalogs = { "indexing.workspaceUnavailable": "The project folder is unavailable. Restore it, then retry.", "indexing.writeFailed": "Could not save project indexing settings. Your previous settings remain unchanged.", "inlineEdit.addApiKey": "Add API key", + "inlineEdit.AI_INLINE_EDIT_ENDPOINT_MISSING": "Custom provider base URL is required. Add one in Settings > AI.", + "inlineEdit.AI_INLINE_EDIT_FAILED": "Inline edit failed. Please try again.", + "inlineEdit.AI_INLINE_EDIT_HTTP": "The AI provider returned HTTP {status}. Check your key and model.", + "inlineEdit.AI_INLINE_EDIT_INSECURE_ENDPOINT": "This provider requires HTTPS.", + "inlineEdit.AI_INLINE_EDIT_INVALID_ENDPOINT": "The provider URL is invalid. Use an HTTP(S) URL without credentials, query or fragment.", + "inlineEdit.AI_INLINE_EDIT_INVALID_REQUEST": "The selection or its context is too large for inline edit.", + "inlineEdit.AI_INLINE_EDIT_INVALID_RESPONSE": "The AI provider returned an unexpected response.", + "inlineEdit.AI_INLINE_EDIT_MISSING_KEY": "An API key is required for inline edit. Add one in Settings > AI.", + "inlineEdit.AI_INLINE_EDIT_MODEL_MISSING": "No inline edit model selected.", + "inlineEdit.AI_INLINE_EDIT_MODEL_NOT_FOUND": "The selected model is not offered by this provider. Refresh the model list or choose another model.", + "inlineEdit.AI_INLINE_EDIT_NETWORK_ERROR": "Could not reach the AI provider. Check your network and provider URL.", + "inlineEdit.AI_INLINE_EDIT_OUTPUT_LIMIT": "The model reached its output limit before finishing. Select less text and try again.", + "inlineEdit.AI_INLINE_EDIT_PROVIDER_NOT_FOUND": "The selected AI provider is not available. Choose another provider in Settings > AI.", + "inlineEdit.AI_INLINE_EDIT_UNSUPPORTED_PROVIDER": "This AI provider does not support inline edit.", "inlineEdit.apiKeyRequired": "{provider} API key is required for inline edit.", "inlineEdit.applied": "Inline edit applied.", "inlineEdit.apply": "Apply inline edit", @@ -3549,6 +3579,12 @@ export const sharedCatalogs = { "menu.zoomOut": "Zoom Out", "native.languageServerReturnedAnInvalidTextRange": "Language server returned an invalid text range.", "native.languageServerReturnedOverlappingTextEdits": "Language server returned overlapping text edits.", + "aiCommit.AI_PULL_REQUEST_EMPTY_RESPONSE": "The AI provider returned an empty pull request description.", + "aiCommit.AI_PULL_REQUEST_INVALID_RESPONSE": "The AI provider returned an unexpected pull request description.", + "native.theAgentDidNotConfirmTheSelectedSessionSetting": "The Agent did not confirm the selected session setting.", + "native.theAgentNoLongerSupportsTheSelectedSessionSetting": "The Agent no longer supports the selected session setting.", + "native.theAgentRequestFailed": "The Agent request failed.", + "aiCommit.AI_PULL_REQUEST_EMPTY_COMPARISON": "The selected branches have no textual changes to summarize.", "navigation.definition": "definition", "navigation.enterValidLineNumber": "Enter a valid line or line:column.", "navigation.goToLine": "Go to Line", @@ -5230,6 +5266,22 @@ export const sharedCatalogs = { "agent.history.tool": "工具", "agent.history.unknownProvider": "未知供应商", "agent.history.you": "你", + "agent.hooks.draft.agents.duplicate": "每个 Agent 只能选择一次。", + "agent.hooks.draft.agents.required": "请至少选择一个 Agent。", + "agent.hooks.draft.agents.unsupported": "只有 Codex 和 Claude Code 支持 Hook。", + "agent.hooks.draft.command.contains_nul": "命令不能包含 NUL 字符。", + "agent.hooks.draft.command.required": "请输入命令。", + "agent.hooks.draft.command.too_long": "命令最多 32768 字节。", + "agent.hooks.draft.description.too_long": "描述最多 200 个字符。", + "agent.hooks.draft.id.invalid": "此 Hook 草稿的标识无效,请关闭编辑器后重试。", + "agent.hooks.draft.matcher.incompatible_event": "工具筛选只适用于工具相关的事件。", + "agent.hooks.draft.name.duplicate": "已存在同名的 Hook。", + "agent.hooks.draft.name.invalid_characters": "Hook 名称只能包含字母、数字、连字符或下划线。", + "agent.hooks.draft.name.required": "请输入 Hook 名称。", + "agent.hooks.draft.name.too_long": "Hook 名称最多 80 个字符。", + "The Hook draft validation response was not recognised.": "无法识别 Hook 草稿校验结果。", + "agent.hooks.draft.timeout.not_integer": "超时请填写整数秒,或留空。", + "agent.hooks.draft.timeout.out_of_range": "超时必须在 1 到 86400 秒之间。", "agent.notice.dismiss": "关闭通知", "agent.permission.deny": "拒绝", "agent.permission.dismiss": "暂不处理", @@ -8104,6 +8156,20 @@ export const sharedCatalogs = { "indexing.workspaceUnavailable": "项目目录不可用。请恢复目录后重试。", "indexing.writeFailed": "无法保存项目索引设置,原有设置未改变。", "inlineEdit.addApiKey": "添加 API 密钥", + "inlineEdit.AI_INLINE_EDIT_ENDPOINT_MISSING": "需要自定义服务商的 Base URL,请在“设置 > AI”中添加。", + "inlineEdit.AI_INLINE_EDIT_FAILED": "行内编辑失败,请重试。", + "inlineEdit.AI_INLINE_EDIT_HTTP": "AI 服务商返回 HTTP {status},请检查密钥和模型。", + "inlineEdit.AI_INLINE_EDIT_INSECURE_ENDPOINT": "该服务商要求使用 HTTPS。", + "inlineEdit.AI_INLINE_EDIT_INVALID_ENDPOINT": "服务商 URL 无效,请使用不含凭据、查询参数或片段的 HTTP(S) 地址。", + "inlineEdit.AI_INLINE_EDIT_INVALID_REQUEST": "选区或其上下文过大,无法进行行内编辑。", + "inlineEdit.AI_INLINE_EDIT_INVALID_RESPONSE": "AI 服务商返回了无法识别的响应。", + "inlineEdit.AI_INLINE_EDIT_MISSING_KEY": "行内编辑需要 API 密钥,请在“设置 > AI”中添加。", + "inlineEdit.AI_INLINE_EDIT_MODEL_MISSING": "尚未选择行内编辑模型。", + "inlineEdit.AI_INLINE_EDIT_MODEL_NOT_FOUND": "该服务商未提供所选模型,请刷新模型列表或选择其他模型。", + "inlineEdit.AI_INLINE_EDIT_NETWORK_ERROR": "无法连接 AI 服务商,请检查网络和服务商地址。", + "inlineEdit.AI_INLINE_EDIT_OUTPUT_LIMIT": "模型在完成前达到输出上限,请缩小选区后重试。", + "inlineEdit.AI_INLINE_EDIT_PROVIDER_NOT_FOUND": "所选 AI 服务商不可用,请在“设置 > AI”中选择其他服务商。", + "inlineEdit.AI_INLINE_EDIT_UNSUPPORTED_PROVIDER": "该 AI 服务商不支持行内编辑。", "inlineEdit.apiKeyRequired": "行内编辑需要 {provider} API 密钥。", "inlineEdit.applied": "行内编辑已应用。", "inlineEdit.apply": "应用行内编辑", @@ -8608,6 +8674,12 @@ export const sharedCatalogs = { "menu.zoomOut": "缩小", "native.languageServerReturnedAnInvalidTextRange": "语言服务器返回了无效的文本范围。", "native.languageServerReturnedOverlappingTextEdits": "语言服务器返回了重叠的文本编辑。", + "aiCommit.AI_PULL_REQUEST_EMPTY_RESPONSE": "AI 服务返回了空的拉取请求描述。", + "aiCommit.AI_PULL_REQUEST_INVALID_RESPONSE": "AI 服务返回了无法识别的拉取请求描述。", + "native.theAgentDidNotConfirmTheSelectedSessionSetting": "Agent 未确认所选会话设置。", + "native.theAgentNoLongerSupportsTheSelectedSessionSetting": "Agent 已不再支持所选会话设置。", + "native.theAgentRequestFailed": "Agent 请求失败。", + "aiCommit.AI_PULL_REQUEST_EMPTY_COMPARISON": "所选分支之间没有可供总结的文本更改。", "navigation.definition": "定义", "navigation.enterValidLineNumber": "请输入有效的行号或行号:列号。", "navigation.goToLine": "转到行", From 541753425bd3309de88c0ff663842bf80ee484cb Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Wed, 4 Nov 2026 22:34:13 -0800 Subject: [PATCH 2/8] =?UTF-8?q?feat(core):=20AGT-03=20CLI=20=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E5=8F=91=E7=8E=B0=E4=B8=8E=E8=A7=A3=E6=9E=90=E4=B8=8B?= =?UTF-8?q?=E6=B2=89=E5=88=B0=20Core=EF=BC=88ai.configuration.sources/pars?= =?UTF-8?q?e=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Core 决定读取哪些文件并解析为不含密钥的元数据和凭据定位器,宿主只读文件并在本地解析定位器。macOS 删除 Swift 的 Codex/Claude 配置解析器,改走 Core;Windows 宿主与前端接入同一接口;移除 agent.parseProviderConfiguration,夹具合并为 shared/fixtures/ai/cli-configuration-v1.json。 Co-Authored-By: Claude Opus 5.5 --- .../MacAgentProviderConfigurationParser.swift | 109 +++-- .../MacOS/AI/MacCLIConfigurationReader.swift | 135 ++++++ ...tLaunchConfigurationIntegrationTests.swift | 2 +- .../AgentProviderConfigurationTests.swift | 33 +- rust/lithe-core/src/ai/agent_configuration.rs | 177 +++++-- rust/lithe-core/src/ai/configuration.rs | 447 +++++++++++++++--- rust/lithe-core/src/ai/tests.rs | 242 +++++++--- shared/fixtures/ai/cli-configuration-v1.json | 278 +++++++++++ .../agent-provider-configuration.json | 7 +- .../services/agent-provider-import.test.ts | 9 +- .../agent/services/agent-provider-import.ts | 15 +- windows/tauri/src/platform/tauri-core.ts | 2 +- 12 files changed, 1233 insertions(+), 223 deletions(-) create mode 100644 macos/Sources/Lithe/Platform/MacOS/AI/MacCLIConfigurationReader.swift create mode 100644 shared/fixtures/ai/cli-configuration-v1.json diff --git a/macos/Sources/Lithe/Platform/MacOS/AI/MacAgentProviderConfigurationParser.swift b/macos/Sources/Lithe/Platform/MacOS/AI/MacAgentProviderConfigurationParser.swift index db591697e6..1d92807119 100644 --- a/macos/Sources/Lithe/Platform/MacOS/AI/MacAgentProviderConfigurationParser.swift +++ b/macos/Sources/Lithe/Platform/MacOS/AI/MacAgentProviderConfigurationParser.swift @@ -1,62 +1,103 @@ import Foundation import LitheCoreContracts -/// Shared TOML/JSON metadata parsing plus native, ephemeral credential extraction. +/// Shared Rust Core parsing of pasted CLI configuration plus native, ephemeral credential extraction. +/// +/// Core returns metadata and a credential locator only; this adapter resolves the +/// locator against the text the user pasted, so the key never crosses the Core boundary. struct MacAgentProviderConfigurationParser: AgentProviderConfigurationParsing { let core: RustCoreBridge + private struct Files: Encodable { + var config: String? + var auth: String? + var settings: String? + } private struct Payload: Encodable { let source: String - let configuration: String + let files: Files let allowIncomplete: Bool } - private struct Metadata: Decodable { - let name: String - let endpoint: String - let model: String - let apiProtocol: CommitMessageAPIProtocol - let authentication: AIProviderAuthentication + private struct Locator: Decodable { + let kind: String + let file: String? + let path: [String]? + } + private struct Response: Decodable { + struct Provider: Decodable { + let name: String + let endpoint: String + let model: String + let apiProtocol: CommitMessageAPIProtocol + let authentication: AIProviderAuthentication + } + let provider: Provider? + let hasCredential: Bool + let credential: Locator? + let unsupportedAuthentication: Bool } func parse(source: AIConfigurationSourceKind, configuration: String, authentication: String, allowIncomplete: Bool) throws -> AIConfigurationSnapshot { guard configuration.utf8.count <= 64 * 1024, authentication.utf8.count <= 64 * 1024 else { throw AgentProviderConfigurationError.invalidConfiguration } - let metadata: Metadata + let files: Files + switch source { + case .codex: files = Files(config: configuration, auth: authentication) + case .claude: files = Files(settings: configuration) + } + let response: Response? do { - metadata = try core.executeResult(command: "agent.parseProviderConfiguration", payload: Payload( - source: source.rawValue, configuration: configuration, allowIncomplete: allowIncomplete + response = try core.executeResult(command: "ai.configuration.parse", payload: Payload( + source: source.rawValue, files: files, allowIncomplete: allowIncomplete )).get() + } catch let error as RustCoreBridge.CoreCallError { + // Fixed codes only: parser diagnostics could quote a pasted credential. + if error.message == "AI_CONFIGURATION_SMART_QUOTES" { throw AgentProviderConfigurationError.invalidConfigurationQuotes } + if error.message == "AI_CONFIGURATION_INVALID_AUTHENTICATION" { throw AgentProviderConfigurationError.invalidAuthentication } + throw AgentProviderConfigurationError.invalidConfiguration } catch { - // Never present parser details, which could quote a pasted credential. - if source == .codex, configuration.contains("“") || configuration.contains("”") { - throw AgentProviderConfigurationError.invalidConfigurationQuotes - } throw AgentProviderConfigurationError.invalidConfiguration } - let key: String? + guard let response else { + // Strict Claude parsing reports "not configured" as no data; the editor asks for a key. + throw source == .claude && !allowIncomplete + ? AgentProviderConfigurationError.missingAPIKey + : AgentProviderConfigurationError.invalidConfiguration + } + guard let provider = response.provider else { + throw AgentProviderConfigurationError.invalidConfiguration + } + let key = Self.resolve(response.credential, files: files) switch source { case .codex: - let text = allowIncomplete && authentication.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? "{}" : authentication - guard let object = try? JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any] else { - throw AgentProviderConfigurationError.invalidAuthentication - } - let value = object["OPENAI_API_KEY"] ?? object["api_key"] - guard value is String || (allowIncomplete && value == nil) else { - throw AgentProviderConfigurationError.invalidAuthentication - } - key = value as? String ?? "" + // A saved Codex provider must carry the pasted `auth.json` key. + if !allowIncomplete, key == nil { throw AgentProviderConfigurationError.invalidAuthentication } case .claude: - let snapshot = MacClaudeConfigurationParser.parse(settingsData: Data(configuration.utf8), - credentialsData: nil, rootConfigData: nil, environment: [:]) - if !allowIncomplete { - guard snapshot?.hasAPIKey == true else { throw AgentProviderConfigurationError.missingAPIKey } + if !allowIncomplete, key == nil { throw AgentProviderConfigurationError.missingAPIKey } + guard provider.authentication == .apiKey, !response.unsupportedAuthentication else { + throw AgentProviderConfigurationError.unsupportedProtocol } - guard metadata.authentication == .apiKey else { throw AgentProviderConfigurationError.unsupportedProtocol } - key = snapshot?.apiKey ?? "" } - return AIConfigurationSnapshot(source: source, providerName: metadata.name, endpoint: metadata.endpoint, - model: metadata.model, apiProtocol: metadata.apiProtocol, authentication: metadata.authentication, - reasoningEffort: nil, requiresAPIKey: true, apiKey: key) + return AIConfigurationSnapshot(source: source, providerName: provider.name, endpoint: provider.endpoint, + model: provider.model, apiProtocol: provider.apiProtocol, authentication: provider.authentication, + reasoningEffort: nil, requiresAPIKey: true, apiKey: key ?? "") + } + + /// Reads the value a file locator names from the pasted JSON; draft parsing never consults the environment. + private static func resolve(_ locator: Locator?, files: Files) -> String? { + guard let locator, locator.kind == "file", let path = locator.path else { return nil } + let text: String? + switch locator.file { + case "auth": text = files.auth + case "settings": text = files.settings + default: text = nil + } + guard let text, var value = try? JSONSerialization.jsonObject(with: Data(text.utf8)) else { return nil } + for key in path { + guard let object = value as? [String: Any], let next = object[key] else { return nil } + value = next + } + return value as? String } } diff --git a/macos/Sources/Lithe/Platform/MacOS/AI/MacCLIConfigurationReader.swift b/macos/Sources/Lithe/Platform/MacOS/AI/MacCLIConfigurationReader.swift new file mode 100644 index 0000000000..7357380a6a --- /dev/null +++ b/macos/Sources/Lithe/Platform/MacOS/AI/MacCLIConfigurationReader.swift @@ -0,0 +1,135 @@ +import Foundation +import LitheCoreContracts + +/// Native file and environment access for CLI configuration discovery. +/// +/// Rust Core decides which files a source reads and how their text becomes a +/// provider (`ai.configuration.sources` / `ai.configuration.parse`). This reader +/// only touches the file system and resolves the credential locator Core returns, +/// so the secret never appears in a Core response. +struct MacCLIConfigurationReader: Sendable { + let core: RustCoreBridge + var fileManager: FileManager + var environment: [String: String] + + init(core: RustCoreBridge, fileManager: FileManager = .default, + environment: [String: String] = ProcessInfo.processInfo.environment) { + self.core = core + self.fileManager = fileManager + self.environment = environment + } + + struct Result { + let model: String + let snapshot: AIConfigurationSnapshot? + } + + private struct SourcesPayload: Encodable { + let source: String + let home: String + let environment: [String: String] + } + private struct SourceFile: Decodable { + let file: String + let path: String + } + private struct SourcesResponse: Decodable { let files: [SourceFile] } + private struct ParsePayload: Encodable { + let source: String + let files: [String: String] + let environment: [String: String] + } + private struct Locator: Decodable { + let kind: String + let name: String? + let file: String? + let path: [String]? + } + private struct Parsed: Decodable { + struct Provider: Decodable { + let name: String + let endpoint: String + let model: String + let apiProtocol: CommitMessageAPIProtocol + let authentication: AIProviderAuthentication + let requiresApiKey: Bool + } + let model: String + let provider: Provider? + let reasoningEffort: String? + let credential: Locator? + } + + /// `nil` when the CLI is not configured, the files are unreadable, or Core rejects them. + func read(_ source: AIConfigurationSourceKind) -> Result? { + // Only directory overrides influence file discovery; the full snapshot is passed to parsing. + let overrides = environment.filter { ["CODEX_HOME", "CLAUDE_CONFIG_DIR"].contains($0.key) } + guard let listing = try? core.executeResult(command: "ai.configuration.sources", payload: SourcesPayload( + source: source.rawValue, home: fileManager.homeDirectoryForCurrentUser.path, environment: overrides + )).get() as SourcesResponse else { return nil } + var files: [String: String] = [:] + for entry in listing.files { + guard let data = fileManager.contents(atPath: entry.path), + let text = String(data: data, encoding: .utf8) else { continue } + files[entry.file] = text + } + let bounded = environment.filter { $0.key.utf8.count + $0.value.utf8.count <= 32 * 1024 } + guard let parsed = try? core.executeResult(command: "ai.configuration.parse", payload: ParsePayload( + source: source.rawValue, files: files, environment: Dictionary(uniqueKeysWithValues: bounded.prefix(4096).map { ($0.key, $0.value) }) + )).get() as Parsed? else { return nil } + guard let provider = parsed.provider else { + return Result(model: parsed.model, snapshot: nil) + } + return Result(model: parsed.model, snapshot: AIConfigurationSnapshot( + source: source, providerName: provider.name, endpoint: provider.endpoint, model: provider.model, + apiProtocol: provider.apiProtocol, authentication: provider.authentication, + reasoningEffort: parsed.reasoningEffort.flatMap(CommitMessageReasoningEffort.init(rawValue:)), + requiresAPIKey: provider.requiresApiKey, apiKey: resolve(parsed.credential, files: files))) + } + + /// Reads the value a locator names. A credential inside the TOML `config` file is not + /// resolved: Lithe never parsed TOML credentials natively and the key is treated as absent. + private func resolve(_ locator: Locator?, files: [String: String]) -> String? { + guard let locator else { return nil } + if locator.kind == "environment" { return locator.name.flatMap { environment[$0] } } + guard locator.kind == "file", let file = locator.file, file != "config", let path = locator.path, + let text = files[file], var value = try? JSONSerialization.jsonObject(with: Data(text.utf8)) else { return nil } + for key in path { + guard let object = value as? [String: Any], let next = object[key] else { return nil } + value = next + } + return value as? String + } +} + +/// Codex CLI configuration (`config.toml` plus `auth.json`) read through Rust Core. +final class MacCodexConfigurationSource: CodexConfigurationSource, @unchecked Sendable { + private let reader: MacCLIConfigurationReader + + init(core: RustCoreBridge, fileManager: FileManager = .default, + environment: [String: String] = ProcessInfo.processInfo.environment) { + reader = MacCLIConfigurationReader(core: core, fileManager: fileManager, environment: environment) + } + + func loadModel() -> AIConfigurationModel? { + reader.read(.codex).map { AIConfigurationModel(source: .codex, model: $0.model) } + } + + func load() -> CodexConfigurationSnapshot? { reader.read(.codex)?.snapshot } +} + +/// Claude CLI configuration (settings, credentials and root JSON) read through Rust Core. +final class MacClaudeConfigurationSource: ClaudeConfigurationSource, @unchecked Sendable { + private let reader: MacCLIConfigurationReader + + init(core: RustCoreBridge, fileManager: FileManager = .default, + environment: [String: String] = ProcessInfo.processInfo.environment) { + reader = MacCLIConfigurationReader(core: core, fileManager: fileManager, environment: environment) + } + + func loadModel() -> AIConfigurationModel? { + reader.read(.claude).map { AIConfigurationModel(source: .claude, model: $0.model) } + } + + func load() -> AIConfigurationSnapshot? { reader.read(.claude)?.snapshot } +} diff --git a/macos/Tests/LitheTests/AgentLaunchConfigurationIntegrationTests.swift b/macos/Tests/LitheTests/AgentLaunchConfigurationIntegrationTests.swift index 8df9e953d1..e551b87b71 100644 --- a/macos/Tests/LitheTests/AgentLaunchConfigurationIntegrationTests.swift +++ b/macos/Tests/LitheTests/AgentLaunchConfigurationIntegrationTests.swift @@ -43,7 +43,7 @@ struct AgentLaunchConfigurationIntegrationTests { catch { Issue.record("Temporary Agent test files could not be removed") } } } - let source = MacClaudeConfigurationSource(fileManager: RouteIntegrationFileManager(home: home)) + let source = MacClaudeConfigurationSource(core: RustCoreBridge(), fileManager: RouteIntegrationFileManager(home: home), environment: [:]) let store = RouteIntegrationSettingsStore() let settings = AppSettings(store: store) let credentials = MacAIProviderCredentialResolver(localStore: secureStore, configurationSources: [source]) diff --git a/macos/Tests/LitheTests/AgentProviderConfigurationTests.swift b/macos/Tests/LitheTests/AgentProviderConfigurationTests.swift index f5194b3b79..37cbee118c 100644 --- a/macos/Tests/LitheTests/AgentProviderConfigurationTests.swift +++ b/macos/Tests/LitheTests/AgentProviderConfigurationTests.swift @@ -140,11 +140,14 @@ struct AgentProviderConfigurationTests { @Test func nativeParserUsesSharedFixtureAndRoundTripsEditorTemplates() throws { - let fixtureURL = URL(fileURLWithPath: #filePath).deletingLastPathComponent() - .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() - .appendingPathComponent("shared/fixtures/agent/provider-configuration-v1.json") - let fixture = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: fixtureURL)) as? [String: Any]) - let cases = try #require(fixture["cases"] as? [[String: Any]]) + // Parsing rules are covered by shared/fixtures/ai/cli-configuration-v1.json in Core; + // these editor templates only prove the adapter round-trips through Core. + let cases: [[String: Any]] = [ + ["source": "codex", "configuration": "model_provider = 'gateway'\nmodel = 'fixture-model'\n[model_providers.gateway]\nbase_url = 'https://example.test/v1'\nwire_api = 'responses'\nrequires_openai_auth = true\n", + "expected": ["endpoint": "https://example.test/v1", "model": "fixture-model", "apiProtocol": "responses"]], + ["source": "claude", "configuration": #"{"env":{"ANTHROPIC_BASE_URL":"https://example.test/v1","ANTHROPIC_MODEL":"fixture-model","ANTHROPIC_API_KEY":"fixture-secret"}}"#, + "expected": ["endpoint": "https://example.test/v1", "model": "fixture-model", "apiProtocol": "anthropicMessages"]], + ] let parser = MacAgentProviderConfigurationParser(core: RustCoreBridge()) #expect(throws: AgentProviderConfigurationError.invalidConfigurationQuotes) { try parser.parse(source: .codex, configuration: "model = “fixture-model”", @@ -294,15 +297,23 @@ struct AgentProviderConfigurationTests { let fixtureURL = URL(fileURLWithPath: #filePath).deletingLastPathComponent() .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() - .appendingPathComponent("shared/fixtures/agent/provider-configuration-v1.json") + .appendingPathComponent("shared/fixtures/ai/cli-configuration-v1.json") let fixture = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: fixtureURL)) as? [String: Any]) let cases = try #require(fixture["draftCases"] as? [[String: Any]]) for value in cases where value["source"] as? String == source.rawValue { - let text = try #require(value["configuration"] as? String) - let expected = try #require(value["expected"] as? [String: String]) - let snapshot = try parser.parse(source: source, configuration: text, authentication: "{}", allowIncomplete: true) - #expect(snapshot.endpoint == expected["endpoint"] && snapshot.model == expected["model"]) - #expect(snapshot.apiKey == (value["expectedAPIKey"] as? String ?? "")) + let files = try #require(value["files"] as? [String: String]) + let text = files[source == .codex ? "config" : "settings"] ?? "" + let expected = try #require(value["expected"] as? [String: Any]) + if expected["authentication"] as? String == "bearer" && source == .claude + || (expected["unsupportedAuthentication"] as? Bool) == true { + #expect(throws: AgentProviderConfigurationError.unsupportedProtocol) { + try parser.parse(source: source, configuration: text, authentication: "{}", allowIncomplete: true) + } + continue + } + let snapshot = try parser.parse(source: source, configuration: text, authentication: files["auth"] ?? "{}", allowIncomplete: true) + #expect(snapshot.endpoint == expected["endpoint"] as? String && snapshot.model == expected["model"] as? String) + #expect((snapshot.apiKey ?? "").isEmpty == (value["expectedCredential"] == nil || value["expectedCredential"] is NSNull)) } if source == .codex { #expect(throws: AgentProviderConfigurationError.invalidAuthentication) { diff --git a/rust/lithe-core/src/ai/agent_configuration.rs b/rust/lithe-core/src/ai/agent_configuration.rs index 2316a43ad7..d86429866c 100644 --- a/rust/lithe-core/src/ai/agent_configuration.rs +++ b/rust/lithe-core/src/ai/agent_configuration.rs @@ -1,49 +1,162 @@ -//! Bounded provider metadata parsing for Agent settings; hosts retain credentials and persistence. +//! Credential-free JSON entry points for CLI configuration discovery and parsing. +//! +//! `ai.configuration.sources` names the files a platform reads for a source, and +//! `ai.configuration.parse` applies the shared rules to their text. Responses +//! carry metadata and a credential locator only; hosts resolve the locator +//! natively, so secrets never appear in a response, error, or diagnostic. +use super::configuration::{ + self, codex_model, configuration_sources, ConfigurationFiles, DetectedConfiguration, + INVALID_AUTHENTICATION, INVALID_CONFIG, +}; use crate::protocol::{CoreError, ErrorCode}; use serde::Deserialize; -use serde_json::Value; +use serde_json::{json, Value}; use std::collections::BTreeMap; +use std::path::PathBuf; -/// Parses pasted configuration without consulting files or the host environment. -/// Responses and failures never include authentication material or raw input. -pub fn parse_provider_configuration(payload: Value) -> Result { +/// Largest accepted file text; matches the Windows host's native read bound. +const MAXIMUM_FILE_BYTES: usize = 1024 * 1024; +/// Bounds the environment snapshot a platform may pass. +const MAXIMUM_ENVIRONMENT_ENTRIES: usize = 4096; +const MAXIMUM_ENVIRONMENT_VALUE_BYTES: usize = 32 * 1024; +/// Oversized input; stable so platforms can explain the limit. +const TOO_LARGE: &str = "AI_CONFIGURATION_TOO_LARGE"; + +/// Fixed messages only: parser diagnostics may quote a pasted credential. +fn invalid(code: &'static str) -> CoreError { + CoreError::new(ErrorCode::InvalidRequest, code) +} + +fn bounded_environment(environment: &BTreeMap) -> Result<(), CoreError> { + if environment.len() > MAXIMUM_ENVIRONMENT_ENTRIES + || environment + .iter() + .any(|(name, value)| name.len() + value.len() > MAXIMUM_ENVIRONMENT_VALUE_BYTES) + { + return Err(invalid(TOO_LARGE)); + } + Ok(()) +} + +/// Implements `ai.configuration.sources`: the native files of one source. +pub fn configuration_sources_command(payload: Value) -> Result { #[derive(Deserialize)] - #[serde(rename_all = "camelCase")] + #[serde(rename_all = "camelCase", deny_unknown_fields)] struct Request { - /// CLI configuration format, either `codex` or `claude`. + /// `codex` or `claude`. source: String, - /// UTF-8 TOML or JSON, limited to 64 KiB before parsing. - configuration: String, + /// Absolute home directory of the current user. + home: PathBuf, + /// Directory overrides such as `CODEX_HOME`; other variables are ignored. + #[serde(default)] + environment: BTreeMap, + } + let request: Request = serde_json::from_value(payload).map_err(|_| invalid(INVALID_CONFIG))?; + bounded_environment(&request.environment)?; + if !request.home.is_absolute() { + return Err(invalid(INVALID_CONFIG)); + } + let files = configuration_sources(&request.source, &request.home, &request.environment) + .map_err(invalid)?; + Ok(json!({ "files": files })) +} + +/// Implements `ai.configuration.parse` without consulting files or the host environment. +/// +/// Strict mode returns `null` when nothing is configured, and `provider: null` +/// with `issue` when the configuration parses but is not a usable provider. +/// Draft mode (`allowIncomplete`) parses editor text only: it ignores the +/// environment and keeps missing endpoint and model fields empty. +pub fn parse_configuration_command(payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct Request { + /// `codex` (TOML plus `auth.json`) or `claude` (JSON files). + source: String, + /// File text keyed like the `ai.configuration.sources` result. + #[serde(default)] + files: ConfigurationFiles, + /// Process environment snapshot for strict parsing. + #[serde(default)] + environment: BTreeMap, /// Editor-only parsing preserves empty fields instead of applying CLI defaults. #[serde(default)] allow_incomplete: bool, } - let invalid = || { - CoreError::new( - ErrorCode::InvalidRequest, - "Invalid Agent provider configuration", - ) - }; - let request: Request = serde_json::from_value(payload).map_err(|_| invalid())?; - if request.configuration.len() > 64 * 1024 - || (!request.allow_incomplete && request.configuration.trim().is_empty()) + let request: Request = serde_json::from_value(payload).map_err(|_| invalid(INVALID_CONFIG))?; + let files = &request.files; + if [ + &files.config, + &files.auth, + &files.settings, + &files.credentials, + &files.root, + ] + .iter() + .any(|text| text.len() > MAXIMUM_FILE_BYTES) { - return Err(invalid()); + return Err(invalid(TOO_LARGE)); } - let environment = BTreeMap::new(); - let detected = match request.source.as_str() { - "codex" if request.allow_incomplete => { - super::configuration::parse_codex_draft(&request.configuration) + bounded_environment(&request.environment)?; + let source = request.source.as_str(); + if request.allow_incomplete { + let detected = match source { + "codex" => configuration::parse_codex_draft(&files.config, &files.auth), + "claude" => configuration::parse_claude_draft(&files.settings), + _ => Err(INVALID_CONFIG), } - "claude" if request.allow_incomplete => { - super::configuration::parse_claude_draft(&request.configuration) - } - "codex" => super::parse_codex(&request.configuration, "{}", &environment), - "claude" => super::parse_claude(&request.configuration, "", "", &environment), - _ => return Err(invalid()), + .map_err(invalid)?; + let model = detected.provider.model.clone(); + return Ok(response(model, Ok(detected))); + } + if !matches!(source, "codex" | "claude") { + return Err(invalid(INVALID_CONFIG)); + } + if !configuration::is_configured(source, files, &request.environment) { + return Ok(Value::Null); + } + let environment = &request.environment; + if source == "claude" { + // Claude has no incomplete state: every parse failure is malformed input. + let detected = configuration::parse_claude( + &files.settings, + &files.credentials, + &files.root, + environment, + ) + .map_err(invalid)?; + return Ok(response(detected.provider.model.clone(), Ok(detected))); + } + // Malformed TOML or auth JSON is an error; an incomplete provider still reports the model. + let model = codex_model(&files.config).map_err(invalid)?; + match configuration::parse_codex(&files.config, &files.auth, environment) { + Ok(detected) => Ok(response(model, Ok(detected))), + Err(INVALID_AUTHENTICATION) => Err(invalid(INVALID_AUTHENTICATION)), + Err(code) => Ok(response(model, Err(code))), + } +} + +/// Serializes metadata only; the credential value is `#[serde(skip)]`. +fn response(model: String, detected: Result) -> Value { + match detected { + Ok(detected) => json!({ + "model": model, + "provider": detected.provider, + "issue": null, + "reasoningEffort": detected.reasoning_effort, + "hasCredential": detected.has_credential, + "credential": detected.credential_locator, + "unsupportedAuthentication": detected.unsupported_authentication, + }), + Err(code) => json!({ + "model": model, + "provider": null, + "issue": code, + "reasoningEffort": null, + "hasCredential": false, + "credential": null, + "unsupportedAuthentication": false, + }), } - .map_err(|_| invalid())?; - // Serialize metadata only; even the credential-presence flag stays host-owned. - serde_json::to_value(detected.provider).map_err(|_| invalid()) } diff --git a/rust/lithe-core/src/ai/configuration.rs b/rust/lithe-core/src/ai/configuration.rs index 382d20f5e4..1e86f7d10b 100644 --- a/rust/lithe-core/src/ai/configuration.rs +++ b/rust/lithe-core/src/ai/configuration.rs @@ -1,23 +1,197 @@ -//! Parses externally supplied configuration text without reading files or process environment. +//! Parses externally supplied Codex and Claude configuration without reading files or process environment. +//! +//! This module is the single owner of CLI configuration rules shared by commit +//! generation and Agent providers: which files belong to a source, profile and +//! provider selection, defaults, model aliases, and the precedence among +//! credential sources. Platforms read the named files natively and pass their +//! text in. Results that cross a JSON boundary never contain a secret: they +//! name where the effective credential lives through [`CredentialLocator`], and +//! only an in-process host reads [`DetectedConfiguration::credential`]. use super::{ChatTokenLimitField, Provider}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// Malformed or unusable configuration; shared with the commit error catalog. +pub(super) const INVALID_CONFIG: &str = "AI_COMMIT_INVALID_CONFIG"; +/// A Codex `auth.json` that is not an object or whose API key is not a string. +pub(super) const INVALID_AUTHENTICATION: &str = "AI_CONFIGURATION_INVALID_AUTHENTICATION"; +/// Codex TOML that fails to parse and contains typographic quotes, usually pasted from a document. +pub(super) const SMART_QUOTES: &str = "AI_CONFIGURATION_SMART_QUOTES"; + +/// One native file a configuration source may read. Serialized names are the +/// stable keys of [`ConfigurationFiles`] and of file credential locators. +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "camelCase")] +pub enum ConfigurationFile { + /// Codex `config.toml`. + Config, + /// Codex `auth.json`. + Auth, + /// Claude `settings.json`. + Settings, + /// Claude `.credentials.json`. + Credentials, + /// Claude `~/.claude.json`. + Root, +} + +/// Text of the files of one source, as read by the platform. A missing or +/// unreadable-but-absent file is an empty string; callers report read failures +/// themselves instead of passing partial text. +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ConfigurationFiles { + /// Codex TOML configuration. + #[serde(default)] + pub config: String, + /// Codex API-key authentication JSON. + #[serde(default)] + pub auth: String, + /// Claude settings JSON. + #[serde(default)] + pub settings: String, + /// Claude credentials JSON. + #[serde(default)] + pub credentials: String, + /// Claude root configuration JSON. + #[serde(default)] + pub root: String, +} + +/// Where the effective credential lives. Hosts resolve it natively against the +/// same file text or environment they passed in, so secrets never cross IPC. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum CredentialLocator { + /// A process environment variable. + Environment { + /// Variable name, for example `OPENAI_API_KEY`. + name: String, + }, + /// A string value inside one of the source files. + File { + /// File the value lives in. + file: ConfigurationFile, + /// Object keys from the document root to the string value. + path: Vec, + }, +} + +/// One file the platform should read for a source, in deterministic order. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ConfigurationSourceFile { + /// Key under which the text is passed back in [`ConfigurationFiles`]. + pub file: ConfigurationFile, + /// Absolute native path built from the platform's home directory. + pub path: PathBuf, +} /// Discovered profile plus an ephemeral credential that is never serialized to a UI. -#[derive(Serialize)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct DetectedConfiguration { /// Editable metadata is locked by the UI when source is not local. pub provider: Provider, /// Indicates whether the source contains a supported API credential. pub has_credential: bool, + /// Location of the effective credential, present exactly when `has_credential` is true. + pub credential_locator: Option, + /// CLI reasoning effort selection (`model_reasoning_effort`), when configured. + pub reasoning_effort: Option, + /// The CLI authenticates through a route Lithe cannot reproduce (cloud + /// provider or key helper), so no static credential is authoritative. + pub unsupported_authentication: bool, /// Host-only credential, not persisted or returned across IPC. #[serde(skip)] pub credential: Option, } +/// Files a source reads. `CODEX_HOME` and `CLAUDE_CONFIG_DIR` replace the +/// default directories when nonblank; `~/.claude.json` always stays in home. +pub fn configuration_sources( + source: &str, + home: &Path, + environment: &BTreeMap, +) -> Result, &'static str> { + let directory = |variable: &str, default: &str| { + environment + .get(variable) + .map(|value| value.trim()) + .filter(|value| !value.is_empty()) + .map(PathBuf::from) + .unwrap_or_else(|| home.join(default)) + }; + let file = |file, path: PathBuf| ConfigurationSourceFile { file, path }; + match source { + "codex" => { + let directory = directory("CODEX_HOME", ".codex"); + Ok(vec![ + file(ConfigurationFile::Config, directory.join("config.toml")), + file(ConfigurationFile::Auth, directory.join("auth.json")), + ]) + } + "claude" => { + let directory = directory("CLAUDE_CONFIG_DIR", ".claude"); + Ok(vec![ + file(ConfigurationFile::Settings, directory.join("settings.json")), + file( + ConfigurationFile::Credentials, + directory.join(".credentials.json"), + ), + file(ConfigurationFile::Root, home.join(".claude.json")), + ]) + } + _ => Err(INVALID_CONFIG), + } +} + +/// Whether the files and environment describe a configuration at all. Codex +/// needs its TOML; Claude also counts any `ANTHROPIC_*` environment override. +pub fn is_configured( + source: &str, + files: &ConfigurationFiles, + environment: &BTreeMap, +) -> bool { + match source { + "codex" => !files.config.trim().is_empty(), + "claude" => { + [&files.settings, &files.credentials, &files.root] + .iter() + .any(|text| !text.trim().is_empty()) + || environment.keys().any(|key| key.starts_with("ANTHROPIC_")) + } + _ => false, + } +} + +/// Detects one installed CLI source. `Ok(None)` means nothing is configured. +pub fn detect( + source: &str, + files: &ConfigurationFiles, + environment: &BTreeMap, +) -> Result, &'static str> { + if !matches!(source, "codex" | "claude") { + return Err(INVALID_CONFIG); + } + if !is_configured(source, files, environment) { + return Ok(None); + } + match source { + "codex" => parse_codex(&files.config, &files.auth, environment), + _ => parse_claude( + &files.settings, + &files.credentials, + &files.root, + environment, + ), + } + .map(Some) +} + /// Parses Codex TOML plus API-key auth. OAuth credentials are not interpreted as API keys. pub fn parse_codex( config: &str, @@ -28,8 +202,73 @@ pub fn parse_codex( } /// Reads editable fields without requiring a complete provider or adding CLI defaults. -pub(super) fn parse_codex_draft(config: &str) -> Result { - parse_codex_configuration(config, "{}", &BTreeMap::new(), true) +pub(super) fn parse_codex_draft( + config: &str, + auth: &str, +) -> Result { + parse_codex_configuration(config, auth, &BTreeMap::new(), true) +} + +/// Parsed Codex TOML with the active profile applied to top-level selections. +struct CodexDocument { + value: toml::Value, + profile: Option, +} + +impl CodexDocument { + fn parse(config: &str) -> Result { + let value: toml::Value = toml::from_str(config).map_err(|_| { + // Typographic quotes are the common cause when TOML is pasted from a + // document; a dedicated code lets the UI say so without quoting input. + if config.contains('\u{201C}') || config.contains('\u{201D}') { + SMART_QUOTES + } else { + INVALID_CONFIG + } + })?; + let profile = value + .get("profile") + .and_then(toml::Value::as_str) + .filter(|name| value.get("profiles").and_then(|p| p.get(*name)).is_some()) + .map(str::to_owned); + Ok(Self { value, profile }) + } + + /// A profile value wins over the top-level value of the same key. + fn setting(&self, key: &str) -> Option<&str> { + self.profile + .as_deref() + .and_then(|name| self.value.get("profiles")?.get(name)?.get(key)) + .or_else(|| self.value.get(key)) + .and_then(toml::Value::as_str) + } +} + +/// The CLI's model selection even when no usable provider is configured. +pub(super) fn codex_model(config: &str) -> Result { + Ok(CodexDocument::parse(config)? + .setting("model") + .map(str::trim) + .unwrap_or_default() + .to_owned()) +} + +/// Parses an `auth.json` document; blank text is an empty object. +fn codex_auth(auth: &str) -> Result { + if auth.trim().is_empty() { + return Ok(Value::Object(Default::default())); + } + let value: Value = serde_json::from_str(auth).map_err(|_| INVALID_AUTHENTICATION)?; + if !value.is_object() { + return Err(INVALID_AUTHENTICATION); + } + // ChatGPT login stores `null`; any other non-string key is malformed. + for key in ["OPENAI_API_KEY", "api_key"] { + if !matches!(value.get(key), None | Some(Value::Null | Value::String(_))) { + return Err(INVALID_AUTHENTICATION); + } + } + Ok(value) } fn parse_codex_configuration( @@ -38,19 +277,11 @@ fn parse_codex_configuration( environment: &BTreeMap, allow_incomplete: bool, ) -> Result { - let value: toml::Value = toml::from_str(config).map_err(|_| "AI_COMMIT_INVALID_CONFIG")?; - let profile = value - .get("profile") - .and_then(toml::Value::as_str) - .and_then(|name| value.get("profiles")?.get(name)); - let setting = |key: &str| { - profile - .and_then(|v| v.get(key)) - .or_else(|| value.get(key)) - .and_then(toml::Value::as_str) - }; - let provider_name = setting("model_provider").unwrap_or("openai"); - let provider = value + let document = CodexDocument::parse(config)?; + let auth = codex_auth(auth)?; + let provider_name = document.setting("model_provider").unwrap_or("openai"); + let provider = document + .value .get("model_providers") .and_then(|v| v.get(provider_name)); let option = |key: &str| { @@ -63,40 +294,59 @@ fn parse_codex_configuration( (!allow_incomplete && provider_name == "openai").then_some("https://api.openai.com/v1") }) .or_else(|| allow_incomplete.then_some("")) - .ok_or("AI_COMMIT_INVALID_CONFIG")?; - let model = setting("model") + .ok_or(INVALID_CONFIG)?; + let model = document + .setting("model") .filter(|s| !s.is_empty()) .or_else(|| allow_incomplete.then_some("")) - .ok_or("AI_COMMIT_INVALID_CONFIG")?; - let auth: Value = serde_json::from_str(auth).unwrap_or(Value::Null); + .ok_or(INVALID_CONFIG)?; let uses_openai_auth = provider .and_then(|v| v.get("requires_openai_auth")) .and_then(toml::Value::as_bool) .unwrap_or(provider_name == "openai"); let env_key = option("env_key").map(str::trim); if env_key.is_some_and(str::is_empty) { - return Err("AI_COMMIT_INVALID_CONFIG"); + return Err(INVALID_CONFIG); } let bearer_token = option("experimental_bearer_token"); + let auth_field = |key: &str| { + candidate( + auth.get(key).and_then(Value::as_str), + CredentialLocator::File { + file: ConfigurationFile::Auth, + path: vec![key.into()], + }, + ) + }; // An explicit provider credential source must never fall back to another account. let credential = if let Some(key) = env_key { - first_nonempty([environment.get(key).map(String::as_str)]) + first_candidate([environment_candidate(environment, key)]) } else if bearer_token.is_some() { - first_nonempty([bearer_token]) - } else if uses_openai_auth { - first_nonempty([ - auth["OPENAI_API_KEY"].as_str(), - auth["api_key"].as_str(), - environment.get("OPENAI_API_KEY").map(String::as_str), + first_candidate([candidate( + bearer_token, + CredentialLocator::File { + file: ConfigurationFile::Config, + path: vec![ + "model_providers".into(), + provider_name.into(), + "experimental_bearer_token".into(), + ], + }, + )]) + } else if uses_openai_auth || allow_incomplete { + // An editor draft supplies its key through the pasted `auth.json` text. + first_candidate([ + auth_field("OPENAI_API_KEY"), + auth_field("api_key"), + environment_candidate(environment, "OPENAI_API_KEY"), ]) } else { None - } - .map(str::to_owned); + }; let protocol = match option("wire_api").unwrap_or("responses") { "responses" => "responses", "chat" | "chat_completions" => "chatCompletions", - _ => return Err("AI_COMMIT_INVALID_CONFIG"), + _ => return Err(INVALID_CONFIG), }; let mut configuration = detected( "codex", @@ -109,6 +359,11 @@ fn parse_codex_configuration( ); configuration.provider.requires_api_key = uses_openai_auth || env_key.is_some() || bearer_token.is_some(); + configuration.reasoning_effort = document + .setting("model_reasoning_effort") + .map(str::trim) + .filter(|effort| !effort.is_empty()) + .map(str::to_owned); Ok(configuration) } @@ -135,37 +390,78 @@ fn parse_claude_configuration( allow_incomplete: bool, ) -> Result { fn object(text: &str) -> Result { - if text.is_empty() { + if text.trim().is_empty() { return Ok(Value::Null); } - let value: Value = serde_json::from_str(text).map_err(|_| "AI_COMMIT_INVALID_CONFIG")?; + let value: Value = serde_json::from_str(text).map_err(|_| INVALID_CONFIG)?; if !value.is_object() { - return Err("AI_COMMIT_INVALID_CONFIG"); + return Err(INVALID_CONFIG); } Ok(value) } let settings = object(settings)?; let credentials = object(credentials)?; let root = object(root)?; - let env = |key: &str| { - first_nonempty([ - settings["env"][key].as_str(), - environment.get(key).map(String::as_str), - ]) + fn in_file<'a>(file: ConfigurationFile, document: &'a Value, path: &[&str]) -> Candidate<'a> { + let value = path + .iter() + .try_fold(document, |value, key| value.get(*key)) + .and_then(Value::as_str); + candidate( + value, + CredentialLocator::File { + file, + path: path.iter().map(|key| (*key).to_owned()).collect(), + }, + ) + } + // `settings.env` overrides the process environment, as in Claude Code. + let env_candidates = |key: &str| { + [ + in_file(ConfigurationFile::Settings, &settings, &["env", key]), + environment_candidate(environment, key), + ] }; - let key = first_nonempty([ - settings["env"]["ANTHROPIC_API_KEY"].as_str(), - settings["apiKey"].as_str(), - root["apiKey"].as_str(), - credentials["apiKey"].as_str(), - env("ANTHROPIC_API_KEY"), - ]); - let token = first_nonempty([ - env("ANTHROPIC_AUTH_TOKEN"), - settings["authToken"].as_str(), - root["authToken"].as_str(), + let env = |key: &str| first_candidate(env_candidates(key)).map(|(value, _)| value); + // File keys sit between `settings.env` and the inherited process environment. + let key = first_candidate([ + in_file( + ConfigurationFile::Settings, + &settings, + &["env", "ANTHROPIC_API_KEY"], + ), + in_file(ConfigurationFile::Settings, &settings, &["apiKey"]), + in_file(ConfigurationFile::Root, &root, &["apiKey"]), + in_file(ConfigurationFile::Credentials, &credentials, &["apiKey"]), + environment_candidate(environment, "ANTHROPIC_API_KEY"), ]); - let credential = key.or(token).map(str::to_owned); + let token = first_candidate(env_candidates("ANTHROPIC_AUTH_TOKEN").into_iter().chain([ + in_file(ConfigurationFile::Settings, &settings, &["authToken"]), + in_file(ConfigurationFile::Root, &root, &["authToken"]), + ])); + // Claude Code prefers cloud-provider routes, then an auth token, then an API + // key, and consults `apiKeyHelper` only without either. Lithe cannot run + // cloud or helper routes, so those make no static credential authoritative. + let enabled = |key: &str| env(key).is_some_and(|value| !matches!(value, "0" | "false")); + let cloud_route = [ + "CLAUDE_CODE_USE_BEDROCK", + "CLAUDE_CODE_USE_VERTEX", + "CLAUDE_CODE_USE_FOUNDRY", + ] + .iter() + .any(|key| enabled(key)); + let helper = settings["apiKeyHelper"] + .as_str() + .is_some_and(|value| !value.trim().is_empty()); + let unsupported_authentication = cloud_route || (token.is_none() && key.is_none() && helper); + let authentication = if token.is_some() { + "bearer" + } else if key.is_some() || allow_incomplete { + "apiKey" + } else { + "bearer" + }; + let credential = if cloud_route { None } else { token.or(key) }; let endpoint = first_nonempty([ env("ANTHROPIC_BASE_URL"), env("ANTHROPIC_API_URL"), @@ -199,19 +495,41 @@ fn parse_claude_configuration( } else { model }; - Ok(detected( + let mut configuration = detected( "claude", "Claude", endpoint, model, "anthropicMessages", - if key.is_some() || (allow_incomplete && token.is_none()) { - "apiKey" - } else { - "bearer" - }, + authentication, credential, - )) + ); + configuration.unsupported_authentication = unsupported_authentication; + Ok(configuration) +} + +/// A credential value with its location; blank values are never candidates. +type Candidate<'a> = Option<(&'a str, CredentialLocator)>; + +fn candidate(value: Option<&str>, locator: CredentialLocator) -> Candidate<'_> { + value + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(|value| (value, locator)) +} + +fn environment_candidate<'a>( + environment: &'a BTreeMap, + name: &str, +) -> Candidate<'a> { + candidate( + environment.get(name).map(String::as_str), + CredentialLocator::Environment { name: name.into() }, + ) +} + +fn first_candidate<'a>(values: impl IntoIterator>) -> Candidate<'a> { + values.into_iter().flatten().next() } fn first_nonempty<'a>(values: impl IntoIterator>) -> Option<&'a str> { @@ -229,8 +547,12 @@ fn detected( model: &str, protocol: &str, authentication: &str, - credential: Option, + credential: Candidate<'_>, ) -> DetectedConfiguration { + let (credential, credential_locator) = match credential { + Some((value, locator)) => (Some(value.to_owned()), Some(locator)), + None => (None, None), + }; DetectedConfiguration { provider: Provider { id: format!("imported-{source}"), @@ -245,6 +567,9 @@ fn detected( chat_token_limit_field: ChatTokenLimitField::default(), }, has_credential: credential.is_some(), + credential_locator, + reasoning_effort: None, + unsupported_authentication: false, credential, } } diff --git a/rust/lithe-core/src/ai/tests.rs b/rust/lithe-core/src/ai/tests.rs index 4bc3d61b09..e81a8f05f2 100644 --- a/rust/lithe-core/src/ai/tests.rs +++ b/rust/lithe-core/src/ai/tests.rs @@ -1,91 +1,197 @@ -//! Behavioral coverage for configuration import, secret boundaries and commit wire protocols. +//! Behavioral coverage for CLI configuration import, secret boundaries and commit wire protocols. use super::*; use serde_json::{json, Value}; use std::collections::BTreeMap; -#[test] -fn agent_provider_configuration_matches_fixture_without_credentials() { - let fixture: Value = serde_json::from_str(include_str!( - "../../../../shared/fixtures/agent/provider-configuration-v1.json" +fn configuration_fixture() -> Value { + serde_json::from_str(include_str!( + "../../../../shared/fixtures/ai/cli-configuration-v1.json" )) - .unwrap(); - for case in fixture["cases"].as_array().unwrap() { - let response: Value = serde_json::from_str(&crate::execute_json( - &json!({ - "id": "provider-fixture", "command": "agent.parseProviderConfiguration", - "payload": {"source": case["source"], "configuration": case["configuration"]} - }) - .to_string(), - )) - .unwrap(); - assert_eq!(response["ok"], true); - assert_eq!(response["id"], "provider-fixture"); - let parsed = &response["data"]; - for (key, value) in case["expected"].as_object().unwrap() { - assert_eq!(&parsed[key], value); + .unwrap() +} + +fn execute(command: &str, payload: &Value) -> Value { + serde_json::from_str(&crate::execute_json( + &json!({"id": "configuration-fixture", "command": command, "payload": payload}).to_string(), + )) + .unwrap() +} + +/// Every expected field must match; unspecified response fields are free. +fn assert_subset(actual: &Value, expected: &Value, case: &Value) { + match expected { + Value::Object(fields) => { + for (key, value) in fields { + assert_subset(&actual[key], value, case); + } } - assert!(!parsed.to_string().contains("fixture-secret")); - assert!(parsed.get("credential").is_none()); - assert!(parsed.get("hasCredential").is_none()); + _ => assert_eq!(actual, expected, "{}", case["id"]), + } +} + +/// Resolves a locator the way a host does, against the request it sent. +fn resolve_locator(locator: &Value, files: &Value, environment: &Value) -> Option { + match locator["kind"].as_str()? { + "environment" => environment[locator["name"].as_str()?] + .as_str() + .map(str::to_owned), + "file" => { + let text = files[locator["file"].as_str()?].as_str()?; + let document: Value = if locator["file"] == "config" { + serde_json::to_value(toml::from_str::(text).ok()?).ok()? + } else { + serde_json::from_str(text).ok()? + }; + let path = locator["path"].as_array()?; + path.iter() + .try_fold(&document, |value, key| value.get(key.as_str()?))? + .as_str() + .map(|value| value.trim().to_owned()) + } + _ => None, } } #[test] -fn agent_provider_configuration_errors_are_bounded_and_redacted() { - for payload in [ - json!({"source":"codex", "configuration":"fixture-secret = ["}), - json!({"source":"claude", "configuration":"[]"}), - json!({"source":"unknown", "configuration":"{}"}), - json!({"source":"codex", "configuration":"x".repeat(65 * 1024)}), - json!({"source":"codex", "configuration": null}), - ] { - for allow_incomplete in [false, true] { - let mut payload = payload.clone(); - payload["allowIncomplete"] = allow_incomplete.into(); - let error = parse_provider_configuration(payload).unwrap_err(); - let value = serde_json::to_string(&error).unwrap(); - assert!(value.contains("invalid_request")); - assert!(!value.contains("fixture-secret")); - assert!(!value.contains("details")); +fn configuration_sources_match_fixture() { + let fixture = configuration_fixture(); + // Fixture paths are POSIX; Windows needs a drive for them to be absolute. + let native = |path: &str| { + if cfg!(windows) { + format!("C:{path}") + } else { + path.to_owned() + } + }; + for case in fixture["sourceCases"].as_array().unwrap() { + let mut request = case["request"].clone(); + request["home"] = native(request["home"].as_str().unwrap()).into(); + for (_, value) in request["environment"].as_object_mut().unwrap() { + if value.as_str().unwrap().starts_with('/') { + *value = native(value.as_str().unwrap()).into(); + } + } + let response = execute("ai.configuration.sources", &request); + assert_eq!(response["ok"], true, "{}", case["id"]); + let actual = response["data"]["files"].as_array().unwrap(); + let expected = case["expected"].as_array().unwrap(); + assert_eq!(actual.len(), expected.len(), "{}", case["id"]); + for (actual, expected) in actual.iter().zip(expected) { + assert_eq!(actual["file"], expected["file"], "{}", case["id"]); + // Component comparison keeps the fixture valid with Windows separators. + assert_eq!( + std::path::Path::new(actual["path"].as_str().unwrap()), + std::path::Path::new(&native(expected["path"].as_str().unwrap())), + "{}", + case["id"] + ); } } + let relative = execute( + "ai.configuration.sources", + &json!({"source": "codex", "home": "relative"}), + ); + assert_eq!(relative["ok"], false); } #[test] -fn agent_provider_drafts_preserve_missing_fields_without_credentials_or_cli_defaults() { - let fixture: Value = serde_json::from_str(include_str!( - "../../../../shared/fixtures/agent/provider-configuration-v1.json" - )) - .unwrap(); +fn strict_configuration_parse_matches_fixture_without_secrets() { + let fixture = configuration_fixture(); + let marker = fixture["secretMarker"].as_str().unwrap(); + for case in fixture["strictCases"].as_array().unwrap() { + let payload = json!({ + "source": case["source"], "files": case["files"], "environment": case["environment"], + }); + let response = execute("ai.configuration.parse", &payload); + assert_eq!(response["ok"], true, "{}", case["id"]); + assert!(!response.to_string().contains(marker), "{}", case["id"]); + let data = &response["data"]; + if case["expected"].is_null() { + assert!(data.is_null(), "{}", case["id"]); + continue; + } + assert_subset(data, &case["expected"], case); + assert_eq!( + resolve_locator(&data["credential"], &case["files"], &case["environment"]), + case["expectedCredentialValue"].as_str().map(str::to_owned), + "{}", + case["id"] + ); + assert_eq!( + data["hasCredential"], + !data["credential"].is_null(), + "{}", + case["id"] + ); + // The in-process Rust API used by the Windows host agrees with the locator. + let files: ConfigurationFiles = serde_json::from_value(case["files"].clone()).unwrap(); + let environment: BTreeMap = + serde_json::from_value(case["environment"].clone()).unwrap(); + if let Ok(Some(detected)) = detect(case["source"].as_str().unwrap(), &files, &environment) { + assert_eq!( + detected.credential.as_deref(), + case["expectedCredentialValue"].as_str(), + "{}", + case["id"] + ); + assert!(!serde_json::to_string(&detected).unwrap().contains(marker)); + } + } +} + +#[test] +fn draft_configuration_parse_preserves_missing_fields_without_cli_defaults() { + let fixture = configuration_fixture(); + let marker = fixture["secretMarker"].as_str().unwrap(); for case in fixture["draftCases"].as_array().unwrap() { - let response: Value = serde_json::from_str(&crate::execute_json(&json!({ - "id": "draft-fixture", "command": "agent.parseProviderConfiguration", - "payload": {"source": case["source"], "configuration": case["configuration"], "allowIncomplete": true} - }).to_string())).unwrap(); + let payload = + json!({"source": case["source"], "files": case["files"], "allowIncomplete": true}); + let response = execute("ai.configuration.parse", &payload); assert_eq!(response["ok"], true, "{}", case["id"]); - for (key, value) in case["expected"].as_object().unwrap() { - assert_eq!(&response["data"][key], value, "{}", case["id"]); + assert!(!response.to_string().contains(marker), "{}", case["id"]); + let data = &response["data"]; + let mut expected = case["expected"].clone(); + if let Some(flag) = expected + .as_object_mut() + .unwrap() + .remove("unsupportedAuthentication") + { + assert_eq!(data["unsupportedAuthentication"], flag, "{}", case["id"]); + } + assert_subset(&data["provider"], &expected, case); + if let Some(locator) = case.get("expectedCredential") { + assert_eq!(&data["credential"], locator, "{}", case["id"]); } - assert!(!response.to_string().contains("fixture-secret")); - assert!(response["data"].get("credential").is_none()); - assert!(response["data"].get("hasCredential").is_none()); + assert_eq!( + resolve_locator(&data["credential"], &case["files"], &json!({})), + case["expectedCredentialValue"].as_str().map(str::to_owned), + "{}", + case["id"] + ); } - // The editor-only flag must not relax the existing strict/default CLI parser. - let strict_codex = parse_provider_configuration( - json!({"source":"codex", "configuration":"model = 'draft-model'"}), - ) - .unwrap(); - assert_eq!(strict_codex["endpoint"], "https://api.openai.com/v1"); - assert!(parse_provider_configuration( - json!({"source":"codex", "configuration":"model_provider = 'custom'"}) - ) - .is_err()); - let strict = - parse_provider_configuration(json!({"source":"claude", "configuration":"{}"})).unwrap(); - assert_eq!(strict["endpoint"], "https://api.anthropic.com/v1"); - assert_eq!(strict["model"], "claude-sonnet-4-5"); - assert_eq!(strict["authentication"], "bearer"); +} + +#[test] +fn configuration_parse_errors_are_stable_codes_without_input() { + let fixture = configuration_fixture(); + let marker = fixture["secretMarker"].as_str().unwrap(); + for case in fixture["errorCases"].as_array().unwrap() { + let response = execute("ai.configuration.parse", &case["payload"]); + assert_eq!(response["ok"], false, "{}", case["id"]); + assert_eq!( + response["error"]["code"], "invalid_request", + "{}", + case["id"] + ); + assert_eq!(response["error"]["message"], case["code"], "{}", case["id"]); + assert!(!response.to_string().contains(marker), "{}", case["id"]); + } + let oversized = execute( + "ai.configuration.parse", + &json!({"source": "codex", "files": {"config": "x".repeat(1024 * 1024 + 1)}}), + ); + assert_eq!(oversized["error"]["message"], "AI_CONFIGURATION_TOO_LARGE"); } fn fixture() -> (Provider, CommitOptions, Vec, Value) { diff --git a/shared/fixtures/ai/cli-configuration-v1.json b/shared/fixtures/ai/cli-configuration-v1.json new file mode 100644 index 0000000000..3bb8b35489 --- /dev/null +++ b/shared/fixtures/ai/cli-configuration-v1.json @@ -0,0 +1,278 @@ +{ + "schemaVersion": 1, + "description": "ai.configuration.sources and ai.configuration.parse. Every credential value is an obviously fake string containing secretMarker; no response may contain it. expectedCredentialValue is what a host obtains by resolving the returned locator against the same files and environment.", + "secretMarker": "fixture-secret", + "sourceCases": [ + { + "id": "codex-default-directory", + "request": { "source": "codex", "home": "/fixture-home", "environment": {} }, + "expected": [ + { "file": "config", "path": "/fixture-home/.codex/config.toml" }, + { "file": "auth", "path": "/fixture-home/.codex/auth.json" } + ] + }, + { + "id": "codex-home-override", + "request": { "source": "codex", "home": "/fixture-home", "environment": { "CODEX_HOME": "/fixture-codex" } }, + "expected": [ + { "file": "config", "path": "/fixture-codex/config.toml" }, + { "file": "auth", "path": "/fixture-codex/auth.json" } + ] + }, + { + "id": "claude-config-dir-override-keeps-root-in-home", + "request": { "source": "claude", "home": "/fixture-home", "environment": { "CLAUDE_CONFIG_DIR": "/fixture-claude", "CODEX_HOME": " " } }, + "expected": [ + { "file": "settings", "path": "/fixture-claude/settings.json" }, + { "file": "credentials", "path": "/fixture-claude/.credentials.json" }, + { "file": "root", "path": "/fixture-home/.claude.json" } + ] + } + ], + "strictCases": [ + { + "id": "codex-profile-defaults-to-responses-and-reads-auth-key", + "source": "codex", + "files": { + "config": "model = 'unused'\nprofile = 'work'\n[profiles.work]\nmodel = 'fixture-model'\nmodel_provider = 'gateway'\nmodel_reasoning_effort = 'high'\n[model_providers.gateway]\nbase_url = 'https://example.test/v1'\nrequires_openai_auth = true\n", + "auth": "{\"OPENAI_API_KEY\":\"fixture-secret-auth\"}" + }, + "environment": { "OPENAI_API_KEY": "fixture-secret-environment" }, + "expected": { + "model": "fixture-model", + "provider": { "endpoint": "https://example.test/v1", "model": "fixture-model", "apiProtocol": "responses", "authentication": "bearer", "requiresApiKey": true, "source": "codex" }, + "issue": null, + "reasoningEffort": "high", + "hasCredential": true, + "credential": { "kind": "file", "file": "auth", "path": ["OPENAI_API_KEY"] }, + "unsupportedAuthentication": false + }, + "expectedCredentialValue": "fixture-secret-auth" + }, + { + "id": "codex-default-openai-provider-falls-back-to-environment", + "source": "codex", + "files": { "config": "model = 'fixture-model'\n", "auth": "{\"OPENAI_API_KEY\":null,\"tokens\":{\"access_token\":\"fixture-secret-oauth\"}}" }, + "environment": { "OPENAI_API_KEY": "fixture-secret-environment" }, + "expected": { + "model": "fixture-model", + "provider": { "endpoint": "https://api.openai.com/v1", "apiProtocol": "responses", "requiresApiKey": true }, + "hasCredential": true, + "credential": { "kind": "environment", "name": "OPENAI_API_KEY" } + }, + "expectedCredentialValue": "fixture-secret-environment" + }, + { + "id": "codex-declared-env-key-never-falls-back", + "source": "codex", + "files": { + "config": "model = 'fixture-model'\nmodel_provider = 'company'\n[model_providers.company]\nbase_url = 'https://gateway.example.test/v1'\nwire_api = 'chat'\nenv_key = 'COMPANY_KEY'\n", + "auth": "{\"OPENAI_API_KEY\":\"fixture-secret-auth\"}" + }, + "environment": { "OPENAI_API_KEY": "fixture-secret-environment" }, + "expected": { + "provider": { "endpoint": "https://gateway.example.test/v1", "apiProtocol": "chatCompletions", "requiresApiKey": true }, + "hasCredential": false, + "credential": null + } + }, + { + "id": "codex-env-key-resolves-from-environment", + "source": "codex", + "files": { + "config": "model = 'fixture-model'\nmodel_provider = 'company'\n[model_providers.company]\nbase_url = 'https://gateway.example.test/v1'\nenv_key = 'COMPANY_KEY'\n" + }, + "environment": { "COMPANY_KEY": "fixture-secret-company" }, + "expected": { + "hasCredential": true, + "credential": { "kind": "environment", "name": "COMPANY_KEY" } + }, + "expectedCredentialValue": "fixture-secret-company" + }, + { + "id": "codex-inline-bearer-token", + "source": "codex", + "files": { + "config": "model = 'fixture-model'\nmodel_provider = 'company'\n[model_providers.company]\nbase_url = 'https://gateway.example.test/v1'\nexperimental_bearer_token = 'fixture-secret-inline'\n" + }, + "environment": {}, + "expected": { + "hasCredential": true, + "credential": { "kind": "file", "file": "config", "path": ["model_providers", "company", "experimental_bearer_token"] } + }, + "expectedCredentialValue": "fixture-secret-inline" + }, + { + "id": "codex-keyless-local-provider", + "source": "codex", + "files": { + "config": "model = 'local-model'\nmodel_provider = 'local'\n[model_providers.local]\nbase_url = 'http://localhost:1234/v1'\n", + "auth": "{\"OPENAI_API_KEY\":\"fixture-secret-auth\"}" + }, + "environment": {}, + "expected": { + "provider": { "endpoint": "http://localhost:1234/v1", "requiresApiKey": false }, + "hasCredential": false, + "credential": null + } + }, + { + "id": "codex-incomplete-provider-still-reports-model", + "source": "codex", + "files": { "config": "model = 'fixture-model'\nmodel_provider = 'custom'\n" }, + "environment": {}, + "expected": { + "model": "fixture-model", + "provider": null, + "issue": "AI_COMMIT_INVALID_CONFIG", + "hasCredential": false, + "credential": null + } + }, + { + "id": "codex-not-configured", + "source": "codex", + "files": { "config": " \n", "auth": "{\"OPENAI_API_KEY\":\"fixture-secret-auth\"}" }, + "environment": { "OPENAI_API_KEY": "fixture-secret-environment" }, + "expected": null + }, + { + "id": "claude-settings-env-wins-and-resolves-alias", + "source": "claude", + "files": { + "settings": "{\"env\":{\"ANTHROPIC_BASE_URL\":\"https://example.test/v1\",\"ANTHROPIC_MODEL\":\"sonnet\",\"ANTHROPIC_DEFAULT_SONNET_MODEL\":\"fixture-model\",\"ANTHROPIC_API_KEY\":\"fixture-secret-settings\"}}", + "root": "{\"apiKey\":\"fixture-secret-root\"}" + }, + "environment": { "ANTHROPIC_API_KEY": "fixture-secret-environment", "ANTHROPIC_BASE_URL": "https://ignored.example.test" }, + "expected": { + "model": "fixture-model", + "provider": { "endpoint": "https://example.test/v1", "model": "fixture-model", "apiProtocol": "anthropicMessages", "authentication": "apiKey", "source": "claude" }, + "hasCredential": true, + "credential": { "kind": "file", "file": "settings", "path": ["env", "ANTHROPIC_API_KEY"] }, + "unsupportedAuthentication": false + }, + "expectedCredentialValue": "fixture-secret-settings" + }, + { + "id": "claude-process-environment-api-url-and-key", + "source": "claude", + "files": { "settings": "{\"model\":\"fixture-model\",\"apiKey\":\" \"}" }, + "environment": { "ANTHROPIC_API_URL": "https://environment.example.test/v1", "ANTHROPIC_API_KEY": "fixture-secret-environment" }, + "expected": { + "provider": { "endpoint": "https://environment.example.test/v1", "model": "fixture-model", "authentication": "apiKey" }, + "credential": { "kind": "environment", "name": "ANTHROPIC_API_KEY" } + }, + "expectedCredentialValue": "fixture-secret-environment" + }, + { + "id": "claude-auth-token-wins-over-api-key", + "source": "claude", + "files": { "settings": "{\"apiKey\":\"fixture-secret-key\",\"env\":{\"ANTHROPIC_AUTH_TOKEN\":\"fixture-secret-token\"}}" }, + "environment": {}, + "expected": { + "provider": { "endpoint": "https://api.anthropic.com/v1", "model": "claude-sonnet-4-5", "authentication": "bearer" }, + "credential": { "kind": "file", "file": "settings", "path": ["env", "ANTHROPIC_AUTH_TOKEN"] } + }, + "expectedCredentialValue": "fixture-secret-token" + }, + { + "id": "claude-cloud-route-has-no-static-credential", + "source": "claude", + "files": { "settings": "{\"env\":{\"CLAUDE_CODE_USE_BEDROCK\":\"1\",\"ANTHROPIC_API_KEY\":\"fixture-secret-settings\"}}" }, + "environment": {}, + "expected": { + "hasCredential": false, + "credential": null, + "unsupportedAuthentication": true + } + }, + { + "id": "claude-key-helper-without-key-is-unsupported", + "source": "claude", + "files": { "settings": "{\"apiKeyHelper\":\"/fixture/print-key\"}" }, + "environment": {}, + "expected": { + "hasCredential": false, + "credential": null, + "unsupportedAuthentication": true + } + }, + { + "id": "claude-key-helper-is-ignored-when-a-key-exists", + "source": "claude", + "files": { "settings": "{\"apiKeyHelper\":\"/fixture/print-key\"}", "credentials": "{\"apiKey\":\"fixture-secret-credentials\"}" }, + "environment": {}, + "expected": { + "hasCredential": true, + "credential": { "kind": "file", "file": "credentials", "path": ["apiKey"] }, + "unsupportedAuthentication": false + }, + "expectedCredentialValue": "fixture-secret-credentials" + }, + { + "id": "claude-environment-only", + "source": "claude", + "files": {}, + "environment": { "ANTHROPIC_API_KEY": "fixture-secret-environment" }, + "expected": { + "provider": { "endpoint": "https://api.anthropic.com/v1", "authentication": "apiKey" }, + "credential": { "kind": "environment", "name": "ANTHROPIC_API_KEY" } + }, + "expectedCredentialValue": "fixture-secret-environment" + }, + { + "id": "claude-not-configured", + "source": "claude", + "files": { "settings": "", "credentials": " " }, + "environment": { "OPENAI_API_KEY": "fixture-secret-environment" }, + "expected": null + } + ], + "draftCases": [ + { "id": "codex-empty", "source": "codex", "files": { "config": "" }, + "expected": { "endpoint": "", "model": "", "apiProtocol": "responses", "authentication": "bearer" } }, + { "id": "codex-whitespace", "source": "codex", "files": { "config": " \n\t " }, + "expected": { "endpoint": "", "model": "", "apiProtocol": "responses", "authentication": "bearer" } }, + { "id": "codex-model-only", "source": "codex", "files": { "config": "model = 'draft-model'" }, + "expected": { "endpoint": "", "model": "draft-model", "apiProtocol": "responses", "authentication": "bearer" } }, + { "id": "codex-endpoint-only", "source": "codex", "files": { "config": "model_provider = 'custom'\n[model_providers.custom]\nbase_url = 'https://example.test/v1'" }, + "expected": { "endpoint": "https://example.test/v1", "model": "", "apiProtocol": "responses", "authentication": "bearer" } }, + { "id": "codex-pasted-auth-key", "source": "codex", + "files": { "config": "model_provider = \"lithe\"\nmodel = \"draft-model\"\n[model_providers.lithe]\nbase_url = \"https://example.test/v1\"\nwire_api = \"responses\"\n", "auth": "{\"api_key\":\"fixture-secret-pasted\"}" }, + "expected": { "endpoint": "https://example.test/v1", "model": "draft-model", "apiProtocol": "responses" }, + "expectedCredential": { "kind": "file", "file": "auth", "path": ["api_key"] }, + "expectedCredentialValue": "fixture-secret-pasted" }, + { "id": "claude-blank", "source": "claude", "files": { "settings": "" }, + "expected": { "endpoint": "", "model": "", "apiProtocol": "anthropicMessages", "authentication": "apiKey" } }, + { "id": "claude-whitespace", "source": "claude", "files": { "settings": " \n\t " }, + "expected": { "endpoint": "", "model": "", "apiProtocol": "anthropicMessages", "authentication": "apiKey" } }, + { "id": "claude-empty", "source": "claude", "files": { "settings": "{}" }, + "expected": { "endpoint": "", "model": "", "apiProtocol": "anthropicMessages", "authentication": "apiKey" } }, + { "id": "claude-empty-template", "source": "claude", "files": { "settings": "{\"env\":{\"ANTHROPIC_BASE_URL\":\"\",\"ANTHROPIC_MODEL\":\"\",\"ANTHROPIC_API_KEY\":\"\"}}" }, + "expected": { "endpoint": "", "model": "", "apiProtocol": "anthropicMessages", "authentication": "apiKey" } }, + { "id": "claude-model-only", "source": "claude", "files": { "settings": "{\"env\":{\"ANTHROPIC_MODEL\":\"draft-model\"}}" }, + "expected": { "endpoint": "", "model": "draft-model", "apiProtocol": "anthropicMessages", "authentication": "apiKey" } }, + { "id": "claude-key-only", "source": "claude", "files": { "settings": "{\"env\":{\"ANTHROPIC_API_KEY\":\"fixture-secret-pasted\"}}" }, + "expected": { "endpoint": "", "model": "", "apiProtocol": "anthropicMessages", "authentication": "apiKey" }, + "expectedCredential": { "kind": "file", "file": "settings", "path": ["env", "ANTHROPIC_API_KEY"] }, + "expectedCredentialValue": "fixture-secret-pasted" }, + { "id": "claude-alias", "source": "claude", "files": { "settings": "{\"env\":{\"ANTHROPIC_MODEL\":\"sonnet\",\"ANTHROPIC_DEFAULT_SONNET_MODEL\":\"alias-model\"}}" }, + "expected": { "endpoint": "", "model": "alias-model", "apiProtocol": "anthropicMessages", "authentication": "apiKey" } }, + { "id": "claude-pasted-token-is-bearer", "source": "claude", "files": { "settings": "{\"env\":{\"ANTHROPIC_AUTH_TOKEN\":\"fixture-secret-token\",\"ANTHROPIC_API_KEY\":\"fixture-secret-pasted\"}}" }, + "expected": { "authentication": "bearer", "unsupportedAuthentication": false }, + "expectedCredential": { "kind": "file", "file": "settings", "path": ["env", "ANTHROPIC_AUTH_TOKEN"] }, + "expectedCredentialValue": "fixture-secret-token" }, + { "id": "claude-pasted-cloud-route", "source": "claude", "files": { "settings": "{\"env\":{\"CLAUDE_CODE_USE_VERTEX\":\"true\",\"ANTHROPIC_API_KEY\":\"fixture-secret-pasted\"}}" }, + "expected": { "unsupportedAuthentication": true }, + "expectedCredential": null } + ], + "errorCases": [ + { "id": "codex-malformed", "payload": { "source": "codex", "files": { "config": "fixture-secret = [" } }, "code": "AI_COMMIT_INVALID_CONFIG" }, + { "id": "codex-smart-quotes", "payload": { "source": "codex", "files": { "config": "model = “fixture-secret”" }, "allowIncomplete": true }, "code": "AI_CONFIGURATION_SMART_QUOTES" }, + { "id": "codex-auth-not-object", "payload": { "source": "codex", "files": { "config": "model = 'x'", "auth": "[\"fixture-secret\"]" } }, "code": "AI_CONFIGURATION_INVALID_AUTHENTICATION" }, + { "id": "codex-auth-key-not-string", "payload": { "source": "codex", "files": { "config": "model = 'x'", "auth": "{\"OPENAI_API_KEY\":42}" }, "allowIncomplete": true }, "code": "AI_CONFIGURATION_INVALID_AUTHENTICATION" }, + { "id": "claude-not-object", "payload": { "source": "claude", "files": { "settings": "[\"fixture-secret\"]" } }, "code": "AI_COMMIT_INVALID_CONFIG" }, + { "id": "unknown-source", "payload": { "source": "fixture", "files": {} }, "code": "AI_COMMIT_INVALID_CONFIG" }, + { "id": "unknown-file", "payload": { "source": "codex", "files": { "fixture": "fixture-secret" } }, "code": "AI_COMMIT_INVALID_CONFIG" } + ] +} diff --git a/shared/platform-feature-matrix/features/agent-provider-configuration.json b/shared/platform-feature-matrix/features/agent-provider-configuration.json index 30e3a642d6..24e57cf40e 100644 --- a/shared/platform-feature-matrix/features/agent-provider-configuration.json +++ b/shared/platform-feature-matrix/features/agent-provider-configuration.json @@ -20,7 +20,8 @@ "macos/Sources/Lithe/Models/Settings/AppSettings.swift", "macos/Tests/LitheTests/AgentLaunchConfigurationResolverTests.swift", "macos/Tests/LitheTests/AgentLaunchConfigurationIntegrationTests.swift", - "macos/Sources/Lithe/Platform/MacOS/AI/MacAgentProviderConfigurationParser.swift" + "macos/Sources/Lithe/Platform/MacOS/AI/MacAgentProviderConfigurationParser.swift", + "macos/Sources/Lithe/Platform/MacOS/AI/MacCLIConfigurationReader.swift" ] }, "windows": { @@ -28,7 +29,7 @@ "verificationStatus": "pending", "evidence": [ "rust/lithe-core/src/ai/agent_configuration.rs", - "shared/fixtures/agent/provider-configuration-v1.json", + "shared/fixtures/ai/cli-configuration-v1.json", "windows/tauri/src/features/agent/components/agent-settings-section.tsx", "windows/tauri/src/features/agent/services/agent-launch.ts", "windows/tauri/src/features/agent/services/agent-provider-import.ts", @@ -42,5 +43,5 @@ }, "owner": "Agent", "verification": "macOS:本机 Codex/Claude 配置使用 HTTP 回环代理时,确认默认被拒绝;在当前本机配置行打开 Allow insecure HTTP,空闲重连后检查所选代理接收请求,关闭后再次拒绝;刷新、重新导入及重启保留许可且另一来源不受影响,忙碌时拒绝更改,另一窗口刷新或删除后过期更改失败。验证本机 Codex/Claude 配置读取、刷新与取消关联;外部 CLI 连续切换地址、模型与密钥后直接建立新连接,确认每个连接使用同次快照且面板元数据同步,不依赖手动刷新;原供应商 ID、关联、提交供应商选择、另一来源和 HTTP 许可不变,密钥不进入设置;缺失配置或密钥拒绝旧路由,仅模型可读时保留回退显示;自定义配置及订阅不读取本机 API 快照;新增 Codex 专用编辑器时确认默认模型为 gpt-6.1-sol,新增 Claude 专用编辑器确认预填 claude-fable-5-1 且 settings JSON 与表单一致;两种草稿往返切换后保留默认值,编辑已有 Claude 供应商保留自定义或空模型;通用 AI Providers 的 Add Provider 切换 Anthropic Messages 后,未填写模型时确认 Claude 草稿模型为空且提交信息请求在发送前被拒绝,填写模型后检查 Anthropic 请求使用该值;协议切换保留手动模型(包括恰好等于 Codex 默认值的输入),编辑已有服务商时确认保留已保存的模型;新增与编辑默认显示名称、API Key、API 请求地址和模型表单,必填项为空禁用保存,密钥默认隐藏且可显隐;修改字段后切到配置文本确认 TOML/JSON 正确转义,修改配置文本后切回表单检查同步回填;新增 Codex/Claude 后不填任何值往返切换,以及分别缺少地址、模型、Key 时返回表单,确认不报缺失密钥、不填隐式默认值且仍不能保存;粘贴部分配置和模型别名确认字段与 Key 保留,切换失败保留原文和当前模式,保存只读取当前模式的输入;检查表单 HTTP 默认阻止且显式许可后可保存,编辑回填地址、模型、Key、HTTP 许可及原 ID;添加自定义 TOML/auth JSON 或 Claude settings JSON,检查格式化、输入直引号不被自动替换、弯引号 TOML 错误在保存按钮上方始终可见、非法配置和缺失密钥、取消不保存、编辑保持 ID、删除确认及安全存储失败不丢失配置。在一个窗口保存并等待连接关闭期间,由另一窗口删除或修改同一供应商,确认旧保存失败且不恢复/覆盖供应商、密钥或 Agent 关联。检查窄宽面板、深浅主题、中英文本。空闲切换后确认请求到所选地址和模型;未发送空会话切换或意外退出后重新创建,不向旧 ID 加载,首条消息与文件只发送一次;已有消息、上游列出或成功加载的会话继续恢复,历史加载失败保留记录;正在响应、加载、权限待处理或配置确认时拒绝切换。提交服务商选择不被添加/启用改变。CLI 文件与 bundle 不被写入。2026-10-07 已通过 claude-fable-5-1 真实新连接、重连、历史回放与继续回复验证;Windows 编辑器及完整供应商管理界面验收待验证。 Windows:在真实 Tauri 窗口执行 Windows 已支持按 Agent 保存独立配置、命名供应商列表、确认移除与解除密钥关联;密钥按 Agent/供应商 ID 存入 Windows 凭据库,地址变化使用新凭据所有者。表单可生成 Codex TOML/Claude JSON,文本可解析返回表单;Codex auth JSON 的显式 API Key 安全保存。可只读导入本机元数据,或关联本机配置,在每次连接读取最新地址、模型与同次读取的显式 API Key,缺失时拒绝使用旧路由。CLI 文件保持只读。供应商新增和编辑使用独立草稿,取消不保存;显式保存通过 native CAS 同时提交元数据与安全凭据,过期修订拒绝覆盖。已关联本机配置在连接时刷新元数据与凭据,密钥字段支持显隐,读取完成前禁用编辑与保存。真实 Claude/Codex 服务请求和完整多窗口桌面验收保持 pending。 单元测试不替代运行时验收,未执行的真实服务及平台动作保持 pending。 Windows 回归:Codex TOML/auth JSON 和 Claude settings JSON 在文本模式导入后切回表单,直接保存保留导入的地址、模型及凭据草稿;密钥只交给凭据保存动作,不写入普通设置。", - "notes": "2026-10-22:Windows 已支持按 Agent 保存独立配置、命名供应商列表、确认移除与解除密钥关联;密钥按 Agent/供应商 ID 存入 Windows 凭据库,地址变化使用新凭据所有者。表单可生成 Codex TOML/Claude JSON,文本可解析返回表单;Codex auth JSON 的显式 API Key 安全保存。可只读导入本机元数据,或关联本机配置,在每次连接读取最新地址、模型与同次读取的显式 API Key,缺失时拒绝使用旧路由。CLI 文件保持只读。供应商新增和编辑使用独立草稿,取消不保存;显式保存通过 native CAS 同时提交元数据与安全凭据,过期修订拒绝覆盖。已关联本机配置在连接时刷新元数据与凭据,密钥字段支持显隐,读取完成前禁用编辑与保存。真实 Claude/Codex 服务请求和完整多窗口桌面验收保持 pending。 Windows 回归:Codex TOML/auth JSON 和 Claude settings JSON 在文本模式导入后切回表单,直接保存保留导入的地址、模型及凭据草稿;密钥只交给凭据保存动作,不写入普通设置。" + "notes": "2026-10-22:Windows 已支持按 Agent 保存独立配置、命名供应商列表、确认移除与解除密钥关联;密钥按 Agent/供应商 ID 存入 Windows 凭据库,地址变化使用新凭据所有者。表单可生成 Codex TOML/Claude JSON,文本可解析返回表单;Codex auth JSON 的显式 API Key 安全保存。可只读导入本机元数据,或关联本机配置,在每次连接读取最新地址、模型与同次读取的显式 API Key,缺失时拒绝使用旧路由。CLI 文件保持只读。供应商新增和编辑使用独立草稿,取消不保存;显式保存通过 native CAS 同时提交元数据与安全凭据,过期修订拒绝覆盖。已关联本机配置在连接时刷新元数据与凭据,密钥字段支持显隐,读取完成前禁用编辑与保存。真实 Claude/Codex 服务请求和完整多窗口桌面验收保持 pending。 Windows 回归:Codex TOML/auth JSON 和 Claude settings JSON 在文本模式导入后切回表单,直接保存保留导入的地址、模型及凭据草稿;密钥只交给凭据保存动作,不写入普通设置。 CLI 配置发现与解析(AGT-03):Core 的 ai.configuration.sources/parse 决定读取哪些文件并解析为不含密钥的元数据与凭据定位器,两端宿主只读文件并本地解析定位器;macOS 原 Swift 解析器已删除。Codex config.toml 内联 experimental_bearer_token 的定位器 macOS 不解析(与原行为一致,视为无密钥)。" } diff --git a/windows/tauri/src/features/agent/services/agent-provider-import.test.ts b/windows/tauri/src/features/agent/services/agent-provider-import.test.ts index 012cf8e6e0..c18d7798ac 100644 --- a/windows/tauri/src/features/agent/services/agent-provider-import.test.ts +++ b/windows/tauri/src/features/agent/services/agent-provider-import.test.ts @@ -1,21 +1,22 @@ import { describe, expect, test } from "bun:test"; -import fixture from "../../../../../../shared/fixtures/agent/provider-configuration-v1.json"; +import fixture from "../../../../../../shared/fixtures/ai/cli-configuration-v1.json"; import { agentProviderConfigSource, importedProviderMatchesAgent, parseImportedAgentProvider, } from "./agent-provider-import"; -const [codexCase, claudeCase] = fixture.cases; +const codexCase = fixture.strictCases.find((entry) => entry.source === "codex"); +const claudeCase = fixture.strictCases.find((entry) => entry.source === "claude"); describe("Imported Agent provider metadata", () => { test("reads the metadata the shared parser reported for each format", () => { - expect(parseImportedAgentProvider(codexCase?.expected)).toEqual({ + expect(parseImportedAgentProvider(codexCase?.expected.provider)).toEqual({ protocol: "responses", baseUrl: "https://example.test/v1", model: "fixture-model", }); - expect(parseImportedAgentProvider(claudeCase?.expected)).toEqual({ + expect(parseImportedAgentProvider(claudeCase?.expected.provider)).toEqual({ protocol: "anthropicMessages", baseUrl: "https://example.test/v1", model: "fixture-model", diff --git a/windows/tauri/src/features/agent/services/agent-provider-import.ts b/windows/tauri/src/features/agent/services/agent-provider-import.ts index 15b8d6152a..a149439361 100644 --- a/windows/tauri/src/features/agent/services/agent-provider-import.ts +++ b/windows/tauri/src/features/agent/services/agent-provider-import.ts @@ -1,11 +1,10 @@ /** * Import Agent provider metadata from pasted CLI configuration text. * - * The parse itself belongs to the shared Rust core - * (`agent.parseProviderConfiguration`), which returns provider metadata only: - * endpoint, model and wire protocol, with no credentials or credential - * presence. Explicit credentials are handled separately by the platform CLI - * snapshot or the editor's credential parser, never returned by the core parser. + * The parse itself belongs to the shared Rust core (`ai.configuration.parse`), + * and only the provider metadata (endpoint, model and wire protocol) is read + * from its response. Credentials are resolved natively by the host from the + * credential locator and are never part of the core response. */ import { invoke } from "@/platform/tauri-core"; @@ -70,12 +69,12 @@ export async function importAgentProviderConfiguration( configuration: string, allowIncomplete = false, ): Promise { - const response = await invoke("agent.parseProviderConfiguration", { + const response = await invoke<{ provider?: unknown } | null>("ai.configuration.parse", { source, - configuration, + files: source === "codex" ? { config: configuration } : { settings: configuration }, allowIncomplete, }); - const provider = parseImportedAgentProvider(response, allowIncomplete); + const provider = parseImportedAgentProvider(response?.provider, allowIncomplete); if (provider === null) throw new Error("The provider configuration could not be read."); return provider; } diff --git a/windows/tauri/src/platform/tauri-core.ts b/windows/tauri/src/platform/tauri-core.ts index 13485b9e11..c0926f401f 100644 --- a/windows/tauri/src/platform/tauri-core.ts +++ b/windows/tauri/src/platform/tauri-core.ts @@ -192,7 +192,7 @@ function capabilityForCommand(command: string): BackendCapability | null { command === "agent.install" || command === "agent.uninstall" || command === "agent.installCli" || - command === "agent.parseProviderConfiguration" + command === "ai.configuration.parse" ) { return "agent"; } From 24a4491513dba70f9c3468d7a767992ba431e099 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Wed, 4 Nov 2026 22:34:13 -0800 Subject: [PATCH 3/8] =?UTF-8?q?feat(core):=20AGT-04/08=20Agent=20=E7=BC=96?= =?UTF-8?q?=E8=BE=91=E5=9B=9E=E6=BB=9A=E8=AE=A1=E5=88=92=E4=B8=8E=20diff?= =?UTF-8?q?=20=E8=AF=81=E6=8D=AE=E8=A7=84=E8=8C=83=E5=8C=96=EF=BC=88agent.?= =?UTF-8?q?edits.reversePlan=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Host 统一生成并规范化 diff 证据与计数单位,Core 暴露 agent.edits.reversePlan;macOS 与 Windows 删除各自的回滚与证据计算,只负责路径、编码与写入。 Co-Authored-By: Claude Opus 5.5 --- .../Lithe/Core/Ports/AgentEditRestoring.swift | 16 + .../Rust/RustAgentEditReversePlanner.swift | 54 + .../MacOS/Agent/MacAgentEditRestorer.swift | 37 +- .../Platform/MacOS/MacServiceContainer.swift | 7 +- .../Application/AgentActivity.swift | 11 +- .../AgentSessionConfiguration.swift | 66 +- .../AgentActivityPresentationTests.swift | 3 +- .../Tests/LitheTests/AgentActivityTests.swift | 50 +- .../AgentEditEvidenceTestSupport.swift | 36 + .../LitheTests/AgentEditRestorerTests.swift | 84 +- rust/lithe-agent-host/src/edit_review.rs | 399 ++++++ .../lithe-agent-host/src/edit_review/tests.rs | 125 ++ rust/lithe-core/src/agent/edits.rs | 14 + shared/fixtures/agent/edit-review-v1.json | 1087 +++++++++++++++++ .../agent/services/agent-edit-review.test.ts | 122 +- .../agent/services/agent-edit-review.ts | 93 +- .../src/features/agent/types/agent.types.ts | 39 +- .../src/platform/agent-edit-restorer.test.ts | 64 + .../tauri/src/platform/agent-edit-restorer.ts | 11 +- 19 files changed, 2076 insertions(+), 242 deletions(-) create mode 100644 macos/Sources/Lithe/Core/Rust/RustAgentEditReversePlanner.swift create mode 100644 macos/Tests/LitheTests/AgentEditEvidenceTestSupport.swift create mode 100644 rust/lithe-agent-host/src/edit_review.rs create mode 100644 rust/lithe-agent-host/src/edit_review/tests.rs create mode 100644 rust/lithe-core/src/agent/edits.rs create mode 100644 shared/fixtures/agent/edit-review-v1.json create mode 100644 windows/tauri/src/platform/agent-edit-restorer.test.ts diff --git a/macos/Sources/Lithe/Core/Ports/AgentEditRestoring.swift b/macos/Sources/Lithe/Core/Ports/AgentEditRestoring.swift index 5304729bb7..f7f3ee991d 100644 --- a/macos/Sources/Lithe/Core/Ports/AgentEditRestoring.swift +++ b/macos/Sources/Lithe/Core/Ports/AgentEditRestoring.swift @@ -21,6 +21,22 @@ enum AgentEditRestoreError: LocalizedError { } } +/// What the native adapter must do to reverse one file's Agent edits. +enum AgentEditReversePlan: Equatable, Sendable { + /// Guarded write of the restored text in the disk's encoding. + case write(String) + /// The file did not exist before the edits; move it to Trash. + case trash + /// The disk already matches the state before the edits. + case none +} + +/// Plans a rollback from evidence and the current disk text. Conflicts throw +/// ``AgentEditRestoreError`` so nothing is written. +protocol AgentEditReversePlanning: Sendable { + func reversePlan(for change: AgentFileChange, disk: String?) throws -> AgentEditReversePlan +} + struct UnavailableAgentEditRestorer: AgentEditRestoring { func restore(_ change: AgentFileChange, in workspace: URL) async throws { throw AgentEditRestoreError.unavailable } } diff --git a/macos/Sources/Lithe/Core/Rust/RustAgentEditReversePlanner.swift b/macos/Sources/Lithe/Core/Rust/RustAgentEditReversePlanner.swift new file mode 100644 index 0000000000..46c498c863 --- /dev/null +++ b/macos/Sources/Lithe/Core/Rust/RustAgentEditReversePlanner.swift @@ -0,0 +1,54 @@ +import Foundation +import LitheAgentConversationModule + +/// Rust Core-backed rollback planning (`agent.edits.reversePlan`). Matching, +/// line endings, deletion and conflict rules live in `lithe-agent-host`; this +/// adapter only encodes the evidence and maps the plan back into the port. +struct RustAgentEditReversePlanner: AgentEditReversePlanning { + private let core: RustCoreBridge + + init(core: RustCoreBridge = RustCoreBridge()) { + self.core = core + } + + func reversePlan(for change: AgentFileChange, disk: String?) throws -> AgentEditReversePlan { + struct Diff: Encodable { + let oldText: String? + let newText: String + let operation: String? + let toolKind: String? + let truncated: Bool + } + struct Payload: Encodable { + let diffs: [Diff] + let pending: Bool + let missingEvidence: Bool + let disk: String? + } + struct Plan: Decodable { + let action: String + let text: String? + let reason: String? + } + let payload = Payload( + diffs: change.diffs.map { + Diff(oldText: $0.oldText, newText: $0.newText, operation: $0.operation, + toolKind: $0.toolKind, truncated: $0.isTruncated) + }, + pending: change.isPending, missingEvidence: change.hasMissingDiff, disk: disk) + let plan: Plan + do { + plan = try core.executeResult(command: "agent.edits.reversePlan", payload: payload).get() + } catch { + throw AgentEditRestoreError.unavailable + } + switch (plan.action, plan.text, plan.reason) { + case ("write", let text?, _): return .write(text) + case ("trash", _, _): return .trash + case ("none", _, _): return .none + case ("conflict", _, "incomplete"): throw AgentEditRestoreError.incomplete + case ("conflict", _, _): throw AgentEditRestoreError.changed + default: throw AgentEditRestoreError.unavailable + } + } +} diff --git a/macos/Sources/Lithe/Platform/MacOS/Agent/MacAgentEditRestorer.swift b/macos/Sources/Lithe/Platform/MacOS/Agent/MacAgentEditRestorer.swift index 6f56a6af31..0c80756ed3 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Agent/MacAgentEditRestorer.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Agent/MacAgentEditRestorer.swift @@ -5,6 +5,7 @@ import LitheAgentConversationModule /// read-only; snapshots live in conversation memory, without a new disk cache. struct MacAgentEditRestorer: AgentEditRestoring { let fileOperations: any WorkspaceFileOperations + let planner: any AgentEditReversePlanning private static let queue = DispatchQueue(label: "app.lithe.agent-edit-review", qos: .userInitiated) func restore(_ change: AgentFileChange, in workspace: URL) async throws { @@ -33,40 +34,20 @@ struct MacAgentEditRestorer: AgentEditRestoring { } // Reuse the document adapter's size/link checks, encoding and byte identity. let disk = try fileOperations.readDocumentDetails(from: url, encoding: nil) - var restored = disk?.text - for diff in change.diffs.reversed() { - try cancellation.check() - if diff.operation == "delete" || (change.isDeletion && change.diffs.count == 1) { - guard restored == nil, let old = diff.oldText else { throw AgentEditRestoreError.changed } - restored = old - } else if let old = diff.oldText { - guard let current = restored else { throw AgentEditRestoreError.changed } - if current == diff.newText { restored = old } - else { - // Claude sometimes supplies an excerpt. Reverse only one - // exact nonempty match; ambiguous or missing text is a conflict. - guard !diff.newText.isEmpty, let range = current.range(of: diff.newText), - current.range(of: diff.newText, range: current.index(after: range.lowerBound).. 100 || new.count > Self.textLimit || (old?.count ?? 0) > Self.textLimit, - operation: metadata?["kind"] as? String, - additions: validStats ? (stats?["added"] as? Int).flatMap { $0 >= 0 ? $0 : nil } : nil, - deletions: validStats ? (stats?["removed"] as? Int).flatMap { $0 >= 0 ? $0 : nil } : nil) - } // Parse each picture once; an `image` block no decoder accepts falls back to a text entry. var parsedIndices = Set() let reported = content.prefix(100).enumerated().compactMap { index, item -> AgentImage? in @@ -149,24 +163,10 @@ public struct AgentToolDetails: Equatable, Sendable { let card = AgentDesktopCard(lithe["claudeDesktop"]) { desktopCard = card } - // The pinned Claude adapter forwards the SDK's public FileWriteOutput - // in tool metadata. Prefer its complete text over newline-less hunks; - // the explicit create type distinguishes a new file from an insertion. - if let metadata = update["_meta"] as? [String: Any], - let claude = metadata["claudeCode"] as? [String: Any], claude["toolName"] as? String == "Write", - let response = claude["toolResponse"] as? [String: Any], - let type = response["type"] as? String, let path = response["filePath"] as? String, !path.isEmpty, - let new = response["content"] as? String { - let old = response["originalFile"] as? String - if type == "create" || (type == "update" && old != nil) { - var reported = AgentFileChange(path: path) - reported.diffs = diffs.filter { $0.path == path } - let completeStats = !reported.diffs.contains(where: \.isTruncated) - diffs = [Diff(path: path, oldText: type == "create" ? nil : old.map(Self.bounded), - newText: Self.bounded(new), isTruncated: new.count > Self.textLimit || (old?.count ?? 0) > Self.textLimit, - operation: type == "create" ? "add" : "update", - additions: completeStats ? reported.additions : nil, deletions: completeStats ? reported.deletions : nil)] - } + // Agent Host restates normalized diff evidence whenever an update determines it. + if let metadata = update["_meta"] as? [String: Any], let lithe = metadata["lithe"] as? [String: Any], + let reported = lithe["diffs"] as? [[String: Any]] { + diffs = reported.compactMap(Diff.init(evidence:)) } } diff --git a/macos/Tests/LitheTests/AgentActivityPresentationTests.swift b/macos/Tests/LitheTests/AgentActivityPresentationTests.swift index 092ec8a1cb..8a5d30a0cb 100644 --- a/macos/Tests/LitheTests/AgentActivityPresentationTests.swift +++ b/macos/Tests/LitheTests/AgentActivityPresentationTests.swift @@ -510,7 +510,8 @@ struct AgentActivityPresentationTests { private func editedFile(path: String = "a.txt") -> AgentConversationMessage { var result = AgentConversationMessage(id: "edit-\(path)", role: .tool, text: "Edit \(path)", toolStatus: .completed) - result.toolDetails.merge(["kind": "edit", "content": [["type": "diff", "path": path, "oldText": "before", "newText": "after"]]]) + result.toolDetails.merge((["kind": "edit"] as [String: Any]) + .merging(AgentEditEvidenceTestSupport.diffContent(path: path, old: "before", new: "after")) { $1 }) return result } diff --git a/macos/Tests/LitheTests/AgentActivityTests.swift b/macos/Tests/LitheTests/AgentActivityTests.swift index b8a5c60304..3283469823 100644 --- a/macos/Tests/LitheTests/AgentActivityTests.swift +++ b/macos/Tests/LitheTests/AgentActivityTests.swift @@ -27,7 +27,8 @@ struct AgentActivityTests { #expect(change.diffs.first?.newText == new) #expect(change.diffs.first?.operation == operation) message.toolDetails.merge(["status": "completed"]) - #expect(message.toolDetails.diffs == change.diffs) + #expect(message.toolDetails.diffs.map(\.newText) == change.diffs.map(\.newText)) + #expect(change.diffs.allSatisfy { $0.toolKind == "edit" }) } var unknown = AgentToolDetails() unknown.merge(["_meta": ["claudeCode": ["toolName": "Write", "toolResponse": [ @@ -67,17 +68,41 @@ struct AgentActivityTests { #expect(!AgentActivity(messages: [unknownCreation]).files[0].canRevert) var creation = unknownCreation creation.toolDetails.diffs[0].operation = "add" + creation.toolDetails.diffs[0].isRevertible = true #expect(AgentActivity(messages: [creation]).files[0].canRevert) - let oversized = tool("large", path: "a.txt", old: "before", new: String(repeating: "x", count: AgentToolDetails.textLimit + 1)) - #expect(oversized.toolDetails.diffs[0].isTruncated) - #expect(!AgentActivity(messages: [oversized]).files[0].canRevert) - details.merge(["content": (0..<101).map { _ in ["type": "diff", "path": "a.txt", "oldText": "before", "newText": "after"] }]) - #expect(details.diffs.count == 100) - #expect(details.diffs.allSatisfy { $0.isTruncated }, "Dropping reported hunks must also disable rollback") - details.merge(["content": []]) + details.merge(["content": [], "_meta": ["lithe": ["diffs": []]]]) #expect(details.diffs.isEmpty, "Explicit replacement must remove optimistic evidence") } + /// Limits and eligibility are the Host's verdict; Swift neither recounts + /// text nor parses raw diff content (AGT-08). + @Test func sharedHostEvidenceFixtureMapsWithoutRecountingText() throws { + let data = try Data(contentsOf: AgentEditEvidenceTestSupport.repositoryRoot() + .appendingPathComponent("shared/fixtures/agent/edit-review-v1.json")) + let fixture = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + let cases = try #require(fixture["evidence"] as? [[String: Any]]) + for entry in cases { + guard let expected = AgentEditEvidenceTestSupport.expand(entry["expected"] as Any) as? [[String: Any]] else { continue } + var update = try #require(AgentEditEvidenceTestSupport.expand(entry["update"] as Any) as? [String: Any]) + var meta = update["_meta"] as? [String: Any] ?? [:] + meta["lithe"] = ["diffs": expected] + update["_meta"] = meta + var details = AgentToolDetails() + details.merge(update) + #expect(details.diffs.count == expected.count, "\(entry["name"] ?? "")") + for (diff, evidence) in zip(details.diffs, expected) { + #expect(diff.newText == evidence["newText"] as? String) + #expect(diff.oldText == evidence["oldText"] as? String) + #expect(diff.isTruncated == evidence["truncated"] as? Bool) + #expect(diff.isRevertible == evidence["revertible"] as? Bool) + #expect(diff.additions == evidence["additions"] as? Int) + } + } + var raw = AgentToolDetails() + raw.merge(["content": [["type": "diff", "path": "a.txt", "oldText": "a", "newText": "b"]]]) + #expect(raw.diffs.isEmpty, "Raw ACP content without Host evidence is display-only") + } + @Test func keepingChangesAdvancesTheBaselineAndIsIsolatedByConversation() async throws { let connection = AgentConnectionModel(transport: ActivityUnusedTransport()) seed(connection, session: "one", id: "first", path: "a.txt", old: "A", new: "B") @@ -167,9 +192,9 @@ struct AgentActivityTests { } private func seed(_ connection: AgentConnectionModel, session: String, id: String, path: String, old: String, new: String) { - let update: [String: Any] = ["kind": "update", "sessionId": session, "update": [ + let update: [String: Any] = ["kind": "update", "sessionId": session, "update": ([ "sessionUpdate": "tool_call", "toolCallId": id, "title": "Edit file", "kind": "edit", "status": "completed", - "content": [["type": "diff", "path": path, "oldText": old, "newText": new]]]] + ] as [String: Any]).merging(AgentEditEvidenceTestSupport.diffContent(path: path, old: old, new: new)) { $1 }] let data = try! JSONSerialization.data(withJSONObject: update) connection.receive(String(decoding: data, as: UTF8.self)) } @@ -177,9 +202,8 @@ struct AgentActivityTests { private func tool(_ id: String, path: String, old: String?, new: String, status: AgentConversationMessage.ToolStatus = .completed, stats: Bool = false) -> AgentConversationMessage { var message = AgentConversationMessage(id: id, role: .tool, text: "Edit \(path)", toolStatus: status) - var diff: [String: Any] = ["type": "diff", "path": path, "oldText": old as Any, "newText": new] - if stats { diff["_meta"] = ["jetbrains": ["air": ["diffStats": ["version": 1, "added": 1, "removed": 1]]]] } - message.toolDetails.merge(["kind": "edit", "locations": [["path": path], ["path": path]], "content": [diff]]) + let evidence = AgentEditEvidenceTestSupport.diffContent(path: path, old: old, new: new, stats: stats ? (1, 1) : nil) + message.toolDetails.merge((["kind": "edit", "locations": [["path": path], ["path": path]]] as [String: Any]).merging(evidence) { $1 }) return message } } diff --git a/macos/Tests/LitheTests/AgentEditEvidenceTestSupport.swift b/macos/Tests/LitheTests/AgentEditEvidenceTestSupport.swift new file mode 100644 index 0000000000..1303aeb238 --- /dev/null +++ b/macos/Tests/LitheTests/AgentEditEvidenceTestSupport.swift @@ -0,0 +1,36 @@ +import Foundation + +/// Builds a tool update the way Agent Host presents it: the raw ACP diff plus +/// the Host's normalized `_meta.lithe.diffs` evidence. Swift never derives +/// evidence from raw content, so tests must supply the Host annotation. +enum AgentEditEvidenceTestSupport { + static func diffContent(path: String, old: String?, new: String, operation: String? = nil, + stats: (added: Int, removed: Int)? = nil) -> [String: Any] { + ["content": [["type": "diff", "path": path, "oldText": old as Any, "newText": new]], + "_meta": ["lithe": ["diffs": [evidence(path: path, old: old, new: new, operation: operation, stats: stats)]]]] + } + + static func evidence(path: String, old: String?, new: String, operation: String? = nil, + stats: (added: Int, removed: Int)? = nil, truncated: Bool = false) -> [String: Any] { + ["path": path, "oldText": old ?? NSNull(), "newText": new, "operation": operation ?? NSNull(), + "additions": stats?.added ?? NSNull(), "deletions": stats?.removed ?? NSNull(), "truncated": truncated, + "revertible": !truncated && (old != nil || operation == "add")] + } + + static func repositoryRoot(_ file: String = #filePath) -> URL { + URL(fileURLWithPath: file).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + } + + /// Expands the shared fixture's `{repeat, count, suffix?}` text generators. + static func expand(_ value: Any) -> Any { + if let object = value as? [String: Any] { + if let unit = object["repeat"] as? String, let count = object["count"] as? Int { + return String(repeating: unit, count: count) + (object["suffix"] as? String ?? "") + } + return object.mapValues(expand) + } + if let array = value as? [Any] { return array.map(expand) } + return value + } +} diff --git a/macos/Tests/LitheTests/AgentEditRestorerTests.swift b/macos/Tests/LitheTests/AgentEditRestorerTests.swift index bc4d31380c..aafefb1c17 100644 --- a/macos/Tests/LitheTests/AgentEditRestorerTests.swift +++ b/macos/Tests/LitheTests/AgentEditRestorerTests.swift @@ -42,7 +42,7 @@ struct AgentEditRestorerTests { let url = workspace.appendingPathComponent("a.txt") try Data([0xef, 0xbb, 0xbf] + Array("C\n".utf8)).write(to: url) let change = change([("A\n", "B\n"), ("B\n", "C\n")]) - try await MacAgentEditRestorer(fileOperations: files).restore(change, in: workspace) + try await MacAgentEditRestorer(fileOperations: files, planner: planner).restore(change, in: workspace) #expect(try Data(contentsOf: url) == Data([0xef, 0xbb, 0xbf] + Array("A\n".utf8))) } } @@ -51,7 +51,7 @@ struct AgentEditRestorerTests { try await withWorkspace { workspace, files in let url = workspace.appendingPathComponent("a.txt") try Data("prefix\nnew line\nsuffix\n".utf8).write(to: url) - try await MacAgentEditRestorer(fileOperations: files).restore(change([("old line", "new line")]), in: workspace) + try await MacAgentEditRestorer(fileOperations: files, planner: planner).restore(change([("old line", "new line")]), in: workspace) #expect(try String(contentsOf: url, encoding: .utf8) == "prefix\nold line\nsuffix\n") } } @@ -63,7 +63,7 @@ struct AgentEditRestorerTests { let bytes = Data(disk.utf8) try bytes.write(to: url) await #expect(throws: AgentEditRestoreError.self) { - try await MacAgentEditRestorer(fileOperations: files).restore(change([("before", reported)]), in: workspace) + try await MacAgentEditRestorer(fileOperations: files, planner: planner).restore(change([("before", reported)]), in: workspace) } #expect(try Data(contentsOf: url) == bytes) } @@ -74,12 +74,13 @@ struct AgentEditRestorerTests { try await withWorkspace { workspace, files in let url = workspace.appendingPathComponent("a.txt") var deleted = change([("original", "")]) - deleted.isDeletion = true - try await MacAgentEditRestorer(fileOperations: files).restore(deleted, in: workspace) + // A delete tool marks the operation-less diff as a deletion. + deleted.diffs[0].toolKind = "delete" + try await MacAgentEditRestorer(fileOperations: files, planner: planner).restore(deleted, in: workspace) #expect(try String(contentsOf: url, encoding: .utf8) == "original") try Data("new user file".utf8).write(to: url) await #expect(throws: AgentEditRestoreError.self) { - try await MacAgentEditRestorer(fileOperations: files).restore(deleted, in: workspace) + try await MacAgentEditRestorer(fileOperations: files, planner: planner).restore(deleted, in: workspace) } #expect(try String(contentsOf: url, encoding: .utf8) == "new user file") } @@ -92,12 +93,12 @@ struct AgentEditRestorerTests { var incomplete = change([("before", "after")]) incomplete.diffs[0].oldText = nil await #expect(throws: AgentEditRestoreError.self) { - try await MacAgentEditRestorer(fileOperations: files).restore(incomplete, in: workspace) + try await MacAgentEditRestorer(fileOperations: files, planner: planner).restore(incomplete, in: workspace) } incomplete.diffs[0].oldText = "before" incomplete.diffs[0].isTruncated = true await #expect(throws: AgentEditRestoreError.self) { - try await MacAgentEditRestorer(fileOperations: files).restore(incomplete, in: workspace) + try await MacAgentEditRestorer(fileOperations: files, planner: planner).restore(incomplete, in: workspace) } #expect(try String(contentsOf: url, encoding: .utf8) == "after") } @@ -116,7 +117,7 @@ struct AgentEditRestorerTests { var escaping = change([("before", "after")], path: path) escaping.diffs[0].path = path await #expect(throws: AgentEditRestoreError.self) { - try await MacAgentEditRestorer(fileOperations: files).restore(escaping, in: root) + try await MacAgentEditRestorer(fileOperations: files, planner: planner).restore(escaping, in: root) } } #expect(try String(contentsOf: target, encoding: .utf8) == "after") @@ -133,11 +134,11 @@ struct AgentEditRestorerTests { let adapter = ReviewFileOperations(native: files, recovered: recovered) try Data("user modified".utf8).write(to: url) await #expect(throws: AgentEditRestoreError.self) { - try await MacAgentEditRestorer(fileOperations: adapter).restore(created, in: workspace) + try await MacAgentEditRestorer(fileOperations: adapter, planner: planner).restore(created, in: workspace) } #expect(!files.fileExists(at: recovered)) try Data("created".utf8).write(to: url) - try await MacAgentEditRestorer(fileOperations: adapter).restore(created, in: workspace) + try await MacAgentEditRestorer(fileOperations: adapter, planner: planner).restore(created, in: workspace) #expect(!files.fileExists(at: url)) #expect(try String(contentsOf: recovered, encoding: .utf8) == "created") } @@ -150,7 +151,7 @@ struct AgentEditRestorerTests { let adapter = ReviewFileOperations(native: files, recovered: workspace.appendingPathComponent("recovered.txt"), concurrentText: "another writer") await #expect(throws: AgentEditRestoreError.self) { - try await MacAgentEditRestorer(fileOperations: adapter).restore(change([("before", "after")]), in: workspace) + try await MacAgentEditRestorer(fileOperations: adapter, planner: planner).restore(change([("before", "after")]), in: workspace) } #expect(try String(contentsOf: url, encoding: .utf8) == "another writer") } @@ -165,7 +166,7 @@ struct AgentEditRestorerTests { try FileManager.default.createSymbolicLink(at: url, withDestinationURL: target) let adapter = ReviewFileOperations(native: files, recovered: recovered) await #expect(throws: (any Error).self) { - try await MacAgentEditRestorer(fileOperations: adapter).restore(creation(), in: workspace) + try await MacAgentEditRestorer(fileOperations: adapter, planner: planner).restore(creation(), in: workspace) } #expect(try FileManager.default.destinationOfSymbolicLink(atPath: url.path) == target.path) #expect(try String(contentsOf: target, encoding: .utf8) == "created") @@ -184,7 +185,7 @@ struct AgentEditRestorerTests { guard case .saved = result else { throw AgentEditRestoreError.changed } }) await #expect(throws: AgentEditRestoreError.self) { - try await MacAgentEditRestorer(fileOperations: adapter).restore(creation(), in: workspace) + try await MacAgentEditRestorer(fileOperations: adapter, planner: planner).restore(creation(), in: workspace) } #expect(try String(contentsOf: url, encoding: .utf8) == "saved by editor") #expect(!files.fileExists(at: recovered)) @@ -203,7 +204,7 @@ struct AgentEditRestorerTests { return recovered }) await #expect(throws: AgentEditRestoreError.self) { - try await MacAgentEditRestorer(fileOperations: files).restore(creation(), in: workspace) + try await MacAgentEditRestorer(fileOperations: files, planner: planner).restore(creation(), in: workspace) } #expect(try String(contentsOf: url, encoding: .utf8) == "external version") #expect(!files.fileExists(at: recovered)) @@ -224,7 +225,7 @@ struct AgentEditRestorerTests { return recovered }) await #expect(throws: DocumentFileAccessError.symbolicLink) { - try await MacAgentEditRestorer(fileOperations: files).restore(creation(), in: workspace) + try await MacAgentEditRestorer(fileOperations: files, planner: planner).restore(creation(), in: workspace) } #expect(try FileManager.default.destinationOfSymbolicLink(atPath: url.path) == target.path) #expect(try String(contentsOf: target, encoding: .utf8) == "created") @@ -244,7 +245,7 @@ struct AgentEditRestorerTests { return recovered }) do { - try await MacAgentEditRestorer(fileOperations: files).restore(creation(), in: workspace) + try await MacAgentEditRestorer(fileOperations: files, planner: planner).restore(creation(), in: workspace) Issue.record("A conflict requiring manual recovery must not acknowledge rollback") } catch { #expect(error.localizedDescription.contains(recovered.path)) @@ -260,12 +261,57 @@ struct AgentEditRestorerTests { try Data("created".utf8).write(to: url) let files = MacWorkspaceFileOperations(moveToTrash: { _ in throw CocoaError(.fileWriteNoPermission) }) await #expect(throws: CocoaError.self) { - try await MacAgentEditRestorer(fileOperations: files).restore(creation(), in: workspace) + try await MacAgentEditRestorer(fileOperations: files, planner: planner).restore(creation(), in: workspace) } #expect(try String(contentsOf: url, encoding: .utf8) == "created") } } + @Test func lfEvidenceRevertsInsideACRLFFileWithoutTouchingOtherLines() async throws { + try await withWorkspace { workspace, files in + let url = workspace.appendingPathComponent("a.txt") + try Data("keep\r\nx\nafter\nend\r\n".utf8).write(to: url) + try await MacAgentEditRestorer(fileOperations: files, planner: planner) + .restore(change([("before\nend\n", "after\nend\n")]), in: workspace) + #expect(try String(contentsOf: url, encoding: .utf8) == "keep\r\nx\nbefore\r\nend\r\n") + } + } + + /// Bridge regression: every shared plan decodes to the same port outcome. + @Test func sharedReversePlanFixtureDecodesThroughTheCoreBridge() throws { + let data = try Data(contentsOf: AgentEditEvidenceTestSupport.repositoryRoot() + .appendingPathComponent("shared/fixtures/agent/edit-review-v1.json")) + let fixture = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + for entry in try #require(fixture["reversePlan"] as? [[String: Any]]) { + let request = try #require(entry["request"] as? [String: Any]) + let expected = try #require(entry["expected"] as? [String: Any]) + var change = AgentFileChange(path: "a.txt") + change.isPending = request["pending"] as? Bool ?? false + change.hasMissingDiff = request["missingEvidence"] as? Bool ?? false + change.diffs = try #require(request["diffs"] as? [[String: Any]]).map { diff in + var result = AgentToolDetails.Diff(path: "a.txt", oldText: diff["oldText"] as? String, + newText: diff["newText"] as? String ?? "", isTruncated: diff["truncated"] as? Bool ?? false, + isRevertible: true, operation: diff["operation"] as? String) + result.toolKind = diff["toolKind"] as? String + return result + } + let disk = request["disk"] as? String + let name = entry["name"] as? String ?? "" + switch (expected["action"] as? String, expected["reason"] as? String) { + case ("write", _): + #expect(try planner.reversePlan(for: change, disk: disk) == .write(expected["text"] as? String ?? ""), "\(name)") + case ("trash", _): #expect(try planner.reversePlan(for: change, disk: disk) == .trash, "\(name)") + case ("none", _): #expect(try planner.reversePlan(for: change, disk: disk) == AgentEditReversePlan.none, "\(name)") + case ("conflict", "incomplete"): + #expect(throws: AgentEditRestoreError.incomplete, "\(name)") { try planner.reversePlan(for: change, disk: disk) } + default: + #expect(throws: AgentEditRestoreError.changed, "\(name)") { try planner.reversePlan(for: change, disk: disk) } + } + } + } + + private var planner: RustAgentEditReversePlanner { RustAgentEditReversePlanner() } + private func creation() -> AgentFileChange { var created = change([("", "created")]) created.diffs[0].oldText = nil @@ -275,7 +321,7 @@ struct AgentEditRestorerTests { private func change(_ versions: [(String, String)], path: String = "a.txt") -> AgentFileChange { var result = AgentFileChange(path: path) - result.diffs = versions.map { .init(path: path, oldText: $0.0, newText: $0.1, isTruncated: false) } + result.diffs = versions.map { .init(path: path, oldText: $0.0, newText: $0.1, isTruncated: false, isRevertible: true) } return result } diff --git a/rust/lithe-agent-host/src/edit_review.rs b/rust/lithe-agent-host/src/edit_review.rs new file mode 100644 index 0000000000..c6fc8a4237 --- /dev/null +++ b/rust/lithe-agent-host/src/edit_review.rs @@ -0,0 +1,399 @@ +//! Agent edit evidence: one normalization of ACP diff reports and one rollback planner. +//! +//! The Host annotates every presented tool update that restates its diffs with +//! `_meta.lithe.diffs`, so both desktop products store identical evidence and +//! revert eligibility. Text limits count Unicode scalar values: Rust `char`, +//! Swift `unicodeScalars` and JavaScript code points agree on them, unlike +//! grapheme clusters or UTF-16 code units. Rollback planning is pure text work; +//! path containment, encoding, guarded writes and Trash stay with the platform. +//! Contract: `shared/contracts/agent-edit-review.md`. + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +/// Largest `oldText`/`newText` kept per diff, in Unicode scalar values. +pub const TEXT_LIMIT_SCALARS: usize = 32_768; +/// Content entries inspected per update; any beyond make every diff incomplete. +pub const CONTENT_LIMIT: usize = 100; +/// Appended to bounded text so a reader sees that the excerpt is shortened. +const TRUNCATION_MARKER: &str = "\n[...]"; + +/// One normalized diff of a tool update, as stored by both platforms. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DiffEvidence { + /// Path exactly as the Agent reported it; platforms resolve it in the workspace. + pub path: String, + /// Previous text, or `None` when the Agent reported none (insertion or creation). + pub old_text: Option, + /// Reported text after the edit; empty when the Agent omitted it. + pub new_text: String, + /// Explicit upstream operation (`add`, `delete`, `update`), never inferred. + pub operation: Option, + /// Upstream-reported added lines; `None` when the Agent did not report them. + pub additions: Option, + /// Upstream-reported removed lines; `None` when the Agent did not report them. + pub deletions: Option, + /// The texts are not a complete copy of what the Agent changed. + pub truncated: bool, + /// The evidence alone is sufficient to plan a rollback of this diff. + pub revertible: bool, +} + +/// Adds `_meta.lithe.diffs` to a `tool_call` or `tool_call_update` that restates +/// its diffs. Updates without diff information are left untouched, so platforms +/// keep earlier evidence exactly when the Agent sent none. +pub fn annotate(update: &mut Value) { + if !matches!( + update["sessionUpdate"].as_str(), + Some("tool_call" | "tool_call_update") + ) { + return; + } + let Some(diffs) = evidence(update) else { + return; + }; + let Ok(diffs) = serde_json::to_value(diffs) else { + return; + }; + if !update["_meta"].is_object() { + update["_meta"] = json!({}); + } + if !update["_meta"]["lithe"].is_object() { + update["_meta"]["lithe"] = json!({}); + } + update["_meta"]["lithe"]["diffs"] = diffs; +} + +/// Diff evidence an update determines, or `None` when it carries no diff information. +pub fn evidence(update: &Value) -> Option> { + let content = update["content"].as_array(); + let reported = content.map(|content| content_diffs(content)); + if let Some(written) = claude_write(update, reported.as_deref()) { + return Some(vec![written]); + } + reported +} + +fn content_diffs(content: &[Value]) -> Vec { + let overflow = content.len() > CONTENT_LIMIT; + content + .iter() + .take(CONTENT_LIMIT) + .filter(|entry| entry["type"] == "diff") + .filter_map(|entry| { + let path = entry["path"].as_str()?; + let old = entry["oldText"].as_str(); + let new = entry["newText"].as_str(); + let operation = entry["_meta"]["kind"].as_str().map(str::to_owned); + let stats = &entry["_meta"]["jetbrains"]["air"]["diffStats"]; + let stats_valid = stats["version"].as_i64() == Some(1); + let stat = |key: &str| stats_valid.then(|| stats[key].as_u64()).flatten(); + let truncated = overflow + || new.is_none() + || entry["isTruncated"].as_bool() == Some(true) + || old.is_some_and(exceeds_limit) + || new.is_some_and(exceeds_limit); + Some(diff( + path, + old, + new.unwrap_or(""), + operation, + (stat("added"), stat("removed")), + truncated, + )) + }) + .collect() +} + +/// The pinned Claude adapter forwards the SDK's public `FileWriteOutput`. Its +/// complete text replaces newline-less hunks, and its explicit `create` type is +/// the only proof that a null previous text means file creation. +fn claude_write(update: &Value, reported: Option<&[DiffEvidence]>) -> Option { + let claude = &update["_meta"]["claudeCode"]; + if claude["toolName"] != "Write" { + return None; + } + let response = &claude["toolResponse"]; + let path = response["filePath"].as_str().filter(|path| !path.is_empty())?; + let new = response["content"].as_str()?; + let old = response["originalFile"].as_str(); + let operation = match response["type"].as_str()? { + "create" => "add", + "update" if old.is_some() => "update", + _ => return None, + }; + let old = (operation == "update").then_some(old).flatten(); + // Statistics stay upstream-scoped: only complete hunks of the same update + // may describe the whole write. + let hunks: Vec<&DiffEvidence> = reported + .unwrap_or_default() + .iter() + .filter(|diff| diff.path == path) + .collect(); + let complete = !hunks.iter().any(|diff| diff.truncated); + let total = |field: fn(&DiffEvidence) -> Option| { + if !complete || hunks.is_empty() { + return None; + } + hunks + .iter() + .try_fold(0u64, |sum, diff| sum.checked_add(field(diff)?)) + }; + let stats = (total(|diff| diff.additions), total(|diff| diff.deletions)); + let truncated = exceeds_limit(new) || old.is_some_and(exceeds_limit); + Some(diff( + path, + old, + new, + Some(operation.to_owned()), + stats, + truncated, + )) +} + +fn diff( + path: &str, + old: Option<&str>, + new: &str, + operation: Option, + (additions, deletions): (Option, Option), + truncated: bool, +) -> DiffEvidence { + let revertible = is_revertible(truncated, old.is_some(), operation.as_deref()); + DiffEvidence { + path: path.to_owned(), + old_text: old.map(bounded), + new_text: bounded(new), + operation, + additions, + deletions, + truncated, + revertible, + } +} + +/// A null previous text is only reversible with explicit creation metadata, +/// because some Agents report an inserted excerpt the same way. +fn is_revertible(truncated: bool, has_old: bool, operation: Option<&str>) -> bool { + !truncated && (has_old || operation == Some("add")) +} + +fn exceeds_limit(text: &str) -> bool { + text.chars().nth(TEXT_LIMIT_SCALARS).is_some() +} + +fn bounded(text: &str) -> String { + match text.char_indices().nth(TEXT_LIMIT_SCALARS) { + Some((end, _)) => format!("{}{TRUNCATION_MARKER}", &text[..end]), + None => text.to_owned(), + } +} + +/// Payload of `agent.edits.reversePlan`: one file's evidence plus its disk text. +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReverseRequest { + /// Evidence in tool execution order; the newest diff is reversed first. + pub diffs: Vec, + /// Some tool that touched the file has not completed yet. + #[serde(default)] + pub pending: bool, + /// Some tool touched the file without diff evidence, or moved it. + #[serde(default)] + pub missing_evidence: bool, + /// Current decoded disk text, or `None` when the file does not exist. + pub disk: Option, +} + +/// One diff of [`ReverseRequest`], as stored from [`DiffEvidence`]. +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReverseDiff { + /// Previous text; `None` without creation metadata is not reversible. + pub old_text: Option, + /// Reported text after the edit. + pub new_text: String, + /// Explicit upstream operation of the diff. + #[serde(default)] + pub operation: Option, + /// ACP `kind` of the tool that reported the diff. A `delete` tool marks an + /// operation-less diff as a deletion. + #[serde(default)] + pub tool_kind: Option, + /// The diff texts are incomplete. + pub truncated: bool, +} + +/// What the platform must do to reverse one file's Agent edits. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "action", rename_all = "camelCase")] +pub enum ReversePlan { + /// Write `text` with the platform's guarded write, keeping the disk encoding. + Write { + /// Restored text, in the disk's dominant line ending where text was matched. + text: String, + }, + /// Move the existing file to recoverable Trash; it did not exist before. + Trash, + /// The disk already matches the state before the edits. + None, + /// Rollback is unsafe; nothing may be written. + Conflict { + /// Stable reason code, localized by the platform. + reason: ConflictReason, + }, +} + +/// Stable rollback conflict codes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ConflictReason { + /// The evidence is pending, missing, truncated or lacks original content. + Incomplete, + /// The disk no longer matches the evidence (edited, missing or ambiguous). + Changed, +} + +/// Plans a rollback of one file's edits, newest first. +/// +/// Matching tolerates LF evidence against CRLF files: ACP diffs carry LF while +/// a document read keeps the disk's line endings. Only the matched span is +/// rewritten, in the disk's dominant line ending, so unrelated lines keep theirs. +pub fn reverse_plan(request: &ReverseRequest) -> ReversePlan { + let conflict = |reason| ReversePlan::Conflict { reason }; + let eligible = !request.pending + && !request.missing_evidence + && !request.diffs.is_empty() + && request.diffs.iter().all(|diff| { + is_revertible( + diff.truncated, + diff.old_text.is_some(), + diff.operation.as_deref(), + ) + }); + if !eligible { + return conflict(ConflictReason::Incomplete); + } + let mut restored = request.disk.clone(); + for diff in request.diffs.iter().rev() { + let deletion = match diff.operation.as_deref() { + Some(operation) => operation == "delete", + None => diff.tool_kind.as_deref() == Some("delete"), + }; + restored = match (deletion, diff.old_text.as_deref(), restored) { + // A deleted file is restored only while its path is still free. + (true, Some(old), None) => Some(old.to_owned()), + (true, _, _) => return conflict(ConflictReason::Changed), + // Creation: remove only the exact created content. + (false, None, Some(current)) if canonical(¤t).0 == canonical(&diff.new_text).0 => { + None + } + (false, None, _) => return conflict(ConflictReason::Changed), + (false, Some(old), Some(current)) => { + match unique_replacement(¤t, &diff.new_text, old) { + Some(text) => Some(text), + None => return conflict(ConflictReason::Changed), + } + } + (false, Some(_), None) => return conflict(ConflictReason::Changed), + }; + } + match (restored, request.disk.as_deref()) { + (None, None) => ReversePlan::None, + (None, Some(_)) => ReversePlan::Trash, + (Some(text), Some(disk)) if text == disk => ReversePlan::None, + (Some(text), _) => ReversePlan::Write { text }, + } +} + +/// Replaces exactly one occurrence of `new` in `current` with `old`. +/// Complete snapshots match verbatim; excerpts must be nonempty and unambiguous, +/// including overlapping occurrences. +fn unique_replacement(current: &str, new: &str, old: &str) -> Option { + if current == new { + return Some(old.to_owned()); + } + if new.is_empty() { + return None; + } + let ending = dominant_line_ending(current); + let disk_new = with_line_ending(new, ending); + let disk_old = with_line_ending(old, ending); + if let Some(start) = unique_occurrence(current, &disk_new)? { + return Some(splice(current, start, start + disk_new.len(), &disk_old)); + } + // Mixed line endings defeat the exact match; compare canonically and map + // the matched span back to original byte offsets. + let (canonical_current, offsets) = canonical(current); + let canonical_new = canonical(new).0; + let start = unique_occurrence(&canonical_current, &canonical_new)??; + let end = start + canonical_new.len(); + let original = |index: usize| offsets.get(index).copied().unwrap_or(current.len()); + Some(splice(current, original(start), original(end), &disk_old)) +} + +/// `Some(Some(index))` for one match, `Some(None)` for none, `None` for several. +fn unique_occurrence(haystack: &str, needle: &str) -> Option> { + let Some(first) = haystack.find(needle) else { + return Some(None); + }; + // Resume one character later so overlapping repeats count as ambiguous. + let next = first + haystack[first..].chars().next().map_or(1, char::len_utf8); + if haystack[next..].contains(needle) { + None + } else { + Some(Some(first)) + } +} + +fn splice(text: &str, start: usize, end: usize, replacement: &str) -> String { + format!("{}{replacement}{}", &text[..start], &text[end..]) +} + +/// LF-normalized text plus, per canonical byte, its original byte offset. +fn canonical(text: &str) -> (String, Vec) { + let mut normalized = String::with_capacity(text.len()); + let mut offsets = Vec::with_capacity(text.len()); + let bytes = text.as_bytes(); + let mut index = 0; + while index < bytes.len() { + if bytes[index] == b'\r' { + offsets.push(index); + normalized.push('\n'); + index += if bytes.get(index + 1) == Some(&b'\n') { + 2 + } else { + 1 + }; + continue; + } + let character = text[index..].chars().next().unwrap_or_default(); + for _ in 0..character.len_utf8() { + offsets.push(index); + } + normalized.push(character); + index += character.len_utf8(); + } + (normalized, offsets) +} + +fn dominant_line_ending(text: &str) -> &'static str { + if text.contains("\r\n") { + "\r\n" + } else { + "\n" + } +} + +fn with_line_ending(text: &str, ending: &str) -> String { + let normalized = canonical(text).0; + if ending == "\n" { + normalized + } else { + normalized.replace('\n', ending) + } +} + +#[cfg(test)] +mod tests; diff --git a/rust/lithe-agent-host/src/edit_review/tests.rs b/rust/lithe-agent-host/src/edit_review/tests.rs new file mode 100644 index 0000000000..c4c35ae38b --- /dev/null +++ b/rust/lithe-agent-host/src/edit_review/tests.rs @@ -0,0 +1,125 @@ +use super::*; + +fn fixture() -> Value { + serde_json::from_str(include_str!( + "../../../../shared/fixtures/agent/edit-review-v1.json" + )) + .expect("edit review fixture is JSON") +} + +/// Expands `{repeat, count, suffix?}` text generators used by the shared fixture. +fn expand(value: &Value) -> Value { + match value { + Value::Object(object) if object.contains_key("repeat") => { + let unit = object["repeat"].as_str().expect("repeat text"); + let count = object["count"].as_u64().expect("repeat count") as usize; + let suffix = object.get("suffix").and_then(Value::as_str).unwrap_or(""); + Value::String(unit.repeat(count) + suffix) + } + Value::Object(object) => Value::Object( + object + .iter() + .map(|(key, value)| (key.clone(), expand(value))) + .collect(), + ), + Value::Array(items) => Value::Array(items.iter().map(expand).collect()), + other => other.clone(), + } +} + +#[test] +fn shared_evidence_fixture_matches_host_annotation() { + let fixture = fixture(); + assert_eq!(fixture["textLimitScalars"], TEXT_LIMIT_SCALARS); + assert_eq!(fixture["contentLimit"], CONTENT_LIMIT); + for case in fixture["evidence"].as_array().expect("evidence cases") { + let name = case["name"].as_str().unwrap_or_default(); + let mut update = expand(&case["update"]); + let original = update.clone(); + annotate(&mut update); + let expected = expand(&case["expected"]); + if expected.is_null() { + assert_eq!(update, original, "{name}: update must stay untouched"); + } else { + assert_eq!(update["_meta"]["lithe"]["diffs"], expected, "{name}"); + // Annotation adds evidence without rewriting the raw ACP fields. + assert_eq!(update["content"], original["content"], "{name}"); + } + } +} + +#[test] +fn shared_reverse_plan_fixture_matches_planner() { + let fixture = fixture(); + for case in fixture["reversePlan"].as_array().expect("reverse plan cases") { + let name = case["name"].as_str().unwrap_or_default(); + let request: ReverseRequest = + serde_json::from_value(expand(&case["request"])).expect(name); + let plan = serde_json::to_value(reverse_plan(&request)).expect(name); + assert_eq!(plan, expand(&case["expected"]), "{name}"); + } +} + +#[test] +fn content_beyond_the_entry_limit_marks_every_diff_incomplete() { + let mut content = vec![json!({"type": "diff", "path": "a.txt", "oldText": "a", "newText": "b"})]; + content.extend((0..CONTENT_LIMIT).map(|_| json!({"type": "content", "content": {"type": "text", "text": "x"}}))); + let diffs = evidence(&json!({"sessionUpdate": "tool_call", "content": content})).expect("diffs"); + assert_eq!(diffs.len(), 1); + assert!(diffs[0].truncated && !diffs[0].revertible); +} + +#[test] +fn existing_lithe_metadata_is_preserved() { + let mut update = json!({ + "sessionUpdate": "tool_call_update", + "content": [{"type": "diff", "path": "a.txt", "oldText": "a", "newText": "b"}], + "_meta": {"lithe": {"claudeDesktop": {"kind": "card"}}, "other": 1} + }); + annotate(&mut update); + assert_eq!(update["_meta"]["lithe"]["claudeDesktop"]["kind"], "card"); + assert_eq!(update["_meta"]["other"], 1); + assert_eq!(update["_meta"]["lithe"]["diffs"][0]["newText"], "b"); +} + +#[test] +fn canonical_match_maps_multibyte_offsets_back_to_the_original() { + // A lone CR and multibyte text before the match must not shift the span. + let request = ReverseRequest { + diffs: vec![ReverseDiff { + old_text: Some("旧\n".into()), + new_text: "新\n".into(), + operation: None, + tool_kind: None, + truncated: false, + }], + pending: false, + missing_evidence: false, + disk: Some("😀\r前\r\n新\n后".into()), + }; + assert_eq!( + reverse_plan(&request), + ReversePlan::Write { text: "😀\r前\r\n旧\r\n后".into() } + ); +} + +#[test] +fn presented_acp_fixture_edits_carry_host_evidence() { + // The platform event fixture shows presented updates; removing the Host + // annotation and presenting again must reproduce them exactly. + let fixture: Value = serde_json::from_str(include_str!( + "../../../../shared/fixtures/agent/acp-events-v1.json" + )) + .expect("ACP event fixture is JSON"); + for name in ["fileEdit", "claudeFileCreated", "claudeFileWriteUpdated"] { + let presented = &fixture["events"][name]["update"]; + let mut raw = presented.clone(); + let meta = raw["_meta"].as_object_mut().expect("annotated metadata"); + meta.remove("lithe"); + if meta.is_empty() { + raw.as_object_mut().expect("update").remove("_meta"); + } + annotate(&mut raw); + assert_eq!(&raw, presented, "{name}"); + } +} diff --git a/rust/lithe-core/src/agent/edits.rs b/rust/lithe-core/src/agent/edits.rs new file mode 100644 index 0000000000..90fb03271a --- /dev/null +++ b/rust/lithe-core/src/agent/edits.rs @@ -0,0 +1,14 @@ +//! Typed Agent edit rollback planning. Evidence rules belong to Agent Host; +//! platforms own path containment, encoding, guarded writes and Trash. + +use crate::protocol::{cancellation, CoreError, ErrorCode}; +use lithe_agent_host::edit_review; +use serde_json::Value; + +/// Plans `agent.edits.reversePlan` without touching the file system. +/// Rollback conflicts are successful plans; only malformed payloads fail. +pub(crate) fn reverse_plan(request: edit_review::ReverseRequest) -> Result { + cancellation::check()?; + serde_json::to_value(edit_review::reverse_plan(&request)) + .map_err(|issue| CoreError::new(ErrorCode::Unknown, issue.to_string())) +} diff --git a/shared/fixtures/agent/edit-review-v1.json b/shared/fixtures/agent/edit-review-v1.json new file mode 100644 index 0000000000..285855fc39 --- /dev/null +++ b/shared/fixtures/agent/edit-review-v1.json @@ -0,0 +1,1087 @@ +{ + "description": "Agent edit evidence normalization (Host annotation `_meta.lithe.diffs`) and `agent.edits.reversePlan`. Text values may be {repeat, count, suffix?} and expand to repeat×count followed by suffix. Limits count Unicode scalar values.", + "textLimitScalars": 32768, + "contentLimit": 100, + "evidence": [ + { + "name": "plain diff", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "a.txt", + "oldText": "one", + "newText": "two" + } + ] + }, + "expected": [ + { + "path": "a.txt", + "oldText": "one", + "newText": "two", + "operation": null, + "additions": null, + "deletions": null, + "truncated": false, + "revertible": true + } + ] + }, + { + "name": "null previous text without creation metadata is an insertion, not revertible", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "a.txt", + "oldText": null, + "newText": "inserted" + } + ] + }, + "expected": [ + { + "path": "a.txt", + "oldText": null, + "newText": "inserted", + "operation": null, + "additions": null, + "deletions": null, + "truncated": false, + "revertible": false + } + ] + }, + { + "name": "explicit creation metadata makes null previous text revertible", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "a.txt", + "oldText": null, + "newText": "created", + "_meta": { + "kind": "add" + } + } + ] + }, + "expected": [ + { + "path": "a.txt", + "oldText": null, + "newText": "created", + "operation": "add", + "additions": null, + "deletions": null, + "truncated": false, + "revertible": true + } + ] + }, + { + "name": "missing newText keeps the hunk as incomplete evidence instead of dropping it", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "a.txt", + "oldText": "one" + }, + { + "type": "diff", + "path": "a.txt", + "oldText": "two", + "newText": "three" + } + ] + }, + "expected": [ + { + "path": "a.txt", + "oldText": "one", + "newText": "", + "operation": null, + "additions": null, + "deletions": null, + "truncated": true, + "revertible": false + }, + { + "path": "a.txt", + "oldText": "two", + "newText": "three", + "operation": null, + "additions": null, + "deletions": null, + "truncated": false, + "revertible": true + } + ] + }, + { + "name": "upstream truncation flag", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "a.txt", + "oldText": "one", + "newText": "two", + "isTruncated": true + } + ] + }, + "expected": [ + { + "path": "a.txt", + "oldText": "one", + "newText": "two", + "operation": null, + "additions": null, + "deletions": null, + "truncated": true, + "revertible": false + } + ] + }, + { + "name": "20000 emoji: 40000 UTF-16 units but 20000 scalars stay complete", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "a.txt", + "oldText": { + "repeat": "😀", + "count": 20000 + }, + "newText": "x" + } + ] + }, + "expected": [ + { + "path": "a.txt", + "oldText": { + "repeat": "😀", + "count": 20000 + }, + "newText": "x", + "operation": null, + "additions": null, + "deletions": null, + "truncated": false, + "revertible": true + } + ] + }, + { + "name": "20000 combining sequences: 20000 graphemes but 40000 scalars are truncated", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "a.txt", + "oldText": "x", + "newText": { + "repeat": "é", + "count": 20000 + } + } + ] + }, + "expected": [ + { + "path": "a.txt", + "oldText": "x", + "newText": { + "repeat": "é", + "count": 16384, + "suffix": "\n[...]" + }, + "operation": null, + "additions": null, + "deletions": null, + "truncated": true, + "revertible": false + } + ] + }, + { + "name": "CJK text exactly at the scalar limit stays complete", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "a.txt", + "oldText": { + "repeat": "汉", + "count": 32768 + }, + "newText": "x" + } + ] + }, + "expected": [ + { + "path": "a.txt", + "oldText": { + "repeat": "汉", + "count": 32768 + }, + "newText": "x", + "operation": null, + "additions": null, + "deletions": null, + "truncated": false, + "revertible": true + } + ] + }, + { + "name": "CJK text one scalar over the limit is truncated", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "a.txt", + "oldText": { + "repeat": "汉", + "count": 32769 + }, + "newText": "x" + } + ] + }, + "expected": [ + { + "path": "a.txt", + "oldText": { + "repeat": "汉", + "count": 32768, + "suffix": "\n[...]" + }, + "newText": "x", + "operation": null, + "additions": null, + "deletions": null, + "truncated": true, + "revertible": false + } + ] + }, + { + "name": "version 1 diff statistics are kept", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "a.txt", + "oldText": "a", + "newText": "b", + "_meta": { + "jetbrains": { + "air": { + "diffStats": { + "version": 1, + "added": 3, + "removed": 2 + } + } + } + } + } + ] + }, + "expected": [ + { + "path": "a.txt", + "oldText": "a", + "newText": "b", + "operation": null, + "additions": 3, + "deletions": 2, + "truncated": false, + "revertible": true + } + ] + }, + { + "name": "unknown statistics versions stay unknown", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "a.txt", + "oldText": "a", + "newText": "b", + "_meta": { + "jetbrains": { + "air": { + "diffStats": { + "version": 2, + "added": 3, + "removed": 2 + } + } + } + } + } + ] + }, + "expected": [ + { + "path": "a.txt", + "oldText": "a", + "newText": "b", + "operation": null, + "additions": null, + "deletions": null, + "truncated": false, + "revertible": true + } + ] + }, + { + "name": "Claude Write create replaces newline-less hunks", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "w.txt", + "oldText": null, + "newText": "fragment" + } + ], + "_meta": { + "claudeCode": { + "toolName": "Write", + "toolResponse": { + "type": "create", + "filePath": "w.txt", + "content": "whole\nfile\n" + } + } + } + }, + "expected": [ + { + "path": "w.txt", + "oldText": null, + "newText": "whole\nfile\n", + "operation": "add", + "additions": null, + "deletions": null, + "truncated": false, + "revertible": true + } + ] + }, + { + "name": "Claude Write update keeps complete statistics of the same update", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "w.txt", + "oldText": "a", + "newText": "b", + "_meta": { + "jetbrains": { + "air": { + "diffStats": { + "version": 1, + "added": 1, + "removed": 1 + } + } + } + } + } + ], + "_meta": { + "claudeCode": { + "toolName": "Write", + "toolResponse": { + "type": "update", + "filePath": "w.txt", + "content": "b\n", + "originalFile": "a\n" + } + } + } + }, + "expected": [ + { + "path": "w.txt", + "oldText": "a\n", + "newText": "b\n", + "operation": "update", + "additions": 1, + "deletions": 1, + "truncated": false, + "revertible": true + } + ] + }, + { + "name": "Claude Write update without the original file is ignored", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "diff", + "path": "w.txt", + "oldText": "a", + "newText": "b" + } + ], + "_meta": { + "claudeCode": { + "toolName": "Write", + "toolResponse": { + "type": "update", + "filePath": "w.txt", + "content": "b\n" + } + } + } + }, + "expected": [ + { + "path": "w.txt", + "oldText": "a", + "newText": "b", + "operation": null, + "additions": null, + "deletions": null, + "truncated": false, + "revertible": true + } + ] + }, + { + "name": "content without diffs clears the evidence", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "content": [ + { + "type": "content", + "content": { + "type": "text", + "text": "done" + } + } + ] + }, + "expected": [] + }, + { + "name": "an update without content keeps earlier evidence", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "tool-1", + "status": "completed", + "title": "Edit" + }, + "expected": null + }, + { + "name": "non-tool updates are not annotated", + "update": { + "sessionUpdate": "agent_message_chunk", + "content": [ + { + "type": "diff", + "path": "a.txt", + "oldText": "a", + "newText": "b" + } + ] + }, + "expected": null + } + ], + "reversePlan": [ + { + "name": "reverses chained edits newest first around unrelated text", + "request": { + "diffs": [ + { + "oldText": "one", + "newText": "two", + "operation": null, + "toolKind": null, + "truncated": false + }, + { + "oldText": "two", + "newText": "three", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "before\nthree\nafter" + }, + "expected": { + "action": "write", + "text": "before\none\nafter" + } + }, + { + "name": "complete snapshot matches verbatim", + "request": { + "diffs": [ + { + "oldText": "A\n", + "newText": "B\n", + "operation": null, + "toolKind": null, + "truncated": false + }, + { + "oldText": "B\n", + "newText": "C\n", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "C\n" + }, + "expected": { + "action": "write", + "text": "A\n" + } + }, + { + "name": "LF evidence reverses inside a CRLF file", + "request": { + "diffs": [ + { + "oldText": "before\n", + "newText": "after\n", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "before\r\nafter\r\n" + }, + "expected": { + "action": "write", + "text": "before\r\nbefore\r\n" + } + }, + { + "name": "LF snapshot reverses a CRLF file", + "request": { + "diffs": [ + { + "oldText": "before\n", + "newText": "after\n", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "after\r\n" + }, + "expected": { + "action": "write", + "text": "before\r\n" + } + }, + { + "name": "mixed line endings rewrite only the matched span", + "request": { + "diffs": [ + { + "oldText": "before\nend\n", + "newText": "after\nend\n", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "keep\r\nx\nafter\nend\r\n" + }, + "expected": { + "action": "write", + "text": "keep\r\nx\nbefore\r\nend\r\n" + } + }, + { + "name": "ambiguous excerpt is a conflict", + "request": { + "diffs": [ + { + "oldText": "old", + "newText": "new", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "new new" + }, + "expected": { + "action": "conflict", + "reason": "changed" + } + }, + { + "name": "missing excerpt is a conflict", + "request": { + "diffs": [ + { + "oldText": "old", + "newText": "new", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "unrelated" + }, + "expected": { + "action": "conflict", + "reason": "changed" + } + }, + { + "name": "overlapping exact excerpts are ambiguous", + "request": { + "diffs": [ + { + "oldText": "x", + "newText": "aba", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "ababa" + }, + "expected": { + "action": "conflict", + "reason": "changed" + } + }, + { + "name": "overlapping canonical excerpts are ambiguous", + "request": { + "diffs": [ + { + "oldText": "x", + "newText": "a\nb\na", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "a\nb\r\na\nb\r\na" + }, + "expected": { + "action": "conflict", + "reason": "changed" + } + }, + { + "name": "empty excerpt never matches", + "request": { + "diffs": [ + { + "oldText": "x", + "newText": "", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "abc" + }, + "expected": { + "action": "conflict", + "reason": "changed" + } + }, + { + "name": "insertion without creation metadata is incomplete", + "request": { + "diffs": [ + { + "oldText": null, + "newText": "inserted", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "a inserted" + }, + "expected": { + "action": "conflict", + "reason": "incomplete" + } + }, + { + "name": "creation removes only the exact created content", + "request": { + "diffs": [ + { + "oldText": null, + "newText": "created", + "operation": "add", + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "created" + }, + "expected": { + "action": "trash" + } + }, + { + "name": "creation matches across line endings", + "request": { + "diffs": [ + { + "oldText": null, + "newText": "created\n", + "operation": "add", + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "created\r\n" + }, + "expected": { + "action": "trash" + } + }, + { + "name": "edited creation is a conflict", + "request": { + "diffs": [ + { + "oldText": null, + "newText": "created", + "operation": "add", + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "created and edited" + }, + "expected": { + "action": "conflict", + "reason": "changed" + } + }, + { + "name": "deletion restores a still missing path", + "request": { + "diffs": [ + { + "oldText": "deleted", + "newText": "", + "operation": "delete", + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": null + }, + "expected": { + "action": "write", + "text": "deleted" + } + }, + { + "name": "deletion never overwrites a recreated path", + "request": { + "diffs": [ + { + "oldText": "deleted", + "newText": "", + "operation": "delete", + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "recreated" + }, + "expected": { + "action": "conflict", + "reason": "changed" + } + }, + { + "name": "tool-level delete kind marks an operation-less diff as deletion", + "request": { + "diffs": [ + { + "oldText": "original", + "newText": "", + "operation": null, + "toolKind": "delete", + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": null + }, + "expected": { + "action": "write", + "text": "original" + } + }, + { + "name": "explicit update operation wins over a delete tool kind", + "request": { + "diffs": [ + { + "oldText": "old", + "newText": "new", + "operation": "update", + "toolKind": "delete", + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "new" + }, + "expected": { + "action": "write", + "text": "old" + } + }, + { + "name": "editing a missing file is a conflict", + "request": { + "diffs": [ + { + "oldText": "old", + "newText": "new", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": null + }, + "expected": { + "action": "conflict", + "reason": "changed" + } + }, + { + "name": "created then deleted needs no change", + "request": { + "diffs": [ + { + "oldText": null, + "newText": "tmp", + "operation": "add", + "toolKind": null, + "truncated": false + }, + { + "oldText": "tmp", + "newText": "", + "operation": "delete", + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": null + }, + "expected": { + "action": "none" + } + }, + { + "name": "restoring identical text needs no write", + "request": { + "diffs": [ + { + "oldText": "same", + "newText": "same", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": false, + "disk": "same" + }, + "expected": { + "action": "none" + } + }, + { + "name": "pending tools are incomplete", + "request": { + "diffs": [ + { + "oldText": "old", + "newText": "new", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": true, + "missingEvidence": false, + "disk": "new" + }, + "expected": { + "action": "conflict", + "reason": "incomplete" + } + }, + { + "name": "missing or moved evidence is incomplete", + "request": { + "diffs": [ + { + "oldText": "old", + "newText": "new", + "operation": null, + "toolKind": null, + "truncated": false + } + ], + "pending": false, + "missingEvidence": true, + "disk": "new" + }, + "expected": { + "action": "conflict", + "reason": "incomplete" + } + }, + { + "name": "truncated evidence is incomplete", + "request": { + "diffs": [ + { + "oldText": "old", + "newText": "new", + "operation": null, + "toolKind": null, + "truncated": true + } + ], + "pending": false, + "missingEvidence": false, + "disk": "new" + }, + "expected": { + "action": "conflict", + "reason": "incomplete" + } + }, + { + "name": "no diffs is incomplete", + "request": { + "diffs": [], + "pending": false, + "missingEvidence": false, + "disk": "new" + }, + "expected": { + "action": "conflict", + "reason": "incomplete" + } + } + ] +} diff --git a/windows/tauri/src/features/agent/services/agent-edit-review.test.ts b/windows/tauri/src/features/agent/services/agent-edit-review.test.ts index 52a4f0adfd..57bf75afd9 100644 --- a/windows/tauri/src/features/agent/services/agent-edit-review.test.ts +++ b/windows/tauri/src/features/agent/services/agent-edit-review.test.ts @@ -1,81 +1,97 @@ import { describe, expect, test } from "bun:test"; +import evidenceFixture from "../../../../../../shared/fixtures/agent/edit-review-v1.json"; import { createConversation, upsertToolMessage } from "../types/agent.types"; -import { agentFileChanges, canRevertAgentChange, reverseAgentChange } from "./agent-edit-review"; +import { agentFileChanges, agentReversePlanRequest, canRevertAgentChange } from "./agent-edit-review"; + +type Evidence = { path: string; oldText: string | null; newText: string; operation: string | null; truncated: boolean; revertible: boolean }; + +/** Host-presented tool update: raw ACP diff plus the Host's `_meta.lithe.diffs`. */ +function hostDiff(oldText: string | null, newText: string, options: { operation?: string; truncated?: boolean } = {}) { + const truncated = options.truncated ?? false; + const evidence: Evidence = { path: "sample.txt", oldText, newText, operation: options.operation ?? null, truncated, + revertible: !truncated && (oldText !== null || options.operation === "add") }; + return { content: [{ type: "diff", path: "sample.txt", oldText, newText }], _meta: { lithe: { diffs: [evidence] } } }; +} function transcript(updates: Record[]) { return updates.reduce((conversation, update, index) => upsertToolMessage(conversation, String(index), { status: "completed", kind: "edit", ...update, }), createConversation()).messages; } -const diff = (oldText: string | null, newText: string, operation?: string) => ({ - type: "diff", path: "sample.txt", oldText, newText, _meta: { kind: operation }, -}); + +/** Expands the shared fixture's `{repeat, count, suffix?}` text generators. */ +function expand(value: unknown): unknown { + if (Array.isArray(value)) return value.map(expand); + if (value && typeof value === "object") { + const object = value as Record; + if (typeof object.repeat === "string" && typeof object.count === "number") { + return object.repeat.repeat(object.count) + (typeof object.suffix === "string" ? object.suffix : ""); + } + return Object.fromEntries(Object.entries(object).map(([key, entry]) => [key, expand(entry)])); + } + return value; +} describe("Agent edit review", () => { - test("reverses consecutive edits newest first without touching surrounding content", () => { - const [change] = agentFileChanges(transcript([ - { content: [diff("one", "two")] }, { content: [diff("two", "three")] }, - ])); - expect(reverseAgentChange(change, "before\nthree\nafter")).toBe("before\none\nafter"); - }); - test("reverses LF ACP edits against a CRLF Windows document", () => { - const [change] = agentFileChanges(transcript([{ content: [diff("before\n", "after\n")] }])); - expect(reverseAgentChange(change, "before\r\nafter\r\n")).toBe("before\r\nbefore\r\n"); - expect(reverseAgentChange(change, "after\r\n")).toBe("before\r\n"); + test("stores Host evidence verbatim without recounting UTF-16 units", () => { + for (const entry of evidenceFixture.evidence) { + const expected = expand(entry.expected) as Evidence[] | null; + if (expected === null) continue; + const update = expand(entry.update) as Record; + const meta = (update._meta ?? {}) as Record; + const [message] = transcript([{ ...update, _meta: { ...meta, lithe: { diffs: expected } } }]); + const diffs = message.role === "tool" ? message.toolDetails.diffs ?? [] : []; + expect(diffs.map((diff) => [diff.newText, diff.oldText, diff.incomplete, diff.revertible])) + .toEqual(expected.map((diff) => [diff.newText, diff.oldText, diff.truncated, diff.revertible])); + } }); - test("rejects ambiguous excerpts and external disk changes", () => { - const [change] = agentFileChanges(transcript([{ content: [diff("old", "new")] }])); - expect(() => reverseAgentChange(change, "new new")).toThrow("agent.edits.changed"); - expect(() => reverseAgentChange(change, "unrelated")).toThrow("agent.edits.changed"); + test("raw ACP diff content without Host evidence is display-only", () => { + const [message] = transcript([{ content: [{ type: "diff", path: "sample.txt", oldText: "a", newText: "b" }] }]); + expect(message.role === "tool" ? message.toolDetails.diffs ?? [] : null).toEqual([]); }); - test("rejects overlapping exact excerpts instead of reverting the wrong occurrence", () => { - const [change] = agentFileChanges(transcript([{ content: [diff("x", "aba")] }])); - expect(() => reverseAgentChange(change, "ababa")).toThrow("agent.edits.changed"); - }); - test("rejects overlapping excerpts after normalizing mixed line endings", () => { - const [change] = agentFileChanges(transcript([{ content: [diff("x", "a\nb\na")] }])); - // Mixed LF/CRLF prevents an exact match; the canonical matches overlap. - expect(() => reverseAgentChange(change, "a\nb\r\na\nb\r\na")).toThrow("agent.edits.changed"); + test("builds the shared reverse plan request in execution order with tool kinds", () => { + const [change] = agentFileChanges(transcript([ + { content: hostDiff("one", "two").content, _meta: hostDiff("one", "two")._meta }, + { kind: "delete", ...hostDiff("two", "") }, + ])); + expect(agentReversePlanRequest(change, "two")).toEqual({ + diffs: [ + { oldText: "one", newText: "two", operation: null, toolKind: "edit", truncated: false }, + { oldText: "two", newText: "", operation: null, toolKind: "delete", truncated: false }, + ], + pending: false, + missingEvidence: false, + disk: "two", + }); }); test("an insertion with no original content is not proof of file creation", () => { - const [change] = agentFileChanges(transcript([{ content: [diff(null, "inserted")] }])); - expect(canRevertAgentChange(change)).toBe(false); - }); - test("creation can remove only the exact created content", () => { - const [change] = agentFileChanges(transcript([{ content: [diff(null, "created", "add")] }])); - expect(reverseAgentChange(change, "created")).toBeNull(); - expect(() => reverseAgentChange(change, "created and edited")).toThrow(); - }); - test("deletion restores only to a still missing destination", () => { - const [change] = agentFileChanges(transcript([{ kind: "delete", content: [diff("deleted", "", "delete")] }])); - expect(reverseAgentChange(change, null)).toBe("deleted"); - expect(() => reverseAgentChange(change, "recreated")).toThrow(); + expect(canRevertAgentChange(agentFileChanges(transcript([hostDiff(null, "inserted")]))[0])).toBe(false); + expect(canRevertAgentChange(agentFileChanges(transcript([hostDiff(null, "created", { operation: "add" })]))[0])).toBe(true); }); test("pending, moved and truncated evidence cannot be reverted", () => { for (const update of [ - { status: "in_progress", content: [diff("old", "new")] }, - { kind: "move", content: [diff("old", "new")] }, - { content: [{ ...diff("old", "new"), isTruncated: true }] }, - { content: [diff("a".repeat(40_000), "new")] }, + { status: "in_progress", ...hostDiff("old", "new") }, + { kind: "move", ...hostDiff("old", "new") }, + hostDiff("old", "new", { truncated: true }), ]) expect(canRevertAgentChange(agentFileChanges(transcript([update]))[0])).toBe(false); + const [moved] = agentFileChanges(transcript([{ kind: "move", ...hostDiff("old", "new") }])); + expect(agentReversePlanRequest(moved, "new").missingEvidence).toBe(true); }); test("failed and interrupted tool effects are excluded", () => { - expect(agentFileChanges(transcript(["failed", "interrupted"].map((status) => ({ status, content: [diff("old", "new")] }))))).toEqual([]); + expect(agentFileChanges(transcript(["failed", "interrupted"].map((status) => ({ status, ...hostDiff("old", "new") }))))).toEqual([]); }); test("keeping an exact prefix preserves new edits and invalidates replaced evidence", () => { - const first = { content: [diff("one", "two")] }; + const first = hostDiff("one", "two"); const initial = agentFileChanges(transcript([first]))[0]; const reviewed = { "sample.txt": initial.versions }; expect(agentFileChanges(transcript([first]), reviewed)).toEqual([]); - const [later] = agentFileChanges(transcript([first, { content: [diff("two", "three")] }]), reviewed); - expect(later.diffs).toHaveLength(1); - expect(reverseAgentChange(later, "three")).toBe("two"); - expect(agentFileChanges(transcript([{ content: [diff("one", "changed replay")] }]), reviewed)).toHaveLength(1); + const [later] = agentFileChanges(transcript([first, hostDiff("two", "three")]), reviewed); + expect(later.diffs.map((diff) => diff.oldText)).toEqual(["two"]); + expect(agentFileChanges(transcript([hostDiff("one", "changed replay")]), reviewed)).toHaveLength(1); }); - test("Claude Write metadata replaces partial hunks with complete file evidence", () => { - const [change] = agentFileChanges(transcript([{ content: [diff(null, "fragment")], - _meta: { claudeCode: { toolName: "Write", toolResponse: { type: "create", filePath: "sample.txt", content: "whole\nfile\n" } } }, - }])); - expect(reverseAgentChange(change, "whole\nfile\n")).toBeNull(); + test("an update without Host evidence keeps earlier evidence", () => { + const [change] = agentFileChanges(transcript([hostDiff("one", "two")]).map((message) => + message.role === "tool" ? upsertToolMessage({ ...createConversation(), messages: [message] }, "0", { rawOutput: "saved" }).messages[0] : message)); + expect(change.diffs.map((diff) => diff.newText)).toEqual(["two"]); }); }); diff --git a/windows/tauri/src/features/agent/services/agent-edit-review.ts b/windows/tauri/src/features/agent/services/agent-edit-review.ts index 8276b15477..178ceeec6b 100644 --- a/windows/tauri/src/features/agent/services/agent-edit-review.ts +++ b/windows/tauri/src/features/agent/services/agent-edit-review.ts @@ -1,9 +1,17 @@ import type { AgentConversationMessage, AgentToolDiff } from "../types/agent.types"; +/** Host evidence plus the ACP kind of the tool that reported it. */ +export interface AgentFileChangeDiff extends AgentToolDiff { + toolKind: string | null; +} + export interface AgentFileChange { path: string; versions: string[]; - diffs: AgentToolDiff[]; + diffs: AgentFileChangeDiff[]; + /** A tool touched the file without diff evidence, or moved it. */ + missingEvidence: boolean; + /** Presentation: some evidence is missing or truncated. */ incomplete: boolean; pending: boolean; } @@ -19,10 +27,11 @@ export function agentFileChanges(messages: AgentConversationMessage[], reviewed: const paths = new Set([...diffs.map((diff) => diff.path), ...details.locations.map((location) => location.path)]); for (const path of paths) { const selected = diffs.filter((diff) => diff.path === path); - const file = files.get(path) ?? { path, versions: [], diffs: [], incomplete: false, pending: false }; + const file = files.get(path) ?? { path, versions: [], diffs: [], missingEvidence: false, incomplete: false, pending: false }; file.versions.push(JSON.stringify([tool.id, tool.toolStatus, details.kind, selected])); - file.diffs.push(...selected); - file.incomplete ||= selected.length === 0 || details.kind === "move" || selected.some((diff) => diff.incomplete); + file.diffs.push(...selected.map((diff) => ({ ...diff, toolKind: details.kind }))); + file.missingEvidence ||= selected.length === 0 || details.kind === "move"; + file.incomplete ||= file.missingEvidence || selected.some((diff) => diff.incomplete); file.pending ||= tool.toolStatus !== "completed"; files.set(path, file); } @@ -38,67 +47,25 @@ export function agentFileChanges(messages: AgentConversationMessage[], reviewed: }); } +/** Agent Host decides per-diff eligibility; `agent.edits.reversePlan` rechecks it. */ export function canRevertAgentChange(change: AgentFileChange): boolean { - return !change.pending && !change.incomplete && change.diffs.length > 0 && - change.diffs.every((diff) => !diff.incomplete && (diff.oldText !== null || diff.operation === "add")); -} - -function normalizeLineEndings(value: string): string { - return value.replace(/\r\n?/g, "\n"); + return !change.pending && !change.missingEvidence && change.diffs.length > 0 && change.diffs.every((diff) => diff.revertible); } -function dominantLineEnding(value: string): "\n" | "\r\n" { - return value.includes("\r\n") ? "\r\n" : "\n"; +/** Payload of `agent.edits.reversePlan` (shared/contracts/agent-edit-review.md). */ +export function agentReversePlanRequest(change: AgentFileChange, disk: string | null) { + return { + diffs: change.diffs.map((diff) => ({ oldText: diff.oldText, newText: diff.newText, operation: diff.operation, + toolKind: diff.toolKind, truncated: diff.incomplete })), + pending: change.pending, + missingEvidence: change.missingEvidence, + disk, + }; } -function withLineEnding(value: string, lineEnding: "\n" | "\r\n"): string { - return normalizeLineEndings(value).replace(/\n/g, lineEnding); -} - -function uniqueTextReplacement(restored: string, newText: string, oldText: string): string | null { - if (restored === newText) return oldText; - - const lineEnding = dominantLineEnding(restored); - const diskNewText = withLineEnding(newText, lineEnding); - const diskOldText = withLineEnding(oldText, lineEnding); - const exactIndex = restored.indexOf(diskNewText); - if (exactIndex >= 0) { - if (restored.indexOf(diskNewText, exactIndex + 1) >= 0) return null; - return restored.slice(0, exactIndex) + diskOldText + restored.slice(exactIndex + diskNewText.length); - } - - // ACP diffs use LF while Windows document reads may return CRLF. Compare - // canonically, but preserve the disk's line-ending style in the result. - const canonicalRestored = normalizeLineEndings(restored); - const canonicalNewText = normalizeLineEndings(newText); - const canonicalIndex = canonicalRestored.indexOf(canonicalNewText); - if (canonicalIndex < 0 || canonicalRestored.indexOf(canonicalNewText, canonicalIndex + 1) >= 0) { - return null; - } - return withLineEnding( - canonicalRestored.slice(0, canonicalIndex) + normalizeLineEndings(oldText) + canonicalRestored.slice(canonicalIndex + canonicalNewText.length), - lineEnding, - ); -} - -/** Reverse complete snapshots or exactly one nonempty excerpt, newest first. */ -export function reverseAgentChange(change: AgentFileChange, disk: string | null): string | null { - if (!canRevertAgentChange(change)) throw new Error("agent.edits.incomplete"); - let restored = disk; - for (const diff of [...change.diffs].reverse()) { - if (diff.operation === "delete") { - if (restored !== null || diff.oldText === null) throw new Error("agent.edits.changed"); - restored = diff.oldText; - } else if (diff.oldText === null) { - if (diff.operation !== "add" || restored === null || normalizeLineEndings(restored) !== normalizeLineEndings(diff.newText)) { - throw new Error("agent.edits.changed"); - } - restored = null; - } else if (restored !== null) { - const replacement = uniqueTextReplacement(restored, diff.newText, diff.oldText); - if (replacement === null) throw new Error("agent.edits.changed"); - restored = replacement; - } - } - return restored; -} +/** Core rollback plan; conflicts carry a stable reason instead of a write. */ +export type AgentReversePlan = + | { action: "write"; text: string } + | { action: "trash" } + | { action: "none" } + | { action: "conflict"; reason: "changed" | "incomplete" }; diff --git a/windows/tauri/src/features/agent/types/agent.types.ts b/windows/tauri/src/features/agent/types/agent.types.ts index 0b57446fc5..3c32b48c1a 100644 --- a/windows/tauri/src/features/agent/types/agent.types.ts +++ b/windows/tauri/src/features/agent/types/agent.types.ts @@ -84,12 +84,19 @@ export interface AgentToolContent { text: string; } +/** + * Agent Host evidence (`_meta.lithe.diffs`, shared/contracts/agent-edit-review.md). + * Text limits and revert eligibility come from the Host and are never recounted here. + */ export interface AgentToolDiff { path: string; oldText: string | null; newText: string; operation: string | null; + /** Host verdict: the texts are not a complete copy of the change. */ incomplete: boolean; + /** Host verdict: this diff alone is sufficient to plan a rollback. */ + revertible: boolean; } /** Bounded presentation of ACP tool evidence; partial updates replace present fields only. */ @@ -460,16 +467,6 @@ export function mergeToolDetails(details: AgentToolDetails, update: Record { - if (!isRecord(entry) || entry.type !== "diff" || typeof entry.path !== "string") return []; - const oldText = asString(entry.oldText); - const newText = asString(entry.newText); - return [{ path: entry.path, oldText: oldText === null ? null : bounded(oldText), - newText: bounded(newText ?? ""), operation: isRecord(entry._meta) ? asString(entry._meta.kind) : null, - incomplete: newText === null || entry.isTruncated === true || content.length > TOOL_CONTENT_LIMIT || - (oldText?.length ?? 0) > AGENT_TOOL_TEXT_LIMIT || (newText?.length ?? 0) > AGENT_TOOL_TEXT_LIMIT }]; - }); merged.content = update.content.slice(0, TOOL_CONTENT_LIMIT).flatMap((entry): AgentToolContent[] => { if (!isRecord(entry)) return []; if (entry.type === "content") { @@ -490,22 +487,20 @@ export function mergeToolDetails(details: AgentToolDetails, update: Record AGENT_TOOL_TEXT_LIMIT || (oldText?.length ?? 0) > AGENT_TOOL_TEXT_LIMIT }]; - } + const lithe = metadata && isRecord(metadata.lithe) ? metadata.lithe : null; + if (lithe && Array.isArray(lithe.diffs)) merged.diffs = lithe.diffs.flatMap(hostDiffEvidence); return merged; } +function hostDiffEvidence(entry: unknown): AgentToolDiff[] { + if (!isRecord(entry) || typeof entry.path !== "string" || typeof entry.newText !== "string" || + typeof entry.truncated !== "boolean" || typeof entry.revertible !== "boolean") return []; + return [{ path: entry.path, oldText: asString(entry.oldText), newText: entry.newText, + operation: asString(entry.operation), incomplete: entry.truncated, revertible: entry.revertible }]; +} + function toolStatusOf(update: Record): AgentToolStatus | null { const status = asString(update.status); switch (status) { diff --git a/windows/tauri/src/platform/agent-edit-restorer.test.ts b/windows/tauri/src/platform/agent-edit-restorer.test.ts new file mode 100644 index 0000000000..53e50f8381 --- /dev/null +++ b/windows/tauri/src/platform/agent-edit-restorer.test.ts @@ -0,0 +1,64 @@ +import { beforeEach, describe, expect, mock, test } from "bun:test"; + +/** + * Host stubs for the rollback flow. Core planning is stubbed by `plan`; the + * shared fixture proves the planner itself in Rust and through the macOS bridge. + */ +let plan: unknown = { action: "none" }; +let disk: { content: string; encoding: string; identity: string } | null = { content: "new", encoding: "UTF-8", identity: "id-1" }; +const calls: [string, unknown][] = []; +const invoke = mock(async (command: string, args?: unknown): Promise => { + calls.push([command, args]); + if (command === "resolve_agent_document_path") return "C:/work/sample.txt"; + if (command === "agent.edits.reversePlan") return plan; + if (command === "save_agent_document") return { status: "saved" }; + if (command === "trash_agent_document") return null; + throw new Error(`Unexpected command: ${command}`); +}); +const tauriCoreModule = await import("@/platform/tauri-core"); +mock.module("@/platform/tauri-core", () => ({ ...tauriCoreModule, invoke })); +const documentFilesModule = await import("@/platform/document-files"); +mock.module("@/platform/document-files", () => ({ ...documentFilesModule, readDocumentFileDetails: async () => disk })); +const { restoreAgentEdit } = await import("./agent-edit-restorer"); + +const change = { + path: "sample.txt", versions: [], pending: false, missingEvidence: false, incomplete: false, + diffs: [{ path: "sample.txt", oldText: "old", newText: "new", operation: null, incomplete: false, revertible: true, toolKind: "edit" }], +}; +const commands = () => calls.map(([command]) => command); + +describe("Agent edit restorer", () => { + beforeEach(() => { + calls.length = 0; + disk = { content: "new", encoding: "UTF-8", identity: "id-1" }; + }); + test("sends evidence and disk text to Core and writes the planned text", async () => { + plan = { action: "write", text: "old" }; + await restoreAgentEdit("C:/work", change, () => false); + expect(calls.find(([command]) => command === "agent.edits.reversePlan")?.[1]).toEqual({ + diffs: [{ oldText: "old", newText: "new", operation: null, toolKind: "edit", truncated: false }], + pending: false, missingEvidence: false, disk: "new", + }); + expect(calls.find(([command]) => command === "save_agent_document")?.[1]).toMatchObject({ content: "old", expectedContent: "new", expectedIdentity: "id-1" }); + }); + test("trashes a created file only through the guarded native command", async () => { + plan = { action: "trash" }; + await restoreAgentEdit("C:/work", change, () => false); + expect(commands()).toContain("trash_agent_document"); + expect(commands()).not.toContain("save_agent_document"); + }); + test("a plan without changes writes nothing", async () => { + plan = { action: "none" }; + await restoreAgentEdit("C:/work", change, () => false); + expect(commands()).not.toContain("save_agent_document"); + expect(commands()).not.toContain("trash_agent_document"); + }); + test("conflicts surface the stable localized key and never write", async () => { + for (const [reason, key] of [["changed", "agent.edits.changed"], ["incomplete", "agent.edits.incomplete"]]) { + calls.length = 0; + plan = { action: "conflict", reason }; + await expect(restoreAgentEdit("C:/work", change, () => false)).rejects.toThrow(key); + expect(commands()).not.toContain("save_agent_document"); + } + }); +}); diff --git a/windows/tauri/src/platform/agent-edit-restorer.ts b/windows/tauri/src/platform/agent-edit-restorer.ts index 0c1b32755d..a35fbb31bb 100644 --- a/windows/tauri/src/platform/agent-edit-restorer.ts +++ b/windows/tauri/src/platform/agent-edit-restorer.ts @@ -1,6 +1,6 @@ import { invoke } from "./tauri-core"; import { readDocumentFileDetails, type DocumentSaveOutcome } from "./document-files"; -import { reverseAgentChange, type AgentFileChange } from "@/features/agent/services/agent-edit-review"; +import { agentReversePlanRequest, type AgentFileChange, type AgentReversePlan } from "@/features/agent/services/agent-edit-review"; export async function resolveAgentEditPath(workspace: string, path: string): Promise { return invoke("resolve_agent_document_path", { workspace, path }); @@ -11,15 +11,18 @@ export async function restoreAgentEdit(workspace: string, change: AgentFileChang const path = await resolveAgentEditPath(workspace, change.path); if (isDirty(path)) throw new Error("agent.edits.dirty"); const disk = await readDocumentFileDetails(path); - const restored = reverseAgentChange(change, disk?.content ?? null); + // Core owns matching, line endings, deletion and conflict rules. + const plan = await invoke("agent.edits.reversePlan", agentReversePlanRequest(change, disk?.content ?? null)); + if (plan.action === "conflict") throw new Error(plan.reason === "incomplete" ? "agent.edits.incomplete" : "agent.edits.changed"); + if (plan.action === "none") return; if (isDirty(path)) throw new Error("agent.edits.dirty"); // Resolve again after asynchronous reads; parent links must still point inside this workspace. if (await resolveAgentEditPath(workspace, change.path) !== path || isDirty(path)) throw new Error("agent.edits.changed"); - if (restored === null) { + if (plan.action === "trash") { if (!disk) throw new Error("agent.edits.changed"); await invoke("trash_agent_document", { workspace, path, expectedIdentity: disk.identity }); } else { - const result = await invoke("save_agent_document", { workspace, path, content: restored, + const result = await invoke("save_agent_document", { workspace, path, content: plan.text, expectedContent: disk?.content ?? null, encoding: disk?.encoding ?? "UTF-8", expectedIdentity: disk?.identity }); if (result.status !== "saved") throw new Error("agent.edits.changed"); } From a510a3685ace45b7bccca2646c2d4f86be20142a Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Wed, 4 Nov 2026 22:34:13 -0800 Subject: [PATCH 4/8] =?UTF-8?q?feat(agent):=20AGT-07/09=20=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E8=B0=83=E7=94=A8=E7=BB=9F=E8=AE=A1=E4=B8=8E=E4=B8=8B?= =?UTF-8?q?=E4=B8=80=E8=BD=AE=E9=85=8D=E7=BD=AE=E4=B8=8B=E6=B2=89=E5=88=B0?= =?UTF-8?q?=20Agent=20Host?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 统计归约与会话配置应用统一在 lithe-agent-host(model_call_statistics、next_turn_config),两端删除各自实现并按共享夹具验证。 Co-Authored-By: Claude Opus 5.5 --- ...026-09-25-shared-acp-agent-conversation.md | 4 +- ...2026-10-13-agent-model-call-observation.md | 9 +- ...0-17-windows-agent-connection-ownership.md | 2 +- .../Application/AgentConnectionModel.swift | 84 +- .../Application/AgentConversationState.swift | 1 - .../Application/AgentModelCall.swift | 107 +- .../AgentConversationPresentationTests.swift | 12 +- .../AgentModelCallTestSupport.swift | 25 + .../AgentNextTurnConfigurationTests.swift | 83 +- .../AgentSessionSelectorLayoutTests.swift | 2 +- .../src/model_call_statistics.rs | 252 ++++ rust/lithe-agent-host/src/model_calls.rs | 4 +- rust/lithe-agent-host/src/next_turn_config.rs | 227 ++++ rust/lithe-agent-host/src/tests.rs | 38 + .../tests/claude_api_failure.rs | 1 + .../tests/codex_api_failure.rs | 1 + .../agent/model-call-statistics-v1.json | 409 ++++++ .../agent/next-turn-configuration-v1.json | 1118 +++++++++++++++++ .../agent-connection-model-switching.json | 11 +- .../features/agent-model-call-statistics.json | 11 +- .../components/agent-observed-statistics.tsx | 6 +- .../agent/stores/agent-connection-service.ts | 2 +- .../agent/stores/agent-connection.model.ts | 57 +- .../agent/stores/agent-parity.test.ts | 62 +- .../agent/types/agent-observations.test.ts | 39 +- .../agent/types/agent-observations.ts | 78 +- 26 files changed, 2394 insertions(+), 251 deletions(-) create mode 100644 macos/Tests/LitheTests/AgentModelCallTestSupport.swift create mode 100644 rust/lithe-agent-host/src/model_call_statistics.rs create mode 100644 rust/lithe-agent-host/src/next_turn_config.rs create mode 100644 shared/fixtures/agent/model-call-statistics-v1.json create mode 100644 shared/fixtures/agent/next-turn-configuration-v1.json diff --git a/.agents/notes/implemented/architecture/2026-09-25-shared-acp-agent-conversation.md b/.agents/notes/implemented/architecture/2026-09-25-shared-acp-agent-conversation.md index 6e889b5228..4ef7acaaac 100644 --- a/.agents/notes/implemented/architecture/2026-09-25-shared-acp-agent-conversation.md +++ b/.agents/notes/implemented/architecture/2026-09-25-shared-acp-agent-conversation.md @@ -167,11 +167,11 @@ macOS 的审批模式、模型和思考强度在等待、推理、输出、工 参考 [CC GUI 的输入栏选择器](https://github.com/zhukunpenglinyutong/jetbrains-cc-gui/blob/7bcd6c3803ec44944cef90f5bff0aa666cab99a2/webview/src/components/ChatInputBox/ButtonArea.tsx)在生成期间继续提供模式和模型回调,以及 [发送入口](https://github.com/zhukunpenglinyutong/jetbrains-cc-gui/blob/7bcd6c3803ec44944cef90f5bff0aa666cab99a2/webview/src/hooks/useMessageSender.ts)读取用户选择。Lithe 保留已有共享 Host 的忙碌边界:响应期间不发送 `setConfigOption`,只由当前会话的功能模型保存每个选项最后一次预选;重新选择已确认值取消该项预选。视图不另存配置队列,也不改本机 CLI 配置。 -正常结束、取消确认或本轮请求失败后,功能模型先提交模型,再按最新上游选项顺序提交剩余配置,每个请求确认后才提交下一个。换模型可能改变思考强度和速度目录,因此每一步都重新校验;拒绝、发送失败、能力消失或返回值未确认时,清除剩余预选,恢复已经确认的值并显示配置错误。等待全部确认期间继续阻止发送,不自动提交用户草稿。停止请求本身不能解除等待,也不能让新配置进入尚未结束的一轮。 +正常结束、取消确认或本轮请求失败后,产品把该会话全部预选连同最新已确认目录一次交给 Host(`applyNextTurnConfiguration`)。排序、校验和确认规则只在 Host 的 `rust/lithe-agent-host/src/next_turn_config.rs` 写一份,两端共用 `shared/fixtures/agent/next-turn-configuration-v1.json`:先提交模型,再按 Agent 目录顺序提交剩余配置(不按用户点击顺序),每个请求确认后才提交下一个。换模型可能改变思考强度和速度目录,因此每一步都用 Agent 最新返回的目录重新校验,已是当前值的跳过;能力消失(`unsupported`)、返回值未确认(`notConfirmed`)或请求失败(`requestFailed`,附上游原文)时停止,结果以一个 `nextTurnConfigured` 事件返回,已确认的配置保留生效。产品本地化失败码、清除剩余预选并显示配置错误。等待结果期间继续阻止发送,不自动提交用户草稿。停止请求本身不能解除等待,也不能让新配置进入尚未结束的一轮。本轮失败时,暂存的续写输入按该轮错误标记为失败、不自动作为新一轮发送,但预选配置仍然提交。2026-11(#1662 AGT-09)前两端各写一份:Windows 按点击顺序提交、不核对确认值、本轮失败时丢弃预选;macOS 本轮失败后会把续写输入自动发成新一轮。 正确做法:当前轮使用模型 A,用户选择 B 和 High;本轮结束后确认 B,再用 B 的最新目录确认 High,下一条消息才使用新值。不要这样做:仅移除控件的禁用条件并立即请求 `session/set_config_option`,或把本地预选直接覆盖到已确认配置中;前者可能影响当前工具授权且会被 Host 拒绝,后者会把失败当成成功。 -预选按项目、Agent 和会话隔离;切换标签不丢失,后台完成只提交该后台会话的配置。新的上游配置或模式通知只更新已确认状态,不覆盖用户的有效预选。断连清除未确认预选和请求关联,迟到确认不能恢复它们。代价是本轮结束与下一轮发送之间可能多出数次配置确认,且不兼容的新模型选项需要用户重新选择。该能力目前只接入 macOS;Windows 不据此标记完成。状态仅保存在会话内存中,不新增下载、缓存或工作树可复用资源,不写发行包,不影响代码签名和 Sparkle delta。 +预选按项目、Agent 和会话隔离;切换标签不丢失,后台完成只提交该后台会话的配置。新的上游配置或模式通知只更新已确认状态,不覆盖用户的有效预选。断连清除未确认预选和请求关联,迟到确认不能恢复它们。代价是本轮结束与下一轮发送之间可能多出数次配置确认,且不兼容的新模型选项需要用户重新选择。Windows 使用同一 Host 命令与事件。状态仅保存在会话内存中,不新增下载、缓存或工作树可复用资源,不写发行包,不影响代码签名和 Sparkle delta。 ### 思考、计划、斜杠命令与模式通知 diff --git a/.agents/notes/implemented/architecture/2026-10-13-agent-model-call-observation.md b/.agents/notes/implemented/architecture/2026-10-13-agent-model-call-observation.md index 3989dc1f52..3475f12134 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-agent-model-call-observation.md +++ b/.agents/notes/implemented/architecture/2026-10-13-agent-model-call-observation.md @@ -52,11 +52,14 @@ HTTP 请求不带 ACP 会话 ID。请求开始时,如果恰好只有一个未 代理在响应流结束时才上报调用,可能晚于 prompt 响应。Host 用 `CallsInFlight` 记录已归属但未上报的调用,在发出 `turnFinished` 前最多等 2 秒,保证每轮统计能收到本轮调用;超过这个上限仍未结束的流只计入会话统计,不会拖住回合结束:代理在请求开始时记下会话和 Host 的回合序号(generation),该回合发出 `turnFinished` 后才上报的调用带 `afterTurnFinished: true`,macOS 只把它记入会话,不会记到用户随后开始的下一轮。 -### 5. macOS 只聚合、不保存明细 +### 5. 统计口径只在 Host 写一份,产品只做加法 -`AgentModelCallTotals` 对会话和每轮做有界聚合(次数、失败数、非流式数、带用量的次数、时长、首 token、生成时间、用量、最近一次主请求构成),会话再长内存也不增长。 +每个 `modelCall` 事件都带 Host 计算的 `statistics`(`rust/lithe-agent-host/src/model_call_statistics.rs`,共享 fixture `shared/fixtures/agent/model-call-statistics-v1.json`):这次请求算几步、是否失败、是否算非流式回答、计入多少时长与首 token、生成速度的时间和 token,以及它是否代表当前上下文。两端只按事件顺序把这些贡献相加(计数相加、上报过的 reasoning 相加、出现的上下文覆盖旧值),不得再从 `call` 推导口径。2026-11(#1662 AGT-07)前两端各写一份:Windows 把 HTTP 500 的非流式请求也计入“非流式”,并把最后一次请求(包括辅助请求)的构成当作当前上下文。 -- 主请求的识别:Agent 一旦发送过工具定义,就只有带工具的请求更新上下文构成,不带工具的(例如生成标题)视为辅助请求;从不发送工具的 Agent 每次请求都更新,避免构成停在第一次请求。 +macOS 的 `AgentModelCallTotals` 与 Windows 的会话统计对会话和每轮做有界聚合(次数、失败数、非流式数、带用量的次数、时长、首 token、生成时间、用量、最近一次主请求构成),会话再长内存也不增长。 + +- 失败请求(状态码 ≥ 400,含传输失败的 502)计为失败的步,不计为非流式回答。 +- 主请求的识别(由 Host 按会话记忆):Agent 一旦发送过工具定义,就只有带工具的请求更新上下文构成,不带工具的(例如生成标题)视为辅助请求;从不发送工具的 Agent 每次请求都更新,避免构成停在第一次请求。 - 有调用缺少用量(流中断、服务商没给最终 usage)时,Token 合计只是下限,界面显示“≥”并说明缺了几次。 正确:会话卡片的“步”= 观测到的模型调用数;TPS = 流式调用的输出 token ÷(调用时长 − 首 token 时间)。 diff --git a/.agents/notes/implemented/architecture/2026-10-17-windows-agent-connection-ownership.md b/.agents/notes/implemented/architecture/2026-10-17-windows-agent-connection-ownership.md index e54777f588..764fa2d059 100644 --- a/.agents/notes/implemented/architecture/2026-10-17-windows-agent-connection-ownership.md +++ b/.agents/notes/implemented/architecture/2026-10-17-windows-agent-connection-ownership.md @@ -27,7 +27,7 @@ Windows Agent 面板的一次启动只对应一个 ACP 进程,进程身份由 - 切走前用 `captureSnapshot()` 保存当前可见状态,切回时 `restoreSnapshot()` 放回。恢复会清掉全部进程相关标记,`prepareConversation()` 因此走 `loadSession` 重新附着,用户看到的仍是原会话;工作区切换清空全部保留状态,避免跨项目串台。 - 发送条件包含 `pendingConfigToken == null`:会话设置还在确认时不接受新消息,界面沿用「准备中」提示。 - `draft` 与 `files` 由 `agent-surface.store` 按 Agent 与会话保存,`AgentComposer` 为受控组件;工具窗口与编辑区标签读取同一份草稿。新会话确认后迁移其草稿,历史加载失败不挪用其他会话的输入。 -- 响应中的模型、权限和 Effort 选择作为下一轮草稿配置;轮次完成后顺序提交并等待各自确认,全部成功才发送下一条消息。不能把菜单显示值提前当成上游已确认值。 +- 响应中的模型、权限和 Effort 选择作为下一轮草稿配置;轮次结束(含失败)后一次交给 Host 的 `applyNextTurnConfiguration`,由 Host 按共享规则排序、校验并逐项确认,收到成功的 `nextTurnConfigured` 才发送下一条消息。不能把菜单显示值提前当成上游已确认值。 - 附件校验在事件处理阶段先算出结果,成功后再写入状态;上限错误只显示提示,不改动原有草稿与附件。 - 文件菜单跨 Agent 添加附件时,先提交目标配置,再用提交返回的配置内容核对当前设置。连接服务返回本次启动实际生效的设置,包含自己保存的本机 CLI 地址与模型刷新;被取代、启动失败或刷新保存失败时返回空结果。菜单必须核对该结果与当前设置,允许本次刷新,但拒绝外部配置变更。保存会重新规范化并发布对象,不能拿保存前的对象引用当作修订身份;保存失败或工作区切换时,附件草稿保持不变。 - 子 Agent 的活动记录必须保留到终止,才能继续路由其输出和授权;只有已结束的展示记录限制为最近 64 条。正确做法是清理旧的终态记录后继续接收第 65 个子 Agent;不能因展示名额耗尽而忽略 Host 已挂起的授权。 diff --git a/macos/Sources/LitheAgentConversationModule/Application/AgentConnectionModel.swift b/macos/Sources/LitheAgentConversationModule/Application/AgentConnectionModel.swift index 5852b963d1..7c58ceecab 100644 --- a/macos/Sources/LitheAgentConversationModule/Application/AgentConnectionModel.swift +++ b/macos/Sources/LitheAgentConversationModule/Application/AgentConnectionModel.swift @@ -757,16 +757,18 @@ public final class AgentConnectionModel: ObservableObject { applyConfiguration(event["configOptions"], to: sessionID) conversations[sessionID]?.pendingConfigToken = nil applyPendingModeNotice(in: sessionID) - if let id = conversations[sessionID]?.pendingQueuedConfigID { - let requested = conversations[sessionID]?.queuedConfigValues[id] - let confirmed = conversations[sessionID]?.configOptions.first { $0.id == id }?.currentValue - conversations[sessionID]?.pendingQueuedConfigID = nil - guard requested == confirmed else { - failQueuedConfiguration(in: sessionID, message: "The Agent did not confirm the selected session setting.") - return - } - conversations[sessionID]?.queuedConfigValues[id] = nil - applyQueuedConfiguration(in: sessionID) + case "nextTurnConfigured": + guard let sessionID, let token, conversations[sessionID]?.pendingConfigToken == token else { return } + // Settings the Agent confirmed before a failure stay applied. + if event["configOptions"] != nil { applyConfiguration(event["configOptions"], to: sessionID) } + conversations[sessionID]?.pendingConfigToken = nil + applyPendingModeNotice(in: sessionID) + if let failure = event["failure"] as? String { + failQueuedConfiguration(in: sessionID, message: Self.nextTurnFailureMessage( + failure, upstream: event["message"] as? String)) + } else { + conversations[sessionID]?.queuedConfigValues.removeAll() + resumeContinuation(in: sessionID) } case "turnRetrying": guard let sessionID, @@ -823,7 +825,7 @@ public final class AgentConnectionModel: ObservableObject { case "modelCall": // Unattributed calls cannot be assigned to a session without guessing. guard let sessionID, conversations[sessionID] != nil, - let call = AgentModelCall.parse(event["call"]) else { return } + let call = AgentModelCall.parse(event["statistics"]) else { return } // A stream that outlived its turn must not count toward the next one. let afterTurn = event["afterTurnFinished"] as? Bool == true conversations[sessionID]?.recordModelCall(call, countsForActiveTurn: !afterTurn) @@ -932,6 +934,11 @@ public final class AgentConnectionModel: ObservableObject { conversations[sessionID]?.pendingPermissions.removeAll() conversations[sessionID]?.errorMessage = message updateAttention() + // A failed turn never starts a deferred supplement as a new prompt; + // the user's next-turn settings still apply. + if let supplement = continuations.removeValue(forKey: sessionID) { + setDelivery(.failed(message), messageID: supplement.messageID, in: sessionID) + } applyQueuedConfiguration(in: sessionID) } else { errorMessage = message @@ -1146,44 +1153,44 @@ public final class AgentConnectionModel: ObservableObject { applyNotice(notice, to: sessionID) } - /// Submit next-turn choices only after the Host has released this session's prompt. + /// Hand every next-turn choice to the Host once it has released this + /// session's prompt. The Host orders, revalidates, and confirms them. private func applyQueuedConfiguration(in sessionID: String) { guard let conversation = conversations[sessionID], conversation.isAttached, !conversation.isResponding, !conversation.isLoading, conversation.pendingConfigToken == nil else { return } - // A model acknowledgement can replace the available reasoning/speed choices. - // Revalidate each remaining choice against that latest complete option list. - let ordered = conversation.configOptions.filter { $0.category == "model" } - + conversation.configOptions.filter { $0.category != "model" } - for option in ordered { - guard let value = conversations[sessionID]?.queuedConfigValues[option.id] else { continue } - if option.currentValue == value { - conversations[sessionID]?.queuedConfigValues[option.id] = nil - continue - } - guard option.choices.contains(where: { $0.id == value }) else { - failQueuedConfiguration(in: sessionID, message: "The Agent no longer supports the selected session setting.") - return - } - let token = makeToken() - conversations[sessionID]?.pendingConfigToken = token - conversations[sessionID]?.pendingQueuedConfigID = option.id - if !sendCommand(["kind": "setConfigOption", "token": token, "sessionId": sessionID, - "configId": option.id, "value": value]) { - conversations[sessionID]?.pendingConfigToken = nil - failQueuedConfiguration(in: sessionID, message: errorMessage ?? AgentConversationError.notConnected.localizedDescription) - } + guard !conversation.queuedConfigValues.isEmpty else { + resumeContinuation(in: sessionID) return } - if conversations[sessionID]?.queuedConfigValues.isEmpty == false { - failQueuedConfiguration(in: sessionID, message: "The Agent no longer supports the selected session setting.") + let catalog: [[String: Any]] = conversation.configOptions.map { option in + var entry: [String: Any] = ["id": option.id, "currentValue": option.currentValue, + "choices": option.choices.map(\.id)] + if let category = option.category { entry["category"] = category } + return entry + } + let choices = conversation.queuedConfigValues.sorted { $0.key < $1.key } + .map { ["configId": $0.key, "value": $0.value] } + let token = makeToken() + conversations[sessionID]?.pendingConfigToken = token + if !sendCommand(["kind": "applyNextTurnConfiguration", "token": token, "sessionId": sessionID, + "catalog": catalog, "choices": choices]) { + conversations[sessionID]?.pendingConfigToken = nil + failQueuedConfiguration(in: sessionID, message: errorMessage ?? AgentConversationError.notConnected.localizedDescription) + } + } + + /// Localizes the Host's stable failure code; a failed request keeps the Agent's own message. + static func nextTurnFailureMessage(_ failure: String, upstream: String?) -> String { + switch failure { + case "notConfirmed": return L10n.string("The Agent did not confirm the selected session setting.") + case "requestFailed": return upstream ?? L10n.string("The Agent request failed.") + default: return L10n.string("The Agent no longer supports the selected session setting.") } - resumeContinuation(in: sessionID) } private func failQueuedConfiguration(in sessionID: String, message: String) { conversations[sessionID]?.queuedConfigValues.removeAll() - conversations[sessionID]?.pendingQueuedConfigID = nil conversations[sessionID]?.configurationError = message resumeContinuation(in: sessionID) } @@ -1556,7 +1563,6 @@ public final class AgentConnectionModel: ObservableObject { conversations[id]?.pendingSteeringToken = nil conversations[id]?.pendingConfigToken = nil conversations[id]?.queuedConfigValues.removeAll() - conversations[id]?.pendingQueuedConfigID = nil conversations[id]?.isLoading = false conversations[id]?.isAttached = false conversations[id]?.pendingPermissions.removeAll() diff --git a/macos/Sources/LitheAgentConversationModule/Application/AgentConversationState.swift b/macos/Sources/LitheAgentConversationModule/Application/AgentConversationState.swift index 2b50a15841..21a82d435d 100644 --- a/macos/Sources/LitheAgentConversationModule/Application/AgentConversationState.swift +++ b/macos/Sources/LitheAgentConversationModule/Application/AgentConversationState.swift @@ -135,7 +135,6 @@ public struct AgentConversation: Equatable, Sendable { public var pendingConfigToken: String? /// Choices for the next turn, separate from the Agent-confirmed configuration. var queuedConfigValues: [String: String] = [:] - var pendingQueuedConfigID: String? public var displayConfigOptions: [AgentSessionConfigOption] { configOptions.map { option in var displayed = option diff --git a/macos/Sources/LitheAgentConversationModule/Application/AgentModelCall.swift b/macos/Sources/LitheAgentConversationModule/Application/AgentModelCall.swift index ee3dca2f2f..fb22e55620 100644 --- a/macos/Sources/LitheAgentConversationModule/Application/AgentModelCall.swift +++ b/macos/Sources/LitheAgentConversationModule/Application/AgentModelCall.swift @@ -1,19 +1,11 @@ import Foundation -/// One provider request observed by the Host's opt-in loopback proxy. -/// Shape fixed by the `modelCall` event in `shared/fixtures/agent/acp-events-v1.json`. +/// The Host's accounting of one provider request observed by its opt-in +/// loopback proxy: the `statistics` of a `modelCall` event. The Host decides +/// which requests are steps, failures, non-streaming answers, or the current +/// context; this product only adds contributions in event order. +/// Shape fixed by `shared/fixtures/agent/model-call-statistics-v1.json`. public struct AgentModelCall: Decodable, Equatable, Sendable { - /// Provider counters normalized to disjoint input buckets. - public struct Usage: Codable, Equatable, Sendable { - public let inputTokens: UInt64 - public let cacheReadTokens: UInt64 - public let cacheWriteTokens: UInt64 - public let outputTokens: UInt64 - public let reasoningTokens: UInt64? - - public var promptTokens: UInt64 { inputTokens + cacheReadTokens + cacheWriteTokens } - } - /// Estimated split of the request prompt; see `scaledToUsage`. public struct Context: Codable, Equatable, Sendable { public let systemPromptTokens: UInt64 @@ -29,19 +21,23 @@ public struct AgentModelCall: Decodable, Equatable, Sendable { public var totalTokens: UInt64 { systemPromptTokens + toolTokens + mcpToolTokens + messageTokens } } - public let api: String - public let model: String? - public let status: Int - public let streaming: Bool - public let firstTokenMs: UInt64? + public let requests: Int + public let steps: Int + public let failedSteps: Int + public let nonStreamingSteps: Int public let durationMs: UInt64 - public let usage: Usage? + public let inputTokens: UInt64 + public let cacheReadTokens: UInt64 + public let cacheWriteTokens: UInt64 + public let outputTokens: UInt64 + public let reasoningTokens: UInt64? + public let callsWithUsage: Int + public let firstTokenMs: UInt64 + public let firstTokenCount: Int + public let generationMs: UInt64 + public let generatedTokens: UInt64 + /// Present only when this request describes the conversation's current prompt. public let context: Context? - /// Present only for a background request the Agent made for itself, such as - /// naming the session. Absent means an ordinary conversation step. - public var auxiliary: Bool? = nil - - public var isAuxiliary: Bool { auxiliary == true } static func parse(_ value: Any?) -> Self? { guard let value, JSONSerialization.isValidJSONObject(value), @@ -71,11 +67,8 @@ public struct AgentModelCallTotals: Codable, Equatable, Sendable { /// only these; the rest (e.g. interrupted streams) are missing from them. public private(set) var callsWithUsage = 0 public var hasUsage: Bool { callsWithUsage > 0 } - /// Composition of the latest main conversation request. + /// Composition of the request the Host last reported as the current context. public private(set) var latestContext: AgentModelCall.Context? - /// Once an Agent sends tool definitions, only requests that carry them are - /// main conversation requests; tool-less ones are auxiliary (e.g. titles). - private var sendsTools = false private var firstTokenTotal: TimeInterval = 0 private var firstTokenCount = 0 /// Streaming time after the first token, and the output produced in it. @@ -94,7 +87,7 @@ public struct AgentModelCallTotals: Codable, Equatable, Sendable { } /// Adds a later period's totals, e.g. this connection's calls onto the - /// persisted history of the session. The later composition wins. + /// persisted history of the session. A later composition replaces an earlier one. mutating func add(_ later: AgentModelCallTotals) { observedCallCount = requestCount + later.requestCount callCount += later.callCount @@ -108,51 +101,29 @@ public struct AgentModelCallTotals: Codable, Equatable, Sendable { if let reasoning = later.reasoningTokens { reasoningTokens = (reasoningTokens ?? 0) + reasoning } callsWithUsage += later.callsWithUsage if let context = later.latestContext { latestContext = context } - sendsTools = sendsTools || later.sendsTools firstTokenTotal += later.firstTokenTotal firstTokenCount += later.firstTokenCount generationTime += later.generationTime generatedTokens += later.generatedTokens } - private mutating func recordUsage(_ usage: AgentModelCall.Usage?) { - guard let usage else { return } - callsWithUsage += 1 - inputTokens += usage.inputTokens - cacheReadTokens += usage.cacheReadTokens - cacheWriteTokens += usage.cacheWriteTokens - outputTokens += usage.outputTokens - if let reasoning = usage.reasoningTokens { reasoningTokens = (reasoningTokens ?? 0) + reasoning } - } - + /// Adds one Host contribution. Every rule about what counts lives in the Host. mutating func record(_ call: AgentModelCall) { - observedCallCount = requestCount + 1 - if call.isAuxiliary { - // The tokens were really spent, but a title request is neither a step - // of the conversation nor a measure of its latency or generation speed. - recordUsage(call.usage) - return - } - callCount += 1 - if call.status >= 400 { failedCount += 1 } - if !call.streaming && call.status < 400 { nonStreamingCount += 1 } - let duration = Double(call.durationMs) / 1000 - self.duration += duration - recordUsage(call.usage) - if call.streaming, let firstToken = call.firstTokenMs.map({ Double($0) / 1000 }) { - firstTokenTotal += firstToken - firstTokenCount += 1 - if let output = call.usage?.outputTokens, duration > firstToken { - generationTime += duration - firstToken - generatedTokens += output - } - } - // Agents that never send tools keep refreshing from every request, so - // a growing conversation is not frozen at its first composition. - if let context = call.context { - let carriesTools = context.toolCount + context.mcpToolCount > 0 - if carriesTools { sendsTools = true } - if carriesTools || !sendsTools { latestContext = context } - } + observedCallCount = requestCount + call.requests + callCount += call.steps + failedCount += call.failedSteps + nonStreamingCount += call.nonStreamingSteps + duration += Double(call.durationMs) / 1000 + inputTokens += call.inputTokens + cacheReadTokens += call.cacheReadTokens + cacheWriteTokens += call.cacheWriteTokens + outputTokens += call.outputTokens + if let reasoning = call.reasoningTokens { reasoningTokens = (reasoningTokens ?? 0) + reasoning } + callsWithUsage += call.callsWithUsage + if let context = call.context { latestContext = context } + firstTokenTotal += Double(call.firstTokenMs) / 1000 + firstTokenCount += call.firstTokenCount + generationTime += Double(call.generationMs) / 1000 + generatedTokens += call.generatedTokens } } diff --git a/macos/Tests/LitheTests/AgentConversationPresentationTests.swift b/macos/Tests/LitheTests/AgentConversationPresentationTests.swift index 9749b48830..ed6dd0d52b 100644 --- a/macos/Tests/LitheTests/AgentConversationPresentationTests.swift +++ b/macos/Tests/LitheTests/AgentConversationPresentationTests.swift @@ -578,7 +578,7 @@ struct AgentConversationPresentationTests { conversation.completedTurns = [AgentTurnStatistics(id: "turn", startedAt: .now)] // Without proxy observations, steps and speed are absent rather than estimated. #expect(AgentSessionStatusPresentation.summary(conversation.sessionStatistics, locale: locale) == "1 turns") - let call = try #require(AgentModelCall.parse([ + let call = try #require(AgentModelCall.streamedStep([ "api": "anthropicMessages", "status": 200, "streaming": true, "firstTokenMs": 500, "durationMs": 2500, "usage": ["inputTokens": 100, "cacheReadTokens": 900, "cacheWriteTokens": 0, "outputTokens": 400], "context": ["systemPromptTokens": 100, "toolTokens": 200, "mcpToolTokens": 300, "messageTokens": 400, @@ -615,7 +615,7 @@ struct AgentConversationPresentationTests { @Test func contextBreakdownUsesReportedWindowInsteadOfNormalizingTheRequestToFull() throws { let locale = Locale(identifier: "en_US") - let context = try #require(AgentModelCall.parse([ + let context = try #require(AgentModelCall.streamedStep([ "api": "responses", "status": 200, "streaming": true, "durationMs": 100, "context": ["systemPromptTokens": 11700, "toolTokens": 33900, "messageTokens": 30300, "mcpToolTokens": 300, "toolCount": 18, "mcpToolCount": 2, "scaledToUsage": true] @@ -637,7 +637,7 @@ struct AgentConversationPresentationTests { let resourceURL = URL(fileURLWithPath: #filePath).deletingLastPathComponent() .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Resources") let bundle = try #require(Bundle(url: resourceURL)) - let composition = try #require(AgentModelCall.parse([ + let composition = try #require(AgentModelCall.streamedStep([ "api": "responses", "status": 200, "streaming": true, "durationMs": 100, "context": ["systemPromptTokens": 11700, "toolTokens": 33900, "messageTokens": 30300, "mcpToolTokens": 300, "toolCount": 18, "mcpToolCount": 2, "scaledToUsage": true] @@ -677,7 +677,7 @@ struct AgentConversationPresentationTests { func defaultWidthDetailsCardsKeepAllReportedStatistics() throws { var conversation = AgentConversation() conversation.completedTurns = [AgentTurnStatistics(id: "turn", startedAt: .now)] - conversation.recordModelCall(try #require(AgentModelCall.parse([ + conversation.recordModelCall(try #require(AgentModelCall.streamedStep([ "api": "anthropicMessages", "status": 200, "streaming": true, "firstTokenMs": 700, "durationMs": 1250, "usage": ["inputTokens": 62063, "cacheReadTokens": 61696, "cacheWriteTokens": 0, "outputTokens": 165] ]))) @@ -723,7 +723,7 @@ struct AgentConversationPresentationTests { var conversation = AgentConversation() conversation.completedTurns = (0..<7).map { AgentTurnStatistics(id: "turn-\($0)", startedAt: .now) } for _ in 0..<54 { - conversation.recordModelCall(try #require(AgentModelCall.parse([ + conversation.recordModelCall(try #require(AgentModelCall.streamedStep([ "api": "anthropicMessages", "status": 200, "streaming": true, "firstTokenMs": 950, "durationMs": 7400, "usage": ["inputTokens": 1100, "cacheReadTokens": 65600, "cacheWriteTokens": 900, "outputTokens": 1500] ]))) @@ -745,7 +745,7 @@ struct AgentConversationPresentationTests { return turn } for index in 0..<54 { - let call = try #require(AgentModelCall.parse([ + let call = try #require(AgentModelCall.streamedStep([ "api": "anthropicMessages", "status": 200, "streaming": true, "firstTokenMs": 900 + index * 4, "durationMs": 7400, "usage": ["inputTokens": 1100, "cacheReadTokens": 65600, "cacheWriteTokens": 900, "outputTokens": 1500], diff --git a/macos/Tests/LitheTests/AgentModelCallTestSupport.swift b/macos/Tests/LitheTests/AgentModelCallTestSupport.swift new file mode 100644 index 0000000000..6eec701b52 --- /dev/null +++ b/macos/Tests/LitheTests/AgentModelCallTestSupport.swift @@ -0,0 +1,25 @@ +import Foundation +@testable import LitheAgentConversationModule + +extension AgentModelCall { + /// The Host contribution of one successful streamed conversation step, + /// described in the raw `modelCall.call` shape for readable view fixtures. + /// Accounting rules for other calls are covered by the shared fixture. + static func streamedStep(_ call: [String: Any]) -> Self? { + guard call["status"] as? Int == 200, call["streaming"] as? Bool == true, call["auxiliary"] == nil, + let duration = call["durationMs"] as? Int else { return nil } + let usage = call["usage"] as? [String: Int] + let firstToken = call["firstTokenMs"] as? Int + let measured = firstToken.map { usage != nil && duration > $0 } ?? false + var statistics: [String: Any] = [ + "requests": 1, "steps": 1, "failedSteps": 0, "nonStreamingSteps": 0, "durationMs": duration, + "inputTokens": usage?["inputTokens"] ?? 0, "cacheReadTokens": usage?["cacheReadTokens"] ?? 0, + "cacheWriteTokens": usage?["cacheWriteTokens"] ?? 0, "outputTokens": usage?["outputTokens"] ?? 0, + "callsWithUsage": usage == nil ? 0 : 1, + "firstTokenMs": firstToken ?? 0, "firstTokenCount": firstToken == nil ? 0 : 1, + "generationMs": measured ? duration - (firstToken ?? 0) : 0, + "generatedTokens": measured ? usage?["outputTokens"] ?? 0 : 0] + if let context = call["context"] { statistics["context"] = context } + return parse(statistics) + } +} diff --git a/macos/Tests/LitheTests/AgentNextTurnConfigurationTests.swift b/macos/Tests/LitheTests/AgentNextTurnConfigurationTests.swift index 81d9dffbcb..86d17be62f 100644 --- a/macos/Tests/LitheTests/AgentNextTurnConfigurationTests.swift +++ b/macos/Tests/LitheTests/AgentNextTurnConfigurationTests.swift @@ -1,5 +1,6 @@ import Foundation import LitheCoreContracts +import LitheModuleAPI import Testing @testable import LitheAgentConversationModule @@ -21,7 +22,8 @@ struct AgentNextTurnConfigurationTests { try receive(feature, "turnFinished", ["stopReason": "end_turn"]) #expect(feature.selectedConversation?.isResponding == false) #expect(feature.hasPendingContinuation) - #expect(connection.commands.last?["configId"] as? String == "model") + #expect(connection.commands.last?["kind"] as? String == "applyNextTurnConfiguration") + #expect(choices(connection) == ["mode=auto", "model=model-b"]) let configToken = feature.selectedConversation?.pendingConfigToken let count = connection.commands.count @@ -37,9 +39,6 @@ struct AgentNextTurnConfigurationTests { } #expect(connection.commands.count == count) #expect(feature.selectedConversation?.pendingConfigToken == configToken) - try acknowledge(feature, connection, options(model: "model-b")) - #expect(connection.commands.last?["configId"] as? String == "mode") - #expect(feature.hasPendingContinuation == !cancel) try acknowledge(feature, connection, options(model: "model-b", mode: "auto")) #expect(!feature.hasPendingContinuation) #expect(feature.selectedConversation?.pendingConfigToken == nil) @@ -80,23 +79,23 @@ struct AgentNextTurnConfigurationTests { #expect(connection.commands.count == count) try receive(feature, "turnFinished", ["stopReason": "end_turn"]) - #expect(connection.commands.last?["configId"] as? String == "model") + // The Host orders, revalidates, and confirms; the latest catalog travels with the choices. + #expect(choices(connection) == ["mode=auto", "model=model-b", "reasoning_effort=high"]) + let catalog = try #require(connection.commands.last?["catalog"] as? [[String: Any]]) + #expect(catalog.compactMap { $0["currentValue"] as? String } == ["model-a", "plan", "medium"]) + #expect(catalog.first?["category"] as? String == "model") #expect(throws: AgentConversationError.configurationPending) { try feature.send("Before confirmation") } let token = try #require(connection.commands.last?["token"] as? String) - try receive(feature, "sessionConfigured", ["token": "stale", "configOptions": options(model: "model-b")]) + try receive(feature, "nextTurnConfigured", ["token": "stale", "configOptions": options(model: "model-b")]) #expect(feature.selectedConversation?.pendingConfigToken == token) - try acknowledge(feature, connection, options(model: "model-b", mode: "plan")) - #expect(connection.commands.last?["configId"] as? String == "mode") - try acknowledge(feature, connection, options(model: "model-b", mode: "auto")) - #expect(connection.commands.last?["configId"] as? String == "reasoning_effort") #expect(throws: AgentConversationError.configurationPending) { try feature.send("Still confirming") } try acknowledge(feature, connection, options(model: "model-b", mode: "auto", effort: "high")) #expect(feature.selectedConversation?.pendingConfigToken == nil) #expect(feature.selectedConversation?.queuedConfigValues.isEmpty == true) #expect(values(feature.selectedConversation?.configOptions) == ["model-b", "auto", "high"]) try feature.send("Next turn") - #expect(connection.commands.suffix(4).compactMap { $0["kind"] as? String } == - ["setConfigOption", "setConfigOption", "setConfigOption", "prompt"]) + #expect(connection.commands.suffix(2).compactMap { $0["kind"] as? String } == + ["applyNextTurnConfiguration", "prompt"]) } } @@ -134,8 +133,7 @@ struct AgentNextTurnConfigurationTests { #expect(feature.selectedConversation?.isResponding == true) #expect(feature.selectedConversation?.isCancelling == true) try receive(feature, kind, ["stopReason": "cancelled", "message": "Turn failed"]) - #expect(connection.commands.last?["kind"] as? String == "setConfigOption") - #expect(connection.commands.last?["value"] as? String == "plan") + #expect(choices(connection) == ["mode=plan"]) #expect(feature.selectedConversation?.isResponding == false) try acknowledge(feature, connection, options(mode: "plan")) try feature.send("Next turn") @@ -158,7 +156,7 @@ struct AgentNextTurnConfigurationTests { feature.selectSession("session-2") try receive(feature, "turnFinished") #expect(connection.commands.last?["sessionId"] as? String == "session-1") - #expect(connection.commands.last?["configId"] as? String == "mode") + #expect(choices(connection) == ["mode=auto"]) try acknowledge(feature, connection, options(mode: "auto")) #expect(feature.selectedSessionID == "session-2") #expect(feature.selectedConversation?.isResponding == true) @@ -166,7 +164,7 @@ struct AgentNextTurnConfigurationTests { #expect(values(feature.selectedConversation?.displayConfigOptions) == ["model-a", "read-only", "high"]) try receive(feature, "turnFinished", ["sessionId": "session-2"]) #expect(connection.commands.last?["sessionId"] as? String == "session-2") - #expect(connection.commands.last?["configId"] as? String == "reasoning_effort") + #expect(choices(connection) == ["reasoning_effort=high"]) try acknowledge(feature, connection, options(effort: "high")) } } @@ -183,9 +181,9 @@ struct AgentNextTurnConfigurationTests { case "requestFailed": try receive(feature, "requestFailed", ["token": connection.commands.last?["token"] as Any, "message": "Rejected"]) case "unconfirmed": - try acknowledge(feature, connection, options()) + try acknowledge(feature, connection, options(), failure: "notConfirmed") case "removedChoice": - try acknowledge(feature, connection, Array(options(model: "model-b").prefix(2))) + try acknowledge(feature, connection, Array(options(model: "model-b").prefix(2)), failure: "unsupported") default: break } @@ -194,7 +192,35 @@ struct AgentNextTurnConfigurationTests { #expect(feature.selectedConversation?.pendingConfigToken == nil) #expect(feature.selectedConversation?.displayConfigOptions == feature.selectedConversation?.configOptions) #expect(connection.commands.filter { $0["kind"] as? String == "prompt" }.count == 1) - #expect(connection.commands.filter { $0["kind"] as? String == "setConfigOption" }.count == (failure == "sendFailed" ? 0 : 1)) + #expect(connection.commands.filter { $0["kind"] as? String == "applyNextTurnConfiguration" }.count == (failure == "sendFailed" ? 0 : 1)) + if failure == "unconfirmed" { + #expect(feature.selectedConversation?.configurationError == + L10n.string("The Agent did not confirm the selected session setting.")) + } + if failure == "removedChoice" { + // Settings the Agent confirmed before the failure stay applied. + #expect(values(feature.selectedConversation?.configOptions) == ["model-b", "read-only"]) + } + } + } + + @Test + func failedTurnAppliesNextTurnSettingsWithoutReplayingDeferredInput() async throws { + try await withFeature { feature, connection in + try receive(feature, "ready", ["canSteer": true]) + try feature.send("First turn") + feature.setConfigOption("model", value: "model-b") + try feature.send("Supplement") + let token = try #require(connection.commands.last?["token"] as? String) + let messageID = try #require(feature.selectedConversation?.messages.last?.id) + try receive(feature, "steeringResult", ["token": token, "outcome": "promptRequired"]) + try receive(feature, "requestFailed", ["message": "Turn failed"]) + #expect(!feature.hasPendingContinuation) + #expect(feature.selectedConversation?.messages.first { $0.id == messageID }?.delivery == .failed("Turn failed")) + #expect(choices(connection) == ["model=model-b"]) + try acknowledge(feature, connection, options(model: "model-b")) + #expect(connection.commands.filter { $0["kind"] as? String == "prompt" }.count == 1) + #expect(values(feature.selectedConversation?.configOptions) == ["model-b", "read-only", "medium"]) } } @@ -206,7 +232,7 @@ struct AgentNextTurnConfigurationTests { try receive(feature, "turnFinished") let token = try #require(connection.commands.last?["token"]) await feature.stop() - try receive(feature, "sessionConfigured", ["token": token, "configOptions": options(mode: "auto")]) + try receive(feature, "nextTurnConfigured", ["token": token, "configOptions": options(mode: "auto")]) #expect(feature.selectedConversation?.queuedConfigValues.isEmpty == true) #expect(feature.selectedConversation?.pendingConfigToken == nil) #expect(values(feature.selectedConversation?.displayConfigOptions) == ["model-a", "read-only", "medium"]) @@ -240,10 +266,21 @@ struct AgentNextTurnConfigurationTests { feature.receive(String(decoding: try JSONSerialization.data(withJSONObject: event), as: UTF8.self)) } - private func acknowledge(_ feature: AgentConnectionModel, _ connection: NextTurnConnection, _ options: [[String: Any]]) throws { + /// Answers the last `applyNextTurnConfiguration` as the Host does. + private func acknowledge(_ feature: AgentConnectionModel, _ connection: NextTurnConnection, _ options: [[String: Any]], + failure: String? = nil) throws { let command = try #require(connection.commands.last) - try receive(feature, "sessionConfigured", ["token": command["token"] as Any, - "sessionId": command["sessionId"] as Any, "configOptions": options]) + #expect(command["kind"] as? String == "applyNextTurnConfiguration") + var event: [String: Any] = ["token": command["token"] as Any, "sessionId": command["sessionId"] as Any, + "configOptions": options] + if let failure { event["failure"] = failure } + try receive(feature, "nextTurnConfigured", event) + } + + private func choices(_ connection: NextTurnConnection) -> [String] { + guard connection.commands.last?["kind"] as? String == "applyNextTurnConfiguration" else { return [] } + return (connection.commands.last?["choices"] as? [[String: String]] ?? []) + .map { "\($0["configId"] ?? "")=\($0["value"] ?? "")" } } private func values(_ options: [AgentSessionConfigOption]?) -> [String]? { options?.map(\.currentValue) } diff --git a/macos/Tests/LitheTests/AgentSessionSelectorLayoutTests.swift b/macos/Tests/LitheTests/AgentSessionSelectorLayoutTests.swift index 4b1e089d4f..2374b3fbf9 100644 --- a/macos/Tests/LitheTests/AgentSessionSelectorLayoutTests.swift +++ b/macos/Tests/LitheTests/AgentSessionSelectorLayoutTests.swift @@ -100,7 +100,7 @@ struct AgentSessionSelectorLayoutTests { let usage = try #require(AgentContextUsage(usedTokens: 1200, capacityTokens: 10000)) var conversation = AgentConversation() conversation.completedTurns = [.init(id: "turn", startedAt: .now)] - conversation.recordModelCall(try #require(AgentModelCall.parse([ + conversation.recordModelCall(try #require(AgentModelCall.streamedStep([ "api": "anthropicMessages", "status": 200, "streaming": true, "firstTokenMs": 700, "durationMs": 1250, "usage": ["inputTokens": 1200, "cacheReadTokens": 600, "cacheWriteTokens": 0, "outputTokens": 165] ]))) diff --git a/rust/lithe-agent-host/src/model_call_statistics.rs b/rust/lithe-agent-host/src/model_call_statistics.rs new file mode 100644 index 0000000000..7de176c3fa --- /dev/null +++ b/rust/lithe-agent-host/src/model_call_statistics.rs @@ -0,0 +1,252 @@ +//! Shared accounting rules for observed model calls. +//! +//! The Host attaches one [`ModelCallStatistics`] contribution to every +//! `modelCall` event, so both desktop products count the same request the same +//! way: which calls are conversation steps, which failed, which count as +//! non-streaming, which timings describe generation speed, and which request +//! describes the current context. Platforms only add contributions with +//! [`ModelCallStatistics::merge`]; they never reinterpret a raw call. +//! Contract: `shared/fixtures/agent/model-call-statistics-v1.json`. + +use std::collections::HashSet; +use std::sync::Mutex; + +use serde::{Deserialize, Serialize}; + +use crate::model_calls::{ContextComposition, ModelCall}; + +/// Additive statistics of one or more observed calls. +/// +/// Every counter is a sum, `reasoning_tokens` is a sum over the calls that +/// reported it, and `context` is the latest composition that may describe the +/// conversation's current prompt. Merging contributions in event order yields +/// the totals of a turn or a session. +#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelCallStatistics { + /// Observed provider requests, including auxiliary ones. + pub requests: u64, + /// Requests that are steps of the conversation (not auxiliary). + pub steps: u64, + /// Steps whose HTTP status is 400 or higher, including transport failures. + pub failed_steps: u64, + /// Successful steps answered without streaming. A failed response is an + /// error body, not a non-streaming answer, so it is never counted here. + pub non_streaming_steps: u64, + /// Milliseconds of complete step requests, including time to first token. + pub duration_ms: u64, + /// Provider prompt tokens outside the cache, from every request with usage. + pub input_tokens: u64, + pub cache_read_tokens: u64, + pub cache_write_tokens: u64, + pub output_tokens: u64, + /// Sum of reported reasoning tokens; absent when no call reported any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_tokens: Option, + /// Requests whose response carried usage counters. Token sums cover only + /// these, so `requests > calls_with_usage` marks the sums as a lower bound. + pub calls_with_usage: u64, + /// Sum and count of first-token latencies of streaming steps. + pub first_token_ms: u64, + pub first_token_count: u64, + /// Streaming time after the first token and the output produced in it; + /// their ratio is the generation speed. + pub generation_ms: u64, + pub generated_tokens: u64, + /// Composition that replaces the current context, or absent when this + /// contribution does not describe the conversation's prompt. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context: Option, +} + +impl ModelCallStatistics { + /// Contribution of one call. `sends_tools` is the per-session memory that + /// the conversation's main requests carry tool definitions; once set, only + /// tool-carrying requests describe the current context, because tool-less + /// ones are background requests the marker did not recognize. + pub fn of_call(call: &ModelCall, sends_tools: &mut bool) -> Self { + let mut statistics = Self { + requests: 1, + ..Self::default() + }; + if let Some(usage) = call.usage { + statistics.calls_with_usage = 1; + statistics.input_tokens = usage.input_tokens; + statistics.cache_read_tokens = usage.cache_read_tokens; + statistics.cache_write_tokens = usage.cache_write_tokens; + statistics.output_tokens = usage.output_tokens; + statistics.reasoning_tokens = usage.reasoning_tokens; + } + if call.auxiliary { + // Its tokens were spent, but a title request is neither a step nor + // a measure of latency, generation speed, or the current context. + return statistics; + } + let failed = call.status >= 400; + statistics.steps = 1; + statistics.failed_steps = u64::from(failed); + statistics.non_streaming_steps = u64::from(!call.streaming && !failed); + statistics.duration_ms = call.duration_ms; + if let (true, Some(first_token)) = (call.streaming, call.first_token_ms) { + statistics.first_token_ms = first_token; + statistics.first_token_count = 1; + if let Some(usage) = call.usage.filter(|_| call.duration_ms > first_token) { + statistics.generation_ms = call.duration_ms - first_token; + statistics.generated_tokens = usage.output_tokens; + } + } + if let Some(context) = call.context { + let carries_tools = context.tool_count + context.mcp_tool_count > 0; + if carries_tools || !*sends_tools { + statistics.context = Some(context); + } + *sends_tools |= carries_tools; + } + statistics + } + + /// Adds a later contribution. A later context replaces an earlier one. + pub fn merge(&mut self, later: &Self) { + self.requests += later.requests; + self.steps += later.steps; + self.failed_steps += later.failed_steps; + self.non_streaming_steps += later.non_streaming_steps; + self.duration_ms += later.duration_ms; + self.input_tokens += later.input_tokens; + self.cache_read_tokens += later.cache_read_tokens; + self.cache_write_tokens += later.cache_write_tokens; + self.output_tokens += later.output_tokens; + if let Some(reasoning) = later.reasoning_tokens { + self.reasoning_tokens = Some(self.reasoning_tokens.unwrap_or(0) + reasoning); + } + self.calls_with_usage += later.calls_with_usage; + self.first_token_ms += later.first_token_ms; + self.first_token_count += later.first_token_count; + self.generation_ms += later.generation_ms; + self.generated_tokens += later.generated_tokens; + if later.context.is_some() { + self.context = later.context; + } + } +} + +/// Per-connection memory of which sessions' main requests carry tools. +/// Bounded by the sessions a connection prompts, which the connection owns. +#[derive(Default)] +pub(crate) struct StatisticsTracker { + sessions_sending_tools: Mutex>, +} + +impl StatisticsTracker { + /// Contribution of a call attributed to `session_id`. Unattributed calls + /// are dropped by both products, so they keep no per-session memory. + pub(crate) fn contribution(&self, session_id: Option<&str>, call: &ModelCall) -> ModelCallStatistics { + let Some(session_id) = session_id else { + return ModelCallStatistics::of_call(call, &mut false); + }; + let Ok(mut sessions) = self.sessions_sending_tools.lock() else { + return ModelCallStatistics::of_call(call, &mut false); + }; + let mut sends_tools = sessions.contains(session_id); + let statistics = ModelCallStatistics::of_call(call, &mut sends_tools); + if sends_tools { + sessions.insert(session_id.to_owned()); + } + statistics + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model_calls::{ModelApi, ModelCallUsage}; + use serde_json::Value; + + fn call(value: &Value) -> ModelCall { + let usage = value.get("usage").map(|usage| ModelCallUsage { + input_tokens: usage["inputTokens"].as_u64().unwrap(), + cache_read_tokens: usage["cacheReadTokens"].as_u64().unwrap(), + cache_write_tokens: usage["cacheWriteTokens"].as_u64().unwrap(), + output_tokens: usage["outputTokens"].as_u64().unwrap(), + reasoning_tokens: usage["reasoningTokens"].as_u64(), + }); + let context = value.get("context").map(|context| ContextComposition { + system_prompt_tokens: context["systemPromptTokens"].as_u64().unwrap(), + tool_tokens: context["toolTokens"].as_u64().unwrap(), + mcp_tool_tokens: context["mcpToolTokens"].as_u64().unwrap(), + message_tokens: context["messageTokens"].as_u64().unwrap(), + tool_count: context["toolCount"].as_u64().unwrap() as u32, + mcp_tool_count: context["mcpToolCount"].as_u64().unwrap() as u32, + scaled_to_usage: context["scaledToUsage"].as_bool().unwrap(), + }); + ModelCall { + api: serde_json::from_value::(value["api"].clone()).unwrap().0, + model: None, + status: value["status"].as_u64().unwrap() as u16, + streaming: value["streaming"].as_bool().unwrap_or(false), + first_token_ms: value["firstTokenMs"].as_u64(), + duration_ms: value["durationMs"].as_u64().unwrap(), + usage, + context, + auxiliary: value["auxiliary"].as_bool().unwrap_or(false), + } + } + + /// `ModelApi` is output-only on the wire; the fixture names it by its value. + struct ModelApiName(ModelApi); + impl<'de> Deserialize<'de> for ModelApiName { + fn deserialize>(deserializer: D) -> Result { + Ok(Self(match String::deserialize(deserializer)?.as_str() { + "anthropicMessages" => ModelApi::AnthropicMessages, + "responses" => ModelApi::Responses, + _ => ModelApi::ChatCompletions, + })) + } + } + + /// Every fixture case fixes each call's contribution and the merged + /// totals both desktop products must display. + #[test] + fn fixture_contributions_and_totals_match() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../shared/fixtures/agent/model-call-statistics-v1.json" + )) + .unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + let tracker = StatisticsTracker::default(); + let mut total = ModelCallStatistics::default(); + let events = case["events"].as_array().unwrap(); + for (index, event) in events.iter().enumerate() { + let contribution = + tracker.contribution(event["sessionId"].as_str(), &call(&event["call"])); + let expected: ModelCallStatistics = + serde_json::from_value(event["statistics"].clone()).unwrap(); + assert_eq!(contribution, expected, "{name} call {index}"); + assert_eq!( + serde_json::to_value(&contribution).unwrap(), + event["statistics"], + "{name} call {index} wire shape" + ); + total.merge(&contribution); + } + let expected: ModelCallStatistics = + serde_json::from_value(case["total"].clone()).unwrap(); + assert_eq!(total, expected, "{name} total"); + } + } + + /// Sessions keep separate tool memory: one session's tool-carrying + /// request must not freeze another session's tool-less composition. + #[test] + fn tool_memory_is_per_session() { + let tracker = StatisticsTracker::default(); + let tools = call(&serde_json::json!({"api":"responses","status":200,"durationMs":1, + "context":{"systemPromptTokens":1,"toolTokens":1,"mcpToolTokens":0,"messageTokens":1,"toolCount":1,"mcpToolCount":0,"scaledToUsage":false}})); + let toolless = call(&serde_json::json!({"api":"responses","status":200,"durationMs":1, + "context":{"systemPromptTokens":1,"toolTokens":0,"mcpToolTokens":0,"messageTokens":9,"toolCount":0,"mcpToolCount":0,"scaledToUsage":false}})); + assert!(tracker.contribution(Some("a"), &tools).context.is_some()); + assert!(tracker.contribution(Some("a"), &toolless).context.is_none()); + assert!(tracker.contribution(Some("b"), &toolless).context.is_some()); + } +} diff --git a/rust/lithe-agent-host/src/model_calls.rs b/rust/lithe-agent-host/src/model_calls.rs index f1d9c65db2..43dfb84cff 100644 --- a/rust/lithe-agent-host/src/model_calls.rs +++ b/rust/lithe-agent-host/src/model_calls.rs @@ -11,7 +11,7 @@ use std::time::{Duration, Instant}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use serde_json::Value; /// Bound on one buffered SSE line or non-streaming body kept for parsing. @@ -70,7 +70,7 @@ impl ModelCallUsage { /// Estimated split of one request's prompt. Byte sizes of the serialized /// sections are scaled to the provider-reported prompt tokens when available; /// otherwise a four-bytes-per-token approximation is used. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ContextComposition { pub system_prompt_tokens: u64, diff --git a/rust/lithe-agent-host/src/next_turn_config.rs b/rust/lithe-agent-host/src/next_turn_config.rs new file mode 100644 index 0000000000..4ca601aa05 --- /dev/null +++ b/rust/lithe-agent-host/src/next_turn_config.rs @@ -0,0 +1,227 @@ +//! Applying the session settings a user chose while a turn was running. +//! +//! Choices made during a turn stay local to the product until the turn ends. +//! The product then hands every remaining choice to the Host in one +//! `applyNextTurnConfiguration` command. The Host applies them one ACP +//! request at a time: model choices first, because a model change can replace +//! the other options, then the rest in catalog order. Each remaining choice is +//! revalidated against the latest catalog the Agent returned, and each request +//! must be confirmed by the Agent's reported value. The first problem stops the +//! sequence with one stable failure code. +//! Contract: `shared/fixtures/agent/next-turn-configuration-v1.json`. + +use agent_client_protocol::schema::v1::{ + SessionConfigKind, SessionConfigOption, SessionConfigOptionCategory, SessionConfigSelectOptions, +}; +use serde::{Deserialize, Serialize}; + +/// One selectable session setting as both products parse it from ACP. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CatalogOption { + pub id: String, + /// ACP category, e.g. `model`; absent for uncategorized options. + #[serde(default)] + pub category: Option, + pub current_value: String, + /// Selectable value identifiers, flattened across groups. + pub choices: Vec, +} + +/// A value the user chose for the next turn. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ConfigChoice { + pub config_id: String, + pub value: String, +} + +/// Why the remaining choices were abandoned. Products localize the code; a +/// request failure additionally carries the Agent's own message. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ConfigFailure { + /// The latest catalog no longer offers the option or the chosen value. + Unsupported, + /// The Agent answered but reported a different current value. + NotConfirmed, + /// The ACP request failed; the event's `message` is upstream diagnostics. + RequestFailed, +} + +/// Next action of the sequence. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Step { + /// Send one `session/set_config_option` request. + Send(ConfigChoice), + /// Every choice is applied or already current. + Done, + /// Stop without sending the remaining choices. + Failed(ConfigFailure), +} + +/// Deterministic state of one next-turn application. +#[derive(Debug, Clone)] +pub struct NextTurnPlan { + catalog: Vec, + remaining: Vec, + awaiting: Option, +} + +impl NextTurnPlan { + /// `catalog` is the product's latest confirmed catalog. A later choice for + /// the same option replaces an earlier one. + pub fn new(catalog: Vec, choices: Vec) -> Self { + let mut remaining: Vec = Vec::new(); + for choice in choices { + remaining.retain(|existing| existing.config_id != choice.config_id); + remaining.push(choice); + } + Self { + catalog, + remaining, + awaiting: None, + } + } + + /// Chooses the next request against the latest catalog. + pub fn next(&mut self) -> Step { + debug_assert!(self.awaiting.is_none(), "confirm the sent choice first"); + let is_model = |option: &CatalogOption| option.category.as_deref() == Some("model"); + let ordered = self + .catalog + .iter() + .filter(|option| is_model(option)) + .chain(self.catalog.iter().filter(|option| !is_model(option))); + for option in ordered { + let Some(index) = self + .remaining + .iter() + .position(|choice| choice.config_id == option.id) + else { + continue; + }; + if option.current_value == self.remaining[index].value { + // A model change may already have produced the chosen value. + self.remaining.remove(index); + continue; + } + if !option.choices.contains(&self.remaining[index].value) { + return Step::Failed(ConfigFailure::Unsupported); + } + let choice = self.remaining.remove(index); + self.awaiting = Some(choice.clone()); + return Step::Send(choice); + } + if self.remaining.is_empty() { + Step::Done + } else { + // The catalog no longer contains a chosen option at all. + Step::Failed(ConfigFailure::Unsupported) + } + } + + /// Records the Agent's answer to the sent choice. + pub fn confirm(&mut self, catalog: Vec) -> Result<(), ConfigFailure> { + let sent = self.awaiting.take(); + self.catalog = catalog; + let confirmed = sent.is_some_and(|sent| { + self.catalog + .iter() + .any(|option| option.id == sent.config_id && option.current_value == sent.value) + }); + if confirmed { + Ok(()) + } else { + Err(ConfigFailure::NotConfirmed) + } + } +} + +/// Parses an Agent catalog the way both products do: select options only, +/// with grouped values flattened. +pub fn catalog(options: &[SessionConfigOption]) -> Vec { + options + .iter() + .filter_map(|option| { + let SessionConfigKind::Select(select) = &option.kind else { + return None; + }; + let choices = match &select.options { + SessionConfigSelectOptions::Ungrouped(values) => { + values.iter().map(|value| value.value.0.to_string()).collect() + } + SessionConfigSelectOptions::Grouped(groups) => groups + .iter() + .flat_map(|group| group.options.iter()) + .map(|value| value.value.0.to_string()) + .collect(), + _ => Vec::new(), + }; + Some(CatalogOption { + id: option.id.0.to_string(), + category: option.category.as_ref().map(category_name), + current_value: select.current_value.0.to_string(), + choices, + }) + }) + .collect() +} + +fn category_name(category: &SessionConfigOptionCategory) -> String { + serde_json::to_value(category) + .ok() + .and_then(|value| value.as_str().map(str::to_owned)) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::Value; + + /// Drives every fixture case against scripted Agent answers and checks + /// the requests, their order, and the final outcome. + #[test] + fn fixture_cases_apply_in_the_shared_order() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../shared/fixtures/agent/next-turn-configuration-v1.json" + )) + .unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + let options: Vec = + serde_json::from_value(case["catalog"].clone()).unwrap(); + let choices: Vec = + serde_json::from_value(case["choices"].clone()).unwrap(); + let mut answers = case["answers"].as_array().unwrap().iter(); + let mut plan = NextTurnPlan::new(catalog(&options), choices); + let mut sent = Vec::new(); + let failure = loop { + match plan.next() { + Step::Done => break None, + Step::Failed(failure) => break Some(failure), + Step::Send(choice) => { + sent.push(serde_json::to_value(&choice).unwrap()); + let answer = answers.next().expect("scripted answer"); + if answer.get("error").is_some() { + break Some(ConfigFailure::RequestFailed); + } + let options: Vec = + serde_json::from_value(answer["configOptions"].clone()).unwrap(); + if let Err(failure) = plan.confirm(catalog(&options)) { + break Some(failure); + } + } + } + }; + assert_eq!(Value::Array(sent), case["expected"]["requests"], "{name} requests"); + assert_eq!( + failure.map(|failure| serde_json::to_value(failure).unwrap()), + case["expected"]["failure"].as_str().map(Value::from), + "{name} failure" + ); + assert!(answers.next().is_none(), "{name} left answers unused"); + } + } +} diff --git a/rust/lithe-agent-host/src/tests.rs b/rust/lithe-agent-host/src/tests.rs index 9050eab915..07aa4c6d8d 100644 --- a/rust/lithe-agent-host/src/tests.rs +++ b/rust/lithe-agent-host/src/tests.rs @@ -2449,6 +2449,41 @@ async fn session_configuration_round_trips_upstream_options() { assert_eq!(harness.stop().await, Ok(())); } +/// The Host applies next-turn choices as one confirmed sequence and answers +/// with the shared event shape, both on success and when a request fails. +#[tokio::test(flavor = "current_thread")] +async fn next_turn_configuration_applies_choices_and_reports_one_result() { + let next: Value = serde_json::from_str(include_str!( + "../../../shared/fixtures/agent/next-turn-configuration-v1.json" + )) + .unwrap(); + let mut harness = Harness::ready().await; + harness.open_session("session-1").await; + let configured = next["events"]["configured"].clone(); + harness.send(next["command"].clone()); + let request = harness.agent.expect("session/set_config_option").await; + assert_eq!(request["params"]["configId"], "model"); + assert_eq!(request["params"]["value"], "model-b"); + harness + .agent + .reply(&request, json!({ "configOptions": configured["configOptions"] })) + .await; + assert_eq!(serde_json::to_value(harness.event().await).unwrap(), configured); + + harness.send(next["command"].clone()); + let request = harness.agent.expect("session/set_config_option").await; + harness + .agent + .write(json!({ "jsonrpc": "2.0", "id": request["id"], "error": { "code": -32602, "message": "Rejected" } })) + .await; + let failed = serde_json::to_value(harness.event().await).unwrap(); + assert_eq!(failed["kind"], "nextTurnConfigured"); + assert_eq!(failed["failure"], "requestFailed"); + assert!(failed.get("configOptions").is_none(), "no request succeeded"); + assert!(failed["message"].as_str().unwrap().contains("Rejected")); + assert_eq!(harness.stop().await, Ok(())); +} + #[tokio::test(flavor = "current_thread")] async fn every_new_session_repairs_a_stale_model_before_publishing_options() { let mut harness = Harness::ready().await; @@ -4046,16 +4081,19 @@ fn model_call_events_use_the_fixture_shape() { }), auxiliary: false, }; + let statistics = crate::ModelCallStatistics::of_call(&call, &mut false); let event = AgentEvent::ModelCall { session_id: Some("session-1".into()), after_turn_finished: false, call: call.clone(), + statistics: statistics.clone(), }; assert_eq!(serde_json::to_value(event).unwrap(), expected); let late = AgentEvent::ModelCall { session_id: Some("session-1".into()), after_turn_finished: true, call, + statistics, }; assert_eq!( serde_json::to_value(late).unwrap(), diff --git a/rust/lithe-agent-host/tests/claude_api_failure.rs b/rust/lithe-agent-host/tests/claude_api_failure.rs index 8651264019..8420609c1b 100644 --- a/rust/lithe-agent-host/tests/claude_api_failure.rs +++ b/rust/lithe-agent-host/tests/claude_api_failure.rs @@ -423,6 +423,7 @@ fn run_local_api_turn_with(status: u16, observe_model_calls: bool) { session_id: id, after_turn_finished, call, + .. } => { assert!(!after_turn_finished, "the turn waits for its own calls"); model_calls.push((id, call)); diff --git a/rust/lithe-agent-host/tests/codex_api_failure.rs b/rust/lithe-agent-host/tests/codex_api_failure.rs index 79d6ef1872..0f5a5a1814 100644 --- a/rust/lithe-agent-host/tests/codex_api_failure.rs +++ b/rust/lithe-agent-host/tests/codex_api_failure.rs @@ -302,6 +302,7 @@ fn run_with( session_id, after_turn_finished, call, + .. } => { assert!(!after_turn_finished, "the turn waits for its own calls"); model_calls.push((session_id, call)); diff --git a/shared/fixtures/agent/model-call-statistics-v1.json b/shared/fixtures/agent/model-call-statistics-v1.json new file mode 100644 index 0000000000..72b18b1175 --- /dev/null +++ b/shared/fixtures/agent/model-call-statistics-v1.json @@ -0,0 +1,409 @@ +{ + "version": 1, + "description": "Shared accounting of observed model calls. The Host attaches `statistics` to each `modelCall` event; desktop products merge contributions in event order: counters add, reasoningTokens adds over calls that report it, and a present context replaces the previous one.", + "cases": [ + { + "name": "failedNonStreamingStepIsNotANonStreamingAnswer", + "description": "HTTP 500 counts as a failed step, never as a non-streaming answer; Windows previously counted it.", + "events": [ + { + "sessionId": "session-1", + "call": { + "api": "responses", + "status": 500, + "streaming": false, + "durationMs": 40 + }, + "statistics": { + "requests": 1, + "steps": 1, + "failedSteps": 1, + "nonStreamingSteps": 0, + "durationMs": 40, + "inputTokens": 0, + "cacheReadTokens": 0, + "cacheWriteTokens": 0, + "outputTokens": 0, + "callsWithUsage": 0, + "firstTokenMs": 0, + "firstTokenCount": 0, + "generationMs": 0, + "generatedTokens": 0 + } + }, + { + "sessionId": "session-1", + "call": { + "api": "responses", + "status": 200, + "streaming": false, + "durationMs": 3000, + "usage": { + "inputTokens": 500, + "cacheReadTokens": 0, + "cacheWriteTokens": 0, + "outputTokens": 300, + "reasoningTokens": 100 + } + }, + "statistics": { + "requests": 1, + "steps": 1, + "failedSteps": 0, + "nonStreamingSteps": 1, + "durationMs": 3000, + "inputTokens": 500, + "cacheReadTokens": 0, + "cacheWriteTokens": 0, + "outputTokens": 300, + "reasoningTokens": 100, + "callsWithUsage": 1, + "firstTokenMs": 0, + "firstTokenCount": 0, + "generationMs": 0, + "generatedTokens": 0 + } + } + ], + "total": { + "requests": 2, + "steps": 2, + "failedSteps": 1, + "nonStreamingSteps": 1, + "durationMs": 3040, + "inputTokens": 500, + "cacheReadTokens": 0, + "cacheWriteTokens": 0, + "outputTokens": 300, + "reasoningTokens": 100, + "callsWithUsage": 1, + "firstTokenMs": 0, + "firstTokenCount": 0, + "generationMs": 0, + "generatedTokens": 0 + } + }, + { + "name": "auxiliaryAndToollessRequestsKeepTheMainContext", + "description": "An auxiliary title request and an unrecognized tool-less background request spend tokens but never replace the current context; Windows previously showed the last request's composition.", + "events": [ + { + "sessionId": "session-1", + "call": { + "api": "anthropicMessages", + "status": 200, + "streaming": true, + "firstTokenMs": 100, + "durationMs": 1000, + "usage": { + "inputTokens": 100, + "cacheReadTokens": 900, + "cacheWriteTokens": 0, + "outputTokens": 50 + }, + "context": { + "systemPromptTokens": 10, + "toolTokens": 20, + "mcpToolTokens": 0, + "messageTokens": 70, + "toolCount": 12, + "mcpToolCount": 0, + "scaledToUsage": true + } + }, + "statistics": { + "requests": 1, + "steps": 1, + "failedSteps": 0, + "nonStreamingSteps": 0, + "durationMs": 1000, + "inputTokens": 100, + "cacheReadTokens": 900, + "cacheWriteTokens": 0, + "outputTokens": 50, + "callsWithUsage": 1, + "firstTokenMs": 100, + "firstTokenCount": 1, + "generationMs": 900, + "generatedTokens": 50, + "context": { + "systemPromptTokens": 10, + "toolTokens": 20, + "mcpToolTokens": 0, + "messageTokens": 70, + "toolCount": 12, + "mcpToolCount": 0, + "scaledToUsage": true + } + } + }, + { + "sessionId": "session-1", + "call": { + "api": "anthropicMessages", + "status": 200, + "streaming": true, + "firstTokenMs": 1900, + "durationMs": 2000, + "usage": { + "inputTokens": 30, + "cacheReadTokens": 0, + "cacheWriteTokens": 0, + "outputTokens": 20 + }, + "context": { + "systemPromptTokens": 5, + "toolTokens": 0, + "mcpToolTokens": 0, + "messageTokens": 300, + "toolCount": 0, + "mcpToolCount": 0, + "scaledToUsage": true + }, + "auxiliary": true + }, + "statistics": { + "requests": 1, + "steps": 0, + "failedSteps": 0, + "nonStreamingSteps": 0, + "durationMs": 0, + "inputTokens": 30, + "cacheReadTokens": 0, + "cacheWriteTokens": 0, + "outputTokens": 20, + "callsWithUsage": 1, + "firstTokenMs": 0, + "firstTokenCount": 0, + "generationMs": 0, + "generatedTokens": 0 + } + }, + { + "sessionId": "session-1", + "call": { + "api": "anthropicMessages", + "status": 200, + "streaming": false, + "durationMs": 200, + "context": { + "systemPromptTokens": 1, + "toolTokens": 0, + "mcpToolTokens": 0, + "messageTokens": 40, + "toolCount": 0, + "mcpToolCount": 0, + "scaledToUsage": false + } + }, + "statistics": { + "requests": 1, + "steps": 1, + "failedSteps": 0, + "nonStreamingSteps": 1, + "durationMs": 200, + "inputTokens": 0, + "cacheReadTokens": 0, + "cacheWriteTokens": 0, + "outputTokens": 0, + "callsWithUsage": 0, + "firstTokenMs": 0, + "firstTokenCount": 0, + "generationMs": 0, + "generatedTokens": 0 + } + } + ], + "total": { + "requests": 3, + "steps": 2, + "failedSteps": 0, + "nonStreamingSteps": 1, + "durationMs": 1200, + "inputTokens": 130, + "cacheReadTokens": 900, + "cacheWriteTokens": 0, + "outputTokens": 70, + "callsWithUsage": 2, + "firstTokenMs": 100, + "firstTokenCount": 1, + "generationMs": 900, + "generatedTokens": 50, + "context": { + "systemPromptTokens": 10, + "toolTokens": 20, + "mcpToolTokens": 0, + "messageTokens": 70, + "toolCount": 12, + "mcpToolCount": 0, + "scaledToUsage": true + } + } + }, + { + "name": "toollessAgentRefreshesContextFromEveryStep", + "description": "An Agent that never sends tools keeps its composition current instead of freezing the first one.", + "events": [ + { + "sessionId": "session-1", + "call": { + "api": "chatCompletions", + "status": 200, + "streaming": true, + "durationMs": 500, + "context": { + "systemPromptTokens": 0, + "toolTokens": 0, + "mcpToolTokens": 0, + "messageTokens": 1000, + "toolCount": 0, + "mcpToolCount": 0, + "scaledToUsage": false + } + }, + "statistics": { + "requests": 1, + "steps": 1, + "failedSteps": 0, + "nonStreamingSteps": 0, + "durationMs": 500, + "inputTokens": 0, + "cacheReadTokens": 0, + "cacheWriteTokens": 0, + "outputTokens": 0, + "callsWithUsage": 0, + "firstTokenMs": 0, + "firstTokenCount": 0, + "generationMs": 0, + "generatedTokens": 0, + "context": { + "systemPromptTokens": 0, + "toolTokens": 0, + "mcpToolTokens": 0, + "messageTokens": 1000, + "toolCount": 0, + "mcpToolCount": 0, + "scaledToUsage": false + } + } + }, + { + "sessionId": "session-1", + "call": { + "api": "chatCompletions", + "status": 200, + "streaming": false, + "durationMs": 300, + "context": { + "systemPromptTokens": 0, + "toolTokens": 0, + "mcpToolTokens": 0, + "messageTokens": 5000, + "toolCount": 0, + "mcpToolCount": 0, + "scaledToUsage": false + } + }, + "statistics": { + "requests": 1, + "steps": 1, + "failedSteps": 0, + "nonStreamingSteps": 1, + "durationMs": 300, + "inputTokens": 0, + "cacheReadTokens": 0, + "cacheWriteTokens": 0, + "outputTokens": 0, + "callsWithUsage": 0, + "firstTokenMs": 0, + "firstTokenCount": 0, + "generationMs": 0, + "generatedTokens": 0, + "context": { + "systemPromptTokens": 0, + "toolTokens": 0, + "mcpToolTokens": 0, + "messageTokens": 5000, + "toolCount": 0, + "mcpToolCount": 0, + "scaledToUsage": false + } + } + } + ], + "total": { + "requests": 2, + "steps": 2, + "failedSteps": 0, + "nonStreamingSteps": 1, + "durationMs": 800, + "inputTokens": 0, + "cacheReadTokens": 0, + "cacheWriteTokens": 0, + "outputTokens": 0, + "callsWithUsage": 0, + "firstTokenMs": 0, + "firstTokenCount": 0, + "generationMs": 0, + "generatedTokens": 0, + "context": { + "systemPromptTokens": 0, + "toolTokens": 0, + "mcpToolTokens": 0, + "messageTokens": 5000, + "toolCount": 0, + "mcpToolCount": 0, + "scaledToUsage": false + } + } + }, + { + "name": "streamWithoutUsageMeasuresLatencyOnly", + "description": "A stream without provider counters reports first-token latency but no generation speed, and leaves the token sums a lower bound.", + "events": [ + { + "sessionId": "session-1", + "call": { + "api": "responses", + "status": 200, + "streaming": true, + "firstTokenMs": 300, + "durationMs": 900 + }, + "statistics": { + "requests": 1, + "steps": 1, + "failedSteps": 0, + "nonStreamingSteps": 0, + "durationMs": 900, + "inputTokens": 0, + "cacheReadTokens": 0, + "cacheWriteTokens": 0, + "outputTokens": 0, + "callsWithUsage": 0, + "firstTokenMs": 300, + "firstTokenCount": 1, + "generationMs": 0, + "generatedTokens": 0 + } + } + ], + "total": { + "requests": 1, + "steps": 1, + "failedSteps": 0, + "nonStreamingSteps": 0, + "durationMs": 900, + "inputTokens": 0, + "cacheReadTokens": 0, + "cacheWriteTokens": 0, + "outputTokens": 0, + "callsWithUsage": 0, + "firstTokenMs": 300, + "firstTokenCount": 1, + "generationMs": 0, + "generatedTokens": 0 + } + } + ] +} diff --git a/shared/fixtures/agent/next-turn-configuration-v1.json b/shared/fixtures/agent/next-turn-configuration-v1.json new file mode 100644 index 0000000000..c6aceebfff --- /dev/null +++ b/shared/fixtures/agent/next-turn-configuration-v1.json @@ -0,0 +1,1118 @@ +{ + "version": 1, + "description": "Next-turn session settings. The product sends `applyNextTurnConfiguration` with its latest catalog and the user's choices after a turn ends; the Host applies one request at a time and answers with one `nextTurnConfigured` event. `answers` script the Agent's catalog after each request.", + "command": { + "kind": "applyNextTurnConfiguration", + "token": "config-2", + "sessionId": "session-1", + "catalog": [ + { + "id": "model", + "category": "model", + "currentValue": "model-a", + "choices": [ + "model-a", + "model-b" + ] + } + ], + "choices": [ + { + "configId": "model", + "value": "model-b" + } + ] + }, + "events": { + "configured": { + "kind": "nextTurnConfigured", + "token": "config-2", + "sessionId": "session-1", + "configOptions": [ + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-b", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + } + ] + }, + "failed": { + "kind": "nextTurnConfigured", + "token": "config-2", + "sessionId": "session-1", + "configOptions": [ + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-b", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + } + ], + "failure": "requestFailed", + "message": "Rejected" + }, + "unsupportedBeforeAnyRequest": { + "kind": "nextTurnConfigured", + "token": "config-2", + "sessionId": "session-1", + "failure": "unsupported" + } + }, + "cases": [ + { + "name": "modelFirstThenCatalogOrder", + "description": "Model choices apply first; the rest follow the Agent's catalog order, not the order the user chose them (Windows previously used choice order).", + "catalog": [ + { + "id": "mode", + "name": "mode", + "type": "select", + "currentValue": "read-only", + "options": [ + { + "value": "read-only", + "name": "read-only" + }, + { + "value": "auto", + "name": "auto" + }, + { + "value": "plan", + "name": "plan" + } + ], + "category": "mode" + }, + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-a", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ], + "choices": [ + { + "configId": "reasoning_effort", + "value": "high" + }, + { + "configId": "mode", + "value": "auto" + }, + { + "configId": "model", + "value": "model-b" + } + ], + "answers": [ + { + "configOptions": [ + { + "id": "mode", + "name": "mode", + "type": "select", + "currentValue": "read-only", + "options": [ + { + "value": "read-only", + "name": "read-only" + }, + { + "value": "auto", + "name": "auto" + }, + { + "value": "plan", + "name": "plan" + } + ], + "category": "mode" + }, + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-b", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ] + }, + { + "configOptions": [ + { + "id": "mode", + "name": "mode", + "type": "select", + "currentValue": "auto", + "options": [ + { + "value": "read-only", + "name": "read-only" + }, + { + "value": "auto", + "name": "auto" + }, + { + "value": "plan", + "name": "plan" + } + ], + "category": "mode" + }, + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-b", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ] + }, + { + "configOptions": [ + { + "id": "mode", + "name": "mode", + "type": "select", + "currentValue": "auto", + "options": [ + { + "value": "read-only", + "name": "read-only" + }, + { + "value": "auto", + "name": "auto" + }, + { + "value": "plan", + "name": "plan" + } + ], + "category": "mode" + }, + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-b", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "high", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ] + } + ], + "expected": { + "requests": [ + { + "configId": "model", + "value": "model-b" + }, + { + "configId": "mode", + "value": "auto" + }, + { + "configId": "reasoning_effort", + "value": "high" + } + ], + "failure": null + } + }, + { + "name": "modelChangeRemovesAChosenValue", + "description": "Remaining choices are revalidated against the catalog the model change returned.", + "catalog": [ + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-a", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ], + "choices": [ + { + "configId": "model", + "value": "model-b" + }, + { + "configId": "reasoning_effort", + "value": "high" + } + ], + "answers": [ + { + "configOptions": [ + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-b", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "medium" + } + ], + "category": "thought_level" + } + ] + } + ], + "expected": { + "requests": [ + { + "configId": "model", + "value": "model-b" + } + ], + "failure": "unsupported" + } + }, + { + "name": "modelChangeAlreadyAppliesAChoice", + "description": "A choice the new catalog already reports as current is not sent again.", + "catalog": [ + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-a", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ], + "choices": [ + { + "configId": "model", + "value": "model-b" + }, + { + "configId": "reasoning_effort", + "value": "high" + } + ], + "answers": [ + { + "configOptions": [ + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-b", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "high", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ] + } + ], + "expected": { + "requests": [ + { + "configId": "model", + "value": "model-b" + } + ], + "failure": null + } + }, + { + "name": "agentDoesNotConfirmTheChoice", + "description": "An answer that reports another current value stops the sequence (Windows previously accepted any answer).", + "catalog": [ + { + "id": "mode", + "name": "mode", + "type": "select", + "currentValue": "read-only", + "options": [ + { + "value": "read-only", + "name": "read-only" + }, + { + "value": "auto", + "name": "auto" + }, + { + "value": "plan", + "name": "plan" + } + ], + "category": "mode" + }, + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-a", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ], + "choices": [ + { + "configId": "model", + "value": "model-b" + }, + { + "configId": "mode", + "value": "auto" + } + ], + "answers": [ + { + "configOptions": [ + { + "id": "mode", + "name": "mode", + "type": "select", + "currentValue": "read-only", + "options": [ + { + "value": "read-only", + "name": "read-only" + }, + { + "value": "auto", + "name": "auto" + }, + { + "value": "plan", + "name": "plan" + } + ], + "category": "mode" + }, + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-a", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ] + } + ], + "expected": { + "requests": [ + { + "configId": "model", + "value": "model-b" + } + ], + "failure": "notConfirmed" + } + }, + { + "name": "optionMissingFromTheCatalog", + "description": "Choices for options the Agent still offers apply first; a choice whose option disappeared then fails the sequence.", + "catalog": [ + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-a", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + } + ], + "choices": [ + { + "configId": "verbosity", + "value": "high" + }, + { + "configId": "model", + "value": "model-b" + } + ], + "answers": [ + { + "configOptions": [ + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-b", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + } + ] + } + ], + "expected": { + "requests": [ + { + "configId": "model", + "value": "model-b" + } + ], + "failure": "unsupported" + } + }, + { + "name": "requestFailsMidway", + "description": "A failed request keeps the settings the Agent already confirmed and abandons the rest.", + "catalog": [ + { + "id": "mode", + "name": "mode", + "type": "select", + "currentValue": "read-only", + "options": [ + { + "value": "read-only", + "name": "read-only" + }, + { + "value": "auto", + "name": "auto" + }, + { + "value": "plan", + "name": "plan" + } + ], + "category": "mode" + }, + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-a", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ], + "choices": [ + { + "configId": "model", + "value": "model-b" + }, + { + "configId": "mode", + "value": "auto" + } + ], + "answers": [ + { + "configOptions": [ + { + "id": "mode", + "name": "mode", + "type": "select", + "currentValue": "read-only", + "options": [ + { + "value": "read-only", + "name": "read-only" + }, + { + "value": "auto", + "name": "auto" + }, + { + "value": "plan", + "name": "plan" + } + ], + "category": "mode" + }, + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-b", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ] + }, + { + "error": "Rejected" + } + ], + "expected": { + "requests": [ + { + "configId": "model", + "value": "model-b" + }, + { + "configId": "mode", + "value": "auto" + } + ], + "failure": "requestFailed" + } + }, + { + "name": "laterChoiceReplacesEarlierChoice", + "description": "Only the latest choice for one option is applied.", + "catalog": [ + { + "id": "mode", + "name": "mode", + "type": "select", + "currentValue": "read-only", + "options": [ + { + "value": "read-only", + "name": "read-only" + }, + { + "value": "auto", + "name": "auto" + }, + { + "value": "plan", + "name": "plan" + } + ], + "category": "mode" + }, + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-a", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ], + "choices": [ + { + "configId": "mode", + "value": "auto" + }, + { + "configId": "mode", + "value": "plan" + } + ], + "answers": [ + { + "configOptions": [ + { + "id": "mode", + "name": "mode", + "type": "select", + "currentValue": "plan", + "options": [ + { + "value": "read-only", + "name": "read-only" + }, + { + "value": "auto", + "name": "auto" + }, + { + "value": "plan", + "name": "plan" + } + ], + "category": "mode" + }, + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-a", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ] + } + ], + "expected": { + "requests": [ + { + "configId": "mode", + "value": "plan" + } + ], + "failure": null + } + }, + { + "name": "choiceEqualToCurrentValueSendsNothing", + "description": "Returning to the confirmed value needs no request.", + "catalog": [ + { + "id": "mode", + "name": "mode", + "type": "select", + "currentValue": "read-only", + "options": [ + { + "value": "read-only", + "name": "read-only" + }, + { + "value": "auto", + "name": "auto" + }, + { + "value": "plan", + "name": "plan" + } + ], + "category": "mode" + }, + { + "id": "model", + "name": "model", + "type": "select", + "currentValue": "model-a", + "options": [ + { + "value": "model-a", + "name": "model-a" + }, + { + "value": "model-b", + "name": "model-b" + } + ], + "category": "model" + }, + { + "id": "reasoning_effort", + "name": "reasoning_effort", + "type": "select", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "medium" + }, + { + "value": "high", + "name": "high" + } + ], + "category": "thought_level" + } + ], + "choices": [ + { + "configId": "mode", + "value": "read-only" + } + ], + "answers": [], + "expected": { + "requests": [], + "failure": null + } + } + ] +} diff --git a/shared/platform-feature-matrix/features/agent-connection-model-switching.json b/shared/platform-feature-matrix/features/agent-connection-model-switching.json index 79ba2f2635..edcf312f0d 100644 --- a/shared/platform-feature-matrix/features/agent-connection-model-switching.json +++ b/shared/platform-feature-matrix/features/agent-connection-model-switching.json @@ -15,7 +15,10 @@ "rust/lithe-agent-host/tests/real_agent.rs", "macos/Sources/Lithe/Views/Agent/AgentReasoningEffortControl.swift", "macos/Tests/LitheTests/AgentSessionSelectorLayoutTests.swift", - "macos/Tests/LitheTests/AgentSessionSelectorPresentationTests.swift" + "macos/Tests/LitheTests/AgentSessionSelectorPresentationTests.swift", + "rust/lithe-agent-host/src/next_turn_config.rs", + "shared/fixtures/agent/next-turn-configuration-v1.json", + "macos/Tests/LitheTests/AgentNextTurnConfigurationTests.swift" ] }, "windows": { @@ -30,10 +33,12 @@ ".agents/notes/implemented/architecture/2026-10-17-windows-agent-connection-ownership.md", "windows/tauri/tests/agent-connection-service.test.ts", "windows/tauri/src/features/agent/components/agent-session-selectors.tsx", - "windows/tauri/src/features/agent/stores/agent-parity.test.ts" + "windows/tauri/src/features/agent/stores/agent-parity.test.ts", + "rust/lithe-agent-host/src/next_turn_config.rs", + "shared/fixtures/agent/next-turn-configuration-v1.json" ] }, "owner": "Agent", "verification": "macOS:不触发 AppModel 通知或替换宿主根视图,切换 Claude/Codex,确认品牌、当前连接和模型列表立即同步;切到未准备的连接时保持会话设置加载提示,不闪现本地保存的默认模型;进程 ready 后继续等待会话确认,过期响应不解除等待;加载历史等待其配置,创建/加载/连接失败和不提供配置能力时退出加载,回车与发送按钮都禁止准备期间发送;已准备的连接来回切换不重复加载;分别在 Claude/Codex 关闭最后一个已准备标签,确认连接保持 ready、立即且只发一次 newSession,过期确认不恢复旧会话,新确认后底栏退出等待且消息发送到新会话;仍有标签时切到已有会话,断连时不创建。选择模型后等待上游确认,重新展开检查勾选,来回切换确认模型和会话分别保留;打开模型菜单后无搜索框且立即展示全部上游名称、顺序与分组,空目录有明确提示且仍能调整 Effort,当前 Agent 移除后正确回退,实际模型切换后发送最小消息验证回复。模型入口位于输入框下方 Agent 右侧,模式入口保留框内;深浅主题及280/540pt面板验证两个菜单可选择且模型与Agent同行。模型弹框至少 300pt 宽,长内容继续测量至共享宽度上限,顶部直接显示模型标题,不留搜索框占位;验证左侧勾选与hover、思考强度单行圆点滑块:中英文界面统一显示 Effort,Medium 与最长档位名称不省略;2/4/6 档及未知上游名称按实际目录显示、点击首尾档、调整强度后同一弹窗保持,等待期间禁用,拒绝后仍用已确认值,确认后能继续调整;Esc、外部点击及选择模型仍关闭;拖动仅在松开时提交一次、方向键和辅助功能可调整、禁用态不提交、确认后重新打开保持当前值、空模型目录仍可改强度、长模型列表最后一项可选择,其他配置子菜单仍按触发行定位并可关闭。 Windows 已实现连接身份切换、会话快照保留与配置确认前等待,真机往返切换验收待执行。模型入口位于输入框下方 Agent 右侧,模式入口保留框内;深浅主题及280/540pt面板验证两个菜单可选择且模型与Agent同行。模型弹框按内容测量宽度而非固定330pt,搜索框使用共享28pt控件;验证左侧勾选与hover、思考强度同级选择、名称搜索及空结果仍可改强度、长模型列表最后一项可选择,其他配置子菜单仍按触发行定位并可关闭。 Windows:用可控传输挂起首次启动,在完成前切换 Agent 或认证方式,确认先关闭旧进程再启动新配置;停止后立即重开也不得越过清理。 编辑区与侧栏同时请求相同身份时只启动一次,两个请求均在所有权登记后完成。 Windows:在真实 Tauri 窗口执行 Windows Agent 配置独立保留,切回恢复会话;模型目录完整显示,Effort 使用可访问的档位滑块。响应中预选模型、权限和 Effort,只在下一轮开始前按顺序等待 ACK,失败保留未确认状态且不发送。模型选项来自上游,不推测目录。 单元测试不替代运行时验收,未执行的真实服务及平台动作保持 pending。", - "notes": "2026-10-22:Windows Agent 配置独立保留,切回恢复会话;模型目录完整显示,Effort 使用可访问的档位滑块。响应中预选模型、权限和 Effort,只在下一轮开始前按顺序等待 ACK,失败保留未确认状态且不发送。模型选项来自上游,不推测目录。" + "notes": "2026-10-22:Windows Agent 配置独立保留,切回恢复会话;模型目录完整显示,Effort 使用可访问的档位滑块。响应中预选模型、权限和 Effort,只在下一轮开始前按顺序等待 ACK,失败保留未确认状态且不发送。模型选项来自上游,不推测目录。 2026-11-05(#1662 AGT-09):响应中预选的下一轮配置在轮次结束后一次交给 Host(applyNextTurnConfiguration),由 Host 统一按模型优先、目录顺序、逐项确认与重新校验提交。Windows 改为核对确认值、按目录顺序提交、本轮失败后仍提交预选;macOS 本轮失败后不再把暂存的续写输入自动发成新一轮,改为按该轮错误标记失败。失败提示两端使用同一组词条。两端运行时验证仍待执行。" } diff --git a/shared/platform-feature-matrix/features/agent-model-call-statistics.json b/shared/platform-feature-matrix/features/agent-model-call-statistics.json index 2c15afe8dd..39313f9538 100644 --- a/shared/platform-feature-matrix/features/agent-model-call-statistics.json +++ b/shared/platform-feature-matrix/features/agent-model-call-statistics.json @@ -22,7 +22,9 @@ "macos/Sources/Lithe/Views/Agent/AgentEditorConversationChrome.swift", "macos/Tests/LitheTests/AgentSessionSelectorLayoutTests.swift", "rust/lithe-agent-host/src/codex-config-relay.cjs", - "scripts/agent/test-codex-config-relay.mjs" + "scripts/agent/test-codex-config-relay.mjs", + "rust/lithe-agent-host/src/model_call_statistics.rs", + "shared/fixtures/agent/model-call-statistics-v1.json" ], "implementationStatus": "implemented", "verificationStatus": "pending" @@ -37,12 +39,15 @@ "rust/lithe-agent-host/src/codex-config-relay.cjs", "scripts/agent/test-codex-config-relay.mjs", "windows/tauri/src/features/agent/components/agent-observed-statistics.tsx", - "windows/tauri/src/features/agent/types/agent-observations.test.ts" + "windows/tauri/src/features/agent/types/agent-observations.test.ts", + "rust/lithe-agent-host/src/model_call_statistics.rs", + "shared/fixtures/agent/model-call-statistics-v1.json", + "windows/tauri/src/features/agent/types/agent-observations.ts" ], "implementationStatus": "implemented", "verificationStatus": "pending" }, "owner": "Agent", "verification": "macOS:在 Agent 设置开启“模型调用统计”,用 API Key 模式的 Claude 与 Codex 各完成一轮带工具调用的对话,确认 Agent 正常回复;点击会话详情显示会话统计(模型用时、工具与授权用时、TTFT、TPS)、Token 明细和上下文构成;发送旁圆环悬停仅显示百分比与已用/容量,点击展开上下文明细,数值与服务商控制台大致一致;每轮页脚显示模型调用次数、首字和速度,非流式响应有标记。关闭开关并重新连接后,步数、TPS、TTFT 与上下文构成隐藏,只显示轮次、Agent 上报的最近一轮 Token 与上下文占用;Codex订阅与API Key模式共用可选统计。并发两个会话时不串数据。窄宽面板、深浅主题检查布局。Windows 已消费 observeModelCalls 与 modelCall 事件并呈现观测统计。受控代理可验证 UI 与持久化;真实供应商代理观测仍待验收。 统计与上下文入口统一位于发送旁,顶部不再显示重复信息按钮;有报告显示用量圆环,未上报显示信息图标,均打开同一可滚动面板,窄面板可查看全部会话、Token与缓存命中、上下文四类分项及工具/MCP数量;主界面不常驻统计长文本。发送旁同一入口同时展示上下文构成、会话统计与Token明细,标题关闭按钮、Esc、外部点击关闭同一弹窗,历史快照仅显示用量数字,未上报不显示为0%;隐藏工具栏或切换会话关闭原弹层,编辑页与工具窗口数据保持一致。 上下文与MCP共用多色容量条和图例,缺少分项不显示伪造零值或技能分类,详情仅展示上下文构成、会话与Token统计,移除更改区、Git分支、变更文件数、Agent编辑行数和未编辑文件提示;弹窗与右侧详情栏一致,文件活动栏及回撤仍可用。 有分项数据后面板底部不常驻估算说明和分隔线;分项比例仍有~,悬停显示估算Token及按请求大小估算/按供应商输入校准的口径。无分项的未知或启用指引继续保留。 开启统计后,Codex订阅重连并发送消息,验证四类分项、调用次数、TTFT/TPS和缓存命中;关闭统计重连保持原生直连。WebSocket压缩、分片、控制帧和认证头原样透传,预热不计数,连续两轮基于完整上下文估算,未知前序ID不编造分项;旧历史缺分项等待新请求,不显示“订阅不统计”提示。原生Codex与本地假服务验收不等于真实供应商或Windows运行验收。 原生account/read仅对普通后台且NO_CONSTRAINT启用采集;地区受限、未知或失败保留原生直连,账户变更关闭已观察连接。 会话详情展开并滚动至会话统计与Token用量,确认左侧边框竖向且无横穿面板中间的多余线;正常标题分隔、滚动和关闭行为保留,深浅主题均检查。 会话统计不显示“模型调用由本机代理观测”说明,Token卡片不显示“本会话所有模型请求由服务商返回的计数”说明;数值、标题分隔和卡片间距正常,无说明残留空白;缺失统计指引、缺失用量下界及Agent原生计数口径按原状态保留。 确定性回放account/read请求→account/updated或account/login/completed通知→旧成功响应→新建/恢复/分叉,确认同邮箱工作区切换也保持原生路由,通知后的新查询成功才允许观察;已观察连接仍关闭。darwin/win32协议模拟均覆盖,不等于Windows原生验收。 Windows:在真实 Tauri 窗口执行 Windows 消费 Host 模型调用观测,展示调用数、输入输出 Token、首 Token 延迟、输出速度、模型耗时与非流式调用;未知用量保留未知,部分观测按下界提示。按会话持久化累计数字,未保存原始请求、正文或凭据。真实供应商代理观测仍待验收。 单元测试不替代运行时验收,未执行的真实服务及平台动作保持 pending。 Claude 订阅(本机 Claude Code 账号)与 API Key、Codex 订阅一样可观测:发送一轮后上下文分项有数值,Claude Code 在会话开始时自己发的“起标题”请求不计入步数、首字延迟和输出速度,但它花掉的 Token 计入 Token 合计。说明文字统一收进 ⓘ(详情栏卡片标题行、发送旁面板标题旁),悬停小卡片仍直接显示。 macOS 确定性回放一条有 usage 的标题请求加一条缺 usage 的普通或辅助请求,确认缺失次数为 1、Token 保持下界;全部有 usage 时缺失为 0。仅标题请求也显示与保存真实 Token,重载合并后请求数继续累计,对话步数仍不含标题;旧统计文档无新计数字段时可读取。", - "notes": "2026-10-22:Windows 消费 Host 模型调用观测,展示调用数、输入输出 Token、首 Token 延迟、输出速度、模型耗时与非流式调用;未知用量保留未知,部分观测按下界提示。按会话持久化累计数字,未保存原始请求、正文或凭据。真实供应商代理观测仍待验收。 2026-10-25:Claude 订阅经透传代理观测;模型调用事件新增 auxiliary 标记,起标题请求不计步数。" + "notes": "2026-10-22:Windows 消费 Host 模型调用观测,展示调用数、输入输出 Token、首 Token 延迟、输出速度、模型耗时与非流式调用;未知用量保留未知,部分观测按下界提示。按会话持久化累计数字,未保存原始请求、正文或凭据。真实供应商代理观测仍待验收。 2026-10-25:Claude 订阅经透传代理观测;模型调用事件新增 auxiliary 标记,起标题请求不计步数。 2026-11-05(#1662 AGT-07):统计口径由 Host 在 modelCall.statistics 中给出,两端只相加。Windows 不再把 HTTP 失败的非流式请求计入“非流式”,上下文构成改为 Host 标记的最近一次主请求(辅助请求和已发工具后的无工具请求不再覆盖);macOS 行为不变。两端运行时验证仍待执行。" } diff --git a/windows/tauri/src/features/agent/components/agent-observed-statistics.tsx b/windows/tauri/src/features/agent/components/agent-observed-statistics.tsx index 8dad56137b..82f94972ee 100644 --- a/windows/tauri/src/features/agent/components/agent-observed-statistics.tsx +++ b/windows/tauri/src/features/agent/components/agent-observed-statistics.tsx @@ -1,5 +1,5 @@ import { useTranslation } from "@/i18n/locale-provider"; -import { modelCallTotals, type AgentModelCall, type AgentModelCallTotals } from "../types/agent-observations"; +import { latestContext, modelCallTotals, type AgentModelCall, type AgentModelCallTotals } from "../types/agent-observations"; /** Provider observations and ACP counters have different scopes; never sum them. */ export function AgentObservedStatistics({ calls, totals = modelCallTotals(calls) }: { calls: AgentModelCall[]; totals?: AgentModelCallTotals }) { @@ -27,8 +27,8 @@ export function AgentObservedStatistics({ calls, totals = modelCallTotals(calls) export function AgentContextComposition({ calls }: { calls: AgentModelCall[] }) { const { t, language } = useTranslation(); - // Only the latest request describes the current context; billing is cumulative. - const context = calls[calls.length - 1]?.context; + // The Host marks which request describes the current context; billing is cumulative. + const context = latestContext(calls); if (context == null) return

{t("agent.stats.noComposition")}

; const entries = [ { key: "system", count: context.systemPromptTokens, color: "bg-primary" }, diff --git a/windows/tauri/src/features/agent/stores/agent-connection-service.ts b/windows/tauri/src/features/agent/stores/agent-connection-service.ts index cc25aa2ac3..a430f392fa 100644 --- a/windows/tauri/src/features/agent/stores/agent-connection-service.ts +++ b/windows/tauri/src/features/agent/stores/agent-connection-service.ts @@ -62,7 +62,7 @@ export function agentConnection(): AgentConnectionModel { write: (sessionID, statistics) => { if (workspacePath && connectionAgentID) writeAgentStatistics(workspacePath, connectionAgentID, sessionID, statistics); }, - }); + }, (key) => translator()(key)); return model; } diff --git a/windows/tauri/src/features/agent/stores/agent-connection.model.ts b/windows/tauri/src/features/agent/stores/agent-connection.model.ts index db77d05998..1b57564862 100644 --- a/windows/tauri/src/features/agent/stores/agent-connection.model.ts +++ b/windows/tauri/src/features/agent/stores/agent-connection.model.ts @@ -42,6 +42,7 @@ import { import { parseTurnUsage, startTurn } from "../types/agent-turn-statistics"; import { addModelCall, childSubtree, finishChildren, parseModelCall, parseNotice, retainSubagentHistory, terminalChild, updateChild, type AgentNotice } from "../types/agent-observations"; import { contextModels, type AgentStatisticsStore } from "../types/agent-session-statistics"; +import { createTranslator, DEFAULT_DISPLAY_LANGUAGE } from "@/i18n/locale"; import type { AgentLaunchConfiguration, AgentTransport, @@ -95,6 +96,15 @@ function asString(value: unknown): string | null { return typeof value === "string" ? value : null; } +/** Localizes a Host next-turn failure code; a failed request keeps the Agent's own message. */ +function nextTurnFailureMessage(translate: (key: string) => string, failure: string, upstream: string | null): string { + switch (failure) { + case "notConfirmed": return translate("native.theAgentDidNotConfirmTheSelectedSessionSetting"); + case "requestFailed": return upstream ?? translate("native.theAgentRequestFailed"); + default: return translate("native.theAgentNoLongerSupportsTheSelectedSessionSetting"); + } +} + function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error); } @@ -227,6 +237,8 @@ export class AgentConnectionModel { now: () => number = () => performance.now(), private readonly onSessionCreated?: (sessionID: string) => void, private readonly statisticsStore?: AgentStatisticsStore, + /** Localizes Host failure codes; the product passes the selected display language. */ + private readonly translate: (key: string) => string = createTranslator(DEFAULT_DISPLAY_LANGUAGE), ) { this.transport = transport; this.scheduler = scheduler; @@ -882,7 +894,7 @@ export class AgentConnectionModel { case "modelCall": { if (sessionID === null) return; const current = this.snapshot.conversations[sessionID]; - const call = parseModelCall(event.call); + const call = parseModelCall(event.statistics); if (current === undefined || current.isLoading || call === null) return; this.editConversation(sessionID, (view) => ({ ...view, statistics: { ...view.statistics, calls: addModelCall(view.statistics.calls, call) }, @@ -1076,7 +1088,19 @@ export class AgentConnectionModel { this.applyConfiguration(event.configOptions, sessionID); this.editConversation(sessionID, (current) => ({ ...current, pendingConfigToken: null })); this.applyPendingNotice(sessionID); - this.applyStagedConfiguration(sessionID); + return; + } + case "nextTurnConfigured": { + if (sessionID === null || token === null) return; + const conversation = this.snapshot.conversations[sessionID]; + if (conversation === undefined || conversation.pendingConfigToken !== token) return; + // Settings the Agent confirmed before a failure stay applied. + if (event.configOptions !== undefined) this.applyConfiguration(event.configOptions, sessionID); + const failure = asString(event.failure); + this.editConversation(sessionID, (current) => ({ ...current, pendingConfigToken: null, stagedConfig: {}, + configurationError: failure === null ? null : nextTurnFailureMessage(this.translate, failure, asString(event.message)) })); + this.applyPendingNotice(sessionID); + this.resumeContinuation(sessionID); return; } case "turnCancelling": @@ -1256,9 +1280,11 @@ export class AgentConnectionModel { isResponding: false, isCancelling: false, pendingPermissions: [], - quiet: false, retry: null, stagedConfig: {}, subagents: finishChildren(current.subagents), + quiet: false, retry: null, subagents: finishChildren(current.subagents), errorMessage: message, })); + // A failed turn does not withdraw the user's next-turn settings. + this.applyStagedConfiguration(sessionID); return; } this.update({ errorMessage: message }); @@ -1353,28 +1379,17 @@ export class AgentConnectionModel { if (this.retiredTurnIDs.size > 1024) this.retiredTurnIDs = new Set([...this.retiredTurnIDs].slice(-512)); } - /** Apply one confirmed option at a time; model changes can replace the catalog. */ + /** Hand every next-turn choice to the Host, which orders, revalidates and confirms them. */ private applyStagedConfiguration(sessionID: string): void { const view = this.snapshot.conversations[sessionID]; - if (view === undefined || view.isResponding || view.pendingConfigToken !== null) return; - const entries = Object.entries(view.stagedConfig).sort(([left], [right]) => - Number(view.configOptions.find((option) => option.id === right)?.category === "model") - Number(view.configOptions.find((option) => option.id === left)?.category === "model")); - const entry = entries[0]; - if (entry === undefined) { this.resumeContinuation(sessionID); return; } - const [id, value] = entry; - const option = view.configOptions.find((option) => option.id === id); - const stagedConfig = { ...view.stagedConfig }; - delete stagedConfig[id]; - if (!view.isAttached || option === undefined || !option.choices.some((choice) => choice.id === value)) { - this.editConversation(sessionID, (current) => ({ ...current, stagedConfig: {}, configurationError: "The Agent no longer offers the selected configuration. Select it again." })); - this.resumeContinuation(sessionID); - return; - } - this.editConversation(sessionID, (current) => ({ ...current, stagedConfig })); - if (option.currentValue === value) { this.applyStagedConfiguration(sessionID); return; } + if (view === undefined || !view.isAttached || view.isLoading || view.isResponding || view.pendingConfigToken !== null) return; + const choices = Object.entries(view.stagedConfig).sort(([left], [right]) => left.localeCompare(right)) + .map(([configId, value]) => ({ configId, value })); + if (choices.length === 0) { this.resumeContinuation(sessionID); return; } + const catalog = view.configOptions.map((option) => ({ id: option.id, category: option.category, currentValue: option.currentValue, choices: option.choices.map((choice) => choice.id) })); const token = this.makeToken(); this.editConversation(sessionID, (current) => ({ ...current, pendingConfigToken: token, configurationError: null })); - if (!this.sendCommand({ kind: "setConfigOption", token, sessionId: sessionID, configId: id, value })) this.requestFailed(token, sessionID, "The Agent is not connected."); + if (!this.sendCommand({ kind: "applyNextTurnConfiguration", token, sessionId: sessionID, catalog, choices })) this.requestFailed(token, sessionID, this.snapshot.errorMessage ?? "The Agent is not connected."); } private apply(update: Record, sessionID: string): void { diff --git a/windows/tauri/src/features/agent/stores/agent-parity.test.ts b/windows/tauri/src/features/agent/stores/agent-parity.test.ts index 7baca84c60..7741da2bd0 100644 --- a/windows/tauri/src/features/agent/stores/agent-parity.test.ts +++ b/windows/tauri/src/features/agent/stores/agent-parity.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import fixture from "../../../../../../shared/fixtures/agent/acp-events-v1.json"; +import { createTranslator, DEFAULT_DISPLAY_LANGUAGE } from "@/i18n/locale"; import { AgentConnectionModel } from "./agent-connection.model"; import type { AgentTransport } from "../services/agent-transport"; import type { AgentSessionStatistics } from "../types/agent-session-statistics"; @@ -233,37 +234,70 @@ describe("Agent parity lifecycle", () => { expect(view().reviewedEdits).toBeUndefined(); }); - test("next-turn settings apply model first, wait for each ACK, then continue", () => { + test("next-turn settings go to the Host as one batch after the turn, then continue", () => { model.send("First turn"); model.setConfigOption("reasoning_effort", "high"); model.setConfigOption("model", "other"); model.send("Continue"); deliver({ ...fixture.events.steeringResult, token: command("steer").token, outcome: "promptRequired" }); - expect(commands.filter((item) => item.kind === "setConfigOption")).toHaveLength(0); + expect(commands.filter((item) => item.kind === "applyNextTurnConfiguration")).toHaveLength(0); deliver({ kind: "turnFinished", sessionId: "session-1", stopReason: "end_turn" }); - expect(command("setConfigOption").configId).toBe("model"); + // The Host orders, revalidates and confirms the choices; the product sends them once. + const batch = command("applyNextTurnConfiguration"); + expect(batch.choices).toEqual([{ configId: "model", value: "other" }, { configId: "reasoning_effort", value: "high" }]); + expect((batch.catalog as { id: string }[]).map((option) => option.id)).toEqual(["model", "reasoning_effort"]); + expect(commands.filter((item) => item.kind === "setConfigOption")).toHaveLength(0); expect(commands.filter((item) => item.kind === "prompt")).toHaveLength(1); - deliver({ kind: "sessionConfigured", token: command("setConfigOption").token, sessionId: "session-1", configOptions: options("other") }); - expect(command("setConfigOption").configId).toBe("reasoning_effort"); - deliver({ kind: "sessionConfigured", token: command("setConfigOption").token, sessionId: "session-1", configOptions: options("other").map((item) => item.id === "reasoning_effort" ? { ...item, currentValue: "high" } : item) }); + deliver({ kind: "sessionConfigured", token: "stale", sessionId: "session-1", configOptions: options("other") }); + expect(view().pendingConfigToken).toBe(batch.token as string); + deliver({ kind: "nextTurnConfigured", token: batch.token, sessionId: "session-1", configOptions: options("other").map((item) => item.id === "reasoning_effort" ? { ...item, currentValue: "high" } : item) }); expect(command("prompt").text).toBe("Continue"); + expect(view().configOptions[0].currentValue).toBe("other"); expect(view().stagedConfig).toEqual({}); }); - test("configuration rejection preserves confirmed value and fails the queued continuation", () => { + test.each([ + ["notConfirmed", "native.theAgentDidNotConfirmTheSelectedSessionSetting"], + ["unsupported", "native.theAgentNoLongerSupportsTheSelectedSessionSetting"], + ])("a %s next-turn failure keeps confirmed settings and fails the queued continuation", (failure, key) => { + const message = createTranslator(DEFAULT_DISPLAY_LANGUAGE)(key); model.send("First turn"); model.setConfigOption("model", "other"); model.send("Continue"); deliver({ ...fixture.events.steeringResult, token: command("steer").token, outcome: "promptRequired" }); deliver({ kind: "turnFinished", sessionId: "session-1", stopReason: "end_turn" }); - deliver({ kind: "requestFailed", token: command("setConfigOption").token, sessionId: "session-1", message: "Not available" }); + deliver({ kind: "nextTurnConfigured", token: command("applyNextTurnConfiguration").token, sessionId: "session-1", failure }); expect(view().configOptions[0].currentValue).toBe("example-model"); expect(view().pendingConfigToken).toBeNull(); + expect(view().configurationError).toBe(message); expect(command("prompt").text).toBe("First turn"); - expect(view().messages.slice(-1)[0]?.delivery).toEqual({ failed: "Not available" }); + expect(view().messages.slice(-1)[0]?.delivery).toEqual({ failed: message }); expect(model.getSnapshot().hasPendingContinuation).toBe(false); }); + test("a failed request keeps the Agent's message", () => { + model.send("First turn"); + model.setConfigOption("model", "other"); + deliver({ kind: "turnFinished", sessionId: "session-1", stopReason: "end_turn" }); + deliver({ kind: "nextTurnConfigured", token: command("applyNextTurnConfiguration").token, sessionId: "session-1", failure: "requestFailed", message: "Not available" }); + expect(view().configurationError).toBe("Not available"); + deliver({ kind: "requestFailed", token: command("applyNextTurnConfiguration").token, sessionId: "session-1", message: "Late" }); + expect(view().configurationError).toBe("Not available"); + }); + + test("a failed turn still applies next-turn settings but never replays the deferred input", () => { + model.send("First turn"); + model.setConfigOption("model", "other"); + model.send("Continue"); + deliver({ ...fixture.events.steeringResult, token: command("steer").token, outcome: "promptRequired" }); + deliver({ kind: "requestFailed", token: null, sessionId: "session-1", message: "Turn failed" }); + expect(view().messages.slice(-1)[0]?.delivery).toEqual({ failed: "Turn failed" }); + expect(command("applyNextTurnConfiguration").choices).toEqual([{ configId: "model", value: "other" }]); + deliver({ kind: "nextTurnConfigured", token: command("applyNextTurnConfiguration").token, sessionId: "session-1", configOptions: options("other") }); + expect(commands.filter((item) => item.kind === "prompt")).toHaveLength(1); + expect(view().configOptions[0].currentValue).toBe("other"); + }); + test("activity clears retry indicators and retired retries cannot contaminate a later turn", () => { model.send("First turn"); deliver(fixture.events.turnActivityQuiet); @@ -292,16 +326,16 @@ describe("Agent parity lifecycle", () => { model.send("First turn"); deliver({ kind: "turnFinished", sessionId: "session-1", stopReason: "end_turn" }); model.send("Second turn"); - deliver({ kind: "modelCall", sessionId: "session-1", afterTurnFinished: true, call: { api: "messages", model: "test", status: 200, streaming: false, durationMs: 12 } }); + deliver({ ...fixture.events.modelCallNonStreaming, afterTurnFinished: true }); expect(view().modelCalls).toHaveLength(1); - expect(view().modelCalls[0].usage).toBeNull(); + expect(view().modelCalls[0].nonStreamingSteps).toBe(1); + expect(view().statistics.calls.nonStreaming).toBe(1); expect(view().activeTurn?.modelCalls).toEqual([]); }); test("durable statistics survive closing and loading without counting history replay", () => { model.send("Count once"); - deliver({ kind: "modelCall", sessionId: "session-1", call: { api: "messages", status: 200, streaming: true, durationMs: 900, firstTokenMs: 100, - usage: { inputTokens: 20, cacheReadTokens: 5, cacheWriteTokens: 0, outputTokens: 10 } } }); + deliver(fixture.events.modelCall); deliver(fixture.events.turnFinishedWithUsage); const saved = statistics.get("session-1")!; expect(saved.turnCount).toBe(1); @@ -310,7 +344,7 @@ describe("Agent parity lifecycle", () => { model.selectSession("session-1"); update({ sessionUpdate: "user_message_chunk", content: { type: "text", text: "Count once" } }); // Even if a peer replays observations, loading must never charge them twice. - deliver({ kind: "modelCall", sessionId: "session-1", call: { api: "messages", status: 200, durationMs: 900 } }); + deliver(fixture.events.modelCallNonStreaming); deliver({ kind: "sessionLoaded", token: command("loadSession").token, sessionId: "session-1", configOptions: options() }); deliver({ kind: "turnFinished", sessionId: "session-1", stopReason: "end_turn" }); expect(view().statistics).toEqual(saved); diff --git a/windows/tauri/src/features/agent/types/agent-observations.test.ts b/windows/tauri/src/features/agent/types/agent-observations.test.ts index d4978bd224..cf3e112b5d 100644 --- a/windows/tauri/src/features/agent/types/agent-observations.test.ts +++ b/windows/tauri/src/features/agent/types/agent-observations.test.ts @@ -1,5 +1,6 @@ import { describe, expect, test } from "bun:test"; -import { finishChildren, modelCallTotals, parseModelCall, updateChild, type AgentSubagent } from "./agent-observations"; +import statisticsFixture from "../../../../../../shared/fixtures/agent/model-call-statistics-v1.json"; +import { finishChildren, latestContext, modelCallTotals, parseModelCall, updateChild, type AgentSubagent } from "./agent-observations"; const child = (id: string, parentID: string): AgentSubagent => ({ id, parentID, name: id, task: "Inspect", state: "running", messages: [], plan: [], contextUsage: null, @@ -17,25 +18,25 @@ describe("Agent observations", () => { expect(updateChild(result[0], { sessionUpdate: "agent_message_chunk", content: { text: "late" } })).toBe(result[0]); }); - test("missing and malformed provider usage stays unknown in cumulative totals", () => { - const known = parseModelCall({ api: "responses", status: 200, durationMs: 900, streaming: true, - firstTokenMs: 100, usage: { inputTokens: 20, cacheReadTokens: 5, cacheWriteTokens: 0, outputTokens: 10 }, - })!; - const unknown = parseModelCall({ api: "responses", status: 500, durationMs: 10, usage: { inputTokens: -1 } })!; - expect(known.usage?.reasoningTokens).toBeNull(); - expect(unknown.usage).toBeNull(); - expect(modelCallTotals([known, unknown])).toMatchObject({ calls: 2, input: 20, cacheRead: 5, cacheWrite: 0, output: 10, lowerBound: true, - durationMs: 910, latencyCount: 1, latencyMs: 100, generatingMs: 800, streamingOutput: 10, nonStreaming: 1 }); - expect(parseModelCall({ api: "responses", status: 200, durationMs: Infinity })).toBeNull(); + test("Host contributions sum to the shared totals", () => { + for (const entry of statisticsFixture.cases) { + const calls = entry.events.map((event) => parseModelCall(event.statistics)!); + const total = entry.total as Record; + const expected = parseModelCall(total)!; + expect(modelCallTotals(calls)).toEqual({ + calls: expected.steps, input: expected.inputTokens, cacheRead: expected.cacheReadTokens, cacheWrite: expected.cacheWriteTokens, + output: expected.outputTokens, lowerBound: entry.events.some((event) => event.statistics.requests > event.statistics.callsWithUsage), + durationMs: expected.durationMs, latencyMs: expected.firstTokenMs, latencyCount: expected.firstTokenCount, + generatingMs: expected.generationMs, streamingOutput: expected.generatedTokens, nonStreaming: expected.nonStreamingSteps, + }); + expect(latestContext(calls)).toEqual(expected.context); + } }); - test("auxiliary requests spend tokens but are not steps or latency samples", () => { - const title = parseModelCall({ api: "anthropicMessages", status: 200, durationMs: 2000, streaming: true, firstTokenMs: 1900, - auxiliary: true, usage: { inputTokens: 10, cacheReadTokens: 0, cacheWriteTokens: 0, outputTokens: 16 } })!; - const step = parseModelCall({ api: "anthropicMessages", status: 200, durationMs: 1000, streaming: true, firstTokenMs: 100, - usage: { inputTokens: 20, cacheReadTokens: 0, cacheWriteTokens: 0, outputTokens: 4 } })!; - expect(title.auxiliary).toBe(true); - expect(modelCallTotals([title, step])).toMatchObject({ calls: 1, input: 30, output: 20, durationMs: 1000, - latencyCount: 1, latencyMs: 100, generatingMs: 900, streamingOutput: 4 }); + test("malformed contributions are dropped instead of guessed", () => { + const valid = statisticsFixture.cases[0].events[0].statistics; + expect(parseModelCall({ ...valid, steps: -1 })).toBeNull(); + expect(parseModelCall({ ...valid, durationMs: Infinity })).toBeNull(); + expect(parseModelCall({ api: "responses", status: 200, durationMs: 1 })).toBeNull(); }); }); diff --git a/windows/tauri/src/features/agent/types/agent-observations.ts b/windows/tauri/src/features/agent/types/agent-observations.ts index d046fb473d..dc100454cf 100644 --- a/windows/tauri/src/features/agent/types/agent-observations.ts +++ b/windows/tauri/src/features/agent/types/agent-observations.ts @@ -23,17 +23,20 @@ export interface AgentNotice { description: string | null; } +export interface AgentModelCallContext { systemPromptTokens: number; toolTokens: number; mcpToolTokens: number; messageTokens: number; toolCount: number; mcpToolCount: number; scaledToUsage: boolean } + +/** + * The Host's accounting of one observed provider request: the `statistics` of a + * `modelCall` event. The Host decides which requests are steps, failures, + * non-streaming answers or the current context; this product only adds them. + * Shape fixed by `shared/fixtures/agent/model-call-statistics-v1.json`. + */ export interface AgentModelCall { - api: string; - model: string | null; - status: number; - streaming: boolean; - durationMs: number; - firstTokenMs: number | null; - usage: { inputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; outputTokens: number; reasoningTokens: number | null } | null; - context: { systemPromptTokens: number; toolTokens: number; mcpToolTokens: number; messageTokens: number; toolCount: number; mcpToolCount: number; scaledToUsage: boolean } | null; - /** A background request the Agent made for itself (Claude Code naming the session): its tokens count, it is not a step. */ - auxiliary: boolean; + requests: number; steps: number; failedSteps: number; nonStreamingSteps: number; durationMs: number; + inputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; outputTokens: number; reasoningTokens: number | null; + callsWithUsage: number; firstTokenMs: number; firstTokenCount: number; generationMs: number; generatedTokens: number; + /** Present only when this request describes the conversation's current prompt. */ + context: AgentModelCallContext | null; } export function record(value: unknown): value is Record { @@ -106,27 +109,31 @@ export function parseNotice(update: Record): AgentNotice | null return { id: failure.id, revision: count(failure.revision) ?? 0, severity: String(failure.severity ?? "error"), title: failure.title, description: typeof failure.details === "string" ? failure.details : null }; } +const MODEL_CALL_COUNTERS = ["requests", "steps", "failedSteps", "nonStreamingSteps", "durationMs", "inputTokens", "cacheReadTokens", "cacheWriteTokens", + "outputTokens", "callsWithUsage", "firstTokenMs", "firstTokenCount", "generationMs", "generatedTokens"] as const; + export function parseModelCall(value: unknown): AgentModelCall | null { - if (!record(value) || typeof value.api !== "string") return null; - const status = count(value.status), durationMs = count(value.durationMs); - if (status === null || durationMs === null) return null; - const usage = record(value.usage) ? value.usage : null; + if (!record(value) || MODEL_CALL_COUNTERS.some((key) => count(value[key]) === null)) return null; const context = record(value.context) ? value.context : null; - const validUsage = usage !== null && ["inputTokens", "cacheReadTokens", "cacheWriteTokens", "outputTokens"].every((key) => count(usage[key]) !== null); const validContext = context !== null && ["systemPromptTokens", "toolTokens", "mcpToolTokens", "messageTokens", "toolCount", "mcpToolCount"].every((key) => count(context[key]) !== null); + const counters = Object.fromEntries(MODEL_CALL_COUNTERS.map((key) => [key, value[key] as number])) as Record<(typeof MODEL_CALL_COUNTERS)[number], number>; return { - api: value.api, model: typeof value.model === "string" ? value.model : null, status, - streaming: value.streaming === true, durationMs, firstTokenMs: count(value.firstTokenMs), auxiliary: value.auxiliary === true, - usage: validUsage ? { inputTokens: usage.inputTokens as number, cacheReadTokens: usage.cacheReadTokens as number, cacheWriteTokens: usage.cacheWriteTokens as number, outputTokens: usage.outputTokens as number, reasoningTokens: count(usage.reasoningTokens) } : null, + ...counters, reasoningTokens: count(value.reasoningTokens), context: validContext ? { systemPromptTokens: context.systemPromptTokens as number, toolTokens: context.toolTokens as number, mcpToolTokens: context.mcpToolTokens as number, messageTokens: context.messageTokens as number, toolCount: context.toolCount as number, mcpToolCount: context.mcpToolCount as number, scaledToUsage: context.scaledToUsage === true } : null, }; } -/** No accounting is inferred for requests without a provider usage report. */ +/** Sums Host contributions; no accounting is inferred here. */ export function modelCallTotals(calls: AgentModelCall[]) { return calls.reduce((total, call) => addModelCall(total, call), emptyModelCallTotals()); } +/** The Host marks the requests that describe the current prompt; the latest one wins. */ +export function latestContext(calls: AgentModelCall[]): AgentModelCallContext | null { + for (let index = calls.length - 1; index >= 0; index--) if (calls[index].context !== null) return calls[index].context; + return null; +} + export function emptyModelCallTotals() { return { calls: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, lowerBound: false, durationMs: 0, latencyMs: 0, latencyCount: 0, generatingMs: 0, streamingOutput: 0, nonStreaming: 0 }; @@ -134,29 +141,18 @@ export function emptyModelCallTotals() { export type AgentModelCallTotals = ReturnType; export function addModelCall(total: AgentModelCallTotals, call: AgentModelCall): AgentModelCallTotals { - if (call.auxiliary) { - return { - ...total, - input: total.input + (call.usage?.inputTokens ?? 0), - cacheRead: total.cacheRead + (call.usage?.cacheReadTokens ?? 0), - cacheWrite: total.cacheWrite + (call.usage?.cacheWriteTokens ?? 0), - output: total.output + (call.usage?.outputTokens ?? 0), - lowerBound: total.lowerBound || call.usage === null, - }; - } - const measuredStream = call.streaming && call.usage !== null && call.firstTokenMs !== null && call.durationMs > call.firstTokenMs; return { - calls: total.calls + 1, - input: total.input + (call.usage?.inputTokens ?? 0), - cacheRead: total.cacheRead + (call.usage?.cacheReadTokens ?? 0), - cacheWrite: total.cacheWrite + (call.usage?.cacheWriteTokens ?? 0), - output: total.output + (call.usage?.outputTokens ?? 0), - lowerBound: total.lowerBound || call.usage === null, + calls: total.calls + call.steps, + input: total.input + call.inputTokens, + cacheRead: total.cacheRead + call.cacheReadTokens, + cacheWrite: total.cacheWrite + call.cacheWriteTokens, + output: total.output + call.outputTokens, + lowerBound: total.lowerBound || call.requests > call.callsWithUsage, durationMs: total.durationMs + call.durationMs, - latencyMs: total.latencyMs + (call.firstTokenMs ?? 0), - latencyCount: total.latencyCount + (call.firstTokenMs === null ? 0 : 1), - generatingMs: total.generatingMs + (measuredStream ? call.durationMs - call.firstTokenMs! : 0), - streamingOutput: total.streamingOutput + (measuredStream ? call.usage!.outputTokens : 0), - nonStreaming: total.nonStreaming + (call.streaming ? 0 : 1), + latencyMs: total.latencyMs + call.firstTokenMs, + latencyCount: total.latencyCount + call.firstTokenCount, + generatingMs: total.generatingMs + call.generationMs, + streamingOutput: total.streamingOutput + call.generatedTokens, + nonStreaming: total.nonStreaming + call.nonStreamingSteps, }; } From 0f895d67de635b06266f68f1a02551930196e527 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Wed, 4 Nov 2026 22:34:13 -0800 Subject: [PATCH 5/8] =?UTF-8?q?feat(core):=20AGT-18=20Hook=20=E8=8D=89?= =?UTF-8?q?=E7=A8=BF=E6=A0=A1=E9=AA=8C=E4=B8=8B=E6=B2=89=E5=88=B0=20Core?= =?UTF-8?q?=EF=BC=88agent.hooks.validateDraft=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 复用 lithe-agent-host hooks 规则,macOS 与 Windows 编辑器按 Core 的逐字段结论显示问题并控制保存,删除各自的校验。 Co-Authored-By: Claude Opus 5.5 --- .../feature/2026-10-24-agent-hooks.md | 13 +- .../Features/AgentHooksFeatureModel.swift | 34 +- .../Core/Rust/RustAgentHooksService.swift | 23 + .../Views/Agent/AgentHooksSettingsView.swift | 24 +- .../LitheCoreContracts/Agent/AgentHooks.swift | 23 + .../AgentHooksFeatureModelTests.swift | 82 +- rust/lithe-agent-host/src/hooks.rs | 257 +++++- rust/lithe-agent-host/src/hooks/tests.rs | 65 ++ rust/lithe-core/src/agent/hooks.rs | 6 + .../agent/hook-draft-validation-v1.json | 806 ++++++++++++++++++ .../features/agent-hooks.json | 12 +- .../agent/services/agent-hooks.test.ts | 34 +- .../features/agent/services/agent-hooks.ts | 37 +- .../tabs/agent-hooks-settings.test.tsx | 10 +- .../components/tabs/agent-hooks-settings.tsx | 25 +- 15 files changed, 1367 insertions(+), 84 deletions(-) create mode 100644 shared/fixtures/agent/hook-draft-validation-v1.json diff --git a/.agents/notes/implemented/feature/2026-10-24-agent-hooks.md b/.agents/notes/implemented/feature/2026-10-24-agent-hooks.md index 370527bbf6..b8294587f8 100644 --- a/.agents/notes/implemented/feature/2026-10-24-agent-hooks.md +++ b/.agents/notes/implemented/feature/2026-10-24-agent-hooks.md @@ -39,11 +39,20 @@ Lithe 管理资源库并显式写入原生配置;何时运行、Shell、标准 创建与编辑分别显示「新 Hook」和「编辑 Hook」,主按钮也区分添加与保存。 Agent 使用带原有品牌标志的选择按钮及「全部」动作,只展示已支持的两个 -Agent;全不选时仍由已有校验禁止保存。macOS 复用 MCP 资源库原有的选择 +Agent;全不选时由 Core 草稿校验禁止保存。macOS 复用 MCP 资源库原有的选择 按钮外观,抽为 `AgentSelectionChip`,不再分别维护两套样式。说明继续遵守 macOS 设置的 ⓘ 规则,不复制参考页的控件下方说明段落。描述字段通过共享 文本编辑器显式选择正文字体,其他调用者继续使用原有等宽字体与控件样式。 +编辑器的字段校验只有一份规则:Agent Host 的 `hooks::validate_draft`,经 +Core `agent.hooks.validateDraft` 返回逐字段的 `{field, code}`,与 `save` 的最终 +校验共用同一组规则(#1662 AGT-18)。以前 Swift `canSave` 漏掉重复 Agent 和 +非工具事件的工具筛选、Windows `validHook` 另写了一份正则且重名单独判断, +草稿能通过编辑器却在保存时被 Host 拒绝。超时字段把原始文本交给 Core, +只接受 ASCII 数字,保存时写入 Core 解析出的秒数;两端把 +`agent.hooks.draft..` 本地化后显示在编辑器内,空名称和空命令 +只禁用保存、不显示提示,避免新建时立即报错。 + 搜索按名称、描述和命令筛选。页面必须根据筛选后的列表显示空状态:有 搜索词而无结果时提示「没有匹配的 Hook」,无搜索词且资源库为空时提示 「还没有 Hook」。不能只检查资源库总数,否则已有内容的无匹配搜索会留下 @@ -107,6 +116,8 @@ Swift 功能模型负责草稿与 UI 状态,Rust Core 负责严格命令分派 自有条目、trust 索引不变、只读/符号链接、冲突、部分失败、取消与日志恢复。 - Core `hook_contract_dispatch_is_strict_before_accessing_native_files` 校验 严格请求;Swift 与 TypeScript 读取同一个跨平台 fixture。 +- `shared/fixtures/agent/hook-draft-validation-v1.json` 由 Host、Core 分发、 + Swift 桥接与 TypeScript 请求测试共同读取,固定每个字段码。 - `./.agents/skills/write-stable-tests/scripts/verify-test-stability.sh`。 - `./.agents/skills/write-stable-tests/scripts/test-stability-macos.sh -- --filter 'AgentHooks|SettingsSidebarLayoutTests|SettingsSearchVocabularyTests|ContextMenuCoverageTests'`。 - `./scripts/macos/verify/verify-runtime-bundle-immutability.sh`、`./scripts/architecture/verify-service-boundaries.sh`、 diff --git a/macos/Sources/Lithe/Application/Features/AgentHooksFeatureModel.swift b/macos/Sources/Lithe/Application/Features/AgentHooksFeatureModel.swift index b44c1b3dba..f52fb0015e 100644 --- a/macos/Sources/Lithe/Application/Features/AgentHooksFeatureModel.swift +++ b/macos/Sources/Lithe/Application/Features/AgentHooksFeatureModel.swift @@ -6,8 +6,12 @@ import LitheCoreContracts final class AgentHooksFeatureModel: ObservableObject { enum Phase: Equatable { case idle, loading, ready, saving, failed(String) } @Published private(set) var phase: Phase = .idle - @Published private(set) var library: AgentHookLibrary? - @Published var draft: AgentHook? + @Published private(set) var library: AgentHookLibrary? { didSet { revalidate() } } + @Published var draft: AgentHook? { didSet { revalidate() } } + /// Raw timeout text; Core parses it so the integer and range rules have one owner. + @Published var timeoutText = "" { didSet { revalidate() } } + /// Core's field-level verdict for the current draft; `nil` without a draft or library. + @Published private(set) var draftValidation: AgentHookDraftValidation? @Published var query = "" private let service: any AgentHooksService @@ -18,14 +22,21 @@ final class AgentHooksFeatureModel: ObservableObject { query.isEmpty || [entry.hook.name, entry.hook.description, entry.hook.command].contains { $0.localizedCaseInsensitiveContains(query) } } } - var canSave: Bool { - guard let draft, library != nil, !isBusy else { return false } - return !draft.name.isEmpty && draft.name.utf8.count <= 80 - && draft.name.utf8.allSatisfy { (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || $0 == 45 || $0 == 95 } - && draft.description.unicodeScalars.count <= 200 && !draft.command.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - && draft.command.utf8.count <= 32768 && !draft.command.contains("\0") && !draft.agents.isEmpty - && (draft.timeoutSeconds == nil || (1...86400).contains(draft.timeoutSeconds!)) - && !(library?.hooks.contains { $0.id != draft.id && $0.hook.name.caseInsensitiveCompare(draft.name) == .orderedSame } ?? false) + var canSave: Bool { draft != nil && library != nil && !isBusy && draftValidation?.valid == true } + + /// Starts editing `hook`, seeding the timeout field from its stored value. + func beginEditing(_ hook: AgentHook) { + timeoutText = hook.timeoutSeconds.map(String.init) ?? "" + draft = hook + } + + private func revalidate() { + guard let draft, let library else { draftValidation = nil; return } + do { draftValidation = try service.validateDraft(draft, timeoutText: timeoutText, library: library) } + catch { + // log-exempt: 同一次失败已经记录过:Core 请求轨迹已记录 agent.hooks.validateDraft 的失败,保存按钮保持禁用 + draftValidation = nil + } } func load() async { @@ -36,7 +47,8 @@ final class AgentHooksFeatureModel: ObservableObject { catch { phase = .failed(error.localizedDescription) } } func save() async { - guard canSave, let draft, let library else { return } + guard canSave, var draft, let library, let validation = draftValidation else { return } + draft.timeoutSeconds = validation.timeoutSeconds phase = .saving do { self.library = try await service.save(draft, library: library) diff --git a/macos/Sources/Lithe/Core/Rust/RustAgentHooksService.swift b/macos/Sources/Lithe/Core/Rust/RustAgentHooksService.swift index 51a065863e..5da1807d51 100644 --- a/macos/Sources/Lithe/Core/Rust/RustAgentHooksService.swift +++ b/macos/Sources/Lithe/Core/Rust/RustAgentHooksService.swift @@ -14,6 +14,29 @@ struct RustAgentHooksService: AgentHooksService { var id: String? = nil } + private struct DraftRequest: Encodable, Sendable { + struct Draft: Encodable, Sendable { + let id, name, description: String + let event: AgentHookEvent + let matcher: AgentHookMatcher + let command, timeoutText: String + let agents: [String] + } + struct Existing: Encodable, Sendable { let id, name: String } + let hook: Draft + let existingHooks: [Existing] + } + + func validateDraft(_ hook: AgentHook, timeoutText: String, library: AgentHookLibrary) throws -> AgentHookDraftValidation { + let request = DraftRequest( + hook: .init(id: hook.id, name: hook.name, description: hook.description, event: hook.event, + matcher: hook.matcher, command: hook.command, timeoutText: timeoutText, agents: hook.agents), + existingHooks: library.hooks.map { .init(id: $0.id, name: $0.hook.name) }) + let result: Result = core.executeResult( + command: "agent.hooks.validateDraft", payload: request) + return try result.get() + } + func load() async throws -> AgentHookLibrary { try await run(Request(dataDirectory: directory.path, action: "read")) } func save(_ hook: AgentHook, library: AgentHookLibrary) async throws -> AgentHookLibrary { try await run(Request(dataDirectory: directory.path, action: "save", expectedRevision: library.revision, diff --git a/macos/Sources/Lithe/Views/Agent/AgentHooksSettingsView.swift b/macos/Sources/Lithe/Views/Agent/AgentHooksSettingsView.swift index 69354fff91..98f32a7d7d 100644 --- a/macos/Sources/Lithe/Views/Agent/AgentHooksSettingsView.swift +++ b/macos/Sources/Lithe/Views/Agent/AgentHooksSettingsView.swift @@ -47,7 +47,7 @@ struct AgentHooksSettingsView: View { Text(feature.query.isEmpty ? key("No Hooks yet.") : key("No matching Hooks.")) .foregroundStyle(LitheTheme.secondaryText) if feature.query.isEmpty { - Button(key("Add Hook")) { feature.draft = AgentHook(); showsEditor = true } + Button(key("Add Hook")) { feature.beginEditing(AgentHook()); showsEditor = true } .buttonStyle(LitheActionButtonStyle()).disabled(feature.isBusy) } }.frame(maxWidth: .infinity).padding(.vertical, 35) @@ -65,7 +65,7 @@ struct AgentHooksSettingsView: View { })).labelsHidden().toggleStyle(.switch).controlSize(.small) .disabled(feature.isBusy || entry.hook.pendingRemoval) .accessibilityLabel(Text(verbatim: entry.hook.name + ": " + localized("Enable Hook"))) - Button(key("Edit")) { feature.draft = entry.hook; showsEditor = true } + Button(key("Edit")) { feature.beginEditing(entry.hook); showsEditor = true } .buttonStyle(LitheActionButtonStyle()).disabled(feature.isBusy || entry.hook.pendingRemoval) Button(key("Delete")) { removal = entry }.buttonStyle(LitheActionButtonStyle()).disabled(feature.isBusy) } @@ -102,7 +102,7 @@ struct AgentHooksSettingsView: View { } @ViewBuilder private var toolbar: some View { Button(key("Reload from disk")) { run { await feature.load() } }.buttonStyle(LitheActionButtonStyle()) - Button(key("Add Hook")) { feature.draft = AgentHook(); showsEditor = true } + Button(key("Add Hook")) { feature.beginEditing(AgentHook()); showsEditor = true } .buttonStyle(LitheActionButtonStyle(isPrimary: true)).disabled(feature.library == nil) } private func localized(_ value: String.LocalizationValue) -> String { @@ -125,7 +125,6 @@ private struct AgentHookEditor: View { @ObservedObject var feature: AgentHooksFeatureModel let onSave: () -> Void @Environment(\.dismiss) private var dismiss - @State private var timeout = "" @FocusState private var nameFocused: Bool @FocusState private var descriptionFocused: Bool @@ -143,7 +142,11 @@ private struct AgentHookEditor: View { AgentLocalization.string(value, locale: locale, bundle: localizationBundle) } private func key(_ value: String.LocalizationValue) -> LocalizedStringKey { LocalizedStringKey(localized(value)) } - private var timeoutValid: Bool { timeout.isEmpty || (Int(timeout).map { (1...86400).contains($0) } ?? false) } + /// Core issue keys shown inline; an empty name or command only disables saving. + private var visibleIssueKeys: [String] { + (feature.draftValidation?.issues ?? []).filter { !($0.code == "required" && ["name", "command"].contains($0.field)) } + .map { "agent.hooks.draft.\($0.field).\($0.code)" } + } private var isNew: Bool { !(feature.library?.hooks.contains { $0.id == feature.draft?.id } ?? false) } var body: some View { VStack(spacing: 0) { @@ -185,10 +188,9 @@ private struct AgentHookEditor: View { .accessibilityLabel(Text(key("Hook command"))).accessibilityIdentifier("hook-editor.command") } row("Timeout (seconds)", info: "Leave empty to use the Agent default, or enter an integer from 1 to 86400.") { - LitheTextField(key("Agent default"), text: $timeout) + LitheTextField(key("Agent default"), text: $feature.timeoutText) .frame(width: 200).accessibilityLabel(Text(key("Timeout (seconds)"))) .accessibilityIdentifier("hook-editor.timeout") - .onChange(of: timeout) { value in feature.draft?.timeoutSeconds = value.isEmpty ? nil : Int(value) } } row("Agent") { HStack(spacing: 8) { @@ -205,6 +207,7 @@ private struct AgentHookEditor: View { } } } + ForEach(visibleIssueKeys, id: \.self) { AgentSettingsIssue(localized(String.LocalizationValue($0))) } if case .failed(let message) = feature.phase { AgentSettingsIssue(localized(String.LocalizationValue(message))) } }.padding(Layout.padding) }.frame(maxHeight: 510).fixedSize(horizontal: false, vertical: true) @@ -215,14 +218,11 @@ private struct AgentHookEditor: View { Button(key("Cancel")) { feature.draft = nil; dismiss() }.buttonStyle(LitheActionButtonStyle()).keyboardShortcut(.cancelAction) Button(isNew ? key("Add Hook") : key("Save Hook"), action: onSave) .buttonStyle(LitheActionButtonStyle(isPrimary: true)) - .disabled(!feature.canSave || !timeoutValid).keyboardShortcut(.defaultAction) + .disabled(!feature.canSave).keyboardShortcut(.defaultAction) }.padding(Layout.padding) }.font(LitheTheme.settingsFont).frame(width: Layout.width).background(LitheTheme.settingsSurface) .disabled(feature.isBusy) - .onAppear { - timeout = feature.draft?.timeoutSeconds.map(String.init) ?? "" - nameFocused = true - } + .onAppear { nameFocused = true } .onChange(of: feature.draft?.event) { event in if event?.supportsMatcher != true { feature.draft?.matcher = .all } } .interactiveDismissDisabled(feature.isBusy) } diff --git a/macos/Sources/LitheCoreContracts/Agent/AgentHooks.swift b/macos/Sources/LitheCoreContracts/Agent/AgentHooks.swift index 58abc85ae9..5b137a078b 100644 --- a/macos/Sources/LitheCoreContracts/Agent/AgentHooks.swift +++ b/macos/Sources/LitheCoreContracts/Agent/AgentHooks.swift @@ -90,7 +90,27 @@ public struct AgentHookLibrary: Decodable, Equatable, Sendable { } } +/// One field-level problem from Core's `agent.hooks.validateDraft`; `field` and +/// `code` are stable identifiers the editor localizes. +public struct AgentHookDraftIssue: Decodable, Equatable, Sendable { + public let field: String + public let code: String + public init(field: String, code: String) { self.field = field; self.code = code } +} + +/// Core verdict for an unsaved draft. `timeoutSeconds` is the parsed timeout to store. +public struct AgentHookDraftValidation: Decodable, Equatable, Sendable { + public let valid: Bool + public let issues: [AgentHookDraftIssue] + public let timeoutSeconds: Int? + public init(valid: Bool, issues: [AgentHookDraftIssue], timeoutSeconds: Int?) { + self.valid = valid; self.issues = issues; self.timeoutSeconds = timeoutSeconds + } +} + public protocol AgentHooksService: Sendable { + /// Pure, file-free validation using the same rules as `save`; cheap enough per edit. + func validateDraft(_ hook: AgentHook, timeoutText: String, library: AgentHookLibrary) throws -> AgentHookDraftValidation func load() async throws -> AgentHookLibrary func save(_ hook: AgentHook, library: AgentHookLibrary) async throws -> AgentHookLibrary func remove(id: String, library: AgentHookLibrary) async throws -> AgentHookLibrary @@ -99,6 +119,9 @@ public protocol AgentHooksService: Sendable { public struct UnavailableAgentHooksService: AgentHooksService { public init() {} + public func validateDraft(_ hook: AgentHook, timeoutText: String, library: AgentHookLibrary) throws -> AgentHookDraftValidation { + throw CocoaError(.featureUnsupported) + } public func load() async throws -> AgentHookLibrary { throw CocoaError(.featureUnsupported) } public func save(_ hook: AgentHook, library: AgentHookLibrary) async throws -> AgentHookLibrary { throw CocoaError(.featureUnsupported) } public func remove(id: String, library: AgentHookLibrary) async throws -> AgentHookLibrary { throw CocoaError(.featureUnsupported) } diff --git a/macos/Tests/LitheTests/AgentHooksFeatureModelTests.swift b/macos/Tests/LitheTests/AgentHooksFeatureModelTests.swift index 55fd226dbf..611b6c82ec 100644 --- a/macos/Tests/LitheTests/AgentHooksFeatureModelTests.swift +++ b/macos/Tests/LitheTests/AgentHooksFeatureModelTests.swift @@ -6,32 +6,90 @@ import LitheCoreContracts @Suite("Agent Hook settings") @MainActor struct AgentHooksFeatureModelTests { - @Test func validatesDraftsWithoutExecutingOrSavingThem() async { + @Test(.enabled(if: RustCoreBridge().isAvailable, "Requires the linked Rust Core integration library")) + func validatesDraftsThroughCoreWithoutExecutingOrSavingThem() async { let stub = HookTestService() let feature = AgentHooksFeatureModel(service: stub) await feature.load() - feature.draft = AgentHook(name: "remind", description: "结束提醒", command: "printf done") + feature.beginEditing(AgentHook(name: "remind", description: "结束提醒", command: "printf done")) #expect(feature.canSave) - for name in ["", "../escape", "spaces here", String(repeating: "a", count: 81)] { + for name in ["", "../escape", "spaces here", String(repeating: "a", count: 81), "NOTIFY"] { feature.draft?.name = name #expect(!feature.canSave) } feature.draft?.name = "valid_1" - feature.draft?.timeoutSeconds = 0 + feature.timeoutText = "0" #expect(!feature.canSave) - feature.draft?.timeoutSeconds = 86400 + #expect(feature.draftValidation?.issues == [AgentHookDraftIssue(field: "timeout", code: "out_of_range")]) + feature.timeoutText = "86400" #expect(feature.canSave) + // Swift used to accept these; the host rejected them only when saving. + feature.draft?.agents = ["codex-acp", "codex-acp"] + #expect(!feature.canSave) + feature.draft?.agents = ["codex-acp"] + feature.draft?.matcher = .shell + #expect(feature.draftValidation?.issues == [AgentHookDraftIssue(field: "matcher", code: "incompatible_event")]) + feature.draft?.matcher = .all feature.draft?.agents = [] #expect(!feature.canSave) #expect(await stub.writes == 0) } - @Test func failedSaveRetainsTheDraftAndExplicitReloadRefreshesGuards() async { + @Test(.enabled(if: RustCoreBridge().isAvailable, "Requires the linked Rust Core integration library")) + func savingStoresTheTimeoutCoreParsed() async { + let stub = HookTestService() + let feature = AgentHooksFeatureModel(service: stub) + await feature.load() + feature.beginEditing(AgentHook(name: "timed", command: "printf done")) + feature.timeoutText = "30" + await feature.save() + #expect(await stub.lastSaved?.timeoutSeconds == 30) + } + + @Test(.enabled(if: RustCoreBridge().isAvailable, "Requires the linked Rust Core integration library")) + func bridgeReturnsTheSharedFixtureVerdicts() throws { + struct Fixture: Decodable { + struct Case: Decodable { + struct Request: Decodable { + struct Draft: Decodable { + let id, name, description: String + let event: AgentHookEvent + let matcher: AgentHookMatcher + let command, timeoutText: String + let agents: [String] + } + struct Existing: Decodable { let id, name: String } + let hook: Draft + let existingHooks: [Existing] + } + let name: String + let request: Request + let expected: AgentHookDraftValidation + } + let cases: [Case] + } + let url = DeclarativePluginTestSupport.repositoryRoot.appendingPathComponent("shared/fixtures/agent/hook-draft-validation-v1.json") + let fixture = try JSONDecoder().decode(Fixture.self, from: Data(contentsOf: url)) + let service = RustAgentHooksService(core: RustCoreBridge(), directory: URL(fileURLWithPath: "/fixture/library")) + for item in fixture.cases { + let draft = item.request.hook + let hook = AgentHook(id: draft.id, name: draft.name, description: draft.description, event: draft.event, + matcher: draft.matcher, command: draft.command, agents: draft.agents) + let library = AgentHookLibrary(revision: "fixture", hooks: item.request.existingHooks.map { + AgentHookEntry(hook: AgentHook(id: $0.id, name: $0.name, command: "printf done"), configuredAgents: [], needsSync: false) + }, targets: []) + let result = try service.validateDraft(hook, timeoutText: draft.timeoutText, library: library) + #expect(result == item.expected, "\(item.name)") + } + } + + @Test(.enabled(if: RustCoreBridge().isAvailable, "Requires the linked Rust Core integration library")) + func failedSaveRetainsTheDraftAndExplicitReloadRefreshesGuards() async { let stub = HookTestService() let feature = AgentHooksFeatureModel(service: stub) await feature.load() let draft = AgentHook(name: "new-hook", command: "printf new") - feature.draft = draft + feature.beginEditing(draft) await stub.setFailure(true) await feature.save() #expect(feature.draft == draft) @@ -44,11 +102,12 @@ struct AgentHooksFeatureModelTests { #expect(feature.library?.hooks.last?.id == draft.id) } - @Test func mutationsDoNotOverlapAndPartialSynchronizationRemainsVisible() async { + @Test(.enabled(if: RustCoreBridge().isAvailable, "Requires the linked Rust Core integration library")) + func mutationsDoNotOverlapAndPartialSynchronizationRemainsVisible() async { let stub = HookTestService() let feature = AgentHooksFeatureModel(service: stub) await feature.load() - feature.draft = AgentHook(name: "new-hook", command: "printf new") + feature.beginEditing(AgentHook(name: "new-hook", command: "printf new")) await stub.onSave { await MainActor.run { #expect(feature.isBusy && !feature.canSave) } await feature.load() @@ -101,6 +160,11 @@ actor HookTestService: AgentHooksService { func setFailure(_ value: Bool) { failure = value } func onSave(_ action: @escaping @Sendable () async -> Void) { saving = action } struct Failure: LocalizedError { var errorDescription: String? { "Fixture conflict" } } + /// Draft rules are Core's; the stub only replaces file-backed operations. + nonisolated func validateDraft(_ hook: AgentHook, timeoutText: String, library: AgentHookLibrary) throws -> AgentHookDraftValidation { + try RustAgentHooksService(core: RustCoreBridge(), directory: URL(fileURLWithPath: "/fixture/library")) + .validateDraft(hook, timeoutText: timeoutText, library: library) + } func load() throws -> AgentHookLibrary { reads += 1 if failure { throw Failure() } diff --git a/rust/lithe-agent-host/src/hooks.rs b/rust/lithe-agent-host/src/hooks.rs index 16077b74a0..38f615669e 100644 --- a/rust/lithe-agent-host/src/hooks.rs +++ b/rust/lithe-agent-host/src/hooks.rs @@ -243,11 +243,14 @@ fn execute_in( match &request.action { Action::Save { hook, .. } => { let mut hook = hook.clone(); - if stored - .hooks - .iter() - .any(|h| h.id != hook.id && h.name.eq_ignore_ascii_case(&hook.name)) - { + if name_taken( + stored + .hooks + .iter() + .map(|h| (h.id.as_str(), h.name.as_str())), + &hook.id, + &hook.name, + ) { return Err(error( "invalid_request", "A Hook with this name already exists.", @@ -378,27 +381,17 @@ fn decode(source: &InstructionFile) -> Result { } fn validate(hook: &Hook) -> Result<(), Error> { - if uuid::Uuid::parse_str(&hook.id).is_err() - || hook.name.is_empty() - || hook.name.len() > 80 - || !hook - .name - .bytes() - .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') - || hook.description.chars().count() > 200 - || hook.command.trim().is_empty() - || hook.command.len() > 32768 - || hook.command.contains('\0') - || hook - .timeout_seconds - .is_some_and(|seconds| seconds == 0 || seconds > 86400) - || hook.agents.is_empty() - || hook.agents.len() > 2 - || hook.agents.iter().any(|a| !AGENTS.contains(&a.as_str())) - || (hook.agents.len() == 2 && hook.agents[0] == hook.agents[1]) - || (!matches!(hook.event, Event::BeforeTool | Event::AfterTool) - && hook.matcher != Matcher::All) - { + let fields = Fields { + id: &hook.id, + name: &hook.name, + description: &hook.description, + event: hook.event, + matcher: hook.matcher, + command: &hook.command, + timeout: Ok(hook.timeout_seconds), + agents: &hook.agents, + }; + if !field_issues(&fields, &[]).is_empty() { return Err(error( "invalid_request", "Check the Hook name, command, event, Agents and timeout (1–86400 seconds).", @@ -407,6 +400,218 @@ fn validate(hook: &Hook) -> Result<(), Error> { Ok(()) } +/// Longest Hook name in UTF-8 bytes; names are ASCII-only, so bytes equal characters. +const MAX_NAME_BYTES: usize = 80; +/// Longest description in Unicode scalar values. +const MAX_DESCRIPTION_SCALARS: usize = 200; +/// Longest command in UTF-8 bytes, matching the native file write budget. +const MAX_COMMAND_BYTES: usize = 32768; +/// Largest explicit timeout in seconds (one day). +const MAX_TIMEOUT_SECONDS: u64 = 86400; + +/// Unsaved editor state. `timeoutText` is the raw text field so integer parsing +/// and the range rule stay in one place; an empty value inherits the Agent default. +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Draft { + pub id: String, + pub name: String, + pub description: String, + pub event: Event, + pub matcher: Matcher, + pub command: String, + pub timeout_text: String, + pub agents: Vec, +} + +/// Identity of a Hook already in the library, used only for the unique-name rule. +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ExistingHook { + pub id: String, + pub name: String, +} + +/// Payload of `agent.hooks.validateDraft`. Pure: no files are read or written. +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DraftRequest { + pub hook: Draft, + /// Library rows other than the draft; the draft's own id is ignored here. + #[serde(default)] + pub existing_hooks: Vec, +} + +/// One field-level problem. `field` is a draft field name (`id`, `name`, +/// `description`, `command`, `timeout`, `agents`, `matcher`); `code` is a stable +/// snake_case reason the platform localizes. Each field reports at most one issue. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct DraftIssue { + pub field: &'static str, + pub code: &'static str, +} + +/// Draft verdict. Saving is allowed only when `valid`; `timeoutSeconds` is the +/// parsed value the platform stores in the Hook it saves. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct DraftValidation { + pub valid: bool, + pub issues: Vec, + pub timeout_seconds: Option, +} + +/// Applies the same rules `save` enforces, field by field, without touching files. +pub fn validate_draft(request: &DraftRequest) -> DraftValidation { + let draft = &request.hook; + let timeout = parse_timeout(&draft.timeout_text); + let fields = Fields { + id: &draft.id, + name: &draft.name, + description: &draft.description, + event: draft.event, + matcher: draft.matcher, + command: &draft.command, + timeout, + agents: &draft.agents, + }; + let issues = field_issues(&fields, &request.existing_hooks); + // A rejected timeout has no value to store. + let timeout_seconds = if issues.iter().any(|issue| issue.field == "timeout") { + None + } else { + timeout.ok().flatten() + }; + DraftValidation { + valid: issues.is_empty(), + timeout_seconds, + issues, + } +} + +/// Names are unique ignoring ASCII case; a Hook never conflicts with itself. +fn name_taken<'a>( + mut others: impl Iterator, + id: &str, + name: &str, +) -> bool { + others.any(|(other_id, other_name)| other_id != id && other_name.eq_ignore_ascii_case(name)) +} + +/// Accepts only ASCII digits so signs, spaces and fractions never round silently. +fn parse_timeout(text: &str) -> Result, &'static str> { + if text.is_empty() { + return Ok(None); + } + if !text.bytes().all(|b| b.is_ascii_digit()) { + return Err("not_integer"); + } + // Overlong digit strings are still integers, just out of range. + Ok(Some(text.parse::().unwrap_or(u64::MAX))) +} + +struct Fields<'a> { + id: &'a str, + name: &'a str, + description: &'a str, + event: Event, + matcher: Matcher, + command: &'a str, + timeout: Result, &'static str>, + agents: &'a [String], +} + +// Field order is the editor's top-to-bottom order so the first issue is the first +// control the user sees. +fn field_issues(fields: &Fields<'_>, existing: &[ExistingHook]) -> Vec { + let mut issues = Vec::new(); + let mut push = |field, code: Option<&'static str>| { + if let Some(code) = code { + issues.push(DraftIssue { field, code }); + } + }; + push( + "id", + uuid::Uuid::parse_str(fields.id) + .is_err() + .then_some("invalid"), + ); + let name = fields.name; + push( + "name", + if name.is_empty() { + Some("required") + } else if name.len() > MAX_NAME_BYTES { + Some("too_long") + } else if !name + .bytes() + .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') + { + Some("invalid_characters") + } else if name_taken( + existing.iter().map(|h| (h.id.as_str(), h.name.as_str())), + fields.id, + name, + ) { + Some("duplicate") + } else { + None + }, + ); + push( + "description", + (fields.description.chars().count() > MAX_DESCRIPTION_SCALARS).then_some("too_long"), + ); + push( + "matcher", + (!matches!(fields.event, Event::BeforeTool | Event::AfterTool) + && fields.matcher != Matcher::All) + .then_some("incompatible_event"), + ); + let command = fields.command; + push( + "command", + if command.trim().is_empty() { + Some("required") + } else if command.len() > MAX_COMMAND_BYTES { + Some("too_long") + } else if command.contains('\0') { + Some("contains_nul") + } else { + None + }, + ); + push( + "timeout", + match fields.timeout { + Err(code) => Some(code), + Ok(Some(seconds)) if seconds == 0 || seconds > MAX_TIMEOUT_SECONDS => { + Some("out_of_range") + } + Ok(_) => None, + }, + ); + let agents = fields.agents; + push( + "agents", + if agents.is_empty() { + Some("required") + } else if agents.iter().any(|a| !AGENTS.contains(&a.as_str())) { + Some("unsupported") + } else if agents + .iter() + .enumerate() + .any(|(i, a)| agents[..i].contains(a)) + { + Some("duplicate") + } else { + None + }, + ); + issues +} + fn native_file(agent: &str, resolve: &Resolver<'_>) -> Result { let directory = resolve(agent).map_err(storage::file_error)?; storage::read( diff --git a/rust/lithe-agent-host/src/hooks/tests.rs b/rust/lithe-agent-host/src/hooks/tests.rs index 9f958214ae..7484f4e412 100644 --- a/rust/lithe-agent-host/src/hooks/tests.rs +++ b/rust/lithe-agent-host/src/hooks/tests.rs @@ -449,3 +449,68 @@ fn symlinked_native_files_are_not_followed_and_readonly_permissions_are_preserve 0o400 ); } + +fn draft(hook: &Hook) -> Draft { + Draft { + id: hook.id.clone(), + name: hook.name.clone(), + description: hook.description.clone(), + event: hook.event, + matcher: hook.matcher, + command: hook.command.clone(), + timeout_text: hook + .timeout_seconds + .map(|s| s.to_string()) + .unwrap_or_default(), + agents: hook.agents.clone(), + } +} + +/// The shared fixture pins every field-level code both editors localize, so a +/// platform cannot accept a draft that `save` would later reject. +#[test] +fn draft_validation_matches_the_shared_fixture_and_the_save_rules() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../shared/fixtures/agent/hook-draft-validation-v1.json" + )) + .unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let request: DraftRequest = serde_json::from_value(case["request"].clone()).unwrap(); + let result = serde_json::to_value(validate_draft(&request)).unwrap(); + assert_eq!(result, case["expected"], "{}", case["name"]); + } +} + +#[test] +fn every_draft_accepted_by_the_editor_is_accepted_by_save_validation() { + let base = hook(); + let mut timed = base.clone(); + timed.timeout_seconds = Some(MAX_TIMEOUT_SECONDS); + let mut tool = base.clone(); + tool.event = Event::BeforeTool; + tool.matcher = Matcher::Edit; + for accepted in [base.clone(), timed, tool] { + let verdict = validate_draft(&DraftRequest { + hook: draft(&accepted), + existing_hooks: vec![], + }); + assert!(verdict.valid, "{verdict:?}"); + assert_eq!(verdict.timeout_seconds, accepted.timeout_seconds); + assert!(validate(&accepted).is_ok()); + } + // Swift previously accepted these; the host always rejected them at save time. + let mut duplicate_agents = base.clone(); + duplicate_agents.agents = vec!["codex-acp".into(), "codex-acp".into()]; + let mut matcher = base.clone(); + matcher.matcher = Matcher::Shell; + for rejected in [duplicate_agents, matcher] { + assert!( + !validate_draft(&DraftRequest { + hook: draft(&rejected), + existing_hooks: vec![] + }) + .valid + ); + assert!(validate(&rejected).is_err()); + } +} diff --git a/rust/lithe-core/src/agent/hooks.rs b/rust/lithe-core/src/agent/hooks.rs index 285ecd2a83..57c4020593 100644 --- a/rust/lithe-core/src/agent/hooks.rs +++ b/rust/lithe-core/src/agent/hooks.rs @@ -18,3 +18,9 @@ pub(crate) fn execute(request: hooks::Request) -> Result { serde_json::to_value(library) .map_err(|issue| CoreError::new(ErrorCode::Unknown, issue.to_string())) } + +/// Field-level draft verdict from the same rules `save` enforces; reads no files. +pub(crate) fn validate_draft(request: hooks::DraftRequest) -> Result { + serde_json::to_value(hooks::validate_draft(&request)) + .map_err(|issue| CoreError::new(ErrorCode::Unknown, issue.to_string())) +} diff --git a/shared/fixtures/agent/hook-draft-validation-v1.json b/shared/fixtures/agent/hook-draft-validation-v1.json new file mode 100644 index 0000000000..cb44a40f2b --- /dev/null +++ b/shared/fixtures/agent/hook-draft-validation-v1.json @@ -0,0 +1,806 @@ +{ + "command": "agent.hooks.validateDraft", + "description": "Field-level Hook draft validation shared by the macOS and Windows editors. The rules are the ones agent.hooks save enforces; platforms localize field/code pairs and enable saving only when valid.", + "cases": [ + { + "name": "valid default draft", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": true, + "issues": [], + "timeoutSeconds": null + } + }, + { + "name": "valid tool draft with explicit timeout", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "before-tool", + "matcher": "edit", + "command": "printf done", + "timeoutText": "86400", + "agents": [ + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": true, + "issues": [], + "timeoutSeconds": 86400 + } + }, + { + "name": "editing a Hook keeps its own name", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000001", + "name": "NOTIFY", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": true, + "issues": [], + "timeoutSeconds": null + } + }, + { + "name": "empty name", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "name", + "code": "required" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "name over 80 bytes", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "name", + "code": "too_long" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "name with path characters", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "../escape", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "name", + "code": "invalid_characters" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "name with spaces", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "spaces here", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "name", + "code": "invalid_characters" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "duplicate name ignores ASCII case", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "Notify", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "name", + "code": "duplicate" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "description over 200 Unicode scalars", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "description", + "code": "too_long" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "description of 200 Unicode scalars", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": true, + "issues": [], + "timeoutSeconds": null + } + }, + { + "name": "matcher on a non-tool event", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "shell", + "command": "printf done", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "matcher", + "code": "incompatible_event" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "whitespace-only command", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": " \n\t", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "command", + "code": "required" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "command over 32768 bytes", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉汉", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "command", + "code": "too_long" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "command containing NUL", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf\u0000done", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "command", + "code": "contains_nul" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "zero timeout", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "0", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "timeout", + "code": "out_of_range" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "timeout above one day", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "86401", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "timeout", + "code": "out_of_range" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "overlong digit timeout", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "99999999999999999999999", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "timeout", + "code": "out_of_range" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "non-numeric timeout", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "abc", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "timeout", + "code": "not_integer" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "signed timeout", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "+5", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "timeout", + "code": "not_integer" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "no Agent selected", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "", + "agents": [] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "agents", + "code": "required" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "unknown Agent", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "", + "agents": [ + "gemini-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "agents", + "code": "unsupported" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "duplicate Agent", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "", + "agents": [ + "codex-acp", + "codex-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "agents", + "code": "duplicate" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "invalid identifier", + "request": { + "hook": { + "id": "not-a-uuid", + "name": "remind", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "printf done", + "timeoutText": "", + "agents": [ + "codex-acp", + "claude-acp" + ] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "id", + "code": "invalid" + } + ], + "timeoutSeconds": null + } + }, + { + "name": "several fields report in editor order", + "request": { + "hook": { + "id": "00000000-0000-4000-8000-000000000002", + "name": "", + "description": "结束提醒", + "event": "turn-end", + "matcher": "all", + "command": "", + "timeoutText": "0", + "agents": [] + }, + "existingHooks": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "notify" + } + ] + }, + "expected": { + "valid": false, + "issues": [ + { + "field": "name", + "code": "required" + }, + { + "field": "command", + "code": "required" + }, + { + "field": "timeout", + "code": "out_of_range" + }, + { + "field": "agents", + "code": "required" + } + ], + "timeoutSeconds": null + } + } + ] +} diff --git a/shared/platform-feature-matrix/features/agent-hooks.json b/shared/platform-feature-matrix/features/agent-hooks.json index 57871a053a..4687716298 100644 --- a/shared/platform-feature-matrix/features/agent-hooks.json +++ b/shared/platform-feature-matrix/features/agent-hooks.json @@ -16,7 +16,9 @@ "shared/fixtures/agent/hooks-management-v1.json", ".agents/notes/implemented/feature/2026-10-24-agent-hooks.md", "macos/Sources/Lithe/Views/Agent/AgentSelectionChip.swift", - "macos/Sources/Lithe/Views/Components/LitheSettingsControls.swift" + "macos/Sources/Lithe/Views/Components/LitheSettingsControls.swift", + "shared/fixtures/agent/hook-draft-validation-v1.json", + "rust/lithe-core/src/agent/hooks.rs" ] }, "windows": { @@ -27,10 +29,12 @@ "windows/tauri/src/features/agent/services/agent-hooks.ts", "windows/tauri/src/features/agent/services/agent-hooks.test.ts", "rust/lithe-agent-host/src/hooks.rs", - "windows/tauri/src/features/settings/components/tabs/agent-hooks-settings.test.tsx" + "windows/tauri/src/features/settings/components/tabs/agent-hooks-settings.test.tsx", + "shared/fixtures/agent/hook-draft-validation-v1.json", + "rust/lithe-core/src/agent/hooks.rs" ] }, "owner": "Agent", - "verification": "在 macOS 与真实 Windows 中打开 AI > Hooks,创建、编辑、搜索、启停和删除命令;确认五种事件和 Shell/文件编辑筛选映射正确,超时空值沿用原生默认。使用隔离用户目录运行真实 Codex/Claude Agent,批准原生信任后触发会话开始、提示词、工具前后和回合结束,并验证 JSON stdin 与工作目录。保留已有设置及用户 Hook;删除后其他组的位置不变,Codex trust 配置不变;外部修改、只读、非法 JSON、符号链接、原生单项失败、中断和取消显示可重试状态。运行 Host Hook、Core 契约、Swift 功能/外观/设置导航测试与 Windows frontend 验证,检查中英文深浅色窄宽页面及编辑面板。比较操作前后发行 bundle 文件清单与哈希不变。 按参考页检查编辑器两列标签对齐、多行描述与命令、创建/编辑标题和固定底部动作;验证 Agent 品牌选择按钮、全部恢复和全不选时禁用保存。 搜索不匹配时应显示中英文「没有匹配的 Hook」,清空后恢复列表;区分无搜索词的空资源库,搜索不发起配置写入。", - "notes": "源与所有权日志由平台 storage adapter 提供可写目录;1 MiB 有界读写,非阻塞 OS 锁,逐文件原子替换,跨文件部分失败明确可见。原生 JSON 保留未知字段值但规范化格式;非法 JSON/重复键拒绝覆盖。Codex 仍须在原生 /hooks 中启用与信任命令,配置已写入不表示已执行。macOS 已通过 51 项相关 Swift 计时测试、14 项 Hook 文件测试和真实界面 CRUD/搜索/启停/冲突恢复验收;10 个原生 CLI 与 4 个 ACP 真实模型会话覆盖 Codex 0.160.0、Claude Code 2.1.310、Codex ACP 1.13.1、Claude ACP 0.81.2,验证五种事件、工具筛选、JSON stdin、会话目录、命令修改、停用/删除/重新启用和原生超时。1382 个 bundle 文件哈希不变,测试配置与进程已清理。完整 Host lane 为 231 通过、39 个 opt-in 跳过。Windows 实机运行尚未执行,verificationStatus 保持 pending。 Windows frontend 的 9 项计时测试与类型检查通过,包含重新加载不携带写入快照的请求边界回归;这不替代 Windows 实机验收。 编辑器按参考设计采用两列表单、独立标题/底栏和品牌选择按钮;macOS 复用 MCP 原有选择按钮,新增布局与输入回归。 布局调整后 78 项 macOS Swift 计时测试和 9 项 frontend 测试通过,类型检查通过;已检查中英文深浅色编辑器截图,并在真实预览验证焦点、多行描述、全部/单选和工具事件切换。 Review 修复 Windows 无匹配搜索留白,空状态改为依据筛选结果;新增中英文界面回归后 11 项 frontend 计时测试和类型检查通过。覆盖名称/命令大小写、中文描述、清空恢复、空资源库和搜索不写入;目标 Windows 运行证据仍待补充。" + "verification": "在 macOS 与真实 Windows 中打开 AI > Hooks,创建、编辑、搜索、启停和删除命令;确认五种事件和 Shell/文件编辑筛选映射正确,超时空值沿用原生默认。使用隔离用户目录运行真实 Codex/Claude Agent,批准原生信任后触发会话开始、提示词、工具前后和回合结束,并验证 JSON stdin 与工作目录。保留已有设置及用户 Hook;删除后其他组的位置不变,Codex trust 配置不变;外部修改、只读、非法 JSON、符号链接、原生单项失败、中断和取消显示可重试状态。运行 Host Hook、Core 契约、Swift 功能/外观/设置导航测试与 Windows frontend 验证,检查中英文深浅色窄宽页面及编辑面板。比较操作前后发行 bundle 文件清单与哈希不变。 按参考页检查编辑器两列标签对齐、多行描述与命令、创建/编辑标题和固定底部动作;验证 Agent 品牌选择按钮、全部恢复和全不选时禁用保存。 搜索不匹配时应显示中英文「没有匹配的 Hook」,清空后恢复列表;区分无搜索词的空资源库,搜索不发起配置写入。 编辑器的字段校验来自 Core `agent.hooks.validateDraft`:逐项输入非法名称、重名(忽略大小写)、超长描述、非工具事件配工具筛选、空命令/NUL、超时 0/86401/非整数、清空或重复 Agent,确认两端显示相同的中英文字段提示并禁用保存,合法后可保存且超时按 Core 解析值写入。", + "notes": "源与所有权日志由平台 storage adapter 提供可写目录;1 MiB 有界读写,非阻塞 OS 锁,逐文件原子替换,跨文件部分失败明确可见。原生 JSON 保留未知字段值但规范化格式;非法 JSON/重复键拒绝覆盖。Codex 仍须在原生 /hooks 中启用与信任命令,配置已写入不表示已执行。macOS 已通过 51 项相关 Swift 计时测试、14 项 Hook 文件测试和真实界面 CRUD/搜索/启停/冲突恢复验收;10 个原生 CLI 与 4 个 ACP 真实模型会话覆盖 Codex 0.160.0、Claude Code 2.1.310、Codex ACP 1.13.1、Claude ACP 0.81.2,验证五种事件、工具筛选、JSON stdin、会话目录、命令修改、停用/删除/重新启用和原生超时。1382 个 bundle 文件哈希不变,测试配置与进程已清理。完整 Host lane 为 231 通过、39 个 opt-in 跳过。Windows 实机运行尚未执行,verificationStatus 保持 pending。 Windows frontend 的 9 项计时测试与类型检查通过,包含重新加载不携带写入快照的请求边界回归;这不替代 Windows 实机验收。 编辑器按参考设计采用两列表单、独立标题/底栏和品牌选择按钮;macOS 复用 MCP 原有选择按钮,新增布局与输入回归。 布局调整后 78 项 macOS Swift 计时测试和 9 项 frontend 测试通过,类型检查通过;已检查中英文深浅色编辑器截图,并在真实预览验证焦点、多行描述、全部/单选和工具事件切换。 Review 修复 Windows 无匹配搜索留白,空状态改为依据筛选结果;新增中英文界面回归后 11 项 frontend 计时测试和类型检查通过。覆盖名称/命令大小写、中文描述、清空恢复、空资源库和搜索不写入;目标 Windows 运行证据仍待补充。 #1662 AGT-18:名称字符集、描述长度、命令字节数、超时、Agent 选择和 matcher/event 兼容规则只保留 Agent Host 一份,两端编辑器改为调用 `agent.hooks.validateDraft` 获取字段级错误码并本地化显示;删除 Swift `canSave` 与 Windows `validHook` 的平台副本。行为变化:macOS 不再接受重复 Agent、非工具事件的工具筛选(以前要到 Host 保存时才被拒绝);Windows 重名检查改由 Core 完成;两端都在编辑器内显示具体字段原因。该改动有 Host/Core/Swift 桥接与 Windows frontend 单元测试证据,界面尚未在两端重新目视验收。" } diff --git a/windows/tauri/src/features/agent/services/agent-hooks.test.ts b/windows/tauri/src/features/agent/services/agent-hooks.test.ts index 91b636b6d0..ab8f7e085b 100644 --- a/windows/tauri/src/features/agent/services/agent-hooks.test.ts +++ b/windows/tauri/src/features/agent/services/agent-hooks.test.ts @@ -1,8 +1,10 @@ import { describe, expect, spyOn, test } from "bun:test"; import fixture from "../../../../../../shared/fixtures/agent/hooks-management-v1.json"; +import draftFixture from "../../../../../../shared/fixtures/agent/hook-draft-validation-v1.json"; import * as platform from "@/platform/tauri-core"; import * as appData from "@/platform/app-data-directory"; -import { manageHooks, parseHookLibrary, validHook, type AgentHook } from "./agent-hooks"; +import { hookDraftIssueKey, manageHooks, parseHookLibrary, validateHookDraft, type AgentHook } from "./agent-hooks"; +import { createTranslator } from "@/i18n/locale"; describe("native Agent Hook management contract", () => { test("reload omits mutation guards while save preserves the reviewed snapshots", async () => { @@ -34,12 +36,30 @@ describe("native Agent Hook management contract", () => { expect(parseHookLibrary({ ...fixture.library, hooks: [{ ...fixture.library.hooks[0], event: "unknown" }] })).toBeNull(); expect(parseHookLibrary({ ...fixture.library, hooks: [{ ...fixture.library.hooks[0], timeoutSeconds: -1 }] })).toBeNull(); }); - test("validates command drafts, names, Agent choices and bounded integer timeouts", () => { - const hook = fixture.hook as AgentHook; - expect(validHook(hook)).toBe(true); - for (const invalid of [{ name: "../escape" }, { command: " " }, { agents: [] }, { timeoutSeconds: 0 }, { timeoutSeconds: 1.5 }, { timeoutSeconds: 86401 }]) { - expect(validHook({ ...hook, ...invalid })).toBe(false); + test("draft validation sends the raw timeout text and library names to Core and accepts its verdict", async () => { + const library = parseHookLibrary(fixture.library)!; + for (const item of draftFixture.cases) { + const invoked = spyOn(platform, "invoke").mockResolvedValue(item.expected); + try { + const { timeoutText, ...fields } = item.request.hook; + const hook = { ...fields, timeoutSeconds: null, enabled: true, pendingRemoval: false } as AgentHook; + expect(await validateHookDraft(hook, timeoutText, library)).toEqual(item.expected as never); + expect(invoked).toHaveBeenLastCalledWith("agent.hooks.validateDraft", { + hook: item.request.hook, + existingHooks: library.hooks.map(entry => ({ id: entry.id, name: entry.name })), + }); + } finally { invoked.mockRestore(); } + } + const invalid = spyOn(platform, "invoke").mockResolvedValue({ valid: "yes" }); + try { + await expect(validateHookDraft(fixture.hook as AgentHook, "", library)).rejects.toThrow("not recognised"); + } finally { invalid.mockRestore(); } + }); + test("every Core draft issue in the shared fixture has English and Chinese text", () => { + const issues = draftFixture.cases.flatMap(item => item.expected.issues); + for (const language of ["en-US", "zh-CN"] as const) { + const t = createTranslator(language); + for (const issue of issues) expect(t(hookDraftIssueKey(issue))).not.toBe(hookDraftIssueKey(issue)); } - expect(validHook({ ...hook, timeoutSeconds: 86400 })).toBe(true); }); }); diff --git a/windows/tauri/src/features/agent/services/agent-hooks.ts b/windows/tauri/src/features/agent/services/agent-hooks.ts index 208155fdb5..b3304d66cd 100644 --- a/windows/tauri/src/features/agent/services/agent-hooks.ts +++ b/windows/tauri/src/features/agent/services/agent-hooks.ts @@ -31,15 +31,38 @@ export function parseHookLibrary(value: unknown): HookLibrary | null { return value as unknown as HookLibrary; } -export function validHook(hook: AgentHook): boolean { - return /^[A-Za-z0-9_-]{1,80}$/.test(hook.name) && [...hook.description].length <= 200 - && hook.command.trim().length > 0 && new TextEncoder().encode(hook.command).length <= 32768 && !hook.command.includes("\0") - && hook.agents.length > 0 && hook.agents.length <= 2 && new Set(hook.agents).size === hook.agents.length - && hook.agents.every(id => hookAgents.includes(id as typeof hookAgents[number])) - && (hook.matcher === "all" || hook.event === "before-tool" || hook.event === "after-tool") - && (hook.timeoutSeconds === null || (Number.isInteger(hook.timeoutSeconds) && hook.timeoutSeconds >= 1 && hook.timeoutSeconds <= 86400)); +/** One field-level problem from Core; `field` and `code` are stable identifiers for localization. */ +export interface HookDraftIssue { field: string; code: string } +/** Core verdict for an unsaved draft; `timeoutSeconds` is the parsed value to store. */ +export interface HookDraftValidation { valid: boolean; issues: HookDraftIssue[]; timeoutSeconds: number | null } + +function parseDraftValidation(value: unknown): HookDraftValidation | null { + if (!record(value) || typeof value.valid !== "boolean" || !Array.isArray(value.issues)) return null; + if (!value.issues.every(issue => record(issue) && typeof issue.field === "string" && typeof issue.code === "string")) return null; + if (value.timeoutSeconds !== null && !Number.isInteger(value.timeoutSeconds)) return null; + return value as unknown as HookDraftValidation; +} + +/** + * Validates an unsaved draft with the rules `agent.hooks` save enforces. The raw + * timeout text goes to Core so integer parsing and the range rule have one owner. + */ +export async function validateHookDraft(hook: AgentHook, timeoutText: string, library: HookLibrary): Promise { + const value = await invoke("agent.hooks.validateDraft", { + hook: { + id: hook.id, name: hook.name, description: hook.description, event: hook.event, matcher: hook.matcher, + command: hook.command, timeoutText, agents: hook.agents, + }, + existingHooks: library.hooks.map(entry => ({ id: entry.id, name: entry.name })), + }); + const result = parseDraftValidation(value); + if (!result) throw new Error("The Hook draft validation response was not recognised."); + return result; } +/** Localization key for one Core draft issue. */ +export const hookDraftIssueKey = (issue: HookDraftIssue) => `agent.hooks.draft.${issue.field}.${issue.code}`; + /** Only configuration is written. Native runtimes retain shell, stdin and trust ownership. */ export async function manageHooks(action: "read" | "save" | "remove" | "sync", library?: HookLibrary, hook?: AgentHook, id?: string): Promise { const root = await resolveAppDataDirectory(); diff --git a/windows/tauri/src/features/settings/components/tabs/agent-hooks-settings.test.tsx b/windows/tauri/src/features/settings/components/tabs/agent-hooks-settings.test.tsx index 27361b2faf..a943c3fdd9 100644 --- a/windows/tauri/src/features/settings/components/tabs/agent-hooks-settings.test.tsx +++ b/windows/tauri/src/features/settings/components/tabs/agent-hooks-settings.test.tsx @@ -85,6 +85,13 @@ test("Hook editor retains a failed draft, retries with its guard and updates nat if (action === "remove") return { ...library, revision: "removed", hooks: [] }; return library; }); + // Core owns the rules (see shared/fixtures/agent/hook-draft-validation-v1.json); this + // double only reports the one issue this UI flow exercises. + const validated = spyOn(service, "validateHookDraft").mockImplementation(async (hook, timeoutText) => ({ + valid: hook.agents.length > 0, + issues: hook.agents.length > 0 ? [] : [{ field: "agents", code: "required" }], + timeoutSeconds: timeoutText === "" ? null : Number(timeoutText), + })); const frame = spyOn(dialog, "default").mockImplementation(({ children, footer, title }) =>

{title}

{children}{footer}
); const confirms = spyOn(dialog, "showConfirmDialog").mockResolvedValue(true); const toggle = spyOn(switchControl, "default").mockImplementation(({ checked, onChange, disabled, "aria-label": label }) => ( @@ -107,6 +114,7 @@ test("Hook editor retains a failed draft, retries with its guard and updates nat await act(async () => button("Codex").click()); await act(async () => button("Claude Code").click()); expect(button("Save Hook").disabled).toBe(true); + expect(container.textContent).toContain("Select at least one Agent."); expect(writes).toHaveLength(0); await act(async () => button("All").click()); expect(button("Codex").getAttribute("aria-pressed")).toBe("true"); @@ -134,7 +142,7 @@ test("Hook editor retains a failed draft, retries with its guard and updates nat } finally { try { await act(async () => root.unmount()); } finally { - toggle.mockRestore(); confirms.mockRestore(); frame.mockRestore(); managed.mockRestore(); + toggle.mockRestore(); confirms.mockRestore(); frame.mockRestore(); validated.mockRestore(); managed.mockRestore(); container.remove(); if (previousAct === undefined) delete environment.IS_REACT_ACT_ENVIRONMENT; else environment.IS_REACT_ACT_ENVIRONMENT = previousAct; diff --git a/windows/tauri/src/features/settings/components/tabs/agent-hooks-settings.tsx b/windows/tauri/src/features/settings/components/tabs/agent-hooks-settings.tsx index 94ca6efc29..5a5d00e724 100644 --- a/windows/tauri/src/features/settings/components/tabs/agent-hooks-settings.tsx +++ b/windows/tauri/src/features/settings/components/tabs/agent-hooks-settings.tsx @@ -8,8 +8,8 @@ import Switch from "@/ui/switch"; import AppDialog, { showConfirmDialog } from "@/ui/dialog"; import { AgentBrandIcon } from "@/features/agent/components/brand/agent-brand-icon"; import { - hookEvents, hookMatchers, hookAgents, manageHooks, validHook, - type AgentHook, type HookLibrary, type HookEntry, + hookEvents, hookMatchers, hookAgents, manageHooks, validateHookDraft, hookDraftIssueKey, + type AgentHook, type HookLibrary, type HookEntry, type HookDraftValidation, } from "@/features/agent/services/agent-hooks"; const agentTitle = (id: string) => id === "codex-acp" ? "Codex" : "Claude Code"; @@ -34,6 +34,8 @@ export function AgentHooksSettings() { const [query, setQuery] = useState(""); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); + // Verdict for exactly the current draft, timeout text and library; anything else disables saving. + const [validation, setValidation] = useState<{ draft: AgentHook; timeout: string; library: HookLibrary; result: HookDraftValidation } | null>(null); const mounted = useRef(false); const pending = useRef(false); const nameInput = useRef(null); @@ -49,6 +51,15 @@ export function AgentHooksSettings() { return () => { current = false; mounted.current = false; }; }, []); + useEffect(() => { + if (!draft || !library) return; + let current = true; + void validateHookDraft(draft, timeout, library) + .then(result => { if (current) setValidation({ draft, timeout, library, result }); }) + .catch(failure => { if (current) { setValidation(null); setError(t(failure instanceof Error ? failure.message : String(failure))); } }); + return () => { current = false; }; + }, [draft, timeout, library, t]); + const run = async (action: "read" | "save" | "remove" | "sync", hook?: AgentHook, id?: string) => { if (pending.current) return; pending.current = true; @@ -65,8 +76,9 @@ export function AgentHooksSettings() { const confirmed = await showConfirmDialog(t("hooks.deleteHint"), { title: t("hooks.deleteTitle"), confirmLabel: t("hooks.delete"), cancelLabel: t("ui.cancel") }); if (confirmed && mounted.current) await run("remove", undefined, hook.id); }; - const timeoutValid = timeout === "" || (/^[0-9]+$/.test(timeout) && Number(timeout) >= 1 && Number(timeout) <= 86400); - const duplicate = draft && library?.hooks.some(h => h.id !== draft.id && h.name.toLowerCase() === draft.name.toLowerCase()); + const verdict = validation && validation.draft === draft && validation.timeout === timeout && validation.library === library ? validation.result : null; + // An empty name or command only disables saving; other issues are shown inline. + const visibleIssues = verdict?.issues.filter(issue => !(issue.code === "required" && (issue.field === "name" || issue.field === "command"))) ?? []; const isNew = draft && !library?.hooks.some(h => h.id === draft.id); const filteredHooks = library?.hooks.filter(h => [h.name, h.description, h.command].some(value => value.toLowerCase().includes(query.toLowerCase()))); return
@@ -99,18 +111,19 @@ export function AgentHooksSettings() { {draft ? { if (!busy) setDraft(null); }} size="lg" initialFocus={nameInput} classNames={{ modal: "w-[calc(100vw-2rem)] max-w-[44rem]", header: "border-b border-border px-6 py-4", content: "p-6", footer: "border-t border-border px-6 py-4" }} footer={<> - + }>
update("name", e.target.value)} />

{t("hooks.nameHint")}