From cf3116bc4aaa234b7c4669fa598305e460479a7a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 20 May 2026 17:15:29 -0700 Subject: [PATCH] Improve setup script discoverability (#2402) Co-authored-by: Orca --- src/main/ipc/worktrees.ts | 64 +++- src/main/runtime/orca-runtime.test.ts | 6 +- src/main/runtime/orca-runtime.ts | 39 ++- src/main/runtime/rpc/methods/client-ui.ts | 1 + src/main/runtime/rpc/methods/repo.test.ts | 10 + src/main/runtime/rpc/methods/repo.ts | 5 + src/preload/api-types.ts | 2 + src/preload/index.ts | 3 + .../settings/RepositoryHooksSection.tsx | 2 + .../settings/repository-settings-targets.ts | 3 + .../sidebar/SetupScriptPromptCard.tsx | 297 ++++++++++++++++++ src/renderer/src/components/sidebar/index.tsx | 3 + .../src/runtime/runtime-hooks-client.test.ts | 17 +- .../src/runtime/runtime-hooks-client.ts | 17 + .../slices/repos-update-serialization.test.ts | 2 +- src/renderer/src/store/slices/repos.ts | 17 +- src/renderer/src/store/slices/ui.ts | 29 ++ src/renderer/src/web/web-preload-api.ts | 2 + src/shared/constants.ts | 1 + .../setup-script-import-codex-environment.ts | 153 +++++++++ src/shared/setup-script-imports.test.ts | 222 +++++++++++++ src/shared/setup-script-imports.ts | 289 +++++++++++++++++ src/shared/types.ts | 1 + tests/e2e/setup-script-import.spec.ts | 199 ++++++++++++ 24 files changed, 1367 insertions(+), 17 deletions(-) create mode 100644 src/renderer/src/components/settings/repository-settings-targets.ts create mode 100644 src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx create mode 100644 src/shared/setup-script-import-codex-environment.ts create mode 100644 src/shared/setup-script-imports.test.ts create mode 100644 src/shared/setup-script-imports.ts create mode 100644 tests/e2e/setup-script-import.spec.ts diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 17b84923c..829151bca 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -1,10 +1,11 @@ /* oxlint-disable max-lines */ import type { BrowserWindow } from 'electron' import { ipcMain } from 'electron' -import { rm } from 'fs/promises' +import { readFile, rm } from 'fs/promises' import { randomUUID } from 'crypto' import type { Store } from '../persistence' import { isFolderRepo } from '../../shared/repo-kind' +import { inspectSetupScriptImportCandidates } from '../../shared/setup-script-imports' import { deleteWorktreeHistoryDir } from '../terminal-history' import type { CreateWorktreeArgs, @@ -26,10 +27,12 @@ import { getProjectRef as getGlabProjectRef, getGlabKnownHosts } from '../gitlab import { getWorkItemByProjectRef as getGitLabWorkItemByProjectRef } from '../gitlab/client' import { listRepoWorktrees, createFolderWorktree } from '../repo-worktrees' import { getSshGitProvider, requireSshGitProvider } from '../providers/ssh-git-dispatch' +import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' import { createIssueCommandRunnerScript, getEffectiveHooks, loadHooks, + parseOrcaYaml, readIssueCommand, runHook, hasHooksFile, @@ -44,12 +47,17 @@ import { isOrphanCompatiblePreflightError, isOrphanedWorktreeError } from './worktree-logic' +import { joinWorktreeRelativePath } from '../runtime/runtime-relative-paths' import { createLocalWorktree, createRemoteWorktree, notifyWorktreesChanged } from './worktree-remote' -import { invalidateAuthorizedRootsCache, registerWorktreeRootsForRepo } from './filesystem-auth' +import { + invalidateAuthorizedRootsCache, + isENOENT, + registerWorktreeRootsForRepo +} from './filesystem-auth' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { killAllProcessesForWorktree } from '../runtime/worktree-teardown' import { getLocalPtyProvider } from './pty' @@ -229,6 +237,7 @@ export function registerWorktreeHandlers( ipcMain.removeHandler('worktrees:updateLineage') ipcMain.removeHandler('worktrees:persistSortOrder') ipcMain.removeHandler('hooks:check') + ipcMain.removeHandler('hooks:inspectSetupScriptImports') ipcMain.removeHandler('hooks:createIssueCommandRunner') ipcMain.removeHandler('hooks:readIssueCommand') ipcMain.removeHandler('hooks:writeIssueCommand') @@ -750,12 +759,29 @@ export function registerWorktreeHandlers( } }) - ipcMain.handle('hooks:check', (_event, args: { repoId: string }) => { + ipcMain.handle('hooks:check', async (_event, args: { repoId: string }) => { const repo = store.getRepo(args.repoId) if (!repo || isFolderRepo(repo)) { return { hasHooks: false, hooks: null, mayNeedUpdate: false } } + if (repo.connectionId) { + const fsProvider = getSshFilesystemProvider(repo.connectionId) + if (!fsProvider) { + return { hasHooks: false, hooks: null, mayNeedUpdate: false } + } + try { + const result = await fsProvider.readFile(joinWorktreeRelativePath(repo.path, 'orca.yaml')) + return { + hasHooks: !result.isBinary, + hooks: result.isBinary ? null : parseOrcaYaml(result.content), + mayNeedUpdate: false + } + } catch { + return { hasHooks: false, hooks: null, mayNeedUpdate: false } + } + } + const has = hasHooksFile(repo.path) const hooks = has ? loadHooks(repo.path) : null // Why: when a newer Orca version adds a top-level key to `orca.yaml`, older @@ -782,6 +808,38 @@ export function registerWorktreeHandlers( } ) + ipcMain.handle('hooks:inspectSetupScriptImports', async (_event, args: { repoId: string }) => { + const repo = store.getRepo(args.repoId) + if (!repo || isFolderRepo(repo)) { + return [] + } + + return inspectSetupScriptImportCandidates(async (relativePath) => { + const filePath = joinWorktreeRelativePath(repo.path, relativePath) + if (repo.connectionId) { + const fsProvider = getSshFilesystemProvider(repo.connectionId) + if (!fsProvider) { + return null + } + try { + const result = await fsProvider.readFile(filePath) + return result.isBinary ? null : result.content + } catch { + return null + } + } + + try { + return await readFile(filePath, 'utf-8') + } catch (error) { + if (!isENOENT(error)) { + console.warn('[hooks] Failed to inspect setup script import candidate:', error) + } + return null + } + }) + }) + ipcMain.handle('hooks:readIssueCommand', (_event, args: { repoId: string }) => { const repo = store.getRepo(args.repoId) if (!repo || isFolderRepo(repo)) { diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 92e9c2e8d..14738d758 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -1021,7 +1021,7 @@ describe('OrcaRuntimeService', () => { unregisterSshFilesystemProvider('ssh-1') } - expect(fsProvider.readFile).toHaveBeenCalledWith('C:\\remote\\repo\\.orca.yaml') + expect(fsProvider.readFile).toHaveBeenCalledWith('C:\\remote\\repo\\orca.yaml') expect(hasHooksFile).not.toHaveBeenCalled() expect(getEffectiveHooks).not.toHaveBeenCalled() }) @@ -1042,7 +1042,7 @@ describe('OrcaRuntimeService', () => { } const fsProvider = { readFile: vi.fn(async (filePath: string) => ({ - content: filePath.includes('.orca.yaml') + content: filePath.endsWith('orca.yaml') ? 'scripts:\n setup: pnpm install\n' : filePath.endsWith('.gitignore') ? 'node_modules\n' @@ -1073,7 +1073,7 @@ describe('OrcaRuntimeService', () => { unregisterSshFilesystemProvider('ssh-1') } - expect(fsProvider.readFile).toHaveBeenCalledWith('C:\\remote\\repo\\.orca.yaml') + expect(fsProvider.readFile).toHaveBeenCalledWith('C:\\remote\\repo\\orca.yaml') expect(fsProvider.readFile).toHaveBeenCalledWith('C:\\remote\\repo\\.orca\\issue-command') expect(fsProvider.createDir).toHaveBeenCalledWith('C:\\remote\\repo\\.orca') expect(fsProvider.writeFile).toHaveBeenCalledWith( diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 269bd04c6..745acd88e 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -11,7 +11,7 @@ import { gitExecFileAsync, wslAwareSpawn } from '../git/runner' import { isWslPath, parseWslPath, getWslHome } from '../wsl' import { randomUUID } from 'crypto' import { basename, isAbsolute, join } from 'path' -import { mkdir, readdir, rm, stat } from 'fs/promises' +import { mkdir, readFile, readdir, rm, stat } from 'fs/promises' import { OrchestrationDb } from './orchestration/db' import { formatMessagesForInjection } from './orchestration/formatter' import type { @@ -154,6 +154,7 @@ import type { GitHubPRFile, GitHubPRReviewCommentInput } from '../../shared/types' +import { inspectSetupScriptImportCandidates } from '../../shared/setup-script-imports' import type { CreateHostedReviewInput, CreateHostedReviewResult, @@ -5568,7 +5569,7 @@ export class OrcaRuntimeService { } } try { - const result = await fsProvider.readFile(joinWorktreeRelativePath(repo.path, '.orca.yaml')) + const result = await fsProvider.readFile(joinWorktreeRelativePath(repo.path, 'orca.yaml')) const hooks = result.isBinary ? null : parseOrcaYaml(result.content) return { hasHooksFile: Boolean(hooks), @@ -5608,7 +5609,7 @@ export class OrcaRuntimeService { return { hasHooks: false, hooks: null, mayNeedUpdate: false } } try { - const result = await fsProvider.readFile(joinWorktreeRelativePath(repo.path, '.orca.yaml')) + const result = await fsProvider.readFile(joinWorktreeRelativePath(repo.path, 'orca.yaml')) if (result.isBinary) { return { hasHooks: false, hooks: null, mayNeedUpdate: false } } @@ -5629,6 +5630,38 @@ export class OrcaRuntimeService { } } + async inspectRepoSetupScriptImports(repoSelector: string) { + const repo = await this.resolveRepoSelector(repoSelector) + if (isFolderRepo(repo)) { + return [] + } + + return inspectSetupScriptImportCandidates(async (relativePath) => { + const filePath = joinWorktreeRelativePath(repo.path, relativePath) + if (repo.connectionId) { + const fsProvider = getSshFilesystemProvider(repo.connectionId) + if (!fsProvider) { + return null + } + try { + const result = await fsProvider.readFile(filePath) + return result.isBinary ? null : result.content + } catch { + return null + } + } + + try { + return await readFile(filePath, 'utf-8') + } catch (error) { + if (!isENOENT(error)) { + console.warn('[runtime] Failed to inspect setup script import candidate:', error) + } + return null + } + }) + } + async readRepoIssueCommand(repoSelector: string) { const repo = await this.resolveRepoSelector(repoSelector) if (isFolderRepo(repo)) { diff --git a/src/main/runtime/rpc/methods/client-ui.ts b/src/main/runtime/rpc/methods/client-ui.ts index 7a5756376..f81a13f74 100644 --- a/src/main/runtime/rpc/methods/client-ui.ts +++ b/src/main/runtime/rpc/methods/client-ui.ts @@ -101,6 +101,7 @@ const UiUpdate = z starNagNextThreshold: z.number().finite().optional(), starNagCompleted: z.boolean().optional(), trustedOrcaHooks: z.record(z.string(), z.unknown()).optional(), + setupScriptPromptDismissedRepoIds: StringArray.optional(), petVisible: z.boolean().optional(), petId: z.string().optional(), customPets: UnknownRecordArray.optional(), diff --git a/src/main/runtime/rpc/methods/repo.test.ts b/src/main/runtime/rpc/methods/repo.test.ts index da7b92122..7f05a2cb5 100644 --- a/src/main/runtime/rpc/methods/repo.test.ts +++ b/src/main/runtime/rpc/methods/repo.test.ts @@ -69,6 +69,14 @@ describe('repo RPC methods', () => { hooks: { scripts: { setup: 'pnpm install' } }, mayNeedUpdate: false }), + inspectRepoSetupScriptImports: vi.fn().mockResolvedValue([ + { + provider: 'conductor', + label: 'Conductor', + files: ['conductor.json'], + setup: 'pnpm install' + } + ]), readRepoIssueCommand: vi.fn().mockResolvedValue({ localContent: null, sharedContent: 'Fix {{artifact_url}}', @@ -81,6 +89,7 @@ describe('repo RPC methods', () => { const dispatcher = new RpcDispatcher({ runtime, methods: REPO_METHODS }) await dispatcher.dispatch(makeRequest('repo.hooksCheck', { repo: 'repo-1' })) + await dispatcher.dispatch(makeRequest('repo.setupScriptImports', { repo: 'repo-1' })) await dispatcher.dispatch(makeRequest('repo.issueCommandRead', { repo: 'repo-1' })) await dispatcher.dispatch( makeRequest('repo.issueCommandWrite', { @@ -90,6 +99,7 @@ describe('repo RPC methods', () => { ) expect(runtime.checkRepoHooks).toHaveBeenCalledWith('repo-1') + expect(runtime.inspectRepoSetupScriptImports).toHaveBeenCalledWith('repo-1') expect(runtime.readRepoIssueCommand).toHaveBeenCalledWith('repo-1') expect(runtime.writeRepoIssueCommand).toHaveBeenCalledWith('repo-1', 'Fix it') }) diff --git a/src/main/runtime/rpc/methods/repo.ts b/src/main/runtime/rpc/methods/repo.ts index 9b466a2ce..203ea9790 100644 --- a/src/main/runtime/rpc/methods/repo.ts +++ b/src/main/runtime/rpc/methods/repo.ts @@ -135,6 +135,11 @@ export const REPO_METHODS: RpcMethod[] = [ params: RepoSelector, handler: async (params, { runtime }) => runtime.checkRepoHooks(params.repo) }), + defineMethod({ + name: 'repo.setupScriptImports', + params: RepoSelector, + handler: async (params, { runtime }) => runtime.inspectRepoSetupScriptImports(params.repo) + }), defineMethod({ name: 'repo.issueCommandRead', params: RepoSelector, diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 3bec7b061..c04dd89e3 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -104,6 +104,7 @@ import type { WorktreeStartupLaunch, WorkspaceSessionState } from '../shared/types' +import type { SetupScriptImportCandidate } from '../shared/setup-script-imports' import type { GitHistoryOptions, GitHistoryResult } from '../shared/git-history' import type { PublicKnownRuntimeEnvironment } from '../shared/runtime-environments' import type { RuntimeAccessGrant } from '../shared/runtime-access-grants' @@ -1288,6 +1289,7 @@ export type PreloadApi = { check: (args: { repoId: string }) => Promise<{ hasHooks: boolean; hooks: OrcaHooks | null; mayNeedUpdate: boolean }> + inspectSetupScriptImports: (args: { repoId: string }) => Promise createIssueCommandRunner: (args: { repoId: string worktreePath: string diff --git a/src/preload/index.ts b/src/preload/index.ts index e8f8c34ba..d613b19b3 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1755,6 +1755,9 @@ const api = { }): Promise<{ hasHooks: boolean; hooks: unknown; mayNeedUpdate: boolean }> => ipcRenderer.invoke('hooks:check', args), + inspectSetupScriptImports: (args: { repoId: string }): Promise => + ipcRenderer.invoke('hooks:inspectSetupScriptImports', args), + createIssueCommandRunner: (args: { repoId: string worktreePath: string diff --git a/src/renderer/src/components/settings/RepositoryHooksSection.tsx b/src/renderer/src/components/settings/RepositoryHooksSection.tsx index 23d00b55d..d069db48e 100644 --- a/src/renderer/src/components/settings/RepositoryHooksSection.tsx +++ b/src/renderer/src/components/settings/RepositoryHooksSection.tsx @@ -16,6 +16,7 @@ import { useAppStore } from '@/store' import { readRuntimeIssueCommand, writeRuntimeIssueCommand } from '@/runtime/runtime-hooks-client' import { DEFAULT_REPO_HOOK_SETTINGS } from './SettingsConstants' import { normalizeHookCommandSourcePolicy } from '../../../../shared/hook-command-source-policy' +import { getRepositoryLocalCommandsSectionId } from './repository-settings-targets' type RepositoryHooksSectionProps = { repo: Repo @@ -560,6 +561,7 @@ export function RepositoryHooksSection({ 0 + ? `${candidate.label} (${primaryFile} +${remainingFiles.length})` + : `${candidate.label} (${primaryFile})` +} + +function SetupScriptPromptCard(): React.JSX.Element | null { + const sidebarOpen = useAppStore((s) => s.sidebarOpen) + const repos = useAppStore((s) => s.repos) + const activeRepoId = useAppStore((s) => s.activeRepoId) + const settings = useAppStore((s) => s.settings) + const updateRepo = useAppStore((s) => s.updateRepo) + const openSettingsPage = useAppStore((s) => s.openSettingsPage) + const openSettingsTarget = useAppStore((s) => s.openSettingsTarget) + const setSettingsSearchQuery = useAppStore((s) => s.setSettingsSearchQuery) + const dismissedRepoIds = useAppStore((s) => s.setupScriptPromptDismissedRepoIds) + const dismissSetupScriptPrompt = useAppStore((s) => s.dismissSetupScriptPrompt) + const [promptState, setPromptState] = useState(null) + const [isImporting, setIsImporting] = useState(false) + + const activeRepo = useMemo( + () => repos.find((repo) => repo.id === activeRepoId) ?? null, + [activeRepoId, repos] + ) + const isDismissed = activeRepo ? dismissedRepoIds.includes(activeRepo.id) : false + + useEffect(() => { + if (!sidebarOpen || !activeRepo || !isGitRepoKind(activeRepo) || isDismissed) { + setPromptState(null) + return + } + + const repo = activeRepo + let cancelled = false + setPromptState(null) + + async function inspectRepoSetup(): Promise { + try { + const hooksResult = await checkRuntimeHooks(settings, repo.id) + if (cancelled) { + return + } + + const hasEffectiveSetup = hasEffectiveSetupCommand(repo, hooksResult) + if (hasEffectiveSetup) { + setPromptState({ + repoId: repo.id, + hasEffectiveSetup: true, + hasSharedHooks: hooksResult.hasHooks, + candidate: null + }) + return + } + + const candidates = await inspectRuntimeSetupScriptImports(settings, repo.id).catch(() => []) + if (cancelled) { + return + } + + setPromptState({ + repoId: repo.id, + hasEffectiveSetup: false, + hasSharedHooks: hooksResult.hasHooks, + candidate: candidates[0] ?? null + }) + } catch (error) { + if (!cancelled) { + console.warn('[setup-script-prompt] Failed to inspect setup scripts:', error) + setPromptState(null) + } + } + } + + void inspectRepoSetup() + + return () => { + cancelled = true + } + }, [activeRepo, isDismissed, settings, sidebarOpen]) + + const openLocalCommandSettings = useCallback( + (repoId: string) => { + // Why: imported setup commands are local repo settings; a stale Settings + // search should not hide the exact editor this action opens. + setSettingsSearchQuery('') + openSettingsTarget({ + pane: 'repo', + repoId, + sectionId: getRepositoryLocalCommandsSectionId(repoId) + }) + openSettingsPage() + }, + [openSettingsPage, openSettingsTarget, setSettingsSearchQuery] + ) + + const handleConfigure = useCallback(() => { + if (!activeRepo) { + return + } + openLocalCommandSettings(activeRepo.id) + }, [activeRepo, openLocalCommandSettings]) + + const handleDismiss = useCallback(() => { + if (activeRepo) { + dismissSetupScriptPrompt(activeRepo.id) + } + }, [activeRepo, dismissSetupScriptPrompt]) + + const handleImport = useCallback(async () => { + if (!activeRepo || !promptState?.candidate) { + return + } + setIsImporting(true) + try { + const importedRepoId = activeRepo.id + const nextSettings = buildImportedHookSettings( + activeRepo, + promptState.candidate, + promptState.hasSharedHooks + ) + const didUpdate = await updateRepo(activeRepo.id, { hookSettings: nextSettings }) + if (!didUpdate) { + toast.error('Failed to import setup script') + return + } + setPromptState((current) => + current?.repoId === activeRepo.id ? { ...current, hasEffectiveSetup: true } : current + ) + const skippedCount = promptState.candidate.unsupportedFields?.length ?? 0 + toast.success('Setup script imported', { + description: + skippedCount > 0 + ? `${skippedCount} unsupported field${skippedCount === 1 ? '' : 's'} skipped. Saved to this repo's local settings.` + : "Saved to this repo's local settings.", + action: { + label: 'View in Settings', + onClick: () => openLocalCommandSettings(importedRepoId) + } + }) + } finally { + setIsImporting(false) + } + }, [activeRepo, openLocalCommandSettings, promptState, updateRepo]) + + if ( + !sidebarOpen || + !activeRepo || + !isGitRepoKind(activeRepo) || + isDismissed || + promptState?.repoId !== activeRepo.id || + promptState.hasEffectiveSetup + ) { + return null + } + + const candidate = promptState.candidate + const title = 'Setup scripts' + const candidateSource = candidate ? formatCandidateSource(candidate) : null + const actionLabel = candidate ? 'Import setup' : 'Configure' + const ActionIcon = candidate ? Download : Settings + + return ( +
+
+ + Setup + + + + + + + Dismiss + + + +

{title}

+

+ {candidateSource ? ( + <> + Detected setup config from {candidateSource}. + + ) : ( + <>Automate workspace setup for {activeRepo.displayName}. + )} +

+ + +
+
+ ) +} + +export default React.memo(SetupScriptPromptCard) diff --git a/src/renderer/src/components/sidebar/index.tsx b/src/renderer/src/components/sidebar/index.tsx index 95d556273..bb87e69ea 100644 --- a/src/renderer/src/components/sidebar/index.tsx +++ b/src/renderer/src/components/sidebar/index.tsx @@ -4,6 +4,7 @@ import { TooltipProvider } from '@/components/ui/tooltip' import { useSidebarResize } from '@/hooks/useSidebarResize' import SidebarHeader from './SidebarHeader' import SidebarNav from './SidebarNav' +import SetupScriptPromptCard from './SetupScriptPromptCard' import WorktreeList from './WorktreeList' import SidebarToolbar from './SidebarToolbar' import WorktreeMetaDialog from './WorktreeMetaDialog' @@ -72,6 +73,8 @@ function Sidebar({ scrollAnchorRef={worktreeScrollAnchorRef} /> + + {/* Fixed bottom toolbar */} diff --git a/src/renderer/src/runtime/runtime-hooks-client.test.ts b/src/renderer/src/runtime/runtime-hooks-client.test.ts index 53c9d6891..b3ce8dfea 100644 --- a/src/renderer/src/runtime/runtime-hooks-client.test.ts +++ b/src/renderer/src/runtime/runtime-hooks-client.test.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { checkRuntimeHooks, + inspectRuntimeSetupScriptImports, readRuntimeIssueCommand, writeRuntimeIssueCommand } from './runtime-hooks-client' @@ -13,6 +14,7 @@ import { clearRuntimeCompatibilityCacheForTests } from './runtime-rpc-client' const runtimeEnvironmentCall = vi.fn() const runtimeEnvironmentTransportCall = vi.fn() const hooksCheck = vi.fn() +const hooksInspectSetupScriptImports = vi.fn() const hooksReadIssueCommand = vi.fn() const hooksWriteIssueCommand = vi.fn() @@ -21,6 +23,7 @@ beforeEach(() => { runtimeEnvironmentCall.mockReset() runtimeEnvironmentTransportCall.mockReset() hooksCheck.mockReset() + hooksInspectSetupScriptImports.mockReset() hooksReadIssueCommand.mockReset() hooksWriteIssueCommand.mockReset() runtimeEnvironmentTransportCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { @@ -31,6 +34,7 @@ beforeEach(() => { runtimeEnvironments: { call: runtimeEnvironmentTransportCall }, hooks: { check: hooksCheck, + inspectSetupScriptImports: hooksInspectSetupScriptImports, readIssueCommand: hooksReadIssueCommand, writeIssueCommand: hooksWriteIssueCommand } @@ -41,6 +45,7 @@ beforeEach(() => { describe('runtime hooks client', () => { it('uses local hook IPC when no runtime environment is active', async () => { hooksCheck.mockResolvedValue({ hasHooks: false, hooks: null, mayNeedUpdate: false }) + hooksInspectSetupScriptImports.mockResolvedValue([]) hooksReadIssueCommand.mockResolvedValue({ localContent: null, sharedContent: null, @@ -50,10 +55,12 @@ describe('runtime hooks client', () => { }) await checkRuntimeHooks({ activeRuntimeEnvironmentId: null }, 'repo-1') + await inspectRuntimeSetupScriptImports({ activeRuntimeEnvironmentId: null }, 'repo-1') await readRuntimeIssueCommand({ activeRuntimeEnvironmentId: null }, 'repo-1') await writeRuntimeIssueCommand({ activeRuntimeEnvironmentId: null }, 'repo-1', 'Fix it') expect(hooksCheck).toHaveBeenCalledWith({ repoId: 'repo-1' }) + expect(hooksInspectSetupScriptImports).toHaveBeenCalledWith({ repoId: 'repo-1' }) expect(hooksReadIssueCommand).toHaveBeenCalledWith({ repoId: 'repo-1' }) expect(hooksWriteIssueCommand).toHaveBeenCalledWith({ repoId: 'repo-1', content: 'Fix it' }) expect(runtimeEnvironmentCall).not.toHaveBeenCalled() @@ -68,6 +75,7 @@ describe('runtime hooks client', () => { }) await checkRuntimeHooks({ activeRuntimeEnvironmentId: 'env-1' }, 'repo-1') + await inspectRuntimeSetupScriptImports({ activeRuntimeEnvironmentId: 'env-1' }, 'repo-1') await readRuntimeIssueCommand({ activeRuntimeEnvironmentId: 'env-1' }, 'repo-1') await writeRuntimeIssueCommand({ activeRuntimeEnvironmentId: 'env-1' }, 'repo-1', 'Fix it') @@ -79,17 +87,24 @@ describe('runtime hooks client', () => { }) expect(runtimeEnvironmentCall).toHaveBeenNthCalledWith(2, { selector: 'env-1', - method: 'repo.issueCommandRead', + method: 'repo.setupScriptImports', params: { repo: 'repo-1' }, timeoutMs: 15_000 }) expect(runtimeEnvironmentCall).toHaveBeenNthCalledWith(3, { + selector: 'env-1', + method: 'repo.issueCommandRead', + params: { repo: 'repo-1' }, + timeoutMs: 15_000 + }) + expect(runtimeEnvironmentCall).toHaveBeenNthCalledWith(4, { selector: 'env-1', method: 'repo.issueCommandWrite', params: { repo: 'repo-1', content: 'Fix it' }, timeoutMs: 15_000 }) expect(hooksCheck).not.toHaveBeenCalled() + expect(hooksInspectSetupScriptImports).not.toHaveBeenCalled() expect(hooksReadIssueCommand).not.toHaveBeenCalled() expect(hooksWriteIssueCommand).not.toHaveBeenCalled() }) diff --git a/src/renderer/src/runtime/runtime-hooks-client.ts b/src/renderer/src/runtime/runtime-hooks-client.ts index 3179de7ee..cf02e3098 100644 --- a/src/renderer/src/runtime/runtime-hooks-client.ts +++ b/src/renderer/src/runtime/runtime-hooks-client.ts @@ -1,4 +1,5 @@ import type { GlobalSettings, OrcaHooks } from '../../../shared/types' +import type { SetupScriptImportCandidate } from '../../../shared/setup-script-imports' import { callRuntimeRpc, getActiveRuntimeTarget } from './runtime-rpc-client' export type HookCheckResult = { @@ -31,6 +32,22 @@ export async function checkRuntimeHooks( ) } +export async function inspectRuntimeSetupScriptImports( + settings: Pick | null | undefined, + repoId: string +): Promise { + const target = getActiveRuntimeTarget(settings) + if (target.kind !== 'environment') { + return window.api.hooks.inspectSetupScriptImports({ repoId }) + } + return callRuntimeRpc( + target, + 'repo.setupScriptImports', + { repo: repoId }, + { timeoutMs: 15_000 } + ) +} + export async function readRuntimeIssueCommand( settings: Pick | null | undefined, repoId: string diff --git a/src/renderer/src/store/slices/repos-update-serialization.test.ts b/src/renderer/src/store/slices/repos-update-serialization.test.ts index 4f536be66..de5ecd3ff 100644 --- a/src/renderer/src/store/slices/repos-update-serialization.test.ts +++ b/src/renderer/src/store/slices/repos-update-serialization.test.ts @@ -119,7 +119,7 @@ describe('repo update serialization', () => { const failed = store.getState().updateRepo(localRepo.id, { displayName: 'Failed' }) const recovered = store.getState().updateRepo(localRepo.id, { displayName: 'Recovered' }) - await Promise.all([failed, recovered]) + await expect(Promise.all([failed, recovered])).resolves.toEqual([false, true]) expect(reposUpdate).toHaveBeenCalledTimes(2) expect(store.getState().repos[0]?.displayName).toBe('Recovered') diff --git a/src/renderer/src/store/slices/repos.ts b/src/renderer/src/store/slices/repos.ts index 18745a7c6..e32eca612 100644 --- a/src/renderer/src/store/slices/repos.ts +++ b/src/renderer/src/store/slices/repos.ts @@ -26,12 +26,12 @@ type RepoUpdate = Partial< > > -const updateRepoChainsByStore = new WeakMap<() => AppState, Map>>() +const updateRepoChainsByStore = new WeakMap<() => AppState, Map>>() -function getRepoUpdateChains(get: () => AppState) { +function getRepoUpdateChains(get: () => AppState): Map> { let chains = updateRepoChainsByStore.get(get) if (!chains) { - chains = new Map>() + chains = new Map>() updateRepoChainsByStore.set(get, chains) } return chains @@ -45,7 +45,7 @@ export type RepoSlice = { addRepoPath: (path: string, kind?: 'git' | 'folder') => Promise addNonGitFolder: (path: string) => Promise removeRepo: (repoId: string) => Promise - updateRepo: (repoId: string, updates: RepoUpdate) => Promise + updateRepo: (repoId: string, updates: RepoUpdate) => Promise setActiveRepo: (repoId: string | null) => void reorderRepos: (orderedIds: string[]) => Promise } @@ -76,7 +76,10 @@ export const createRepoSlice: StateCreator = (set, return { repos, activeRepoId: s.activeRepoId && validRepoIds.has(s.activeRepoId) ? s.activeRepoId : null, - filterRepoIds: s.filterRepoIds.filter((repoId) => validRepoIds.has(repoId)) + filterRepoIds: s.filterRepoIds.filter((repoId) => validRepoIds.has(repoId)), + setupScriptPromptDismissedRepoIds: s.setupScriptPromptDismissedRepoIds.filter((repoId) => + validRepoIds.has(repoId) + ) } }) } catch (err) { @@ -332,8 +335,10 @@ export const createRepoSlice: StateCreator = (set, set((s) => ({ repos: s.repos.map((r) => (r.id === repoId ? { ...r, ...updates } : r)) })) + return true } catch (err) { console.error('Failed to update repo:', err) + return false } } const previous = updateRepoChains.get(repoId) @@ -349,7 +354,7 @@ export const createRepoSlice: StateCreator = (set, } } void next.then(cleanup, cleanup) - await next + return next }, setActiveRepo: (repoId) => set({ activeRepoId: repoId }), diff --git a/src/renderer/src/store/slices/ui.ts b/src/renderer/src/store/slices/ui.ts index 98c7c8f39..f2d7d8bc8 100644 --- a/src/renderer/src/store/slices/ui.ts +++ b/src/renderer/src/store/slices/ui.ts @@ -138,6 +138,19 @@ function filterTrustedOrcaHooksToValidRepos( return next } +function filterRepoIdListToValidRepos(value: unknown, validRepoIds: Set): string[] { + if (!Array.isArray(value)) { + return [] + } + const next: string[] = [] + for (const repoId of value) { + if (typeof repoId === 'string' && validRepoIds.has(repoId) && !next.includes(repoId)) { + next.push(repoId) + } + } + return next +} + function sanitizePersistedSidebarWidth(width: unknown, fallback: number, maxWidth: number): number { if (typeof width !== 'number' || !Number.isFinite(width)) { return fallback @@ -368,6 +381,8 @@ export type UISlice = { ) => void markOrcaHookRepoAlwaysTrusted: (repoId: string) => void clearOrcaHookTrustForRepo: (repoId: string) => void + setupScriptPromptDismissedRepoIds: string[] + dismissSetupScriptPrompt: (repoId: string) => void groupBy: 'none' | 'workspace-status' | 'repo' | 'pr-status' setGroupBy: (g: UISlice['groupBy']) => void sortBy: 'name' | 'smart' | 'recent' | 'repo' @@ -790,6 +805,16 @@ export const createUISlice: StateCreator = (set, get) window.api.ui.set({ trustedOrcaHooks: next }).catch(console.error) return { trustedOrcaHooks: next } }), + setupScriptPromptDismissedRepoIds: [], + dismissSetupScriptPrompt: (repoId) => + set((s) => { + if (!repoId || s.setupScriptPromptDismissedRepoIds.includes(repoId)) { + return s + } + const next = [...s.setupScriptPromptDismissedRepoIds, repoId] + window.api.ui.set({ setupScriptPromptDismissedRepoIds: next }).catch(console.error) + return { setupScriptPromptDismissedRepoIds: next } + }), groupBy: 'workspace-status', // Why: group keys are mode-specific (e.g. repo id vs PR status), so @@ -1049,6 +1074,10 @@ export const createUISlice: StateCreator = (set, get) ui.trustedOrcaHooks ?? {}, validRepoIds ), + setupScriptPromptDismissedRepoIds: filterRepoIdListToValidRepos( + ui.setupScriptPromptDismissedRepoIds, + validRepoIds + ), // Why: restore visited-row acks alongside the persisted hook entries // they pair with. Stale acks for paneKeys whose tab/PTY no longer // exists are inert (no row references them); a paneKey reuse stamps a diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index 3c4d675d1..09fe8bd73 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -763,6 +763,8 @@ function createRuntimeNamespaceApi(prefix: string): never { function createHooksApi(): NonNullable['hooks']> { return { check: async ({ repoId }) => callRuntimeResult('repo.hooksCheck', { repo: repoId }), + inspectSetupScriptImports: async ({ repoId }) => + callRuntimeResult('repo.setupScriptImports', { repo: repoId }), createIssueCommandRunner: async () => ({ launched: false }) as never, readIssueCommand: async ({ repoId }) => callRuntimeResult('repo.issueCommandRead', { repo: repoId }), diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 160756fcf..647a3a390 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -360,6 +360,7 @@ export function getDefaultUIState(): PersistedUIState { dismissedUpdateVersion: null, lastUpdateCheckAt: null, trustedOrcaHooks: {}, + setupScriptPromptDismissedRepoIds: [], acknowledgedAgentsByPaneKey: {}, workspaceCleanup: { dismissals: {} }, featureTipsSeenIds: [] diff --git a/src/shared/setup-script-import-codex-environment.ts b/src/shared/setup-script-import-codex-environment.ts new file mode 100644 index 000000000..45d8fd9ba --- /dev/null +++ b/src/shared/setup-script-import-codex-environment.ts @@ -0,0 +1,153 @@ +import type { SetupScriptImportCandidate, SetupScriptImportFileRead } from './setup-script-imports' + +const CODEX_ENVIRONMENT_PATH = '.codex/environments/environment.toml' + +type CodexEnvironmentToml = { + setupScript?: string + cleanupScript?: string + unsupportedFields: string[] +} + +export async function inspectCodexEnvironmentConfig( + readFile: SetupScriptImportFileRead +): Promise { + const content = await readFile(CODEX_ENVIRONMENT_PATH) + if (!content) { + return null + } + + const parsed = parseCodexEnvironmentToml(content) + const setup = parsed.setupScript?.trim() + if (!setup) { + return null + } + + return { + provider: 'codex', + label: 'Codex environment', + files: [CODEX_ENVIRONMENT_PATH], + setup, + archive: parsed.cleanupScript?.trim() || undefined, + unsupportedFields: parsed.unsupportedFields + } +} + +function parseCodexEnvironmentToml(content: string): CodexEnvironmentToml { + const lines = content.split(/\r?\n/) + const unsupportedFields: string[] = [] + let section = '' + let setupScript: string | undefined + let cleanupScript: string | undefined + + for (let index = 0; index < lines.length; index++) { + const line = lines[index] + const trimmed = line.trim() + if (/^actions\s*=/.test(trimmed)) { + unsupportedFields.push('actions') + } + const sectionMatch = trimmed.match(/^\[([A-Za-z0-9_.-]+)\]\s*(?:#.*)?$/) + if (sectionMatch) { + section = sectionMatch[1] + if (section === 'actions' || section.startsWith('actions.')) { + unsupportedFields.push(`[${section}]`) + } + continue + } + + if (section !== 'setup' && section !== 'cleanup') { + continue + } + + const assignment = line.match(/^\s*script\s*=\s*(.*)$/) + if (!assignment) { + continue + } + + const parsed = parseTomlStringValue(lines, index, assignment[1]) + index = parsed.endLineIndex + if (section === 'setup') { + setupScript = parsed.value + } else { + cleanupScript = parsed.value + } + } + + return { setupScript, cleanupScript, unsupportedFields } +} + +function parseTomlStringValue( + lines: string[], + startLineIndex: number, + rawValue: string +): { value: string; endLineIndex: number } { + const value = rawValue.trimStart() + if (value.startsWith('"""') || value.startsWith("'''")) { + const delimiter = value.startsWith('"""') ? '"""' : "'''" + return parseTomlMultilineString(lines, startLineIndex, value.slice(3), delimiter) + } + if (value.startsWith('"')) { + return { value: parseTomlBasicString(value), endLineIndex: startLineIndex } + } + if (value.startsWith("'")) { + return { value: parseTomlLiteralString(value), endLineIndex: startLineIndex } + } + return { value: value.replace(/\s+#.*$/, '').trim(), endLineIndex: startLineIndex } +} + +function parseTomlMultilineString( + lines: string[], + startLineIndex: number, + firstLineRemainder: string, + delimiter: '"""' | "'''" +): { value: string; endLineIndex: number } { + let content = '' + let remainder = firstLineRemainder + for (let index = startLineIndex; index < lines.length; index++) { + if (index > startLineIndex) { + remainder = lines[index] + } + const closeIndex = remainder.indexOf(delimiter) + if (closeIndex >= 0) { + return { + value: content + remainder.slice(0, closeIndex), + endLineIndex: index + } + } + content += `${remainder}\n` + } + return { value: content.trimEnd(), endLineIndex: lines.length - 1 } +} + +function parseTomlBasicString(value: string): string { + const raw = value.slice(0, findTomlStringEnd(value, '"') + 1) + try { + return JSON.parse(raw) as string + } catch { + return raw.slice(1, -1) + } +} + +function parseTomlLiteralString(value: string): string { + const end = findTomlStringEnd(value, "'") + return value.slice(1, end) +} + +function findTomlStringEnd(value: string, quote: '"' | "'"): number { + for (let index = 1; index < value.length; index++) { + if (value[index] !== quote) { + continue + } + if (quote === "'" || !isEscaped(value, index)) { + return index + } + } + return value.length - 1 +} + +function isEscaped(value: string, index: number): boolean { + let slashCount = 0 + for (let cursor = index - 1; cursor >= 0 && value[cursor] === '\\'; cursor--) { + slashCount++ + } + return slashCount % 2 === 1 +} diff --git a/src/shared/setup-script-imports.test.ts b/src/shared/setup-script-imports.test.ts new file mode 100644 index 000000000..97e62d691 --- /dev/null +++ b/src/shared/setup-script-imports.test.ts @@ -0,0 +1,222 @@ +import { describe, expect, it } from 'vitest' +import { inspectSetupScriptImportCandidates } from './setup-script-imports' + +function makeReader(files: Record) { + return async (relativePath: string): Promise => files[relativePath] ?? null +} + +describe('inspectSetupScriptImportCandidates', () => { + it('imports setup and teardown commands from Superset config', async () => { + const candidates = await inspectSetupScriptImportCandidates( + makeReader({ + '.superset/config.json': JSON.stringify({ + setup: ['./.superset/setup.sh', 'bun install'], + teardown: ['./.superset/teardown.sh'], + run: ['bun dev'] + }) + }) + ) + + expect(candidates).toEqual([ + { + provider: 'superset', + label: 'Superset', + files: ['.superset/config.json'], + setup: './.superset/setup.sh\nbun install', + archive: './.superset/teardown.sh', + unsupportedFields: ['run'] + } + ]) + }) + + it('applies Superset local before and after setup overlays', async () => { + const candidates = await inspectSetupScriptImportCandidates( + makeReader({ + '.superset/config.json': JSON.stringify({ + setup: ['bun install'], + teardown: ['docker compose down'], + cwd: 'packages/web' + }), + '.superset/config.local.json': JSON.stringify({ + setup: { + before: ['corepack enable'], + after: ['bun run db:migrate'] + }, + teardown: ['docker compose down --remove-orphans'], + run: ['bun dev'] + }) + }) + ) + + expect(candidates).toEqual([ + { + provider: 'superset', + label: 'Superset', + files: ['.superset/config.json', '.superset/config.local.json'], + setup: 'corepack enable\nbun install\nbun run db:migrate', + archive: 'docker compose down --remove-orphans', + unsupportedFields: ['cwd', 'config.local.run'] + } + ]) + }) + + it('reports unsupported Superset local script object fields', async () => { + const candidates = await inspectSetupScriptImportCandidates( + makeReader({ + '.superset/config.json': JSON.stringify({ + setup: ['bun install'] + }), + '.superset/config.local.json': JSON.stringify({ + setup: { + before: ['corepack enable'], + after: ['bun run db:migrate'], + cwd: 'packages/web' + } + }) + }) + ) + + expect(candidates).toEqual([ + { + provider: 'superset', + label: 'Superset', + files: ['.superset/config.json', '.superset/config.local.json'], + setup: 'corepack enable\nbun install\nbun run db:migrate', + archive: undefined, + unsupportedFields: ['config.local.setup.cwd'] + } + ]) + }) + + it('imports setup commands from cmux project config', async () => { + const candidates = await inspectSetupScriptImportCandidates( + makeReader({ + '.cmux/cmux.json': JSON.stringify({ + commands: [ + { + name: 'Run Unit Tests', + keywords: ['test', 'unit'], + command: './scripts/test-unit.sh' + }, + { + name: 'Setup', + description: 'Initialize submodules and build dependencies', + keywords: ['setup', 'init', 'install'], + command: './scripts/setup.sh', + confirm: true, + cwd: 'packages/web' + } + ] + }) + }) + ) + + expect(candidates).toEqual([ + { + provider: 'cmux', + label: 'cmux', + files: ['.cmux/cmux.json'], + setup: './scripts/setup.sh', + unsupportedFields: ['commands.1.confirm', 'commands.1.cwd'] + } + ]) + }) + + it('imports setup commands from root cmux config when project config is absent', async () => { + const candidates = await inspectSetupScriptImportCandidates( + makeReader({ + 'cmux.json': JSON.stringify({ + commands: [ + { + title: 'Workspace Setup', + keywords: ['setup'], + command: 'pnpm install' + } + ] + }) + }) + ) + + expect(candidates).toEqual([ + { + provider: 'cmux', + label: 'cmux', + files: ['cmux.json'], + setup: 'pnpm install', + unsupportedFields: [] + } + ]) + }) + + it('imports setup and archive commands from Conductor config', async () => { + const candidates = await inspectSetupScriptImportCandidates( + makeReader({ + 'conductor.json': JSON.stringify({ + scripts: { + setup: 'pnpm install', + archive: 'pnpm clean', + run: 'pnpm dev' + }, + runScriptMode: 'manual' + }) + }) + ) + + expect(candidates).toEqual([ + { + provider: 'conductor', + label: 'Conductor', + files: ['conductor.json'], + setup: 'pnpm install', + archive: 'pnpm clean', + unsupportedFields: ['runScriptMode', 'scripts.run'] + } + ]) + }) + + it('imports setup and cleanup scripts from Codex environment config', async () => { + const candidates = await inspectSetupScriptImportCandidates( + makeReader({ + '.codex/environments/environment.toml': ` +[setup] +script = """ +npm ci +pnpm build +""" + +[cleanup] +script = "pnpm clean" + +[actions.test] +command = "pnpm test" +` + }) + ) + + expect(candidates).toEqual([ + { + provider: 'codex', + label: 'Codex environment', + files: ['.codex/environments/environment.toml'], + setup: 'npm ci\npnpm build', + archive: 'pnpm clean', + unsupportedFields: ['[actions.test]'] + } + ]) + }) + + it('ignores malformed or setup-less configs', async () => { + const candidates = await inspectSetupScriptImportCandidates( + makeReader({ + '.superset/config.json': '{', + 'conductor.json': JSON.stringify({ scripts: { run: 'pnpm dev' } }), + '.codex/environments/environment.toml': '[cleanup]\nscript = "pnpm clean"', + '.cmux/cmux.json': JSON.stringify({ + commands: [{ name: 'Build', keywords: ['build'], command: 'pnpm build' }] + }) + }) + ) + + expect(candidates).toEqual([]) + }) +}) diff --git a/src/shared/setup-script-imports.ts b/src/shared/setup-script-imports.ts new file mode 100644 index 000000000..0163b7f06 --- /dev/null +++ b/src/shared/setup-script-imports.ts @@ -0,0 +1,289 @@ +import { inspectCodexEnvironmentConfig } from './setup-script-import-codex-environment' + +export type SetupScriptImportProvider = 'superset' | 'conductor' | 'codex' | 'cmux' + +export type SetupScriptImportCandidate = { + provider: SetupScriptImportProvider + label: string + files: string[] + setup: string + archive?: string + unsupportedFields?: string[] +} + +export type SetupScriptImportFileRead = (relativePath: string) => Promise + +const SUPERSET_CONFIG_PATH = '.superset/config.json' +const SUPERSET_LOCAL_CONFIG_PATH = '.superset/config.local.json' +const CONDUCTOR_CONFIG_PATH = 'conductor.json' +const CMUX_CONFIG_PATHS = ['.cmux/cmux.json', 'cmux.json'] as const + +export async function inspectSetupScriptImportCandidates( + readFile: SetupScriptImportFileRead +): Promise { + const candidates = await Promise.all([ + inspectSupersetConfig(readFile), + inspectConductorConfig(readFile), + inspectCodexEnvironmentConfig(readFile), + inspectCmuxConfig(readFile) + ]) + return candidates.filter( + (candidate): candidate is SetupScriptImportCandidate => candidate != null + ) +} + +async function inspectSupersetConfig( + readFile: SetupScriptImportFileRead +): Promise { + const config = parseJsonObject(await readFile(SUPERSET_CONFIG_PATH)) + if (!config) { + return null + } + + const localConfig = parseJsonObject(await readFile(SUPERSET_LOCAL_CONFIG_PATH)) + const unsupportedFields = collectUnsupportedFields(config, ['run', 'cwd']) + const files = localConfig + ? [SUPERSET_CONFIG_PATH, SUPERSET_LOCAL_CONFIG_PATH] + : [SUPERSET_CONFIG_PATH] + if (localConfig) { + unsupportedFields.push( + ...collectUnsupportedFields(localConfig, ['run', 'cwd']).map( + (field) => `config.local.${field}` + ) + ) + } + + const setup = resolveSupersetScriptValue( + config.setup, + localConfig?.setup, + 'setup', + unsupportedFields + ) + if (!setup) { + return null + } + + collectUnsupportedScriptObjectFields(config.setup, 'setup', unsupportedFields) + collectUnsupportedScriptObjectFields(config.teardown, 'teardown', unsupportedFields) + + return { + provider: 'superset', + label: 'Superset', + files, + setup, + archive: + resolveSupersetScriptValue( + config.teardown, + localConfig?.teardown, + 'teardown', + unsupportedFields + ) || undefined, + unsupportedFields + } +} + +async function inspectConductorConfig( + readFile: SetupScriptImportFileRead +): Promise { + const config = parseJsonObject(await readFile(CONDUCTOR_CONFIG_PATH)) + const scripts = asRecord(config?.scripts) + if (!config || !scripts) { + return null + } + + const setup = normalizeCommandValue(scripts.setup) + if (!setup) { + return null + } + + const unsupportedFields = collectUnsupportedFields(config, [ + 'enterpriseDataPrivacy', + 'runScriptMode' + ]) + for (const field of ['run', 'teardown'] as const) { + if (normalizeCommandValue(scripts[field])) { + unsupportedFields.push(`scripts.${field}`) + } + } + + return { + provider: 'conductor', + label: 'Conductor', + files: [CONDUCTOR_CONFIG_PATH], + setup, + archive: normalizeCommandValue(scripts.archive) || undefined, + unsupportedFields + } +} + +async function inspectCmuxConfig( + readFile: SetupScriptImportFileRead +): Promise { + for (const configPath of CMUX_CONFIG_PATHS) { + const config = parseJsonObject(await readFile(configPath)) + const candidate = config ? buildCmuxSetupCandidate(configPath, config) : null + if (candidate) { + return candidate + } + } + return null +} + +function parseJsonObject(content: string | null): Record | null { + if (!content) { + return null + } + try { + return asRecord(JSON.parse(content)) + } catch { + return null + } +} + +function asRecord(value: unknown): Record | null { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null +} + +function normalizeCommandValue(value: unknown): string { + if (typeof value === 'string') { + return value.trim() + } + if (!Array.isArray(value)) { + return '' + } + const commands = value + .map((item) => (typeof item === 'string' ? item.trim() : '')) + .filter(Boolean) + return commands.join('\n') +} + +function resolveSupersetScriptValue( + baseValue: unknown, + localValue: unknown, + key: 'setup' | 'teardown', + unsupportedFields: string[] +): string { + const baseCommand = normalizeCommandValue(baseValue) + if (localValue === undefined) { + return baseCommand + } + if (typeof localValue === 'string' || Array.isArray(localValue)) { + return normalizeCommandValue(localValue) + } + + const localRecord = asRecord(localValue) + if (!localRecord) { + unsupportedFields.push(`config.local.${key}`) + return baseCommand + } + + for (const field of Object.keys(localRecord)) { + if (field !== 'before' && field !== 'after') { + unsupportedFields.push(`config.local.${key}.${field}`) + } + } + + const beforeCommand = normalizeCommandValue(localRecord.before) + const afterCommand = normalizeCommandValue(localRecord.after) + return [beforeCommand, baseCommand, afterCommand].filter(Boolean).join('\n') +} + +function buildCmuxSetupCandidate( + configPath: string, + config: Record +): SetupScriptImportCandidate | null { + const commands = Array.isArray(config.commands) ? config.commands : [] + for (let index = 0; index < commands.length; index++) { + const command = asRecord(commands[index]) + if (!command || !isCmuxSetupCommand(command)) { + continue + } + + const setup = normalizeCommandValue(command.command) + if (!setup) { + continue + } + + return { + provider: 'cmux', + label: 'cmux', + files: [configPath], + setup, + unsupportedFields: collectUnsupportedCmuxCommandFields(command, index) + } + } + return null +} + +function isCmuxSetupCommand(command: Record): boolean { + if (typeof command.command !== 'string' || !command.command.trim()) { + return false + } + + const name = normalizeMatchText(command.name) + const title = normalizeMatchText(command.title) + const labels = [name, title].filter(Boolean) + if ( + labels.some((label) => + ['setup', 'project setup', 'workspace setup', 'repository setup'].includes(label) + ) + ) { + return true + } + + const keywords = getStringArray(command.keywords).map(normalizeMatchText) + const hasSetupKeyword = keywords.some((keyword) => + ['setup', 'init', 'initialize', 'install'].includes(keyword) + ) + if (!hasSetupKeyword) { + return false + } + + const commandText = normalizeMatchText(command.command) + return labels.some((label) => label.includes('setup')) || /\bsetup\b/.test(commandText) +} + +function normalizeMatchText(value: unknown): string { + return typeof value === 'string' ? value.trim().toLowerCase().replace(/\s+/g, ' ') : '' +} + +function getStringArray(value: unknown): string[] { + return Array.isArray(value) + ? value.filter((item): item is string => typeof item === 'string') + : [] +} + +function collectUnsupportedCmuxCommandFields( + command: Record, + commandIndex: number +): string[] { + const supportedFields = new Set(['name', 'title', 'description', 'keywords', 'command']) + return Object.keys(command) + .filter((field) => !supportedFields.has(field)) + .map((field) => `commands.${commandIndex}.${field}`) +} + +function collectUnsupportedFields( + source: Record, + fieldNames: readonly string[] +): string[] { + return fieldNames.filter((field) => source[field] !== undefined) +} + +function collectUnsupportedScriptObjectFields( + value: unknown, + prefix: string, + unsupportedFields: string[] +): void { + const record = asRecord(value) + if (!record) { + return + } + for (const field of ['before', 'after'] as const) { + if (record[field] !== undefined) { + unsupportedFields.push(`${prefix}.${field}`) + } + } +} diff --git a/src/shared/types.ts b/src/shared/types.ts index b594bd8f5..190aca818 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -2060,6 +2060,7 @@ export type PersistedUIState = { * suppress the nag — no further thresholds, no notifications. */ starNagCompleted?: boolean trustedOrcaHooks?: PersistedTrustedOrcaHooks + setupScriptPromptDismissedRepoIds?: string[] /** Whether the experimental pet overlay is currently visible. Separate * from the experimentalPet settings flag so "Hide pet" from the * status-bar menu is a reversible dismiss (re-show without re-enabling the diff --git a/tests/e2e/setup-script-import.spec.ts b/tests/e2e/setup-script-import.spec.ts new file mode 100644 index 000000000..b57ae59d8 --- /dev/null +++ b/tests/e2e/setup-script-import.spec.ts @@ -0,0 +1,199 @@ +import { execFileSync } from 'node:child_process' +import { mkdirSync, rmSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import type { Locator, Page } from '@stablyai/playwright-test' +import { test, expect } from './helpers/orca-app' +import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' + +function runGit(repoPath: string, args: string[]): void { + execFileSync('git', args, { cwd: repoPath, stdio: 'pipe' }) +} + +function createGitRepo(repoPath: string): void { + rmSync(repoPath, { recursive: true, force: true }) + mkdirSync(repoPath, { recursive: true }) + runGit(repoPath, ['init']) + runGit(repoPath, ['config', 'user.email', 'e2e@test.local']) + runGit(repoPath, ['config', 'user.name', 'E2E Test']) + writeFileSync(path.join(repoPath, 'README.md'), '# Setup import E2E\n') + runGit(repoPath, ['add', '-A']) + runGit(repoPath, ['commit', '-m', 'Initial commit']) +} + +function createSupersetSetupRepo(repoPath: string): string { + createGitRepo(repoPath) + mkdirSync(path.join(repoPath, '.superset'), { recursive: true }) + writeFileSync( + path.join(repoPath, '.superset', 'config.json'), + `${JSON.stringify( + { + setup: ['bun install'], + teardown: ['docker compose down'], + cwd: 'packages/web' + }, + null, + 2 + )}\n` + ) + writeFileSync( + path.join(repoPath, '.superset', 'config.local.json'), + `${JSON.stringify( + { + setup: { + before: ['corepack enable'], + after: ['bun run db:migrate'] + }, + teardown: ['docker compose down --remove-orphans'], + run: ['bun dev'] + }, + null, + 2 + )}\n` + ) + return repoPath +} + +function createCmuxSetupRepo(repoPath: string): string { + createGitRepo(repoPath) + mkdirSync(path.join(repoPath, '.cmux'), { recursive: true }) + writeFileSync( + path.join(repoPath, '.cmux', 'cmux.json'), + `${JSON.stringify( + { + commands: [ + { + name: 'Run Unit Tests', + keywords: ['test', 'unit'], + command: './scripts/test-unit.sh' + }, + { + name: 'Setup', + description: 'Initialize submodules and build dependencies', + keywords: ['setup', 'init', 'install'], + command: './scripts/setup.sh', + confirm: true, + cwd: 'packages/web' + } + ] + }, + null, + 2 + )}\n` + ) + return repoPath +} + +async function addAndActivateRepo(page: Page, repoPath: string): Promise { + return page.evaluate(async (targetRepoPath) => { + const store = window.__store + if (!store) { + throw new Error('window.__store is not available') + } + + const addedRepo = await store.getState().addRepoPath(targetRepoPath) + if (!addedRepo) { + throw new Error(`Failed to add repo at ${targetRepoPath}`) + } + + await store.getState().fetchWorktrees(addedRepo.id) + const state = store.getState() + const worktree = state.worktreesByRepo[addedRepo.id]?.find( + (entry) => entry.path === targetRepoPath + ) + if (!worktree) { + throw new Error(`Failed to find primary worktree for ${targetRepoPath}`) + } + + state.setActiveRepo(addedRepo.id) + state.setActiveWorktree(worktree.id) + state.setSidebarOpen(true) + return addedRepo.id + }, repoPath) +} + +async function openRepoSettings(page: Page, repoId: string): Promise { + await page.evaluate((targetRepoId) => { + const state = window.__store?.getState() + state?.setSettingsSearchQuery('') + state?.openSettingsTarget({ pane: 'repo', repoId: targetRepoId }) + state?.openSettingsPage() + }, repoId) + + const repoSettings = page.locator(`[data-settings-section="repo-${repoId}"]`) + await expect(repoSettings).toBeVisible({ timeout: 10_000 }) + await expect(repoSettings.getByText('Local Settings Commands').first()).toBeVisible() + return repoSettings +} + +async function openImportedSetupSettingsFromToast(page: Page, repoId: string): Promise { + await page.getByRole('button', { name: 'View in Settings' }).click() + const localCommands = page.locator(`[id="repo-${repoId}-local-commands"]`) + await expect(localCommands).toBeVisible({ timeout: 10_000 }) + await expect(localCommands.getByText('Local Settings Commands').first()).toBeVisible() + return localCommands +} + +async function expectSettingsInputValue(container: Locator, value: string): Promise { + await expect + .poll( + () => + container + .locator('input') + .evaluateAll( + (inputs, expectedValue) => + inputs.some((input) => (input as HTMLInputElement).value === expectedValue), + value + ), + { + timeout: 10_000, + message: `Settings input value "${value}" was not visible` + } + ) + .toBe(true) +} + +test.describe('Setup script import prompt', () => { + test.beforeEach(async ({ orcaPage }) => { + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + }) + + test('imports Superset local overlays through the prompt UI', async ({ orcaPage }, testInfo) => { + const repoPath = createSupersetSetupRepo(testInfo.outputPath('superset-setup-repo')) + const repoId = await addAndActivateRepo(orcaPage, repoPath) + + await expect( + orcaPage.getByText(/Detected setup config from Superset \(\.superset\/config\.json \+1\)\./) + ).toBeVisible({ timeout: 15_000 }) + + await orcaPage.getByRole('button', { name: 'Import setup' }).click() + + await expect(orcaPage.getByText('Setup script imported')).toBeVisible() + await expect( + orcaPage.getByText("2 unsupported fields skipped. Saved to this repo's local settings.") + ).toBeVisible() + + const localCommands = await openImportedSetupSettingsFromToast(orcaPage, repoId) + await expectSettingsInputValue(localCommands, 'corepack enable') + await expectSettingsInputValue(localCommands, 'bun install') + await expectSettingsInputValue(localCommands, 'bun run db:migrate') + await expectSettingsInputValue(localCommands, 'docker compose down --remove-orphans') + }) + + test('imports cmux setup commands through the prompt UI', async ({ orcaPage }, testInfo) => { + const repoPath = createCmuxSetupRepo(testInfo.outputPath('cmux-setup-repo')) + const repoId = await addAndActivateRepo(orcaPage, repoPath) + + await expect( + orcaPage.getByText(/Detected setup config from cmux \(\.cmux\/cmux\.json\)\./) + ).toBeVisible({ timeout: 15_000 }) + + await orcaPage.getByRole('button', { name: 'Import setup' }).click() + + await expect(orcaPage.getByText('Setup script imported')).toBeVisible() + + const repoSettings = await openRepoSettings(orcaPage, repoId) + await expectSettingsInputValue(repoSettings, './scripts/setup.sh') + await expect(repoSettings.getByText('No local archive commands configured.')).toBeVisible() + }) +})