From 6e7216a53df1a25867d3e0422e104a2713baba50 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sat, 1 Aug 2026 03:49:17 -0700 Subject: [PATCH] feat(ios): complete native task composition --- apps/swift-ios/App/NativeFeatureClient.swift | 200 +++++++++- apps/swift-ios/Core/ServerConfigModels.swift | 22 ++ apps/swift-ios/Core/T3Client.swift | 18 +- apps/swift-ios/Core/WorkspaceModels.swift | 19 + .../Chat/FeatureComposerCommandPopover.swift | 120 ++++++ .../Chat/FeatureComposerPowerFeatures.swift | 346 ++++++++++++++++++ .../Features/Chat/FeatureComposerView.swift | 167 ++++++++- .../Features/Chat/ThreadDetailView.swift | 32 +- .../Features/Shared/FeatureClient.swift | 26 ++ .../Shared/FeatureComposerDraftStore.swift | 54 ++- .../Features/Shared/FeatureModels.swift | 13 +- .../Features/Workspace/DailyUXModels.swift | 5 + .../Features/Workspace/NewThreadView.swift | 180 ++++++++- .../Tests/CoreTests/CoreContractTests.swift | 36 ++ .../NativeContractExpansionTests.swift | 25 ++ .../ComposerDraftStoreTests.swift | 8 +- .../FeatureTests/DailyUXNewTaskTests.swift | 19 +- .../FeatureComposerPowerTests.swift | 162 ++++++++ 18 files changed, 1404 insertions(+), 48 deletions(-) create mode 100644 apps/swift-ios/Features/Chat/FeatureComposerCommandPopover.swift create mode 100644 apps/swift-ios/Features/Chat/FeatureComposerPowerFeatures.swift create mode 100644 apps/swift-ios/Tests/FeatureTests/FeatureComposerPowerTests.swift diff --git a/apps/swift-ios/App/NativeFeatureClient.swift b/apps/swift-ios/App/NativeFeatureClient.swift index f4814fbd96..6818cefd40 100644 --- a/apps/swift-ios/App/NativeFeatureClient.swift +++ b/apps/swift-ios/App/NativeFeatureClient.swift @@ -33,6 +33,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr private var environmentConnectionStates: [String: FeatureConnection.State] = [:] private var environmentConnectionDetails: [String: String] = [:] private var latestServerConfig: ServerConfigSnapshot? + private var serverConfigsByEnvironmentID: [String: ServerConfigSnapshot] = [:] private var latestSnapshot: FeatureSnapshot? private var activeThreadID: String? private var activeThreadEnvironmentID: String? @@ -239,6 +240,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr if !preserveEnvironmentSnapshots { environmentClients.removeAll() shellsByEnvironmentID.removeAll() + serverConfigsByEnvironmentID.removeAll() archivedThreadsByEnvironmentID.removeAll() projectEnvironmentIDs.removeAll() projectWireIDs.removeAll() @@ -350,6 +352,29 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr try await refresh(client: client) } + func listWorkspaceBranches( + projectID: String, + refresh: Bool + ) async throws -> [FeatureWorkspaceBranch] { + let route = try projectRoute(for: projectID) + let project = try project(for: route) + let result = try await route.client.listVCSRefs( + cwd: project.workspaceRoot, + refresh: refresh, + limit: 100 + ) + guard result.isRepo else { return [] } + return result.refs.map { ref in + FeatureWorkspaceBranch( + name: ref.name, + isRemote: ref.isRemote ?? false, + isCurrent: ref.current, + isDefault: ref.isDefault, + worktreePath: ref.worktreePath + ) + } + } + func createThread( projectID: String, title: String?, @@ -415,11 +440,43 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr runtimeMode: FeatureRuntimeMode, interactionMode: FeatureInteractionMode, attachments: [FeatureUploadAttachment] + ) async throws -> FeatureThread { + try await createThreadAndSend( + projectID: projectID, + prompt: prompt, + selection: selection, + runtimeMode: runtimeMode, + interactionMode: interactionMode, + workspaceMode: .local, + branch: nil, + worktreePath: nil, + startFromOrigin: false, + attachments: attachments + ) + } + + func createThreadAndSend( + projectID: String, + prompt: String, + selection: FeatureSelection?, + runtimeMode: FeatureRuntimeMode, + interactionMode: FeatureInteractionMode, + workspaceMode: FeatureWorkspaceMode, + branch: String?, + worktreePath: String?, + startFromOrigin: Bool, + attachments: [FeatureUploadAttachment] ) async throws -> FeatureThread { let route = try projectRoute(for: projectID) let client = route.client let environment = client.environment let generation = environmentGeneration + let routedProject = try project(for: route) + let branch = branch?.trimmingCharacters(in: .whitespacesAndNewlines) + guard workspaceMode != .worktree || branch?.isEmpty == false else { + throw NativeFeatureClientError.branchRequired + } + let worktreePath = workspaceMode == .local ? worktreePath : nil let model = modelSelection( selection, projectID: route.wireID, @@ -435,6 +492,10 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr model: model, runtimeMode: runtime, interactionMode: interaction, + workspaceMode: workspaceMode, + branch: branch, + worktreePath: worktreePath, + startFromOrigin: startFromOrigin, attachments: attachments ) let pending: PendingBootstrapSubmission @@ -445,7 +506,10 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr pending = PendingBootstrapSubmission( signature: signature, threadID: UUID().uuidString, - identity: CommandIdentity() + identity: CommandIdentity(), + worktreeBranchName: workspaceMode == .worktree + ? Self.temporaryWorktreeBranchName() + : nil ) pendingBootstrapSubmission = pending } @@ -459,6 +523,18 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr model: model, runtimeMode: runtime, interactionMode: interaction, + branch: branch, + worktreePath: worktreePath, + worktreePreparation: pending.worktreeBranchName.flatMap { worktreeBranch in + branch.map { + ThreadWorktreePreparation( + projectCwd: routedProject.workspaceRoot, + baseBranch: $0, + branch: worktreeBranch, + startFromOrigin: startFromOrigin + ) + } + }, attachments: uploads, commandID: pending.identity.commandID, messageID: pending.identity.messageID, @@ -519,6 +595,8 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr environmentID: environment.id, environmentName: environment.label, title: title, + branch: workspaceMode == .worktree ? pending.worktreeBranchName : branch, + worktreePath: worktreePath, providerID: model.instanceId, providerName: providerDisplayName(model.instanceId), modelID: model.model, @@ -889,6 +967,46 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr return NativeWorkspaceMapper.files(result.entries, directory: path) } + func searchProjectFiles( + projectID: String, + query: String, + limit: Int + ) async throws -> [FeatureFileEntry] { + let route = try projectRoute(for: projectID) + let project = try project(for: route) + let result = try await route.client.searchProjectEntries( + cwd: project.workspaceRoot, + query: query, + limit: limit + ) + return result.entries.map(Self.mapSearchEntry) + } + + func searchThreadFiles( + threadID: String, + query: String, + limit: Int + ) async throws -> [FeatureFileEntry] { + let route = try threadRoute(for: threadID) + let context = try workspaceContext(route: route) + let result = try await route.client.searchProjectEntries( + cwd: context.cwd, + query: query, + limit: limit + ) + return result.entries.map(Self.mapSearchEntry) + } + + private static func mapSearchEntry(_ entry: ProjectEntry) -> FeatureFileEntry { + let name = URL(fileURLWithPath: entry.path).lastPathComponent + return FeatureFileEntry( + path: entry.path, + name: name, + kind: entry.kind == .directory ? .directory : .file, + isHidden: name.hasPrefix(".") + ) + } + func readFile(threadID: String, path: String) async throws -> FeatureFileContent { let route = try threadRoute(for: threadID) let context = try workspaceContext(route: route) @@ -1129,6 +1247,15 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr ) } + private func project(for route: NativeProjectRoute) throws -> OrchestrationProject { + guard let project = shellsByEnvironmentID[route.environmentID]?.projects.first(where: { + $0.id == route.wireID + }) else { + throw NativeFeatureClientError.projectNotFound + } + return project + } + private func threadRoute(for threadID: String) throws -> NativeThreadRoute { guard let environmentID = threadEnvironmentIDs[threadID], let wireID = threadWireIDs[threadID], @@ -1408,8 +1535,11 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr switch event { case let .snapshot(config): self.latestServerConfig = config + self.serverConfigsByEnvironmentID[activeClient.environment.id] = config case let .providerStatuses(providers): - self.latestServerConfig = ServerConfigSnapshot(providers: providers) + let config = ServerConfigSnapshot(providers: providers) + self.latestServerConfig = config + self.serverConfigsByEnvironmentID[activeClient.environment.id] = config case .unrelated: continue } @@ -1854,10 +1984,13 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr return await withTaskGroup(of: EnvironmentShellLoad.self) { group in for pair in clients { group.addTask { - EnvironmentShellLoad( + async let shell: OrchestrationShellSnapshot? = try? await pair.client.shellSnapshot() + async let config: ServerConfigSnapshot? = try? await pair.client.serverConfig() + return await EnvironmentShellLoad( environment: pair.environment, client: pair.client, - shell: try? await pair.client.shellSnapshot() + shell: shell, + config: config ) } } @@ -1879,6 +2012,9 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr let savedIDs = Set(savedEnvironments.map(\.id)) environmentClients = environmentClients.filter { savedIDs.contains($0.key) } shellsByEnvironmentID = shellsByEnvironmentID.filter { savedIDs.contains($0.key) } + serverConfigsByEnvironmentID = serverConfigsByEnvironmentID.filter { + savedIDs.contains($0.key) + } archivedThreadsByEnvironmentID = archivedThreadsByEnvironmentID.filter { savedIDs.contains($0.key) } @@ -1891,6 +2027,12 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr for load in loads { environmentClients[load.environment.id] = load.client + if let config = load.config { + serverConfigsByEnvironmentID[load.environment.id] = config + if load.environment.id == activeEnvironment?.id { + latestServerConfig = config + } + } if let shell = load.shell { shellsByEnvironmentID[load.environment.id] = shell environmentConnectionStates[load.environment.id] = .connected @@ -2358,7 +2500,15 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr ) } } - let activeShell = shellsByEnvironmentID[activeEnvironment.id] + let providersByEnvironment = environments.reduce( + into: [String: [FeatureProvider]]() + ) { catalogues, environment in + guard let shell = shellsByEnvironmentID[environment.id] else { return } + catalogues[environment.id] = mapProviders( + shell, + config: serverConfigsByEnvironmentID[environment.id] + ) + } return FeatureSnapshot( connection: FeatureConnection( state: connectionState, @@ -2371,7 +2521,8 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr }, projects: projects, threads: threads, - providers: activeShell.map(mapProviders) ?? [], + providers: providersByEnvironment[activeEnvironment.id] ?? [], + providersByEnvironment: providersByEnvironment, settings: loadSettings() ) } @@ -2999,8 +3150,11 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr .default } - private func mapProviders(_ shell: OrchestrationShellSnapshot) -> [FeatureProvider] { - if let providers = latestServerConfig?.providers, !providers.isEmpty { + private func mapProviders( + _ shell: OrchestrationShellSnapshot, + config: ServerConfigSnapshot? + ) -> [FeatureProvider] { + if let providers = config?.providers, !providers.isEmpty { return providers.map { provider in FeatureProvider( id: provider.instanceId, @@ -3030,6 +3184,24 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr isDefault: model.isDefault ?? false, options: options ) + }, + slashCommands: (provider.slashCommands ?? []).map { command in + FeatureProviderSlashCommand( + name: command.name, + description: command.description, + inputHint: command.input?.hint + ) + }, + skills: (provider.skills ?? []).map { skill in + FeatureProviderSkill( + name: skill.name, + displayName: skill.displayName, + description: skill.description, + shortDescription: skill.shortDescription, + path: skill.path, + scope: skill.scope, + isEnabled: skill.enabled + ) } ) } @@ -3408,6 +3580,10 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, FeaturePr return "\(compact.prefix(69).trimmingCharacters(in: .whitespacesAndNewlines))..." } + private static func temporaryWorktreeBranchName() -> String { + "t3code/\(UUID().uuidString.prefix(8).lowercased())" + } + private func previewText(_ text: String?) -> String? { guard let text else { return nil } let compact = text.split(whereSeparator: \.isWhitespace).joined(separator: " ") @@ -3884,6 +4060,7 @@ private struct EnvironmentShellLoad: Sendable { let environment: Environment let client: T3Client let shell: OrchestrationShellSnapshot? + let config: ServerConfigSnapshot? } private struct EntityWireOwner: Hashable { @@ -3937,6 +4114,10 @@ private struct BootstrapSubmissionSignature: Equatable { let model: ModelSelection let runtimeMode: RuntimeMode let interactionMode: InteractionMode + let workspaceMode: FeatureWorkspaceMode + let branch: String? + let worktreePath: String? + let startFromOrigin: Bool let attachments: [FeatureUploadAttachment] } @@ -3944,6 +4125,7 @@ private struct PendingBootstrapSubmission { let signature: BootstrapSubmissionSignature let threadID: String let identity: CommandIdentity + let worktreeBranchName: String? } private struct TurnSubmissionSignature: Equatable { @@ -3968,6 +4150,7 @@ private enum NativeFeatureClientError: LocalizedError { case approvalNotFound case inputRequestNotFound case invalidProjectPath + case branchRequired case terminalNotOpen case deviceSessionNotFound case missingScope(String) @@ -3983,6 +4166,7 @@ private enum NativeFeatureClientError: LocalizedError { case .approvalNotFound: "The approval request is no longer active." case .inputRequestNotFound: "The input request is no longer active." case .invalidProjectPath: "Enter a workspace path on the connected environment." + case .branchRequired: "Choose a base branch for the new worktree." 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." diff --git a/apps/swift-ios/Core/ServerConfigModels.swift b/apps/swift-ios/Core/ServerConfigModels.swift index d62606842c..40321c05a0 100644 --- a/apps/swift-ios/Core/ServerConfigModels.swift +++ b/apps/swift-ios/Core/ServerConfigModels.swift @@ -82,6 +82,26 @@ public struct ServerProviderModelSnapshot: Codable, Identifiable, Equatable, Sen public let capabilities: ServerModelCapabilities? } +public struct ServerProviderSlashCommandSnapshot: Codable, Equatable, Sendable { + public struct Input: Codable, Equatable, Sendable { + public let hint: String + } + + public let name: String + public let description: String? + public let input: Input? +} + +public struct ServerProviderSkillSnapshot: Codable, Equatable, Sendable { + public let name: String + public let description: String? + public let path: String + public let scope: String? + public let enabled: Bool + public let displayName: String? + public let shortDescription: String? +} + public struct ServerProviderSnapshot: Codable, Identifiable, Equatable, Sendable { public var id: String { instanceId } @@ -102,6 +122,8 @@ public struct ServerProviderSnapshot: Codable, Identifiable, Equatable, Sendable public let availability: String? public let unavailableReason: String? public let models: [ServerProviderModelSnapshot] + public let slashCommands: [ServerProviderSlashCommandSnapshot]? + public let skills: [ServerProviderSkillSnapshot]? } /// Narrow decode view of the much larger `ServerConfig` RPC result. diff --git a/apps/swift-ios/Core/T3Client.swift b/apps/swift-ios/Core/T3Client.swift index 6154839b29..a3ac105adb 100644 --- a/apps/swift-ios/Core/T3Client.swift +++ b/apps/swift-ios/Core/T3Client.swift @@ -237,6 +237,7 @@ public actor T3Client { interactionMode: InteractionMode = .default, branch: String? = nil, worktreePath: String? = nil, + worktreePreparation: ThreadWorktreePreparation? = nil, attachments: [UploadChatImageAttachment] = [], commandID: String = UUID().uuidString, messageID: String = UUID().uuidString, @@ -253,6 +254,7 @@ public actor T3Client { interactionMode: interactionMode, branch: branch, worktreePath: worktreePath, + worktreePreparation: worktreePreparation, attachments: attachments, commandID: commandID, messageID: messageID, @@ -1140,6 +1142,7 @@ public enum OrchestrationCommands { interactionMode: InteractionMode = .default, branch: String? = nil, worktreePath: String? = nil, + worktreePreparation: ThreadWorktreePreparation? = nil, attachments: [UploadChatImageAttachment] = [], commandID: String = UUID().uuidString, messageID: String = UUID().uuidString, @@ -1156,6 +1159,19 @@ public enum OrchestrationCommands { "createdAt": .string(createdAt), ] create["createdAt"] = .string(createdAt) + var bootstrap: [String: JSONValue] = ["createThread": .object(create)] + if let worktreePreparation { + var prepareWorktree: [String: JSONValue] = [ + "projectCwd": .string(worktreePreparation.projectCwd), + "baseBranch": .string(worktreePreparation.baseBranch), + "branch": .string(worktreePreparation.branch), + ] + if worktreePreparation.startFromOrigin { + prepareWorktree["startFromOrigin"] = .bool(true) + } + bootstrap["prepareWorktree"] = .object(prepareWorktree) + bootstrap["runSetupScript"] = .bool(true) + } return .object([ "type": .string("thread.turn.start"), "commandId": .string(commandID), @@ -1170,7 +1186,7 @@ public enum OrchestrationCommands { "titleSeed": .string(title), "runtimeMode": .string(runtimeMode.rawValue), "interactionMode": .string(interactionMode.rawValue), - "bootstrap": .object(["createThread": .object(create)]), + "bootstrap": .object(bootstrap), "createdAt": .string(createdAt), ]) } diff --git a/apps/swift-ios/Core/WorkspaceModels.swift b/apps/swift-ios/Core/WorkspaceModels.swift index dcaab19870..5a37dd3122 100644 --- a/apps/swift-ios/Core/WorkspaceModels.swift +++ b/apps/swift-ios/Core/WorkspaceModels.swift @@ -28,6 +28,25 @@ public struct ProjectWriteFileResult: Codable, Equatable, Sendable { public let relativePath: String } +public struct ThreadWorktreePreparation: Equatable, Sendable { + public let projectCwd: String + public let baseBranch: String + public let branch: String + public let startFromOrigin: Bool + + public init( + projectCwd: String, + baseBranch: String, + branch: String, + startFromOrigin: Bool + ) { + self.projectCwd = projectCwd + self.baseBranch = baseBranch + self.branch = branch + self.startFromOrigin = startFromOrigin + } +} + public struct FilesystemBrowseEntry: Codable, Equatable, Sendable { public let name: String public let fullPath: String diff --git a/apps/swift-ios/Features/Chat/FeatureComposerCommandPopover.swift b/apps/swift-ios/Features/Chat/FeatureComposerCommandPopover.swift new file mode 100644 index 0000000000..2ef54f0df2 --- /dev/null +++ b/apps/swift-ios/Features/Chat/FeatureComposerCommandPopover.swift @@ -0,0 +1,120 @@ +import SwiftUI + +struct FeatureComposerCommandPopover: View { + let triggerKind: FeatureComposerTriggerKind + let items: [FeatureComposerMenuItem] + let isLoading: Bool + let errorMessage: String? + let pathSearchAvailable: Bool + let onSelect: (FeatureComposerMenuItem) -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + if items.isEmpty { + Text(emptyMessage) + .font(T3Typography.supporting) + .foregroundStyle(T3Colors.textSecondary) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 14) + .padding(.vertical, 12) + } else { + ScrollView { + LazyVStack(spacing: 0) { + ForEach(Array(items.enumerated()), id: \.element.id) { index, item in + Button { + onSelect(item) + } label: { + FeatureComposerCommandRow(item: item) + } + .buttonStyle(.plain) + .accessibilityIdentifier("composer-suggestion-\(item.id)") + + if index < items.count - 1 { + Divider() + .overlay(T3Colors.separator) + .padding(.leading, 40) + } + } + } + } + .scrollIndicators(.hidden) + } + } + .frame(height: menuHeight, alignment: .top) + .background(T3Colors.surfaceRaised.opacity(0.98)) + .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous)) + .overlay { + RoundedRectangle(cornerRadius: 16, style: .continuous) + .stroke(T3Colors.border, lineWidth: 1) + } + .accessibilityLabel(groupLabel) + .accessibilityIdentifier("composer-command-menu") + } + + private var groupLabel: String { + switch triggerKind { + case .slashCommand: return "Commands" + case .model: return "Models" + case .skill: return "Skills" + case .path: return "Files" + } + } + + private var emptyMessage: String { + if isLoading { return "Searching files…" } + if let errorMessage, !errorMessage.isEmpty { return errorMessage } + switch triggerKind { + case .slashCommand: return "No matching commands." + case .model: return "No matching models." + case .skill: return "No matching skills." + case .path where !pathSearchAvailable: return "File search is unavailable." + case .path: return "Type a file name to search." + } + } + + private var menuHeight: CGFloat { + guard !items.isEmpty else { return 48 } + let rowHeight: CGFloat = 47 + return min(CGFloat(items.count) * rowHeight, 188) + } +} + +private struct FeatureComposerCommandRow: View { + let item: FeatureComposerMenuItem + + var body: some View { + HStack(spacing: 10) { + Image(systemName: iconName) + .font(.system(size: 14, weight: .medium)) + .foregroundStyle(T3Colors.textTertiary) + .frame(width: 17) + + Text(item.label) + .font(T3Typography.control) + .foregroundStyle(T3Colors.textPrimary) + .lineLimit(1) + + if !item.description.isEmpty { + Text(item.description) + .font(T3Typography.supporting) + .foregroundStyle(T3Colors.textTertiary) + .lineLimit(1) + .frame(maxWidth: .infinity, alignment: .leading) + } else { + Spacer(minLength: 0) + } + } + .padding(.horizontal, 14) + .frame(minHeight: 46) + .contentShape(Rectangle()) + } + + private var iconName: String { + switch item { + case .modelCommand, .providerCommand: return "terminal" + case .model: return "cpu" + case .skill: return "shippingbox" + case let .path(entry): return entry.kind == .directory ? "folder" : "doc" + } + } +} diff --git a/apps/swift-ios/Features/Chat/FeatureComposerPowerFeatures.swift b/apps/swift-ios/Features/Chat/FeatureComposerPowerFeatures.swift new file mode 100644 index 0000000000..8d17030dd4 --- /dev/null +++ b/apps/swift-ios/Features/Chat/FeatureComposerPowerFeatures.swift @@ -0,0 +1,346 @@ +import Foundation + +/// Provider- and project-scoped data used by the composer command menu. +/// The feature layer supplies these values because the composer should not +/// know how a particular environment fetches provider or workspace data. +struct FeatureComposerPowerFeatures { + typealias PathSearch = (_ query: String) async throws -> [FeatureComposerPathEntry] + + var slashCommands: [FeatureProviderSlashCommand] + var skills: [FeatureProviderSkill] + var pathSearchScopeID: String + var searchPaths: PathSearch? + + init( + slashCommands: [FeatureProviderSlashCommand] = [], + skills: [FeatureProviderSkill] = [], + pathSearchScopeID: String = "", + searchPaths: PathSearch? = nil + ) { + self.slashCommands = slashCommands + self.skills = skills + self.pathSearchScopeID = pathSearchScopeID + self.searchPaths = searchPaths + } + + static let disabled = FeatureComposerPowerFeatures() +} + +public struct FeatureProviderSlashCommand: Identifiable, Sendable, Equatable, Hashable, Codable { + public var id: String { name } + public let name: String + public let description: String? + public let inputHint: String? + + public init( + name: String, + description: String? = nil, + inputHint: String? = nil + ) { + self.name = name + self.description = description + self.inputHint = inputHint + } +} + +public struct FeatureProviderSkill: Identifiable, Sendable, Equatable, Hashable, Codable { + public var id: String { name } + public let name: String + public let displayName: String? + public let description: String? + public let shortDescription: String? + public let path: String + public let scope: String? + public let isEnabled: Bool + + public init( + name: String, + displayName: String? = nil, + description: String? = nil, + shortDescription: String? = nil, + path: String = "", + scope: String? = nil, + isEnabled: Bool = true + ) { + self.name = name + self.displayName = displayName + self.description = description + self.shortDescription = shortDescription + self.path = path + self.scope = scope + self.isEnabled = isEnabled + } +} + +struct FeatureComposerPathEntry: Identifiable, Sendable, Equatable, Hashable { + enum Kind: String, Sendable, Equatable, Hashable { + case file + case directory + } + + var id: String { path } + let path: String + let kind: Kind + + init(path: String, kind: Kind) { + self.path = path + self.kind = kind + } + + var name: String { + let normalized = path.replacingOccurrences(of: "\\", with: "/") + return normalized.split(separator: "/", omittingEmptySubsequences: true) + .last + .map(String.init) ?? path + } + + var parentPath: String { + let normalized = path.replacingOccurrences(of: "\\", with: "/") + let parts = normalized.split(separator: "/", omittingEmptySubsequences: true) + return parts.dropLast().joined(separator: "/") + } +} + +enum FeatureComposerTriggerKind: Sendable, Equatable { + case slashCommand + case model + case skill + case path +} + +struct FeatureComposerTrigger: Sendable, Equatable { + let kind: FeatureComposerTriggerKind + let query: String + let range: Range +} + +/// Mirrors the shared web/mobile trigger grammar while keeping this target +/// independent of the TypeScript runtime. +enum FeatureComposerTriggerParser { + static func detect(in text: String, cursorOffset: Int? = nil) -> FeatureComposerTrigger? { + let cursor = min(max(cursorOffset ?? text.count, 0), text.count) + let cursorIndex = text.index(text.startIndex, offsetBy: cursor) + let prefix = text[.. text.startIndex { + let previous = text.index(before: tokenStartIndex) + if text[previous].isWhitespace { break } + tokenStartIndex = previous + } + let token = String(text[tokenStartIndex.., + in text: String, + with replacement: String + ) -> String { + let lower = min(max(range.lowerBound, 0), text.count) + let upper = min(max(range.upperBound, lower), text.count) + let start = text.index(text.startIndex, offsetBy: lower) + let end = text.index(text.startIndex, offsetBy: upper) + return String(text[.. String { + let normalized = path.replacingOccurrences(of: "\\", with: "/") + let basename = normalized.split(separator: "/", omittingEmptySubsequences: true) + .last + .map(String.init) ?? path + let label = basename + .replacingOccurrences(of: "\\", with: "\\\\") + .replacingOccurrences(of: "[", with: "\\[") + .replacingOccurrences(of: "]", with: "\\]") + return "[\(label)](\(encodeDestination(path)))" + } + + private static func encodeDestination(_ path: String) -> String { + let unescaped = Set( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;,/:@&=+$-_.!~*'" + ) + return path.utf8.map { byte -> String in + guard byte < 128, + let scalar = UnicodeScalar(Int(byte)), + unescaped.contains(Character(String(scalar))) else { + return String(format: "%%%02X", byte) + } + return String(scalar) + }.joined() + } +} + +enum FeatureComposerMenuItem: Identifiable, Sendable, Equatable { + case modelCommand + case model(selection: FeatureSelection, label: String, description: String) + case providerCommand(FeatureProviderSlashCommand) + case skill(FeatureProviderSkill) + case path(FeatureComposerPathEntry) + + var id: String { + switch self { + case .modelCommand: "command:model" + case let .model(selection, _, _): "model:\(selection.providerID):\(selection.modelID)" + case let .providerCommand(command): "command:\(command.id)" + case let .skill(skill): "skill:\(skill.id)" + case let .path(entry): "path:\(entry.path)" + } + } + + var label: String { + switch self { + case .modelCommand: "/model" + case let .model(_, label, _): label + case let .providerCommand(command): "/\(command.name)" + case let .skill(skill): skill.displayName ?? skill.name + case let .path(entry): entry.name + } + } + + var description: String { + switch self { + case .modelCommand: "Switch model" + case let .model(_, _, description): description + case let .providerCommand(command): + command.description ?? command.inputHint ?? "" + case let .skill(skill): + skill.shortDescription ?? skill.description ?? skill.scope ?? "" + case let .path(entry): entry.parentPath + } + } +} + +enum FeatureComposerMenuBuilder { + static func items( + trigger: FeatureComposerTrigger, + providers: [FeatureProvider], + currentSelection: FeatureSelection?, + threadSelection: FeatureSelection?, + powerFeatures: FeatureComposerPowerFeatures, + pathEntries: [FeatureComposerPathEntry] + ) -> [FeatureComposerMenuItem] { + switch trigger.kind { + case .slashCommand: + let query = trigger.query.lowercased() + var items: [FeatureComposerMenuItem] = [] + if query.isEmpty || "model".contains(query) { + items.append(.modelCommand) + } + let commands = powerFeatures.slashCommands + .filter { !["model", "plan", "default"].contains($0.name.lowercased()) } + .filter { query.isEmpty || $0.name.localizedCaseInsensitiveContains(query) } + .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } + items.append(contentsOf: commands.prefix(19).map(FeatureComposerMenuItem.providerCommand)) + return items + + case .model: + let query = trigger.query.trimmingCharacters(in: .whitespacesAndNewlines) + let lockedProviderID = threadSelection.flatMap { selection in + providers.first { $0.id == selection.providerID }? + .requiresNewThreadForModelChange == true + ? selection.providerID + : nil + } + return providers + .filter(\.isAvailable) + .filter { lockedProviderID == nil || $0.id == lockedProviderID } + .flatMap { provider in + provider.models + .filter { model in + guard lockedProviderID != nil, let threadSelection else { return true } + return model.id == threadSelection.modelID + } + .map { model in + ( + item: FeatureComposerMenuItem.model( + selection: FeatureSelection( + providerID: provider.id, + modelID: model.id, + options: currentSelection?.providerID == provider.id + && currentSelection?.modelID == model.id + ? currentSelection?.options ?? [] + : DailyUXModelOptions.defaults(for: model) + ), + label: model.name, + description: provider.name + ), + searchText: "\(provider.name) \(model.name) \(model.id)" + ) + } + } + .filter { query.isEmpty || $0.searchText.localizedCaseInsensitiveContains(query) } + .prefix(20) + .map(\.item) + + case .skill: + let query = trigger.query.trimmingCharacters(in: .whitespacesAndNewlines) + return powerFeatures.skills + .filter(\.isEnabled) + .filter { skill in + guard !query.isEmpty else { return true } + return [skill.name, skill.displayName, skill.shortDescription, skill.description] + .compactMap { $0 } + .contains { $0.localizedCaseInsensitiveContains(query) } + } + .sorted { + ($0.displayName ?? $0.name).localizedStandardCompare($1.displayName ?? $1.name) + == .orderedAscending + } + .prefix(20) + .map(FeatureComposerMenuItem.skill) + + case .path: + return pathEntries + .uniquedByPath() + .prefix(20) + .map(FeatureComposerMenuItem.path) + } + } +} + +private extension Array where Element == FeatureComposerPathEntry { + func uniquedByPath() -> [Element] { + var seen = Set() + return filter { seen.insert($0.path).inserted } + } +} diff --git a/apps/swift-ios/Features/Chat/FeatureComposerView.swift b/apps/swift-ios/Features/Chat/FeatureComposerView.swift index c944276624..5dc6ade814 100644 --- a/apps/swift-ios/Features/Chat/FeatureComposerView.swift +++ b/apps/swift-ios/Features/Chat/FeatureComposerView.swift @@ -3,6 +3,9 @@ import SwiftUI struct FeatureComposerView: View { @State private var isManuallyExpanded = false @State private var attachmentPreparation = FeatureAttachmentPreparationState() + @State private var pathEntries: [FeatureComposerPathEntry] = [] + @State private var isPathSearchLoading = false + @State private var pathSearchError: String? @Binding private var text: String @Binding private var selection: FeatureSelection? @@ -18,6 +21,7 @@ struct FeatureComposerView: View { private let pendingApprovals: [FeatureApproval] private let pendingUserInputs: [FeatureUserInput] private let isResolvingRequest: Bool + private let powerFeatures: FeatureComposerPowerFeatures private let onSend: () -> Void private let onStop: () -> Void private let onApprovalDecision: ((String, FeatureApprovalDecision) -> Void)? @@ -39,6 +43,7 @@ struct FeatureComposerView: View { pendingApprovals: [FeatureApproval] = [], pendingUserInputs: [FeatureUserInput] = [], isResolvingRequest: Bool = false, + powerFeatures: FeatureComposerPowerFeatures = .disabled, onApprovalDecision: ((String, FeatureApprovalDecision) -> Void)? = nil, onUserInputSubmit: ((String, [String: FeatureInputAnswer]) -> Void)? = nil ) { @@ -57,11 +62,53 @@ struct FeatureComposerView: View { self.pendingApprovals = pendingApprovals self.pendingUserInputs = pendingUserInputs self.isResolvingRequest = isResolvingRequest + self.powerFeatures = powerFeatures self.onApprovalDecision = onApprovalDecision self.onUserInputSubmit = onUserInputSubmit } var body: some View { + composerSurface + .overlay(alignment: .top) { + if showsCommandMenu, let trigger = composerTrigger { + FeatureComposerCommandPopover( + triggerKind: trigger.kind, + items: commandMenuItems, + isLoading: isPathSearchLoading, + errorMessage: pathSearchError, + pathSearchAvailable: powerFeatures.searchPaths != nil, + onSelect: selectCommandItem + ) + .alignmentGuide(.top) { dimensions in + dimensions[.bottom] + 8 + } + } + } + .padding(.horizontal, 12) + .padding(.top, 12) + .padding(.bottom, 10) + .background { + LinearGradient( + colors: [.clear, .black.opacity(0.94), .black], + startPoint: .top, + endPoint: .bottom + ) + .ignoresSafeArea() + } + .onChange(of: focused.wrappedValue) { + if !focused.wrappedValue, + textIsEmpty, + attachments.isEmpty, + !attachmentPreparation.isPreparing { + isManuallyExpanded = false + } + } + .task(id: pathSearchRequest) { + await updatePathSearch() + } + } + + private var composerSurface: some View { VStack(spacing: 0) { if let approval = pendingApprovals.first, let onApprovalDecision { FeatureComposerApprovalPanel( @@ -94,25 +141,6 @@ struct FeatureComposerView: View { .stroke(Color.white.opacity(0.105), lineWidth: 1) } .clipShape(composerShape) - .padding(.horizontal, 12) - .padding(.top, 12) - .padding(.bottom, 10) - .background { - LinearGradient( - colors: [.clear, .black.opacity(0.94), .black], - startPoint: .top, - endPoint: .bottom - ) - .ignoresSafeArea() - } - .onChange(of: focused.wrappedValue) { - if !focused.wrappedValue, - textIsEmpty, - attachments.isEmpty, - !attachmentPreparation.isPreparing { - isManuallyExpanded = false - } - } } private var collapsedComposer: some View { @@ -276,7 +304,8 @@ struct FeatureComposerView: View { } private var canSend: Bool { - FeatureComposerSubmissionEligibility.canSend( + guard composerTrigger?.kind != .model else { return false } + return FeatureComposerSubmissionEligibility.canSend( text: text, attachmentCount: attachments.count, imagesAllowed: imagesAllowed, @@ -289,6 +318,99 @@ struct FeatureComposerView: View { DailyUXModelOptions.supportsImages(selection: selection, providers: providers) } + private var composerTrigger: FeatureComposerTrigger? { + FeatureComposerTriggerParser.detect(in: text) + } + + private var commandMenuItems: [FeatureComposerMenuItem] { + guard let composerTrigger else { return [] } + return FeatureComposerMenuBuilder.items( + trigger: composerTrigger, + providers: providers, + currentSelection: selection, + threadSelection: threadSelection, + powerFeatures: powerFeatures, + pathEntries: pathEntries + ) + } + + private var showsCommandMenu: Bool { + isExpanded + && pendingApprovals.isEmpty + && pendingUserInputs.isEmpty + && composerTrigger != nil + } + + private var pathSearchRequest: FeatureComposerPathSearchRequest? { + guard let trigger = composerTrigger, + trigger.kind == .path, + powerFeatures.searchPaths != nil else { + return nil + } + let query = trigger.query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !query.isEmpty else { return nil } + return FeatureComposerPathSearchRequest( + scopeID: powerFeatures.pathSearchScopeID, + query: query + ) + } + + @MainActor + private func updatePathSearch() async { + guard let request = pathSearchRequest, let searchPaths = powerFeatures.searchPaths else { + pathEntries = [] + isPathSearchLoading = false + pathSearchError = nil + return + } + + pathEntries = [] + pathSearchError = nil + isPathSearchLoading = true + do { + try await Task.sleep(for: .milliseconds(140)) + let result = try await searchPaths(request.query) + guard !Task.isCancelled else { return } + pathEntries = result + isPathSearchLoading = false + } catch is CancellationError { + return + } catch { + guard !Task.isCancelled else { return } + pathSearchError = "Couldn’t search files." + isPathSearchLoading = false + } + } + + private func selectCommandItem(_ item: FeatureComposerMenuItem) { + guard let trigger = composerTrigger else { return } + let replacement: String + switch item { + case .modelCommand: + replacement = "/model " + case let .model(nextSelection, _, _): + selection = nextSelection + replacement = "" + case let .providerCommand(command): + replacement = "/\(command.name) " + case let .skill(skill): + replacement = "$\(skill.name) " + case let .path(entry): + replacement = FeatureComposerFileLinkSerializer.markdownLink(for: entry.path) + " " + } + text = FeatureComposerTriggerParser.replacing( + trigger.range, + in: text, + with: replacement + ) + pathEntries = [] + pathSearchError = nil + Task { @MainActor in + await Task.yield() + focused.wrappedValue = true + } + } + private func performPrimaryAction() { if showsStop { onStop() @@ -299,6 +421,11 @@ struct FeatureComposerView: View { } +private struct FeatureComposerPathSearchRequest: Hashable { + let scopeID: String + let query: String +} + enum FeatureComposerSubmissionEligibility { static func canSend( text: String, diff --git a/apps/swift-ios/Features/Chat/ThreadDetailView.swift b/apps/swift-ios/Features/Chat/ThreadDetailView.swift index 7f78c761c0..d19940dc4b 100644 --- a/apps/swift-ios/Features/Chat/ThreadDetailView.swift +++ b/apps/swift-ios/Features/Chat/ThreadDetailView.swift @@ -139,7 +139,7 @@ public struct ThreadDetailView: View { defaultSelection.modelID == modelID { return defaultSelection } - let provider = model.snapshot.providers.first { $0.id == providerID } + let provider = threadProviders.first { $0.id == providerID } let featureModel = provider?.models.first { $0.id == modelID } let savedOptions = detail?.thread.modelOptions ?? thread.modelOptions return FeatureSelection( @@ -323,7 +323,7 @@ public struct ThreadDetailView: View { text: $draft, selection: $selection, attachments: $attachments, - providers: model.snapshot.providers, + providers: threadProviders, threadSelection: currentSelection, isSending: isSending, isWorking: detail.thread.state == .working || detail.thread.state == .queued, @@ -335,6 +335,7 @@ public struct ThreadDetailView: View { pendingApprovals: detail.approvals, pendingUserInputs: detail.userInputs, isResolvingRequest: model.isPerformingAction, + powerFeatures: composerPowerFeatures, onApprovalDecision: { id, decision in Task { await model.resolveApproval(id, decision: decision) } }, @@ -358,6 +359,33 @@ public struct ThreadDetailView: View { } } + private var composerPowerFeatures: FeatureComposerPowerFeatures { + let selectedProviderID = selection?.providerID ?? currentSelection?.providerID + let provider = threadProviders.first { $0.id == selectedProviderID } + return FeatureComposerPowerFeatures( + slashCommands: provider?.slashCommands ?? [], + skills: provider?.skills ?? [], + pathSearchScopeID: currentThread.id, + searchPaths: { query in + try await model.client.searchThreadFiles( + threadID: currentThread.id, + query: query, + limit: 20 + ).map { entry in + FeatureComposerPathEntry( + path: entry.path, + kind: entry.kind == .directory ? .directory : .file + ) + } + } + ) + } + + private var threadProviders: [FeatureProvider] { + let project = model.snapshot.projects.first { $0.id == currentThread.projectID } + return DailyUXCreationContext.providers(for: project, in: model.snapshot) + } + private func dismissKeyboard() { guard composerFocused else { return } composerFocused = false diff --git a/apps/swift-ios/Features/Shared/FeatureClient.swift b/apps/swift-ios/Features/Shared/FeatureClient.swift index bd4cab9954..7ec9f84b2e 100644 --- a/apps/swift-ios/Features/Shared/FeatureClient.swift +++ b/apps/swift-ios/Features/Shared/FeatureClient.swift @@ -62,6 +62,16 @@ public protocol FeatureClient: AnyObject { func saveSettings(_ settings: FeatureSettings) async throws func listFiles(threadID: String, path: String?) async throws -> [FeatureFileEntry] + func searchProjectFiles( + projectID: String, + query: String, + limit: Int + ) async throws -> [FeatureFileEntry] + func searchThreadFiles( + threadID: String, + query: String, + limit: Int + ) async throws -> [FeatureFileEntry] func readFile(threadID: String, path: String) async throws -> FeatureFileContent func loadReview(threadID: String) async throws -> FeatureReview @@ -174,6 +184,22 @@ public extension FeatureClient { throw FeatureCapabilityUnavailable("Files") } + func searchProjectFiles( + projectID: String, + query: String, + limit: Int + ) async throws -> [FeatureFileEntry] { + throw FeatureCapabilityUnavailable("File search") + } + + func searchThreadFiles( + threadID: String, + query: String, + limit: Int + ) async throws -> [FeatureFileEntry] { + throw FeatureCapabilityUnavailable("File search") + } + func readFile(threadID: String, path: String) async throws -> FeatureFileContent { throw FeatureCapabilityUnavailable("File preview") } diff --git a/apps/swift-ios/Features/Shared/FeatureComposerDraftStore.swift b/apps/swift-ios/Features/Shared/FeatureComposerDraftStore.swift index 5dfc0e4dec..f8fe7eee2b 100644 --- a/apps/swift-ios/Features/Shared/FeatureComposerDraftStore.swift +++ b/apps/swift-ios/Features/Shared/FeatureComposerDraftStore.swift @@ -4,19 +4,41 @@ public struct FeatureComposerDraft: Sendable, Equatable { public var text: String public var attachments: [FeatureDraftAttachment] public var selection: FeatureSelection? + public var workspace: FeatureComposerWorkspaceDraft? public init( text: String = "", attachments: [FeatureDraftAttachment] = [], - selection: FeatureSelection? = nil + selection: FeatureSelection? = nil, + workspace: FeatureComposerWorkspaceDraft? = nil ) { self.text = text self.attachments = attachments self.selection = selection + self.workspace = workspace } public var isEmpty: Bool { - text.isEmpty && attachments.isEmpty && selection == nil + text.isEmpty && attachments.isEmpty && selection == nil && workspace == nil + } +} + +public struct FeatureComposerWorkspaceDraft: Sendable, Equatable { + public var mode: FeatureWorkspaceMode + public var branch: String? + public var worktreePath: String? + public var startFromOrigin: Bool + + public init( + mode: FeatureWorkspaceMode, + branch: String?, + worktreePath: String?, + startFromOrigin: Bool + ) { + self.mode = mode + self.branch = branch + self.worktreePath = worktreePath + self.startFromOrigin = startFromOrigin } } @@ -35,18 +57,44 @@ public actor FeatureComposerDraftStore { var text: String var attachments: [PersistedAttachment] var selection: FeatureSelection? + var workspace: PersistedWorkspace? init(_ draft: FeatureComposerDraft) { text = draft.text attachments = draft.attachments.map(PersistedAttachment.init) selection = draft.selection + workspace = draft.workspace.map(PersistedWorkspace.init) } var featureValue: FeatureComposerDraft { FeatureComposerDraft( text: text, attachments: attachments.map(\.featureValue), - selection: selection + selection: selection, + workspace: workspace?.featureValue + ) + } + } + + private struct PersistedWorkspace: Codable { + var mode: FeatureWorkspaceMode + var branch: String? + var worktreePath: String? + var startFromOrigin: Bool + + init(_ workspace: FeatureComposerWorkspaceDraft) { + mode = workspace.mode + branch = workspace.branch + worktreePath = workspace.worktreePath + startFromOrigin = workspace.startFromOrigin + } + + var featureValue: FeatureComposerWorkspaceDraft { + FeatureComposerWorkspaceDraft( + mode: mode, + branch: branch, + worktreePath: worktreePath, + startFromOrigin: startFromOrigin ) } } diff --git a/apps/swift-ios/Features/Shared/FeatureModels.swift b/apps/swift-ios/Features/Shared/FeatureModels.swift index 924c29e9f6..14520fa894 100644 --- a/apps/swift-ios/Features/Shared/FeatureModels.swift +++ b/apps/swift-ios/Features/Shared/FeatureModels.swift @@ -629,6 +629,8 @@ public struct FeatureProvider: Identifiable, Sendable, Equatable, Hashable, Coda public var driver: String public var requiresNewThreadForModelChange: Bool public var models: [FeatureModel] + public var slashCommands: [FeatureProviderSlashCommand]? + public var skills: [FeatureProviderSkill]? public init( id: String, @@ -636,7 +638,9 @@ public struct FeatureProvider: Identifiable, Sendable, Equatable, Hashable, Coda isAvailable: Bool = true, driver: String = "", requiresNewThreadForModelChange: Bool = false, - models: [FeatureModel] = [] + models: [FeatureModel] = [], + slashCommands: [FeatureProviderSlashCommand] = [], + skills: [FeatureProviderSkill] = [] ) { self.id = id self.name = name @@ -644,6 +648,8 @@ public struct FeatureProvider: Identifiable, Sendable, Equatable, Hashable, Coda self.driver = driver self.requiresNewThreadForModelChange = requiresNewThreadForModelChange self.models = models + self.slashCommands = slashCommands + self.skills = skills } } @@ -693,6 +699,9 @@ public struct FeatureSnapshot: Sendable, Equatable, Codable { public var projects: [FeatureProject] public var threads: [FeatureThread] public var providers: [FeatureProvider] + /// Provider catalogues are environment-scoped. `providers` remains the + /// active environment's catalogue for source-compatible consumers. + public var providersByEnvironment: [String: [FeatureProvider]]? public var settings: FeatureSettings public init( @@ -701,6 +710,7 @@ public struct FeatureSnapshot: Sendable, Equatable, Codable { projects: [FeatureProject] = [], threads: [FeatureThread] = [], providers: [FeatureProvider] = [], + providersByEnvironment: [String: [FeatureProvider]]? = nil, settings: FeatureSettings = .init() ) { self.connection = connection @@ -708,6 +718,7 @@ public struct FeatureSnapshot: Sendable, Equatable, Codable { self.projects = projects self.threads = threads self.providers = providers + self.providersByEnvironment = providersByEnvironment self.settings = settings } } diff --git a/apps/swift-ios/Features/Workspace/DailyUXModels.swift b/apps/swift-ios/Features/Workspace/DailyUXModels.swift index 0939b1ba14..a3368adc5a 100644 --- a/apps/swift-ios/Features/Workspace/DailyUXModels.swift +++ b/apps/swift-ios/Features/Workspace/DailyUXModels.swift @@ -114,6 +114,11 @@ enum DailyUXCreationContext { for project: FeatureProject?, in snapshot: FeatureSnapshot ) -> [FeatureProvider] { + if let project, + let providers = snapshot.providersByEnvironment?[project.environmentID], + !providers.isEmpty { + return providers + } guard let project, let activeID = snapshot.environments.first(where: \.isActive)?.id, project.environmentID != activeID else { diff --git a/apps/swift-ios/Features/Workspace/NewThreadView.swift b/apps/swift-ios/Features/Workspace/NewThreadView.swift index 992478cf78..cd66564a85 100644 --- a/apps/swift-ios/Features/Workspace/NewThreadView.swift +++ b/apps/swift-ios/Features/Workspace/NewThreadView.swift @@ -5,6 +5,7 @@ public struct NewThreadView: View { @Bindable var model: FeatureRootModel let submit: (NewTaskRequest) async -> FeatureThread? let onCreated: (FeatureThread) -> Void + private let draftStore: FeatureComposerDraftStore @State private var projectID = "" @State private var prompt = "" @@ -19,16 +20,21 @@ public struct NewThreadView: View { @State private var showingBranchPicker = false @State private var isSubmitting = false @State private var submissionFailed = false + @State private var restoredDraftProjectID: String? + @State private var draftSaveTask: Task? + @State private var submittedSuccessfully = false @FocusState private var promptFocused: Bool public init( model: FeatureRootModel, submit: @escaping (NewTaskRequest) async -> FeatureThread?, - onCreated: @escaping (FeatureThread) -> Void + onCreated: @escaping (FeatureThread) -> Void, + draftStore: FeatureComposerDraftStore = .shared ) { self.model = model self.submit = submit self.onCreated = onCreated + self.draftStore = draftStore } public var body: some View { @@ -57,7 +63,8 @@ public struct NewThreadView: View { focused: $promptFocused, onSend: startTask, onStop: {}, - forceExpanded: true + forceExpanded: true, + powerFeatures: composerPowerFeatures ) } .background(T3Colors.background) @@ -66,15 +73,23 @@ public struct NewThreadView: View { if projectID.isEmpty { projectID = creationProjects.first?.id ?? "" } - if selection == nil { - selection = initialSelection - } } .onChange(of: projectID) { + restoredDraftProjectID = nil selection = initialSelection resetWorkspaceSelection() } - .task(id: projectID) { await loadBranches() } + .onChange(of: prompt) { scheduleDraftSave() } + .onChange(of: selection) { scheduleDraftSave() } + .onChange(of: attachments) { scheduleDraftSave() } + .onChange(of: workspaceMode) { scheduleDraftSave() } + .onChange(of: selectedBranch) { scheduleDraftSave() } + .onChange(of: startFromOrigin) { scheduleDraftSave() } + .task(id: projectID) { await restoreDraftAndLoadBranches() } + .onDisappear { + guard !submittedSuccessfully else { return } + persistCurrentDraftImmediately() + } .sheet(isPresented: $showingBranchPicker) { NewTaskBranchPicker( branches: branches, @@ -119,7 +134,7 @@ public struct NewThreadView: View { Menu { ForEach(creationProjects) { project in Button { - projectID = project.id + selectProject(project.id) } label: { if project.id == projectID { Label(project.name, systemImage: "checkmark") @@ -282,12 +297,43 @@ public struct NewThreadView: View { ) } - /// Provider catalogues are active-device-only. For a passive project, keep - /// its own default selectable without leaking models from another machine. + /// Model and provider capabilities belong to the project's environment, + /// which may not be the connection currently selected in Settings. private var creationProviders: [FeatureProvider] { DailyUXCreationContext.providers(for: selectedProject, in: model.snapshot) } + private var composerPowerFeatures: FeatureComposerPowerFeatures { + let provider = creationProviders.first { + $0.id == selection?.providerID + } + guard let project = selectedProject else { + return FeatureComposerPowerFeatures( + slashCommands: provider?.slashCommands ?? [], + skills: provider?.skills ?? [] + ) + } + return FeatureComposerPowerFeatures( + slashCommands: provider?.slashCommands ?? [], + skills: provider?.skills ?? [], + pathSearchScopeID: project.id, + searchPaths: { query in + try await model.client.searchProjectFiles( + projectID: project.id, + query: query, + limit: 20 + ).map(Self.composerPathEntry) + } + ) + } + + private static func composerPathEntry(_ entry: FeatureFileEntry) -> FeatureComposerPathEntry { + FeatureComposerPathEntry( + path: entry.path, + kind: entry.kind == .directory ? .directory : .file + ) + } + private var canSubmit: Bool { !isSubmitting && !projectID.isEmpty @@ -311,6 +357,9 @@ public struct NewThreadView: View { guard canSubmit else { return } promptFocused = false isSubmitting = true + draftSaveTask?.cancel() + let draftKey = currentDraftKey + let draftSnapshot = composerDraft let request = NewTaskRequest( projectID: projectID, prompt: trimmedPrompt, @@ -330,7 +379,15 @@ public struct NewThreadView: View { ) Task { + if let draftKey { + try? await draftStore.setDraft(draftSnapshot, for: draftKey) + } if let thread = await submit(request) { + submittedSuccessfully = true + draftSaveTask?.cancel() + if let draftKey { + try? await draftStore.removeDraft(for: draftKey) + } onCreated(thread) } else { isSubmitting = false @@ -346,6 +403,12 @@ public struct NewThreadView: View { branchLoadFailed = false } + private func selectProject(_ id: String) { + guard id != projectID else { return } + persistCurrentDraftImmediately() + projectID = id + } + private func setWorkspaceMode(_ mode: FeatureWorkspaceMode) { workspaceMode = mode selectedBranch = switch mode { @@ -370,7 +433,7 @@ public struct NewThreadView: View { branches = loaded.sorted(by: Self.branchSort) if let selectedBranch, - let updated = branches.first(where: { $0.id == selectedBranch.id }) { + let updated = branches.first(where: { $0.name == selectedBranch.name }) { self.selectedBranch = updated } else { self.selectedBranch = switch workspaceMode { @@ -388,6 +451,103 @@ public struct NewThreadView: View { branchesLoading = false } + @MainActor + private func restoreDraftAndLoadBranches() async { + let requestedProjectID = projectID + guard let project = selectedProject, !requestedProjectID.isEmpty else { return } + let key = FeatureComposerDraftStore.newTaskKey(project: project) + let saved = try? await draftStore.draft(for: key) + guard !Task.isCancelled, projectID == requestedProjectID else { return } + + if let saved { + prompt = saved.text + attachments = saved.attachments + selection = saved.selection ?? initialSelection + if let workspace = saved.workspace { + workspaceMode = workspace.mode + selectedBranch = workspace.branch.map { + FeatureWorkspaceBranch( + name: $0, + worktreePath: workspace.worktreePath + ) + } + startFromOrigin = workspace.startFromOrigin + } else { + workspaceMode = .local + selectedBranch = nil + startFromOrigin = true + } + } else { + prompt = "" + attachments = [] + selection = initialSelection + workspaceMode = .local + selectedBranch = nil + startFromOrigin = true + } + restoredDraftProjectID = requestedProjectID + await loadBranches() + } + + private var currentDraftKey: String? { + guard let project = selectedProject else { return nil } + return FeatureComposerDraftStore.newTaskKey(project: project) + } + + private var composerDraft: FeatureComposerDraft { + FeatureComposerDraft( + text: prompt, + attachments: attachments, + selection: selection, + workspace: FeatureComposerWorkspaceDraft( + mode: workspaceMode, + branch: selectedBranch?.name, + worktreePath: workspaceMode == .local + ? NewTaskWorkspaceDefaults.normalizedWorktreePath( + for: selectedBranch, + projectPath: selectedProject?.path ?? "" + ) + : nil, + startFromOrigin: startFromOrigin + ) + ) + } + + private func scheduleDraftSave() { + guard restoredDraftProjectID == projectID, + !submittedSuccessfully, + let key = currentDraftKey else { + return + } + draftSaveTask?.cancel() + let snapshot = composerDraft + draftSaveTask = Task { + do { + try await Task.sleep(for: .milliseconds(220)) + try Task.checkCancellation() + try await draftStore.setDraft(snapshot, for: key) + } catch is CancellationError { + return + } catch { + return + } + } + } + + private func persistCurrentDraftImmediately() { + guard restoredDraftProjectID == projectID, + !submittedSuccessfully, + let key = currentDraftKey else { + return + } + draftSaveTask?.cancel() + let snapshot = composerDraft + draftSaveTask = nil + Task { + try? await draftStore.setDraft(snapshot, for: key) + } + } + private static func branchSort( _ lhs: FeatureWorkspaceBranch, _ rhs: FeatureWorkspaceBranch diff --git a/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift b/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift index e30ec908f0..bcd8a2553a 100644 --- a/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift +++ b/apps/swift-ios/Tests/CoreTests/CoreContractTests.swift @@ -91,6 +91,42 @@ final class CoreContractTests: XCTestCase { ) } + func testFirstSendCanPrepareAWorktreeBeforeDispatchingTheTurn() throws { + let command = try OrchestrationCommands.createThreadAndSend( + threadID: "thread-worktree", + projectID: "project-1", + title: "Build in isolation", + text: "Build in isolation", + model: ModelSelection(instanceId: "codex", model: "gpt-5.6-sol"), + runtimeMode: .fullAccess, + branch: "main", + worktreePreparation: ThreadWorktreePreparation( + projectCwd: "/work/t3", + baseBranch: "main", + branch: "t3code/deadbeef", + startFromOrigin: true + ) + ) + + XCTAssertEqual( + command["bootstrap"]?["prepareWorktree"]?["projectCwd"]?.stringValue, + "/work/t3" + ) + XCTAssertEqual( + command["bootstrap"]?["prepareWorktree"]?["baseBranch"]?.stringValue, + "main" + ) + XCTAssertEqual( + command["bootstrap"]?["prepareWorktree"]?["branch"]?.stringValue, + "t3code/deadbeef" + ) + XCTAssertEqual( + command["bootstrap"]?["prepareWorktree"]?["startFromOrigin"], + .bool(true) + ) + XCTAssertEqual(command["bootstrap"]?["runSetupScript"], .bool(true)) + } + func testEnvironmentStorePersistsSelectionAndClearsRemovedActiveEnvironment() async throws { let directory = FileManager.default.temporaryDirectory .appendingPathComponent("t3-swift-core-\(UUID().uuidString)", isDirectory: true) diff --git a/apps/swift-ios/Tests/CoreTests/NativeContractExpansionTests.swift b/apps/swift-ios/Tests/CoreTests/NativeContractExpansionTests.swift index 31c55215d9..d67695cc27 100644 --- a/apps/swift-ios/Tests/CoreTests/NativeContractExpansionTests.swift +++ b/apps/swift-ios/Tests/CoreTests/NativeContractExpansionTests.swift @@ -179,6 +179,27 @@ final class NativeContractExpansionTests: XCTestCase { "currentValue": true }] } + }, { + "slug": "gpt-5.6-terra", + "name": "GPT-5.6 Terra", + "shortName": "Terra", + "isCustom": false, + "isDefault": false, + "capabilities": null + }], + "slashCommands": [{ + "name": "review", + "description": "Review the current changes", + "input": { "hint": "focus" } + }], + "skills": [{ + "name": "gh-fix-ci", + "description": "Fix CI failures", + "path": "/skills/gh-fix-ci/SKILL.md", + "scope": "user", + "enabled": true, + "displayName": "Fix CI", + "shortDescription": "Debug GitHub Actions" }] }] } @@ -189,6 +210,10 @@ final class NativeContractExpansionTests: XCTestCase { let provider = try XCTUnwrap(config.providers.first) XCTAssertEqual(provider.instanceId, "codex-work") XCTAssertEqual(provider.auth.status, "authenticated") + XCTAssertEqual(provider.models.map(\.slug), ["gpt-5.6-sol", "gpt-5.6-terra"]) + XCTAssertEqual(provider.slashCommands?.first?.name, "review") + XCTAssertEqual(provider.slashCommands?.first?.input?.hint, "focus") + XCTAssertEqual(provider.skills?.first?.displayName, "Fix CI") let model = try XCTUnwrap(provider.models.first) XCTAssertEqual(model.slug, "gpt-5.6-sol") let descriptors = try XCTUnwrap(model.capabilities?.optionDescriptors) diff --git a/apps/swift-ios/Tests/FeatureTests/ComposerDraftStoreTests.swift b/apps/swift-ios/Tests/FeatureTests/ComposerDraftStoreTests.swift index 2bc81d6c9b..9c752f0755 100644 --- a/apps/swift-ios/Tests/FeatureTests/ComposerDraftStoreTests.swift +++ b/apps/swift-ios/Tests/FeatureTests/ComposerDraftStoreTests.swift @@ -19,7 +19,13 @@ struct ComposerDraftStoreTests { let draft = FeatureComposerDraft( text: "Keep this work", attachments: [attachment], - selection: FeatureSelection(providerID: "openai", modelID: "gpt-5.6") + selection: FeatureSelection(providerID: "openai", modelID: "gpt-5.6"), + workspace: FeatureComposerWorkspaceDraft( + mode: .worktree, + branch: "main", + worktreePath: nil, + startFromOrigin: true + ) ) try await store.setDraft(draft, for: "environment:test:thread:one") diff --git a/apps/swift-ios/Tests/FeatureTests/DailyUXNewTaskTests.swift b/apps/swift-ios/Tests/FeatureTests/DailyUXNewTaskTests.swift index 3cf4684c22..2412329361 100644 --- a/apps/swift-ios/Tests/FeatureTests/DailyUXNewTaskTests.swift +++ b/apps/swift-ios/Tests/FeatureTests/DailyUXNewTaskTests.swift @@ -91,7 +91,7 @@ struct DailyUXNewTaskTests { } @Test - func passiveProjectsKeepTheirOwnModelCatalogAndDefault() throws { + func passiveProjectsExposeTheirFullEnvironmentModelCatalogAndDefault() throws { let passiveDefault = FeatureSelection( providerID: "claudeAgent", modelID: "claude-opus-4-1" @@ -148,6 +148,18 @@ struct DailyUXNewTaskTests { name: "Codex", models: [.init(id: "gpt-5.6-sol", name: "GPT-5.6")] ), + ], + providersByEnvironment: [ + "passive": [ + .init( + id: "claudeAgent", + name: "Claude", + models: [ + .init(id: "claude-opus-4-1", name: "Opus"), + .init(id: "claude-sonnet-4", name: "Sonnet"), + ] + ), + ], ] ) @@ -160,7 +172,10 @@ struct DailyUXNewTaskTests { in: snapshot ) #expect(passiveProviders.map(\.id) == ["claudeAgent"]) - #expect(passiveProviders.first?.models.map(\.id) == ["claude-opus-4-1"]) + #expect( + passiveProviders.first?.models.map(\.id) + == ["claude-opus-4-1", "claude-sonnet-4"] + ) #expect( DailyUXCreationContext.initialSelection(for: passiveProject, in: snapshot) == passiveDefault diff --git a/apps/swift-ios/Tests/FeatureTests/FeatureComposerPowerTests.swift b/apps/swift-ios/Tests/FeatureTests/FeatureComposerPowerTests.swift new file mode 100644 index 0000000000..842a268425 --- /dev/null +++ b/apps/swift-ios/Tests/FeatureTests/FeatureComposerPowerTests.swift @@ -0,0 +1,162 @@ +import Testing +@testable import T3Code + +@Suite("Composer power features") +struct FeatureComposerPowerTests { + @Test + func detectsCommandsModelsSkillsAndPathsAtTheCursor() { + #expect( + FeatureComposerTriggerParser.detect(in: "/re") + == FeatureComposerTrigger(kind: .slashCommand, query: "re", range: 0..<3) + ) + #expect( + FeatureComposerTriggerParser.detect(in: "/model claude") + == FeatureComposerTrigger(kind: .model, query: "claude", range: 0..<13) + ) + #expect( + FeatureComposerTriggerParser.detect(in: "Use $dep") + == FeatureComposerTrigger(kind: .skill, query: "dep", range: 4..<8) + ) + #expect( + FeatureComposerTriggerParser.detect(in: "Read @Sources/App") + == FeatureComposerTrigger(kind: .path, query: "Sources/App", range: 5..<17) + ) + + let editedText = "Use @Sources/App then continue" + #expect( + FeatureComposerTriggerParser.detect(in: editedText, cursorOffset: 16) + == FeatureComposerTrigger(kind: .path, query: "Sources/App", range: 4..<16) + ) + } + + @Test + func replacementsPreserveTextOutsideTheActiveTrigger() { + let text = "Review @Sources/App please" + let result = FeatureComposerTriggerParser.replacing( + 7..<19, + in: text, + with: "[App](Sources/App) " + ) + #expect(result == "Review [App](Sources/App) please") + } + + @Test + func fileLinksMatchTheSharedComposerFormat() { + #expect( + FeatureComposerFileLinkSerializer.markdownLink(for: "path/to/package.json") + == "[package.json](path/to/package.json)" + ) + #expect( + FeatureComposerFileLinkSerializer.markdownLink(for: "docs/My File (draft).md") + == "[My File (draft).md](docs/My%20File%20%28draft%29.md)" + ) + #expect( + FeatureComposerFileLinkSerializer.markdownLink(for: "C:\\repo\\src\\index.ts") + == "[index.ts](C:%5Crepo%5Csrc%5Cindex.ts)" + ) + #expect( + FeatureComposerFileLinkSerializer.markdownLink(for: "@scope/package.json") + == "[package.json](@scope/package.json)" + ) + } + + @Test + func commandMenuIncludesProviderCommandsButNotRemovedMobileModes() throws { + let trigger = try #require(FeatureComposerTriggerParser.detect(in: "/")) + let powerFeatures = FeatureComposerPowerFeatures( + slashCommands: [ + FeatureProviderSlashCommand(name: "review", description: "Review changes"), + FeatureProviderSlashCommand(name: "plan", description: "Legacy mode"), + FeatureProviderSlashCommand(name: "default", description: "Legacy mode"), + ] + ) + let items = FeatureComposerMenuBuilder.items( + trigger: trigger, + providers: [], + currentSelection: nil, + threadSelection: nil, + powerFeatures: powerFeatures, + pathEntries: [] + ) + + #expect(items.map(\.label) == ["/model", "/review"]) + } + + @Test + func modelAndSkillMenusFilterTheirCatalogs() throws { + let provider = FeatureProvider( + id: "claude", + name: "Claude", + models: [ + FeatureModel(id: "sonnet", name: "Sonnet"), + FeatureModel(id: "opus", name: "Opus"), + ] + ) + let modelTrigger = try #require( + FeatureComposerTriggerParser.detect(in: "/model op") + ) + let modelItems = FeatureComposerMenuBuilder.items( + trigger: modelTrigger, + providers: [provider], + currentSelection: nil, + threadSelection: nil, + powerFeatures: .disabled, + pathEntries: [] + ) + #expect(modelItems.map(\.label) == ["Opus"]) + + let skillTrigger = try #require(FeatureComposerTriggerParser.detect(in: "$fix")) + let skillItems = FeatureComposerMenuBuilder.items( + trigger: skillTrigger, + providers: [provider], + currentSelection: nil, + threadSelection: nil, + powerFeatures: FeatureComposerPowerFeatures( + skills: [ + FeatureProviderSkill( + name: "gh-fix-ci", + displayName: "Fix CI", + shortDescription: "Repair failing checks" + ), + FeatureProviderSkill(name: "deploy", displayName: "Deploy") + ] + ), + pathEntries: [] + ) + #expect(skillItems.map(\.label) == ["Fix CI"]) + } + + @Test + func modelCommandHonorsProvidersThatLockAThreadModel() throws { + let provider = FeatureProvider( + id: "locked", + name: "Locked provider", + requiresNewThreadForModelChange: true, + models: [ + FeatureModel(id: "current", name: "Current"), + FeatureModel(id: "other", name: "Other"), + ] + ) + let trigger = try #require(FeatureComposerTriggerParser.detect(in: "/model")) + let currentSelection = FeatureSelection( + providerID: "locked", + modelID: "current", + options: [FeatureModelOptionSelection(id: "reasoning", value: .string("high"))] + ) + let items = FeatureComposerMenuBuilder.items( + trigger: trigger, + providers: [provider], + currentSelection: currentSelection, + threadSelection: currentSelection, + powerFeatures: .disabled, + pathEntries: [] + ) + + #expect(items.map(\.label) == ["Current"]) + if case let .model(selection, _, _) = try #require(items.first) { + #expect(selection.options == currentSelection.options) + } else { + Issue.record("Expected a model menu item") + } + } +}