diff --git a/apps/swift-ios/App/NativeFeatureClient.swift b/apps/swift-ios/App/NativeFeatureClient.swift index 2fe5d480b9..dda366492d 100644 --- a/apps/swift-ios/App/NativeFeatureClient.swift +++ b/apps/swift-ios/App/NativeFeatureClient.swift @@ -14,8 +14,14 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { private var latestServerConfig: ServerConfigSnapshot? private var archivedThreads: [FeatureThread] = [] private var latestSnapshot: FeatureSnapshot? - private var loadedThreadIDs = Set() + private var activeThreadID: String? private var latestDetails: [String: FeatureThreadDetail] = [:] + private var attachmentURLs: [AttachmentCacheKey: CachedAttachmentURL] = [:] + private var pendingBootstrapSubmission: PendingBootstrapSubmission? + private var pendingTurnSubmissions: [String: PendingTurnSubmission] = [:] + private var attachmentHydrationTasks: [ + String: (id: UUID, task: Task) + ] = [:] private var approvalThreadIDs: [String: String] = [:] private var inputThreadIDs: [String: String] = [:] private var terminalIDs: [String: String] = [:] @@ -24,7 +30,14 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { String: [UUID: AsyncStream.Continuation] ] = [:] private var pollingTask: Task? + private var fallbackPollingTask: Task? private var configurationTask: Task? + private var archivedRefreshTask: Task? + private var detailRefreshTask: Task? + private var detailRefreshPending = false + private var detailRefreshGeneration = 0 + private var environmentGeneration = 0 + private var lastShellEventAt: Date? init( runtime: EnvironmentRuntime = EnvironmentRuntime(), @@ -39,7 +52,11 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { deinit { pollingTask?.cancel() + fallbackPollingTask?.cancel() configurationTask?.cancel() + archivedRefreshTask?.cancel() + detailRefreshTask?.cancel() + attachmentHydrationTasks.values.forEach { $0.task.cancel() } continuation.finish() } @@ -47,23 +64,36 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { let environments = try await runtime.environments() guard let environment = try await runtime.activeEnvironment(), let activeClient = try await runtime.activeClient() else { + await clearActiveEnvironment() let snapshot = disconnectedSnapshot(environments: environments) latestSnapshot = snapshot return snapshot } - activeEnvironment = environment - client = activeClient - async let shellRequest = activeClient.shellSnapshot() - async let readModelRequest = activeClient.readModel() - async let serverConfigRequest: ServerConfigSnapshot? = try? activeClient.serverConfig() - let (shell, readModel) = try await (shellRequest, readModelRequest) - latestServerConfig = await serverConfigRequest + await adoptEnvironment(environment, client: activeClient) + let generation = environmentGeneration + let shell: OrchestrationShellSnapshot + do { + shell = try await activeClient.shellSnapshot() + } catch { + guard isCurrentSession(client: activeClient, generation: generation) else { + throw CancellationError() + } + await clearActiveEnvironment() + let snapshot = disconnectedSnapshot( + environments: environments, + detail: "That server is currently unreachable." + ) + latestSnapshot = snapshot + return snapshot + } + guard isCurrentSession(client: activeClient, generation: generation) else { + throw CancellationError() + } latestShell = shell - archivedThreads = readModel.threads - .filter { $0.archivedAt != nil } - .map(mapThread) + archivedThreads = [] startPolling(activeClient) + scheduleArchivedRefresh(client: activeClient) let snapshot = makeSnapshot( shell: shell, environments: environments, @@ -88,72 +118,97 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { } else { pairedClient = try await runtime.pair(url: endpoint, clientLabel: "T3 Code Swift") } - activeEnvironment = pairedClient.environment - client = pairedClient - loadedThreadIDs.removeAll() - latestDetails.removeAll() - archivedThreads.removeAll() - latestServerConfig = nil + await adoptEnvironment(pairedClient.environment, client: pairedClient) startPolling(pairedClient) } func activateEnvironment(id: String) async throws { - pollingTask?.cancel() - configurationTask?.cancel() let activated = try await runtime.activate(id: id) - activeEnvironment = activated.environment - client = activated - loadedThreadIDs.removeAll() - latestDetails.removeAll() - latestShell = nil - latestServerConfig = nil - archivedThreads.removeAll() - finishTerminalStreams() - terminalIDs.removeAll() - terminalSnapshots.removeAll() + await adoptEnvironment(activated.environment, client: activated) startPolling(activated) } func removeEnvironment(id: String) async throws { if activeEnvironment?.id == id { - pollingTask?.cancel() - configurationTask?.cancel() - pollingTask = nil - configurationTask = nil - client = nil - activeEnvironment = nil - latestShell = nil - latestServerConfig = nil - archivedThreads.removeAll() - loadedThreadIDs.removeAll() - latestDetails.removeAll() - finishTerminalStreams() - terminalIDs.removeAll() - terminalSnapshots.removeAll() + await clearActiveEnvironment(disconnectClient: false) } try await runtime.remove(id: id) } func disconnect() async { + await clearActiveEnvironment() + } + + private func adoptEnvironment( + _ environment: Environment, + client newClient: T3Client + ) async { + let previousClient = client pollingTask?.cancel() + fallbackPollingTask?.cancel() configurationTask?.cancel() + archivedRefreshTask?.cancel() pollingTask = nil + fallbackPollingTask = nil configurationTask = nil - if let client { - await client.disconnect() + archivedRefreshTask = nil + clearEnvironmentState() + activeEnvironment = environment + client = newClient + if let previousClient, previousClient !== newClient { + await previousClient.disconnect() } + } + + private func clearActiveEnvironment(disconnectClient: Bool = true) async { + let previousClient = client + pollingTask?.cancel() + fallbackPollingTask?.cancel() + configurationTask?.cancel() + archivedRefreshTask?.cancel() + pollingTask = nil + fallbackPollingTask = nil + configurationTask = nil + archivedRefreshTask = nil + clearEnvironmentState() client = nil activeEnvironment = nil + if disconnectClient, let previousClient { + await previousClient.disconnect() + } + } + + private func clearEnvironmentState() { + environmentGeneration &+= 1 + resetDetailRefresh() + attachmentHydrationTasks.values.forEach { $0.task.cancel() } + attachmentHydrationTasks.removeAll() + archivedRefreshTask?.cancel() + archivedRefreshTask = nil latestShell = nil + lastShellEventAt = nil latestServerConfig = nil archivedThreads.removeAll() - loadedThreadIDs.removeAll() + latestSnapshot = nil + activeThreadID = nil latestDetails.removeAll() + attachmentURLs.removeAll() + pendingBootstrapSubmission = nil + pendingTurnSubmissions.removeAll() + approvalThreadIDs.removeAll() + inputThreadIDs.removeAll() finishTerminalStreams() terminalIDs.removeAll() terminalSnapshots.removeAll() } + private func isCurrentSession(client: T3Client, generation: Int) -> Bool { + guard generation == environmentGeneration, let currentClient = self.client else { + return false + } + return currentClient === client + } + func addProject(path: String) async throws { let client = try requireClient() let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) @@ -175,6 +230,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { selection: FeatureSelection? ) async throws -> FeatureThread { let client = try requireClient() + let generation = environmentGeneration let threadID = UUID().uuidString let model = modelSelection(selection, projectID: projectID) let resolvedTitle = title?.trimmingCharacters(in: .whitespacesAndNewlines) @@ -187,6 +243,9 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { runtimeMode: .fullAccess ) let shell = try await client.shellSnapshot() + guard isCurrentSession(client: client, generation: generation) else { + throw CancellationError() + } latestShell = shell if let created = shell.threads.first(where: { $0.id == threadID }) { let mapped = mapThread(created) @@ -212,30 +271,86 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { attachments: [FeatureUploadAttachment] ) async throws -> FeatureThread { let client = try requireClient() - let threadID = UUID().uuidString + let generation = environmentGeneration let model = modelSelection(selection, projectID: projectID) let title = Self.title(from: prompt, hasAttachments: !attachments.isEmpty) let uploads = try makeUploadAttachments(attachments) - - _ = try await client.createThreadAndSend( - threadID: threadID, + let runtime = coreRuntimeMode(runtimeMode) + let interaction = coreInteractionMode(interactionMode) + let signature = BootstrapSubmissionSignature( projectID: projectID, - title: title, - text: prompt, + prompt: prompt, model: model, - runtimeMode: coreRuntimeMode(runtimeMode), - interactionMode: coreInteractionMode(interactionMode), - attachments: uploads + runtimeMode: runtime, + interactionMode: interaction, + attachments: attachments ) + let pending: PendingBootstrapSubmission + if let existing = pendingBootstrapSubmission, + existing.signature == signature { + pending = existing + } else { + pending = PendingBootstrapSubmission( + signature: signature, + threadID: UUID().uuidString, + identity: CommandIdentity() + ) + pendingBootstrapSubmission = pending + } - let shell = try await client.shellSnapshot() - latestShell = shell - await emitSnapshot(shell) - if let created = shell.threads.first(where: { $0.id == threadID }) { - return mapThread(created) + do { + _ = try await client.createThreadAndSend( + threadID: pending.threadID, + projectID: projectID, + title: title, + text: prompt, + model: model, + runtimeMode: runtime, + interactionMode: interaction, + attachments: uploads, + commandID: pending.identity.commandID, + messageID: pending.identity.messageID, + createdAt: pending.identity.createdAt + ) + } catch { + // A connection can disappear after the server accepted the command + // but before its reply reaches us. Bootstrap expansion creates the + // thread before dispatching the stable final turn, so recover an + // interrupted empty thread by sending only that original turn. + guard try await recoverBootstrap( + client: client, + pending: pending, + projectID: projectID, + text: prompt, + model: model, + runtimeMode: runtime, + interactionMode: interaction, + attachments: uploads + ) else { + throw error + } + } + + guard isCurrentSession(client: client, generation: generation) else { + throw CancellationError() + } + if pendingBootstrapSubmission?.identity == pending.identity { + pendingBootstrapSubmission = nil + } + // Dispatch acceptance is the commit point. A dropped refresh must not + // turn a successful first turn into a retry that creates a duplicate. + if let shell = try? await client.shellSnapshot() { + guard isCurrentSession(client: client, generation: generation) else { + throw CancellationError() + } + latestShell = shell + await emitSnapshot(shell) + if let created = shell.threads.first(where: { $0.id == pending.threadID }) { + return mapThread(created) + } } return FeatureThread( - id: threadID, + id: pending.threadID, projectID: projectID, title: title, providerID: model.instanceId, @@ -246,6 +361,54 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { ) } + private func recoverBootstrap( + client: T3Client, + pending: PendingBootstrapSubmission, + projectID: String, + text: String, + model: ModelSelection, + runtimeMode: RuntimeMode, + interactionMode: InteractionMode, + attachments: [UploadChatImageAttachment] + ) async throws -> Bool { + guard let snapshot = try? await client.threadSnapshot(id: pending.threadID) else { + return false + } + if snapshot.thread.messages.contains(where: { + $0.id == pending.identity.messageID + }) { + return true + } + guard snapshot.thread.projectId == projectID, + snapshot.thread.deletedAt == nil, + snapshot.thread.messages.isEmpty else { + return false + } + + do { + _ = try await client.sendTurn( + threadID: pending.threadID, + text: text, + runtimeMode: runtimeMode, + interactionMode: interactionMode, + model: model, + attachments: attachments, + commandID: pending.identity.commandID, + messageID: pending.identity.messageID, + createdAt: pending.identity.createdAt + ) + } catch { + guard await messageWasCommitted( + client: client, + threadID: pending.threadID, + messageID: pending.identity.messageID + ) else { + throw error + } + } + return true + } + func renameThread(id: String, title: String) async throws { let client = try requireClient() _ = try await client.rename(threadID: id, title: title) @@ -274,7 +437,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { let client = try requireClient() _ = try await client.setRuntimeMode(threadID: id, mode: coreRuntimeMode(mode)) try await refresh(client: client) - if loadedThreadIDs.contains(id) { + if activeThreadID == id { try await refreshThread(id: id, client: client) } } @@ -283,7 +446,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { let client = try requireClient() _ = try await client.setInteractionMode(threadID: id, mode: coreInteractionMode(mode)) try await refresh(client: client) - if loadedThreadIDs.contains(id) { + if activeThreadID == id { try await refreshThread(id: id, client: client) } } @@ -291,17 +454,26 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { func deleteThread(id: String) async throws { let client = try requireClient() _ = try await client.delete(threadID: id) - loadedThreadIDs.remove(id) + if activeThreadID == id { + resetDetailRefresh() + activeThreadID = nil + } 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 generation = environmentGeneration + resetDetailRefresh() + activeThreadID = id let snapshot = try await client.threadSnapshot(id: id) + guard isCurrentSession(client: client, generation: generation) else { + throw CancellationError() + } let detail = mapDetail(snapshot.thread) latestDetails[id] = detail + scheduleAttachmentHydration(in: detail, threadID: id, client: client) return detail } @@ -325,20 +497,79 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { attachments: [FeatureUploadAttachment] ) async throws { let client = try requireClient() + let generation = environmentGeneration guard let shellThread = latestShell?.threads.first(where: { $0.id == threadID }) else { throw NativeFeatureClientError.threadNotFound } - - _ = try await client.sendTurn( - threadID: threadID, + let model = selection.map(coreModelSelection) + let uploads = try makeUploadAttachments(attachments) + let signature = TurnSubmissionSignature( text: text, + model: model, runtimeMode: shellThread.runtimeMode, interactionMode: shellThread.interactionMode, - model: selection.map(coreModelSelection), - attachments: try makeUploadAttachments(attachments) + attachments: attachments ) - try await refreshThread(id: threadID, client: client) - try await refresh(client: client) + let pending: PendingTurnSubmission + if let existing = pendingTurnSubmissions[threadID], + existing.signature == signature { + pending = existing + } else { + pending = PendingTurnSubmission( + signature: signature, + identity: CommandIdentity() + ) + pendingTurnSubmissions[threadID] = pending + } + + do { + _ = try await client.sendTurn( + threadID: threadID, + text: text, + runtimeMode: shellThread.runtimeMode, + interactionMode: shellThread.interactionMode, + model: model, + attachments: uploads, + commandID: pending.identity.commandID, + messageID: pending.identity.messageID, + createdAt: pending.identity.createdAt + ) + } catch { + guard isCurrentSession(client: client, generation: generation) else { + throw CancellationError() + } + guard await messageWasCommitted( + client: client, + threadID: threadID, + messageID: pending.identity.messageID + ) else { + // Keep the stable identity. Retrying the same restored draft + // cannot enqueue a duplicate turn after an ambiguous failure. + throw error + } + } + guard isCurrentSession(client: client, generation: generation) else { + throw CancellationError() + } + if pendingTurnSubmissions[threadID]?.identity == pending.identity { + pendingTurnSubmissions[threadID] = nil + } + // Live sync reconciles these snapshots. Refreshes are opportunistic + // after the accepted command so transient reads cannot invite a + // duplicate user turn. + try? await refreshThread(id: threadID, client: client) + try? await refresh(client: client) + } + + private func messageWasCommitted( + client: T3Client, + threadID: String, + messageID: String + ) async -> Bool { + guard let snapshot = try? await client.threadSnapshot(id: threadID) else { + return false + } + return snapshot.thread.messages.contains { $0.id == messageID } } func cancelTurn(threadID: String) async throws { @@ -502,6 +733,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { guard let client else { return AsyncStream { continuation in continuation.finish() } } + let generation = environmentGeneration return AsyncStream { continuation in let subscriptionID = UUID() terminalContinuations[threadID, default: [:]][subscriptionID] = continuation @@ -513,6 +745,12 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { for try await event in await client.terminalEvents() { guard !Task.isCancelled else { break } guard let self else { break } + guard self.isCurrentSession( + client: client, + generation: generation + ) else { + break + } guard event.threadId == threadID else { continue } if let terminalID = self.terminalIDs[threadID], event.terminalId != nil, @@ -530,6 +768,13 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { continuation.finish() return } + guard self.isCurrentSession( + client: client, + generation: generation + ) else { + continuation.finish() + return + } var snapshot = self.terminalSnapshots[threadID] ?? FeatureTerminalSnapshot(threadID: threadID) snapshot.state = .failed @@ -553,6 +798,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { func openTerminal(threadID: String, columns: Int, rows: Int) async throws { let client = try requireClient() + let generation = environmentGeneration let context = try workspaceContext(threadID: threadID) let terminalID = terminalIDs[threadID] ?? UUID().uuidString terminalIDs[threadID] = terminalID @@ -564,6 +810,9 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { columns: columns, rows: rows ) + guard isCurrentSession(client: client, generation: generation) else { + throw CancellationError() + } let mapped = NativeWorkspaceMapper.terminal(snapshot) terminalSnapshots[threadID] = mapped publishTerminal(mapped, threadID: threadID) @@ -592,8 +841,12 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { func closeTerminal(threadID: String) async throws { let client = try requireClient() + let generation = environmentGeneration let terminalID = try requireTerminalID(threadID: threadID) try await client.closeTerminal(threadID: threadID, terminalID: terminalID) + guard isCurrentSession(client: client, generation: generation) else { + throw CancellationError() + } terminalIDs[threadID] = nil let snapshot = FeatureTerminalSnapshot(threadID: threadID) terminalSnapshots[threadID] = snapshot @@ -681,20 +934,36 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { private func startPolling(_ activeClient: T3Client) { pollingTask?.cancel() + fallbackPollingTask?.cancel() configurationTask?.cancel() + let generation = environmentGeneration pollingTask = Task { [weak self] in do { await activeClient.connect() - let sequence = self?.latestShell?.snapshotSequence + guard let self, + self.isCurrentSession(client: activeClient, generation: generation) else { + return + } + let sequence = self.latestShell?.snapshotSequence for try await item in await activeClient.shellEvents(after: sequence) { - guard !Task.isCancelled, let self else { break } + guard !Task.isCancelled, + self.isCurrentSession( + client: activeClient, + generation: generation + ) else { + break + } + self.lastShellEventAt = .now + self.emitConnection(.connected) switch item { case let .snapshot(shell): - await self.consume(shell: shell, client: activeClient) + await self.consume( + shell: shell, + client: activeClient, + refreshActiveThread: true + ) case .projectUpserted, .projectRemoved, .threadUpserted, .threadRemoved: - if let shell = try? await activeClient.shellSnapshot() { - await self.consume(shell: shell, client: activeClient) - } + await self.consume(delta: item, client: activeClient) case .synchronized: break } @@ -702,22 +971,69 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { } 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)) + // The independent HTTP fallback below keeps the workspace + // fresh while the socket reconnects. + } + + guard !Task.isCancelled, + let self, + self.isCurrentSession(client: activeClient, generation: generation) else { + return + } + self.emitConnection( + .reconnecting, + detail: "Live updates paused. Refreshing over HTTP." + ) + } + fallbackPollingTask = Task { [weak self] in + try? await Task.sleep(for: .seconds(3)) + while !Task.isCancelled { + guard let self, + self.isCurrentSession( + client: activeClient, + generation: generation + ) else { + return } + let socketIsSynchronized = + await activeClient.liveConnectionActive() + && self.lastShellEventAt != nil + if !socketIsSynchronized { + self.emitConnection( + .reconnecting, + detail: "Live updates reconnecting. Refreshing over HTTP." + ) + do { + let shell = try await activeClient.shellSnapshot() + guard !Task.isCancelled else { return } + await self.consume( + shell: shell, + client: activeClient, + refreshActiveThread: true + ) + } catch is CancellationError { + return + } catch { + self.emitConnection( + .reconnecting, + detail: "Server unreachable. Retrying automatically." + ) + } + } + try? await Task.sleep(for: .seconds(2)) } } configurationTask = Task { [weak self] in do { for try await event in await activeClient.serverConfigEvents() { - guard !Task.isCancelled, let self else { break } + guard !Task.isCancelled, + let self, + self.isCurrentSession( + client: activeClient, + generation: generation + ) else { + break + } switch event { case let .snapshot(config): self.latestServerConfig = config @@ -739,42 +1055,210 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { } } - private func consume(shell: OrchestrationShellSnapshot, client: T3Client) async { + private func consume( + shell: OrchestrationShellSnapshot, + client: T3Client, + refreshActiveThread: Bool + ) async { + guard let currentClient = self.client, currentClient === client else { return } 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) + if refreshActiveThread, let threadID = activeThreadID { + scheduleDetailRefresh(threadID: threadID, client: client) } } + private func consume(delta: ShellStreamItem, client: T3Client) async { + guard let currentClient = self.client, currentClient === client else { return } + guard let current = latestShell else { + if let shell = try? await client.shellSnapshot() { + await consume(shell: shell, client: client, refreshActiveThread: true) + } + return + } + + let sequence: Int + + switch delta { + case let .projectUpserted(nextSequence, _): + sequence = nextSequence + case let .projectRemoved(nextSequence, _): + sequence = nextSequence + case let .threadUpserted(nextSequence, _): + sequence = nextSequence + case let .threadRemoved(nextSequence, _): + sequence = nextSequence + case .snapshot, .synchronized: + return + } + + // Replayed deltas are expected after reconnect. They must be entirely + // side-effect free, including for cached detail and selection state. + guard sequence > current.snapshotSequence else { return } + + var projects = current.projects + var threads = current.threads + var changedThreadID: String? + var shouldRefreshArchived = false + + switch delta { + case let .projectUpserted(_, project): + if let index = projects.firstIndex(where: { $0.id == project.id }) { + projects[index] = project + } else { + projects.append(project) + } + case let .projectRemoved(_, projectID): + projects.removeAll { $0.id == projectID } + case let .threadUpserted(_, thread): + changedThreadID = thread.id + archivedThreads.removeAll { $0.id == thread.id } + if let index = threads.firstIndex(where: { $0.id == thread.id }) { + threads[index] = thread + } else { + threads.append(thread) + } + case let .threadRemoved(_, threadID): + changedThreadID = threadID + shouldRefreshArchived = true + threads.removeAll { $0.id == threadID } + latestDetails[threadID] = nil + if activeThreadID == threadID { + resetDetailRefresh() + activeThreadID = nil + } + case .snapshot, .synchronized: + return + } + + let shell = OrchestrationShellSnapshot( + snapshotSequence: sequence, + projects: projects, + threads: threads, + updatedAt: current.updatedAt + ) + latestShell = shell + await emitSnapshot(shell) + if shouldRefreshArchived { + scheduleArchivedRefresh(client: client) + } + if let changedThreadID, activeThreadID == changedThreadID { + scheduleDetailRefresh(threadID: changedThreadID, client: client) + } + } + + private func scheduleDetailRefresh(threadID: String, client: T3Client) { + guard activeThreadID == threadID else { return } + guard detailRefreshTask == nil else { + detailRefreshPending = true + return + } + detailRefreshPending = false + detailRefreshGeneration &+= 1 + let generation = detailRefreshGeneration + let sessionGeneration = environmentGeneration + detailRefreshTask = Task { [weak self] in + do { + try await Task.sleep(for: .milliseconds(160)) + } catch { + self?.finishDetailRefresh(generation: generation, client: client) + return + } + guard let self else { return } + if !Task.isCancelled, + self.activeThreadID == threadID, + self.isCurrentSession(client: client, generation: sessionGeneration) { + try? await self.refreshThread(id: threadID, client: client) + } + self.finishDetailRefresh(generation: generation, client: client) + } + } + + private func finishDetailRefresh(generation: Int, client: T3Client) { + guard detailRefreshGeneration == generation else { return } + detailRefreshTask = nil + let needsTrailingRefresh = detailRefreshPending + detailRefreshPending = false + if needsTrailingRefresh, let threadID = activeThreadID { + scheduleDetailRefresh(threadID: threadID, client: client) + } + } + + private func resetDetailRefresh() { + detailRefreshGeneration &+= 1 + detailRefreshTask?.cancel() + detailRefreshTask = nil + detailRefreshPending = false + } + private func refresh(client: T3Client, includeArchived: Bool = false) async throws { + let generation = environmentGeneration let shell = try await client.shellSnapshot() + guard isCurrentSession(client: client, generation: generation) else { + throw CancellationError() + } latestShell = shell if includeArchived { - let readModel = try await client.readModel() - archivedThreads = readModel.threads - .filter { $0.archivedAt != nil } - .map(mapThread) + scheduleArchivedRefresh(client: client) } await emitSnapshot(shell) } + private func scheduleArchivedRefresh(client: T3Client) { + archivedRefreshTask?.cancel() + let generation = environmentGeneration + archivedRefreshTask = Task { [weak self] in + guard let self, + let archivedShell = try? await client.archivedShellSnapshot(), + !Task.isCancelled, + self.isCurrentSession(client: client, generation: generation) else { + return + } + self.archivedThreads = archivedShell.threads.map(self.mapThread) + if let shell = self.latestShell { + await self.emitSnapshot(shell) + } + } + } + private func refreshThread(id: String, client: T3Client) async throws { + let generation = environmentGeneration + guard let environmentID = activeEnvironment?.id else { + throw CancellationError() + } let snapshot = try await client.threadSnapshot(id: id) + guard isCurrentSession(client: client, generation: generation) else { + throw CancellationError() + } let detail = mapDetail(snapshot.thread) - guard latestDetails[id] != detail else { return } - latestDetails[id] = detail - continuation.yield(.detail(detail)) + if latestDetails[id] != detail { + latestDetails[id] = detail + continuation.yield(.detail(detail)) + } + let hydrationBase = latestDetails[id] ?? detail + let hydrated = await hydratedAttachmentURLs( + in: hydrationBase, + client: client, + environmentID: environmentID, + generation: generation + ) + guard isCurrentSession(client: client, generation: generation), + latestDetails[id] == hydrationBase, + hydrated != hydrationBase else { + return + } + latestDetails[id] = hydrated + continuation.yield(.detail(hydrated)) } private func emitSnapshot(_ shell: OrchestrationShellSnapshot) async { guard let environment = activeEnvironment else { return } + let generation = environmentGeneration let environments = (try? await runtime.environments()) ?? [environment] + guard generation == environmentGeneration, + activeEnvironment?.id == environment.id else { + return + } let snapshot = makeSnapshot( shell: shell, environments: environments, @@ -785,20 +1269,43 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { continuation.yield(.snapshot(snapshot)) } - private func disconnectedSnapshot(environments: [Environment]) -> FeatureSnapshot { + private func disconnectedSnapshot( + environments: [Environment], + detail: String? = nil + ) -> FeatureSnapshot { FeatureSnapshot( - connection: .init(state: .disconnected), + connection: .init(state: .disconnected, detail: detail), environments: environments.map { mapEnvironment($0, activeID: nil) }, settings: loadSettings() ) } + private func emitConnection( + _ state: FeatureConnection.State, + detail: String? = nil + ) { + guard let environment = activeEnvironment else { return } + continuation.yield( + .connection( + FeatureConnection( + state: state, + environmentName: environment.label, + endpoint: environment.httpBaseURL.absoluteString, + detail: detail + ) + ) + ) + } + private func makeSnapshot( shell: OrchestrationShellSnapshot, environments: [Environment], activeEnvironment: Environment ) -> FeatureSnapshot { let threads = shell.threads.map(mapThread) + archivedThreads + let threadCountByProject = threads.reduce(into: [String: Int]()) { counts, thread in + counts[thread.projectID, default: 0] += 1 + } return FeatureSnapshot( connection: FeatureConnection( state: .connected, @@ -814,7 +1321,8 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { environmentID: activeEnvironment.id, name: project.title, path: project.workspaceRoot, - threadCount: threads.lazy.filter { $0.projectID == project.id }.count + threadCount: threadCountByProject[project.id, default: 0], + defaultSelection: project.defaultModelSelection.map(mapSelection) ) }, threads: threads, @@ -850,7 +1358,19 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { modelOptions: mapOptionSelections(thread.modelSelection.options), isArchived: thread.archivedAt != nil, isSettled: isSettled(thread.settledOverride, settledAt: thread.settledAt), + keepsActive: thread.settledOverride == "active", + settledAt: thread.settledAt.map(parseDate), + lastActivityAt: lastActivityDate( + latestUserMessageAt: thread.latestUserMessageAt, + latestTurn: thread.latestTurn + ), snoozedUntil: thread.snoozedUntil.map(parseDate), + snoozedAt: thread.snoozedAt.map(parseDate), + attentionAt: failureDate( + latestTurn: thread.latestTurn, + session: thread.session + ), + latestTurnCompletedAt: thread.latestTurn?.completedAt.map(parseDate), runtimeMode: mapRuntimeMode(thread.runtimeMode), interactionMode: mapInteractionMode(thread.interactionMode) ) @@ -861,7 +1381,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { id: thread.id, projectID: thread.projectId, title: thread.title, - preview: thread.messages.last?.text, + preview: previewText(thread.messages.last?.text), createdAt: parseDate(thread.createdAt), updatedAt: parseDate(thread.updatedAt), state: mapThreadState( @@ -875,7 +1395,19 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { modelOptions: mapOptionSelections(thread.modelSelection.options), isArchived: thread.archivedAt != nil, isSettled: isSettled(thread.settledOverride, settledAt: thread.settledAt), + keepsActive: thread.settledOverride == "active", + settledAt: thread.settledAt.map(parseDate), + lastActivityAt: lastActivityDate( + latestUserMessageAt: thread.messages.last(where: { $0.role == "user" })?.createdAt, + latestTurn: thread.latestTurn + ), snoozedUntil: thread.snoozedUntil.map(parseDate), + snoozedAt: thread.snoozedAt.map(parseDate), + attentionAt: failureDate( + latestTurn: thread.latestTurn, + session: thread.session + ), + latestTurnCompletedAt: thread.latestTurn?.completedAt.map(parseDate), runtimeMode: mapRuntimeMode(thread.runtimeMode), interactionMode: mapInteractionMode(thread.interactionMode) ) @@ -896,25 +1428,14 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { id: $0.id, name: $0.name, mimeType: $0.mimeType, - sizeBytes: $0.sizeBytes + sizeBytes: $0.sizeBytes, + url: cachedAttachmentURL(for: $0.id) ) } ) } - 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 errors = thread.activities.compactMap { activity -> FeatureMessage? in + guard activity.tone == "error" else { return nil } let detail = activity.payload["detail"]?.stringValue let text = detail.map { "\(activity.summary)\n\($0)" } ?? activity.summary return FeatureMessage( @@ -926,12 +1447,13 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { toolName: activity.kind ) } - let mergedMessages = (messages + work).sorted { $0.createdAt < $1.createdAt } + let mergedMessages = (messages + errors + collapsedWorkLogs(thread.activities)) + .sorted { $0.createdAt < $1.createdAt } let mappedThread = FeatureThread( id: thread.id, projectID: thread.projectId, title: thread.title, - preview: thread.messages.last?.text, + preview: previewText(thread.messages.last?.text), createdAt: parseDate(thread.createdAt), updatedAt: parseDate(thread.updatedAt), state: mapThreadState( @@ -945,7 +1467,19 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { modelOptions: mapOptionSelections(thread.modelSelection.options), isArchived: thread.archivedAt != nil, isSettled: isSettled(thread.settledOverride, settledAt: thread.settledAt), + keepsActive: thread.settledOverride == "active", + settledAt: thread.settledAt.map(parseDate), + lastActivityAt: lastActivityDate( + latestUserMessageAt: thread.messages.last(where: { $0.role == "user" })?.createdAt, + latestTurn: thread.latestTurn + ), snoozedUntil: thread.snoozedUntil.map(parseDate), + snoozedAt: thread.snoozedAt.map(parseDate), + attentionAt: failureDate( + latestTurn: thread.latestTurn, + session: thread.session + ), + latestTurnCompletedAt: thread.latestTurn?.completedAt.map(parseDate), runtimeMode: mapRuntimeMode(thread.runtimeMode), interactionMode: mapInteractionMode(thread.interactionMode) ) @@ -957,6 +1491,46 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { ) } + /// Lifecycle updates can number in the thousands on a long turn. Keep the + /// primary transcript message-sized while preserving a bounded, expandable + /// summary for each turn. + private func collapsedWorkLogs( + _ activities: [OrchestrationActivity] + ) -> [FeatureMessage] { + let terminalKinds = Set(["tool.completed", "task.completed", "turn.plan.updated"]) + let completed = activities.filter { + $0.tone != "error" && terminalKinds.contains($0.kind) + } + let groups = Dictionary(grouping: completed) { activity in + activity.turnId ?? "unscoped" + } + + return groups.values.compactMap { unsorted in + let group = unsorted.sorted { $0.createdAt < $1.createdAt } + guard let last = group.last else { return nil } + let visible = group.suffix(40) + var lines: [String] = [] + let hiddenCount = group.count - visible.count + if hiddenCount > 0 { + lines.append("\(hiddenCount) earlier updates hidden") + } + lines.append( + contentsOf: visible.map { activity in + let detail = previewText(activity.payload["detail"]?.stringValue) + return "• \(detail ?? activity.summary)" + } + ) + return FeatureMessage( + id: "work-log-\(last.turnId ?? last.id)", + role: .tool, + text: lines.joined(separator: "\n"), + createdAt: parseDate(last.createdAt), + state: .complete, + toolName: "Work log · \(group.count)" + ) + } + } + private func pendingApprovals(_ thread: OrchestrationThread) -> [FeatureApproval] { var open: [String: FeatureApproval] = [:] for activity in thread.activities.sorted(by: { @@ -1128,6 +1702,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { isAvailable: provider.enabled && provider.installed && provider.status != "disabled" + && provider.status != "error" && provider.auth.status != "unauthenticated" && provider.availability != "unavailable", driver: provider.driver, @@ -1210,6 +1785,14 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { ) } + private func mapSelection(_ selection: ModelSelection) -> FeatureSelection { + FeatureSelection( + providerID: selection.instanceId, + modelID: selection.model, + options: mapOptionSelections(selection.options) + ) + } + private func coreOptionValue(_ value: FeatureModelOptionValue) -> JSONValue { switch value { case let .string(rawValue): @@ -1280,6 +1863,157 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { } } + private func cachedAttachmentURL( + for id: String, + environmentID: String? = nil + ) -> URL? { + guard let environmentID = environmentID ?? activeEnvironment?.id else { + return nil + } + let key = AttachmentCacheKey(environmentID: environmentID, attachmentID: id) + guard let cached = attachmentURLs[key] else { return nil } + guard cached.expiresAt > Date().addingTimeInterval(30) else { + attachmentURLs[key] = nil + return nil + } + return cached.url + } + + private func scheduleAttachmentHydration( + in detail: FeatureThreadDetail, + threadID: String, + client: T3Client + ) { + guard let environmentID = activeEnvironment?.id else { return } + attachmentHydrationTasks[threadID]?.task.cancel() + let generation = environmentGeneration + let workID = UUID() + let task = Task { [weak self] in + guard let self else { return } + let hydrated = await self.hydratedAttachmentURLs( + in: detail, + client: client, + environmentID: environmentID, + generation: generation + ) + guard self.isCurrentSession(client: client, generation: generation), + self.latestDetails[threadID] == detail, + hydrated != detail else { + self.finishAttachmentHydration(threadID: threadID, workID: workID) + return + } + self.latestDetails[threadID] = hydrated + self.continuation.yield(.detail(hydrated)) + self.finishAttachmentHydration(threadID: threadID, workID: workID) + } + attachmentHydrationTasks[threadID] = (workID, task) + } + + private func finishAttachmentHydration(threadID: String, workID: UUID) { + guard attachmentHydrationTasks[threadID]?.id == workID else { return } + attachmentHydrationTasks[threadID] = nil + } + + private func hydratedAttachmentURLs( + in detail: FeatureThreadDetail, + client: T3Client, + environmentID: String, + generation: Int + ) async -> FeatureThreadDetail { + guard isCurrentSession(client: client, generation: generation) else { + return detail + } + let imageIDs = Set( + detail.messages.flatMap(\.attachments) + .filter { $0.mimeType.hasPrefix("image/") } + .map(\.id) + ) + let missingIDs = Array(imageIDs.filter { + cachedAttachmentURL(for: $0, environmentID: environmentID) == nil + }) + + await withTaskGroup(of: (String, ResolvedAssetURL?).self) { group in + var iterator = missingIDs.makeIterator() + for _ in 0.. Date? { + [ + latestUserMessageAt, + latestTurn?.requestedAt, + latestTurn?.startedAt, + latestTurn?.completedAt, + ] + .compactMap { $0.flatMap(parseValidDate) } + .max() + } + + private func failureDate( + latestTurn: OrchestrationLatestTurn?, + session: OrchestrationSession? + ) -> Date? { + guard session?.status == "error" || latestTurn?.state == "error" else { + return nil + } + return [ + session?.updatedAt, + latestTurn?.completedAt, + latestTurn?.startedAt, + latestTurn?.requestedAt, + ] + .compactMap { $0.flatMap(parseValidDate) } + .max() + } + private func makeUploadAttachments( _ attachments: [FeatureUploadAttachment] ) throws -> [UploadChatImageAttachment] { @@ -1313,6 +2047,13 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { return "\(compact.prefix(69).trimmingCharacters(in: .whitespacesAndNewlines))..." } + private func previewText(_ text: String?) -> String? { + guard let text else { return nil } + let compact = text.split(whereSeparator: \.isWhitespace).joined(separator: " ") + guard !compact.isEmpty else { return nil } + return compact.count > 160 ? "\(compact.prefix(157))..." : compact + } + private func loadSettings() -> FeatureSettings { guard let data = settingsStore.data(forKey: Self.settingsKey), let settings = try? JSONDecoder().decode(FeatureSettings.self, from: data) else { @@ -1322,9 +2063,12 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { } private func parseDate(_ value: String) -> Date { + parseValidDate(value) ?? .distantPast + } + + private func parseValidDate(_ value: String) -> Date? { Self.fractionalDateFormatter.date(from: value) ?? Self.dateFormatter.date(from: value) - ?? .distantPast } private static let settingsKey = "swift-ios.feature-settings.v1" @@ -1336,6 +2080,60 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { private static let dateFormatter = ISO8601DateFormatter() } +private struct AttachmentCacheKey: Hashable { + let environmentID: String + let attachmentID: String +} + +private struct CachedAttachmentURL { + let url: URL + let expiresAt: Date +} + +private struct CommandIdentity: Equatable { + let commandID: String + let messageID: String + let createdAt: String + + init( + commandID: String = UUID().uuidString, + messageID: String = UUID().uuidString, + createdAt: String = OrchestrationCommands.now() + ) { + self.commandID = commandID + self.messageID = messageID + self.createdAt = createdAt + } +} + +private struct BootstrapSubmissionSignature: Equatable { + let projectID: String + let prompt: String + let model: ModelSelection + let runtimeMode: RuntimeMode + let interactionMode: InteractionMode + let attachments: [FeatureUploadAttachment] +} + +private struct PendingBootstrapSubmission { + let signature: BootstrapSubmissionSignature + let threadID: String + let identity: CommandIdentity +} + +private struct TurnSubmissionSignature: Equatable { + let text: String + let model: ModelSelection? + let runtimeMode: RuntimeMode + let interactionMode: InteractionMode + let attachments: [FeatureUploadAttachment] +} + +private struct PendingTurnSubmission { + let signature: TurnSubmissionSignature + let identity: CommandIdentity +} + private enum NativeFeatureClientError: LocalizedError { case notConnected case threadNotFound diff --git a/apps/swift-ios/Core/Attachments.swift b/apps/swift-ios/Core/Attachments.swift index 6ca3451688..f079307284 100644 --- a/apps/swift-ios/Core/Attachments.swift +++ b/apps/swift-ios/Core/Attachments.swift @@ -100,3 +100,8 @@ public struct AssetCreateURLResult: Codable, Equatable, Sendable { /// Unix epoch milliseconds from the server contract. public let expiresAt: Double } + +public struct ResolvedAssetURL: Equatable, Sendable { + public let url: URL + public let expiresAt: Date +} diff --git a/apps/swift-ios/Core/PairingService.swift b/apps/swift-ios/Core/PairingService.swift index 906954663f..76b37b14cc 100644 --- a/apps/swift-ios/Core/PairingService.swift +++ b/apps/swift-ios/Core/PairingService.swift @@ -17,20 +17,6 @@ public struct TokenExchangeResult: Decodable, Sendable { } public actor PairingService { - public static let standardScopes = [ - "orchestration:read", - "orchestration:operate", - "terminal:operate", - "review:write", - // Startup pairing credentials carry administrative access. Requesting - // these scopes preserves that access for native multi-device - // management; ordinary pairing links remain bounded by the scopes the - // server granted them. - "access:read", - "access:write", - "relay:read", - ] - private let transport: any HTTPTransport private let environmentStore: EnvironmentStore private let credentialStore: any CredentialStore @@ -124,7 +110,6 @@ public actor PairingService { 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"), ] diff --git a/apps/swift-ios/Core/T3Client.swift b/apps/swift-ios/Core/T3Client.swift index 03dd1df7f5..ab2c77a7e5 100644 --- a/apps/swift-ios/Core/T3Client.swift +++ b/apps/swift-ios/Core/T3Client.swift @@ -9,12 +9,16 @@ public actor T3Client { environment: Environment, credentialStore: any CredentialStore, httpTransport: any HTTPTransport = URLSessionHTTPTransport(), - webSocketConnector: any WebSocketConnecting = URLSessionWebSocketConnector() + webSocketConnector: any WebSocketConnecting = URLSessionWebSocketConnector(), + rpcConnectionWaitTimeout: Duration = .seconds(4) ) { self.environment = environment let api = EnvironmentAPI(transport: httpTransport, credentials: credentialStore) self.api = api - self.rpc = WebSocketRPCClient(connector: webSocketConnector) { + self.rpc = WebSocketRPCClient( + connector: webSocketConnector, + connectionWaitTimeout: rpcConnectionWaitTimeout + ) { let ticket = try await api.webSocketTicket(for: environment) var components = URLComponents( url: environment.webSocketBaseURL, @@ -40,6 +44,10 @@ public actor T3Client { await rpc.stop() } + public func liveConnectionActive() async -> Bool { + await rpc.isConnected() + } + public func shellSnapshot() async throws -> OrchestrationShellSnapshot { try await api.shellSnapshot(for: environment) } @@ -48,6 +56,13 @@ public actor T3Client { try await api.readModel(for: environment) } + public func archivedShellSnapshot() async throws -> OrchestrationShellSnapshot { + try await rpc.request( + RPCMethod.getArchivedShellSnapshot.rawValue, + as: OrchestrationShellSnapshot.self + ) + } + public func threadSnapshot(id: String) async throws -> OrchestrationThreadDetailSnapshot { try await api.threadSnapshot(id: id, environment: environment) } @@ -145,7 +160,16 @@ public actor T3Client { @discardableResult public func dispatch(_ command: JSONValue) async throws -> DispatchResult { - try await api.dispatch(command, environment: environment) + guard await rpc.isConnected() else { + return try await api.dispatch(command, environment: environment) + } + do { + return try await dispatchOverWebSocket(command) + } catch RPCError.connectionUnavailable { + // The request provably never crossed the socket, so HTTP is a safe + // fallback without risking duplicate side effects. + return try await api.dispatch(command, environment: environment) + } } @discardableResult @@ -155,7 +179,10 @@ public actor T3Client { runtimeMode: RuntimeMode, interactionMode: InteractionMode = .default, model: ModelSelection? = nil, - attachments: [UploadChatImageAttachment] = [] + attachments: [UploadChatImageAttachment] = [], + commandID: String = UUID().uuidString, + messageID: String = UUID().uuidString, + createdAt: String = OrchestrationCommands.now() ) async throws -> DispatchResult { try await dispatch( try OrchestrationCommands.sendTurn( @@ -164,7 +191,10 @@ public actor T3Client { runtimeMode: runtimeMode, interactionMode: interactionMode, model: model, - attachments: attachments + attachments: attachments, + commandID: commandID, + messageID: messageID, + createdAt: createdAt ) ) } @@ -194,8 +224,8 @@ public actor T3Client { ) } - /// Atomically creates a thread and starts its first turn. This is the - /// server-supported path for message-first thread creation. + /// Creates a thread and starts its first turn through the server-supported + /// message-first bootstrap path. @discardableResult public func createThreadAndSend( threadID: String = UUID().uuidString, @@ -207,9 +237,12 @@ public actor T3Client { interactionMode: InteractionMode = .default, branch: String? = nil, worktreePath: String? = nil, - attachments: [UploadChatImageAttachment] = [] + attachments: [UploadChatImageAttachment] = [], + commandID: String = UUID().uuidString, + messageID: String = UUID().uuidString, + createdAt: String = OrchestrationCommands.now() ) async throws -> DispatchResult { - try await dispatch( + try await dispatchOverWebSocket( try OrchestrationCommands.createThreadAndSend( threadID: threadID, projectID: projectID, @@ -220,11 +253,22 @@ public actor T3Client { interactionMode: interactionMode, branch: branch, worktreePath: worktreePath, - attachments: attachments + attachments: attachments, + commandID: commandID, + messageID: messageID, + createdAt: createdAt ) ) } + private func dispatchOverWebSocket(_ command: JSONValue) async throws -> DispatchResult { + try await rpc.request( + RPCMethod.dispatchCommand.rawValue, + payload: command, + as: DispatchResult.self + ) + } + @discardableResult public func createProject( projectID: String = UUID().uuidString, @@ -408,6 +452,10 @@ public actor T3Client { } public func resolvedAssetURL(resource: AssetResource) async throws -> URL { + try await resolvedAsset(resource: resource).url + } + + public func resolvedAsset(resource: AssetResource) async throws -> ResolvedAssetURL { let result = try await createAssetURL(resource: resource) guard let url = URL( string: result.relativeUrl, @@ -415,7 +463,10 @@ public actor T3Client { )?.absoluteURL else { throw RPCError.protocolViolation("The server returned an invalid asset URL.") } - return url + return ResolvedAssetURL( + url: url, + expiresAt: Date(timeIntervalSince1970: result.expiresAt / 1_000) + ) } // MARK: VCS and source control @@ -881,12 +932,12 @@ public actor EnvironmentRuntime { throw RPCError.remote("Environment \(id) is not saved.") } try await environmentStore.setActiveEnvironment(id: id) - return client(for: environment) + return await client(for: environment) } public func activeClient() async throws -> T3Client? { guard let environment = try await activeEnvironment() else { return nil } - return client(for: environment) + return await client(for: environment) } @discardableResult @@ -898,7 +949,7 @@ public actor EnvironmentRuntime { ) let environment = try await service.pair(url: url, label: clientLabel) try await environmentStore.setActiveEnvironment(id: environment.id) - return client(for: environment) + return await client(for: environment) } @discardableResult @@ -914,7 +965,7 @@ public actor EnvironmentRuntime { ) let environment = try await service.pair(host: host, code: code, label: clientLabel) try await environmentStore.setActiveEnvironment(id: environment.id) - return client(for: environment) + return await client(for: environment) } public func remove(id: String) async throws { @@ -925,8 +976,14 @@ public actor EnvironmentRuntime { try await environmentStore.remove(id: id) } - private func client(for environment: Environment) -> T3Client { - if let existing = clients[environment.id] { return existing } + private func client(for environment: Environment) async -> T3Client { + if let existing = clients[environment.id] { + if existing.environment == environment { + return existing + } + clients.removeValue(forKey: environment.id) + await existing.disconnect() + } let client = T3Client( environment: environment, credentialStore: credentialStore, @@ -942,6 +999,7 @@ public enum RPCMethod: String, Sendable { case serverProbe = "server.probe" case serverGetConfig = "server.getConfig" case dispatchCommand = "orchestration.dispatchCommand" + case getArchivedShellSnapshot = "orchestration.getArchivedShellSnapshot" case subscribeShell = "orchestration.subscribeShell" case subscribeThread = "orchestration.subscribeThread" case projectsListEntries = "projects.listEntries" @@ -1097,6 +1155,8 @@ public enum OrchestrationCommands { "text": .string(text), "attachments": .array(attachments.map(\.jsonValue)), ]), + "modelSelection": try .encode(model), + "titleSeed": .string(title), "runtimeMode": .string(runtimeMode.rawValue), "interactionMode": .string(interactionMode.rawValue), "bootstrap": .object(["createThread": .object(create)]), diff --git a/apps/swift-ios/Core/WebSocketRPC.swift b/apps/swift-ios/Core/WebSocketRPC.swift index 075223471e..99f9e5a772 100644 --- a/apps/swift-ios/Core/WebSocketRPC.swift +++ b/apps/swift-ios/Core/WebSocketRPC.swift @@ -90,12 +90,15 @@ private actor URLSessionWebSocketConnection: WebSocketConnection { } public enum RPCError: LocalizedError, Sendable { + case connectionUnavailable case disconnected case remote(String) case protocolViolation(String) public var errorDescription: String? { switch self { + case .connectionUnavailable: + "The live command connection is unavailable." case .disconnected: "The environment disconnected." case let .remote(message): message case let .protocolViolation(message): message @@ -164,6 +167,7 @@ public actor WebSocketRPCClient { private let connector: any WebSocketConnecting private let endpointProvider: EndpointProvider + private let connectionWaitTimeout: Duration private var connection: (any WebSocketConnection)? private var loopTask: Task? private var keepaliveTask: Task? @@ -175,9 +179,11 @@ public actor WebSocketRPCClient { public init( connector: any WebSocketConnecting = URLSessionWebSocketConnector(), + connectionWaitTimeout: Duration = .seconds(4), endpointProvider: @escaping EndpointProvider ) { self.connector = connector + self.connectionWaitTimeout = connectionWaitTimeout self.endpointProvider = endpointProvider } @@ -192,6 +198,10 @@ public actor WebSocketRPCClient { loopTask = Task { await self.connectionLoop() } } + public func isConnected() -> Bool { + connection != nil + } + public func stop() async { desired = false loopTask?.cancel() @@ -281,6 +291,15 @@ public actor WebSocketRPCClient { if connection != nil { Task { await self.sendUnary(id) } } + let timeout = connectionWaitTimeout + Task { [weak self] in + do { + try await Task.sleep(for: timeout) + } catch { + return + } + await self?.failUnaryIfUnsent(id) + } } } @@ -356,8 +375,7 @@ public actor WebSocketRPCClient { 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 let request = unary.removeValue(forKey: requestID) { if exit._tag == "Success" { request.resume(.success(exit.value ?? .null)) } else { @@ -380,13 +398,18 @@ public actor WebSocketRPCClient { private func sendUnary(_ id: Int) async { guard let connection, var request = unary[id], !request.sent else { return } + // Actor methods are reentrant at the send below. Record that this + // command crossed the socket boundary first so a concurrent + // disconnect fails it instead of replaying an ambiguous mutation. + request.sent = true + unary[id] = request 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) + // A response, disconnect, or stop may have completed the request + // while send was suspended. Only its current owner may resume it. + guard let failed = unary.removeValue(forKey: id) else { return } + failed.resume(.failure(error)) } } @@ -441,6 +464,12 @@ public actor WebSocketRPCClient { } } + private func failUnaryIfUnsent(_ id: Int) { + guard let request = unary[id], !request.sent else { return } + unary.removeValue(forKey: id) + request.resume(.failure(RPCError.connectionUnavailable)) + } + private func remoteError(_ exit: RPCResponseEnvelope.Exit) -> RPCError { let value = exit.cause?.first?.error let message = value?["message"]?.stringValue diff --git a/apps/swift-ios/Features/Chat/FeatureComposerView.swift b/apps/swift-ios/Features/Chat/FeatureComposerView.swift index 6cac31d62a..1cecec6283 100644 --- a/apps/swift-ios/Features/Chat/FeatureComposerView.swift +++ b/apps/swift-ios/Features/Chat/FeatureComposerView.swift @@ -47,6 +47,9 @@ struct FeatureComposerView: View { .padding(.trailing, 7) .padding(.bottom, 7) .accessibilityLabel(isWorking && textIsEmpty ? "Stop agent" : "Send") + .accessibilityIdentifier( + isWorking && textIsEmpty ? "thread-stop" : "message-send" + ) } .background(T3Colors.input, in: RoundedRectangle(cornerRadius: 18)) .overlay { diff --git a/apps/swift-ios/Features/Chat/ImageAttachmentViews.swift b/apps/swift-ios/Features/Chat/ImageAttachmentViews.swift index f60ab53c87..9f66498879 100644 --- a/apps/swift-ios/Features/Chat/ImageAttachmentViews.swift +++ b/apps/swift-ios/Features/Chat/ImageAttachmentViews.swift @@ -1,3 +1,4 @@ +import ImageIO import PhotosUI import SwiftUI import UniformTypeIdentifiers @@ -37,6 +38,7 @@ struct FeatureImageAttachmentPicker: View { .disabled(!isEnabled || isLoading || attachments.count >= maximumCount) .opacity(isEnabled ? 1 : 0.3) .accessibilityLabel(isLoading ? "Adding images" : "Add images") + .accessibilityIdentifier("image-attachment-picker") .accessibilityHint(isEnabled ? "" : "The selected model does not accept images") .onChange(of: selection) { loadSelection() @@ -67,12 +69,13 @@ struct FeatureImageAttachmentPicker: View { guard let data = try await item.loadTransferable(type: Data.self) else { continue } - let type = item.supportedContentTypes.first ?? .jpeg - let attachment = try FeatureImageProcessor.attachment( - from: data, - sourceType: type, - ordinal: attachments.count + 1 - ) + let ordinal = attachments.count + 1 + let attachment = try await Task.detached(priority: .userInitiated) { + try FeatureImageProcessor.attachment( + from: data, + ordinal: ordinal + ) + }.value attachments.append(attachment) } catch { errorMessage = error.localizedDescription @@ -107,11 +110,12 @@ struct FeatureAttachmentStrip: View { private struct FeatureAttachmentThumbnail: View { let attachment: FeatureDraftAttachment let onRemove: () -> Void + @State private var image: UIImage? var body: some View { ZStack(alignment: .topTrailing) { Group { - if let image = UIImage(data: attachment.data) { + if let image { Image(uiImage: image) .resizable() .scaledToFill() @@ -130,12 +134,23 @@ private struct FeatureAttachmentThumbnail: View { .foregroundStyle(.white) .frame(width: 22, height: 22) .background(.black.opacity(0.78), in: Circle()) + .frame( + width: T3Metrics.minimumTapTarget, + height: T3Metrics.minimumTapTarget + ) + .contentShape(Rectangle()) } - .offset(x: 5, y: -5) + .offset(x: 11, y: -11) .accessibilityLabel("Remove \(attachment.filename)") } - .padding(.top, 5) - .padding(.trailing, 5) + .padding(.top, 11) + .padding(.trailing, 11) + .task(id: attachment.id) { + let data = attachment.thumbnailData ?? attachment.data + image = await Task.detached(priority: .utility) { + UIImage(data: data) + }.value + } } } @@ -145,15 +160,25 @@ enum FeatureImageProcessor { static func attachment( from sourceData: Data, - sourceType _: UTType, ordinal: Int ) throws -> FeatureDraftAttachment { - guard let sourceImage = UIImage(data: sourceData) else { + guard let source = CGImageSourceCreateWithData(sourceData as CFData, nil), + let image = CGImageSourceCreateThumbnailAtIndex( + source, + 0, + [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: maximumDimension, + kCGImageSourceShouldCacheImmediately: true, + ] as CFDictionary + ) else { throw FeatureImageAttachmentError.invalidImage } - let image = resized(sourceImage) - guard let data = image.jpegData(compressionQuality: 0.82) else { + let preparedImage = UIImage(cgImage: image) + guard let data = preparedImage.jpegData(compressionQuality: 0.82), + let thumbnailData = thumbnail(from: preparedImage) else { throw FeatureImageAttachmentError.encodingFailed } guard data.count <= maximumEncodedBytes else { @@ -162,20 +187,25 @@ enum FeatureImageProcessor { return FeatureDraftAttachment( data: data, + thumbnailData: thumbnailData, filename: "Image \(ordinal).jpg", mimeType: "image/jpeg" ) } - private static func resized(_ image: UIImage) -> UIImage { + private static func thumbnail(from image: UIImage) -> Data? { let longestSide = max(image.size.width, image.size.height) - guard longestSide > maximumDimension else { return image } - let scale = maximumDimension / longestSide - let size = CGSize(width: image.size.width * scale, height: image.size.height * scale) - let renderer = UIGraphicsImageRenderer(size: size) + let scale = min(1, 160 / longestSide) + let size = CGSize( + width: max(1, image.size.width * scale), + height: max(1, image.size.height * scale) + ) + let format = UIGraphicsImageRendererFormat() + format.scale = 1 + let renderer = UIGraphicsImageRenderer(size: size, format: format) return renderer.image { _ in image.draw(in: CGRect(origin: .zero, size: size)) - } + }.jpegData(compressionQuality: 0.72) } } diff --git a/apps/swift-ios/Features/Chat/ThreadDetailView.swift b/apps/swift-ios/Features/Chat/ThreadDetailView.swift index 3026ba373d..b0f0ced751 100644 --- a/apps/swift-ios/Features/Chat/ThreadDetailView.swift +++ b/apps/swift-ios/Features/Chat/ThreadDetailView.swift @@ -124,7 +124,7 @@ public struct ThreadDetailView: View { } .task(id: thread.id) { isLoading = true - _ = await model.detail(for: thread.id) + _ = await model.detail(for: thread.id, force: true) selection = currentSelection isLoading = false } @@ -233,9 +233,12 @@ public struct ThreadDetailView: View { .padding(.top, 14) .padding(.bottom, 10) } - .defaultScrollAnchor(.bottom) .scrollDismissesKeyboard(.interactively) - .onChange(of: detail.messages.count) { + .task(id: thread.id) { + await Task.yield() + proxy.scrollTo("timeline-bottom", anchor: .bottom) + } + .onChange(of: detail.messages.last?.id) { withAnimation(.easeOut(duration: 0.18)) { proxy.scrollTo("timeline-bottom", anchor: .bottom) } @@ -279,8 +282,17 @@ public struct ThreadDetailView: View { ) ) if !sent { - draft = message - attachments = pendingAttachments + let currentDraft = draft + let restoredMessage = message.trimmingCharacters(in: .whitespacesAndNewlines) + if currentDraft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + draft = message + } else if !restoredMessage.isEmpty { + draft = "\(message)\n\(currentDraft)" + } + let pendingIDs = Set(pendingAttachments.map(\.id)) + attachments = pendingAttachments + attachments.filter { + !pendingIDs.contains($0.id) + } sendFailed = true } isSending = false @@ -414,7 +426,8 @@ struct FeatureMessageView: View { .background(Color.white.opacity(0.11), in: RoundedRectangle(cornerRadius: 15)) } .accessibilityLabel("You") - .accessibilityValue(message.text) + .accessibilityValue(accessibilityValue) + .accessibilityIdentifier("message-\(message.id)") case .assistant: VStack(alignment: .leading, spacing: 7) { HStack(spacing: 6) { @@ -431,6 +444,7 @@ struct FeatureMessageView: View { } } .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityIdentifier("message-\(message.id)") case .tool: DisclosureGroup { Text(message.text) @@ -444,17 +458,30 @@ struct FeatureMessageView: View { } .padding(11) .background(Color.white.opacity(0.055), in: RoundedRectangle(cornerRadius: 10)) + .accessibilityIdentifier("message-\(message.id)") case .system: Text(message.text) .font(.footnote) .foregroundStyle(.secondary) .frame(maxWidth: .infinity, alignment: .center) + .accessibilityIdentifier("message-\(message.id)") } } + + private var accessibilityValue: String { + let attachmentSummary = message.attachments.isEmpty + ? "" + : "\(message.attachments.count) image attachment" + + (message.attachments.count == 1 ? "" : "s") + return [message.text, attachmentSummary] + .filter { !$0.isEmpty } + .joined(separator: ", ") + } } private struct FeatureMessageAttachmentsView: View { let attachments: [FeatureMessageAttachment] + @State private var previewedAttachment: FeatureMessageAttachment? var body: some View { if !attachments.isEmpty { @@ -466,19 +493,62 @@ private struct FeatureMessageAttachmentsView: View { spacing: 7 ) { ForEach(attachments) { attachment in - HStack(spacing: 9) { - Image(systemName: attachment.mimeType.hasPrefix("image/") ? "photo" : "doc") + VStack(alignment: .leading, spacing: 6) { + if attachment.mimeType.hasPrefix("image/") { + Group { + if let url = attachment.url { + AsyncImage(url: url) { phase in + switch phase { + case let .success(image): + image + .resizable() + .scaledToFit() + case .failure: + attachmentPlaceholder( + systemImage: "exclamationmark.triangle" + ) + case .empty: + attachmentPlaceholder(systemImage: "photo") + @unknown default: + attachmentPlaceholder(systemImage: "photo") + } + } + } else { + attachmentPlaceholder(systemImage: "photo") + } + } + .frame(height: 160) + .frame(maxWidth: .infinity) + .background(T3Colors.surfaceRaised) + .clipShape(RoundedRectangle(cornerRadius: 8)) + } + + HStack(spacing: 9) { + Image( + systemName: attachment.mimeType.hasPrefix("image/") + ? "photo" + : "doc" + ) .font(.system(size: 16, weight: .medium)) .foregroundStyle(T3Colors.textSecondary) .frame(width: 30, height: 30) - .background(T3Colors.surfaceRaised, in: RoundedRectangle(cornerRadius: 6)) - VStack(alignment: .leading, spacing: 1) { - Text(attachment.name) - .font(.caption.weight(.medium)) - .lineLimit(1) - Text(ByteCountFormatter.string(fromByteCount: Int64(attachment.sizeBytes), countStyle: .file)) + .background( + T3Colors.surfaceRaised, + in: RoundedRectangle(cornerRadius: 6) + ) + VStack(alignment: .leading, spacing: 1) { + Text(attachment.name) + .font(.caption.weight(.medium)) + .lineLimit(1) + Text( + ByteCountFormatter.string( + fromByteCount: Int64(attachment.sizeBytes), + countStyle: .file + ) + ) .font(.caption2.monospacedDigit()) .foregroundStyle(T3Colors.textSecondary) + } } } .frame(maxWidth: .infinity, alignment: .leading) @@ -488,10 +558,100 @@ private struct FeatureMessageAttachmentsView: View { .stroke(T3Colors.border, lineWidth: 1) } .accessibilityElement(children: .combine) + .accessibilityLabel( + attachment.mimeType.hasPrefix("image/") + ? "Image attachment" + : "File attachment" + ) + .accessibilityValue(attachmentAccessibilityValue(attachment)) + .accessibilityIdentifier("attachment-\(attachment.id)") + .accessibilityAddTraits( + attachment.mimeType.hasPrefix("image/") && attachment.url != nil + ? .isButton + : [] + ) + .accessibilityHint( + attachment.mimeType.hasPrefix("image/") && attachment.url != nil + ? "Opens full-screen preview" + : "" + ) + .accessibilityAction { + if attachment.mimeType.hasPrefix("image/"), attachment.url != nil { + previewedAttachment = attachment + } + } + .contentShape(Rectangle()) + .onTapGesture { + if attachment.mimeType.hasPrefix("image/"), attachment.url != nil { + previewedAttachment = attachment + } + } } } + .fullScreenCover(item: $previewedAttachment) { attachment in + FeatureAttachmentPreview(attachment: attachment) + } } } + + private func attachmentPlaceholder(systemImage: String) -> some View { + Image(systemName: systemImage) + .font(.system(size: 22, weight: .medium)) + .foregroundStyle(T3Colors.textSecondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + private func attachmentAccessibilityValue( + _ attachment: FeatureMessageAttachment + ) -> String { + let size = ByteCountFormatter.string( + fromByteCount: Int64(attachment.sizeBytes), + countStyle: .file + ) + return "\(attachment.name), \(size)" + } +} + +private struct FeatureAttachmentPreview: View { + @SwiftUI.Environment(\.dismiss) private var dismiss + let attachment: FeatureMessageAttachment + + var body: some View { + NavigationStack { + ZStack { + Color.black.ignoresSafeArea() + if let url = attachment.url { + AsyncImage(url: url) { phase in + switch phase { + case let .success(image): + image + .resizable() + .scaledToFit() + case .failure: + ContentUnavailableView( + "Image unavailable", + systemImage: "exclamationmark.triangle" + ) + case .empty: + ProgressView() + @unknown default: + ProgressView() + } + } + .padding(12) + } + } + .navigationTitle(attachment.name) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { dismiss() } + } + } + .t3NavigationChrome() + } + .preferredColorScheme(.dark) + } } struct StreamingStatusView: View { @@ -510,7 +670,7 @@ struct StreamingStatusView: View { .font(.footnote.weight(.semibold)) } .padding(.vertical, 6) - .accessibilityElement(children: .combine) + .accessibilityElement(children: .contain) } } diff --git a/apps/swift-ios/Features/Connection/ConnectionOnboardingView.swift b/apps/swift-ios/Features/Connection/ConnectionOnboardingView.swift index 20780e3fa3..315802383e 100644 --- a/apps/swift-ios/Features/Connection/ConnectionOnboardingView.swift +++ b/apps/swift-ios/Features/Connection/ConnectionOnboardingView.swift @@ -16,6 +16,8 @@ public struct ConnectionOnboardingView: View { @State private var showsPermissionAction = false @State private var showingScanner = false @State private var entryHeading = "Connect manually" + @State private var connectionTask: Task? + @State private var connectionAttemptID: UUID? @FocusState private var focusedField: ConnectionField? public init( @@ -65,6 +67,16 @@ public struct ConnectionOnboardingView: View { ToolbarItem(placement: .cancellationAction) { Button("Close", action: onCancel) } + } else if stage == .checking { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { + connectionTask?.cancel() + connectionTask = nil + connectionAttemptID = nil + model.errorMessage = nil + stage = .details + } + } } } .fullScreenCover(isPresented: $showingScanner) { @@ -95,6 +107,12 @@ public struct ConnectionOnboardingView: View { errorMessage = nil } } + .interactiveDismissDisabled(stage == .connecting) + .onDisappear { + connectionTask?.cancel() + connectionTask = nil + connectionAttemptID = nil + } } private var welcomeView: some View { @@ -509,13 +527,17 @@ public struct ConnectionOnboardingView: View { @MainActor private func connect(_ action: ConnectionAction) { + connectionTask?.cancel() + let attemptID = UUID() + connectionAttemptID = attemptID endpoint = action.endpoint errorMessage = nil showsPermissionAction = false stage = .checking - Task { + connectionTask = Task { let readiness = await readinessChecker.check(endpoint: action.endpoint) + guard !Task.isCancelled, connectionAttemptID == attemptID else { return } switch readiness { case .ready: stage = .connecting @@ -539,14 +561,19 @@ public struct ConnectionOnboardingView: View { await model.activateEnvironment(id) didConnect = model.snapshot.connection.state == .connected } + guard !Task.isCancelled, connectionAttemptID == attemptID else { return } if didConnect { + connectionAttemptID = nil + connectionTask = nil stage = .success onConnected() } else { let rawError = model.errorMessage model.errorMessage = nil errorMessage = ConnectionErrorCopy.message(for: rawError) + connectionAttemptID = nil + connectionTask = nil stage = .details } } diff --git a/apps/swift-ios/Features/Devices/DevicesView.swift b/apps/swift-ios/Features/Devices/DevicesView.swift index 9439296b23..350be5797a 100644 --- a/apps/swift-ios/Features/Devices/DevicesView.swift +++ b/apps/swift-ios/Features/Devices/DevicesView.swift @@ -23,6 +23,17 @@ public struct DevicesView: View { .font(.footnote) .foregroundStyle(.secondary) } + } else if let errorMessage, sessions.isEmpty { + ContentUnavailableView { + Label("Couldn’t load devices", systemImage: "exclamationmark.circle") + } description: { + Text(errorMessage) + } actions: { + Button("Try again") { + Task { await reload() } + } + .buttonStyle(.borderedProminent) + } } else if sessions.isEmpty { ContentUnavailableView { Label("No devices found", systemImage: "laptopcomputer.and.iphone") diff --git a/apps/swift-ios/Features/Root/FeatureRootModel.swift b/apps/swift-ios/Features/Root/FeatureRootModel.swift index a474240ad9..5754a85375 100644 --- a/apps/swift-ios/Features/Root/FeatureRootModel.swift +++ b/apps/swift-ios/Features/Root/FeatureRootModel.swift @@ -20,7 +20,9 @@ public final class FeatureRootModel { do { snapshot = try await client.initialSnapshot() } catch { - errorMessage = error.localizedDescription + if !Self.isBenignCancellation(error) { + errorMessage = error.localizedDescription + } } isLoading = false @@ -33,13 +35,16 @@ public final class FeatureRootModel { do { snapshot = try await client.initialSnapshot() } catch { - errorMessage = error.localizedDescription + if !Self.isBenignCancellation(error) { + errorMessage = error.localizedDescription + } } } public func pair(endpoint: String, token: String?) async -> Bool { await perform { try await client.pair(endpoint: endpoint, token: token) + details.removeAll() snapshot = try await client.initialSnapshot() } } @@ -78,6 +83,7 @@ public final class FeatureRootModel { title: String?, selection: FeatureSelection? ) async -> FeatureThread? { + let environment = currentEnvironmentIdentity var created: FeatureThread? let succeeded = await perform { let thread = try await client.createThread( @@ -85,6 +91,9 @@ public final class FeatureRootModel { title: title, selection: selection ) + guard currentEnvironmentIdentity == environment else { + throw CancellationError() + } upsert(thread) created = thread } @@ -95,8 +104,9 @@ public final class FeatureRootModel { let prompt = request.trimmedPrompt guard !prompt.isEmpty || !request.attachments.isEmpty else { return nil } + let environment = currentEnvironmentIdentity var created: FeatureThread? - let succeeded = await perform { + let succeeded = await perform(reportError: false) { let thread = try await client.createThreadAndSend( projectID: request.projectID, prompt: prompt, @@ -105,6 +115,9 @@ public final class FeatureRootModel { interactionMode: request.interactionMode, attachments: request.attachments.map(\.upload) ) + guard currentEnvironmentIdentity == environment else { + throw CancellationError() + } upsert(thread) created = thread } @@ -112,8 +125,10 @@ public final class FeatureRootModel { } public func renameThread(_ id: String, title: String) async { + let environment = currentEnvironmentIdentity await perform { try await client.renameThread(id: id, title: title) + guard currentEnvironmentIdentity == environment else { return } guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return } snapshot.threads[index].title = title details[id]?.thread.title = title @@ -121,8 +136,10 @@ public final class FeatureRootModel { } public func setArchived(_ id: String, archived: Bool) async { + let environment = currentEnvironmentIdentity await perform { try await client.setThreadArchived(id: id, archived: archived) + guard currentEnvironmentIdentity == environment else { return } guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return } snapshot.threads[index].isArchived = archived details[id]?.thread.isArchived = archived @@ -130,26 +147,39 @@ public final class FeatureRootModel { } public func setSettled(_ id: String, settled: Bool) async { + let environment = currentEnvironmentIdentity await perform { try await client.setThreadSettled(id: id, settled: settled) + guard currentEnvironmentIdentity == environment else { return } guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return } snapshot.threads[index].isSettled = settled + snapshot.threads[index].keepsActive = !settled + snapshot.threads[index].settledAt = settled ? .now : nil details[id]?.thread.isSettled = settled + details[id]?.thread.keepsActive = !settled + details[id]?.thread.settledAt = settled ? .now : nil } } public func setSnoozed(_ id: String, until: Date?) async { + let environment = currentEnvironmentIdentity await perform { try await client.setThreadSnoozed(id: id, until: until) + guard currentEnvironmentIdentity == environment else { return } guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return } + let snoozedAt = until.map { _ in Date.now } snapshot.threads[index].snoozedUntil = until + snapshot.threads[index].snoozedAt = snoozedAt details[id]?.thread.snoozedUntil = until + details[id]?.thread.snoozedAt = snoozedAt } } public func setRuntimeMode(_ id: String, mode: FeatureRuntimeMode) async { + let environment = currentEnvironmentIdentity await perform { try await client.setRuntimeMode(id: id, mode: mode) + guard currentEnvironmentIdentity == environment else { return } guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return } snapshot.threads[index].runtimeMode = mode details[id]?.thread.runtimeMode = mode @@ -157,8 +187,10 @@ public final class FeatureRootModel { } public func setInteractionMode(_ id: String, mode: FeatureInteractionMode) async { + let environment = currentEnvironmentIdentity await perform { try await client.setInteractionMode(id: id, mode: mode) + guard currentEnvironmentIdentity == environment else { return } guard let index = snapshot.threads.firstIndex(where: { $0.id == id }) else { return } snapshot.threads[index].interactionMode = mode details[id]?.thread.interactionMode = mode @@ -166,8 +198,10 @@ public final class FeatureRootModel { } public func deleteThread(_ id: String) async { + let environment = currentEnvironmentIdentity await perform { try await client.deleteThread(id: id) + guard currentEnvironmentIdentity == environment else { return } snapshot.threads.removeAll { $0.id == id } details[id] = nil } @@ -177,14 +211,20 @@ public final class FeatureRootModel { if !force, let cached = details[id] { return cached } + let environment = currentEnvironmentIdentity do { let detail = try await client.loadThread(id: id) + guard currentEnvironmentIdentity == environment else { + return details[id] + } details[id] = detail upsert(detail.thread) return detail } catch { - errorMessage = error.localizedDescription - return nil + if !Self.isBenignCancellation(error) { + errorMessage = error.localizedDescription + } + return details[id] } } @@ -202,6 +242,7 @@ public final class FeatureRootModel { let trimmed = submission.text.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty || !submission.attachments.isEmpty else { return false } + let environment = currentEnvironmentIdentity let optimisticID = "local-\(UUID().uuidString)" let optimistic = FeatureMessage( id: optimisticID, @@ -219,7 +260,7 @@ public final class FeatureRootModel { ) details[submission.threadID]?.messages.append(optimistic) - let sent = await perform { + let sent = await perform(reportError: false) { try await client.sendMessage( threadID: submission.threadID, text: trimmed, @@ -228,6 +269,7 @@ public final class FeatureRootModel { ) } if !sent { + guard currentEnvironmentIdentity == environment else { return false } details[submission.threadID]?.messages.removeAll { $0.id == optimisticID } } return sent @@ -240,8 +282,10 @@ public final class FeatureRootModel { } public func resolveApproval(_ id: String, decision: FeatureApprovalDecision) async { + let environment = currentEnvironmentIdentity await perform { try await client.resolveApproval(id: id, decision: decision) + guard currentEnvironmentIdentity == environment else { return } for key in details.keys { details[key]?.approvals.removeAll { $0.id == id } } @@ -249,8 +293,10 @@ public final class FeatureRootModel { } public func resolveUserInput(_ id: String, answers: [String: String]) async { + let environment = currentEnvironmentIdentity await perform { try await client.resolveUserInput(id: id, answers: answers) + guard currentEnvironmentIdentity == environment else { return } for key in details.keys { details[key]?.userInputs.removeAll { $0.id == id } } @@ -265,14 +311,17 @@ public final class FeatureRootModel { } @discardableResult - private func perform(_ operation: () async throws -> Void) async -> Bool { + private func perform( + reportError: Bool = true, + _ operation: () async throws -> Void + ) async -> Bool { isPerformingAction = true defer { isPerformingAction = false } do { try await operation() return true } catch { - if !Self.isBenignCancellation(error) { + if reportError, !Self.isBenignCancellation(error) { errorMessage = error.localizedDescription } return false @@ -287,6 +336,17 @@ public final class FeatureRootModel { return message == "cancelled" || message == "canceled" } + private var currentEnvironmentIdentity: String { + let active = snapshot.environments.first(where: \.isActive) + return [ + active?.id, + active?.endpoint, + snapshot.connection.endpoint, + ] + .compactMap { $0 } + .joined(separator: "|") + } + private func apply(_ event: FeatureEvent) { switch event { case let .snapshot(value): diff --git a/apps/swift-ios/Features/Root/FeatureRootView.swift b/apps/swift-ios/Features/Root/FeatureRootView.swift index 48adc2bbfe..70896804c3 100644 --- a/apps/swift-ios/Features/Root/FeatureRootView.swift +++ b/apps/swift-ios/Features/Root/FeatureRootView.swift @@ -11,7 +11,7 @@ public struct FeatureRootView: View { Group { if model.isLoading { FeatureLoadingView() - } else if model.snapshot.connection.state == .connected { + } else if model.snapshot.connection.state != .disconnected { WorkspaceView( model: model, submitNewTask: { request in diff --git a/apps/swift-ios/Features/Shared/FeatureModels.swift b/apps/swift-ios/Features/Shared/FeatureModels.swift index 8c5db5c2cc..1a800d92fa 100644 --- a/apps/swift-ios/Features/Shared/FeatureModels.swift +++ b/apps/swift-ios/Features/Shared/FeatureModels.swift @@ -46,13 +46,22 @@ public struct FeatureProject: Identifiable, Sendable, Equatable, Hashable, Codab public var name: String public var path: String public var threadCount: Int + public var defaultSelection: FeatureSelection? - public init(id: String, environmentID: String, name: String, path: String, threadCount: Int = 0) { + public init( + id: String, + environmentID: String, + name: String, + path: String, + threadCount: Int = 0, + defaultSelection: FeatureSelection? = nil + ) { self.id = id self.environmentID = environmentID self.name = name self.path = path self.threadCount = threadCount + self.defaultSelection = defaultSelection } } @@ -91,7 +100,13 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl public var modelOptions: [FeatureModelOptionSelection] public var isArchived: Bool public var isSettled: Bool + public var keepsActive: Bool + public var settledAt: Date? + public var lastActivityAt: Date? public var snoozedUntil: Date? + public var snoozedAt: Date? + public var attentionAt: Date? + public var latestTurnCompletedAt: Date? public var runtimeMode: FeatureRuntimeMode public var interactionMode: FeatureInteractionMode @@ -108,7 +123,13 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl modelOptions: [FeatureModelOptionSelection] = [], isArchived: Bool = false, isSettled: Bool = false, + keepsActive: Bool = false, + settledAt: Date? = nil, + lastActivityAt: Date? = nil, snoozedUntil: Date? = nil, + snoozedAt: Date? = nil, + attentionAt: Date? = nil, + latestTurnCompletedAt: Date? = nil, runtimeMode: FeatureRuntimeMode = .fullAccess, interactionMode: FeatureInteractionMode = .standard ) { @@ -124,7 +145,13 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl self.modelOptions = modelOptions self.isArchived = isArchived self.isSettled = isSettled + self.keepsActive = keepsActive + self.settledAt = settledAt + self.lastActivityAt = lastActivityAt self.snoozedUntil = snoozedUntil + self.snoozedAt = snoozedAt + self.attentionAt = attentionAt + self.latestTurnCompletedAt = latestTurnCompletedAt self.runtimeMode = runtimeMode self.interactionMode = interactionMode } diff --git a/apps/swift-ios/Features/Workspace/DailyUXModels.swift b/apps/swift-ios/Features/Workspace/DailyUXModels.swift index 279c55dc38..bd3350825c 100644 --- a/apps/swift-ios/Features/Workspace/DailyUXModels.swift +++ b/apps/swift-ios/Features/Workspace/DailyUXModels.swift @@ -3,17 +3,20 @@ import Foundation public struct FeatureDraftAttachment: Identifiable, Sendable, Equatable { public let id: UUID public var data: Data + public var thumbnailData: Data? public var filename: String public var mimeType: String public init( id: UUID = UUID(), data: Data, + thumbnailData: Data? = nil, filename: String, mimeType: String ) { self.id = id self.data = data + self.thumbnailData = thumbnailData self.filename = filename self.mimeType = mimeType } @@ -73,6 +76,7 @@ public struct FeatureMessageSubmission: Sendable, Equatable { struct DailyUXSidebarIndex { let active: [FeatureThread] + let snoozed: [FeatureThread] let settled: [FeatureThread] let searchResults: [FeatureThread] @@ -85,11 +89,11 @@ struct DailyUXSidebarIndex { let projectByID = Dictionary(uniqueKeysWithValues: snapshot.projects.map { ($0.id, $0) }) let visible = snapshot.threads.filter { thread in guard !thread.isArchived else { return false } - guard thread.snoozedUntil.map({ $0 > now }) != true else { return false } return projectID == nil || thread.projectID == projectID } + let available = visible.filter { !$0.isEffectivelySnoozed(at: now) } - active = visible + active = available .filter { !$0.isEffectivelySettled(at: now) } .sorted { lhs, rhs in if lhs.createdAt != rhs.createdAt { @@ -98,11 +102,22 @@ struct DailyUXSidebarIndex { return lhs.id < rhs.id } - settled = visible + snoozed = visible + .filter { $0.isEffectivelySnoozed(at: now) } + .sorted { lhs, rhs in + let lhsUntil = lhs.snoozedUntil ?? .distantFuture + let rhsUntil = rhs.snoozedUntil ?? .distantFuture + if lhsUntil != rhsUntil { + return lhsUntil < rhsUntil + } + return lhs.id < rhs.id + } + + settled = available .filter { $0.isEffectivelySettled(at: now) } .sorted { lhs, rhs in - if lhs.updatedAt != rhs.updatedAt { - return lhs.updatedAt > rhs.updatedAt + if lhs.settledSortDate != rhs.settledSortDate { + return lhs.settledSortDate > rhs.settledSortDate } return lhs.id < rhs.id } @@ -113,7 +128,7 @@ struct DailyUXSidebarIndex { return } - searchResults = (active + settled).filter { thread in + searchResults = (active + snoozed + settled).filter { thread in let project = projectByID[thread.projectID] return [ thread.title, @@ -132,15 +147,44 @@ extension FeatureThread { func isEffectivelySettled(at now: Date) -> Bool { switch state { - case .queued, .working, .waitingForApproval, .waitingForInput, .failed: + case .queued, .working, .waitingForApproval, .waitingForInput: return false - case .idle, .completed: + case .idle, .failed, .completed: break } if isSettled { return true } - return now.timeIntervalSince(updatedAt) >= 3 * 24 * 60 * 60 + if keepsActive { + return false + } + guard let lastActivityAt else { + return false + } + return now.timeIntervalSince(lastActivityAt) >= 3 * 24 * 60 * 60 + } + + func isEffectivelySnoozed(at now: Date) -> Bool { + guard let snoozedUntil, snoozedUntil > now else { return false } + if state == .waitingForApproval || state == .waitingForInput { + return false + } + if state == .failed, + let snoozedAt, + let attentionAt, + attentionAt > snoozedAt { + return false + } + if let snoozedAt, + let latestTurnCompletedAt, + latestTurnCompletedAt > snoozedAt { + return false + } + return true + } + + var settledSortDate: Date { + settledAt ?? lastActivityAt ?? updatedAt } } @@ -199,6 +243,16 @@ struct DailyUXModelCatalog { } enum DailyUXModelOptions { + static func initialSelection( + projectDefault: FeatureSelection?, + appDefault: FeatureSelection?, + providers: [FeatureProvider] + ) -> FeatureSelection? { + validated(projectDefault, in: providers) + ?? validated(appDefault, in: providers) + ?? preferredSelection(in: providers) + } + static func validated( _ selection: FeatureSelection?, in providers: [FeatureProvider] diff --git a/apps/swift-ios/Features/Workspace/NewThreadView.swift b/apps/swift-ios/Features/Workspace/NewThreadView.swift index 1c87894b54..f687fdeb63 100644 --- a/apps/swift-ios/Features/Workspace/NewThreadView.swift +++ b/apps/swift-ios/Features/Workspace/NewThreadView.swift @@ -98,6 +98,7 @@ public struct NewThreadView: View { .disabled(!canSubmit) .opacity(canSubmit ? 1 : 0.35) .accessibilityLabel(isSubmitting ? "Starting task" : "Start task") + .accessibilityIdentifier("new-task-submit") } } .padding(.horizontal, 12) @@ -123,14 +124,13 @@ public struct NewThreadView: View { projectID = model.snapshot.projects.first?.id ?? "" } if selection == nil { - selection = DailyUXModelOptions.validated( - model.snapshot.settings.defaultSelection, - in: model.snapshot.providers - ) - ?? DailyUXModelOptions.preferredSelection(in: model.snapshot.providers) + selection = initialSelection } promptFocused = true } + .onChange(of: projectID) { + selection = initialSelection + } .alert("Couldn’t start task", isPresented: $submissionFailed) { Button("OK") {} } message: { @@ -212,6 +212,14 @@ public struct NewThreadView: View { model.snapshot.projects.first { $0.id == projectID } } + private var initialSelection: FeatureSelection? { + DailyUXModelOptions.initialSelection( + projectDefault: selectedProject?.defaultSelection, + appDefault: model.snapshot.settings.defaultSelection, + providers: model.snapshot.providers + ) + } + private var canSubmit: Bool { !isSubmitting && !projectID.isEmpty diff --git a/apps/swift-ios/Features/Workspace/WorkspaceView.swift b/apps/swift-ios/Features/Workspace/WorkspaceView.swift index bdeb147332..86a161bd06 100644 --- a/apps/swift-ios/Features/Workspace/WorkspaceView.swift +++ b/apps/swift-ios/Features/Workspace/WorkspaceView.swift @@ -15,6 +15,7 @@ public struct WorkspaceView: View { @State private var showingArchived = false @State private var renamingThread: FeatureThread? @State private var renameTitle = "" + @State private var sidebarClock = Date.now public init( model: FeatureRootModel, @@ -119,6 +120,17 @@ public struct WorkspaceView: View { self.selectedThreadID = nil } } + .task(id: sidebarBoundarySignature) { + while !Task.isCancelled { + sidebarClock = .now + let delay = nextSidebarRefreshDelay(from: sidebarClock) + do { + try await Task.sleep(for: .seconds(delay)) + } catch { + return + } + } + } } private var sidebar: some View { @@ -129,6 +141,7 @@ public struct WorkspaceView: View { if searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { projectFilter activeSection + snoozedSection settledSection archiveAction } else { @@ -296,13 +309,27 @@ public struct WorkspaceView: View { } label: { ProjectFilterRow( project: model.snapshot.projects.first { $0.id == selectedProjectID }, - totalCount: sidebarIndex.active.count + sidebarIndex.settled.count + totalCount: sidebarIndex.active.count + + sidebarIndex.snoozed.count + + sidebarIndex.settled.count ) } .buttonStyle(.plain) .listRowSeparator(.hidden) } + @ViewBuilder + private var snoozedSection: some View { + if !sidebarIndex.snoozed.isEmpty { + Section("Snoozed") { + ForEach(sidebarIndex.snoozed) { thread in + threadLink(thread, showsProject: selectedProjectID == nil) + .opacity(0.76) + } + } + } + } + @ViewBuilder private var activeSection: some View { Section("Active") { @@ -349,11 +376,23 @@ public struct WorkspaceView: View { Button { showingArchived = true } label: { - Label("Archived", systemImage: "archivebox") - .font(.subheadline) - .foregroundStyle(T3Colors.textSecondary) + HStack { + Label("Archived", systemImage: "archivebox") + .font(.subheadline) + .foregroundStyle(T3Colors.textSecondary) + Spacer() + } + .contentShape(Rectangle()) + .accessibilityElement(children: .ignore) + .accessibilityLabel("Archived") + .accessibilityAddTraits(.isButton) + .accessibilityAction { + showingArchived = true + } } .buttonStyle(.plain) + .accessibilityLabel("Archived") + .accessibilityIdentifier("archived-threads-button") } @ViewBuilder @@ -403,13 +442,13 @@ public struct WorkspaceView: View { } label: { Label("Archive", systemImage: "archivebox") } - if thread.isSettled { + if thread.isEffectivelySettled(at: .now) { Button { Task { await model.setSettled(thread.id, settled: false) } } label: { Label("Reopen", systemImage: "arrow.counterclockwise") } - } else if !thread.isEffectivelySettled(at: .now) { + } else { Button { Task { await model.setSettled(thread.id, settled: true) } } label: { @@ -417,20 +456,25 @@ public struct WorkspaceView: View { } } Button { + let isSnoozed = thread.isEffectivelySnoozed(at: sidebarClock) Task { await model.setSnoozed( thread.id, - until: thread.snoozedUntil == nil - ? Date().addingTimeInterval(60 * 60) - : nil + until: isSnoozed ? nil : Date().addingTimeInterval(60 * 60) ) } } label: { + let isSnoozed = thread.isEffectivelySnoozed(at: sidebarClock) Label( - thread.snoozedUntil == nil ? "Snooze 1 hour" : "Unsnooze", - systemImage: thread.snoozedUntil == nil ? "clock" : "bell" + isSnoozed ? "Unsnooze" : "Snooze 1 hour", + systemImage: isSnoozed ? "bell" : "clock" ) } + .disabled( + thread.state == .queued + || thread.state == .waitingForApproval + || thread.state == .waitingForInput + ) Button(role: .destructive) { Task { await model.deleteThread(thread.id) } } label: { @@ -443,10 +487,34 @@ public struct WorkspaceView: View { DailyUXSidebarIndex( snapshot: model.snapshot, query: searchText, - projectID: selectedProjectID + projectID: selectedProjectID, + now: sidebarClock ) } + private var sidebarBoundarySignature: String { + model.snapshot.threads.map { + [ + $0.id, + $0.state.rawValue, + $0.lastActivityAt?.timeIntervalSince1970.description ?? "", + $0.snoozedUntil?.timeIntervalSince1970.description ?? "", + $0.snoozedAt?.timeIntervalSince1970.description ?? "", + $0.attentionAt?.timeIntervalSince1970.description ?? "", + ].joined(separator: ":") + } + .joined(separator: "|") + } + + private func nextSidebarRefreshDelay(from now: Date) -> TimeInterval { + let nextSnoozeBoundary = model.snapshot.threads + .compactMap(\.snoozedUntil) + .filter { $0 > now } + .min() + .map { $0.timeIntervalSince(now) } + return max(0.25, min(60, nextSnoozeBoundary ?? 60)) + } + private var connectionColor: Color { switch model.snapshot.connection.state { case .connected: T3Colors.success diff --git a/apps/swift-ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png b/apps/swift-ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png new file mode 100644 index 0000000000..3da005aaaf Binary files /dev/null and b/apps/swift-ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png differ diff --git a/apps/swift-ios/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json b/apps/swift-ios/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000000..f01d4958bf --- /dev/null +++ b/apps/swift-ios/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "AppIcon-1024.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/apps/swift-ios/T3Code.xcodeproj/project.pbxproj b/apps/swift-ios/T3Code.xcodeproj/project.pbxproj index 2fb2a41950..be6a9c2193 100644 --- a/apps/swift-ios/T3Code.xcodeproj/project.pbxproj +++ b/apps/swift-ios/T3Code.xcodeproj/project.pbxproj @@ -339,12 +339,13 @@ AB0000000000000000000003 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 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_CFBundleDisplayName = "T3 Code"; INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools"; INFOPLIST_KEY_NSAppTransportSecurity_NSAllowsArbitraryLoads = YES; @@ -376,6 +377,7 @@ AB0000000000000000000004 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; diff --git a/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift b/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift index ca4a64990f..e30ec908f0 100644 --- a/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift +++ b/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift @@ -64,6 +64,33 @@ final class CoreContractTests: XCTestCase { XCTAssertEqual(command["runtimeMode"]?.stringValue, "full-access") } + func testFirstSendCommandCarriesCanonicalBootstrapMetadata() throws { + let model = ModelSelection(instanceId: "codex", model: "gpt-5.4") + let command = try OrchestrationCommands.createThreadAndSend( + threadID: "thread-first-send", + projectID: "project-1", + title: "Build the native app", + text: "Build the native app", + model: model, + runtimeMode: .fullAccess, + commandID: "command-first-send", + messageID: "message-first-send", + createdAt: "2026-07-30T12:00:00.000Z" + ) + + XCTAssertEqual(command["type"]?.stringValue, "thread.turn.start") + XCTAssertEqual(command["titleSeed"]?.stringValue, "Build the native app") + XCTAssertEqual(command["modelSelection"]?["model"]?.stringValue, "gpt-5.4") + XCTAssertEqual( + command["bootstrap"]?["createThread"]?["projectId"]?.stringValue, + "project-1" + ) + XCTAssertEqual( + command["bootstrap"]?["createThread"]?["modelSelection"]?["instanceId"]?.stringValue, + "codex" + ) + } + func testEnvironmentStorePersistsSelectionAndClearsRemovedActiveEnvironment() async throws { let directory = FileManager.default.temporaryDirectory .appendingPathComponent("t3-swift-core-\(UUID().uuidString)", isDirectory: true) @@ -94,4 +121,42 @@ final class CoreContractTests: XCTestCase { XCTAssertEqual(remaining.map(\.id), [first.id]) XCTAssertEqual(fallback, first.id) } + + func testRuntimeReplacesCachedClientWhenSavedEndpointChanges() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("t3-swift-runtime-\(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: "same-server", + label: "Studio", + httpBaseURL: URL(string: "http://192.168.1.10:3773")!, + webSocketBaseURL: URL(string: "ws://192.168.1.10:3773")! + ) + let moved = Environment( + id: "same-server", + label: "Studio", + httpBaseURL: URL(string: "http://192.168.1.20:4773")!, + webSocketBaseURL: URL(string: "ws://192.168.1.20:4773")! + ) + try await store.save([first]) + try await store.setActiveEnvironment(id: first.id) + let runtime = EnvironmentRuntime( + environmentStore: store, + credentialStore: InMemoryCredentialStore() + ) + + let firstClientValue = try await runtime.activeClient() + let firstClient = try XCTUnwrap(firstClientValue) + try await store.upsert(moved) + let movedClientValue = try await runtime.activeClient() + let movedClient = try XCTUnwrap(movedClientValue) + let movedEnvironment = await movedClient.environment + + XCTAssertFalse(firstClient === movedClient) + XCTAssertEqual(movedEnvironment.httpBaseURL, moved.httpBaseURL) + XCTAssertEqual(movedEnvironment.webSocketBaseURL, moved.webSocketBaseURL) + } } diff --git a/apps/swift-ios/Tests/CoreTests/PairingServiceTests.swift b/apps/swift-ios/Tests/CoreTests/PairingServiceTests.swift index 3e537e9a0d..9057fb88cb 100644 --- a/apps/swift-ios/Tests/CoreTests/PairingServiceTests.swift +++ b/apps/swift-ios/Tests/CoreTests/PairingServiceTests.swift @@ -40,6 +40,10 @@ final class PairingServiceTests: XCTestCase { let form = String(data: requests[1].httpBody!, encoding: .utf8)! XCTAssertTrue(form.contains("subject_token=pair-once")) XCTAssertTrue(form.contains("client_device_type=mobile")) + // Omitting scope accepts the exact grant carried by the one-time link. + // Requesting administrative scopes consumes ordinary links and then + // fails with scope_not_granted. + XCTAssertFalse(form.contains("scope=")) } } diff --git a/apps/swift-ios/Tests/CoreTests/TransportReliabilityTests.swift b/apps/swift-ios/Tests/CoreTests/TransportReliabilityTests.swift index 8a8db050a8..65e8b94603 100644 --- a/apps/swift-ios/Tests/CoreTests/TransportReliabilityTests.swift +++ b/apps/swift-ios/Tests/CoreTests/TransportReliabilityTests.swift @@ -69,6 +69,133 @@ final class TransportReliabilityTests: XCTestCase { ) } + func testBootstrapUsesCanonicalWebSocketRPCDispatch() async throws { + let environment = Environment( + id: "environment-1", + label: "Studio", + httpBaseURL: URL(string: "https://studio.example")!, + webSocketBaseURL: URL(string: "wss://studio.example")! + ) + let credentials = InMemoryCredentialStore( + credentials: [ + environment.id: EnvironmentCredential(accessToken: "access-token"), + ] + ) + let transport = RecordingHTTPTransport { request in + let body = """ + { + "ticket": "websocket-ticket", + "expiresAt": "2026-07-30T12:05:00.000Z" + } + """ + return (Data(body.utf8), transportResponse(request)) + } + let connection = RecordingWebSocketConnection() + let client = T3Client( + environment: environment, + credentialStore: credentials, + httpTransport: transport, + webSocketConnector: StaticWebSocketConnector(connection: connection) + ) + + let result = try await client.createThreadAndSend( + threadID: "thread-first-send", + projectID: "project-1", + title: "Native first send", + text: "Start from this message", + model: ModelSelection(instanceId: "codex", model: "gpt-5.4"), + runtimeMode: .fullAccess, + commandID: "stable-command", + messageID: "stable-message", + createdAt: "2026-07-30T12:00:00.000Z" + ) + await client.disconnect() + + XCTAssertEqual(result.sequence, 42) + let requests = await connection.requests() + XCTAssertEqual(requests.count, 1) + XCTAssertEqual(requests.first?["tag"]?.stringValue, "orchestration.dispatchCommand") + XCTAssertEqual( + requests.first?["payload"]?["bootstrap"]?["createThread"]?["projectId"]?.stringValue, + "project-1" + ) + XCTAssertEqual(requests.first?["payload"]?["commandId"]?.stringValue, "stable-command") + XCTAssertEqual( + requests.first?["payload"]?["message"]?["messageId"]?.stringValue, + "stable-message" + ) + + let httpRequests = await transport.requests + XCTAssertEqual(httpRequests.map(\.url?.path), ["/api/auth/websocket-ticket"]) + } + + func testUnsentCommandsFallBackToHTTPButBootstrapDoesNot() async throws { + let environment = Environment( + id: "environment-1", + label: "Studio", + httpBaseURL: URL(string: "https://studio.example")!, + webSocketBaseURL: URL(string: "wss://studio.example")! + ) + let credentials = InMemoryCredentialStore( + credentials: [ + environment.id: EnvironmentCredential(accessToken: "access-token"), + ] + ) + let transport = RecordingHTTPTransport { request in + let body = if request.url?.path == "/api/auth/websocket-ticket" { + """ + { + "ticket": "websocket-ticket", + "expiresAt": "2026-07-30T12:05:00.000Z" + } + """ + } else { + """ + {"sequence": 9} + """ + } + return (Data(body.utf8), transportResponse(request)) + } + let client = T3Client( + environment: environment, + credentialStore: credentials, + httpTransport: transport, + webSocketConnector: FailingWebSocketConnector(), + rpcConnectionWaitTimeout: .milliseconds(30) + ) + + let rename = try await client.rename(threadID: "thread-1", title: "Renamed") + XCTAssertEqual(rename.sequence, 9) + + do { + _ = try await client.createThreadAndSend( + threadID: "thread-first-send", + projectID: "project-1", + title: "Native first send", + text: "Start from this message", + model: ModelSelection(instanceId: "codex", model: "gpt-5.4"), + runtimeMode: .fullAccess + ) + XCTFail("Bootstrap must not use the HTTP endpoint that cannot expand it.") + } catch let error as RPCError { + guard case .connectionUnavailable = error else { + return XCTFail("Unexpected RPC error: \(error)") + } + } + await client.disconnect() + + let requests = await transport.requests + let dispatchRequests = requests.filter { + $0.url?.path == "/api/orchestration/dispatch" + } + XCTAssertEqual(dispatchRequests.count, 1) + let command = try JSONDecoder.t3.decode( + JSONValue.self, + from: try XCTUnwrap(dispatchRequests.first?.httpBody) + ) + XCTAssertEqual(command["type"]?.stringValue, "thread.meta.update") + } + /// Set `T3_SWIFT_WS_DEFLATE_ECHO_URL` to a WebSocket endpoint that rejects /// non-deflate handshakes and echoes binary frames. This is intentionally /// opt-in because XCTest does not own a Node process. A successful round @@ -191,3 +318,65 @@ private actor RecordingHTTPTransport: HTTPTransport { return try handler(request) } } + +private struct StaticWebSocketConnector: WebSocketConnecting { + let connection: RecordingWebSocketConnection + + func connect(to _: URL) async throws -> any WebSocketConnection { + connection + } +} + +private struct FailingWebSocketConnector: WebSocketConnecting { + func connect(to _: URL) async throws -> any WebSocketConnection { + throw URLError(.cannotConnectToHost) + } +} + +private actor RecordingWebSocketConnection: WebSocketConnection { + private var recordedRequests: [JSONValue] = [] + private var queuedResponses: [Data] = [] + private var receiver: CheckedContinuation? + + func send(_ data: Data) throws { + let request = try JSONDecoder.t3.decode(JSONValue.self, from: data) + recordedRequests.append(request) + guard case let .number(rawID) = request["id"] else { return } + let response = JSONValue.object([ + "_tag": .string("Exit"), + "requestId": .number(rawID), + "exit": .object([ + "_tag": .string("Success"), + "value": .object(["sequence": .number(42)]), + ]), + ]) + enqueue(try JSONEncoder.t3.encode(response)) + } + + func receive() async throws -> Data { + if !queuedResponses.isEmpty { + return queuedResponses.removeFirst() + } + return try await withCheckedThrowingContinuation { continuation in + receiver = continuation + } + } + + func close() { + receiver?.resume(throwing: CancellationError()) + receiver = nil + } + + func requests() -> [JSONValue] { + recordedRequests + } + + private func enqueue(_ data: Data) { + if let receiver { + self.receiver = nil + receiver.resume(returning: data) + } else { + queuedResponses.append(data) + } + } +} diff --git a/apps/swift-ios/Tests/CoreTests/WebSocketRPCRaceTests.swift b/apps/swift-ios/Tests/CoreTests/WebSocketRPCRaceTests.swift new file mode 100644 index 0000000000..70ff21f278 --- /dev/null +++ b/apps/swift-ios/Tests/CoreTests/WebSocketRPCRaceTests.swift @@ -0,0 +1,185 @@ +import XCTest +@testable import T3Code + +@MainActor +final class WebSocketRPCRaceTests: XCTestCase { + func testDisconnectWhileUnarySendIsSuspendedFailsWithoutReplay() async throws { + let first = SuspendedSendConnection() + let second = AutoReplyConnection() + let connector = SequencedConnector(connections: [first, second]) + let client = WebSocketRPCClient( + connector: connector, + connectionWaitTimeout: .seconds(2), + endpointProvider: { URL(string: "wss://studio.example/ws")! } + ) + + await client.start() + await first.waitUntilReceiving() + + let request = Task { + do { + let value = try await client.request( + "thread.rename", + as: JSONValue.self + ) + return Result.success(value) + } catch { + return Result.failure(error) + } + } + + await first.waitUntilSending() + await first.failReceive() + + let outcome = await request.value + guard case let .failure(error) = outcome, + case .disconnected = error as? RPCError + else { + await client.stop() + await first.releaseSend() + return XCTFail("An ambiguous unary send must fail as disconnected.") + } + + await connector.waitUntilConnectionCount(2) + let replayedRequestCount = await second.sentRequestCount() + XCTAssertEqual( + replayedRequestCount, + 0, + "A unary request that crossed a broken socket must not be replayed." + ) + + await client.stop() + await first.releaseSend() + } +} + +private actor SequencedConnector: WebSocketConnecting { + private let connections: [any WebSocketConnection] + private var nextIndex = 0 + private var countWaiters: [(Int, CheckedContinuation)] = [] + + init(connections: [any WebSocketConnection]) { + self.connections = connections + } + + func connect(to _: URL) throws -> any WebSocketConnection { + guard nextIndex < connections.count else { + throw URLError(.cannotConnectToHost) + } + let connection = connections[nextIndex] + nextIndex += 1 + let completed = countWaiters.filter { nextIndex >= $0.0 } + countWaiters.removeAll { nextIndex >= $0.0 } + completed.forEach { $0.1.resume() } + return connection + } + + func waitUntilConnectionCount(_ count: Int) async { + guard nextIndex < count else { return } + await withCheckedContinuation { continuation in + countWaiters.append((count, continuation)) + } + } +} + +private actor SuspendedSendConnection: WebSocketConnection { + private var sendContinuation: CheckedContinuation? + private var receiveContinuation: CheckedContinuation? + private var sendWaiters: [CheckedContinuation] = [] + private var receiveWaiters: [CheckedContinuation] = [] + + func send(_: Data) async throws { + let waiters = sendWaiters + sendWaiters.removeAll() + waiters.forEach { $0.resume() } + try await withCheckedThrowingContinuation { continuation in + sendContinuation = continuation + } + } + + func receive() async throws -> Data { + let waiters = receiveWaiters + receiveWaiters.removeAll() + waiters.forEach { $0.resume() } + return try await withCheckedThrowingContinuation { continuation in + receiveContinuation = continuation + } + } + + func close() { + receiveContinuation?.resume(throwing: CancellationError()) + receiveContinuation = nil + } + + func waitUntilSending() async { + guard sendContinuation == nil else { return } + await withCheckedContinuation { continuation in + sendWaiters.append(continuation) + } + } + + func waitUntilReceiving() async { + guard receiveContinuation == nil else { return } + await withCheckedContinuation { continuation in + receiveWaiters.append(continuation) + } + } + + func failReceive() { + receiveContinuation?.resume(throwing: URLError(.networkConnectionLost)) + receiveContinuation = nil + } + + func releaseSend() { + sendContinuation?.resume() + sendContinuation = nil + } +} + +private actor AutoReplyConnection: WebSocketConnection { + private var sentRequests = 0 + private var queuedResponses: [Data] = [] + private var receiveContinuation: CheckedContinuation? + + func send(_ data: Data) throws { + sentRequests += 1 + let request = try JSONDecoder.t3.decode(JSONValue.self, from: data) + guard case let .number(requestID) = request["id"] else { return } + let response = JSONValue.object([ + "_tag": .string("Exit"), + "requestId": .number(requestID), + "exit": .object([ + "_tag": .string("Success"), + "value": .object([:]), + ]), + ]) + enqueue(try JSONEncoder.t3.encode(response)) + } + + func receive() async throws -> Data { + if !queuedResponses.isEmpty { + return queuedResponses.removeFirst() + } + return try await withCheckedThrowingContinuation { continuation in + receiveContinuation = continuation + } + } + + func close() { + receiveContinuation?.resume(throwing: CancellationError()) + receiveContinuation = nil + } + + func sentRequestCount() -> Int { + sentRequests + } + + private func enqueue(_ data: Data) { + if let receiveContinuation { + self.receiveContinuation = nil + receiveContinuation.resume(returning: data) + } else { + queuedResponses.append(data) + } + } +} diff --git a/apps/swift-ios/Tests/CoreTests/WorkspaceContractTests.swift b/apps/swift-ios/Tests/CoreTests/WorkspaceContractTests.swift index c034ba6fdc..39cc965381 100644 --- a/apps/swift-ios/Tests/CoreTests/WorkspaceContractTests.swift +++ b/apps/swift-ios/Tests/CoreTests/WorkspaceContractTests.swift @@ -129,6 +129,10 @@ final class WorkspaceContractTests: XCTestCase { XCTAssertEqual(RPCMethod.projectsListEntries.rawValue, "projects.listEntries") XCTAssertEqual(RPCMethod.vcsRefreshStatus.rawValue, "vcs.refreshStatus") XCTAssertEqual(RPCMethod.reviewDiffPreview.rawValue, "review.getDiffPreview") + XCTAssertEqual( + RPCMethod.getArchivedShellSnapshot.rawValue, + "orchestration.getArchivedShellSnapshot" + ) XCTAssertEqual(RPCMethod.terminalAttach.rawValue, "terminal.attach") XCTAssertEqual(RPCMethod.subscribeTerminalEvents.rawValue, "subscribeTerminalEvents") } diff --git a/apps/swift-ios/Tests/FeatureTests/DailyUXModelPickerTests.swift b/apps/swift-ios/Tests/FeatureTests/DailyUXModelPickerTests.swift index 7f756c1bfd..a624dd7a65 100644 --- a/apps/swift-ios/Tests/FeatureTests/DailyUXModelPickerTests.swift +++ b/apps/swift-ios/Tests/FeatureTests/DailyUXModelPickerTests.swift @@ -173,4 +173,27 @@ struct DailyUXModelPickerTests { FeatureModelOptionSelection(id: "fast", value: .boolean(true)), ]) } + + @Test + func projectDefaultWinsBeforeAppAndCatalogDefaults() { + let providers = [ + FeatureProvider( + id: "codex", + name: "Codex", + models: [ + .init(id: "project", name: "Project"), + .init(id: "app", name: "App"), + .init(id: "catalog", name: "Catalog", isDefault: true), + ] + ), + ] + + let selection = DailyUXModelOptions.initialSelection( + projectDefault: .init(providerID: "codex", modelID: "project"), + appDefault: .init(providerID: "codex", modelID: "app"), + providers: providers + ) + + #expect(selection?.modelID == "project") + } } diff --git a/apps/swift-ios/Tests/FeatureTests/DailyUXNewTaskTests.swift b/apps/swift-ios/Tests/FeatureTests/DailyUXNewTaskTests.swift index 30c89b3fbe..6ef3fb2be8 100644 --- a/apps/swift-ios/Tests/FeatureTests/DailyUXNewTaskTests.swift +++ b/apps/swift-ios/Tests/FeatureTests/DailyUXNewTaskTests.swift @@ -1,5 +1,6 @@ import Foundation import Testing +import UIKit @testable import T3Code @Suite("Message-first task creation") @@ -24,4 +25,27 @@ struct DailyUXNewTaskTests { #expect(request.interactionMode == .plan) #expect(request.attachments.first?.byteCount == 3) } + + @Test @MainActor + func imageProcessorDownsamplesUploadAndBuildsSmallThumbnail() throws { + let source = UIGraphicsImageRenderer(size: CGSize(width: 2_400, height: 1_200)) + .image { context in + UIColor.systemPink.setFill() + context.fill(CGRect(x: 0, y: 0, width: 2_400, height: 1_200)) + } + let sourceData = try #require(source.pngData()) + + let attachment = try FeatureImageProcessor.attachment( + from: sourceData, + ordinal: 1 + ) + let prepared = try #require(UIImage(data: attachment.data)) + let thumbnail = try #require( + attachment.thumbnailData.flatMap(UIImage.init(data:)) + ) + + #expect(max(prepared.size.width, prepared.size.height) <= 2_048) + #expect(max(thumbnail.size.width, thumbnail.size.height) <= 160) + #expect(attachment.mimeType == "image/jpeg") + } } diff --git a/apps/swift-ios/Tests/FeatureTests/DailyUXSidebarTests.swift b/apps/swift-ios/Tests/FeatureTests/DailyUXSidebarTests.swift index 0be3cef829..2ee338a1f8 100644 --- a/apps/swift-ios/Tests/FeatureTests/DailyUXSidebarTests.swift +++ b/apps/swift-ios/Tests/FeatureTests/DailyUXSidebarTests.swift @@ -74,7 +74,23 @@ struct DailyUXSidebarTests { } @Test - func snoozedAndArchivedThreadsStayOutOfBothBlocks() { + func explicitActiveOverridePreventsAutoSettlement() { + var reopened = thread( + id: "reopened", + created: -400_000, + updated: -300_000, + state: .idle + ) + reopened.keepsActive = true + + let index = makeIndex([reopened]) + + #expect(index.active.map(\.id) == ["reopened"]) + #expect(index.settled.isEmpty) + } + + @Test + func snoozedThreadsHaveAReachableReverseState() { var snoozed = thread(id: "snoozed", created: -20, updated: -10) snoozed.snoozedUntil = now.addingTimeInterval(3_600) var archived = thread(id: "archived", created: -30, updated: -20) @@ -84,9 +100,56 @@ struct DailyUXSidebarTests { let index = makeIndex([snoozed, archived, visible]) #expect(index.active.map(\.id) == ["visible"]) + #expect(index.snoozed.map(\.id) == ["snoozed"]) #expect(index.settled.isEmpty) } + @Test + func snoozeExpiresAtTheClockBoundary() { + var thread = thread(id: "timed", created: -20, updated: -10) + thread.snoozedUntil = now.addingTimeInterval(30) + + #expect(makeIndex([thread]).snoozed.map(\.id) == ["timed"]) + let expired = DailyUXSidebarIndex( + snapshot: FeatureSnapshot(threads: [thread]), + query: "", + now: now.addingTimeInterval(31) + ) + #expect(expired.active.map(\.id) == ["timed"]) + } + + @Test + func onlyFailuresRaisedAfterSnoozingWakeTheThread() { + var acknowledged = thread( + id: "acknowledged", + created: -30, + updated: -10, + state: .failed + ) + acknowledged.snoozedUntil = now.addingTimeInterval(3_600) + acknowledged.snoozedAt = now.addingTimeInterval(-10) + acknowledged.attentionAt = now.addingTimeInterval(-20) + + var fresh = acknowledged + fresh = FeatureThread( + id: "fresh", + projectID: fresh.projectID, + title: fresh.title, + createdAt: fresh.createdAt, + updatedAt: fresh.updatedAt, + state: .failed, + lastActivityAt: fresh.lastActivityAt, + snoozedUntil: fresh.snoozedUntil, + snoozedAt: fresh.snoozedAt, + attentionAt: now.addingTimeInterval(-5) + ) + + let index = makeIndex([acknowledged, fresh]) + + #expect(index.snoozed.map(\.id) == ["acknowledged"]) + #expect(index.active.map(\.id) == ["fresh"]) + } + @Test func projectFilterAndSearchUseRepositoryContext() { let projects = [ @@ -128,7 +191,8 @@ struct DailyUXSidebarTests { createdAt: now.addingTimeInterval(created), updatedAt: now.addingTimeInterval(updated), state: state, - isSettled: isSettled + isSettled: isSettled, + lastActivityAt: now.addingTimeInterval(updated) ) } } diff --git a/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift b/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift index e3734c8eb8..9d858f5829 100644 --- a/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift +++ b/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift @@ -16,7 +16,13 @@ struct FeatureRootModelTests { endpoint: "https://studio.example" ) ) + let oldThread = FeatureThread(id: "same-id", projectID: "old-project", title: "Old") + client.threadDetail = FeatureThreadDetail( + thread: oldThread, + messages: [FeatureMessage(id: "old-message", role: .assistant, text: "Old")] + ) let model = FeatureRootModel(client: client) + _ = await model.detail(for: oldThread.id) let result = await model.pair(endpoint: "https://studio.example", token: "pair-token") @@ -24,6 +30,7 @@ struct FeatureRootModelTests { #expect(client.pairEndpoint == "https://studio.example") #expect(client.pairToken == "pair-token") #expect(model.snapshot.connection.state == .connected) + #expect(model.details.isEmpty) } @Test @@ -120,6 +127,53 @@ struct FeatureRootModelTests { await model.deleteThread(thread.id) #expect(model.snapshot.threads.isEmpty) } + + @Test + func testCancelledDetailRefreshKeepsCachedContentWithoutAlert() async { + let client = FeatureClientStub() + let thread = FeatureThread(id: "thread-1", projectID: "project-1", title: "Thread") + let detail = FeatureThreadDetail( + thread: thread, + messages: [ + FeatureMessage(id: "message-1", role: .assistant, text: "Still here"), + ] + ) + client.threadDetail = detail + let model = FeatureRootModel(client: client) + _ = await model.detail(for: thread.id) + client.loadThreadError = CancellationError() + + let refreshed = await model.detail(for: thread.id, force: true) + + #expect(refreshed == detail) + #expect(model.errorMessage == nil) + } + + @Test + func testResnoozeRefreshesTheOptimisticSnoozeTimestamp() async { + let client = FeatureClientStub() + var thread = FeatureThread( + id: "thread-1", + projectID: "project-1", + title: "Thread", + state: .failed + ) + let oldSnooze = Date.now.addingTimeInterval(-600) + thread.snoozedAt = oldSnooze + thread.attentionAt = Date.now.addingTimeInterval(-300) + client.createdThread = thread + let model = FeatureRootModel(client: client) + _ = await model.createThread(projectID: thread.projectID, title: nil, selection: nil) + + await model.setSnoozed( + thread.id, + until: Date.now.addingTimeInterval(3_600) + ) + + let updated = model.snapshot.threads[0] + #expect(updated.snoozedAt != oldSnooze) + #expect(updated.snoozedAt! > updated.attentionAt!) + } } @MainActor @@ -135,6 +189,7 @@ private final class FeatureClientStub: FeatureClient { var startedAttachments: [FeatureUploadAttachment] = [] var createThreadCallCount = 0 var sendMessageCallCount = 0 + var loadThreadError: (any Error)? func initialSnapshot() async throws -> FeatureSnapshot { if pairEndpoint != nil, let snapshotAfterPair { @@ -175,6 +230,9 @@ private final class FeatureClientStub: FeatureClient { func deleteThread(id: String) async throws {} func loadThread(id: String) async throws -> FeatureThreadDetail { + if let loadThreadError { + throw loadThreadError + } if let threadDetail { return threadDetail } diff --git a/apps/swift-ios/Tests/FeatureTests/NativeRetryIdentityTests.swift b/apps/swift-ios/Tests/FeatureTests/NativeRetryIdentityTests.swift new file mode 100644 index 0000000000..9b93336007 --- /dev/null +++ b/apps/swift-ios/Tests/FeatureTests/NativeRetryIdentityTests.swift @@ -0,0 +1,419 @@ +import Foundation +import XCTest +@testable import T3Code + +@MainActor +final class NativeRetryIdentityTests: XCTestCase { + func testAmbiguousFailuresReuseStableTurnAndBootstrapIdentities() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("t3-native-retry-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + + let environment = Environment( + id: "environment-retry", + label: "Retry", + httpBaseURL: URL(string: "https://retry.example")!, + webSocketBaseURL: URL(string: "wss://retry.example")! + ) + let store = EnvironmentStore( + fileURL: directory.appendingPathComponent("environments.json") + ) + try await store.save([environment]) + try await store.setActiveEnvironment(id: environment.id) + + let connection = AmbiguousDispatchWebSocketConnection() + let runtime = EnvironmentRuntime( + environmentStore: store, + credentialStore: InMemoryCredentialStore( + credentials: [ + environment.id: EnvironmentCredential(accessToken: "token"), + ] + ), + httpTransport: RetryIdentityHTTPTransport(shell: retryShellSnapshot()), + webSocketConnector: RetryIdentityWebSocketConnector(connection: connection) + ) + let settings = UserDefaults( + suiteName: "t3-native-retry-\(UUID().uuidString)" + )! + let client = NativeFeatureClient(runtime: runtime, settingsStore: settings) + _ = try await client.initialSnapshot() + await connection.waitUntilConnected() + + for _ in 0..<2 { + do { + try await client.sendMessage( + threadID: "thread-existing", + text: "Retry without duplicating", + selection: nil + ) + XCTFail("The synthetic dispatch should fail ambiguously.") + } catch {} + } + + for _ in 0..<2 { + do { + _ = try await client.createThreadAndSend( + projectID: "project-1", + prompt: "Create exactly one task", + selection: FeatureSelection(providerID: "codex", modelID: "gpt-5.4"), + runtimeMode: .fullAccess, + interactionMode: .standard, + attachments: [] + ) + XCTFail("The synthetic bootstrap should fail ambiguously.") + } catch {} + } + + let commands = await connection.dispatchCommands() + XCTAssertEqual(commands.count, 4) + assertStableIdentity(commands[0], commands[1], includesThreadID: false) + assertStableIdentity(commands[2], commands[3], includesThreadID: true) + await client.disconnect() + } + + func testPartialBootstrapRecoversBySendingOnlyTheStableFinalTurn() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("t3-native-partial-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + + let environment = Environment( + id: "environment-partial", + label: "Partial", + httpBaseURL: URL(string: "https://partial.example")!, + webSocketBaseURL: URL(string: "wss://partial.example")! + ) + let store = EnvironmentStore( + fileURL: directory.appendingPathComponent("environments.json") + ) + try await store.save([environment]) + try await store.setActiveEnvironment(id: environment.id) + + let connection = PartialBootstrapWebSocketConnection() + let runtime = EnvironmentRuntime( + environmentStore: store, + credentialStore: InMemoryCredentialStore( + credentials: [ + environment.id: EnvironmentCredential(accessToken: "token"), + ] + ), + httpTransport: PartialBootstrapHTTPTransport(shell: retryShellSnapshot()), + webSocketConnector: PartialBootstrapWebSocketConnector(connection: connection) + ) + let settings = UserDefaults( + suiteName: "t3-native-partial-\(UUID().uuidString)" + )! + let client = NativeFeatureClient(runtime: runtime, settingsStore: settings) + _ = try await client.initialSnapshot() + await connection.waitUntilConnected() + + let created = try await client.createThreadAndSend( + projectID: "project-1", + prompt: "Recover the first turn", + selection: FeatureSelection(providerID: "codex", modelID: "gpt-5.4"), + runtimeMode: .fullAccess, + interactionMode: .standard, + attachments: [] + ) + + let commands = await connection.dispatchCommands() + XCTAssertEqual(commands.count, 2) + XCTAssertNotNil(commands[0]["bootstrap"]) + XCTAssertNil(commands[1]["bootstrap"]) + assertStableIdentity(commands[0], commands[1], includesThreadID: true) + XCTAssertEqual(created.id, commands[0]["threadId"]?.stringValue) + await client.disconnect() + } + + private func assertStableIdentity( + _ first: JSONValue, + _ second: JSONValue, + includesThreadID: Bool + ) { + XCTAssertEqual(first["commandId"], second["commandId"]) + XCTAssertEqual(first["message"]?["messageId"], second["message"]?["messageId"]) + XCTAssertEqual(first["createdAt"], second["createdAt"]) + if includesThreadID { + XCTAssertEqual(first["threadId"], second["threadId"]) + } + } +} + +private func retryShellSnapshot() -> OrchestrationShellSnapshot { + let timestamp = "2026-07-30T12:00:00.000Z" + let model = ModelSelection(instanceId: "codex", model: "gpt-5.4") + return OrchestrationShellSnapshot( + snapshotSequence: 1, + projects: [ + OrchestrationProject( + id: "project-1", + title: "T3 Code", + workspaceRoot: "/work/t3", + repositoryIdentity: nil, + defaultModelSelection: model, + scripts: [], + createdAt: timestamp, + updatedAt: timestamp, + deletedAt: nil + ), + ], + threads: [ + OrchestrationThreadShell( + id: "thread-existing", + projectId: "project-1", + title: "Existing", + modelSelection: model, + runtimeMode: .fullAccess, + interactionMode: .default, + branch: nil, + worktreePath: nil, + latestTurn: nil, + createdAt: timestamp, + updatedAt: timestamp, + archivedAt: nil, + settledOverride: nil, + settledAt: nil, + snoozedUntil: nil, + snoozedAt: nil, + session: nil, + latestUserMessageAt: nil, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false + ), + ], + updatedAt: timestamp + ) +} + +private actor RetryIdentityHTTPTransport: HTTPTransport { + private let shellData: Data + + init(shell: OrchestrationShellSnapshot) { + shellData = try! JSONEncoder.t3.encode(shell) + } + + func data(for request: URLRequest) throws -> (Data, HTTPURLResponse) { + let path = request.url?.path ?? "" + if path == "/api/orchestration/shell" { + return (shellData, retryHTTPResponse(request)) + } + if path == "/api/auth/websocket-ticket" { + return ( + Data( + """ + { + "ticket": "ticket", + "expiresAt": "2026-07-30T12:05:00.000Z" + } + """.utf8 + ), + retryHTTPResponse(request) + ) + } + if path.hasPrefix("/api/orchestration/threads/") { + throw URLError(.networkConnectionLost) + } + throw URLError(.unsupportedURL) + } +} + +private struct RetryIdentityWebSocketConnector: WebSocketConnecting { + let connection: AmbiguousDispatchWebSocketConnection + + func connect(to _: URL) async throws -> any WebSocketConnection { + connection + } +} + +private actor PartialBootstrapHTTPTransport: HTTPTransport { + private let shellData: Data + + init(shell: OrchestrationShellSnapshot) { + shellData = try! JSONEncoder.t3.encode(shell) + } + + func data(for request: URLRequest) throws -> (Data, HTTPURLResponse) { + let path = request.url?.path ?? "" + if path == "/api/orchestration/shell" { + return (shellData, retryHTTPResponse(request)) + } + if path == "/api/auth/websocket-ticket" { + return ( + Data( + """ + { + "ticket": "ticket", + "expiresAt": "2026-07-30T12:05:00.000Z" + } + """.utf8 + ), + retryHTTPResponse(request) + ) + } + if path.hasPrefix("/api/orchestration/threads/") { + let threadID = request.url?.lastPathComponent.removingPercentEncoding ?? "thread" + let snapshot = retryEmptyThreadDetail(id: threadID) + return (try JSONEncoder.t3.encode(snapshot), retryHTTPResponse(request)) + } + throw URLError(.unsupportedURL) + } +} + +private struct PartialBootstrapWebSocketConnector: WebSocketConnecting { + let connection: PartialBootstrapWebSocketConnection + + func connect(to _: URL) async throws -> any WebSocketConnection { + connection + } +} + +private actor AmbiguousDispatchWebSocketConnection: WebSocketConnection { + private var commands: [JSONValue] = [] + private var didConnect = false + private var connectionWaiters: [CheckedContinuation] = [] + private var receiver: CheckedContinuation? + + func send(_ data: Data) throws { + let request = try JSONDecoder.t3.decode(JSONValue.self, from: data) + if !didConnect { + didConnect = true + connectionWaiters.forEach { $0.resume() } + connectionWaiters.removeAll() + } + if request["tag"]?.stringValue == RPCMethod.dispatchCommand.rawValue, + let payload = request["payload"] { + commands.append(payload) + throw URLError(.networkConnectionLost) + } + } + + func receive() async throws -> Data { + try await withCheckedThrowingContinuation { continuation in + receiver = continuation + } + } + + func close() { + receiver?.resume(throwing: CancellationError()) + receiver = nil + } + + func waitUntilConnected() async { + guard !didConnect else { return } + await withCheckedContinuation { continuation in + connectionWaiters.append(continuation) + } + } + + func dispatchCommands() -> [JSONValue] { + commands + } +} + +private actor PartialBootstrapWebSocketConnection: WebSocketConnection { + private var commands: [JSONValue] = [] + private var queuedResponses: [Data] = [] + private var receiver: CheckedContinuation? + private var didConnect = false + private var connectionWaiters: [CheckedContinuation] = [] + + func send(_ data: Data) throws { + let request = try JSONDecoder.t3.decode(JSONValue.self, from: data) + if !didConnect { + didConnect = true + connectionWaiters.forEach { $0.resume() } + connectionWaiters.removeAll() + } + guard request["tag"]?.stringValue == RPCMethod.dispatchCommand.rawValue, + let payload = request["payload"] else { + return + } + commands.append(payload) + if payload["bootstrap"] != nil { + throw URLError(.networkConnectionLost) + } + guard case let .number(requestID) = request["id"] else { return } + let response = JSONValue.object([ + "_tag": .string("Exit"), + "requestId": .number(requestID), + "exit": .object([ + "_tag": .string("Success"), + "value": .object(["sequence": .number(42)]), + ]), + ]) + enqueue(try JSONEncoder.t3.encode(response)) + } + + func receive() async throws -> Data { + if !queuedResponses.isEmpty { + return queuedResponses.removeFirst() + } + return try await withCheckedThrowingContinuation { continuation in + receiver = continuation + } + } + + func close() { + receiver?.resume(throwing: CancellationError()) + receiver = nil + } + + func waitUntilConnected() async { + guard !didConnect else { return } + await withCheckedContinuation { continuation in + connectionWaiters.append(continuation) + } + } + + func dispatchCommands() -> [JSONValue] { + commands + } + + private func enqueue(_ data: Data) { + if let receiver { + self.receiver = nil + receiver.resume(returning: data) + } else { + queuedResponses.append(data) + } + } +} + +private func retryEmptyThreadDetail(id: String) -> OrchestrationThreadDetailSnapshot { + let timestamp = "2026-07-30T12:00:00.000Z" + return OrchestrationThreadDetailSnapshot( + snapshotSequence: 2, + thread: OrchestrationThread( + id: id, + projectId: "project-1", + title: "Recover the first turn", + modelSelection: ModelSelection(instanceId: "codex", model: "gpt-5.4"), + runtimeMode: .fullAccess, + interactionMode: .default, + branch: nil, + worktreePath: nil, + latestTurn: nil, + createdAt: timestamp, + updatedAt: timestamp, + archivedAt: nil, + settledOverride: nil, + settledAt: nil, + snoozedUntil: nil, + snoozedAt: nil, + deletedAt: nil, + messages: [], + activities: [], + checkpoints: [], + session: nil + ) + ) +} + +private func retryHTTPResponse(_ request: URLRequest) -> HTTPURLResponse { + HTTPURLResponse( + url: request.url!, + statusCode: 200, + httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json"] + )! +}