From fa91f066624ded8ddcb16cc0b3c245cc99c30c8f Mon Sep 17 00:00:00 2001 From: weishu Date: Tue, 18 Aug 2026 10:03:05 +0800 Subject: [PATCH] feat(ios): new session flow (A-M3c) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port of the tested Android NEW SESSION reference (B-M3d) to iOS: - HapiProtocol: NewSessionCatalogs (static claude models/efforts + codex reasoning-effort fallback, exact Android data) in Catalog/; CodexModelSummary + CodexModelsResponse wire types (shared/src/apiTypes.ts). - HapiClient: machineCodexModels endpoint (GET /api/machines/:id/codex-models, rpc_target_missing surfaces as APIError); NewSession/NewSessionForm.swift — typed Codable draft (tolerant decode) + NewSessionLogic: exact spawn body per SpawnSessionRequestSchema (yolo incl. false for non-grok/non-codex-family, permissionMode incl. 'default' for grok+codex-family, sessionType always, trimmed-or-absent worktreeName, serviceTier only while fast tier visible, collaborationMode only when plan, model only claude/codex), parent-path derivation, suggestion filtering, recent-path LRU(8), worktree-name validation, codex catalog helpers, draft sanitization. - App: Features/NewSession (NewSessionModel @Observable orchestration — machine preselect last-used, 250 ms debounced list-directory autocomplete with per-parent cache, exists probe with worktree-blocking / simple two-tap-create, codex catalog fetch + selection reconcile, UserDefaults draft/prefs per hub; NewSessionView Form UI with per-flavor option matrix); session-list "+" toolbar button on HomeView presents the sheet, success dismisses and pushes the chat. - Tests: spawn-body exactness (4 configs, canonical JSON), parent query, suggestions, LRU, worktree validation, fast-tier detection, reasoning-effort normalization, draft sanitize + tolerant decode; codex-models endpoint request/error construction. --- ios/Hapi/Features/Home/HomeView.swift | 21 +- .../Features/NewSession/NewSessionModel.swift | 719 ++++++++++++++++++ .../Features/NewSession/NewSessionView.swift | 389 ++++++++++ .../Endpoints/MachineEndpoints.swift | 9 + .../NewSession/NewSessionForm.swift | 346 +++++++++ .../Catalog/NewSessionCatalogs.swift | 57 ++ .../HapiProtocol/Models/ApiResponses.swift | 51 ++ .../EndpointRequestTests.swift | 32 + .../HapiClientTests/NewSessionFormTests.swift | 262 +++++++ ios/README.md | 37 +- 10 files changed, 1919 insertions(+), 4 deletions(-) create mode 100644 ios/Hapi/Features/NewSession/NewSessionModel.swift create mode 100644 ios/Hapi/Features/NewSession/NewSessionView.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/NewSessionCatalogs.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift diff --git a/ios/Hapi/Features/Home/HomeView.swift b/ios/Hapi/Features/Home/HomeView.swift index 2f9d6ffd..e224f3c5 100644 --- a/ios/Hapi/Features/Home/HomeView.swift +++ b/ios/Hapi/Features/Home/HomeView.swift @@ -2,13 +2,16 @@ import HapiClient import SwiftUI /// Post-pairing home: the session list for the active hub, with the hub -/// switcher (switch / add / sign out) and the live global-SSE connection dot -/// in the toolbar. Tapping a row pushes the read-only chat (M2f). +/// switcher (switch / add / sign out), the "+" new-session sheet (A-M3c), +/// and the live global-SSE connection dot in the toolbar. Tapping a row +/// pushes the chat (M2f); a successful spawn dismisses the sheet and pushes +/// the new chat the same way. struct HomeView: View { let session: HubSession @Environment(AppModel.self) private var model @State private var confirmSignOut = false + @State private var showNewSession = false @State private var path: [String] = [] var body: some View { @@ -31,6 +34,13 @@ struct HomeView: View { ToolbarItem(placement: .topBarLeading) { connectionIndicator } + ToolbarItem(placement: .topBarTrailing) { + Button { + showNewSession = true + } label: { + Label("New Session", systemImage: "plus") + } + } ToolbarItem(placement: .topBarTrailing) { hubMenu } @@ -51,6 +61,13 @@ struct HomeView: View { .sheet(isPresented: $model.showAddHub) { PairingFlowView(context: .addHub) } + .sheet(isPresented: $showNewSession) { + NewSessionView(session: session) { sessionId in + // Navigate-replace: drop the sheet, push the fresh chat. + showNewSession = false + path.append(sessionId) + } + } } // MARK: - Connection state diff --git a/ios/Hapi/Features/NewSession/NewSessionModel.swift b/ios/Hapi/Features/NewSession/NewSessionModel.swift new file mode 100644 index 00000000..1e583d95 --- /dev/null +++ b/ios/Hapi/Features/NewSession/NewSessionModel.swift @@ -0,0 +1,719 @@ +import Foundation +import HapiClient +import HapiProtocol +import Observation + +// MARK: - UI models + +/// One machine row of the picker (Android `MachineOptionUi` port). +struct MachineOptionUI: Identifiable, Equatable { + let id: String + /// `displayName || host || id.prefix(8)` plus ` (platform)` and CLI version. + let label: String + /// e.g. `CPU 12% · Mem 45%`; nil when the runner reports no health. + let healthLabel: String? +} + +/// Directory hint under the input (web `directoryStatusMessage` + tone). +struct DirectoryStatusUI: Equatable { + let message: String + let isError: Bool +} + +/// Which permission control the current flavor renders (web `PermissionField`). +enum PermissionUI: Equatable { + /// Native permission-mode picker (grok + codex-family). + case nativeSelect([PermissionModeOption]) + /// HAPI YOLO toggle (claude/agy/cursor) with the native mode it maps to. + case yoloToggle(nativeModeLabel: String?) + /// Pi: the agent manages its own permissions. + case managed +} + +/// Machine codex-models catalog state (web `useCodexModels`). +enum CodexModelsState: Equatable { + case hidden + case loading + case loaded([CodexModelSummary]) + /// Runner has no machine RPC (`rpc_target_missing`) — hide the picker. + case unsupported + case failed(String) +} + +// MARK: - Persistence + +/// Create-form persistence: last-used machine + per-machine recent paths +/// (web `useRecentPaths`) and the in-progress draft (web +/// `newSessionFormDraft.ts`) so backing out of the sheet loses nothing. +/// JSON blobs in `UserDefaults`, keyed per hub (the Android original keys +/// app-wide; per-hub matches this app's multi-hub stores). +struct NewSessionPrefsData: Codable, Equatable { + var lastMachineId: String? + /// Machine id → most-recent-first spawn directories + /// (cap `NewSessionLogic.maxRecentPaths`). + var recentPaths: [String: [String]] = [:] +} + +struct NewSessionPrefsStore { + let hubUrl: String + var defaults: UserDefaults = .standard + + private var prefsKey: String { "newSession.prefs.\(hubUrl)" } + private var draftKey: String { "newSession.draft.\(hubUrl)" } + + func readPrefs() -> NewSessionPrefsData { + decode(prefsKey) ?? NewSessionPrefsData() + } + + func writePrefs(_ data: NewSessionPrefsData) { + encode(data, key: prefsKey) + } + + /// Nil when no draft is stored (or it fails to decode). + func readDraft() -> NewSessionForm? { + decode(draftKey) + } + + func writeDraft(_ draft: NewSessionForm) { + encode(draft, key: draftKey) + } + + func clearDraft() { + defaults.removeObject(forKey: draftKey) + } + + private func decode(_ key: String) -> T? { + guard let data = defaults.data(forKey: key) else { return nil } + return try? HapiJSON.decoder.decode(T.self, from: data) + } + + private func encode(_ value: T, key: String) { + guard let data = try? HapiJSON.encoder.encode(value) else { return } + defaults.set(data, forKey: key) + } +} + +// MARK: - Model + +/// New-session state machine (A-M3c): machine → directory → agent/options → +/// spawn — the iOS counterpart of the Android reference's +/// `NewSessionViewModel` in this app's viewModel-less `@Observable` style. +/// Pure mapping/validation lives in `NewSessionLogic` (HapiClient, tested); +/// this model orchestrates debounce, caching, fetches, and persistence. +/// Web reference: `web/src/components/NewSession/index.tsx`. +/// +/// v1 notes (deliberate cuts, mirrored from the Android/web option matrix): +/// - model pickers: claude (static presets) + codex (machine catalog; hidden +/// when the runner lacks the RPC). agy/opencode/grok/copilot/cursor/pi +/// model discovery is TODO — spawn omits `model` so the agent default +/// applies. +/// - effort: claude static levels; codex reasoning effort from the catalog. +/// - `startingMode` stays unset → the runner spawns `'remote'` (pty deferred). +@MainActor @Observable +final class NewSessionModel { + static let debounce: Duration = .milliseconds(250) + + static let msgWorktreeMissing = + "Worktree sessions require an existing repository directory." + static let msgDirectoryMissing = + "Directory does not exist. Creating the session will create it automatically." + static let msgDirectoryMissingConfirm = + "Directory does not exist. Tap Create again to create it automatically." + + // MARK: Observable state + + private(set) var form = NewSessionForm() + private(set) var suggestions: [String] = [] + private(set) var codexModels: CodexModelsState = .hidden + private(set) var isSpawning = false + private(set) var spawnError: String? + private(set) var confirmCreateDirectoryArmed = false + private(set) var machinesSettled = false + /// Probed existence per trimmed path (feeds the directory status hint). + private(set) var pathExistence: [String: Bool] = [:] + private(set) var prefsData = NewSessionPrefsData() + + // MARK: Wiring + + private let session: HubSession + private let prefsStore: NewSessionPrefsStore + /// Fired once with the new session id — navigate-replace to the chat. + private let onCreated: @MainActor (String) -> Void + + @ObservationIgnored private var directoryTask: Task? + @ObservationIgnored private var codexTask: Task? + @ObservationIgnored private var codexFetchedForMachine: String? + @ObservationIgnored private var suppressSuggestions = false + @ObservationIgnored private var spawnInFlight = false + /// Parent-listing cache: retyping within the same parent re-filters + /// locally instead of re-requesting. + @ObservationIgnored private var cachedListing: + (machineId: String, parent: String, entries: [MachineDirectoryEntry])? + + init(session: HubSession, onCreated: @escaping @MainActor (String) -> Void) { + self.session = session + self.prefsStore = NewSessionPrefsStore(hubUrl: session.hubUrl) + self.onCreated = onCreated + } + + // MARK: - Lifecycle (paired with the sheet's `.task`) + + /// Restore prefs + sanitized draft, preselect a machine, refresh the + /// roster. Call once per presentation. + func start() async { + prefsData = prefsStore.readPrefs() + var initial = prefsStore.readDraft().map(NewSessionLogic.sanitizeDraft) ?? NewSessionForm() + if initial.machineId != nil, initial.trimmedDirectory.isEmpty { + initial.directory = recentPaths(for: initial.machineId).first ?? "" + } + form = initial + reconcileMachineSelection() + refreshCodexModelsIfNeeded() + // A restored directory should probe existence but not pop the + // autocomplete dropdown — suggestions belong to typing. + suppressSuggestions = true + scheduleDirectoryWork() + + do { + try await session.machineStore.refresh() + } catch { + // Snapshot (if any) keeps serving; the picker shows what it has. + } + machinesSettled = true + reconcileMachineSelection() + } + + /// Machine roster changed (SSE / refresh) — re-run the preselection: + /// keep a still-online selection; otherwise last-used, else first. + func machinesChanged() { + reconcileMachineSelection() + } + + // MARK: - Derived state + + var machines: [MachineOptionUI] { + session.machineStore.machines.map(Self.machineOption) + } + + var machinesLoading: Bool { + session.machineStore.machines.isEmpty && !machinesSettled + } + + /// `runnerState.lastSpawnError` of the selected machine, formatted + /// (`web/src/utils/formatRunnerSpawnError.ts`). + var runnerSpawnError: String? { + Self.formatRunnerSpawnError(selectedMachine) + } + + var recentPaths: [String] { + recentPaths(for: form.machineId) + } + + var directoryStatus: DirectoryStatusUI? { + if missingWorktreeDirectory { + return DirectoryStatusUI(message: Self.msgWorktreeMissing, isError: true) + } + if needsCreationWarning { + return DirectoryStatusUI( + message: confirmCreateDirectory + ? Self.msgDirectoryMissingConfirm + : Self.msgDirectoryMissing, + isError: false + ) + } + return nil + } + + /// Creatable flavors (`CREATABLE_AGENT_FLAVORS`), labeled. + var agents: [NewSessionOption] { + AgentFlavor.creatableFlavors.map { + NewSessionOption(value: $0.rawValue, label: $0.displayLabel) + } + } + + /// Nil hides the model picker (v1: only claude + supported codex). + var modelOptions: [NewSessionOption]? { + switch (form.agent, codexModels) { + case (.claude, _): + return NewSessionCatalogs.claudeModels + case (.codex, .loaded(let models)): + return [NewSessionOption(value: "auto", label: "Default")] + + models.map { NewSessionOption(value: $0.id, label: $0.displayName) } + case (.codex, .loading), (.codex, .failed): + return [NewSessionOption(value: "auto", label: "Default")] + default: + // codex `.unsupported` (old runner) and every other flavor: hidden. + return nil + } + } + + var modelsLoading: Bool { + form.agent == .codex && codexModels == .loading + } + + var modelsError: String? { + if case .failed(let message) = codexModels { + return "Failed to load models: \(message)" + } + return nil + } + + /// Claude launch-effort options; nil hides the field. + var effortOptions: [NewSessionOption]? { + form.agent == .claude ? NewSessionCatalogs.claudeEfforts : nil + } + + /// Codex reasoning-effort options; nil hides the field. + var reasoningEffortOptions: [NewSessionOption]? { + guard form.agent == .codex, codexModels != .unsupported else { return nil } + if case .loaded(let models) = codexModels, + let advertised = NewSessionLogic.codexReasoningEfforts(models: models, model: form.model) { + return [NewSessionOption(value: "default", label: "Default")] + + advertised.map { + NewSessionOption(value: $0, label: NewSessionCatalogs.effortLabel($0)) + } + } + return NewSessionCatalogs.codexReasoningEfforts + } + + var permission: PermissionUI { + let agent = form.agent + if agent == .pi { + return .managed + } + if NewSessionLogic.usesNativePermissionSelect(agent) { + return .nativeSelect(agent.permissionModes.map { PermissionModeOption(mode: $0) }) + } + return .yoloToggle(nativeModeLabel: NewSessionLogic.hapiYoloNativeMode(for: agent)?.label) + } + + var showCollaborationMode: Bool { + form.agent == .codex + } + + var showCopilotAgentMode: Bool { + form.agent == .copilot + } + + var showFastMode: Bool { + guard form.agent == .codex, case .loaded(let models) = codexModels else { return false } + return NewSessionLogic.codexModelAdvertisesFastTier(model: form.model, models: models) + } + + var worktreeNameError: String? { + form.sessionType == .worktree + ? NewSessionLogic.worktreeNameError(form.worktreeName) + : nil + } + + /// Armed after the first Create tap on a missing simple directory. + var confirmCreateDirectory: Bool { + confirmCreateDirectoryArmed && needsCreationWarning + } + + var canCreate: Bool { + form.machineId != nil + && !form.trimmedDirectory.isEmpty + && !isSpawning + && !missingWorktreeDirectory + && worktreeNameError == nil + && !codexValidationPending + } + + private var selectedMachine: Machine? { + session.machineStore.machines.first { $0.id == form.machineId } + } + + private var directoryExists: Bool? { + let trimmed = form.trimmedDirectory + guard !trimmed.isEmpty else { return nil } + return pathExistence[trimmed] + } + + private var missingWorktreeDirectory: Bool { + form.sessionType == .worktree && directoryExists == false + } + + private var needsCreationWarning: Bool { + form.sessionType == .simple && directoryExists == false + } + + /// Web `isLaunchPreferenceValidationPending` (codex slice): a restored + /// codex model/effort must not spawn before the catalog validated it. + private var codexValidationPending: Bool { + form.agent == .codex && codexModels == .loading + && (form.model != "auto" + || form.modelReasoningEffort != "default" + || form.serviceTier == .fast) + } + + // MARK: - Actions + + func setMachine(_ machineId: String) { + guard machineId != form.machineId else { return } + applyMachineSelection(machineId, resetDirectory: true) + } + + func setDirectory(_ value: String) { + suppressSuggestions = false + confirmCreateDirectoryArmed = false + form.directory = value + persistDraft() + scheduleDirectoryWork() + } + + func pickSuggestion(_ path: String) { + pickPath(path) + } + + func pickRecentPath(_ path: String) { + pickPath(path) + } + + func setAgent(_ agent: AgentFlavor) { + guard agent != form.agent else { return } + // Web parity: switching agents resets every agent-dependent field + // (yolo is a cross-flavor preference and survives). + form.agent = agent + form.model = "auto" + form.effort = "auto" + form.modelReasoningEffort = "default" + form.permissionMode = .default + form.serviceTier = .standard + form.collaborationMode = .default + form.copilotAgentMode = .interactive + persistDraft() + refreshCodexModelsIfNeeded() + } + + func setModel(_ model: String) { + form.model = model + if form.agent == .codex { + form = reconcileCodexSelections(form) + } + persistDraft() + } + + func setEffort(_ effort: String) { + form.effort = effort + persistDraft() + } + + func setModelReasoningEffort(_ value: String) { + form.modelReasoningEffort = value + persistDraft() + } + + func setPermissionMode(_ mode: PermissionMode) { + form.permissionMode = mode + persistDraft() + } + + func setYolo(_ enabled: Bool) { + form.yolo = enabled + persistDraft() + } + + func setSessionType(_ sessionType: SpawnSessionType) { + confirmCreateDirectoryArmed = false + form.sessionType = sessionType + persistDraft() + } + + func setWorktreeName(_ name: String) { + form.worktreeName = name + persistDraft() + } + + func setServiceTier(_ tier: ServiceTier) { + form.serviceTier = tier + persistDraft() + } + + func setCollaborationMode(_ mode: CodexCollaborationMode) { + form.collaborationMode = mode + persistDraft() + } + + func setCopilotAgentMode(_ mode: CopilotAgentMode) { + form.copilotAgentMode = mode + persistDraft() + } + + func retryCodexModels() { + codexFetchedForMachine = nil + refreshCodexModelsIfNeeded() + } + + /// Spawn. Directory existence is re-checked server-side first (web + /// `handleCreate`): a missing worktree base is an error; a missing + /// simple directory arms a second-tap confirmation, after which the hub + /// creates it. Success persists prefs, clears the draft, and hands the + /// new session id to `onCreated`; failure lands in the inline error. + func create() { + let current = form + guard let machineId = current.machineId else { return } + let directory = current.trimmedDirectory + guard !directory.isEmpty, !spawnInFlight else { return } + if current.sessionType == .worktree, + NewSessionLogic.worktreeNameError(current.worktreeName) != nil { + return + } + spawnInFlight = true + isSpawning = true + spawnError = nil + Task { [weak self] in + defer { + self?.spawnInFlight = false + self?.isSpawning = false + } + guard let self else { return } + let api = self.session.api + let exists = (try? await api.machinePathsExist(machineId: machineId, paths: [directory]))?[directory] + if let exists { + self.pathExistence[directory] = exists + } + if current.sessionType == .worktree, exists == false { + self.spawnError = Self.msgWorktreeMissing + return + } + if current.sessionType == .simple, exists == false, !self.confirmCreateDirectoryArmed { + self.confirmCreateDirectoryArmed = true + return + } + + let request = NewSessionLogic.buildSpawnRequest( + form: current, + codexFastTierVisible: self.codexFastTierVisible(current) + ) + do { + switch try await api.spawnSession(machineId: machineId, request) { + case .success(let sessionId): + self.persistOnSuccess(machineId: machineId, directory: directory) + self.onCreated(sessionId) + case .error(let message): + self.spawnError = message.isEmpty ? "Failed to create session" : message + } + } catch { + self.spawnError = (error as? LocalizedError)?.errorDescription + ?? "Failed to create session" + } + } + } + + // MARK: - Internals + + private func pickPath(_ path: String) { + suppressSuggestions = true + confirmCreateDirectoryArmed = false + suggestions = [] + form.directory = path + persistDraft() + scheduleDirectoryWork() + } + + private func recentPaths(for machineId: String?) -> [String] { + machineId.flatMap { prefsData.recentPaths[$0] } ?? [] + } + + private func reconcileMachineSelection() { + let machines = session.machineStore.machines + guard !machines.isEmpty else { return } + if let current = form.machineId, machines.contains(where: { $0.id == current }) { + return + } + let target = machines.first { $0.id == prefsData.lastMachineId } ?? machines[0] + applyMachineSelection(target.id, resetDirectory: form.trimmedDirectory.isEmpty) + } + + private func applyMachineSelection(_ machineId: String, resetDirectory: Bool) { + pathExistence = [:] + suggestions = [] + cachedListing = nil + confirmCreateDirectoryArmed = false + // The seeded recent path is a pick, not typing — no dropdown. + suppressSuggestions = true + form.machineId = machineId + form.model = "auto" + if resetDirectory { + form.directory = recentPaths(for: machineId).first ?? "" + } + persistDraft() + refreshCodexModelsIfNeeded() + scheduleDirectoryWork() + } + + /// Debounced directory work: parent listing for autocomplete + exists + /// probe, both riding one 250 ms debounce like the Android reference. + private func scheduleDirectoryWork() { + directoryTask?.cancel() + guard let machineId = form.machineId else { + suggestions = [] + return + } + directoryTask = Task { [weak self] in + try? await Task.sleep(for: Self.debounce) + guard !Task.isCancelled, let self else { return } + await self.performDirectoryWork(machineId: machineId) + } + } + + private func performDirectoryWork(machineId: String) async { + let text = form.directory + let trimmed = form.trimmedDirectory + let api = session.api + + let query = suppressSuggestions ? nil : NewSessionLogic.parentQuery(for: text) + if let query { + let cacheKey = (machineId, query.parent) + let entries: [MachineDirectoryEntry] + if let cached = cachedListing, (cached.machineId, cached.parent) == cacheKey { + entries = cached.entries + } else { + let response = try? await api.listMachineDirectory( + machineId: machineId, + path: query.parent + ) + guard !Task.isCancelled else { return } + if let response, response.success { + entries = response.entries ?? [] + cachedListing = (machineId, query.parent, entries) + } else { + entries = [] + } + } + // Never suggest the path already typed verbatim. + suggestions = NewSessionLogic.buildSuggestions(query: query, entries: entries) + .filter { $0 != trimmed } + } else { + suggestions = [] + } + + if !trimmed.isEmpty { + // Unknown existence (request failed): no status hint, the spawn + // re-checks anyway. + if let result = try? await api.machinePathsExist(machineId: machineId, paths: [trimmed]) { + guard !Task.isCancelled else { return } + pathExistence.merge(result) { _, new in new } + } + } + } + + private func refreshCodexModelsIfNeeded() { + guard form.agent == .codex else { + codexTask?.cancel() + codexFetchedForMachine = nil + codexModels = .hidden + return + } + guard let machineId = form.machineId else { + codexModels = .hidden + return + } + if codexFetchedForMachine == machineId, codexModels != .hidden { + return + } + codexFetchedForMachine = machineId + codexTask?.cancel() + codexModels = .loading + codexTask = Task { [weak self] in + guard let self else { return } + let state: CodexModelsState + do { + let response = try await self.session.api.machineCodexModels(machineId: machineId) + state = response.success + ? .loaded(response.models ?? []) + : .failed(response.error ?? "Failed to load Codex models") + } catch let error as APIError where error.code == "rpc_target_missing" { + state = .unsupported + } catch is CancellationError { + return + } catch { + state = .failed( + (error as? LocalizedError)?.errorDescription ?? "Failed to load Codex models" + ) + } + guard !Task.isCancelled else { return } + self.codexModels = state + if case .loaded = state { + // Reconcile restored selections with the live catalog (web + // validation effects): unknown model → auto; unsupported + // effort → default; no fast tier → standard. + self.form = self.reconcileCodexSelections(self.form) + self.persistDraft() + } + } + } + + private func reconcileCodexSelections(_ current: NewSessionForm) -> NewSessionForm { + guard case .loaded(let models) = codexModels else { return current } + var next = current + if next.model != "auto", !models.contains(where: { $0.id == next.model }) { + next.model = "auto" + } + if next.modelReasoningEffort != "default", + let supported = NewSessionLogic.codexReasoningEfforts(models: models, model: next.model), + !supported.contains(next.modelReasoningEffort) { + next.modelReasoningEffort = "default" + } + if next.serviceTier != .standard, + !NewSessionLogic.codexModelAdvertisesFastTier(model: next.model, models: models) { + next.serviceTier = .standard + } + return next + } + + private func codexFastTierVisible(_ current: NewSessionForm) -> Bool { + guard current.agent == .codex, case .loaded(let models) = codexModels else { return false } + return NewSessionLogic.codexModelAdvertisesFastTier(model: current.model, models: models) + } + + private func persistDraft() { + prefsStore.writeDraft(form) + } + + private func persistOnSuccess(machineId: String, directory: String) { + prefsData.lastMachineId = machineId + prefsData.recentPaths[machineId] = NewSessionLogic.pushRecent( + prefsData.recentPaths[machineId] ?? [], + path: directory + ) + prefsStore.writePrefs(prefsData) + prefsStore.clearDraft() + } + + // MARK: - Formatting (Android `NewSessionViewModel` companion ports) + + /// `getMachineOptionLabel` (web `MachineSelector`), minus capability-skew + /// (TODO with the machine detail screen). + static func machineOption(_ machine: Machine) -> MachineOptionUI { + let metadata = machine.metadata + let title = metadata?.displayName.flatMap { name in + name.trimmingCharacters(in: .whitespaces).isEmpty ? nil : name + } + ?? metadata?.host + ?? String(machine.id.prefix(8)) + let platform = metadata.map { " (\($0.platform))" } ?? "" + let version = metadata.map { " · CLI \($0.happyCliVersion)" } ?? "" + let healthParts: [String] = [ + machine.health?.cpuPercent.map { "CPU \(Int($0))%" }, + machine.health?.memoryPercent.map { "Mem \(Int($0))%" }, + ].compactMap { $0 } + return MachineOptionUI( + id: machine.id, + label: "\(title)\(platform)\(version)", + healthLabel: healthParts.isEmpty ? nil : healthParts.joined(separator: " · ") + ) + } + + /// `formatRunnerSpawnError` (`web/src/utils/formatRunnerSpawnError.ts`). + static func formatRunnerSpawnError(_ machine: Machine?) -> String? { + guard case .object(let error)? = machine?.runnerState?.lastSpawnError else { return nil } + guard case .string(let message)? = error["message"], !message.isEmpty else { return nil } + if case .number(let at)? = error["at"] { + let date = Date(timeIntervalSince1970: at / 1000) + return "\(message) (\(date.formatted(date: .abbreviated, time: .shortened)))" + } + return message + } +} diff --git a/ios/Hapi/Features/NewSession/NewSessionView.swift b/ios/Hapi/Features/NewSession/NewSessionView.swift new file mode 100644 index 00000000..c7157d91 --- /dev/null +++ b/ios/Hapi/Features/NewSession/NewSessionView.swift @@ -0,0 +1,389 @@ +import HapiClient +import HapiProtocol +import SwiftUI + +/// NEW SESSION (A-M3c): machine → directory → agent/options → spawn, +/// presented as a sheet off the session list's "+" button. State and +/// behavior live in `NewSessionModel`; this view renders it and forwards +/// intents. A successful spawn surfaces through `onCreated` (the presenter +/// dismisses the sheet and pushes the chat — navigate-replace). +struct NewSessionView: View { + @State private var model: NewSessionModel + @Environment(\.dismiss) private var dismiss + private let session: HubSession + + init(session: HubSession, onCreated: @escaping @MainActor (String) -> Void) { + _model = State(initialValue: NewSessionModel(session: session, onCreated: onCreated)) + self.session = session + } + + var body: some View { + NavigationStack { + Form { + machineSection + directorySection + sessionTypeSection + agentSection + optionsSection + createSection + } + .navigationTitle("New Session") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { + dismiss() + } + } + } + .task { + await model.start() + } + .onChange(of: session.machineStore.listRevision) { + model.machinesChanged() + } + } + } + + // MARK: - Machine + + private var machineSection: some View { + Section("Machine") { + if model.machines.isEmpty { + Text(model.machinesLoading ? "Loading machines…" : "No machines online") + .foregroundStyle(.secondary) + } else { + Picker("Machine", selection: machineBinding) { + ForEach(model.machines) { machine in + Text(machine.label).tag(machine.id) + } + } + if let health = selectedMachineHealth { + Text(health) + .font(.caption) + .foregroundStyle(.secondary) + } + } + if let error = model.runnerSpawnError { + Text("Runner last spawn error: \(error)") + .font(.footnote) + .foregroundStyle(.red) + } + } + .disabled(model.isSpawning) + } + + private var selectedMachineHealth: String? { + model.machines.first { $0.id == model.form.machineId }?.healthLabel + } + + private var machineBinding: Binding { + Binding( + get: { model.form.machineId ?? "" }, + set: { model.setMachine($0) } + ) + } + + // MARK: - Directory + + private var directorySection: some View { + Section { + TextField( + "/path/to/project", + text: Binding(get: { model.form.directory }, set: { model.setDirectory($0) }) + ) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .font(.system(.callout, design: .monospaced)) + + // Server-side autocomplete (list-directory on the parent path). + ForEach(model.suggestions, id: \.self) { suggestion in + Button { + model.pickSuggestion(suggestion) + } label: { + Label { + Text(suggestion) + .lineLimit(1) + .truncationMode(.head) + } icon: { + Image(systemName: "folder") + } + .font(.callout) + } + .buttonStyle(.plain) + } + + if !model.recentPaths.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + ForEach(model.recentPaths, id: \.self) { path in + FilterChip(label: path, selected: false) { + model.pickRecentPath(path) + } + } + } + } + .listRowInsets(EdgeInsets(top: 6, leading: 12, bottom: 6, trailing: 12)) + } + } header: { + Text("Directory") + } footer: { + if let status = model.directoryStatus { + Text(status.message) + .foregroundStyle(status.isError ? AnyShapeStyle(.red) : AnyShapeStyle(.secondary)) + } + } + .disabled(model.isSpawning) + } + + // MARK: - Session type + + private var sessionTypeSection: some View { + Section { + Picker("Session type", selection: sessionTypeBinding) { + Text("Simple").tag(SpawnSessionType.simple) + Text("Worktree").tag(SpawnSessionType.worktree) + } + .pickerStyle(.segmented) + .labelsHidden() + + if model.form.sessionType == .worktree { + TextField( + "feature-x (optional)", + text: Binding( + get: { model.form.worktreeName }, + set: { model.setWorktreeName($0) } + ) + ) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + } + } header: { + Text("Session Type") + } footer: { + if let error = model.worktreeNameError { + Text(error).foregroundStyle(.red) + } else { + Text( + model.form.sessionType == .worktree + ? "Create a new git worktree next to the repo" + : "Use selected directory as-is" + ) + } + } + .disabled(model.isSpawning) + } + + private var sessionTypeBinding: Binding { + Binding( + get: { model.form.sessionType }, + set: { model.setSessionType($0) } + ) + } + + // MARK: - Agent + + private var agentSection: some View { + Section("Agent") { + Picker("Agent", selection: agentBinding) { + ForEach(model.agents, id: \.value) { agent in + Text(agent.label).tag(agent.value) + } + } + } + .disabled(model.isSpawning) + } + + private var agentBinding: Binding { + Binding( + get: { model.form.agent.rawValue }, + set: { model.setAgent(AgentFlavor(rawValue: $0)) } + ) + } + + // MARK: - Options + + @ViewBuilder + private var optionsSection: some View { + Section("Options") { + if let options = model.modelOptions { + optionPicker( + "Model", + options: options, + selection: Binding(get: { model.form.model }, set: { model.setModel($0) }) + ) + .disabled(model.modelsLoading || model.modelsError != nil) + if model.modelsLoading { + Text("Loading…") + .font(.caption) + .foregroundStyle(.secondary) + } + if let error = model.modelsError { + HStack { + Text(error) + .font(.footnote) + .foregroundStyle(.red) + Spacer() + Button("Retry") { + model.retryCodexModels() + } + .font(.footnote) + } + } + } + + if let options = model.effortOptions { + optionPicker( + "Effort", + options: options, + selection: Binding(get: { model.form.effort }, set: { model.setEffort($0) }) + ) + } + + if let options = model.reasoningEffortOptions { + optionPicker( + "Reasoning Effort", + options: options, + selection: Binding( + get: { model.form.modelReasoningEffort }, + set: { model.setModelReasoningEffort($0) } + ) + ) + .disabled(model.modelsLoading) + } + + permissionControl + + if model.showCollaborationMode { + Picker("Collaboration Mode", selection: collaborationModeBinding) { + ForEach(CodexCollaborationMode.allCases, id: \.self) { mode in + Text(mode.label).tag(mode) + } + } + } + + if model.showCopilotAgentMode { + Picker("Agent Mode", selection: copilotAgentModeBinding) { + ForEach(CopilotAgentMode.allCases, id: \.self) { mode in + Text(mode.label).tag(mode) + } + } + } + + if model.showFastMode { + Picker("Fast Mode", selection: serviceTierBinding) { + Text("Standard").tag(ServiceTier.standard) + Text("Fast").tag(ServiceTier.fast) + } + } + } + .disabled(model.isSpawning) + } + + @ViewBuilder + private var permissionControl: some View { + switch model.permission { + case .nativeSelect(let options): + Picker("Permission Mode", selection: permissionModeBinding) { + ForEach(options, id: \.mode) { option in + Text(option.label).tag(option.mode) + } + } + case .yoloToggle(let nativeModeLabel): + VStack(alignment: .leading, spacing: 2) { + Toggle( + "Bypass approvals and sandbox", + isOn: Binding(get: { model.form.yolo }, set: { model.setYolo($0) }) + ) + Text( + nativeModeLabel.map { "Uses dangerous agent flags when spawning. Applies native \($0) mode." } + ?? "Uses dangerous agent flags when spawning." + ) + .font(.caption) + .foregroundStyle(.secondary) + } + case .managed: + VStack(alignment: .leading, spacing: 2) { + LabeledContent("Permission Mode", value: "Managed by agent") + Text("This agent manages its own permissions. YOLO mode is not available.") + .font(.caption) + .foregroundStyle(.secondary) + } + } + } + + private var permissionModeBinding: Binding { + Binding( + get: { model.form.permissionMode }, + set: { model.setPermissionMode($0) } + ) + } + + private var collaborationModeBinding: Binding { + Binding( + get: { model.form.collaborationMode }, + set: { model.setCollaborationMode($0) } + ) + } + + private var copilotAgentModeBinding: Binding { + Binding( + get: { model.form.copilotAgentMode }, + set: { model.setCopilotAgentMode($0) } + ) + } + + private var serviceTierBinding: Binding { + Binding( + get: { model.form.serviceTier }, + set: { model.setServiceTier($0) } + ) + } + + private func optionPicker( + _ title: String, + options: [NewSessionOption], + selection: Binding + ) -> some View { + Picker(title, selection: selection) { + ForEach(options, id: \.value) { option in + Text(option.label).tag(option.value) + } + } + } + + // MARK: - Create + + private var createSection: some View { + Section { + Button { + model.create() + } label: { + HStack(spacing: 8) { + if model.isSpawning { + ProgressView() + .controlSize(.small) + } + Text(createLabel) + .fontWeight(.semibold) + } + .frame(maxWidth: .infinity) + } + .disabled(!model.canCreate) + } footer: { + if let error = model.spawnError { + Text(error).foregroundStyle(.red) + } + } + } + + private var createLabel: String { + if model.isSpawning { + return "Creating…" + } + if model.confirmCreateDirectory { + return "Create and Make Directory" + } + return "Create" + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift index 47790ec2..6d8d14de 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift @@ -63,4 +63,13 @@ extension APIClient { ) return response.exists } + + /// `GET /api/machines/:id/codex-models` — pre-spawn codex model catalog + /// (RPC envelope — check `success`). A runner without the machine-scoped + /// RPC answers 503 `rpc_target_missing`, surfaced as an ``APIError`` + /// whose `code` the new-session form uses to hide the picker. Added in + /// A-M3c (endpoint documented in `docs/api/client-contract/rest.md`). + public func machineCodexModels(machineId: String) async throws -> CodexModelsResponse { + try await request(.get, "/api/machines/\(encodePathComponent(machineId))/codex-models") + } } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift b/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift new file mode 100644 index 00000000..7513095c --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift @@ -0,0 +1,346 @@ +import Foundation +import HapiProtocol + +/// New-session form state + the pure mapping/validation logic around it +/// (A-M3c) — the iOS counterpart of the Android reference's +/// `NewSessionForm.kt`, which itself ports the web create form +/// (`web/src/components/NewSession/index.tsx`, `handleCreate`). Everything +/// here is UI-free so package tests can assert the exact spawn body against +/// `SpawnSessionRequestSchema`. +/// +/// Unlike the Android original (open strings everywhere), enum-backed fields +/// use the `HapiProtocol` catalog types directly — a draft holding a value +/// these enums cannot represent fails to decode and degrades to no draft, +/// which is the same end state as the web's try/catch around +/// `loadNewSessionFormDraft`. +public struct NewSessionForm: Codable, Equatable, Sendable { + public var machineId: String? + public var directory: String + /// Flavor from ``AgentFlavor/creatableFlavors``. + public var agent: AgentFlavor + /// `'auto'` = no explicit model (claude presets / codex catalog ids). + public var model: String + /// Claude launch effort; `'auto'` = omit. + public var effort: String + /// Codex reasoning effort; `'default'` = omit. + public var modelReasoningEffort: String + /// Native permission mode for grok + codex-family flavors. + public var permissionMode: PermissionMode + /// HAPI YOLO preference for the remaining flavors (claude/agy/cursor/pi). + public var yolo: Bool + public var sessionType: SpawnSessionType + public var worktreeName: String + /// Codex; only sent while the fast tier is visible. + public var serviceTier: ServiceTier + /// Codex collaboration mode. + public var collaborationMode: CodexCollaborationMode + /// Copilot; always sent for copilot. + public var copilotAgentMode: CopilotAgentMode + + public init( + machineId: String? = nil, + directory: String = "", + agent: AgentFlavor = .claude, + model: String = "auto", + effort: String = "auto", + modelReasoningEffort: String = "default", + permissionMode: PermissionMode = .default, + yolo: Bool = false, + sessionType: SpawnSessionType = .simple, + worktreeName: String = "", + serviceTier: ServiceTier = .standard, + collaborationMode: CodexCollaborationMode = .default, + copilotAgentMode: CopilotAgentMode = .interactive + ) { + self.machineId = machineId + self.directory = directory + self.agent = agent + self.model = model + self.effort = effort + self.modelReasoningEffort = modelReasoningEffort + self.permissionMode = permissionMode + self.yolo = yolo + self.sessionType = sessionType + self.worktreeName = worktreeName + self.serviceTier = serviceTier + self.collaborationMode = collaborationMode + self.copilotAgentMode = copilotAgentMode + } + + public var trimmedDirectory: String { + directory.trimmingCharacters(in: .whitespacesAndNewlines) + } + + // Manual decode with per-field defaults so a draft written by an older + // app version (missing keys) still restores, mirroring kotlinx defaults + // on the Android side. Encoding stays synthesized. + private enum CodingKeys: String, CodingKey { + case machineId, directory, agent, model, effort, modelReasoningEffort + case permissionMode, yolo, sessionType, worktreeName, serviceTier + case collaborationMode, copilotAgentMode + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + machineId = try container.decodeIfPresent(String.self, forKey: .machineId) + directory = try container.decodeIfPresent(String.self, forKey: .directory) ?? "" + agent = try container.decodeIfPresent(AgentFlavor.self, forKey: .agent) ?? .claude + model = try container.decodeIfPresent(String.self, forKey: .model) ?? "auto" + effort = try container.decodeIfPresent(String.self, forKey: .effort) ?? "auto" + modelReasoningEffort = try container.decodeIfPresent(String.self, forKey: .modelReasoningEffort) + ?? "default" + permissionMode = try container.decodeIfPresent(PermissionMode.self, forKey: .permissionMode) + ?? .default + yolo = try container.decodeIfPresent(Bool.self, forKey: .yolo) ?? false + sessionType = try container.decodeIfPresent(SpawnSessionType.self, forKey: .sessionType) + ?? .simple + worktreeName = try container.decodeIfPresent(String.self, forKey: .worktreeName) ?? "" + serviceTier = try container.decodeIfPresent(ServiceTier.self, forKey: .serviceTier) + ?? .standard + collaborationMode = try container.decodeIfPresent( + CodexCollaborationMode.self, + forKey: .collaborationMode + ) ?? .default + copilotAgentMode = try container.decodeIfPresent(CopilotAgentMode.self, forKey: .copilotAgentMode) + ?? .interactive + } +} + +/// Pure new-session logic (Android `NewSessionLogic` port; web reference in +/// each doc comment). +public enum NewSessionLogic { + // MARK: - Permission control routing + + /// Flavors sharing the codex-style native permission select + /// (`web/src/lib/codexFamilyPermissionAgents.ts`). Gemini is listed for + /// completeness though it is not creatable. + public static let codexFamilyPermissionAgents: Set = [ + .codex, .gemini, .kimi, .copilot, .opencode, + ] + + public static func usesCodexFamilyPermissionModes(_ flavor: AgentFlavor) -> Bool { + codexFamilyPermissionAgents.contains(flavor) + } + + /// Flavors whose permission control is the native-mode select. + public static func usesNativePermissionSelect(_ flavor: AgentFlavor) -> Bool { + flavor == .grok || usesCodexFamilyPermissionModes(flavor) + } + + /// `resolveHapiYoloPermissionMode` (`shared/src/agentConfig.ts`) — the + /// native mode the HAPI YOLO toggle maps to, for the toggle's caption. + public static func hapiYoloNativeMode(for flavor: AgentFlavor) -> PermissionMode? { + switch flavor { + case .claude, .grok: return .bypassPermissions + case .agy: return .alwaysProceed + case .codex, .copilot, .cursor, .gemini, .kimi, .opencode: return .yolo + case .pi, .other: return nil + } + } + + // MARK: - Spawn body + + /// Exact spawn body (`POST /api/machines/:id/spawn`), field-for-field + /// port of the web `handleCreate` mapping: + /// - `model`/`effort` only for flavors whose picker exists in this v1 + /// (claude static list, codex machine catalog; others send no model); + /// - `yolo` for non-grok/non-codex-family flavors — **including `false`**; + /// - `permissionMode` for grok + codex-family — including `'default'`; + /// - `sessionType` always; `worktreeName` only for worktree and non-blank; + /// - `serviceTier` only while the codex fast tier is visible (then also + /// `'standard'`); `collaborationMode` only when not `'default'`; + /// - `copilotAgentMode` always for copilot; + /// - `startingMode` omitted = the runner's `'remote'` default (v1 fixes + /// remote; pty is deferred, matching the web create form). + public static func buildSpawnRequest( + form: NewSessionForm, + codexFastTierVisible: Bool + ) -> SpawnRequest { + let agent = form.agent + let codexFamily = usesCodexFamilyPermissionModes(agent) + let isGrok = agent == .grok + // v1 model pickers: claude (static presets) and codex (machine + // catalog). Other flavors' discovery endpoints are TODO(M4+), so + // their model is never sent. + let resolvedModel: String? = ((agent == .claude || agent == .codex) && form.model != "auto") + ? form.model + : nil + let trimmedWorktreeName = form.worktreeName.trimmingCharacters(in: .whitespacesAndNewlines) + return SpawnRequest( + directory: form.trimmedDirectory, + agent: agent, + model: resolvedModel, + effort: (agent == .claude && form.effort != "auto") ? form.effort : nil, + modelReasoningEffort: (agent == .codex && form.modelReasoningEffort != "default") + ? form.modelReasoningEffort + : nil, + yolo: (isGrok || codexFamily) ? nil : form.yolo, + permissionMode: (isGrok || codexFamily) ? form.permissionMode : nil, + sessionType: form.sessionType, + worktreeName: (form.sessionType == .worktree && !trimmedWorktreeName.isEmpty) + ? trimmedWorktreeName + : nil, + serviceTier: (agent == .codex && codexFastTierVisible) ? form.serviceTier : nil, + collaborationMode: (agent == .codex && form.collaborationMode != .default) + ? form.collaborationMode + : nil, + copilotAgentMode: agent == .copilot ? form.copilotAgentMode : nil, + startingMode: nil + ) + } + + // MARK: - Directory autocomplete + + /// Parent listing target for the autocomplete dropdown. + public struct ParentQuery: Equatable, Sendable { + /// Absolute directory to `POST list-directory`. + public let parent: String + /// Typed tail the entries are prefix-filtered by (case-insensitive). + public let prefix: String + + public init(parent: String, prefix: String) { + self.parent = parent + self.prefix = prefix + } + } + + /// Derives the list-directory request from the typed text: list the + /// parent of the path segment being typed. Only absolute paths + /// autocomplete (the hub lists runner-local absolute paths). + /// + /// `/data/gi` → list `/data`, prefix `gi`; `/data/` → list `/data`, no + /// prefix; `/` → list `/`; relative text → nil (no request). + public static func parentQuery(for input: String) -> ParentQuery? { + let text = input.trimmingCharacters(in: .whitespacesAndNewlines) + guard text.hasPrefix("/") else { return nil } + guard let lastSlash = text.lastIndex(of: "/") else { return nil } + let parent = lastSlash == text.startIndex ? "/" : String(text[.. [String] { + let base = query.parent == "/" ? "/" : "\(query.parent)/" + let loweredPrefix = query.prefix.lowercased() + return entries + .filter { $0.type == .directory } + .filter { loweredPrefix.isEmpty || $0.name.lowercased().hasPrefix(loweredPrefix) } + .prefix(limit) + .map { "\(base)\($0.name)" } + } + + // MARK: - Recent paths + + /// LRU cap per machine (web caps at 5; native chips fit a couple more). + public static let maxRecentPaths = 8 + + /// Dedupe-to-front LRU push (web `addRecentPath`). Blank input is a no-op. + public static func pushRecent( + _ existing: [String], + path: String, + cap: Int = maxRecentPaths + ) -> [String] { + let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return existing } + return Array(([trimmed] + existing.filter { $0 != trimmed }).prefix(cap)) + } + + // MARK: - Worktree + + /// Client-side worktree-name check. The runner slugs the name to + /// `[a-z0-9-]` (`cli/src/runner/worktree.ts` `toSlug`); a name with no + /// alphanumeric characters slugs to nothing and the spawn fails server + /// side, so reject it up front. Empty is fine — the runner generates a + /// `MMDD-xxxx` default. + public static func worktreeNameError(_ name: String) -> String? { + let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return nil } + let hasAlphanumeric = trimmed.contains { $0.isLetter || $0.isNumber } + return hasAlphanumeric ? nil : "Name needs at least one letter or digit" + } + + // MARK: - Codex catalog + + /// Active catalog entry for `model` (`'auto'` → the default row). + public static func resolveCodexModel( + models: [CodexModelSummary], + model: String + ) -> CodexModelSummary? { + let normalized = model.trimmingCharacters(in: .whitespacesAndNewlines) + if normalized.isEmpty || normalized == "auto" { + return models.first { $0.isDefault } ?? models.first + } + return models.first { $0.id == normalized } + } + + /// `codexModelAdvertisesFastTier`: the fast-mode control only appears + /// when the active model's catalog row advertises a fast service tier. + /// Empty catalog → hidden (no authoritative answer yet). + public static func codexModelAdvertisesFastTier( + model: String, + models: [CodexModelSummary] + ) -> Bool { + guard !models.isEmpty else { return false } + let normalized = model.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + let active: CodexModelSummary? + if !normalized.isEmpty && normalized != "auto" { + active = models.first { + $0.id.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == normalized + } + } else { + active = models.first { $0.isDefault } + } + return active?.serviceTiers?.contains { + $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased().contains("fast") + } == true + } + + /// Supported reasoning efforts of the active codex model, normalized + /// (trim/lowercase/dedupe — `getCodexModelReasoningEfforts`); nil when + /// the catalog does not advertise any (fall back to the static list). + public static func codexReasoningEfforts( + models: [CodexModelSummary], + model: String + ) -> [String]? { + guard let efforts = resolveCodexModel(models: models, model: model)? + .supportedReasoningEfforts + else { + return nil + } + var seen = Set() + let normalized = efforts + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() } + .filter { !$0.isEmpty && seen.insert($0).inserted } + return normalized.isEmpty ? nil : normalized + } + + // MARK: - Drafts + + /// Draft sanitization on restore (web `loadNewSessionFormDraft`): an + /// uncreatable/unknown agent coerces to claude and drops the + /// agent-dependent fields; a permission mode outside the flavor's + /// catalog resets to default. (The Android original also re-normalizes + /// serviceTier/collaborationMode/copilotAgentMode/sessionType strings — + /// here those are enum-constrained already.) + public static func sanitizeDraft(_ draft: NewSessionForm) -> NewSessionForm { + let creatable = AgentFlavor.creatableFlavors.contains(draft.agent) + var base = creatable ? draft : NewSessionForm( + machineId: draft.machineId, + directory: draft.directory, + agent: .claude, + yolo: draft.yolo, + sessionType: draft.sessionType, + worktreeName: draft.worktreeName + ) + if !base.agent.permissionModes.contains(base.permissionMode) { + base.permissionMode = .default + } + return base + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/NewSessionCatalogs.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/NewSessionCatalogs.swift new file mode 100644 index 00000000..28843135 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/NewSessionCatalogs.swift @@ -0,0 +1,57 @@ +import Foundation + +/// A `(wire value, display label)` pair for the create-form option pickers. +public struct NewSessionOption: Equatable, Hashable, Sendable { + public let value: String + public let label: String + + public init(value: String, label: String) { + self.value = value + self.label = label + } +} + +/// Static option catalogs for the new-session form — data ports of +/// `shared/src/models.ts` (`CLAUDE_MODEL_LABELS`), `shared/src/effort.ts` +/// (`CLAUDE_EFFORT_LABELS`) and the web `CODEX_REASONING_EFFORT_OPTIONS` +/// (`web/src/components/NewSession/types.ts`). Data mirrors the Android +/// reference (`NewSessionCatalogs.kt`) exactly. They live in the catalog +/// package (unlike Android's feature-local copy) so the pure form logic and +/// the app UI share one source. +public enum NewSessionCatalogs { + /// `'auto'` sentinel rows use the web's "Default" label. + public static let claudeModels: [NewSessionOption] = [ + NewSessionOption(value: "auto", label: "Default"), + NewSessionOption(value: "sonnet", label: "Sonnet"), + NewSessionOption(value: "sonnet[1m]", label: "Sonnet 1M"), + NewSessionOption(value: "opus", label: "Opus"), + NewSessionOption(value: "opus[1m]", label: "Opus 1M"), + NewSessionOption(value: "fable", label: "Fable"), + NewSessionOption(value: "fable[1m]", label: "Fable 1M"), + ] + + public static let claudeEfforts: [NewSessionOption] = [ + NewSessionOption(value: "auto", label: "Auto"), + NewSessionOption(value: "low", label: "Low"), + NewSessionOption(value: "medium", label: "Medium"), + NewSessionOption(value: "high", label: "High"), + NewSessionOption(value: "xhigh", label: "XHigh"), + NewSessionOption(value: "max", label: "Max"), + ] + + /// Static codex fallback when the model row advertises no efforts + /// (the web drops `max` for codex — `EffortField.tsx`). + public static let codexReasoningEfforts: [NewSessionOption] = [ + NewSessionOption(value: "default", label: "Default"), + NewSessionOption(value: "low", label: "Low"), + NewSessionOption(value: "medium", label: "Medium"), + NewSessionOption(value: "high", label: "High"), + NewSessionOption(value: "xhigh", label: "XHigh"), + ] + + /// Capitalized label for a server-advertised effort id (`high` → `High`). + public static func effortLabel(_ value: String) -> String { + guard let first = value.first else { return value } + return String(first).uppercased() + value.dropFirst() + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift index fdd93f8f..a76d9e48 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift @@ -387,6 +387,57 @@ public struct MachinePathsExistsResponse: Codable, Equatable, Sendable { } } +// MARK: - Codex model catalog + +/// One row of `GET /api/machines/:id/codex-models` (also the session-level +/// twin). Mirrors `CodexModelSummary` (`shared/src/apiTypes.ts`). +public struct CodexModelSummary: Codable, Equatable, Sendable { + public var id: String + public var displayName: String + public var isDefault: Bool + public var defaultReasoningEffort: String? + public var defaultServiceTier: String? + public var supportedReasoningEfforts: [String]? + /// Service tier ids advertised for this model in the current auth/plan + /// context (e.g. `fast`). + public var serviceTiers: [String]? + + public init( + id: String, + displayName: String, + isDefault: Bool, + defaultReasoningEffort: String? = nil, + defaultServiceTier: String? = nil, + supportedReasoningEfforts: [String]? = nil, + serviceTiers: [String]? = nil + ) { + self.id = id + self.displayName = displayName + self.isDefault = isDefault + self.defaultReasoningEffort = defaultReasoningEffort + self.defaultServiceTier = defaultServiceTier + self.supportedReasoningEfforts = supportedReasoningEfforts + self.serviceTiers = serviceTiers + } +} + +/// Body of `GET /api/machines/:id/codex-models` (RPC envelope — check +/// `success`). A runner that does not expose the machine-scoped RPC answers +/// HTTP 503 `{success:false, code:'rpc_target_missing'}`, which surfaces as +/// the transport error, not this body. Added in A-M3c for the new-session +/// codex model picker; mirrors `CodexModelsResponse` (`shared/src/apiTypes.ts`). +public struct CodexModelsResponse: Codable, Equatable, Sendable { + public var success: Bool + public var models: [CodexModelSummary]? + public var error: String? + + public init(success: Bool, models: [CodexModelSummary]? = nil, error: String? = nil) { + self.success = success + self.models = models + self.error = error + } +} + // MARK: - Uploads /// Body of `POST /api/sessions/:id/upload` (RPC envelope). `path` feeds the diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift index 885593f1..608ca447 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/EndpointRequestTests.swift @@ -136,4 +136,36 @@ struct EndpointRequestTests { let failed = try await harness.client.spawnSession(machineId: "m1", SpawnRequest(directory: "/x")) #expect(failed == .error(message: "no runner")) } + + @Test func machineCodexModelsRequestAndRpcTargetMissing() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue( + json: "{\"success\":true,\"models\":[{\"id\":\"gpt-5.2-codex\"," + + "\"displayName\":\"GPT-5.2 Codex\",\"isDefault\":true," + + "\"supportedReasoningEfforts\":[\"low\",\"medium\"]," + + "\"serviceTiers\":[\"standard\",\"fast\"]}]}" + ) + let response = try await harness.client.machineCodexModels(machineId: "m 1") + #expect(response.success) + #expect(response.models?.first?.id == "gpt-5.2-codex") + #expect(response.models?.first?.serviceTiers == ["standard", "fast"]) + let request = await harness.performer.requests.first + #expect( + request?.url?.absoluteString + == "\(testHubURLString)/api/machines/m%201/codex-models" + ) + #expect(request?.httpMethod == "GET") + + // Old runner without the machine RPC: 503 with the stable code the + // new-session form keys off to hide the codex model picker. + await harness.performer.enqueue( + status: 503, + json: "{\"success\":false,\"code\":\"rpc_target_missing\"}" + ) + let error = await capturedError { + try await harness.client.machineCodexModels(machineId: "m1") + } + #expect((error as? APIError)?.status == 503) + #expect((error as? APIError)?.code == "rpc_target_missing") + } } diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift new file mode 100644 index 00000000..04eeca4a --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift @@ -0,0 +1,262 @@ +import Foundation +import HapiClient +import HapiProtocol +import Testing + +/// New-session pure logic (A-M3c), transcribed from the Android reference +/// suite (`NewSessionViewModelTest.kt`: `SpawnBodyTest` + +/// `NewSessionLogicTest`), which is itself asserted against the web create +/// form. Spawn bodies are compared as canonical JSON (`HapiJSON.encoder` +/// sorts keys), so a drifted field set or a leaked default fails loudly. +@Suite("New-session spawn body exactness") +struct NewSessionSpawnBodyTests { + private func canonicalBody(_ form: NewSessionForm, codexFastTierVisible: Bool) throws -> String { + let request = NewSessionLogic.buildSpawnRequest( + form: form, + codexFastTierVisible: codexFastTierVisible + ) + let data = try HapiJSON.encoder.encode(request) + return String(decoding: data, as: UTF8.self) + } + + @Test func claudeSimpleSessionWithModelEffortAndYoloOff() throws { + // Exact SpawnSessionRequestSchema field set — yolo false IS sent for + // claude; permissionMode / reasoning / codex fields are absent. + let body = try canonicalBody( + NewSessionForm( + machineId: "m1", + directory: " /data/github/hapi ", + agent: .claude, + model: "opus", + effort: "high", + yolo: false + ), + codexFastTierVisible: false + ) + #expect(body == """ + {"agent":"claude","directory":"/data/github/hapi","effort":"high",\ + "model":"opus","sessionType":"simple","yolo":false} + """) + } + + @Test func codexWorktreeWithReasoningEffortPermissionModePlanAndFastTier() throws { + // yolo=true must NOT leak into the body for codex-family; the + // worktree name is trimmed; startingMode stays unset in v1 (runner + // defaults to remote). + let body = try canonicalBody( + NewSessionForm( + machineId: "m1", + directory: "/repo", + agent: .codex, + model: "gpt-5.2-codex", + modelReasoningEffort: "high", + permissionMode: .safeYolo, + yolo: true, + sessionType: .worktree, + worktreeName: " feature-x ", + serviceTier: .fast, + collaborationMode: .plan + ), + codexFastTierVisible: true + ) + #expect(body == """ + {"agent":"codex","collaborationMode":"plan","directory":"/repo",\ + "model":"gpt-5.2-codex","modelReasoningEffort":"high",\ + "permissionMode":"safe-yolo","serviceTier":"fast",\ + "sessionType":"worktree","worktreeName":"feature-x"} + """) + } + + @Test func grokSendsPermissionModeNotYoloCursorSendsYoloNotPermissionMode() throws { + let grok = try canonicalBody( + NewSessionForm(directory: "/repo", agent: .grok, permissionMode: .auto, yolo: true), + codexFastTierVisible: false + ) + #expect(grok == """ + {"agent":"grok","directory":"/repo","permissionMode":"auto","sessionType":"simple"} + """) + + // Cursor has no v1 model picker: even a stashed model id is not sent. + let cursor = try canonicalBody( + NewSessionForm(directory: "/repo", agent: .cursor, model: "sonic", yolo: true), + codexFastTierVisible: false + ) + #expect(cursor == """ + {"agent":"cursor","directory":"/repo","sessionType":"simple","yolo":true} + """) + } + + @Test func codexDefaultSelectionsSendNoOptionalFieldsAndHiddenFastTierNoServiceTier() throws { + let body = try canonicalBody( + NewSessionForm(directory: "/repo", agent: .codex, serviceTier: .fast), + codexFastTierVisible: false + ) + // permissionMode 'default' IS sent for codex-family. + #expect(body == """ + {"agent":"codex","directory":"/repo","permissionMode":"default","sessionType":"simple"} + """) + } +} + +@Suite("New-session pure logic") +struct NewSessionLogicTests { + private func dir(_ name: String) -> MachineDirectoryEntry { + MachineDirectoryEntry(name: name, type: .directory) + } + + @Test func parentQueryDerivation() { + #expect( + NewSessionLogic.parentQuery(for: "/data/gi") + == NewSessionLogic.ParentQuery(parent: "/data", prefix: "gi") + ) + #expect( + NewSessionLogic.parentQuery(for: "/data/") + == NewSessionLogic.ParentQuery(parent: "/data", prefix: "") + ) + #expect( + NewSessionLogic.parentQuery(for: "/d") + == NewSessionLogic.ParentQuery(parent: "/", prefix: "d") + ) + #expect( + NewSessionLogic.parentQuery(for: "/") + == NewSessionLogic.ParentQuery(parent: "/", prefix: "") + ) + #expect(NewSessionLogic.parentQuery(for: "relative/path") == nil) + #expect(NewSessionLogic.parentQuery(for: "") == nil) + } + + @Test func suggestionsFilterDirectoriesByPrefixAndJoinWithParent() { + let query = NewSessionLogic.ParentQuery(parent: "/data", prefix: "gi") + let entries = [ + dir("github"), + dir("gists"), + dir("archive"), + MachineDirectoryEntry(name: "gitconfig", type: .file), + ] + #expect( + NewSessionLogic.buildSuggestions(query: query, entries: entries) + == ["/data/github", "/data/gists"] + ) + // Root parent must not double the slash. + #expect( + NewSessionLogic.buildSuggestions( + query: NewSessionLogic.ParentQuery(parent: "/", prefix: "da"), + entries: [dir("data")] + ) == ["/data"] + ) + } + + @Test func recentPathsLRUDedupesToFrontAndCapsAtEight() { + var list: [String] = [] + for index in 1...10 { + list = NewSessionLogic.pushRecent(list, path: "/p\(index)") + } + #expect(list.count == 8) + #expect(list.first == "/p10") + #expect(list.last == "/p3") + + list = NewSessionLogic.pushRecent(list, path: "/p5") + #expect(list.first == "/p5") + #expect(list.count == 8) + #expect(Set(list).count == list.count) + + #expect(NewSessionLogic.pushRecent(list, path: " ") == list) + } + + @Test func worktreeNameValidation() { + #expect(NewSessionLogic.worktreeNameError("") == nil) + #expect(NewSessionLogic.worktreeNameError("feature-x") == nil) + #expect(NewSessionLogic.worktreeNameError("Fix Bug #42") == nil) + #expect(NewSessionLogic.worktreeNameError("---") != nil) + #expect(NewSessionLogic.worktreeNameError("!!!") != nil) + } + + @Test func codexFastTierDetectionFollowsTheActiveModel() { + let models = [ + CodexModelSummary( + id: "gpt-5.2-codex", + displayName: "GPT-5.2", + isDefault: true, + serviceTiers: ["standard", "fast"] + ), + CodexModelSummary( + id: "gpt-5.2-mini", + displayName: "Mini", + isDefault: false, + serviceTiers: ["standard"] + ), + ] + #expect(NewSessionLogic.codexModelAdvertisesFastTier(model: "auto", models: models)) + #expect(NewSessionLogic.codexModelAdvertisesFastTier(model: "gpt-5.2-codex", models: models)) + #expect(!NewSessionLogic.codexModelAdvertisesFastTier(model: "gpt-5.2-mini", models: models)) + #expect(!NewSessionLogic.codexModelAdvertisesFastTier(model: "auto", models: [])) + } + + @Test func codexReasoningEffortsNormalizeAndFallBackToNil() { + let models = [ + CodexModelSummary( + id: "gpt-5.2-codex", + displayName: "GPT-5.2", + isDefault: true, + supportedReasoningEfforts: [" Low ", "medium", "MEDIUM", "", "high"] + ), + CodexModelSummary(id: "bare", displayName: "Bare", isDefault: false), + ] + #expect( + NewSessionLogic.codexReasoningEfforts(models: models, model: "auto") + == ["low", "medium", "high"] + ) + // A row without advertised efforts falls back to the static list (nil). + #expect(NewSessionLogic.codexReasoningEfforts(models: models, model: "bare") == nil) + #expect(NewSessionLogic.codexReasoningEfforts(models: [], model: "auto") == nil) + } + + @Test func draftSanitizationCoercesUncreatableAgentAndStalePermissionMode() { + // Gemini is decodable (stored sessions stay viewable) but not + // creatable: the draft coerces to claude and drops the + // agent-dependent fields while keeping directory/yolo/session type. + let gemini = NewSessionLogic.sanitizeDraft( + NewSessionForm(directory: "/repo", agent: .gemini, model: "gemini-2.5-pro") + ) + #expect(gemini.agent == .claude) + #expect(gemini.model == "auto") + #expect(gemini.directory == "/repo") + + let badMode = NewSessionLogic.sanitizeDraft( + NewSessionForm(agent: .codex, permissionMode: .bypassPermissions) + ) + #expect(badMode.permissionMode == .default) + + let goodMode = NewSessionLogic.sanitizeDraft( + NewSessionForm(agent: .codex, permissionMode: .safeYolo) + ) + #expect(goodMode.permissionMode == .safeYolo) + } + + @Test func draftDecodingToleratesMissingKeysAndRoundTrips() throws { + // Older-version draft with most keys absent → per-field defaults. + let partial = Data(#"{"directory":"/repo","agent":"codex"}"#.utf8) + let decoded = try HapiJSON.decoder.decode(NewSessionForm.self, from: partial) + #expect(decoded == NewSessionForm(directory: "/repo", agent: .codex)) + + // Full round-trip preserves every field. + let full = NewSessionForm( + machineId: "m1", + directory: "/repo", + agent: .copilot, + permissionMode: .yolo, + sessionType: .worktree, + worktreeName: "wip", + copilotAgentMode: .autopilot + ) + let data = try HapiJSON.encoder.encode(full) + #expect(try HapiJSON.decoder.decode(NewSessionForm.self, from: data) == full) + + // A value the catalog enums cannot represent fails the decode — the + // caller treats that as "no draft" (web try/catch parity). + let unknownMode = Data(#"{"permissionMode":"brand-new-mode"}"#.utf8) + #expect(throws: (any Error).self) { + try HapiJSON.decoder.decode(NewSessionForm.self, from: unknownMode) + } + } +} diff --git a/ios/README.md b/ios/README.md index 5b6b32f2..07f2e551 100644 --- a/ios/README.md +++ b/ios/README.md @@ -84,7 +84,25 @@ ios/ Links/ (app-wide \.hapiOpenURL handler: https/http → SFSafariViewController, confirm-first schemes → alert, - hapi-file:// → M4 placeholder). + hapi-file:// → M4 placeholder), + NewSession/ (A-M3c create form, a sheet + off the session list "+": machine picker + with last-used preselect + health line, + directory field with debounced 250 ms + list-directory autocomplete (per-parent + cache) + per-machine recent-path chips + + exists probe (worktree-blocking / + simple two-tap-create), flavor picker + over CREATABLE, per-flavor options — + claude model/effort/yolo; codex machine + catalog (rpc_target_missing hides it), + reasoning effort, native permission, + collaboration + fast tier when + advertised; copilot agent mode; pi + managed note — session type simple/ + worktree + name, UserDefaults draft + + prefs per hub; success dismisses the + sheet and pushes the chat). Packages/HapiKit/ Local SPM package with the real logic: HapiProtocol Pure-Foundation protocol layer. As of M2a: Models/ wire types mirroring shared/src/schemas.ts @@ -101,7 +119,10 @@ ios/ globalPinned > pinned > active > pending desc among active > recency, stable) Catalog/ permission-mode / flavor tables ported from - shared/src/{modes,flavors,copilotModes}.ts + shared/src/{modes,flavors,copilotModes}.ts, + plus the static create-form option lists + (claude models/efforts, codex reasoning- + effort fallback — NewSessionCatalogs) Patch/ versioned session-patch application ported from web/src/lib/sessionPatch.ts Pairing/ BindLink — parses both pairing QR forms @@ -223,6 +244,18 @@ ios/ normalize memoized by row instance identity, reduce + toolGroups with previousGroups-stable group ids. + NewSession/ pure create-form logic (A-M3c), + tested against the Android/web + reference: NewSessionForm (typed + draft, tolerant decode) + + NewSessionLogic (the exact spawn + body per SpawnSessionRequestSchema + incl. the per-flavor yolo/ + permissionMode matrix, parent-path + derivation + suggestion filtering, + recent-path LRU(8), worktree-name + validation, codex catalog helpers, + draft sanitization). Feature endpoints (git/files, scratchlist, voice, usage) join Endpoints/ with their feature packages in M3/M4.