From d389ee4d539c23bcd752f973c6b6141836f63d68 Mon Sep 17 00:00:00 2001 From: ltf Date: Sat, 7 Nov 2026 05:01:44 +0800 Subject: [PATCH 1/2] 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" + ) + } +} From 2c47c807f316ff6908db212c3f949b573944bf5e Mon Sep 17 00:00:00 2001 From: ltf Date: Sat, 7 Nov 2026 05:02:40 +0800 Subject: [PATCH 2/2] feat(ios): add the SwiftUI iOS companion app with Live Activity Pairing by scan/paste, conversations grouped by project, conversation detail (incremental transcript, streaming reveal, thinking, tool chips with per-file diffs, task list and prompt bar with model/effort/permission controls, permission and question cards), read-only file browser and git diff, and a Live Activity widget (Dynamic Island / Lock Screen) that follows the Agent's task list or the current step. --- mobile/ios/App/ApprovalCard.swift | 216 +++++++ mobile/ios/App/BranchedMenu.swift | 176 ++++++ mobile/ios/App/ConversationDetailView.swift | 327 +++++++++++ mobile/ios/App/ConversationModel.swift | 247 ++++++++ mobile/ios/App/ConversationTools.swift | 366 ++++++++++++ mobile/ios/App/ConversationsView.swift | 193 +++++++ mobile/ios/App/FilesView.swift | 51 ++ mobile/ios/App/KeychainStore.swift | 49 ++ mobile/ios/App/LoadingState.swift | 96 ++++ mobile/ios/App/PairView.swift | 119 ++++ mobile/ios/App/PromptBar.swift | 544 ++++++++++++++++++ mobile/ios/App/QRScannerView.swift | 88 +++ mobile/ios/App/RemoteList.swift | 32 ++ mobile/ios/App/RequiresServer.swift | 46 ++ mobile/ios/App/RootTabView.swift | 46 ++ mobile/ios/App/ServerDetailView.swift | 35 ++ mobile/ios/App/ServerStore.swift | 74 +++ mobile/ios/App/SettingsView.swift | 36 ++ mobile/ios/App/StreamingText.swift | 97 ++++ mobile/ios/App/TaskActivityController.swift | 126 ++++ mobile/ios/App/TaskRows.swift | 185 ++++++ mobile/ios/App/ThinkingView.swift | 64 +++ mobile/ios/App/ToolChips.swift | 174 ++++++ mobile/ios/App/VibeXCompanionApp.swift | 13 + mobile/ios/Info.plist | 19 + mobile/ios/README.md | 4 + .../ios/Shared/TaskActivityAttributes.swift | 16 + .../ios/TaskWidget/TaskActivityWidget.swift | 142 +++++ mobile/ios/TaskWidgetInfo.plist | 11 + .../VibeXCompanion.xcodeproj/project.pbxproj | 396 +++++++++++++ 30 files changed, 3988 insertions(+) create mode 100644 mobile/ios/App/ApprovalCard.swift create mode 100644 mobile/ios/App/BranchedMenu.swift create mode 100644 mobile/ios/App/ConversationDetailView.swift create mode 100644 mobile/ios/App/ConversationModel.swift create mode 100644 mobile/ios/App/ConversationTools.swift create mode 100644 mobile/ios/App/ConversationsView.swift create mode 100644 mobile/ios/App/FilesView.swift create mode 100644 mobile/ios/App/KeychainStore.swift create mode 100644 mobile/ios/App/LoadingState.swift create mode 100644 mobile/ios/App/PairView.swift create mode 100644 mobile/ios/App/PromptBar.swift create mode 100644 mobile/ios/App/QRScannerView.swift create mode 100644 mobile/ios/App/RemoteList.swift create mode 100644 mobile/ios/App/RequiresServer.swift create mode 100644 mobile/ios/App/RootTabView.swift create mode 100644 mobile/ios/App/ServerDetailView.swift create mode 100644 mobile/ios/App/ServerStore.swift create mode 100644 mobile/ios/App/SettingsView.swift create mode 100644 mobile/ios/App/StreamingText.swift create mode 100644 mobile/ios/App/TaskActivityController.swift create mode 100644 mobile/ios/App/TaskRows.swift create mode 100644 mobile/ios/App/ThinkingView.swift create mode 100644 mobile/ios/App/ToolChips.swift create mode 100644 mobile/ios/App/VibeXCompanionApp.swift create mode 100644 mobile/ios/Info.plist create mode 100644 mobile/ios/Shared/TaskActivityAttributes.swift create mode 100644 mobile/ios/TaskWidget/TaskActivityWidget.swift create mode 100644 mobile/ios/TaskWidgetInfo.plist create mode 100644 mobile/ios/VibeXCompanion.xcodeproj/project.pbxproj diff --git a/mobile/ios/App/ApprovalCard.swift b/mobile/ios/App/ApprovalCard.swift new file mode 100644 index 000000000..a84841d67 --- /dev/null +++ b/mobile/ios/App/ApprovalCard.swift @@ -0,0 +1,216 @@ +import CompanionCore +import SwiftUI + +/// Human-in-the-loop question card: one question at a time, the stack slides between them, single-choice +/// answers advance on their own and multi-select waits for Continue. +struct ApprovalCard: View { + let request: PendingQuestion + let submit: (JSONValue?) async -> Void + + private let questions: [FormQuestion] + @State private var index = 0 + @State private var answers: [String: QuestionAnswer] = [:] + @State private var sent = false + @State private var pendingAdvance: Task? + + init(request: PendingQuestion, submit: @escaping (JSONValue?) async -> Void) { + self.request = request + self.submit = submit + self.questions = QuestionForm.questions(for: request) + } + + private var question: FormQuestion { questions[index] } + private var isLast: Bool { index == questions.count - 1 } + private var answer: QuestionAnswer { answers[question.id] ?? QuestionAnswer() } + + var body: some View { + if sent { + Label("答案已发送", systemImage: "checkmark.circle.fill") + .font(.system(size: 12.5, weight: .medium)) + .foregroundStyle(.green) + .padding(.vertical, 6) + .padding(.horizontal, 10) + .background(Color.green.opacity(0.12), in: Capsule()) + .transition(.scale(scale: 0.95).combined(with: .opacity)) + } else { + card + .transition(.move(edge: .bottom).combined(with: .opacity)) + } + } + + private var card: some View { + VStack(spacing: 0) { + ZStack(alignment: .topLeading) { + questionView + .id(index) + .transition(.asymmetric( + insertion: .move(edge: .bottom).combined(with: .opacity), + removal: .move(edge: .top).combined(with: .opacity) + )) + } + .padding(16) + .frame(maxWidth: .infinity, alignment: .leading) + .clipped() + footer + .padding(.horizontal, 12) + .padding(.vertical, 10) + } + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 16)) + .overlay(RoundedRectangle(cornerRadius: 16).stroke(Color.primary.opacity(0.06))) + .shadow(color: .black.opacity(0.06), radius: 8, y: 2) + .animation(.timingCurve(0.22, 1, 0.36, 1, duration: 0.36), value: index) + .onDisappear { pendingAdvance?.cancel() } + } + + private var questionView: some View { + VStack(alignment: .leading, spacing: 10) { + Text(question.text).font(.system(size: 14, weight: .medium)) + VStack(alignment: .leading, spacing: 2) { + ForEach(question.choices) { choice in optionRow(choice) } + TextField("其他…", text: customText) + .font(.system(size: 13)) + .padding(.vertical, 6) + .padding(.leading, 22) + .submitLabel(.send) + .onSubmit { if !answer.isEmpty { advance() } } + } + } + } + + private func optionRow(_ choice: QuestionChoice) -> some View { + let on = answer.selected.contains(choice.value) + return Button { + toggle(choice) + } label: { + HStack(alignment: .top, spacing: 8) { + indicator(on: on) + VStack(alignment: .leading, spacing: 1) { + Text(choice.label) + .font(.system(size: 13)) + .foregroundStyle(on ? Color.primary : Color.primary.opacity(0.7)) + if let description = choice.description, !description.isEmpty { + Text(description).font(.system(size: 11)).foregroundStyle(.secondary) + } + } + Spacer(minLength: 0) + } + .padding(.vertical, 6) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityAddTraits(on ? .isSelected : []) + } + + private func indicator(on: Bool) -> some View { + ZStack { + if question.multiSelect { + RoundedRectangle(cornerRadius: 5) + .fill(on ? Color.primary : .clear) + .overlay(RoundedRectangle(cornerRadius: 5).stroke(Color.primary.opacity(on ? 0 : 0.3), lineWidth: 1.5)) + if on { Image(systemName: "checkmark").font(.system(size: 9, weight: .heavy)).foregroundStyle(Color(.systemBackground)) } + } else { + Circle() + .fill(on ? Color.primary : .clear) + .overlay(Circle().stroke(Color.primary.opacity(on ? 0 : 0.3), lineWidth: 1.5)) + Circle().fill(Color(.systemBackground)).frame(width: 6, height: 6).scaleEffect(on ? 1 : 0) + } + } + .frame(width: 16, height: 16) + .animation(.easeOut(duration: 0.2), value: on) + } + + private var footer: some View { + HStack(spacing: 10) { + HStack(spacing: 4) { + navButton("chevron.up", enabled: index > 0) { go(index - 1) } + Text("\(index + 1) / \(questions.count)") + .font(.system(size: 12, weight: .medium)) + .monospacedDigit() + .foregroundStyle(.tertiary) + .contentTransition(.numericText()) + navButton("chevron.down", enabled: !isLast) { go(index + 1) } + } + Spacer() + Button("跳过") { advance() } + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(.secondary) + .buttonStyle(.plain) + .padding(.horizontal, 8) + Button(action: advance) { + HStack(spacing: 6) { + Text(isLast ? "发送" : "继续") + Image(systemName: "return").font(.system(size: 10, weight: .semibold)) + } + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(Color(.systemBackground)) + .padding(.horizontal, 14) + .padding(.vertical, 6) + .background(Color.primary.opacity(answer.isEmpty ? 0.25 : 1), in: Capsule()) + } + .buttonStyle(.plain) + .disabled(answer.isEmpty) + } + } + + private func navButton(_ symbol: String, enabled: Bool, action: @escaping () -> Void) -> some View { + Button(action: action) { + Image(systemName: symbol) + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(.secondary) + .frame(width: 22, height: 22) + } + .buttonStyle(.plain) + .disabled(!enabled) + .opacity(enabled ? 1 : 0.3) + } + + private var customText: Binding { + Binding( + get: { answer.customText }, + set: { text in + var next = answer + next.customText = text + if !question.multiSelect, !text.isEmpty { next.selected = [] } + answers[question.id] = next + } + ) + } + + private func toggle(_ choice: QuestionChoice) { + var next = answer + if question.multiSelect { + if let at = next.selected.firstIndex(of: choice.value) { + next.selected.remove(at: at) + } else { + next.selected.append(choice.value) + } + } else { + next.selected = [choice.value] + next.customText = "" + } + answers[question.id] = next + pendingAdvance?.cancel() + guard !question.multiSelect else { return } + pendingAdvance = Task { + try? await Task.sleep(for: .milliseconds(480)) + guard !Task.isCancelled else { return } + await MainActor.run { advance() } + } + } + + private func go(_ target: Int) { + pendingAdvance?.cancel() + index = min(max(target, 0), questions.count - 1) + } + + private func advance() { + pendingAdvance?.cancel() + if isLast { + withAnimation { sent = true } + let content = QuestionForm.content(for: request, questions: questions, answers: answers) + Task { await submit(content) } + } else { + index += 1 + } + } +} diff --git a/mobile/ios/App/BranchedMenu.swift b/mobile/ios/App/BranchedMenu.swift new file mode 100644 index 000000000..0fb1ffe56 --- /dev/null +++ b/mobile/ios/App/BranchedMenu.swift @@ -0,0 +1,176 @@ +import SwiftUI + +struct BranchedItem: Identifiable, Equatable { + let id: String + let label: String + var icon: String? +} + +struct BranchedSection: Identifiable, Equatable { + let id: String + let label: String + let children: [BranchedItem] +} + +/// SwiftUI port of the web BranchedMenu: sections fold open, each child hangs off a drawn branch. +struct BranchedMenu: View { + let sections: [BranchedSection] + @Binding var active: String + var onSelect: ((String) -> Void)? + @State private var open: Set + @Namespace private var marker + + private let pad: CGFloat = 6 + private let rowHeight: CGFloat = 36 + private let indent: CGFloat = 40 + private let trunk: CGFloat = 14 + private let radius: CGFloat = 10 + private let lineWidth: CGFloat = 1.5 + + init( + sections: [BranchedSection], + active: Binding, + initiallyOpen: Set? = nil, + onSelect: ((String) -> Void)? = nil + ) { + self.sections = sections + _active = active + self.onSelect = onSelect + _open = State(initialValue: initiallyOpen ?? Set(sections.map(\.id))) + } + + private var line: Color { Color.primary.opacity(0.2) } + private var muted: Color { Color.primary.opacity(0.55) } + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + ForEach(sections) { section in + sectionView(section) + } + } + .padding(.leading, 14) + .background(alignment: .topLeading) { + Rectangle() + .fill(LinearGradient( + stops: [.init(color: line, location: 0), .init(color: line, location: 0.55), .init(color: .clear, location: 1)], + startPoint: .top, + endPoint: .bottom + )) + .frame(width: 2) + .padding(.top, 8) + } + } + + private func sectionView(_ section: BranchedSection) -> some View { + let isOpen = open.contains(section.id) + let holdsActive = section.children.contains { $0.id == active } + return VStack(alignment: .leading, spacing: 0) { + Button { + withAnimation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.3)) { + if isOpen { open.remove(section.id) } else { open.insert(section.id) } + } + } label: { + Text(section.label) + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(isOpen ? Color.primary : muted) + .padding(.vertical, 9) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .background(alignment: .leading) { + if holdsActive && isOpen { + Rectangle() + .fill(Color.primary) + .frame(width: 2, height: 16) + .offset(x: -14) + .matchedGeometryEffect(id: "marker", in: marker) + } + } + if isOpen { + tree(section) + .clipped() + .transition(.opacity.combined(with: .move(edge: .top))) + } + } + } + + private func rowY(_ k: Int) -> CGFloat { pad + CGFloat(k) * rowHeight + rowHeight / 2 } + + private func tree(_ section: BranchedSection) -> some View { + let kids = section.children + let height = pad * 2 + CGFloat(kids.count) * rowHeight + let endX = indent - 8 + let r = min(radius, rowHeight / 2 - 2) + return ZStack(alignment: .topLeading) { + Path { p in + p.move(to: CGPoint(x: trunk, y: 0)) + p.addLine(to: CGPoint(x: trunk, y: rowY(kids.count - 1) - r)) + } + .stroke(line, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round, lineJoin: .round)) + ForEach(Array(kids.enumerated()), id: \.element.id) { k, kid in + branch(k: k, endX: endX, r: r, from: rowY(k) - r) + .stroke(line, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round, lineJoin: .round)) + branch(k: k, endX: endX, r: r, from: 0) + .trim(from: 0, to: kid.id == active ? 1 : 0) + .stroke(Color.primary, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round, lineJoin: .round)) + .animation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.4), value: active) + } + VStack(spacing: 0) { + ForEach(kids) { kid in + Button { + active = kid.id + onSelect?(kid.id) + } label: { + HStack(spacing: 8) { + if let icon = kid.icon { + Image(systemName: icon).font(.system(size: 14)) + } + Text(kid.label).lineLimit(1) + } + .font(.system(size: 14, weight: kid.id == active ? .medium : .regular)) + .foregroundStyle(kid.id == active ? Color.primary : muted) + .padding(.leading, indent) + .frame(maxWidth: .infinity, minHeight: rowHeight, maxHeight: rowHeight, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + } + .padding(.vertical, pad) + } + .frame(height: height) + } + + private func branch(k: Int, endX: CGFloat, r: CGFloat, from startY: CGFloat) -> Path { + let y = rowY(k) + return Path { p in + p.move(to: CGPoint(x: trunk, y: startY)) + p.addLine(to: CGPoint(x: trunk, y: y - r)) + p.addQuadCurve(to: CGPoint(x: trunk + r, y: y), control: CGPoint(x: trunk, y: y)) + p.addLine(to: CGPoint(x: endX, y: y)) + } + } +} + +#Preview { + struct Demo: View { + @State private var active = "src" + var body: some View { + BranchedMenu( + sections: [ + BranchedSection(id: "dirs", label: "目录", children: [ + BranchedItem(id: "src", label: "src", icon: "folder"), + BranchedItem(id: "docs", label: "docs", icon: "folder"), + ]), + BranchedSection(id: "files", label: "文件", children: [ + BranchedItem(id: "readme", label: "README.md", icon: "doc.text"), + ]), + ], + active: $active + ) + .padding() + } + } + return Demo() +} diff --git a/mobile/ios/App/ConversationDetailView.swift b/mobile/ios/App/ConversationDetailView.swift new file mode 100644 index 000000000..982606ba3 --- /dev/null +++ b/mobile/ios/App/ConversationDetailView.swift @@ -0,0 +1,327 @@ +import CompanionCore +import SwiftUI + +struct ConversationDetailView: View { + @State private var model: ConversationModel + @State private var draft = "" + @State private var menu: ComposerMenu? + @State private var panel: DetailPanel? + @State private var created: ConversationListItem? + @State private var diffChange: FileChangeItem? + + init(client: HostClient, conversation: ConversationListItem) { + _model = State(initialValue: ConversationModel(client: client, conversation: conversation)) + } + + var body: some View { + VStack(spacing: 0) { + messages + .overlay { + if menu != nil { + Color.clear.contentShape(Rectangle()).onTapGesture { menu = nil } + } + } + if !model.items.currentPlan.isEmpty { + TaskDock(tasks: model.items.currentPlan, running: model.session.isTurnRunning) + .padding(.horizontal, 12) + .padding(.bottom, 8) + } + if let question = model.session.pendingQuestions.first { + ApprovalCard(request: question) { content in + await model.respond(to: question, content: content) + } + .id(question.id) + .padding(.horizontal, 12) + .padding(.bottom, 8) + } + if let prompt = model.session.pendingPermissions.first { + PermissionBanner(prompt: prompt) { option in + Task { await model.respond(to: prompt, option: option) } + } + } + if let message = model.actionError { + Text(message) + .font(.footnote) + .foregroundStyle(.red) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 16) + .padding(.top, 6) + } + promptBar.padding(.top, 8) + } + .navigationTitle(model.conversation.title ?? "未命名对话") + .navigationBarTitleDisplayMode(.inline) + .toolbar(.hidden, for: .tabBar) + .toolbar { + ToolbarItem(placement: .primaryAction) { + Menu { + Menu("新对话", systemImage: "square.and.pencil") { + ForEach(model.newConversationAgents) { agent in + Button(agent.displayName) { + Task { created = await model.createConversation(agentID: agent.id) } + } + } + } + Button("浏览文件", systemImage: "folder") { panel = .files } + Button("代码差异", systemImage: "plus.forwardslash.minus") { panel = .changes } + } label: { + Image(systemName: "ellipsis") + } + .accessibilityLabel("更多") + } + } + .sheet(item: $panel) { panel in + switch panel { + case .files: + FileBrowserView(client: model.client, workspaceID: model.conversation.workspace_id) + case .changes: + DiffListView(client: model.client, workspaceID: model.conversation.workspace_id) + } + } + .sheet(item: $diffChange) { change in + if let hunks = change.hunks { + NavigationStack { + DiffFileView( + client: model.client, + workspaceID: model.conversation.workspace_id, + diff: FileDiff(path: change.path, hunks: hunks) + ) + } + } else { + FileDiffSheet(client: model.client, workspaceID: model.conversation.workspace_id, path: change.path) + } + } + .onDisappear { model.stopActivity() } + .navigationDestination(item: $created) { ConversationDetailView(client: model.client, conversation: $0) } + .background { Color(.systemGroupedBackground).ignoresSafeArea() } + .task { + while !Task.isCancelled { + await model.reload() + try? await Task.sleep(for: .seconds(model.session.isTurnRunning ? 0.6 : 4)) + } + } + .onChange(of: menu) { _, kind in + if kind == .model { Task { await model.refreshCatalog() } } + } + } + + // MARK: Prompt bar + + private var promptBar: some View { + PromptBar( + draft: $draft, + menu: $menu, + isRunning: model.session.isTurnRunning, + busy: model.busy, + hasAlert: !model.session.pendingPermissions.isEmpty, + modelName: model.currentModelLabel, + modelChoices: modelChoices, + otherModelGroups: otherModelGroups, + otherAgentNote: otherModelGroups.isEmpty + ? nil + : "此对话使用 \(model.currentAgent?.displayName ?? "当前 Agent"),换 Agent 请新建对话", + accessChoices: model.accessModes.map { + PromptChoice( + id: $0.id, + title: $0.label, + detail: $0.description, + icon: "shield", + selected: $0.id == model.currentAccessModeID + ) + }, + extraChoices: model.extraOptions.map { + PromptChoice(id: "option:" + $0.key, title: $0.label, tag: $0.currentLabel, icon: "slider.horizontal.3") + }, + effort: effort, + send: { + let text = draft + Task { if await model.send(text) { draft = "" } } + }, + stop: { Task { await model.cancelTurn() } }, + pickModel: { id in + guard let (option, choice) = findModelChoice(id) else { return } + menu = nil + Task { await model.set(option, to: choice) } + }, + pickAccess: { id in + guard let mode = model.accessModes.first(where: { $0.id == id }) else { return } + menu = nil + Task { await model.setMode(mode) } + }, + pickExtra: { id in + guard let option = model.extraOptions.first(where: { "option:" + $0.key == id }), + let next = nextChoice(of: option) + else { return } + Task { await model.set(option, to: next) } + }, + setEffort: { index in + guard let option = model.effortOption, option.choices.indices.contains(index), + index != effort?.index + else { return } + Task { await model.set(option, to: option.choices[index]) } + } + ) + } + + private var modelChoices: [PromptChoice] { + model.modelOptions.flatMap { option in + option.choices.map { + PromptChoice( + id: option.key + "|" + $0.id, + title: $0.label, + tag: $0.description, + selected: $0.value == model.value(of: option) + ) + } + } + } + + private var otherModelGroups: [PromptGroup] { + model.otherAgentsWithModels.map { agent in + PromptGroup( + title: agent.displayName, + choices: agent.modelOptions.flatMap(\.choices).map { + PromptChoice(id: agent.id + "|" + $0.id, title: $0.label, enabled: false) + } + ) + } + } + + private func findModelChoice(_ id: String) -> (ConfigOption, ConfigChoice)? { + for option in model.modelOptions { + if let choice = option.choices.first(where: { option.key + "|" + $0.id == id }) { + return (option, choice) + } + } + return nil + } + + private var effort: PromptEffort? { + guard let option = model.effortOption, option.choices.count > 1 else { return nil } + let value = model.value(of: option) + let index = option.choices.firstIndex { $0.value == value } ?? 0 + return PromptEffort(levels: option.choices.map(\.label), index: index) + } + + private func nextChoice(of option: ConfigOption) -> ConfigChoice? { + guard !option.choices.isEmpty else { return nil } + let value = model.value(of: option) + let current = option.choices.firstIndex { $0.value == value } ?? -1 + return option.choices[(current + 1) % option.choices.count] + } + + // MARK: Messages + + @ViewBuilder + private var messages: some View { + if model.hasLoaded { + if model.items.isEmpty { + ContentUnavailableView("还没有消息", systemImage: "text.bubble") + } else { + ScrollViewReader { proxy in + ScrollView { + LazyVStack(alignment: .leading, spacing: 18) { + ForEach(model.items) { item in + MessageRow( + item: item, + isLast: item.id == model.items.last?.id, + running: model.session.isTurnRunning, + openDiff: { diffChange = $0 } + ) + .id(item.id) + } + if model.session.isTurnRunning && model.items.last?.role != .assistant { + LoadingState(label: "正在思考").id("loading") + } + } + .padding() + } + .scrollDismissesKeyboard(.interactively) + .onChange(of: model.items.last) { _, last in + if let last { withAnimation { proxy.scrollTo(last.id, anchor: .bottom) } } + } + } + } + } else if let message = model.loadError { + LoadFailureView(message: message) { Task { await model.reload() } } + } else { + ProgressView().frame(maxHeight: .infinity) + } + } +} + +extension String: @retroactive Identifiable { + public var id: String { self } +} + +enum DetailPanel: String, Identifiable { + case files, changes + var id: String { rawValue } +} + +private struct MessageRow: View { + let item: TimelineItem + let isLast: Bool + let running: Bool + let openDiff: (FileChangeItem) -> Void + + var body: some View { + switch item.role { + case .user: + HStack { + Spacer(minLength: 40) + Text(item.text) + .textSelection(.enabled) + .padding(12) + .background(Color.accentColor.opacity(0.15), in: RoundedRectangle(cornerRadius: 14)) + } + case .assistant: + let streaming = running && isLast + VStack(alignment: .leading, spacing: 10) { + if !item.thinking.isEmpty { + ThinkingView(item: item, working: streaming && item.text.isEmpty) + } + if !item.tools.isEmpty || !item.changes.isEmpty { + ToolChipsView(item: item, working: streaming, openDiff: openDiff) + } + if !item.text.isEmpty { + StreamingMessageText(text: item.text, streaming: streaming) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } +} + +private struct PermissionBanner: View { + let prompt: PermissionPrompt + let respond: (PermissionOption?) -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + Label(prompt.title, systemImage: "exclamationmark.shield") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.orange) + ForEach(prompt.options) { option in + let allow = option.kind.hasPrefix("allow") + Button { respond(option) } label: { + Text(option.label) + .font(.subheadline) + .multilineTextAlignment(.leading) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 14) + .padding(.vertical, 10) + .background( + (allow ? Color.accentColor : Color.secondary).opacity(0.14), + in: RoundedRectangle(cornerRadius: 12, style: .continuous) + ) + } + .buttonStyle(.plain) + .foregroundStyle(allow ? Color.accentColor : Color.secondary) + } + } + .padding() + .frame(maxWidth: .infinity, alignment: .leading) + .background(Color.orange.opacity(0.1)) + } +} diff --git a/mobile/ios/App/ConversationModel.swift b/mobile/ios/App/ConversationModel.swift new file mode 100644 index 000000000..85631d4d0 --- /dev/null +++ b/mobile/ios/App/ConversationModel.swift @@ -0,0 +1,247 @@ +import CompanionCore +import Foundation +import Observation + +@MainActor +@Observable +final class ConversationModel { + let client: HostClient + let conversation: ConversationListItem + + private(set) var items: [TimelineItem] = [] + private var transcript: TranscriptState + private let activity = TaskActivityController() + private var events: [RemoteEvent] = [] + private var lastSequence: Int64 = 0 + private(set) var session = SessionState() + private(set) var agents: [CatalogAgent] = [] + /// Choices shown immediately while the Host confirms them; dropped once the Host answers. + private(set) var optionOverrides: [String: JSONValue] = [:] + private(set) var modeOverride: String? + private var liveControls: SessionState? + private var controlsRequested = false + private(set) var hasLoaded = false + private(set) var loadError: String? + private(set) var busy = false + var actionError: String? + + init(client: HostClient, conversation: ConversationListItem) { + self.client = client + self.conversation = conversation + self.transcript = TranscriptState(conversationID: conversation.id) + } + + func reload() async { + do { + var state = transcript + try await client.refresh(&state) + transcript = state + items = state.items + hasLoaded = true + loadError = nil + } catch is CancellationError { + return + } catch { + loadError = describeHostFailure(error) + return + } + // Mode, model, permission and question state come from the control-plane events; a failure keeps the last state. + if let cache = try? await client.offlineConversation(id: conversation.id, afterSequence: lastSequence) { + let fresh = cache.events ?? [] + events += fresh + lastSequence = max(lastSequence, cache.confirmed_through) + session = SessionStateBuilder.build(from: events) + } + await applyLiveControls() + if agents.isEmpty { await refreshCatalog() } + let step = items.last?.tools.last.map { tool in + tool.preview.map { "\(tool.name) \($0)" } ?? tool.name + } + activity.sync(title: conversation.title ?? "对话", tasks: items.currentPlan, step: step, running: session.isTurnRunning) + } + + func stopActivity() { activity.stop() } + + /// Brings the Agent session up (once per visit) so its modes and options exist even before the first message. + private func applyLiveControls() async { + if !controlsRequested { + controlsRequested = true + await ensureLiveControls() + } + guard let live = liveControls else { return } + if session.modes.isEmpty { + session.modes = live.modes + session.currentModeID = session.currentModeID ?? live.currentModeID + } + if session.options.isEmpty { session.options = live.options } + } + + private func ensureLiveControls() async { + do { + liveControls = try await client.ensureSessionControls(conversationID: conversation.id) + } catch is CancellationError { + return + } catch { + // Only worth a message when the user acts; reading stays on the saved controls. + } + } + + /// Runs a session-control change, starting the Agent session first if the Host says it is not running. + private func changingSession(_ action: () async throws -> Void) async throws { + do { + try await action() + } catch HostError.server(_, let message) where message.localizedCaseInsensitiveContains("was not found") { + liveControls = try await client.ensureSessionControls(conversationID: conversation.id) + try await action() + } + } + + /// Agents and their models are whatever the desktop has configured in its Agent settings. + func refreshCatalog() async { + if let latest = try? await client.agentCatalog() { agents = latest } + } + + var currentAgent: CatalogAgent? { agents.first { $0.id == conversation.agent_id } } + + /// Live session controls win; before the Agent has reported any, fall back to the desktop's saved ones. + var modelOptions: [ConfigOption] { + session.modelOptions.isEmpty ? (currentAgent?.modelOptions ?? []) : session.modelOptions + } + + var otherOptions: [ConfigOption] { + session.otherOptions.isEmpty ? (currentAgent?.otherOptions ?? []) : session.otherOptions + } + + var accessModes: [SessionMode] { + session.modes.isEmpty ? (currentAgent?.modes ?? []) : session.modes + } + + var currentAccessModeID: String? { + modeOverride ?? session.currentModeID ?? currentAgent?.currentModeID + } + + func value(of option: ConfigOption) -> JSONValue? { optionOverrides[option.key] ?? option.value } + + /// Reasoning effort is shown as a slider; any remaining options (fast mode, ...) go in the + menu. + var effortOption: ConfigOption? { + otherOptions.first { + $0.category == "thought_level" || $0.key.localizedCaseInsensitiveContains("effort") + || $0.key.localizedCaseInsensitiveContains("reasoning") + } + } + + var extraOptions: [ConfigOption] { otherOptions.filter { $0.key != effortOption?.key } } + + var currentModelLabel: String? { + guard let option = modelOptions.first else { return conversation.model } + let value = value(of: option) + return option.choices.first { $0.value == value }?.label ?? option.currentLabel ?? conversation.model + } + + /// Other usable Agents with models: shown for reference, a conversation keeps its Agent. + var otherAgentsWithModels: [CatalogAgent] { + agents.filter { $0.usable && $0.id != conversation.agent_id && !$0.modelOptions.isEmpty } + } + + func send(_ text: String) async -> Bool { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return false } + guard let agentID = conversation.agent_id else { + actionError = "此对话没有绑定 Agent,无法发送" + return false + } + return await perform { + try await client.sendMessage( + conversationID: conversation.id, + workspaceID: conversation.workspace_id, + agentID: agentID, + text: trimmed + ) + } + } + + /// Agents that can start a new conversation in this workspace. + var newConversationAgents: [CatalogAgent] { agents.filter(\.usable) } + + /// A new empty conversation in the same workspace; defaults to the current Agent. + func createConversation(agentID: String? = nil) async -> ConversationListItem? { + guard let agentID = agentID ?? conversation.agent_id else { + actionError = "此对话没有绑定 Agent,无法新建" + return nil + } + do { + let created = try await client.createConversation( + workspaceID: conversation.workspace_id, + agentID: agentID + ) + actionError = nil + return created + } catch { + actionError = describeHostFailure(error) + return nil + } + } + + func cancelTurn() async { + _ = await perform { try await client.cancelTurn(conversationID: conversation.id) } + } + + func respond(to prompt: PermissionPrompt, option: PermissionOption?) async { + _ = await perform { + try await client.respondPermission( + conversationID: conversation.id, + permissionID: prompt.id, + optionID: option?.id + ) + } + } + + /// `content` nil declines the question. + func respond(to question: PendingQuestion, content: JSONValue?) async { + _ = await perform { + try await client.respondQuestion( + conversationID: conversation.id, + questionID: question.id, + content: content + ) + } + } + + func setMode(_ mode: SessionMode) async { + modeOverride = mode.id + let applied = await perform { + try await changingSession { + try await client.setSessionMode(conversationID: conversation.id, modeID: mode.id) + } + } + if !applied || modeOverride == mode.id { modeOverride = nil } + } + + func set(_ option: ConfigOption, to choice: ConfigChoice) async { + optionOverrides[option.key] = choice.value + _ = await perform { + try await changingSession { + try await client.setSessionConfigOption( + conversationID: conversation.id, + key: option.key, + value: choice.value + ) + } + } + optionOverrides[option.key] = nil + } + + private func perform(_ action: () async throws -> Void) async -> Bool { + busy = true + defer { busy = false } + do { + try await action() + actionError = nil + await reload() + return true + } catch { + actionError = error.localizedDescription + return false + } + } +} diff --git a/mobile/ios/App/ConversationTools.swift b/mobile/ios/App/ConversationTools.swift new file mode 100644 index 000000000..108f5e217 --- /dev/null +++ b/mobile/ios/App/ConversationTools.swift @@ -0,0 +1,366 @@ +import CompanionCore +import SwiftUI + +// MARK: - 浏览文件 + +private enum BrowseTarget: Hashable { + case directory(String) + case file(String) +} + +/// "浏览文件": the workspace one directory at a time, each laid out as a branched menu. +struct FileBrowserView: View { + let client: HostClient + let workspaceID: String + @State private var stack: [BrowseTarget] = [] + + var body: some View { + NavigationStack(path: $stack) { + DirectoryView(client: client, workspaceID: workspaceID, path: "", navigate: { stack.append($0) }) + .navigationDestination(for: BrowseTarget.self) { target in + switch target { + case .directory(let path): + DirectoryView(client: client, workspaceID: workspaceID, path: path, navigate: { stack.append($0) }) + case .file(let path): + FileContentView(client: client, workspaceID: workspaceID, path: path) + } + } + } + } +} + +private struct DirectoryView: View { + let client: HostClient + let workspaceID: String + let path: String + let navigate: (BrowseTarget) -> Void + @State private var list = RemoteList() + @State private var truncated = false + @State private var active = "" + + var body: some View { + content + .navigationTitle(path.isEmpty ? "浏览文件" : (path as NSString).lastPathComponent) + .navigationBarTitleDisplayMode(.inline) + .task { await load() } + } + + @ViewBuilder + private var content: some View { + if let entries = list.items { + if entries.isEmpty { + ContentUnavailableView("这个目录是空的", systemImage: "folder") + } else { + ScrollView { + BranchedMenu(sections: sections(entries), active: $active, onSelect: open) + .padding(.horizontal, 20) + .padding(.vertical, 12) + .frame(maxWidth: .infinity, alignment: .leading) + if truncated { + Text("只显示前 500 项") + .font(.footnote) + .foregroundStyle(.secondary) + .padding(.horizontal, 20) + } + } + } + } else if let message = list.errorMessage { + LoadFailureView(message: message) { Task { await load() } } + } else { + ProgressView() + } + } + + private func load() async { + await list.load { + let tree = try await client.workspaceTree(workspaceID: workspaceID, path: path) + truncated = tree.truncated + return tree.entries + } + } + + private func sections(_ entries: [WorkspaceEntry]) -> [BranchedSection] { + let dirs = entries.filter(\.directory).map { BranchedItem(id: "d:" + $0.path, label: $0.name, icon: "folder") } + let files = entries.filter { !$0.directory }.map { BranchedItem(id: "f:" + $0.path, label: $0.name, icon: "doc.text") } + return [ + BranchedSection(id: "dirs", label: "目录 \(dirs.count)", children: dirs), + BranchedSection(id: "files", label: "文件 \(files.count)", children: files), + ].filter { !$0.children.isEmpty } + } + + private func open(_ id: String) { + let target = String(id.dropFirst(2)) + // Let the branch finish drawing before the page slides in. + Task { + try? await Task.sleep(for: .milliseconds(220)) + navigate(id.hasPrefix("d:") ? .directory(target) : .file(target)) + } + } +} + +private struct FileContentView: View { + let client: HostClient + let workspaceID: String + let path: String + @State private var file: WorkspaceFile? + @State private var errorMessage: String? + + var body: some View { + Group { + if let file { + if file.binary { + ContentUnavailableView("二进制文件无法预览", systemImage: "doc.zipper") + } else { + CodeView(lines: (file.content ?? "").split(separator: "\n", omittingEmptySubsequences: false).map(String.init), + note: file.truncated ? "只显示前 256 KB" : nil) + } + } else if let errorMessage { + LoadFailureView(message: errorMessage) { Task { await load() } } + } else { + ProgressView() + } + } + .navigationTitle((path as NSString).lastPathComponent) + .navigationBarTitleDisplayMode(.inline) + .task { await load() } + } + + private func load() async { + do { + file = try await client.workspaceFile(workspaceID: workspaceID, path: path) + errorMessage = nil + } catch { + errorMessage = describeHostFailure(error) + } + } +} + +private struct CodeView: View { + let lines: [String] + let note: String? + + var body: some View { + ScrollView([.vertical, .horizontal]) { + LazyVStack(alignment: .leading, spacing: 0) { + ForEach(Array(lines.enumerated()), id: \.offset) { index, text in + HStack(alignment: .top, spacing: 12) { + Text("\(index + 1)") + .foregroundStyle(.tertiary) + .frame(minWidth: 36, alignment: .trailing) + Text(text.isEmpty ? " " : text) + } + .font(.system(size: 12, design: .monospaced)) + .textSelection(.enabled) + } + if let note { + Text(note).font(.footnote).foregroundStyle(.secondary).padding(.top, 12) + } + } + .padding(12) + } + } +} + +// MARK: - 代码差异 + +/// "代码差异": working tree against HEAD, file by file, line by line. +struct DiffListView: View { + let client: HostClient + let workspaceID: String + @State private var list = RemoteList() + + var body: some View { + NavigationStack { + content + .navigationTitle("代码差异") + .navigationBarTitleDisplayMode(.inline) + .navigationDestination(for: FileDiff.self) { + DiffFileView(client: client, workspaceID: workspaceID, diff: $0) + } + } + .task { await list.load { try await client.workspaceDiff(workspaceID: workspaceID) } } + } + + @ViewBuilder + private var content: some View { + if let diffs = list.items { + if diffs.isEmpty { + ContentUnavailableView("没有未提交的改动", systemImage: "checkmark.circle") + } else { + List(diffs) { diff in + NavigationLink(value: diff) { + VStack(alignment: .leading, spacing: 4) { + Text((diff.path as NSString).lastPathComponent).lineLimit(1) + HStack(spacing: 8) { + Text(label(for: diff.change)).foregroundStyle(.secondary) + if !diff.isBinary && diff.change != .untracked { + Text("+\(diff.additions)").foregroundStyle(.green) + Text("−\(diff.deletions)").foregroundStyle(.red) + } + Text(diff.path).foregroundStyle(.tertiary).lineLimit(1).truncationMode(.head) + } + .font(.footnote) + } + } + } + .refreshable { await list.load { try await client.workspaceDiff(workspaceID: workspaceID) } } + } + } else if let message = list.errorMessage { + LoadFailureView(message: message) { + Task { await list.load { try await client.workspaceDiff(workspaceID: workspaceID) } } + } + } else { + ProgressView() + } + } + + private func label(for change: FileDiff.Change) -> String { + switch change { + case .added, .untracked: "新增" + case .deleted: "删除" + case .renamed: "重命名" + case .modified: "修改" + } + } +} + +extension FileDiff: Hashable { + public func hash(into hasher: inout Hasher) { hasher.combine(path) } +} + +struct DiffFileView: View { + let client: HostClient + let workspaceID: String + let diff: FileDiff + @State private var hunks: [DiffHunk] + @State private var loadingContent = false + + init(client: HostClient, workspaceID: String, diff: FileDiff) { + self.client = client + self.workspaceID = workspaceID + self.diff = diff + _hunks = State(initialValue: diff.hunks) + } + + var body: some View { + Group { + if diff.isBinary { + ContentUnavailableView("二进制文件没有文本差异", systemImage: "doc.zipper") + } else if hunks.isEmpty && !loadingContent { + ContentUnavailableView("没有可显示的文本差异", systemImage: "plus.forwardslash.minus") + } else { + ScrollView([.vertical, .horizontal]) { + LazyVStack(alignment: .leading, spacing: 0) { + ForEach(hunks) { hunk in + Text(hunk.header) + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(.secondary) + .padding(.vertical, 6) + .padding(.horizontal, 12) + ForEach(hunk.lines) { DiffRow(line: $0) } + } + if diff.truncated { + Text("差异过长,只显示前一部分") + .font(.footnote) + .foregroundStyle(.secondary) + .padding(12) + } + } + .frame(minWidth: UIScreen.main.bounds.width, alignment: .leading) + } + } + } + .navigationTitle((diff.path as NSString).lastPathComponent) + .navigationBarTitleDisplayMode(.inline) + .task { + guard diff.needsContent, hunks.isEmpty else { return } + loadingContent = true + defer { loadingContent = false } + if let file = try? await client.workspaceFile(workspaceID: workspaceID, path: diff.path), + let content = file.content + { + hunks = FileDiff.additions(of: content) + } + } + } +} + +private struct DiffRow: View { + let line: DiffLine + + var body: some View { + HStack(alignment: .top, spacing: 8) { + number(line.oldNumber) + number(line.newNumber) + Text(marker).foregroundStyle(tint) + Text(line.text.isEmpty ? " " : line.text) + } + .font(.system(size: 12, design: .monospaced)) + .padding(.horizontal, 12) + .frame(maxWidth: .infinity, alignment: .leading) + .background(tint.opacity(line.kind == .context ? 0 : 0.12)) + .textSelection(.enabled) + } + + private func number(_ value: Int?) -> some View { + Text(value.map(String.init) ?? "") + .foregroundStyle(.tertiary) + .frame(minWidth: 30, alignment: .trailing) + } + + private var marker: String { + switch line.kind { + case .added: "+" + case .removed: "−" + case .context: " " + } + } + + private var tint: Color { + switch line.kind { + case .added: .green + case .removed: .red + case .context: .secondary + } + } +} + +/// One file's diff, opened from a changed-file chip. +struct FileDiffSheet: View { + let client: HostClient + let workspaceID: String + let path: String + @State private var diff: FileDiff? + @State private var missing = false + @State private var errorMessage: String? + + var body: some View { + NavigationStack { + Group { + if let diff { + DiffFileView(client: client, workspaceID: workspaceID, diff: diff) + } else if missing { + ContentUnavailableView("这个文件已经没有未提交的改动", systemImage: "checkmark.circle") + .navigationTitle((path as NSString).lastPathComponent) + .navigationBarTitleDisplayMode(.inline) + } else if let errorMessage { + LoadFailureView(message: errorMessage) { Task { await load() } } + } else { + ProgressView() + } + } + } + .task { await load() } + } + + private func load() async { + do { + let all = try await client.workspaceDiff(workspaceID: workspaceID) + diff = all.first { $0.path == path } + missing = diff == nil + errorMessage = nil + } catch { + errorMessage = describeHostFailure(error) + } + } +} diff --git a/mobile/ios/App/ConversationsView.swift b/mobile/ios/App/ConversationsView.swift new file mode 100644 index 000000000..ccdad1106 --- /dev/null +++ b/mobile/ios/App/ConversationsView.swift @@ -0,0 +1,193 @@ +import CompanionCore +import SwiftUI + +/// Conversations grouped by project: the root lists projects, a project lists only its own conversations. +struct ConversationsView: View { + let client: HostClient + @State private var list = RemoteList() + @State private var projects: [ProjectSummary]? + + var body: some View { + NavigationStack { + content + .navigationTitle("对话") + .navigationDestination(for: ProjectRoute.self) { route in + ProjectConversationsView( + client: client, + group: group(id: route.id), + projects: projects ?? [], + onRefresh: { await reload() } + ) + } + .navigationDestination(for: ConversationListItem.self) { + ConversationDetailView(client: client, conversation: $0) + } + } + .task { + while !Task.isCancelled { + await reload() + try? await Task.sleep(for: .seconds(list.errorMessage == nil ? 30 : 4)) + } + } + } + + private var groups: [ProjectGroup] { + ProjectGroup.make(conversations: list.items ?? [], projects: projects ?? []) + } + + private func group(id: String) -> ProjectGroup { + groups.first { $0.id == id } ?? ProjectGroup(id: id, name: "", conversations: []) + } + + @ViewBuilder + private var content: some View { + if let items = list.items { + if items.isEmpty { + ContentUnavailableView("最近没有对话", systemImage: "bubble.left.and.bubble.right") + } else if projects == nil { + // The Host did not describe its projects; fall back to one flat list. + List(items) { item in + NavigationLink(value: item) { ConversationRow(item: item) } + } + .refreshable { await reload() } + } else { + List(groups) { group in + NavigationLink(value: ProjectRoute(id: group.id)) { ProjectRow(group: group) } + } + .refreshable { await reload() } + } + } else if let message = list.errorMessage { + LoadFailureView(message: message) { Task { await reload() } } + } else { + ProgressView() + } + } + + private func reload() async { + projects = try? await client.projects() + await list.load { + try await client.call( + "conversation_list_recent", + args: ["sinceDays": 30, "limit": 100], + as: [ConversationListItem].self + ) + } + } +} + +private struct ProjectRoute: Hashable { let id: String } + +extension ConversationListItem: Hashable { + public func hash(into hasher: inout Hasher) { hasher.combine(id) } +} + +private struct ProjectConversationsView: View { + let client: HostClient + let group: ProjectGroup + let projects: [ProjectSummary] + let onRefresh: () async -> Void + + @State private var agents: [CatalogAgent] = [] + @State private var created: ConversationListItem? + @State private var errorMessage: String? + + var body: some View { + List(group.conversations) { item in + NavigationLink(value: item) { ConversationRow(item: item) } + } + .overlay { + if group.conversations.isEmpty { + ContentUnavailableView("这个项目还没有对话", systemImage: "bubble.left.and.bubble.right") + } + } + .navigationTitle(group.name) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + if let workspace = workspaceID, group.id != "other" { + ToolbarItem(placement: .primaryAction) { + Menu { + ForEach(agents.filter(\.usable)) { agent in + Button(agent.displayName) { create(agent: agent, workspace: workspace) } + } + } label: { + Image(systemName: "square.and.pencil") + } + .accessibilityLabel("新对话") + .disabled(agents.allSatisfy { !$0.usable }) + } + } + } + .safeAreaInset(edge: .bottom) { + if let errorMessage { + Text(errorMessage) + .font(.footnote) + .foregroundStyle(.red) + .padding(.horizontal, 16) + .padding(.vertical, 8) + } + } + .navigationDestination(item: $created) { ConversationDetailView(client: client, conversation: $0) } + .refreshable { await onRefresh() } + .task { agents = (try? await client.agentCatalog()) ?? [] } + } + + /// New conversations go to the project's most recently used workspace. + private var workspaceID: String? { + group.conversations.first?.workspace_id + ?? projects.first { $0.id == group.id }?.workspaceIds.first + } + + private func create(agent: CatalogAgent, workspace: String) { + Task { + do { + created = try await client.createConversation(workspaceID: workspace, agentID: agent.id) + errorMessage = nil + } catch { + errorMessage = describeHostFailure(error) + } + } + } +} + +private struct ProjectRow: View { + let group: ProjectGroup + + var body: some View { + HStack(spacing: 12) { + Image(systemName: group.id == "other" ? "tray" : "folder") + .font(.system(size: 18)) + .foregroundStyle(.secondary) + .frame(width: 26) + VStack(alignment: .leading, spacing: 4) { + Text(group.name).lineLimit(1) + HStack(spacing: 8) { + Text("\(group.conversations.count) 个对话") + if let date = group.latest { + Text(date, format: .relative(presentation: .named)) + } + } + .font(.footnote) + .foregroundStyle(.secondary) + } + } + } +} + +private struct ConversationRow: View { + let item: ConversationListItem + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + Text(item.title ?? "未命名对话").lineLimit(1) + HStack(spacing: 8) { + if let date = item.updatedAt { + Text(date, format: .relative(presentation: .named)) + } + Text("\(item.message_count) 条消息") + if let model = item.model { Text(model).lineLimit(1) } + } + .font(.footnote) + .foregroundStyle(.secondary) + } + } +} diff --git a/mobile/ios/App/FilesView.swift b/mobile/ios/App/FilesView.swift new file mode 100644 index 000000000..f4cadcd38 --- /dev/null +++ b/mobile/ios/App/FilesView.swift @@ -0,0 +1,51 @@ +import CompanionCore +import SwiftUI + +struct FilesView: View { + let client: HostClient + @State private var list = RemoteList() + + var body: some View { + NavigationStack { + content.navigationTitle("文件") + } + .task { + while !Task.isCancelled { + await reload() + try? await Task.sleep(for: .seconds(list.errorMessage == nil ? 30 : 4)) + } + } + } + + @ViewBuilder + private var content: some View { + if let items = list.items { + if items.isEmpty { + ContentUnavailableView("还没有 Agent 生成的文件", systemImage: "folder") + } else { + List(items) { item in + VStack(alignment: .leading, spacing: 4) { + Text(item.fileName).lineLimit(1) + HStack(spacing: 8) { + Text(item.updatedAt, format: .relative(presentation: .named)) + Text(item.media_type).lineLimit(1) + } + .font(.footnote) + .foregroundStyle(.secondary) + } + } + .refreshable { await reload() } + } + } else if let message = list.errorMessage { + LoadFailureView(message: message) { Task { await reload() } } + } else { + ProgressView() + } + } + + private func reload() async { + await list.load { + try await client.call("artifact_list", args: ["limit": 100], as: [ArtifactListItem].self) + } + } +} diff --git a/mobile/ios/App/KeychainStore.swift b/mobile/ios/App/KeychainStore.swift new file mode 100644 index 000000000..bfa90c784 --- /dev/null +++ b/mobile/ios/App/KeychainStore.swift @@ -0,0 +1,49 @@ +import Foundation +import Security + +enum KeychainStore { + private static let service = "dev.vibex.companion.credentials" + + static func save(_ secret: String, account: String) throws { + let query = baseQuery(account: account) + SecItemDelete(query as CFDictionary) + var item = query + item[kSecValueData as String] = Data(secret.utf8) + item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly + let status = SecItemAdd(item as CFDictionary, nil) + guard status == errSecSuccess else { throw KeychainError.failed(status) } + } + + static func read(account: String) -> String? { + var query = baseQuery(account: account) + query[kSecReturnData as String] = true + query[kSecMatchLimit as String] = kSecMatchLimitOne + var result: AnyObject? + guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, + let data = result as? Data + else { return nil } + return String(data: data, encoding: .utf8) + } + + static func delete(account: String) { + SecItemDelete(baseQuery(account: account) as CFDictionary) + } + + private static func baseQuery(account: String) -> [String: Any] { + [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + ] + } +} + +enum KeychainError: LocalizedError { + case failed(OSStatus) + + var errorDescription: String? { + switch self { + case .failed(let status): return "无法保存凭据(\(status))" + } + } +} diff --git a/mobile/ios/App/LoadingState.swift b/mobile/ios/App/LoadingState.swift new file mode 100644 index 000000000..778847b8a --- /dev/null +++ b/mobile/ios/App/LoadingState.swift @@ -0,0 +1,96 @@ +import SwiftUI + +/// 3×3 pixel grid with a chevron wavefront driving right; two fronts are always in flight. +struct PixelLoader: View { + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + private let cycle = 650.0 + private let delays: [Double] = (0..<9).map { index in + let row = index / 3, column = index % 3 + return Double((column + abs(row - 1)) * 90) + } + + var body: some View { + TimelineView(.animation(minimumInterval: 1.0 / 30, paused: reduceMotion)) { context in + let now = context.date.timeIntervalSinceReferenceDate * 1000 + Grid(horizontalSpacing: 1.5, verticalSpacing: 1.5) { + ForEach(0..<3, id: \.self) { row in + GridRow { + ForEach(0..<3, id: \.self) { column in + RoundedRectangle(cornerRadius: 1) + .fill(Color.primary) + .frame(width: 4, height: 4) + .opacity(opacity(now: now, index: row * 3 + column)) + } + } + } + } + } + .accessibilityHidden(true) + } + + private func opacity(now: Double, index: Int) -> Double { + guard !reduceMotion else { return 0.15 } + let local = (now - delays[index]).truncatingRemainder(dividingBy: cycle) + let phase = (local < 0 ? local + cycle : local) / cycle + return 0.15 + 0.85 * pow(sin(.pi * phase), 2) + } +} + +/// Label whose highlight sweeps across it while work is in progress. +struct ShimmerText: View { + let text: String + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + var body: some View { + TimelineView(.animation(minimumInterval: 1.0 / 30, paused: reduceMotion)) { context in + let phase = (context.date.timeIntervalSinceReferenceDate / 1.4).truncatingRemainder(dividingBy: 1) + Text(text) + .foregroundStyle(.secondary) + .overlay { + if !reduceMotion { + Text(text) + .foregroundStyle(.primary) + .mask { + GeometryReader { proxy in + LinearGradient( + colors: [.clear, .black, .clear], + startPoint: .leading, + endPoint: .trailing + ) + .frame(width: proxy.size.width * 0.6) + .offset(x: (phase * 1.6 - 0.3) * proxy.size.width) + } + } + } + } + } + } +} + +/// Long-running work indicator: pixel grid, shimmering label and a live elapsed timer. +struct LoadingState: View { + let label: String + @State private var started = Date() + + var body: some View { + HStack(spacing: 10) { + PixelLoader() + ShimmerText(text: label).font(.system(size: 13, weight: .medium)) + TimelineView(.periodic(from: started, by: 0.1)) { context in + Text(elapsed(context.date.timeIntervalSince(started))) + .font(.system(size: 12, design: .monospaced)) + .monospacedDigit() + .foregroundStyle(.tertiary) + } + } + .accessibilityElement(children: .combine) + .accessibilityLabel(label) + } + + private func elapsed(_ seconds: TimeInterval) -> String { + seconds < 60 + ? String(format: "%.1fs", seconds) + : String(format: "%dm %.1fs", Int(seconds) / 60, seconds.truncatingRemainder(dividingBy: 60)) + } +} diff --git a/mobile/ios/App/PairView.swift b/mobile/ios/App/PairView.swift new file mode 100644 index 000000000..aa1b8e21a --- /dev/null +++ b/mobile/ios/App/PairView.swift @@ -0,0 +1,119 @@ +import CompanionCore +import SwiftUI +import UIKit + +struct PairView: View { + @Environment(ServerStore.self) private var servers + @Environment(\.dismiss) private var dismiss + @State private var code = "" + @State private var origin = "" + @State private var deviceName = UIDevice.current.name + @State private var busy = false + @State private var scanning = false + @State private var errorMessage: String? + + private var isInvitation: Bool { PairingInvitation.looksLikeInvitation(code) } + + private var canSubmit: Bool { + guard !busy, !code.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + return false + } + return isInvitation || !origin.trimmingCharacters(in: .whitespaces).isEmpty + } + + var body: some View { + NavigationStack { + Form { + Section("连接码") { + TextField("粘贴连接码", text: $code) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + HStack { + Button("粘贴", systemImage: "doc.on.clipboard") { + if let text = UIPasteboard.general.string { code = text } + } + Spacer() + Button("扫码", systemImage: "qrcode.viewfinder") { scanning = true } + } + .buttonStyle(.borderless) + } + Section("电脑地址") { + if isInvitation { + Text("已包含在连接码中").foregroundStyle(.secondary) + } else { + TextField("http://192.168.1.2:17891", text: $origin) + .keyboardType(.URL) + .textContentType(.URL) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + } + } + Section("设备名称") { + TextField("设备名称", text: $deviceName) + } + if let errorMessage { + Section { Text(errorMessage).foregroundStyle(.red) } + } + } + .navigationTitle("配对电脑") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("取消") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + if busy { + ProgressView() + } else { + Button("配对", action: submit).disabled(!canSubmit) + } + } + } + .interactiveDismissDisabled(busy) + .fullScreenCover(isPresented: $scanning) { scanner } + } + } + + private var scanner: some View { + NavigationStack { + QRScannerView( + onCode: { text in + code = text + scanning = false + if PairingInvitation.looksLikeInvitation(text) { submit() } + }, + onFailure: { message in + errorMessage = message + scanning = false + } + ) + .ignoresSafeArea() + .navigationTitle("扫描二维码") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("取消") { scanning = false } + } + } + } + } + + private func submit() { + busy = true + errorMessage = nil + let input = code.trimmingCharacters(in: .whitespacesAndNewlines) + Task { + do { + try await servers.pair(input: input, manualOrigin: origin, deviceName: deviceName) + dismiss() + } catch { + errorMessage = error.localizedDescription + busy = false + } + } + } +} + +#Preview { + PairView().environment(ServerStore(defaults: UserDefaults(suiteName: "preview")!)) +} diff --git a/mobile/ios/App/PromptBar.swift b/mobile/ios/App/PromptBar.swift new file mode 100644 index 000000000..24e0ef49d --- /dev/null +++ b/mobile/ios/App/PromptBar.swift @@ -0,0 +1,544 @@ +import SwiftUI + +enum ComposerMenu: Equatable { + case access, model, effort +} + +struct PromptChoice: Identifiable, Equatable { + let id: String + var title: String + var detail: String? + var tag: String? + var icon: String? + var selected = false + var enabled = true +} + +struct PromptGroup: Identifiable, Equatable { + var id: String { title } + let title: String + let choices: [PromptChoice] +} + +struct PromptEffort: Equatable { + let levels: [String] + let index: Int +} + +/// SwiftUI port of the web PromptBar: one rounded field, a tool row, and floating menus above it. +struct PromptBar: View { + @Binding var draft: String + @Binding var menu: ComposerMenu? + let isRunning: Bool + let busy: Bool + let hasAlert: Bool + let modelName: String? + let modelChoices: [PromptChoice] + let otherModelGroups: [PromptGroup] + let otherAgentNote: String? + let accessChoices: [PromptChoice] + let extraChoices: [PromptChoice] + let effort: PromptEffort? + let send: () -> Void + let stop: () -> Void + let pickModel: (String) -> Void + let pickAccess: (String) -> Void + let pickExtra: (String) -> Void + let setEffort: (Int) -> Void + + @FocusState private var focused: Bool + + private let spark = Color(red: 0.70, green: 0.62, blue: 1.0) + private var armed: Bool { + isRunning || !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + private var effortAtMax: Bool { + guard let effort else { return false } + return effort.levels.count > 1 && effort.index == effort.levels.count - 1 + } + + var body: some View { + VStack(spacing: 8) { + if let menu { + menuView(menu) + .padding(.horizontal, 12) + .transition(.scale(scale: 0.98, anchor: .bottom).combined(with: .opacity)) + } + field + } + .animation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.18), value: menu) + } + + // MARK: Field + + private var field: some View { + VStack(alignment: .leading, spacing: 8) { + TextField("发消息", text: $draft, axis: .vertical) + .lineLimit(1...5) + .font(.system(size: 16)) + .focused($focused) + .onChange(of: focused) { _, isFocused in if isFocused { menu = nil } } + .onChange(of: draft) { _, _ in menu = nil } + toolRow + } + .padding(.horizontal, 16) + .padding(.top, 12) + .padding(.bottom, 8) + .frame(maxWidth: .infinity) + .background(alignment: .bottom) { + // The dock runs to the screen edge so its colour and the home-indicator area are one surface. + let dock = UnevenRoundedRectangle(topLeadingRadius: 20, topTrailingRadius: 20) + ZStack { + dock.fill(Color(.secondarySystemGroupedBackground)) + dock + .fill(RadialGradient( + colors: [spark.opacity(0.26), .clear], + center: .bottomLeading, + startRadius: 0, + endRadius: 220 + )) + .opacity(effortAtMax ? 1 : 0) + .animation(.easeInOut(duration: 0.5), value: effortAtMax) + dock.stroke(Color.primary.opacity(0.06)) + } + .shadow(color: .black.opacity(0.06), radius: 8, y: -2) + .ignoresSafeArea(edges: .bottom) + } + .contentShape(Rectangle()) + .onTapGesture { focused = true } + } + + private var toolRow: some View { + HStack(spacing: 4) { + ToolButton(icon: "plus", on: menu == .access, alert: hasAlert, label: "权限与模式") { + toggle(.access) + } + if let modelName { + PickPill(on: menu == .model, label: "选择模型") { toggle(.model) } content: { + Text(modelName).lineLimit(1) + Image(systemName: "chevron.down").font(.system(size: 10, weight: .bold)) + } + } + if let effort { + PickPill(on: menu == .effort, tint: effortAtMax ? spark : nil, label: "推理强度") { + toggle(.effort) + } content: { + Image(systemName: "sparkles").font(.system(size: 12, weight: .semibold)) + Text(effort.levels[effort.index]) + } + } + Spacer(minLength: 0) + SendButton(armed: armed, running: isRunning, busy: busy, send: send, stop: stop) + } + } + + private func toggle(_ target: ComposerMenu) { + focused = false + menu = menu == target ? nil : target + } + + // MARK: Menus + + @ViewBuilder + private func menuView(_ kind: ComposerMenu) -> some View { + Group { + switch kind { + case .access: + MenuList(rows: accessChoices + extraChoices, empty: "Agent 没有提供权限设置") { id in + if accessChoices.contains(where: { $0.id == id }) { pickAccess(id) } else { pickExtra(id) } + } + case .model: + MenuList( + rows: modelChoices, + groups: otherModelGroups, + footnote: otherAgentNote, + empty: "电脑端没有配置可选模型", + select: pickModel + ) + .frame(maxWidth: 240) + case .effort: + if let effort { + EffortMenu(effort: effort, atMax: effortAtMax, spark: spark, change: setEffort) + .frame(maxWidth: 260) + } + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } +} + +// MARK: - Controls + +private struct ToolButton: View { + let icon: String + let on: Bool + var alert = false + let label: String + let action: () -> Void + + var body: some View { + Button(action: action) { + Image(systemName: icon) + .font(.system(size: 15, weight: .semibold)) + .rotationEffect(.degrees(on ? 45 : 0)) + .frame(width: 28, height: 28) + .background(on ? Color.primary.opacity(0.08) : .clear, in: RoundedRectangle(cornerRadius: 8)) + .foregroundStyle(on ? Color.primary : Color.primary.opacity(0.6)) + .overlay(alignment: .topTrailing) { + if alert { Circle().fill(.orange).frame(width: 8, height: 8).offset(x: 1, y: -1) } + } + .animation(.spring(duration: 0.25), value: on) + } + .buttonStyle(PressStyle(scale: 0.94)) + .accessibilityLabel(label) + } +} + +private struct PickPill: View { + let on: Bool + var tint: Color? + let label: String + let action: () -> Void + @ViewBuilder let content: () -> Content + + var body: some View { + Button(action: action) { + HStack(spacing: 4, content: content) + .font(.system(size: 12, weight: .medium)) + .padding(.horizontal, 8) + .frame(height: 28) + .background(on ? Color.primary.opacity(0.08) : .clear, in: RoundedRectangle(cornerRadius: 8)) + .foregroundStyle(tint ?? (on ? Color.primary : Color.primary.opacity(0.7))) + } + .buttonStyle(PressStyle(scale: 0.96)) + .accessibilityLabel(label) + } +} + +private struct PressStyle: ButtonStyle { + let scale: CGFloat + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .scaleEffect(configuration.isPressed ? scale : 1) + .animation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.16), value: configuration.isPressed) + } +} + +private struct SendButton: View { + let armed: Bool + let running: Bool + let busy: Bool + let send: () -> Void + let stop: () -> Void + + var body: some View { + Button(action: running ? stop : send) { + SendGlyph(morph: running ? 1 : 0) + .frame(width: 16, height: 16) + .frame(width: 28, height: 28) + .foregroundStyle(armed ? Color(.systemBackground) : Color.primary.opacity(0.35)) + .background( + armed ? Color.primary : Color.primary.opacity(0.08), + in: RoundedRectangle(cornerRadius: 8) + ) + .animation(.easeOut(duration: 0.2), value: armed) + } + .buttonStyle(PressStyle(scale: armed ? 0.96 : 1)) + .disabled(!armed || (busy && !running)) + .accessibilityLabel(running ? "停止" : "发送") + } +} + +// MARK: - Send glyph (arrow morphs into a stop square) + +private let arrowPoints: [CGPoint] = [ + (12, 4.5), (18.5, 11), (14.25, 11), (14.25, 19.5), (9.75, 19.5), (9.75, 11), (5.5, 11), +].map { CGPoint(x: $0.0, y: $0.1) } + +private let squarePoints: [CGPoint] = [ + (12, 6), (18, 6), (18, 12), (18, 18), (6, 18), (6, 12), (6, 6), +].map { CGPoint(x: $0.0, y: $0.1) } + +private struct GlyphShape: Shape { + var t: Double + var animatableData: Double { + get { t } + set { t = newValue } + } + + func path(in rect: CGRect) -> Path { + let scale = rect.width / 24 + var path = Path() + for (i, (a, b)) in zip(arrowPoints, squarePoints).enumerated() { + let point = CGPoint( + x: (a.x + (b.x - a.x) * t) * scale, + y: (a.y + (b.y - a.y) * t) * scale + ) + i == 0 ? path.move(to: point) : path.addLine(to: point) + } + path.closeSubpath() + return path + } +} + +/// Squash and tilt while morphing, peaking halfway through. +private struct GooEffect: GeometryEffect { + var t: Double + var direction: Double + var animatableData: Double { + get { t } + set { t = newValue } + } + + func effectValue(size: CGSize) -> ProjectionTransform { + let goo = sin(t * .pi) + let sx = 1 - 0.12 * goo + var transform = CGAffineTransform(translationX: size.width / 2, y: size.height / 2) + transform = transform.rotated(by: direction * 8 * goo * .pi / 180) + transform = transform.scaledBy(x: sx, y: 1 / sx) + transform = transform.translatedBy(x: -size.width / 2, y: -size.height / 2) + return ProjectionTransform(transform) + } +} + +private struct SendGlyph: View { + let morph: Double + + var body: some View { + GlyphShape(t: morph) + .fill() + .overlay(GlyphShape(t: morph).stroke(style: StrokeStyle(lineWidth: 1.33, lineJoin: .round))) + .modifier(GooEffect(t: morph, direction: morph == 1 ? 1 : -1)) + .animation(.timingCurve(0.77, 0, 0.175, 1, duration: 0.24), value: morph) + } +} + +// MARK: - Menus + +private struct MenuList: View { + let rows: [PromptChoice] + var groups: [PromptGroup] = [] + var footnote: String? + let empty: String + let select: (String) -> Void + + private var estimatedHeight: CGFloat { + CGFloat(rows.count) * 36 + + groups.reduce(0) { $0 + 28 + CGFloat($1.choices.count) * 36 } + + (footnote == nil ? 0 : 40) + } + + var body: some View { + MenuSurface { + if rows.isEmpty && groups.isEmpty { + Text(empty) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .frame(height: 36) + .padding(.horizontal, 8) + } else { + ScrollView { + VStack(spacing: 0) { + ForEach(rows) { row in MenuRow(row: row) { select(row.id) } } + ForEach(groups) { group in + Text(group.title) + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 8) + .padding(.top, 8) + ForEach(group.choices) { row in MenuRow(row: row) {} } + } + if let footnote { + Text(footnote) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(8) + } + } + } + .frame(height: min(estimatedHeight, 300)) + } + } + } +} + +private struct MenuRow: View { + let row: PromptChoice + let action: () -> Void + + var body: some View { + Button(action: action) { + HStack(spacing: 10) { + if let icon = row.icon { + Image(systemName: icon) + .font(.system(size: 14)) + .frame(width: 20) + .foregroundStyle(.secondary) + } + Text(row.title).font(.system(size: 13, weight: .medium)).lineLimit(1) + if let detail = row.detail, !detail.isEmpty { + Text(detail) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Spacer(minLength: 0) + if let tag = row.tag { + Text(tag).font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1) + } + Image(systemName: "checkmark") + .font(.system(size: 11, weight: .heavy)) + .opacity(row.selected ? 1 : 0) + } + .padding(.horizontal, 8) + .frame(height: 36) + .contentShape(Rectangle()) + .foregroundStyle(row.enabled ? Color.primary : Color.primary.opacity(0.4)) + } + .buttonStyle(RowStyle()) + .disabled(!row.enabled) + } +} + +private struct RowStyle: ButtonStyle { + func makeBody(configuration: Configuration) -> some View { + configuration.label + .background( + configuration.isPressed ? Color.primary.opacity(0.08) : .clear, + in: RoundedRectangle(cornerRadius: 8) + ) + } +} + +private struct MenuSurface: View { + @ViewBuilder let content: () -> Content + + var body: some View { + content() + .padding(4) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 12)) + .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.primary.opacity(0.06))) + .shadow(color: .black.opacity(0.08), radius: 10, y: 2) + } +} + +private struct EffortMenu: View { + let effort: PromptEffort + let atMax: Bool + let spark: Color + let change: (Int) -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 8) { + Text("推理强度").foregroundStyle(.secondary) + Text(effort.levels[effort.index]).fontWeight(.medium) + Spacer() + } + .font(.system(size: 13)) + HStack { + Text("更快") + Spacer() + Text("更强") + } + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .padding(.top, 12) + EffortSlider(levels: effort.levels.count, index: effort.index, atMax: atMax, spark: spark, change: change) + .padding(.top, 8) + } + .padding(.horizontal, 14) + .padding(.top, 12) + .padding(.bottom, 14) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 12)) + .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.primary.opacity(0.06))) + .shadow(color: .black.opacity(0.08), radius: 10, y: 2) + } +} + +private struct EffortSlider: View { + let levels: Int + let index: Int + let atMax: Bool + let spark: Color + let change: (Int) -> Void + + private let edge: CGFloat = 11 + + var body: some View { + GeometryReader { geo in + let usable = max(1, geo.size.width - 2 * edge) + let steps = CGFloat(max(1, levels - 1)) + let x = { (i: Int) in edge + usable * CGFloat(i) / steps } + ZStack(alignment: .leading) { + Capsule().fill(Color.primary.opacity(0.08)) + Capsule() + .fill(atMax ? spark.opacity(0.35) : Color.primary.opacity(0.18)) + .frame(width: index == levels - 1 ? geo.size.width : x(index) + 7) + ForEach(0.. Void + let onFailure: (String) -> Void + + func makeUIViewController(context: Context) -> ScannerController { + let controller = ScannerController() + controller.onCode = onCode + controller.onFailure = onFailure + return controller + } + + func updateUIViewController(_ controller: ScannerController, context: Context) {} +} + +final class ScannerController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { + var onCode: ((String) -> Void)? + var onFailure: ((String) -> Void)? + private let session = AVCaptureSession() + private var previewLayer: AVCaptureVideoPreviewLayer? + private var delivered = false + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .black + switch AVCaptureDevice.authorizationStatus(for: .video) { + case .authorized: + configure() + case .notDetermined: + AVCaptureDevice.requestAccess(for: .video) { granted in + DispatchQueue.main.async { + granted ? self.configure() : self.onFailure?("需要相机权限才能扫码") + } + } + default: + onFailure?("需要相机权限才能扫码,请在系统设置中允许") + } + } + + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + previewLayer?.frame = view.bounds + } + + override func viewDidDisappear(_ animated: Bool) { + super.viewDidDisappear(animated) + if session.isRunning { session.stopRunning() } + } + + private func configure() { + guard let device = AVCaptureDevice.default(for: .video), + let input = try? AVCaptureDeviceInput(device: device), + session.canAddInput(input) + else { + onFailure?("此设备无法使用相机") + return + } + session.addInput(input) + let output = AVCaptureMetadataOutput() + guard session.canAddOutput(output) else { + onFailure?("此设备无法使用相机") + return + } + session.addOutput(output) + output.setMetadataObjectsDelegate(self, queue: .main) + output.metadataObjectTypes = [.qr] + let layer = AVCaptureVideoPreviewLayer(session: session) + layer.videoGravity = .resizeAspectFill + layer.frame = view.bounds + view.layer.addSublayer(layer) + previewLayer = layer + DispatchQueue.global(qos: .userInitiated).async { self.session.startRunning() } + } + + func metadataOutput( + _ output: AVCaptureMetadataOutput, + didOutput objects: [AVMetadataObject], + from connection: AVCaptureConnection + ) { + guard !delivered, + let text = (objects.first as? AVMetadataMachineReadableCodeObject)?.stringValue + else { return } + delivered = true + onCode?(text) + } +} diff --git a/mobile/ios/App/RemoteList.swift b/mobile/ios/App/RemoteList.swift new file mode 100644 index 000000000..17dc97ec2 --- /dev/null +++ b/mobile/ios/App/RemoteList.swift @@ -0,0 +1,32 @@ +import CompanionCore +import Foundation +import Observation + +/// Reader-facing text for a failed Host call: unreachable and revoked need different actions. +func describeHostFailure(_ error: Error) -> String { + if error is URLError { + return "无法连接电脑。请确认电脑上的 VibeX 正在运行并已开启远程访问,恢复后会自动重试" + } + if case HostError.server(let status, _) = error, status == 401 { + return "配对已失效,请在设置里重新配对" + } + return error.localizedDescription +} + +@MainActor +@Observable +final class RemoteList { + private(set) var items: [Item]? + private(set) var errorMessage: String? + + func load(_ fetch: () async throws -> [Item]) async { + do { + items = try await fetch() + errorMessage = nil + } catch is CancellationError { + return + } catch { + errorMessage = describeHostFailure(error) + } + } +} diff --git a/mobile/ios/App/RequiresServer.swift b/mobile/ios/App/RequiresServer.swift new file mode 100644 index 000000000..d24137c75 --- /dev/null +++ b/mobile/ios/App/RequiresServer.swift @@ -0,0 +1,46 @@ +import CompanionCore +import SwiftUI + +/// Gate for tabs that read from the paired computer. +struct RequiresServer: View { + @Environment(ServerStore.self) private var servers + @Binding var selection: AppTab + @ViewBuilder let content: (HostClient) -> Content + + var body: some View { + if let profile = servers.activeProfile { + if let client = servers.client(for: profile) { + content(client) + } else { + ContentUnavailableView { + Label("连接凭据已失效", systemImage: "key.slash") + } actions: { + Button("重新配对") { selection = .settings } + .buttonStyle(.borderedProminent) + } + } + } else { + ContentUnavailableView { + Label("尚未连接电脑", systemImage: "desktopcomputer") + } actions: { + Button("去配对") { selection = .settings } + .buttonStyle(.borderedProminent) + } + } + } +} + +struct LoadFailureView: View { + let message: String + let retry: () -> Void + + var body: some View { + ContentUnavailableView { + Label("无法读取", systemImage: "exclamationmark.triangle") + } description: { + Text(message) + } actions: { + Button("重试", action: retry) + } + } +} diff --git a/mobile/ios/App/RootTabView.swift b/mobile/ios/App/RootTabView.swift new file mode 100644 index 000000000..6287b252a --- /dev/null +++ b/mobile/ios/App/RootTabView.swift @@ -0,0 +1,46 @@ +import SwiftUI + +enum AppTab: Hashable { + case conversations, board, space, files, settings +} + +struct RootTabView: View { + @State private var selection: AppTab = .conversations + + var body: some View { + TabView(selection: $selection) { + RequiresServer(selection: $selection) { ConversationsView(client: $0) } + .tabItem { Label("对话", systemImage: "bubble.left.and.bubble.right") } + .tag(AppTab.conversations) + UnsupportedTab(title: "看板", icon: "square.grid.2x2") + .tabItem { Label("看板", systemImage: "square.grid.2x2") } + .tag(AppTab.board) + UnsupportedTab(title: "协作空间", icon: "person.2") + .tabItem { Label("协作空间", systemImage: "person.2") } + .tag(AppTab.space) + RequiresServer(selection: $selection) { FilesView(client: $0) } + .tabItem { Label("文件", systemImage: "folder") } + .tag(AppTab.files) + SettingsView() + .tabItem { Label("设置", systemImage: "gearshape") } + .tag(AppTab.settings) + } + } +} + +/// The Host does not grant the Companion preset access to this surface (ADR-0054). +private struct UnsupportedTab: View { + let title: String + let icon: String + + var body: some View { + NavigationStack { + ContentUnavailableView(title, systemImage: icon, description: Text("手机端暂不支持")) + .navigationTitle(title) + } + } +} + +#Preview { + RootTabView().environment(ServerStore(defaults: UserDefaults(suiteName: "preview")!)) +} diff --git a/mobile/ios/App/ServerDetailView.swift b/mobile/ios/App/ServerDetailView.swift new file mode 100644 index 000000000..93e05348d --- /dev/null +++ b/mobile/ios/App/ServerDetailView.swift @@ -0,0 +1,35 @@ +import SwiftUI + +struct ServerDetailView: View { + @Environment(ServerStore.self) private var servers + @Environment(\.dismiss) private var dismiss + let profile: ServerProfile + @State private var confirmingForget = false + + var body: some View { + List { + Section("电脑") { + LabeledContent("地址", value: profile.origin) + LabeledContent("VibeX 版本", value: profile.serverVersion) + LabeledContent("协议版本", value: profile.protocolVersion) + LabeledContent("设备名称", value: profile.deviceName) + } + Section("权限") { + ForEach(profile.scopes, id: \.self) { Text($0).font(.footnote.monospaced()) } + } + Section { + Button("忘记此电脑", role: .destructive) { confirmingForget = true } + } + } + .navigationTitle("电脑详情") + .navigationBarTitleDisplayMode(.inline) + .confirmationDialog("忘记此电脑?", isPresented: $confirmingForget, titleVisibility: .visible) { + Button("忘记", role: .destructive) { + servers.forget(profile) + dismiss() + } + } message: { + Text("需要重新配对才能再次连接") + } + } +} diff --git a/mobile/ios/App/ServerStore.swift b/mobile/ios/App/ServerStore.swift new file mode 100644 index 000000000..6aa3ba2c3 --- /dev/null +++ b/mobile/ios/App/ServerStore.swift @@ -0,0 +1,74 @@ +import CompanionCore +import Foundation +import Observation + +struct ServerProfile: Codable, Identifiable, Hashable { + let id: String + var origin: String + var deviceName: String + var serverVersion: String + var protocolVersion: String + var scopes: [String] +} + +@Observable +final class ServerStore { + private(set) var profiles: [ServerProfile] + private let defaults: UserDefaults + private static let key = "server-profiles" + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + self.profiles = (defaults.data(forKey: Self.key)) + .flatMap { try? JSONDecoder().decode([ServerProfile].self, from: $0) } ?? [] + } + + /// `input` is a pasted or scanned invitation, or a bare connection code with a manual origin. + func pair(input: String, manualOrigin: String, deviceName: String) async throws { + let client = PairingClient() + let session: CompanionSession + if PairingInvitation.looksLikeInvitation(input) { + let invitation = try PairingInvitation.parse(input) + session = try await client.redeem(invitation: invitation, deviceName: deviceName) + } else { + session = try await client.redeem( + origin: try HostOrigin.parse(manualOrigin), + pairingToken: input, + deviceName: deviceName + ) + } + let id = session.credential.device_id + try KeychainStore.save(session.credential.access_token, account: id) + let profile = ServerProfile( + id: id, + origin: session.origin.value, + deviceName: deviceName, + serverVersion: session.capabilities.server_version, + protocolVersion: session.capabilities.protocol_version, + scopes: session.credential.scopes + ) + profiles.removeAll { $0.origin == profile.origin } + profiles.append(profile) + persist() + } + + /// The most recently paired computer is the one the tabs read from. + var activeProfile: ServerProfile? { profiles.last } + + func client(for profile: ServerProfile) -> HostClient? { + guard let origin = try? HostOrigin.parse(profile.origin), + let token = KeychainStore.read(account: profile.id) + else { return nil } + return HostClient(origin: origin, accessToken: token) + } + + func forget(_ profile: ServerProfile) { + KeychainStore.delete(account: profile.id) + profiles.removeAll { $0.id == profile.id } + persist() + } + + private func persist() { + defaults.set(try? JSONEncoder().encode(profiles), forKey: Self.key) + } +} diff --git a/mobile/ios/App/SettingsView.swift b/mobile/ios/App/SettingsView.swift new file mode 100644 index 000000000..9cc4b396a --- /dev/null +++ b/mobile/ios/App/SettingsView.swift @@ -0,0 +1,36 @@ +import SwiftUI + +struct SettingsView: View { + @Environment(ServerStore.self) private var servers + @State private var showingPair = false + + var body: some View { + NavigationStack { + List { + Section("电脑") { + ForEach(servers.profiles) { profile in + NavigationLink(value: profile) { + VStack(alignment: .leading, spacing: 2) { + Text(profile.origin) + Text("VibeX \(profile.serverVersion)") + .font(.footnote) + .foregroundStyle(.secondary) + } + } + } + .onDelete { offsets in + offsets.map { servers.profiles[$0] }.forEach(servers.forget) + } + Button("配对电脑", systemImage: "plus") { showingPair = true } + } + } + .navigationTitle("设置") + .navigationDestination(for: ServerProfile.self) { ServerDetailView(profile: $0) } + .sheet(isPresented: $showingPair) { PairView() } + } + } +} + +#Preview { + SettingsView().environment(ServerStore(defaults: UserDefaults(suiteName: "preview")!)) +} diff --git a/mobile/ios/App/StreamingText.swift b/mobile/ios/App/StreamingText.swift new file mode 100644 index 000000000..1857a51a0 --- /dev/null +++ b/mobile/ios/App/StreamingText.swift @@ -0,0 +1,97 @@ +import SwiftUI + +/// An assistant answer. As the transcript grows, the new words resolve out of blur one after another; +/// once the turn is done a small action row appears. +struct StreamingMessageText: View { + let text: String + let streaming: Bool + + @State private var settled = 0 + @State private var progress = 1.0 + @State private var copied = false + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + rendered + .font(.system(size: 15)) + .lineSpacing(4) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + if !streaming && !text.isEmpty { + Button { + UIPasteboard.general.string = text + withAnimation { copied = true } + Task { + try? await Task.sleep(for: .seconds(1.5)) + withAnimation { copied = false } + } + } label: { + Image(systemName: copied ? "checkmark" : "doc.on.doc") + .font(.system(size: 13)) + .foregroundStyle(.secondary) + .frame(width: 28, height: 24) + .contentTransition(.symbolEffect(.replace)) + } + .buttonStyle(.plain) + .accessibilityLabel("复制") + .transition(.opacity) + } + } + .animation(.easeOut(duration: 0.3), value: streaming) + .onAppear { settled = text.count } + .onChange(of: text) { old, new in + guard new.hasPrefix(old), new.count > old.count else { + settled = new.count + progress = 1 + return + } + settled = old.count + var instant = Transaction() + instant.disablesAnimations = true + withTransaction(instant) { progress = 0 } + Task { @MainActor in + await Task.yield() + withAnimation(.easeOut(duration: 0.55)) { progress = 1 } + } + } + } + + @ViewBuilder + private var rendered: some View { + let display = streaming ? text + "▍" : text + if #available(iOS 18.0, *) { + Text(display).textRenderer(RevealRenderer(settled: settled, progress: progress, hasCursor: streaming)) + } else { + Text(display) + } + } +} + +@available(iOS 18.0, *) +private struct RevealRenderer: TextRenderer { + var settled: Int + var progress: Double + var hasCursor: Bool + + var animatableData: Double { + get { progress } + set { progress = newValue } + } + + func draw(layout: Text.Layout, in context: inout GraphicsContext) { + let slices = layout.flatMap { $0 }.flatMap { $0 } + let fresh = max(1, slices.count - settled - (hasCursor ? 1 : 0)) + for (index, slice) in slices.enumerated() { + if index < settled || (hasCursor && index == slices.count - 1) { + context.draw(slice) + continue + } + let order = Double(index - settled) / Double(fresh) + let local = min(1, max(0, progress * 1.6 - 0.6 * order)) + var copy = context + copy.opacity = local + copy.addFilter(.blur(radius: (1 - local) * 4)) + copy.draw(slice) + } + } +} diff --git a/mobile/ios/App/TaskActivityController.swift b/mobile/ios/App/TaskActivityController.swift new file mode 100644 index 000000000..fde959400 --- /dev/null +++ b/mobile/ios/App/TaskActivityController.swift @@ -0,0 +1,126 @@ +import ActivityKit +import CompanionCore +import Foundation +import UIKit + +/// Mirrors the Agent's task list into a Live Activity: Dynamic Island where the iPhone has one, +/// Lock Screen everywhere else. iOS only lets the app change it while the app is running, so it +/// follows the plan while the app is open and keeps its last state once the app is suspended. +@MainActor +final class TaskActivityController { + private var activity: Activity? + private var lastState: TaskActivityAttributes.ContentState? + + private var runStart: Date? + private var lingerTask: Task? + private var lastPush = Date.distantPast + private var background = UIBackgroundTaskIdentifier.invalid + private var observer: NSObjectProtocol? + + /// How long the activity stays fresh without another push; past it the widget says syncing paused. + private static let freshness: TimeInterval = 45 + + init() { + observer = NotificationCenter.default.addObserver( + forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.holdBackgroundTime() } + } + } + + deinit { + if let observer { NotificationCenter.default.removeObserver(observer) } + } + + /// iOS suspends the app shortly after it leaves the foreground; ask for the extra time it grants + /// so the activity keeps following a run that is still going. + private func holdBackgroundTime() { + guard activity != nil, background == .invalid else { return } + let app = UIApplication.shared + background = app.beginBackgroundTask { [weak self] in self?.releaseBackgroundTime() } + } + + private func releaseBackgroundTime() { + guard background != .invalid else { return } + UIApplication.shared.endBackgroundTask(background) + background = .invalid + } + + /// `tasks` is the Agent's published plan; without an unfinished plan the activity follows the + /// run itself and shows `step` (the latest tool call) with an elapsed timer. + func sync(title: String, tasks: [PlanTask], step: String?, running: Bool) { + let completed = tasks.filter { $0.status == .completed }.count + let planActive = !tasks.isEmpty && completed < tasks.count + guard running || planActive else { + finish() + return + } + lingerTask?.cancel() + lingerTask = nil + if runStart == nil { runStart = Date() } + let current = tasks.first { $0.status == .running } ?? tasks.first { $0.status == .pending } + let state = TaskActivityAttributes.ContentState( + completed: planActive ? completed : 0, + total: planActive ? tasks.count : 0, + currentTask: planActive ? (current?.label ?? "") : (step ?? "处理中"), + isRunning: running, + startedAt: runStart ?? Date() + ) + guard state != lastState || Date().timeIntervalSince(lastPush) > Self.freshness / 3 else { return } + lastState = state + lastPush = Date() + let content = ActivityContent(state: state, staleDate: Date().addingTimeInterval(Self.freshness)) + if let activity { + Task { await activity.update(content) } + } else { + start(title: title, state: state) + } + } + + /// The Dynamic Island only shows live activities, so the finished state is pushed while the + /// activity is still live and held for a moment before it is ended. + private func finish() { + runStart = nil + guard activity != nil, lingerTask == nil, var done = lastState, done.isRunning else { return } + done.isRunning = false + lastState = done + guard let current = activity else { return } + lingerTask = Task { [weak self] in + let app = UIApplication.shared + var background = UIBackgroundTaskIdentifier.invalid + background = app.beginBackgroundTask { app.endBackgroundTask(background) } + await current.update(ActivityContent(state: done, staleDate: nil)) + try? await Task.sleep(for: .seconds(20)) + if !Task.isCancelled { self?.end(final: done, after: 30) } + app.endBackgroundTask(background) + } + } + + func stop() { + lingerTask?.cancel() + lingerTask = nil + end(after: 0) + } + + private func start(title: String, state: TaskActivityAttributes.ContentState) { + guard ActivityAuthorizationInfo().areActivitiesEnabled else { return } + activity = try? Activity.request( + attributes: TaskActivityAttributes(conversationTitle: title), + content: ActivityContent(state: state, staleDate: Date().addingTimeInterval(Self.freshness)) + ) + } + + private func end(final: TaskActivityAttributes.ContentState? = nil, after seconds: TimeInterval) { + guard let current = activity else { return } + activity = nil + lastState = nil + runStart = nil + let content = final.map { ActivityContent(state: $0, staleDate: nil) } + Task { + await current.end( + content, + dismissalPolicy: seconds > 0 ? .after(Date().addingTimeInterval(seconds)) : .immediate + ) + } + } +} diff --git a/mobile/ios/App/TaskRows.swift b/mobile/ios/App/TaskRows.swift new file mode 100644 index 000000000..e5025939b --- /dev/null +++ b/mobile/ios/App/TaskRows.swift @@ -0,0 +1,185 @@ +import CompanionCore +import SwiftUI + +private struct SpinnerRing: View { + let label: String + var active = false + @State private var spinning = false + + var body: some View { + ZStack { + Circle().stroke(Color.primary.opacity(0.15), lineWidth: 2) + if active { + Circle() + .trim(from: 0, to: 0.28) + .stroke(Color.secondary, style: StrokeStyle(lineWidth: 2, lineCap: .round)) + .rotationEffect(.degrees(spinning ? 360 : 0)) + .animation(.linear(duration: 1.1).repeatForever(autoreverses: false), value: spinning) + } + Text(label).font(.system(size: 10.5, weight: .semibold)).monospacedDigit() + } + .frame(width: 24, height: 24) + .onAppear { spinning = true } + } +} + +private struct DoneBadge: View { + var body: some View { + Image(systemName: "checkmark") + .font(.system(size: 11, weight: .heavy)) + .foregroundStyle(.white) + .frame(width: 22, height: 22) + .background(Color.green, in: Circle()) + .transition(.scale(scale: 0.5).combined(with: .opacity)) + } +} + +/// The Agent's plan as capsule rows: status badge, label, step counter and a status pill; rows expand for details. +struct TaskRowsView: View { + let tasks: [PlanTask] + @State private var open: Set = [] + + var body: some View { + VStack(spacing: 8) { + ForEach(tasks) { task in row(task) } + } + .animation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.3), value: open) + .animation(.easeOut(duration: 0.25), value: tasks) + } + + private func row(_ task: PlanTask) -> some View { + let isOpen = open.contains(task.id) + return VStack(spacing: 0) { + Button { + if isOpen { open.remove(task.id) } else { open.insert(task.id) } + } label: { + HStack(spacing: 10) { + badge(task) + Text(task.label).font(.system(size: 13, weight: .medium)).lineLimit(1) + Spacer(minLength: 4) + Text("\(task.id + 1)/\(tasks.count)") + .font(.system(size: 12.5)) + .monospacedDigit() + .foregroundStyle(.secondary) + if task.status == .completed { + Text("已完成") + .font(.system(size: 11.5, weight: .medium)) + .foregroundStyle(.green) + .padding(.horizontal, 8) + .frame(height: 22) + .background(Color.green.opacity(0.12), in: Capsule()) + } + Image(systemName: "chevron.down") + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(.tertiary) + .rotationEffect(.degrees(isOpen ? 180 : 0)) + } + .padding(.horizontal, 10) + .frame(height: 44) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + if isOpen { + HStack(alignment: .top, spacing: 10) { + Rectangle().fill(Color.primary.opacity(0.12)).frame(width: 1).padding(.leading, 21) + VStack(alignment: .leading, spacing: 6) { + detail("状态", statusText(task.status)) + if let priority = task.priority { detail("优先级", priorityText(priority)) } + } + .padding(.trailing, 12) + } + .padding(.bottom, 10) + .transition(.opacity.combined(with: .move(edge: .top))) + } + } + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: isOpen ? 14 : 22)) + .overlay(RoundedRectangle(cornerRadius: isOpen ? 14 : 22).stroke(Color.primary.opacity(0.06))) + .clipShape(RoundedRectangle(cornerRadius: isOpen ? 14 : 22)) + } + + @ViewBuilder + private func badge(_ task: PlanTask) -> some View { + switch task.status { + case .completed: DoneBadge() + case .running: SpinnerRing(label: "\(task.id + 1)", active: true) + case .pending: SpinnerRing(label: "\(task.id + 1)") + } + } + + private func detail(_ name: String, _ value: String) -> some View { + HStack { + Text(name).foregroundStyle(.secondary) + Spacer() + Text(value).foregroundStyle(.tertiary) + } + .font(.system(size: 12)) + } + + private func statusText(_ status: PlanTask.Status) -> String { + switch status { + case .completed: "已完成" + case .running: "进行中" + case .pending: "待开始" + } + } + + private func priorityText(_ priority: String) -> String { + switch priority { + case "high": "高" + case "medium": "中" + case "low": "低" + default: priority + } + } +} + +/// Where the plan lives on the conversation page: a capsule above the prompt bar that opens the full list. +struct TaskDock: View { + let tasks: [PlanTask] + let running: Bool + @State private var expanded = false + + private var completed: Int { tasks.filter { $0.status == .completed }.count } + private var current: PlanTask? { tasks.first { $0.status == .running } ?? tasks.first { $0.status == .pending } } + private var finished: Bool { completed == tasks.count } + + var body: some View { + VStack(spacing: 8) { + if expanded { + ScrollView { TaskRowsView(tasks: tasks).padding(.vertical, 2) } + .frame(maxHeight: 260) + .fixedSize(horizontal: false, vertical: true) + .transition(.scale(scale: 0.98, anchor: .bottom).combined(with: .opacity)) + } + Button { + withAnimation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.3)) { expanded.toggle() } + } label: { + HStack(spacing: 10) { + if finished { + DoneBadge() + } else if running { + PixelLoader() + } else { + Image(systemName: "list.bullet").font(.system(size: 12)).foregroundStyle(.secondary) + } + Text("任务 \(completed)/\(tasks.count)").font(.system(size: 13, weight: .semibold)).monospacedDigit() + Text(finished ? "已全部完成" : (current?.label ?? "")) + .font(.system(size: 12.5)) + .foregroundStyle(.secondary) + .lineLimit(1) + Spacer(minLength: 0) + Image(systemName: "chevron.up") + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(.tertiary) + .rotationEffect(.degrees(expanded ? 180 : 0)) + } + .padding(.horizontal, 14) + .frame(height: 40) + .background(Color(.secondarySystemGroupedBackground), in: Capsule()) + .overlay(Capsule().stroke(Color.primary.opacity(0.06))) + .contentShape(Capsule()) + } + .buttonStyle(.plain) + } + } +} diff --git a/mobile/ios/App/ThinkingView.swift b/mobile/ios/App/ThinkingView.swift new file mode 100644 index 000000000..e55087cd6 --- /dev/null +++ b/mobile/ios/App/ThinkingView.swift @@ -0,0 +1,64 @@ +import CompanionCore +import SwiftUI + +/// Expandable reasoning the Agent produced before answering. +/// Open while work is in progress, then settles and stays expandable. +struct ThinkingView: View { + let item: TimelineItem + let working: Bool + @State private var manual: Bool? + + private var expanded: Bool { manual ?? working } + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + Button { + withAnimation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.4)) { manual = !expanded } + } label: { + HStack(spacing: 8) { + Image(systemName: "sparkle") + .font(.system(size: 13)) + .foregroundStyle(working ? Color.primary.opacity(0.7) : Color.secondary) + if working { + ShimmerText(text: workingLabel) + } else { + Text(doneLabel).foregroundStyle(.secondary) + } + Image(systemName: "chevron.down") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.tertiary) + .rotationEffect(.degrees(expanded ? 180 : 0)) + } + .font(.system(size: 13, weight: .medium)) + .padding(.vertical, 4) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + + if expanded { + HStack(alignment: .top, spacing: 12) { + Rectangle().fill(Color.primary.opacity(0.12)).frame(width: 1) + VStack(alignment: .leading, spacing: 6) { + if !item.thinking.isEmpty { + Text(item.thinking) + .font(.system(size: 12.5)) + .foregroundStyle(.secondary) + .lineSpacing(3) + .textSelection(.enabled) + } + } + .padding(.vertical, 2) + } + .padding(.leading, 6) + .transition(.opacity.combined(with: .move(edge: .top))) + } + } + } + + private var workingLabel: String { "思考中" } + + private var doneLabel: String { + if let ms = item.durationMs, ms >= 1000 { return "思考了 \(ms / 1000) 秒" } + return "已思考" + } +} diff --git a/mobile/ios/App/ToolChips.swift b/mobile/ios/App/ToolChips.swift new file mode 100644 index 000000000..abaf466a7 --- /dev/null +++ b/mobile/ios/App/ToolChips.swift @@ -0,0 +1,174 @@ +import CompanionCore +import SwiftUI + +/// An agent run as compact rows: tool calls with inline chips, then file-diff chips for the edits. +struct ToolChipsView: View { + let item: TimelineItem + let working: Bool + let openDiff: (FileChangeItem) -> Void + + @State private var runOpen = true + @State private var openRows: Set = [] + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + if !item.tools.isEmpty { + Button { + withAnimation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.3)) { runOpen.toggle() } + } label: { + HStack(spacing: 6) { + Image(systemName: "chevron.down") + .font(.system(size: 10, weight: .bold)) + .rotationEffect(.degrees(runOpen ? 0 : -90)) + Text("\(item.tools.count) 次工具调用").monospacedDigit() + } + .font(.system(size: 12.5)) + .foregroundStyle(.secondary) + .padding(.vertical, 4) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + if runOpen { + VStack(alignment: .leading, spacing: 6) { + ForEach(item.tools) { tool in toolRow(tool) } + } + .transition(.opacity.combined(with: .move(edge: .top))) + } + } + if !item.changes.isEmpty { + Divider().padding(.top, 8) + FlowLayout(spacing: 6) { + ForEach(item.changes.prefix(Self.visibleChanges)) { change in + Button { openDiff(change) } label: { + HStack(spacing: 8) { + Text((change.path as NSString).lastPathComponent).lineLimit(1) + if let additions = change.additions { Text("+\(additions)").foregroundStyle(.green) } + if let deletions = change.deletions, deletions > 0 { + Text("−\(deletions)").foregroundStyle(.red) + } + } + .font(.system(size: 12, design: .monospaced)) + .padding(.horizontal, 10) + .frame(height: 30) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 9, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 9, style: .continuous).stroke(Color.primary.opacity(0.08))) + } + .buttonStyle(.plain) + .accessibilityLabel("查看 \(change.path) 的差异") + } + if item.changes.count > Self.visibleChanges { + Text("+\(item.changes.count - Self.visibleChanges)") + .font(.system(size: 11.5, design: .monospaced)) + .foregroundStyle(.tertiary) + .frame(height: 28) + .padding(.horizontal, 6) + } + } + .padding(.top, 2) + } + } + } + + private static let visibleChanges = 6 + + private func toolRow(_ tool: ToolStep) -> some View { + let isOpen = openRows.contains(tool.id) + return VStack(alignment: .leading, spacing: 2) { + Button { + withAnimation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.3)) { + if isOpen { openRows.remove(tool.id) } else { openRows.insert(tool.id) } + } + } label: { + HStack(spacing: 8) { + ZStack { + if tool.isFinished || !working { + Image(systemName: icon(for: tool.name)).font(.system(size: 12)) + } else { + ProgressView().controlSize(.mini) + } + } + .foregroundStyle(.tertiary) + .frame(width: 16) + Text(tool.label) + .font(.system(size: 13, weight: .semibold)) + .lineLimit(1) + .fixedSize() + Text(tool.preview ?? " ") + .font(.system(size: 12.5, design: .monospaced)) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.tail) + .padding(.horizontal, 10) + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: 30) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 9, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 9, style: .continuous).stroke(Color.primary.opacity(0.06))) + .opacity(tool.preview == nil ? 0 : 1) + } + .frame(minHeight: 34) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + if isOpen && !tool.detail.isEmpty { + VStack(alignment: .leading, spacing: 2) { + ForEach(Array(tool.detail.enumerated()), id: \.offset) { _, line in + Text(line) + .font(.system(size: 11.5, design: .monospaced)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + .padding(.leading, 12) + .padding(.vertical, 2) + .overlay(alignment: .leading) { Rectangle().fill(Color.primary.opacity(0.12)).frame(width: 1) } + .padding(.leading, 8) + .transition(.opacity.combined(with: .move(edge: .top))) + } + } + } + + private func icon(for name: String) -> String { + let lowered = name.lowercased() + if lowered.contains("read") || lowered.contains("view") { return "doc.text" } + if lowered.contains("edit") || lowered.contains("write") || lowered.contains("patch") { return "pencil" } + if lowered.contains("run") || lowered.contains("bash") || lowered.contains("exec") || lowered.contains("shell") { + return "terminal" + } + if lowered.contains("search") || lowered.contains("grep") || lowered.contains("find") { return "magnifyingglass" } + return "wrench.and.screwdriver" + } +} + +/// Wraps its children onto new lines when a row is full. +private struct FlowLayout: Layout { + var spacing: CGFloat + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + arrange(width: proposal.width ?? .infinity, subviews: subviews).size + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + let result = arrange(width: bounds.width, subviews: subviews) + for (index, origin) in result.origins.enumerated() { + subviews[index].place(at: CGPoint(x: bounds.minX + origin.x, y: bounds.minY + origin.y), proposal: .unspecified) + } + } + + private func arrange(width: CGFloat, subviews: Subviews) -> (size: CGSize, origins: [CGPoint]) { + var origins: [CGPoint] = [] + var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, maxX: CGFloat = 0 + for subview in subviews { + let size = subview.sizeThatFits(.unspecified) + if x > 0 && x + size.width > width { + x = 0 + y += rowHeight + spacing + rowHeight = 0 + } + origins.append(CGPoint(x: x, y: y)) + x += size.width + spacing + rowHeight = max(rowHeight, size.height) + maxX = max(maxX, x - spacing) + } + return (CGSize(width: maxX, height: y + rowHeight), origins) + } +} diff --git a/mobile/ios/App/VibeXCompanionApp.swift b/mobile/ios/App/VibeXCompanionApp.swift new file mode 100644 index 000000000..d39acf3d2 --- /dev/null +++ b/mobile/ios/App/VibeXCompanionApp.swift @@ -0,0 +1,13 @@ +import SwiftUI + +@main +struct VibeXCompanionApp: App { + @State private var servers = ServerStore() + + var body: some Scene { + WindowGroup { + RootTabView() + .environment(servers) + } + } +} diff --git a/mobile/ios/Info.plist b/mobile/ios/Info.plist new file mode 100644 index 000000000..5f79bf11e --- /dev/null +++ b/mobile/ios/Info.plist @@ -0,0 +1,19 @@ + + + + + NSAppTransportSecurity + + NSAllowsLocalNetworking + + + NSCameraUsageDescription + 扫描电脑上的配对二维码 + NSSupportsLiveActivities + + NSSupportsLiveActivitiesFrequentUpdates + + NSLocalNetworkUsageDescription + 连接局域网内的 VibeX 电脑 + + diff --git a/mobile/ios/README.md b/mobile/ios/README.md index 935d57553..fd73b283c 100644 --- a/mobile/ios/README.md +++ b/mobile/ios/README.md @@ -8,3 +8,7 @@ Wire models come from `docs/protocol/v1/generated/swift/RemoteProtocolModels.swi # pairing client and scope tests; needs a Swift 6 toolchain swift test ``` + +## Run in Xcode + +Open `VibeXCompanion.xcodeproj`, choose the `VibeXCompanion` scheme and an iPhone simulator (iOS 17+), then Run. Pair with a Host using its Host origin and one-time pairing token. diff --git a/mobile/ios/Shared/TaskActivityAttributes.swift b/mobile/ios/Shared/TaskActivityAttributes.swift new file mode 100644 index 000000000..f06bc3b00 --- /dev/null +++ b/mobile/ios/Shared/TaskActivityAttributes.swift @@ -0,0 +1,16 @@ +import ActivityKit +import Foundation + +/// Live Activity for an Agent run (task list progress, or the current step when there is none): Dynamic Island on supporting iPhones, Lock Screen otherwise. +struct TaskActivityAttributes: ActivityAttributes { + struct ContentState: Codable, Hashable { + var completed: Int + var total: Int + var currentTask: String + var isRunning: Bool + /// When the current run began; drives the elapsed timer shown while there is no task list. + var startedAt: Date + } + + var conversationTitle: String +} diff --git a/mobile/ios/TaskWidget/TaskActivityWidget.swift b/mobile/ios/TaskWidget/TaskActivityWidget.swift new file mode 100644 index 000000000..e11a65db7 --- /dev/null +++ b/mobile/ios/TaskWidget/TaskActivityWidget.swift @@ -0,0 +1,142 @@ +import ActivityKit +import SwiftUI +import WidgetKit + +@main +struct VibeXTaskWidgetBundle: WidgetBundle { + var body: some Widget { TaskActivityWidget() } +} + +struct TaskActivityWidget: Widget { + var body: some WidgetConfiguration { + ActivityConfiguration(for: TaskActivityAttributes.self) { context in + LockScreenTaskView(title: context.attributes.conversationTitle, state: context.state, stale: context.isStale) + .padding(16) + .activityBackgroundTint(Color(.systemBackground).opacity(0.85)) + } dynamicIsland: { context in + DynamicIsland { + DynamicIslandExpandedRegion(.leading) { + TaskRing(state: context.state, size: 30).padding(.leading, 6).padding(.top, 2) + } + DynamicIslandExpandedRegion(.trailing) { + ProgressLabel(state: context.state, size: 17).padding(.trailing, 6).padding(.top, 2) + } + DynamicIslandExpandedRegion(.bottom) { + VStack(alignment: .leading, spacing: 6) { + Text(context.attributes.conversationTitle) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(.secondary) + .lineLimit(1) + Text(context.isStale && context.state.isRunning ? staleNote : context.state.currentTask) + .font(.system(size: 15, weight: .medium)) + .lineLimit(2) + .multilineTextAlignment(.leading) + if context.state.total > 0 { TaskProgressBar(state: context.state).padding(.top, 2) } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 6) + .padding(.top, 6) + } + } compactLeading: { + TaskRing(state: context.state, size: 18) + } compactTrailing: { + ProgressLabel(state: context.state, size: 13) + } minimal: { + TaskRing(state: context.state, size: 18) + } + } + } +} + +private let staleNote = "已暂停同步,打开 App 查看最新进度" + +private struct LockScreenTaskView: View { + let title: String + let state: TaskActivityAttributes.ContentState + let stale: Bool + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + HStack(spacing: 10) { + TaskRing(state: state, size: 24) + Text(title).font(.system(size: 14, weight: .semibold)).lineLimit(1) + Spacer() + ProgressLabel(state: state, size: 14).foregroundStyle(.secondary) + } + Text(stale && state.isRunning ? staleNote : state.currentTask) + .font(.system(size: 13)) + .foregroundStyle(.secondary) + .lineLimit(2) + if state.total > 0 { TaskProgressBar(state: state) } + } + } +} + +/// `completed/total` for a task list, otherwise the elapsed time of the run. +private struct ProgressLabel: View { + let state: TaskActivityAttributes.ContentState + let size: CGFloat + + var body: some View { + Group { + if state.total > 0 { + Text("\(state.completed)/\(state.total)") + } else if state.isRunning { + Text(state.startedAt, style: .timer).frame(maxWidth: 52, alignment: .trailing) + } else { + Text("完成") + } + } + .font(.system(size: size, weight: .semibold)) + .monospacedDigit() + } +} + +private struct TaskRing: View { + let state: TaskActivityAttributes.ContentState + let size: CGFloat + + private var fraction: Double { + state.total == 0 ? 0 : Double(state.completed) / Double(state.total) + } + + var body: some View { + if state.total == 0 && state.isRunning { + ProgressView().frame(width: size, height: size) + } else { + ring + } + } + + private var ring: some View { + ZStack { + Circle().stroke(Color.primary.opacity(0.18), lineWidth: 2.5) + Circle() + .trim(from: 0, to: max(0.04, fraction)) + .stroke(finished ? Color.green : Color.primary, style: StrokeStyle(lineWidth: 2.5, lineCap: .round)) + .rotationEffect(.degrees(-90)) + if finished { + Image(systemName: "checkmark").font(.system(size: size * 0.4, weight: .bold)).foregroundStyle(.green) + } + } + .frame(width: size, height: size) + } + + private var finished: Bool { !state.isRunning && state.completed >= state.total } +} + +private struct TaskProgressBar: View { + let state: TaskActivityAttributes.ContentState + + var body: some View { + GeometryReader { proxy in + ZStack(alignment: .leading) { + Capsule().fill(Color.primary.opacity(0.15)) + Capsule() + .fill(Color.primary) + .frame(width: proxy.size.width * (state.total == 0 ? 0 : Double(state.completed) / Double(state.total))) + } + } + .frame(height: 4) + } +} diff --git a/mobile/ios/TaskWidgetInfo.plist b/mobile/ios/TaskWidgetInfo.plist new file mode 100644 index 000000000..0f118fb75 --- /dev/null +++ b/mobile/ios/TaskWidgetInfo.plist @@ -0,0 +1,11 @@ + + + + + NSExtension + + NSExtensionPointIdentifier + com.apple.widgetkit-extension + + + diff --git a/mobile/ios/VibeXCompanion.xcodeproj/project.pbxproj b/mobile/ios/VibeXCompanion.xcodeproj/project.pbxproj new file mode 100644 index 000000000..4b3641e52 --- /dev/null +++ b/mobile/ios/VibeXCompanion.xcodeproj/project.pbxproj @@ -0,0 +1,396 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXBuildFile section */ + A10000000000000000000003 /* CompanionCore in Frameworks */ = {isa = PBXBuildFile; productRef = A10000000000000000000007 /* CompanionCore */; }; + A10000000000000000000021 /* VibeXTaskWidget.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = A10000000000000000000020 /* VibeXTaskWidget.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + A10000000000000000000025 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A10000000000000000000010 /* Project object */; + proxyType = 1; + remoteGlobalIDString = A10000000000000000000026; + remoteInfo = VibeXTaskWidget; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + A10000000000000000000027 /* Embed Foundation Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 13; + files = ( + A10000000000000000000021 /* VibeXTaskWidget.appex in Embed Foundation Extensions */, + ); + name = "Embed Foundation Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + A10000000000000000000001 /* VibeXCompanion.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = VibeXCompanion.app; sourceTree = BUILT_PRODUCTS_DIR; }; + A10000000000000000000009 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A10000000000000000000020 /* VibeXTaskWidget.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = VibeXTaskWidget.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + A10000000000000000000022 /* TaskWidgetInfo.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = TaskWidgetInfo.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + A10000000000000000000002 /* App */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = App; + sourceTree = ""; + }; + A10000000000000000000023 /* TaskWidget */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = TaskWidget; + sourceTree = ""; + }; + A10000000000000000000024 /* Shared */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = Shared; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + A10000000000000000000004 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A10000000000000000000003 /* CompanionCore in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A10000000000000000000029 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + A10000000000000000000005 = { + isa = PBXGroup; + children = ( + A10000000000000000000002 /* App */, + A10000000000000000000023 /* TaskWidget */, + A10000000000000000000024 /* Shared */, + A10000000000000000000009 /* Info.plist */, + A10000000000000000000022 /* TaskWidgetInfo.plist */, + A1000000000000000000000A /* Products */, + ); + sourceTree = ""; + }; + A1000000000000000000000A /* Products */ = { + isa = PBXGroup; + children = ( + A10000000000000000000001 /* VibeXCompanion.app */, + A10000000000000000000020 /* VibeXTaskWidget.appex */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + A1000000000000000000000B /* VibeXCompanion */ = { + isa = PBXNativeTarget; + buildConfigurationList = A1000000000000000000000F /* Build configuration list for PBXNativeTarget "VibeXCompanion" */; + buildPhases = ( + A1000000000000000000000C /* Sources */, + A10000000000000000000004 /* Frameworks */, + A1000000000000000000000D /* Resources */, + A10000000000000000000027 /* Embed Foundation Extensions */, + ); + buildRules = ( + ); + dependencies = ( + A10000000000000000000028 /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + A10000000000000000000002 /* App */, + A10000000000000000000024 /* Shared */, + ); + name = VibeXCompanion; + packageProductDependencies = ( + A10000000000000000000007 /* CompanionCore */, + ); + productName = VibeXCompanion; + productReference = A10000000000000000000001 /* VibeXCompanion.app */; + productType = "com.apple.product-type.application"; + }; + A10000000000000000000026 /* VibeXTaskWidget */ = { + isa = PBXNativeTarget; + buildConfigurationList = A1000000000000000000002E /* Build configuration list for PBXNativeTarget "VibeXTaskWidget" */; + buildPhases = ( + A1000000000000000000002B /* Sources */, + A10000000000000000000029 /* Frameworks */, + A1000000000000000000002A /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + A10000000000000000000023 /* TaskWidget */, + A10000000000000000000024 /* Shared */, + ); + name = VibeXTaskWidget; + productName = VibeXTaskWidget; + productReference = A10000000000000000000020 /* VibeXTaskWidget.appex */; + productType = "com.apple.product-type.app-extension"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + A10000000000000000000010 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 2700; + LastUpgradeCheck = 2700; + }; + buildConfigurationList = A10000000000000000000011 /* Build configuration list for PBXProject "VibeXCompanion" */; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + "zh-Hans", + Base, + ); + mainGroup = A10000000000000000000005; + minimizedProjectReferenceProxies = 1; + packageReferences = ( + A10000000000000000000006 /* XCLocalSwiftPackageReference "." */, + ); + preferredProjectObjectVersion = 77; + productRefGroup = A1000000000000000000000A /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + A1000000000000000000000B /* VibeXCompanion */, + A10000000000000000000026 /* VibeXTaskWidget */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + A1000000000000000000000D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A1000000000000000000002A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + A1000000000000000000000C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A1000000000000000000002B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + A10000000000000000000028 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = A10000000000000000000026 /* VibeXTaskWidget */; + targetProxy = A10000000000000000000025 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + A10000000000000000000012 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ENABLE_MODULES = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + A10000000000000000000013 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ENABLE_MODULES = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + A10000000000000000000014 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = VibeX; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortraitUpsideDown"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.vibex.companion.ios; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 1; + }; + name = Debug; + }; + A10000000000000000000015 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = VibeX; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortraitUpsideDown"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.vibex.companion.ios; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 1; + }; + name = Release; + }; + A1000000000000000000002C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = TaskWidgetInfo.plist; + INFOPLIST_KEY_CFBundleDisplayName = "VibeX 任务"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.vibex.companion.ios.TaskWidget; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 1; + }; + name = Debug; + }; + A1000000000000000000002D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = TaskWidgetInfo.plist; + INFOPLIST_KEY_CFBundleDisplayName = "VibeX 任务"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.vibex.companion.ios.TaskWidget; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 1; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + A1000000000000000000000F /* Build configuration list for PBXNativeTarget "VibeXCompanion" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A10000000000000000000014 /* Debug */, + A10000000000000000000015 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A10000000000000000000011 /* Build configuration list for PBXProject "VibeXCompanion" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A10000000000000000000012 /* Debug */, + A10000000000000000000013 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A1000000000000000000002E /* Build configuration list for PBXNativeTarget "VibeXTaskWidget" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A1000000000000000000002C /* Debug */, + A1000000000000000000002D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + A10000000000000000000006 /* XCLocalSwiftPackageReference "." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = .; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + A10000000000000000000007 /* CompanionCore */ = { + isa = XCSwiftPackageProductDependency; + productName = CompanionCore; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = A10000000000000000000010 /* Project object */; +}