From 577504f8c7055efb6d6a2ab19588285a331b2a36 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Fri, 5 Jun 2026 16:41:37 -0400 Subject: [PATCH] Improve remote server project add flow (#4715) Co-authored-by: Orca --- src/main/runtime/orca-runtime.test.ts | 21 ++ src/main/runtime/orca-runtime.ts | 159 +++++++++--- ...ime-request-connection.integration.test.ts | 171 +++++++++++++ src/main/runtime/rpc/methods/client-events.ts | 31 +++ src/main/runtime/rpc/methods/files.test.ts | 19 ++ src/main/runtime/rpc/methods/files.ts | 12 + src/main/runtime/rpc/methods/index.ts | 2 + src/main/runtime/runtime-rpc.ts | 2 + .../components/sidebar/AddRepoCreateStep.tsx | 78 +++--- .../src/components/sidebar/AddRepoDialog.tsx | 1 + .../sidebar/AddRepoDialogStepContent.test.tsx | 147 ++++++----- .../sidebar/AddRepoDialogStepContent.tsx | 8 +- .../sidebar/AddRepoServerStartStep.tsx | 233 ++++++++++++++++++ .../sidebar/AddRepoStartSteps.test.tsx | 39 +++ .../components/sidebar/AddRepoStartSteps.tsx | 94 ------- .../src/components/sidebar/AddRepoSteps.tsx | 40 ++- .../sidebar/CreateProjectLocationField.tsx | 129 ++++++++++ .../components/sidebar/RemoteFileBrowser.tsx | 24 +- src/renderer/src/hooks/useIpcEvents.test.ts | 215 ++++++++++++++++ src/renderer/src/hooks/useIpcEvents.ts | 197 ++++++++++----- .../src/runtime/runtime-client-events.test.ts | 58 +++++ .../src/runtime/runtime-client-events.ts | 58 +++++ .../runtime-server-directory-browser.test.ts | 59 +++++ .../runtime-server-directory-browser.ts | 19 ++ src/shared/runtime-client-events.ts | 48 ++++ 25 files changed, 1559 insertions(+), 305 deletions(-) create mode 100644 src/main/runtime/rpc/methods/client-events.ts create mode 100644 src/renderer/src/components/sidebar/AddRepoServerStartStep.tsx create mode 100644 src/renderer/src/components/sidebar/CreateProjectLocationField.tsx create mode 100644 src/renderer/src/runtime/runtime-client-events.test.ts create mode 100644 src/renderer/src/runtime/runtime-client-events.ts create mode 100644 src/renderer/src/runtime/runtime-server-directory-browser.test.ts create mode 100644 src/renderer/src/runtime/runtime-server-directory-browser.ts create mode 100644 src/shared/runtime-client-events.ts diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index d14dd4137..f035ab758 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -3043,6 +3043,27 @@ describe('OrcaRuntimeService', () => { expect(added).toHaveLength(0) }) + it('browses runtime server directories before projects are added', async () => { + const tempRoot = await mkdtemp(join(tmpdir(), 'orca-runtime-browse-')) + try { + await mkdir(join(tempRoot, 'zeta')) + await mkdir(join(tempRoot, 'alpha')) + await writeFile(join(tempRoot, 'readme.md'), '# Readme\n') + const runtime = new OrcaRuntimeService(store) + + const result = await runtime.browseServerDir(tempRoot) + + expect(result.resolvedPath).toBe(tempRoot) + expect(result.entries).toEqual([ + { name: 'alpha', isDirectory: true, isSymlink: false }, + { name: 'zeta', isDirectory: true, isSymlink: false }, + { name: 'readme.md', isDirectory: false, isSymlink: false } + ]) + } finally { + await rm(tempRoot, { recursive: true, force: true }) + } + }) + it('defaults runtime addRepo badgeColor to DEFAULT_REPO_BADGE_COLOR', async () => { const added: Record[] = [] const colorStore = { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index b488e6f58..29a6ab038 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -19,7 +19,8 @@ import { getClonePathComparisonKey } from '../git/repo-clone-path' import { createHash, randomUUID } from 'crypto' -import { isAbsolute, join } from 'path' +import { homedir } from 'os' +import { isAbsolute, join, resolve } from 'path' import { mkdir, readFile, readdir, rm, stat } from 'fs/promises' import { OrchestrationDb } from './orchestration/db' import { formatMessagesForInjection } from './orchestration/formatter' @@ -70,8 +71,11 @@ import type { TerminalLayoutSnapshot, TerminalTab, TuiAgent, - WorkspaceCreateTelemetrySource + WorkspaceCreateTelemetrySource, + DirEntry } from '../../shared/types' +import type { RuntimeClientEvent } from '../../shared/runtime-client-events' +import { toRuntimeActivateWorktreeEvent } from '../../shared/runtime-client-events' import type { FeatureInteractionId } from '../../shared/feature-interactions' import type { TerminalPaneSplitSource } from '../../shared/feature-education-telemetry' import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR, splitWorktreeId } from '../../shared/worktree-id' @@ -1095,6 +1099,25 @@ async function pathExists(pathValue: string): Promise { } } +function resolveServerBrowsePath(pathValue: string): string { + const trimmed = pathValue.trim() || '~' + if (trimmed.includes('\0')) { + throw new Error('Path cannot contain null bytes') + } + if (trimmed === '~') { + return homedir() + } + if (/^~[\\/]/.test(trimmed)) { + return resolve(homedir(), trimmed.slice(2)) + } + if (isAbsolute(trimmed)) { + return resolve(trimmed) + } + // Why: remote clients do not share the server process cwd; relative browse + // inputs are anchored to the server user's home to match the `~` picker root. + return resolve(homedir(), trimmed) +} + type ResolvedWorktree = Worktree & { parentWorktreeId: string | null childWorktreeIds: string[] @@ -1253,6 +1276,7 @@ export class OrcaRuntimeService { private waitersByHandle = new Map>() private ptyController: RuntimePtyController | null = null private notifier: RuntimeNotifier | null = null + private clientEventListeners = new Set<(event: RuntimeClientEvent) => void>() private forkBackfillStarted = false private agentBrowserBridge: AgentBrowserBridge | null = null private resolvedWorktreeCache: ResolvedWorktreeCache | null = null @@ -1883,6 +1907,42 @@ export class OrcaRuntimeService { } } + onClientEvent(listener: (event: RuntimeClientEvent) => void): () => void { + this.clientEventListeners.add(listener) + return () => { + this.clientEventListeners.delete(listener) + } + } + + private emitClientEvent(event: RuntimeClientEvent): void { + for (const listener of this.clientEventListeners) { + listener(event) + } + } + + private notifyWorktreesChanged(repoId: string): void { + this.notifier?.worktreesChanged(repoId) + this.emitClientEvent({ type: 'worktreesChanged', repoId }) + } + + private notifyReposChanged(): void { + this.notifier?.reposChanged() + this.emitClientEvent({ type: 'reposChanged' }) + } + + private notifyActivateWorktree( + repoId: string, + worktreeId: string, + setup?: CreateWorktreeResult['setup'], + startup?: WorktreeStartupLaunch, + defaultTabs?: CreateWorktreeResult['defaultTabs'] + ): void { + this.notifier?.activateWorktree(repoId, worktreeId, setup, startup, defaultTabs) + this.emitClientEvent( + toRuntimeActivateWorktreeEvent(repoId, worktreeId, setup, startup, defaultTabs) + ) + } + setAgentBrowserBridge(bridge: AgentBrowserBridge | null): void { this.agentBrowserBridge = bridge } @@ -5835,7 +5895,7 @@ export class OrcaRuntimeService { parentGroupId: input.parentGroupId ?? null, createdFrom: input.createdFrom ?? 'manual' }) - this.notifier?.reposChanged() + this.notifyReposChanged() return group } @@ -5848,7 +5908,7 @@ export class OrcaRuntimeService { } const updated = this.store.updateProjectGroup(groupId, updates) if (updated) { - this.notifier?.reposChanged() + this.notifyReposChanged() } return updated } @@ -5859,7 +5919,7 @@ export class OrcaRuntimeService { } const deleted = this.store.deleteProjectGroup(groupId) if (deleted) { - this.notifier?.reposChanged() + this.notifyReposChanged() } return { deleted } } @@ -5877,7 +5937,7 @@ export class OrcaRuntimeService { if (!moved) { throw new Error('repo_not_found') } - this.notifier?.reposChanged() + this.notifyReposChanged() return moved } @@ -5888,6 +5948,29 @@ export class OrcaRuntimeService { return scanNestedRepos({ path, options: { timeoutMs: 15_000 } }) } + async browseServerDir(pathValue: string): Promise<{ resolvedPath: string; entries: DirEntry[] }> { + const dirPath = resolveServerBrowsePath(pathValue) + const dirStat = await stat(dirPath) + if (!dirStat.isDirectory()) { + throw new Error(`${dirPath} is not a directory`) + } + const entries = await readdir(dirPath, { withFileTypes: true }) + const mapped = entries + .filter((entry) => entry.name !== '.' && entry.name !== '..') + .map((entry) => ({ + name: entry.name, + isDirectory: entry.isDirectory(), + isSymlink: entry.isSymbolicLink() + })) + mapped.sort((a, b) => { + if (a.isDirectory !== b.isDirectory) { + return a.isDirectory ? -1 : 1 + } + return a.name.localeCompare(b.name) + }) + return { resolvedPath: dirPath, entries: mapped } + } + async importNestedRepos(args: { parentPath: string groupName: string @@ -5970,7 +6053,7 @@ export class OrcaRuntimeService { } } this.invalidateResolvedWorktreeCache() - this.notifier?.reposChanged() + this.notifyReposChanged() const rootGroup = groupResolver.getRootGroup() return { ...(rootGroup && importedCount + alreadyKnownCount > 0 ? { group: rootGroup } : {}), @@ -6049,7 +6132,7 @@ export class OrcaRuntimeService { } this.store.addRepo(repo) this.invalidateResolvedWorktreeCache() - this.notifier?.reposChanged() + this.notifyReposChanged() return this.store.getRepo(repo.id) ?? repo } @@ -6166,7 +6249,7 @@ export class OrcaRuntimeService { this.store.addRepo(repo) invalidateAuthorizedRootsCache() this.invalidateResolvedWorktreeCache() - this.notifier?.reposChanged() + this.notifyReposChanged() return { repo: this.store.getRepo(repo.id) ?? repo } } @@ -6285,7 +6368,7 @@ export class OrcaRuntimeService { if (isFolderRepo(existing)) { const updated = this.store.updateRepo(existing.id, { kind: 'git' }) if (updated) { - this.notifier?.reposChanged() + this.notifyReposChanged() return updated } } @@ -6307,7 +6390,7 @@ export class OrcaRuntimeService { this.store.addRepo(repo) invalidateAuthorizedRootsCache() this.invalidateResolvedWorktreeCache() - this.notifier?.reposChanged() + this.notifyReposChanged() return this.store.getRepo(repo.id) ?? repo } @@ -6328,7 +6411,7 @@ export class OrcaRuntimeService { throw new Error('repo_not_found') } this.invalidateResolvedWorktreeCache() - this.notifier?.reposChanged() + this.notifyReposChanged() return updated } @@ -6371,7 +6454,7 @@ export class OrcaRuntimeService { invalidateAuthorizedRootsCache() } this.invalidateResolvedWorktreeCache() - this.notifier?.reposChanged() + this.notifyReposChanged() return updated } @@ -6383,7 +6466,7 @@ export class OrcaRuntimeService { this.store.removeProject(repo.id) this.invalidateResolvedWorktreeCache() invalidateAuthorizedRootsCache() - this.notifier?.reposChanged() + this.notifyReposChanged() return { removed: true } } @@ -6412,7 +6495,7 @@ export class OrcaRuntimeService { return { status: 'rejected' } } this.invalidateResolvedWorktreeCache() - this.notifier?.reposChanged() + this.notifyReposChanged() return { status: 'applied' } } @@ -6586,7 +6669,7 @@ export class OrcaRuntimeService { changed = true } if (changed) { - this.notifier?.reposChanged() + this.notifyReposChanged() } } catch { // Best-effort startup backfill; never disrupt launch. @@ -7889,7 +7972,7 @@ export class OrcaRuntimeService { // Why: inactive worktree terminal panes are renderer-owned and may not have // live PTYs until the desktop activates the worktree and mounts them. - this.notifier?.activateWorktree(repo.id, worktree.id) + this.notifyActivateWorktree(repo.id, worktree.id) return { repoId: repo.id, worktreeId: worktree.id, activated: true } } @@ -8358,7 +8441,7 @@ export class OrcaRuntimeService { }) const worktree = mergeRuntimeFolderWorkspace(repo, worktreeId, meta) this.invalidateResolvedWorktreeCache() - this.notifier?.worktreesChanged(repo.id) + this.notifyWorktreesChanged(repo.id) const shouldActivate = args.activate === true || args.runHooks === true let warning: string | undefined let didSpawnStartup = false @@ -8388,9 +8471,9 @@ export class OrcaRuntimeService { } if (shouldActivate) { if (effectiveStartup && !didSpawnStartup) { - this.notifier?.activateWorktree(repo.id, worktree.id, undefined, effectiveStartup) + this.notifyActivateWorktree(repo.id, worktree.id, undefined, effectiveStartup) } else { - this.notifier?.activateWorktree(repo.id, worktree.id) + this.notifyActivateWorktree(repo.id, worktree.id) } } else if (this.ptyController?.spawn && !didSpawnStartup) { try { @@ -8765,7 +8848,7 @@ export class OrcaRuntimeService { // unknown repository or worktree path". invalidateAuthorizedRootsCache() - this.notifier?.worktreesChanged(repo.id) + this.notifyWorktreesChanged(repo.id) const shouldActivate = args.activate === true || args.runHooks === true let didSpawnStartup = false let didSpawnSetup = false @@ -8844,7 +8927,7 @@ export class OrcaRuntimeService { // the user can watch prompts/output in a visible pane. const activationSetup = didSpawnSetup ? undefined : setup if (effectiveStartup && !didSpawnStartup) { - this.notifier?.activateWorktree( + this.notifyActivateWorktree( repo.id, worktree.id, activationSetup, @@ -8852,13 +8935,7 @@ export class OrcaRuntimeService { defaultTabs ) } else { - this.notifier?.activateWorktree( - repo.id, - worktree.id, - activationSetup, - undefined, - defaultTabs - ) + this.notifyActivateWorktree(repo.id, worktree.id, activationSetup, undefined, defaultTabs) } } else if (this.ptyController?.spawn) { try { @@ -8991,7 +9068,7 @@ export class OrcaRuntimeService { } this.invalidateResolvedWorktreeCache() - this.notifier?.worktreesChanged(repo.id) + this.notifyWorktreesChanged(repo.id) let warning = result.warning let didSpawnStartup = false @@ -9070,7 +9147,7 @@ export class OrcaRuntimeService { if (shouldActivate) { const activationSetup = didSpawnSetup ? undefined : result.setup if (args.startup && !didSpawnStartup) { - this.notifier?.activateWorktree( + this.notifyActivateWorktree( repo.id, result.worktree.id, activationSetup, @@ -9078,7 +9155,7 @@ export class OrcaRuntimeService { result.defaultTabs ) } else { - this.notifier?.activateWorktree( + this.notifyActivateWorktree( repo.id, result.worktree.id, activationSetup, @@ -9587,7 +9664,7 @@ export class OrcaRuntimeService { // Why: unlike renderer-initiated optimistic updates, CLI callers need an // explicit push so the editor refreshes metadata changed outside the UI. this.invalidateResolvedWorktreeCache() - this.notifier?.worktreesChanged(worktree.repoId) + this.notifyWorktreesChanged(worktree.repoId) return await this.showManagedWorktree(`id:${worktree.id}`) } @@ -9602,7 +9679,7 @@ export class OrcaRuntimeService { updated++ } this.invalidateResolvedWorktreeCache() - this.notifier?.reposChanged() + this.notifyReposChanged() return { updated } } @@ -10037,7 +10114,7 @@ export class OrcaRuntimeService { this.removeWorktreeMetadataAndHistory(store, removalTarget.id) this.preservedBranchCleanupByWorktreeId.delete(removalTarget.id) this.invalidateResolvedWorktreeCache() - this.notifier?.worktreesChanged(repo.id) + this.notifyWorktreesChanged(repo.id) return {} } const provider = repo.connectionId ? requireSshGitProvider(repo.connectionId) : null @@ -10111,7 +10188,7 @@ export class OrcaRuntimeService { this.preservedBranchCleanupByWorktreeId.delete(removalTarget.id) this.invalidateResolvedWorktreeCache() invalidateAuthorizedRootsCache() - this.notifier?.worktreesChanged(repo.id) + this.notifyWorktreesChanged(repo.id) return {} } if (await isRuntimeWorktreePathMissing(repo, removalTarget.path)) { @@ -10137,7 +10214,7 @@ export class OrcaRuntimeService { this.preservedBranchCleanupByWorktreeId.delete(removalTarget.id) this.invalidateResolvedWorktreeCache() invalidateAuthorizedRootsCache() - this.notifier?.worktreesChanged(repo.id) + this.notifyWorktreesChanged(repo.id) return {} } throw new Error(`Refusing to delete unregistered worktree path: ${removalTarget.path}`) @@ -10169,7 +10246,7 @@ export class OrcaRuntimeService { this.removeWorktreeMetadataAndHistory(store, removalTarget.id) this.invalidateResolvedWorktreeCache() invalidateAuthorizedRootsCache() - this.notifier?.worktreesChanged(repo.id) + this.notifyWorktreesChanged(repo.id) return removalResult ?? {} } @@ -10259,7 +10336,7 @@ export class OrcaRuntimeService { this.preservedBranchCleanupByWorktreeId.delete(removalTarget.id) this.invalidateResolvedWorktreeCache() invalidateAuthorizedRootsCache() - this.notifier?.worktreesChanged(repo.id) + this.notifyWorktreesChanged(repo.id) return { ...(warning ? { warning } : {}) } @@ -10283,7 +10360,7 @@ export class OrcaRuntimeService { this.removeWorktreeMetadataAndHistory(store, removalTarget.id) this.invalidateResolvedWorktreeCache() invalidateAuthorizedRootsCache() - this.notifier?.worktreesChanged(repo.id) + this.notifyWorktreesChanged(repo.id) return { ...removalResult, ...(warning ? { warning } : {}) @@ -11802,7 +11879,7 @@ export class OrcaRuntimeService { * name surfaces without waiting for the next ambient refresh. */ notifyBranchRenamed(repoId: string): void { this.invalidateResolvedWorktreeCache() - this.notifier?.worktreesChanged(repoId) + this.notifyWorktreesChanged(repoId) } private recordPtyWorktree( diff --git a/src/main/runtime/remote-runtime-request-connection.integration.test.ts b/src/main/runtime/remote-runtime-request-connection.integration.test.ts index 540ad425b..4f04e5b54 100644 --- a/src/main/runtime/remote-runtime-request-connection.integration.test.ts +++ b/src/main/runtime/remote-runtime-request-connection.integration.test.ts @@ -6,6 +6,11 @@ import { getDefaultRepoHookSettings } from '../../shared/constants' import type { Repo } from '../../shared/types' import { parsePairingCode } from '../../shared/pairing' import { RemoteRuntimeRequestConnection } from '../../shared/remote-runtime-request-connection' +import { subscribeRemoteRuntimeRequest } from '../../shared/remote-runtime-client' +import type { + RuntimeClientEvent, + RuntimeClientEventStreamMessage +} from '../../shared/runtime-client-events' import type { OrcaRuntimeService } from './orca-runtime' import { OrcaRuntimeRpcServer } from './runtime-rpc' @@ -64,4 +69,170 @@ describe('remote runtime request connection integration', () => { rmSync(userDataPath, { recursive: true, force: true }) } }) + + it('streams server worktree changes to another remote client', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-request-events-')) + const repoPath = join(userDataPath, 'repo') + const repo: Repo = { + id: 'repo-1', + path: repoPath, + displayName: 'repo', + badgeColor: 'blue', + addedAt: 1, + hookSettings: getDefaultRepoHookSettings(), + worktreeBaseRef: 'main', + kind: 'git' + } + const worktrees: unknown[] = [ + { + id: 'repo-1::main', + repoId: repo.id, + path: repoPath, + branch: 'main', + displayName: 'repo', + isMainWorktree: true + } + ] + const clientEventListeners = new Set<(event: RuntimeClientEvent) => void>() + const subscriptionCleanups = new Map void>() + const runtime = { + getRuntimeId: () => 'runtime-test', + getStartedAt: () => 1, + cleanupSubscriptionsForConnection: (connectionId: string) => { + for (const [id, cleanup] of subscriptionCleanups) { + if (id.includes(connectionId)) { + cleanup() + subscriptionCleanups.delete(id) + } + } + }, + registerSubscriptionCleanup: (id: string, cleanup: () => void) => { + subscriptionCleanups.set(id, cleanup) + }, + cleanupSubscription: (id: string) => { + subscriptionCleanups.get(id)?.() + subscriptionCleanups.delete(id) + }, + cancelMobileDictationForConnection: () => {}, + onClientDisconnected: () => {}, + onClientEvent: (listener: (event: RuntimeClientEvent) => void) => { + clientEventListeners.add(listener) + return () => clientEventListeners.delete(listener) + }, + listDetectedManagedWorktrees: () => ({ + repoId: repo.id, + authoritative: true, + source: 'git', + worktrees + }), + createManagedWorktree: ({ name }: { name?: string }) => { + const worktree = { + id: `repo-1::${name || 'created'}`, + repoId: repo.id, + path: join(userDataPath, name || 'created'), + branch: name || 'created', + displayName: name || 'created', + isMainWorktree: false + } + worktrees.push(worktree) + for (const listener of clientEventListeners) { + listener({ type: 'worktreesChanged', repoId: repo.id }) + } + return { worktree } + } + } as unknown as OrcaRuntimeService + const server = new OrcaRuntimeRpcServer({ + runtime, + userDataPath, + enableWebSocket: true, + wsPort: 0 + }) + + await server.start() + try { + const offer = server.createPairingOffer({ name: 'integration', scope: 'runtime' }) + if (!offer.available) { + throw new Error('pairing unavailable') + } + const pairing = parsePairingCode(offer.pairingUrl) + if (!pairing) { + throw new Error('invalid pairing') + } + + const events: RuntimeClientEventStreamMessage[] = [] + const subscription = await subscribeRemoteRuntimeRequest( + pairing, + 'runtime.clientEvents.subscribe', + undefined, + 1000, + { + onResponse: (response) => { + if (response.ok) { + events.push(response.result) + } + }, + onError: (error) => { + throw error + } + } + ) + const desktop = new RemoteRuntimeRequestConnection(pairing) + const mobile = new RemoteRuntimeRequestConnection(pairing) + try { + await waitFor(() => events.some((event) => event.type === 'ready')) + + await expect( + desktop.request<{ worktrees: unknown[] }>( + 'worktree.detectedList', + { repo: repo.id }, + 1000 + ) + ).resolves.toMatchObject({ + ok: true, + result: { worktrees: [{ id: 'repo-1::main' }] } + }) + + await expect( + mobile.request('worktree.create', { repo: repo.id, name: 'mobile-created' }, 1000) + ).resolves.toMatchObject({ + ok: true, + result: { worktree: { id: 'repo-1::mobile-created' } } + }) + + await waitFor(() => + events.some((event) => event.type === 'worktreesChanged' && event.repoId === repo.id) + ) + await expect( + desktop.request<{ worktrees: unknown[] }>( + 'worktree.detectedList', + { repo: repo.id }, + 1000 + ) + ).resolves.toMatchObject({ + ok: true, + result: { + worktrees: [{ id: 'repo-1::main' }, { id: 'repo-1::mobile-created' }] + } + }) + } finally { + subscription.close() + desktop.close() + mobile.close() + } + } finally { + await server.stop() + rmSync(userDataPath, { recursive: true, force: true }) + } + }) }) + +async function waitFor(predicate: () => boolean, timeoutMs = 1000): Promise { + const start = Date.now() + while (Date.now() - start < timeoutMs) { + if (predicate()) { + return + } + await new Promise((resolve) => setTimeout(resolve, 10)) + } + throw new Error('Timed out waiting for condition') +} diff --git a/src/main/runtime/rpc/methods/client-events.ts b/src/main/runtime/rpc/methods/client-events.ts new file mode 100644 index 000000000..4197fc133 --- /dev/null +++ b/src/main/runtime/rpc/methods/client-events.ts @@ -0,0 +1,31 @@ +import { defineStreamingMethod, type RpcAnyMethod } from '../core' + +let clientEventSubscriptionSeq = 0 + +export const CLIENT_EVENT_METHODS: readonly RpcAnyMethod[] = [ + defineStreamingMethod({ + name: 'runtime.clientEvents.subscribe', + params: null, + handler: async (_params, { runtime, connectionId }, emit) => { + await new Promise((resolve) => { + const unsubscribe = runtime.onClientEvent((event) => { + emit(event) + }) + + const seq = ++clientEventSubscriptionSeq + const subscriptionId = `runtime-client-events-${connectionId ?? 'inproc'}-${seq}` + runtime.registerSubscriptionCleanup( + subscriptionId, + () => { + unsubscribe() + emit({ type: 'end' }) + resolve() + }, + connectionId + ) + + emit({ type: 'ready', subscriptionId }) + }) + } + }) +] diff --git a/src/main/runtime/rpc/methods/files.test.ts b/src/main/runtime/rpc/methods/files.test.ts index 9d91ca093..7843ba4bb 100644 --- a/src/main/runtime/rpc/methods/files.test.ts +++ b/src/main/runtime/rpc/methods/files.test.ts @@ -83,6 +83,25 @@ describe('file RPC methods', () => { }) }) + it('browses server directories before a project is added', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + browseServerDir: vi.fn().mockResolvedValue({ + resolvedPath: '/home/me', + entries: [{ name: 'project', isDirectory: true, isSymlink: false }] + }) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: FILE_METHODS }) + + const response = await dispatcher.dispatch(makeRequest('files.browseServerDir', { path: '~' })) + + expect(runtime.browseServerDir).toHaveBeenCalledWith('~') + expect(response).toMatchObject({ + ok: true, + result: { resolvedPath: '/home/me', entries: [{ name: 'project', isDirectory: true }] } + }) + }) + it('streams file watch changes until the subscription is cleaned up', async () => { vi.useFakeTimers() try { diff --git a/src/main/runtime/rpc/methods/files.ts b/src/main/runtime/rpc/methods/files.ts index 520a48cdf..1060081ba 100644 --- a/src/main/runtime/rpc/methods/files.ts +++ b/src/main/runtime/rpc/methods/files.ts @@ -37,6 +37,13 @@ const FileTreePath = WorktreeSelector.extend({ .pipe(z.string()) }) +const ServerDirectoryBrowse = z.object({ + path: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string()) +}) + // Why: write content must be a real string. Coercing a missing/non-string value // to '' silently truncated the target file to empty instead of erroring. An // explicit '' is still accepted (writing an empty file is legitimate). @@ -156,6 +163,11 @@ export const FILE_METHODS: RpcAnyMethod[] = [ handler: async (params, { runtime }) => runtime.readFileExplorerDir(params.worktree, params.relativePath) }), + defineMethod({ + name: 'files.browseServerDir', + params: ServerDirectoryBrowse, + handler: async (params, { runtime }) => runtime.browseServerDir(params.path) + }), defineMethod({ name: 'files.write', params: FileWrite, diff --git a/src/main/runtime/rpc/methods/index.ts b/src/main/runtime/rpc/methods/index.ts index 4ec7a883d..3093c4634 100644 --- a/src/main/runtime/rpc/methods/index.ts +++ b/src/main/runtime/rpc/methods/index.ts @@ -25,6 +25,7 @@ import { JIRA_METHODS } from './jira' import { SSH_METHODS } from './ssh' import { SPEECH_METHODS } from './speech' import { CLIENT_UI_METHODS } from './client-ui' +import { CLIENT_EVENT_METHODS } from './client-events' import { WORKSPACE_PORT_METHODS } from './workspace-ports' import { SKILL_METHODS } from './skills' import { CLIPBOARD_METHODS } from './clipboard' @@ -63,5 +64,6 @@ export const ALL_RPC_METHODS: readonly RpcAnyMethod[] = [ ...SKILL_METHODS, ...CLIPBOARD_METHODS, ...HOST_CAPABILITY_METHODS, + ...CLIENT_EVENT_METHODS, ...CLIENT_UI_METHODS ] diff --git a/src/main/runtime/runtime-rpc.ts b/src/main/runtime/runtime-rpc.ts index 3c56dc56a..b29f74b4d 100644 --- a/src/main/runtime/runtime-rpc.ts +++ b/src/main/runtime/runtime-rpc.ts @@ -142,6 +142,7 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'browser.viewport', 'clipboard.saveImageAsTempFile', 'diagnostics.memory', + 'files.browseServerDir', 'files.createFile', 'files.list', 'files.open', @@ -255,6 +256,7 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'repo.searchRefs', 'repo.sparsePresets', 'repo.update', + 'runtime.clientEvents.subscribe', 'session.tabs.activate', 'session.tabs.close', 'session.tabs.createTerminal', diff --git a/src/renderer/src/components/sidebar/AddRepoCreateStep.tsx b/src/renderer/src/components/sidebar/AddRepoCreateStep.tsx index 7375e45b3..262c0975f 100644 --- a/src/renderer/src/components/sidebar/AddRepoCreateStep.tsx +++ b/src/renderer/src/components/sidebar/AddRepoCreateStep.tsx @@ -1,7 +1,7 @@ // Step for AddRepoDialog (orca#763), split out so create-project state stays scoped. import React, { useCallback, useRef, useState } from 'react' import { toast } from 'sonner' -import { Folder, GitBranch, Home, Pencil } from 'lucide-react' +import { Folder, GitBranch } from 'lucide-react' import { useAppStore } from '@/store' import { useMountedRef } from '@/hooks/useMountedRef' import { DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog' @@ -12,6 +12,10 @@ import { markOnboardingProjectAdded } from '@/lib/onboarding-project-checklist' import { callRuntimeRpc, getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' import { isGitRepoKind } from '../../../../shared/repo-kind' import type { Repo } from '../../../../shared/types' +import { + CreateProjectLocationField, + CreateProjectParentBrowser +} from './CreateProjectLocationField' type RepoKind = 'git' | 'folder' @@ -256,6 +260,7 @@ type CreateStepProps = { createError: string | null isCreating: boolean manualParentEntry?: boolean + runtimeEnvironmentId?: string | null onNameChange: (value: string) => void onParentChange: (value: string) => void onKindChange: (kind: RepoKind) => void @@ -270,6 +275,7 @@ export function CreateStep({ createError, isCreating, manualParentEntry = false, + runtimeEnvironmentId, onNameChange, onParentChange, onKindChange, @@ -278,6 +284,7 @@ export function CreateStep({ }: CreateStepProps): React.JSX.Element { const radioGroupRef = useRef(null) const radioFocusFrameRef = useRef(null) + const [browsingParent, setBrowsingParent] = useState(false) const cancelRadioFocusFrame = useCallback((): void => { if (radioFocusFrameRef.current === null) { @@ -314,6 +321,17 @@ export function CreateStep({ const canSubmit = createName.trim().length > 0 && createParent.trim().length > 0 && !isCreating + if (browsingParent && runtimeEnvironmentId) { + return ( + setBrowsingParent(false)} + /> + ) + } + return ( <> @@ -378,54 +396,16 @@ export function CreateStep({ /> - {/* Location. The local flow uses a folder picker; runtime servers need - manual server-path entry because the client cannot browse that filesystem yet. */} -
- Location - - {manualParentEntry ? ( - onParentChange(e.target.value)} - placeholder="/home/user/projects" - className="h-11 text-sm font-mono" - disabled={isCreating} - spellCheck={false} - /> - ) : createParent ? ( -
- - - - - {createParent} - - -
- ) : ( - - )} -
+ {/* The local picker returns client paths; runtime servers browse host paths via RPC. */} + setBrowsingParent(true)} + /> {createError && (

diff --git a/src/renderer/src/components/sidebar/AddRepoDialog.tsx b/src/renderer/src/components/sidebar/AddRepoDialog.tsx index 88aeb7ee4..f9975630d 100644 --- a/src/renderer/src/components/sidebar/AddRepoDialog.tsx +++ b/src/renderer/src/components/sidebar/AddRepoDialog.tsx @@ -301,6 +301,7 @@ const AddRepoDialog = React.memo(function AddRepoDialog() { + +function renderStepContent(overrides: Partial): string { + const props: StepContentProps = { + step: 'nested', + isRuntimeEnvironmentActive: false, + activeRuntimeEnvironmentId: null, + isSshLikely: false, + repoCount: 1, + isAdding: false, + addProjectBusyLabel: null, + nestedScanInProgress: false, + nestedScanId: null, + serverPath: '', + isAddingServerPath: false, + cloneUrl: '', + cloneDestination: '', + cloneError: null, + cloneProgress: null, + isCloning: false, + sshTargets: [], + selectedTargetId: null, + remotePath: '', + remoteError: null, + isAddingRemote: false, + isScanningRemoteNested: false, + nestedScan, + nestedSelectedPaths: new Set(nestedScan.repos.map((repo) => repo.path)), + nestedGroupName: 'platform', + createName: '', + createParent: '', + createKind: 'git', + createError: null, + isCreating: false, + onBrowse: vi.fn(), + onOpenCloneStep: vi.fn(), + onOpenCreateStep: vi.fn(), + onOpenRemoteStep: vi.fn(), + onStopNestedScan: vi.fn(), + onServerPathChange: vi.fn(), + onAddServerPath: vi.fn(), + onSelectTarget: vi.fn(), + onRemotePathChange: vi.fn(), + onAddRemoteRepo: vi.fn(), + onOpenSshSettings: vi.fn(), + onConnectTarget: vi.fn(), + onStopRemoteNestedScan: vi.fn(), + onCloneUrlChange: vi.fn(), + onCloneDestinationChange: vi.fn(), + onPickCloneDestination: vi.fn(), + onClone: vi.fn(), + onNestedGroupNameChange: vi.fn(), + onNestedSelectedPathsChange: vi.fn(), + onImportNestedRepos: vi.fn(), + onCreateNameChange: vi.fn(), + onCreateParentChange: vi.fn(), + onCreateKindChange: vi.fn(), + onPickCreateParent: vi.fn(), + onCreate: vi.fn(), + ...overrides + } + return renderToStaticMarkup(

- repo.path))} - nestedGroupName="platform" - createName="" - createParent="" - createKind="git" - createError={null} - isCreating={false} - onBrowse={vi.fn()} - onOpenCloneStep={vi.fn()} - onOpenCreateStep={vi.fn()} - onOpenRemoteStep={vi.fn()} - onStopNestedScan={vi.fn()} - onServerPathChange={vi.fn()} - onAddServerPath={vi.fn()} - onSelectTarget={vi.fn()} - onRemotePathChange={vi.fn()} - onAddRemoteRepo={vi.fn()} - onOpenSshSettings={vi.fn()} - onConnectTarget={vi.fn()} - onStopRemoteNestedScan={vi.fn()} - onCloneUrlChange={vi.fn()} - onCloneDestinationChange={vi.fn()} - onPickCloneDestination={vi.fn()} - onClone={vi.fn()} - onNestedGroupNameChange={vi.fn()} - onNestedSelectedPathsChange={vi.fn()} - onImportNestedRepos={vi.fn()} - onCreateNameChange={vi.fn()} - onCreateParentChange={vi.fn()} - onCreateKindChange={vi.fn()} - onPickCreateParent={vi.fn()} - onCreate={vi.fn()} - /> + ) } +function renderNestedStep(repoCount: number): string { + return renderStepContent({ repoCount }) +} + describe('AddRepoDialogStepContent nested imports', () => { it('uses the first-import nested repo action when no repos exist yet', () => { const html = renderNestedStep(0) @@ -104,4 +115,26 @@ describe('AddRepoDialogStepContent nested imports', () => { expect(html).toContain('Import as group') expect(html).not.toContain('>Import') }) + + it('offers server browsing for remote create project locations', () => { + const html = renderStepContent({ + step: 'create', + isRuntimeEnvironmentActive: true, + activeRuntimeEnvironmentId: 'env-1' + }) + + expect(html).toContain('Start a new project') + expect(html).toContain('aria-label="Browse server filesystem"') + }) + + it('offers server browsing for remote clone destinations', () => { + const html = renderStepContent({ + step: 'clone', + isRuntimeEnvironmentActive: true, + activeRuntimeEnvironmentId: 'env-1' + }) + + expect(html).toContain('Clone from URL') + expect(html).toContain('aria-label="Browse server filesystem"') + }) }) diff --git a/src/renderer/src/components/sidebar/AddRepoDialogStepContent.tsx b/src/renderer/src/components/sidebar/AddRepoDialogStepContent.tsx index 3519839f4..8172131de 100644 --- a/src/renderer/src/components/sidebar/AddRepoDialogStepContent.tsx +++ b/src/renderer/src/components/sidebar/AddRepoDialogStepContent.tsx @@ -2,7 +2,8 @@ import type { Dispatch, SetStateAction } from 'react' import { CloneStep } from './AddRepoSteps' import { RemoteStep } from './AddRepoRemoteStep' import { CreateStep } from './AddRepoCreateStep' -import { AddRepoLocalStartStep, AddRepoServerPathStartStep } from './AddRepoStartSteps' +import { AddRepoLocalStartStep } from './AddRepoStartSteps' +import { AddRepoServerPathStartStep } from './AddRepoServerStartStep' import { AddRepoNestedImportStep } from './AddRepoNestedImportStep' import type { AddRepoDialogStep } from './add-repo-dialog-types' import type { NestedRepoScanResult } from '../../../../shared/types' @@ -11,6 +12,7 @@ import type { SshConnectionState, SshTarget } from '../../../../shared/ssh-types type AddRepoDialogStepContentProps = { step: AddRepoDialogStep isRuntimeEnvironmentActive: boolean + activeRuntimeEnvironmentId: string | null | undefined isSshLikely: boolean repoCount: number isAdding: boolean @@ -68,6 +70,7 @@ type AddRepoDialogStepContentProps = { export function AddRepoDialogStepContent({ step, isRuntimeEnvironmentActive, + activeRuntimeEnvironmentId, isSshLikely, repoCount, isAdding, @@ -125,6 +128,7 @@ export function AddRepoDialogStepContent({ return ( void + onAddServerPath: (kind: 'git' | 'folder') => void + onOpenCloneStep: () => void + onOpenCreateStep: () => void +} + +export function AddRepoServerPathStartStep({ + serverPath, + runtimeEnvironmentId, + isAddingServerPath, + addProjectBusyLabel, + onServerPathChange, + onAddServerPath, + onOpenCloneStep, + onOpenCreateStep +}: AddRepoServerPathStartStepProps): React.JSX.Element { + const [browsing, setBrowsing] = useState(false) + const [pathEntryOpen, setPathEntryOpen] = useState(false) + + if (browsing && runtimeEnvironmentId) { + return ( + <> + + Browse server filesystem + + Navigate to a directory and click Select to choose it. + + + { + onServerPathChange(path) + setBrowsing(false) + setPathEntryOpen(true) + }} + onCancel={() => setBrowsing(false)} + /> + + ) + } + + if (!pathEntryOpen) { + const disabled = isAddingServerPath || !runtimeEnvironmentId + + return ( + <> + + Add a project + + Add another project from the selected runtime server. + + + +
+
+ setBrowsing(true)} + /> + + +
+ +
+ + + + + Want to import many repos at once? Browse to the parent folder. + +
+ + +
+ + ) + } + + return ( + <> + + Open server project + + Add a Git repository or folder that already exists on the selected runtime server. + + + +
+
+ +
+ onServerPathChange(event.target.value)} + placeholder="/home/user/project" + className="h-11 min-w-0 flex-1 font-mono text-sm" + disabled={isAddingServerPath} + autoFocus + spellCheck={false} + /> + + + + + + Browse server filesystem + + +
+
+
+ + +
+ {isAddingServerPath && addProjectBusyLabel ? ( +
+ + {addProjectBusyLabel} +
+ ) : null} + +
+ + ) +} + +type AddRepoServerStartActionProps = { + icon: ComponentType<{ className?: string }> + title: string + description: string + disabled: boolean + onClick: () => void +} + +function AddRepoServerStartAction({ + icon: Icon, + title, + description, + disabled, + onClick +}: AddRepoServerStartActionProps): React.JSX.Element { + return ( + + ) +} diff --git a/src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx b/src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx index 8693c09d8..10e3ff8ed 100644 --- a/src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx +++ b/src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx @@ -5,7 +5,9 @@ import { createRoot, type Root } from 'react-dom/client' import { renderToStaticMarkup } from 'react-dom/server' import type * as ReactModule from 'react' import { afterEach, describe, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' import { AddRepoLocalStartStep } from './AddRepoStartSteps' +import { AddRepoServerPathStartStep } from './AddRepoServerStartStep' import { getAddRepoLocalStartActions } from './add-repo-local-start-actions' vi.mock('@/components/ui/dialog', () => ({ @@ -32,6 +34,23 @@ function renderLocalStartStep(isSshLikely: boolean): string { ) } +function renderServerPathStartStep(runtimeEnvironmentId: string | null): string { + return renderToStaticMarkup( + + + + ) +} + async function renderLocalStartStepDom(isSshLikely: boolean): Promise<{ container: HTMLDivElement root: Root @@ -164,3 +183,23 @@ describe('AddRepoLocalStartStep', () => { }) }) }) + +describe('AddRepoServerPathStartStep', () => { + it('uses native-style project entry cards in server mode', () => { + const markup = renderServerPathStartStep('env-1') + + expect(markup).toContain('Add a project') + expect(markup).toContain('Add another project from the selected runtime server.') + expect(markup).toContain('Browse server') + expect(markup).toContain('Clone from URL') + expect(markup).toContain('Create on server') + expect(markup).toContain('Want to import many repos at once?') + expect(markup).toContain('Or enter a server path manually') + }) + + it('disables server entry cards without an active runtime environment', () => { + const markup = renderServerPathStartStep(null) + + expect(markup).toContain('disabled=""') + }) +}) diff --git a/src/renderer/src/components/sidebar/AddRepoStartSteps.tsx b/src/renderer/src/components/sidebar/AddRepoStartSteps.tsx index aae6d4e26..7dfb6e4da 100644 --- a/src/renderer/src/components/sidebar/AddRepoStartSteps.tsx +++ b/src/renderer/src/components/sidebar/AddRepoStartSteps.tsx @@ -2,7 +2,6 @@ import { useEffect, useRef, type ComponentType, type Ref } from 'react' import { CircleStop, Loader2 } from 'lucide-react' import { DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Button } from '@/components/ui/button' -import { Input } from '@/components/ui/input' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' import { getAddRepoLocalStartActions } from './add-repo-local-start-actions' @@ -49,99 +48,6 @@ function AddRepoNestedScanProgressNotice({ ) } -type AddRepoServerPathStartStepProps = { - serverPath: string - isAddingServerPath: boolean - addProjectBusyLabel: string | null - onServerPathChange: (path: string) => void - onAddServerPath: (kind: 'git' | 'folder') => void - onOpenCloneStep: () => void - onOpenCreateStep: () => void -} - -export function AddRepoServerPathStartStep({ - serverPath, - isAddingServerPath, - addProjectBusyLabel, - onServerPathChange, - onAddServerPath, - onOpenCloneStep, - onOpenCreateStep -}: AddRepoServerPathStartStepProps): React.JSX.Element { - return ( - <> - - Add a server project - - Add a Git repository or folder that already exists on the selected runtime server. - - - -
-
- - onServerPathChange(event.target.value)} - placeholder="/home/user/project" - className="h-11 text-sm font-mono" - disabled={isAddingServerPath} - autoFocus - spellCheck={false} - /> -
-
- - -
- {isAddingServerPath && addProjectBusyLabel ? ( -
- - {addProjectBusyLabel} -
- ) : null} -
- - -
-
- - ) -} - type AddRepoLocalStartStepProps = { repoCount: number isSshLikely: boolean diff --git a/src/renderer/src/components/sidebar/AddRepoSteps.tsx b/src/renderer/src/components/sidebar/AddRepoSteps.tsx index d5d0deb7c..d2e46b3fb 100644 --- a/src/renderer/src/components/sidebar/AddRepoSteps.tsx +++ b/src/renderer/src/components/sidebar/AddRepoSteps.tsx @@ -6,6 +6,7 @@ import { DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/di import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { useMountedRef } from '@/hooks/useMountedRef' +import { RemoteFileBrowser } from './RemoteFileBrowser' import type { NestedRepoScanResult } from '../../../../shared/types' import type { SshTarget, SshConnectionState } from '../../../../shared/ssh-types' import { createNestedRepoTelemetryAttemptId } from '../../../../shared/nested-repo-telemetry' @@ -256,6 +257,7 @@ type CloneStepProps = { cloneProgress: { phase: string; percent: number } | null isCloning: boolean disableDestinationPicker?: boolean + runtimeEnvironmentId?: string | null onUrlChange: (value: string) => void onDestChange: (value: string) => void onPickDestination: () => void @@ -269,11 +271,13 @@ export function CloneStep({ cloneProgress, isCloning, disableDestinationPicker = false, + runtimeEnvironmentId, onUrlChange, onDestChange, onPickDestination, onClone }: CloneStepProps): React.JSX.Element { + const [browsingDestination, setBrowsingDestination] = useState(false) const canClone = !!cloneUrl.trim() && !!cloneDestination.trim() && !isCloning const handleKeyDown = (e: React.KeyboardEvent): void => { if (e.key === 'Enter' && !e.nativeEvent.isComposing) { @@ -283,6 +287,29 @@ export function CloneStep({ } } } + + if (browsingDestination && runtimeEnvironmentId) { + return ( + <> + + Browse server filesystem + + Navigate to a directory and click Select to choose it. + + + { + onDestChange(path) + setBrowsingDestination(false) + }} + onCancel={() => setBrowsingDestination(false)} + /> + + ) + } + return ( <> @@ -319,9 +346,16 @@ export function CloneStep({ variant="outline" size="sm" className="h-8 px-2 shrink-0" - onClick={onPickDestination} - disabled={isCloning || disableDestinationPicker} - title={disableDestinationPicker ? 'Enter a server path manually' : 'Choose folder'} + onClick={() => { + if (runtimeEnvironmentId) { + setBrowsingDestination(true) + return + } + onPickDestination() + }} + disabled={isCloning || (disableDestinationPicker && !runtimeEnvironmentId)} + title={runtimeEnvironmentId ? 'Browse server filesystem' : 'Choose folder'} + aria-label={runtimeEnvironmentId ? 'Browse server filesystem' : 'Choose folder'} > diff --git a/src/renderer/src/components/sidebar/CreateProjectLocationField.tsx b/src/renderer/src/components/sidebar/CreateProjectLocationField.tsx new file mode 100644 index 000000000..31122237e --- /dev/null +++ b/src/renderer/src/components/sidebar/CreateProjectLocationField.tsx @@ -0,0 +1,129 @@ +import { Folder, FolderOpen, Home, Pencil } from 'lucide-react' +import { DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { RemoteFileBrowser } from './RemoteFileBrowser' + +type CreateProjectParentBrowserProps = { + runtimeEnvironmentId: string + createParent: string + onParentChange: (value: string) => void + onClose: () => void +} + +export function CreateProjectParentBrowser({ + runtimeEnvironmentId, + createParent, + onParentChange, + onClose +}: CreateProjectParentBrowserProps): React.JSX.Element { + return ( + <> + + Browse server filesystem + + Navigate to a directory and click Select to choose it. + + + { + onParentChange(path) + onClose() + }} + onCancel={onClose} + /> + + ) +} + +type CreateProjectLocationFieldProps = { + createParent: string + isCreating: boolean + manualParentEntry: boolean + runtimeEnvironmentId?: string | null + onParentChange: (value: string) => void + onPickParent: () => void + onBrowseServer: () => void +} + +export function CreateProjectLocationField({ + createParent, + isCreating, + manualParentEntry, + runtimeEnvironmentId, + onParentChange, + onPickParent, + onBrowseServer +}: CreateProjectLocationFieldProps): React.JSX.Element { + return ( +
+ Location + + {manualParentEntry ? ( +
+ onParentChange(e.target.value)} + placeholder="/home/user/projects" + className="h-11 min-w-0 flex-1 text-sm font-mono" + disabled={isCreating} + spellCheck={false} + /> + + + + + + Browse server filesystem + + +
+ ) : createParent ? ( +
+ + + + + {createParent} + + +
+ ) : ( + + )} +
+ ) +} diff --git a/src/renderer/src/components/sidebar/RemoteFileBrowser.tsx b/src/renderer/src/components/sidebar/RemoteFileBrowser.tsx index 8cbe47f6e..c24edffeb 100644 --- a/src/renderer/src/components/sidebar/RemoteFileBrowser.tsx +++ b/src/renderer/src/components/sidebar/RemoteFileBrowser.tsx @@ -15,9 +15,12 @@ import { resolveSegmentStep, type DirEntry } from './remote-file-browser-helpers' +import { browseRuntimeServerDirectory } from '@/runtime/runtime-server-directory-browser' -type RemoteFileBrowserProps = { - targetId: string +type RemoteFileBrowserProps = ( + | { targetId: string; runtimeEnvironmentId?: never } + | { runtimeEnvironmentId: string; targetId?: never } +) & { initialPath?: string onSelect: (path: string) => void onCancel: () => void @@ -39,6 +42,7 @@ type PreviewState = { export function RemoteFileBrowser({ targetId, + runtimeEnvironmentId, initialPath = '~', onSelect, onCancel @@ -116,7 +120,12 @@ export function RemoteFileBrowser({ if (cached) { return cached } - const result = await window.api.ssh.browseDir({ targetId, dirPath }) + const result = targetId + ? await window.api.ssh.browseDir({ targetId, dirPath }) + : await browseRuntimeServerDirectory( + requireRuntimeEnvironmentId(runtimeEnvironmentId), + dirPath + ) listingCacheRef.current.set(result.resolvedPath, result) // Also cache under the requested dirPath when it differs from the // server-resolved canonical path (e.g. `~`, `~/foo`, or a relative @@ -127,7 +136,7 @@ export function RemoteFileBrowser({ } return result }, - [targetId] + [runtimeEnvironmentId, targetId] ) const loadDir = useCallback( @@ -749,3 +758,10 @@ function committedPrefix(raw: string): string { const i = raw.lastIndexOf('/') return i === -1 ? '' : raw.slice(0, i + 1) } + +function requireRuntimeEnvironmentId(runtimeEnvironmentId: string | undefined): string { + if (!runtimeEnvironmentId) { + throw new Error('Runtime environment is required') + } + return runtimeEnvironmentId +} diff --git a/src/renderer/src/hooks/useIpcEvents.test.ts b/src/renderer/src/hooks/useIpcEvents.test.ts index 7837c3e6a..4ee6eca3f 100644 --- a/src/renderer/src/hooks/useIpcEvents.test.ts +++ b/src/renderer/src/hooks/useIpcEvents.test.ts @@ -2683,6 +2683,221 @@ describe('useIpcEvents CLI-created worktree activation', () => { expect(activateAndRevealWorktree).toHaveBeenCalledTimes(1) expect(activateAndRevealWorktree).toHaveBeenCalledWith('wt-existing', {}) }) + + it('refreshes active runtime worktrees from remote client events', async () => { + const fetchWorktrees = vi.fn() + const fetchWorktreeLineage = vi.fn() + let runtimeOnResponse: ((response: unknown) => void) | undefined + const runtimeSubscribe = vi.fn(async (_args, callbacks) => { + runtimeOnResponse = (callbacks as { onResponse: (response: unknown) => void }).onResponse + return { unsubscribe: vi.fn(), sendBinary: vi.fn() } + }) + + vi.doMock('react', async () => { + const actual = await vi.importActual('react') + return { + ...actual, + useEffect: (effect: () => void | (() => void)) => { + effect() + } + } + }) + + vi.doMock('../store', () => ({ + useAppStore: { + subscribe: vi.fn(() => () => {}), + getState: () => ({ + fetchRepos: vi.fn(), + fetchProjectGroups: vi.fn(), + fetchWorktrees, + fetchWorktreeLineage, + detectedWorktreesByRepo: { + 'repo-1': { + repoId: 'repo-1', + authoritative: true, + source: 'git', + worktrees: [{ id: 'wt-old' }] + } + }, + worktreesByRepo: {}, + purgeWorktreeTerminalState: vi.fn(), + removeWorkspaceSpaceWorktrees: vi.fn(), + setUpdateStatus: vi.fn(), + activeModal: null, + closeModal: vi.fn(), + openModal: vi.fn(), + getKnownWorktreeById: vi.fn(), + activeWorktreeId: 'wt-old', + activeView: 'terminal', + setActiveView: vi.fn(), + setActiveRepo: vi.fn(), + setActiveWorktree: vi.fn(), + revealWorktreeInSidebar: vi.fn(), + setIsFullScreen: vi.fn(), + updateBrowserPageState: vi.fn(), + activeTabType: 'terminal', + editorFontZoomLevel: 0, + setEditorFontZoomLevel: vi.fn(), + setRateLimitsFromPush: vi.fn(), + setSshConnectionState: vi.fn(), + setSshTargetLabels: vi.fn(), + setPortForwards: vi.fn(), + clearPortForwards: vi.fn(), + setDetectedPorts: vi.fn(), + enqueueSshCredentialRequest: vi.fn(), + removeSshCredentialRequest: vi.fn(), + clearTabPtyId: vi.fn(), + settings: { activeRuntimeEnvironmentId: 'env-1', terminalFontSize: 13 } + }) + } + })) + + vi.doMock('@/lib/ui-zoom', () => ({ + applyUIZoom: vi.fn() + })) + vi.doMock('@/lib/worktree-activation', () => ({ + activateAndRevealWorktree: vi.fn(), + ensureWorktreeHasInitialTerminal: vi.fn() + })) + vi.doMock('@/components/sidebar/visible-worktrees', () => ({ + getVisibleWorktreeIds: () => [] + })) + vi.doMock('@/lib/editor-font-zoom', () => ({ + nextEditorFontZoomLevel: vi.fn(() => 0), + computeEditorFontSize: vi.fn(() => 13) + })) + vi.doMock('@/components/settings/SettingsConstants', () => ({ + zoomLevelToPercent: vi.fn(() => 100), + ZOOM_MIN: -3, + ZOOM_MAX: 3 + })) + vi.doMock('@/lib/zoom-events', () => ({ + dispatchZoomLevelChanged: vi.fn() + })) + + vi.stubGlobal('window', { + api: { + repos: { onChanged: () => () => {} }, + worktrees: { + onChanged: () => () => {}, + onBaseStatus: () => () => {}, + onRemoteBranchConflict: () => () => {} + }, + runtimeEnvironments: { subscribe: runtimeSubscribe }, + ui: { + onOpenSettings: () => () => {}, + onOpenFeatureTour: () => () => {}, + onToggleLeftSidebar: () => () => {}, + onToggleRightSidebar: () => () => {}, + onToggleWorktreePalette: () => () => {}, + onToggleFloatingTerminal: () => () => {}, + onOpenQuickOpen: () => () => {}, + onOpenNewWorkspace: () => () => {}, + onOpenTasks: () => () => {}, + onJumpToWorktreeIndex: () => () => {}, + onJumpToTabIndex: () => () => {}, + onWorktreeHistoryNavigate: () => () => {}, + onActivateWorktree: () => () => {}, + onCreateTerminal: () => () => {}, + onRequestTerminalCreate: () => () => {}, + replyTerminalCreate: () => {}, + onSplitTerminal: () => () => {}, + onRenameTerminal: () => () => {}, + onFocusTerminal: () => () => {}, + onFocusEditorTab: () => () => {}, + onCloseSessionTab: () => () => {}, + onMoveSessionTab: () => () => {}, + onOpenFileFromMobile: () => () => {}, + onOpenDiffFromMobile: () => () => {}, + onCloseTerminal: () => () => {}, + onSleepWorktree: () => () => {}, + onNewBrowserTab: () => () => {}, + onNewMarkdownTab: () => () => {}, + onRequestTabCreate: () => () => {}, + replyTabCreate: () => {}, + onRequestTabClose: () => () => {}, + replyTabClose: () => {}, + onRequestTabSetProfile: () => () => {}, + replyTabSetProfile: () => {}, + onNewTerminalTab: () => () => {}, + onCloseActiveTab: () => () => {}, + onSwitchTab: () => () => {}, + onSwitchTabAcrossAllTypes: () => () => {}, + onSwitchRecentTab: () => () => {}, + onSwitchTerminalTab: () => () => {}, + onToggleStatusBar: () => () => {}, + onFullscreenChanged: () => () => {}, + onTerminalZoom: () => () => {}, + getZoomLevel: () => 0, + set: vi.fn() + }, + settings: { + onChanged: () => () => {} + }, + updater: { + getStatus: () => Promise.resolve({ state: 'idle' }), + onStatus: () => () => {}, + onClearDismissal: () => () => {} + }, + browser: { + onGuestLoadFailed: () => () => {}, + onOpenLinkInOrcaTab: () => () => {}, + onNavigationUpdate: () => () => {}, + onActivateView: () => () => {}, + onPaneFocus: () => () => {} + }, + rateLimits: { + get: () => Promise.resolve({ limits: {}, lastUpdatedAt: Date.now() }), + onUpdate: () => () => {} + }, + ssh: { + listTargets: () => Promise.resolve([]), + listPortForwards: () => Promise.resolve([]), + listDetectedPorts: () => Promise.resolve([]), + getState: () => Promise.resolve(null), + onStateChanged: () => () => {}, + onCredentialRequest: () => () => {}, + onPortForwardsChanged: () => () => {}, + onDetectedPortsChanged: () => () => {}, + onCredentialResolved: () => () => {} + }, + runtime: { + getTerminalFitOverrides: () => Promise.resolve([]), + getTerminalDrivers: () => Promise.resolve([]), + getBrowserDrivers: () => Promise.resolve([]), + onTerminalFitOverrideChanged: () => () => {}, + onTerminalDriverChanged: () => () => {}, + onBrowserDriverChanged: () => () => {} + }, + agentStatus: { onSet: () => () => {} } + } + }) + + const { useIpcEvents } = await import('./useIpcEvents') + useIpcEvents() + await Promise.resolve() + + expect(runtimeSubscribe).toHaveBeenCalledWith( + { + selector: 'env-1', + method: 'runtime.clientEvents.subscribe', + timeoutMs: 15_000 + }, + expect.any(Object) + ) + if (!runtimeOnResponse) { + throw new Error('Expected runtime client event callbacks') + } + runtimeOnResponse({ + ok: true, + result: { type: 'worktreesChanged', repoId: 'repo-1' } + }) + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(fetchWorktrees).toHaveBeenCalledWith('repo-1') + expect(fetchWorktreeLineage).toHaveBeenCalledTimes(1) + }) }) // Why: end-to-end exercise of startup agent-status restoration through diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index 2bfae42a0..1f5ce1ce1 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -71,6 +71,7 @@ import { releaseBrowserAutomationVisibility } from '@/components/browser-pane/browser-automation-visibility' import { attachMobileMarkdownBridge } from '@/runtime/mobile-markdown-bridge' +import { subscribeRuntimeClientEvents } from '@/runtime/runtime-client-events' import { detectLanguage } from '@/lib/language-detect' import { parsePaneKey } from '../../../shared/stable-pane-id' import { collectLeafIdsInOrder } from '@/components/terminal-pane/layout-serialization' @@ -78,6 +79,7 @@ import { track } from '@/lib/telemetry' import { singlePaneLayoutSnapshot } from '@/store/slices/terminal-helpers' import { buildWorkspaceSessionPayload } from '@/lib/workspace-session' import { getLinearIssueWorkspaceName } from '../../../shared/workspace-name' +import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' import type { AppState } from '../store/types' import { closeWebRuntimeSessionTab, @@ -672,9 +674,138 @@ export function useIpcEvents(): void { type AgentStatusApplyResult = 'applied' | 'pending' | 'dropped' const pendingAgentStatusEvents: PendingAgentStatusEvent[] = [] let pendingAgentStatusRetryTimer: ReturnType | null = null + let runtimeClientEventsUnsubscribe: (() => void) | null = null + let runtimeClientEventsEnvironmentId: string | null = null + let runtimeClientEventsGeneration = 0 unsubs.push(attachMobileMarkdownBridge()) + const handleWorktreesChanged = async (repoId: string): Promise => { + // Why: diff before vs. after fetchWorktrees to detect server-side + // deletions (CLI `orca worktree rm`, other window, out-of-band RPC) + // and purge worktree-scoped state for removed ids. Without this, + // `ptyIdsByTabId` would retain entries for tabs whose worktree is + // gone, and SessionsStatusSegment's `boundPtyIds` set would keep + // misclassifying the zombie as bound (design §2c, §4.4). + const state = useAppStore.getState() + const before = + getAuthoritativeDetectedWorktreeIds(state, repoId) ?? + getVisibleWorktreeIdsForRepo(state, repoId) + await state.fetchWorktrees(repoId) + await useAppStore.getState().fetchWorktreeLineage() + const afterState = useAppStore.getState() + const after = getAuthoritativeDetectedWorktreeIds(afterState, repoId) + if (!after) { + return + } + const removed: string[] = [] + for (const id of before) { + if (!after.has(id)) { + removed.push(id) + } + } + if (removed.length > 0) { + console.warn( + `[worktree-purge] diff-based purge removing state for ${removed.length} worktree(s):`, + removed + ) + afterState.purgeWorktreeTerminalState(removed) + afterState.removeWorkspaceSpaceWorktrees(removed) + } + } + + const activateNotifiedWorktree = async ( + { + repoId, + worktreeId, + setup, + startup, + defaultTabs + }: Extract, + options: { allowRuntimeEnvironment: boolean } + ): Promise => { + if (!options.allowRuntimeEnvironment && isRuntimeEnvironmentActive()) { + // Why: local CLI-created worktree events carry local repo/worktree + // ids. Runtime server activation arrives through the remote event + // stream and is allowed through this helper separately. + return + } + const existedBeforeFetch = Boolean(useAppStore.getState().getKnownWorktreeById(worktreeId)) + // Why: fetch worktrees first so the activation helper can resolve + // the CLI-created worktree via findWorktreeById — it arrived from + // the main process and is not yet in the renderer state. + await useAppStore.getState().fetchWorktrees(repoId) + const existsAfterFetch = Boolean(useAppStore.getState().getKnownWorktreeById(worktreeId)) + // Why: route through activateAndRevealWorktree so CLI-created + // worktrees share the canonical activation path with UI-created + // ones. This records the visit in the back/forward history stack + // (recordWorktreeVisit), without which the nav buttons would + // ignore the CLI-driven workspace switch. + activateAndRevealWorktree(worktreeId, { + ...(setup ? { setup } : {}), + ...(startup ? { startup } : {}), + ...(defaultTabs ? { defaultTabs } : {}), + ...(!existedBeforeFetch && existsAfterFetch ? { sidebarRevealBehavior: 'auto' } : {}) + }) + } + + const handleRuntimeClientEvent = (event: RuntimeClientEvent): void => { + if (event.type === 'reposChanged') { + const state = useAppStore.getState() + void state.fetchProjectGroups() + void state.fetchRepos() + return + } + if (event.type === 'worktreesChanged') { + void handleWorktreesChanged(event.repoId) + return + } + void activateNotifiedWorktree(event, { allowRuntimeEnvironment: true }).catch((error) => { + console.error('Failed to activate runtime-created worktree:', error) + }) + } + + const stopRuntimeClientEvents = (): void => { + runtimeClientEventsGeneration += 1 + runtimeClientEventsEnvironmentId = null + runtimeClientEventsUnsubscribe?.() + runtimeClientEventsUnsubscribe = null + } + + const syncRuntimeClientEventsSubscription = (): void => { + const environmentId = getActiveRuntimeEnvironmentId() + if (!environmentId) { + stopRuntimeClientEvents() + return + } + if (runtimeClientEventsEnvironmentId === environmentId) { + return + } + stopRuntimeClientEvents() + runtimeClientEventsEnvironmentId = environmentId + const generation = runtimeClientEventsGeneration + void subscribeRuntimeClientEvents(environmentId, handleRuntimeClientEvent, (error) => { + console.warn('[runtime-client-events] subscription error:', error) + }) + .then((subscription) => { + if (generation !== runtimeClientEventsGeneration) { + subscription.unsubscribe() + return + } + runtimeClientEventsUnsubscribe = subscription.unsubscribe + }) + .catch((error) => { + if (generation === runtimeClientEventsGeneration) { + runtimeClientEventsEnvironmentId = null + console.warn('[runtime-client-events] failed to subscribe:', error) + } + }) + } + + syncRuntimeClientEventsSubscription() + unsubs.push(useAppStore.subscribe(syncRuntimeClientEventsSubscription)) + unsubs.push(stopRuntimeClientEvents) + unsubs.push( window.api.repos.onChanged(() => { if (isRuntimeEnvironmentActive()) { @@ -696,37 +827,7 @@ export function useIpcEvents(): void { // active runtime with those ids can purge or overwrite server state. return } - // Why: diff before vs. after fetchWorktrees to detect server-side - // deletions (CLI `orca worktree rm`, other window, out-of-band RPC) - // and purge worktree-scoped state for removed ids. Without this, - // `ptyIdsByTabId` would retain entries for tabs whose worktree is - // gone, and SessionsStatusSegment's `boundPtyIds` set would keep - // misclassifying the zombie as bound (design §2c, §4.4). - const state = useAppStore.getState() - const before = - getAuthoritativeDetectedWorktreeIds(state, data.repoId) ?? - getVisibleWorktreeIdsForRepo(state, data.repoId) - await state.fetchWorktrees(data.repoId) - await useAppStore.getState().fetchWorktreeLineage() - const afterState = useAppStore.getState() - const after = getAuthoritativeDetectedWorktreeIds(afterState, data.repoId) - if (!after) { - return - } - const removed: string[] = [] - for (const id of before) { - if (!after.has(id)) { - removed.push(id) - } - } - if (removed.length > 0) { - console.warn( - `[worktree-purge] diff-based purge removing state for ${removed.length} worktree(s):`, - removed - ) - afterState.purgeWorktreeTerminalState(removed) - afterState.removeWorkspaceSpaceWorktrees(removed) - } + await handleWorktreesChanged(data.repoId) }) ) @@ -947,33 +1048,17 @@ export function useIpcEvents(): void { unsubs.push( window.api.ui.onActivateWorktree(({ repoId, worktreeId, setup, startup, defaultTabs }) => { - void (async () => { - if (isRuntimeEnvironmentActive()) { - // Why: local CLI-created worktree events carry local repo/worktree - // ids. Runtime server activation arrives through runtime state, - // not this local Electron event. - return - } - const existedBeforeFetch = Boolean( - useAppStore.getState().getKnownWorktreeById(worktreeId) - ) - // Why: fetch worktrees first so the activation helper can resolve - // the CLI-created worktree via findWorktreeById — it arrived from - // the main process and is not yet in the renderer state. - await useAppStore.getState().fetchWorktrees(repoId) - const existsAfterFetch = Boolean(useAppStore.getState().getKnownWorktreeById(worktreeId)) - // Why: route through activateAndRevealWorktree so CLI-created - // worktrees share the canonical activation path with UI-created - // ones. This records the visit in the back/forward history stack - // (recordWorktreeVisit), without which the nav buttons would - // ignore the CLI-driven workspace switch. - activateAndRevealWorktree(worktreeId, { + void activateNotifiedWorktree( + { + type: 'activateWorktree', + repoId, + worktreeId, ...(setup ? { setup } : {}), ...(startup ? { startup } : {}), - ...(defaultTabs ? { defaultTabs } : {}), - ...(!existedBeforeFetch && existsAfterFetch ? { sidebarRevealBehavior: 'auto' } : {}) - }) - })().catch((error) => { + ...(defaultTabs ? { defaultTabs } : {}) + }, + { allowRuntimeEnvironment: false } + ).catch((error) => { console.error('Failed to activate CLI-created worktree:', error) }) }) diff --git a/src/renderer/src/runtime/runtime-client-events.test.ts b/src/renderer/src/runtime/runtime-client-events.test.ts new file mode 100644 index 000000000..70acb4006 --- /dev/null +++ b/src/renderer/src/runtime/runtime-client-events.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it, vi } from 'vitest' +import { subscribeRuntimeClientEvents } from './runtime-client-events' + +describe('subscribeRuntimeClientEvents', () => { + it('subscribes to runtime client events and forwards event frames', async () => { + const unsubscribe = vi.fn() + let capturedOnResponse: ((response: unknown) => void) | undefined + const subscribe = vi.fn(async (_args, nextCallbacks) => { + capturedOnResponse = (nextCallbacks as { onResponse: (response: unknown) => void }).onResponse + return { unsubscribe, sendBinary: vi.fn() } + }) + const onEvent = vi.fn() + const onError = vi.fn() + + vi.stubGlobal('window', { + api: { + runtimeEnvironments: { subscribe } + } + }) + + const subscription = await subscribeRuntimeClientEvents('env-1', onEvent, onError) + + expect(subscribe).toHaveBeenCalledWith( + { + selector: 'env-1', + method: 'runtime.clientEvents.subscribe', + timeoutMs: 15_000 + }, + expect.objectContaining({ + onResponse: expect.any(Function), + onError + }) + ) + + if (!capturedOnResponse) { + throw new Error('Expected subscription callbacks') + } + capturedOnResponse({ + ok: true, + result: { type: 'ready', subscriptionId: 'sub-1' } + }) + capturedOnResponse({ + ok: true, + result: { type: 'worktreesChanged', repoId: 'repo-1' } + }) + capturedOnResponse({ + ok: false, + error: { code: 'method_not_found', message: 'missing' } + }) + + expect(onEvent).toHaveBeenCalledTimes(1) + expect(onEvent).toHaveBeenCalledWith({ type: 'worktreesChanged', repoId: 'repo-1' }) + expect(onError).toHaveBeenCalledWith({ code: 'method_not_found', message: 'missing' }) + + subscription.unsubscribe() + expect(unsubscribe).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/renderer/src/runtime/runtime-client-events.ts b/src/renderer/src/runtime/runtime-client-events.ts new file mode 100644 index 000000000..31d77cd7a --- /dev/null +++ b/src/renderer/src/runtime/runtime-client-events.ts @@ -0,0 +1,58 @@ +import type { + RuntimeClientEvent, + RuntimeClientEventStreamMessage +} from '../../../shared/runtime-client-events' +import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' + +export type RuntimeClientEventSubscription = { + unsubscribe: () => void +} + +export async function subscribeRuntimeClientEvents( + environmentId: string, + onEvent: (event: RuntimeClientEvent) => void, + onError: (error: unknown) => void = console.warn +): Promise { + const handle = await window.api.runtimeEnvironments.subscribe( + { + selector: environmentId, + method: 'runtime.clientEvents.subscribe', + timeoutMs: 15_000 + }, + { + onResponse: (response) => { + handleRuntimeClientEventResponse(response, onEvent, onError) + }, + onError + } + ) + return { unsubscribe: handle.unsubscribe } +} + +function handleRuntimeClientEventResponse( + response: RuntimeRpcResponse, + onEvent: (event: RuntimeClientEvent) => void, + onError: (error: unknown) => void +): void { + if (response.ok === false) { + onError(response.error) + return + } + const message = response.result as RuntimeClientEventStreamMessage + if (message.type === 'ready' || message.type === 'end') { + return + } + if (isRuntimeClientEvent(message)) { + onEvent(message) + } +} + +function isRuntimeClientEvent( + message: RuntimeClientEventStreamMessage +): message is RuntimeClientEvent { + return ( + message.type === 'reposChanged' || + message.type === 'worktreesChanged' || + message.type === 'activateWorktree' + ) +} diff --git a/src/renderer/src/runtime/runtime-server-directory-browser.test.ts b/src/renderer/src/runtime/runtime-server-directory-browser.test.ts new file mode 100644 index 000000000..fea0a9183 --- /dev/null +++ b/src/renderer/src/runtime/runtime-server-directory-browser.test.ts @@ -0,0 +1,59 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { browseRuntimeServerDirectory } from './runtime-server-directory-browser' +import { clearRuntimeCompatibilityCacheForTests } from './runtime-rpc-client' +import { + MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, + RUNTIME_PROTOCOL_VERSION +} from '../../../shared/protocol-version' + +const runtimeEnvironmentCall = vi.fn() + +beforeEach(() => { + clearRuntimeCompatibilityCacheForTests() + runtimeEnvironmentCall.mockReset() + runtimeEnvironmentCall.mockImplementation((args: { method: string }) => { + if (args.method === 'status.get') { + return Promise.resolve({ + id: 'status', + ok: true, + result: { + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION + }, + _meta: { runtimeId: 'remote-runtime' } + }) + } + return Promise.resolve({ + id: 'browse', + ok: true, + result: { + resolvedPath: '/home/me', + entries: [{ name: 'repo', isDirectory: true, isSymlink: false }] + }, + _meta: { runtimeId: 'remote-runtime' } + }) + }) + vi.stubGlobal('window', { + api: { + runtimeEnvironments: { + call: runtimeEnvironmentCall + } + } + }) +}) + +describe('runtime server directory browser', () => { + it('routes browse requests through the selected runtime environment', async () => { + await expect(browseRuntimeServerDirectory('env-1', '~')).resolves.toEqual({ + resolvedPath: '/home/me', + entries: [{ name: 'repo', isDirectory: true, isSymlink: false }] + }) + + expect(runtimeEnvironmentCall).toHaveBeenLastCalledWith({ + selector: 'env-1', + method: 'files.browseServerDir', + params: { path: '~' }, + timeoutMs: 15_000 + }) + }) +}) diff --git a/src/renderer/src/runtime/runtime-server-directory-browser.ts b/src/renderer/src/runtime/runtime-server-directory-browser.ts new file mode 100644 index 000000000..a5b0eff00 --- /dev/null +++ b/src/renderer/src/runtime/runtime-server-directory-browser.ts @@ -0,0 +1,19 @@ +import type { DirEntry } from '../../../shared/types' +import { callRuntimeRpc } from './runtime-rpc-client' + +export type RuntimeServerDirectoryListing = { + resolvedPath: string + entries: DirEntry[] +} + +export async function browseRuntimeServerDirectory( + environmentId: string, + path: string +): Promise { + return callRuntimeRpc( + { kind: 'environment', environmentId }, + 'files.browseServerDir', + { path }, + { timeoutMs: 15_000 } + ) +} diff --git a/src/shared/runtime-client-events.ts b/src/shared/runtime-client-events.ts new file mode 100644 index 000000000..551212ae7 --- /dev/null +++ b/src/shared/runtime-client-events.ts @@ -0,0 +1,48 @@ +import type { + CreateWorktreeResult, + WorktreeDefaultTabsLaunch, + WorktreeSetupLaunch, + WorktreeStartupLaunch +} from './types' + +export type RuntimeClientEvent = + | { type: 'reposChanged' } + | { type: 'worktreesChanged'; repoId: string } + | { + type: 'activateWorktree' + repoId: string + worktreeId: string + setup?: WorktreeSetupLaunch + startup?: WorktreeStartupLaunch + defaultTabs?: WorktreeDefaultTabsLaunch + } + +export type RuntimeClientEventStreamMessage = + | ({ type: 'ready'; subscriptionId: string } & { + snapshot?: { + // Reserved for future hydration. Current clients refresh through the + // existing repo/worktree RPCs after receiving server events. + repos?: unknown[] + } + }) + | RuntimeClientEvent + | { type: 'end' } + +export type RuntimeActivateWorktreeEvent = Extract + +export function toRuntimeActivateWorktreeEvent( + repoId: string, + worktreeId: string, + setup?: CreateWorktreeResult['setup'], + startup?: WorktreeStartupLaunch, + defaultTabs?: CreateWorktreeResult['defaultTabs'] +): RuntimeActivateWorktreeEvent { + return { + type: 'activateWorktree', + repoId, + worktreeId, + ...(setup ? { setup } : {}), + ...(startup ? { startup } : {}), + ...(defaultTabs ? { defaultTabs } : {}) + } +}