From d389ee4d539c23bcd752f973c6b6141836f63d68 Mon Sep 17 00:00:00 2001 From: ltf Date: Sat, 7 Nov 2026 05:01:44 +0800 Subject: [PATCH] feat(ios): add CompanionCore Swift package for the iOS companion Pairing (vibex-pairing invitation, companion preset check, origin fallback), an authenticated Remote Protocol v1 HostClient (conversations, incremental transcript, offline control-plane events, permission/question answers, session modes and config, read-only workspace tree/file/diff, projects), and the models that fold them into UI state. Wire models are linked from docs/protocol/v1/generated/swift. 31 unit tests. --- mobile/ios/.gitignore | 4 + mobile/ios/Package.swift | 21 + mobile/ios/README.md | 10 + .../Sources/CompanionCore/AgentCatalog.swift | 41 ++ .../CompanionCore/CompanionScopes.swift | 23 + .../Sources/CompanionCore/HostClient.swift | 234 ++++++++++ .../Sources/CompanionCore/HostModels.swift | 393 +++++++++++++++++ .../Sources/CompanionCore/HostOrigin.swift | 36 ++ .../CompanionCore/JSONValueAccess.swift | 45 ++ .../Sources/CompanionCore/PairingClient.swift | 214 +++++++++ .../CompanionCore/PairingInvitation.swift | 57 +++ .../Sources/CompanionCore/QuestionForm.swift | 202 +++++++++ .../CompanionCore/RemoteProtocolModels.swift | 1 + .../Sources/CompanionCore/SessionState.swift | 185 ++++++++ .../CompanionCore/TranscriptState.swift | 26 ++ .../CompanionCore/WorkspaceModels.swift | 152 +++++++ .../CompanionCoreTests/HostClientTests.swift | 417 ++++++++++++++++++ .../PairingClientTests.swift | 183 ++++++++ 18 files changed, 2244 insertions(+) create mode 100644 mobile/ios/.gitignore create mode 100644 mobile/ios/Package.swift create mode 100644 mobile/ios/README.md create mode 100644 mobile/ios/Sources/CompanionCore/AgentCatalog.swift create mode 100644 mobile/ios/Sources/CompanionCore/CompanionScopes.swift create mode 100644 mobile/ios/Sources/CompanionCore/HostClient.swift create mode 100644 mobile/ios/Sources/CompanionCore/HostModels.swift create mode 100644 mobile/ios/Sources/CompanionCore/HostOrigin.swift create mode 100644 mobile/ios/Sources/CompanionCore/JSONValueAccess.swift create mode 100644 mobile/ios/Sources/CompanionCore/PairingClient.swift create mode 100644 mobile/ios/Sources/CompanionCore/PairingInvitation.swift create mode 100644 mobile/ios/Sources/CompanionCore/QuestionForm.swift create mode 120000 mobile/ios/Sources/CompanionCore/RemoteProtocolModels.swift create mode 100644 mobile/ios/Sources/CompanionCore/SessionState.swift create mode 100644 mobile/ios/Sources/CompanionCore/TranscriptState.swift create mode 100644 mobile/ios/Sources/CompanionCore/WorkspaceModels.swift create mode 100644 mobile/ios/Tests/CompanionCoreTests/HostClientTests.swift create mode 100644 mobile/ios/Tests/CompanionCoreTests/PairingClientTests.swift diff --git a/mobile/ios/.gitignore b/mobile/ios/.gitignore new file mode 100644 index 000000000..11e09ea18 --- /dev/null +++ b/mobile/ios/.gitignore @@ -0,0 +1,4 @@ +.build/ +.swiftpm/ +xcuserdata/ +*.xcworkspace/xcuserdata/ diff --git a/mobile/ios/Package.swift b/mobile/ios/Package.swift new file mode 100644 index 000000000..17ae4c720 --- /dev/null +++ b/mobile/ios/Package.swift @@ -0,0 +1,21 @@ +// swift-tools-version: 6.0 +import PackageDescription + +let package = Package( + name: "VibeXCompanion", + platforms: [.iOS(.v17), .macOS(.v14)], + products: [ + .library(name: "CompanionCore", targets: ["CompanionCore"]), + ], + targets: [ + .target( + name: "CompanionCore", + swiftSettings: [.swiftLanguageMode(.v5)] + ), + .testTarget( + name: "CompanionCoreTests", + dependencies: ["CompanionCore"], + swiftSettings: [.swiftLanguageMode(.v5)] + ), + ] +) diff --git a/mobile/ios/README.md b/mobile/ios/README.md new file mode 100644 index 000000000..935d57553 --- /dev/null +++ b/mobile/ios/README.md @@ -0,0 +1,10 @@ +# VibeX Companion (iOS) + +iOS is a Companion Device. It pairs with the Host using the `companion` preset and never runs Agent, Git, or plugins. See ADR-0084 and `docs/plans/2026-11-06-ios-companion.md`. + +Wire models come from `docs/protocol/v1/generated/swift/RemoteProtocolModels.swift`, linked into `Sources/CompanionCore`. Do not copy or edit a second protocol copy. + +```bash +# pairing client and scope tests; needs a Swift 6 toolchain +swift test +``` diff --git a/mobile/ios/Sources/CompanionCore/AgentCatalog.swift b/mobile/ios/Sources/CompanionCore/AgentCatalog.swift new file mode 100644 index 000000000..afcab4251 --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/AgentCatalog.swift @@ -0,0 +1,41 @@ +import Foundation + +/// An Agent configured in the desktop's settings, as listed by `conversation_catalog`. +public struct CatalogAgent: Equatable, Sendable, Identifiable { + public let id: String + public let displayName: String + public let usable: Bool + public let currentModeID: String? + public let modes: [SessionMode] + public let options: [ConfigOption] + + public var modelOptions: [ConfigOption] { options.filter { $0.category == "model" } } + public var otherOptions: [ConfigOption] { + options.filter { $0.category != "model" && $0.category != "mode" } + } +} + +public enum AgentCatalogParser { + public static func agents(from catalog: JSONValue) -> [CatalogAgent] { + (catalog["agents"]?.arrayValue ?? []).compactMap { item in + guard let id = item["id"]?.stringValue else { return nil } + var usable = false + if case .bool(let flag)? = item["usable"] { usable = flag } + return CatalogAgent( + id: id, + displayName: item["displayName"]?.stringValue ?? id, + usable: usable, + currentModeID: item["currentMode"]?.stringValue, + modes: (item["sessionModes"]?.arrayValue ?? []).compactMap(SessionStateBuilder.mode), + options: (item["sessionConfig"]?.arrayValue ?? []).compactMap(SessionStateBuilder.option) + ) + } + } +} + +extension HostClient { + public func agentCatalog() async throws -> [CatalogAgent] { + let catalog: JSONValue = try await call("conversation_catalog", as: JSONValue.self) + return AgentCatalogParser.agents(from: catalog) + } +} diff --git a/mobile/ios/Sources/CompanionCore/CompanionScopes.swift b/mobile/ios/Sources/CompanionCore/CompanionScopes.swift new file mode 100644 index 000000000..91bc2c24c --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/CompanionScopes.swift @@ -0,0 +1,23 @@ +/// Companion Device scopes from ADR-0054. Authorization still checks each +/// scope; this set is only the pairing allowlist the phone will accept. +public enum CompanionScopes { + public static let allowed: Set = [ + "conversation.read", + "conversation.write", + "conversation.attach", + "conversation.permission", + "conversation.question", + "conversation.cancel", + "conversation.steer", + "artifact.read", + "workflow.read", + "automation.read", + "delegation.read", + "notification.summary", + "offline.read", + ] + + public static func extras(_ scopes: [String]) -> Set { + Set(scopes).subtracting(allowed) + } +} diff --git a/mobile/ios/Sources/CompanionCore/HostClient.swift b/mobile/ios/Sources/CompanionCore/HostClient.swift new file mode 100644 index 000000000..0a0e1b717 --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/HostClient.swift @@ -0,0 +1,234 @@ +import Foundation + +public enum HostError: Error, Equatable, LocalizedError { + case server(status: Int, message: String) + case malformedResponse + + public var errorDescription: String? { + switch self { + case .server(let status, let message): + return message.isEmpty ? "电脑返回错误(\(status))" : message + case .malformedResponse: + return "电脑返回了无法识别的数据" + } + } +} + +private struct CommandEnvelope: Decodable { let data: Payload } + +/// Authenticated Remote Protocol v1 calls against one paired Host. +public struct HostClient: Sendable { + private let origin: HostOrigin + private let accessToken: String + private let transport: HttpTransport + + public init( + origin: HostOrigin, + accessToken: String, + transport: HttpTransport = URLSessionTransport() + ) { + self.origin = origin + self.accessToken = accessToken + self.transport = transport + } + + public func call( + _ command: String, + args: [String: Any] = [:], + as type: T.Type = T.self + ) async throws -> T { + let body = try JSONSerialization.data( + withJSONObject: ["operation_id": UUID().uuidString.lowercased(), "args": args] + ) + let exchange = try await transport.execute( + method: "POST", + url: origin.resolve("/api/v1/call/\(command)"), + headers: headers(contentType: true), + body: body + ) + let data = try Self.successBody(exchange) + guard let envelope = try? JSONDecoder().decode(CommandEnvelope.self, from: data) else { + throw HostError.malformedResponse + } + return envelope.data + } + + public func offlineConversation(id: String, afterSequence: Int64 = 0) async throws + -> OfflineConversationCache + { + let exchange = try await transport.execute( + method: "GET", + url: origin.resolve("/api/v1/conversations/\(id)/offline?after_sequence=\(afterSequence)"), + headers: headers(contentType: false), + body: nil + ) + let data = try Self.successBody(exchange) + guard let cache = try? JSONDecoder().decode(OfflineConversationCache.self, from: data) else { + throw HostError.malformedResponse + } + return cache + } + + /// Brings `state` up to date. The first call reads everything; later calls re-read only the + /// tail, which is where a streaming answer grows, so polling stays cheap. + public func refresh(_ state: inout TranscriptState) async throws { + var start = max(0, state.nextIndex - 4) + var end = state.nextIndex + for _ in 0..<20 { + var args: [String: Any] = ["conversationId": state.conversationID, "limit": 200] + if start > 0 { args["cursor"] = String(start) } + let page: JSONValue = try await call("conversation_timeline_page", args: args, as: JSONValue.self) + let rows = page["rows"]?.arrayValue ?? [] + let pageStart = page["cursor"]?.stringValue.flatMap(Int.init) ?? start + state.merge(rows) + end = max(end, pageStart + rows.count) + guard let next = page["next_cursor"]?.stringValue.flatMap(Int.init) else { break } + start = next + } + state.nextIndex = end + } + + /// Projects with the workspaces they own, for grouping conversations by project. + public func projects() async throws -> [ProjectSummary] { + try await call("conversation_projects", as: [ProjectSummary].self) + } + + /// One directory level of the workspace; `path` is relative to its root ("" is the root). + public func workspaceTree(workspaceID: String, path: String = "") async throws -> WorkspaceTree { + try await call( + "conversation_workspace_tree", + args: ["workspaceId": workspaceID, "path": path], + as: WorkspaceTree.self + ) + } + + public func workspaceFile(workspaceID: String, path: String) async throws -> WorkspaceFile { + try await call( + "conversation_workspace_file", + args: ["workspaceId": workspaceID, "path": path], + as: WorkspaceFile.self + ) + } + + /// Working tree against HEAD, one entry per changed file, with the unified diff parsed into hunks. + public func workspaceDiff(workspaceID: String) async throws -> [FileDiff] { + let entries: [WorkspaceDiffEntry] = try await call( + "conversation_workspace_diff", + args: ["workspaceId": workspaceID], + as: [WorkspaceDiffEntry].self + ) + return entries.map(FileDiff.init) + } + + /// Creates an empty Conversation in the same workspace with the same Agent. + public func createConversation(workspaceID: String, agentID: String) async throws -> ConversationListItem { + try await call( + "conversation_create", + args: ["workspaceId": workspaceID, "agentId": agentID], + as: ConversationListItem.self + ) + } + + /// Starts (or resumes) the Agent session behind a Conversation so its modes and options can be read and changed. + public func ensureSessionControls(conversationID: String) async throws -> SessionState { + let snapshot: JSONValue = try await call( + "conversation_ensure_session_controls", + args: ["conversationId": conversationID], + as: JSONValue.self + ) + return SessionStateBuilder.controls(from: snapshot) + } + + // MARK: Conversation writes (Companion scopes: conversation.write / .cancel / .permission) + + private func command(_ name: String, _ args: [String: Any]) async throws { + let _: JSONValue = try await call(name, args: args, as: JSONValue.self) + } + + public func sendMessage( + conversationID: String, + workspaceID: String, + agentID: String, + text: String + ) async throws { + try await command("conversation_input_submit", [ + "request": [ + "conversationId": conversationID, + "payload": ["agentId": agentID, "workspaceId": workspaceID, "text": text], + ] as [String: Any], + ]) + } + + public func cancelTurn(conversationID: String) async throws { + try await command("conversation_cancel_turn", [ + "request": ["conversationId": conversationID] as [String: Any], + ]) + } + + /// `content` is the form answer; `nil` declines the question. + public func respondQuestion( + conversationID: String, + questionID: String, + content: JSONValue? + ) async throws { + let response: [String: Any] = content.map { ["action": "accept", "content": $0.foundationValue] } + ?? ["action": "decline"] + try await command("conversation_respond_question", [ + "request": [ + "conversationId": conversationID, + "questionId": questionID, + "response": response, + ] as [String: Any], + ]) + } + + public func respondPermission( + conversationID: String, + permissionID: String, + optionID: String? + ) async throws { + let response: [String: Any] = optionID.map { ["kind": "selected", "option_id": $0] } + ?? ["kind": "cancelled"] + try await command("conversation_respond_permission", [ + "request": [ + "conversationId": conversationID, + "permissionId": permissionID, + "response": response, + ] as [String: Any], + ]) + } + + public func setSessionMode(conversationID: String, modeID: String) async throws { + try await command("conversation_set_session_mode", [ + "conversationId": conversationID, "modeId": modeID, + ]) + } + + public func setSessionConfigOption( + conversationID: String, + key: String, + value: JSONValue + ) async throws { + try await command("conversation_set_session_config_option", [ + "conversationId": conversationID, "key": key, "value": value.foundationValue, + ]) + } + + private func headers(contentType: Bool) -> [String: String] { + var result = [ + "authorization": "Bearer \(accessToken)", + PairingClient.protocolHeader: PairingClient.clientProtocolVersion, + ] + if contentType { result["content-type"] = "application/json" } + return result + } + + private static func successBody(_ exchange: HttpExchange) throws -> Data { + guard (200...299).contains(exchange.status) else { + struct Failure: Decodable { let message: String? } + let message = (try? JSONDecoder().decode(Failure.self, from: exchange.body))?.message + throw HostError.server(status: exchange.status, message: message ?? "") + } + return exchange.body + } +} diff --git a/mobile/ios/Sources/CompanionCore/HostModels.swift b/mobile/ios/Sources/CompanionCore/HostModels.swift new file mode 100644 index 000000000..43b1ea726 --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/HostModels.swift @@ -0,0 +1,393 @@ +import Foundation + +/// Row of `conversation_list_recent`; fields the phone does not show are not decoded. +/// Optional fields tolerate a Host that changes their encoding. +public struct ConversationListItem: Decodable, Identifiable, Equatable, Sendable { + public let id: String + public let workspace_id: String + public let title: String? + public let status: String? + public let agent_id: String? + public let model: String? + public let message_count: Int + public let updated_at: String + + private enum CodingKeys: String, CodingKey { + case id, workspace_id, title, status, agent_id, model, message_count, updated_at + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = try c.decode(String.self, forKey: .id) + workspace_id = try c.decode(String.self, forKey: .workspace_id) + title = try? c.decodeIfPresent(String.self, forKey: .title) + status = try? c.decodeIfPresent(String.self, forKey: .status) + agent_id = try? c.decodeIfPresent(String.self, forKey: .agent_id) + model = try? c.decodeIfPresent(String.self, forKey: .model) + message_count = (try? c.decode(Int.self, forKey: .message_count)) ?? 0 + updated_at = try c.decode(String.self, forKey: .updated_at) + } + + public var updatedAt: Date? { Self.parseDate(updated_at) } + + static func parseDate(_ text: String) -> Date? { + let fractional = ISO8601DateFormatter() + fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return fractional.date(from: text) ?? ISO8601DateFormatter().date(from: text) + } +} + +/// Row of `artifact_list`. The Host also sends absolute paths; they are deliberately not decoded. +public struct ArtifactListItem: Decodable, Identifiable, Equatable, Sendable { + public let id: String + public let conversation_id: String + public let relative_path: String + public let media_type: String + public let revision: Int + public let updated_at_unix_ms: Int64 + + public var fileName: String { (relative_path as NSString).lastPathComponent } + public var updatedAt: Date { Date(timeIntervalSince1970: Double(updated_at_unix_ms) / 1000) } +} + +/// Entry of `conversation_workspace_tree` (one directory level, path relative to the workspace root). +public struct WorkspaceEntry: Decodable, Identifiable, Equatable, Sendable { + public let name: String + public let path: String + public let directory: Bool + public var id: String { path } +} + +/// One file an assistant turn changed, as reported by a `file_change_summary` row. +public struct FileChangeItem: Identifiable, Equatable, Sendable { + public let path: String + public let additions: Int? + public let deletions: Int? + /// The change rebuilt from the Agent's own Write/Edit calls, for workspaces without git; + /// nil when the Host reported the change and the diff is fetched from it. + public var hunks: [DiffHunk]? = nil + public var id: String { path } +} + +/// A file write or in-place edit taken from a tool call's input. +public struct ToolEdit: Equatable, Sendable { + public let path: String + /// The text being replaced; nil when the whole file was written. + public let old: String? + public let new: String +} + +/// One tool call the Agent made, shown as a row of chips. +public struct ToolStep: Identifiable, Equatable, Sendable { + public let id: String + public let name: String + public let status: String? + /// The target of the call (file name, command, query) shown as the row's chip. + public let preview: String? + /// File writes/edits this call made, when its input describes them. + public let edits: [ToolEdit] + /// The call's action with its target removed, e.g. `Write` for `Write notes.txt`. + public let label: String + /// The first lines of the tool input, for the expanded row. + public let detail: [String] + + public var isFinished: Bool { + guard let status else { return false } + return ["completed", "complete", "success", "done", "failed", "error"].contains(status.lowercased()) + } +} + +/// One step of the Agent's plan/todo checklist (`plan` content block). +public struct PlanTask: Identifiable, Equatable, Sendable { + public enum Status: Sendable { case pending, running, completed } + + public let id: Int + public let label: String + public let status: Status + public let priority: String? +} + +public struct TimelineItem: Identifiable, Equatable, Sendable { + public enum Role: Sendable { case user, assistant } + + public let id: String + public let role: Role + public var text: String + /// Reasoning prose the Agent produced before answering (assistant only). + public var thinking: String = "" + public var tools: [ToolStep] = [] + public var plan: [PlanTask] = [] + public var changes: [FileChangeItem] = [] + public var durationMs: Int? + + public var hasTrace: Bool { !thinking.isEmpty || !tools.isEmpty || !changes.isEmpty } +} + +public extension Array where Element == TimelineItem { + /// The most recent plan the Agent published; later plans replace earlier ones. + var currentPlan: [PlanTask] { last { !$0.plan.isEmpty }?.plan ?? [] } +} + +public enum TimelineBuilder { + /// Messages from `conversation_timeline_page` rows (the JSONL transcript is the Host's + /// history authority, ADR-0082). Rows that are not user/assistant turns are skipped. + public static func build(fromRows rows: [JSONValue]) -> [TimelineItem] { + var order: [String] = [] + var latest: [String: (revision: Double, item: TimelineItem)] = [:] + var changes: [String: [FileChangeItem]] = [:] + var lastAssistant: String? + for row in rows { + if row["row"]?["kind"]?.stringValue == "file_change_summary", let owner = lastAssistant { + for file in row["row"]?["summary"]?["files"]?.arrayValue ?? [] { + guard let path = file["path"]?.stringValue else { continue } + func count(_ key: String) -> Int? { + if case .number(let value)? = file[key] { return Int(value) } + return nil + } + var list = changes[owner] ?? [] + list.removeAll { $0.path == path } + list.append(FileChangeItem(path: path, additions: count("additions"), deletions: count("deletions"))) + changes[owner] = list + } + continue + } + guard let rowID = row["row_id"]?.stringValue, + row["row"]?["kind"]?.stringValue == "message_turn", + let turn = row["row"]?["turn"], + let role = role(turn["role"]?.stringValue) + else { continue } + if role == .assistant { lastAssistant = rowID } + var item = TimelineItem(id: rowID, role: role, text: "") + var texts: [String] = [] + var thoughts: [String] = [] + for (index, block) in (turn["blocks"]?.arrayValue ?? []).enumerated() { + switch block["type"]?.stringValue { + case "text": + if let text = block["text"]?.stringValue { texts.append(text) } + case "thinking": + if role == .assistant, let text = block["text"]?.stringValue { thoughts.append(text) } + case "tool_use": + guard role == .assistant, let name = block["tool_name"]?.stringValue else { continue } + let input = ToolInput(block["input_preview"]?.stringValue) + item.tools.append(ToolStep( + id: block["tool_use_id"]?.stringValue ?? "\(rowID)-\(index)", + name: name, + status: block["status"]?.stringValue, + preview: input.target, + edits: input.edits, + label: input.label(for: name), + detail: input.detail + )) + case "plan": + guard role == .assistant else { continue } + item.plan = (block["entries"]?.arrayValue ?? []).enumerated().compactMap { offset, entry in + guard let label = entry["content"]?.stringValue else { return nil } + let status: PlanTask.Status + switch entry["status"]?.stringValue { + case "completed": status = .completed + case "in_progress": status = .running + default: status = .pending + } + return PlanTask(id: offset, label: label, status: status, priority: entry["priority"]?.stringValue) + } + default: + continue + } + } + item.text = texts.joined(separator: "\n") + item.thinking = thoughts.joined(separator: "\n\n") + if case .number(let value)? = turn["duration_ms"] { item.durationMs = Int(value) } + let hasText = !item.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + guard hasText || item.hasTrace || !item.plan.isEmpty else { continue } + var revision = 0.0 + if case .number(let value)? = row["revision"] { revision = value } + if let known = latest[rowID], known.revision > revision { continue } + if latest[rowID] == nil { order.append(rowID) } + latest[rowID] = (revision, item) + } + return order.compactMap { + guard var item = latest[$0]?.item else { return nil } + item.changes = changes[item.id] ?? [] + if item.changes.isEmpty { item.changes = Self.changes(fromEdits: item.tools.flatMap(\.edits)) } + return item + } + } + + /// One change per file, in the order the Agent first touched it, from its Write/Edit inputs. + private static func changes(fromEdits edits: [ToolEdit]) -> [FileChangeItem] { + var order: [String] = [] + var hunks: [String: [DiffHunk]] = [:] + for edit in edits { + if hunks[edit.path] == nil { order.append(edit.path) } + let id = hunks[edit.path]?.count ?? 0 + let rows: [DiffLine] + if let old = edit.old { + rows = lines(of: old).map { DiffLine(id: 0, kind: .removed, text: $0, oldNumber: nil, newNumber: nil) } + + lines(of: edit.new).map { DiffLine(id: 0, kind: .added, text: $0, oldNumber: nil, newNumber: nil) } + } else { + rows = lines(of: edit.new).map { DiffLine(id: 0, kind: .added, text: $0, oldNumber: nil, newNumber: nil) } + } + let numbered = rows.enumerated().map { + DiffLine(id: $0.offset, kind: $0.element.kind, text: $0.element.text, oldNumber: nil, newNumber: nil) + } + hunks[edit.path, default: []].append( + DiffHunk(id: id, header: edit.old == nil ? "新文件内容" : "修改", lines: numbered) + ) + } + return order.map { path in + let all = hunks[path] ?? [] + let rows = all.flatMap(\.lines) + return FileChangeItem( + path: path, + additions: rows.filter { $0.kind == .added }.count, + deletions: rows.filter { $0.kind == .removed }.count, + hunks: all + ) + } + } + + private static func lines(of text: String) -> [String] { + var rows = text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) + if rows.last == "" { rows.removeLast() } + return rows + } + + private static func role(_ value: String?) -> TimelineItem.Role? { + switch value { + case "user": return .user + case "assistant": return .assistant + default: return nil + } + } +} + +/// A tool call's raw input preview (usually JSON) turned into a chip target and detail lines. +struct ToolInput { + let target: String? + let detail: [String] + var edits: [ToolEdit] = [] + + private static let targetKeys = ["file_path", "path", "command", "cmd", "pattern", "query", "url", "description"] + + init(_ raw: String?) { + guard let raw, !raw.isEmpty else { + target = nil + detail = [] + return + } + guard let data = raw.data(using: .utf8), + let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] + else { + target = Self.clip(raw.split(separator: "\n").first.map(String.init) ?? raw, 60) + detail = Self.lines(raw) + return + } + if let path = (object["file_path"] ?? object["path"]) as? String { + if let content = object["content"] as? String { + edits = [ToolEdit(path: path, old: nil, new: content)] + } else if let old = object["old_string"] as? String, let new = object["new_string"] as? String { + edits = [ToolEdit(path: path, old: old, new: new)] + } else if let list = object["edits"] as? [[String: Any]] { + edits = list.compactMap { entry in + guard let old = entry["old_string"] as? String, let new = entry["new_string"] as? String else { return nil } + return ToolEdit(path: path, old: old, new: new) + } + } + } + let key = Self.targetKeys.first { object[$0] is String } + let value = key.flatMap { object[$0] as? String } + if let key, let value { + target = Self.clip(key.hasSuffix("path") ? (value as NSString).lastPathComponent : value, 60) + } else { + target = nil + } + detail = object.keys.sorted().compactMap { name -> [String]? in + guard name != key, let text = Self.text(object[name]), !text.isEmpty else { return nil } + let rows = Self.lines(text) + guard let first = rows.first else { return nil } + return ["\(name): \(first)"] + rows.dropFirst().prefix(1) + }.flatMap { $0 }.prefix(4).map { $0 } + } + + /// The action word(s) of `name` once the target is taken out of it. + func label(for name: String) -> String { + guard let target, !target.isEmpty else { return name } + let stripped = name.replacingOccurrences(of: target, with: "").trimmingCharacters(in: .whitespaces) + if stripped.isEmpty || stripped == name { return stripped.isEmpty ? Self.verb(name) : name } + return stripped + } + + private static func verb(_ name: String) -> String { + name.split(separator: " ").first.map(String.init) ?? name + } + + private static func text(_ value: Any?) -> String? { + switch value { + case let value as String: return value + case let value as NSNumber: return value.stringValue + case let value?: return (try? JSONSerialization.data(withJSONObject: value)).flatMap { String(data: $0, encoding: .utf8) } + default: return nil + } + } + + private static func lines(_ raw: String) -> [String] { + raw.split(separator: "\n").prefix(4).map { + clip(String($0).trimmingCharacters(in: .whitespaces), 80) + } + } + + private static func clip(_ value: String, _ limit: Int) -> String { + value.count > limit ? String(value.prefix(limit)) + "…" : value + } +} + +/// A project and the workspaces whose conversations belong to it. +public struct ProjectSummary: Decodable, Identifiable, Equatable, Hashable, Sendable { + public let id: String + public let name: String + public let workspaceIds: [String] + + public init(id: String, name: String, workspaceIds: [String]) { + self.id = id + self.name = name + self.workspaceIds = workspaceIds + } +} + +/// Conversations bucketed by project, newest activity first. +public struct ProjectGroup: Identifiable, Equatable, Sendable { + public let id: String + public let name: String + public let conversations: [ConversationListItem] + + public init(id: String, name: String, conversations: [ConversationListItem]) { + self.id = id + self.name = name + self.conversations = conversations + } + + public var latest: Date? { conversations.compactMap(\.updatedAt).max() } + + /// Projects that have conversations, most recently active first; conversations whose + /// workspace belongs to no known project fall into one trailing "其他" group. + public static func make(conversations: [ConversationListItem], projects: [ProjectSummary]) -> [ProjectGroup] { + var owner: [String: ProjectSummary] = [:] + for project in projects { + for workspace in project.workspaceIds { owner[workspace.lowercased()] = project } + } + var buckets: [String: [ConversationListItem]] = [:] + var names: [String: String] = [:] + for conversation in conversations { + let project = owner[conversation.workspace_id.lowercased()] + let key = project?.id ?? "other" + buckets[key, default: []].append(conversation) + names[key] = project?.name ?? "其他" + } + let groups = buckets.map { ProjectGroup(id: $0.key, name: names[$0.key] ?? "其他", conversations: $0.value) } + return groups.sorted { + if $0.id == "other" { return false } + if $1.id == "other" { return true } + return ($0.latest ?? .distantPast) > ($1.latest ?? .distantPast) + } + } +} diff --git a/mobile/ios/Sources/CompanionCore/HostOrigin.swift b/mobile/ios/Sources/CompanionCore/HostOrigin.swift new file mode 100644 index 000000000..1b7d5859c --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/HostOrigin.swift @@ -0,0 +1,36 @@ +import Foundation + +public struct HostOrigin: Equatable, Sendable { + public let value: String + + public func resolve(_ path: String) -> String { + value + (path.hasPrefix("/") ? path : "/" + path) + } + + public static func parse(_ raw: String) throws -> HostOrigin { + var trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + while trimmed.hasSuffix("/") { trimmed.removeLast() } + guard !trimmed.isEmpty else { throw PairingError.invalidOrigin("Host origin is required") } + guard let components = URLComponents(string: trimmed) else { + throw PairingError.invalidOrigin("Host origin is not a valid URI") + } + guard components.scheme == "http" || components.scheme == "https" else { + throw PairingError.invalidOrigin("Host origin must be http or https") + } + guard let host = components.host, !host.isEmpty else { + throw PairingError.invalidOrigin("Host origin must include a host") + } + guard components.user == nil, components.password == nil else { + throw PairingError.invalidOrigin("Host origin must not include credentials") + } + guard components.query == nil else { + throw PairingError.invalidOrigin("Host origin must not include a query string") + } + guard components.fragment == nil else { + throw PairingError.invalidOrigin("Host origin must not include a fragment") + } + let hostPart = host.contains(":") ? "[\(host)]" : host + let port = components.port.map { ":\($0)" } ?? "" + return HostOrigin(value: "\(components.scheme!)://\(hostPart)\(port)\(components.path)") + } +} diff --git a/mobile/ios/Sources/CompanionCore/JSONValueAccess.swift b/mobile/ios/Sources/CompanionCore/JSONValueAccess.swift new file mode 100644 index 000000000..4328f825e --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/JSONValueAccess.swift @@ -0,0 +1,45 @@ +import Foundation + +extension JSONValue { + subscript(key: String) -> JSONValue? { + if case .object(let fields) = self { return fields[key] } + return nil + } + + var stringValue: String? { + if case .string(let text) = self { return text } + return nil + } + + var arrayValue: [JSONValue]? { + if case .array(let items) = self { return items } + return nil + } + + /// The Host may nest the event body under `event`; accept both shapes. + func eventField(_ key: String) -> JSONValue? { + self[key] ?? self["event"]?[key] + } + + /// Plain Foundation value for `JSONSerialization`. + var foundationValue: Any { + switch self { + case .null: return NSNull() + case .bool(let value): return value + case .number(let value): return value + case .string(let value): return value + case .array(let items): return items.map(\.foundationValue) + case .object(let fields): return fields.mapValues(\.foundationValue) + } + } + + /// Short text for showing a config choice's current value. + var displayText: String? { + switch self { + case .string(let value): return value + case .bool(let value): return value ? "开" : "关" + case .number(let value): return value == value.rounded() ? String(Int(value)) : String(value) + default: return nil + } + } +} diff --git a/mobile/ios/Sources/CompanionCore/PairingClient.swift b/mobile/ios/Sources/CompanionCore/PairingClient.swift new file mode 100644 index 000000000..654442b89 --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/PairingClient.swift @@ -0,0 +1,214 @@ +import Foundation + +public struct HttpExchange: Sendable { + public let status: Int + public let body: Data + + public init(status: Int, body: Data) { + self.status = status + self.body = body + } +} + +public protocol HttpTransport: Sendable { + func execute( + method: String, + url: String, + headers: [String: String], + body: Data? + ) async throws -> HttpExchange +} + +public enum PairingError: Error, Equatable, LocalizedError { + case invalidOrigin(String) + case missingInput(String) + case redeemFailed(Int) + case codeAlreadyUsed + case codeExpired + case codeInvalid + case nonCompanionScopes([String]) + case capabilitiesFailed(Int) + case incompatibleProtocol(host: String, client: String) + case invalidInvitation + case notCompanionInvitation + case invitationExpired + case unreachable + + public var errorDescription: String? { + switch self { + case .invalidOrigin(let message), .missingInput(let message): + return message + case .redeemFailed(let status): + return "配对失败(\(status))" + case .codeAlreadyUsed: + return "连接码已被使用,请在电脑上重新生成" + case .codeExpired: + return "连接码已过期,请在电脑上重新生成" + case .codeInvalid: + return "连接码不正确,请检查后重试" + case .nonCompanionScopes(let scopes): + return "Host granted non-companion scopes: \(scopes.joined(separator: ", "))" + case .capabilitiesFailed(let status): + return "Capabilities check failed (\(status))" + case .incompatibleProtocol(let host, let client): + return "Host protocol \(host) is incompatible with client \(client)" + case .invalidInvitation: + return "无法识别连接码" + case .notCompanionInvitation: + return "此连接码不是手机用的。在电脑上将“连接设备”选为“手机”后重新生成" + case .invitationExpired: + return "连接码已过期,请在电脑上重新生成" + case .unreachable: + return "无法连接到电脑,请确认手机与电脑在同一网络" + } + } +} + +public struct CompanionSession { + public let origin: HostOrigin + public let credential: DeviceCredential + public let capabilities: ServerCapabilities +} + +public struct PairingClient { + public static let clientProtocolVersion = "1.0" + public static let protocolHeader = "x-vibex-protocol-version" + + private let transport: HttpTransport + private let protocolVersion: String + + public init( + transport: HttpTransport = URLSessionTransport(), + protocolVersion: String = PairingClient.clientProtocolVersion + ) { + self.transport = transport + self.protocolVersion = protocolVersion + } + + public func redeem( + origin: HostOrigin, + pairingToken: String, + deviceName: String = "iOS Companion" + ) async throws -> CompanionSession { + let token = pairingToken.trimmingCharacters(in: .whitespacesAndNewlines) + let name = deviceName.trimmingCharacters(in: .whitespacesAndNewlines) + guard !token.isEmpty else { throw PairingError.missingInput("Pairing token is required") } + guard !name.isEmpty else { throw PairingError.missingInput("Device name is required") } + + let body = try JSONSerialization.data( + withJSONObject: ["pairing_token": token, "device_name": name] + ) + let redeem = try await transport.execute( + method: "POST", + url: origin.resolve("/api/v1/auth/pairings/redeem"), + headers: [ + "content-type": "application/json", + Self.protocolHeader: protocolVersion, + ], + body: body + ) + guard (200...299).contains(redeem.status) else { + throw Self.redeemError(status: redeem.status, body: redeem.body) + } + let credential = try JSONDecoder().decode(DeviceCredential.self, from: redeem.body) + let extras = CompanionScopes.extras(credential.scopes) + guard extras.isEmpty else { + throw PairingError.nonCompanionScopes(extras.sorted()) + } + + let response = try await transport.execute( + method: "GET", + url: origin.resolve("/api/v1/capabilities"), + headers: [ + "authorization": "Bearer \(credential.access_token)", + Self.protocolHeader: protocolVersion, + ], + body: nil + ) + guard (200...299).contains(response.status) else { + throw PairingError.capabilitiesFailed(response.status) + } + let capabilities = try JSONDecoder().decode(ServerCapabilities.self, from: response.body) + guard Self.major(capabilities.protocol_version) == Self.major(protocolVersion) else { + throw PairingError.incompatibleProtocol( + host: capabilities.protocol_version, + client: protocolVersion + ) + } + return CompanionSession(origin: origin, credential: credential, capabilities: capabilities) + } + + public func redeem( + invitation: PairingInvitation, + deviceName: String = "iOS Companion", + now: Date = Date() + ) async throws -> CompanionSession { + guard invitation.preset == PairingInvitation.companionPreset else { + throw PairingError.notCompanionInvitation + } + if let expiry = invitation.expiresAtDate, expiry <= now { + throw PairingError.invitationExpired + } + let origins = invitation.candidateOrigins + guard !origins.isEmpty else { throw PairingError.unreachable } + for origin in origins { + do { + return try await redeem( + origin: origin, + pairingToken: invitation.pairing_token, + deviceName: deviceName + ) + } catch let error as PairingError { + throw error + } catch { + continue + } + } + throw PairingError.unreachable + } + + /// The Host explains a rejected code in `details.reason`; map it to something the user can act on. + static func redeemError(status: Int, body: Data) -> PairingError { + struct Failure: Decodable { + struct Details: Decodable { let reason: String? } + let details: Details? + } + let reason = (try? JSONDecoder().decode(Failure.self, from: body))?.details?.reason + switch reason { + case "pairing_redeemed": return .codeAlreadyUsed + case "pairing_expired": return .codeExpired + case "invalid_pairing": return .codeInvalid + default: return status == 401 ? .codeInvalid : .redeemFailed(status) + } + } + + static func major(_ version: String) -> Substring { + version.split(separator: ".", maxSplits: 1).first ?? "" + } +} + +public struct URLSessionTransport: HttpTransport { + private let session: URLSession + + public init(session: URLSession = .shared) { + self.session = session + } + + public func execute( + method: String, + url: String, + headers: [String: String], + body: Data? + ) async throws -> HttpExchange { + guard let target = URL(string: url) else { + throw PairingError.invalidOrigin("Host origin is not a valid URI") + } + var request = URLRequest(url: target, timeoutInterval: 20) + request.httpMethod = method + request.httpBody = body + for (key, value) in headers { request.setValue(value, forHTTPHeaderField: key) } + let (data, response) = try await session.data(for: request) + let status = (response as? HTTPURLResponse)?.statusCode ?? 0 + return HttpExchange(status: status, body: data) + } +} diff --git a/mobile/ios/Sources/CompanionCore/PairingInvitation.swift b/mobile/ios/Sources/CompanionCore/PairingInvitation.swift new file mode 100644 index 000000000..45bffbe85 --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/PairingInvitation.swift @@ -0,0 +1,57 @@ +import Foundation + +/// Text shown by the Host as QR and copyable connection code: `vibex-pairing:` + JSON. +public struct PairingInvitation: Decodable, Equatable, Sendable { + public struct Reachability: Decodable, Equatable, Sendable { + public let origin: String + public let kind: String + } + + public static let prefix = "vibex-pairing:" + public static let companionPreset = "companion" + + public let version: Int + public let host_id: String + public let preset: String + public let expires_at: String + public let pairing_id: String + public let pairing_token: String + public let reachability: [Reachability] + + public static func looksLikeInvitation(_ text: String) -> Bool { + text.trimmingCharacters(in: .whitespacesAndNewlines).hasPrefix(prefix) + } + + public static func parse(_ text: String) throws -> PairingInvitation { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard trimmed.hasPrefix(prefix) else { throw PairingError.invalidInvitation } + let json = Data(trimmed.dropFirst(prefix.count).utf8) + guard let invitation = try? JSONDecoder().decode(PairingInvitation.self, from: json), + !invitation.pairing_token.isEmpty + else { throw PairingError.invalidInvitation } + return invitation + } + + public var expiresAtDate: Date? { + let plain = ISO8601DateFormatter() + let fractional = ISO8601DateFormatter() + fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return fractional.date(from: expires_at) ?? plain.date(from: expires_at) + } + + /// Published HTTPS first, then the rest in Host order; loopback never reaches a phone. + public var candidateOrigins: [HostOrigin] { + let parsed = reachability.compactMap { item -> (HostOrigin, Bool)? in + guard let origin = try? HostOrigin.parse(item.origin), + !Self.isLoopback(origin.value) + else { return nil } + return (origin, origin.value.hasPrefix("https://")) + } + return parsed.filter(\.1).map(\.0) + parsed.filter { !$0.1 }.map(\.0) + } + + private static func isLoopback(_ origin: String) -> Bool { + guard let host = URLComponents(string: origin)?.host?.lowercased() else { return true } + return host == "localhost" || host == "127.0.0.1" || host == "::1" + } +} diff --git a/mobile/ios/Sources/CompanionCore/QuestionForm.swift b/mobile/ios/Sources/CompanionCore/QuestionForm.swift new file mode 100644 index 000000000..978e40bef --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/QuestionForm.swift @@ -0,0 +1,202 @@ +import Foundation + +public struct QuestionChoice: Equatable, Sendable, Identifiable { + public let value: JSONValue + public let label: String + public let description: String? + public var id: String { label } +} + +/// One step of a question card. +public struct FormQuestion: Equatable, Sendable, Identifiable { + public enum ValueType: Sendable { case string, number, integer, boolean } + + public let id: String + /// Schema property the answer is stored under; nil for `x-vibex-questions`, which answer by id. + public let fieldName: String? + public let customFieldName: String? + public let header: String + public let text: String + public let multiSelect: Bool + public let valueType: ValueType + public let choices: [QuestionChoice] +} + +public struct QuestionAnswer: Equatable, Sendable { + public var selected: [JSONValue] = [] + public var customText = "" + + public init(selected: [JSONValue] = [], customText: String = "") { + self.selected = selected + self.customText = customText + } + + public var trimmedCustom: String { customText.trimmingCharacters(in: .whitespacesAndNewlines) } + public var isEmpty: Bool { selected.isEmpty && trimmedCustom.isEmpty } +} + +/// Turns a question request into card steps and the answer back into the `content` the Agent expects. +/// The shapes mirror the desktop's question card so both clients answer identically. +public enum QuestionForm { + public static func questions(for request: PendingQuestion) -> [FormQuestion] { + let root = request.schema + if let list = root?["x-vibex-questions"]?.arrayValue { + let parsed = list.enumerated().compactMap { index, item -> FormQuestion? in + guard item["question"]?.stringValue != nil || item["header"]?.stringValue != nil else { return nil } + let text = item["question"]?.stringValue ?? "问题 \(index + 1)" + return FormQuestion( + id: item["id"]?.stringValue ?? "question-\(index + 1)", + fieldName: nil, + customFieldName: nil, + header: item["header"]?.stringValue ?? text, + text: text, + multiSelect: flag(item["multiSelect"]) || flag(item["multi_select"]) || flag(item["is_multi_select"]), + valueType: .string, + choices: choices(from: item["options"]?.arrayValue ?? []) + ) + } + if !parsed.isEmpty { return parsed } + } + if case .object(let properties)? = root?["properties"], !properties.isEmpty { + let names = properties.keys.sorted() + let companions = Set(names.filter { name in + name.hasSuffix("_custom") && properties[String(name.dropLast("_custom".count))] != nil + }) + return names.filter { !companions.contains($0) }.enumerated().map { index, name in + let property = properties[name] ?? .null + let isArray = property["type"]?.stringValue == "array" + let source = isArray ? (property["items"] ?? .null) : property + var type = FormQuestion.ValueType.string + switch source["type"]?.stringValue { + case "number": type = .number + case "integer": type = .integer + case "boolean": type = .boolean + default: break + } + var options = schemaChoices(source) + if type == .boolean && options.isEmpty { + options = [ + QuestionChoice(value: .bool(true), label: "是", description: nil), + QuestionChoice(value: .bool(false), label: "否", description: nil), + ] + } + let text = property["description"]?.stringValue ?? property["title"]?.stringValue ?? name + return FormQuestion( + id: name, + fieldName: name, + customFieldName: companions.contains(name + "_custom") ? name + "_custom" : nil, + header: property["title"]?.stringValue ?? "问题 \(index + 1)", + text: text, + multiSelect: isArray, + valueType: type, + choices: options + ) + } + } + return [FormQuestion( + id: "answer", + fieldName: "answer", + customFieldName: nil, + header: request.prompt, + text: request.prompt, + multiSelect: false, + valueType: .string, + choices: request.options.map { QuestionChoice(value: .string($0), label: $0, description: nil) } + )] + } + + /// `nil` when nothing was answered, which the card sends as a decline. + public static func content( + for request: PendingQuestion, + questions: [FormQuestion], + answers: [String: QuestionAnswer] + ) -> JSONValue? { + guard answers.values.contains(where: { !$0.isEmpty }) else { return nil } + if request.schema?["x-vibex-questions"]?.arrayValue != nil { + let items = questions.map { question -> JSONValue in + let answer = answers[question.id] ?? QuestionAnswer() + var labels = answer.selected.compactMap { value in + question.choices.first { $0.value == value }?.label ?? value.displayText + } + if !answer.trimmedCustom.isEmpty { labels.append(answer.trimmedCustom) } + return .object([ + "questionId": .string(question.id), + "labels": .array(labels.map(JSONValue.string)), + ]) + } + return .object(["answers": .array(items)]) + } + var content: [String: JSONValue] = [:] + for question in questions { + let answer = answers[question.id] ?? QuestionAnswer() + let field = question.fieldName ?? question.id + let custom = answer.trimmedCustom + if !custom.isEmpty, let companion = question.customFieldName { + if question.multiSelect { + content[field] = .array(answer.selected) + } else if let first = answer.selected.first { + content[field] = first + } + content[companion] = .string(custom) + } else if !custom.isEmpty { + let value = parsed(custom, as: question.valueType) + content[field] = question.multiSelect ? .array(answer.selected + [value]) : value + } else { + content[field] = question.multiSelect ? .array(answer.selected) : (answer.selected.first ?? .string("")) + } + } + return .object(content) + } + + // MARK: Parsing helpers + + private static func flag(_ value: JSONValue?) -> Bool { + if case .bool(true)? = value { return true } + return false + } + + private static func choices(from list: [JSONValue]) -> [QuestionChoice] { + list.compactMap { item in + if let label = item.stringValue { return QuestionChoice(value: .string(label), label: label, description: nil) } + guard let label = item["label"]?.stringValue ?? item["value"]?.stringValue else { return nil } + return QuestionChoice( + value: item["value"] ?? .string(label), + label: label, + description: item["description"]?.stringValue + ) + } + } + + private static func schemaChoices(_ property: JSONValue) -> [QuestionChoice] { + if let values = property["enum"]?.arrayValue { + let names = property["enumNames"]?.arrayValue ?? [] + return values.enumerated().compactMap { index, value in + let label = (index < names.count ? names[index].stringValue : nil) ?? value.displayText + return label.map { QuestionChoice(value: value, label: $0, description: nil) } + } + } + for key in ["oneOf", "anyOf"] { + if let variants = property[key]?.arrayValue { + return variants.compactMap { variant in + guard let value = variant["const"] else { return nil } + let label = variant["title"]?.stringValue ?? value.displayText + return label.map { QuestionChoice(value: value, label: $0, description: variant["description"]?.stringValue) } + } + } + } + return [] + } + + private static func parsed(_ text: String, as type: FormQuestion.ValueType) -> JSONValue { + switch type { + case .number, .integer: + if let number = Double(text) { return .number(number) } + case .boolean: + if text.lowercased() == "true" { return .bool(true) } + if text.lowercased() == "false" { return .bool(false) } + case .string: + break + } + return .string(text) + } +} diff --git a/mobile/ios/Sources/CompanionCore/RemoteProtocolModels.swift b/mobile/ios/Sources/CompanionCore/RemoteProtocolModels.swift new file mode 120000 index 000000000..a21ae8ba2 --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/RemoteProtocolModels.swift @@ -0,0 +1 @@ +../../../../docs/protocol/v1/generated/swift/RemoteProtocolModels.swift \ No newline at end of file diff --git a/mobile/ios/Sources/CompanionCore/SessionState.swift b/mobile/ios/Sources/CompanionCore/SessionState.swift new file mode 100644 index 000000000..44dfe3c01 --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/SessionState.swift @@ -0,0 +1,185 @@ +import Foundation + +public struct PermissionOption: Equatable, Sendable, Identifiable { + public let id: String + public let label: String + public let kind: String +} + +public struct PermissionPrompt: Equatable, Sendable, Identifiable { + public let id: String + public let title: String + public let options: [PermissionOption] +} + +/// A question the Agent is waiting on (`question_requested`), before it is turned into a form. +public struct PendingQuestion: Equatable, Sendable, Identifiable { + public let id: String + public let prompt: String + public let options: [String] + public let schema: JSONValue? +} + +public struct SessionMode: Equatable, Sendable, Identifiable { + public let id: String + public let label: String + public let description: String? +} + +public struct ConfigChoice: Equatable, Sendable, Identifiable { + public let value: JSONValue + public let label: String + public let description: String? + public var id: String { label + (value.displayText ?? "") } +} + +public struct ConfigOption: Equatable, Sendable, Identifiable { + public let key: String + public let label: String + public let category: String? + public let value: JSONValue? + public let choices: [ConfigChoice] + public var id: String { key } + + public var currentLabel: String? { + guard let value else { return nil } + return choices.first(where: { $0.value == value })?.label ?? value.displayText + } +} + +/// What the phone may show and change for one Conversation, folded from its event log. +public struct SessionState: Equatable, Sendable { + public var modes: [SessionMode] = [] + public var currentModeID: String? + public var options: [ConfigOption] = [] + public var pendingPermissions: [PermissionPrompt] = [] + public var pendingQuestions: [PendingQuestion] = [] + public var isTurnRunning = false + + public init() {} + + public var currentModeLabel: String? { + modes.first(where: { $0.id == currentModeID })?.label ?? currentModeID + } + + public var modelOptions: [ConfigOption] { options.filter { $0.category == "model" } } + + /// Everything else the Agent advertises (reasoning effort, fast mode, ...), minus the mode picker. + public var otherOptions: [ConfigOption] { + options.filter { $0.category != "model" && $0.category != "mode" } + } +} + +public enum SessionStateBuilder { + public static func build(from events: [RemoteEvent]) -> SessionState { + var state = SessionState() + var pending: [(id: String, prompt: PermissionPrompt)] = [] + var questions: [PendingQuestion] = [] + for event in events.sorted(by: { $0.sequence < $1.sequence }) { + let payload = event.payload + switch event.kind { + case "session_mode_updated": + state.currentModeID = payload.eventField("current")?.stringValue + state.modes = (payload.eventField("modes")?.arrayValue ?? []).compactMap(mode) + case "session_config_options_updated": + state.options = (payload.eventField("options")?.arrayValue ?? []).compactMap(option) + case "permission_requested": + if let prompt = permission(payload) { + pending.removeAll { $0.id == prompt.id } + pending.append((prompt.id, prompt)) + } + case "permission_responded": + if let id = payload.eventField("permission_id")?.stringValue { + pending.removeAll { $0.id == id } + } + case "question_requested": + if let question = pendingQuestion(payload) { + questions.removeAll { $0.id == question.id } + questions.append(question) + } + case "question_responded": + if let id = payload.eventField("question_id")?.stringValue { + questions.removeAll { $0.id == id } + } + case "user_turn_started": + state.isTurnRunning = true + case "turn_completed", "turn_failed", "turn_cancelled", "turn_interrupted": + state.isTurnRunning = false + pending.removeAll() + questions.removeAll() + default: + continue + } + } + state.pendingPermissions = pending.map(\.prompt) + state.pendingQuestions = questions + return state + } + + /// Controls of a live Agent session, as returned by `conversation_ensure_session_controls`. + public static func controls(from snapshot: JSONValue) -> SessionState { + var state = SessionState() + state.modes = (snapshot["modes"]?.arrayValue ?? []).compactMap(mode) + state.currentModeID = snapshot["current_mode"]?.stringValue + state.options = (snapshot["config_options"]?.arrayValue ?? []).compactMap(option) + return state + } + + static func mode(_ item: JSONValue) -> SessionMode? { + guard let id = item["id"]?.stringValue else { return nil } + return SessionMode( + id: id, + label: item["label"]?.stringValue ?? id, + description: item["description"]?.stringValue + ) + } + + static func option(_ item: JSONValue) -> ConfigOption? { + guard let key = item["key"]?.stringValue else { return nil } + let choices = (item["choices"]?.arrayValue ?? []).compactMap { choice -> ConfigChoice? in + guard let value = choice["value"] else { return nil } + return ConfigChoice( + value: value, + label: choice["label"]?.stringValue ?? value.displayText ?? "", + description: choice["description"]?.stringValue + ) + } + return ConfigOption( + key: key, + label: item["label"]?.stringValue ?? key, + category: item["category"]?.stringValue, + value: item["value"], + choices: choices + ) + } + + private static func pendingQuestion(_ payload: JSONValue) -> PendingQuestion? { + guard let request = payload.eventField("request"), + let id = request["question_id"]?.stringValue + else { return nil } + var schema = request["schema"] + if case .null? = schema { schema = nil } + return PendingQuestion( + id: id, + prompt: request["prompt"]?.stringValue ?? "", + options: (request["options"]?.arrayValue ?? []).compactMap(\.stringValue), + schema: schema + ) + } + + private static func permission(_ payload: JSONValue) -> PermissionPrompt? { + guard let wrapper = payload.eventField("request"), + let id = wrapper["permission_id"]?.stringValue + else { return nil } + let request = wrapper["request"] + let options = (request?["options"]?.arrayValue ?? []).compactMap { item -> PermissionOption? in + guard let optionID = item["id"]?.stringValue else { return nil } + return PermissionOption( + id: optionID, + label: item["label"]?.stringValue ?? optionID, + kind: item["kind"]?.stringValue ?? "unknown" + ) + } + return PermissionPrompt(id: id, title: request?["title"]?.stringValue ?? "权限请求", options: options) + } +} diff --git a/mobile/ios/Sources/CompanionCore/TranscriptState.swift b/mobile/ios/Sources/CompanionCore/TranscriptState.swift new file mode 100644 index 000000000..76af30b90 --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/TranscriptState.swift @@ -0,0 +1,26 @@ +import Foundation + +/// Rows of one Conversation's transcript, merged across polls. +public struct TranscriptState: Sendable { + public let conversationID: String + public private(set) var items: [TimelineItem] = [] + var nextIndex = 0 + private var order: [String] = [] + private var rows: [String: (revision: Double, row: JSONValue)] = [:] + + public init(conversationID: String) { + self.conversationID = conversationID + } + + mutating func merge(_ incoming: [JSONValue]) { + for row in incoming { + guard let id = row["row_id"]?.stringValue else { continue } + var revision = 0.0 + if case .number(let value)? = row["revision"] { revision = value } + if let known = rows[id], known.revision > revision { continue } + if rows[id] == nil { order.append(id) } + rows[id] = (revision, row) + } + items = TimelineBuilder.build(fromRows: order.compactMap { rows[$0]?.row }) + } +} diff --git a/mobile/ios/Sources/CompanionCore/WorkspaceModels.swift b/mobile/ios/Sources/CompanionCore/WorkspaceModels.swift new file mode 100644 index 000000000..dfb4858a8 --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/WorkspaceModels.swift @@ -0,0 +1,152 @@ +import Foundation + +public struct WorkspaceTree: Decodable, Equatable, Sendable { + public let path: String + public let entries: [WorkspaceEntry] + public let truncated: Bool +} + +public struct WorkspaceFile: Decodable, Equatable, Sendable { + public let path: String + public let size: Int + public let binary: Bool + public let truncated: Bool + public let content: String? +} + +struct WorkspaceDiffEntry: Decodable { + let path: String + let status: String + let diff: String + let is_binary: Bool + let truncated: Bool? +} + +public struct DiffLine: Identifiable, Equatable, Sendable { + public enum Kind: Sendable { case context, added, removed } + + public let id: Int + public let kind: Kind + public let text: String + public let oldNumber: Int? + public let newNumber: Int? +} + +public struct DiffHunk: Identifiable, Equatable, Sendable { + public let id: Int + public let header: String + public let lines: [DiffLine] +} + +public struct FileDiff: Identifiable, Equatable, Sendable { + public enum Change: Sendable { case added, modified, deleted, renamed, untracked } + + public let path: String + public let change: Change + public let isBinary: Bool + public let truncated: Bool + public let hunks: [DiffHunk] + + public var id: String { path } + public var additions: Int { count(.added) } + public var deletions: Int { count(.removed) } + /// Untracked files carry no diff; the phone shows their whole content as additions instead. + public var needsContent: Bool { change == .untracked && !isBinary } + + private func count(_ kind: DiffLine.Kind) -> Int { + hunks.reduce(0) { $0 + $1.lines.filter { $0.kind == kind }.count } + } + + public init(path: String, hunks: [DiffHunk]) { + self.path = path + self.change = .modified + self.isBinary = false + self.truncated = false + self.hunks = hunks + } + + init(_ entry: WorkspaceDiffEntry) { + path = entry.path + isBinary = entry.is_binary + truncated = entry.truncated ?? false + hunks = UnifiedDiff.parse(entry.diff) + switch entry.status { + case "A": change = .added + case "D": change = .deleted + case "R", "C": change = .renamed + case "?": change = .untracked + default: change = .modified + } + } + + /// Every line of a new file as an addition. + public static func additions(of content: String) -> [DiffHunk] { + let lines = content.split(separator: "\n", omittingEmptySubsequences: false) + let trimmed = lines.last == "" ? Array(lines.dropLast()) : lines + guard !trimmed.isEmpty else { return [] } + let rows = trimmed.enumerated().map { + DiffLine(id: $0.offset, kind: .added, text: String($0.element), oldNumber: nil, newNumber: $0.offset + 1) + } + return [DiffHunk(id: 0, header: "@@ -0,0 +1,\(rows.count) @@", lines: rows)] + } +} + +public enum UnifiedDiff { + /// Parses the hunks of one file's `git diff` text; header lines before the first hunk are skipped. + public static func parse(_ text: String) -> [DiffHunk] { + var hunks: [DiffHunk] = [] + var header = "" + var lines: [DiffLine] = [] + var oldNumber = 0 + var newNumber = 0 + var inHunk = false + + func flush() { + if inHunk { hunks.append(DiffHunk(id: hunks.count, header: header, lines: lines)) } + lines = [] + } + + for raw in text.split(separator: "\n", omittingEmptySubsequences: false) { + let line = String(raw) + if line.hasPrefix("@@") { + flush() + guard let (old, new) = hunkStarts(line) else { + inHunk = false + continue + } + header = line + oldNumber = old + newNumber = new + inHunk = true + continue + } + guard inHunk, let marker = line.first else { continue } + let body = String(line.dropFirst()) + switch marker { + case "+": + lines.append(DiffLine(id: lines.count, kind: .added, text: body, oldNumber: nil, newNumber: newNumber)) + newNumber += 1 + case "-": + lines.append(DiffLine(id: lines.count, kind: .removed, text: body, oldNumber: oldNumber, newNumber: nil)) + oldNumber += 1 + case " ": + lines.append(DiffLine(id: lines.count, kind: .context, text: body, oldNumber: oldNumber, newNumber: newNumber)) + oldNumber += 1 + newNumber += 1 + default: + continue // "\ No newline at end of file" + } + } + flush() + return hunks + } + + /// `@@ -a[,b] +c[,d] @@ ...` → (a, c) + private static func hunkStarts(_ header: String) -> (Int, Int)? { + let parts = header.split(separator: " ") + guard parts.count >= 3, parts[1].hasPrefix("-"), parts[2].hasPrefix("+") else { return nil } + func start(_ part: Substring) -> Int? { Int(part.dropFirst().split(separator: ",").first ?? "") } + guard let old = start(parts[1]), let new = start(parts[2]) else { return nil } + return (old, new) + } +} diff --git a/mobile/ios/Tests/CompanionCoreTests/HostClientTests.swift b/mobile/ios/Tests/CompanionCoreTests/HostClientTests.swift new file mode 100644 index 000000000..f4906e16d --- /dev/null +++ b/mobile/ios/Tests/CompanionCoreTests/HostClientTests.swift @@ -0,0 +1,417 @@ +import Foundation +import Testing +@testable import CompanionCore + +private struct StubTransport: HttpTransport { + let status: Int + let reply: String + func execute( + method: String, url: String, headers: [String: String], body: Data? + ) async throws -> HttpExchange { + HttpExchange(status: status, body: Data(reply.utf8)) + } +} + +private func client(_ status: Int, _ body: String) throws -> HostClient { + HostClient( + origin: try HostOrigin.parse("http://192.168.1.2:17891"), + accessToken: "t", + transport: StubTransport(status: status, reply: body) + ) +} + +@Test func callDecodesConversationList() async throws { + let json = """ + {"operation_id":"o","data":[{"id":"c1","workspace_id":"w","title":null,"status":"idle","model":"m","message_count":2,"created_at":"2026-11-06T14:00:00Z","updated_at":"2026-11-06T14:59:55.123456Z","extra":1}]} + """ + let items: [ConversationListItem] = try await client(200, json).call("conversation_list_recent") + #expect(items.count == 1) + #expect(items[0].title == nil) + #expect(items[0].updatedAt != nil) +} + +@Test func callSurfacesServerMessage() async throws { + let body = "{\"code\":\"forbidden\",\"message\":\"principal lacks artifact.read\",\"retryable\":false,\"operation_id\":\"o\"}" + await #expect(throws: HostError.server(status: 403, message: "principal lacks artifact.read")) { + let _: [ArtifactListItem] = try await client(403, body).call("artifact_list") + } +} + +@Test func timelineReadsMessageTurnsFromTranscriptRows() throws { + let raw = """ + [ + {"row_id":"u1","revision":1,"row":{"kind":"message_turn","phase":"done","turn":{"id":"t1","role":"user","blocks":[{"type":"text","text":"你好"}]}}}, + {"row_id":"a1","revision":2,"row":{"kind":"message_turn","phase":"done","turn":{"id":"t2","role":"assistant","blocks":[{"type":"thinking","text":"hm"},{"type":"text","text":"你好,Sara!"},{"type":"tool_use","tool_name":"ls"}]}}}, + {"row_id":"a1","revision":1,"row":{"kind":"message_turn","phase":"streaming","turn":{"id":"t2","role":"assistant","blocks":[{"type":"text","text":"你好"}]}}}, + {"row_id":"s1","revision":1,"row":{"kind":"message_turn","phase":"done","turn":{"id":"t3","role":"system","blocks":[{"type":"text","text":"x"}]}}}, + {"row_id":"p1","revision":1,"row":{"kind":"permission_request","request":{}}} + ] + """ + let rows = try JSONDecoder().decode([JSONValue].self, from: Data(raw.utf8)) + let items = TimelineBuilder.build(fromRows: rows) + #expect(items.map(\.text) == ["你好", "你好,Sara!"]) + #expect(items.map(\.role) == [.user, .assistant]) +} + +@Test func refreshReadsEverythingOnceThenOnlyTheTail() async throws { + final class Pager: HttpTransport, @unchecked Sendable { + private let lock = NSLock() + private(set) var cursors: [String?] = [] + private var assistantText = "r" + func grow() { lock.withLock { assistantText += "r" } } + func execute( + method: String, url: String, headers: [String: String], body: Data? + ) async throws -> HttpExchange { + let args = (body.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any])?["args"] as? [String: Any] + let cursor = args?["cursor"] as? String + let text = lock.withLock { () -> String in cursors.append(cursor); return assistantText } + func row(_ id: String, _ role: String, _ text: String, _ revision: Int) -> String { + "{\"row_id\":\"\(id)\",\"revision\":\(revision),\"row\":{\"kind\":\"message_turn\",\"phase\":\"done\",\"turn\":{\"id\":\"\(id)\",\"role\":\"\(role)\",\"blocks\":[{\"type\":\"text\",\"text\":\"\(text)\"}]}}}" + } + let json: String + switch cursor { + case nil: + json = "{\"operation_id\":\"o\",\"data\":{\"cursor\":\"0\",\"rows\":[\(row("u", "user", "q", 1))],\"next_cursor\":\"1\"}}" + case "1": + json = "{\"operation_id\":\"o\",\"data\":{\"cursor\":\"1\",\"rows\":[\(row("a", "assistant", text, text.count))],\"next_cursor\":null}}" + default: // tail re-read from index max(0, 2 - 4) = 0 + json = "{\"operation_id\":\"o\",\"data\":{\"cursor\":\"0\",\"rows\":[\(row("u", "user", "q", 1)),\(row("a", "assistant", text, text.count))],\"next_cursor\":null}}" + } + return HttpExchange(status: 200, body: Data(json.utf8)) + } + } + let pager = Pager() + let host = HostClient( + origin: try HostOrigin.parse("http://192.168.1.2:17891"), + accessToken: "t", + transport: pager + ) + var state = TranscriptState(conversationID: "c") + try await host.refresh(&state) + #expect(state.items.map(\.text) == ["q", "r"]) + pager.grow() + try await host.refresh(&state) + #expect(state.items.map(\.text) == ["q", "rr"]) + #expect(state.items.count == 2) +} + +@Test func assistantTurnKeepsThinkingAndToolSteps() throws { + let raw = """ + [{"row_id":"a","revision":1,"row":{"kind":"message_turn","phase":"done","turn":{"id":"a","role":"assistant","duration_ms":4200,"blocks":[ + {"type":"thinking","text":"先看看文件"}, + {"type":"tool_use","tool_use_id":"t1","tool_name":"Read","status":"completed","input_preview":"src/main.rs\\nmore"}, + {"type":"tool_use","tool_name":"Edit","status":"in_progress"}, + {"type":"text","text":"改好了"}]}}}, + {"row_id":"b","revision":1,"row":{"kind":"message_turn","phase":"streaming","turn":{"id":"b","role":"assistant","blocks":[{"type":"thinking","text":"想一想"}]}}}] + """ + let rows = try JSONDecoder().decode([JSONValue].self, from: Data(raw.utf8)) + let items = TimelineBuilder.build(fromRows: rows) + #expect(items.count == 2) + #expect(items[0].text == "改好了" && items[0].thinking == "先看看文件") + #expect(items[0].tools.map(\.name) == ["Read", "Edit"]) + #expect(items[0].tools[0].preview == "src/main.rs" && items[0].tools[0].isFinished) + #expect(!items[0].tools[1].isFinished && items[0].durationMs == 4200) + #expect(items[1].text.isEmpty && items[1].hasTrace) +} + +@Test func toolStepsShowTargetNotRawJSON() throws { + let raw = """ + [{"row_id":"a","revision":1,"row":{"kind":"message_turn","phase":"done","turn":{"id":"a","role":"assistant","blocks":[ + {"type":"tool_use","tool_use_id":"w","tool_name":"Write notes.txt","input_preview":"{\\"file_path\\":\\"/tmp/ws/notes.txt\\",\\"content\\":\\"one\\\\ntwo\\"}"}, + {"type":"tool_use","tool_use_id":"b","tool_name":"ls -l notes.txt","input_preview":"{\\"command\\":\\"ls -l notes.txt\\"}"}, + {"type":"text","text":"ok"}]}}}] + """ + let rows = try JSONDecoder().decode([JSONValue].self, from: Data(raw.utf8)) + let tools = TimelineBuilder.build(fromRows: rows)[0].tools + #expect(tools[0].preview == "notes.txt" && tools[0].label == "Write") + #expect(tools[0].detail.first?.hasPrefix("content: one") == true) + #expect(tools[1].preview == "ls -l notes.txt" && tools[1].label == "ls") +} + +@Test func writeAndEditCallsBecomeDiffChipsWithoutGit() throws { + let raw = """ + [{"row_id":"a","revision":1,"row":{"kind":"message_turn","phase":"done","turn":{"id":"a","role":"assistant","blocks":[ + {"type":"tool_use","tool_use_id":"w","tool_name":"Write","input_preview":"{\\"file_path\\":\\"/ws/n.txt\\",\\"content\\":\\"a\\\\nb\\\\nc\\"}"}, + {"type":"tool_use","tool_use_id":"e","tool_name":"Edit","input_preview":"{\\"file_path\\":\\"/ws/n.txt\\",\\"old_string\\":\\"b\\",\\"new_string\\":\\"B\\\\nB2\\"}"}, + {"type":"text","text":"ok"}]}}}] + """ + let rows = try JSONDecoder().decode([JSONValue].self, from: Data(raw.utf8)) + let change = try #require(TimelineBuilder.build(fromRows: rows)[0].changes.first) + #expect(change.path == "/ws/n.txt" && change.additions == 5 && change.deletions == 1) + #expect(change.hunks?.count == 2) +} + +@Test func conversationsGroupByProjectAndKeepStrays() throws { + func item(_ id: String, _ workspace: String, _ updated: String) -> String { + "{\"id\":\"\(id)\",\"workspace_id\":\"\(workspace)\",\"message_count\":0,\"updated_at\":\"\(updated)\"}" + } + let raw = "[" + [ + item("1", "W1", "2026-11-06T10:00:00Z"), + item("2", "W2", "2026-11-06T12:00:00Z"), + item("3", "W1", "2026-11-06T11:00:00Z"), + item("4", "ZZ", "2026-11-06T13:00:00Z"), + ].joined(separator: ",") + "]" + let conversations = try JSONDecoder().decode([ConversationListItem].self, from: Data(raw.utf8)) + let projects = [ + ProjectSummary(id: "p1", name: "webhub", workspaceIds: ["w1"]), + ProjectSummary(id: "p2", name: "测试 hub", workspaceIds: ["W2"]), + ] + let groups = ProjectGroup.make(conversations: conversations, projects: projects) + #expect(groups.map(\.name) == ["测试 hub", "webhub", "其他"]) + #expect(groups[1].conversations.map(\.id) == ["1", "3"]) + #expect(groups[2].conversations.map(\.id) == ["4"]) +} + +@Test func sessionStateFoldsModesOptionsAndPendingPermission() throws { + let raw = """ + [ + {"sequence":1,"kind":"session_mode_updated","payload":{"current":"full","modes":[{"id":"ro","label":"Read-only"},{"id":"full","label":"完全访问"}]}}, + {"sequence":2,"kind":"session_config_options_updated","payload":{"options":[ + {"key":"model","label":"Model","category":"model","value":"a","choices":[{"value":"a","label":"Model A"},{"value":"b","label":"Model B"}]}, + {"key":"effort","label":"Reasoning effort","category":"thought_level","value":"low","choices":[{"value":"low","label":"低"}]}]}}, + {"sequence":3,"kind":"user_turn_started","payload":{}}, + {"sequence":4,"kind":"permission_requested","payload":{"request":{"permission_id":"p1","request":{"id":"p1","title":"Run ls","options":[{"id":"o1","label":"允许一次","kind":"allow_once"},{"id":"o2","label":"拒绝","kind":"reject_once"}]}}}}, + {"sequence":5,"kind":"permission_requested","payload":{"request":{"permission_id":"p2","request":{"id":"p2","title":"Write file","options":[]}}}}, + {"sequence":6,"kind":"permission_responded","payload":{"permission_id":"p2","response":{}}} + ] + """ + let events = try JSONDecoder().decode([RemoteEvent].self, from: Data(raw.utf8)) + let state = SessionStateBuilder.build(from: events) + #expect(state.currentModeLabel == "完全访问") + #expect(state.modelOptions.first?.currentLabel == "Model A") + #expect(state.otherOptions.map(\.key) == ["effort"]) + #expect(state.isTurnRunning) + #expect(state.pendingPermissions.map(\.id) == ["p1"]) + #expect(state.pendingPermissions[0].options.map(\.kind) == ["allow_once", "reject_once"]) +} + +@Test func sessionStateClearsTurnAndPermissionsOnTerminalEvent() throws { + let raw = """ + [ + {"sequence":1,"kind":"user_turn_started","payload":{}}, + {"sequence":2,"kind":"permission_requested","payload":{"request":{"permission_id":"p1","request":{"id":"p1","title":"t","options":[]}}}}, + {"sequence":3,"kind":"turn_cancelled","payload":{}} + ] + """ + let events = try JSONDecoder().decode([RemoteEvent].self, from: Data(raw.utf8)) + let state = SessionStateBuilder.build(from: events) + #expect(!state.isTurnRunning) + #expect(state.pendingPermissions.isEmpty) +} + +private final class RecordingTransport: HttpTransport, @unchecked Sendable { + private let lock = NSLock() + private(set) var lastBody: [String: Any] = [:] + private(set) var lastURL = "" + func execute( + method: String, url: String, headers: [String: String], body: Data? + ) async throws -> HttpExchange { + lock.withLock { + lastURL = url + lastBody = (body.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any]) ?? [:] + } + return HttpExchange(status: 200, body: Data("{\"operation_id\":\"o\",\"data\":null}".utf8)) + } +} + +@Test func writeCommandsUseHostArgumentShapes() async throws { + let transport = RecordingTransport() + let host = HostClient( + origin: try HostOrigin.parse("http://192.168.1.2:17891"), + accessToken: "t", + transport: transport + ) + try await host.sendMessage(conversationID: "c", workspaceID: "w", agentID: "a", text: "hi") + #expect(transport.lastURL.hasSuffix("/api/v1/call/conversation_input_submit")) + let request = (transport.lastBody["args"] as? [String: Any])?["request"] as? [String: Any] + let payload = request?["payload"] as? [String: Any] + #expect(request?["conversationId"] as? String == "c") + #expect(payload?["agentId"] as? String == "a") + #expect(payload?["workspaceId"] as? String == "w") + #expect(payload?["text"] as? String == "hi") + + try await host.respondPermission(conversationID: "c", permissionID: "p", optionID: "o1") + let permission = ((transport.lastBody["args"] as? [String: Any])?["request"] as? [String: Any]) + let response = permission?["response"] as? [String: Any] + #expect(response?["kind"] as? String == "selected") + #expect(response?["option_id"] as? String == "o1") + + try await host.setSessionMode(conversationID: "c", modeID: "ro") + let args = transport.lastBody["args"] as? [String: Any] + #expect(args?["modeId"] as? String == "ro") + + try await host.setSessionConfigOption(conversationID: "c", key: "model", value: .string("b")) + #expect((transport.lastBody["args"] as? [String: Any])?["value"] as? String == "b") +} + +@Test func catalogListsDesktopAgentsWithTheirModels() throws { + let raw = """ + {"projects":[],"workspaces":[],"agents":[ + {"id":"codex","ready":true,"usable":true,"displayName":"Codex","currentMode":"full", + "sessionModes":[{"id":"ro","label":"Read-only","description":"只读"},{"id":"full","label":"完全访问"}], + "sessionConfig":[{"key":"model","label":"Model","category":"model","value":"gpt-6-sol","choices":[{"value":"gpt-6-astra","label":"gpt-6-astra"},{"value":"gpt-6-sol","label":"gpt-6-sol"}]}]}, + {"id":"grok","ready":true,"usable":false,"displayName":"Grok"} + ]} + """ + let catalog = try JSONDecoder().decode(JSONValue.self, from: Data(raw.utf8)) + let agents = AgentCatalogParser.agents(from: catalog) + #expect(agents.map(\.displayName) == ["Codex", "Grok"]) + #expect(agents[0].usable && !agents[1].usable) + #expect(agents[0].modelOptions.first?.currentLabel == "gpt-6-sol") + #expect(agents[0].modes.first?.description == "只读") + #expect(agents[0].currentModeID == "full") +} + +@Test func liveControlsSnapshotYieldsModesAndOptions() throws { + let raw = """ + {"modes":[{"id":"ro","label":"Read-only"}],"current_mode":"ro","config_options":[ + {"key":"effort","label":"Effort","category":"thought_level","value":"low","choices":[{"value":"low","label":"低"},{"value":"high","label":"高"}]}]} + """ + let snapshot = try JSONDecoder().decode(JSONValue.self, from: Data(raw.utf8)) + let state = SessionStateBuilder.controls(from: snapshot) + #expect(state.currentModeID == "ro") + #expect(state.modes.map(\.label) == ["Read-only"]) + #expect(state.otherOptions.map(\.key) == ["effort"]) +} + +@Test func unifiedDiffParsesHunksWithLineNumbers() { + let text = """ + diff --git a/a.rs b/a.rs + index 1..2 100644 + --- a/a.rs + +++ b/a.rs + @@ -10,3 +10,4 @@ fn main() { + keep + -old + +new + +extra + tail + \\ No newline at end of file + @@ -40 +41 @@ + -x + +y + """ + let hunks = UnifiedDiff.parse(text) + #expect(hunks.count == 2) + let first = hunks[0].lines + #expect(first.map(\.kind) == [.context, .removed, .added, .added, .context]) + #expect(first[1].oldNumber == 11 && first[1].newNumber == nil) + #expect(first[2].newNumber == 11 && first[3].newNumber == 12) + #expect(first[4].oldNumber == 12 && first[4].newNumber == 13) + #expect(hunks[1].lines[0].oldNumber == 40 && hunks[1].lines[1].newNumber == 41) +} + +@Test func workspaceDiffCallsHostAndKeepsCounts() async throws { + let reply = """ + {"operation_id":"o","data":[ + {"path":"a.rs","status":"M","diff":"@@ -1 +1,2 @@\\n-a\\n+b\\n+c\\n","is_binary":false,"is_image":false,"truncated":false}, + {"path":"new.txt","status":"?","diff":"","is_binary":false,"is_image":false,"truncated":false}, + {"path":"logo.png","status":"M","diff":"","is_binary":true,"is_image":true,"truncated":false}]} + """ + let diffs = try await client(200, reply).workspaceDiff(workspaceID: "w") + #expect(diffs.map(\.path) == ["a.rs", "new.txt", "logo.png"]) + #expect(diffs[0].additions == 2 && diffs[0].deletions == 1) + #expect(diffs[1].change == .untracked && diffs[1].needsContent) + #expect(!diffs[2].needsContent) + let added = FileDiff.additions(of: "x\ny\n") + #expect(added.first?.lines.map(\.newNumber) == [1, 2]) +} + +@Test func workspaceTreeAndFileDecode() async throws { + let tree = try await client(200, "{\"operation_id\":\"o\",\"data\":{\"path\":\"src\",\"entries\":[{\"name\":\"main.rs\",\"path\":\"src/main.rs\",\"directory\":false}],\"truncated\":false}}") + .workspaceTree(workspaceID: "w", path: "src") + #expect(tree.entries.first?.path == "src/main.rs") + let file = try await client(200, "{\"operation_id\":\"o\",\"data\":{\"path\":\"a\",\"size\":3,\"binary\":false,\"truncated\":false,\"content\":\"abc\"}}") + .workspaceFile(workspaceID: "w", path: "a") + #expect(file.content == "abc") +} + +@Test func workspaceEntriesAndCreatedConversationDecode() async throws { + let created = """ + {"operation_id":"o","data":{"id":"c2","workspace_id":"w","title":null,"agent_id":"codex","message_count":0,"updated_at":"2026-11-06T14:00:00Z"}} + """ + let host = try client(200, created) + let item = try await host.createConversation(workspaceID: "w", agentID: "codex") + #expect(item.id == "c2" && item.agent_id == "codex") +} + +@Test func questionFormsFollowTheDesktopAnswerShapes() throws { + func decode(_ text: String) throws -> JSONValue { try JSONDecoder().decode(JSONValue.self, from: Data(text.utf8)) } + // plain options + let plain = PendingQuestion(id: "q", prompt: "继续吗", options: ["是", "否"], schema: nil) + let plainForm = QuestionForm.questions(for: plain) + #expect(plainForm.count == 1 && plainForm[0].choices.map(\.label) == ["是", "否"]) + let picked = QuestionForm.content(for: plain, questions: plainForm, answers: ["answer": QuestionAnswer(selected: [.string("是")])]) + #expect(picked == .object(["answer": .string("是")])) + #expect(QuestionForm.content(for: plain, questions: plainForm, answers: [:]) == nil) + + // schema properties, including a multi-select and a custom companion + let schema = try decode(""" + {"type":"object","properties":{ + "scope":{"title":"范围","type":"string","enum":["a","b"]}, + "tags":{"title":"标签","type":"array","items":{"enum":["x","y"]}}, + "note":{"type":"string"},"note_custom":{"type":"string"}}} + """) + let withSchema = PendingQuestion(id: "q2", prompt: "", options: [], schema: schema) + let forms = QuestionForm.questions(for: withSchema) + #expect(forms.map(\.id) == ["note", "scope", "tags"]) + #expect(forms.first { $0.id == "tags" }?.multiSelect == true) + let content = QuestionForm.content(for: withSchema, questions: forms, answers: [ + "scope": QuestionAnswer(selected: [.string("b")]), + "tags": QuestionAnswer(selected: [.string("x"), .string("y")], customText: ""), + "note": QuestionAnswer(customText: "补充"), + ]) + #expect(content?["scope"] == .string("b")) + #expect(content?["tags"] == .array([.string("x"), .string("y")])) + #expect(content?["note_custom"] == .string("补充")) + + // x-vibex-questions answer by id with labels + let vibex = try decode(""" + {"x-vibex-questions":[{"id":"n","header":"数量","question":"几个?","options":[{"label":"三个"},{"label":"五个"}],"multiSelect":false}]} + """) + let request = PendingQuestion(id: "q3", prompt: "", options: [], schema: vibex) + let steps = QuestionForm.questions(for: request) + let answer = QuestionForm.content(for: request, questions: steps, answers: ["n": QuestionAnswer(selected: [.string("三个")])]) + #expect(answer?["answers"]?.arrayValue?.first?["labels"] == .array([.string("三个")])) +} + +@Test func sessionStateTracksPendingQuestions() throws { + let raw = """ + [{"sequence":1,"kind":"question_requested","payload":{"request":{"question_id":"q1","prompt":"选哪个","options":["甲","乙"]}}}, + {"sequence":2,"kind":"question_requested","payload":{"request":{"question_id":"q2","prompt":"再选","options":[]}}}, + {"sequence":3,"kind":"question_responded","payload":{"question_id":"q1","response":{}}}] + """ + let events = try JSONDecoder().decode([RemoteEvent].self, from: Data(raw.utf8)) + let state = SessionStateBuilder.build(from: events) + #expect(state.pendingQuestions.map(\.id) == ["q2"]) +} + +@Test func latestPlanBecomesTheCurrentTaskList() throws { + let raw = """ + [{"row_id":"a","revision":1,"row":{"kind":"message_turn","phase":"done","turn":{"id":"a","role":"assistant","blocks":[ + {"type":"plan","entries":[{"content":"读代码","status":"completed"},{"content":"写测试","status":"pending"}]}]}}}, + {"row_id":"b","revision":1,"row":{"kind":"message_turn","phase":"streaming","turn":{"id":"b","role":"assistant","blocks":[ + {"type":"plan","entries":[{"content":"读代码","status":"completed"},{"content":"写测试","status":"in_progress","priority":"high"},{"content":"提交","status":"pending"}]}, + {"type":"text","text":"进行中"}]}}}] + """ + let rows = try JSONDecoder().decode([JSONValue].self, from: Data(raw.utf8)) + let items = TimelineBuilder.build(fromRows: rows) + let plan = items.currentPlan + #expect(plan.map(\.label) == ["读代码", "写测试", "提交"]) + #expect(plan.map(\.status) == [.completed, .running, .pending]) + #expect(plan[1].priority == "high") + #expect(items[0].plan.count == 2) +} + +@Test func changedFilesAttachToTheAssistantTurnBeforeThem() throws { + let raw = """ + [{"row_id":"a","revision":1,"row":{"kind":"message_turn","phase":"done","turn":{"id":"a","role":"assistant","blocks":[ + {"type":"tool_use","tool_name":"Edit","input_preview":"a.rs\\nline2\\nline3\\nline4\\nline5"},{"type":"text","text":"好了"}]}}}, + {"row_id":"f","revision":1,"row":{"kind":"file_change_summary","summary":{"source":"git","files":[ + {"path":"a.rs","change_kind":"modified","additions":3,"deletions":1}]}}}] + """ + let rows = try JSONDecoder().decode([JSONValue].self, from: Data(raw.utf8)) + let item = try #require(TimelineBuilder.build(fromRows: rows).first) + #expect(item.changes.map(\.path) == ["a.rs"] && item.changes[0].additions == 3) + #expect(item.tools[0].detail == ["a.rs", "line2", "line3", "line4"]) +} diff --git a/mobile/ios/Tests/CompanionCoreTests/PairingClientTests.swift b/mobile/ios/Tests/CompanionCoreTests/PairingClientTests.swift new file mode 100644 index 000000000..38432cb5d --- /dev/null +++ b/mobile/ios/Tests/CompanionCoreTests/PairingClientTests.swift @@ -0,0 +1,183 @@ +import Foundation +import Testing +@testable import CompanionCore + +private final class ScriptedTransport: HttpTransport, @unchecked Sendable { + struct Recorded { + let method: String + let url: String + let headers: [String: String] + let body: Data? + } + + private let lock = NSLock() + private var responses: [HttpExchange] + private(set) var requests: [Recorded] = [] + + init(_ responses: [String], statuses: [Int]) { + self.responses = zip(statuses, responses).map { + HttpExchange(status: $0, body: Data($1.utf8)) + } + } + + func execute( + method: String, url: String, headers: [String: String], body: Data? + ) async throws -> HttpExchange { + lock.withLock { + requests.append(Recorded(method: method, url: url, headers: headers, body: body)) + return responses.removeFirst() + } + } +} + +private let credentialJSON = """ +{"device_id":"11111111-1111-1111-1111-111111111111","access_token":"device-token","scopes":["conversation.read","conversation.attach"]} +""" +private let capabilitiesJSON = """ +{"server_version":"0.1.3","protocol_version":"1.0","minimum_client_version":"1.0","capabilities":["conversation.attach"]} +""" + +@Test func redeemStoresCompanionCredentialAndChecksCapabilities() async throws { + let transport = ScriptedTransport([credentialJSON, capabilitiesJSON], statuses: [201, 200]) + let session = try await PairingClient(transport: transport).redeem( + origin: HostOrigin.parse("http://127.0.0.1:17891"), + pairingToken: "one-time-secret", + deviceName: "iPhone" + ) + #expect(session.credential.access_token == "device-token") + #expect(session.capabilities.protocol_version == "1.0") + #expect(transport.requests.count == 2) + #expect(transport.requests[0].method == "POST") + #expect(transport.requests[0].url.hasSuffix("/api/v1/auth/pairings/redeem")) + let sent = try #require(transport.requests[0].body.flatMap { String(data: $0, encoding: .utf8) }) + #expect(sent.contains("\"pairing_token\":\"one-time-secret\"")) + #expect(transport.requests[1].headers["authorization"] == "Bearer device-token") +} + +@Test func redeemRejectsWorkstationScopes() async throws { + let granted = """ + {"device_id":"11111111-1111-1111-1111-111111111111","access_token":"t","scopes":["conversation.read","plugin.write"]} + """ + let transport = ScriptedTransport([granted], statuses: [201]) + await #expect(throws: PairingError.nonCompanionScopes(["plugin.write"])) { + try await PairingClient(transport: transport).redeem( + origin: HostOrigin.parse("https://host.example"), + pairingToken: "token" + ) + } +} + +@Test func redeemRejectsIncompatibleProtocolMajor() async throws { + let newer = """ + {"server_version":"9","protocol_version":"2.0","minimum_client_version":"2.0","capabilities":[]} + """ + let transport = ScriptedTransport([credentialJSON, newer], statuses: [201, 200]) + await #expect(throws: PairingError.incompatibleProtocol(host: "2.0", client: "1.0")) { + try await PairingClient(transport: transport).redeem( + origin: HostOrigin.parse("https://host.example"), + pairingToken: "token" + ) + } +} + +@Test func hostOriginRejectsCredentialsInUrl() { + #expect(throws: PairingError.self) { + try HostOrigin.parse("http://user:secret@127.0.0.1:17891") + } +} + +@Test func hostOriginNormalizesTrailingSlash() throws { + let origin = try HostOrigin.parse(" https://host.example:8443/base/ ") + #expect(origin.value == "https://host.example:8443/base") + #expect(origin.resolve("api/v1/capabilities") == "https://host.example:8443/base/api/v1/capabilities") +} + +private func invitationText( + preset: String = "companion", + expiresAt: String = "2999-01-01T00:00:00Z", + origins: [String] +) -> String { + let reach = origins.map { "{\"origin\":\"\($0)\",\"kind\":\"lan\"}" }.joined(separator: ",") + return "vibex-pairing:{\"version\":1,\"host_id\":\"h\",\"preset\":\"\(preset)\",\"expires_at\":\"\(expiresAt)\",\"pairing_id\":\"p\",\"pairing_token\":\"secret\",\"reachability\":[\(reach)]}" +} + +private final class FlakyTransport: HttpTransport, @unchecked Sendable { + private let lock = NSLock() + private(set) var urls: [String] = [] + func execute( + method: String, url: String, headers: [String: String], body: Data? + ) async throws -> HttpExchange { + let step = lock.withLock { () -> Int in + urls.append(url) + return urls.count + } + if step == 1 { throw URLError(.cannotConnectToHost) } + let text = step == 2 ? credentialJSON : capabilitiesJSON + return HttpExchange(status: 200, body: Data(text.utf8)) + } +} + +@Test func invitationRejectsWorkstationPresetBeforeAnyRequest() async throws { + let transport = ScriptedTransport([], statuses: []) + let invitation = try PairingInvitation.parse( + invitationText(preset: "workstation", origins: ["http://192.168.1.2:17891"]) + ) + await #expect(throws: PairingError.notCompanionInvitation) { + try await PairingClient(transport: transport).redeem(invitation: invitation) + } + #expect(transport.requests.isEmpty) +} + +@Test func invitationRejectsExpired() async throws { + let invitation = try PairingInvitation.parse( + invitationText(expiresAt: "2000-01-01T00:00:00Z", origins: ["http://192.168.1.2:17891"]) + ) + await #expect(throws: PairingError.invitationExpired) { + try await PairingClient(transport: ScriptedTransport([], statuses: [])).redeem( + invitation: invitation + ) + } +} + +@Test func invitationFallsBackToNextOriginAndSkipsLoopback() async throws { + let transport = FlakyTransport() + let invitation = try PairingInvitation.parse( + invitationText(origins: [ + "http://127.0.0.1:17891", "http://192.168.1.2:17891", "http://192.168.1.3:17891", + ]) + ) + let session = try await PairingClient(transport: transport).redeem(invitation: invitation) + #expect(session.origin.value == "http://192.168.1.3:17891") + #expect(transport.urls.first?.hasPrefix("http://192.168.1.2") == true) +} + +@Test func invitationParseRejectsGarbage() { + #expect(throws: PairingError.invalidInvitation) { try PairingInvitation.parse("K7M2NPQX") } + #expect(throws: PairingError.invalidInvitation) { try PairingInvitation.parse("vibex-pairing:{") } +} + +@Test func redeemExplainsWhyTheHostRejectedTheCode() async throws { + func body(_ reason: String) -> String { + "{\"code\":\"conflict\",\"message\":\"x\",\"retryable\":false,\"operation_id\":\"o\",\"details\":{\"reason\":\"\(reason)\"}}" + } + for (reason, status, expected) in [ + ("pairing_redeemed", 409, PairingError.codeAlreadyUsed), + ("pairing_expired", 409, PairingError.codeExpired), + ("invalid_pairing", 401, PairingError.codeInvalid), + ] { + let transport = ScriptedTransport([body(reason)], statuses: [status]) + await #expect(throws: expected) { + try await PairingClient(transport: transport).redeem( + origin: HostOrigin.parse("http://127.0.0.1:17891"), + pairingToken: "YGFQX9R2" + ) + } + } + let unknown = ScriptedTransport(["oops"], statuses: [500]) + await #expect(throws: PairingError.redeemFailed(500)) { + try await PairingClient(transport: unknown).redeem( + origin: HostOrigin.parse("http://127.0.0.1:17891"), + pairingToken: "x" + ) + } +}