diff --git a/apps/swift-ios/App/NativeFeatureClient.swift b/apps/swift-ios/App/NativeFeatureClient.swift index 11493ef9d4..2fe5d480b9 100644 --- a/apps/swift-ios/App/NativeFeatureClient.swift +++ b/apps/swift-ios/App/NativeFeatureClient.swift @@ -2,7 +2,7 @@ import Foundation /// Composes the transport-focused Core layer with the UI-focused Features layer. @MainActor -final class NativeFeatureClient: FeatureClient { +final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging { private let runtime: EnvironmentRuntime private let settingsStore: UserDefaults private let stream: AsyncStream @@ -11,6 +11,7 @@ final class NativeFeatureClient: FeatureClient { private var activeEnvironment: Environment? private var client: T3Client? private var latestShell: OrchestrationShellSnapshot? + private var latestServerConfig: ServerConfigSnapshot? private var archivedThreads: [FeatureThread] = [] private var latestSnapshot: FeatureSnapshot? private var loadedThreadIDs = Set() @@ -23,6 +24,7 @@ final class NativeFeatureClient: FeatureClient { String: [UUID: AsyncStream.Continuation] ] = [:] private var pollingTask: Task? + private var configurationTask: Task? init( runtime: EnvironmentRuntime = EnvironmentRuntime(), @@ -37,6 +39,7 @@ final class NativeFeatureClient: FeatureClient { deinit { pollingTask?.cancel() + configurationTask?.cancel() continuation.finish() } @@ -53,7 +56,9 @@ final class NativeFeatureClient: FeatureClient { 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 latestShell = shell archivedThreads = readModel.threads .filter { $0.archivedAt != nil } @@ -88,17 +93,20 @@ final class NativeFeatureClient: FeatureClient { loadedThreadIDs.removeAll() latestDetails.removeAll() archivedThreads.removeAll() + latestServerConfig = nil 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() @@ -109,10 +117,13 @@ final class NativeFeatureClient: FeatureClient { 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() @@ -125,13 +136,16 @@ final class NativeFeatureClient: FeatureClient { func disconnect() async { pollingTask?.cancel() + configurationTask?.cancel() pollingTask = nil + configurationTask = nil if let client { await client.disconnect() } client = nil activeEnvironment = nil latestShell = nil + latestServerConfig = nil archivedThreads.removeAll() loadedThreadIDs.removeAll() latestDetails.removeAll() @@ -189,6 +203,49 @@ final class NativeFeatureClient: FeatureClient { ) } + func createThreadAndSend( + projectID: String, + prompt: String, + selection: FeatureSelection?, + runtimeMode: FeatureRuntimeMode, + interactionMode: FeatureInteractionMode, + attachments: [FeatureUploadAttachment] + ) async throws -> FeatureThread { + let client = try requireClient() + let threadID = UUID().uuidString + 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, + projectID: projectID, + title: title, + text: prompt, + model: model, + runtimeMode: coreRuntimeMode(runtimeMode), + interactionMode: coreInteractionMode(interactionMode), + attachments: uploads + ) + + let shell = try await client.shellSnapshot() + latestShell = shell + await emitSnapshot(shell) + if let created = shell.threads.first(where: { $0.id == threadID }) { + return mapThread(created) + } + return FeatureThread( + id: threadID, + projectID: projectID, + title: title, + providerID: model.instanceId, + modelID: model.model, + modelOptions: mapOptionSelections(model.options), + runtimeMode: runtimeMode, + interactionMode: interactionMode + ) + } + func renameThread(id: String, title: String) async throws { let client = try requireClient() _ = try await client.rename(threadID: id, title: title) @@ -252,32 +309,33 @@ final class NativeFeatureClient: FeatureClient { threadID: String, text: String, selection: FeatureSelection? + ) async throws { + try await sendMessage( + threadID: threadID, + text: text, + selection: selection, + attachments: [] + ) + } + + func sendMessage( + threadID: String, + text: String, + selection: FeatureSelection?, + attachments: [FeatureUploadAttachment] ) async throws { let client = try requireClient() guard let shellThread = latestShell?.threads.first(where: { $0.id == threadID }) else { throw NativeFeatureClientError.threadNotFound } - if let selection, - selection.providerID != shellThread.modelSelection.instanceId - || selection.modelID != shellThread.modelSelection.model { - _ = try await client.dispatch( - .object([ - "type": .string("thread.meta.update"), - "commandId": .string(UUID().uuidString), - "threadId": .string(threadID), - "modelSelection": try .encode( - ModelSelection(instanceId: selection.providerID, model: selection.modelID) - ), - ]) - ) - } - _ = try await client.sendTurn( threadID: threadID, text: text, runtimeMode: shellThread.runtimeMode, - interactionMode: shellThread.interactionMode + interactionMode: shellThread.interactionMode, + model: selection.map(coreModelSelection), + attachments: try makeUploadAttachments(attachments) ) try await refreshThread(id: threadID, client: client) try await refresh(client: client) @@ -329,6 +387,40 @@ final class NativeFeatureClient: FeatureClient { settingsStore.set(data, forKey: Self.settingsKey) } + func loadDeviceSessions() async throws -> [FeatureDeviceSession] { + let client = try requireClient() + try await requireScope("access:read", client: client) + return try await client.clientSessions().map { session in + FeatureDeviceSession( + sessionID: session.sessionId, + label: session.client.label, + deviceType: FeatureDeviceType(rawValue: session.client.deviceType) ?? .unknown, + operatingSystem: session.client.os, + browser: session.client.browser, + ipAddress: session.client.ipAddress, + issuedAt: parseDate(session.issuedAt), + expiresAt: parseDate(session.expiresAt), + lastConnectedAt: session.lastConnectedAt.map(parseDate), + isConnected: session.connected, + isCurrent: session.current + ) + } + } + + func revokeDeviceSession(id: String) async throws { + let client = try requireClient() + try await requireScope("access:write", client: client) + guard try await client.revokeClientSession(id: id) else { + throw NativeFeatureClientError.deviceSessionNotFound + } + } + + func revokeOtherDeviceSessions() async throws { + let client = try requireClient() + try await requireScope("access:write", client: client) + _ = try await client.revokeOtherClientSessions() + } + func listFiles(threadID: String, path: String?) async throws -> [FeatureFileEntry] { let client = try requireClient() let context = try workspaceContext(threadID: threadID) @@ -589,6 +681,7 @@ final class NativeFeatureClient: FeatureClient { private func startPolling(_ activeClient: T3Client) { pollingTask?.cancel() + configurationTask?.cancel() pollingTask = Task { [weak self] in do { await activeClient.connect() @@ -621,6 +714,29 @@ final class NativeFeatureClient: FeatureClient { } } } + configurationTask = Task { [weak self] in + do { + for try await event in await activeClient.serverConfigEvents() { + guard !Task.isCancelled, let self else { break } + switch event { + case let .snapshot(config): + self.latestServerConfig = config + case let .providerStatuses(providers): + self.latestServerConfig = ServerConfigSnapshot(providers: providers) + case .unrelated: + continue + } + if let shell = self.latestShell { + await self.emitSnapshot(shell) + } + } + } catch is CancellationError { + return + } catch { + // The shell and thread streams remain useful on older servers + // that do not expose the provider catalogue subscription. + } + } } private func consume(shell: OrchestrationShellSnapshot, client: T3Client) async { @@ -721,6 +837,7 @@ final class NativeFeatureClient: FeatureClient { id: thread.id, projectID: thread.projectId, title: thread.title, + createdAt: parseDate(thread.createdAt), updatedAt: parseDate(thread.updatedAt), state: mapThreadState( latestTurn: thread.latestTurn, @@ -730,6 +847,7 @@ final class NativeFeatureClient: FeatureClient { ), providerID: thread.modelSelection.instanceId, modelID: thread.modelSelection.model, + modelOptions: mapOptionSelections(thread.modelSelection.options), isArchived: thread.archivedAt != nil, isSettled: isSettled(thread.settledOverride, settledAt: thread.settledAt), snoozedUntil: thread.snoozedUntil.map(parseDate), @@ -744,6 +862,7 @@ final class NativeFeatureClient: FeatureClient { projectID: thread.projectId, title: thread.title, preview: thread.messages.last?.text, + createdAt: parseDate(thread.createdAt), updatedAt: parseDate(thread.updatedAt), state: mapThreadState( latestTurn: thread.latestTurn, @@ -753,6 +872,7 @@ final class NativeFeatureClient: FeatureClient { ), providerID: thread.modelSelection.instanceId, modelID: thread.modelSelection.model, + modelOptions: mapOptionSelections(thread.modelSelection.options), isArchived: thread.archivedAt != nil, isSettled: isSettled(thread.settledOverride, settledAt: thread.settledAt), snoozedUntil: thread.snoozedUntil.map(parseDate), @@ -770,7 +890,15 @@ final class NativeFeatureClient: FeatureClient { role: mapRole(message.role), text: message.text, createdAt: parseDate(message.createdAt), - state: message.streaming ? .streaming : .complete + state: message.streaming ? .streaming : .complete, + attachments: (message.attachments ?? []).map { + FeatureMessageAttachment( + id: $0.id, + name: $0.name, + mimeType: $0.mimeType, + sizeBytes: $0.sizeBytes + ) + } ) } let work = thread.activities.compactMap { activity -> FeatureMessage? in @@ -804,6 +932,7 @@ final class NativeFeatureClient: FeatureClient { projectID: thread.projectId, title: thread.title, preview: thread.messages.last?.text, + createdAt: parseDate(thread.createdAt), updatedAt: parseDate(thread.updatedAt), state: mapThreadState( latestTurn: thread.latestTurn, @@ -813,6 +942,7 @@ final class NativeFeatureClient: FeatureClient { ), providerID: thread.modelSelection.instanceId, modelID: thread.modelSelection.model, + modelOptions: mapOptionSelections(thread.modelSelection.options), isArchived: thread.archivedAt != nil, isSettled: isSettled(thread.settledOverride, settledAt: thread.settledAt), snoozedUntil: thread.snoozedUntil.map(parseDate), @@ -990,6 +1120,40 @@ final class NativeFeatureClient: FeatureClient { } private func mapProviders(_ shell: OrchestrationShellSnapshot) -> [FeatureProvider] { + if let providers = latestServerConfig?.providers, !providers.isEmpty { + return providers.map { provider in + FeatureProvider( + id: provider.instanceId, + name: provider.displayName ?? providerDisplayName(provider.driver), + isAvailable: provider.enabled + && provider.installed + && provider.status != "disabled" + && provider.auth.status != "unauthenticated" + && provider.availability != "unavailable", + driver: provider.driver, + requiresNewThreadForModelChange: + provider.requiresNewThreadForModelChange ?? false, + models: provider.models.map { model in + let options = (model.capabilities?.optionDescriptors ?? []) + .map(mapOptionDescriptor) + return FeatureModel( + id: model.slug, + name: model.name, + detail: model.subProvider ?? model.shortName, + supportsReasoning: options.contains { descriptor in + let searchable = "\(descriptor.id) \(descriptor.label)".lowercased() + return searchable.contains("reason") + || searchable.contains("effort") + || searchable.contains("thinking") + }, + isDefault: model.isDefault ?? false, + options: options + ) + } + ) + } + } + var modelsByProvider: [String: Set] = [:] for selection in shell.projects.compactMap(\.defaultModelSelection) + shell.threads.map(\.modelSelection) { @@ -1002,6 +1166,7 @@ final class NativeFeatureClient: FeatureClient { FeatureProvider( id: providerID, name: providerDisplayName(providerID), + driver: providerID, models: (modelsByProvider[providerID] ?? []).sorted().map { FeatureModel(id: $0, name: $0) } @@ -1014,7 +1179,7 @@ final class NativeFeatureClient: FeatureClient { projectID: String ) -> ModelSelection { if let selection { - return ModelSelection(instanceId: selection.providerID, model: selection.modelID) + return coreModelSelection(selection) } if let projectDefault = latestShell?.projects .first(where: { $0.id == projectID })? @@ -1026,11 +1191,84 @@ final class NativeFeatureClient: FeatureClient { private func defaultModelSelection() -> ModelSelection { if let selection = loadSettings().defaultSelection { - return ModelSelection(instanceId: selection.providerID, model: selection.modelID) + return coreModelSelection(selection) } return ModelSelection(instanceId: "codex", model: "gpt-5.6-sol") } + private func coreModelSelection(_ selection: FeatureSelection) -> ModelSelection { + let options = selection.options.map { option in + ModelSelection.OptionSelection( + id: option.id, + value: coreOptionValue(option.value) + ) + } + return ModelSelection( + instanceId: selection.providerID, + model: selection.modelID, + options: options.isEmpty ? nil : options + ) + } + + private func coreOptionValue(_ value: FeatureModelOptionValue) -> JSONValue { + switch value { + case let .string(rawValue): + return .string(rawValue) + case let .boolean(rawValue): + return .bool(rawValue) + } + } + + private func mapOptionSelections( + _ selections: [ModelSelection.OptionSelection]? + ) -> [FeatureModelOptionSelection] { + (selections ?? []).compactMap { selection in + let value: FeatureModelOptionValue + switch selection.value { + case let .string(rawValue): + value = .string(rawValue) + case let .bool(rawValue): + value = .boolean(rawValue) + default: + return nil + } + return FeatureModelOptionSelection(id: selection.id, value: value) + } + } + + private func mapOptionDescriptor( + _ descriptor: ServerProviderOptionDescriptor + ) -> FeatureModelOptionDescriptor { + switch descriptor { + case let .select(value): + let defaultValue = value.currentValue + ?? value.options.first(where: { $0.isDefault == true })?.id + return FeatureModelOptionDescriptor( + id: value.id, + label: value.label, + detail: value.description, + kind: .select, + choices: value.options.map { + FeatureModelOptionChoice( + id: $0.id, + label: $0.label, + detail: $0.description, + isDefault: $0.isDefault ?? false + ) + }, + defaultValue: defaultValue.map(FeatureModelOptionValue.string) + ) + case let .boolean(value): + return FeatureModelOptionDescriptor( + id: value.id, + label: value.label, + detail: value.description, + kind: .boolean, + defaultValue: value.currentValue.map(FeatureModelOptionValue.boolean) + ) + } + } + private func providerDisplayName(_ id: String) -> String { switch id { case "codex": "Codex" @@ -1042,6 +1280,39 @@ final class NativeFeatureClient: FeatureClient { } } + private func makeUploadAttachments( + _ attachments: [FeatureUploadAttachment] + ) throws -> [UploadChatImageAttachment] { + guard attachments.count <= 8 else { + throw NativeFeatureClientError.tooManyAttachments + } + return try attachments.map { + try UploadChatImageAttachment( + data: $0.data, + name: $0.name, + mimeType: $0.mimeType + ) + } + } + + private func requireScope(_ scope: String, client: T3Client) async throws { + let session = try await client.authSession() + guard session.scopes?.contains(scope) == true else { + throw NativeFeatureClientError.missingScope(scope) + } + } + + private static func title(from prompt: String, hasAttachments: Bool) -> String { + let compact = prompt + .split(whereSeparator: \.isWhitespace) + .joined(separator: " ") + guard !compact.isEmpty else { + return hasAttachments ? "Image task" : "New thread" + } + guard compact.count > 72 else { return compact } + return "\(compact.prefix(69).trimmingCharacters(in: .whitespacesAndNewlines))..." + } + private func loadSettings() -> FeatureSettings { guard let data = settingsStore.data(forKey: Self.settingsKey), let settings = try? JSONDecoder().decode(FeatureSettings.self, from: data) else { @@ -1073,6 +1344,9 @@ private enum NativeFeatureClientError: LocalizedError { case inputRequestNotFound case invalidProjectPath case terminalNotOpen + case deviceSessionNotFound + case missingScope(String) + case tooManyAttachments var errorDescription: String? { switch self { @@ -1083,6 +1357,9 @@ private enum NativeFeatureClientError: LocalizedError { case .inputRequestNotFound: "The input request is no longer active." case .invalidProjectPath: "Enter a workspace path on the connected environment." case .terminalNotOpen: "Open the terminal before sending input." + case .deviceSessionNotFound: "That device session is no longer active." + case .missingScope: "This connection does not have permission to manage devices." + case .tooManyAttachments: "You can attach up to 8 images per message." } } } diff --git a/apps/swift-ios/Features/Chat/FeatureComposerView.swift b/apps/swift-ios/Features/Chat/FeatureComposerView.swift index 8c3fc1a20d..6cac31d62a 100644 --- a/apps/swift-ios/Features/Chat/FeatureComposerView.swift +++ b/apps/swift-ios/Features/Chat/FeatureComposerView.swift @@ -3,7 +3,9 @@ import SwiftUI struct FeatureComposerView: View { @Binding var text: String @Binding var selection: FeatureSelection? + @Binding var attachments: [FeatureDraftAttachment] let providers: [FeatureProvider] + let threadSelection: FeatureSelection? let isSending: Bool let isWorking: Bool let focused: FocusState.Binding @@ -11,8 +13,20 @@ struct FeatureComposerView: View { let onStop: () -> Void var body: some View { - VStack(spacing: 8) { + VStack(spacing: 7) { + FeatureAttachmentStrip(attachments: $attachments) + HStack(alignment: .bottom, spacing: 9) { + FeatureImageAttachmentPicker( + attachments: $attachments, + isEnabled: DailyUXModelOptions.supportsImages( + selection: selection, + providers: providers + ) + ) + .padding(.leading, 2) + .padding(.bottom, 1) + TextField("Message agent", text: $text, axis: .vertical) .lineLimit(1...7) .focused(focused) @@ -20,8 +34,7 @@ struct FeatureComposerView: View { .onSubmit { if canSend { onSend() } } - .padding(.leading, 12) - .padding(.vertical, 10) + .padding(.vertical, 11) Button(action: isWorking && textIsEmpty ? onStop : onSend) { Image(systemName: isWorking && textIsEmpty ? "stop.fill" : "arrow.up") @@ -35,18 +48,29 @@ struct FeatureComposerView: View { .padding(.bottom, 7) .accessibilityLabel(isWorking && textIsEmpty ? "Stop agent" : "Send") } - .background(Color.white.opacity(0.09), in: RoundedRectangle(cornerRadius: 16)) + .background(T3Colors.input, in: RoundedRectangle(cornerRadius: 18)) .overlay { - RoundedRectangle(cornerRadius: 16) - .stroke(Color.white.opacity(0.14), lineWidth: 1) + RoundedRectangle(cornerRadius: 18) + .stroke(T3Colors.border, lineWidth: 1) } HStack { - CompactModelMenu(providers: providers, selection: $selection) + ProviderModelPicker( + providers: providers, + selection: $selection, + style: .compact, + threadSelection: threadSelection + ) Spacer() - Text("Return to send") - .font(.caption2) - .foregroundStyle(.tertiary) + if !attachments.isEmpty, !imagesAllowed { + Text("Choose an image model") + .font(.caption2) + .foregroundStyle(T3Colors.warning) + } else if !attachments.isEmpty { + Text("\(attachments.count) image\(attachments.count == 1 ? "" : "s")") + .font(.caption2.monospacedDigit()) + .foregroundStyle(T3Colors.textTertiary) + } } .padding(.horizontal, 3) } @@ -64,51 +88,12 @@ struct FeatureComposerView: View { } private var canSend: Bool { - !textIsEmpty && !isSending - } -} - -private struct CompactModelMenu: View { - let providers: [FeatureProvider] - @Binding var selection: FeatureSelection? - - var body: some View { - Menu { - ForEach(providers.filter(\.isAvailable)) { provider in - Section(provider.name) { - ForEach(provider.models) { model in - Button { - selection = .init(providerID: provider.id, modelID: model.id) - } label: { - if selection?.providerID == provider.id, selection?.modelID == model.id { - Label(model.name, systemImage: "checkmark") - } else { - Text(model.name) - } - } - } - } - } - } label: { - HStack(spacing: 5) { - Image(systemName: "cpu") - Text(label) - Image(systemName: "chevron.down") - .font(.system(size: 8, weight: .bold)) - } - .font(.caption.weight(.medium)) - .foregroundStyle(.secondary) - .contentShape(Rectangle()) - } - .accessibilityLabel("Choose model") - } - - private var label: String { - guard let selection, - let provider = providers.first(where: { $0.id == selection.providerID }), - let model = provider.models.first(where: { $0.id == selection.modelID }) else { - return "Automatic" - } - return model.name + (!textIsEmpty || !attachments.isEmpty) + && (attachments.isEmpty || imagesAllowed) + && !isSending + } + + private var imagesAllowed: Bool { + DailyUXModelOptions.supportsImages(selection: selection, providers: providers) } } diff --git a/apps/swift-ios/Features/Chat/ImageAttachmentViews.swift b/apps/swift-ios/Features/Chat/ImageAttachmentViews.swift new file mode 100644 index 0000000000..f60ab53c87 --- /dev/null +++ b/apps/swift-ios/Features/Chat/ImageAttachmentViews.swift @@ -0,0 +1,197 @@ +import PhotosUI +import SwiftUI +import UniformTypeIdentifiers +import UIKit + +struct FeatureImageAttachmentPicker: View { + @Binding var attachments: [FeatureDraftAttachment] + let maximumCount: Int + let isEnabled: Bool + + @State private var selection: [PhotosPickerItem] = [] + @State private var isLoading = false + @State private var errorMessage: String? + + init( + attachments: Binding<[FeatureDraftAttachment]>, + maximumCount: Int = 8, + isEnabled: Bool = true + ) { + _attachments = attachments + self.maximumCount = maximumCount + self.isEnabled = isEnabled + } + + var body: some View { + PhotosPicker( + selection: $selection, + maxSelectionCount: max(1, maximumCount - attachments.count), + matching: .images + ) { + Image(systemName: isLoading ? "ellipsis" : "photo") + .font(.system(size: 17, weight: .medium)) + .foregroundStyle(T3Colors.textSecondary) + .frame(width: T3Metrics.minimumTapTarget, height: T3Metrics.minimumTapTarget) + .contentShape(Rectangle()) + } + .disabled(!isEnabled || isLoading || attachments.count >= maximumCount) + .opacity(isEnabled ? 1 : 0.3) + .accessibilityLabel(isLoading ? "Adding images" : "Add images") + .accessibilityHint(isEnabled ? "" : "The selected model does not accept images") + .onChange(of: selection) { + loadSelection() + } + .alert( + "Couldn’t add image", + isPresented: Binding( + get: { errorMessage != nil }, + set: { if !$0 { errorMessage = nil } } + ) + ) { + Button("OK") { errorMessage = nil } + } message: { + Text(errorMessage ?? "") + } + } + + private func loadSelection() { + let items = selection + guard !items.isEmpty else { return } + selection = [] + isLoading = true + + Task { + defer { isLoading = false } + for item in items.prefix(maximumCount - attachments.count) { + do { + 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 + ) + attachments.append(attachment) + } catch { + errorMessage = error.localizedDescription + break + } + } + } + } +} + +struct FeatureAttachmentStrip: View { + @Binding var attachments: [FeatureDraftAttachment] + + var body: some View { + if !attachments.isEmpty { + ScrollView(.horizontal) { + HStack(spacing: 8) { + ForEach(attachments) { attachment in + FeatureAttachmentThumbnail(attachment: attachment) { + attachments.removeAll { $0.id == attachment.id } + } + } + } + .padding(.horizontal, 1) + } + .scrollIndicators(.hidden) + .accessibilityLabel("\(attachments.count) image attachments") + } + } +} + +private struct FeatureAttachmentThumbnail: View { + let attachment: FeatureDraftAttachment + let onRemove: () -> Void + + var body: some View { + ZStack(alignment: .topTrailing) { + Group { + if let image = UIImage(data: attachment.data) { + Image(uiImage: image) + .resizable() + .scaledToFill() + } else { + Image(systemName: "photo") + .foregroundStyle(T3Colors.textSecondary) + } + } + .frame(width: 66, height: 66) + .background(T3Colors.surface) + .clipShape(RoundedRectangle(cornerRadius: 9)) + + Button(action: onRemove) { + Image(systemName: "xmark") + .font(.system(size: 9, weight: .bold)) + .foregroundStyle(.white) + .frame(width: 22, height: 22) + .background(.black.opacity(0.78), in: Circle()) + } + .offset(x: 5, y: -5) + .accessibilityLabel("Remove \(attachment.filename)") + } + .padding(.top, 5) + .padding(.trailing, 5) + } +} + +enum FeatureImageProcessor { + private static let maximumDimension: CGFloat = 2_048 + private static let maximumEncodedBytes = 10 * 1_024 * 1_024 + + static func attachment( + from sourceData: Data, + sourceType _: UTType, + ordinal: Int + ) throws -> FeatureDraftAttachment { + guard let sourceImage = UIImage(data: sourceData) else { + throw FeatureImageAttachmentError.invalidImage + } + + let image = resized(sourceImage) + guard let data = image.jpegData(compressionQuality: 0.82) else { + throw FeatureImageAttachmentError.encodingFailed + } + guard data.count <= maximumEncodedBytes else { + throw FeatureImageAttachmentError.tooLarge + } + + return FeatureDraftAttachment( + data: data, + filename: "Image \(ordinal).jpg", + mimeType: "image/jpeg" + ) + } + + private static func resized(_ image: UIImage) -> UIImage { + 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) + return renderer.image { _ in + image.draw(in: CGRect(origin: .zero, size: size)) + } + } +} + +enum FeatureImageAttachmentError: LocalizedError { + case invalidImage + case encodingFailed + case tooLarge + + var errorDescription: String? { + switch self { + case .invalidImage: + "That photo could not be read." + case .encodingFailed: + "That photo could not be prepared." + case .tooLarge: + "Images must be smaller than 10 MB." + } + } +} diff --git a/apps/swift-ios/Features/Chat/ThreadDetailView.swift b/apps/swift-ios/Features/Chat/ThreadDetailView.swift index 58c66a62d6..3026ba373d 100644 --- a/apps/swift-ios/Features/Chat/ThreadDetailView.swift +++ b/apps/swift-ios/Features/Chat/ThreadDetailView.swift @@ -3,17 +3,25 @@ import SwiftUI public struct ThreadDetailView: View { @Bindable var model: FeatureRootModel let thread: FeatureThread + let submitMessage: (FeatureMessageSubmission) async -> Bool @State private var draft = "" @State private var selection: FeatureSelection? + @State private var attachments: [FeatureDraftAttachment] = [] @State private var isSending = false @State private var isLoading = true + @State private var sendFailed = false @State private var toolSurface: FeatureThreadToolSurface? @FocusState private var composerFocused: Bool - public init(model: FeatureRootModel, thread: FeatureThread) { + public init( + model: FeatureRootModel, + thread: FeatureThread, + submitMessage: @escaping (FeatureMessageSubmission) async -> Bool + ) { self.model = model self.thread = thread + self.submitMessage = submitMessage } public var body: some View { @@ -143,6 +151,11 @@ public struct ThreadDetailView: View { .presentationDetents([.large]) .presentationDragIndicator(.visible) } + .alert("Message not sent", isPresented: $sendFailed) { + Button("OK") {} + } message: { + Text("Your draft is still here. Check your connection and try again.") + } } private var detail: FeatureThreadDetail? { @@ -158,7 +171,21 @@ public struct ThreadDetailView: View { let modelID = detail?.thread.modelID ?? thread.modelID else { return model.snapshot.settings.defaultSelection } - return FeatureSelection(providerID: providerID, modelID: modelID) + if let defaultSelection = model.snapshot.settings.defaultSelection, + defaultSelection.providerID == providerID, + defaultSelection.modelID == modelID { + return defaultSelection + } + let provider = model.snapshot.providers.first { $0.id == providerID } + let featureModel = provider?.models.first { $0.id == modelID } + let savedOptions = detail?.thread.modelOptions ?? thread.modelOptions + return FeatureSelection( + providerID: providerID, + modelID: modelID, + options: savedOptions.isEmpty + ? featureModel.map(DailyUXModelOptions.defaults) ?? [] + : savedOptions + ) } private func timeline(_ detail: FeatureThreadDetail) -> some View { @@ -217,7 +244,9 @@ public struct ThreadDetailView: View { FeatureComposerView( text: $draft, selection: $selection, + attachments: $attachments, providers: model.snapshot.providers, + threadSelection: currentSelection, isSending: isSending, isWorking: detail.thread.state == .working || detail.thread.state == .queued, focused: $composerFocused, @@ -232,17 +261,27 @@ public struct ThreadDetailView: View { private func send() { let message = draft - guard !message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } + let pendingAttachments = attachments + guard !message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + || !pendingAttachments.isEmpty else { + return + } draft = "" + attachments = [] isSending = true Task { - let sent = await model.sendMessage( + let sent = await submitMessage( + FeatureMessageSubmission( threadID: thread.id, text: message, - selection: selection + selection: selection, + attachments: pendingAttachments + ) ) if !sent { draft = message + attachments = pendingAttachments + sendFailed = true } isSending = false composerFocused = true @@ -363,11 +402,16 @@ struct FeatureMessageView: View { case .user: HStack { Spacer(minLength: 34) - Text(.init(message.text)) - .textSelection(.enabled) - .padding(.horizontal, 13) - .padding(.vertical, 10) - .background(Color.white.opacity(0.11), in: RoundedRectangle(cornerRadius: 15)) + VStack(alignment: .leading, spacing: 8) { + FeatureMessageAttachmentsView(attachments: message.attachments) + if !message.text.isEmpty { + Text(.init(message.text)) + .textSelection(.enabled) + } + } + .padding(.horizontal, 13) + .padding(.vertical, 10) + .background(Color.white.opacity(0.11), in: RoundedRectangle(cornerRadius: 15)) } .accessibilityLabel("You") .accessibilityValue(message.text) @@ -379,9 +423,12 @@ struct FeatureMessageView: View { } .font(.caption.weight(.semibold)) .foregroundStyle(.secondary) - Text(.init(message.text)) - .textSelection(.enabled) - .lineSpacing(3) + FeatureMessageAttachmentsView(attachments: message.attachments) + if !message.text.isEmpty { + Text(.init(message.text)) + .textSelection(.enabled) + .lineSpacing(3) + } } .frame(maxWidth: .infinity, alignment: .leading) case .tool: @@ -406,6 +453,47 @@ struct FeatureMessageView: View { } } +private struct FeatureMessageAttachmentsView: View { + let attachments: [FeatureMessageAttachment] + + var body: some View { + if !attachments.isEmpty { + LazyVGrid( + columns: [ + GridItem(.adaptive(minimum: 118, maximum: 190), spacing: 7), + ], + alignment: .leading, + spacing: 7 + ) { + ForEach(attachments) { attachment in + 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)) + .font(.caption2.monospacedDigit()) + .foregroundStyle(T3Colors.textSecondary) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(7) + .overlay { + RoundedRectangle(cornerRadius: 8) + .stroke(T3Colors.border, lineWidth: 1) + } + .accessibilityElement(children: .combine) + } + } + } + } +} + struct StreamingStatusView: View { let state: FeatureThreadState let onStop: () -> Void diff --git a/apps/swift-ios/Features/Root/FeatureRootModel.swift b/apps/swift-ios/Features/Root/FeatureRootModel.swift index c85c4dce40..a474240ad9 100644 --- a/apps/swift-ios/Features/Root/FeatureRootModel.swift +++ b/apps/swift-ios/Features/Root/FeatureRootModel.swift @@ -91,6 +91,26 @@ public final class FeatureRootModel { return succeeded ? created : nil } + public func startTask(_ request: NewTaskRequest) async -> FeatureThread? { + let prompt = request.trimmedPrompt + guard !prompt.isEmpty || !request.attachments.isEmpty else { return nil } + + var created: FeatureThread? + let succeeded = await perform { + let thread = try await client.createThreadAndSend( + projectID: request.projectID, + prompt: prompt, + selection: request.selection, + runtimeMode: request.runtimeMode, + interactionMode: request.interactionMode, + attachments: request.attachments.map(\.upload) + ) + upsert(thread) + created = thread + } + return succeeded ? created : nil + } + public func renameThread(_ id: String, title: String) async { await perform { try await client.renameThread(id: id, title: title) @@ -169,19 +189,48 @@ public final class FeatureRootModel { } public func sendMessage(threadID: String, text: String, selection: FeatureSelection?) async -> Bool { - let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return false } - - return await perform { - let optimistic = FeatureMessage( - id: "local-\(UUID().uuidString)", - role: .user, - text: trimmed, - state: .queued + await sendMessage( + FeatureMessageSubmission( + threadID: threadID, + text: text, + selection: selection + ) + ) + } + + public func sendMessage(_ submission: FeatureMessageSubmission) async -> Bool { + let trimmed = submission.text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty || !submission.attachments.isEmpty else { return false } + + let optimisticID = "local-\(UUID().uuidString)" + let optimistic = FeatureMessage( + id: optimisticID, + role: .user, + text: trimmed, + state: .queued, + attachments: submission.attachments.map { + FeatureMessageAttachment( + id: $0.id.uuidString, + name: $0.filename, + mimeType: $0.mimeType, + sizeBytes: $0.byteCount + ) + } + ) + details[submission.threadID]?.messages.append(optimistic) + + let sent = await perform { + try await client.sendMessage( + threadID: submission.threadID, + text: trimmed, + selection: submission.selection, + attachments: submission.attachments.map(\.upload) ) - details[threadID]?.messages.append(optimistic) - try await client.sendMessage(threadID: threadID, text: trimmed, selection: selection) } + if !sent { + details[submission.threadID]?.messages.removeAll { $0.id == optimisticID } + } + return sent } public func cancelTurn(threadID: String) async { @@ -223,11 +272,21 @@ public final class FeatureRootModel { try await operation() return true } catch { - errorMessage = error.localizedDescription + if !Self.isBenignCancellation(error) { + errorMessage = error.localizedDescription + } return false } } + private static func isBenignCancellation(_ error: any Error) -> Bool { + if error is CancellationError { return true } + let message = error.localizedDescription + .trimmingCharacters(in: .whitespacesAndNewlines) + .lowercased() + return message == "cancelled" || message == "canceled" + } + private func apply(_ event: FeatureEvent) { switch event { case let .snapshot(value): @@ -258,3 +317,9 @@ public final class FeatureRootModel { } } } + +private extension FeatureDraftAttachment { + var upload: FeatureUploadAttachment { + FeatureUploadAttachment(data: data, name: filename, mimeType: mimeType) + } +} diff --git a/apps/swift-ios/Features/Root/FeatureRootView.swift b/apps/swift-ios/Features/Root/FeatureRootView.swift index ff2e51059e..48adc2bbfe 100644 --- a/apps/swift-ios/Features/Root/FeatureRootView.swift +++ b/apps/swift-ios/Features/Root/FeatureRootView.swift @@ -12,7 +12,15 @@ public struct FeatureRootView: View { if model.isLoading { FeatureLoadingView() } else if model.snapshot.connection.state == .connected { - WorkspaceView(model: model) + WorkspaceView( + model: model, + submitNewTask: { request in + await model.startTask(request) + }, + submitMessage: { submission in + await model.sendMessage(submission) + } + ) } else { ConnectionOnboardingView(model: model) } diff --git a/apps/swift-ios/Features/Shared/FeatureClient.swift b/apps/swift-ios/Features/Shared/FeatureClient.swift index e06d9ddcb2..fdc595ad35 100644 --- a/apps/swift-ios/Features/Shared/FeatureClient.swift +++ b/apps/swift-ios/Features/Shared/FeatureClient.swift @@ -14,6 +14,14 @@ public protocol FeatureClient: AnyObject { func addProject(path: String) async throws func createThread(projectID: String, title: String?, selection: FeatureSelection?) async throws -> FeatureThread + func createThreadAndSend( + projectID: String, + prompt: String, + selection: FeatureSelection?, + runtimeMode: FeatureRuntimeMode, + interactionMode: FeatureInteractionMode, + attachments: [FeatureUploadAttachment] + ) async throws -> FeatureThread func renameThread(id: String, title: String) async throws func setThreadArchived(id: String, archived: Bool) async throws func setThreadSettled(id: String, settled: Bool) async throws @@ -24,6 +32,12 @@ public protocol FeatureClient: AnyObject { func loadThread(id: String) async throws -> FeatureThreadDetail func sendMessage(threadID: String, text: String, selection: FeatureSelection?) async throws + func sendMessage( + threadID: String, + text: String, + selection: FeatureSelection?, + attachments: [FeatureUploadAttachment] + ) async throws func cancelTurn(threadID: String) async throws func resolveApproval(id: String, decision: FeatureApprovalDecision) async throws func resolveUserInput(id: String, answers: [String: String]) async throws @@ -64,6 +78,40 @@ public extension FeatureClient { func setRuntimeMode(id: String, mode: FeatureRuntimeMode) async throws {} func setInteractionMode(id: String, mode: FeatureInteractionMode) async throws {} + func createThreadAndSend( + projectID: String, + prompt: String, + selection: FeatureSelection?, + runtimeMode: FeatureRuntimeMode, + interactionMode: FeatureInteractionMode, + attachments: [FeatureUploadAttachment] + ) async throws -> FeatureThread { + let thread = try await createThread( + projectID: projectID, + title: prompt, + selection: selection + ) + try await sendMessage( + threadID: thread.id, + text: prompt, + selection: selection, + attachments: attachments + ) + return thread + } + + func sendMessage( + threadID: String, + text: String, + selection: FeatureSelection?, + attachments: [FeatureUploadAttachment] + ) async throws { + guard attachments.isEmpty else { + throw FeatureCapabilityUnavailable("Image attachments") + } + try await sendMessage(threadID: threadID, text: text, selection: selection) + } + func listFiles(threadID: String, path: String?) async throws -> [FeatureFileEntry] { throw FeatureCapabilityUnavailable("Files") } diff --git a/apps/swift-ios/Features/Shared/FeatureModels.swift b/apps/swift-ios/Features/Shared/FeatureModels.swift index 05edbc9fe2..8c5db5c2cc 100644 --- a/apps/swift-ios/Features/Shared/FeatureModels.swift +++ b/apps/swift-ios/Features/Shared/FeatureModels.swift @@ -83,10 +83,12 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl public var projectID: String public var title: String public var preview: String? + public var createdAt: Date public var updatedAt: Date public var state: FeatureThreadState public var providerID: String? public var modelID: String? + public var modelOptions: [FeatureModelOptionSelection] public var isArchived: Bool public var isSettled: Bool public var snoozedUntil: Date? @@ -98,10 +100,12 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl projectID: String, title: String, preview: String? = nil, + createdAt: Date = .now, updatedAt: Date = .now, state: FeatureThreadState = .idle, providerID: String? = nil, modelID: String? = nil, + modelOptions: [FeatureModelOptionSelection] = [], isArchived: Bool = false, isSettled: Bool = false, snoozedUntil: Date? = nil, @@ -112,10 +116,12 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl self.projectID = projectID self.title = title self.preview = preview + self.createdAt = createdAt self.updatedAt = updatedAt self.state = state self.providerID = providerID self.modelID = modelID + self.modelOptions = modelOptions self.isArchived = isArchived self.isSettled = isSettled self.snoozedUntil = snoozedUntil @@ -138,6 +144,40 @@ public enum FeatureMessageState: String, Sendable, Codable { case failed } +public struct FeatureMessageAttachment: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var name: String + public var mimeType: String + public var sizeBytes: Int + public var url: URL? + + public init( + id: String, + name: String, + mimeType: String, + sizeBytes: Int, + url: URL? = nil + ) { + self.id = id + self.name = name + self.mimeType = mimeType + self.sizeBytes = sizeBytes + self.url = url + } +} + +public struct FeatureUploadAttachment: Sendable, Equatable { + public var data: Data + public var name: String + public var mimeType: String + + public init(data: Data, name: String, mimeType: String) { + self.data = data + self.name = name + self.mimeType = mimeType + } +} + public struct FeatureMessage: Identifiable, Sendable, Equatable, Hashable, Codable { public let id: String public var role: FeatureMessageRole @@ -145,6 +185,7 @@ public struct FeatureMessage: Identifiable, Sendable, Equatable, Hashable, Codab public var createdAt: Date public var state: FeatureMessageState public var toolName: String? + public var attachments: [FeatureMessageAttachment] public init( id: String, @@ -152,7 +193,8 @@ public struct FeatureMessage: Identifiable, Sendable, Equatable, Hashable, Codab text: String, createdAt: Date = .now, state: FeatureMessageState = .complete, - toolName: String? = nil + toolName: String? = nil, + attachments: [FeatureMessageAttachment] = [] ) { self.id = id self.role = role @@ -160,6 +202,7 @@ public struct FeatureMessage: Identifiable, Sendable, Equatable, Hashable, Codab self.createdAt = createdAt self.state = state self.toolName = toolName + self.attachments = attachments } } @@ -256,19 +299,121 @@ public struct FeatureModel: Identifiable, Sendable, Equatable, Hashable, Codable public var detail: String? public var supportsImages: Bool public var supportsReasoning: Bool + public var isDefault: Bool + public var options: [FeatureModelOptionDescriptor] public init( id: String, name: String, detail: String? = nil, supportsImages: Bool = false, - supportsReasoning: Bool = false + supportsReasoning: Bool = false, + isDefault: Bool = false, + options: [FeatureModelOptionDescriptor] = [] ) { self.id = id self.name = name self.detail = detail self.supportsImages = supportsImages self.supportsReasoning = supportsReasoning + self.isDefault = isDefault + self.options = options + } +} + +public enum FeatureModelOptionKind: String, Sendable, Equatable, Hashable, Codable { + case select + case boolean +} + +public struct FeatureModelOptionChoice: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var label: String + public var detail: String? + public var isDefault: Bool + + public init( + id: String, + label: String, + detail: String? = nil, + isDefault: Bool = false + ) { + self.id = id + self.label = label + self.detail = detail + self.isDefault = isDefault + } +} + +public struct FeatureModelOptionDescriptor: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var label: String + public var detail: String? + public var kind: FeatureModelOptionKind + public var choices: [FeatureModelOptionChoice] + public var defaultValue: FeatureModelOptionValue? + + public init( + id: String, + label: String, + detail: String? = nil, + kind: FeatureModelOptionKind, + choices: [FeatureModelOptionChoice] = [], + defaultValue: FeatureModelOptionValue? = nil + ) { + self.id = id + self.label = label + self.detail = detail + self.kind = kind + self.choices = choices + self.defaultValue = defaultValue + } +} + +public enum FeatureModelOptionValue: Sendable, Equatable, Hashable, Codable { + case string(String) + case boolean(Bool) + + private enum CodingKeys: String, CodingKey { + case type + case value + } + + private enum ValueType: String, Codable { + case string + case boolean + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + switch try container.decode(ValueType.self, forKey: .type) { + case .string: + self = try .string(container.decode(String.self, forKey: .value)) + case .boolean: + self = try .boolean(container.decode(Bool.self, forKey: .value)) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + switch self { + case let .string(value): + try container.encode(ValueType.string, forKey: .type) + try container.encode(value, forKey: .value) + case let .boolean(value): + try container.encode(ValueType.boolean, forKey: .type) + try container.encode(value, forKey: .value) + } + } +} + +public struct FeatureModelOptionSelection: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: String + public var value: FeatureModelOptionValue + + public init(id: String, value: FeatureModelOptionValue) { + self.id = id + self.value = value } } @@ -276,12 +421,23 @@ public struct FeatureProvider: Identifiable, Sendable, Equatable, Hashable, Coda public let id: String public var name: String public var isAvailable: Bool + public var driver: String + public var requiresNewThreadForModelChange: Bool public var models: [FeatureModel] - public init(id: String, name: String, isAvailable: Bool = true, models: [FeatureModel] = []) { + public init( + id: String, + name: String, + isAvailable: Bool = true, + driver: String = "", + requiresNewThreadForModelChange: Bool = false, + models: [FeatureModel] = [] + ) { self.id = id self.name = name self.isAvailable = isAvailable + self.driver = driver + self.requiresNewThreadForModelChange = requiresNewThreadForModelChange self.models = models } } @@ -289,10 +445,16 @@ public struct FeatureProvider: Identifiable, Sendable, Equatable, Hashable, Coda public struct FeatureSelection: Sendable, Equatable, Hashable, Codable { public var providerID: String public var modelID: String + public var options: [FeatureModelOptionSelection] - public init(providerID: String, modelID: String) { + public init( + providerID: String, + modelID: String, + options: [FeatureModelOptionSelection] = [] + ) { self.providerID = providerID self.modelID = modelID + self.options = options } } diff --git a/apps/swift-ios/Features/Workspace/DailyUXModels.swift b/apps/swift-ios/Features/Workspace/DailyUXModels.swift new file mode 100644 index 0000000000..279c55dc38 --- /dev/null +++ b/apps/swift-ios/Features/Workspace/DailyUXModels.swift @@ -0,0 +1,312 @@ +import Foundation + +public struct FeatureDraftAttachment: Identifiable, Sendable, Equatable { + public let id: UUID + public var data: Data + public var filename: String + public var mimeType: String + + public init( + id: UUID = UUID(), + data: Data, + filename: String, + mimeType: String + ) { + self.id = id + self.data = data + self.filename = filename + self.mimeType = mimeType + } + + public var byteCount: Int { + data.count + } +} + +public struct NewTaskRequest: Sendable, Equatable { + public var projectID: String + public var prompt: String + public var selection: FeatureSelection? + public var runtimeMode: FeatureRuntimeMode + public var interactionMode: FeatureInteractionMode + public var attachments: [FeatureDraftAttachment] + + public init( + projectID: String, + prompt: String, + selection: FeatureSelection?, + runtimeMode: FeatureRuntimeMode, + interactionMode: FeatureInteractionMode, + attachments: [FeatureDraftAttachment] = [] + ) { + self.projectID = projectID + self.prompt = prompt + self.selection = selection + self.runtimeMode = runtimeMode + self.interactionMode = interactionMode + self.attachments = attachments + } + + public var trimmedPrompt: String { + prompt.trimmingCharacters(in: .whitespacesAndNewlines) + } +} + +public struct FeatureMessageSubmission: Sendable, Equatable { + public var threadID: String + public var text: String + public var selection: FeatureSelection? + public var attachments: [FeatureDraftAttachment] + + public init( + threadID: String, + text: String, + selection: FeatureSelection?, + attachments: [FeatureDraftAttachment] = [] + ) { + self.threadID = threadID + self.text = text + self.selection = selection + self.attachments = attachments + } +} + +struct DailyUXSidebarIndex { + let active: [FeatureThread] + let settled: [FeatureThread] + let searchResults: [FeatureThread] + + init( + snapshot: FeatureSnapshot, + query: String, + projectID: String? = nil, + now: Date = .now + ) { + 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 + } + + active = visible + .filter { !$0.isEffectivelySettled(at: now) } + .sorted { lhs, rhs in + if lhs.createdAt != rhs.createdAt { + return lhs.createdAt > rhs.createdAt + } + return lhs.id < rhs.id + } + + settled = visible + .filter { $0.isEffectivelySettled(at: now) } + .sorted { lhs, rhs in + if lhs.updatedAt != rhs.updatedAt { + return lhs.updatedAt > rhs.updatedAt + } + return lhs.id < rhs.id + } + + let normalizedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !normalizedQuery.isEmpty else { + searchResults = [] + return + } + + searchResults = (active + settled).filter { thread in + let project = projectByID[thread.projectID] + return [ + thread.title, + thread.preview ?? "", + project?.name ?? "", + project?.path ?? "", + ].contains { $0.localizedCaseInsensitiveContains(normalizedQuery) } + } + } +} + +extension FeatureThread { + var needsAttention: Bool { + state == .waitingForApproval || state == .waitingForInput || state == .failed + } + + func isEffectivelySettled(at now: Date) -> Bool { + switch state { + case .queued, .working, .waitingForApproval, .waitingForInput, .failed: + return false + case .idle, .completed: + break + } + if isSettled { + return true + } + return now.timeIntervalSince(updatedAt) >= 3 * 24 * 60 * 60 + } +} + +struct DailyUXModelOption: Identifiable, Equatable, Hashable { + let provider: FeatureProvider + let model: FeatureModel + + var id: String { Self.key(providerID: provider.id, modelID: model.id) } + + static func key(providerID: String, modelID: String) -> String { + "\(providerID)::\(modelID)" + } +} + +struct DailyUXModelCatalog { + let all: [DailyUXModelOption] + let favorites: [DailyUXModelOption] + let recents: [DailyUXModelOption] + let providerGroups: [(provider: FeatureProvider, models: [DailyUXModelOption])] + + init( + providers: [FeatureProvider], + query: String, + favoriteIDs: Set, + recentIDs: [String] + ) { + let available = providers.filter(\.isAvailable) + let unfiltered = available.flatMap { provider in + provider.models.map { DailyUXModelOption(provider: provider, model: $0) } + } + let normalizedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines) + let matches = normalizedQuery.isEmpty + ? unfiltered + : unfiltered.filter { option in + [ + option.provider.name, + option.model.name, + option.model.id, + option.model.detail ?? "", + option.model.supportsImages ? "images vision" : "", + option.model.supportsReasoning ? "reasoning thinking" : "", + ].contains { $0.localizedCaseInsensitiveContains(normalizedQuery) } + } + + all = matches + favorites = matches.filter { favoriteIDs.contains($0.id) } + + let byID = Dictionary(uniqueKeysWithValues: matches.map { ($0.id, $0) }) + recents = recentIDs.compactMap { byID[$0] }.filter { !favoriteIDs.contains($0.id) } + + providerGroups = available.compactMap { provider in + let options = matches.filter { $0.provider.id == provider.id } + return options.isEmpty ? nil : (provider, options) + } + } +} + +enum DailyUXModelOptions { + static func validated( + _ selection: FeatureSelection?, + in providers: [FeatureProvider] + ) -> FeatureSelection? { + guard let selection, + let provider = providers.first(where: { + $0.id == selection.providerID && $0.isAvailable + }), + provider.models.contains(where: { $0.id == selection.modelID }) else { + return nil + } + return selection + } + + static func preferredSelection(in providers: [FeatureProvider]) -> FeatureSelection? { + let available = providers.filter(\.isAvailable) + let preferred = available.lazy.compactMap { provider in + provider.models.first(where: \.isDefault).map { (provider, $0) } + }.first + ?? available.first.flatMap { provider in + provider.models.first.map { (provider, $0) } + } + guard let (provider, model) = preferred else { return nil } + return FeatureSelection( + providerID: provider.id, + modelID: model.id, + options: defaults(for: model) + ) + } + + static func defaults(for model: FeatureModel) -> [FeatureModelOptionSelection] { + model.options.compactMap { descriptor in + if let defaultValue = descriptor.defaultValue { + return FeatureModelOptionSelection(id: descriptor.id, value: defaultValue) + } + switch descriptor.kind { + case .select: + guard let choice = descriptor.choices.first(where: \.isDefault) + ?? descriptor.choices.first else { + return nil + } + return FeatureModelOptionSelection(id: descriptor.id, value: .string(choice.id)) + case .boolean: + return FeatureModelOptionSelection(id: descriptor.id, value: .boolean(false)) + } + } + } + + static func value( + for descriptor: FeatureModelOptionDescriptor, + in selections: [FeatureModelOptionSelection] + ) -> FeatureModelOptionValue? { + if let selected = selections.first(where: { $0.id == descriptor.id })?.value { + return selected + } + if let defaultValue = descriptor.defaultValue { + return defaultValue + } + switch descriptor.kind { + case .select: + let choice = descriptor.choices.first(where: \.isDefault) + ?? descriptor.choices.first + return choice.map { .string($0.id) } + case .boolean: + return .boolean(false) + } + } + + static func updating( + _ selections: [FeatureModelOptionSelection], + id: String, + value: FeatureModelOptionValue + ) -> [FeatureModelOptionSelection] { + var next = selections.filter { $0.id != id } + next.append(FeatureModelOptionSelection(id: id, value: value)) + return next + } + + static func summary( + for model: FeatureModel, + selections: [FeatureModelOptionSelection] + ) -> String? { + let labels = model.options.compactMap { descriptor -> String? in + guard let value = value(for: descriptor, in: selections) else { return nil } + switch value { + case let .string(choiceID): + return descriptor.choices.first(where: { $0.id == choiceID })?.label + case let .boolean(isEnabled): + return isEnabled ? descriptor.label : nil + } + } + return labels.isEmpty ? nil : labels.joined(separator: " · ") + } + + static func supportsImages( + selection: FeatureSelection?, + providers: [FeatureProvider] + ) -> Bool { + // Older environments do not advertise image capability. In that case the + // server remains the source of truth instead of hiding attachments entirely. + guard providers.lazy.flatMap(\.models).contains(where: \.supportsImages) else { + return true + } + guard let selection, + let provider = providers.first(where: { $0.id == selection.providerID }), + let model = provider.models.first(where: { $0.id == selection.modelID }) else { + return true + } + return model.supportsImages + } +} diff --git a/apps/swift-ios/Features/Workspace/NewThreadView.swift b/apps/swift-ios/Features/Workspace/NewThreadView.swift index dca6e73f4d..1c87894b54 100644 --- a/apps/swift-ios/Features/Workspace/NewThreadView.swift +++ b/apps/swift-ios/Features/Workspace/NewThreadView.swift @@ -3,127 +3,295 @@ import SwiftUI public struct NewThreadView: View { @SwiftUI.Environment(\.dismiss) private var dismiss @Bindable var model: FeatureRootModel + let submit: (NewTaskRequest) async -> FeatureThread? let onCreated: (FeatureThread) -> Void @State private var projectID = "" - @State private var title = "" + @State private var prompt = "" @State private var selection: FeatureSelection? - @State private var isCreating = false + @State private var runtimeMode: FeatureRuntimeMode = .fullAccess + @State private var interactionMode: FeatureInteractionMode = .standard + @State private var attachments: [FeatureDraftAttachment] = [] + @State private var isSubmitting = false + @State private var submissionFailed = false + @FocusState private var promptFocused: Bool - public init(model: FeatureRootModel, onCreated: @escaping (FeatureThread) -> Void) { + public init( + model: FeatureRootModel, + submit: @escaping (NewTaskRequest) async -> FeatureThread?, + onCreated: @escaping (FeatureThread) -> Void + ) { self.model = model + self.submit = submit self.onCreated = onCreated } public var body: some View { NavigationStack { - Form { - Section("Project") { - Picker("Project", selection: $projectID) { - ForEach(model.snapshot.projects) { project in - Text(project.name).tag(project.id) - } + VStack(spacing: 0) { + contextBar + Divider() + .overlay(T3Colors.separator) + + ZStack(alignment: .topLeading) { + if prompt.isEmpty { + Text("What do you want to build?") + .font(.title3) + .foregroundStyle(T3Colors.textTertiary) + .padding(.horizontal, 17) + .padding(.top, 17) + .allowsHitTesting(false) } + + TextEditor(text: $prompt) + .font(.title3) + .lineSpacing(3) + .scrollContentBackground(.hidden) + .focused($promptFocused) + .padding(.horizontal, 12) + .padding(.vertical, 10) + .accessibilityLabel("Task") } - Section("Task") { - TextField("Optional title", text: $title, axis: .vertical) - .lineLimit(1...3) - ProviderModelPicker( - providers: model.snapshot.providers, - selection: $selection - ) + VStack(spacing: 9) { + FeatureAttachmentStrip(attachments: $attachments) + + HStack(spacing: 8) { + FeatureImageAttachmentPicker( + attachments: $attachments, + isEnabled: DailyUXModelOptions.supportsImages( + selection: selection, + providers: model.snapshot.providers + ) + ) + + if !attachments.isEmpty, !imagesAllowed { + Text("Choose an image model") + .font(.caption) + .foregroundStyle(T3Colors.warning) + } else if !attachments.isEmpty { + Text("\(attachments.count) selected") + .font(.caption) + .foregroundStyle(T3Colors.textSecondary) + } + + Spacer() + + Button(action: startTask) { + HStack(spacing: 7) { + if isSubmitting { + ProgressView() + .controlSize(.small) + .tint(.black) + } else { + Text("Start task") + Image(systemName: "arrow.up") + .font(.system(size: 13, weight: .bold)) + } + } + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.black) + .padding(.horizontal, 16) + .frame(height: 40) + .background(.white, in: RoundedRectangle(cornerRadius: 10)) + } + .disabled(!canSubmit) + .opacity(canSubmit ? 1 : 0.35) + .accessibilityLabel(isSubmitting ? "Starting task" : "Start task") + } + } + .padding(.horizontal, 12) + .padding(.top, 8) + .padding(.bottom, 10) + .background(T3Colors.background) + .overlay(alignment: .top) { + Divider().overlay(T3Colors.separator) } } - .scrollContentBackground(.hidden) - .background(Color.black) - .navigationTitle("New Thread") + .background(T3Colors.background) + .navigationTitle("New task") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } - } - ToolbarItem(placement: .confirmationAction) { - Button(isCreating ? "Creating…" : "Create") { - create() - } - .disabled(projectID.isEmpty || isCreating) + .disabled(isSubmitting) } } + .t3NavigationChrome() .onAppear { if projectID.isEmpty { projectID = model.snapshot.projects.first?.id ?? "" } if selection == nil { - selection = model.snapshot.settings.defaultSelection - ?? model.snapshot.providers.first?.models.first.map { - FeatureSelection( - providerID: model.snapshot.providers.first?.id ?? "", - modelID: $0.id - ) - } + selection = DailyUXModelOptions.validated( + model.snapshot.settings.defaultSelection, + in: model.snapshot.providers + ) + ?? DailyUXModelOptions.preferredSelection(in: model.snapshot.providers) } + promptFocused = true + } + .alert("Couldn’t start task", isPresented: $submissionFailed) { + Button("OK") {} + } message: { + Text("Check your connection and try again.") } } + .interactiveDismissDisabled(isSubmitting) + .presentationDetents([.large]) + .presentationDragIndicator(.visible) + .preferredColorScheme(.dark) } - private func create() { - isCreating = true - Task { - let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines) - if let thread = await model.createThread( - projectID: projectID, - title: trimmed.isEmpty ? nil : trimmed, - selection: selection - ) { - onCreated(thread) - } - isCreating = false - } - } -} - -public struct ProviderModelPicker: View { - let providers: [FeatureProvider] - @Binding var selection: FeatureSelection? - - public init(providers: [FeatureProvider], selection: Binding) { - self.providers = providers - _selection = selection - } - - public var body: some View { - Menu { - ForEach(providers.filter(\.isAvailable)) { provider in - Section(provider.name) { - ForEach(provider.models) { model in + private var contextBar: some View { + ScrollView(.horizontal) { + HStack(spacing: 18) { + Menu { + ForEach(model.snapshot.projects) { project in Button { - selection = FeatureSelection(providerID: provider.id, modelID: model.id) + projectID = project.id } label: { - if selection?.providerID == provider.id, selection?.modelID == model.id { - Label(model.name, systemImage: "checkmark") + if project.id == projectID { + Label(project.name, systemImage: "checkmark") } else { - Text(model.name) + Text(project.name) } } } + } label: { + contextLabel( + icon: "folder", + title: selectedProject?.name ?? "Choose project" + ) + } + + ProviderModelPicker( + providers: model.snapshot.providers, + selection: $selection, + style: .compact, + isLoading: model.isLoading + ) + + Menu { + Section("Interaction") { + Button { + interactionMode = .standard + } label: { + modeLabel("Build", selected: interactionMode == .standard) + } + Button { + interactionMode = .plan + } label: { + modeLabel("Plan", selected: interactionMode == .plan) + } + } + + Section("Access") { + ForEach(FeatureRuntimeMode.allCases, id: \.self) { mode in + Button { + runtimeMode = mode + } label: { + modeLabel(runtimeLabel(mode), selected: runtimeMode == mode) + } + } + } + } label: { + contextLabel( + icon: interactionMode == .plan ? "list.bullet.clipboard" : "bolt", + title: interactionMode == .plan ? "Plan" : runtimeShortLabel + ) } } - } label: { - LabeledContent("Model") { - Text(selectionLabel) - .foregroundStyle(.secondary) - } + .padding(.horizontal, 16) + .frame(height: 48) } - .accessibilityLabel("Provider and model") + .scrollIndicators(.hidden) } - private var selectionLabel: String { - guard let selection, - let provider = providers.first(where: { $0.id == selection.providerID }), - let model = provider.models.first(where: { $0.id == selection.modelID }) else { - return "Automatic" + private var selectedProject: FeatureProject? { + model.snapshot.projects.first { $0.id == projectID } + } + + private var canSubmit: Bool { + !isSubmitting + && !projectID.isEmpty + && (!trimmedPrompt.isEmpty || !attachments.isEmpty) + && (attachments.isEmpty || imagesAllowed) + } + + private var trimmedPrompt: String { + prompt.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var imagesAllowed: Bool { + DailyUXModelOptions.supportsImages( + selection: selection, + providers: model.snapshot.providers + ) + } + + private var runtimeShortLabel: String { + switch runtimeMode { + case .approvalRequired: "Ask" + case .autoAcceptEdits: "Edits" + case .automatic: "Automatic" + case .fullAccess: "Full access" + } + } + + private func contextLabel(icon: String, title: String) -> some View { + HStack(spacing: 6) { + Image(systemName: icon) + Text(title) + .lineLimit(1) + Image(systemName: "chevron.down") + .font(.system(size: 8, weight: .bold)) + } + .font(.caption.weight(.medium)) + .foregroundStyle(T3Colors.textSecondary) + .contentShape(Rectangle()) + } + + private func modeLabel(_ title: String, selected: Bool) -> some View { + Group { + if selected { + Label(title, systemImage: "checkmark") + } else { + Text(title) + } + } + } + + private func runtimeLabel(_ mode: FeatureRuntimeMode) -> String { + switch mode { + case .approvalRequired: "Ask before changes" + case .autoAcceptEdits: "Auto-accept edits" + case .automatic: "Automatic" + case .fullAccess: "Full access" + } + } + + private func startTask() { + guard canSubmit else { return } + promptFocused = false + isSubmitting = true + let request = NewTaskRequest( + projectID: projectID, + prompt: trimmedPrompt, + selection: selection, + runtimeMode: runtimeMode, + interactionMode: interactionMode, + attachments: attachments + ) + + Task { + if let thread = await submit(request) { + onCreated(thread) + } else { + isSubmitting = false + submissionFailed = true + promptFocused = true + } } - return "\(provider.name) · \(model.name)" } } diff --git a/apps/swift-ios/Features/Workspace/ProviderModelPicker.swift b/apps/swift-ios/Features/Workspace/ProviderModelPicker.swift new file mode 100644 index 0000000000..6eae8cb9e4 --- /dev/null +++ b/apps/swift-ios/Features/Workspace/ProviderModelPicker.swift @@ -0,0 +1,544 @@ +import SwiftUI + +public struct ProviderModelPicker: View { + public enum Style { + case row + case compact + } + + let providers: [FeatureProvider] + @Binding var selection: FeatureSelection? + let style: Style + let isLoading: Bool + let threadSelection: FeatureSelection? + + @State private var isPresented = false + + public init( + providers: [FeatureProvider], + selection: Binding, + style: Style = .row, + isLoading: Bool = false, + threadSelection: FeatureSelection? = nil + ) { + self.providers = providers + _selection = selection + self.style = style + self.isLoading = isLoading + self.threadSelection = threadSelection + } + + public var body: some View { + Button { + isPresented = true + } label: { + switch style { + case .row: + HStack(spacing: 12) { + Image(systemName: "cpu") + .foregroundStyle(T3Colors.textSecondary) + VStack(alignment: .leading, spacing: 2) { + Text("Model") + .font(.caption) + .foregroundStyle(T3Colors.textSecondary) + Text(selectionLabel) + .font(.subheadline.weight(.medium)) + .foregroundStyle(T3Colors.textPrimary) + .lineLimit(1) + } + Spacer() + Image(systemName: "chevron.right") + .font(.caption.weight(.semibold)) + .foregroundStyle(T3Colors.textTertiary) + } + .contentShape(Rectangle()) + case .compact: + HStack(spacing: 6) { + Image(systemName: "cpu") + Text(compactSelectionLabel) + .lineLimit(1) + Image(systemName: "chevron.up.chevron.down") + .font(.system(size: 8, weight: .bold)) + } + .font(.caption.weight(.medium)) + .foregroundStyle(T3Colors.textSecondary) + .contentShape(Rectangle()) + } + } + .buttonStyle(.plain) + .accessibilityLabel("Choose model") + .accessibilityValue(selectionLabel) + .sheet(isPresented: $isPresented) { + ModelPickerSheet( + providers: providers, + selection: $selection, + isLoading: isLoading, + threadSelection: threadSelection + ) + } + } + + private var selectedOption: DailyUXModelOption? { + guard let selection, + let provider = providers.first(where: { $0.id == selection.providerID }), + let model = provider.models.first(where: { $0.id == selection.modelID }) else { + return nil + } + return DailyUXModelOption(provider: provider, model: model) + } + + private var selectionLabel: String { + guard let selectedOption else { + return selection == nil ? "Automatic" : "Model unavailable" + } + let base = "\(selectedOption.provider.name) · \(selectedOption.model.name)" + guard let selection, + let summary = DailyUXModelOptions.summary( + for: selectedOption.model, + selections: selection.options + ) else { + return base + } + return "\(base) · \(summary)" + } + + private var compactSelectionLabel: String { + guard let selectedOption else { + return selection == nil ? "Automatic" : "Choose model" + } + guard let selection, + let summary = DailyUXModelOptions.summary( + for: selectedOption.model, + selections: selection.options + ) else { + return selectedOption.model.name + } + return "\(selectedOption.model.name) · \(summary)" + } +} + +private struct ModelPickerSheet: View { + @SwiftUI.Environment(\.dismiss) private var dismiss + let providers: [FeatureProvider] + @Binding var selection: FeatureSelection? + let isLoading: Bool + let threadSelection: FeatureSelection? + + @AppStorage("swift-ios.model-picker.favorites") private var favoriteStorage = "" + @AppStorage("swift-ios.model-picker.recents") private var recentStorage = "" + @State private var query = "" + @State private var configuring: DailyUXModelOption? + + var body: some View { + NavigationStack { + Group { + if isLoading, availableModelCount == 0 { + VStack(spacing: 12) { + ProgressView() + Text("Loading models") + .font(.subheadline) + .foregroundStyle(T3Colors.textSecondary) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if availableModelCount == 0 { + ContentUnavailableView( + "No models available", + systemImage: "cpu", + description: Text("Check the providers enabled on this environment.") + ) + } else { + modelList + } + } + .background(T3Colors.background) + .navigationTitle("Choose model") + .navigationBarTitleDisplayMode(.inline) + .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search models") + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + } + .navigationDestination(item: $configuring) { option in + ModelConfigurationView( + option: option, + currentSelection: selection + ) { configuredSelection in + selection = configuredSelection + recordRecent(option.id) + dismiss() + } + } + .t3NavigationChrome() + } + .presentationDetents([.large]) + .presentationDragIndicator(.visible) + .preferredColorScheme(.dark) + } + + private var modelList: some View { + List { + if query.isEmpty { + Section { + Button { + selection = nil + dismiss() + } label: { + ModelAutomaticRow(isSelected: selection == nil) + } + .buttonStyle(.plain) + .disabled(modelChangesAreLocked) + .opacity(modelChangesAreLocked ? 0.36 : 1) + } + } + + if modelChangesAreLocked { + Section { + Label( + "This provider fixes the model when a task starts.", + systemImage: "lock" + ) + .font(.caption) + .foregroundStyle(T3Colors.textSecondary) + } + } + + if !catalog.favorites.isEmpty { + Section("Favorites") { + ForEach(catalog.favorites) { option in + modelRow(option) + } + } + } + + if !catalog.recents.isEmpty { + Section("Recent") { + ForEach(catalog.recents) { option in + modelRow(option) + } + } + } + + ForEach(catalog.providerGroups, id: \.provider.id) { group in + Section(group.provider.name) { + ForEach(group.models) { option in + modelRow(option) + } + } + } + + if catalog.all.isEmpty { + ContentUnavailableView.search(text: query) + .listRowBackground(Color.clear) + } + } + .listStyle(.plain) + .scrollContentBackground(.hidden) + .background(T3Colors.background) + } + + private var availableModelCount: Int { + providers + .filter(\.isAvailable) + .reduce(into: 0) { count, provider in + count += provider.models.count + } + } + + private func modelRow(_ option: DailyUXModelOption) -> some View { + HStack(spacing: 10) { + Button { + select(option) + } label: { + ModelOptionLabel( + option: option, + isSelected: selection?.providerID == option.provider.id + && selection?.modelID == option.model.id + ) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + + Button { + toggleFavorite(option.id) + } label: { + Image(systemName: favoriteIDs.contains(option.id) ? "star.fill" : "star") + .font(.system(size: 15)) + .foregroundStyle( + favoriteIDs.contains(option.id) + ? T3Colors.warning + : T3Colors.textTertiary + ) + .frame(width: 34, height: 34) + } + .buttonStyle(.borderless) + .accessibilityLabel( + favoriteIDs.contains(option.id) ? "Remove favorite" : "Add favorite" + ) + } + .disabled(isLocked(option)) + .opacity(isLocked(option) ? 0.36 : 1) + .listRowBackground(T3Colors.background) + } + + private var favoriteIDs: Set { + Set(favoriteStorage.split(separator: "\n").map(String.init)) + } + + private var recentIDs: [String] { + recentStorage.split(separator: "\n").map(String.init) + } + + private var catalog: DailyUXModelCatalog { + DailyUXModelCatalog( + providers: providers, + query: query, + favoriteIDs: favoriteIDs, + recentIDs: recentIDs + ) + } + + private func select(_ option: DailyUXModelOption) { + guard !isLocked(option) else { return } + if option.model.options.isEmpty { + selection = FeatureSelection(providerID: option.provider.id, modelID: option.model.id) + recordRecent(option.id) + dismiss() + } else { + configuring = option + } + } + + private func recordRecent(_ id: String) { + recentStorage = ([id] + recentIDs.filter { $0 != id }) + .prefix(8) + .joined(separator: "\n") + } + + private var modelChangesAreLocked: Bool { + guard let threadSelection, + let provider = providers.first(where: { $0.id == threadSelection.providerID }) else { + return false + } + return provider.requiresNewThreadForModelChange + } + + private func isLocked(_ option: DailyUXModelOption) -> Bool { + guard modelChangesAreLocked, let threadSelection else { return false } + return option.provider.id != threadSelection.providerID + || option.model.id != threadSelection.modelID + } + + private func toggleFavorite(_ id: String) { + var next = favoriteIDs + if next.contains(id) { + next.remove(id) + } else { + next.insert(id) + } + favoriteStorage = next.sorted().joined(separator: "\n") + } +} + +private struct ModelConfigurationView: View { + let option: DailyUXModelOption + let onConfirm: (FeatureSelection) -> Void + @State private var optionSelections: [FeatureModelOptionSelection] + + init( + option: DailyUXModelOption, + currentSelection: FeatureSelection?, + onConfirm: @escaping (FeatureSelection) -> Void + ) { + self.option = option + self.onConfirm = onConfirm + if currentSelection?.providerID == option.provider.id, + currentSelection?.modelID == option.model.id { + _optionSelections = State(initialValue: currentSelection?.options ?? []) + } else { + _optionSelections = State(initialValue: DailyUXModelOptions.defaults(for: option.model)) + } + } + + var body: some View { + Form { + Section { + ModelOptionLabel(option: option, isSelected: false) + } + + ForEach(option.model.options) { descriptor in + Section { + switch descriptor.kind { + case .select: + Picker( + descriptor.label, + selection: stringBinding(for: descriptor) + ) { + ForEach(descriptor.choices) { choice in + VStack(alignment: .leading) { + Text(choice.label) + if let detail = choice.detail { + Text(detail) + } + } + .tag(choice.id) + } + } + .pickerStyle(.navigationLink) + case .boolean: + Toggle( + descriptor.label, + isOn: booleanBinding(for: descriptor) + ) + } + } footer: { + if let detail = descriptor.detail { + Text(detail) + } + } + } + } + .scrollContentBackground(.hidden) + .background(T3Colors.background) + .navigationTitle("Model options") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Use model") { + onConfirm( + FeatureSelection( + providerID: option.provider.id, + modelID: option.model.id, + options: optionSelections + ) + ) + } + .fontWeight(.semibold) + } + } + } + + private func stringBinding( + for descriptor: FeatureModelOptionDescriptor + ) -> Binding { + Binding( + get: { + guard case let .string(value) = DailyUXModelOptions.value( + for: descriptor, + in: optionSelections + ) else { + return "" + } + return value + }, + set: { value in + optionSelections = DailyUXModelOptions.updating( + optionSelections, + id: descriptor.id, + value: .string(value) + ) + } + ) + } + + private func booleanBinding( + for descriptor: FeatureModelOptionDescriptor + ) -> Binding { + Binding( + get: { + guard case let .boolean(value) = DailyUXModelOptions.value( + for: descriptor, + in: optionSelections + ) else { + return false + } + return value + }, + set: { value in + optionSelections = DailyUXModelOptions.updating( + optionSelections, + id: descriptor.id, + value: .boolean(value) + ) + } + ) + } +} + +private struct ModelAutomaticRow: View { + let isSelected: Bool + + var body: some View { + HStack(spacing: 12) { + Image(systemName: "wand.and.stars") + .foregroundStyle(T3Colors.textSecondary) + .frame(width: 24) + VStack(alignment: .leading, spacing: 2) { + Text("Automatic") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(T3Colors.textPrimary) + Text("Use the environment default") + .font(.caption) + .foregroundStyle(T3Colors.textSecondary) + } + Spacer() + if isSelected { + Image(systemName: "checkmark") + .font(.subheadline.weight(.bold)) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.vertical, 4) + } +} + +private struct ModelOptionLabel: View { + let option: DailyUXModelOption + let isSelected: Bool + + var body: some View { + HStack(spacing: 12) { + providerMark + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 7) { + Text(option.model.name) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(T3Colors.textPrimary) + .lineLimit(1) + if option.model.supportsReasoning { + capability("Reasoning", icon: "brain") + } + if option.model.supportsImages { + capability("Images", icon: "photo") + } + } + Text(option.model.detail ?? option.model.id) + .font(.caption) + .foregroundStyle(T3Colors.textSecondary) + .lineLimit(1) + } + Spacer(minLength: 6) + if isSelected { + Image(systemName: "checkmark") + .font(.subheadline.weight(.bold)) + .foregroundStyle(T3Colors.textPrimary) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.vertical, 4) + } + + private var providerMark: some View { + Text(String(option.provider.name.prefix(1)).uppercased()) + .font(.caption.weight(.bold)) + .foregroundStyle(T3Colors.textPrimary) + .frame(width: 26, height: 26) + .background(T3Colors.surfaceRaised, in: RoundedRectangle(cornerRadius: 6)) + } + + private func capability(_ title: String, icon: String) -> some View { + Label(title, systemImage: icon) + .font(.caption2) + .foregroundStyle(T3Colors.textSecondary) + } +} diff --git a/apps/swift-ios/Features/Workspace/WorkspaceView.swift b/apps/swift-ios/Features/Workspace/WorkspaceView.swift index 8c6785cdf6..bdeb147332 100644 --- a/apps/swift-ios/Features/Workspace/WorkspaceView.swift +++ b/apps/swift-ios/Features/Workspace/WorkspaceView.swift @@ -2,75 +2,84 @@ import SwiftUI public struct WorkspaceView: View { @Bindable var model: FeatureRootModel + private let submitNewTask: (NewTaskRequest) async -> FeatureThread? + private let submitMessage: (FeatureMessageSubmission) async -> Bool + @State private var selectedThreadID: String? @State private var searchText = "" - @State private var showingNewThread = false + @State private var selectedProjectID: String? + @State private var settledLimit = 10 + @State private var showingNewTask = false @State private var showingAddProject = false @State private var showingSettings = false @State private var showingArchived = false @State private var renamingThread: FeatureThread? @State private var renameTitle = "" - public init(model: FeatureRootModel) { + public init( + model: FeatureRootModel, + submitNewTask: ((NewTaskRequest) async -> FeatureThread?)? = nil, + submitMessage: ((FeatureMessageSubmission) async -> Bool)? = nil + ) { self.model = model + self.submitNewTask = submitNewTask ?? { request in + do { + let thread = try await model.client.createThreadAndSend( + projectID: request.projectID, + prompt: request.trimmedPrompt, + selection: request.selection, + runtimeMode: request.runtimeMode, + interactionMode: request.interactionMode, + attachments: request.attachments.map(\.uploadValue) + ) + await model.reload() + return thread + } catch { + return nil + } + } + self.submitMessage = submitMessage ?? { submission in + if submission.attachments.isEmpty { + return await model.sendMessage( + threadID: submission.threadID, + text: submission.text, + selection: submission.selection + ) + } + do { + try await model.client.sendMessage( + threadID: submission.threadID, + text: submission.text, + selection: submission.selection, + attachments: submission.attachments.map(\.uploadValue) + ) + _ = await model.detail(for: submission.threadID, force: true) + return true + } catch { + return false + } + } } public var body: some View { NavigationSplitView { - List(selection: $selectedThreadID) { - connectionSection - projectSection - threadSection - } - .listStyle(.sidebar) - .scrollContentBackground(.hidden) - .background(Color.black) - .searchable(text: $searchText, prompt: "Search threads") - .navigationTitle("T3 Code") - .toolbar { - ToolbarItem(placement: .topBarLeading) { - Button { - showingSettings = true - } label: { - Image(systemName: "gearshape") - } - .accessibilityLabel("Settings") - } - ToolbarItemGroup(placement: .topBarTrailing) { - Button { - showingAddProject = true - } label: { - Image(systemName: "folder.badge.plus") - } - .accessibilityLabel("Add project") - Button { - showingNewThread = true - } label: { - Image(systemName: "square.and.pencil") - } - .accessibilityLabel("New thread") - .disabled(model.snapshot.projects.isEmpty) - } - } - } detail: { - if let id = selectedThreadID, - let thread = model.snapshot.threads.first(where: { $0.id == id }) { - ThreadDetailView(model: model, thread: thread) - .id(id) - } else { - ContentUnavailableView( - "Choose a thread", - systemImage: "bubble.left.and.bubble.right", - description: Text("Select a thread or start a new task.") + sidebar + .navigationSplitViewColumnWidth( + min: T3Metrics.minimumSidebarWidth, + ideal: T3Metrics.sidebarWidth, + max: T3Metrics.maximumSidebarWidth ) - .background(Color.black) - } + } detail: { + detail } .navigationSplitViewStyle(.balanced) - .sheet(isPresented: $showingNewThread) { - NewThreadView(model: model) { thread in + .sheet(isPresented: $showingNewTask) { + NewThreadView( + model: model, + submit: submitNewTask + ) { thread in selectedThreadID = thread.id - showingNewThread = false + showingNewTask = false } } .sheet(isPresented: $showingAddProject) { @@ -112,169 +121,346 @@ public struct WorkspaceView: View { } } - @ViewBuilder - private var connectionSection: some View { - Section { - Menu { - ForEach(model.snapshot.environments) { environment in - Button { - Task { await model.activateEnvironment(environment.id) } - } label: { - if environment.isActive { - Label(environment.name, systemImage: "checkmark") - } else { - Text(environment.name) - } - } - } - } label: { - HStack(spacing: 9) { - Circle() - .fill(Color.green) - .frame(width: 7, height: 7) - Text(model.snapshot.connection.environmentName ?? "Connected") - .font(.subheadline.weight(.medium)) - .foregroundStyle(.primary) - .lineLimit(1) - Spacer() - if model.snapshot.environments.count > 1 { - Image(systemName: "chevron.up.chevron.down") - .font(.caption2) - .foregroundStyle(.secondary) - } - } - } - .buttonStyle(.plain) - } - } + private var sidebar: some View { + List(selection: $selectedThreadID) { + connectionHeader + newTaskAction - @ViewBuilder - private var projectSection: some View { - Section("Projects") { - if model.snapshot.projects.isEmpty { - Text("No projects") - .font(.footnote) - .foregroundStyle(.secondary) + if searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + projectFilter + activeSection + settledSection + archiveAction } else { - ForEach(model.snapshot.projects) { project in - HStack(spacing: 10) { - Image(systemName: "folder") - .foregroundStyle(.secondary) - VStack(alignment: .leading, spacing: 2) { - Text(project.name) - .font(.subheadline.weight(.medium)) - .lineLimit(1) - Text(project.path) - .font(.caption2) - .foregroundStyle(.secondary) - .lineLimit(1) - } - Spacer() - Text("\(activeThreads.filter { $0.projectID == project.id }.count)") - .font(.caption.monospacedDigit()) - .foregroundStyle(.tertiary) + searchResults + } + } + .listStyle(.sidebar) + .scrollContentBackground(.hidden) + .background(T3Colors.background) + .searchable(text: $searchText, prompt: "Search tasks and projects") + .navigationTitle("T3") + .toolbar { + ToolbarItem(placement: .topBarLeading) { + Button { + showingSettings = true + } label: { + Image(systemName: "slider.horizontal.3") + } + .accessibilityLabel("Settings") + } + ToolbarItem(placement: .topBarTrailing) { + Button { + showingAddProject = true + } label: { + Image(systemName: "folder.badge.plus") + } + .accessibilityLabel("Add project") + } + } + .t3NavigationChrome() + .onChange(of: selectedProjectID) { + settledLimit = 10 + } + } + + @ViewBuilder + private var detail: some View { + if let id = selectedThreadID, + let thread = model.snapshot.threads.first(where: { $0.id == id }) { + ThreadDetailView( + model: model, + thread: thread, + submitMessage: submitMessage + ) + .id(id) + } else { + VStack(spacing: 18) { + Image(systemName: "cursorarrow.rays") + .font(.system(size: 34, weight: .light)) + .foregroundStyle(T3Colors.textTertiary) + VStack(spacing: 5) { + Text("Ready when you are") + .font(.title3.weight(.semibold)) + Text("Pick up a task or start something new.") + .font(.subheadline) + .foregroundStyle(T3Colors.textSecondary) + } + Button("New task") { + showingNewTask = true + } + .buttonStyle(.borderedProminent) + .tint(.white) + .foregroundStyle(.black) + .disabled(model.snapshot.projects.isEmpty) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(T3Colors.background) + } + } + + private var connectionHeader: some View { + Menu { + ForEach(model.snapshot.environments) { environment in + Button { + Task { await model.activateEnvironment(environment.id) } + } label: { + if environment.isActive { + Label(environment.name, systemImage: "checkmark") + } else { + Text(environment.name) } - .accessibilityElement(children: .combine) + } + } + Divider() + Button { + showingSettings = true + } label: { + Label("Manage devices", systemImage: "externaldrive.connected.to.line.below") + } + } label: { + HStack(spacing: 9) { + Circle() + .fill(connectionColor) + .frame(width: 7, height: 7) + VStack(alignment: .leading, spacing: 1) { + Text(model.snapshot.connection.environmentName ?? "T3 environment") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(T3Colors.textPrimary) + .lineLimit(1) + Text(connectionLabel) + .font(.caption2) + .foregroundStyle(T3Colors.textSecondary) + } + Spacer() + Image(systemName: "chevron.up.chevron.down") + .font(.caption2.weight(.semibold)) + .foregroundStyle(T3Colors.textTertiary) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .listRowSeparator(.hidden) + } + + private var newTaskAction: some View { + Button { + showingNewTask = true + } label: { + HStack(spacing: 10) { + Image(systemName: "plus") + .font(.system(size: 14, weight: .bold)) + Text("New task") + .font(.subheadline.weight(.semibold)) + Spacer() + Image(systemName: "arrow.up.right") + .font(.caption.weight(.bold)) + .foregroundStyle(.black.opacity(0.48)) + } + .foregroundStyle(.black) + .padding(.horizontal, 12) + .frame(height: 42) + .background(.white, in: RoundedRectangle(cornerRadius: 9)) + } + .buttonStyle(.plain) + .disabled(model.snapshot.projects.isEmpty) + .opacity(model.snapshot.projects.isEmpty ? 0.35 : 1) + .listRowInsets(EdgeInsets(top: 7, leading: 12, bottom: 9, trailing: 12)) + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + .accessibilityHint("Compose a message and start a thread") + } + + private var projectFilter: some View { + Menu { + Button { + selectedProjectID = nil + } label: { + if selectedProjectID == nil { + Label("All projects", systemImage: "checkmark") + } else { + Text("All projects") + } + } + ForEach(model.snapshot.projects) { project in + Button { + selectedProjectID = project.id + } label: { + if selectedProjectID == project.id { + Label(project.name, systemImage: "checkmark") + } else { + Text(project.name) + } + } + } + } label: { + ProjectFilterRow( + project: model.snapshot.projects.first { $0.id == selectedProjectID }, + totalCount: sidebarIndex.active.count + sidebarIndex.settled.count + ) + } + .buttonStyle(.plain) + .listRowSeparator(.hidden) + } + + @ViewBuilder + private var activeSection: some View { + Section("Active") { + if sidebarIndex.active.isEmpty { + Text(selectedProjectID == nil ? "No active tasks" : "No active tasks in this project") + .font(.footnote) + .foregroundStyle(T3Colors.textSecondary) + } else { + ForEach(sidebarIndex.active) { thread in + threadLink(thread, showsProject: selectedProjectID == nil) } } } } @ViewBuilder - private var threadSection: some View { - Section { - if filteredThreads.isEmpty { - Text(searchText.isEmpty ? "No active threads" : "No results") - .font(.footnote) - .foregroundStyle(.secondary) + private var settledSection: some View { + if !sidebarIndex.settled.isEmpty { + Section("Settled") { + ForEach(sidebarIndex.settled.prefix(settledLimit)) { thread in + threadLink(thread, showsProject: selectedProjectID == nil) + .opacity(0.76) + } + if sidebarIndex.settled.count > settledLimit { + Button { + settledLimit += 25 + } label: { + HStack { + Text("Show more") + Spacer() + Text("\(sidebarIndex.settled.count - settledLimit)") + .font(.caption.monospacedDigit()) + .foregroundStyle(T3Colors.textTertiary) + } + .font(.subheadline) + } + .buttonStyle(.plain) + } } - ForEach(filteredThreads) { thread in - NavigationLink(value: thread.id) { - FeatureThreadRow( - thread: thread, - projectName: projectName(for: thread.projectID) + } + } + + private var archiveAction: some View { + Button { + showingArchived = true + } label: { + Label("Archived", systemImage: "archivebox") + .font(.subheadline) + .foregroundStyle(T3Colors.textSecondary) + } + .buttonStyle(.plain) + } + + @ViewBuilder + private var searchResults: some View { + Section("Results") { + if sidebarIndex.searchResults.isEmpty { + ContentUnavailableView.search(text: searchText) + .listRowBackground(Color.clear) + } else { + ForEach(sidebarIndex.searchResults) { thread in + threadLink(thread, showsProject: true) + } + } + } + } + + private func threadLink(_ thread: FeatureThread, showsProject: Bool) -> some View { + NavigationLink(value: thread.id) { + FeatureThreadRow( + thread: thread, + projectName: showsProject ? projectName(for: thread.projectID) : nil + ) + } + .tag(thread.id) + .swipeActions(edge: .trailing, allowsFullSwipe: false) { + Button(role: .destructive) { + Task { await model.deleteThread(thread.id) } + } label: { + Label("Delete", systemImage: "trash") + } + Button { + Task { await model.setArchived(thread.id, archived: true) } + } label: { + Label("Archive", systemImage: "archivebox") + } + .tint(.orange) + } + .contextMenu { + Button { + renameTitle = thread.title + renamingThread = thread + } label: { + Label("Rename", systemImage: "pencil") + } + Button { + Task { await model.setArchived(thread.id, archived: true) } + } label: { + Label("Archive", systemImage: "archivebox") + } + if thread.isSettled { + Button { + Task { await model.setSettled(thread.id, settled: false) } + } label: { + Label("Reopen", systemImage: "arrow.counterclockwise") + } + } else if !thread.isEffectivelySettled(at: .now) { + Button { + Task { await model.setSettled(thread.id, settled: true) } + } label: { + Label("Mark done", systemImage: "checkmark") + } + } + Button { + Task { + await model.setSnoozed( + thread.id, + until: thread.snoozedUntil == nil + ? Date().addingTimeInterval(60 * 60) + : nil ) } - .tag(thread.id) - .swipeActions(edge: .trailing, allowsFullSwipe: false) { - Button(role: .destructive) { - Task { await model.deleteThread(thread.id) } - } label: { - Label("Delete", systemImage: "trash") - } - Button { - Task { await model.setArchived(thread.id, archived: true) } - } label: { - Label("Archive", systemImage: "archivebox") - } - .tint(.orange) - } - .contextMenu { - Button { - renameTitle = thread.title - renamingThread = thread - } label: { - Label("Rename", systemImage: "pencil") - } - Button { - Task { await model.setArchived(thread.id, archived: true) } - } label: { - Label("Archive", systemImage: "archivebox") - } - Button { - Task { await model.setSettled(thread.id, settled: !thread.isSettled) } - } label: { - Label( - thread.isSettled ? "Reopen" : "Mark done", - systemImage: thread.isSettled ? "arrow.counterclockwise" : "checkmark" - ) - } - Button { - Task { - await model.setSnoozed( - thread.id, - until: thread.snoozedUntil == nil - ? Date().addingTimeInterval(60 * 60) - : nil - ) - } - } label: { - Label( - thread.snoozedUntil == nil ? "Snooze 1 hour" : "Unsnooze", - systemImage: thread.snoozedUntil == nil ? "clock" : "bell" - ) - } - Button(role: .destructive) { - Task { await model.deleteThread(thread.id) } - } label: { - Label("Delete", systemImage: "trash") - } - } - } - - Button { - showingArchived = true } label: { - Label("Archived", systemImage: "archivebox") - .font(.subheadline) + Label( + thread.snoozedUntil == nil ? "Snooze 1 hour" : "Unsnooze", + systemImage: thread.snoozedUntil == nil ? "clock" : "bell" + ) + } + Button(role: .destructive) { + Task { await model.deleteThread(thread.id) } + } label: { + Label("Delete", systemImage: "trash") } - } header: { - Text("Threads") } } - private var activeThreads: [FeatureThread] { - model.snapshot.threads - .filter { !$0.isArchived } - .sorted { $0.updatedAt > $1.updatedAt } + private var sidebarIndex: DailyUXSidebarIndex { + DailyUXSidebarIndex( + snapshot: model.snapshot, + query: searchText, + projectID: selectedProjectID + ) } - private var filteredThreads: [FeatureThread] { - guard !searchText.isEmpty else { return activeThreads } - return activeThreads.filter { - $0.title.localizedCaseInsensitiveContains(searchText) - || ($0.preview?.localizedCaseInsensitiveContains(searchText) ?? false) - || projectName(for: $0.projectID).localizedCaseInsensitiveContains(searchText) + private var connectionColor: Color { + switch model.snapshot.connection.state { + case .connected: T3Colors.success + case .connecting, .reconnecting: T3Colors.warning + case .disconnected: T3Colors.danger + } + } + + private var connectionLabel: String { + switch model.snapshot.connection.state { + case .connected: "Connected" + case .connecting: "Connecting" + case .reconnecting: "Reconnecting" + case .disconnected: "Offline" } } @@ -283,29 +469,83 @@ public struct WorkspaceView: View { } } -struct FeatureThreadRow: View { - let thread: FeatureThread - let projectName: String +private extension FeatureDraftAttachment { + var uploadValue: FeatureUploadAttachment { + FeatureUploadAttachment(data: data, name: filename, mimeType: mimeType) + } +} + +private struct ProjectFilterRow: View { + let project: FeatureProject? + let totalCount: Int var body: some View { - HStack(alignment: .top, spacing: 10) { - Circle() - .fill(statusColor) - .frame(width: 7, height: 7) - .padding(.top, 6) - VStack(alignment: .leading, spacing: 3) { - Text(thread.title) + HStack(spacing: 10) { + Image(systemName: "folder") + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(T3Colors.textSecondary) + .frame(width: 18) + VStack(alignment: .leading, spacing: 1) { + Text(project?.name ?? "All projects") .font(.subheadline.weight(.medium)) + .foregroundStyle(T3Colors.textPrimary) .lineLimit(1) + Text(project?.path ?? "Filter tasks by repository") + .font(.caption2) + .foregroundStyle(T3Colors.textTertiary) + .lineLimit(1) + } + Spacer() + if totalCount > 0 { + Text("\(totalCount)") + .font(.caption2.monospacedDigit()) + .foregroundStyle(T3Colors.textTertiary) + } + Image(systemName: "chevron.up.chevron.down") + .font(.caption2.weight(.semibold)) + .foregroundStyle(T3Colors.textTertiary) + } + .contentShape(Rectangle()) + .accessibilityElement(children: .combine) + } +} + +struct FeatureThreadRow: View { + let thread: FeatureThread + let projectName: String? + + var body: some View { + HStack(alignment: .top, spacing: 9) { + Image(systemName: statusIcon) + .font(.system(size: 8, weight: .bold)) + .foregroundStyle(statusColor) + .frame(width: 10, height: 18) + VStack(alignment: .leading, spacing: 3) { + HStack(spacing: 6) { + Text(thread.title) + .font(.subheadline.weight(thread.needsAttention ? .semibold : .regular)) + .foregroundStyle(T3Colors.textPrimary) + .lineLimit(1) + Spacer(minLength: 4) + Text(thread.updatedAt, format: .relative(presentation: .numeric)) + .font(.system(size: 10)) + .foregroundStyle(T3Colors.textTertiary) + .lineLimit(1) + } HStack(spacing: 5) { - Text(projectName) + if let projectName { + Text(projectName) + } if let preview = thread.preview, !preview.isEmpty { - Text("·") + if projectName != nil { Text("·") } Text(preview) + } else if thread.needsAttention { + if projectName != nil { Text("·") } + Text(statusText) } } .font(.caption) - .foregroundStyle(.secondary) + .foregroundStyle(thread.needsAttention ? statusColor : T3Colors.textSecondary) .lineLimit(1) } } @@ -314,22 +554,35 @@ struct FeatureThreadRow: View { .accessibilityValue(statusText) } + private var statusIcon: String { + switch thread.state { + case .idle, .completed: "circle.fill" + case .queued, .working: "bolt.fill" + case .waitingForApproval: "exclamationmark.circle.fill" + case .waitingForInput: "questionmark.circle.fill" + case .failed: "xmark.circle.fill" + } + } + private var statusColor: Color { switch thread.state { - case .idle, .completed: .gray - case .queued: .blue + case .idle, .completed: T3Colors.textTertiary + case .queued: T3Colors.accent case .working: .cyan - case .waitingForApproval: .orange + case .waitingForApproval: T3Colors.warning case .waitingForInput: .indigo - case .failed: .red + case .failed: T3Colors.danger } } private var statusText: String { switch thread.state { - case .waitingForApproval: "Waiting for approval" - case .waitingForInput: "Waiting for input" - default: thread.state.rawValue + case .waitingForApproval: "Approval needed" + case .waitingForInput: "Answer needed" + case .working: "Working" + case .queued: "Queued" + case .failed: "Failed" + case .idle, .completed: thread.state.rawValue.capitalized } } } diff --git a/apps/swift-ios/Tests/FeatureTests/DailyUXModelPickerTests.swift b/apps/swift-ios/Tests/FeatureTests/DailyUXModelPickerTests.swift new file mode 100644 index 0000000000..7f756c1bfd --- /dev/null +++ b/apps/swift-ios/Tests/FeatureTests/DailyUXModelPickerTests.swift @@ -0,0 +1,176 @@ +import Foundation +import Testing +@testable import T3Code + +@Suite("Model picker") +struct DailyUXModelPickerTests { + @Test + func catalogPreservesFavoritesRecentsAndProviderGroups() { + let providers = [ + FeatureProvider( + id: "codex", + name: "Codex", + models: [ + FeatureModel(id: "gpt-5", name: "GPT-5", supportsImages: true), + FeatureModel(id: "gpt-5-mini", name: "GPT-5 Mini"), + ] + ), + FeatureProvider( + id: "claude", + name: "Claude", + models: [FeatureModel(id: "sonnet", name: "Sonnet", supportsReasoning: true)] + ), + ] + let favorite = DailyUXModelOption.key(providerID: "claude", modelID: "sonnet") + let recent = DailyUXModelOption.key(providerID: "codex", modelID: "gpt-5") + + let catalog = DailyUXModelCatalog( + providers: providers, + query: "", + favoriteIDs: [favorite], + recentIDs: [recent] + ) + + #expect(catalog.favorites.map(\.id) == [favorite]) + #expect(catalog.recents.map(\.id) == [recent]) + #expect(catalog.providerGroups.map(\.provider.id) == ["codex", "claude"]) + } + + @Test + func searchIncludesCapabilitiesAndProviderNames() { + let providers = [ + FeatureProvider( + id: "codex", + name: "Codex", + models: [ + FeatureModel(id: "vision", name: "Visual", supportsImages: true), + FeatureModel(id: "plain", name: "Plain"), + ] + ), + ] + + let catalog = DailyUXModelCatalog( + providers: providers, + query: "images", + favoriteIDs: [], + recentIDs: [] + ) + + #expect(catalog.all.map(\.model.id) == ["vision"]) + } + + @Test + func optionDefaultsUseTypedDescriptorDefaults() { + let model = FeatureModel( + id: "gpt-5", + name: "GPT-5", + options: [ + FeatureModelOptionDescriptor( + id: "effort", + label: "Reasoning effort", + kind: .select, + choices: [ + .init(id: "low", label: "Low"), + .init(id: "high", label: "High", isDefault: true), + ] + ), + FeatureModelOptionDescriptor( + id: "fast", + label: "Fast mode", + kind: .boolean, + defaultValue: .boolean(true) + ), + ] + ) + + let defaults = DailyUXModelOptions.defaults(for: model) + + #expect(defaults == [ + FeatureModelOptionSelection(id: "effort", value: .string("high")), + FeatureModelOptionSelection(id: "fast", value: .boolean(true)), + ]) + } + + @Test + func updatingAnOptionReplacesOnlyItsPreviousValue() { + let initial = [ + FeatureModelOptionSelection(id: "effort", value: .string("low")), + FeatureModelOptionSelection(id: "fast", value: .boolean(false)), + ] + + let updated = DailyUXModelOptions.updating( + initial, + id: "effort", + value: .string("high") + ) + + #expect(updated.first { $0.id == "effort" }?.value == .string("high")) + #expect(updated.first { $0.id == "fast" }?.value == .boolean(false)) + #expect(updated.count == 2) + } + + @Test + func optionSummaryUsesChoiceLabelsAndEnabledBooleans() { + let model = FeatureModel( + id: "gpt-5", + name: "GPT-5", + options: [ + .init( + id: "effort", + label: "Reasoning", + kind: .select, + choices: [.init(id: "high", label: "High")] + ), + .init(id: "fast", label: "Fast", kind: .boolean), + ] + ) + + let summary = DailyUXModelOptions.summary( + for: model, + selections: [ + .init(id: "effort", value: .string("high")), + .init(id: "fast", value: .boolean(true)), + ] + ) + + #expect(summary == "High · Fast") + } + + @Test + func preferredSelectionFindsDefaultAcrossProvidersAndIncludesDefaults() { + let providers = [ + FeatureProvider( + id: "first", + name: "First", + models: [.init(id: "basic", name: "Basic")] + ), + FeatureProvider( + id: "second", + name: "Second", + models: [ + .init( + id: "preferred", + name: "Preferred", + isDefault: true, + options: [ + .init( + id: "fast", + label: "Fast", + kind: .boolean, + defaultValue: .boolean(true) + ), + ] + ), + ] + ), + ] + + let selection = DailyUXModelOptions.preferredSelection(in: providers) + + #expect(selection?.providerID == "second") + #expect(selection?.modelID == "preferred") + #expect(selection?.options == [ + FeatureModelOptionSelection(id: "fast", value: .boolean(true)), + ]) + } +} diff --git a/apps/swift-ios/Tests/FeatureTests/DailyUXNewTaskTests.swift b/apps/swift-ios/Tests/FeatureTests/DailyUXNewTaskTests.swift new file mode 100644 index 0000000000..30c89b3fbe --- /dev/null +++ b/apps/swift-ios/Tests/FeatureTests/DailyUXNewTaskTests.swift @@ -0,0 +1,27 @@ +import Foundation +import Testing +@testable import T3Code + +@Suite("Message-first task creation") +struct DailyUXNewTaskTests { + @Test + func requestKeepsPromptModesAndImageBytesTogether() { + let image = FeatureDraftAttachment( + data: Data([1, 2, 3]), + filename: "Image 1.jpg", + mimeType: "image/jpeg" + ) + let request = NewTaskRequest( + projectID: "project", + prompt: " Build it \n", + selection: FeatureSelection(providerID: "codex", modelID: "gpt-5"), + runtimeMode: .fullAccess, + interactionMode: .plan, + attachments: [image] + ) + + #expect(request.trimmedPrompt == "Build it") + #expect(request.interactionMode == .plan) + #expect(request.attachments.first?.byteCount == 3) + } +} diff --git a/apps/swift-ios/Tests/FeatureTests/DailyUXSidebarTests.swift b/apps/swift-ios/Tests/FeatureTests/DailyUXSidebarTests.swift new file mode 100644 index 0000000000..0be3cef829 --- /dev/null +++ b/apps/swift-ios/Tests/FeatureTests/DailyUXSidebarTests.swift @@ -0,0 +1,134 @@ +import Foundation +import Testing +@testable import T3Code + +@Suite("Sidebar v2") +struct DailyUXSidebarTests { + private let now = Date(timeIntervalSince1970: 2_000_000) + + @Test + func activeOrderUsesCreationTimeAndDoesNotJumpWithActivity() { + let olderCreationRecentActivity = thread( + id: "old", + created: -500, + updated: -5, + state: .working + ) + let newerCreationOlderActivity = thread( + id: "new", + created: -100, + updated: -80, + state: .working + ) + + let index = makeIndex([olderCreationRecentActivity, newerCreationOlderActivity]) + + #expect(index.active.map(\.id) == ["new", "old"]) + } + + @Test + func settledUsesExplicitStateOrThreeDayRestingAge() { + let explicitlySettled = thread( + id: "explicit", + created: -10, + updated: -10, + state: .idle, + isSettled: true + ) + let resting = thread( + id: "resting", + created: -400_000, + updated: -300_000, + state: .idle + ) + let oldButWorking = thread( + id: "working", + created: -400_000, + updated: -300_000, + state: .working + ) + let settledButWorking = thread( + id: "settled-working", + created: -400_000, + updated: -300_000, + state: .working, + isSettled: true + ) + let oldButWaiting = thread( + id: "waiting", + created: -400_000, + updated: -300_000, + state: .waitingForApproval + ) + + let index = makeIndex([ + explicitlySettled, + resting, + oldButWorking, + settledButWorking, + oldButWaiting, + ]) + + #expect(Set(index.settled.map(\.id)) == ["explicit", "resting"]) + #expect(Set(index.active.map(\.id)) == ["working", "settled-working", "waiting"]) + } + + @Test + func snoozedAndArchivedThreadsStayOutOfBothBlocks() { + var snoozed = thread(id: "snoozed", created: -20, updated: -10) + snoozed.snoozedUntil = now.addingTimeInterval(3_600) + var archived = thread(id: "archived", created: -30, updated: -20) + archived.isArchived = true + let visible = thread(id: "visible", created: -10, updated: -5) + + let index = makeIndex([snoozed, archived, visible]) + + #expect(index.active.map(\.id) == ["visible"]) + #expect(index.settled.isEmpty) + } + + @Test + func projectFilterAndSearchUseRepositoryContext() { + let projects = [ + FeatureProject(id: "p1", environmentID: "e", name: "Mobile", path: "/work/mobile"), + FeatureProject(id: "p2", environmentID: "e", name: "Server", path: "/work/server"), + ] + let mobile = thread(id: "mobile", projectID: "p1", title: "Polish picker", created: -10, updated: -5) + let server = thread(id: "server", projectID: "p2", title: "Compression", created: -20, updated: -5) + let snapshot = FeatureSnapshot(projects: projects, threads: [mobile, server]) + + let filtered = DailyUXSidebarIndex(snapshot: snapshot, query: "", projectID: "p1", now: now) + let searched = DailyUXSidebarIndex(snapshot: snapshot, query: "server", now: now) + + #expect(filtered.active.map(\.id) == ["mobile"]) + #expect(searched.searchResults.map(\.id) == ["server"]) + } + + private func makeIndex(_ threads: [FeatureThread]) -> DailyUXSidebarIndex { + DailyUXSidebarIndex( + snapshot: FeatureSnapshot(threads: threads), + query: "", + now: now + ) + } + + private func thread( + id: String, + projectID: String = "project", + title: String = "Task", + created: TimeInterval, + updated: TimeInterval, + state: FeatureThreadState = .idle, + isSettled: Bool = false + ) -> FeatureThread { + FeatureThread( + id: id, + projectID: projectID, + title: title, + createdAt: now.addingTimeInterval(created), + updatedAt: now.addingTimeInterval(updated), + state: state, + isSettled: isSettled + ) + } +} diff --git a/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift b/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift index 32062f6e3a..e3734c8eb8 100644 --- a/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift +++ b/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift @@ -1,3 +1,4 @@ +import Foundation import Testing @testable import T3Code @@ -68,6 +69,43 @@ struct FeatureRootModelTests { #expect(model.details[thread.id]?.messages.last?.state == .queued) } + @Test + func testNewTaskStartsThreadAndFirstTurnAtomically() async { + let client = FeatureClientStub() + let created = FeatureThread( + id: "thread-atomic", + projectID: "project-1", + title: "Ship the native app", + providerID: "codex", + modelID: "gpt-5.6-sol" + ) + client.createdThread = created + let model = FeatureRootModel(client: client) + let attachment = FeatureDraftAttachment( + data: Data([0xFF, 0xD8, 0xFF]), + filename: "reference.jpg", + mimeType: "image/jpeg" + ) + + let result = await model.startTask( + NewTaskRequest( + projectID: "project-1", + prompt: " Ship the native app ", + selection: .init(providerID: "codex", modelID: "gpt-5.6-sol"), + runtimeMode: .fullAccess, + interactionMode: .standard, + attachments: [attachment] + ) + ) + + #expect(result == created) + #expect(client.startedPrompt == "Ship the native app") + #expect(client.startedAttachments.map(\.name) == ["reference.jpg"]) + #expect(client.createThreadCallCount == 0) + #expect(client.sendMessageCallCount == 0) + #expect(model.snapshot.threads == [created]) + } + @Test func testArchiveAndDeleteKeepLocalListsConsistent() async { let client = FeatureClientStub() @@ -93,6 +131,10 @@ private final class FeatureClientStub: FeatureClient { var pairEndpoint: String? var pairToken: String? var sentText: String? + var startedPrompt: String? + var startedAttachments: [FeatureUploadAttachment] = [] + var createThreadCallCount = 0 + var sendMessageCallCount = 0 func initialSnapshot() async throws -> FeatureSnapshot { if pairEndpoint != nil, let snapshotAfterPair { @@ -111,7 +153,21 @@ private final class FeatureClientStub: FeatureClient { title: String?, selection: FeatureSelection? ) async throws -> FeatureThread { - createdThread + createThreadCallCount += 1 + return createdThread + } + + func createThreadAndSend( + projectID: String, + prompt: String, + selection: FeatureSelection?, + runtimeMode: FeatureRuntimeMode, + interactionMode: FeatureInteractionMode, + attachments: [FeatureUploadAttachment] + ) async throws -> FeatureThread { + startedPrompt = prompt + startedAttachments = attachments + return createdThread } func renameThread(id: String, title: String) async throws {} @@ -126,6 +182,7 @@ private final class FeatureClientStub: FeatureClient { } func sendMessage(threadID: String, text: String, selection: FeatureSelection?) async throws { + sendMessageCallCount += 1 sentText = text }