Improve remote server project add flow (#4715)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-06-05 13:41:37 -07:00
committed by GitHub
co-authored by Orca
parent 5710bcaf1f
commit 577504f8c7
25 changed files with 1559 additions and 305 deletions
+21
View File
@@ -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<string, unknown>[] = []
const colorStore = {
+118 -41
View File
@@ -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<boolean> {
}
}
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<string, Set<TerminalWaiter>>()
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(
@@ -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<string, () => 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<RuntimeClientEventStreamMessage>(
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<void> {
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')
}
@@ -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<void>((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 })
})
}
})
]
@@ -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 {
+12
View File
@@ -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,
+2
View File
@@ -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
]
+2
View File
@@ -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',
@@ -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<HTMLDivElement>(null)
const radioFocusFrameRef = useRef<number | null>(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 (
<CreateProjectParentBrowser
runtimeEnvironmentId={runtimeEnvironmentId}
createParent={createParent}
onParentChange={onParentChange}
onClose={() => setBrowsingParent(false)}
/>
)
}
return (
<>
<DialogHeader>
@@ -378,54 +396,16 @@ export function CreateStep({
/>
</div>
{/* Location. The local flow uses a folder picker; runtime servers need
manual server-path entry because the client cannot browse that filesystem yet. */}
<div className="space-y-1">
<span className="text-[11px] font-medium text-muted-foreground block">Location</span>
{manualParentEntry ? (
<Input
value={createParent}
onChange={(e) => onParentChange(e.target.value)}
placeholder="/home/user/projects"
className="h-11 text-sm font-mono"
disabled={isCreating}
spellCheck={false}
/>
) : createParent ? (
<div className="group flex items-center gap-2.5 rounded-md border border-border bg-background/40 h-11 min-w-0 px-3 text-sm">
<span className="shrink-0 inline-flex items-center justify-center size-7 rounded-md border border-border/70 bg-background/50 text-muted-foreground">
<Home className="size-3.5" />
</span>
<span className="flex-1 min-w-0 truncate font-mono text-[12px]" title={createParent}>
{createParent}
</span>
<button
type="button"
onClick={onPickParent}
disabled={isCreating}
className="shrink-0 inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground transition-colors cursor-pointer disabled:cursor-not-allowed"
aria-label="Change parent folder"
>
<Pencil className="size-3" />
Change
</button>
</div>
) : (
<Button
type="button"
variant="outline"
onClick={onPickParent}
disabled={isCreating}
className="w-full h-11 justify-start text-sm text-muted-foreground font-normal gap-2.5"
>
<span className="shrink-0 inline-flex items-center justify-center size-7 rounded-md border border-border/70 bg-background/40">
<Folder className="size-3.5" />
</span>
Choose parent folder…
</Button>
)}
</div>
{/* The local picker returns client paths; runtime servers browse host paths via RPC. */}
<CreateProjectLocationField
createParent={createParent}
isCreating={isCreating}
manualParentEntry={manualParentEntry}
runtimeEnvironmentId={runtimeEnvironmentId}
onParentChange={onParentChange}
onPickParent={onPickParent}
onBrowseServer={() => setBrowsingParent(true)}
/>
{createError && (
<p className="text-[11px] text-destructive" role="alert">
@@ -301,6 +301,7 @@ const AddRepoDialog = React.memo(function AddRepoDialog() {
<AddRepoDialogStepContent
step={step}
isRuntimeEnvironmentActive={isRuntimeEnvironmentActive}
activeRuntimeEnvironmentId={settings?.activeRuntimeEnvironmentId}
isSshLikely={isSshLikely}
repoCount={repos.length}
isAdding={isAdding}
@@ -1,5 +1,6 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import type { ComponentProps } from 'react'
import { Dialog } from '@/components/ui/dialog'
import { TooltipProvider } from '@/components/ui/tooltip'
import { AddRepoDialogStepContent } from './AddRepoDialogStepContent'
@@ -21,71 +22,81 @@ const nestedScan: NestedRepoScanResult = {
timeoutMs: null
}
function renderNestedStep(repoCount: number): string {
type StepContentProps = ComponentProps<typeof AddRepoDialogStepContent>
function renderStepContent(overrides: Partial<StepContentProps>): 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(
<TooltipProvider>
<Dialog open>
<AddRepoDialogStepContent
step="nested"
isRuntimeEnvironmentActive={false}
isSshLikely={false}
repoCount={repoCount}
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={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()}
/>
<AddRepoDialogStepContent {...props} />
</Dialog>
</TooltipProvider>
)
}
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</button>')
})
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"')
})
})
@@ -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 (
<AddRepoServerPathStartStep
serverPath={serverPath}
runtimeEnvironmentId={activeRuntimeEnvironmentId}
isAddingServerPath={isAddingServerPath}
addProjectBusyLabel={addProjectBusyLabel}
onServerPathChange={onServerPathChange}
@@ -181,6 +185,7 @@ export function AddRepoDialogStepContent({
cloneProgress={cloneProgress}
isCloning={isCloning}
disableDestinationPicker={isRuntimeEnvironmentActive}
runtimeEnvironmentId={activeRuntimeEnvironmentId}
onUrlChange={onCloneUrlChange}
onDestChange={onCloneDestinationChange}
onPickDestination={onPickCloneDestination}
@@ -215,6 +220,7 @@ export function AddRepoDialogStepContent({
createError={createError}
isCreating={isCreating}
manualParentEntry={isRuntimeEnvironmentActive}
runtimeEnvironmentId={activeRuntimeEnvironmentId}
onNameChange={onCreateNameChange}
onParentChange={onCreateParentChange}
onKindChange={onCreateKindChange}
@@ -0,0 +1,233 @@
import { useState, type ComponentType } from 'react'
import { FolderOpen, Globe, Lightbulb, Loader2, Server } 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 AddRepoServerPathStartStepProps = {
serverPath: string
runtimeEnvironmentId: string | null | undefined
isAddingServerPath: boolean
addProjectBusyLabel: string | null
onServerPathChange: (path: string) => 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 (
<>
<DialogHeader>
<DialogTitle>Browse server filesystem</DialogTitle>
<DialogDescription>
Navigate to a directory and click Select to choose it.
</DialogDescription>
</DialogHeader>
<RemoteFileBrowser
runtimeEnvironmentId={runtimeEnvironmentId}
initialPath={serverPath || '~'}
onSelect={(path) => {
onServerPathChange(path)
setBrowsing(false)
setPathEntryOpen(true)
}}
onCancel={() => setBrowsing(false)}
/>
</>
)
}
if (!pathEntryOpen) {
const disabled = isAddingServerPath || !runtimeEnvironmentId
return (
<>
<DialogHeader>
<DialogTitle>Add a project</DialogTitle>
<DialogDescription>
Add another project from the selected runtime server.
</DialogDescription>
</DialogHeader>
<div className="space-y-3 pt-2">
<div className="grid grid-cols-3 gap-2">
<AddRepoServerStartAction
icon={FolderOpen}
title="Browse server"
description="Existing project or folder"
disabled={disabled}
onClick={() => setBrowsing(true)}
/>
<AddRepoServerStartAction
icon={Globe}
title="Clone from URL"
description="Remote Git repository"
disabled={disabled}
onClick={onOpenCloneStep}
/>
<AddRepoServerStartAction
icon={Server}
title="Create on server"
description="New repo or folder"
disabled={disabled}
onClick={onOpenCreateStep}
/>
</div>
<div className="flex items-center gap-3 rounded-md border border-border bg-muted px-3 py-2.5 text-xs text-muted-foreground">
<span className="grid size-7 shrink-0 place-items-center rounded-md bg-background text-foreground">
<Lightbulb className="size-3.5" />
</span>
<span className="min-w-0">
Want to import many repos at once? Browse to the parent folder.
</span>
</div>
<button
type="button"
onClick={() => setPathEntryOpen(true)}
disabled={disabled}
className="mx-auto block rounded px-2 py-1 text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-default disabled:opacity-40"
>
Or enter a server path manually
</button>
</div>
</>
)
}
return (
<>
<DialogHeader>
<DialogTitle>Open server project</DialogTitle>
<DialogDescription>
Add a Git repository or folder that already exists on the selected runtime server.
</DialogDescription>
</DialogHeader>
<div className="space-y-3 pt-2">
<div className="space-y-1">
<label
htmlFor="server-project-path"
className="block text-[11px] font-medium text-muted-foreground"
>
Server path
</label>
<div className="flex gap-2">
<Input
id="server-project-path"
value={serverPath}
onChange={(event) => 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}
/>
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
className="h-11 w-11 shrink-0"
onClick={() => setBrowsing(true)}
disabled={isAddingServerPath || !runtimeEnvironmentId}
aria-label="Browse server filesystem"
>
<FolderOpen className="size-4" />
</Button>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={4}>
Browse server filesystem
</TooltipContent>
</Tooltip>
</div>
</div>
<div className="grid grid-cols-2 gap-2">
<Button
onClick={() => onAddServerPath('git')}
disabled={!serverPath.trim() || isAddingServerPath}
className="h-10"
>
Add Git Project
</Button>
<Button
onClick={() => onAddServerPath('folder')}
disabled={!serverPath.trim() || isAddingServerPath}
variant="outline"
className="h-10"
>
Open as Folder
</Button>
</div>
{isAddingServerPath && addProjectBusyLabel ? (
<div className="flex items-center gap-2 rounded-md border border-border bg-muted px-3 py-2 text-xs text-muted-foreground">
<Loader2 className="size-3.5 shrink-0 animate-spin" />
<span>{addProjectBusyLabel}</span>
</div>
) : null}
<button
type="button"
onClick={() => setPathEntryOpen(false)}
disabled={isAddingServerPath}
className="mx-auto block rounded px-2 py-1 text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-default disabled:opacity-40"
>
Back to add options
</button>
</div>
</>
)
}
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 (
<Button
type="button"
variant="outline"
disabled={disabled}
onClick={onClick}
className="h-32 min-w-0 flex-col gap-3 whitespace-normal border-border/80 bg-background px-3 py-4 text-center"
>
<span className="grid size-9 shrink-0 place-items-center rounded-md text-muted-foreground">
<Icon className="size-5" />
</span>
<span className="min-w-0">
<span className="block text-[13px] font-semibold leading-5 text-foreground">{title}</span>
<span className="mt-0.5 block text-[11px] font-normal leading-4 text-muted-foreground">
{description}
</span>
</span>
</Button>
)
}
@@ -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(
<TooltipProvider>
<AddRepoServerPathStartStep
serverPath=""
runtimeEnvironmentId={runtimeEnvironmentId}
isAddingServerPath={false}
addProjectBusyLabel={null}
onServerPathChange={vi.fn()}
onAddServerPath={vi.fn()}
onOpenCloneStep={vi.fn()}
onOpenCreateStep={vi.fn()}
/>
</TooltipProvider>
)
}
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=""')
})
})
@@ -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 (
<>
<DialogHeader>
<DialogTitle>Add a server project</DialogTitle>
<DialogDescription>
Add a Git repository or folder that already exists on the selected runtime server.
</DialogDescription>
</DialogHeader>
<div className="space-y-3 pt-2">
<div className="space-y-1">
<label
htmlFor="server-project-path"
className="text-[11px] font-medium text-muted-foreground block"
>
Server path
</label>
<Input
id="server-project-path"
value={serverPath}
onChange={(event) => onServerPathChange(event.target.value)}
placeholder="/home/user/project"
className="h-11 text-sm font-mono"
disabled={isAddingServerPath}
autoFocus
spellCheck={false}
/>
</div>
<div className="grid grid-cols-2 gap-2">
<Button
onClick={() => onAddServerPath('git')}
disabled={!serverPath.trim() || isAddingServerPath}
className="h-10"
>
Add Git Project
</Button>
<Button
onClick={() => onAddServerPath('folder')}
disabled={!serverPath.trim() || isAddingServerPath}
variant="outline"
className="h-10"
>
Open as Folder
</Button>
</div>
{isAddingServerPath && addProjectBusyLabel ? (
<div className="flex items-center gap-2 rounded-md border border-border bg-muted px-3 py-2 text-xs text-muted-foreground">
<Loader2 className="size-3.5 shrink-0 animate-spin" />
<span>{addProjectBusyLabel}</span>
</div>
) : null}
<div className="flex items-center justify-center gap-4 pt-1">
<button
type="button"
onClick={onOpenCloneStep}
disabled={isAddingServerPath}
className="text-xs text-muted-foreground hover:text-foreground transition-colors cursor-pointer rounded focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-default disabled:opacity-40"
>
Clone into server path
</button>
<button
type="button"
onClick={onOpenCreateStep}
disabled={isAddingServerPath}
className="text-xs text-muted-foreground hover:text-foreground transition-colors cursor-pointer rounded focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-default disabled:opacity-40"
>
Create on server
</button>
</div>
</div>
</>
)
}
type AddRepoLocalStartStepProps = {
repoCount: number
isSshLikely: boolean
@@ -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<HTMLInputElement>): void => {
if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
@@ -283,6 +287,29 @@ export function CloneStep({
}
}
}
if (browsingDestination && runtimeEnvironmentId) {
return (
<>
<DialogHeader>
<DialogTitle>Browse server filesystem</DialogTitle>
<DialogDescription>
Navigate to a directory and click Select to choose it.
</DialogDescription>
</DialogHeader>
<RemoteFileBrowser
runtimeEnvironmentId={runtimeEnvironmentId}
initialPath={cloneDestination || '~'}
onSelect={(path) => {
onDestChange(path)
setBrowsingDestination(false)
}}
onCancel={() => setBrowsingDestination(false)}
/>
</>
)
}
return (
<>
<DialogHeader>
@@ -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'}
>
<Folder className="size-3.5" />
</Button>
@@ -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 (
<>
<DialogHeader>
<DialogTitle>Browse server filesystem</DialogTitle>
<DialogDescription>
Navigate to a directory and click Select to choose it.
</DialogDescription>
</DialogHeader>
<RemoteFileBrowser
runtimeEnvironmentId={runtimeEnvironmentId}
initialPath={createParent || '~'}
onSelect={(path) => {
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 (
<div className="space-y-1">
<span className="text-[11px] font-medium text-muted-foreground block">Location</span>
{manualParentEntry ? (
<div className="flex gap-2">
<Input
value={createParent}
onChange={(e) => onParentChange(e.target.value)}
placeholder="/home/user/projects"
className="h-11 min-w-0 flex-1 text-sm font-mono"
disabled={isCreating}
spellCheck={false}
/>
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
className="h-11 w-11 shrink-0"
onClick={onBrowseServer}
disabled={isCreating || !runtimeEnvironmentId}
aria-label="Browse server filesystem"
>
<FolderOpen className="size-4" />
</Button>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={4}>
Browse server filesystem
</TooltipContent>
</Tooltip>
</div>
) : createParent ? (
<div className="group flex items-center gap-2.5 rounded-md border border-border bg-background/40 h-11 min-w-0 px-3 text-sm">
<span className="shrink-0 inline-flex items-center justify-center size-7 rounded-md border border-border/70 bg-background/50 text-muted-foreground">
<Home className="size-3.5" />
</span>
<span className="flex-1 min-w-0 truncate font-mono text-[12px]" title={createParent}>
{createParent}
</span>
<button
type="button"
onClick={onPickParent}
disabled={isCreating}
className="shrink-0 inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground transition-colors cursor-pointer disabled:cursor-not-allowed"
aria-label="Change parent folder"
>
<Pencil className="size-3" />
Change
</button>
</div>
) : (
<Button
type="button"
variant="outline"
onClick={onPickParent}
disabled={isCreating}
className="w-full h-11 justify-start text-sm text-muted-foreground font-normal gap-2.5"
>
<span className="shrink-0 inline-flex items-center justify-center size-7 rounded-md border border-border/70 bg-background/40">
<Folder className="size-3.5" />
</span>
Choose parent folder...
</Button>
)}
</div>
)
}
@@ -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
}
+215
View File
@@ -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<typeof ReactModule>('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
+141 -56
View File
@@ -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<typeof setTimeout> | null = null
let runtimeClientEventsUnsubscribe: (() => void) | null = null
let runtimeClientEventsEnvironmentId: string | null = null
let runtimeClientEventsGeneration = 0
unsubs.push(attachMobileMarkdownBridge())
const handleWorktreesChanged = async (repoId: string): Promise<void> => {
// 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<RuntimeClientEvent, { type: 'activateWorktree' }>,
options: { allowRuntimeEnvironment: boolean }
): Promise<void> => {
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)
})
})
@@ -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)
})
})
@@ -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<RuntimeClientEventSubscription> {
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<unknown>,
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'
)
}
@@ -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
})
})
})
@@ -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<RuntimeServerDirectoryListing> {
return callRuntimeRpc<RuntimeServerDirectoryListing>(
{ kind: 'environment', environmentId },
'files.browseServerDir',
{ path },
{ timeoutMs: 15_000 }
)
}
+48
View File
@@ -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<RuntimeClientEvent, { type: 'activateWorktree' }>
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 } : {})
}
}