fix(onboarding): stop wrong-host Open as Folder fallback (#6393)

* fix(onboarding): stop wrong-host folder fallback (#6367)

* test(repos): isolate runtime fallback proofs

* test(repos): cover runtime status RPC failures

* test(repos): drop obsolete max-lines suppression

* Prevent runtime path probes from leaking project groups

* fix(onboarding): gate runtime folder fallback status

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com>
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Rod Boev
2026-06-25 18:42:46 -07:00
committed by GitHub
co-authored by Orca Jinwoo-H
parent 6881475532
commit a12566b962
16 changed files with 647 additions and 32 deletions
+5
View File
@@ -793,6 +793,11 @@ const FolderWorkspacePathStatusArgs = z.discriminatedUnion('scope', [
z.object({
scope: z.literal('project-group'),
projectGroupId: z.string().min(1)
}),
z.object({
scope: z.literal('path'),
path: z.string().min(1),
connectionId: z.string().min(1).nullable().optional()
})
])
@@ -4,6 +4,7 @@ import { tmpdir } from 'os'
import { join } from 'path'
import { describe, expect, it, vi } from 'vitest'
import {
getFolderWorkspacePathStatus,
getFolderWorkspacePathStatusForPath,
inferFolderWorkspacePathConnection
} from './folder-workspace-path-status'
@@ -185,6 +186,25 @@ describe('folder workspace path status', () => {
).toEqual({ kind: 'ambiguous' })
})
it('supports direct path scope without a persisted project group', async () => {
const provider = {
stat: vi.fn().mockResolvedValue({ size: 0, type: 'directory', mtime: 1 })
} as unknown as IFilesystemProvider
await expect(
getFolderWorkspacePathStatus(
{
getRepos: () => [makeRepo({ connectionId: 'ssh-1' })],
getProjectGroups: () => [],
getFolderWorkspaces: () => []
},
{ scope: 'path', path: '/workspace/platform', connectionId: 'ssh-1' },
{ getSshFilesystemProvider: () => provider }
)
).resolves.toEqual({ path: '/workspace/platform', exists: true })
expect(provider.stat).toHaveBeenCalledWith('/workspace/platform')
})
it('keeps explicit SSH scopes isolated from unrelated same-path SSH repos', async () => {
const provider = {
stat: vi.fn().mockResolvedValue({ size: 0, type: 'directory', mtime: 1 })
@@ -25,18 +25,22 @@ type FolderWorkspacePathStatusDeps = {
function getFolderScopeCandidateRepos(args: {
folderPath: string
projectGroupId: string
projectGroupId?: string | null
connectionId?: string | null
projectGroups: readonly ProjectGroup[]
repos: readonly Repo[]
}): Repo[] {
const groupIds = getProjectGroupSubtreeIds(args.projectGroups, args.projectGroupId)
const groupRepos = args.repos.filter(
(repo) => typeof repo.projectGroupId === 'string' && groupIds.has(repo.projectGroupId)
)
const groupIds = args.projectGroupId
? getProjectGroupSubtreeIds(args.projectGroups, args.projectGroupId)
: null
const groupRepos = groupIds
? args.repos.filter(
(repo) => typeof repo.projectGroupId === 'string' && groupIds.has(repo.projectGroupId)
)
: []
const pathRepos = args.repos.filter(
(repo) =>
!(typeof repo.projectGroupId === 'string' && groupIds.has(repo.projectGroupId)) &&
!(groupIds && typeof repo.projectGroupId === 'string' && groupIds.has(repo.projectGroupId)) &&
isPathInsideOrEqual(args.folderPath, repo.path)
)
if (args.connectionId) {
@@ -57,7 +61,7 @@ function getFolderScopeCandidateRepos(args: {
export function inferFolderWorkspacePathConnection(args: {
folderPath: string
projectGroupId: string
projectGroupId?: string | null
connectionId?: string | null
projectGroups: readonly ProjectGroup[]
repos: readonly Repo[]
@@ -134,7 +138,7 @@ async function statFolderPath(
export async function getFolderWorkspacePathStatusForPath(
args: {
folderPath: string
projectGroupId: string
projectGroupId?: string | null
connectionId?: string | null
projectGroups: readonly ProjectGroup[]
repos: readonly Repo[]
@@ -148,7 +152,7 @@ export async function getFolderWorkspacePathStatusForPath(
export function resolveFolderWorkspaceStatusPath(args: {
store: FolderWorkspacePathStatusStore
request: FolderWorkspacePathStatusRequest
}): { folderPath: string; projectGroupId: string; connectionId?: string | null } {
}): { folderPath: string; projectGroupId: string | null; connectionId?: string | null } {
const { request } = args
if (request.scope === 'project-group') {
const group = args.store
@@ -164,6 +168,14 @@ export function resolveFolderWorkspaceStatusPath(args: {
}
}
if (request.scope === 'path') {
return {
folderPath: request.path,
projectGroupId: null,
connectionId: request.connectionId ?? null
}
}
const workspace = args.store
.getFolderWorkspaces?.()
.find((entry) => entry.id === request.folderWorkspaceId)
@@ -58,6 +58,11 @@ const FolderWorkspacePathStatus = z.discriminatedUnion('scope', [
z.object({
scope: z.literal('project-group'),
projectGroupId: requiredString('Missing project group id')
}),
z.object({
scope: z.literal('path'),
path: requiredString('Missing folder path'),
connectionId: OptionalString.nullable().optional()
})
])
+14
View File
@@ -418,6 +418,12 @@ describe('repo RPC methods', () => {
folderWorkspaceId: 'folder-workspace-1'
})
)
const directPathStatusResponse = await dispatcher.dispatch(
makeRequest('folderWorkspace.getPathStatus', {
scope: 'path',
path: '/srv/platform'
})
)
expect(runtime.listProjectGroups).toHaveBeenCalled()
expect(runtime.createProjectGroup).toHaveBeenCalledWith({
@@ -444,6 +450,10 @@ describe('repo RPC methods', () => {
scope: 'folder-workspace',
folderWorkspaceId: 'folder-workspace-1'
})
expect(runtime.getFolderWorkspacePathStatus).toHaveBeenCalledWith({
scope: 'path',
path: '/srv/platform'
})
expect(moveResponse).toMatchObject({
ok: true,
result: { repo: { id: 'repo-1', projectGroupId: group.id } }
@@ -458,6 +468,10 @@ describe('repo RPC methods', () => {
ok: true,
result: { status: { path: '/srv/platform', exists: true } }
})
expect(directPathStatusResponse).toMatchObject({
ok: true,
result: { status: { path: '/srv/platform', exists: true } }
})
})
it('allows separate nested-repo imports without a group name', async () => {
@@ -0,0 +1,112 @@
import { renderToStaticMarkup } from 'react-dom/server'
import type * as ReactModule from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
type ButtonCapture = {
label: string
onClick?: () => unknown
}
const mocks = vi.hoisted(() => ({
buttons: [] as ButtonCapture[],
state: {
activeModal: 'confirm-non-git-folder',
modalData: {
folderPath: '/srv/non-git',
runtimeEnvironmentId: 'env-1'
} as Record<string, unknown>,
closeModal: vi.fn(),
addNonGitFolder: vi.fn(),
runtimeEnvironments: [{ id: 'env-1', name: 'Remote Mac' }]
}
}))
function textContent(node: ReactModule.ReactNode): string {
if (node == null || typeof node === 'boolean') {
return ''
}
if (typeof node === 'string' || typeof node === 'number') {
return String(node)
}
if (Array.isArray(node)) {
return node.map(textContent).join('')
}
if (typeof node === 'object' && 'props' in node) {
return textContent((node as { props?: { children?: ReactModule.ReactNode } }).props?.children)
}
return ''
}
vi.mock('@/store', () => {
const useAppStore = Object.assign(
(selector: (state: typeof mocks.state) => unknown) => selector(mocks.state),
{
getState: () => mocks.state,
setState: (next: Partial<typeof mocks.state>) => {
Object.assign(mocks.state, next)
}
}
)
return { useAppStore }
})
vi.mock('@/components/ui/dialog', () => ({
Dialog: ({ open, children }: { open: boolean; children: ReactModule.ReactNode }) =>
open ? <div>{children}</div> : null,
DialogContent: ({ children }: { children: ReactModule.ReactNode }) => <div>{children}</div>,
DialogDescription: ({ children }: { children: ReactModule.ReactNode }) => <p>{children}</p>,
DialogFooter: ({ children }: { children: ReactModule.ReactNode }) => <footer>{children}</footer>,
DialogHeader: ({ children }: { children: ReactModule.ReactNode }) => <header>{children}</header>,
DialogTitle: ({ children }: { children: ReactModule.ReactNode }) => <h1>{children}</h1>
}))
vi.mock('@/components/ui/button', () => ({
Button: ({ children, onClick }: { children: ReactModule.ReactNode; onClick?: () => unknown }) => {
mocks.buttons.push({ label: textContent(children), onClick })
return <button onClick={onClick}>{children}</button>
}
}))
vi.mock('sonner', () => ({
toast: {
error: vi.fn()
}
}))
vi.mock('@/lib/worktree-activation', () => ({
activateAndRevealWorktree: vi.fn()
}))
import NonGitFolderDialog from './NonGitFolderDialog'
describe('NonGitFolderDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.buttons.length = 0
mocks.state.activeModal = 'confirm-non-git-folder'
mocks.state.modalData = {
folderPath: '/srv/non-git',
runtimeEnvironmentId: 'env-1'
}
mocks.state.runtimeEnvironments = [{ id: 'env-1', name: 'Remote Mac' }]
})
it('shows the checked host in the folder confirmation', () => {
const html = renderToStaticMarkup(<NonGitFolderDialog />)
expect(html).toContain('Remote Mac')
expect(html).toContain('/srv/non-git')
})
it('confirms runtime folder imports on the checked host', () => {
renderToStaticMarkup(<NonGitFolderDialog />)
const button = mocks.buttons.find((entry) => entry.label.includes('Open as Folder'))
button?.onClick?.()
expect(mocks.state.addNonGitFolder).toHaveBeenCalledWith('/srv/non-git', {
runtimeEnvironmentId: 'env-1'
})
expect(mocks.state.closeModal).toHaveBeenCalled()
})
})
@@ -20,10 +20,32 @@ const NonGitFolderDialog = React.memo(function NonGitFolderDialog() {
const modalData = useAppStore((s) => s.modalData)
const closeModal = useAppStore((s) => s.closeModal)
const addNonGitFolder = useAppStore((s) => s.addNonGitFolder)
const runtimeEnvironments = useAppStore((s) => s.runtimeEnvironments)
const isOpen = activeModal === 'confirm-non-git-folder'
const folderPath = typeof modalData.folderPath === 'string' ? modalData.folderPath : ''
const connectionId = typeof modalData.connectionId === 'string' ? modalData.connectionId : ''
const runtimeEnvironmentId =
typeof modalData.runtimeEnvironmentId === 'string' ? modalData.runtimeEnvironmentId : ''
const runtimeEnvironmentName =
runtimeEnvironmentId &&
(runtimeEnvironments.find((environment) => environment.id === runtimeEnvironmentId)?.name ||
runtimeEnvironmentId)
const checkedHostDescription = connectionId
? translate(
'auto.components.sidebar.NonGitFolderDialog.9a766f33ac',
'This path was checked on the SSH host.'
)
: runtimeEnvironmentName
? translate(
'auto.components.sidebar.NonGitFolderDialog.79fd02cf5f',
'This path was checked on {{hostName}}.',
{ hostName: runtimeEnvironmentName }
)
: translate(
'auto.components.sidebar.NonGitFolderDialog.8851b77327',
'This path was checked locally.'
)
const handleConfirm = useCallback(() => {
if (connectionId && folderPath) {
@@ -79,10 +101,12 @@ const NonGitFolderDialog = React.memo(function NonGitFolderDialog() {
}
})()
} else if (folderPath) {
void addNonGitFolder(folderPath)
void addNonGitFolder(folderPath, {
runtimeEnvironmentId: runtimeEnvironmentId || null
})
}
closeModal()
}, [addNonGitFolder, closeModal, folderPath, connectionId])
}, [addNonGitFolder, closeModal, folderPath, connectionId, runtimeEnvironmentId])
const handleOpenChange = useCallback(
(open: boolean) => {
@@ -105,6 +129,7 @@ const NonGitFolderDialog = React.memo(function NonGitFolderDialog() {
'auto.components.sidebar.NonGitFolderDialog.8fba4b8cbb',
"This folder isn't a Git repository. You'll have the editor, terminal, and search, but Git-based features won't be available."
)}
<span className="mt-2 block">{checkedHostDescription}</span>
</DialogDescription>
</DialogHeader>
+8 -2
View File
@@ -230,13 +230,16 @@
"81f13f48d2": "Git could not safely delete branch \"{{value0}}\" after deleting worktree \"{{value1}}\", so Orca kept it to avoid losing local commits."
},
"repos": {
"2975400634": "Update Orca server to open non-Git folders on this runtime.",
"b7e14472ae": "Failed to add folder",
"e649269645": "Use Add Project to enter a path on the selected host.",
"c6e022ddfc": "Failed to add project",
"90d129b48b": "Folder added",
"8bb3ad7935": "Project added",
"a8e4b3af5b": "Project already added",
"6d3318e813": "Failed to import repositories"
"6d3318e813": "Failed to import repositories",
"3be0f7df04": "Cannot open folder on selected runtime",
"15cf5319ec": "{{path}} was checked on {{hostName}}, but that host did not report a usable folder."
},
"settings": {
"e12dab333b": "Failed to switch servers",
@@ -3546,7 +3549,10 @@
"e52454b7f6": "Open as Folder",
"05b33a17a9": "Cancel",
"8fba4b8cbb": "This folder isn't a Git repository. You'll have the editor, terminal, and search, but Git-based features won't be available.",
"c49fb13492": "Failed to add folder on this host"
"c49fb13492": "Failed to add folder on this host",
"9a766f33ac": "This path was checked on the SSH host.",
"79fd02cf5f": "This path was checked on {{hostName}}.",
"8851b77327": "This path was checked locally."
},
"OrcaYamlTrustDialog": {
"f3e2b868fb": "Run hooks",
+8 -2
View File
@@ -230,13 +230,16 @@
"81f13f48d2": "Git no pudo eliminar de forma segura la rama \"{{value0}}\" después de eliminar el árbol de trabajo \"{{value1}}\", por lo que Orca la conservó para evitar perder commits locales."
},
"repos": {
"2975400634": "Update Orca server to open non-Git folders on this runtime.",
"b7e14472ae": "No se pudo agregar la carpeta",
"e649269645": "Utilice una ruta de servidor para agregar proyectos desde un tiempo de ejecución remoto.",
"c6e022ddfc": "No se pudo agregar el proyecto",
"90d129b48b": "Carpeta agregada",
"8bb3ad7935": "Proyecto agregado",
"a8e4b3af5b": "Proyecto ya agregado",
"6d3318e813": "No se pudieron importar repositorios"
"6d3318e813": "No se pudieron importar repositorios",
"3be0f7df04": "Cannot open folder on selected runtime",
"15cf5319ec": "{{path}} was checked on {{hostName}}, but that host did not report a usable folder."
},
"settings": {
"e12dab333b": "No se pudo cambiar de servidor",
@@ -3540,7 +3543,10 @@
"e52454b7f6": "Abrir como carpeta",
"05b33a17a9": "Cancelar",
"8fba4b8cbb": "Esta carpeta no es un repositorio de Git. Tendrás el editor, la terminal y la búsqueda, pero las funciones basadas en Git no estarán disponibles.",
"c49fb13492": "No se pudo agregar la carpeta remota"
"c49fb13492": "No se pudo agregar la carpeta remota",
"9a766f33ac": "This path was checked on the SSH host.",
"79fd02cf5f": "This path was checked on {{hostName}}.",
"8851b77327": "This path was checked locally."
},
"OrcaYamlTrustDialog": {
"f3e2b868fb": "Ejecutar ganchos",
+8 -2
View File
@@ -230,13 +230,16 @@
"81f13f48d2": "ワークツリー\"{{value1}}\"を削除した後、Git はブランチ\"{{value0}}\"を安全に削除できなかったため、Orca はローカルコミットを失わないように保持しました。"
},
"repos": {
"2975400634": "Update Orca server to open non-Git folders on this runtime.",
"b7e14472ae": "フォルダーの追加に失敗しました",
"e649269645": "サーバー パスを使用して、リモート ランタイムからプロジェクトを追加します。",
"c6e022ddfc": "プロジェクトの追加に失敗しました",
"90d129b48b": "フォルダーが追加されました",
"8bb3ad7935": "プロジェクトを追加しました",
"a8e4b3af5b": "プロジェクトはすでに追加されています",
"6d3318e813": "repos のインポートに失敗しました"
"6d3318e813": "repos のインポートに失敗しました",
"3be0f7df04": "Cannot open folder on selected runtime",
"15cf5319ec": "{{path}} was checked on {{hostName}}, but that host did not report a usable folder."
},
"settings": {
"e12dab333b": "サーバーの切り替えに失敗しました",
@@ -3521,7 +3524,10 @@
"e52454b7f6": "フォルダーとして開く",
"05b33a17a9": "キャンセル",
"8fba4b8cbb": "このフォルダーは Git repos ではありません。エディター、terminal、検索は利用できますが、Git ベースの機能は利用できません。",
"c49fb13492": "リモートフォルダーの追加に失敗しました"
"c49fb13492": "リモートフォルダーの追加に失敗しました",
"9a766f33ac": "This path was checked on the SSH host.",
"79fd02cf5f": "This path was checked on {{hostName}}.",
"8851b77327": "This path was checked locally."
},
"OrcaYamlTrustDialog": {
"f3e2b868fb": "フックを実行する",
+8 -2
View File
@@ -230,13 +230,16 @@
"81f13f48d2": "\"{{value1}}\" 워크트리를 삭제한 후 Git이 \"{{value0}}\" 브랜치를 안전하게 삭제할 수 없어 Orca가 로컬 커밋 손실을 방지하기 위해 유지했습니다."
},
"repos": {
"2975400634": "Update Orca server to open non-Git folders on this runtime.",
"b7e14472ae": "폴더를 추가하지 못했습니다.",
"e649269645": "선택한 호스트에 경로를 입력하려면 프로젝트 추가를 사용하세요.",
"c6e022ddfc": "프로젝트를 추가하지 못했습니다.",
"90d129b48b": "폴더가 추가됨",
"8bb3ad7935": "프로젝트가 추가됨",
"a8e4b3af5b": "프로젝트가 이미 추가되었습니다.",
"6d3318e813": "repos를 가져오지 못했습니다."
"6d3318e813": "repos를 가져오지 못했습니다.",
"3be0f7df04": "Cannot open folder on selected runtime",
"15cf5319ec": "{{path}} was checked on {{hostName}}, but that host did not report a usable folder."
},
"settings": {
"e12dab333b": "서버를 전환하지 못했습니다.",
@@ -3521,7 +3524,10 @@
"e52454b7f6": "폴더로 열기",
"05b33a17a9": "취소",
"8fba4b8cbb": "이 폴더는 Git repos가 아닙니다. 편집기, terminal, 검색 기능은 제공되지만 Git 기반 기능은 사용할 수 없습니다.",
"c49fb13492": "이 호스트에 폴더를 추가하지 못했습니다."
"c49fb13492": "이 호스트에 폴더를 추가하지 못했습니다.",
"9a766f33ac": "This path was checked on the SSH host.",
"79fd02cf5f": "This path was checked on {{hostName}}.",
"8851b77327": "This path was checked locally."
},
"OrcaYamlTrustDialog": {
"f3e2b868fb": "후크 실행",
+8 -2
View File
@@ -230,13 +230,16 @@
"81f13f48d2": "删除工作树\"{{value1}}\"后,Git 无法安全删除分支\"{{value0}}\",因此 Orca 将其保留以避免丢失本地提交。"
},
"repos": {
"2975400634": "Update Orca server to open non-Git folders on this runtime.",
"b7e14472ae": "添加文件夹失败",
"e649269645": "使用\"添加项目\"在所选主机上输入路径。",
"c6e022ddfc": "添加项目失败",
"90d129b48b": "文件夹已添加",
"8bb3ad7935": "项目已添加",
"a8e4b3af5b": "项目已添加过了",
"6d3318e813": "导入存储库失败"
"6d3318e813": "导入存储库失败",
"3be0f7df04": "Cannot open folder on selected runtime",
"15cf5319ec": "{{path}} was checked on {{hostName}}, but that host did not report a usable folder."
},
"settings": {
"e12dab333b": "切换服务器失败",
@@ -3521,7 +3524,10 @@
"e52454b7f6": "作为文件夹打开",
"05b33a17a9": "取消",
"8fba4b8cbb": "此文件夹不是 Git 存储库。您将拥有编辑器、终端和搜索,但基于 Git 的功能将不可用。",
"c49fb13492": "添加远程文件夹失败"
"c49fb13492": "添加远程文件夹失败",
"9a766f33ac": "This path was checked on the SSH host.",
"79fd02cf5f": "This path was checked on {{hostName}}.",
"8851b77327": "This path was checked locally."
},
"OrcaYamlTrustDialog": {
"f3e2b868fb": "运行钩子",
@@ -0,0 +1,282 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createTestStore } from './store-test-helpers'
import type { Repo } from '../../../../shared/types'
import {
FOLDER_WORKSPACE_PATH_STATUS_RUNTIME_CAPABILITY,
RUNTIME_CAPABILITIES
} from '../../../../shared/protocol-version'
import {
createCompatibleRuntimeStatusResponse,
createCompatibleRuntimeStatusResponseIfNeeded,
type RuntimeEnvironmentCallRequest
} from '../../runtime/runtime-compatibility-test-fixture'
import { clearRuntimeCompatibilityCacheForTests } from '../../runtime/runtime-rpc-client'
const toastError = vi.hoisted(() => vi.fn())
const toastInfo = vi.hoisted(() => vi.fn())
const toastSuccess = vi.hoisted(() => vi.fn())
vi.mock('sonner', () => ({
toast: {
error: toastError,
info: toastInfo,
success: toastSuccess
}
}))
const remoteRepo: Repo = {
id: 'remote-repo',
path: '/remote',
displayName: 'Remote',
badgeColor: '#111',
addedAt: 2
}
const runtimeEnvironmentCall = vi.fn()
const runtimeEnvironmentTransportCall = vi.fn()
beforeEach(() => {
clearRuntimeCompatibilityCacheForTests()
runtimeEnvironmentCall.mockReset()
runtimeEnvironmentTransportCall.mockReset()
toastError.mockReset()
toastInfo.mockReset()
toastSuccess.mockReset()
runtimeEnvironmentTransportCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
return createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args)
})
vi.stubGlobal('window', {
api: {
runtimeEnvironments: { call: runtimeEnvironmentTransportCall }
}
})
})
describe('repo slice runtime folder fallback', () => {
it('blocks wrong-host runtime fallback', async () => {
runtimeEnvironmentCall.mockImplementation((request: RuntimeEnvironmentCallRequest) => {
const { method } = request
if (method === 'repo.add') {
return {
id: 'rpc-add-git',
ok: false,
error: { code: 'repo.invalid', message: 'Not a valid git repository' },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (method === 'folderWorkspace.getPathStatus') {
return {
id: 'rpc-path-status',
ok: true,
result: {
status: {
path: '/Users/me/GitHub/travel-hub',
exists: false,
reason: 'missing'
}
},
_meta: { runtimeId: 'runtime-remote' }
}
}
if (method === 'projectGroup.delete') {
return {
id: 'rpc-delete-status-scope',
ok: true,
result: { deleted: true },
_meta: { runtimeId: 'runtime-remote' }
}
}
throw new Error(`Unexpected runtime method ${method}`)
})
const store = createTestStore()
store.setState({
settings: { activeRuntimeEnvironmentId: 'env-1' } as never,
runtimeEnvironments: [{ id: 'env-1', name: 'Remote Mac' }] as never
})
await expect(
store.getState().addRepoPath('/Users/me/GitHub/travel-hub', 'git')
).resolves.toBeNull()
expect(store.getState().activeModal).not.toBe('confirm-non-git-folder')
expect(runtimeEnvironmentCall).toHaveBeenCalledWith({
selector: 'env-1',
method: 'folderWorkspace.getPathStatus',
params: { scope: 'path', path: '/Users/me/GitHub/travel-hub' },
timeoutMs: 15_000
})
expect(toastError).toHaveBeenCalledWith(
'Cannot open folder on selected runtime',
expect.objectContaining({
description: expect.stringContaining('Remote Mac')
})
)
})
it('treats runtime status RPC failures as host-scoped errors', async () => {
runtimeEnvironmentCall.mockImplementation((request: RuntimeEnvironmentCallRequest) => {
const { method } = request
if (method === 'repo.add') {
return {
id: 'rpc-add-git',
ok: false,
error: { code: 'repo.invalid', message: 'Not a valid git repository' },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (method === 'folderWorkspace.getPathStatus') {
throw new Error('status unavailable')
}
throw new Error(`Unexpected runtime method ${method}`)
})
const store = createTestStore()
store.setState({
settings: { activeRuntimeEnvironmentId: 'env-1' } as never,
runtimeEnvironments: [{ id: 'env-1', name: 'Remote Mac' }] as never
})
await expect(
store.getState().addRepoPath('/Users/me/GitHub/travel-hub', 'git')
).resolves.toBeNull()
expect(store.getState().activeModal).not.toBe('confirm-non-git-folder')
expect(toastError).toHaveBeenCalledWith(
'Cannot open folder on selected runtime',
expect.objectContaining({
description: expect.stringContaining('Remote Mac')
})
)
})
it('reports an update error when the checked runtime lacks raw path status support', async () => {
runtimeEnvironmentTransportCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
if (args.method === 'status.get') {
const response = createCompatibleRuntimeStatusResponse()
if (!response.ok) {
throw new Error('Expected compatible runtime status fixture')
}
return {
...response,
result: {
...response.result,
capabilities: RUNTIME_CAPABILITIES.filter(
(capability) => capability !== FOLDER_WORKSPACE_PATH_STATUS_RUNTIME_CAPABILITY
)
}
}
}
return runtimeEnvironmentCall(args)
})
runtimeEnvironmentCall.mockImplementation((request: RuntimeEnvironmentCallRequest) => {
const { method } = request
if (method === 'repo.add') {
return {
id: 'rpc-add-git',
ok: false,
error: { code: 'repo.invalid', message: 'Not a valid git repository' },
_meta: { runtimeId: 'runtime-remote' }
}
}
throw new Error(`Unexpected runtime method ${method}`)
})
const store = createTestStore()
store.setState({
settings: { activeRuntimeEnvironmentId: 'env-1' } as never,
runtimeEnvironments: [{ id: 'env-1', name: 'Remote Mac' }] as never
})
await expect(store.getState().addRepoPath('/srv/non-git', 'git')).resolves.toBeNull()
expect(store.getState().activeModal).not.toBe('confirm-non-git-folder')
expect(runtimeEnvironmentCall).not.toHaveBeenCalledWith(
expect.objectContaining({
method: 'folderWorkspace.getPathStatus'
})
)
expect(toastError).toHaveBeenCalledWith(
'Failed to add project',
expect.objectContaining({
description: 'Update Orca server to open non-Git folders on this runtime.'
})
)
})
it('keeps runtime folder fallback on the checked host', async () => {
const folderRepo: Repo = {
...remoteRepo,
id: 'runtime-folder',
path: '/srv/non-git',
displayName: 'non-git',
kind: 'folder'
}
runtimeEnvironmentCall.mockImplementation((request) => {
const { selector, method, params } = request as {
selector: string
method: string
params?: unknown
}
if (method === 'repo.add' && (params as { kind?: string }).kind === 'git') {
return {
id: 'rpc-add-git',
ok: false,
error: { code: 'repo.invalid', message: 'Not a valid git repository' },
_meta: { runtimeId: 'runtime-remote' }
}
}
if (method === 'repo.add' && (params as { kind?: string }).kind === 'folder') {
return {
id: 'rpc-add-folder',
ok: true,
result: { repo: folderRepo },
_meta: { runtimeId: `runtime-${selector}` }
}
}
if (method === 'folderWorkspace.getPathStatus') {
return {
id: 'rpc-path-status',
ok: true,
result: {
status: {
path: '/srv/non-git',
exists: true
}
},
_meta: { runtimeId: 'runtime-remote' }
}
}
throw new Error(`Unexpected runtime method ${method}`)
})
const store = createTestStore()
store.setState({
settings: { activeRuntimeEnvironmentId: 'env-1' } as never,
fetchWorktrees: vi.fn().mockResolvedValue(undefined) as never
})
await expect(store.getState().addRepoPath('/srv/non-git', 'git')).resolves.toBeNull()
expect(store.getState().activeModal).toBe('confirm-non-git-folder')
expect(store.getState().modalData).toEqual({
folderPath: '/srv/non-git',
runtimeEnvironmentId: 'env-1'
})
store.setState({ settings: { activeRuntimeEnvironmentId: 'env-2' } as never })
await expect(
store.getState().addNonGitFolder('/srv/non-git', { runtimeEnvironmentId: 'env-1' })
).resolves.toEqual({ ...folderRepo, executionHostId: 'runtime:env-1' })
expect(runtimeEnvironmentCall).toHaveBeenCalledWith({
selector: 'env-1',
method: 'repo.add',
params: { path: '/srv/non-git', kind: 'folder' },
timeoutMs: 15_000
})
expect(runtimeEnvironmentCall).not.toHaveBeenCalledWith(
expect.objectContaining({
selector: 'env-2',
method: 'repo.add',
params: { path: '/srv/non-git', kind: 'folder' }
})
)
})
})
+116 -10
View File
@@ -30,6 +30,7 @@ import {
type ProjectHostSetupProjection
} from '../../../../shared/project-host-setup-projection'
import {
FOLDER_WORKSPACE_PATH_STATUS_RUNTIME_CAPABILITY,
PROJECT_HOST_SETUP_RUNTIME_CAPABILITY,
WORKSPACE_RUN_CONTEXT_RUNTIME_CAPABILITY
} from '../../../../shared/protocol-version'
@@ -905,9 +906,13 @@ function settingsForRepoOwner(state: Pick<AppState, 'repos' | 'settings'>, repoI
}
function getFolderWorkspacePathStatusScopeKey(request: FolderWorkspacePathStatusRequest): string {
return request.scope === 'project-group'
? `project-group:${request.projectGroupId}`
: `folder-workspace:${request.folderWorkspaceId}`
if (request.scope === 'project-group') {
return `project-group:${request.projectGroupId}`
}
if (request.scope === 'path') {
return `path:${request.connectionId ?? ''}:${request.path}`
}
return `folder-workspace:${request.folderWorkspaceId}`
}
function getRuntimeTargetCachePrefix(
@@ -918,6 +923,7 @@ function getRuntimeTargetCachePrefix(
}
type FolderWorkspacePathStatusRouteOptions = { runtimeEnvironmentId?: string | null }
type AddRepoPathRouteOptions = { runtimeEnvironmentId?: string | null }
function getFolderWorkspacePathStatusRouteSettings(
options: FolderWorkspacePathStatusRouteOptions | undefined,
@@ -928,10 +934,82 @@ function getFolderWorkspacePathStatusRouteSettings(
: fallbackSettings
}
function getAddRepoPathRouteSettings(
options: AddRepoPathRouteOptions | undefined,
fallbackSettings: GlobalSettings | null
): Pick<GlobalSettings, 'activeRuntimeEnvironmentId'> | null | undefined {
return options && 'runtimeEnvironmentId' in options
? { activeRuntimeEnvironmentId: options.runtimeEnvironmentId ?? null }
: fallbackSettings
}
function getRuntimeEnvironmentDisplayName(state: AppState, environmentId: string): string {
const environment = state.runtimeEnvironments.find((entry) => entry.id === environmentId)
return environment?.name || environmentId
}
async function fetchRuntimeAddProjectPathStatus(args: {
target: Extract<ReturnType<typeof getActiveRuntimeTarget>, { kind: 'environment' }>
path: string
}): Promise<FolderWorkspacePathStatus | null> {
await assertRuntimeEnvironmentCapability(
args.target.environmentId,
FOLDER_WORKSPACE_PATH_STATUS_RUNTIME_CAPABILITY,
translate(
'auto.store.slices.repos.2975400634',
'Update Orca server to open non-Git folders on this runtime.'
),
15_000
)
try {
const { status } = await callRuntimeRpc<{ status: FolderWorkspacePathStatus }>(
args.target,
'folderWorkspace.getPathStatus',
{ scope: 'path', path: args.path },
{ timeoutMs: 15_000 }
)
return status
} catch (err) {
console.warn('Failed to check runtime folder path status:', err)
return null
}
}
function getFolderWorkspaceStatusRequestSnapshot(
state: Pick<AppState, 'projectGroups' | 'folderWorkspaces' | 'repos' | 'sshConnectionStates'>,
request: FolderWorkspacePathStatusRequest
): string | null {
if (request.scope === 'path') {
const candidateRepos = state.repos.filter((repo) =>
isPathInsideOrEqual(request.path, repo.path)
)
const relevantConnectionIds = new Set<string>()
if (request.connectionId) {
relevantConnectionIds.add(request.connectionId)
}
for (const repo of candidateRepos) {
if (repo.connectionId) {
relevantConnectionIds.add(repo.connectionId)
}
}
const sshFingerprint = [...relevantConnectionIds]
.map(
(connectionId) =>
`${connectionId}:${state.sshConnectionStates.get(connectionId)?.status ?? 'missing'}`
)
.sort()
.join('|')
const repoFingerprint = candidateRepos
.map(
(repo) => `${repo.id}:${repo.path}:${repo.projectGroupId ?? ''}:${repo.connectionId ?? ''}`
)
.sort()
.join('|')
return [request.path, '', request.connectionId ?? '', sshFingerprint, repoFingerprint].join(
'\0'
)
}
const scope =
request.scope === 'project-group'
? state.projectGroups.find((group) => group.id === request.projectGroupId)
@@ -1040,7 +1118,11 @@ export type RepoSlice = {
fetchFolderWorkspaces: () => Promise<void>
fetchFolderWorkspacesForAllHosts: () => Promise<void>
addRepo: () => Promise<Repo | null>
addRepoPath: (path: string, kind?: 'git' | 'folder') => Promise<Repo | null>
addRepoPath: (
path: string,
kind?: 'git' | 'folder',
options?: AddRepoPathRouteOptions
) => Promise<Repo | null>
setupProjectExistingFolder: (
args: ProjectHostSetupExistingFolderArgs
) => Promise<ProjectHostSetupResult | null>
@@ -1054,7 +1136,7 @@ export type RepoSlice = {
args: ProjectHostSetupDeleteArgs
) => Promise<ProjectHostSetupDeleteResult | null>
setupProjectClone: (args: ProjectHostSetupCloneArgs) => Promise<ProjectHostSetupResult | null>
addNonGitFolder: (path: string) => Promise<Repo | null>
addNonGitFolder: (path: string, options?: AddRepoPathRouteOptions) => Promise<Repo | null>
scanNestedRepos: (
path: string,
connectionId?: string,
@@ -1837,9 +1919,9 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
}
},
addRepoPath: async (path, kind = 'git') => {
addRepoPath: async (path, kind = 'git', options) => {
try {
const target = getActiveRuntimeTarget(get().settings)
const target = getActiveRuntimeTarget(getAddRepoPathRouteSettings(options, get().settings))
let repo: Repo
try {
if (target.kind === 'local') {
@@ -1863,12 +1945,36 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
if (kind !== 'git' || !message.includes('Not a valid git repository')) {
throw err
}
if (target.kind !== 'local') {
const status = await fetchRuntimeAddProjectPathStatus({ target, path })
if (status?.exists !== true) {
const hostName = getRuntimeEnvironmentDisplayName(get(), target.environmentId)
toast.error(
translate(
'auto.store.slices.repos.3be0f7df04',
'Cannot open folder on selected runtime'
),
{
description: translate(
'auto.store.slices.repos.15cf5319ec',
'{{path}} was checked on {{hostName}}, but that host did not report a usable folder.',
{ path, hostName }
),
duration: ERROR_TOAST_DURATION
}
)
return null
}
}
// Why: folder mode is a capability downgrade, not a silent fallback.
// Show an in-app confirmation dialog so users understand that worktrees,
// SCM, PRs, and checks will be unavailable for this root. The dialog's
// OK handler calls addNonGitFolder to complete the flow.
const { openModal } = get()
openModal('confirm-non-git-folder', { folderPath: path })
openModal('confirm-non-git-folder', {
folderPath: path,
...(target.kind === 'environment' ? { runtimeEnvironmentId: target.environmentId } : {})
})
return null
}
repo = repoWithFetchedOwner(repo, target)
@@ -2172,10 +2278,10 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
return get().addRepoPath(path)
},
addNonGitFolder: async (path) => {
addNonGitFolder: async (path, options) => {
try {
const hadProjectBeforeAdd = get().repos.length > 0
const repo = await get().addRepoPath(path, 'folder')
const repo = await get().addRepoPath(path, 'folder', options)
if (!repo) {
return null
}
@@ -9,6 +9,7 @@ export const FOLDER_WORKSPACE_PATH_STATUS_TTL_MS = 10_000
export type FolderWorkspacePathStatusRequest =
| { scope: 'folder-workspace'; folderWorkspaceId: string }
| { scope: 'project-group'; projectGroupId: string }
| { scope: 'path'; path: string; connectionId?: string | null }
export type FolderWorkspacePathStatus = {
path: string
+4 -1
View File
@@ -25,6 +25,8 @@ export const PROJECT_HOST_SETUP_RUNTIME_CAPABILITY = 'project-host-setup.v1' as
export const TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY = 'task-source-context.v1' as const
export const WORKSPACE_RUN_CONTEXT_RUNTIME_CAPABILITY = 'workspace-run-context.v1' as const
export const REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY = 'remote-runtime.shared-control.v1' as const
export const FOLDER_WORKSPACE_PATH_STATUS_RUNTIME_CAPABILITY =
'folder-workspace.path-status.v1' as const
// Why: signals a host owns browser pages with no renderer (headless serve via the
// offscreen backend). Advertised only when that backend is actually available, so
// clients never fall back to a local desktop browser tab for a remote-owned page.
@@ -41,7 +43,8 @@ export const RUNTIME_CAPABILITIES = [
'mobile.tasks.v1',
PROJECT_HOST_SETUP_RUNTIME_CAPABILITY,
TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY,
WORKSPACE_RUN_CONTEXT_RUNTIME_CAPABILITY
WORKSPACE_RUN_CONTEXT_RUNTIME_CAPABILITY,
FOLDER_WORKSPACE_PATH_STATUS_RUNTIME_CAPABILITY
] as const
export type RuntimeCapability = (typeof RUNTIME_CAPABILITIES)[number] | (string & {})