From 29b8e36c39c6ca06838e274417356b6b69cea8ce Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Sun, 17 May 2026 23:55:30 -0400 Subject: [PATCH] Fix mobile SSH worktrees (#2198) Co-authored-by: Orca --- src/main/runtime/orca-runtime.test.ts | 119 ++++++++++++++++++++++++-- src/main/runtime/orca-runtime.ts | 84 +++++++++++++++++- src/relay/fs-handler-git-fallback.ts | 3 + src/relay/fs-handler.ts | 8 +- src/relay/git-handler.ts | 3 + src/relay/relay-command-env.test.ts | 22 +++++ src/relay/relay-command-env.ts | 37 ++++++++ 7 files changed, 265 insertions(+), 11 deletions(-) create mode 100644 src/relay/relay-command-env.test.ts create mode 100644 src/relay/relay-command-env.ts diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 2d0a98e62..f9aeab02c 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -38,6 +38,8 @@ const { getSshGitProviderMock, registerSshGitProviderMock, unregisterSshGitProviderMock, + getActiveMultiplexerMock, + muxRequestMock, invalidateAuthorizedRootsCacheMock, createHostedReviewMock, getHostedReviewCreationEligibilityMock @@ -68,6 +70,8 @@ const { unregisterSshGitProviderMock: vi.fn((connectionId: string) => { sshGitProviders.delete(connectionId) }), + getActiveMultiplexerMock: vi.fn(), + muxRequestMock: vi.fn(), invalidateAuthorizedRootsCacheMock: vi.fn(), createHostedReviewMock: vi.fn(), getHostedReviewCreationEligibilityMock: vi.fn() @@ -87,6 +91,10 @@ vi.mock('../providers/ssh-git-dispatch', () => ({ unregisterSshGitProvider: unregisterSshGitProviderMock })) +vi.mock('../ipc/ssh', () => ({ + getActiveMultiplexer: getActiveMultiplexerMock +})) + vi.mock('../hooks', () => ({ createSetupRunnerScript: vi.fn(), getEffectiveHooks: vi.fn().mockReturnValue(null), @@ -153,6 +161,10 @@ afterEach(() => { unregisterSshGitProviderMock.mockImplementation((connectionId: string) => { sshGitProviders.delete(connectionId) }) + muxRequestMock.mockReset() + muxRequestMock.mockResolvedValue(undefined) + getActiveMultiplexerMock.mockReset() + getActiveMultiplexerMock.mockReturnValue({ request: muxRequestMock, notify: vi.fn() }) vi.mocked(createSetupRunnerScript).mockReset() vi.mocked(getEffectiveHooks).mockReset() vi.mocked(hasHooksFile).mockReset() @@ -622,9 +634,17 @@ describe('OrcaRuntimeService', () => { }) }) - it('does not run local git when runtime worktree creation targets an SSH repo', async () => { + it('creates SSH-backed worktrees through the SSH provider for mobile/runtime callers', async () => { vi.mocked(listWorktrees).mockClear() vi.mocked(addWorktree).mockClear() + const created = { + path: '/remote/mobile-feature', + head: 'def', + branch: 'refs/heads/mobile-feature', + isBare: false, + isMainWorktree: false + } + const metaById: Record = {} const remoteStore = { ...store, getRepos: () => [ @@ -636,14 +656,53 @@ describe('OrcaRuntimeService', () => { addedAt: 1, connectionId: 'ssh-1' } - ] + ], + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: (worktreeId: string, meta: Partial) => { + metaById[worktreeId] = { ...(metaById[worktreeId] ?? makeWorktreeMeta()), ...meta } + return metaById[worktreeId] + } } + const provider = { + exec: vi.fn(async (args: string[]) => { + if (args[0] === 'config') { + return { stdout: 'Remote User\n', stderr: '' } + } + if (args[0] === 'branch') { + return { stdout: '', stderr: '' } + } + if (args[0] === 'symbolic-ref') { + return { stdout: 'origin/main\n', stderr: '' } + } + if (args[0] === 'fetch') { + return { stdout: '', stderr: '' } + } + throw new Error(`unexpected git call: ${args.join(' ')}`) + }), + addWorktree: vi.fn().mockResolvedValue(undefined), + listWorktrees: vi.fn().mockResolvedValue([created]) + } + registerSshGitProvider('ssh-1', provider as never) + getActiveMultiplexerMock.mockReturnValue({ request: muxRequestMock, notify: vi.fn() }) const runtime = new OrcaRuntimeService(remoteStore as never) - await expect( - runtime.createManagedWorktree({ repoSelector: TEST_REPO_ID, name: 'feature' }) - ).rejects.toThrow('SSH-backed worktree creation is not supported through runtime RPC yet') + const result = await runtime.createManagedWorktree({ + repoSelector: TEST_REPO_ID, + name: 'mobile-feature', + startup: { command: 'claude' } + }) + expect(provider.addWorktree).toHaveBeenCalledWith( + '/remote/repo', + 'mobile-feature', + '/remote/repo/../mobile-feature', + { base: 'origin/main' } + ) + expect(result.worktree).toMatchObject({ + id: `${TEST_REPO_ID}::${created.path}`, + path: created.path + }) expect(addWorktree).not.toHaveBeenCalled() expect(listWorktrees).not.toHaveBeenCalled() }) @@ -2351,6 +2410,56 @@ describe('OrcaRuntimeService', () => { }) }) + it('includes SSH-backed worktrees in the mobile worktree summary', async () => { + const remoteRepo = { + id: 'repo-ssh', + path: '/home/me/project', + displayName: 'remote-vm', + badgeColor: 'blue', + addedAt: 1, + connectionId: 'ssh-1' + } + const remoteWorktree = { + path: '/home/me/project/.worktrees/feature-mobile', + head: 'def', + branch: 'refs/heads/feature/mobile', + isBare: false, + isMainWorktree: false + } + const metaById: Record = { + [`${remoteRepo.id}::${remoteWorktree.path}`]: makeWorktreeMeta({ + displayName: 'Remote mobile' + }) + } + const runtimeStore = { + ...store, + getRepos: () => [remoteRepo], + getRepo: (id: string) => (id === remoteRepo.id ? remoteRepo : undefined), + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: (worktreeId: string, meta: Partial) => { + metaById[worktreeId] = { ...(metaById[worktreeId] ?? makeWorktreeMeta()), ...meta } + return metaById[worktreeId] + } + } + registerSshGitProvider('ssh-1', { + listWorktrees: vi.fn().mockResolvedValue([remoteWorktree]) + } as never) + + const runtime = new OrcaRuntimeService(runtimeStore as never) + const summaries = await runtime.getWorktreePs() + + expect(summaries.worktrees).toEqual([ + expect.objectContaining({ + worktreeId: `${remoteRepo.id}::${remoteWorktree.path}`, + repoId: remoteRepo.id, + repo: 'remote-vm', + path: remoteWorktree.path, + displayName: 'Remote mobile' + }) + ]) + }) + it('clears stale working status after the agent exits and the shell takes over the title', async () => { // Why: regression test for issue #1437 — the mobile worktree-list spinner // kept playing forever because lastAgentStatus was sticky on 'working' diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 9e3f642b1..bd16cdf10 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -235,6 +235,7 @@ import { DEFAULT_REPO_BADGE_COLOR, getDefaultVoiceSettings } from '../../shared/ import { listRepoWorktrees } from '../repo-worktrees' import { createWorktreeSymlinks } from '../ipc/worktree-symlinks' import { + createRemoteWorktree, configureCreatedWorktreePushTarget, prepareWorktreePushTarget } from '../ipc/worktree-remote' @@ -5249,10 +5250,7 @@ export class OrcaRuntimeService { throw new Error('Folder mode does not support creating worktrees.') } if (repo.connectionId) { - // Why: SSH-backed worktree creation still relies on the desktop SSH - // flow, which can prime relay roots and enforce its remote constraints. - // Runtime RPC must not fall through to local git against server paths. - throw new Error('SSH-backed worktree creation is not supported through runtime RPC yet.') + return await this.createManagedRemoteWorktree(repo, args) } const lineageInput = args.lineage || args.comment ? { ...args.lineage, comment: args.comment } : undefined @@ -5593,6 +5591,84 @@ export class OrcaRuntimeService { } } + private async createManagedRemoteWorktree( + repo: Repo, + args: { + name: string + baseBranch?: string + branchNameOverride?: string + linkedIssue?: number | null + linkedPR?: number | null + linkedLinearIssue?: string + comment?: string + displayName?: string + workspaceStatus?: string + sparseCheckout?: { directories: string[]; presetId?: string } + pushTarget?: GitPushTarget + setupDecision?: 'run' | 'skip' | 'inherit' + createdWithAgent?: TuiAgent + startup?: WorktreeStartupLaunch + } + ): Promise { + if (!this.store) { + throw new Error('runtime_unavailable') + } + + // Why: runtime/mobile callers do not own a renderer BrowserWindow, but the + // SSH create helper only uses it for progress and change notifications. + // Runtime emits those through RuntimeNotifier after the create succeeds. + const headlessWindow = { + isDestroyed: () => false, + webContents: { send: () => undefined } + } as unknown as BrowserWindow + + const result = await createRemoteWorktree( + { + repoId: repo.id, + name: args.name, + ...(args.displayName ? { displayName: args.displayName } : {}), + ...(args.baseBranch ? { baseBranch: args.baseBranch } : {}), + ...(args.branchNameOverride ? { branchNameOverride: args.branchNameOverride } : {}), + ...(args.setupDecision ? { setupDecision: args.setupDecision } : {}), + ...(args.sparseCheckout ? { sparseCheckout: args.sparseCheckout } : {}), + ...(args.linkedIssue != null ? { linkedIssue: args.linkedIssue } : {}), + ...(args.linkedPR != null ? { linkedPR: args.linkedPR } : {}), + ...(args.linkedLinearIssue ? { linkedLinearIssue: args.linkedLinearIssue } : {}), + ...(args.pushTarget ? { pushTarget: args.pushTarget } : {}), + ...(args.workspaceStatus ? { workspaceStatus: args.workspaceStatus as never } : {}), + ...(args.createdWithAgent ? { createdWithAgent: args.createdWithAgent } : {}) + }, + repo, + this.store as unknown as Store, + headlessWindow + ) + + if (args.comment !== undefined) { + this.store.setWorktreeMeta(result.worktree.id, { comment: args.comment }) + result.worktree.comment = args.comment + } + + this.invalidateResolvedWorktreeCache() + this.notifier?.worktreesChanged(repo.id) + + if (args.startup && this.ptyController?.spawn) { + try { + await this.createTerminal(`path:${result.worktree.path}`, { + command: args.startup.command, + env: args.startup.env + }) + } catch (err) { + const message = err instanceof Error ? err.message : String(err) + return { + ...result, + warning: `Failed to create the startup terminal for ${result.worktree.path}: ${message}` + } + } + } + + return result + } + /** * Fetch `remote` in `repoPath`, sharing the 30s freshness window + in-flight * serialization with all other callers (renderer-create path, CLI create, diff --git a/src/relay/fs-handler-git-fallback.ts b/src/relay/fs-handler-git-fallback.ts index db7c23c43..ac8732e85 100644 --- a/src/relay/fs-handler-git-fallback.ts +++ b/src/relay/fs-handler-git-fallback.ts @@ -21,6 +21,7 @@ import { ingestGitGrepLine, SEARCH_TIMEOUT_MS } from '../shared/text-search' +import { buildRelayCommandEnv } from './relay-command-env' /** * List files using `git ls-files`. Fallback when rg is not installed. @@ -60,6 +61,7 @@ export function listFilesWithGit( const child = spawn('git', ['ls-files', ...args], { cwd: rootPath, + env: buildRelayCommandEnv(), stdio: ['ignore', 'pipe', 'pipe'] }) child.stdout!.setEncoding('utf-8') @@ -150,6 +152,7 @@ export function searchWithGitGrep( const child = spawn('git', gitArgs, { cwd: rootPath, + env: buildRelayCommandEnv(), stdio: ['ignore', 'pipe', 'pipe'] }) child.stdout!.setEncoding('utf-8') diff --git a/src/relay/fs-handler.ts b/src/relay/fs-handler.ts index 57fa9c8f8..15312d84a 100644 --- a/src/relay/fs-handler.ts +++ b/src/relay/fs-handler.ts @@ -21,6 +21,7 @@ import { buildInstallRgMessage } from './fs-handler-install-rg' import { readRelayFileContent, readRelayFileStreamMetadata } from './fs-handler-file-read' import { RelayStreamRegistry } from './fs-stream-registry' import { scanWorkspaceSpaceDirectory } from './workspace-space-scan' +import { buildRelayCommandEnv } from './relay-command-env' type WatchState = { rootPath: string @@ -260,8 +261,11 @@ export class FsHandler { // Without this, a git subdirectory would fall through to readdir and // surface .gitignore'd build artifacts. const isGitRepo = await new Promise((resolve) => { - execFile('git', ['rev-parse', '--is-inside-work-tree'], { cwd: rootPath }, (err) => - resolve(!err) + execFile( + 'git', + ['rev-parse', '--is-inside-work-tree'], + { cwd: rootPath, env: buildRelayCommandEnv() }, + (err) => resolve(!err) ) }) if (isGitRepo) { diff --git a/src/relay/git-handler.ts b/src/relay/git-handler.ts index 06bc00165..c710504e8 100644 --- a/src/relay/git-handler.ts +++ b/src/relay/git-handler.ts @@ -20,6 +20,7 @@ import { checkIgnoredPathsOp, detectConflictOperation, getStatusOp } from './git import { resolveRelayPushTarget } from './git-handler-push-target' import { normalizeGitErrorMessage, isNoUpstreamError } from '../shared/git-remote-error' import { loadGitHistoryFromExecutor } from '../shared/git-history' +import { buildRelayCommandEnv } from './relay-command-env' const execFileAsync = promisify(execFile) const MAX_GIT_BUFFER = 10 * 1024 * 1024 @@ -70,6 +71,7 @@ export class GitHandler { ): Promise<{ stdout: string; stderr: string }> { return execFileAsync('git', args, { cwd: expandTilde(cwd), + env: buildRelayCommandEnv(), encoding: 'utf-8', maxBuffer: opts?.maxBuffer ?? MAX_GIT_BUFFER }) @@ -78,6 +80,7 @@ export class GitHandler { private async gitBuffer(args: string[], cwd: string): Promise { const { stdout } = (await execFileAsync('git', args, { cwd, + env: buildRelayCommandEnv(), encoding: 'buffer', maxBuffer: MAX_GIT_BUFFER })) as { stdout: Buffer } diff --git a/src/relay/relay-command-env.test.ts b/src/relay/relay-command-env.test.ts new file mode 100644 index 000000000..3a53eae35 --- /dev/null +++ b/src/relay/relay-command-env.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { buildRelayCommandEnv } from './relay-command-env' + +describe('buildRelayCommandEnv', () => { + it('adds POSIX git locations when the relay starts with an empty PATH', () => { + const env = buildRelayCommandEnv({ HOME: '/home/me', PATH: '' }, 'linux') + + expect(env.PATH?.split(':')).toEqual( + expect.arrayContaining(['/usr/local/bin', '/usr/bin', '/bin']) + ) + expect(env.HOME).toBe('/home/me') + }) + + it('preserves Windows Path casing and adds Git install locations', () => { + const env = buildRelayCommandEnv({ Path: 'C:\\Tools' }, 'win32') + + expect(env.PATH).toBeUndefined() + expect(env.Path?.split(';')).toEqual( + expect.arrayContaining(['C:\\Tools', 'C:\\Program Files\\Git\\cmd']) + ) + }) +}) diff --git a/src/relay/relay-command-env.ts b/src/relay/relay-command-env.ts new file mode 100644 index 000000000..2939e660f --- /dev/null +++ b/src/relay/relay-command-env.ts @@ -0,0 +1,37 @@ +const POSIX_RELAY_PATH_FALLBACKS = ['/usr/local/bin', '/opt/homebrew/bin', '/usr/bin', '/bin'] +const WINDOWS_RELAY_PATH_FALLBACKS = [ + 'C:\\Program Files\\Git\\cmd', + 'C:\\Program Files\\Git\\bin', + 'C:\\Windows\\System32', + 'C:\\Windows' +] + +function getPathKey(env: NodeJS.ProcessEnv): 'PATH' | 'Path' { + return env.Path !== undefined && env.PATH === undefined ? 'Path' : 'PATH' +} + +function getPathDelimiter(platform: NodeJS.Platform): string { + return platform === 'win32' ? ';' : ':' +} + +function getFallbackSegments(platform: NodeJS.Platform): string[] { + return platform === 'win32' ? WINDOWS_RELAY_PATH_FALLBACKS : POSIX_RELAY_PATH_FALLBACKS +} + +export function buildRelayCommandEnv( + baseEnv: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform +): NodeJS.ProcessEnv { + const key = getPathKey(baseEnv) + const delimiter = getPathDelimiter(platform) + const segments = new Set((baseEnv[key] ?? '').split(delimiter).filter(Boolean)) + + for (const segment of getFallbackSegments(platform)) { + segments.add(segment) + } + + return { + ...baseEnv, + [key]: [...segments].join(delimiter) + } +}