Improve setup script discoverability (#2402)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -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)) {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<SetupScriptImportCandidate[]>
|
||||
createIssueCommandRunner: (args: {
|
||||
repoId: string
|
||||
worktreePath: string
|
||||
|
||||
@@ -1755,6 +1755,9 @@ const api = {
|
||||
}): Promise<{ hasHooks: boolean; hooks: unknown; mayNeedUpdate: boolean }> =>
|
||||
ipcRenderer.invoke('hooks:check', args),
|
||||
|
||||
inspectSetupScriptImports: (args: { repoId: string }): Promise<unknown[]> =>
|
||||
ipcRenderer.invoke('hooks:inspectSetupScriptImports', args),
|
||||
|
||||
createIssueCommandRunner: (args: {
|
||||
repoId: string
|
||||
worktreePath: string
|
||||
|
||||
@@ -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({
|
||||
</SearchableSetting>
|
||||
|
||||
<SearchableSetting
|
||||
id={getRepositoryLocalCommandsSectionId(repo.id)}
|
||||
title="Local Settings Commands"
|
||||
description="Personal setup and archive commands stored locally on this machine."
|
||||
keywords={['local', 'personal', 'setup', 'archive']}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export function getRepositoryLocalCommandsSectionId(repoId: string): string {
|
||||
return `repo-${repoId}-local-commands`
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Download, LoaderCircle, Settings, X } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { useAppStore } from '@/store'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { getRepositoryLocalCommandsSectionId } from '@/components/settings/repository-settings-targets'
|
||||
import {
|
||||
checkRuntimeHooks,
|
||||
inspectRuntimeSetupScriptImports,
|
||||
type HookCheckResult
|
||||
} from '@/runtime/runtime-hooks-client'
|
||||
import { getDefaultRepoHookSettings } from '../../../../shared/constants'
|
||||
import { normalizeHookCommandSourcePolicy } from '../../../../shared/hook-command-source-policy'
|
||||
import { isGitRepoKind } from '../../../../shared/repo-kind'
|
||||
import type { Repo, RepoHookSettings } from '../../../../shared/types'
|
||||
import type { SetupScriptImportCandidate } from '../../../../shared/setup-script-imports'
|
||||
|
||||
type PromptState = {
|
||||
repoId: string
|
||||
hasEffectiveSetup: boolean
|
||||
hasSharedHooks: boolean
|
||||
candidate: SetupScriptImportCandidate | null
|
||||
}
|
||||
|
||||
function hasEffectiveSetupCommand(repo: Repo, hooksResult: HookCheckResult): boolean {
|
||||
const localSetup = repo.hookSettings?.scripts?.setup?.trim()
|
||||
const sharedSetup = hooksResult.hooks?.scripts?.setup?.trim()
|
||||
const rawPolicy = repo.hookSettings?.commandSourcePolicy
|
||||
const sourcePolicy = normalizeHookCommandSourcePolicy(rawPolicy)
|
||||
|
||||
if (sourcePolicy === 'local-only') {
|
||||
return Boolean(localSetup)
|
||||
}
|
||||
|
||||
if (sourcePolicy === 'run-both') {
|
||||
return Boolean(sharedSetup || localSetup)
|
||||
}
|
||||
|
||||
// Why: local setup commands saved before commandSourcePolicy existed still
|
||||
// run when there is no tracked hook file; the prompt should respect that.
|
||||
if (rawPolicy === undefined && !hooksResult.hasHooks) {
|
||||
return Boolean(localSetup)
|
||||
}
|
||||
|
||||
return Boolean(sharedSetup)
|
||||
}
|
||||
|
||||
function buildImportedHookSettings(
|
||||
repo: Repo,
|
||||
candidate: SetupScriptImportCandidate,
|
||||
hasSharedHooks: boolean
|
||||
): RepoHookSettings {
|
||||
const defaults = getDefaultRepoHookSettings()
|
||||
const current = repo.hookSettings
|
||||
return {
|
||||
...defaults,
|
||||
...current,
|
||||
setupRunPolicy: current?.setupRunPolicy ?? defaults.setupRunPolicy,
|
||||
// Why: imported setup commands are stored as local settings. If a shared
|
||||
// hook file exists, run-both preserves its archive hook; otherwise local
|
||||
// settings need to be authoritative so the imported setup actually runs.
|
||||
commandSourcePolicy: hasSharedHooks ? 'run-both' : 'local-only',
|
||||
scripts: {
|
||||
...defaults.scripts,
|
||||
...current?.scripts,
|
||||
setup: candidate.setup,
|
||||
archive: candidate.archive ?? current?.scripts?.archive ?? defaults.scripts.archive
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function formatCandidateSource(candidate: SetupScriptImportCandidate): string {
|
||||
const [primaryFile, ...remainingFiles] = candidate.files
|
||||
if (!primaryFile) {
|
||||
return candidate.label
|
||||
}
|
||||
return remainingFiles.length > 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<PromptState | null>(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<void> {
|
||||
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 (
|
||||
<div className="px-3 pb-2">
|
||||
<div className="relative rounded-lg border border-sidebar-border bg-card p-3 text-card-foreground shadow-xs">
|
||||
<Badge variant="outline" className="h-5 px-1.5 text-[11px]">
|
||||
Setup
|
||||
</Badge>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
aria-label="Dismiss setup scripts"
|
||||
className="absolute right-2 top-2 text-muted-foreground"
|
||||
onClick={handleDismiss}
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" sideOffset={4}>
|
||||
Dismiss
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
<p className="mt-2 pr-6 text-sm font-semibold leading-snug">{title}</p>
|
||||
<p className="mt-1 text-xs leading-snug text-muted-foreground">
|
||||
{candidateSource ? (
|
||||
<>
|
||||
Detected setup config from <span className="break-words">{candidateSource}</span>.
|
||||
</>
|
||||
) : (
|
||||
<>Automate workspace setup for {activeRepo.displayName}.</>
|
||||
)}
|
||||
</p>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="mt-3 h-7 w-full text-xs"
|
||||
onClick={candidate ? () => void handleImport() : handleConfigure}
|
||||
disabled={isImporting}
|
||||
>
|
||||
{isImporting ? (
|
||||
<LoaderCircle className="size-3.5 animate-spin" />
|
||||
) : (
|
||||
<ActionIcon className="size-3.5" />
|
||||
)}
|
||||
<span className={cn('truncate', isImporting && 'text-muted-foreground')}>
|
||||
{actionLabel}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(SetupScriptPromptCard)
|
||||
@@ -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}
|
||||
/>
|
||||
|
||||
<SetupScriptPromptCard />
|
||||
|
||||
{/* Fixed bottom toolbar */}
|
||||
<SidebarToolbar />
|
||||
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
|
||||
@@ -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<GlobalSettings, 'activeRuntimeEnvironmentId'> | null | undefined,
|
||||
repoId: string
|
||||
): Promise<SetupScriptImportCandidate[]> {
|
||||
const target = getActiveRuntimeTarget(settings)
|
||||
if (target.kind !== 'environment') {
|
||||
return window.api.hooks.inspectSetupScriptImports({ repoId })
|
||||
}
|
||||
return callRuntimeRpc<SetupScriptImportCandidate[]>(
|
||||
target,
|
||||
'repo.setupScriptImports',
|
||||
{ repo: repoId },
|
||||
{ timeoutMs: 15_000 }
|
||||
)
|
||||
}
|
||||
|
||||
export async function readRuntimeIssueCommand(
|
||||
settings: Pick<GlobalSettings, 'activeRuntimeEnvironmentId'> | null | undefined,
|
||||
repoId: string
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -26,12 +26,12 @@ type RepoUpdate = Partial<
|
||||
>
|
||||
>
|
||||
|
||||
const updateRepoChainsByStore = new WeakMap<() => AppState, Map<string, Promise<void>>>()
|
||||
const updateRepoChainsByStore = new WeakMap<() => AppState, Map<string, Promise<boolean>>>()
|
||||
|
||||
function getRepoUpdateChains(get: () => AppState) {
|
||||
function getRepoUpdateChains(get: () => AppState): Map<string, Promise<boolean>> {
|
||||
let chains = updateRepoChainsByStore.get(get)
|
||||
if (!chains) {
|
||||
chains = new Map<string, Promise<void>>()
|
||||
chains = new Map<string, Promise<boolean>>()
|
||||
updateRepoChainsByStore.set(get, chains)
|
||||
}
|
||||
return chains
|
||||
@@ -45,7 +45,7 @@ export type RepoSlice = {
|
||||
addRepoPath: (path: string, kind?: 'git' | 'folder') => Promise<Repo | null>
|
||||
addNonGitFolder: (path: string) => Promise<Repo | null>
|
||||
removeRepo: (repoId: string) => Promise<void>
|
||||
updateRepo: (repoId: string, updates: RepoUpdate) => Promise<void>
|
||||
updateRepo: (repoId: string, updates: RepoUpdate) => Promise<boolean>
|
||||
setActiveRepo: (repoId: string | null) => void
|
||||
reorderRepos: (orderedIds: string[]) => Promise<void>
|
||||
}
|
||||
@@ -76,7 +76,10 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (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<AppState, [], [], RepoSlice> = (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<AppState, [], [], RepoSlice> = (set,
|
||||
}
|
||||
}
|
||||
void next.then(cleanup, cleanup)
|
||||
await next
|
||||
return next
|
||||
},
|
||||
|
||||
setActiveRepo: (repoId) => set({ activeRepoId: repoId }),
|
||||
|
||||
@@ -138,6 +138,19 @@ function filterTrustedOrcaHooksToValidRepos(
|
||||
return next
|
||||
}
|
||||
|
||||
function filterRepoIdListToValidRepos(value: unknown, validRepoIds: Set<string>): 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<AppState, [], [], UISlice> = (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<AppState, [], [], UISlice> = (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
|
||||
|
||||
@@ -763,6 +763,8 @@ function createRuntimeNamespaceApi(prefix: string): never {
|
||||
function createHooksApi(): NonNullable<Partial<PreloadApi>['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 }),
|
||||
|
||||
@@ -360,6 +360,7 @@ export function getDefaultUIState(): PersistedUIState {
|
||||
dismissedUpdateVersion: null,
|
||||
lastUpdateCheckAt: null,
|
||||
trustedOrcaHooks: {},
|
||||
setupScriptPromptDismissedRepoIds: [],
|
||||
acknowledgedAgentsByPaneKey: {},
|
||||
workspaceCleanup: { dismissals: {} },
|
||||
featureTipsSeenIds: []
|
||||
|
||||
@@ -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<SetupScriptImportCandidate | null> {
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { inspectSetupScriptImportCandidates } from './setup-script-imports'
|
||||
|
||||
function makeReader(files: Record<string, string>) {
|
||||
return async (relativePath: string): Promise<string | null> => 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([])
|
||||
})
|
||||
})
|
||||
@@ -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<string | null>
|
||||
|
||||
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<SetupScriptImportCandidate[]> {
|
||||
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<SetupScriptImportCandidate | null> {
|
||||
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<SetupScriptImportCandidate | null> {
|
||||
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<SetupScriptImportCandidate | null> {
|
||||
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<string, unknown> | null {
|
||||
if (!content) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
return asRecord(JSON.parse(content))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: 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<string, unknown>
|
||||
): 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<string, unknown>): 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<string, unknown>,
|
||||
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<string, unknown>,
|
||||
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}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<string> {
|
||||
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<Locator> {
|
||||
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<Locator> {
|
||||
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<void> {
|
||||
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()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user