From 40b6ac462c8d530064e74cb27eea123f0ce84026 Mon Sep 17 00:00:00 2001 From: weishu Date: Mon, 14 Sep 2026 08:28:49 +0800 Subject: [PATCH] fix: align directory browsing and iOS session creation --- cli/src/api/apiMachine.test.ts | 40 +++ cli/src/api/apiMachine.ts | 28 +- cli/src/api/machinePathPolicy.test.ts | 10 +- cli/src/api/machinePathPolicy.ts | 18 +- cli/src/runner/run.ts | 2 +- docs/api/client-contract/rest.md | 10 + docs/guide/installation.md | 8 +- .../RemoteDirectoryBrowserView.swift | 2 +- .../Features/NewSession/NewSessionModel.swift | 266 ++++++++---------- .../Features/NewSession/NewSessionView.swift | 58 +++- ios/Hapi/Models/LocalizedNoticeMapper.swift | 1 + ios/Hapi/Resources/Localizable.xcstrings | 77 +++++ ios/HapiTests/NewSessionDirectoryTests.swift | 214 ++++++++++++++ .../RemoteDirectoryBrowserModel.swift | 69 ++++- .../NewSession/NewSessionDirectoryModel.swift | 189 +++++++++++++ .../NewSession/NewSessionForm.swift | 30 ++ .../RemoteDirectoryBrowserModelTests.swift | 56 ++++ .../NewSessionDirectoryModelTests.swift | 266 ++++++++++++++++++ .../HapiClientTests/NewSessionFormTests.swift | 6 + ios/README.md | 9 + 20 files changed, 1152 insertions(+), 207 deletions(-) create mode 100644 ios/HapiTests/NewSessionDirectoryTests.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionDirectoryModel.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionDirectoryModelTests.swift diff --git a/cli/src/api/apiMachine.test.ts b/cli/src/api/apiMachine.test.ts index def544e6..fecf5672 100644 --- a/cli/src/api/apiMachine.test.ts +++ b/cli/src/api/apiMachine.test.ts @@ -765,6 +765,46 @@ describe('ApiMachineClient list-directory handler', () => { return entries.map((entry) => entry.name).sort() } + it('browses outside the home directory when no workspace roots are configured', async () => { + const machine = makeMachine('machine-ls-unrestricted') + const client = new ApiMachineClient('cli-token', machine) + try { + const result = await callListDirectory(client, machine.id, { path: workspaceRoot }) + expect((result as { success: boolean }).success).toBe(true) + expect(entryNames(result)).toEqual(['plain.txt', 'visible-dir']) + } finally { + client.shutdown() + } + }) + + it('lists in-root directory links and rejects links escaping explicit workspace roots', async () => { + const outside = mkdtempSync(join(tmpdir(), 'hapi-machine-ls-outside-')) + mkdirSync(join(workspaceRoot, 'visible-dir', '.git')) + symlinkSync(join(workspaceRoot, 'visible-dir'), join(workspaceRoot, 'linked-repo'), 'dir') + symlinkSync(outside, join(workspaceRoot, 'escape'), 'dir') + const machine = makeMachine('machine-ls-links') + const client = new ApiMachineClient('cli-token', machine, [workspaceRoot]) + try { + const result = await callListDirectory(client, machine.id, { path: workspaceRoot }) + expect(result).toMatchObject({ + success: true, + entries: expect.arrayContaining([ + expect.objectContaining({ name: 'linked-repo', type: 'directory', isGitRepo: true }), + ]), + }) + expect(entryNames(result)).not.toContain('escape') + expect(await callListDirectory(client, machine.id, { path: join(workspaceRoot, 'escape') })) + .toEqual({ success: false, error: 'Path is outside workspace roots' }) + expect(await callListDirectory(client, machine.id, { path: join(workspaceRoot, '..') })) + .toEqual({ success: false, error: 'Path is outside workspace roots' }) + expect(await callListDirectory(client, machine.id, { path: join(workspaceRoot, 'linked-repo') })) + .toMatchObject({ success: true }) + } finally { + client.shutdown() + rmSync(outside, { recursive: true, force: true }) + } + }) + it('filters dot-prefixed entries by default', async () => { const machine = makeMachine('machine-ls-1') const client = new ApiMachineClient('cli-token', machine, [workspaceRoot]) diff --git a/cli/src/api/apiMachine.ts b/cli/src/api/apiMachine.ts index 3c6df8e5..c1ae191a 100644 --- a/cli/src/api/apiMachine.ts +++ b/cli/src/api/apiMachine.ts @@ -113,7 +113,6 @@ export class ApiMachineClient { ) { this.pathPolicy = new MachinePathPolicy({ workspaceRoots, - homeDirectory: this.machine.metadata?.homeDir ?? homedir(), }) this.rpcHandlerManager = new RpcHandlerManager({ @@ -185,7 +184,7 @@ export class ApiMachineClient { const targetPath = await this.pathPolicy.resolveForCheck(rawPath) if (!this.pathPolicy.isWithinBrowseRoots(targetPath)) { - return { success: false, error: 'Path is outside browse roots' } + return { success: false, error: 'Path is outside workspace roots' } } try { @@ -201,34 +200,27 @@ export class ApiMachineClient { if (!includeHidden && entry.name.startsWith('.')) return const fullPath = join(targetPath, entry.name) + const resolvedEntryPath = entry.isSymbolicLink() + ? await this.pathPolicy.resolveForCheck(fullPath) + : fullPath + if (!this.pathPolicy.isWithinBrowseRoots(resolvedEntryPath)) return + const stats = await stat(resolvedEntryPath).catch(() => undefined) let type: 'file' | 'directory' | 'other' = 'other' - let size: number | undefined - let modified: number | undefined let isGitRepo = false - if (entry.isDirectory()) { + if (entry.isDirectory() || stats?.isDirectory()) { type = 'directory' try { - const gitStat = await stat(join(fullPath, '.git')) + const gitStat = await stat(join(resolvedEntryPath, '.git')) isGitRepo = gitStat.isDirectory() || gitStat.isFile() } catch { // not a git repo } - } else if (entry.isFile()) { + } else if (entry.isFile() || stats?.isFile()) { type = 'file' } - if (!entry.isSymbolicLink()) { - try { - const stats = await stat(fullPath) - size = stats.size - modified = stats.mtime.getTime() - } catch { - // ignore stat errors - } - } - - entries.push({ name: entry.name, type, size, modified, isGitRepo }) + entries.push({ name: entry.name, type, size: stats?.size, modified: stats?.mtime.getTime(), isGitRepo }) })) entries.sort((a, b) => { diff --git a/cli/src/api/machinePathPolicy.test.ts b/cli/src/api/machinePathPolicy.test.ts index 347beeb1..7d1bf020 100644 --- a/cli/src/api/machinePathPolicy.test.ts +++ b/cli/src/api/machinePathPolicy.test.ts @@ -16,6 +16,9 @@ describe('MachinePathPolicy', () => { expect(await policy.allowsSpawn(join(first, 'missing', 'child'))).toBe(true) expect(await policy.allowsSpawn(second)).toBe(true) expect(await policy.allowsSpawn(collision)).toBe(false) + expect(await policy.allowsBrowse(first)).toBe(true) + expect(await policy.allowsBrowse(collision)).toBe(false) + expect(await policy.allowsBrowse(join(first, '..project'))).toBe(true) }) it('resolves an existing symlink before checking a missing child', async () => { @@ -28,20 +31,21 @@ describe('MachinePathPolicy', () => { const policy = new MachinePathPolicy({ workspaceRoots: [root] }) expect(await policy.allowsSpawn(join(escape, 'missing'))).toBe(false) + expect(await policy.allowsBrowse(escape)).toBe(false) expect(await policy.resolveForCheck(join(escape, 'missing'))).toBe( join(await realpath(outside), 'missing') ) }) - it('keeps manual spawn unrestricted but scopes browsing to home without roots', async () => { + it('allows both browsing and spawning outside home without explicit roots', async () => { const base = await mkdtemp(join(tmpdir(), 'hapi-path-policy-')) const home = join(base, 'home') const outside = join(base, 'outside') await Promise.all([mkdir(home), mkdir(outside)]) - const policy = new MachinePathPolicy({ homeDirectory: home }) + const policy = new MachinePathPolicy() expect(await policy.allowsSpawn(outside)).toBe(true) expect(await policy.allowsBrowse(join(home, 'missing'))).toBe(true) - expect(await policy.allowsBrowse(outside)).toBe(false) + expect(await policy.allowsBrowse(outside)).toBe(true) }) }) diff --git a/cli/src/api/machinePathPolicy.ts b/cli/src/api/machinePathPolicy.ts index 7b8d8943..2c9de7b7 100644 --- a/cli/src/api/machinePathPolicy.ts +++ b/cli/src/api/machinePathPolicy.ts @@ -1,6 +1,5 @@ import { realpathSync } from 'node:fs' import { realpath } from 'node:fs/promises' -import { homedir } from 'node:os' import { basename, dirname, @@ -8,6 +7,7 @@ import { join, relative, resolve, + sep, } from 'node:path' export function normalizeWindowsDriveRoot(path: string): string { @@ -31,30 +31,24 @@ function normalizeRoots(paths: readonly string[]): string[] { function isPathWithinRoots(path: string, roots: readonly string[]): boolean { return roots.some((root) => { const child = relative(root, path) - return child === '' || (!child.startsWith('..') && !isAbsolute(child)) + return child !== '..' && !child.startsWith(`..${sep}`) && !isAbsolute(child) }) } /** * Single authority for machine-scoped path access. * - * Spawn paths are unrestricted when the runner has no configured workspace - * roots, preserving the legacy manual-entry contract. Browse paths instead - * fall back to the runner's home directory so native autocomplete/pickers can - * remain useful without exposing the whole filesystem. + * Browsing and spawning share the same boundaries. Without explicit workspace + * roots, both can access any path available to the runner's OS account; a + * client's initial directory is a navigation preference, not an access limit. */ export class MachinePathPolicy { readonly workspaceRoots: readonly string[] - readonly browseRoots: readonly string[] constructor(options: { workspaceRoots?: readonly string[] - homeDirectory?: string } = {}) { this.workspaceRoots = normalizeRoots(options.workspaceRoots ?? []) - this.browseRoots = this.workspaceRoots.length > 0 - ? this.workspaceRoots - : normalizeRoots([options.homeDirectory ?? homedir()]) } hasWorkspaceRoots(): boolean { @@ -66,7 +60,7 @@ export class MachinePathPolicy { } isWithinBrowseRoots(path: string): boolean { - return isPathWithinRoots(path, this.browseRoots) + return this.isWithinSpawnRoots(path) } async resolveForCheck(path: string): Promise { diff --git a/cli/src/runner/run.ts b/cli/src/runner/run.ts index 4d0186fe..c182febe 100644 --- a/cli/src/runner/run.ts +++ b/cli/src/runner/run.ts @@ -1257,7 +1257,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // regardless of the verbose/quiet logger setting. console.log(''); console.log('Hapi runner started.'); - console.log(` Workspace roots: ${workspaceRoots?.join(', ') ?? '(not set — browsing is limited to home)'}`); + console.log(` Workspace roots: ${workspaceRoots?.join(', ') ?? '(not set — browsing and spawning are unrestricted)'}`); console.log(` Hub URL: ${configuration.apiUrl}`); console.log(` Machine ID: ${machine.id}`); console.log(` Control port: ${controlPort}`); diff --git a/docs/api/client-contract/rest.md b/docs/api/client-contract/rest.md index 0cb91383..247e63be 100644 --- a/docs/api/client-contract/rest.md +++ b/docs/api/client-contract/rest.md @@ -167,6 +167,16 @@ after the form-level query without requiring a duplicate client RPC. Availability checks executables and static runner configuration only; it does not execute the Agent or verify account/login state. +Directory listing and spawning use the same workspace-root policy. With no +`metadata.workspaceRoots`, paths are unrestricted beyond the runner account's +filesystem permissions; `metadata.homeDir` is only a suggested starting location. +Explicit roots restrict both operations, after canonical symlink resolution. +Listings classify allowed directory symlinks as directories and omit links +whose targets escape the configured roots. Dot-prefixed entries require +`includeHidden: true`. Autocomplete clients can suggest known workspace roots +from metadata while a user types their prefix, without listing a root's +out-of-bounds parent. + ### Git & files (RPC-wrapped) Source: `hub/src/web/routes/git.ts`. Git endpoints return the **raw command output** — `GitCommandResponse` `{success, stdout?, stderr?, exitCode?, error?}` — and the client parses `stdout` itself (reference parsers: `web/src/lib/gitParsers.ts`). diff --git a/docs/guide/installation.md b/docs/guide/installation.md index 08562e21..b90e27d6 100644 --- a/docs/guide/installation.md +++ b/docs/guide/installation.md @@ -332,10 +332,10 @@ Use `--workspace-root ` to restrict which directories the runner can brows hapi runner start --workspace-root ~/projects --workspace-root ~/work ``` -Without `--workspace-root`, manually entered spawn paths remain unrestricted. -Session directory autocomplete and native pickers browse only beneath the -runner's home directory; configuring roots makes both browsing and spawning -use those roots instead. +Without `--workspace-root`, directory browsing and spawning both accept paths +anywhere the runner's OS account can access. The iOS directory picker starts +at the home directory and can navigate above it. Configuring roots restricts +both browsing and spawning to those roots, including symlink targets. For running the hub and runner as persistent background services (pm2, launchd, systemd), see [Deployment](./deployment.md). Supervised installs should set `HAPI_RUNNER_SUPERVISED=1` on the runner process (systemd `Environment=` / pm2 `--env`) so the web **Restart** control can safely stop-runner knowing the supervisor will cold-start it. diff --git a/ios/Hapi/Features/DirectoryBrowser/RemoteDirectoryBrowserView.swift b/ios/Hapi/Features/DirectoryBrowser/RemoteDirectoryBrowserView.swift index 6da25ff4..e3acd424 100644 --- a/ios/Hapi/Features/DirectoryBrowser/RemoteDirectoryBrowserView.swift +++ b/ios/Hapi/Features/DirectoryBrowser/RemoteDirectoryBrowserView.swift @@ -59,7 +59,7 @@ struct RemoteDirectoryBrowserView: View { } } else if let error = model.error { VStack(alignment: .leading, spacing: 8) { - Text(error).foregroundStyle(.red) + Text(LocalizedNoticeMapper.map(error)).foregroundStyle(.red) Button("Retry") { model.refresh() } diff --git a/ios/Hapi/Features/NewSession/NewSessionModel.swift b/ios/Hapi/Features/NewSession/NewSessionModel.swift index 724f7865..668f879e 100644 --- a/ios/Hapi/Features/NewSession/NewSessionModel.swift +++ b/ios/Hapi/Features/NewSession/NewSessionModel.swift @@ -119,8 +119,6 @@ struct NewSessionPrefsStore { /// - `startingMode` stays unset → the runner spawns `'remote'` (pty deferred). @MainActor @Observable final class NewSessionModel { - static let debounce: Duration = .milliseconds(250) - static let msgWorktreeMissing = String(localized: "Worktree sessions require an existing repository directory.") static let msgDirectoryMissing = @@ -130,6 +128,8 @@ final class NewSessionModel { static let msgDirectoryOutsideWorkspaceRoots = String(localized: "Directory must be inside one of this machine's workspace roots.") static let msgDirectoryLookupFailed = String(localized: "Failed to browse directories") + static let msgDirectoryCheckFailed = String(localized: "Failed to check directory") + static let msgMachineOffline = String(localized: "Selected machine is offline. Choose an online machine.") static let msgAgentAvailabilityFailed = String(localized: "Failed to check installed Agents") static let msgRunnerUpgradeRequired = String(localized: "Upgrade and restart this machine's HAPI runner before creating sessions.") @@ -141,17 +141,14 @@ final class NewSessionModel { // MARK: Observable state private(set) var form = NewSessionForm() - private(set) var suggestions: [String] = [] + let directoryInput: NewSessionDirectoryModel + var suggestions: [String] { directoryInput.suggestions } private(set) var codexModels: CodexModelsState = .hidden private(set) var agentAvailability: AgentAvailabilityState = .loading 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 outsideWorkspaceRoots: Set = [] - private(set) var directoryLookupError: String? private(set) var prefsData = NewSessionPrefsData() let directoryBrowser: RemoteDirectoryBrowserModel @@ -162,7 +159,6 @@ final class NewSessionModel { /// 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 availabilityTask: Task? @ObservationIgnored private var defaultDirectoryTask: Task? @@ -170,16 +166,23 @@ final class NewSessionModel { @ObservationIgnored private var availabilityFetchedForMachine: String? @ObservationIgnored private var suppressSuggestions = false @ObservationIgnored private var spawnInFlight = false - @ObservationIgnored private var directoryRequestVersion = 0 - /// 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])? + @ObservationIgnored private var hasStarted = false + @ObservationIgnored private var directoryEdited = false + @ObservationIgnored private var directoryEditVersion = 0 - init(session: HubSession, onCreated: @escaping @MainActor (String) -> Void) { + init( + session: HubSession, + defaults: UserDefaults = .standard, + onCreated: @escaping @MainActor (String) -> Void + ) { self.session = session - self.prefsStore = NewSessionPrefsStore(hubUrl: session.hubUrl) + self.prefsStore = NewSessionPrefsStore(hubUrl: session.hubUrl, defaults: defaults) self.onCreated = onCreated + self.directoryInput = NewSessionDirectoryModel( + requester: session.api, + lookupError: Self.msgDirectoryLookupFailed, + checkError: Self.msgDirectoryCheckFailed + ) self.directoryBrowser = RemoteDirectoryBrowserModel( requester: session.api, fallbackError: Self.msgDirectoryLookupFailed @@ -191,15 +194,18 @@ final class NewSessionModel { /// Restore prefs + sanitized draft, preselect a machine, refresh the /// roster. Call once per presentation. func start() async { - prefsData = prefsStore.readPrefs() - let initial = prefsStore.readDraft().map(NewSessionLogic.sanitizeDraft) ?? NewSessionForm() - form = initial + if !hasStarted { + hasStarted = true + prefsData = prefsStore.readPrefs() + let draft = prefsStore.readDraft().map(NewSessionLogic.sanitizeDraft) + form = draft ?? NewSessionForm() + // A saved empty path can be intentional; never replace it on refresh. + directoryEdited = draft != nil + suppressSuggestions = true + } reconcileMachineSelection() refreshAgentAvailability() refreshCodexModelsIfNeeded() - // A restored directory should probe existence but not pop the - // autocomplete dropdown — suggestions belong to typing. - suppressSuggestions = true scheduleDirectoryWork() do { @@ -207,14 +213,43 @@ final class NewSessionModel { } catch { // Snapshot (if any) keeps serving; the picker shows what it has. } + guard !Task.isCancelled else { return } machinesSettled = true - reconcileMachineSelection() + machinesChanged() } - /// Machine roster changed (SSE / refresh) — re-run the preselection: - /// keep a still-online selection; otherwise last-used, else first. + /// Only an unselected form is auto-selected. Losing a machine must not + /// move the user's path or pending Create action onto a different host. func machinesChanged() { + guard hasStarted else { return } reconcileMachineSelection() + if selectedMachine == nil { + cancelDefaultDirectoryResolution() + directoryBrowser.close() + availabilityTask?.cancel() + codexTask?.cancel() + availabilityFetchedForMachine = nil + codexFetchedForMachine = nil + } else { + if directoryBrowser.isPresented, + directoryBrowser.roots != selectedMachine.map(RemoteDirectoryPath.browseRoots) { + directoryBrowser.close() + } + refreshAgentAvailability() + refreshCodexModelsIfNeeded() + } + scheduleDirectoryWork() + } + + func stopDirectoryWork() { + cancelDefaultDirectoryResolution() + directoryInput.stop() + } + + private func cancelDefaultDirectoryResolution() { + directoryEditVersion += 1 + defaultDirectoryTask?.cancel() + defaultDirectoryTask = nil } // MARK: - Derived state @@ -227,6 +262,14 @@ final class NewSessionModel { session.machineStore.machines.isEmpty && !machinesSettled } + var machineUnavailable: Bool { + machinesSettled && form.machineId != nil && selectedMachine == nil + } + + var normalizedDirectory: String { + RemoteDirectoryPath.expandHome(form.directory, homeDirectory: selectedMachine?.metadata?.homeDir) + } + /// `runnerState.lastSpawnError` of the selected machine, formatted /// (`web/src/utils/formatRunnerSpawnError.ts`). var runnerSpawnError: String? { @@ -252,8 +295,8 @@ final class NewSessionModel { isError: false ) } - if let directoryLookupError { - return DirectoryStatusUI(message: directoryLookupError, isError: true) + if let error = directoryInput.existenceError { + return DirectoryStatusUI(message: error, isError: true) } return nil } @@ -361,8 +404,8 @@ final class NewSessionModel { } var canCreate: Bool { - form.machineId != nil - && !form.trimmedDirectory.isEmpty + selectedMachine != nil + && !normalizedDirectory.isEmpty && !isSpawning && !missingWorktreeDirectory && !directoryOutsideWorkspaceRoots @@ -372,18 +415,15 @@ final class NewSessionModel { } private var selectedMachine: Machine? { - session.machineStore.machines.first { $0.id == form.machineId } + session.machineStore.machines.first { $0.id == form.machineId && $0.active } } private var directoryExists: Bool? { - let trimmed = form.trimmedDirectory - guard !trimmed.isEmpty else { return nil } - return pathExistence[trimmed] + directoryInput.exists } private var directoryOutsideWorkspaceRoots: Bool { - let trimmed = form.trimmedDirectory - return !trimmed.isEmpty && outsideWorkspaceRoots.contains(trimmed) + directoryInput.outsideWorkspaceRoots } private var missingWorktreeDirectory: Bool { @@ -418,11 +458,15 @@ final class NewSessionModel { // MARK: - Actions func setMachine(_ machineId: String) { - guard machineId != form.machineId else { return } + guard !isSpawning, machineId != form.machineId, + session.machineStore.machines.contains(where: { $0.id == machineId && $0.active }) + else { return } applyMachineSelection(machineId, resetDirectory: true) } func setDirectory(_ value: String) { + cancelDefaultDirectoryResolution() + directoryEdited = true suppressSuggestions = false confirmCreateDirectoryArmed = false form.directory = value @@ -443,7 +487,8 @@ final class NewSessionModel { directoryBrowser.open( machineId: machine.id, roots: RemoteDirectoryPath.browseRoots(for: machine), - initialPath: form.trimmedDirectory + initialPath: normalizedDirectory, + defaultPath: RemoteDirectoryPath.defaultDirectory(for: machine) ) } @@ -538,7 +583,10 @@ final class NewSessionModel { /// 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 canCreate, !spawnInFlight else { return } + cancelDefaultDirectoryResolution() + var current = form + current.directory = normalizedDirectory guard let machineId = current.machineId else { return } let directory = current.trimmedDirectory guard !directory.isEmpty, !spawnInFlight else { return } @@ -553,7 +601,7 @@ final class NewSessionModel { spawnInFlight = true isSpawning = true spawnError = nil - Task { [weak self] in + Task { [weak self, current] in defer { self?.spawnInFlight = false self?.isSpawning = false @@ -566,11 +614,11 @@ final class NewSessionModel { paths: [directory] ) let exists = pathResult.exists[directory] - if let exists { - self.pathExistence[directory] = exists + guard self.selectedMachine?.id == machineId else { + self.spawnError = Self.msgMachineOffline + return } - self.outsideWorkspaceRoots.remove(directory) - self.outsideWorkspaceRoots.formUnion(pathResult.outsideWorkspaceRoots ?? []) + self.directoryInput.acceptExistence(pathResult, machineId: machineId, path: directory) if pathResult.outsideWorkspaceRoots?.contains(directory) == true { self.spawnError = Self.msgDirectoryOutsideWorkspaceRoots return @@ -612,9 +660,10 @@ final class NewSessionModel { // MARK: - Internals private func pickPath(_ path: String) { + cancelDefaultDirectoryResolution() + directoryEdited = true suppressSuggestions = true confirmCreateDirectoryArmed = false - suggestions = [] form.directory = path persistDraft() scheduleDirectoryWork() @@ -625,26 +674,17 @@ final class NewSessionModel { } private func reconcileMachineSelection() { - let machines = session.machineStore.machines + guard form.machineId == nil else { return } + let machines = session.machineStore.machines.filter(\.active) guard !machines.isEmpty else { return } - if let current = form.machineId, machines.contains(where: { $0.id == current }) { - if form.trimmedDirectory.isEmpty { - applyMachineSelection(current, resetDirectory: true) - } - return - } let target = machines.first { $0.id == prefsData.lastMachineId } ?? machines[0] - applyMachineSelection(target.id, resetDirectory: form.trimmedDirectory.isEmpty) + applyMachineSelection(target.id, resetDirectory: !directoryEdited && form.trimmedDirectory.isEmpty) } private func applyMachineSelection(_ machineId: String, resetDirectory: Bool) { directoryBrowser.close() - defaultDirectoryTask?.cancel() - pathExistence = [:] - outsideWorkspaceRoots = [] - directoryLookupError = nil - suggestions = [] - cachedListing = nil + cancelDefaultDirectoryResolution() + directoryInput.stop() confirmCreateDirectoryArmed = false // The seeded recent path is a pick, not typing — no dropdown. suppressSuggestions = true @@ -652,7 +692,8 @@ final class NewSessionModel { form.model = "auto" if resetDirectory { let machine = session.machineStore.machines.first { $0.id == machineId } - form.directory = machine.flatMap { RemoteDirectoryPath.browseRoots(for: $0).first } ?? "" + directoryEdited = false + form.directory = machine.map(RemoteDirectoryPath.defaultDirectory) ?? "" } persistDraft() if resetDirectory { @@ -664,7 +705,9 @@ final class NewSessionModel { } private func resolveDefaultDirectory(machineId: String, fallback: String) { - defaultDirectoryTask?.cancel() + cancelDefaultDirectoryResolution() + let editVersion = directoryEditVersion + let roots = selectedMachine.map(RemoteDirectoryPath.browseRoots) let recent = recentPaths(for: machineId) guard !recent.isEmpty else { return } defaultDirectoryTask = Task { [weak self] in @@ -687,7 +730,10 @@ final class NewSessionModel { }) else { return } - guard self.form.machineId == machineId, self.form.directory == fallback else { return } + guard self.selectedMachine?.id == machineId, + self.selectedMachine.map(RemoteDirectoryPath.browseRoots) == roots, + self.directoryEditVersion == editVersion, + self.form.directory == fallback else { return } self.suppressSuggestions = true self.form.directory = valid self.persistDraft() @@ -695,106 +741,22 @@ final class NewSessionModel { } } - /// Debounced directory work: parent listing for autocomplete + exists - /// probe, both riding one 250 ms debounce like the Android reference. private func scheduleDirectoryWork() { - directoryTask?.cancel() - directoryRequestVersion += 1 - let requestVersion = directoryRequestVersion - 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 } - guard self.directoryRequestVersion == requestVersion, - self.form.machineId == machineId - else { - return - } - await self.performDirectoryWork(machineId: machineId, requestVersion: requestVersion) - } - } - - private func performDirectoryWork(machineId: String, requestVersion: Int) 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 - directoryLookupError = nil - } else { - do { - let response = try await api.listMachineDirectory( - machineId: machineId, - path: query.parent - ) - guard isCurrentDirectoryRequest(requestVersion, machineId: machineId) else { return } - if response.success { - entries = response.entries ?? [] - cachedListing = (machineId, query.parent, entries) - directoryLookupError = nil - } else { - entries = [] - directoryLookupError = response.error ?? Self.msgDirectoryLookupFailed - } - } catch is CancellationError { - return - } catch { - guard isCurrentDirectoryRequest(requestVersion, machineId: machineId) else { return } - directoryLookupError = (error as? LocalizedError)?.errorDescription - ?? Self.msgDirectoryLookupFailed - entries = [] - } - } - guard isCurrentDirectoryRequest(requestVersion, machineId: machineId) else { return } - // Never suggest the path already typed verbatim. - suggestions = NewSessionLogic.buildSuggestions(query: query, entries: entries) - .filter { $0 != trimmed } - } else { - suggestions = [] - directoryLookupError = nil - } - - if !trimmed.isEmpty { - // Unknown existence (request failed): no status hint, the spawn - // re-checks anyway. - do { - let result = try await api.machinePathsExist(machineId: machineId, paths: [trimmed]) - guard isCurrentDirectoryRequest(requestVersion, machineId: machineId) else { return } - pathExistence.merge(result.exists) { _, new in new } - outsideWorkspaceRoots.remove(trimmed) - outsideWorkspaceRoots.formUnion(result.outsideWorkspaceRoots ?? []) - } catch is CancellationError { - return - } catch { - // Unknown existence: no status hint, spawn re-checks anyway. - } - } - } - - private func isCurrentDirectoryRequest(_ requestVersion: Int, machineId: String) -> Bool { - !Task.isCancelled - && directoryRequestVersion == requestVersion - && form.machineId == machineId + directoryInput.update( + machine: selectedMachine, + path: form.directory, + showSuggestions: !suppressSuggestions + ) } private func refreshAgentAvailability(force: Bool = false) { - guard let machineId = form.machineId else { + guard let machineId = selectedMachine?.id else { availabilityTask?.cancel() availabilityFetchedForMachine = nil agentAvailability = .loading return } - if !force, - availabilityFetchedForMachine == machineId, - agentAvailability != .loading { + if !force, availabilityFetchedForMachine == machineId { return } availabilityTask?.cancel() @@ -838,7 +800,7 @@ final class NewSessionModel { codexModels = .hidden return } - guard let machineId = form.machineId else { + guard let machineId = selectedMachine?.id else { codexModels = .hidden return } diff --git a/ios/Hapi/Features/NewSession/NewSessionView.swift b/ios/Hapi/Features/NewSession/NewSessionView.swift index f69b161a..708714db 100644 --- a/ios/Hapi/Features/NewSession/NewSessionView.swift +++ b/ios/Hapi/Features/NewSession/NewSessionView.swift @@ -49,6 +49,9 @@ struct NewSessionView: View { onSelect: model.selectBrowsedDirectory ) } + .onDisappear { + model.stopDirectoryWork() + } } // MARK: - Machine @@ -62,6 +65,9 @@ struct NewSessionView: View { .foregroundStyle(.secondary) } else { Picker("Machine", selection: machineBinding) { + if model.machineUnavailable, let machineId = model.form.machineId { + Text("Selected machine is offline").tag(machineId) + } ForEach(model.machines) { machine in Text(machine.label).tag(machine.id) } @@ -72,6 +78,11 @@ struct NewSessionView: View { .foregroundStyle(.secondary) } } + if model.machineUnavailable { + Text(NewSessionModel.msgMachineOffline) + .font(.footnote) + .foregroundStyle(.red) + } if let error = model.runnerSpawnError { Text("Runner last spawn error: \(error)") .font(.footnote) @@ -112,8 +123,11 @@ struct NewSessionView: View { } .buttonStyle(.borderless) .accessibilityLabel("Browse") + .disabled(model.machineUnavailable || model.form.machineId == nil) } + directoryLookupStatus + // Server-side autocomplete (list-directory on the parent path). ForEach(model.suggestions, id: \.self) { suggestion in Button { @@ -146,14 +160,52 @@ struct NewSessionView: View { } header: { Text("Directory") } footer: { - if let status = model.directoryStatus { - Text(status.message) - .foregroundStyle(status.isError ? AnyShapeStyle(.red) : AnyShapeStyle(.secondary)) + if model.directoryInput.isCheckingExistence { + Text("Checking directory…") + } else if let status = model.directoryStatus { + HStack(alignment: .firstTextBaseline) { + Text(LocalizedNoticeMapper.map(status.message)) + .foregroundStyle(status.isError ? AnyShapeStyle(.red) : AnyShapeStyle(.secondary)) + if model.directoryInput.existenceError != nil { + Button("Retry") { model.directoryInput.retry() } + } + } } } .disabled(model.isSpawning) } + @ViewBuilder + private var directoryLookupStatus: some View { + switch model.directoryInput.lookupState { + case .idle: + EmptyView() + case .loading: + HStack(spacing: 8) { + ProgressView().controlSize(.small) + Text("Searching directories…").foregroundStyle(.secondary) + } + .font(.footnote) + case .loaded: + if model.suggestions.isEmpty { + Text("No matching directories") + .font(.footnote) + .foregroundStyle(.secondary) + } + case .outsideRoots: + Text(NewSessionModel.msgDirectoryOutsideWorkspaceRoots) + .font(.footnote) + .foregroundStyle(.red) + case .failed(let error): + HStack(alignment: .firstTextBaseline) { + Text(LocalizedNoticeMapper.map(error)).foregroundStyle(.red) + Spacer() + Button("Retry") { model.directoryInput.retry() } + } + .font(.footnote) + } + } + private var directoryBrowserPresented: Binding { Binding( get: { model.directoryBrowser.isPresented }, diff --git a/ios/Hapi/Models/LocalizedNoticeMapper.swift b/ios/Hapi/Models/LocalizedNoticeMapper.swift index 0e2cef95..f7469152 100644 --- a/ios/Hapi/Models/LocalizedNoticeMapper.swift +++ b/ios/Hapi/Models/LocalizedNoticeMapper.swift @@ -42,6 +42,7 @@ enum LocalizedNoticeMapper { "Transcription failed", // NewSessionLogic "Name needs at least one letter or digit", + "Path is outside workspace roots", // MessageWindowController (degraded-sync banner) "Failed to synchronize messages", "Failed to load older messages", diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index 4649e25f..980ca98b 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -1269,6 +1269,17 @@ } } }, + "Checking directory…" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在检查目录…" + } + } + } + }, "Checking hub…" : { "extractionState" : "manual", "localizations" : { @@ -2182,6 +2193,17 @@ } } }, + "Failed to check directory" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "无法检查目录" + } + } + } + }, "Failed to check installed Agents" : { "extractionState" : "manual", "localizations" : { @@ -3194,6 +3216,17 @@ } } }, + "No matching directories" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "没有匹配的目录" + } + } + } + }, "No messages yet" : { "extractionState" : "manual", "localizations" : { @@ -3645,6 +3678,17 @@ } } }, + "Path is outside workspace roots" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "目录不在此机器允许的工作区内。" + } + } + } + }, "Paused" : { "extractionState" : "manual", "localizations" : { @@ -4459,6 +4503,17 @@ } } }, + "Searching directories…" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在查找目录…" + } + } + } + }, "Section" : { "extractionState" : "manual", "localizations" : { @@ -4503,6 +4558,28 @@ } } }, + "Selected machine is offline" : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "所选机器已离线" + } + } + } + }, + "Selected machine is offline. Choose an online machine." : { + "extractionState" : "manual", + "localizations" : { + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "所选机器已离线,请选择一台在线机器。" + } + } + } + }, "Send" : { "extractionState" : "manual", "localizations" : { diff --git a/ios/HapiTests/NewSessionDirectoryTests.swift b/ios/HapiTests/NewSessionDirectoryTests.swift new file mode 100644 index 00000000..5921303b --- /dev/null +++ b/ios/HapiTests/NewSessionDirectoryTests.swift @@ -0,0 +1,214 @@ +import Foundation +import HapiClient +import HapiProtocol +import XCTest +@testable import Hapi + +@MainActor +final class NewSessionDirectoryTests: XCTestCase { + func testClearingDirectorySurvivesRosterRefreshWithoutResettingModel() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + await harness.model.start() + harness.model.setModel("opus") + harness.model.setDirectory("") + try await harness.session.machineStore.refresh() + harness.model.machinesChanged() + XCTAssertEqual(harness.model.form.directory, "") + XCTAssertEqual(harness.model.form.model, "opus") + XCTAssertFalse(harness.model.canCreate) + } + + func testRestoredEmptyDirectoryIsNotReseeded() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + harness.prefs.writeDraft(NewSessionForm(machineId: "m1", directory: "", model: "opus")) + await harness.model.start() + XCTAssertEqual(harness.model.form.directory, "") + XCTAssertEqual(harness.model.form.model, "opus") + } + + func testExplicitPickOfFallbackSurvivesLateRecentDirectoryResponse() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + harness.prefs.writePrefs(NewSessionPrefsData(lastMachineId: "m1", recentPaths: ["m1": ["/recent"]])) + await harness.http.holdPath("/recent") + await harness.model.start() + try await newSessionEventually { await harness.http.waitingPaths.contains("/recent") } + // Same text as the automatic fallback: string equality alone is insufficient. + harness.model.pickRecentPath("/home/m1") + await harness.http.releasePaths() + try await newSessionEventually { await harness.http.completedPaths.contains("/recent") } + XCTAssertEqual(harness.model.form.directory, "/home/m1") + XCTAssertEqual(harness.prefs.readDraft()?.directory, "/home/m1") + } + + func testOfflineSelectionRetainsItsPathAndExplicitSwitchUsesTheNewMachineDefault() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + await harness.model.start() + harness.model.setDirectory("/project/on/m1") + harness.session.machineStore.applyMachineEvent(machineId: "m1", data: .removed) + harness.model.machinesChanged() + XCTAssertEqual(harness.model.form.machineId, "m1") + XCTAssertEqual(harness.model.form.directory, "/project/on/m1") + XCTAssertTrue(harness.model.machineUnavailable) + XCTAssertFalse(harness.model.canCreate) + harness.model.create() + let spawns = await harness.http.spawns + XCTAssertTrue(spawns.isEmpty) + harness.model.setMachine("m2") + XCTAssertEqual(harness.model.form.machineId, "m2") + XCTAssertEqual(harness.model.form.directory, "/home/m2") + XCTAssertFalse(harness.model.machineUnavailable) + } + + func testHomeExpansionIsUsedForChecksSpawnAndRecentPaths() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + await harness.model.start() + harness.model.setDirectory("~/project") + try await newSessionEventually { harness.model.canCreate } + harness.model.create() + try await newSessionEventually { !harness.model.isSpawning } + let spawns = await harness.http.spawns + XCTAssertEqual(spawns.map(\.directory), ["/home/m1/project"]) + let paths = await harness.http.checkedPaths + XCTAssertTrue(paths.contains("/home/m1/project")) + XCTAssertFalse(paths.contains("~/project")) + XCTAssertEqual(harness.prefs.readPrefs().recentPaths["m1"], ["/home/m1/project"]) + XCTAssertNil(harness.prefs.readDraft()) + } + + func testMissingDirectoryRequiresSecondTapAndWorktreeRemainsBlocked() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + await harness.model.start() + harness.model.setDirectory("/missing") + try await newSessionEventually { harness.model.canCreate } + harness.model.create() + try await newSessionEventually { !harness.model.isSpawning } + XCTAssertTrue(harness.model.confirmCreateDirectory) + let firstSpawns = await harness.http.spawns + XCTAssertTrue(firstSpawns.isEmpty) + harness.model.create() + try await newSessionEventually { !harness.model.isSpawning } + let confirmedSpawns = await harness.http.spawns + XCTAssertEqual(confirmedSpawns.count, 1) + + harness.model.setDirectory("/missing-worktree") + harness.model.setSessionType(.worktree) + try await newSessionEventually { !harness.model.directoryInput.isCheckingExistence } + XCTAssertFalse(harness.model.canCreate) + harness.model.create() + let finalSpawns = await harness.http.spawns + XCTAssertEqual(finalSpawns.count, 1) + } + + func testMachineGoingOfflineDuringCreatePreflightDoesNotSpawnElsewhere() async throws { + let harness = try NewSessionDirectoryHarness() + defer { harness.model.stopDirectoryWork() } + await harness.model.start() + harness.model.setDirectory("/project") + try await newSessionEventually { harness.model.canCreate && !harness.model.directoryInput.isCheckingExistence } + await harness.http.holdPath("/project") + harness.model.create() + try await newSessionEventually { await harness.http.waitingPaths.contains("/project") } + harness.session.machineStore.applyMachineEvent(machineId: "m1", data: .removed) + harness.model.machinesChanged() + await harness.http.releasePaths() + try await newSessionEventually { !harness.model.isSpawning } + let spawns = await harness.http.spawns + XCTAssertTrue(spawns.isEmpty) + XCTAssertEqual(harness.model.spawnError, NewSessionModel.msgMachineOffline) + XCTAssertEqual(harness.model.form.machineId, "m1") + } +} + +@MainActor +private func newSessionEventually(_ condition: @MainActor () async -> Bool) async throws { + let clock = ContinuousClock() + let deadline = clock.now.advanced(by: .seconds(4)) + while clock.now < deadline { + if await condition() { return } + try await Task.sleep(for: .milliseconds(5)) + } + XCTFail("New-session state did not settle") + throw URLError(.timedOut) +} + +@MainActor +private final class NewSessionDirectoryHarness { + let http = NewSessionDirectoryHTTP() + let session: HubSession + let model: NewSessionModel + let prefs: NewSessionPrefsStore + + init() throws { + let hubUrl = "https://directory-\(UUID().uuidString.lowercased()).test" + let credentials = InMemoryCredentialStore() + let payload = Data(#"{"uid":1,"exp":4102444800,"ns":"test"}"#.utf8).base64EncodedString() + try credentials.store(HubCredentials(hubUrl: hubUrl, accessToken: "test", jwt: "e30.\(payload).test")) + session = try XCTUnwrap(HubSession(hubUrl: hubUrl, credentialStore: credentials, performer: http)) + let defaults = try XCTUnwrap(UserDefaults(suiteName: UUID().uuidString)) + prefs = NewSessionPrefsStore(hubUrl: hubUrl, defaults: defaults) + model = NewSessionModel(session: session, defaults: defaults, onCreated: { _ in }) + } +} + +private actor NewSessionDirectoryHTTP: HTTPPerforming { + private(set) var spawns: [SpawnRequest] = [] + private(set) var checkedPaths: [String] = [] + private(set) var completedPaths: [String] = [] + private(set) var waitingPaths: Set = [] + private var heldPaths: Set = [] + private var waiters: [CheckedContinuation] = [] + + func holdPath(_ path: String) { heldPaths.insert(path) } + func releasePaths() { + heldPaths = [] + waitingPaths = [] + let pending = waiters + waiters = [] + for waiter in pending { waiter.resume() } + } + + func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + let url = try XCTUnwrap(request.url) + let data: Data + if url.path == "/api/machines" { + struct Roster: Encodable { let machines: [Machine] } + let machines = ["m1", "m2"].map { id in + Machine( + id: id, namespace: "test", seq: 1, createdAt: 0, updatedAt: 0, active: true, activeAt: 0, + metadata: MachineMetadata(host: id, platform: "linux", happyCliVersion: "test", homeDir: "/home/\(id)"), + metadataVersion: 1, runnerStateVersion: 0 + ) + } + data = try HapiJSON.encoder.encode(Roster(machines: machines)) + } else if url.path.hasSuffix("/agent-availability") { + data = Data(#"{"agents":[{"agent":"claude","available":true}]}"#.utf8) + } else if url.path.hasSuffix("/list-directory") { + data = Data(#"{"success":true,"entries":[]}"#.utf8) + } else if url.path.hasSuffix("/paths/exists") { + struct PathsRequest: Decodable { let paths: [String] } + let paths = try HapiJSON.decoder.decode(PathsRequest.self, from: XCTUnwrap(request.httpBody)).paths + checkedPaths += paths + if paths.contains(where: heldPaths.contains) { + waitingPaths.formUnion(paths) + await withCheckedContinuation { waiters.append($0) } + } + completedPaths += paths + data = try HapiJSON.encoder.encode(MachinePathsExistsResponse( + exists: Dictionary(uniqueKeysWithValues: paths.map { ($0, !$0.hasPrefix("/missing")) }) + )) + } else if url.path.hasSuffix("/spawn") { + spawns.append(try HapiJSON.decoder.decode(SpawnRequest.self, from: XCTUnwrap(request.httpBody))) + data = Data(#"{"type":"success","sessionId":"created"}"#.utf8) + } else { + XCTFail("Unexpected new-session request: \(url.path)") + throw URLError(.badURL) + } + return (data, try XCTUnwrap(HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil))) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/DirectoryBrowser/RemoteDirectoryBrowserModel.swift b/ios/Packages/HapiKit/Sources/HapiClient/DirectoryBrowser/RemoteDirectoryBrowserModel.swift index f638bc12..4ad574d2 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/DirectoryBrowser/RemoteDirectoryBrowserModel.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/DirectoryBrowser/RemoteDirectoryBrowserModel.swift @@ -25,18 +25,51 @@ public struct RemoteDirectoryBreadcrumb: Identifiable, Equatable, Sendable { /** Pure remote-path operations shared by directory-browser consumers. */ public enum RemoteDirectoryPath { + /// Empty roots mean unrestricted browsing, matching the runner's spawn policy. public static func browseRoots(for machine: Machine) -> [String] { - let workspaceRoots = unique( + unique( machine.metadata?.workspaceRoots? + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } ?? [] ) - if !workspaceRoots.isEmpty { return workspaceRoots } + } + + public static func defaultDirectory(for machine: Machine) -> String { + if let root = browseRoots(for: machine).first { return root } if let home = machine.metadata?.homeDir, !home.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - return [home] + return home.trimmingCharacters(in: .whitespacesAndNewlines) } - return [] + return machine.metadata?.platform == "win32" ? "" : "/" + } + + /// Expand against the runner's home, never the phone's local filesystem. + public static func expandHome(_ input: String, homeDirectory: String?) -> String { + let path = input.trimmingCharacters(in: .whitespacesAndNewlines) + guard let home = homeDirectory?.trimmingCharacters(in: .whitespacesAndNewlines), + !home.isEmpty else { return path } + if path == "~" { return home } + if path.hasPrefix("~/") || (home.contains("\\") && path.hasPrefix("~\\")) { + return join(parent: home, child: String(path.dropFirst(2))) + } + return path + } + + public static func filesystemRoot(_ path: String) -> String? { + if isDriveAbsolute(path) { return String(path.prefix(3)) } + if path.hasPrefix("\\\\") || path.hasPrefix("//") { + let parts = path.dropFirst(2).split(whereSeparator: isPathSeparator) + guard parts.count >= 2 else { return nil } + let separator = path.hasPrefix("\\") ? "\\" : "/" + return separator + separator + parts[0] + separator + parts[1] + } + return path.hasPrefix("/") ? "/" : nil + } + + public static func allowsBrowsing(path: String, roots: [String]) -> Bool { + filesystemRoot(path) != nil + && (roots.isEmpty || roots.contains { isWithinRoot(path: path, root: $0) }) } public static func join(parent: String, child: String) -> String { @@ -124,7 +157,8 @@ public enum RemoteDirectoryPath { * Reusable runner-backed directory navigation state machine. * * Consumers own presentation and selection handling. Navigation is lexically - * confined to ``roots``; the runner performs canonical symlink-aware checks. + * confined to explicit ``roots``; empty roots allow any absolute path. The + * runner performs canonical symlink-aware checks. */ @MainActor @Observable public final class RemoteDirectoryBrowserModel { @@ -152,17 +186,25 @@ public final class RemoteDirectoryBrowserModel { self.fallbackError = fallbackError } - public func open(machineId: String, roots: [String], initialPath: String? = nil) { + public func open( + machineId: String, + roots: [String], + initialPath: String? = nil, + defaultPath: String? = nil + ) { close() let usableRoots = unique(roots.filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) let selectedInitialPath = initialPath.flatMap { candidate in - usableRoots.contains { RemoteDirectoryPath.isWithinRoot(path: candidate, root: $0) } + RemoteDirectoryPath.allowsBrowsing(path: candidate, roots: usableRoots) ? candidate : nil } - guard let path = selectedInitialPath ?? usableRoots.first else { return } + let fallback = defaultPath.flatMap { + RemoteDirectoryPath.allowsBrowsing(path: $0, roots: usableRoots) ? $0 : nil + } + guard let path = selectedInitialPath ?? fallback ?? usableRoots.first else { return } self.machineId = machineId self.isPresented = true self.path = path @@ -187,7 +229,7 @@ public final class RemoteDirectoryBrowserModel { public func navigate(to path: String) { guard isPresented, - roots.contains(where: { RemoteDirectoryPath.isWithinRoot(path: path, root: $0) }) + RemoteDirectoryPath.allowsBrowsing(path: path, roots: roots) else { return } @@ -200,7 +242,7 @@ public final class RemoteDirectoryBrowserModel { public func navigateUp() { guard let parent = RemoteDirectoryPath.parent(path), - roots.contains(where: { RemoteDirectoryPath.isWithinRoot(path: parent, root: $0) }) + RemoteDirectoryPath.allowsBrowsing(path: parent, roots: roots) else { return } @@ -220,7 +262,7 @@ public final class RemoteDirectoryBrowserModel { private func load(_ path: String) { guard let machineId, isPresented, - roots.contains(where: { RemoteDirectoryPath.isWithinRoot(path: path, root: $0) }) + RemoteDirectoryPath.allowsBrowsing(path: path, roots: roots) else { return } @@ -235,7 +277,7 @@ public final class RemoteDirectoryBrowserModel { error = nil breadcrumbs = makeBreadcrumbs(path: path, roots: browseRoots) canGoUp = RemoteDirectoryPath.parent(path).map { parent in - browseRoots.contains { RemoteDirectoryPath.isWithinRoot(path: parent, root: $0) } + RemoteDirectoryPath.allowsBrowsing(path: parent, roots: browseRoots) } ?? false loadTask = Task { [weak self] in @@ -298,7 +340,8 @@ public final class RemoteDirectoryBrowserModel { } private func makeBreadcrumbs(path: String, roots: [String]) -> [RemoteDirectoryBreadcrumb] { - guard let root = roots + let breadcrumbRoots = roots.isEmpty ? [RemoteDirectoryPath.filesystemRoot(path)].compactMap { $0 } : roots + guard let root = breadcrumbRoots .filter({ RemoteDirectoryPath.isWithinRoot(path: path, root: $0) }) .max(by: { $0.count < $1.count }) else { diff --git a/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionDirectoryModel.swift b/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionDirectoryModel.swift new file mode 100644 index 00000000..5b35238b --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionDirectoryModel.swift @@ -0,0 +1,189 @@ +import Foundation +import HapiProtocol +import Observation + +public protocol NewSessionDirectoryRequesting: MachineDirectoryRequesting { + func machinePathsExist(machineId: String, paths: [String]) async throws -> MachinePathsExistsResponse +} + +extension APIClient: NewSessionDirectoryRequesting {} + +public enum DirectoryLookupState: Equatable, Sendable { + case idle + case loading + case loaded + case outsideRoots + case failed(String) +} + +/// Directory queries for the create form. Listing and existence checks run +/// independently, so a slow/failed listing cannot hide the path's validation. +/// Every response belongs to one machine and input revision. +@MainActor @Observable +public final class NewSessionDirectoryModel { + public private(set) var suggestions: [String] = [] + public private(set) var lookupState: DirectoryLookupState = .idle + public private(set) var exists: Bool? + public private(set) var outsideWorkspaceRoots = false + public private(set) var isCheckingExistence = false + public private(set) var existenceError: String? + + private struct Input: Equatable { + let machineId: String? + let path: String + let roots: [String] + let showSuggestions: Bool + } + + private struct ListingKey: Equatable { + let machineId: String + let parent: String + let includeHidden: Bool + } + + @ObservationIgnored private let requester: any NewSessionDirectoryRequesting + @ObservationIgnored private let debounce: Duration + @ObservationIgnored private let lookupError: String + @ObservationIgnored private let checkError: String + @ObservationIgnored private var input: Input? + @ObservationIgnored private var requestVersion = 0 + @ObservationIgnored private var listingTask: Task? + @ObservationIgnored private var existenceTask: Task? + @ObservationIgnored private var cachedListing: (key: ListingKey, entries: [MachineDirectoryEntry])? + + public init( + requester: any NewSessionDirectoryRequesting, + debounce: Duration = .milliseconds(250), + lookupError: String = "Failed to browse directories", + checkError: String = "Failed to check directory" + ) { + self.requester = requester + self.debounce = debounce + self.lookupError = lookupError + self.checkError = checkError + } + + public func update(machine: Machine?, path: String, showSuggestions: Bool) { + schedule(Input( + machineId: machine?.id, + path: RemoteDirectoryPath.expandHome(path, homeDirectory: machine?.metadata?.homeDir), + roots: machine.map(RemoteDirectoryPath.browseRoots) ?? [], + showSuggestions: showSuggestions + )) + } + + public func retry() { + guard let input else { return } + cachedListing = nil + schedule(input, force: true) + } + + public func stop() { + listingTask?.cancel() + existenceTask?.cancel() + requestVersion += 1 + input = nil + suggestions = [] + lookupState = .idle + isCheckingExistence = false + exists = nil + outsideWorkspaceRoots = false + existenceError = nil + } + + /// The Create action's authoritative recheck supersedes the background probe. + public func acceptExistence( + _ result: MachinePathsExistsResponse, + machineId: String, + path: String + ) { + guard input?.machineId == machineId, input?.path == path else { return } + existenceTask?.cancel() + applyExistence(result, path: path) + } + + private func applyExistence(_ result: MachinePathsExistsResponse, path: String) { + exists = result.exists[path] + outsideWorkspaceRoots = result.outsideWorkspaceRoots?.contains(path) == true + isCheckingExistence = false + existenceError = nil + } + + private func schedule(_ next: Input, force: Bool = false) { + guard force || input != next else { return } + if input?.machineId != next.machineId || input?.roots != next.roots { + cachedListing = nil + } + stop() + input = next + let version = requestVersion + guard let machineId = next.machineId else { return } + + if !next.path.isEmpty { + isCheckingExistence = true + existenceTask = Task { [weak self, requester, debounce] in + do { + try await Task.sleep(for: debounce) + try Task.checkCancellation() + let result = try await requester.machinePathsExist(machineId: machineId, paths: [next.path]) + guard let self, self.isCurrent(version) else { return } + self.applyExistence(result, path: next.path) + } catch { + guard let self, self.isCurrent(version) else { return } + self.isCheckingExistence = false + self.existenceError = (error as? LocalizedError)?.errorDescription ?? self.checkError + } + } + } + + guard next.showSuggestions else { return } + switch NewSessionLogic.directoryAutocompleteQuery(path: next.path, roots: next.roots) { + case .none: + return + case .roots(let paths): + suggestions = paths + lookupState = .loaded + case .outsideRoots: + lookupState = .outsideRoots + case .directory(let query): + let key = ListingKey(machineId: machineId, parent: query.parent, includeHidden: query.includeHidden) + if let cachedListing, cachedListing.key == key { + applyListing(cachedListing.entries, query: query, path: next.path) + return + } + lookupState = .loading + listingTask = Task { [weak self, requester, debounce] in + do { + try await Task.sleep(for: debounce) + try Task.checkCancellation() + let response = try await requester.listMachineDirectory( + machineId: machineId, + path: query.parent, + includeHidden: query.includeHidden + ) + guard let self, self.isCurrent(version) else { return } + guard response.success else { + self.lookupState = .failed(response.error ?? self.lookupError) + return + } + let entries = response.entries ?? [] + self.cachedListing = (key, entries) + self.applyListing(entries, query: query, path: next.path) + } catch { + guard let self, self.isCurrent(version) else { return } + self.lookupState = .failed((error as? LocalizedError)?.errorDescription ?? self.lookupError) + } + } + } + } + + private func applyListing(_ entries: [MachineDirectoryEntry], query: NewSessionLogic.ParentQuery, path: String) { + suggestions = NewSessionLogic.buildSuggestions(query: query, entries: entries) + .filter { $0 != path } + lookupState = .loaded + } + + private func isCurrent(_ version: Int) -> Bool { + !Task.isCancelled && requestVersion == version + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift b/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift index 7529aaf5..cdffc144 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift @@ -207,6 +207,8 @@ public enum NewSessionLogic { /// Separator used by the typed path; suggestions preserve it. public let separator: String + public var includeHidden: Bool { prefix.hasPrefix(".") } + public init(parent: String, prefix: String, separator: String = "/") { self.parent = parent self.prefix = prefix @@ -214,6 +216,34 @@ public enum NewSessionLogic { } } + public enum DirectoryAutocompleteQuery: Equatable, Sendable { + case none + case roots([String]) + case directory(ParentQuery) + case outsideRoots + } + + /// Complete known roots without listing their forbidden ancestors. Once + /// inside a root, use the normal parent listing. `path` is home-expanded. + public static func directoryAutocompleteQuery( + path: String, + roots: [String] + ) -> DirectoryAutocompleteQuery { + if path.isEmpty { return roots.isEmpty ? .none : .roots(Array(roots.prefix(8))) } + guard let query = parentQuery(for: path) else { return .none } + if roots.contains(where: { + RemoteDirectoryPath.isWithinRoot(path: path, root: $0) + && RemoteDirectoryPath.isWithinRoot(path: $0, root: path) + }) { + return .directory(ParentQuery(parent: path, prefix: "", separator: query.separator)) + } + if RemoteDirectoryPath.allowsBrowsing(path: query.parent, roots: roots) { + return .directory(query) + } + let matchingRoots = roots.filter { $0.lowercased().hasPrefix(path.lowercased()) } + return matchingRoots.isEmpty ? .outsideRoots : .roots(Array(matchingRoots.prefix(8))) + } + /// 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). diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/DirectoryBrowser/RemoteDirectoryBrowserModelTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/DirectoryBrowser/RemoteDirectoryBrowserModelTests.swift index 8924686c..69c9287f 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/DirectoryBrowser/RemoteDirectoryBrowserModelTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/DirectoryBrowser/RemoteDirectoryBrowserModelTests.swift @@ -49,6 +49,62 @@ private func directoryBrowserEventually( @Suite("RemoteDirectoryBrowserModel") @MainActor struct RemoteDirectoryBrowserModelTests { + @Test func defaultDirectoryIsIndependentOfBrowseBoundaries() { + var machine = Machine( + id: "m", namespace: "test", seq: 1, createdAt: 0, updatedAt: 0, + active: true, activeAt: 0, + metadata: MachineMetadata(host: "m", platform: "linux", happyCliVersion: "test", homeDir: "/home/dev"), + metadataVersion: 1, runnerStateVersion: 0 + ) + #expect(RemoteDirectoryPath.browseRoots(for: machine).isEmpty) + #expect(RemoteDirectoryPath.defaultDirectory(for: machine) == "/home/dev") + machine.metadata?.workspaceRoots = ["/data", "/work"] + #expect(RemoteDirectoryPath.browseRoots(for: machine) == ["/data", "/work"]) + #expect(RemoteDirectoryPath.defaultDirectory(for: machine) == "/data") + #expect(RemoteDirectoryPath.expandHome("~/repo", homeDirectory: "/remote/home") == "/remote/home/repo") + #expect(RemoteDirectoryPath.expandHome("~", homeDirectory: "/remote/home") == "/remote/home") + #expect(RemoteDirectoryPath.expandHome("~\\repo", homeDirectory: "D:\\Users\\dev") == "D:\\Users\\dev\\repo") + #expect(RemoteDirectoryPath.filesystemRoot("D:\\Users\\dev") == "D:\\") + #expect(RemoteDirectoryPath.filesystemRoot("\\\\server\\share\\repo") == "\\\\server\\share") + #expect(!RemoteDirectoryPath.allowsBrowsing(path: "relative/path", roots: [])) + } + + @Test func unrestrictedBrowserPreservesExternalInputAndNavigatesAboveHome() async { + let requester = FakeMachineDirectoryRequester() + let model = RemoteDirectoryBrowserModel(requester: requester) + model.open(machineId: "m", roots: [], initialPath: "/data/github/hapi", defaultPath: "/home/dev") + #expect(await directoryBrowserEventually { !model.isLoading }) + #expect(model.path == "/data/github/hapi") + #expect(model.breadcrumbs.map(\.path) == ["/", "/data", "/data/github", "/data/github/hapi"]) + model.navigate(to: "/home/dev") + model.navigateUp() + #expect(await directoryBrowserEventually { !model.isLoading }) + #expect(model.path == "/home") + model.navigate(to: "/") + #expect(await directoryBrowserEventually { !model.isLoading }) + #expect(!model.canGoUp) + model.open(machineId: "m", roots: [], initialPath: "", defaultPath: "/home/dev") + #expect(model.path == "/home/dev") + model.close() + } + + @Test func configuredRootsRemainBoundariesAndSupportSwitchingRoots() async { + let requester = FakeMachineDirectoryRequester() + let model = RemoteDirectoryBrowserModel(requester: requester) + model.open(machineId: "m", roots: ["/data", "/work"], initialPath: "/home/dev", defaultPath: "/home/dev") + #expect(await directoryBrowserEventually { !model.isLoading }) + #expect(model.path == "/data") + #expect(!model.canGoUp) + model.navigate(to: "/work/repo") + #expect(await directoryBrowserEventually { !model.isLoading }) + #expect(model.breadcrumbs.map(\.path) == ["/work", "/work/repo"]) + model.navigateUp() + #expect(await directoryBrowserEventually { !model.isLoading }) + #expect(model.path == "/work") + #expect(!model.canGoUp) + model.close() + } + @Test func pathBoundariesSupportPosixDriveAndUNCPaths() { #expect(RemoteDirectoryPath.isWithinRoot(path: "/workspace/repo", root: "/workspace")) #expect(!RemoteDirectoryPath.isWithinRoot(path: "/workspace-other/repo", root: "/workspace")) diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionDirectoryModelTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionDirectoryModelTests.swift new file mode 100644 index 00000000..1a2d962b --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionDirectoryModelTests.swift @@ -0,0 +1,266 @@ +import Foundation +import HapiClient +import HapiProtocol +import Testing + +private struct ListingCall: Hashable, Sendable { + let machineId: String + let path: String + var includeHidden = false +} + +private struct ExistenceCall: Hashable, Sendable { + let machineId: String + let path: String +} + +private actor DirectoryRequester: NewSessionDirectoryRequesting { + private(set) var listings: [ListingCall] = [] + private(set) var checks: [ExistenceCall] = [] + private(set) var completedListings: [ListingCall] = [] + private(set) var completedChecks: [ExistenceCall] = [] + private var heldListings: Set = [] + private var heldChecks: Set = [] + private var listingWaiters: [ListingCall: CheckedContinuation] = [:] + private var checkWaiters: [ExistenceCall: CheckedContinuation] = [:] + private var listingFailure = false + private var checkFailure = false + private var outside: Set = [] + + func holdListing(_ call: ListingCall) { heldListings.insert(call) } + func holdCheck(_ call: ExistenceCall) { heldChecks.insert(call) } + func setFailures(listing: Bool, check: Bool = false) { + listingFailure = listing + checkFailure = check + } + func setOutside(_ call: ExistenceCall) { outside.insert(call) } + func releaseListing(_ call: ListingCall) { + heldListings.remove(call) + listingWaiters.removeValue(forKey: call)?.resume() + } + func releaseCheck(_ call: ExistenceCall) { + heldChecks.remove(call) + checkWaiters.removeValue(forKey: call)?.resume() + } + + func listMachineDirectory(machineId: String, path: String, includeHidden: Bool) async throws -> MachineListDirectoryResponse { + let call = ListingCall(machineId: machineId, path: path, includeHidden: includeHidden) + listings.append(call) + let failed = listingFailure + // Intentionally ignore cancellation to exercise late transport responses. + if heldListings.contains(call) { + await withCheckedContinuation { listingWaiters[call] = $0 } + } + completedListings.append(call) + return MachineListDirectoryResponse( + success: !failed, + entries: ["github", "gists", ".git", "other"] + .filter { includeHidden || !$0.hasPrefix(".") } + .map { MachineDirectoryEntry(name: $0, type: .directory) }, + error: failed ? "Listing failed" : nil + ) + } + + func machinePathsExist(machineId: String, paths: [String]) async throws -> MachinePathsExistsResponse { + let path = paths[0] + let call = ExistenceCall(machineId: machineId, path: path) + checks.append(call) + let denied = outside.contains(call) + let failed = checkFailure + if heldChecks.contains(call) { + await withCheckedContinuation { checkWaiters[call] = $0 } + } + completedChecks.append(call) + if failed { throw URLError(.timedOut) } + return MachinePathsExistsResponse(exists: [path: false], outsideWorkspaceRoots: denied ? [path] : nil) + } +} + +private func directoryMachine(_ id: String = "m1", roots: [String]? = nil, home: String = "/home/dev") -> Machine { + Machine( + id: id, namespace: "test", seq: 1, createdAt: 0, updatedAt: 0, + active: true, activeAt: 0, + metadata: MachineMetadata(host: id, platform: "linux", happyCliVersion: "test", homeDir: home, workspaceRoots: roots), + metadataVersion: 1, runnerStateVersion: 0 + ) +} + +@MainActor +private func directoryEventually(_ condition: @MainActor () async -> Bool) async -> Bool { + let clock = ContinuousClock() + let deadline = clock.now.advanced(by: .seconds(3)) + while clock.now < deadline { + if await condition() { return true } + try? await Task.sleep(for: .milliseconds(2)) + } + return await condition() +} + +@Suite("NewSessionDirectoryModel") +@MainActor +struct NewSessionDirectoryModelTests { + @Test func completesOutsideHomeAndRefiltersCacheWhileClearingOldSuggestionsImmediately() async { + let requester = DirectoryRequester() + let model = NewSessionDirectoryModel(requester: requester, debounce: .milliseconds(10)) + model.update(machine: directoryMachine(), path: "/data/gi", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + #expect(model.suggestions == ["/data/github", "/data/gists"]) + #expect(await requester.listings == [ListingCall(machineId: "m1", path: "/data")]) + model.update(machine: directoryMachine(), path: "/data/gith", showSuggestions: true) + #expect(model.suggestions == ["/data/github"]) + #expect(await requester.listings.count == 1) + model.update(machine: directoryMachine(), path: "/elsewhere/g", showSuggestions: true) + #expect(model.suggestions.isEmpty) + #expect(model.lookupState == .loading) + model.update(machine: directoryMachine(), path: "", showSuggestions: true) + #expect(model.lookupState == .idle) + #expect(model.exists == nil) + #expect(!model.isCheckingExistence) + model.stop() + } + + @Test func knownRootsCompleteWithoutListingTheirAncestors() async { + let requester = DirectoryRequester() + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + let machine = directoryMachine(roots: ["/data/github", "/work"]) + model.update(machine: machine, path: "/data/gi", showSuggestions: true) + #expect(model.suggestions == ["/data/github"]) + #expect(await requester.listings.isEmpty) + model.update(machine: machine, path: "/data/github", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + #expect(await requester.listings == [ListingCall(machineId: "m1", path: "/data/github")]) + model.update(machine: machine, path: "/unrelated/g", showSuggestions: true) + #expect(model.lookupState == .outsideRoots) + #expect(model.suggestions.isEmpty) + model.stop() + } + + @Test func dotPrefixUsesASeparateHiddenDirectoryCache() async { + let requester = DirectoryRequester() + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(), path: "/data/g", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + model.update(machine: directoryMachine(), path: "/data/.", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + #expect(model.suggestions == ["/data/.git"]) + #expect(await requester.listings.map(\.includeHidden) == [false, true]) + model.update(machine: directoryMachine(), path: "/data/.g", showSuggestions: true) + #expect(model.suggestions == ["/data/.git"]) + #expect(await requester.listings.count == 2) + model.stop() + } + + @Test func slowListingDoesNotBlockExistenceAndCannotReplaceNewInput() async { + let requester = DirectoryRequester() + let held = ListingCall(machineId: "m1", path: "/old") + await requester.holdListing(held) + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(), path: "/old/gi", showSuggestions: true) + #expect(await directoryEventually { await requester.listings.contains(held) && model.exists == false }) + #expect(model.lookupState == .loading) + model.update(machine: directoryMachine(), path: "/new/gith", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + await requester.releaseListing(held) + #expect(await directoryEventually { await requester.completedListings.contains(held) }) + #expect(model.suggestions == ["/new/github"]) + model.stop() + } + + @Test func machineSwitchRejectsOldExistenceAndListingResponses() async { + let requester = DirectoryRequester() + let oldListing = ListingCall(machineId: "m1", path: "/data") + let oldCheck = ExistenceCall(machineId: "m1", path: "/data/gi") + await requester.holdListing(oldListing) + await requester.holdCheck(oldCheck) + await requester.setOutside(ExistenceCall(machineId: "m2", path: "/data/gi")) + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(), path: "/data/gi", showSuggestions: true) + #expect(await directoryEventually { + let checks = await requester.checks + let listings = await requester.listings + return checks.contains(oldCheck) && listings.contains(oldListing) + }) + model.update(machine: directoryMachine("m2", roots: ["/work"]), path: "/data/gi", showSuggestions: true) + #expect(await directoryEventually { model.outsideWorkspaceRoots }) + await requester.releaseListing(oldListing) + await requester.releaseCheck(oldCheck) + #expect(await directoryEventually { + let checks = await requester.completedChecks + let listings = await requester.completedListings + return checks.contains(oldCheck) && listings.contains(oldListing) + }) + #expect(model.outsideWorkspaceRoots) + #expect(model.lookupState == .outsideRoots) + #expect(model.suggestions.isEmpty) + model.stop() + } + + @Test func listingFailureAndMissingPathAreIndependentAndRetryRefreshesBoth() async { + let requester = DirectoryRequester() + await requester.setFailures(listing: true) + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(), path: "/data/gi", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .failed("Listing failed") && model.exists == false }) + await requester.setFailures(listing: false, check: true) + model.retry() + #expect(await directoryEventually { model.lookupState == .loaded && model.existenceError != nil }) + #expect(model.exists == nil) + #expect(model.suggestions == ["/data/github", "/data/gists"]) + await requester.setFailures(listing: false) + model.retry() + #expect(await directoryEventually { model.exists == false && model.lookupState == .loaded }) + #expect(model.existenceError == nil) + #expect(await requester.listings.count == 3) + model.stop() + } + + @Test func homeExpansionUsesTheRemoteMachineAndPickingSuppressesSuggestions() async { + let requester = DirectoryRequester() + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(home: "/remote/home"), path: "~/gi", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + #expect(model.suggestions == ["/remote/home/github", "/remote/home/gists"]) + #expect(await directoryEventually { await requester.checks.contains(ExistenceCall(machineId: "m1", path: "/remote/home/gi")) }) + model.update(machine: directoryMachine(home: "/remote/home"), path: "~/github", showSuggestions: false) + #expect(model.suggestions.isEmpty) + #expect(model.lookupState == .idle) + model.stop() + } + + @Test func createRecheckAndClosingSupersedeBackgroundProbes() async { + let requester = DirectoryRequester() + let check = ExistenceCall(machineId: "m1", path: "/data/gi") + await requester.holdCheck(check) + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(), path: check.path, showSuggestions: false) + #expect(await directoryEventually { await requester.checks.contains(check) }) + model.acceptExistence(MachinePathsExistsResponse(exists: [check.path: true]), machineId: "m1", path: check.path) + await requester.releaseCheck(check) + #expect(await directoryEventually { await requester.completedChecks.contains(check) }) + #expect(model.exists == true) + model.stop() + #expect(model.exists == nil) + #expect(model.lookupState == .idle) + } + + @Test func closingRejectsLateListingsAndSameMachineRootChangesInvalidateCache() async { + let requester = DirectoryRequester() + let model = NewSessionDirectoryModel(requester: requester, debounce: .zero) + model.update(machine: directoryMachine(), path: "/data/gi", showSuggestions: true) + #expect(await directoryEventually { model.lookupState == .loaded }) + model.update(machine: directoryMachine(roots: ["/work"]), path: "/data/gi", showSuggestions: true) + #expect(model.lookupState == .outsideRoots) + #expect(model.suggestions.isEmpty) + + let held = ListingCall(machineId: "m1", path: "/work") + await requester.holdListing(held) + model.update(machine: directoryMachine(roots: ["/work"]), path: "/work/gi", showSuggestions: true) + #expect(await directoryEventually { await requester.listings.contains(held) }) + model.stop() + await requester.releaseListing(held) + #expect(await directoryEventually { await requester.completedListings.contains(held) }) + #expect(model.lookupState == .idle) + #expect(model.suggestions.isEmpty) + #expect(!model.isCheckingExistence) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift index a57508eb..1867549a 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift @@ -160,6 +160,12 @@ struct NewSessionLogicTests { } @Test func windowsDriveAndUNCAutocompletePreserveSeparators() { + #expect(NewSessionLogic.directoryAutocompleteQuery(path: "C:\\wo", roots: ["C:\\work"]) + == .roots(["C:\\work"])) + #expect(NewSessionLogic.directoryAutocompleteQuery(path: "\\\\server\\sh", roots: ["\\\\server\\share"]) + == .roots(["\\\\server\\share"])) + #expect(NewSessionLogic.directoryAutocompleteQuery(path: "C:\\work", roots: ["C:\\work"]) + == .directory(NewSessionLogic.ParentQuery(parent: "C:\\work", prefix: "", separator: "\\"))) #expect( NewSessionLogic.parentQuery(for: "C:\\Users\\pro") == NewSessionLogic.ParentQuery(parent: "C:\\Users", prefix: "pro", separator: "\\") diff --git a/ios/README.md b/ios/README.md index 35afe3aa..1a1f9d38 100644 --- a/ios/README.md +++ b/ios/README.md @@ -95,6 +95,15 @@ presentation. When changing fixture inputs or generation, run hand-edit fixtures. See [fixture guidance](../shared/fixtures/README.md) and [UI development](#ui-development) for targeted app-hosted checks. +New-session directory regression checks: `ios/scripts/linux-test.sh --filter +'NewSession|RemoteDirectoryBrowser'` covers path queries and browser navigation; +`HapiTests/NewSessionDirectoryTests` covers the form's defaults, roster refresh, +offline machines and spawn validation. On a device, verify home → parent → a +project outside home, explicit workspace-root prefixes, `~/` and hidden-directory +completion, and clearing the input while machine health updates arrive. A +restored or selected offline machine stays selected until the user chooses an +online machine; its old path is never silently moved to another host. + ## Pairing The app supports multiple hubs with one active selection. See the