diff --git a/apps/swift-ios/.gitignore b/apps/swift-ios/.gitignore new file mode 100644 index 0000000000..9a2d42b10d --- /dev/null +++ b/apps/swift-ios/.gitignore @@ -0,0 +1,4 @@ +.derivedData/ +DerivedData/ +*.xcuserstate +xcuserdata/ diff --git a/apps/swift-ios/App/NativeFeatureClient.swift b/apps/swift-ios/App/NativeFeatureClient.swift new file mode 100644 index 0000000000..11493ef9d4 --- /dev/null +++ b/apps/swift-ios/App/NativeFeatureClient.swift @@ -0,0 +1,1088 @@ +import Foundation + +/// Composes the transport-focused Core layer with the UI-focused Features layer. +@MainActor +final class NativeFeatureClient: FeatureClient { + private let runtime: EnvironmentRuntime + private let settingsStore: UserDefaults + private let stream: AsyncStream + private let continuation: AsyncStream.Continuation + + private var activeEnvironment: Environment? + private var client: T3Client? + private var latestShell: OrchestrationShellSnapshot? + private var archivedThreads: [FeatureThread] = [] + private var latestSnapshot: FeatureSnapshot? + private var loadedThreadIDs = Set() + private var latestDetails: [String: FeatureThreadDetail] = [:] + private var approvalThreadIDs: [String: String] = [:] + private var inputThreadIDs: [String: String] = [:] + private var terminalIDs: [String: String] = [:] + private var terminalSnapshots: [String: FeatureTerminalSnapshot] = [:] + private var terminalContinuations: [ + String: [UUID: AsyncStream.Continuation] + ] = [:] + private var pollingTask: Task? + + init( + runtime: EnvironmentRuntime = EnvironmentRuntime(), + settingsStore: UserDefaults = .standard + ) { + self.runtime = runtime + self.settingsStore = settingsStore + let pair = AsyncStream.makeStream() + stream = pair.stream + continuation = pair.continuation + } + + deinit { + pollingTask?.cancel() + continuation.finish() + } + + func initialSnapshot() async throws -> FeatureSnapshot { + let environments = try await runtime.environments() + guard let environment = try await runtime.activeEnvironment(), + let activeClient = try await runtime.activeClient() else { + let snapshot = disconnectedSnapshot(environments: environments) + latestSnapshot = snapshot + return snapshot + } + + activeEnvironment = environment + client = activeClient + async let shellRequest = activeClient.shellSnapshot() + async let readModelRequest = activeClient.readModel() + let (shell, readModel) = try await (shellRequest, readModelRequest) + latestShell = shell + archivedThreads = readModel.threads + .filter { $0.archivedAt != nil } + .map(mapThread) + startPolling(activeClient) + let snapshot = makeSnapshot( + shell: shell, + environments: environments, + activeEnvironment: environment + ) + latestSnapshot = snapshot + return snapshot + } + + func events() -> AsyncStream { + stream + } + + func pair(endpoint: String, token: String?) async throws { + let pairedClient: T3Client + if let token, !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + pairedClient = try await runtime.pair( + host: endpoint, + code: token, + clientLabel: "T3 Code Swift" + ) + } else { + pairedClient = try await runtime.pair(url: endpoint, clientLabel: "T3 Code Swift") + } + activeEnvironment = pairedClient.environment + client = pairedClient + loadedThreadIDs.removeAll() + latestDetails.removeAll() + archivedThreads.removeAll() + startPolling(pairedClient) + } + + func activateEnvironment(id: String) async throws { + pollingTask?.cancel() + let activated = try await runtime.activate(id: id) + activeEnvironment = activated.environment + client = activated + loadedThreadIDs.removeAll() + latestDetails.removeAll() + latestShell = nil + archivedThreads.removeAll() + finishTerminalStreams() + terminalIDs.removeAll() + terminalSnapshots.removeAll() + startPolling(activated) + } + + func removeEnvironment(id: String) async throws { + if activeEnvironment?.id == id { + pollingTask?.cancel() + pollingTask = nil + client = nil + activeEnvironment = nil + latestShell = nil + archivedThreads.removeAll() + loadedThreadIDs.removeAll() + latestDetails.removeAll() + finishTerminalStreams() + terminalIDs.removeAll() + terminalSnapshots.removeAll() + } + try await runtime.remove(id: id) + } + + func disconnect() async { + pollingTask?.cancel() + pollingTask = nil + if let client { + await client.disconnect() + } + client = nil + activeEnvironment = nil + latestShell = nil + archivedThreads.removeAll() + loadedThreadIDs.removeAll() + latestDetails.removeAll() + finishTerminalStreams() + terminalIDs.removeAll() + terminalSnapshots.removeAll() + } + + func addProject(path: String) async throws { + let client = try requireClient() + let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { + throw NativeFeatureClientError.invalidProjectPath + } + let title = URL(fileURLWithPath: trimmed).lastPathComponent + _ = try await client.createProject( + title: title.isEmpty ? "Project" : title, + workspaceRoot: trimmed, + defaultModel: defaultModelSelection() + ) + try await refresh(client: client) + } + + func createThread( + projectID: String, + title: String?, + selection: FeatureSelection? + ) async throws -> FeatureThread { + let client = try requireClient() + let threadID = UUID().uuidString + let model = modelSelection(selection, projectID: projectID) + let resolvedTitle = title?.trimmingCharacters(in: .whitespacesAndNewlines) + let threadTitle = resolvedTitle?.isEmpty == false ? resolvedTitle! : "New thread" + _ = try await client.createThread( + threadID: threadID, + projectID: projectID, + title: threadTitle, + model: model, + runtimeMode: .fullAccess + ) + let shell = try await client.shellSnapshot() + latestShell = shell + if let created = shell.threads.first(where: { $0.id == threadID }) { + let mapped = mapThread(created) + await emitSnapshot(shell) + return mapped + } + await emitSnapshot(shell) + return FeatureThread( + id: threadID, + projectID: projectID, + title: threadTitle, + providerID: model.instanceId, + modelID: model.model + ) + } + + func renameThread(id: String, title: String) async throws { + let client = try requireClient() + _ = try await client.rename(threadID: id, title: title) + try await refresh(client: client) + } + + func setThreadArchived(id: String, archived: Bool) async throws { + let client = try requireClient() + _ = try await client.archive(threadID: id, archived: archived) + try await refresh(client: client, includeArchived: true) + } + + func setThreadSettled(id: String, settled: Bool) async throws { + let client = try requireClient() + _ = try await client.settle(threadID: id, settled: settled) + try await refresh(client: client) + } + + func setThreadSnoozed(id: String, until: Date?) async throws { + let client = try requireClient() + _ = try await client.snooze(threadID: id, until: until) + try await refresh(client: client) + } + + func setRuntimeMode(id: String, mode: FeatureRuntimeMode) async throws { + let client = try requireClient() + _ = try await client.setRuntimeMode(threadID: id, mode: coreRuntimeMode(mode)) + try await refresh(client: client) + if loadedThreadIDs.contains(id) { + try await refreshThread(id: id, client: client) + } + } + + func setInteractionMode(id: String, mode: FeatureInteractionMode) async throws { + let client = try requireClient() + _ = try await client.setInteractionMode(threadID: id, mode: coreInteractionMode(mode)) + try await refresh(client: client) + if loadedThreadIDs.contains(id) { + try await refreshThread(id: id, client: client) + } + } + + func deleteThread(id: String) async throws { + let client = try requireClient() + _ = try await client.delete(threadID: id) + loadedThreadIDs.remove(id) + latestDetails[id] = nil + try await refresh(client: client, includeArchived: true) + } + + func loadThread(id: String) async throws -> FeatureThreadDetail { + let client = try requireClient() + loadedThreadIDs.insert(id) + let snapshot = try await client.threadSnapshot(id: id) + let detail = mapDetail(snapshot.thread) + latestDetails[id] = detail + return detail + } + + func sendMessage( + threadID: String, + text: String, + selection: FeatureSelection? + ) async throws { + let client = try requireClient() + guard let shellThread = latestShell?.threads.first(where: { $0.id == threadID }) else { + throw NativeFeatureClientError.threadNotFound + } + + if let selection, + selection.providerID != shellThread.modelSelection.instanceId + || selection.modelID != shellThread.modelSelection.model { + _ = try await client.dispatch( + .object([ + "type": .string("thread.meta.update"), + "commandId": .string(UUID().uuidString), + "threadId": .string(threadID), + "modelSelection": try .encode( + ModelSelection(instanceId: selection.providerID, model: selection.modelID) + ), + ]) + ) + } + + _ = try await client.sendTurn( + threadID: threadID, + text: text, + runtimeMode: shellThread.runtimeMode, + interactionMode: shellThread.interactionMode + ) + try await refreshThread(id: threadID, client: client) + try await refresh(client: client) + } + + func cancelTurn(threadID: String) async throws { + let client = try requireClient() + let turnID = latestShell?.threads + .first(where: { $0.id == threadID })? + .latestTurn? + .turnId + _ = try await client.interrupt(threadID: threadID, turnID: turnID) + try await refresh(client: client) + } + + func resolveApproval(id: String, decision: FeatureApprovalDecision) async throws { + let client = try requireClient() + guard let threadID = approvalThreadIDs[id] else { + throw NativeFeatureClientError.approvalNotFound + } + let wireDecision = switch decision { + case .allowOnce: "accept" + case .allowForSession: "acceptForSession" + case .deny: "decline" + } + _ = try await client.respondToApproval( + threadID: threadID, + requestID: id, + decision: wireDecision + ) + try await refreshThread(id: threadID, client: client) + } + + func resolveUserInput(id: String, answers: [String: String]) async throws { + let client = try requireClient() + guard let threadID = inputThreadIDs[id] else { + throw NativeFeatureClientError.inputRequestNotFound + } + _ = try await client.respondToUserInput( + threadID: threadID, + requestID: id, + answers: answers.mapValues(JSONValue.string) + ) + try await refreshThread(id: threadID, client: client) + } + + func saveSettings(_ settings: FeatureSettings) async throws { + let data = try JSONEncoder().encode(settings) + settingsStore.set(data, forKey: Self.settingsKey) + } + + func listFiles(threadID: String, path: String?) async throws -> [FeatureFileEntry] { + let client = try requireClient() + let context = try workspaceContext(threadID: threadID) + let result = try await client.listProjectEntries(cwd: context.cwd) + return NativeWorkspaceMapper.files(result.entries, directory: path) + } + + func readFile(threadID: String, path: String) async throws -> FeatureFileContent { + let client = try requireClient() + let context = try workspaceContext(threadID: threadID) + let result = try await client.readProjectFile( + cwd: context.cwd, + relativePath: path + ) + return FeatureFileContent( + path: result.relativePath, + text: result.contents, + language: NativeWorkspaceMapper.language(for: result.relativePath), + isTruncated: result.truncated, + totalBytes: result.byteLength + ) + } + + func loadReview(threadID: String) async throws -> FeatureReview { + let client = try requireClient() + let context = try workspaceContext(threadID: threadID) + let preview = try await client.reviewDiffPreview(cwd: context.cwd) + return NativeWorkspaceMapper.review(preview) + } + + func sourceControlStatus(threadID: String) async throws -> FeatureSourceControlStatus { + let client = try requireClient() + let context = try workspaceContext(threadID: threadID) + return NativeWorkspaceMapper.sourceControl( + try await client.refreshVCSStatus(cwd: context.cwd) + ) + } + + func performSourceControlAction( + threadID: String, + action: FeatureSourceControlAction, + message: String? + ) async throws -> FeatureSourceControlStatus { + let client = try requireClient() + let context = try workspaceContext(threadID: threadID) + + if action == .pull { + _ = try await client.pull(cwd: context.cwd) + } else { + let progress = try await client.runGitAction( + cwd: context.cwd, + action: NativeWorkspaceMapper.gitAction(action), + commitMessage: message + ) + for try await event in progress { + if event.kind == "action_failed" { + throw RPCError.remote(event.message ?? "The source-control action failed.") + } + } + } + + return NativeWorkspaceMapper.sourceControl( + try await client.refreshVCSStatus(cwd: context.cwd) + ) + } + + func terminalSnapshot(threadID: String) async throws -> FeatureTerminalSnapshot { + if let snapshot = terminalSnapshots[threadID] { + return snapshot + } + let context = try workspaceContext(threadID: threadID) + return FeatureTerminalSnapshot( + threadID: threadID, + workingDirectory: context.cwd + ) + } + + func terminalEvents(threadID: String) -> AsyncStream { + guard let client else { + return AsyncStream { continuation in continuation.finish() } + } + return AsyncStream { continuation in + let subscriptionID = UUID() + terminalContinuations[threadID, default: [:]][subscriptionID] = continuation + if let snapshot = terminalSnapshots[threadID] { + continuation.yield(snapshot) + } + let task = Task { [weak self] in + do { + for try await event in await client.terminalEvents() { + guard !Task.isCancelled else { break } + guard let self else { break } + guard event.threadId == threadID else { continue } + if let terminalID = self.terminalIDs[threadID], + event.terminalId != nil, + event.terminalId != terminalID { + continue + } + let snapshot = self.consumeTerminalEvent(event, threadID: threadID) + self.publishTerminal(snapshot, threadID: threadID) + } + continuation.finish() + } catch is CancellationError { + continuation.finish() + } catch { + guard let self else { + continuation.finish() + return + } + var snapshot = self.terminalSnapshots[threadID] + ?? FeatureTerminalSnapshot(threadID: threadID) + snapshot.state = .failed + snapshot.error = error.localizedDescription + self.terminalSnapshots[threadID] = snapshot + self.publishTerminal(snapshot, threadID: threadID) + continuation.finish() + } + } + continuation.onTermination = { @Sendable [weak self] _ in + task.cancel() + Task { @MainActor in + self?.terminalContinuations[threadID]?[subscriptionID] = nil + if self?.terminalContinuations[threadID]?.isEmpty == true { + self?.terminalContinuations[threadID] = nil + } + } + } + } + } + + func openTerminal(threadID: String, columns: Int, rows: Int) async throws { + let client = try requireClient() + let context = try workspaceContext(threadID: threadID) + let terminalID = terminalIDs[threadID] ?? UUID().uuidString + terminalIDs[threadID] = terminalID + let snapshot = try await client.openTerminal( + threadID: threadID, + terminalID: terminalID, + cwd: context.cwd, + worktreePath: context.worktreePath, + columns: columns, + rows: rows + ) + let mapped = NativeWorkspaceMapper.terminal(snapshot) + terminalSnapshots[threadID] = mapped + publishTerminal(mapped, threadID: threadID) + } + + func writeTerminal(threadID: String, data: String) async throws { + let client = try requireClient() + let terminalID = try requireTerminalID(threadID: threadID) + try await client.writeTerminal( + threadID: threadID, + terminalID: terminalID, + data: data + ) + } + + func resizeTerminal(threadID: String, columns: Int, rows: Int) async throws { + let client = try requireClient() + let terminalID = try requireTerminalID(threadID: threadID) + try await client.resizeTerminal( + threadID: threadID, + terminalID: terminalID, + columns: columns, + rows: rows + ) + } + + func closeTerminal(threadID: String) async throws { + let client = try requireClient() + let terminalID = try requireTerminalID(threadID: threadID) + try await client.closeTerminal(threadID: threadID, terminalID: terminalID) + terminalIDs[threadID] = nil + let snapshot = FeatureTerminalSnapshot(threadID: threadID) + terminalSnapshots[threadID] = snapshot + publishTerminal(snapshot, threadID: threadID) + } + + private func requireClient() throws -> T3Client { + guard let client else { throw NativeFeatureClientError.notConnected } + return client + } + + private func requireTerminalID(threadID: String) throws -> String { + guard let terminalID = terminalIDs[threadID] else { + throw NativeFeatureClientError.terminalNotOpen + } + return terminalID + } + + private func workspaceContext(threadID: String) throws -> ( + cwd: String, + worktreePath: String? + ) { + guard let thread = latestShell?.threads.first(where: { $0.id == threadID }), + let project = latestShell?.projects.first(where: { $0.id == thread.projectId }) else { + throw NativeFeatureClientError.workspaceNotFound + } + return ( + cwd: thread.worktreePath ?? project.workspaceRoot, + worktreePath: thread.worktreePath + ) + } + + private func consumeTerminalEvent( + _ event: TerminalEvent, + threadID: String + ) -> FeatureTerminalSnapshot { + if let coreSnapshot = event.snapshot { + let snapshot = NativeWorkspaceMapper.terminal(coreSnapshot) + terminalIDs[threadID] = coreSnapshot.terminalId + terminalSnapshots[threadID] = snapshot + return snapshot + } + + var snapshot = terminalSnapshots[threadID] + ?? FeatureTerminalSnapshot(threadID: threadID) + switch event.type { + case "output": + snapshot.buffer.append(NativeWorkspaceMapper.terminalText(event.data ?? "")) + case "exited": + snapshot.state = .exited + snapshot.exitCode = event.exitCode + case "closed": + snapshot.state = .stopped + case "error": + snapshot.state = .failed + snapshot.error = event.message + case "cleared": + snapshot.buffer = "" + case "activity": + snapshot.title = event.label ?? snapshot.title + default: + break + } + terminalSnapshots[threadID] = snapshot + return snapshot + } + + private func publishTerminal( + _ snapshot: FeatureTerminalSnapshot, + threadID: String + ) { + for continuation in terminalContinuations[threadID]?.values ?? [:].values { + continuation.yield(snapshot) + } + } + + private func finishTerminalStreams() { + for continuations in terminalContinuations.values { + for continuation in continuations.values { + continuation.finish() + } + } + terminalContinuations.removeAll() + } + + private func startPolling(_ activeClient: T3Client) { + pollingTask?.cancel() + pollingTask = Task { [weak self] in + do { + await activeClient.connect() + let sequence = self?.latestShell?.snapshotSequence + for try await item in await activeClient.shellEvents(after: sequence) { + guard !Task.isCancelled, let self else { break } + switch item { + case let .snapshot(shell): + await self.consume(shell: shell, client: activeClient) + case .projectUpserted, .projectRemoved, .threadUpserted, .threadRemoved: + if let shell = try? await activeClient.shellSnapshot() { + await self.consume(shell: shell, client: activeClient) + } + case .synchronized: + break + } + } + } catch is CancellationError { + return + } catch { + guard let self else { return } + self.continuation.yield(.failure("Live sync unavailable. Using HTTP updates.")) + do { + for try await shell in await activeClient.pollShell(every: .seconds(2)) { + guard !Task.isCancelled else { break } + await self.consume(shell: shell, client: activeClient) + } + } catch { + self.continuation.yield(.failure(error.localizedDescription)) + } + } + } + } + + private func consume(shell: OrchestrationShellSnapshot, client: T3Client) async { + latestShell = shell + if let readModel = try? await client.readModel() { + archivedThreads = readModel.threads + .filter { $0.archivedAt != nil } + .map(mapThread) + } + await emitSnapshot(shell) + for threadID in loadedThreadIDs { + try? await refreshThread(id: threadID, client: client) + } + } + + private func refresh(client: T3Client, includeArchived: Bool = false) async throws { + let shell = try await client.shellSnapshot() + latestShell = shell + if includeArchived { + let readModel = try await client.readModel() + archivedThreads = readModel.threads + .filter { $0.archivedAt != nil } + .map(mapThread) + } + await emitSnapshot(shell) + } + + private func refreshThread(id: String, client: T3Client) async throws { + let snapshot = try await client.threadSnapshot(id: id) + let detail = mapDetail(snapshot.thread) + guard latestDetails[id] != detail else { return } + latestDetails[id] = detail + continuation.yield(.detail(detail)) + } + + private func emitSnapshot(_ shell: OrchestrationShellSnapshot) async { + guard let environment = activeEnvironment else { return } + let environments = (try? await runtime.environments()) ?? [environment] + let snapshot = makeSnapshot( + shell: shell, + environments: environments, + activeEnvironment: environment + ) + guard latestSnapshot != snapshot else { return } + latestSnapshot = snapshot + continuation.yield(.snapshot(snapshot)) + } + + private func disconnectedSnapshot(environments: [Environment]) -> FeatureSnapshot { + FeatureSnapshot( + connection: .init(state: .disconnected), + environments: environments.map { mapEnvironment($0, activeID: nil) }, + settings: loadSettings() + ) + } + + private func makeSnapshot( + shell: OrchestrationShellSnapshot, + environments: [Environment], + activeEnvironment: Environment + ) -> FeatureSnapshot { + let threads = shell.threads.map(mapThread) + archivedThreads + return FeatureSnapshot( + connection: FeatureConnection( + state: .connected, + environmentName: activeEnvironment.label, + endpoint: activeEnvironment.httpBaseURL.absoluteString + ), + environments: environments.map { + mapEnvironment($0, activeID: activeEnvironment.id) + }, + projects: shell.projects.map { project in + FeatureProject( + id: project.id, + environmentID: activeEnvironment.id, + name: project.title, + path: project.workspaceRoot, + threadCount: threads.lazy.filter { $0.projectID == project.id }.count + ) + }, + threads: threads, + providers: mapProviders(shell), + settings: loadSettings() + ) + } + + private func mapEnvironment(_ environment: Environment, activeID: String?) -> FeatureEnvironment { + FeatureEnvironment( + id: environment.id, + name: environment.label, + endpoint: environment.httpBaseURL.absoluteString, + isActive: environment.id == activeID + ) + } + + private func mapThread(_ thread: OrchestrationThreadShell) -> FeatureThread { + FeatureThread( + id: thread.id, + projectID: thread.projectId, + title: thread.title, + updatedAt: parseDate(thread.updatedAt), + state: mapThreadState( + latestTurn: thread.latestTurn, + session: thread.session, + hasApprovals: thread.hasPendingApprovals, + hasUserInput: thread.hasPendingUserInput + ), + providerID: thread.modelSelection.instanceId, + modelID: thread.modelSelection.model, + isArchived: thread.archivedAt != nil, + isSettled: isSettled(thread.settledOverride, settledAt: thread.settledAt), + snoozedUntil: thread.snoozedUntil.map(parseDate), + runtimeMode: mapRuntimeMode(thread.runtimeMode), + interactionMode: mapInteractionMode(thread.interactionMode) + ) + } + + private func mapThread(_ thread: OrchestrationThread) -> FeatureThread { + FeatureThread( + id: thread.id, + projectID: thread.projectId, + title: thread.title, + preview: thread.messages.last?.text, + updatedAt: parseDate(thread.updatedAt), + state: mapThreadState( + latestTurn: thread.latestTurn, + session: thread.session, + hasApprovals: false, + hasUserInput: false + ), + providerID: thread.modelSelection.instanceId, + modelID: thread.modelSelection.model, + isArchived: thread.archivedAt != nil, + isSettled: isSettled(thread.settledOverride, settledAt: thread.settledAt), + snoozedUntil: thread.snoozedUntil.map(parseDate), + runtimeMode: mapRuntimeMode(thread.runtimeMode), + interactionMode: mapInteractionMode(thread.interactionMode) + ) + } + + private func mapDetail(_ thread: OrchestrationThread) -> FeatureThreadDetail { + let approvals = pendingApprovals(thread) + let userInputs = pendingUserInputs(thread) + let messages = thread.messages.map { message in + FeatureMessage( + id: message.id, + role: mapRole(message.role), + text: message.text, + createdAt: parseDate(message.createdAt), + state: message.streaming ? .streaming : .complete + ) + } + let work = thread.activities.compactMap { activity -> FeatureMessage? in + guard ![ + "approval.requested", + "approval.resolved", + "user-input.requested", + "user-input.resolved", + "context-window.updated", + "checkpoint.captured", + "task.started", + "tool.started", + ].contains(activity.kind), + activity.summary != "Checkpoint captured" else { + return nil + } + let detail = activity.payload["detail"]?.stringValue + let text = detail.map { "\(activity.summary)\n\($0)" } ?? activity.summary + return FeatureMessage( + id: "activity-\(activity.id)", + role: activity.tone == "error" ? .system : .tool, + text: text, + createdAt: parseDate(activity.createdAt), + state: .complete, + toolName: activity.kind + ) + } + let mergedMessages = (messages + work).sorted { $0.createdAt < $1.createdAt } + let mappedThread = FeatureThread( + id: thread.id, + projectID: thread.projectId, + title: thread.title, + preview: thread.messages.last?.text, + updatedAt: parseDate(thread.updatedAt), + state: mapThreadState( + latestTurn: thread.latestTurn, + session: thread.session, + hasApprovals: !approvals.isEmpty, + hasUserInput: !userInputs.isEmpty + ), + providerID: thread.modelSelection.instanceId, + modelID: thread.modelSelection.model, + isArchived: thread.archivedAt != nil, + isSettled: isSettled(thread.settledOverride, settledAt: thread.settledAt), + snoozedUntil: thread.snoozedUntil.map(parseDate), + runtimeMode: mapRuntimeMode(thread.runtimeMode), + interactionMode: mapInteractionMode(thread.interactionMode) + ) + return FeatureThreadDetail( + thread: mappedThread, + messages: mergedMessages, + approvals: approvals, + userInputs: userInputs + ) + } + + private func pendingApprovals(_ thread: OrchestrationThread) -> [FeatureApproval] { + var open: [String: FeatureApproval] = [:] + for activity in thread.activities.sorted(by: { + parseDate($0.createdAt) < parseDate($1.createdAt) + }) { + let requestID = activity.payload["requestId"]?.stringValue + if activity.kind == "approval.requested", let requestID { + let requestKind = activity.payload["requestKind"]?.stringValue + let kind: FeatureApprovalKind = switch requestKind { + case "command": .command + case "file-read": .fileRead + case "file-change": .fileChange + default: .other + } + let detail = activity.payload["detail"]?.stringValue ?? activity.summary + open[requestID] = FeatureApproval( + id: requestID, + threadID: thread.id, + kind: kind, + title: activity.summary, + detail: detail + ) + approvalThreadIDs[requestID] = thread.id + } else if activity.kind == "approval.resolved", let requestID { + open[requestID] = nil + approvalThreadIDs[requestID] = nil + } else if activity.kind == "provider.approval.respond.failed", let requestID { + let detail = activity.payload["detail"]?.stringValue?.lowercased() ?? "" + if detail.contains("stale") || detail.contains("unknown") { + open[requestID] = nil + approvalThreadIDs[requestID] = nil + } + } + } + return open.values.sorted { $0.id < $1.id } + } + + private func pendingUserInputs(_ thread: OrchestrationThread) -> [FeatureUserInput] { + var open: [String: FeatureUserInput] = [:] + for activity in thread.activities.sorted(by: { + parseDate($0.createdAt) < parseDate($1.createdAt) + }) { + let requestID = activity.payload["requestId"]?.stringValue + if activity.kind == "user-input.requested", + let requestID, + let questions = parseInputQuestions(activity.payload), + !questions.isEmpty { + open[requestID] = FeatureUserInput( + id: requestID, + threadID: thread.id, + questions: questions + ) + inputThreadIDs[requestID] = thread.id + } else if activity.kind == "user-input.resolved", let requestID { + open[requestID] = nil + inputThreadIDs[requestID] = nil + } else if activity.kind == "provider.user-input.respond.failed", let requestID { + let detail = activity.payload["detail"]?.stringValue?.lowercased() ?? "" + if detail.contains("stale") || detail.contains("unknown") { + open[requestID] = nil + inputThreadIDs[requestID] = nil + } + } + } + return open.values.sorted { $0.id < $1.id } + } + + private func parseInputQuestions(_ payload: JSONValue) -> [FeatureInputQuestion]? { + guard case let .array(rawQuestions)? = payload["questions"] else { return nil } + return rawQuestions.compactMap { rawQuestion in + guard case let .object(question) = rawQuestion, + let id = question["id"]?.stringValue, + let header = question["header"]?.stringValue, + let text = question["question"]?.stringValue else { + return nil + } + let options: [FeatureInputOption] + if case let .array(rawOptions)? = question["options"] { + options = rawOptions.compactMap { rawOption in + guard case let .object(option) = rawOption, + let label = option["label"]?.stringValue else { + return nil + } + return FeatureInputOption( + label: label, + detail: option["description"]?.stringValue ?? "" + ) + } + } else { + options = [] + } + let allowsMultiple: Bool + if case let .bool(value)? = question["multiSelect"] { + allowsMultiple = value + } else { + allowsMultiple = false + } + return FeatureInputQuestion( + id: id, + header: header, + question: text, + options: options, + allowsMultiple: allowsMultiple + ) + } + } + + private func mapThreadState( + latestTurn: OrchestrationLatestTurn?, + session: OrchestrationSession?, + hasApprovals: Bool, + hasUserInput: Bool + ) -> FeatureThreadState { + if hasApprovals { return .waitingForApproval } + if hasUserInput { return .waitingForInput } + if session?.status == "starting" { return .queued } + if session?.status == "running" || latestTurn?.state == "running" { return .working } + if session?.status == "error" || latestTurn?.state == "error" { return .failed } + if latestTurn?.state == "completed" { return .completed } + return .idle + } + + private func mapRole(_ role: String) -> FeatureMessageRole { + switch role { + case "user": .user + case "assistant": .assistant + case "system": .system + default: .tool + } + } + + private func isSettled(_ override: String?, settledAt: String?) -> Bool { + if override == "active" { return false } + return override == "settled" || settledAt != nil + } + + private func mapRuntimeMode(_ mode: RuntimeMode) -> FeatureRuntimeMode { + switch mode { + case .approvalRequired: .approvalRequired + case .autoAcceptEdits: .autoAcceptEdits + case .auto: .automatic + case .fullAccess: .fullAccess + } + } + + private func coreRuntimeMode(_ mode: FeatureRuntimeMode) -> RuntimeMode { + switch mode { + case .approvalRequired: .approvalRequired + case .autoAcceptEdits: .autoAcceptEdits + case .automatic: .auto + case .fullAccess: .fullAccess + } + } + + private func mapInteractionMode(_ mode: InteractionMode) -> FeatureInteractionMode { + mode == .plan ? .plan : .standard + } + + private func coreInteractionMode(_ mode: FeatureInteractionMode) -> InteractionMode { + mode == .plan ? .plan : .default + } + + private func mapProviders(_ shell: OrchestrationShellSnapshot) -> [FeatureProvider] { + var modelsByProvider: [String: Set] = [:] + for selection in shell.projects.compactMap(\.defaultModelSelection) + + shell.threads.map(\.modelSelection) { + modelsByProvider[selection.instanceId, default: []].insert(selection.model) + } + if modelsByProvider.isEmpty { + modelsByProvider["codex"] = ["gpt-5.6-sol"] + } + return modelsByProvider.keys.sorted().map { providerID in + FeatureProvider( + id: providerID, + name: providerDisplayName(providerID), + models: (modelsByProvider[providerID] ?? []).sorted().map { + FeatureModel(id: $0, name: $0) + } + ) + } + } + + private func modelSelection( + _ selection: FeatureSelection?, + projectID: String + ) -> ModelSelection { + if let selection { + return ModelSelection(instanceId: selection.providerID, model: selection.modelID) + } + if let projectDefault = latestShell?.projects + .first(where: { $0.id == projectID })? + .defaultModelSelection { + return projectDefault + } + return defaultModelSelection() + } + + private func defaultModelSelection() -> ModelSelection { + if let selection = loadSettings().defaultSelection { + return ModelSelection(instanceId: selection.providerID, model: selection.modelID) + } + return ModelSelection(instanceId: "codex", model: "gpt-5.6-sol") + } + + private func providerDisplayName(_ id: String) -> String { + switch id { + case "codex": "Codex" + case "claudeAgent", "claude": "Claude" + case "cursor": "Cursor" + case "grok": "Grok" + case "opencode": "OpenCode" + default: id + } + } + + private func loadSettings() -> FeatureSettings { + guard let data = settingsStore.data(forKey: Self.settingsKey), + let settings = try? JSONDecoder().decode(FeatureSettings.self, from: data) else { + return FeatureSettings() + } + return settings + } + + private func parseDate(_ value: String) -> Date { + Self.fractionalDateFormatter.date(from: value) + ?? Self.dateFormatter.date(from: value) + ?? .distantPast + } + + private static let settingsKey = "swift-ios.feature-settings.v1" + private static let fractionalDateFormatter: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return formatter + }() + private static let dateFormatter = ISO8601DateFormatter() +} + +private enum NativeFeatureClientError: LocalizedError { + case notConnected + case threadNotFound + case workspaceNotFound + case approvalNotFound + case inputRequestNotFound + case invalidProjectPath + case terminalNotOpen + + var errorDescription: String? { + switch self { + case .notConnected: "Connect to a T3 environment first." + case .threadNotFound: "The selected thread is no longer available." + case .workspaceNotFound: "The thread workspace is no longer available." + case .approvalNotFound: "The approval request is no longer active." + case .inputRequestNotFound: "The input request is no longer active." + case .invalidProjectPath: "Enter a workspace path on the connected environment." + case .terminalNotOpen: "Open the terminal before sending input." + } + } +} diff --git a/apps/swift-ios/App/NativeWorkspaceMapper.swift b/apps/swift-ios/App/NativeWorkspaceMapper.swift new file mode 100644 index 0000000000..900982a4fa --- /dev/null +++ b/apps/swift-ios/App/NativeWorkspaceMapper.swift @@ -0,0 +1,321 @@ +import Foundation + +enum NativeWorkspaceMapper { + static func files( + _ entries: [ProjectEntry], + directory: String? + ) -> [FeatureFileEntry] { + let directory = normalize(directory ?? "") + let prefix = directory.isEmpty ? "" : "\(directory)/" + var children: [String: FeatureFileEntry] = [:] + + for entry in entries { + let fullPath = normalize(entry.path) + guard fullPath.hasPrefix(prefix) else { continue } + let remainder = String(fullPath.dropFirst(prefix.count)) + guard !remainder.isEmpty else { continue } + + let component = remainder.split(separator: "/", maxSplits: 1).first.map(String.init)! + let childPath = prefix + component + let isNested = remainder.contains("/") + let kind: FeatureFileKind = isNested || entry.kind == .directory + ? .directory + : .file + if children[childPath]?.kind == .directory { + continue + } + children[childPath] = FeatureFileEntry( + path: childPath, + name: component, + kind: kind, + isHidden: component.hasPrefix(".") + ) + } + + return Array(children.values).featureFiltered(by: "", includesHidden: true) + } + + static func language(for path: String) -> String? { + switch URL(fileURLWithPath: path).pathExtension.lowercased() { + case "swift": "swift" + case "ts", "tsx": "typescript" + case "js", "jsx", "mjs", "cjs": "javascript" + case "json": "json" + case "md", "mdx": "markdown" + case "css", "scss": "css" + case "html": "html" + case "sh", "zsh", "bash": "shell" + case "py": "python" + case "rs": "rust" + case "go": "go" + case "yml", "yaml": "yaml" + default: nil + } + } + + static func review(_ preview: ReviewDiffPreview) -> FeatureReview { + FeatureReview( + title: "Working tree", + files: preview.sources.flatMap(parseDiff), + isTruncated: preview.sources.contains(where: \.truncated) + ) + } + + static func sourceControl(_ status: VCSStatus) -> FeatureSourceControlStatus { + FeatureSourceControlStatus( + isRepository: status.isRepo, + branch: status.refName, + aheadCount: status.aheadCount, + behindCount: status.behindCount, + files: status.workingTree.files.map { + FeatureSourceControlFile( + path: $0.path, + state: .modified, + isStaged: false + ) + }, + pullRequest: status.pr.map { + FeaturePullRequest( + number: $0.number, + title: $0.title, + state: $0.state, + url: URL(string: $0.url) + ) + } + ) + } + + static func gitAction(_ action: FeatureSourceControlAction) -> GitStackedAction { + switch action { + case .commit: .commit + case .push: .push + case .createPullRequest: .createPullRequest + case .commitAndPush: .commitAndPush + case .commitPushAndCreatePullRequest: .commitPushAndPullRequest + case .pull: + // Pull has a dedicated VCS endpoint and never reaches this mapping. + .push + } + } + + static func terminal(_ snapshot: TerminalSessionSnapshot) -> FeatureTerminalSnapshot { + FeatureTerminalSnapshot( + threadID: snapshot.threadId, + state: terminalState(snapshot.status), + title: snapshot.label, + workingDirectory: snapshot.cwd, + buffer: terminalText(snapshot.history), + exitCode: snapshot.exitCode + ) + } + + private static func terminalState(_ status: TerminalSessionStatus) -> FeatureTerminalState { + switch status { + case .starting: .starting + case .running: .running + case .exited: .exited + case .error: .failed + } + } + + /// This surface is a plain-text terminal viewer, not a VT100 emulator. + static func terminalText(_ value: String) -> String { + let withoutEscapes = value + .replacingOccurrences( + of: "\u{1B}\\][^\u{7}\u{1B}]*(?:\u{7}|\u{1B}\\\\)", + with: "", + options: .regularExpression + ) + .replacingOccurrences( + of: "\u{1B}\\[[0-?]*[ -/]*[@-~]", + with: "", + options: .regularExpression + ) + .replacingOccurrences( + of: "\u{1B}[@-_]", + with: "", + options: .regularExpression + ) + return withoutEscapes.reduce(into: "") { output, character in + if character == "\u{8}" || character == "\u{7F}" { + if !output.isEmpty { output.removeLast() } + return + } + if character == "\r" { return } + if character.unicodeScalars.count == 1, + let scalar = character.unicodeScalars.first, + scalar.value < 32, + character != "\n", + character != "\t" { + return + } + output.append(character) + } + } + + private static func normalize(_ path: String) -> String { + path.replacingOccurrences(of: "\\", with: "/") + .split(separator: "/", omittingEmptySubsequences: true) + .joined(separator: "/") + } + + private static func parseDiff(_ source: ReviewDiffSource) -> [FeatureReviewFile] { + let rawLines = source.diff.split( + separator: "\n", + omittingEmptySubsequences: false + ).map(String.init) + var files: [FeatureReviewFile] = [] + var currentPath: String? + var previousPath: String? + var change = FeatureReviewChangeKind.modified + var lines: [FeatureDiffLine] = [] + var oldLine: Int? + var newLine: Int? + var additions = 0 + var deletions = 0 + + func finishFile() { + guard let currentPath else { return } + files.append( + FeatureReviewFile( + path: currentPath, + previousPath: previousPath, + change: change, + additions: additions, + deletions: deletions, + lines: lines + ) + ) + } + + for (index, line) in rawLines.enumerated() { + if line.hasPrefix("diff --git ") { + finishFile() + let parts = line.split(separator: " ") + currentPath = parts.count > 3 ? stripDiffPrefix(String(parts[3])) : source.title + previousPath = parts.count > 2 ? stripDiffPrefix(String(parts[2])) : nil + change = .modified + lines = [] + oldLine = nil + newLine = nil + additions = 0 + deletions = 0 + continue + } + if line.hasPrefix("new file mode ") { + change = .added + continue + } + if line.hasPrefix("deleted file mode ") { + change = .deleted + continue + } + if line.hasPrefix("rename from ") { + previousPath = String(line.dropFirst("rename from ".count)) + change = .renamed + continue + } + if line.hasPrefix("rename to ") { + currentPath = String(line.dropFirst("rename to ".count)) + change = .renamed + continue + } + if line.hasPrefix("Binary files ") || line == "GIT binary patch" { + change = .binary + continue + } + if line.hasPrefix("+++ ") { + let path = String(line.dropFirst(4)) + if path != "/dev/null" { currentPath = stripDiffPrefix(path) } + continue + } + if line.hasPrefix("--- ") { + let path = String(line.dropFirst(4)) + if path != "/dev/null" { previousPath = stripDiffPrefix(path) } + continue + } + if line.hasPrefix("@@") { + let ranges = line.split(separator: " ") + oldLine = ranges.count > 1 ? rangeStart(String(ranges[1])) : nil + newLine = ranges.count > 2 ? rangeStart(String(ranges[2])) : nil + lines.append( + FeatureDiffLine( + id: "\(source.id)-\(index)", + kind: .hunk, + text: line + ) + ) + continue + } + + let kind: FeatureDiffLineKind + let rendered: String + let renderedOld: Int? + let renderedNew: Int? + if line.hasPrefix("+") { + kind = .addition + rendered = String(line.dropFirst()) + renderedOld = nil + renderedNew = newLine + newLine = newLine.map { $0 + 1 } + additions += 1 + } else if line.hasPrefix("-") { + kind = .deletion + rendered = String(line.dropFirst()) + renderedOld = oldLine + renderedNew = nil + oldLine = oldLine.map { $0 + 1 } + deletions += 1 + } else if line.hasPrefix(" ") { + kind = .context + rendered = String(line.dropFirst()) + renderedOld = oldLine + renderedNew = newLine + oldLine = oldLine.map { $0 + 1 } + newLine = newLine.map { $0 + 1 } + } else { + continue + } + lines.append( + FeatureDiffLine( + id: "\(source.id)-\(index)", + kind: kind, + oldLine: renderedOld, + newLine: renderedNew, + text: rendered + ) + ) + } + finishFile() + + if files.isEmpty, !source.diff.isEmpty { + return [ + FeatureReviewFile( + path: source.title, + change: .modified, + additions: additions, + deletions: deletions, + lines: lines + ), + ] + } + return files + } + + private static func stripDiffPrefix(_ path: String) -> String { + if path.hasPrefix("a/") || path.hasPrefix("b/") { + return String(path.dropFirst(2)) + } + return path + } + + private static func rangeStart(_ range: String) -> Int? { + Int( + range + .drop(while: { $0 == "-" || $0 == "+" }) + .split(separator: ",", maxSplits: 1) + .first + ?? "" + ) + } +} diff --git a/apps/swift-ios/App/RootView.swift b/apps/swift-ios/App/RootView.swift new file mode 100644 index 0000000000..95d18ab6bd --- /dev/null +++ b/apps/swift-ios/App/RootView.swift @@ -0,0 +1,17 @@ +import SwiftUI + +/// Owns app-wide presentation while the injected feature root owns product navigation. +struct RootView: View { + private let content: Content + + init(@ViewBuilder content: () -> Content) { + self.content = content() + } + + var body: some View { + content + .background(T3Colors.background.ignoresSafeArea()) + .tint(T3Colors.accent) + .preferredColorScheme(.dark) + } +} diff --git a/apps/swift-ios/App/T3CodeApp.swift b/apps/swift-ios/App/T3CodeApp.swift new file mode 100644 index 0000000000..e36b6690c8 --- /dev/null +++ b/apps/swift-ios/App/T3CodeApp.swift @@ -0,0 +1,14 @@ +import SwiftUI + +@main +struct T3CodeApp: App { + @State private var client = NativeFeatureClient() + + var body: some Scene { + WindowGroup { + RootView { + FeatureRootView(client: client) + } + } + } +} diff --git a/apps/swift-ios/Core/HTTP.swift b/apps/swift-ios/Core/HTTP.swift new file mode 100644 index 0000000000..3ba43180f6 --- /dev/null +++ b/apps/swift-ios/Core/HTTP.swift @@ -0,0 +1,188 @@ +import Foundation + +public protocol HTTPTransport: Sendable { + func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) +} + +public struct URLSessionHTTPTransport: HTTPTransport { + private let session: URLSession + + public init(session: URLSession = .shared) { + self.session = session + } + + public func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) { + let (data, response) = try await session.data(for: request) + guard let httpResponse = response as? HTTPURLResponse else { + throw HTTPError.invalidResponse + } + return (data, httpResponse) + } +} + +public enum HTTPError: LocalizedError, Sendable { + case invalidResponse + case status(Int, message: String, traceID: String?) + case missingCredential + + public var errorDescription: String? { + switch self { + case .invalidResponse: + "The server returned an invalid response." + case let .status(status, message, traceID): + traceID.map { "\(message) (trace \($0))" } ?? "\(message) (HTTP \(status))" + case .missingCredential: + "This environment has no saved credential." + } + } +} + +private struct ErrorBody: Decodable { + let message: String? + let reason: String? + let traceId: String? +} + +public actor EnvironmentAPI { + private let transport: any HTTPTransport + private let credentials: any CredentialStore + + public init( + transport: any HTTPTransport = URLSessionHTTPTransport(), + credentials: any CredentialStore + ) { + self.transport = transport + self.credentials = credentials + } + + public func descriptor(at httpBaseURL: URL) async throws -> EnvironmentDescriptor { + try await send( + URLRequest(url: endpoint(httpBaseURL, path: "/.well-known/t3/environment")), + as: EnvironmentDescriptor.self + ) + } + + public func shellSnapshot(for environment: Environment) async throws + -> OrchestrationShellSnapshot + { + try await authorized( + environment: environment, + path: "/api/orchestration/shell", + method: "GET", + as: OrchestrationShellSnapshot.self + ) + } + + public func readModel(for environment: Environment) async throws -> OrchestrationReadModel { + try await authorized( + environment: environment, + path: "/api/orchestration/snapshot", + method: "GET", + as: OrchestrationReadModel.self + ) + } + + public func threadSnapshot( + id: String, + environment: Environment + ) async throws -> OrchestrationThreadDetailSnapshot { + let encodedID = id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? id + return try await authorized( + environment: environment, + path: "/api/orchestration/threads/\(encodedID)", + method: "GET", + as: OrchestrationThreadDetailSnapshot.self + ) + } + + public func dispatch( + _ command: JSONValue, + environment: Environment + ) async throws -> DispatchResult { + try await authorized( + environment: environment, + path: "/api/orchestration/dispatch", + method: "POST", + body: JSONEncoder.t3.encode(command), + as: DispatchResult.self + ) + } + + public func webSocketTicket(for environment: Environment) async throws -> WebSocketTicket { + try await authorized( + environment: environment, + path: "/api/auth/websocket-ticket", + method: "POST", + as: WebSocketTicket.self + ) + } + + public func session(for environment: Environment) async throws -> AuthSessionState { + try await authorized( + environment: environment, + path: "/api/auth/session", + method: "GET", + as: AuthSessionState.self + ) + } + + private func authorized( + environment: Environment, + path: String, + method: String, + body: Data? = nil, + as type: Result.Type + ) async throws -> Result { + guard let credential = try await credentials.credential(for: environment.id) else { + throw HTTPError.missingCredential + } + var request = URLRequest(url: endpoint(environment.httpBaseURL, path: path)) + request.httpMethod = method + request.httpBody = body + request.setValue("Bearer \(credential.accessToken)", forHTTPHeaderField: "Authorization") + if body != nil { + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + return try await send(request, as: type) + } + + private func send( + _ request: URLRequest, + as type: Result.Type + ) async throws -> Result { + let (data, response) = try await transport.data(for: request) + guard (200..<300).contains(response.statusCode) else { + let body = try? JSONDecoder.t3.decode(ErrorBody.self, from: data) + throw HTTPError.status( + response.statusCode, + message: body?.message ?? body?.reason ?? "Environment request failed.", + traceID: body?.traceId + ) + } + return try JSONDecoder.t3.decode(type, from: data) + } +} + +public struct DispatchResult: Codable, Equatable, Sendable { + public let sequence: Int +} + +public struct WebSocketTicket: Codable, Equatable, Sendable { + public let ticket: String + public let expiresAt: String +} + +public struct AuthSessionState: Codable, Equatable, Sendable { + public let authenticated: Bool + public let scopes: [String]? + public let sessionMethod: String? + public let expiresAt: String? +} + +func endpoint(_ baseURL: URL, path: String) -> URL { + var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false)! + components.path = path + components.query = nil + components.fragment = nil + return components.url! +} diff --git a/apps/swift-ios/Core/JSONValue.swift b/apps/swift-ios/Core/JSONValue.swift new file mode 100644 index 0000000000..16ba8ad98b --- /dev/null +++ b/apps/swift-ios/Core/JSONValue.swift @@ -0,0 +1,86 @@ +import Foundation + +/// A lossless, Sendable JSON representation used at protocol boundaries that +/// intentionally carry provider-defined payloads. +public enum JSONValue: Codable, Equatable, Sendable { + case null + case bool(Bool) + case number(Double) + case string(String) + case array([JSONValue]) + case object([String: JSONValue]) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + if container.decodeNil() { + self = .null + } else if let value = try? container.decode(Bool.self) { + self = .bool(value) + } else if let value = try? container.decode(Double.self) { + self = .number(value) + } else if let value = try? container.decode(String.self) { + self = .string(value) + } else if let value = try? container.decode([JSONValue].self) { + self = .array(value) + } else { + self = .object(try container.decode([String: JSONValue].self)) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .null: + try container.encodeNil() + case let .bool(value): + try container.encode(value) + case let .number(value): + try container.encode(value) + case let .string(value): + try container.encode(value) + case let .array(value): + try container.encode(value) + case let .object(value): + try container.encode(value) + } + } + + public subscript(key: String) -> JSONValue? { + guard case let .object(object) = self else { return nil } + return object[key] + } + + public var stringValue: String? { + guard case let .string(value) = self else { return nil } + return value + } + + public static func encode( + _ value: T, + encoder: JSONEncoder = .t3 + ) throws -> JSONValue { + let data = try encoder.encode(value) + return try JSONDecoder.t3.decode(JSONValue.self, from: data) + } + + public func decode( + _ type: T.Type, + decoder: JSONDecoder = .t3 + ) throws -> T { + try decoder.decode(type, from: JSONEncoder.t3.encode(self)) + } +} + +extension JSONEncoder { + public static var t3: JSONEncoder { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + return encoder + } +} + +extension JSONDecoder { + public static var t3: JSONDecoder { + JSONDecoder() + } +} diff --git a/apps/swift-ios/Core/Models.swift b/apps/swift-ios/Core/Models.swift new file mode 100644 index 0000000000..463df1fd22 --- /dev/null +++ b/apps/swift-ios/Core/Models.swift @@ -0,0 +1,407 @@ +import Foundation + +public enum EnvironmentKind: String, Codable, Sendable { + case bearer + case local +} + +public struct Environment: Codable, Identifiable, Equatable, Sendable { + public let id: String + public var label: String + public var httpBaseURL: URL + public var webSocketBaseURL: URL + public var kind: EnvironmentKind + public var descriptor: EnvironmentDescriptor? + + public init( + id: String, + label: String, + httpBaseURL: URL, + webSocketBaseURL: URL, + kind: EnvironmentKind = .bearer, + descriptor: EnvironmentDescriptor? = nil + ) { + self.id = id + self.label = label + self.httpBaseURL = httpBaseURL + self.webSocketBaseURL = webSocketBaseURL + self.kind = kind + self.descriptor = descriptor + } +} + +public struct EnvironmentDescriptor: Codable, Equatable, Sendable { + public struct Platform: Codable, Equatable, Sendable { + public let os: String + public let arch: String + } + + public struct Capabilities: Codable, Equatable, Sendable { + public let repositoryIdentity: Bool + public let connectionProbe: Bool? + public let threadSettlement: Bool? + public let threadSnooze: Bool? + public let threadTitleRegeneration: Bool? + public let serverSelfUpdate: String? + public let serverSelfUpdateProgress: Bool? + + private enum CodingKeys: String, CodingKey { + case repositoryIdentity + case connectionProbe + case threadSettlement + case threadSnooze + case threadTitleRegeneration + case serverSelfUpdate + case serverSelfUpdateProgress + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + repositoryIdentity = + try container.decodeIfPresent(Bool.self, forKey: .repositoryIdentity) ?? false + connectionProbe = try container.decodeIfPresent(Bool.self, forKey: .connectionProbe) + threadSettlement = try container.decodeIfPresent(Bool.self, forKey: .threadSettlement) + threadSnooze = try container.decodeIfPresent(Bool.self, forKey: .threadSnooze) + threadTitleRegeneration = try container.decodeIfPresent( + Bool.self, + forKey: .threadTitleRegeneration + ) + serverSelfUpdate = try container.decodeIfPresent(String.self, forKey: .serverSelfUpdate) + serverSelfUpdateProgress = try container.decodeIfPresent( + Bool.self, + forKey: .serverSelfUpdateProgress + ) + } + } + + public let environmentId: String + public let label: String + public let platform: Platform + public let serverVersion: String + public let capabilities: Capabilities +} + +public struct EnvironmentCredential: Codable, Equatable, Sendable { + public let accessToken: String + public let expiresAt: Date? + public let scopes: [String] + + public init(accessToken: String, expiresAt: Date? = nil, scopes: [String] = []) { + self.accessToken = accessToken + self.expiresAt = expiresAt + self.scopes = scopes + } +} + +public struct ModelSelection: Codable, Equatable, Sendable { + public struct OptionSelection: Codable, Equatable, Sendable { + public let id: String + public let value: JSONValue + + public init(id: String, value: JSONValue) { + self.id = id + self.value = value + } + } + + public let instanceId: String + public let model: String + public let options: [OptionSelection]? + + public init(instanceId: String, model: String, options: [OptionSelection]? = nil) { + self.instanceId = instanceId + self.model = model + self.options = options + } + + private enum CodingKeys: String, CodingKey { + case instanceId, provider, model, options + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + instanceId = try container.decodeIfPresent(String.self, forKey: .instanceId) + ?? container.decode(String.self, forKey: .provider) + model = try container.decode(String.self, forKey: .model) + if let canonical = try? container.decode([OptionSelection].self, forKey: .options) { + options = canonical + } else if let legacy = try? container.decode( + [String: JSONValue].self, + forKey: .options + ) { + options = legacy.keys.sorted().map { OptionSelection(id: $0, value: legacy[$0]!) } + } else { + options = nil + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(instanceId, forKey: .instanceId) + try container.encode(model, forKey: .model) + try container.encodeIfPresent(options, forKey: .options) + } +} + +public struct RepositoryIdentity: Codable, Equatable, Sendable { + public struct Locator: Codable, Equatable, Sendable { + public let source: String + public let remoteName: String + public let remoteUrl: String + } + + public let canonicalKey: String + public let locator: Locator + public let rootPath: String? + public let displayName: String? + public let provider: String? + public let owner: String? + public let name: String? +} + +public struct ProjectScript: Codable, Identifiable, Equatable, Sendable { + public let id: String + public let name: String + public let command: String + public let icon: String + public let runOnWorktreeCreate: Bool + public let previewUrl: String? + public let autoOpenPreview: Bool? +} + +public struct OrchestrationProject: Codable, Identifiable, Equatable, Sendable { + public let id: String + public let title: String + public let workspaceRoot: String + public let repositoryIdentity: RepositoryIdentity? + public let defaultModelSelection: ModelSelection? + public let scripts: [ProjectScript] + public let createdAt: String + public let updatedAt: String + public let deletedAt: String? +} + +public enum RuntimeMode: String, Codable, CaseIterable, Sendable { + case approvalRequired = "approval-required" + case autoAcceptEdits = "auto-accept-edits" + case auto + case fullAccess = "full-access" +} + +public enum InteractionMode: String, Codable, CaseIterable, Sendable { + case `default` + case plan +} + +public struct OrchestrationLatestTurn: Codable, Equatable, Sendable { + public let turnId: String + public let state: String + public let requestedAt: String + public let startedAt: String? + public let completedAt: String? + public let assistantMessageId: String? +} + +public struct OrchestrationSession: Codable, Equatable, Sendable { + public let threadId: String + public let status: String + public let providerName: String? + public let providerInstanceId: String? + public let runtimeMode: RuntimeMode + public let activeTurnId: String? + public let lastError: String? + public let updatedAt: String +} + +public struct OrchestrationThreadShell: Codable, Identifiable, Equatable, Sendable { + public let id: String + public let projectId: String + public let title: String + public let modelSelection: ModelSelection + public let runtimeMode: RuntimeMode + public let interactionMode: InteractionMode + public let branch: String? + public let worktreePath: String? + public let latestTurn: OrchestrationLatestTurn? + public let createdAt: String + public let updatedAt: String + public let archivedAt: String? + public let settledOverride: String? + public let settledAt: String? + public let snoozedUntil: String? + public let snoozedAt: String? + public let session: OrchestrationSession? + public let latestUserMessageAt: String? + public let hasPendingApprovals: Bool + public let hasPendingUserInput: Bool + public let hasActionableProposedPlan: Bool +} + +public struct OrchestrationMessage: Codable, Identifiable, Equatable, Sendable { + public let id: String + public let role: String + public let text: String + public let attachments: [ChatAttachment]? + public let turnId: String? + public let streaming: Bool + public let createdAt: String + public let updatedAt: String +} + +public struct ChatAttachment: Codable, Identifiable, Equatable, Sendable { + public let type: String + public let id: String + public let name: String + public let mimeType: String + public let sizeBytes: Int +} + +public struct OrchestrationActivity: Codable, Identifiable, Equatable, Sendable { + public let id: String + public let tone: String + public let kind: String + public let summary: String + public let payload: JSONValue + public let turnId: String? + public let sequence: Int? + public let createdAt: String +} + +public struct CheckpointFile: Codable, Equatable, Sendable { + public let path: String + public let kind: String + public let additions: Int + public let deletions: Int +} + +public struct CheckpointSummary: Codable, Equatable, Sendable { + public let turnId: String + public let checkpointTurnCount: Int + public let checkpointRef: String + public let status: String + public let files: [CheckpointFile] + public let assistantMessageId: String? + public let completedAt: String +} + +public struct OrchestrationThread: Codable, Identifiable, Equatable, Sendable { + public let id: String + public let projectId: String + public let title: String + public let modelSelection: ModelSelection + public let runtimeMode: RuntimeMode + public let interactionMode: InteractionMode + public let branch: String? + public let worktreePath: String? + public let latestTurn: OrchestrationLatestTurn? + public let createdAt: String + public let updatedAt: String + public let archivedAt: String? + public let settledOverride: String? + public let settledAt: String? + public let snoozedUntil: String? + public let snoozedAt: String? + public let deletedAt: String? + public let messages: [OrchestrationMessage] + public let activities: [OrchestrationActivity] + public let checkpoints: [CheckpointSummary] + public let session: OrchestrationSession? +} + +public struct OrchestrationShellSnapshot: Codable, Equatable, Sendable { + public let snapshotSequence: Int + public let projects: [OrchestrationProject] + public let threads: [OrchestrationThreadShell] + public let updatedAt: String +} + +public struct OrchestrationReadModel: Codable, Equatable, Sendable { + public let snapshotSequence: Int + public let projects: [OrchestrationProject] + public let threads: [OrchestrationThread] + public let updatedAt: String +} + +public struct OrchestrationThreadDetailSnapshot: Codable, Equatable, Sendable { + public let snapshotSequence: Int + public let thread: OrchestrationThread +} + +public enum ShellStreamItem: Decodable, Sendable { + case synchronized + case snapshot(OrchestrationShellSnapshot) + case projectUpserted(sequence: Int, project: OrchestrationProject) + case projectRemoved(sequence: Int, projectID: String) + case threadUpserted(sequence: Int, thread: OrchestrationThreadShell) + case threadRemoved(sequence: Int, threadID: String) + + private enum CodingKeys: String, CodingKey { + case kind, sequence, snapshot, project, projectId, thread, threadId + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let kind = try container.decode(String.self, forKey: .kind) + switch kind { + case "synchronized": + self = .synchronized + case "snapshot": + self = .snapshot(try container.decode(OrchestrationShellSnapshot.self, forKey: .snapshot)) + case "project-upserted": + self = .projectUpserted( + sequence: try container.decode(Int.self, forKey: .sequence), + project: try container.decode(OrchestrationProject.self, forKey: .project) + ) + case "project-removed": + self = .projectRemoved( + sequence: try container.decode(Int.self, forKey: .sequence), + projectID: try container.decode(String.self, forKey: .projectId) + ) + case "thread-upserted": + self = .threadUpserted( + sequence: try container.decode(Int.self, forKey: .sequence), + thread: try container.decode(OrchestrationThreadShell.self, forKey: .thread) + ) + case "thread-removed": + self = .threadRemoved( + sequence: try container.decode(Int.self, forKey: .sequence), + threadID: try container.decode(String.self, forKey: .threadId) + ) + default: + throw DecodingError.dataCorruptedError( + forKey: .kind, + in: container, + debugDescription: "Unknown shell stream item \(kind)" + ) + } + } +} + +public enum ThreadStreamItem: Decodable, Sendable { + case synchronized + case snapshot(OrchestrationThreadDetailSnapshot) + case event(JSONValue) + + private enum CodingKeys: String, CodingKey { case kind, snapshot, event } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let kind = try container.decode(String.self, forKey: .kind) + switch kind { + case "synchronized": + self = .synchronized + case "snapshot": + self = .snapshot( + try container.decode(OrchestrationThreadDetailSnapshot.self, forKey: .snapshot) + ) + case "event": + self = .event(try container.decode(JSONValue.self, forKey: .event)) + default: + throw DecodingError.dataCorruptedError( + forKey: .kind, + in: container, + debugDescription: "Unknown thread stream item \(kind)" + ) + } + } +} diff --git a/apps/swift-ios/Core/PairingService.swift b/apps/swift-ios/Core/PairingService.swift new file mode 100644 index 0000000000..4643fc9ed5 --- /dev/null +++ b/apps/swift-ios/Core/PairingService.swift @@ -0,0 +1,148 @@ +import Foundation + +public struct TokenExchangeResult: Decodable, Sendable { + public let accessToken: String + public let issuedTokenType: String + public let tokenType: String + public let expiresIn: Double + public let scope: String + + private enum CodingKeys: String, CodingKey { + case accessToken = "access_token" + case issuedTokenType = "issued_token_type" + case tokenType = "token_type" + case expiresIn = "expires_in" + case scope + } +} + +public actor PairingService { + public static let standardScopes = [ + "orchestration:read", + "orchestration:operate", + "terminal:operate", + "review:write", + "relay:read", + ] + + private let transport: any HTTPTransport + private let environmentStore: EnvironmentStore + private let credentialStore: any CredentialStore + + public init( + transport: any HTTPTransport = URLSessionHTTPTransport(), + environmentStore: EnvironmentStore, + credentialStore: any CredentialStore + ) { + self.transport = transport + self.environmentStore = environmentStore + self.credentialStore = credentialStore + } + + @discardableResult + public func pair( + url pairingURL: String, + label clientLabel: String? = nil + ) async throws -> Environment { + try await pair(target: PairingURL.resolve(pairingURL), clientLabel: clientLabel) + } + + @discardableResult + public func pair( + host: String, + code: String, + label clientLabel: String? = nil + ) async throws -> Environment { + try await pair( + target: PairingURL.resolve(host: host, pairingCode: code), + clientLabel: clientLabel + ) + } + + private func pair( + target: PairingTarget, + clientLabel: String? + ) async throws -> Environment { + let api = EnvironmentAPI(transport: transport, credentials: credentialStore) + let descriptor = try await api.descriptor(at: target.httpBaseURL) + let access = try await exchange(target: target, clientLabel: clientLabel) + guard access.tokenType == "Bearer" else { + throw HTTPError.status( + 400, + message: "The environment issued an unsupported \(access.tokenType) token.", + traceID: nil + ) + } + let environment = Environment( + id: descriptor.environmentId, + label: descriptor.label, + httpBaseURL: target.httpBaseURL, + webSocketBaseURL: target.webSocketBaseURL, + descriptor: descriptor + ) + let credential = EnvironmentCredential( + accessToken: access.accessToken, + expiresAt: Date().addingTimeInterval(access.expiresIn), + scopes: access.scope.split(separator: " ").map(String.init) + ) + // Store the secret first. A catalog record must never point at a + // credential that failed to persist. + try await credentialStore.setCredential(credential, for: environment.id) + do { + try await environmentStore.upsert(environment) + if try await environmentStore.activeEnvironmentID() == nil { + try await environmentStore.setActiveEnvironment(id: environment.id) + } + } catch { + try? await credentialStore.removeCredential(for: environment.id) + throw error + } + return environment + } + + private func exchange( + target: PairingTarget, + clientLabel: String? + ) async throws -> TokenExchangeResult { + var fields = [ + URLQueryItem( + name: "grant_type", + value: "urn:ietf:params:oauth:grant-type:token-exchange" + ), + URLQueryItem(name: "subject_token", value: target.credential), + URLQueryItem( + name: "subject_token_type", + value: "urn:t3:params:oauth:token-type:environment-bootstrap" + ), + URLQueryItem( + name: "requested_token_type", + value: "urn:ietf:params:oauth:token-type:access_token" + ), + URLQueryItem(name: "scope", value: Self.standardScopes.joined(separator: " ")), + URLQueryItem(name: "client_device_type", value: "mobile"), + URLQueryItem(name: "client_os", value: "iOS"), + ] + if let clientLabel, !clientLabel.isEmpty { + fields.append(URLQueryItem(name: "client_label", value: clientLabel)) + } + var form = URLComponents() + form.queryItems = fields + var request = URLRequest(url: endpoint(target.httpBaseURL, path: "/oauth/token")) + request.httpMethod = "POST" + request.httpBody = form.percentEncodedQuery?.data(using: .utf8) + request.setValue( + "application/x-www-form-urlencoded", + forHTTPHeaderField: "Content-Type" + ) + let (data, response) = try await transport.data(for: request) + guard (200..<300).contains(response.statusCode) else { + let body = try? JSONDecoder.t3.decode(JSONValue.self, from: data) + throw HTTPError.status( + response.statusCode, + message: body?["reason"]?.stringValue ?? "Pairing failed.", + traceID: body?["traceId"]?.stringValue + ) + } + return try JSONDecoder.t3.decode(TokenExchangeResult.self, from: data) + } +} diff --git a/apps/swift-ios/Core/PairingURL.swift b/apps/swift-ios/Core/PairingURL.swift new file mode 100644 index 0000000000..2df3dccb26 --- /dev/null +++ b/apps/swift-ios/Core/PairingURL.swift @@ -0,0 +1,108 @@ +import Foundation + +public struct PairingTarget: Equatable, Sendable { + public let credential: String + public let httpBaseURL: URL + public let webSocketBaseURL: URL +} + +public enum PairingURLError: LocalizedError, Equatable { + case invalidURL + case unsupportedScheme + case missingToken + case missingHost + + public var errorDescription: String? { + switch self { + case .invalidURL: "Pairing URL is invalid." + case .unsupportedScheme: "Pairing URL uses an unsupported scheme." + case .missingToken: "Pairing URL is missing its token." + case .missingHost: "Pairing URL is missing its environment host." + } + } +} + +public enum PairingURL { + public static func resolve(_ rawValue: String) throws -> PairingTarget { + let trimmed = rawValue.trimmingCharacters(in: .whitespacesAndNewlines) + guard var components = URLComponents(string: trimmed), components.url != nil else { + throw PairingURLError.invalidURL + } + guard ["http", "https", "ws", "wss"].contains(components.scheme?.lowercased() ?? "") else { + throw PairingURLError.unsupportedScheme + } + + let query = components.queryItems ?? [] + let fragment = URLComponents(string: "?\(components.fragment ?? "")")?.queryItems ?? [] + let token = (fragment + query) + .first(where: { $0.name == "token" })? + .value? + .trimmingCharacters(in: .whitespacesAndNewlines) + + if let hosted = query.first(where: { $0.name == "host" })?.value, + !hosted.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + return try directTarget(host: hosted, credential: requireToken(token)) + } + + components.path = "/" + components.query = nil + components.fragment = nil + guard let base = components.url, base.host != nil else { throw PairingURLError.missingHost } + return try target(baseURL: base, credential: requireToken(token)) + } + + public static func resolve(host: String, pairingCode: String) throws -> PairingTarget { + let normalized = host.contains("://") ? host : "https://\(host)" + guard let url = URL(string: normalized), url.host != nil else { + throw PairingURLError.invalidURL + } + return try directTarget(host: normalized, credential: requireToken(pairingCode)) + } + + private static func directTarget(host: String, credential: String) throws -> PairingTarget { + let normalized = host.contains("://") ? host : "https://\(host)" + guard var components = URLComponents(string: normalized), let url = components.url else { + throw PairingURLError.invalidURL + } + guard ["http", "https", "ws", "wss"].contains(components.scheme?.lowercased() ?? "") else { + throw PairingURLError.unsupportedScheme + } + components.path = "/" + components.query = nil + components.fragment = nil + guard let base = components.url, url.host != nil else { throw PairingURLError.missingHost } + return try target(baseURL: base, credential: credential) + } + + private static func target(baseURL: URL, credential: String) throws -> PairingTarget { + guard var http = URLComponents(url: baseURL, resolvingAgainstBaseURL: false), + var socket = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) + else { + throw PairingURLError.invalidURL + } + switch http.scheme?.lowercased() { + case "ws": http.scheme = "http" + case "wss": http.scheme = "https" + default: break + } + switch socket.scheme?.lowercased() { + case "http": socket.scheme = "ws" + case "https": socket.scheme = "wss" + default: break + } + guard let httpURL = http.url, let socketURL = socket.url else { + throw PairingURLError.invalidURL + } + return PairingTarget( + credential: credential, + httpBaseURL: httpURL, + webSocketBaseURL: socketURL + ) + } + + private static func requireToken(_ token: String?) throws -> String { + let trimmed = token?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + guard !trimmed.isEmpty else { throw PairingURLError.missingToken } + return trimmed + } +} diff --git a/apps/swift-ios/Core/Persistence.swift b/apps/swift-ios/Core/Persistence.swift new file mode 100644 index 0000000000..bfc1c8fdcb --- /dev/null +++ b/apps/swift-ios/Core/Persistence.swift @@ -0,0 +1,204 @@ +import Foundation +import Security + +public protocol CredentialStore: Sendable { + func credential(for environmentID: String) async throws -> EnvironmentCredential? + func setCredential(_ credential: EnvironmentCredential, for environmentID: String) async throws + func removeCredential(for environmentID: String) async throws +} + +public enum CredentialStoreError: LocalizedError, Sendable { + case keychain(OSStatus) + case invalidData + + public var errorDescription: String? { + switch self { + case let .keychain(status): + SecCopyErrorMessageString(status, nil) as String? ?? "Keychain error \(status)." + case .invalidData: + "The saved environment credential is invalid." + } + } +} + +/// Access tokens are deliberately isolated from the environment catalog so +/// catalog exports and backups never contain authentication material. +public actor KeychainCredentialStore: CredentialStore { + private let service: String + private let accessibility: CFString + + public init( + service: String = "codes.t3.swift-ios.environment-credentials", + accessibility: CFString = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly + ) { + self.service = service + self.accessibility = accessibility + } + + public func credential(for environmentID: String) throws -> EnvironmentCredential? { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: environmentID, + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitOne, + ] + var item: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &item) + if status == errSecItemNotFound { return nil } + guard status == errSecSuccess else { throw CredentialStoreError.keychain(status) } + guard let data = item as? Data else { throw CredentialStoreError.invalidData } + do { + return try JSONDecoder.t3.decode(EnvironmentCredential.self, from: data) + } catch { + throw CredentialStoreError.invalidData + } + } + + public func setCredential( + _ credential: EnvironmentCredential, + for environmentID: String + ) throws { + let data = try JSONEncoder.t3.encode(credential) + let lookup: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: environmentID, + ] + let attributes: [String: Any] = [ + kSecValueData as String: data, + kSecAttrAccessible as String: accessibility, + ] + let updateStatus = SecItemUpdate(lookup as CFDictionary, attributes as CFDictionary) + if updateStatus == errSecItemNotFound { + var insertion = lookup + attributes.forEach { insertion[$0.key] = $0.value } + let status = SecItemAdd(insertion as CFDictionary, nil) + guard status == errSecSuccess else { throw CredentialStoreError.keychain(status) } + } else if updateStatus != errSecSuccess { + throw CredentialStoreError.keychain(updateStatus) + } + } + + public func removeCredential(for environmentID: String) throws { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: environmentID, + ] + let status = SecItemDelete(query as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { + throw CredentialStoreError.keychain(status) + } + } +} + +public actor InMemoryCredentialStore: CredentialStore { + private var credentials: [String: EnvironmentCredential] + + public init(credentials: [String: EnvironmentCredential] = [:]) { + self.credentials = credentials + } + + public func credential(for environmentID: String) -> EnvironmentCredential? { + credentials[environmentID] + } + + public func setCredential( + _ credential: EnvironmentCredential, + for environmentID: String + ) { + credentials[environmentID] = credential + } + + public func removeCredential(for environmentID: String) { + credentials.removeValue(forKey: environmentID) + } +} + +public actor EnvironmentStore { + private struct Document: Codable { + let version: Int + var environments: [Environment] + var activeEnvironmentID: String? + } + + public let fileURL: URL + + public init(fileURL: URL? = nil) { + if let fileURL { + self.fileURL = fileURL + } else { + let root = FileManager.default.urls( + for: .applicationSupportDirectory, + in: .userDomainMask + ).first! + self.fileURL = root + .appendingPathComponent("T3CodeSwift", isDirectory: true) + .appendingPathComponent("environments.json", isDirectory: false) + } + } + + public func load() throws -> [Environment] { + try loadDocument().environments + } + + public func activeEnvironmentID() throws -> String? { + try loadDocument().activeEnvironmentID + } + + public func setActiveEnvironment(id: String?) throws { + var document = try loadDocument() + document.activeEnvironmentID = id + try save(document) + } + + public func save(_ environments: [Environment]) throws { + try FileManager.default.createDirectory( + at: fileURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + var document = try loadDocument() + document.environments = environments + try save(document) + } + + @discardableResult + public func upsert(_ environment: Environment) throws -> [Environment] { + var environments = try load() + if let index = environments.firstIndex(where: { $0.id == environment.id }) { + environments[index] = environment + } else { + environments.append(environment) + } + try save(environments) + return environments + } + + @discardableResult + public func remove(id: String) throws -> [Environment] { + var document = try loadDocument() + document.environments.removeAll { $0.id == id } + if document.activeEnvironmentID == id { + document.activeEnvironmentID = document.environments.first?.id + } + try save(document) + return document.environments + } + + private func loadDocument() throws -> Document { + guard FileManager.default.fileExists(atPath: fileURL.path) else { + return Document(version: 1, environments: [], activeEnvironmentID: nil) + } + let data = try Data(contentsOf: fileURL) + return try JSONDecoder.t3.decode(Document.self, from: data) + } + + private func save(_ document: Document) throws { + try FileManager.default.createDirectory( + at: fileURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try JSONEncoder.t3.encode(document).write(to: fileURL, options: .atomic) + } +} diff --git a/apps/swift-ios/Core/T3Client.swift b/apps/swift-ios/Core/T3Client.swift new file mode 100644 index 0000000000..6fe2a27994 --- /dev/null +++ b/apps/swift-ios/Core/T3Client.swift @@ -0,0 +1,1169 @@ +import Foundation + +public actor T3Client { + public let environment: Environment + private let api: EnvironmentAPI + private let rpc: WebSocketRPCClient + + public init( + environment: Environment, + credentialStore: any CredentialStore, + httpTransport: any HTTPTransport = URLSessionHTTPTransport(), + webSocketConnector: any WebSocketConnecting = URLSessionWebSocketConnector() + ) { + self.environment = environment + let api = EnvironmentAPI(transport: httpTransport, credentials: credentialStore) + self.api = api + self.rpc = WebSocketRPCClient(connector: webSocketConnector) { + let ticket = try await api.webSocketTicket(for: environment) + var components = URLComponents( + url: environment.webSocketBaseURL, + resolvingAgainstBaseURL: false + )! + if components.path.isEmpty || components.path == "/" { + components.path = "/ws" + } + var query = components.queryItems ?? [] + query.removeAll { $0.name == "wsTicket" } + query.append(URLQueryItem(name: "wsTicket", value: ticket.ticket)) + components.queryItems = query + guard let url = components.url else { throw PairingURLError.invalidURL } + return url + } + } + + public func connect() async { + await rpc.start() + } + + public func disconnect() async { + await rpc.stop() + } + + public func shellSnapshot() async throws -> OrchestrationShellSnapshot { + try await api.shellSnapshot(for: environment) + } + + public func readModel() async throws -> OrchestrationReadModel { + try await api.readModel(for: environment) + } + + public func threadSnapshot(id: String) async throws -> OrchestrationThreadDetailSnapshot { + try await api.threadSnapshot(id: id, environment: environment) + } + + /// HTTP live-sync fallback. Each iteration is an independent request, so a + /// transient network loss naturally reconnects without replaying commands. + public func pollShell( + every interval: Duration = .seconds(2) + ) -> AsyncThrowingStream { + AsyncThrowingStream { continuation in + let task = Task { + var lastSequence: Int? + while !Task.isCancelled { + do { + let snapshot = try await self.shellSnapshot() + if lastSequence != snapshot.snapshotSequence { + lastSequence = snapshot.snapshotSequence + continuation.yield(snapshot) + } + } catch is CancellationError { + break + } catch { + // Keep retrying transient HTTP failures. Authentication + // failures surface from direct loads and pairing UI. + } + try? await Task.sleep(for: interval) + } + continuation.finish() + } + continuation.onTermination = { @Sendable _ in task.cancel() } + } + } + + public func shellEvents( + after sequence: Int? = nil + ) async -> AsyncThrowingStream { + var payload: [String: JSONValue] = ["requestCompletionMarker": .bool(true)] + if let sequence { payload["afterSequence"] = .number(Double(sequence)) } + return await rpc.subscribe( + RPCMethod.subscribeShell.rawValue, + payload: .object(payload), + as: ShellStreamItem.self + ) + } + + public func threadEvents( + threadID: String, + after sequence: Int? = nil + ) async -> AsyncThrowingStream { + var payload: [String: JSONValue] = [ + "threadId": .string(threadID), + "requestCompletionMarker": .bool(true), + ] + if let sequence { payload["afterSequence"] = .number(Double(sequence)) } + return await rpc.subscribe( + RPCMethod.subscribeThread.rawValue, + payload: .object(payload), + as: ThreadStreamItem.self + ) + } + + @discardableResult + public func dispatch(_ command: JSONValue) async throws -> DispatchResult { + try await api.dispatch(command, environment: environment) + } + + @discardableResult + public func sendTurn( + threadID: String, + text: String, + runtimeMode: RuntimeMode, + interactionMode: InteractionMode = .default + ) async throws -> DispatchResult { + try await dispatch( + OrchestrationCommands.sendTurn( + threadID: threadID, + text: text, + runtimeMode: runtimeMode, + interactionMode: interactionMode + ) + ) + } + + @discardableResult + public func createThread( + threadID: String = UUID().uuidString, + projectID: String, + title: String, + model: ModelSelection, + runtimeMode: RuntimeMode, + interactionMode: InteractionMode = .default, + branch: String? = nil, + worktreePath: String? = nil + ) async throws -> DispatchResult { + try await dispatch( + try OrchestrationCommands.createThread( + threadID: threadID, + projectID: projectID, + title: title, + model: model, + runtimeMode: runtimeMode, + interactionMode: interactionMode, + branch: branch, + worktreePath: worktreePath + ) + ) + } + + @discardableResult + public func createProject( + projectID: String = UUID().uuidString, + title: String, + workspaceRoot: String, + defaultModel: ModelSelection? = nil, + createWorkspaceRootIfMissing: Bool = false + ) async throws -> DispatchResult { + try await dispatch( + try OrchestrationCommands.createProject( + projectID: projectID, + title: title, + workspaceRoot: workspaceRoot, + defaultModel: defaultModel, + createWorkspaceRootIfMissing: createWorkspaceRootIfMissing + ) + ) + } + + @discardableResult + public func archive(threadID: String, archived: Bool) async throws -> DispatchResult { + try await dispatch(OrchestrationCommands.archive(threadID: threadID, archived: archived)) + } + + @discardableResult + public func delete(threadID: String) async throws -> DispatchResult { + try await dispatch(OrchestrationCommands.deleteThread(threadID: threadID)) + } + + @discardableResult + public func rename(threadID: String, title: String) async throws -> DispatchResult { + try await dispatch(OrchestrationCommands.rename(threadID: threadID, title: title)) + } + + @discardableResult + public func interrupt(threadID: String, turnID: String? = nil) async throws -> DispatchResult { + try await dispatch( + OrchestrationCommands.interrupt(threadID: threadID, turnID: turnID) + ) + } + + @discardableResult + public func respondToApproval( + threadID: String, + requestID: String, + decision: String + ) async throws -> DispatchResult { + try await dispatch( + OrchestrationCommands.respondToApproval( + threadID: threadID, + requestID: requestID, + decision: decision + ) + ) + } + + @discardableResult + public func respondToUserInput( + threadID: String, + requestID: String, + answers: [String: JSONValue] + ) async throws -> DispatchResult { + try await dispatch( + OrchestrationCommands.respondToUserInput( + threadID: threadID, + requestID: requestID, + answers: answers + ) + ) + } + + @discardableResult + public func settle(threadID: String, settled: Bool) async throws -> DispatchResult { + try await dispatch(OrchestrationCommands.settle(threadID: threadID, settled: settled)) + } + + @discardableResult + public func snooze(threadID: String, until: Date?) async throws -> DispatchResult { + try await dispatch( + OrchestrationCommands.snooze(threadID: threadID, until: until) + ) + } + + @discardableResult + public func setRuntimeMode( + threadID: String, + mode: RuntimeMode + ) async throws -> DispatchResult { + try await dispatch( + OrchestrationCommands.setRuntimeMode(threadID: threadID, mode: mode) + ) + } + + @discardableResult + public func setInteractionMode( + threadID: String, + mode: InteractionMode + ) async throws -> DispatchResult { + try await dispatch( + OrchestrationCommands.setInteractionMode(threadID: threadID, mode: mode) + ) + } + + // MARK: Workspace files + + public func listProjectEntries(cwd: String) async throws -> ProjectEntriesResult { + try await rpc.request( + RPCMethod.projectsListEntries.rawValue, + payload: .object(["cwd": .string(cwd)]), + as: ProjectEntriesResult.self + ) + } + + public func searchProjectEntries( + cwd: String, + query: String, + limit: Int = 100 + ) async throws -> ProjectEntriesResult { + try await rpc.request( + RPCMethod.projectsSearchEntries.rawValue, + payload: .object([ + "cwd": .string(cwd), + "query": .string(query), + "limit": .number(Double(limit)), + ]), + as: ProjectEntriesResult.self + ) + } + + public func readProjectFile( + cwd: String, + relativePath: String + ) async throws -> ProjectReadFileResult { + try await rpc.request( + RPCMethod.projectsReadFile.rawValue, + payload: .object([ + "cwd": .string(cwd), + "relativePath": .string(relativePath), + ]), + as: ProjectReadFileResult.self + ) + } + + public func writeProjectFile( + cwd: String, + relativePath: String, + contents: String + ) async throws -> ProjectWriteFileResult { + try await rpc.request( + RPCMethod.projectsWriteFile.rawValue, + payload: .object([ + "cwd": .string(cwd), + "relativePath": .string(relativePath), + "contents": .string(contents), + ]), + as: ProjectWriteFileResult.self + ) + } + + public func browseFilesystem( + partialPath: String, + cwd: String? = nil + ) async throws -> FilesystemBrowseResult { + var payload: [String: JSONValue] = ["partialPath": .string(partialPath)] + if let cwd { payload["cwd"] = .string(cwd) } + return try await rpc.request( + RPCMethod.filesystemBrowse.rawValue, + payload: .object(payload), + as: FilesystemBrowseResult.self + ) + } + + // MARK: VCS and source control + + public func refreshVCSStatus(cwd: String) async throws -> VCSStatus { + try await rpc.request( + RPCMethod.vcsRefreshStatus.rawValue, + payload: .object(["cwd": .string(cwd)]), + as: VCSStatus.self + ) + } + + public func vcsStatusEvents(cwd: String) async + -> AsyncThrowingStream + { + await rpc.subscribe( + RPCMethod.subscribeVCSStatus.rawValue, + payload: .object(["cwd": .string(cwd)]), + as: VCSStatusEvent.self + ) + } + + public func listVCSRefs( + cwd: String, + query: String? = nil, + cursor: Int? = nil, + kind: String? = nil, + refresh: Bool = false, + limit: Int = 100 + ) async throws -> VCSRefsResult { + var payload: [String: JSONValue] = [ + "cwd": .string(cwd), + "refresh": .bool(refresh), + "limit": .number(Double(limit)), + ] + if let query { payload["query"] = .string(query) } + if let cursor { payload["cursor"] = .number(Double(cursor)) } + if let kind { payload["refKind"] = .string(kind) } + return try await rpc.request( + RPCMethod.vcsListRefs.rawValue, + payload: .object(payload), + as: VCSRefsResult.self + ) + } + + public func pull(cwd: String) async throws -> VCSPullResult { + try await rpc.request( + RPCMethod.vcsPull.rawValue, + payload: .object(["cwd": .string(cwd)]), + as: VCSPullResult.self + ) + } + + public func createVCSRef( + cwd: String, + name: String, + switchToRef: Bool = true + ) async throws -> VCSCreateRefResult { + try await rpc.request( + RPCMethod.vcsCreateRef.rawValue, + payload: .object([ + "cwd": .string(cwd), + "refName": .string(name), + "switchRef": .bool(switchToRef), + ]), + as: VCSCreateRefResult.self + ) + } + + public func switchVCSRef(cwd: String, name: String) async throws -> VCSSwitchRefResult { + try await rpc.request( + RPCMethod.vcsSwitchRef.rawValue, + payload: .object([ + "cwd": .string(cwd), + "refName": .string(name), + ]), + as: VCSSwitchRefResult.self + ) + } + + public func createWorktree( + cwd: String, + refName: String, + newRefName: String? = nil, + baseRefName: String? = nil, + path: String? = nil + ) async throws -> VCSCreateWorktreeResult { + var payload: [String: JSONValue] = [ + "cwd": .string(cwd), + "refName": .string(refName), + "path": path.map(JSONValue.string) ?? .null, + ] + if let newRefName { payload["newRefName"] = .string(newRefName) } + if let baseRefName { payload["baseRefName"] = .string(baseRefName) } + return try await rpc.request( + RPCMethod.vcsCreateWorktree.rawValue, + payload: .object(payload), + as: VCSCreateWorktreeResult.self + ) + } + + public func removeWorktree(cwd: String, path: String, force: Bool = false) async throws { + try await rpc.request( + RPCMethod.vcsRemoveWorktree.rawValue, + payload: .object([ + "cwd": .string(cwd), + "path": .string(path), + "force": .bool(force), + ]) + ) + } + + public func initializeVCS(cwd: String, kind: String? = nil) async throws { + var payload: [String: JSONValue] = ["cwd": .string(cwd)] + if let kind { payload["kind"] = .string(kind) } + try await rpc.request(RPCMethod.vcsInitialize.rawValue, payload: .object(payload)) + } + + public func runGitAction( + cwd: String, + action: GitStackedAction, + commitMessage: String? = nil, + featureBranch: Bool? = nil, + filePaths: [String]? = nil, + actionID: String = UUID().uuidString + ) async throws -> AsyncThrowingStream { + var payload: [String: JSONValue] = [ + "actionId": .string(actionID), + "cwd": .string(cwd), + "action": .string(action.rawValue), + ] + if let commitMessage { payload["commitMessage"] = .string(commitMessage) } + if let featureBranch { payload["featureBranch"] = .bool(featureBranch) } + if let filePaths { payload["filePaths"] = .array(filePaths.map(JSONValue.string)) } + // A command stream must fail on disconnect instead of replaying a + // potentially successful commit or push. + return await rpc.subscribe( + RPCMethod.gitRunStackedAction.rawValue, + payload: .object(payload), + reconnect: false, + as: GitActionProgressEvent.self + ) + } + + public func lookupRepository( + provider: SourceControlProviderKind, + repository: String, + cwd: String? = nil + ) async throws -> SourceControlRepositoryInfo { + var payload: [String: JSONValue] = [ + "provider": .string(provider.rawValue), + "repository": .string(repository), + ] + if let cwd { payload["cwd"] = .string(cwd) } + return try await rpc.request( + RPCMethod.sourceControlLookup.rawValue, + payload: .object(payload), + as: SourceControlRepositoryInfo.self + ) + } + + public func cloneRepository( + provider: SourceControlProviderKind? = nil, + repository: String? = nil, + remoteURL: String? = nil, + destinationPath: String, + cloneProtocol: String? = nil + ) async throws -> SourceControlCloneResult { + var payload: [String: JSONValue] = ["destinationPath": .string(destinationPath)] + if let provider { payload["provider"] = .string(provider.rawValue) } + if let repository { payload["repository"] = .string(repository) } + if let remoteURL { payload["remoteUrl"] = .string(remoteURL) } + if let cloneProtocol { payload["protocol"] = .string(cloneProtocol) } + return try await rpc.request( + RPCMethod.sourceControlClone.rawValue, + payload: .object(payload), + as: SourceControlCloneResult.self + ) + } + + public func publishRepository( + cwd: String, + provider: SourceControlProviderKind, + repository: String, + visibility: String, + remoteName: String? = nil, + cloneProtocol: String? = nil + ) async throws -> SourceControlPublishResult { + var payload: [String: JSONValue] = [ + "cwd": .string(cwd), + "provider": .string(provider.rawValue), + "repository": .string(repository), + "visibility": .string(visibility), + ] + if let remoteName { payload["remoteName"] = .string(remoteName) } + if let cloneProtocol { payload["protocol"] = .string(cloneProtocol) } + return try await rpc.request( + RPCMethod.sourceControlPublish.rawValue, + payload: .object(payload), + as: SourceControlPublishResult.self + ) + } + + // MARK: Review + + public func reviewDiffPreview( + cwd: String, + baseRef: String? = nil, + ignoreWhitespace: Bool = false + ) async throws -> ReviewDiffPreview { + var payload: [String: JSONValue] = [ + "cwd": .string(cwd), + "ignoreWhitespace": .bool(ignoreWhitespace), + ] + if let baseRef { payload["baseRef"] = .string(baseRef) } + return try await rpc.request( + RPCMethod.reviewDiffPreview.rawValue, + payload: .object(payload), + as: ReviewDiffPreview.self + ) + } + + // MARK: Terminal + + public func openTerminal( + threadID: String, + terminalID: String, + cwd: String, + worktreePath: String? = nil, + columns: Int? = nil, + rows: Int? = nil, + environmentVariables: [String: String]? = nil + ) async throws -> TerminalSessionSnapshot { + let payload = try terminalPayload( + threadID: threadID, + terminalID: terminalID, + cwd: cwd, + worktreePath: worktreePath, + columns: columns, + rows: rows, + environmentVariables: environmentVariables + ) + return try await rpc.request( + RPCMethod.terminalOpen.rawValue, + payload: payload, + as: TerminalSessionSnapshot.self + ) + } + + public func attachTerminal( + threadID: String, + terminalID: String, + cwd: String? = nil, + worktreePath: String? = nil, + columns: Int? = nil, + rows: Int? = nil, + environmentVariables: [String: String]? = nil, + restartIfNotRunning: Bool = false + ) async throws -> AsyncThrowingStream { + var payload = try terminalPayloadObject( + threadID: threadID, + terminalID: terminalID, + cwd: cwd, + worktreePath: worktreePath, + columns: columns, + rows: rows, + environmentVariables: environmentVariables + ) + payload["restartIfNotRunning"] = .bool(restartIfNotRunning) + return await rpc.subscribe( + RPCMethod.terminalAttach.rawValue, + payload: .object(payload), + as: TerminalEvent.self + ) + } + + public func terminalEvents() async -> AsyncThrowingStream { + await rpc.subscribe( + RPCMethod.subscribeTerminalEvents.rawValue, + as: TerminalEvent.self + ) + } + + public func terminalMetadataEvents() async + -> AsyncThrowingStream + { + await rpc.subscribe( + RPCMethod.subscribeTerminalMetadata.rawValue, + as: TerminalMetadataEvent.self + ) + } + + public func writeTerminal( + threadID: String, + terminalID: String, + data: String + ) async throws { + try await rpc.request( + RPCMethod.terminalWrite.rawValue, + payload: .object([ + "threadId": .string(threadID), + "terminalId": .string(terminalID), + "data": .string(data), + ]) + ) + } + + public func resizeTerminal( + threadID: String, + terminalID: String, + columns: Int, + rows: Int + ) async throws { + try await rpc.request( + RPCMethod.terminalResize.rawValue, + payload: .object([ + "threadId": .string(threadID), + "terminalId": .string(terminalID), + "cols": .number(Double(columns)), + "rows": .number(Double(rows)), + ]) + ) + } + + public func clearTerminal(threadID: String, terminalID: String) async throws { + try await rpc.request( + RPCMethod.terminalClear.rawValue, + payload: terminalIdentity(threadID: threadID, terminalID: terminalID) + ) + } + + public func restartTerminal( + threadID: String, + terminalID: String, + cwd: String, + worktreePath: String? = nil, + columns: Int, + rows: Int, + environmentVariables: [String: String]? = nil + ) async throws -> TerminalSessionSnapshot { + let payload = try terminalPayload( + threadID: threadID, + terminalID: terminalID, + cwd: cwd, + worktreePath: worktreePath, + columns: columns, + rows: rows, + environmentVariables: environmentVariables + ) + return try await rpc.request( + RPCMethod.terminalRestart.rawValue, + payload: payload, + as: TerminalSessionSnapshot.self + ) + } + + public func closeTerminal( + threadID: String, + terminalID: String? = nil, + deleteHistory: Bool = false + ) async throws { + var payload: [String: JSONValue] = [ + "threadId": .string(threadID), + "deleteHistory": .bool(deleteHistory), + ] + if let terminalID { payload["terminalId"] = .string(terminalID) } + try await rpc.request(RPCMethod.terminalClose.rawValue, payload: .object(payload)) + } + + private func terminalIdentity(threadID: String, terminalID: String) -> JSONValue { + .object([ + "threadId": .string(threadID), + "terminalId": .string(terminalID), + ]) + } + + private func terminalPayload( + threadID: String, + terminalID: String, + cwd: String?, + worktreePath: String?, + columns: Int?, + rows: Int?, + environmentVariables: [String: String]? + ) throws -> JSONValue { + .object( + try terminalPayloadObject( + threadID: threadID, + terminalID: terminalID, + cwd: cwd, + worktreePath: worktreePath, + columns: columns, + rows: rows, + environmentVariables: environmentVariables + ) + ) + } + + private func terminalPayloadObject( + threadID: String, + terminalID: String, + cwd: String?, + worktreePath: String?, + columns: Int?, + rows: Int?, + environmentVariables: [String: String]? + ) throws -> [String: JSONValue] { + var payload: [String: JSONValue] = [ + "threadId": .string(threadID), + "terminalId": .string(terminalID), + ] + if let cwd { payload["cwd"] = .string(cwd) } + if let worktreePath { + payload["worktreePath"] = .string(worktreePath) + } else if cwd != nil { + payload["worktreePath"] = .null + } + if let columns { payload["cols"] = .number(Double(columns)) } + if let rows { payload["rows"] = .number(Double(rows)) } + if let environmentVariables { + payload["env"] = try JSONValue.encode(environmentVariables) + } + return payload + } +} + +/// Owns persisted environment selection and constructs scoped clients without +/// introducing UI-framework state into Core. +public actor EnvironmentRuntime { + public let environmentStore: EnvironmentStore + public let credentialStore: any CredentialStore + private let httpTransport: any HTTPTransport + private let webSocketConnector: any WebSocketConnecting + private var clients: [String: T3Client] = [:] + + public init( + environmentStore: EnvironmentStore = EnvironmentStore(), + credentialStore: any CredentialStore = KeychainCredentialStore(), + httpTransport: any HTTPTransport = URLSessionHTTPTransport(), + webSocketConnector: any WebSocketConnecting = URLSessionWebSocketConnector() + ) { + self.environmentStore = environmentStore + self.credentialStore = credentialStore + self.httpTransport = httpTransport + self.webSocketConnector = webSocketConnector + } + + public func environments() async throws -> [Environment] { + try await environmentStore.load() + } + + public func activeEnvironment() async throws -> Environment? { + let environments = try await environmentStore.load() + guard !environments.isEmpty else { return nil } + let activeID = try await environmentStore.activeEnvironmentID() + return environments.first(where: { $0.id == activeID }) ?? environments[0] + } + + @discardableResult + public func activate(id: String) async throws -> T3Client { + let environments = try await environmentStore.load() + guard let environment = environments.first(where: { $0.id == id }) else { + throw RPCError.remote("Environment \(id) is not saved.") + } + try await environmentStore.setActiveEnvironment(id: id) + return client(for: environment) + } + + public func activeClient() async throws -> T3Client? { + guard let environment = try await activeEnvironment() else { return nil } + return client(for: environment) + } + + @discardableResult + public func pair(url: String, clientLabel: String? = nil) async throws -> T3Client { + let service = PairingService( + transport: httpTransport, + environmentStore: environmentStore, + credentialStore: credentialStore + ) + let environment = try await service.pair(url: url, label: clientLabel) + try await environmentStore.setActiveEnvironment(id: environment.id) + return client(for: environment) + } + + @discardableResult + public func pair( + host: String, + code: String, + clientLabel: String? = nil + ) async throws -> T3Client { + let service = PairingService( + transport: httpTransport, + environmentStore: environmentStore, + credentialStore: credentialStore + ) + let environment = try await service.pair(host: host, code: code, label: clientLabel) + try await environmentStore.setActiveEnvironment(id: environment.id) + return client(for: environment) + } + + public func remove(id: String) async throws { + if let client = clients.removeValue(forKey: id) { + await client.disconnect() + } + try await credentialStore.removeCredential(for: id) + try await environmentStore.remove(id: id) + } + + private func client(for environment: Environment) -> T3Client { + if let existing = clients[environment.id] { return existing } + let client = T3Client( + environment: environment, + credentialStore: credentialStore, + httpTransport: httpTransport, + webSocketConnector: webSocketConnector + ) + clients[environment.id] = client + return client + } +} + +public enum RPCMethod: String, Sendable { + case serverProbe = "server.probe" + case serverGetConfig = "server.getConfig" + case dispatchCommand = "orchestration.dispatchCommand" + case subscribeShell = "orchestration.subscribeShell" + case subscribeThread = "orchestration.subscribeThread" + case projectsListEntries = "projects.listEntries" + case projectsSearchEntries = "projects.searchEntries" + case projectsReadFile = "projects.readFile" + case projectsWriteFile = "projects.writeFile" + case filesystemBrowse = "filesystem.browse" + case subscribeVCSStatus = "subscribeVcsStatus" + case vcsPull = "vcs.pull" + case vcsRefreshStatus = "vcs.refreshStatus" + case vcsListRefs = "vcs.listRefs" + case vcsCreateRef = "vcs.createRef" + case vcsSwitchRef = "vcs.switchRef" + case vcsCreateWorktree = "vcs.createWorktree" + case vcsRemoveWorktree = "vcs.removeWorktree" + case vcsInitialize = "vcs.init" + case gitRunStackedAction = "git.runStackedAction" + case sourceControlLookup = "sourceControl.lookupRepository" + case sourceControlClone = "sourceControl.cloneRepository" + case sourceControlPublish = "sourceControl.publishRepository" + case reviewDiffPreview = "review.getDiffPreview" + case terminalOpen = "terminal.open" + case terminalAttach = "terminal.attach" + case terminalWrite = "terminal.write" + case terminalResize = "terminal.resize" + case terminalClear = "terminal.clear" + case terminalRestart = "terminal.restart" + case terminalClose = "terminal.close" + case subscribeTerminalEvents + case subscribeTerminalMetadata +} + +public enum OrchestrationCommands { + public static func createThread( + threadID: String = UUID().uuidString, + projectID: String, + title: String, + model: ModelSelection, + runtimeMode: RuntimeMode, + interactionMode: InteractionMode = .default, + branch: String? = nil, + worktreePath: String? = nil, + commandID: String = UUID().uuidString, + createdAt: String = now() + ) throws -> JSONValue { + .object([ + "type": .string("thread.create"), + "commandId": .string(commandID), + "threadId": .string(threadID), + "projectId": .string(projectID), + "title": .string(title), + "modelSelection": try .encode(model), + "runtimeMode": .string(runtimeMode.rawValue), + "interactionMode": .string(interactionMode.rawValue), + "branch": branch.map(JSONValue.string) ?? .null, + "worktreePath": worktreePath.map(JSONValue.string) ?? .null, + "createdAt": .string(createdAt), + ]) + } + + public static func createProject( + projectID: String = UUID().uuidString, + title: String, + workspaceRoot: String, + defaultModel: ModelSelection? = nil, + createWorkspaceRootIfMissing: Bool = false, + commandID: String = UUID().uuidString, + createdAt: String = now() + ) throws -> JSONValue { + var value: [String: JSONValue] = [ + "type": .string("project.create"), + "commandId": .string(commandID), + "projectId": .string(projectID), + "title": .string(title), + "workspaceRoot": .string(workspaceRoot), + "createWorkspaceRootIfMissing": .bool(createWorkspaceRootIfMissing), + "createdAt": .string(createdAt), + ] + if let defaultModel { + value["defaultModelSelection"] = try JSONValue.encode(defaultModel) + } else { + value["defaultModelSelection"] = .null + } + return .object(value) + } + + public static func sendTurn( + threadID: String, + text: String, + runtimeMode: RuntimeMode, + interactionMode: InteractionMode = .default, + commandID: String = UUID().uuidString, + messageID: String = UUID().uuidString, + createdAt: String = now() + ) -> JSONValue { + .object([ + "type": .string("thread.turn.start"), + "commandId": .string(commandID), + "threadId": .string(threadID), + "message": .object([ + "messageId": .string(messageID), + "role": .string("user"), + "text": .string(text), + "attachments": .array([]), + ]), + "runtimeMode": .string(runtimeMode.rawValue), + "interactionMode": .string(interactionMode.rawValue), + "createdAt": .string(createdAt), + ]) + } + + public static func createThreadAndSend( + threadID: String = UUID().uuidString, + projectID: String, + title: String, + text: String, + model: ModelSelection, + runtimeMode: RuntimeMode, + interactionMode: InteractionMode = .default, + branch: String? = nil, + worktreePath: String? = nil, + commandID: String = UUID().uuidString, + messageID: String = UUID().uuidString, + createdAt: String = now() + ) throws -> JSONValue { + var create: [String: JSONValue] = [ + "projectId": .string(projectID), + "title": .string(title), + "modelSelection": try .encode(model), + "runtimeMode": .string(runtimeMode.rawValue), + "interactionMode": .string(interactionMode.rawValue), + "branch": branch.map(JSONValue.string) ?? .null, + "worktreePath": worktreePath.map(JSONValue.string) ?? .null, + "createdAt": .string(createdAt), + ] + create["createdAt"] = .string(createdAt) + return .object([ + "type": .string("thread.turn.start"), + "commandId": .string(commandID), + "threadId": .string(threadID), + "message": .object([ + "messageId": .string(messageID), + "role": .string("user"), + "text": .string(text), + "attachments": .array([]), + ]), + "runtimeMode": .string(runtimeMode.rawValue), + "interactionMode": .string(interactionMode.rawValue), + "bootstrap": .object(["createThread": .object(create)]), + "createdAt": .string(createdAt), + ]) + } + + public static func archive( + threadID: String, + archived: Bool, + commandID: String = UUID().uuidString + ) -> JSONValue { + basic( + type: archived ? "thread.archive" : "thread.unarchive", + threadID: threadID, + commandID: commandID + ) + } + + public static func deleteThread( + threadID: String, + commandID: String = UUID().uuidString + ) -> JSONValue { + basic(type: "thread.delete", threadID: threadID, commandID: commandID) + } + + public static func rename( + threadID: String, + title: String, + commandID: String = UUID().uuidString + ) -> JSONValue { + .object([ + "type": .string("thread.meta.update"), + "commandId": .string(commandID), + "threadId": .string(threadID), + "title": .string(title), + ]) + } + + public static func interrupt( + threadID: String, + turnID: String?, + commandID: String = UUID().uuidString, + createdAt: String = now() + ) -> JSONValue { + var value: [String: JSONValue] = [ + "type": .string("thread.turn.interrupt"), + "commandId": .string(commandID), + "threadId": .string(threadID), + "createdAt": .string(createdAt), + ] + if let turnID { value["turnId"] = .string(turnID) } + return .object(value) + } + + public static func respondToApproval( + threadID: String, + requestID: String, + decision: String, + commandID: String = UUID().uuidString, + createdAt: String = now() + ) -> JSONValue { + .object([ + "type": .string("thread.approval.respond"), + "commandId": .string(commandID), + "threadId": .string(threadID), + "requestId": .string(requestID), + "decision": .string(decision), + "createdAt": .string(createdAt), + ]) + } + + public static func respondToUserInput( + threadID: String, + requestID: String, + answers: [String: JSONValue], + commandID: String = UUID().uuidString, + createdAt: String = now() + ) -> JSONValue { + .object([ + "type": .string("thread.user-input.respond"), + "commandId": .string(commandID), + "threadId": .string(threadID), + "requestId": .string(requestID), + "answers": .object(answers), + "createdAt": .string(createdAt), + ]) + } + + public static func settle( + threadID: String, + settled: Bool, + commandID: String = UUID().uuidString + ) -> JSONValue { + var value = basic( + type: settled ? "thread.settle" : "thread.unsettle", + threadID: threadID, + commandID: commandID + ) + if !settled, case var .object(object) = value { + object["reason"] = .string("user") + value = .object(object) + } + return value + } + + public static func snooze( + threadID: String, + until: Date?, + commandID: String = UUID().uuidString + ) -> JSONValue { + if let until { + return .object([ + "type": .string("thread.snooze"), + "commandId": .string(commandID), + "threadId": .string(threadID), + "snoozedUntil": .string(ISO8601DateFormatter().string(from: until)), + ]) + } + return .object([ + "type": .string("thread.unsnooze"), + "commandId": .string(commandID), + "threadId": .string(threadID), + "reason": .string("user"), + ]) + } + + public static func setRuntimeMode( + threadID: String, + mode: RuntimeMode, + commandID: String = UUID().uuidString, + createdAt: String = now() + ) -> JSONValue { + .object([ + "type": .string("thread.runtime-mode.set"), + "commandId": .string(commandID), + "threadId": .string(threadID), + "runtimeMode": .string(mode.rawValue), + "createdAt": .string(createdAt), + ]) + } + + public static func setInteractionMode( + threadID: String, + mode: InteractionMode, + commandID: String = UUID().uuidString, + createdAt: String = now() + ) -> JSONValue { + .object([ + "type": .string("thread.interaction-mode.set"), + "commandId": .string(commandID), + "threadId": .string(threadID), + "interactionMode": .string(mode.rawValue), + "createdAt": .string(createdAt), + ]) + } + + private static func basic(type: String, threadID: String, commandID: String) -> JSONValue { + .object([ + "type": .string(type), + "commandId": .string(commandID), + "threadId": .string(threadID), + ]) + } + + public static func now() -> String { + ISO8601DateFormatter().string(from: Date()) + } +} diff --git a/apps/swift-ios/Core/WebSocketRPC.swift b/apps/swift-ios/Core/WebSocketRPC.swift new file mode 100644 index 0000000000..8b38e6dcb8 --- /dev/null +++ b/apps/swift-ios/Core/WebSocketRPC.swift @@ -0,0 +1,425 @@ +import Foundation + +public protocol WebSocketConnection: Sendable { + func send(_ data: Data) async throws + func receive() async throws -> Data + func close() async +} + +public protocol WebSocketConnecting: Sendable { + func connect(to url: URL) async throws -> any WebSocketConnection +} + +public struct URLSessionWebSocketConnector: WebSocketConnecting { + private let session: URLSession + + public init(session: URLSession = .shared) { + self.session = session + } + + public func connect(to url: URL) async throws -> any WebSocketConnection { + let connection = URLSessionWebSocketConnection(session: session, url: url) + await connection.open() + return connection + } +} + +private actor URLSessionWebSocketConnection: WebSocketConnection { + private let task: URLSessionWebSocketTask + + init(session: URLSession, url: URL) { + task = session.webSocketTask(with: url) + } + + func open() { + task.resume() + } + + func send(_ data: Data) async throws { + try await task.send(.data(data)) + } + + func receive() async throws -> Data { + switch try await task.receive() { + case let .data(data): + return data + case let .string(string): + guard let data = string.data(using: .utf8) else { + throw RPCError.protocolViolation("WebSocket text was not UTF-8.") + } + return data + @unknown default: + throw RPCError.protocolViolation("Unknown WebSocket message.") + } + } + + func close() { + task.cancel(with: .goingAway, reason: nil) + } +} + +public enum RPCError: LocalizedError, Sendable { + case disconnected + case remote(String) + case protocolViolation(String) + + public var errorDescription: String? { + switch self { + case .disconnected: "The environment disconnected." + case let .remote(message): message + case let .protocolViolation(message): message + } + } +} + +private struct RPCRequestEnvelope: Encodable, Sendable { + let _tag = "Request" + let id: Int + let tag: String + let payload: JSONValue + let headers: [[String]] +} + +private struct RPCControlEnvelope: Encodable, Sendable { + let _tag: String + let requestId: Int? + + init(_ tag: String, requestID: Int? = nil) { + _tag = tag + requestId = requestID + } +} + +private struct RPCResponseEnvelope: Decodable, Sendable { + struct Exit: Decodable, Sendable { + struct Cause: Decodable, Sendable { + let _tag: String + let error: JSONValue? + let defect: JSONValue? + } + + let _tag: String + let value: JSONValue? + let cause: [Cause]? + } + + let _tag: String + let requestId: Int? + let values: [JSONValue]? + let exit: Exit? + let defect: JSONValue? +} + +/// Implements Effect RPC's JSON socket framing. Subscriptions survive +/// reconnects; unary calls that crossed a broken connection fail rather than +/// being replayed, because replaying a command could duplicate side effects. +public actor WebSocketRPCClient { + public typealias EndpointProvider = @Sendable () async throws -> URL + + private struct UnaryRequest { + let envelope: RPCRequestEnvelope + var sent: Bool + let resume: @Sendable (Result) -> Void + } + + private struct Subscription { + let tag: String + let payload: JSONValue + let reconnect: Bool + var requestID: Int? + let yield: @Sendable (JSONValue) -> Void + let finish: @Sendable (Error?) -> Void + } + + private let connector: any WebSocketConnecting + private let endpointProvider: EndpointProvider + private var connection: (any WebSocketConnection)? + private var loopTask: Task? + private var keepaliveTask: Task? + private var desired = false + private var nextRequestID = 1 + private var unary: [Int: UnaryRequest] = [:] + private var subscriptions: [UUID: Subscription] = [:] + private var subscriptionByRequestID: [Int: UUID] = [:] + + public init( + connector: any WebSocketConnecting = URLSessionWebSocketConnector(), + endpointProvider: @escaping EndpointProvider + ) { + self.connector = connector + self.endpointProvider = endpointProvider + } + + deinit { + loopTask?.cancel() + keepaliveTask?.cancel() + } + + public func start() { + desired = true + guard loopTask == nil else { return } + loopTask = Task { await self.connectionLoop() } + } + + public func stop() async { + desired = false + loopTask?.cancel() + loopTask = nil + keepaliveTask?.cancel() + keepaliveTask = nil + if let connection { + await connection.close() + } + connection = nil + failUnary(RPCError.disconnected, includingUnsent: true) + let active = subscriptions.values + subscriptions.removeAll() + subscriptionByRequestID.removeAll() + active.forEach { $0.finish(RPCError.disconnected) } + } + + public func request( + _ tag: String, + payload: JSONValue = .object([:]), + as type: Result.Type + ) async throws -> Result { + let raw = try await requestRaw(tag, payload: payload) + return try raw.decode(type) + } + + public func request( + _ tag: String, + payload: JSONValue = .object([:]) + ) async throws { + _ = try await requestRaw(tag, payload: payload) + } + + public func subscribe( + _ tag: String, + payload: JSONValue = .object([:]), + reconnect: Bool = true, + as type: Value.Type + ) -> AsyncThrowingStream { + let subscriptionID = UUID() + return AsyncThrowingStream { continuation in + subscriptions[subscriptionID] = Subscription( + tag: tag, + payload: payload, + reconnect: reconnect, + requestID: nil, + yield: { value in + do { + continuation.yield(try value.decode(type)) + } catch { + continuation.finish(throwing: error) + } + }, + finish: { error in + if let error { + continuation.finish(throwing: error) + } else { + continuation.finish() + } + } + ) + continuation.onTermination = { @Sendable _ in + Task { await self.removeSubscription(subscriptionID) } + } + if connection != nil { + Task { await self.sendSubscription(subscriptionID) } + } + start() + } + } + + private func requestRaw(_ tag: String, payload: JSONValue) async throws -> JSONValue { + start() + let id = allocateRequestID() + let envelope = RPCRequestEnvelope( + id: id, + tag: tag, + payload: payload, + headers: [] + ) + return try await withCheckedThrowingContinuation { continuation in + unary[id] = UnaryRequest( + envelope: envelope, + sent: false, + resume: { continuation.resume(with: $0) } + ) + if connection != nil { + Task { await self.sendUnary(id) } + } + } + } + + private func connectionLoop() async { + var retry = 0 + while desired, !Task.isCancelled { + do { + let url = try await endpointProvider() + let opened = try await connector.connect(to: url) + connection = opened + retry = 0 + await connected() + try await receiveLoop(opened) + } catch is CancellationError { + break + } catch { + await disconnected() + guard desired, !Task.isCancelled else { break } + retry += 1 + let delay = min(5.0, 0.35 * pow(1.7, Double(retry - 1))) + try? await Task.sleep(for: .seconds(delay)) + } + } + loopTask = nil + } + + private func connected() async { + keepaliveTask?.cancel() + keepaliveTask = Task { await self.keepaliveLoop() } + for id in unary.keys { + await sendUnary(id) + } + subscriptionByRequestID.removeAll() + for id in subscriptions.keys { + await sendSubscription(id) + } + } + + private func disconnected() async { + keepaliveTask?.cancel() + keepaliveTask = nil + connection = nil + failUnary(RPCError.disconnected, includingUnsent: false) + subscriptionByRequestID.removeAll() + let oneShotSubscriptions = subscriptions.filter { !$0.value.reconnect } + for (id, subscription) in oneShotSubscriptions { + subscriptions.removeValue(forKey: id) + subscription.finish(RPCError.disconnected) + } + for id in subscriptions.keys { + subscriptions[id]?.requestID = nil + } + } + + private func receiveLoop(_ opened: any WebSocketConnection) async throws { + while desired, !Task.isCancelled { + let data = try await opened.receive() + let response = try JSONDecoder.t3.decode(RPCResponseEnvelope.self, from: data) + try await handle(response) + } + } + + private func handle(_ response: RPCResponseEnvelope) async throws { + switch response._tag { + case "Pong": + return + case "Chunk": + guard let requestID = response.requestId, + let subscriptionID = subscriptionByRequestID[requestID], + let subscription = subscriptions[subscriptionID] + else { return } + response.values?.forEach(subscription.yield) + try await sendControl("Ack", requestID: requestID) + case "Exit": + guard let requestID = response.requestId, let exit = response.exit else { return } + if var request = unary.removeValue(forKey: requestID) { + request.sent = false + if exit._tag == "Success" { + request.resume(.success(exit.value ?? .null)) + } else { + request.resume(.failure(remoteError(exit))) + } + return + } + guard let subscriptionID = subscriptionByRequestID.removeValue(forKey: requestID), + let subscription = subscriptions.removeValue(forKey: subscriptionID) + else { return } + subscription.finish(exit._tag == "Success" ? nil : remoteError(exit)) + case "Defect", "ClientProtocolError": + throw RPCError.remote( + response.defect?.stringValue ?? "The server reported an RPC protocol error." + ) + default: + throw RPCError.protocolViolation("Unknown RPC response \(response._tag).") + } + } + + private func sendUnary(_ id: Int) async { + guard let connection, var request = unary[id], !request.sent else { return } + do { + try await connection.send(JSONEncoder.t3.encode(request.envelope)) + request.sent = true + unary[id] = request + } catch { + request.resume(.failure(error)) + unary.removeValue(forKey: id) + } + } + + private func sendSubscription(_ subscriptionID: UUID) async { + guard let connection, var subscription = subscriptions[subscriptionID] else { return } + let requestID = allocateRequestID() + let envelope = RPCRequestEnvelope( + id: requestID, + tag: subscription.tag, + payload: subscription.payload, + headers: [] + ) + do { + try await connection.send(JSONEncoder.t3.encode(envelope)) + subscription.requestID = requestID + subscriptions[subscriptionID] = subscription + subscriptionByRequestID[requestID] = subscriptionID + } catch { + // The connection loop owns retries; retaining this subscription is + // enough for it to be sent on the next socket. + } + } + + private func removeSubscription(_ id: UUID) async { + guard let subscription = subscriptions.removeValue(forKey: id) else { return } + if let requestID = subscription.requestID { + subscriptionByRequestID.removeValue(forKey: requestID) + try? await sendControl("Interrupt", requestID: requestID) + } + } + + private func keepaliveLoop() async { + while desired, connection != nil, !Task.isCancelled { + try? await Task.sleep(for: .seconds(5)) + guard desired, connection != nil, !Task.isCancelled else { return } + try? await sendControl("Ping", requestID: nil) + } + } + + private func sendControl(_ tag: String, requestID: Int?) async throws { + guard let connection else { throw RPCError.disconnected } + try await connection.send( + JSONEncoder.t3.encode(RPCControlEnvelope(tag, requestID: requestID)) + ) + } + + private func failUnary(_ error: Error, includingUnsent: Bool) { + let failed = unary.filter { includingUnsent || $0.value.sent } + for (id, request) in failed { + unary.removeValue(forKey: id) + request.resume(.failure(error)) + } + } + + private func remoteError(_ exit: RPCResponseEnvelope.Exit) -> RPCError { + let value = exit.cause?.first?.error + let message = value?["message"]?.stringValue + ?? value?["detail"]?.stringValue + ?? "The environment rejected the RPC request." + return .remote(message) + } + + private func allocateRequestID() -> Int { + defer { nextRequestID += 1 } + return nextRequestID + } +} diff --git a/apps/swift-ios/Core/WorkspaceModels.swift b/apps/swift-ios/Core/WorkspaceModels.swift new file mode 100644 index 0000000000..11f86ad69c --- /dev/null +++ b/apps/swift-ios/Core/WorkspaceModels.swift @@ -0,0 +1,343 @@ +import Foundation + +// MARK: - Project files + +public enum ProjectEntryKind: String, Codable, Sendable { + case file + case directory +} + +public struct ProjectEntry: Codable, Equatable, Sendable { + public let path: String + public let kind: ProjectEntryKind +} + +public struct ProjectEntriesResult: Codable, Equatable, Sendable { + public let entries: [ProjectEntry] + public let truncated: Bool +} + +public struct ProjectReadFileResult: Codable, Equatable, Sendable { + public let relativePath: String + public let contents: String + public let byteLength: Int + public let truncated: Bool +} + +public struct ProjectWriteFileResult: Codable, Equatable, Sendable { + public let relativePath: String +} + +public struct FilesystemBrowseEntry: Codable, Equatable, Sendable { + public let name: String + public let fullPath: String +} + +public struct FilesystemBrowseResult: Codable, Equatable, Sendable { + public let parentPath: String + public let entries: [FilesystemBrowseEntry] +} + +// MARK: - Source control and VCS + +public enum SourceControlProviderKind: String, Codable, CaseIterable, Sendable { + case github + case gitlab + case azureDevOps = "azure-devops" + case bitbucket + case unknown +} + +public struct SourceControlProviderInfo: Codable, Equatable, Sendable { + public let kind: SourceControlProviderKind + public let name: String + public let baseUrl: String +} + +public struct SourceControlRepositoryInfo: Codable, Equatable, Sendable { + public let provider: SourceControlProviderKind + public let nameWithOwner: String + public let url: String + public let sshUrl: String +} + +public struct SourceControlCloneResult: Codable, Equatable, Sendable { + public let cwd: String + public let remoteUrl: String + public let repository: SourceControlRepositoryInfo? +} + +public struct SourceControlPublishResult: Codable, Equatable, Sendable { + public let repository: SourceControlRepositoryInfo + public let remoteName: String + public let remoteUrl: String + public let branch: String + public let upstreamBranch: String? + public let status: String +} + +public struct VCSWorkingTreeFile: Codable, Equatable, Sendable { + public let path: String + public let insertions: Int + public let deletions: Int +} + +public struct VCSWorkingTree: Codable, Equatable, Sendable { + public let files: [VCSWorkingTreeFile] + public let insertions: Int + public let deletions: Int +} + +public struct VCSChangeRequest: Codable, Equatable, Sendable { + public let number: Int + public let title: String + public let url: String + public let baseRef: String + public let headRef: String + public let state: String +} + +public struct VCSLocalStatus: Codable, Equatable, Sendable { + public let isRepo: Bool + public let sourceControlProvider: SourceControlProviderInfo? + public let hasPrimaryRemote: Bool + public let isDefaultRef: Bool + public let refName: String? + public let hasWorkingTreeChanges: Bool + public let workingTree: VCSWorkingTree +} + +public struct VCSRemoteStatus: Codable, Equatable, Sendable { + public let hasUpstream: Bool + public let aheadCount: Int + public let behindCount: Int + public let aheadOfDefaultCount: Int? + public let pr: VCSChangeRequest? +} + +public struct VCSStatus: Codable, Equatable, Sendable { + public let isRepo: Bool + public let sourceControlProvider: SourceControlProviderInfo? + public let hasPrimaryRemote: Bool + public let isDefaultRef: Bool + public let refName: String? + public let hasWorkingTreeChanges: Bool + public let workingTree: VCSWorkingTree + public let hasUpstream: Bool + public let aheadCount: Int + public let behindCount: Int + public let aheadOfDefaultCount: Int? + public let pr: VCSChangeRequest? +} + +public enum VCSStatusEvent: Decodable, Sendable { + case snapshot(local: VCSLocalStatus, remote: VCSRemoteStatus?) + case localUpdated(VCSLocalStatus) + case remoteUpdated(VCSRemoteStatus?) + + private enum CodingKeys: String, CodingKey { case _tag, local, remote } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let tag = try container.decode(String.self, forKey: ._tag) + switch tag { + case "snapshot": + self = .snapshot( + local: try container.decode(VCSLocalStatus.self, forKey: .local), + remote: try container.decodeIfPresent(VCSRemoteStatus.self, forKey: .remote) + ) + case "localUpdated": + self = .localUpdated(try container.decode(VCSLocalStatus.self, forKey: .local)) + case "remoteUpdated": + self = .remoteUpdated( + try container.decodeIfPresent(VCSRemoteStatus.self, forKey: .remote) + ) + default: + throw DecodingError.dataCorruptedError( + forKey: ._tag, + in: container, + debugDescription: "Unknown VCS status event \(tag)" + ) + } + } +} + +public struct VCSRef: Codable, Equatable, Sendable { + public let name: String + public let isRemote: Bool? + public let remoteName: String? + public let current: Bool + public let isDefault: Bool + public let worktreePath: String? +} + +public struct VCSRefsResult: Codable, Equatable, Sendable { + public let refs: [VCSRef] + public let isRepo: Bool + public let hasPrimaryRemote: Bool + public let nextCursor: Int? + public let totalCount: Int +} + +public struct VCSPullResult: Codable, Equatable, Sendable { + public let status: String + public let refName: String + public let upstreamRef: String? +} + +public struct VCSCreateRefResult: Codable, Equatable, Sendable { + public let refName: String +} + +public struct VCSSwitchRefResult: Codable, Equatable, Sendable { + public let refName: String? +} + +public struct VCSWorktree: Codable, Equatable, Sendable { + public let path: String + public let refName: String +} + +public struct VCSCreateWorktreeResult: Codable, Equatable, Sendable { + public let worktree: VCSWorktree +} + +public enum GitStackedAction: String, Codable, CaseIterable, Sendable { + case commit + case push + case createPullRequest = "create_pr" + case commitAndPush = "commit_push" + case commitPushAndPullRequest = "commit_push_pr" +} + +public struct GitActionResult: Codable, Equatable, Sendable { + public struct Branch: Codable, Equatable, Sendable { + public let status: String + public let name: String? + } + + public struct Commit: Codable, Equatable, Sendable { + public let status: String + public let commitSha: String? + public let subject: String? + } + + public struct Push: Codable, Equatable, Sendable { + public let status: String + public let branch: String? + public let upstreamBranch: String? + public let setUpstream: Bool? + } + + public struct PullRequest: Codable, Equatable, Sendable { + public let status: String + public let url: String? + public let number: Int? + public let baseBranch: String? + public let headBranch: String? + public let title: String? + } + + public let action: GitStackedAction + public let branch: Branch + public let commit: Commit + public let push: Push + public let pr: PullRequest + public let toast: JSONValue +} + +public struct GitActionProgressEvent: Codable, Equatable, Sendable { + public let actionId: String + public let cwd: String + public let action: GitStackedAction + public let kind: String + public let phases: [String]? + public let phase: String? + public let label: String? + public let hookName: String? + public let stream: String? + public let text: String? + public let exitCode: Int? + public let durationMs: Int? + public let result: GitActionResult? + public let message: String? +} + +// MARK: - Review + +public struct ReviewDiffSource: Codable, Identifiable, Equatable, Sendable { + public let id: String + public let kind: String + public let title: String + public let baseRef: String? + public let headRef: String? + public let diff: String + public let diffHash: String + public let truncated: Bool +} + +public struct ReviewDiffPreview: Codable, Equatable, Sendable { + public let cwd: String + public let generatedAt: String + public let sources: [ReviewDiffSource] +} + +// MARK: - Terminal + +public enum TerminalSessionStatus: String, Codable, Sendable { + case starting + case running + case exited + case error +} + +public struct TerminalSessionSnapshot: Codable, Equatable, Sendable { + public let threadId: String + public let terminalId: String + public let cwd: String + public let worktreePath: String? + public let status: TerminalSessionStatus + public let pid: Int? + public let history: String + public let exitCode: Int? + public let exitSignal: Int? + public let label: String + public let updatedAt: String + public let sequence: Int? +} + +public struct TerminalSummary: Codable, Equatable, Sendable { + public let threadId: String + public let terminalId: String + public let cwd: String + public let worktreePath: String? + public let status: TerminalSessionStatus + public let pid: Int? + public let exitCode: Int? + public let exitSignal: Int? + public let hasRunningSubprocess: Bool + public let label: String + public let updatedAt: String +} + +public struct TerminalEvent: Codable, Equatable, Sendable { + public let type: String + public let threadId: String? + public let terminalId: String? + public let sequence: Int? + public let snapshot: TerminalSessionSnapshot? + public let data: String? + public let exitCode: Int? + public let exitSignal: Int? + public let message: String? + public let hasRunningSubprocess: Bool? + public let label: String? +} + +public struct TerminalMetadataEvent: Codable, Equatable, Sendable { + public let type: String + public let terminals: [TerminalSummary]? + public let terminal: TerminalSummary? + public let threadId: String? + public let terminalId: String? +} diff --git a/apps/swift-ios/DesignSystem/T3Theme.swift b/apps/swift-ios/DesignSystem/T3Theme.swift new file mode 100644 index 0000000000..a723b7db47 --- /dev/null +++ b/apps/swift-ios/DesignSystem/T3Theme.swift @@ -0,0 +1,34 @@ +import SwiftUI + +enum T3Colors { + static let background = Color.black + static let surface = Color(white: 0.055) + static let surfaceRaised = Color(white: 0.09) + static let input = Color(white: 0.075) + static let border = Color.white.opacity(0.09) + static let separator = Color.white.opacity(0.07) + + static let textPrimary = Color.white + static let textSecondary = Color.white.opacity(0.62) + static let textTertiary = Color.white.opacity(0.4) + + static let accent = Color(red: 0.04, green: 0.52, blue: 1) + static let success = Color(red: 0.19, green: 0.82, blue: 0.35) + static let warning = Color(red: 1, green: 0.62, blue: 0.04) + static let danger = Color(red: 1, green: 0.27, blue: 0.23) +} + +enum T3Metrics { + static let minimumTapTarget: CGFloat = 44 + static let sidebarWidth: CGFloat = 320 + static let minimumSidebarWidth: CGFloat = 280 + static let maximumSidebarWidth: CGFloat = 380 + static let readingWidth: CGFloat = 760 +} + +extension View { + func t3NavigationChrome() -> some View { + toolbarBackground(T3Colors.background.opacity(0.97), for: .navigationBar) + .toolbarBackground(.visible, for: .navigationBar) + } +} diff --git a/apps/swift-ios/Features/Chat/FeatureComposerView.swift b/apps/swift-ios/Features/Chat/FeatureComposerView.swift new file mode 100644 index 0000000000..8c3fc1a20d --- /dev/null +++ b/apps/swift-ios/Features/Chat/FeatureComposerView.swift @@ -0,0 +1,114 @@ +import SwiftUI + +struct FeatureComposerView: View { + @Binding var text: String + @Binding var selection: FeatureSelection? + let providers: [FeatureProvider] + let isSending: Bool + let isWorking: Bool + let focused: FocusState.Binding + let onSend: () -> Void + let onStop: () -> Void + + var body: some View { + VStack(spacing: 8) { + HStack(alignment: .bottom, spacing: 9) { + TextField("Message agent", text: $text, axis: .vertical) + .lineLimit(1...7) + .focused(focused) + .submitLabel(.send) + .onSubmit { + if canSend { onSend() } + } + .padding(.leading, 12) + .padding(.vertical, 10) + + Button(action: isWorking && textIsEmpty ? onStop : onSend) { + Image(systemName: isWorking && textIsEmpty ? "stop.fill" : "arrow.up") + .font(.system(size: 14, weight: .bold)) + .foregroundStyle(.black) + .frame(width: 32, height: 32) + .background(.white, in: Circle()) + } + .disabled((!isWorking && !canSend) || isSending) + .padding(.trailing, 7) + .padding(.bottom, 7) + .accessibilityLabel(isWorking && textIsEmpty ? "Stop agent" : "Send") + } + .background(Color.white.opacity(0.09), in: RoundedRectangle(cornerRadius: 16)) + .overlay { + RoundedRectangle(cornerRadius: 16) + .stroke(Color.white.opacity(0.14), lineWidth: 1) + } + + HStack { + CompactModelMenu(providers: providers, selection: $selection) + Spacer() + Text("Return to send") + .font(.caption2) + .foregroundStyle(.tertiary) + } + .padding(.horizontal, 3) + } + .padding(.horizontal, 12) + .padding(.top, 9) + .padding(.bottom, 7) + .background(.black.opacity(0.97)) + .overlay(alignment: .top) { + Divider().opacity(0.4) + } + } + + private var textIsEmpty: Bool { + text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + private var canSend: Bool { + !textIsEmpty && !isSending + } +} + +private struct CompactModelMenu: View { + let providers: [FeatureProvider] + @Binding var selection: FeatureSelection? + + var body: some View { + Menu { + ForEach(providers.filter(\.isAvailable)) { provider in + Section(provider.name) { + ForEach(provider.models) { model in + Button { + selection = .init(providerID: provider.id, modelID: model.id) + } label: { + if selection?.providerID == provider.id, selection?.modelID == model.id { + Label(model.name, systemImage: "checkmark") + } else { + Text(model.name) + } + } + } + } + } + } label: { + HStack(spacing: 5) { + Image(systemName: "cpu") + Text(label) + Image(systemName: "chevron.down") + .font(.system(size: 8, weight: .bold)) + } + .font(.caption.weight(.medium)) + .foregroundStyle(.secondary) + .contentShape(Rectangle()) + } + .accessibilityLabel("Choose model") + } + + private var label: String { + guard let selection, + let provider = providers.first(where: { $0.id == selection.providerID }), + let model = provider.models.first(where: { $0.id == selection.modelID }) else { + return "Automatic" + } + return model.name + } +} diff --git a/apps/swift-ios/Features/Chat/ThreadDetailView.swift b/apps/swift-ios/Features/Chat/ThreadDetailView.swift new file mode 100644 index 0000000000..58c66a62d6 --- /dev/null +++ b/apps/swift-ios/Features/Chat/ThreadDetailView.swift @@ -0,0 +1,484 @@ +import SwiftUI + +public struct ThreadDetailView: View { + @Bindable var model: FeatureRootModel + let thread: FeatureThread + + @State private var draft = "" + @State private var selection: FeatureSelection? + @State private var isSending = false + @State private var isLoading = true + @State private var toolSurface: FeatureThreadToolSurface? + @FocusState private var composerFocused: Bool + + public init(model: FeatureRootModel, thread: FeatureThread) { + self.model = model + self.thread = thread + } + + public var body: some View { + Group { + if isLoading, detail == nil { + ProgressView("Loading thread…") + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if let detail { + timeline(detail) + } else { + ContentUnavailableView( + "Thread unavailable", + systemImage: "exclamationmark.bubble", + description: Text("The thread could not be loaded.") + ) + } + } + .background(Color.black) + .navigationTitle(detail?.thread.title ?? thread.title) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Menu { + Section("Workspace") { + Button { + toolSurface = .files + } label: { + Label("Files", systemImage: "folder") + } + Button { + toolSurface = .review + } label: { + Label("Review changes", systemImage: "doc.text.magnifyingglass") + } + Button { + toolSurface = .sourceControl + } label: { + Label("Source Control", systemImage: "arrow.triangle.branch") + } + Button { + toolSurface = .terminal + } label: { + Label("Terminal", systemImage: "terminal") + } + } + Section("Interaction") { + Button { + Task { + await model.setInteractionMode( + thread.id, + mode: currentThread.interactionMode == .plan ? .standard : .plan + ) + } + } label: { + Label( + currentThread.interactionMode == .plan + ? "Use standard mode" + : "Use plan mode", + systemImage: "list.bullet.clipboard" + ) + } + } + Section("Access") { + ForEach(FeatureRuntimeMode.allCases, id: \.self) { mode in + Button { + Task { await model.setRuntimeMode(thread.id, mode: mode) } + } label: { + if currentThread.runtimeMode == mode { + Label(runtimeModeLabel(mode), systemImage: "checkmark") + } else { + Text(runtimeModeLabel(mode)) + } + } + } + } + Section { + Button { + Task { _ = await model.detail(for: thread.id, force: true) } + } label: { + Label("Reload", systemImage: "arrow.clockwise") + } + Button { + Task { + await model.setArchived(thread.id, archived: !thread.isArchived) + } + } label: { + Label( + thread.isArchived ? "Restore" : "Archive", + systemImage: thread.isArchived + ? "arrow.uturn.backward" + : "archivebox" + ) + } + } + } label: { + Image(systemName: "ellipsis") + } + .accessibilityLabel("Thread actions") + } + } + .task(id: thread.id) { + isLoading = true + _ = await model.detail(for: thread.id) + selection = currentSelection + isLoading = false + } + .sheet(item: $toolSurface) { surface in + NavigationStack { + switch surface { + case .files: + FeatureFilesView(client: model.client, threadID: thread.id) + case .review: + FeatureReviewView(client: model.client, threadID: thread.id) + case .sourceControl: + FeatureSourceControlView(client: model.client, threadID: thread.id) + case .terminal: + FeatureTerminalView(client: model.client, threadID: thread.id) + } + } + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Done") { + toolSurface = nil + } + } + } + .presentationDetents([.large]) + .presentationDragIndicator(.visible) + } + } + + private var detail: FeatureThreadDetail? { + model.details[thread.id] + } + + private var currentThread: FeatureThread { + detail?.thread ?? thread + } + + private var currentSelection: FeatureSelection? { + guard let providerID = detail?.thread.providerID ?? thread.providerID, + let modelID = detail?.thread.modelID ?? thread.modelID else { + return model.snapshot.settings.defaultSelection + } + return FeatureSelection(providerID: providerID, modelID: modelID) + } + + private func timeline(_ detail: FeatureThreadDetail) -> some View { + ScrollViewReader { proxy in + ScrollView { + LazyVStack(alignment: .leading, spacing: 18) { + if detail.messages.isEmpty { + ContentUnavailableView( + "Ready for a task", + systemImage: "sparkles", + description: Text("Tell the agent what you want to build.") + ) + .frame(maxWidth: .infinity) + .padding(.top, 80) + } + + ForEach(detail.messages) { message in + FeatureMessageView(message: message) + .id(message.id) + } + + ForEach(detail.approvals) { approval in + ApprovalRequestView(model: model, approval: approval) + .id("approval-\(approval.id)") + } + + ForEach(detail.userInputs) { input in + UserInputRequestView(model: model, input: input) + .id("user-input-\(input.id)") + } + + if detail.thread.state == .working || detail.thread.state == .queued { + StreamingStatusView( + state: detail.thread.state, + onStop: { + Task { await model.cancelTurn(threadID: thread.id) } + } + ) + .id("streaming-status") + } + + Color.clear.frame(height: 1).id("timeline-bottom") + } + .padding(.horizontal, 16) + .padding(.top, 14) + .padding(.bottom, 10) + } + .defaultScrollAnchor(.bottom) + .scrollDismissesKeyboard(.interactively) + .onChange(of: detail.messages.count) { + withAnimation(.easeOut(duration: 0.18)) { + proxy.scrollTo("timeline-bottom", anchor: .bottom) + } + } + .safeAreaInset(edge: .bottom, spacing: 0) { + FeatureComposerView( + text: $draft, + selection: $selection, + providers: model.snapshot.providers, + isSending: isSending, + isWorking: detail.thread.state == .working || detail.thread.state == .queued, + focused: $composerFocused, + onSend: send, + onStop: { + Task { await model.cancelTurn(threadID: thread.id) } + } + ) + } + } + } + + private func send() { + let message = draft + guard !message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } + draft = "" + isSending = true + Task { + let sent = await model.sendMessage( + threadID: thread.id, + text: message, + selection: selection + ) + if !sent { + draft = message + } + isSending = false + composerFocused = true + } + } + + private func runtimeModeLabel(_ mode: FeatureRuntimeMode) -> String { + switch mode { + case .approvalRequired: "Ask before changes" + case .autoAcceptEdits: "Auto-accept edits" + case .automatic: "Automatic" + case .fullAccess: "Full access" + } + } +} + +private enum FeatureThreadToolSurface: String, Identifiable { + case files + case review + case sourceControl + case terminal + + var id: String { rawValue } +} + +private struct UserInputRequestView: View { + @Bindable var model: FeatureRootModel + let input: FeatureUserInput + @State private var answers: [String: String] = [:] + @State private var isSubmitting = false + + var body: some View { + VStack(alignment: .leading, spacing: 14) { + Label("Input requested", systemImage: "questionmark.bubble") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.indigo) + + ForEach(input.questions) { question in + VStack(alignment: .leading, spacing: 8) { + Text(question.header) + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + Text(question.question) + .font(.callout) + + if !question.options.isEmpty { + ForEach(question.options, id: \.label) { option in + Button { + answers[question.id] = option.label + } label: { + HStack(alignment: .top, spacing: 9) { + Image( + systemName: answers[question.id] == option.label + ? "checkmark.circle.fill" + : "circle" + ) + VStack(alignment: .leading, spacing: 2) { + Text(option.label) + if !option.detail.isEmpty { + Text(option.detail) + .font(.caption) + .foregroundStyle(.secondary) + } + } + Spacer() + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + } + + TextField( + question.options.isEmpty ? "Your answer" : "Or type another answer", + text: Binding( + get: { answers[question.id] ?? "" }, + set: { answers[question.id] = $0 } + ), + axis: .vertical + ) + .lineLimit(1...4) + .textFieldStyle(.roundedBorder) + } + } + + Button(isSubmitting ? "Submitting…" : "Submit") { + isSubmitting = true + Task { + await model.resolveUserInput(input.id, answers: answers) + isSubmitting = false + } + } + .buttonStyle(.borderedProminent) + .tint(.white) + .foregroundStyle(.black) + .disabled( + isSubmitting + || input.questions.contains { + answers[$0.id]?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + != false + } + ) + } + .padding(13) + .background(Color.indigo.opacity(0.1), in: RoundedRectangle(cornerRadius: 12)) + .overlay { + RoundedRectangle(cornerRadius: 12) + .stroke(Color.indigo.opacity(0.35), lineWidth: 1) + } + } +} + +struct FeatureMessageView: View { + let message: FeatureMessage + + var body: some View { + switch message.role { + case .user: + HStack { + Spacer(minLength: 34) + Text(.init(message.text)) + .textSelection(.enabled) + .padding(.horizontal, 13) + .padding(.vertical, 10) + .background(Color.white.opacity(0.11), in: RoundedRectangle(cornerRadius: 15)) + } + .accessibilityLabel("You") + .accessibilityValue(message.text) + case .assistant: + VStack(alignment: .leading, spacing: 7) { + HStack(spacing: 6) { + Image(systemName: "sparkles") + Text(message.state == .streaming ? "Agent · Working" : "Agent") + } + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + Text(.init(message.text)) + .textSelection(.enabled) + .lineSpacing(3) + } + .frame(maxWidth: .infinity, alignment: .leading) + case .tool: + DisclosureGroup { + Text(message.text) + .font(.caption.monospaced()) + .foregroundStyle(.secondary) + .textSelection(.enabled) + .padding(.top, 6) + } label: { + Label(message.toolName ?? "Tool output", systemImage: "terminal") + .font(.subheadline.weight(.medium)) + } + .padding(11) + .background(Color.white.opacity(0.055), in: RoundedRectangle(cornerRadius: 10)) + case .system: + Text(message.text) + .font(.footnote) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .center) + } + } +} + +struct StreamingStatusView: View { + let state: FeatureThreadState + let onStop: () -> Void + + var body: some View { + HStack(spacing: 9) { + ProgressView() + .controlSize(.small) + Text(state == .queued ? "Queued" : "Agent is working") + .font(.footnote) + .foregroundStyle(.secondary) + Spacer() + Button("Stop", role: .destructive, action: onStop) + .font(.footnote.weight(.semibold)) + } + .padding(.vertical, 6) + .accessibilityElement(children: .combine) + } +} + +struct ApprovalRequestView: View { + @Bindable var model: FeatureRootModel + let approval: FeatureApproval + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Label(approval.title, systemImage: icon) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.orange) + + Text(approval.detail) + .font(approval.kind == .command ? .caption.monospaced() : .callout) + .foregroundStyle(.secondary) + .textSelection(.enabled) + + HStack(spacing: 8) { + Button("Deny", role: .destructive) { + decide(.deny) + } + .buttonStyle(.bordered) + Spacer() + Button("Always Allow") { + decide(.allowForSession) + } + .buttonStyle(.bordered) + Button("Allow") { + decide(.allowOnce) + } + .buttonStyle(.borderedProminent) + .tint(.white) + .foregroundStyle(.black) + } + .font(.footnote.weight(.semibold)) + } + .padding(13) + .background(Color.orange.opacity(0.09), in: RoundedRectangle(cornerRadius: 12)) + .overlay { + RoundedRectangle(cornerRadius: 12) + .stroke(Color.orange.opacity(0.3), lineWidth: 1) + } + .accessibilityElement(children: .contain) + } + + private var icon: String { + switch approval.kind { + case .command: "terminal" + case .fileRead: "doc.text.magnifyingglass" + case .fileChange, .patch: "doc.badge.ellipsis" + case .other: "exclamationmark.shield" + } + } + + private func decide(_ decision: FeatureApprovalDecision) { + Task { await model.resolveApproval(approval.id, decision: decision) } + } +} diff --git a/apps/swift-ios/Features/Connection/ConnectionOnboardingView.swift b/apps/swift-ios/Features/Connection/ConnectionOnboardingView.swift new file mode 100644 index 0000000000..025512e413 --- /dev/null +++ b/apps/swift-ios/Features/Connection/ConnectionOnboardingView.swift @@ -0,0 +1,160 @@ +import SwiftUI + +public struct ConnectionOnboardingView: View { + @Bindable var model: FeatureRootModel + @State private var endpoint = "" + @State private var pairingToken = "" + @State private var isPairing = false + + public init(model: FeatureRootModel) { + self.model = model + } + + public var body: some View { + NavigationStack { + ScrollView { + VStack(alignment: .leading, spacing: 28) { + VStack(alignment: .leading, spacing: 8) { + Image(systemName: "chevron.left.forwardslash.chevron.right") + .font(.system(size: 34, weight: .bold)) + Text("T3 Code") + .font(.largeTitle.bold()) + Text("Connect this iPhone to a T3 environment.") + .font(.body) + .foregroundStyle(.secondary) + } + + VStack(alignment: .leading, spacing: 12) { + Text("SERVER") + .font(.caption2.weight(.semibold)) + .foregroundStyle(.secondary) + + TextField("https://your-server.example", text: $endpoint) + .textInputAutocapitalization(.never) + .keyboardType(.URL) + .autocorrectionDisabled() + .featureInput() + .accessibilityLabel("Server address") + + SecureField("Pairing token (optional)", text: $pairingToken) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .featureInput() + + Button { + pair() + } label: { + HStack { + if isPairing { + ProgressView().controlSize(.small) + } + Text(isPairing ? "Connecting…" : "Connect") + } + .frame(maxWidth: .infinity) + } + .buttonStyle(FeaturePrimaryButtonStyle()) + .disabled(normalizedEndpoint == nil || isPairing) + } + + if !model.snapshot.environments.isEmpty { + VStack(alignment: .leading, spacing: 8) { + Text("KNOWN ENVIRONMENTS") + .font(.caption2.weight(.semibold)) + .foregroundStyle(.secondary) + + ForEach(model.snapshot.environments) { environment in + Button { + endpoint = environment.endpoint + } label: { + HStack(spacing: 12) { + Image(systemName: "server.rack") + .foregroundStyle(.secondary) + VStack(alignment: .leading, spacing: 2) { + Text(environment.name) + .foregroundStyle(.primary) + Text(environment.endpoint) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Spacer() + Image(systemName: "chevron.right") + .font(.caption) + .foregroundStyle(.tertiary) + } + .contentShape(Rectangle()) + .padding(.vertical, 8) + } + .buttonStyle(.plain) + } + } + } + + VStack(alignment: .leading, spacing: 6) { + Label("How to pair", systemImage: "info.circle") + .font(.subheadline.weight(.semibold)) + Text("Open T3 Code on the host, copy its mobile pairing link, then paste the server and one-time token above.") + .font(.footnote) + .foregroundStyle(.secondary) + } + } + .padding(24) + .frame(maxWidth: 560) + .frame(maxWidth: .infinity) + } + .scrollDismissesKeyboard(.interactively) + .background(Color.black) + .navigationTitle("Connect") + .navigationBarTitleDisplayMode(.inline) + } + } + + private var normalizedEndpoint: String? { + let value = endpoint.trimmingCharacters(in: .whitespacesAndNewlines) + guard let components = URLComponents(string: value), + let scheme = components.scheme?.lowercased(), + ["http", "https"].contains(scheme), + components.host != nil else { + return nil + } + return value + } + + private func pair() { + guard let endpoint = normalizedEndpoint else { return } + let trimmedToken = pairingToken.trimmingCharacters(in: .whitespacesAndNewlines) + isPairing = true + Task { + _ = await model.pair( + endpoint: endpoint, + token: trimmedToken.isEmpty ? nil : trimmedToken + ) + isPairing = false + } + } +} + +private extension View { + func featureInput() -> some View { + self + .padding(.horizontal, 12) + .frame(minHeight: 46) + .background(Color.white.opacity(0.08), in: RoundedRectangle(cornerRadius: 10)) + .overlay { + RoundedRectangle(cornerRadius: 10) + .stroke(Color.white.opacity(0.12), lineWidth: 1) + } + } +} + +struct FeaturePrimaryButtonStyle: ButtonStyle { + func makeBody(configuration: Configuration) -> some View { + configuration.label + .font(.body.weight(.semibold)) + .foregroundStyle(.black) + .padding(.horizontal, 16) + .frame(minHeight: 46) + .background(configuration.isPressed ? Color.white.opacity(0.75) : .white) + .clipShape(RoundedRectangle(cornerRadius: 10)) + } +} diff --git a/apps/swift-ios/Features/Files/FeatureFilesView.swift b/apps/swift-ios/Features/Files/FeatureFilesView.swift new file mode 100644 index 0000000000..f4d600f627 --- /dev/null +++ b/apps/swift-ios/Features/Files/FeatureFilesView.swift @@ -0,0 +1,238 @@ +import SwiftUI + +public struct FeatureFilesView: View { + let client: any FeatureClient + let threadID: String + + public init(client: any FeatureClient, threadID: String) { + self.client = client + self.threadID = threadID + } + + public var body: some View { + FeatureFileDirectoryView(client: client, threadID: threadID, path: nil, title: "Files") + .background(Color.black) + } +} + +private struct FeatureFileDirectoryView: View { + let client: any FeatureClient + let threadID: String + let path: String? + let title: String + + @State private var entries: [FeatureFileEntry] = [] + @State private var searchText = "" + @State private var includesHidden = false + @State private var isLoading = true + @State private var errorMessage: String? + + var body: some View { + Group { + if isLoading, entries.isEmpty { + ProgressView("Loading files…") + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if let errorMessage, entries.isEmpty { + ContentUnavailableView( + "Files unavailable", + systemImage: "folder.badge.questionmark", + description: Text(errorMessage) + ) + } else if filteredEntries.isEmpty { + ContentUnavailableView( + searchText.isEmpty ? "Empty folder" : "No matches", + systemImage: "folder", + description: Text(searchText.isEmpty ? "This folder has no visible files." : "Try another search.") + ) + } else { + List(filteredEntries) { entry in + NavigationLink { + destination(for: entry) + } label: { + FeatureFileRow(entry: entry) + } + } + .listStyle(.plain) + .scrollContentBackground(.hidden) + .refreshable { await load() } + } + } + .background(Color.black) + .navigationTitle(title) + .navigationBarTitleDisplayMode(.inline) + .searchable(text: $searchText, prompt: "Filter files") + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Menu { + Toggle("Show hidden files", isOn: $includesHidden) + Button { + Task { await load() } + } label: { + Label("Reload", systemImage: "arrow.clockwise") + } + } label: { + Image(systemName: "ellipsis") + } + .accessibilityLabel("File browser options") + } + } + .task(id: path) { await load() } + } + + @ViewBuilder + private func destination(for entry: FeatureFileEntry) -> some View { + if entry.kind == .directory { + FeatureFileDirectoryView( + client: client, + threadID: threadID, + path: entry.path, + title: entry.name + ) + } else { + FeatureFilePreviewView(client: client, threadID: threadID, entry: entry) + } + } + + private var filteredEntries: [FeatureFileEntry] { + entries.featureFiltered(by: searchText, includesHidden: includesHidden) + } + + private func load() async { + isLoading = true + defer { isLoading = false } + do { + entries = try await client.listFiles(threadID: threadID, path: path) + errorMessage = nil + } catch { + errorMessage = error.localizedDescription + } + } +} + +private struct FeatureFileRow: View { + let entry: FeatureFileEntry + + var body: some View { + HStack(spacing: 11) { + Image(systemName: icon) + .font(.system(size: 15)) + .foregroundStyle(entry.kind == .directory ? .blue : .secondary) + .frame(width: 20) + Text(entry.name) + .font(.subheadline) + .lineLimit(1) + Spacer() + if let size = entry.sizeBytes, entry.kind != .directory { + Text(ByteCountFormatter.string(fromByteCount: Int64(size), countStyle: .file)) + .font(.caption2.monospacedDigit()) + .foregroundStyle(.tertiary) + } + } + .padding(.vertical, 3) + .accessibilityElement(children: .combine) + } + + private var icon: String { + switch entry.kind { + case .directory: "folder.fill" + case .symbolicLink: "link" + case .file: + entry.name.hasSuffix(".swift") ? "swift" : "doc.text" + } + } +} + +private struct FeatureFilePreviewView: View { + let client: any FeatureClient + let threadID: String + let entry: FeatureFileEntry + + @State private var content: FeatureFileContent? + @State private var errorMessage: String? + @State private var isLoading = true + + var body: some View { + Group { + if isLoading, content == nil { + ProgressView("Loading file…") + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if let content { + VStack(spacing: 0) { + if content.isTruncated { + Label("Partial preview", systemImage: "exclamationmark.triangle") + .font(.caption.weight(.semibold)) + .foregroundStyle(.orange) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 12) + .padding(.vertical, 8) + .background(Color.orange.opacity(0.09)) + } + FeatureSourceTextView(text: content.text) + } + } else { + ContentUnavailableView( + "File unavailable", + systemImage: "doc.badge.ellipsis", + description: Text(errorMessage ?? "The file could not be read.") + ) + } + } + .background(Color.black) + .navigationTitle(entry.name) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + if let content { + ToolbarItem(placement: .topBarTrailing) { + ShareLink(item: content.text) { + Image(systemName: "square.and.arrow.up") + } + .accessibilityLabel("Share file contents") + } + } + } + .task { await load() } + } + + private func load() async { + isLoading = true + defer { isLoading = false } + do { + content = try await client.readFile(threadID: threadID, path: entry.path) + errorMessage = nil + } catch { + errorMessage = error.localizedDescription + } + } +} + +private struct FeatureSourceTextView: View { + let text: String + + private var lines: [Substring] { + text.split(separator: "\n", omittingEmptySubsequences: false) + } + + var body: some View { + ScrollView([.horizontal, .vertical]) { + LazyVStack(alignment: .leading, spacing: 0) { + ForEach(Array(lines.enumerated()), id: \.offset) { index, line in + HStack(alignment: .top, spacing: 10) { + Text("\(index + 1)") + .foregroundStyle(.tertiary) + .frame(width: 38, alignment: .trailing) + .accessibilityHidden(true) + Text(String(line).isEmpty ? " " : String(line)) + .foregroundStyle(.primary) + .textSelection(.enabled) + } + .font(.system(size: 12, design: .monospaced)) + .frame(minHeight: 19) + } + } + .padding(.vertical, 10) + .padding(.trailing, 14) + } + .background(Color.black) + .accessibilityLabel("Source file") + } +} diff --git a/apps/swift-ios/Features/Review/FeatureReviewView.swift b/apps/swift-ios/Features/Review/FeatureReviewView.swift new file mode 100644 index 0000000000..6330f1e86e --- /dev/null +++ b/apps/swift-ios/Features/Review/FeatureReviewView.swift @@ -0,0 +1,269 @@ +import SwiftUI + +public struct FeatureReviewView: View { + let client: any FeatureClient + let threadID: String + + @State private var review: FeatureReview? + @State private var isLoading = true + @State private var errorMessage: String? + + public init(client: any FeatureClient, threadID: String) { + self.client = client + self.threadID = threadID + } + + public var body: some View { + Group { + if isLoading, review == nil { + ProgressView("Loading changes…") + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if let review { + reviewList(review) + } else { + ContentUnavailableView( + "Review unavailable", + systemImage: "doc.text.magnifyingglass", + description: Text(errorMessage ?? "Changes could not be loaded.") + ) + } + } + .background(Color.black) + .navigationTitle("Review") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Button { + Task { await load() } + } label: { + Image(systemName: "arrow.clockwise") + } + .accessibilityLabel("Reload changes") + } + } + .task { await load() } + } + + private func reviewList(_ review: FeatureReview) -> some View { + List { + Section { + HStack { + VStack(alignment: .leading, spacing: 3) { + Text(review.title) + .font(.headline) + if let base = review.baseReference { + Text(base) + .font(.caption.monospaced()) + .foregroundStyle(.secondary) + } + } + Spacer() + FeatureDiffStatsLabel(additions: review.additions, deletions: review.deletions) + } + .padding(.vertical, 3) + + if review.isTruncated { + Label("Large diff, showing a partial result", systemImage: "exclamationmark.triangle") + .font(.footnote) + .foregroundStyle(.orange) + } + } + + Section("\(review.files.count) changed \(review.files.count == 1 ? "file" : "files")") { + if review.files.isEmpty { + ContentUnavailableView( + "No changes", + systemImage: "checkmark.circle", + description: Text("The working tree is clean.") + ) + .listRowBackground(Color.clear) + } + ForEach(review.files) { file in + NavigationLink { + FeatureDiffView(file: file) + } label: { + FeatureReviewFileRow(file: file) + } + } + } + } + .listStyle(.insetGrouped) + .scrollContentBackground(.hidden) + .refreshable { await load() } + } + + private func load() async { + isLoading = true + defer { isLoading = false } + do { + review = try await client.loadReview(threadID: threadID) + errorMessage = nil + } catch { + errorMessage = error.localizedDescription + } + } +} + +private struct FeatureReviewFileRow: View { + let file: FeatureReviewFile + + var body: some View { + HStack(spacing: 10) { + Text(changeLabel) + .font(.caption2.monospaced().weight(.bold)) + .foregroundStyle(changeColor) + .frame(width: 18) + VStack(alignment: .leading, spacing: 2) { + Text(fileName) + .font(.subheadline.weight(.medium)) + .lineLimit(1) + if !directory.isEmpty { + Text(directory) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + Spacer() + FeatureDiffStatsLabel(additions: file.additions, deletions: file.deletions) + } + .padding(.vertical, 3) + .accessibilityElement(children: .combine) + } + + private var fileName: String { + file.path.split(separator: "/").last.map(String.init) ?? file.path + } + + private var directory: String { + let components = file.path.split(separator: "/") + return components.dropLast().joined(separator: "/") + } + + private var changeLabel: String { + switch file.change { + case .added: "A" + case .modified: "M" + case .deleted: "D" + case .renamed: "R" + case .binary: "B" + } + } + + private var changeColor: Color { + switch file.change { + case .added: .green + case .deleted: .red + case .renamed: .blue + case .modified, .binary: .orange + } + } +} + +struct FeatureDiffStatsLabel: View { + let additions: Int + let deletions: Int + + var body: some View { + HStack(spacing: 5) { + if additions > 0 { + Text("+\(additions)").foregroundStyle(.green) + } + if deletions > 0 { + Text("−\(deletions)").foregroundStyle(.red) + } + } + .font(.caption2.monospacedDigit().weight(.medium)) + .accessibilityElement(children: .combine) + .accessibilityLabel("\(additions) additions, \(deletions) deletions") + } +} + +private struct FeatureDiffView: View { + let file: FeatureReviewFile + + var body: some View { + Group { + if file.lines.isEmpty { + ContentUnavailableView( + file.change == .binary ? "Binary file" : "Diff unavailable", + systemImage: file.change == .binary ? "doc.richtext" : "doc.text.magnifyingglass", + description: Text("No line-level preview is available.") + ) + } else { + ScrollView([.horizontal, .vertical]) { + LazyVStack(alignment: .leading, spacing: 0) { + ForEach(file.lines) { line in + FeatureDiffLineRow(line: line) + } + } + .padding(.vertical, 8) + } + } + } + .background(Color.black) + .navigationTitle(file.path.split(separator: "/").last.map(String.init) ?? file.path) + .navigationBarTitleDisplayMode(.inline) + } +} + +private struct FeatureDiffLineRow: View { + let line: FeatureDiffLine + + var body: some View { + HStack(alignment: .top, spacing: 0) { + if line.kind == .hunk { + Text(line.text) + .foregroundStyle(.blue) + .padding(.horizontal, 10) + } else { + lineNumber(line.oldLine) + lineNumber(line.newLine) + Text(prefix) + .foregroundStyle(prefixColor) + .frame(width: 18) + Text(line.text.isEmpty ? " " : line.text) + .foregroundStyle(.primary) + .textSelection(.enabled) + .padding(.trailing, 12) + } + } + .font(.system(size: 12, design: .monospaced)) + .frame(minHeight: line.kind == .hunk ? 28 : 19, alignment: .leading) + .frame(maxWidth: .infinity, alignment: .leading) + .background(background) + } + + private func lineNumber(_ value: Int?) -> some View { + Text(value.map(String.init) ?? "") + .foregroundStyle(.tertiary) + .frame(width: 42, alignment: .trailing) + .padding(.trailing, 7) + .accessibilityHidden(true) + } + + private var prefix: String { + switch line.kind { + case .addition: "+" + case .deletion: "−" + case .context, .hunk: " " + } + } + + private var prefixColor: Color { + switch line.kind { + case .addition: .green + case .deletion: .red + case .context, .hunk: .secondary + } + } + + private var background: Color { + switch line.kind { + case .addition: Color.green.opacity(0.11) + case .deletion: Color.red.opacity(0.11) + case .hunk: Color.blue.opacity(0.08) + case .context: Color.clear + } + } +} diff --git a/apps/swift-ios/Features/Root/FeatureRootModel.swift b/apps/swift-ios/Features/Root/FeatureRootModel.swift new file mode 100644 index 0000000000..c85c4dce40 --- /dev/null +++ b/apps/swift-ios/Features/Root/FeatureRootModel.swift @@ -0,0 +1,260 @@ +import Foundation +import Observation + +@MainActor +@Observable +public final class FeatureRootModel { + public private(set) var snapshot = FeatureSnapshot() + public private(set) var details: [String: FeatureThreadDetail] = [:] + public private(set) var isLoading = true + public private(set) var isPerformingAction = false + public var errorMessage: String? + + let client: any FeatureClient + + public init(client: any FeatureClient) { + self.client = client + } + + public func start() async { + do { + snapshot = try await client.initialSnapshot() + } catch { + errorMessage = error.localizedDescription + } + isLoading = false + + for await event in client.events() { + apply(event) + } + } + + public func reload() async { + do { + snapshot = try await client.initialSnapshot() + } catch { + errorMessage = error.localizedDescription + } + } + + public func pair(endpoint: String, token: String?) async -> Bool { + await perform { + try await client.pair(endpoint: endpoint, token: token) + snapshot = try await client.initialSnapshot() + } + } + + public func activateEnvironment(_ id: String) async { + await perform { + try await client.activateEnvironment(id: id) + snapshot = try await client.initialSnapshot() + details.removeAll() + } + } + + public func removeEnvironment(_ id: String) async { + await perform { + try await client.removeEnvironment(id: id) + snapshot = try await client.initialSnapshot() + details.removeAll() + } + } + + public func disconnect() async { + await client.disconnect() + snapshot.connection = .init() + details.removeAll() + } + + public func addProject(path: String) async -> Bool { + await perform { + try await client.addProject(path: path) + snapshot = try await client.initialSnapshot() + } + } + + public func createThread( + projectID: String, + title: String?, + selection: FeatureSelection? + ) async -> FeatureThread? { + var created: FeatureThread? + let succeeded = await perform { + let thread = try await client.createThread( + projectID: projectID, + title: title, + selection: selection + ) + upsert(thread) + created = thread + } + return succeeded ? created : nil + } + + public func renameThread(_ id: String, title: String) async { + await perform { + try await client.renameThread(id: id, title: title) + guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return } + snapshot.threads[index].title = title + details[id]?.thread.title = title + } + } + + public func setArchived(_ id: String, archived: Bool) async { + await perform { + try await client.setThreadArchived(id: id, archived: archived) + guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return } + snapshot.threads[index].isArchived = archived + details[id]?.thread.isArchived = archived + } + } + + public func setSettled(_ id: String, settled: Bool) async { + await perform { + try await client.setThreadSettled(id: id, settled: settled) + guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return } + snapshot.threads[index].isSettled = settled + details[id]?.thread.isSettled = settled + } + } + + public func setSnoozed(_ id: String, until: Date?) async { + await perform { + try await client.setThreadSnoozed(id: id, until: until) + guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return } + snapshot.threads[index].snoozedUntil = until + details[id]?.thread.snoozedUntil = until + } + } + + public func setRuntimeMode(_ id: String, mode: FeatureRuntimeMode) async { + await perform { + try await client.setRuntimeMode(id: id, mode: mode) + guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return } + snapshot.threads[index].runtimeMode = mode + details[id]?.thread.runtimeMode = mode + } + } + + public func setInteractionMode(_ id: String, mode: FeatureInteractionMode) async { + await perform { + try await client.setInteractionMode(id: id, mode: mode) + guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return } + snapshot.threads[index].interactionMode = mode + details[id]?.thread.interactionMode = mode + } + } + + public func deleteThread(_ id: String) async { + await perform { + try await client.deleteThread(id: id) + snapshot.threads.removeAll { $0.id == id } + details[id] = nil + } + } + + public func detail(for id: String, force: Bool = false) async -> FeatureThreadDetail? { + if !force, let cached = details[id] { + return cached + } + do { + let detail = try await client.loadThread(id: id) + details[id] = detail + upsert(detail.thread) + return detail + } catch { + errorMessage = error.localizedDescription + return nil + } + } + + public func sendMessage(threadID: String, text: String, selection: FeatureSelection?) async -> Bool { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return false } + + return await perform { + let optimistic = FeatureMessage( + id: "local-\(UUID().uuidString)", + role: .user, + text: trimmed, + state: .queued + ) + details[threadID]?.messages.append(optimistic) + try await client.sendMessage(threadID: threadID, text: trimmed, selection: selection) + } + } + + public func cancelTurn(threadID: String) async { + await perform { + try await client.cancelTurn(threadID: threadID) + } + } + + public func resolveApproval(_ id: String, decision: FeatureApprovalDecision) async { + await perform { + try await client.resolveApproval(id: id, decision: decision) + for key in details.keys { + details[key]?.approvals.removeAll { $0.id == id } + } + } + } + + public func resolveUserInput(_ id: String, answers: [String: String]) async { + await perform { + try await client.resolveUserInput(id: id, answers: answers) + for key in details.keys { + details[key]?.userInputs.removeAll { $0.id == id } + } + } + } + + public func saveSettings(_ settings: FeatureSettings) async { + await perform { + try await client.saveSettings(settings) + snapshot.settings = settings + } + } + + @discardableResult + private func perform(_ operation: () async throws -> Void) async -> Bool { + isPerformingAction = true + defer { isPerformingAction = false } + do { + try await operation() + return true + } catch { + errorMessage = error.localizedDescription + return false + } + } + + private func apply(_ event: FeatureEvent) { + switch event { + case let .snapshot(value): + snapshot = value + case let .connection(value): + snapshot.connection = value + case let .thread(value): + upsert(value) + if details[value.id] != nil { + details[value.id]?.thread = value + } + case let .threadRemoved(id): + snapshot.threads.removeAll { $0.id == id } + details[id] = nil + case let .detail(value): + details[value.thread.id] = value + upsert(value.thread) + case let .failure(message): + errorMessage = message + } + } + + private func upsert(_ thread: FeatureThread) { + if let index = snapshot.threads.firstIndex(where: { $0.id == thread.id }) { + snapshot.threads[index] = thread + } else { + snapshot.threads.append(thread) + } + } +} diff --git a/apps/swift-ios/Features/Root/FeatureRootView.swift b/apps/swift-ios/Features/Root/FeatureRootView.swift new file mode 100644 index 0000000000..ff2e51059e --- /dev/null +++ b/apps/swift-ios/Features/Root/FeatureRootView.swift @@ -0,0 +1,55 @@ +import SwiftUI + +public struct FeatureRootView: View { + @State private var model: FeatureRootModel + + public init(client: any FeatureClient) { + _model = State(initialValue: FeatureRootModel(client: client)) + } + + public var body: some View { + Group { + if model.isLoading { + FeatureLoadingView() + } else if model.snapshot.connection.state == .connected { + WorkspaceView(model: model) + } else { + ConnectionOnboardingView(model: model) + } + } + .preferredColorScheme(model.snapshot.settings.appearance == .dark ? .dark : nil) + .tint(.white) + .background(Color.black.ignoresSafeArea()) + .task { await model.start() } + .alert( + "Something went wrong", + isPresented: Binding( + get: { model.errorMessage != nil }, + set: { if !$0 { model.errorMessage = nil } } + ), + actions: { + Button("OK") { model.errorMessage = nil } + }, + message: { + Text(model.errorMessage ?? "Unknown error") + } + ) + } +} + +private struct FeatureLoadingView: View { + var body: some View { + VStack(spacing: 14) { + Image(systemName: "chevron.left.forwardslash.chevron.right") + .font(.system(size: 30, weight: .semibold)) + ProgressView() + .controlSize(.small) + Text("Connecting to T3 Code") + .font(.footnote) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(Color.black) + .accessibilityElement(children: .combine) + } +} diff --git a/apps/swift-ios/Features/Settings/SettingsView.swift b/apps/swift-ios/Features/Settings/SettingsView.swift new file mode 100644 index 0000000000..370f49b098 --- /dev/null +++ b/apps/swift-ios/Features/Settings/SettingsView.swift @@ -0,0 +1,150 @@ +import SwiftUI + +public struct SettingsView: View { + @SwiftUI.Environment(\.dismiss) private var dismiss + @Bindable var model: FeatureRootModel + @State private var settings: FeatureSettings + @State private var isSaving = false + @State private var showingDisconnect = false + + public init(model: FeatureRootModel) { + self.model = model + _settings = State(initialValue: model.snapshot.settings) + } + + public var body: some View { + NavigationStack { + Form { + Section("Appearance") { + Picker("Theme", selection: $settings.appearance) { + Text("System").tag(FeatureAppearance.system) + Text("Dark").tag(FeatureAppearance.dark) + } + Toggle("Haptics", isOn: $settings.hapticsEnabled) + Toggle("Notifications", isOn: $settings.notificationsEnabled) + } + + Section("Default agent") { + ProviderModelPicker( + providers: model.snapshot.providers, + selection: $settings.defaultSelection + ) + if let provider = selectedProvider, let selectedModel { + LabeledContent("Provider", value: provider.name) + if let detail = selectedModel.detail { + Text(detail) + .font(.footnote) + .foregroundStyle(.secondary) + } + } + } + + Section("Environment") { + LabeledContent( + "Status", + value: model.snapshot.connection.state == .connected ? "Connected" : "Offline" + ) + if let endpoint = model.snapshot.connection.endpoint { + LabeledContent("Server") { + Text(endpoint) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + ForEach(model.snapshot.environments) { environment in + Button { + Task { await model.activateEnvironment(environment.id) } + } label: { + HStack { + VStack(alignment: .leading, spacing: 2) { + Text(environment.name) + .foregroundStyle(.primary) + Text(environment.endpoint) + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + if environment.isActive { + Image(systemName: "checkmark.circle.fill") + .foregroundStyle(.green) + } + } + } + .swipeActions { + Button(role: .destructive) { + Task { await model.removeEnvironment(environment.id) } + } label: { + Label("Remove", systemImage: "trash") + } + } + .contextMenu { + Button(role: .destructive) { + Task { await model.removeEnvironment(environment.id) } + } label: { + Label("Remove Environment", systemImage: "trash") + } + } + } + Button("Disconnect", role: .destructive) { + showingDisconnect = true + } + } + + Section("About") { + LabeledContent("App", value: "T3 Code for iOS") + LabeledContent("Platform", value: "Native SwiftUI") + Link("Open source", destination: URL(string: "https://github.com/pingdotgg/t3code")!) + } + } + .scrollContentBackground(.hidden) + .background(Color.black) + .navigationTitle("Settings") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button(isSaving ? "Saving…" : "Save") { + save() + } + .disabled(isSaving || settings == model.snapshot.settings) + } + } + .confirmationDialog( + "Disconnect from this environment?", + isPresented: $showingDisconnect, + titleVisibility: .visible + ) { + Button("Disconnect", role: .destructive) { + Task { + await model.disconnect() + dismiss() + } + } + Button("Cancel", role: .cancel) {} + } + } + } + + private var selectedProvider: FeatureProvider? { + guard let selection = settings.defaultSelection else { return nil } + return model.snapshot.providers.first { $0.id == selection.providerID } + } + + private var selectedModel: FeatureModel? { + guard let selection = settings.defaultSelection else { return nil } + return selectedProvider?.models.first { $0.id == selection.modelID } + } + + private func save() { + isSaving = true + Task { + await model.saveSettings(settings) + isSaving = false + if model.snapshot.settings == settings { + dismiss() + } + } + } +} diff --git a/apps/swift-ios/Features/Shared/FeatureClient.swift b/apps/swift-ios/Features/Shared/FeatureClient.swift new file mode 100644 index 0000000000..e06d9ddcb2 --- /dev/null +++ b/apps/swift-ios/Features/Shared/FeatureClient.swift @@ -0,0 +1,114 @@ +import Foundation + +/// The app-owned adapter between the native feature layer and T3's WebSocket/Core runtime. +/// Implementations are main-actor isolated so UI state never depends on locking. +@MainActor +public protocol FeatureClient: AnyObject { + func initialSnapshot() async throws -> FeatureSnapshot + func events() -> AsyncStream + + func pair(endpoint: String, token: String?) async throws + func activateEnvironment(id: String) async throws + func removeEnvironment(id: String) async throws + func disconnect() async + + func addProject(path: String) async throws + func createThread(projectID: String, title: String?, selection: FeatureSelection?) async throws -> FeatureThread + func renameThread(id: String, title: String) async throws + func setThreadArchived(id: String, archived: Bool) async throws + func setThreadSettled(id: String, settled: Bool) async throws + func setThreadSnoozed(id: String, until: Date?) async throws + func setRuntimeMode(id: String, mode: FeatureRuntimeMode) async throws + func setInteractionMode(id: String, mode: FeatureInteractionMode) async throws + func deleteThread(id: String) async throws + + func loadThread(id: String) async throws -> FeatureThreadDetail + func sendMessage(threadID: String, text: String, selection: FeatureSelection?) async throws + func cancelTurn(threadID: String) async throws + func resolveApproval(id: String, decision: FeatureApprovalDecision) async throws + func resolveUserInput(id: String, answers: [String: String]) async throws + + func saveSettings(_ settings: FeatureSettings) async throws + + func listFiles(threadID: String, path: String?) async throws -> [FeatureFileEntry] + func readFile(threadID: String, path: String) async throws -> FeatureFileContent + func loadReview(threadID: String) async throws -> FeatureReview + + func sourceControlStatus(threadID: String) async throws -> FeatureSourceControlStatus + func performSourceControlAction( + threadID: String, + action: FeatureSourceControlAction, + message: String? + ) async throws -> FeatureSourceControlStatus + + func terminalSnapshot(threadID: String) async throws -> FeatureTerminalSnapshot + func terminalEvents(threadID: String) -> AsyncStream + func openTerminal(threadID: String, columns: Int, rows: Int) async throws + func writeTerminal(threadID: String, data: String) async throws + func resizeTerminal(threadID: String, columns: Int, rows: Int) async throws + func closeTerminal(threadID: String) async throws +} + +public extension FeatureClient { + func events() -> AsyncStream { + AsyncStream { continuation in continuation.finish() } + } + + func activateEnvironment(id: String) async throws {} + func removeEnvironment(id: String) async throws {} + func disconnect() async {} + func addProject(path: String) async throws {} + func resolveUserInput(id: String, answers: [String: String]) async throws {} + func setThreadSettled(id: String, settled: Bool) async throws {} + func setThreadSnoozed(id: String, until: Date?) async throws {} + func setRuntimeMode(id: String, mode: FeatureRuntimeMode) async throws {} + func setInteractionMode(id: String, mode: FeatureInteractionMode) async throws {} + + func listFiles(threadID: String, path: String?) async throws -> [FeatureFileEntry] { + throw FeatureCapabilityUnavailable("Files") + } + + func readFile(threadID: String, path: String) async throws -> FeatureFileContent { + throw FeatureCapabilityUnavailable("File preview") + } + + func loadReview(threadID: String) async throws -> FeatureReview { + throw FeatureCapabilityUnavailable("Review") + } + + func sourceControlStatus(threadID: String) async throws -> FeatureSourceControlStatus { + throw FeatureCapabilityUnavailable("Source control") + } + + func performSourceControlAction( + threadID: String, + action: FeatureSourceControlAction, + message: String? + ) async throws -> FeatureSourceControlStatus { + throw FeatureCapabilityUnavailable("Source control actions") + } + + func terminalSnapshot(threadID: String) async throws -> FeatureTerminalSnapshot { + throw FeatureCapabilityUnavailable("Terminal") + } + + func terminalEvents(threadID: String) -> AsyncStream { + AsyncStream { $0.finish() } + } + + func openTerminal(threadID: String, columns: Int, rows: Int) async throws { + throw FeatureCapabilityUnavailable("Terminal") + } + + func writeTerminal(threadID: String, data: String) async throws { + throw FeatureCapabilityUnavailable("Terminal") + } + + func resizeTerminal(threadID: String, columns: Int, rows: Int) async throws { + throw FeatureCapabilityUnavailable("Terminal") + } + + func closeTerminal(threadID: String) async throws { + throw FeatureCapabilityUnavailable("Terminal") + } +} diff --git a/apps/swift-ios/Features/Shared/FeatureModels.swift b/apps/swift-ios/Features/Shared/FeatureModels.swift new file mode 100644 index 0000000000..05edbc9fe2 --- /dev/null +++ b/apps/swift-ios/Features/Shared/FeatureModels.swift @@ -0,0 +1,361 @@ +import Foundation + +public struct FeatureConnection: Sendable, Equatable, Codable { + public enum State: String, Sendable, Codable { + case disconnected + case connecting + case connected + case reconnecting + } + + public var state: State + public var environmentName: String? + public var endpoint: String? + public var detail: String? + + public init( + state: State = .disconnected, + environmentName: String? = nil, + endpoint: String? = nil, + detail: String? = nil + ) { + self.state = state + self.environmentName = environmentName + self.endpoint = endpoint + self.detail = detail + } +} + +public struct FeatureEnvironment: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var name: String + public var endpoint: String + public var isActive: Bool + + public init(id: String, name: String, endpoint: String, isActive: Bool = false) { + self.id = id + self.name = name + self.endpoint = endpoint + self.isActive = isActive + } +} + +public struct FeatureProject: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var environmentID: String + public var name: String + public var path: String + public var threadCount: Int + + public init(id: String, environmentID: String, name: String, path: String, threadCount: Int = 0) { + self.id = id + self.environmentID = environmentID + self.name = name + self.path = path + self.threadCount = threadCount + } +} + +public enum FeatureThreadState: String, Sendable, Codable { + case idle + case queued + case working + case waitingForApproval + case waitingForInput + case failed + case completed +} + +public enum FeatureRuntimeMode: String, CaseIterable, Sendable, Codable { + case approvalRequired + case autoAcceptEdits + case automatic + case fullAccess +} + +public enum FeatureInteractionMode: String, CaseIterable, Sendable, Codable { + case standard + case plan +} + +public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var projectID: String + public var title: String + public var preview: String? + public var updatedAt: Date + public var state: FeatureThreadState + public var providerID: String? + public var modelID: String? + public var isArchived: Bool + public var isSettled: Bool + public var snoozedUntil: Date? + public var runtimeMode: FeatureRuntimeMode + public var interactionMode: FeatureInteractionMode + + public init( + id: String, + projectID: String, + title: String, + preview: String? = nil, + updatedAt: Date = .now, + state: FeatureThreadState = .idle, + providerID: String? = nil, + modelID: String? = nil, + isArchived: Bool = false, + isSettled: Bool = false, + snoozedUntil: Date? = nil, + runtimeMode: FeatureRuntimeMode = .fullAccess, + interactionMode: FeatureInteractionMode = .standard + ) { + self.id = id + self.projectID = projectID + self.title = title + self.preview = preview + self.updatedAt = updatedAt + self.state = state + self.providerID = providerID + self.modelID = modelID + self.isArchived = isArchived + self.isSettled = isSettled + self.snoozedUntil = snoozedUntil + self.runtimeMode = runtimeMode + self.interactionMode = interactionMode + } +} + +public enum FeatureMessageRole: String, Sendable, Codable { + case user + case assistant + case system + case tool +} + +public enum FeatureMessageState: String, Sendable, Codable { + case queued + case streaming + case complete + case failed +} + +public struct FeatureMessage: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var role: FeatureMessageRole + public var text: String + public var createdAt: Date + public var state: FeatureMessageState + public var toolName: String? + + public init( + id: String, + role: FeatureMessageRole, + text: String, + createdAt: Date = .now, + state: FeatureMessageState = .complete, + toolName: String? = nil + ) { + self.id = id + self.role = role + self.text = text + self.createdAt = createdAt + self.state = state + self.toolName = toolName + } +} + +public enum FeatureApprovalKind: String, Sendable, Codable { + case command + case fileRead + case fileChange + case patch + case other +} + +public struct FeatureApproval: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var threadID: String + public var kind: FeatureApprovalKind + public var title: String + public var detail: String + + public init(id: String, threadID: String, kind: FeatureApprovalKind, title: String, detail: String) { + self.id = id + self.threadID = threadID + self.kind = kind + self.title = title + self.detail = detail + } +} + +public struct FeatureInputOption: Sendable, Equatable, Hashable, Codable { + public var label: String + public var detail: String + + public init(label: String, detail: String) { + self.label = label + self.detail = detail + } +} + +public struct FeatureInputQuestion: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var header: String + public var question: String + public var options: [FeatureInputOption] + public var allowsMultiple: Bool + + public init( + id: String, + header: String, + question: String, + options: [FeatureInputOption] = [], + allowsMultiple: Bool = false + ) { + self.id = id + self.header = header + self.question = question + self.options = options + self.allowsMultiple = allowsMultiple + } +} + +public struct FeatureUserInput: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var threadID: String + public var questions: [FeatureInputQuestion] + + public init(id: String, threadID: String, questions: [FeatureInputQuestion]) { + self.id = id + self.threadID = threadID + self.questions = questions + } +} + +public struct FeatureThreadDetail: Sendable, Equatable, Codable { + public var thread: FeatureThread + public var messages: [FeatureMessage] + public var approvals: [FeatureApproval] + public var userInputs: [FeatureUserInput] + + public init( + thread: FeatureThread, + messages: [FeatureMessage] = [], + approvals: [FeatureApproval] = [], + userInputs: [FeatureUserInput] = [] + ) { + self.thread = thread + self.messages = messages + self.approvals = approvals + self.userInputs = userInputs + } +} + +public struct FeatureModel: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var name: String + public var detail: String? + public var supportsImages: Bool + public var supportsReasoning: Bool + + public init( + id: String, + name: String, + detail: String? = nil, + supportsImages: Bool = false, + supportsReasoning: Bool = false + ) { + self.id = id + self.name = name + self.detail = detail + self.supportsImages = supportsImages + self.supportsReasoning = supportsReasoning + } +} + +public struct FeatureProvider: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var name: String + public var isAvailable: Bool + public var models: [FeatureModel] + + public init(id: String, name: String, isAvailable: Bool = true, models: [FeatureModel] = []) { + self.id = id + self.name = name + self.isAvailable = isAvailable + self.models = models + } +} + +public struct FeatureSelection: Sendable, Equatable, Hashable, Codable { + public var providerID: String + public var modelID: String + + public init(providerID: String, modelID: String) { + self.providerID = providerID + self.modelID = modelID + } +} + +public enum FeatureAppearance: String, CaseIterable, Sendable, Codable { + case system + case dark +} + +public struct FeatureSettings: Sendable, Equatable, Codable { + public var appearance: FeatureAppearance + public var hapticsEnabled: Bool + public var notificationsEnabled: Bool + public var defaultSelection: FeatureSelection? + + public init( + appearance: FeatureAppearance = .dark, + hapticsEnabled: Bool = true, + notificationsEnabled: Bool = true, + defaultSelection: FeatureSelection? = nil + ) { + self.appearance = appearance + self.hapticsEnabled = hapticsEnabled + self.notificationsEnabled = notificationsEnabled + self.defaultSelection = defaultSelection + } +} + +public struct FeatureSnapshot: Sendable, Equatable, Codable { + public var connection: FeatureConnection + public var environments: [FeatureEnvironment] + public var projects: [FeatureProject] + public var threads: [FeatureThread] + public var providers: [FeatureProvider] + public var settings: FeatureSettings + + public init( + connection: FeatureConnection = .init(), + environments: [FeatureEnvironment] = [], + projects: [FeatureProject] = [], + threads: [FeatureThread] = [], + providers: [FeatureProvider] = [], + settings: FeatureSettings = .init() + ) { + self.connection = connection + self.environments = environments + self.projects = projects + self.threads = threads + self.providers = providers + self.settings = settings + } +} + +public enum FeatureApprovalDecision: String, Sendable, Codable { + case allowOnce + case allowForSession + case deny +} + +public enum FeatureEvent: Sendable { + case snapshot(FeatureSnapshot) + case connection(FeatureConnection) + case thread(FeatureThread) + case threadRemoved(id: String) + case detail(FeatureThreadDetail) + case failure(String) +} diff --git a/apps/swift-ios/Features/Shared/FeatureToolModels.swift b/apps/swift-ios/Features/Shared/FeatureToolModels.swift new file mode 100644 index 0000000000..d014f4627c --- /dev/null +++ b/apps/swift-ios/Features/Shared/FeatureToolModels.swift @@ -0,0 +1,294 @@ +import Foundation + +public struct FeatureCapabilityUnavailable: LocalizedError, Sendable, Equatable { + public let capability: String + + public init(_ capability: String) { + self.capability = capability + } + + public var errorDescription: String? { + "\(capability) is not supported by this environment." + } +} + +public enum FeatureFileKind: String, Sendable, Codable { + case file + case directory + case symbolicLink +} + +public struct FeatureFileEntry: Identifiable, Sendable, Equatable, Hashable, Codable { + public var id: String { path } + public let path: String + public var name: String + public var kind: FeatureFileKind + public var sizeBytes: Int? + public var isHidden: Bool + + public init( + path: String, + name: String, + kind: FeatureFileKind, + sizeBytes: Int? = nil, + isHidden: Bool = false + ) { + self.path = path + self.name = name + self.kind = kind + self.sizeBytes = sizeBytes + self.isHidden = isHidden + } +} + +public extension Array where Element == FeatureFileEntry { + func featureFiltered(by query: String, includesHidden: Bool) -> [FeatureFileEntry] { + let visible = includesHidden ? self : filter { !$0.isHidden } + let filtered: [FeatureFileEntry] + if query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + filtered = visible + } else { + filtered = visible.filter { $0.name.localizedCaseInsensitiveContains(query) } + } + return filtered.sorted { + if $0.kind == .directory, $1.kind != .directory { return true } + if $0.kind != .directory, $1.kind == .directory { return false } + return $0.name.localizedStandardCompare($1.name) == .orderedAscending + } + } +} + +public struct FeatureFileContent: Sendable, Equatable, Codable { + public var path: String + public var text: String + public var language: String? + public var isTruncated: Bool + public var totalBytes: Int? + + public init( + path: String, + text: String, + language: String? = nil, + isTruncated: Bool = false, + totalBytes: Int? = nil + ) { + self.path = path + self.text = text + self.language = language + self.isTruncated = isTruncated + self.totalBytes = totalBytes + } +} + +public enum FeatureDiffLineKind: String, Sendable, Codable { + case context + case addition + case deletion + case hunk +} + +public struct FeatureDiffLine: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var kind: FeatureDiffLineKind + public var oldLine: Int? + public var newLine: Int? + public var text: String + + public init( + id: String, + kind: FeatureDiffLineKind, + oldLine: Int? = nil, + newLine: Int? = nil, + text: String + ) { + self.id = id + self.kind = kind + self.oldLine = oldLine + self.newLine = newLine + self.text = text + } +} + +public enum FeatureReviewChangeKind: String, Sendable, Codable { + case added + case modified + case deleted + case renamed + case binary +} + +public struct FeatureReviewFile: Identifiable, Sendable, Equatable, Hashable, Codable { + public var id: String { path } + public var path: String + public var previousPath: String? + public var change: FeatureReviewChangeKind + public var additions: Int + public var deletions: Int + public var lines: [FeatureDiffLine] + + public init( + path: String, + previousPath: String? = nil, + change: FeatureReviewChangeKind, + additions: Int, + deletions: Int, + lines: [FeatureDiffLine] = [] + ) { + self.path = path + self.previousPath = previousPath + self.change = change + self.additions = additions + self.deletions = deletions + self.lines = lines + } +} + +public struct FeatureReview: Sendable, Equatable, Codable { + public var title: String + public var baseReference: String? + public var files: [FeatureReviewFile] + public var isTruncated: Bool + + public init( + title: String = "Working tree", + baseReference: String? = nil, + files: [FeatureReviewFile] = [], + isTruncated: Bool = false + ) { + self.title = title + self.baseReference = baseReference + self.files = files + self.isTruncated = isTruncated + } + + public var additions: Int { files.reduce(0) { $0 + $1.additions } } + public var deletions: Int { files.reduce(0) { $0 + $1.deletions } } +} + +public enum FeatureSourceControlFileState: String, Sendable, Codable { + case added + case modified + case deleted + case renamed + case untracked + case conflicted +} + +public struct FeatureSourceControlFile: Identifiable, Sendable, Equatable, Hashable, Codable { + public var id: String { path } + public var path: String + public var state: FeatureSourceControlFileState + public var isStaged: Bool + + public init(path: String, state: FeatureSourceControlFileState, isStaged: Bool) { + self.path = path + self.state = state + self.isStaged = isStaged + } +} + +public struct FeaturePullRequest: Sendable, Equatable, Hashable, Codable { + public var number: Int + public var title: String + public var state: String + public var url: URL? + + public init(number: Int, title: String, state: String, url: URL? = nil) { + self.number = number + self.title = title + self.state = state + self.url = url + } +} + +public enum FeatureSourceControlAction: String, CaseIterable, Sendable, Codable { + case commit + case push + case pull + case createPullRequest + case commitAndPush + case commitPushAndCreatePullRequest +} + +public struct FeatureSourceControlStatus: Sendable, Equatable, Codable { + public var isRepository: Bool + public var branch: String? + public var upstream: String? + public var aheadCount: Int + public var behindCount: Int + public var files: [FeatureSourceControlFile] + public var pullRequest: FeaturePullRequest? + public var isBusy: Bool + + public init( + isRepository: Bool = true, + branch: String? = nil, + upstream: String? = nil, + aheadCount: Int = 0, + behindCount: Int = 0, + files: [FeatureSourceControlFile] = [], + pullRequest: FeaturePullRequest? = nil, + isBusy: Bool = false + ) { + self.isRepository = isRepository + self.branch = branch + self.upstream = upstream + self.aheadCount = aheadCount + self.behindCount = behindCount + self.files = files + self.pullRequest = pullRequest + self.isBusy = isBusy + } + + public var availableActions: [FeatureSourceControlAction] { + guard isRepository, !isBusy else { return [] } + var actions: [FeatureSourceControlAction] = [] + if !files.isEmpty { + actions.append(.commit) + actions.append(.commitAndPush) + if pullRequest == nil { + actions.append(.commitPushAndCreatePullRequest) + } + } + if aheadCount > 0 { actions.append(.push) } + if behindCount > 0 { actions.append(.pull) } + if pullRequest == nil { actions.append(.createPullRequest) } + return actions + } +} + +public enum FeatureTerminalState: String, Sendable, Codable { + case stopped + case starting + case running + case exited + case failed +} + +public struct FeatureTerminalSnapshot: Sendable, Equatable, Codable { + public var threadID: String + public var state: FeatureTerminalState + public var title: String + public var workingDirectory: String? + public var buffer: String + public var exitCode: Int? + public var error: String? + + public init( + threadID: String, + state: FeatureTerminalState = .stopped, + title: String = "Terminal", + workingDirectory: String? = nil, + buffer: String = "", + exitCode: Int? = nil, + error: String? = nil + ) { + self.threadID = threadID + self.state = state + self.title = title + self.workingDirectory = workingDirectory + self.buffer = buffer + self.exitCode = exitCode + self.error = error + } +} diff --git a/apps/swift-ios/Features/SourceControl/FeatureSourceControlView.swift b/apps/swift-ios/Features/SourceControl/FeatureSourceControlView.swift new file mode 100644 index 0000000000..a51115c8ad --- /dev/null +++ b/apps/swift-ios/Features/SourceControl/FeatureSourceControlView.swift @@ -0,0 +1,227 @@ +import SwiftUI + +public struct FeatureSourceControlView: View { + let client: any FeatureClient + let threadID: String + + @State private var status: FeatureSourceControlStatus? + @State private var isLoading = true + @State private var isRunningAction = false + @State private var errorMessage: String? + @State private var commitMessage = "" + @State private var pendingCommitAction: FeatureSourceControlAction? + + public init(client: any FeatureClient, threadID: String) { + self.client = client + self.threadID = threadID + } + + public var body: some View { + Group { + if isLoading, status == nil { + ProgressView("Loading repository…") + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if let status { + statusList(status) + } else { + ContentUnavailableView( + "Source control unavailable", + systemImage: "arrow.triangle.branch", + description: Text(errorMessage ?? "Repository status could not be loaded.") + ) + } + } + .background(Color.black) + .navigationTitle("Source Control") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Button { Task { await load() } } label: { Image(systemName: "arrow.clockwise") } + .disabled(isLoading || isRunningAction) + .accessibilityLabel("Reload source control") + } + } + .alert("Commit changes", isPresented: Binding( + get: { pendingCommitAction != nil }, + set: { if !$0 { pendingCommitAction = nil } } + )) { + TextField("Commit message", text: $commitMessage) + Button("Cancel", role: .cancel) { pendingCommitAction = nil } + Button("Commit") { + if let action = pendingCommitAction { + Task { await perform(action, message: commitMessage) } + } + pendingCommitAction = nil + } + .disabled(commitMessage.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + .task { await load() } + } + + private func statusList(_ status: FeatureSourceControlStatus) -> some View { + List { + Section("Repository") { + LabeledContent("Branch", value: status.branch ?? "Detached HEAD") + if let upstream = status.upstream { + LabeledContent("Upstream", value: upstream) + } + HStack { + Label("\(status.aheadCount) ahead", systemImage: "arrow.up") + Spacer() + Label("\(status.behindCount) behind", systemImage: "arrow.down") + } + .font(.footnote) + .foregroundStyle(.secondary) + if let pullRequest = status.pullRequest { + if let url = pullRequest.url { + Link(destination: url) { + Label("PR #\(pullRequest.number) · \(pullRequest.title)", systemImage: "arrow.up.right.square") + } + } else { + LabeledContent("Pull Request", value: "#\(pullRequest.number) · \(pullRequest.state)") + } + } + } + + Section("Actions") { + if status.availableActions.isEmpty { + Text(status.isBusy ? "Source control operation in progress" : "No actions available") + .foregroundStyle(.secondary) + } + ForEach(status.availableActions, id: \.self) { action in + Button { + begin(action) + } label: { + Label(action.title, systemImage: action.icon) + .frame(maxWidth: .infinity, alignment: .leading) + } + .disabled(isRunningAction) + } + } + + Section("\(status.files.count) changed \(status.files.count == 1 ? "file" : "files")") { + if status.files.isEmpty { + Label("Working tree clean", systemImage: "checkmark.circle") + .foregroundStyle(.secondary) + } + ForEach(status.files) { file in + HStack(spacing: 10) { + Text(file.state.shortLabel) + .font(.caption2.monospaced().weight(.bold)) + .foregroundStyle(file.state.color) + .frame(width: 18) + Text(file.path) + .font(.subheadline) + .lineLimit(1) + Spacer() + if file.isStaged { + Text("STAGED") + .font(.system(size: 9, weight: .bold)) + .foregroundStyle(.green) + } + } + .accessibilityElement(children: .combine) + } + } + } + .listStyle(.insetGrouped) + .scrollContentBackground(.hidden) + .refreshable { await load() } + .overlay { + if isRunningAction { + ProgressView() + .padding(12) + .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 10)) + } + } + } + + private func begin(_ action: FeatureSourceControlAction) { + if action.requiresMessage { + commitMessage = "" + pendingCommitAction = action + } else { + Task { await perform(action, message: nil) } + } + } + + private func load() async { + isLoading = true + defer { isLoading = false } + do { + status = try await client.sourceControlStatus(threadID: threadID) + errorMessage = nil + } catch { + errorMessage = error.localizedDescription + } + } + + private func perform(_ action: FeatureSourceControlAction, message: String?) async { + isRunningAction = true + defer { isRunningAction = false } + do { + status = try await client.performSourceControlAction( + threadID: threadID, + action: action, + message: message?.trimmingCharacters(in: .whitespacesAndNewlines) + ) + errorMessage = nil + } catch { + errorMessage = error.localizedDescription + } + } +} + +private extension FeatureSourceControlAction { + var requiresMessage: Bool { + switch self { + case .commit, .commitAndPush, .commitPushAndCreatePullRequest: true + case .push, .pull, .createPullRequest: false + } + } + + var title: String { + switch self { + case .commit: "Commit changes" + case .push: "Push" + case .pull: "Pull latest" + case .createPullRequest: "Create pull request" + case .commitAndPush: "Commit and push" + case .commitPushAndCreatePullRequest: "Commit, push, and create PR" + } + } + + var icon: String { + switch self { + case .commit: "checkmark.circle" + case .push: "arrow.up.circle" + case .pull: "arrow.down.circle" + case .createPullRequest: "arrow.triangle.pull" + case .commitAndPush: "arrow.up.circle.fill" + case .commitPushAndCreatePullRequest: "point.3.connected.trianglepath.dotted" + } + } +} + +private extension FeatureSourceControlFileState { + var shortLabel: String { + switch self { + case .added: "A" + case .modified: "M" + case .deleted: "D" + case .renamed: "R" + case .untracked: "?" + case .conflicted: "!" + } + } + + var color: Color { + switch self { + case .added: .green + case .modified: .orange + case .deleted, .conflicted: .red + case .renamed: .blue + case .untracked: .secondary + } + } +} diff --git a/apps/swift-ios/Features/Terminal/FeatureTerminalView.swift b/apps/swift-ios/Features/Terminal/FeatureTerminalView.swift new file mode 100644 index 0000000000..944d9cf31a --- /dev/null +++ b/apps/swift-ios/Features/Terminal/FeatureTerminalView.swift @@ -0,0 +1,209 @@ +import SwiftUI + +public struct FeatureTerminalView: View { + let client: any FeatureClient + let threadID: String + + @State private var terminal: FeatureTerminalSnapshot? + @State private var input = "" + @State private var isLoading = true + @State private var errorMessage: String? + @FocusState private var inputFocused: Bool + + public init(client: any FeatureClient, threadID: String) { + self.client = client + self.threadID = threadID + } + + public var body: some View { + VStack(spacing: 0) { + terminalHeader + Divider() + terminalBuffer + terminalControls + } + .background(Color.black) + .navigationTitle("Terminal") + .navigationBarTitleDisplayMode(.inline) + .task { await loadAndOpen() } + .task { + for await update in client.terminalEvents(threadID: threadID) { + terminal = update + } + } + } + + private var terminalHeader: some View { + HStack(spacing: 9) { + Circle() + .fill(statusColor) + .frame(width: 7, height: 7) + VStack(alignment: .leading, spacing: 1) { + Text(terminal?.title ?? "Terminal") + .font(.subheadline.weight(.semibold)) + Text(terminal?.workingDirectory ?? statusLabel) + .font(.caption2.monospaced()) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Spacer() + if terminal?.state == .running { + Button("Stop", role: .destructive) { + Task { await stop() } + } + .font(.footnote.weight(.semibold)) + } else { + Button("Start") { + Task { await open() } + } + .font(.footnote.weight(.semibold)) + .disabled(isLoading) + } + } + .padding(.horizontal, 14) + .padding(.vertical, 9) + } + + @ViewBuilder + private var terminalBuffer: some View { + if isLoading, terminal == nil { + ProgressView("Opening terminal…") + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if let errorMessage, terminal == nil { + ContentUnavailableView( + "Terminal unavailable", + systemImage: "terminal", + description: Text(errorMessage) + ) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + ScrollViewReader { proxy in + ScrollView([.horizontal, .vertical]) { + Text(terminal?.buffer.isEmpty == false ? terminal?.buffer ?? "" : " ") + .font(.system(size: 12, design: .monospaced)) + .foregroundStyle(Color(white: 0.86)) + .textSelection(.enabled) + .frame(maxWidth: .infinity, minHeight: 300, alignment: .topLeading) + .padding(12) + .id("terminal-end") + } + .defaultScrollAnchor(.bottom) + .onChange(of: terminal?.buffer) { + proxy.scrollTo("terminal-end", anchor: .bottom) + } + } + } + } + + private var terminalControls: some View { + VStack(spacing: 7) { + HStack(spacing: 7) { + terminalKey("ctrl-c", label: "^C", data: "\u{3}") + terminalKey("escape", label: "esc", data: "\u{1B}") + terminalKey("tab", label: "tab", data: "\t") + Spacer() + } + HStack(spacing: 8) { + TextField("Command", text: $input) + .font(.system(.body, design: .monospaced)) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .focused($inputFocused) + .submitLabel(.send) + .onSubmit(sendCommand) + .padding(.horizontal, 11) + .frame(minHeight: 40) + .background(Color.white.opacity(0.08), in: RoundedRectangle(cornerRadius: 9)) + Button(action: sendCommand) { + Image(systemName: "return") + .frame(width: 40, height: 40) + } + .buttonStyle(.borderedProminent) + .tint(.white) + .foregroundStyle(.black) + .disabled(!isRunning || input.isEmpty) + .accessibilityLabel("Send command") + } + } + .padding(10) + .background(Color(white: 0.025)) + .overlay(alignment: .top) { Divider() } + } + + private func terminalKey(_ id: String, label: String, data: String) -> some View { + Button(label) { + Task { await write(data) } + } + .font(.caption.monospaced().weight(.medium)) + .buttonStyle(.bordered) + .controlSize(.small) + .disabled(!isRunning) + .accessibilityIdentifier("terminal-\(id)") + } + + private var isRunning: Bool { terminal?.state == .running } + + private var statusColor: Color { + switch terminal?.state { + case .running: .green + case .starting: .orange + case .failed: .red + case .exited, .stopped, nil: .gray + } + } + + private var statusLabel: String { + terminal?.state.rawValue.capitalized ?? "Not connected" + } + + private func loadAndOpen() async { + isLoading = true + defer { isLoading = false } + do { + terminal = try await client.terminalSnapshot(threadID: threadID) + if terminal?.state == .stopped || terminal?.state == .exited { + try await client.openTerminal(threadID: threadID, columns: 80, rows: 24) + } + errorMessage = nil + } catch { + errorMessage = error.localizedDescription + } + } + + private func open() async { + do { + try await client.openTerminal(threadID: threadID, columns: 80, rows: 24) + terminal = try await client.terminalSnapshot(threadID: threadID) + errorMessage = nil + } catch { + errorMessage = error.localizedDescription + } + } + + private func stop() async { + do { + try await client.closeTerminal(threadID: threadID) + terminal = try? await client.terminalSnapshot(threadID: threadID) + } catch { + errorMessage = error.localizedDescription + } + } + + private func sendCommand() { + guard isRunning, !input.isEmpty else { return } + let command = input + input = "" + Task { + await write(command + "\n") + inputFocused = true + } + } + + private func write(_ data: String) async { + do { + try await client.writeTerminal(threadID: threadID, data: data) + } catch { + errorMessage = error.localizedDescription + } + } +} diff --git a/apps/swift-ios/Features/Workspace/NewThreadView.swift b/apps/swift-ios/Features/Workspace/NewThreadView.swift new file mode 100644 index 0000000000..dca6e73f4d --- /dev/null +++ b/apps/swift-ios/Features/Workspace/NewThreadView.swift @@ -0,0 +1,129 @@ +import SwiftUI + +public struct NewThreadView: View { + @SwiftUI.Environment(\.dismiss) private var dismiss + @Bindable var model: FeatureRootModel + let onCreated: (FeatureThread) -> Void + + @State private var projectID = "" + @State private var title = "" + @State private var selection: FeatureSelection? + @State private var isCreating = false + + public init(model: FeatureRootModel, onCreated: @escaping (FeatureThread) -> Void) { + self.model = model + self.onCreated = onCreated + } + + public var body: some View { + NavigationStack { + Form { + Section("Project") { + Picker("Project", selection: $projectID) { + ForEach(model.snapshot.projects) { project in + Text(project.name).tag(project.id) + } + } + } + + Section("Task") { + TextField("Optional title", text: $title, axis: .vertical) + .lineLimit(1...3) + ProviderModelPicker( + providers: model.snapshot.providers, + selection: $selection + ) + } + } + .scrollContentBackground(.hidden) + .background(Color.black) + .navigationTitle("New Thread") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button(isCreating ? "Creating…" : "Create") { + create() + } + .disabled(projectID.isEmpty || isCreating) + } + } + .onAppear { + if projectID.isEmpty { + projectID = model.snapshot.projects.first?.id ?? "" + } + if selection == nil { + selection = model.snapshot.settings.defaultSelection + ?? model.snapshot.providers.first?.models.first.map { + FeatureSelection( + providerID: model.snapshot.providers.first?.id ?? "", + modelID: $0.id + ) + } + } + } + } + } + + private func create() { + isCreating = true + Task { + let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines) + if let thread = await model.createThread( + projectID: projectID, + title: trimmed.isEmpty ? nil : trimmed, + selection: selection + ) { + onCreated(thread) + } + isCreating = false + } + } +} + +public struct ProviderModelPicker: View { + let providers: [FeatureProvider] + @Binding var selection: FeatureSelection? + + public init(providers: [FeatureProvider], selection: Binding) { + self.providers = providers + _selection = selection + } + + public var body: some View { + Menu { + ForEach(providers.filter(\.isAvailable)) { provider in + Section(provider.name) { + ForEach(provider.models) { model in + Button { + selection = FeatureSelection(providerID: provider.id, modelID: model.id) + } label: { + if selection?.providerID == provider.id, selection?.modelID == model.id { + Label(model.name, systemImage: "checkmark") + } else { + Text(model.name) + } + } + } + } + } + } label: { + LabeledContent("Model") { + Text(selectionLabel) + .foregroundStyle(.secondary) + } + } + .accessibilityLabel("Provider and model") + } + + private var selectionLabel: String { + guard let selection, + let provider = providers.first(where: { $0.id == selection.providerID }), + let model = provider.models.first(where: { $0.id == selection.modelID }) else { + return "Automatic" + } + return "\(provider.name) · \(model.name)" + } +} diff --git a/apps/swift-ios/Features/Workspace/ProjectAndArchiveViews.swift b/apps/swift-ios/Features/Workspace/ProjectAndArchiveViews.swift new file mode 100644 index 0000000000..72f4c850b0 --- /dev/null +++ b/apps/swift-ios/Features/Workspace/ProjectAndArchiveViews.swift @@ -0,0 +1,135 @@ +import SwiftUI + +public struct AddProjectView: View { + @SwiftUI.Environment(\.dismiss) private var dismiss + @Bindable var model: FeatureRootModel + @State private var path = "" + @State private var isAdding = false + + public init(model: FeatureRootModel) { + self.model = model + } + + public var body: some View { + NavigationStack { + Form { + Section { + TextField("/path/to/project", text: $path) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + } header: { + Text("Workspace path") + } footer: { + Text("The path is resolved by the connected T3 environment.") + } + } + .scrollContentBackground(.hidden) + .background(Color.black) + .navigationTitle("Add Project") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button(isAdding ? "Adding…" : "Add") { add() } + .disabled(trimmedPath.isEmpty || isAdding) + } + } + } + } + + private var trimmedPath: String { + path.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private func add() { + isAdding = true + Task { + if await model.addProject(path: trimmedPath) { + dismiss() + } + isAdding = false + } + } +} + +public struct ArchivedThreadsView: View { + @SwiftUI.Environment(\.dismiss) private var dismiss + @Bindable var model: FeatureRootModel + let onSelect: (FeatureThread) -> Void + + public init(model: FeatureRootModel, onSelect: @escaping (FeatureThread) -> Void) { + self.model = model + self.onSelect = onSelect + } + + public var body: some View { + NavigationStack { + List { + if archived.isEmpty { + ContentUnavailableView( + "No archived threads", + systemImage: "archivebox", + description: Text("Archived work will appear here.") + ) + .listRowBackground(Color.clear) + } + ForEach(archived) { thread in + HStack(spacing: 12) { + Button { + onSelect(thread) + } label: { + FeatureThreadRow( + thread: thread, + projectName: projectName(for: thread.projectID) + ) + .frame(maxWidth: .infinity, alignment: .leading) + } + .buttonStyle(.plain) + + Button { + Task { await model.setArchived(thread.id, archived: false) } + } label: { + Image(systemName: "arrow.uturn.backward") + } + .buttonStyle(.borderless) + .accessibilityLabel("Restore \(thread.title)") + } + .swipeActions { + Button(role: .destructive) { + Task { await model.deleteThread(thread.id) } + } label: { + Label("Delete", systemImage: "trash") + } + Button { + Task { await model.setArchived(thread.id, archived: false) } + } label: { + Label("Restore", systemImage: "arrow.uturn.backward") + } + .tint(.blue) + } + } + } + .scrollContentBackground(.hidden) + .background(Color.black) + .navigationTitle("Archived") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { dismiss() } + } + } + } + } + + private var archived: [FeatureThread] { + model.snapshot.threads + .filter(\.isArchived) + .sorted { $0.updatedAt > $1.updatedAt } + } + + private func projectName(for id: String) -> String { + model.snapshot.projects.first(where: { $0.id == id })?.name ?? "Unknown project" + } +} diff --git a/apps/swift-ios/Features/Workspace/WorkspaceView.swift b/apps/swift-ios/Features/Workspace/WorkspaceView.swift new file mode 100644 index 0000000000..8c6785cdf6 --- /dev/null +++ b/apps/swift-ios/Features/Workspace/WorkspaceView.swift @@ -0,0 +1,335 @@ +import SwiftUI + +public struct WorkspaceView: View { + @Bindable var model: FeatureRootModel + @State private var selectedThreadID: String? + @State private var searchText = "" + @State private var showingNewThread = false + @State private var showingAddProject = false + @State private var showingSettings = false + @State private var showingArchived = false + @State private var renamingThread: FeatureThread? + @State private var renameTitle = "" + + public init(model: FeatureRootModel) { + self.model = model + } + + public var body: some View { + NavigationSplitView { + List(selection: $selectedThreadID) { + connectionSection + projectSection + threadSection + } + .listStyle(.sidebar) + .scrollContentBackground(.hidden) + .background(Color.black) + .searchable(text: $searchText, prompt: "Search threads") + .navigationTitle("T3 Code") + .toolbar { + ToolbarItem(placement: .topBarLeading) { + Button { + showingSettings = true + } label: { + Image(systemName: "gearshape") + } + .accessibilityLabel("Settings") + } + ToolbarItemGroup(placement: .topBarTrailing) { + Button { + showingAddProject = true + } label: { + Image(systemName: "folder.badge.plus") + } + .accessibilityLabel("Add project") + Button { + showingNewThread = true + } label: { + Image(systemName: "square.and.pencil") + } + .accessibilityLabel("New thread") + .disabled(model.snapshot.projects.isEmpty) + } + } + } detail: { + if let id = selectedThreadID, + let thread = model.snapshot.threads.first(where: { $0.id == id }) { + ThreadDetailView(model: model, thread: thread) + .id(id) + } else { + ContentUnavailableView( + "Choose a thread", + systemImage: "bubble.left.and.bubble.right", + description: Text("Select a thread or start a new task.") + ) + .background(Color.black) + } + } + .navigationSplitViewStyle(.balanced) + .sheet(isPresented: $showingNewThread) { + NewThreadView(model: model) { thread in + selectedThreadID = thread.id + showingNewThread = false + } + } + .sheet(isPresented: $showingAddProject) { + AddProjectView(model: model) + } + .sheet(isPresented: $showingSettings) { + SettingsView(model: model) + } + .sheet(isPresented: $showingArchived) { + ArchivedThreadsView(model: model) { thread in + selectedThreadID = thread.id + showingArchived = false + } + } + .alert( + "Rename thread", + isPresented: Binding( + get: { renamingThread != nil }, + set: { if !$0 { renamingThread = nil } } + ) + ) { + TextField("Thread title", text: $renameTitle) + Button("Cancel", role: .cancel) { + renamingThread = nil + } + Button("Save") { + guard let thread = renamingThread else { return } + let title = renameTitle + renamingThread = nil + Task { await model.renameThread(thread.id, title: title) } + } + .disabled(renameTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + .onChange(of: model.snapshot.threads) { + if let selectedThreadID, + !model.snapshot.threads.contains(where: { $0.id == selectedThreadID }) { + self.selectedThreadID = nil + } + } + } + + @ViewBuilder + private var connectionSection: some View { + Section { + Menu { + ForEach(model.snapshot.environments) { environment in + Button { + Task { await model.activateEnvironment(environment.id) } + } label: { + if environment.isActive { + Label(environment.name, systemImage: "checkmark") + } else { + Text(environment.name) + } + } + } + } label: { + HStack(spacing: 9) { + Circle() + .fill(Color.green) + .frame(width: 7, height: 7) + Text(model.snapshot.connection.environmentName ?? "Connected") + .font(.subheadline.weight(.medium)) + .foregroundStyle(.primary) + .lineLimit(1) + Spacer() + if model.snapshot.environments.count > 1 { + Image(systemName: "chevron.up.chevron.down") + .font(.caption2) + .foregroundStyle(.secondary) + } + } + } + .buttonStyle(.plain) + } + } + + @ViewBuilder + private var projectSection: some View { + Section("Projects") { + if model.snapshot.projects.isEmpty { + Text("No projects") + .font(.footnote) + .foregroundStyle(.secondary) + } else { + ForEach(model.snapshot.projects) { project in + HStack(spacing: 10) { + Image(systemName: "folder") + .foregroundStyle(.secondary) + VStack(alignment: .leading, spacing: 2) { + Text(project.name) + .font(.subheadline.weight(.medium)) + .lineLimit(1) + Text(project.path) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Spacer() + Text("\(activeThreads.filter { $0.projectID == project.id }.count)") + .font(.caption.monospacedDigit()) + .foregroundStyle(.tertiary) + } + .accessibilityElement(children: .combine) + } + } + } + } + + @ViewBuilder + private var threadSection: some View { + Section { + if filteredThreads.isEmpty { + Text(searchText.isEmpty ? "No active threads" : "No results") + .font(.footnote) + .foregroundStyle(.secondary) + } + ForEach(filteredThreads) { thread in + NavigationLink(value: thread.id) { + FeatureThreadRow( + thread: thread, + projectName: projectName(for: thread.projectID) + ) + } + .tag(thread.id) + .swipeActions(edge: .trailing, allowsFullSwipe: false) { + Button(role: .destructive) { + Task { await model.deleteThread(thread.id) } + } label: { + Label("Delete", systemImage: "trash") + } + Button { + Task { await model.setArchived(thread.id, archived: true) } + } label: { + Label("Archive", systemImage: "archivebox") + } + .tint(.orange) + } + .contextMenu { + Button { + renameTitle = thread.title + renamingThread = thread + } label: { + Label("Rename", systemImage: "pencil") + } + Button { + Task { await model.setArchived(thread.id, archived: true) } + } label: { + Label("Archive", systemImage: "archivebox") + } + Button { + Task { await model.setSettled(thread.id, settled: !thread.isSettled) } + } label: { + Label( + thread.isSettled ? "Reopen" : "Mark done", + systemImage: thread.isSettled ? "arrow.counterclockwise" : "checkmark" + ) + } + Button { + Task { + await model.setSnoozed( + thread.id, + until: thread.snoozedUntil == nil + ? Date().addingTimeInterval(60 * 60) + : nil + ) + } + } label: { + Label( + thread.snoozedUntil == nil ? "Snooze 1 hour" : "Unsnooze", + systemImage: thread.snoozedUntil == nil ? "clock" : "bell" + ) + } + Button(role: .destructive) { + Task { await model.deleteThread(thread.id) } + } label: { + Label("Delete", systemImage: "trash") + } + } + } + + Button { + showingArchived = true + } label: { + Label("Archived", systemImage: "archivebox") + .font(.subheadline) + } + } header: { + Text("Threads") + } + } + + private var activeThreads: [FeatureThread] { + model.snapshot.threads + .filter { !$0.isArchived } + .sorted { $0.updatedAt > $1.updatedAt } + } + + private var filteredThreads: [FeatureThread] { + guard !searchText.isEmpty else { return activeThreads } + return activeThreads.filter { + $0.title.localizedCaseInsensitiveContains(searchText) + || ($0.preview?.localizedCaseInsensitiveContains(searchText) ?? false) + || projectName(for: $0.projectID).localizedCaseInsensitiveContains(searchText) + } + } + + private func projectName(for id: String) -> String { + model.snapshot.projects.first(where: { $0.id == id })?.name ?? "Unknown project" + } +} + +struct FeatureThreadRow: View { + let thread: FeatureThread + let projectName: String + + var body: some View { + HStack(alignment: .top, spacing: 10) { + Circle() + .fill(statusColor) + .frame(width: 7, height: 7) + .padding(.top, 6) + VStack(alignment: .leading, spacing: 3) { + Text(thread.title) + .font(.subheadline.weight(.medium)) + .lineLimit(1) + HStack(spacing: 5) { + Text(projectName) + if let preview = thread.preview, !preview.isEmpty { + Text("·") + Text(preview) + } + } + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + .padding(.vertical, 2) + .accessibilityElement(children: .combine) + .accessibilityValue(statusText) + } + + private var statusColor: Color { + switch thread.state { + case .idle, .completed: .gray + case .queued: .blue + case .working: .cyan + case .waitingForApproval: .orange + case .waitingForInput: .indigo + case .failed: .red + } + } + + private var statusText: String { + switch thread.state { + case .waitingForApproval: "Waiting for approval" + case .waitingForInput: "Waiting for input" + default: thread.state.rawValue + } + } +} diff --git a/apps/swift-ios/README.md b/apps/swift-ios/README.md new file mode 100644 index 0000000000..99ea13b380 --- /dev/null +++ b/apps/swift-ios/README.md @@ -0,0 +1,67 @@ +# T3 Code for iOS + +A dependency-free, native SwiftUI client for T3 Code. The project targets iOS 17 +and later on iPhone and iPad. + +## Open + +Open `T3Code.xcodeproj`, choose the `T3Code` scheme, and run an installed iOS +simulator. Xcode automatically includes Swift files added below `App`, `Core`, +`Features`, and `DesignSystem`. + +Pair with the same URL produced by a T3 server. The one-time pairing credential is +exchanged for an access token and stored in the Keychain. Environment metadata and +the active selection are stored separately in Application Support. + +## Structure + +- `App` owns the app lifecycle and the thin root composition seam. +- `Core` owns persistence, credentials, transport, and the T3 protocol. +- `Features` owns onboarding, environments, threads, messages, and settings. +- `DesignSystem` contains the small set of shared visual tokens. +- `Resources` contains the asset catalog. +- `Tests` covers pairing, wire contracts, persistence, and feature state changes. + +`RootView` deliberately accepts any SwiftUI content. Production composition injects +`FeatureRootView(client:)` there, keeping protocol adapters out of the UI shell. + +## Included + +- Direct pairing URLs, token exchange, Keychain credentials, saved environment + switching and removal, reconnect, and HTTP polling. +- Server-side project creation from a known workspace path, plus thread search, + creation, rename, archive, restore, delete, settle, snooze, runtime mode, and + interaction mode. +- Provider/model selection, synchronized conversation history, turn cancellation, + approval decisions, and structured user-input requests. +- Workspace files and previews, working-tree review, Git status and common actions, + plus an interactive terminal session scoped to each thread. +- Native settings with persisted appearance and behavior preferences. + +The app speaks the existing HTTP and Effect RPC WebSocket contracts directly. No +JavaScript runtime or third-party package is embedded. + +## Current gaps + +- T3 Connect account sign-in, managed relay environment discovery, and push/live + activity registration are not implemented. Pairing is direct to an environment. +- Adding a project requires entering a path that exists on the server. Remote + filesystem browsing, repository cloning, and source-control account discovery are + not implemented yet. +- Shell updates use the reconnecting WebSocket stream with HTTP polling as a + fallback. Open thread details refresh from the typed thread snapshot when their + shell state changes. +- Attachments and notification deep links are not exposed by the current feature + UI. Source-control status currently reflects changed paths but the server status + response does not distinguish staged files or individual change kinds. + +## Verify + +Run the `T3Code` scheme's tests in Xcode, or use: + +```sh +xcodebuild test \ + -project T3Code.xcodeproj \ + -scheme T3Code \ + -destination 'platform=iOS Simulator,name=iPhone 17 Pro' +``` diff --git a/apps/swift-ios/Resources/Assets.xcassets/AccentColor.colorset/Contents.json b/apps/swift-ios/Resources/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 0000000000..b1e4d30e3c --- /dev/null +++ b/apps/swift-ios/Resources/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,20 @@ +{ + "colors": [ + { + "color": { + "color-space": "srgb", + "components": { + "alpha": "1.000", + "blue": "1.000", + "green": "0.520", + "red": "0.040" + } + }, + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/apps/swift-ios/Resources/Assets.xcassets/Contents.json b/apps/swift-ios/Resources/Assets.xcassets/Contents.json new file mode 100644 index 0000000000..74d6a722cf --- /dev/null +++ b/apps/swift-ios/Resources/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/apps/swift-ios/T3Code.xcodeproj/project.pbxproj b/apps/swift-ios/T3Code.xcodeproj/project.pbxproj new file mode 100644 index 0000000000..3d6d61311a --- /dev/null +++ b/apps/swift-ios/T3Code.xcodeproj/project.pbxproj @@ -0,0 +1,496 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + A10000000000000000000001 /* App */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = App; + sourceTree = ""; + }; + A10000000000000000000002 /* Core */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = Core; + sourceTree = ""; + }; + A10000000000000000000003 /* Features */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = Features; + sourceTree = ""; + }; + A10000000000000000000004 /* DesignSystem */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = DesignSystem; + sourceTree = ""; + }; + A10000000000000000000005 /* Resources */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = Resources; + sourceTree = ""; + }; + A10000000000000000000006 /* Tests */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = Tests; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + A20000000000000000000001 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A20000000000000000000002 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXContainerItemProxy section */ + AC0000000000000000000001 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A90000000000000000000001 /* Project object */; + proxyType = 1; + remoteGlobalIDString = A50000000000000000000001; + remoteInfo = T3Code; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXGroup section */ + A30000000000000000000001 = { + isa = PBXGroup; + children = ( + A10000000000000000000001 /* App */, + A10000000000000000000002 /* Core */, + A10000000000000000000003 /* Features */, + A10000000000000000000004 /* DesignSystem */, + A10000000000000000000005 /* Resources */, + A10000000000000000000006 /* Tests */, + A30000000000000000000002 /* Products */, + ); + sourceTree = ""; + }; + A30000000000000000000002 /* Products */ = { + isa = PBXGroup; + children = ( + A40000000000000000000001 /* T3 Code.app */, + A40000000000000000000002 /* T3CodeTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + A50000000000000000000001 /* T3Code */ = { + isa = PBXNativeTarget; + buildConfigurationList = A60000000000000000000002 /* Build configuration list for PBXNativeTarget "T3Code" */; + buildPhases = ( + A70000000000000000000001 /* Sources */, + A20000000000000000000001 /* Frameworks */, + A80000000000000000000001 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + A10000000000000000000001 /* App */, + A10000000000000000000002 /* Core */, + A10000000000000000000003 /* Features */, + A10000000000000000000004 /* DesignSystem */, + A10000000000000000000005 /* Resources */, + ); + name = T3Code; + packageProductDependencies = ( + ); + productName = T3Code; + productReference = A40000000000000000000001 /* T3 Code.app */; + productType = "com.apple.product-type.application"; + }; + A50000000000000000000002 /* T3CodeTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = A60000000000000000000003 /* Build configuration list for PBXNativeTarget "T3CodeTests" */; + buildPhases = ( + A70000000000000000000002 /* Sources */, + A20000000000000000000002 /* Frameworks */, + A80000000000000000000002 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + AD0000000000000000000001 /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + A10000000000000000000006 /* Tests */, + ); + name = T3CodeTests; + packageProductDependencies = ( + ); + productName = T3CodeTests; + productReference = A40000000000000000000002 /* T3CodeTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + A90000000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 1600; + TargetAttributes = { + A50000000000000000000001 = { + CreatedOnToolsVersion = 16.0; + }; + A50000000000000000000002 = { + CreatedOnToolsVersion = 16.0; + TestTargetID = A50000000000000000000001; + }; + }; + }; + buildConfigurationList = A60000000000000000000001 /* Build configuration list for PBXProject "T3Code" */; + compatibilityVersion = "Xcode 16.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = A30000000000000000000001; + minimizedProjectReferenceProxies = 1; + preferredProjectObjectVersion = 77; + productRefGroup = A30000000000000000000002 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + A50000000000000000000001 /* T3Code */, + A50000000000000000000002 /* T3CodeTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + A80000000000000000000001 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A80000000000000000000002 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + A70000000000000000000001 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A70000000000000000000002 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + AD0000000000000000000001 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = A50000000000000000000001 /* T3Code */; + targetProxy = AC0000000000000000000001 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + AB0000000000000000000001 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + AB0000000000000000000002 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SWIFT_COMPILATION_MODE = wholemodule; + }; + name = Release; + }; + AB0000000000000000000003 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_CFBundleDisplayName = "T3 Code Swift"; + INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools"; + INFOPLIST_KEY_NSAppTransportSecurity_NSAllowsArbitraryLoads = YES; + INFOPLIST_KEY_NSLocalNetworkUsageDescription = "Allow T3 Code to connect to T3 Code servers on your local network or tailnet."; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UIStatusBarStyle = UIStatusBarStyleLightContent; + INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.t3tools.t3code.swift; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + AB0000000000000000000004 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_CFBundleDisplayName = "T3 Code"; + INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools"; + INFOPLIST_KEY_NSAppTransportSecurity_NSAllowsArbitraryLoads = YES; + INFOPLIST_KEY_NSLocalNetworkUsageDescription = "Allow T3 Code to connect to T3 Code servers on your local network or tailnet."; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UIStatusBarStyle = UIStatusBarStyleLightContent; + INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.t3tools.t3code.swift; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + AB0000000000000000000005 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + PRODUCT_BUNDLE_IDENTIFIER = com.t3tools.t3code.swift.tests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/T3Code.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/T3Code"; + }; + name = Debug; + }; + AB0000000000000000000006 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + PRODUCT_BUNDLE_IDENTIFIER = com.t3tools.t3code.swift.tests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/T3Code.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/T3Code"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + A60000000000000000000001 /* Build configuration list for PBXProject "T3Code" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + AB0000000000000000000001 /* Debug */, + AB0000000000000000000002 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A60000000000000000000002 /* Build configuration list for PBXNativeTarget "T3Code" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + AB0000000000000000000003 /* Debug */, + AB0000000000000000000004 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A60000000000000000000003 /* Build configuration list for PBXNativeTarget "T3CodeTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + AB0000000000000000000005 /* Debug */, + AB0000000000000000000006 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin PBXFileReference section */ + A40000000000000000000001 /* T3 Code.app */ = { + isa = PBXFileReference; + explicitFileType = wrapper.application; + includeInIndex = 0; + path = "T3 Code.app"; + sourceTree = BUILT_PRODUCTS_DIR; + }; + A40000000000000000000002 /* T3CodeTests.xctest */ = { + isa = PBXFileReference; + explicitFileType = wrapper.cfbundle; + includeInIndex = 0; + path = T3CodeTests.xctest; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXFileReference section */ + }; + rootObject = A90000000000000000000001 /* Project object */; +} diff --git a/apps/swift-ios/T3Code.xcodeproj/xcshareddata/xcschemes/T3Code.xcscheme b/apps/swift-ios/T3Code.xcodeproj/xcshareddata/xcschemes/T3Code.xcscheme new file mode 100644 index 0000000000..45680ddc0e --- /dev/null +++ b/apps/swift-ios/T3Code.xcodeproj/xcshareddata/xcschemes/T3Code.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift b/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift new file mode 100644 index 0000000000..ca4a64990f --- /dev/null +++ b/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift @@ -0,0 +1,97 @@ +import XCTest +@testable import T3Code + +@MainActor +final class CoreContractTests: XCTestCase { + func testDirectAndHostedPairingURLsResolveLikeExistingClients() throws { + let direct = try PairingURL.resolve("https://studio.example/pair#token=secret") + XCTAssertEqual(direct.credential, "secret") + XCTAssertEqual(direct.httpBaseURL.absoluteString, "https://studio.example/") + XCTAssertEqual(direct.webSocketBaseURL.absoluteString, "wss://studio.example/") + + let hosted = try PairingURL.resolve( + "https://app.t3.codes/pair?host=https%3A%2F%2Fremote.example#token=hosted-secret" + ) + XCTAssertEqual(hosted.credential, "hosted-secret") + XCTAssertEqual(hosted.httpBaseURL.absoluteString, "https://remote.example/") + XCTAssertEqual(hosted.webSocketBaseURL.absoluteString, "wss://remote.example/") + } + + func testShellSnapshotDecodesCurrentWireShape() throws { + let data = Data( + """ + { + "snapshotSequence": 7, + "projects": [{ + "id": "project-1", + "title": "T3 Code", + "workspaceRoot": "/work/t3", + "defaultModelSelection": { + "instanceId": "codex", + "model": "gpt-5.6-sol" + }, + "scripts": [], + "createdAt": "2026-07-30T12:00:00.000Z", + "updatedAt": "2026-07-30T12:00:00.000Z" + }], + "threads": [], + "updatedAt": "2026-07-30T12:00:00.000Z" + } + """.utf8 + ) + + let snapshot = try JSONDecoder.t3.decode(OrchestrationShellSnapshot.self, from: data) + XCTAssertEqual(snapshot.snapshotSequence, 7) + XCTAssertEqual(snapshot.projects.first?.defaultModelSelection?.instanceId, "codex") + XCTAssertNil(snapshot.projects.first?.deletedAt) + } + + func testCommandBuildersMatchOrchestrationContract() throws { + let model = ModelSelection(instanceId: "codex", model: "gpt-5.6-sol") + let command = try OrchestrationCommands.createThread( + threadID: "thread-1", + projectID: "project-1", + title: "Native rebuild", + model: model, + runtimeMode: .fullAccess, + commandID: "command-1", + createdAt: "2026-07-30T12:00:00.000Z" + ) + + XCTAssertEqual(command["type"]?.stringValue, "thread.create") + XCTAssertEqual(command["threadId"]?.stringValue, "thread-1") + XCTAssertEqual(command["modelSelection"]?["instanceId"]?.stringValue, "codex") + XCTAssertEqual(command["runtimeMode"]?.stringValue, "full-access") + } + + func testEnvironmentStorePersistsSelectionAndClearsRemovedActiveEnvironment() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("t3-swift-core-\(UUID().uuidString)", isDirectory: true) + let file = directory.appendingPathComponent("environments.json") + defer { try? FileManager.default.removeItem(at: directory) } + + let store = EnvironmentStore(fileURL: file) + let first = Environment( + id: "one", + label: "One", + httpBaseURL: URL(string: "https://one.example")!, + webSocketBaseURL: URL(string: "wss://one.example")! + ) + let second = Environment( + id: "two", + label: "Two", + httpBaseURL: URL(string: "https://two.example")!, + webSocketBaseURL: URL(string: "wss://two.example")! + ) + + try await store.save([first, second]) + try await store.setActiveEnvironment(id: second.id) + let selected = try await store.activeEnvironmentID() + XCTAssertEqual(selected, second.id) + + let remaining = try await store.remove(id: second.id) + let fallback = try await store.activeEnvironmentID() + XCTAssertEqual(remaining.map(\.id), [first.id]) + XCTAssertEqual(fallback, first.id) + } +} diff --git a/apps/swift-ios/Tests/CoreTests/PairingServiceTests.swift b/apps/swift-ios/Tests/CoreTests/PairingServiceTests.swift new file mode 100644 index 0000000000..3e537e9a0d --- /dev/null +++ b/apps/swift-ios/Tests/CoreTests/PairingServiceTests.swift @@ -0,0 +1,85 @@ +import XCTest +@testable import T3Code + +@MainActor +final class PairingServiceTests: XCTestCase { + func testPairingExchangesTokenAndPersistsSecretSeparately() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("t3-swift-pairing-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + + let transport = PairingHTTPTransport() + let credentials = InMemoryCredentialStore() + let environments = EnvironmentStore( + fileURL: directory.appendingPathComponent("environments.json") + ) + let service = PairingService( + transport: transport, + environmentStore: environments, + credentialStore: credentials + ) + + let environment = try await service.pair( + url: "https://studio.example/#token=pair-once", + label: "Theo's iPhone" + ) + + XCTAssertEqual(environment.id, "environment-1") + let storedEnvironments = try await environments.load() + let activeID = try await environments.activeEnvironmentID() + let credential = await credentials.credential(for: "environment-1") + XCTAssertEqual(storedEnvironments.map(\.id), ["environment-1"]) + XCTAssertEqual(activeID, "environment-1") + XCTAssertEqual(credential?.accessToken, "access-token") + + let requests = await transport.requests + XCTAssertEqual(requests.map { $0.url?.path }, [ + "/.well-known/t3/environment", + "/oauth/token", + ]) + let form = String(data: requests[1].httpBody!, encoding: .utf8)! + XCTAssertTrue(form.contains("subject_token=pair-once")) + XCTAssertTrue(form.contains("client_device_type=mobile")) + } +} + +private actor PairingHTTPTransport: HTTPTransport { + private(set) var requests: [URLRequest] = [] + + func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) { + requests.append(request) + let body: String + switch request.url?.path { + case "/.well-known/t3/environment": + body = """ + { + "environmentId": "environment-1", + "label": "Studio", + "platform": {"os": "darwin", "arch": "arm64"}, + "serverVersion": "1.0.0", + "capabilities": {"repositoryIdentity": true} + } + """ + case "/oauth/token": + body = """ + { + "access_token": "access-token", + "issued_token_type": "urn:ietf:params:oauth:token-type:access_token", + "token_type": "Bearer", + "expires_in": 3600, + "scope": "orchestration:read orchestration:operate" + } + """ + default: + XCTFail("Unexpected request \(request.url?.absoluteString ?? "")") + body = "{}" + } + let response = HTTPURLResponse( + url: request.url!, + statusCode: 200, + httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json"] + )! + return (Data(body.utf8), response) + } +} diff --git a/apps/swift-ios/Tests/CoreTests/WorkspaceContractTests.swift b/apps/swift-ios/Tests/CoreTests/WorkspaceContractTests.swift new file mode 100644 index 0000000000..c034ba6fdc --- /dev/null +++ b/apps/swift-ios/Tests/CoreTests/WorkspaceContractTests.swift @@ -0,0 +1,135 @@ +import XCTest +@testable import T3Code + +@MainActor +final class WorkspaceContractTests: XCTestCase { + func testVCSStatusSnapshotDecodesTaggedEffectRPCShape() throws { + let data = Data( + """ + { + "_tag": "snapshot", + "local": { + "isRepo": true, + "sourceControlProvider": { + "kind": "github", + "name": "GitHub", + "baseUrl": "https://github.com" + }, + "hasPrimaryRemote": true, + "isDefaultRef": false, + "refName": "feat/swift", + "hasWorkingTreeChanges": true, + "workingTree": { + "files": [{"path":"Core/T3Client.swift","insertions":12,"deletions":2}], + "insertions": 12, + "deletions": 2 + } + }, + "remote": { + "hasUpstream": true, + "aheadCount": 1, + "behindCount": 0, + "aheadOfDefaultCount": 3, + "pr": null + } + } + """.utf8 + ) + + let event = try JSONDecoder.t3.decode(VCSStatusEvent.self, from: data) + guard case let .snapshot(local, remote) = event else { + return XCTFail("Expected snapshot") + } + XCTAssertEqual(local.refName, "feat/swift") + XCTAssertEqual(local.workingTree.files.first?.insertions, 12) + XCTAssertEqual(remote?.aheadCount, 1) + } + + func testTerminalAttachEventsDecodeSnapshotAndOutputShapes() throws { + let snapshotData = Data( + """ + { + "type": "snapshot", + "snapshot": { + "threadId": "thread-1", + "terminalId": "term-1", + "cwd": "/workspace", + "worktreePath": null, + "status": "running", + "pid": 42, + "history": "$ ", + "exitCode": null, + "exitSignal": null, + "label": "Shell", + "updatedAt": "2026-07-30T12:00:00.000Z", + "sequence": 4 + } + } + """.utf8 + ) + let outputData = Data( + """ + { + "type": "output", + "threadId": "thread-1", + "terminalId": "term-1", + "sequence": 5, + "data": "hello\\r\\n" + } + """.utf8 + ) + + let snapshot = try JSONDecoder.t3.decode(TerminalEvent.self, from: snapshotData) + let output = try JSONDecoder.t3.decode(TerminalEvent.self, from: outputData) + XCTAssertEqual(snapshot.snapshot?.pid, 42) + XCTAssertEqual(snapshot.snapshot?.sequence, 4) + XCTAssertEqual(output.data, "hello\r\n") + XCTAssertEqual(output.sequence, 5) + } + + func testReviewAndProjectFileResultsDecodeExactServerFields() throws { + let reviewData = Data( + """ + { + "cwd": "/workspace", + "generatedAt": "2026-07-30T12:00:00.000Z", + "sources": [{ + "id": "working-tree", + "kind": "working-tree", + "title": "Working tree", + "baseRef": null, + "headRef": null, + "diff": "diff --git a/file b/file", + "diffHash": "abc123", + "truncated": false + }] + } + """.utf8 + ) + let fileData = Data( + """ + { + "relativePath": "README.md", + "contents": "# T3", + "byteLength": 4, + "truncated": false + } + """.utf8 + ) + + let review = try JSONDecoder.t3.decode(ReviewDiffPreview.self, from: reviewData) + let file = try JSONDecoder.t3.decode(ProjectReadFileResult.self, from: fileData) + XCTAssertEqual(review.sources.first?.kind, "working-tree") + XCTAssertEqual(review.sources.first?.diffHash, "abc123") + XCTAssertEqual(file.relativePath, "README.md") + XCTAssertFalse(file.truncated) + } + + func testWorkspaceRPCMethodNamesMatchContractConstants() { + XCTAssertEqual(RPCMethod.projectsListEntries.rawValue, "projects.listEntries") + XCTAssertEqual(RPCMethod.vcsRefreshStatus.rawValue, "vcs.refreshStatus") + XCTAssertEqual(RPCMethod.reviewDiffPreview.rawValue, "review.getDiffPreview") + XCTAssertEqual(RPCMethod.terminalAttach.rawValue, "terminal.attach") + XCTAssertEqual(RPCMethod.subscribeTerminalEvents.rawValue, "subscribeTerminalEvents") + } +} diff --git a/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift b/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift new file mode 100644 index 0000000000..32062f6e3a --- /dev/null +++ b/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift @@ -0,0 +1,135 @@ +import Testing +@testable import T3Code + +@MainActor +@Suite("Feature root model") +struct FeatureRootModelTests { + @Test + func testPairReloadsConnectedSnapshot() async { + let client = FeatureClientStub() + client.snapshot = FeatureSnapshot(connection: .init(state: .disconnected)) + client.snapshotAfterPair = FeatureSnapshot( + connection: .init( + state: .connected, + environmentName: "Studio", + endpoint: "https://studio.example" + ) + ) + let model = FeatureRootModel(client: client) + + let result = await model.pair(endpoint: "https://studio.example", token: "pair-token") + + #expect(result) + #expect(client.pairEndpoint == "https://studio.example") + #expect(client.pairToken == "pair-token") + #expect(model.snapshot.connection.state == .connected) + } + + @Test + func testCreateThreadOptimisticallyUpsertsIt() async { + let client = FeatureClientStub() + let created = FeatureThread( + id: "thread-1", + projectID: "project-1", + title: "Build native app", + providerID: "codex", + modelID: "gpt-5" + ) + client.createdThread = created + let model = FeatureRootModel(client: client) + + let result = await model.createThread( + projectID: "project-1", + title: created.title, + selection: .init(providerID: "codex", modelID: "gpt-5") + ) + + #expect(result == created) + #expect(model.snapshot.threads == [created]) + } + + @Test + func testSendAddsQueuedMessageBeforeServerEvent() async { + let client = FeatureClientStub() + let thread = FeatureThread(id: "thread-1", projectID: "project-1", title: "Thread") + client.threadDetail = FeatureThreadDetail(thread: thread) + let model = FeatureRootModel(client: client) + _ = await model.detail(for: thread.id) + + let sent = await model.sendMessage( + threadID: thread.id, + text: " ship it ", + selection: nil + ) + + #expect(sent) + #expect(client.sentText == "ship it") + #expect(model.details[thread.id]?.messages.last?.text == "ship it") + #expect(model.details[thread.id]?.messages.last?.state == .queued) + } + + @Test + func testArchiveAndDeleteKeepLocalListsConsistent() async { + let client = FeatureClientStub() + let thread = FeatureThread(id: "thread-1", projectID: "project-1", title: "Thread") + client.createdThread = thread + let model = FeatureRootModel(client: client) + _ = await model.createThread(projectID: thread.projectID, title: nil, selection: nil) + + await model.setArchived(thread.id, archived: true) + #expect(model.snapshot.threads[0].isArchived) + + await model.deleteThread(thread.id) + #expect(model.snapshot.threads.isEmpty) + } +} + +@MainActor +private final class FeatureClientStub: FeatureClient { + var snapshot = FeatureSnapshot() + var snapshotAfterPair: FeatureSnapshot? + var createdThread = FeatureThread(id: "created", projectID: "project", title: "Created") + var threadDetail: FeatureThreadDetail? + var pairEndpoint: String? + var pairToken: String? + var sentText: String? + + func initialSnapshot() async throws -> FeatureSnapshot { + if pairEndpoint != nil, let snapshotAfterPair { + return snapshotAfterPair + } + return snapshot + } + + func pair(endpoint: String, token: String?) async throws { + pairEndpoint = endpoint + pairToken = token + } + + func createThread( + projectID: String, + title: String?, + selection: FeatureSelection? + ) async throws -> FeatureThread { + createdThread + } + + func renameThread(id: String, title: String) async throws {} + func setThreadArchived(id: String, archived: Bool) async throws {} + func deleteThread(id: String) async throws {} + + func loadThread(id: String) async throws -> FeatureThreadDetail { + if let threadDetail { + return threadDetail + } + return FeatureThreadDetail(thread: createdThread) + } + + func sendMessage(threadID: String, text: String, selection: FeatureSelection?) async throws { + sentText = text + } + + func cancelTurn(threadID: String) async throws {} + func resolveApproval(id: String, decision: FeatureApprovalDecision) async throws {} + func saveSettings(_ settings: FeatureSettings) async throws {} +} diff --git a/apps/swift-ios/Tests/FeatureTests/FeatureToolStateTests.swift b/apps/swift-ios/Tests/FeatureTests/FeatureToolStateTests.swift new file mode 100644 index 0000000000..7df5a90ae5 --- /dev/null +++ b/apps/swift-ios/Tests/FeatureTests/FeatureToolStateTests.swift @@ -0,0 +1,58 @@ +import Testing +@testable import T3Code + +@Suite("Thread tool state") +struct FeatureToolStateTests { + @Test + func fileFilteringKeepsDirectoriesFirstAndHonorsHiddenFiles() { + let entries = [ + FeatureFileEntry(path: "z.swift", name: "z.swift", kind: .file), + FeatureFileEntry(path: ".env", name: ".env", kind: .file, isHidden: true), + FeatureFileEntry(path: "Sources", name: "Sources", kind: .directory), + FeatureFileEntry(path: "a.swift", name: "a.swift", kind: .file), + ] + + #expect(entries.featureFiltered(by: "", includesHidden: false).map(\.name) == [ + "Sources", "a.swift", "z.swift", + ]) + #expect(entries.featureFiltered(by: "env", includesHidden: true).map(\.name) == [".env"]) + } + + @Test + func reviewTotalsAggregateAcrossFiles() { + let review = FeatureReview(files: [ + FeatureReviewFile(path: "a.swift", change: .modified, additions: 4, deletions: 1), + FeatureReviewFile(path: "b.swift", change: .added, additions: 8, deletions: 0), + ]) + + #expect(review.additions == 12) + #expect(review.deletions == 1) + } + + @Test + func sourceControlActionsReflectRepositoryState() { + let clean = FeatureSourceControlStatus(branch: "main") + #expect(clean.availableActions == [.createPullRequest]) + + let changed = FeatureSourceControlStatus( + branch: "feature/native", + aheadCount: 2, + behindCount: 1, + files: [.init(path: "App.swift", state: .modified, isStaged: false)] + ) + #expect(changed.availableActions.contains(.commit)) + #expect(changed.availableActions.contains(.push)) + #expect(changed.availableActions.contains(.pull)) + #expect(changed.availableActions.contains(.commitPushAndCreatePullRequest)) + + var busy = changed + busy.isBusy = true + #expect(busy.availableActions.isEmpty) + } + + @Test + func terminalPlainTextDropsControlSequences() { + let prompt = "\u{1B}]0;workspace\u{7}\u{1B}[38;5;221mx\u{8}repo\u{1B}[39m ❯ " + #expect(NativeWorkspaceMapper.terminalText(prompt) == "repo ❯ ") + } +}