diff --git a/config/ast-grep/rule-tests/__snapshots__/claude-chat-entrypoint-callers-snapshot.yml b/config/ast-grep/rule-tests/__snapshots__/claude-chat-entrypoint-callers-snapshot.yml new file mode 100644 index 00000000000..6bd5f856dd1 --- /dev/null +++ b/config/ast-grep/rule-tests/__snapshots__/claude-chat-entrypoint-callers-snapshot.yml @@ -0,0 +1,14 @@ +id: claude-chat-entrypoint-callers +snapshots: + "import { withOrcaClaudeChatEntrypoint as stamp } from './claude-chat-entrypoint'": + labels: + - source: withOrcaClaudeChatEntrypoint + style: primary + start: 9 + end: 37 + 'withOrcaClaudeChatEntrypoint(env, platform)': + labels: + - source: withOrcaClaudeChatEntrypoint + style: primary + start: 0 + end: 28 diff --git a/config/ast-grep/rule-tests/__snapshots__/claude-chat-entrypoint-owner-snapshot.yml b/config/ast-grep/rule-tests/__snapshots__/claude-chat-entrypoint-owner-snapshot.yml new file mode 100644 index 00000000000..05f177c95df --- /dev/null +++ b/config/ast-grep/rule-tests/__snapshots__/claude-chat-entrypoint-owner-snapshot.yml @@ -0,0 +1,20 @@ +id: claude-chat-entrypoint-owner +snapshots: + "const env = { CLAUDE_CODE_ENTRYPOINT: 'orca' }": + labels: + - source: CLAUDE_CODE_ENTRYPOINT + style: primary + start: 14 + end: 36 + const identity = 'sdk-cli': + labels: + - source: sdk-cli + style: primary + start: 18 + end: 25 + "env['claude_code_entrypoint'] = 'other'": + labels: + - source: claude_code_entrypoint + style: primary + start: 5 + end: 27 diff --git a/config/ast-grep/rule-tests/__snapshots__/claude-entrypoint-key-owner-snapshot.yml b/config/ast-grep/rule-tests/__snapshots__/claude-entrypoint-key-owner-snapshot.yml new file mode 100644 index 00000000000..ea2790098fb --- /dev/null +++ b/config/ast-grep/rule-tests/__snapshots__/claude-entrypoint-key-owner-snapshot.yml @@ -0,0 +1,14 @@ +id: claude-entrypoint-key-owner +snapshots: + "env[CLAUDE_ENTRYPOINT_ENV] = 'orca'": + labels: + - source: CLAUDE_ENTRYPOINT_ENV + style: primary + start: 4 + end: 25 + "import { CLAUDE_ENTRYPOINT_ENV as key } from './claude-chat-entrypoint'": + labels: + - source: CLAUDE_ENTRYPOINT_ENV + style: primary + start: 9 + end: 30 diff --git a/config/ast-grep/rule-tests/claude-chat-entrypoint-callers-test.yml b/config/ast-grep/rule-tests/claude-chat-entrypoint-callers-test.yml new file mode 100644 index 00000000000..cca0fcf607c --- /dev/null +++ b/config/ast-grep/rule-tests/claude-chat-entrypoint-callers-test.yml @@ -0,0 +1,6 @@ +id: claude-chat-entrypoint-callers +valid: + - 'stripInheritedClaudeSessionEnv(env)' +invalid: + - 'withOrcaClaudeChatEntrypoint(env, platform)' + - "import { withOrcaClaudeChatEntrypoint as stamp } from './claude-chat-entrypoint'" diff --git a/config/ast-grep/rule-tests/claude-chat-entrypoint-owner-test.yml b/config/ast-grep/rule-tests/claude-chat-entrypoint-owner-test.yml new file mode 100644 index 00000000000..87a75f4a143 --- /dev/null +++ b/config/ast-grep/rule-tests/claude-chat-entrypoint-owner-test.yml @@ -0,0 +1,8 @@ +id: claude-chat-entrypoint-owner +valid: + - 'const env = withOrcaClaudeChatEntrypoint(configured, platform)' + - "const binary = 'orca'" +invalid: + - "const env = { CLAUDE_CODE_ENTRYPOINT: 'orca' }" + - "env['claude_code_entrypoint'] = 'other'" + - "const identity = 'sdk-cli'" diff --git a/config/ast-grep/rule-tests/claude-entrypoint-key-owner-test.yml b/config/ast-grep/rule-tests/claude-entrypoint-key-owner-test.yml new file mode 100644 index 00000000000..c63b8b38063 --- /dev/null +++ b/config/ast-grep/rule-tests/claude-entrypoint-key-owner-test.yml @@ -0,0 +1,6 @@ +id: claude-entrypoint-key-owner +valid: + - "const binary = 'orca'" +invalid: + - "env[CLAUDE_ENTRYPOINT_ENV] = 'orca'" + - "import { CLAUDE_ENTRYPOINT_ENV as key } from './claude-chat-entrypoint'" diff --git a/config/ast-grep/rules/claude-chat-entrypoint.yml b/config/ast-grep/rules/claude-chat-entrypoint.yml new file mode 100644 index 00000000000..cb56d1fa679 --- /dev/null +++ b/config/ast-grep/rules/claude-chat-entrypoint.yml @@ -0,0 +1,117 @@ +id: claude-chat-entrypoint-owner +language: typescript +severity: error +message: Keep the Claude identity literal in claude-chat-entrypoint.ts. +files: ['src/**'] +ignores: + - '**/*.test.*' + - '**/*.test-fixtures.*' + - '**/__fixtures__/**' + - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' +rule: + all: + - any: + - kind: string_fragment + - kind: property_identifier + - kind: identifier + - regex: '(?i)^(CLAUDE_CODE_ENTRYPOINT|sdk-cli)$' +--- +id: claude-chat-entrypoint-owner-tsx +language: tsx +severity: error +message: Keep the Claude identity literal in claude-chat-entrypoint.ts. +files: ['src/**'] +ignores: + - '**/*.test.*' + - '**/*.test-fixtures.*' + - '**/__fixtures__/**' + - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' +rule: + all: + - any: + - kind: string_fragment + - kind: property_identifier + - kind: identifier + - regex: '(?i)^(CLAUDE_CODE_ENTRYPOINT|sdk-cli)$' +--- +id: claude-chat-entrypoint-callers +language: typescript +severity: error +message: Only structured native chat and its own probes may apply the chat identity. +files: ['src/**'] +ignores: + - '**/*.test.*' + - '**/*.test-fixtures.*' + - '**/__fixtures__/**' + - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' + - 'src/main/claude/claude-stream-json-connection.ts' + - 'src/main/claude/claude-agent-sdk-process-spawn.ts' + - 'src/main/claude/structured/launch/claude-structured-child-env.ts' + - 'src/main/claude/claude-model-catalog-probe.ts' +rule: + all: + - any: + - kind: string_fragment + - kind: property_identifier + - kind: identifier + - regex: '^withOrcaClaudeChatEntrypoint$' +--- +id: claude-chat-entrypoint-callers-tsx +language: tsx +severity: error +message: Only structured native chat and its own probes may apply the chat identity. +files: ['src/**'] +ignores: + - '**/*.test.*' + - '**/*.test-fixtures.*' + - '**/__fixtures__/**' + - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' + - 'src/main/claude/claude-stream-json-connection.ts' + - 'src/main/claude/claude-agent-sdk-process-spawn.ts' + - 'src/main/claude/structured/launch/claude-structured-child-env.ts' + - 'src/main/claude/claude-model-catalog-probe.ts' +rule: + all: + - any: + - kind: string_fragment + - kind: property_identifier + - kind: identifier + - regex: '^withOrcaClaudeChatEntrypoint$' +--- +id: claude-entrypoint-key-owner +language: typescript +severity: error +message: Only the chat identity owner and inherited-session isolation may access this key directly. +files: ['src/**'] +ignores: + - '**/*.test.*' + - '**/*.test-fixtures.*' + - '**/__fixtures__/**' + - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' + - 'src/shared/agent-launch/startup/claude-parent-session-env.ts' +rule: + all: + - any: + - kind: string_fragment + - kind: property_identifier + - kind: identifier + - regex: '^CLAUDE_ENTRYPOINT_ENV$' +--- +id: claude-entrypoint-key-owner-tsx +language: tsx +severity: error +message: Only the chat identity owner and inherited-session isolation may access this key directly. +files: ['src/**'] +ignores: + - '**/*.test.*' + - '**/*.test-fixtures.*' + - '**/__fixtures__/**' + - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' + - 'src/shared/agent-launch/startup/claude-parent-session-env.ts' +rule: + all: + - any: + - kind: string_fragment + - kind: property_identifier + - kind: identifier + - regex: '^CLAUDE_ENTRYPOINT_ENV$' diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 67ac9d1f775..36b07604a3e 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -551,7 +551,6 @@ 2 src/main/worker-threads/forked-child-entry-path.ts 4 src/main/workspace-hooks/hooks.ts 10 src/main/workspace-hooks/issue-command-file.ts -4 src/main/workspace-hooks/worktree-runner-script.ts 1 src/main/workspaces/catalog/folder-repo-git-conversion.ts 2 src/main/workspaces/catalog/folder-upgrade-worktree-path.ts 3 src/main/workspaces/execution-host/project-runtime-git-router.ts diff --git a/docs/assets/readme-downloads.svg b/docs/assets/readme-downloads.svg index f1d9f61f62f..25b9a04169b 100644 --- a/docs/assets/readme-downloads.svg +++ b/docs/assets/readme-downloads.svg @@ -1,5 +1,5 @@ - - downloads: 164m + + downloads: 168m @@ -15,7 +15,7 @@ downloads downloads - 164m - 164m + 168m + 168m diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 5100a3cb94a..f14faed6778 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -2988,7 +2988,12 @@ "skip": "Skip", "step": "Step {{step}}", "other": "Other…", - "answerPlaceholder": "Type your answer" + "answerPlaceholder": "Type your answer", + "optionPreview": "{{option}} preview", + "previewPosition": "{{current}} of {{total}}", + "chosen": "Chosen", + "chooseThis": "Choose this", + "viewPreview": "View" }, "permission": { "reason": "Reason: ", diff --git a/mobile/src/session/native-chat/input/MobileNativeChatAsk.previews.test.tsx b/mobile/src/session/native-chat/input/MobileNativeChatAsk.previews.test.tsx new file mode 100644 index 00000000000..6abc1652572 --- /dev/null +++ b/mobile/src/session/native-chat/input/MobileNativeChatAsk.previews.test.tsx @@ -0,0 +1,165 @@ +import { createElement, type ReactNode } from 'react' +import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, expect, it, vi, type Mock } from 'vitest' +import type { AskPrompt } from '../../../../../src/shared/native-chat/input/native-chat-ask-types' +import { MobileNativeChatAsk } from './MobileNativeChatAsk' + +vi.mock('react-native', () => ({ + Keyboard: { dismiss: vi.fn() }, + Platform: { select: (options: { ios: unknown }) => options.ios }, + Pressable: 'Pressable', + ScrollView: 'ScrollView', + Text: 'Text', + View: 'View', + StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 } +})) +vi.mock('lucide-react-native', () => ({ Check: 'Check' })) +vi.mock('../../../components/composer-input/MessageBox', () => ({ MessageBox: 'MessageBox' })) +vi.mock('../transcript/MobileNativeChatQuestionText', () => ({ + MobileNativeChatQuestionText: 'QuestionText' +})) +vi.mock('./MobileNativeChatCardHeaderAction', () => ({ + MobileNativeChatCardHeaderAction: () => null +})) +vi.mock('../../../components/bottom-drawer/keyed-bottom-drawer', () => ({ + KeyedBottomDrawer: ({ + sheet, + children + }: { + sheet: number | null + children: (index: number) => ReactNode + }) => (sheet === null ? null : children(sheet)) +})) +vi.mock('../../../components/nav-bar/SheetHeader', () => ({ + SheetHeader: ({ onClose }: { onClose: () => void }) => + createElement('button', { accessibilityLabel: 'Close viewer', onPress: onClose }) +})) + +let renderer: ReactTestRenderer +const compactedPreview = `${'| panes |'.repeat(450)}…` +function prompt(multiSelect = false): AskPrompt { + return { + questions: [ + { + question: 'Which layout?', + header: 'Layout', + multiSelect, + options: [ + { label: 'First', preview: 'A\t|\n𠀀\t|' }, + { label: 'No preview' }, + { label: 'Last', preview: compactedPreview } + ] + } + ] + } +} +function buttons(): ReactTestInstance[] { + return renderer.root.findAll( + (node) => String(node.type) === 'Pressable' || String(node.type) === 'button' + ) +} +function button(label: string): ReactTestInstance { + return buttons().find((node) => node.props.accessibilityLabel === label)! +} +function row(index: number): ReactTestInstance { + return buttons().filter((node) => ['radio', 'checkbox'].includes(node.props.accessibilityRole))[ + index + ]! +} +function textAction(label: string): ReactTestInstance { + return buttons().find((node) => + node + .findAll((child) => String(child.type) === 'Text') + .some((text) => text.children.includes(label)) + )! +} +function press(node: ReactTestInstance): void { + act(() => node.props.onPress()) +} +type Answer = Parameters[0]['onAnswer'] +function mount(value: AskPrompt): Mock { + const onAnswer = vi.fn(async () => true) + act(() => { + renderer = create(createElement(MobileNativeChatAsk, { prompt: value, onAnswer })) + }) + return onAnswer +} + +afterEach(() => { + act(() => renderer?.unmount()) + vi.useRealTimers() +}) + +it('inspects every preview without choosing, and keeps the original option when choosing and submitting', async () => { + vi.useFakeTimers() + const onAnswer = mount(prompt()) + expect(button('First preview')).toBeDefined() + expect(button('Last preview')).toBeDefined() + expect(row(2).props.accessibilityState.checked).toBe(false) + press(button('First preview')) + expect(renderer.root.findByProps({ selectable: true }).props.children).toBe('A\t|\n𠀀\t|') + // Paging crosses the option with no preview; inspection does not change the answer. + press( + buttons().find( + (node) => node.props.accessibilityLabel === 'Last preview' && node.props.accessibilityState + )! + ) + expect( + renderer.root + .findAll((node) => String(node.type) === 'Text') + .some((node) => node.children.includes(compactedPreview)) + ).toBe(true) + press(button('Close viewer')) + act(() => { + vi.runAllTimers() + }) + expect(onAnswer).not.toHaveBeenCalled() + expect(row(2).props.accessibilityState.checked).toBe(false) + press(button('Last preview')) + press(button('Choose this')) + act(() => { + vi.runAllTimers() + }) + expect(row(2).props.accessibilityState.checked).toBe(true) + expect(onAnswer).not.toHaveBeenCalled() + press(button('Last preview')) + press(button('Chosen')) + press(row(2)) + expect(row(2).props.accessibilityState.checked).toBe(true) + await act(async () => textAction('Submit').props.onPress()) + expect(onAnswer).toHaveBeenCalledWith([{ indices: [2] }], expect.any(Function)) +}) + +it('preserves generic multi choices while inspecting and choosing, with row checkbox removal', async () => { + const onAnswer = mount(prompt(true)) + press(row(0)) + press(button('Last preview')) + press(button('Choose this')) + press(button('Last preview')) + press(button('Chosen')) + expect(row(0).props.accessibilityState.checked).toBe(true) + expect(row(2).props.accessibilityState.checked).toBe(true) + press(row(0)) + await act(async () => textAction('Submit').props.onPress()) + expect(onAnswer).toHaveBeenCalledWith([{ indices: [2] }], expect.any(Function)) +}) + +it('retains automatic answer for an ordinary question and disables the viewer choice while pending', async () => { + vi.useFakeTimers() + const plain = prompt() + plain.questions[0]!.options = [{ label: 'Plain' }] + const onAnswer = mount(plain) + press(row(0)) + await act(async () => { + vi.runAllTimers() + }) + expect(onAnswer).toHaveBeenCalledWith([{ indices: [0] }], expect.any(Function)) + act(() => renderer.unmount()) + act(() => { + renderer = create( + createElement(MobileNativeChatAsk, { prompt: prompt(), answerPending: true, onAnswer }) + ) + }) + press(button('Last preview')) + expect(button('Choose this').props.disabled).toBe(true) +}) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatAsk.styles.ts b/mobile/src/session/native-chat/input/MobileNativeChatAsk.styles.ts new file mode 100644 index 00000000000..cc895c5404f --- /dev/null +++ b/mobile/src/session/native-chat/input/MobileNativeChatAsk.styles.ts @@ -0,0 +1,95 @@ +import { StyleSheet } from 'react-native' +import { colors, radii, spacing, typography } from '../../../theme/mobile-theme' +import { themedStyleSheet } from '../../../theme/themed-styles' + +export const mobileNativeChatAskStyles = themedStyleSheet(() => ({ + card: { + flexShrink: 1, + minHeight: 0, + backgroundColor: colors.bgPanel, + borderTopWidth: StyleSheet.hairlineWidth, + borderTopColor: colors.borderSubtle + }, + tabs: { + flexGrow: 0, + paddingTop: spacing.sm, + borderBottomWidth: StyleSheet.hairlineWidth, + borderBottomColor: colors.borderSubtle + }, + tabsContent: { + paddingHorizontal: spacing.sm, + gap: spacing.xs, + alignItems: 'center' + }, + tab: { + flexDirection: 'row', + alignItems: 'center', + gap: 4, + minHeight: 36, + paddingHorizontal: spacing.sm, + paddingVertical: spacing.xs, + borderBottomWidth: 2, + borderBottomColor: 'transparent' + }, + tabActive: { + borderBottomColor: colors.statusGreen + }, + tabText: { + color: colors.textSecondary, + fontSize: typography.metaSize, + fontWeight: '600' + }, + tabTextActive: { + color: colors.textPrimary + }, + scroll: { + paddingHorizontal: spacing.md + }, + questionRow: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.sm }, + questionText: { + flex: 1, + marginVertical: spacing.sm + }, + other: { + marginBottom: spacing.xs + }, + footer: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + padding: spacing.md, + gap: spacing.sm, + borderTopWidth: StyleSheet.hairlineWidth, + borderTopColor: colors.borderSubtle + }, + cancel: { + paddingVertical: spacing.sm, + paddingHorizontal: spacing.sm + }, + cancelText: { + color: colors.textSecondary, + fontSize: typography.bodySize, + fontWeight: '600' + }, + progress: { + color: colors.textMuted, + fontSize: typography.metaSize + }, + next: { + paddingVertical: spacing.sm, + paddingHorizontal: spacing.lg, + borderRadius: radii.control, + backgroundColor: colors.textPrimary + }, + nextSkip: { + backgroundColor: colors.bgRaised + }, + nextText: { + color: colors.bgBase, + fontSize: typography.bodySize, + fontWeight: '700' + }, + nextSkipText: { + color: colors.textMuted + } +})) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx b/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx index dc1d41efb78..3ec989ff1ee 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx @@ -1,5 +1,5 @@ import { useMemo, useRef, useState } from 'react' -import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native' +import { Keyboard, Pressable, ScrollView, Text, View } from 'react-native' import { Check } from 'lucide-react-native' import { nativeChatAnswerOperationEvidence, @@ -17,8 +17,7 @@ import { askTypedText, toggleAskOption } from '../../../../../src/shared/native-chat/input/native-chat-ask-card-rules' -import { colors, radii, spacing, typography, pressedStyle } from '../../../theme/mobile-theme' -import { themedStyleSheet } from '../../../theme/themed-styles' +import { colors, pressedStyle } from '../../../theme/mobile-theme' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import type { Translate } from '../../../i18n/mobile-i18n' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' @@ -27,6 +26,8 @@ import { MobileNativeChatCardHeaderAction } from './MobileNativeChatCardHeaderAc import { MobileNativeChatQuestionText } from '../transcript/MobileNativeChatQuestionText' import { useMobileNativeChatAskAutoAdvance } from './use-mobile-native-chat-ask-auto-advance' import { MobileNativeChatAskOptionRow } from './MobileNativeChatAskOptionRow' +import { MobileNativeChatOptionPreviewSheet } from './MobileNativeChatOptionPreviewSheet' +import { mobileNativeChatAskStyles as styles } from './MobileNativeChatAsk.styles' import { useMobileNativeChatReplyScroll } from './use-mobile-native-chat-reply-scroll' type Props = { @@ -66,9 +67,9 @@ export function MobileNativeChatAsk({ }: Props): React.JSX.Element { useMobileColorScheme() const t = useMobileTranslation() - const { scrollRef, inputRef, revealReply, scrollViewProps, revealContent } = - useMobileNativeChatReplyScroll() + const { scrollRef, inputRef, revealReply, onViewportLayout } = useMobileNativeChatReplyScroll() const [index, setIndex] = useState(0) + const [viewedOption, setViewedOption] = useState(null) const [selections, setSelections] = useState(() => prompt.questions.map(() => [])) const [otherText, setOtherText] = useState(() => prompt.questions.map((_, qi) => freeTextInputs?.[qi]?.initialValue ?? '') @@ -93,6 +94,7 @@ export function MobileNativeChatAsk({ const autoAdvance = useMobileNativeChatAskAutoAdvance(submitting) // Open each step at its question and end the last step's edit, so no typing lands out of view. const showStep = (next: (current: number) => number): void => { + setViewedOption(null) inputRef.current?.blur() scrollRef.current?.scrollTo({ y: 0, animated: false }) setIndex(next) @@ -105,17 +107,17 @@ export function MobileNativeChatAsk({ askAcceptsEmptyAnswer(prompt.questions[qi], freeTextInputs?.[qi]) // Delay single-select advance to show the choice; Other still needs text. - const toggle = (qi: number, optIndex: number, multi: boolean): void => { + const toggle = (qi: number, optIndex: number, multi: boolean, choosing = false): void => { // Block same-frame taps before disabled state renders. if (isLocalPending(operationRef.current) || answerPending) { return } const cur = selections[qi] ?? [] - // A pick reveals its preview, so a re-tap keeps it and the user confirms. + // Preview choices wait for Submit so inspecting alternatives never commits an answer. const keep = optIndex !== OTHER && askQuestionShowsPreviews(prompt.questions[qi]) const picked = !cur.includes(optIndex) const next = selections.map((s, i) => - i === qi ? toggleAskOption(cur, optIndex, multi, keep) : s + i === qi ? toggleAskOption(cur, optIndex, multi, keep || choosing) : s ) setSelections(next) autoAdvance.cancel() @@ -252,7 +254,12 @@ export function MobileNativeChatAsk({ ) : null} - + { + autoAdvance.cancel() + inputRef.current?.blur() + Keyboard.dismiss() + setViewedOption(optIndex) + }} selected={(selections[index] ?? []).includes(optIndex)} multi={q.multiSelect} disabled={submitting} @@ -333,98 +345,18 @@ export function MobileNativeChatAsk({ + setViewedOption(null)} + onChoose={(optionIndex) => { + setViewedOption(null) + toggle(index, optionIndex, q.multiSelect, true) + }} + /> ) } - -const styles = themedStyleSheet(() => ({ - card: { - flexShrink: 1, - minHeight: 0, - backgroundColor: colors.bgPanel, - borderTopWidth: StyleSheet.hairlineWidth, - borderTopColor: colors.borderSubtle - }, - tabs: { - flexGrow: 0, - paddingTop: spacing.sm, - borderBottomWidth: StyleSheet.hairlineWidth, - borderBottomColor: colors.borderSubtle - }, - tabsContent: { - paddingHorizontal: spacing.sm, - gap: spacing.xs, - alignItems: 'center' - }, - tab: { - flexDirection: 'row', - alignItems: 'center', - gap: 4, - minHeight: 36, - paddingHorizontal: spacing.sm, - paddingVertical: spacing.xs, - borderBottomWidth: 2, - borderBottomColor: 'transparent' - }, - tabActive: { - borderBottomColor: colors.statusGreen - }, - tabText: { - color: colors.textSecondary, - fontSize: typography.metaSize, - fontWeight: '600' - }, - tabTextActive: { - color: colors.textPrimary - }, - scroll: { - paddingHorizontal: spacing.md - }, - questionRow: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.sm }, - questionText: { - flex: 1, - marginVertical: spacing.sm - }, - other: { - marginBottom: spacing.xs - }, - footer: { - flexDirection: 'row', - alignItems: 'center', - justifyContent: 'space-between', - padding: spacing.md, - gap: spacing.sm, - borderTopWidth: StyleSheet.hairlineWidth, - borderTopColor: colors.borderSubtle - }, - cancel: { - paddingVertical: spacing.sm, - paddingHorizontal: spacing.sm - }, - cancelText: { - color: colors.textSecondary, - fontSize: typography.bodySize, - fontWeight: '600' - }, - progress: { - color: colors.textMuted, - fontSize: typography.metaSize - }, - next: { - paddingVertical: spacing.sm, - paddingHorizontal: spacing.lg, - borderRadius: radii.control, - backgroundColor: colors.textPrimary - }, - nextSkip: { - backgroundColor: colors.bgRaised - }, - nextText: { - color: colors.bgBase, - fontSize: typography.bodySize, - fontWeight: '700' - }, - nextSkipText: { - color: colors.textMuted - } -})) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatAskOptionRow.tsx b/mobile/src/session/native-chat/input/MobileNativeChatAskOptionRow.tsx index 4a57a60103c..8734fd41ce0 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatAskOptionRow.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatAskOptionRow.tsx @@ -1,5 +1,6 @@ -import { Pressable, ScrollView, Text, View, type LayoutChangeEvent } from 'react-native' +import { Pressable, Text, View } from 'react-native' import { Check } from 'lucide-react-native' +import { MobileNativeChatOptionThumbnail } from './MobileNativeChatOptionThumbnail' import { colors, concentricRadius, @@ -15,7 +16,7 @@ export function MobileNativeChatAskOptionRow({ label, description, preview, - onPreviewLayout, + onPreview, selected, multi, disabled, @@ -23,16 +24,16 @@ export function MobileNativeChatAskOptionRow({ }: { label: string description?: string - /** Shown under the row while it is selected, as the agent wrote it. */ + /** Read-only inspection is separate from choosing the option. */ preview?: string - /** The preview's edges in the card's scroll content; the row renders as its direct children. */ - onPreviewLayout?: (top: number, bottom: number) => void + onPreview?: () => void selected: boolean multi?: boolean disabled: boolean onPress: () => void }): React.JSX.Element { useMobileColorScheme() + const hasPreview = Boolean(preview && onPreview) const row = ( [ styles.option, selected && styles.optionSelected, + hasPreview && styles.optionWithPreview, pressed && pressedStyle ]} disabled={disabled} @@ -65,29 +67,15 @@ export function MobileNativeChatAskOptionRow({ ) - // One root shape whether or not the preview shows, so selecting never remounts the row. - return ( - <> + return hasPreview ? ( + {row} - {preview && selected ? ( - { - const { y, height } = event.nativeEvent.layout - onPreviewLayout?.(y, y + height) - }} - > - - {/* Mockups are drawn in columns, so they scroll sideways instead of wrapping at phone width. */} - - - {preview} - - - - - ) : null} - + + + + + ) : ( + row ) } @@ -137,18 +125,17 @@ const styles = themedStyleSheet(() => ({ color: colors.textSecondary, fontSize: typography.metaSize }, - preview: { - backgroundColor: colors.bgPanel, + optionCard: { borderWidth: 1, borderColor: colors.borderSubtle, borderRadius: concentricRadius(radii.surface, spacing.xs), - padding: spacing.sm, - marginBottom: spacing.xs, - maxHeight: 220 + backgroundColor: colors.bgRaised, + marginBottom: spacing.xs }, - previewText: { - color: colors.textPrimary, - fontFamily: typography.monoFamily, - fontSize: typography.metaSize + optionWithPreview: { borderWidth: 0, marginBottom: 0 }, + previewInset: { + marginLeft: 18 + spacing.sm * 2, + marginRight: spacing.sm, + marginBottom: spacing.sm } })) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatOptionPreviewSheet.tsx b/mobile/src/session/native-chat/input/MobileNativeChatOptionPreviewSheet.tsx new file mode 100644 index 00000000000..3328570d533 --- /dev/null +++ b/mobile/src/session/native-chat/input/MobileNativeChatOptionPreviewSheet.tsx @@ -0,0 +1,129 @@ +import { useMemo } from 'react' +import { Pressable, ScrollView, Text, View } from 'react-native' +import type { AskQuestion } from '../../../../../src/shared/native-chat/input/native-chat-ask-types' +import { KeyedBottomDrawer } from '../../../components/bottom-drawer/keyed-bottom-drawer' +import { SheetHeader } from '../../../components/nav-bar/SheetHeader' +import { SheetPrimaryButton } from '../../../components/SheetPrimaryButton' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' +import { colors, radii, spacing, typography, pressedStyle } from '../../../theme/mobile-theme' +import { themedStyleSheet } from '../../../theme/themed-styles' +import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' +import { optionPreviewFont } from './mobile-native-chat-option-preview' + +const sheetKey = () => 'option-preview' + +export function MobileNativeChatOptionPreviewSheet({ + options, + viewedIndex, + selected, + disabled, + onView, + onChoose, + onClose +}: { + options: AskQuestion['options'] + viewedIndex: number | null + selected: readonly number[] + disabled: boolean + onView: (index: number) => void + onChoose: (index: number) => void + onClose: () => void +}): React.JSX.Element { + useMobileColorScheme() + const t = useMobileTranslation() + const previews = useMemo( + () => options.flatMap((option, index) => (option.preview ? [{ option, index }] : [])), + [options] + ) + return ( + + {(index) => { + const option = options[index]! + return ( + <> + item.index === index) + 1, + total: previews.length + })} + onClose={onClose} + /> + + {previews.length > 1 ? ( + + {previews.map((item) => ( + onView(item.index)} + style={({ pressed }) => [styles.page, pressed && pressedStyle]} + > + + + ))} + + ) : null} + onChoose(index)} + /> + + ) + }} + + ) +} + +function ReadablePreview({ preview }: { preview: string }): React.JSX.Element { + useMobileColorScheme() + return ( + + + + {preview} + + + + ) +} + +const styles = themedStyleSheet(() => ({ + preview: { flex: 1, minHeight: 0, backgroundColor: colors.bgPanel }, + text: { + padding: spacing.md, + color: colors.textPrimary, + fontFamily: optionPreviewFont, + fontSize: typography.bodySize, + lineHeight: typography.bodySize * 1.5 + }, + pages: { flexGrow: 0, marginVertical: spacing.xs }, + pageContent: { flexGrow: 1, justifyContent: 'center' }, + page: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' }, + dot: { width: 6, height: 6, borderRadius: radii.pill, backgroundColor: colors.borderSubtle }, + currentDot: { backgroundColor: colors.textPrimary } +})) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatOptionThumbnail.tsx b/mobile/src/session/native-chat/input/MobileNativeChatOptionThumbnail.tsx new file mode 100644 index 00000000000..1399a26db65 --- /dev/null +++ b/mobile/src/session/native-chat/input/MobileNativeChatOptionThumbnail.tsx @@ -0,0 +1,117 @@ +import { useState } from 'react' +import { Platform, Pressable, Text, View, type TextStyle } from 'react-native' +import { MobileEdgeFade } from '../../../components/MobileEdgeFade' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' +import { colors, radii, spacing, typography, pressedStyle } from '../../../theme/mobile-theme' +import { themedStyleSheet } from '../../../theme/themed-styles' +import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' +import { optionPreviewFont } from './mobile-native-chat-option-preview' + +const MAX_HEIGHT = 96 - spacing.sm * 2 + +export function MobileNativeChatOptionThumbnail({ + label, + preview, + onPress +}: { + label: string + preview: string + onPress: () => void +}): React.JSX.Element { + return ( + + ) +} + +function MeasuredPreviewThumbnail({ + label, + preview, + onPress +}: { + label: string + preview: string + onPress: () => void +}): React.JSX.Element { + useMobileColorScheme() + const t = useMobileTranslation() + const [width, setWidth] = useState(0) + const [bounds, setBounds] = useState<{ width: number; height: number } | null>(null) + const scale = bounds && width > 0 ? Math.min(1, width / Math.max(1, bounds.width)) : 0 + const height = bounds && width > 0 ? Math.min(MAX_HEIGHT, bounds.height * scale) : MAX_HEIGHT + + return ( + [styles.thumbnail, pressed && pressedStyle]} + > + setWidth(event.nativeEvent.layout.width)} + style={[styles.image, { height }]} + accessibilityElementsHidden + importantForAccessibility="no-hide-descendants" + > + { + const { width, height } = event.nativeEvent.layout + setBounds((previous) => + previous?.width === width && previous.height === height ? previous : { width, height } + ) + }} + style={[styles.text, { transform: [{ scale }] }]} + > + {preview} + + {height >= MAX_HEIGHT ? : null} + + {t('chat.ask.viewPreview', 'View')} + + ) +} + +const styles = themedStyleSheet(() => ({ + thumbnail: { + minHeight: 44, + padding: spacing.sm, + borderWidth: 1, + borderColor: colors.borderSubtle, + borderRadius: radii.control, + backgroundColor: colors.bgPanel, + overflow: 'hidden' + }, + // Native rows measure absolute Text intrinsically; the web uses its explicit CSS width below. + image: { position: 'relative', flexDirection: 'row', overflow: 'hidden' }, + text: { + position: 'absolute', + ...(Platform.OS === 'web' + ? { + whiteSpace: 'pre' as const, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: RN Web accepts intrinsic CSS widths; this branch never reaches native. + width: 'max-content' as TextStyle['width'] + } + : {}), + top: 0, + left: 0, + transformOrigin: 'top left', + fontFamily: optionPreviewFont, + fontSize: typography.metaSize, + lineHeight: typography.metaSize * 1.25, + color: colors.textPrimary, + includeFontPadding: false + }, + view: { + alignSelf: 'flex-end', + color: colors.textSecondary, + fontSize: typography.metaSize, + fontWeight: '600', + position: 'absolute', + right: spacing.xs, + bottom: spacing.xs, + paddingHorizontal: spacing.sm, + borderRadius: radii.pill, + backgroundColor: colors.bgRaised + } +})) diff --git a/mobile/src/session/native-chat/input/mobile-native-chat-option-preview.ts b/mobile/src/session/native-chat/input/mobile-native-chat-option-preview.ts new file mode 100644 index 00000000000..e39b7d52635 --- /dev/null +++ b/mobile/src/session/native-chat/input/mobile-native-chat-option-preview.ts @@ -0,0 +1,7 @@ +import { Platform } from 'react-native' +import { typography } from '../../../theme/mobile-theme' + +export const optionPreviewFont = Platform.select({ + ios: 'Menlo', + default: typography.monoFamily +}) diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-reply-scroll.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-reply-scroll.ts index db204860a4e..b8434307178 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-reply-scroll.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-reply-scroll.ts @@ -1,10 +1,5 @@ import { useRef } from 'react' -import type { - LayoutChangeEvent, - NativeScrollEvent, - NativeSyntheticEvent, - ScrollViewInstance -} from 'react-native' +import type { LayoutChangeEvent, ScrollViewInstance } from 'react-native' import type { MobileTextInputHandle } from '../../../platform/text-input-handle' // Keep a focused reply in view when its card shrinks above the keyboard. @@ -12,7 +7,6 @@ export function useMobileNativeChatReplyScroll() { const scrollRef = useRef(null) const inputRef = useRef(null) const viewportHeight = useRef(0) - const scrollOffset = useRef(0) const revealReply = (): void => { if (inputRef.current?.isFocused()) { scrollRef.current?.scrollToEnd({ animated: false }) @@ -27,31 +21,5 @@ export function useMobileNativeChatReplyScroll() { revealReply() } } - const onScroll = (event: NativeSyntheticEvent): void => { - scrollOffset.current = event.nativeEvent.contentOffset.y - } - // Scroll just enough to show content that opened below the visible edge, never past its top. - const revealContent = (top: number, bottom: number): void => { - const hidden = bottom - (scrollOffset.current + viewportHeight.current) - if (viewportHeight.current > 0 && hidden > 0) { - scrollRef.current?.scrollTo({ - y: Math.min(scrollOffset.current + hidden, top), - animated: true - }) - } - } - const scrollViewProps = { - ref: scrollRef, - onLayout: onViewportLayout, - onScroll, - scrollEventThrottle: 16 - } - return { - scrollRef, - inputRef, - revealReply, - onViewportLayout, - scrollViewProps, - revealContent - } + return { scrollRef, inputRef, revealReply, onViewportLayout } } diff --git a/src/cli/handlers/folder-setup-support-warning.ts b/src/cli/handlers/folder-setup-support-warning.ts new file mode 100644 index 00000000000..35ac1902463 --- /dev/null +++ b/src/cli/handlers/folder-setup-support-warning.ts @@ -0,0 +1,37 @@ +import type { RuntimeClient } from '../runtime-client' +import type { RuntimeStatus } from '../../shared/runtime-types' +import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR } from '../../shared/worktree/id' +import { WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities' + +const FOLDER_SETUP_UNSUPPORTED_WARNING = + 'Setup did not run: this host runs an older Orca without folder workspace setup. Update Orca on that host to run it.' + +/** An older host makes folder workspaces without running setup; say so rather than imply it ran. */ +export async function folderSetupUnsupportedWarning( + client: RuntimeClient, + worktreeId: string | undefined, + create: { setupDecision?: unknown; runHooks?: unknown } +): Promise { + const setupRequested = create.setupDecision === 'run' || create.runHooks === true + if (!setupRequested || !worktreeId?.includes(FOLDER_WORKSPACE_INSTANCE_SEPARATOR)) { + return null + } + const status = await client.call('status.get').catch(() => null) + return status && !status.result.capabilities?.includes(WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY) + ? FOLDER_SETUP_UNSUPPORTED_WARNING + : null +} + +/** Joins the warning onto a create result, so text output and --json both carry it. */ +export async function withFolderSetupSupportWarning< + T extends { worktree?: { id?: string }; warning?: string } +>( + client: RuntimeClient, + result: T, + create: { setupDecision?: unknown; runHooks?: unknown } +): Promise { + const warning = await folderSetupUnsupportedWarning(client, result.worktree?.id, create) + return warning + ? { ...result, warning: result.warning ? `${result.warning} ${warning}` : warning } + : result +} diff --git a/src/cli/handlers/worktree-create-agent-launch.ts b/src/cli/handlers/worktree-create-agent-launch.ts index 05f24c713ef..494ee350859 100644 --- a/src/cli/handlers/worktree-create-agent-launch.ts +++ b/src/cli/handlers/worktree-create-agent-launch.ts @@ -1,5 +1,9 @@ // Use agent.launch for surface/model/effort; older hosts fall back to the create startup terminal. +import { + folderSetupUnsupportedWarning, + withFolderSetupSupportWarning +} from './folder-setup-support-warning' import type { AgentLaunchResult } from '../../shared/agent-launch/contracts/agent-launch-intent' import { AGENT_LAUNCH_LOCAL_PRESENTATION_RUNTIME_CAPABILITY, @@ -65,7 +69,7 @@ export async function createWorktreeWithAgent(args: { startupPrompt: launch.prompt?.text ?? '', launchSource: 'cli' } - const created = await withSetupDecisionRecovery( + const response = await withSetupDecisionRecovery( withCliAgentLaunchRecovery( client.call('worktree.create', params), { @@ -74,6 +78,10 @@ export async function createWorktreeWithAgent(args: { } ) ) + const created = { + ...response, + result: await withFolderSetupSupportWarning(client, response.result, create) + } printHookWarning(created.result, json) printLineageSummary(created.result, json) printResult(created, json, formatWorktreeShow) @@ -93,6 +101,15 @@ export async function createWorktreeWithAgent(args: { launch.operationId !== undefined ) const worktree = await showLaunchedWorktree(client, launched.result.worktreeId) + const setupWarning = await folderSetupUnsupportedWarning( + client, + launched.result.worktreeId, + create + ) + if (setupWarning) { + // stderr keeps --json output parseable while still reporting the skipped setup. + console.error(`warning: ${setupWarning}`) + } const result: WorktreeAgentLaunchResult = { ...(worktree ? { diff --git a/src/cli/handlers/worktree.ts b/src/cli/handlers/worktree.ts index d1ff9d7bf72..5f4acb7f34b 100644 --- a/src/cli/handlers/worktree.ts +++ b/src/cli/handlers/worktree.ts @@ -1,3 +1,4 @@ +import { withFolderSetupSupportWarning } from './folder-setup-support-warning' import { withWorktreeSelectorRecovery } from '../worktree-selector-recovery' import type { RuntimeWorktreeListResult, @@ -207,9 +208,13 @@ export const WORKTREE_HANDLERS: Record = { const result = await withSetupDecisionRecovery( callNamingParentEnvironment(client, 'worktree.create', create) ) - printHookWarning(result.result, json) - printLineageSummary(result.result, json) - printResult(result, json, formatWorktreeShow) + const created = { + ...result, + result: await withFolderSetupSupportWarning(client, result.result, create) + } + printHookWarning(created.result, json) + printLineageSummary(created.result, json) + printResult(created, json, formatWorktreeShow) }, 'worktree set': async ({ flags, client, cwd, json }) => { assertWorktreeParentFlagsCompatible( diff --git a/src/main/acp/acp-dialects/antigravity-dialect.ts b/src/main/acp/acp-dialects/antigravity-dialect.ts index 332d6ea9f7f..a859f9993d7 100644 --- a/src/main/acp/acp-dialects/antigravity-dialect.ts +++ b/src/main/acp/acp-dialects/antigravity-dialect.ts @@ -1,6 +1,6 @@ import { z } from 'zod' import { legacyAgentSessionQuestionAnswers } from '../../../shared/agent-session/agent-session-question-answer' -import { AcpRpcError } from '../transport/acp-errors' +import { AcpRpcError, acpErrorDataWords, type AcpAgentError } from '../transport/acp-errors' import { readAcpPermissionRequest } from '../protocol/acp-permission-requests' import { acpPermissionPresentation } from '../requests/acp-timeline-requests' import type { ToolCallUpdate } from '../generated/acp-protocol.generated' @@ -107,9 +107,28 @@ function normalizeToolUpdate(update: ToolCallUpdate): ToolCallUpdate { } } +const cloudCodeErrorSchema = z.object({ + error: z.object({ message: z.string().trim().min(1) }) +}) + +function promptErrorDetail(error: AcpAgentError): string | undefined { + const text = acpErrorDataWords(error.data) ?? error.message + const prefix = /^Cloud Code Assist API error \(\d{3}\):\s*/.exec(text) + if (!prefix) { + return undefined + } + try { + return cloudCodeErrorSchema.safeParse(JSON.parse(text.slice(prefix[0].length))).data?.error + .message + } catch { + return undefined + } +} + export const ANTIGRAVITY_ACP_DIALECT: AcpDialect = { request: (method, params) => questionRequest(method, params) ?? warnedApproval(method, params), normalizeToolUpdate, + promptErrorDetail, // Avoid using the full command line as the tool name. toolName: (update) => (update.kind === 'execute' ? 'execute' : undefined), // Logout would clear the account shared by every Antigravity chat on this host. diff --git a/src/main/acp/session/acp-structured-antigravity-errors.test.ts b/src/main/acp/session/acp-structured-antigravity-errors.test.ts new file mode 100644 index 00000000000..fabcc889944 --- /dev/null +++ b/src/main/acp/session/acp-structured-antigravity-errors.test.ts @@ -0,0 +1,58 @@ +import { afterEach, expect, it } from 'vitest' +import { closeProviderTimelineRigs } from '../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' +import { acpLaunchSpecFor } from '../launch/acp-launch-registry' +import { + openAcpAdapterRig, + sendHello, + waitFor +} from './testing/acp-structured-adapter.test-support' + +afterEach(closeProviderTimelineRigs) + +const quotaError = `Cloud Code Assist API error (429): { + "error": { + "code": 429, + "message": "Individual quota reached. Please upgrade your subscription to increase your limits. Resets in 3h42m11s.", + "status": "RESOURCE_EXHAUSTED", + "details": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "QUOTA_EXHAUSTED", + "domain": "cloudcode-pa.googleapis.com", + "metadata": { + "quotaResetDelay": "3h42m11.598227131s", + "quotaResetTimeStamp": "2026-11-10T15:58:51Z", + "uiMessage": "true", + "model": "claude-opus-5-5-high" + } + }, + { + "@type": "type.googleapis.com/google.rpc.RetryInfo", + "retryDelay": "13331.598227131s" + } + ] + } +}` + +it('publishes the Cloud Code Assist message instead of its JSON envelope in chat', async () => { + const rig = await openAcpAdapterRig({ + spec: acpLaunchSpecFor('antigravity')!, + script: (agent) => + agent.on('session/prompt', (frame) => + agent.fail(frame, -32603, 'Internal error', { details: quotaError }) + ) + }) + await rig.acquire() + await sendHello(rig, 'send-1') + await waitFor(async () => + expect((await rig.rig.rows()).filter((row) => row.body.kind === 'status')).toEqual([ + expect.objectContaining({ + body: { + kind: 'status', + tone: 'error', + text: 'Individual quota reached. Please upgrade your subscription to increase your limits. Resets in 3h42m11s.' + } + }) + ]) + ) +}) diff --git a/src/main/acp/transport/acp-errors.ts b/src/main/acp/transport/acp-errors.ts index d167f0fd609..2ee2afbf417 100644 --- a/src/main/acp/transport/acp-errors.ts +++ b/src/main/acp/transport/acp-errors.ts @@ -5,6 +5,17 @@ import { withProviderDiagnostic } from '../../../shared/agent-session/failures/agent-session-failure' +// Structured metadata is not user-facing diagnostic text. +export function acpErrorDataWords(data: unknown): string | undefined { + const words = + typeof data === 'string' + ? data + : typeof data === 'object' && data !== null && 'details' in data + ? data.details + : undefined + return typeof words === 'string' && words.trim() ? words : undefined +} + export class AcpRpcError extends Error { constructor( readonly code: number, diff --git a/src/main/acp/turns/acp-prompt-failure.ts b/src/main/acp/turns/acp-prompt-failure.ts index 5af36648fa8..18065efd4a6 100644 --- a/src/main/acp/turns/acp-prompt-failure.ts +++ b/src/main/acp/turns/acp-prompt-failure.ts @@ -6,7 +6,12 @@ import { import type { AcpDialect, AcpTurnEnding } from '../acp-dialects/acp-dialect' -import { AcpAgentError, AcpAuthRequiredError, AcpSignInPromptError } from '../transport/acp-errors' +import { + AcpAgentError, + AcpAuthRequiredError, + AcpSignInPromptError, + acpErrorDataWords +} from '../transport/acp-errors' /** Prefer provider error details over generic messages such as Internal error. */ export function acpPromptErrorDetail(dialect: AcpDialect, error: AcpAgentError): string { @@ -17,17 +22,6 @@ export function acpPromptErrorDetail(dialect: AcpDialect, error: AcpAgentError): return dialect.promptErrorDetail?.(error) ?? acpErrorDataWords(error.data) ?? error.message } -// Structured metadata is not user-facing diagnostic text. -function acpErrorDataWords(data: unknown): string | undefined { - const words = - typeof data === 'string' - ? data - : typeof data === 'object' && data !== null && 'details' in data - ? data.details - : undefined - return typeof words === 'string' && words.trim() ? words : undefined -} - export function acpAuthenticationRequired(dialect: AcpDialect, error: unknown): boolean { return ( error instanceof AcpAuthRequiredError || diff --git a/src/main/claude/claude-agent-sdk-process-spawn.test.ts b/src/main/claude/claude-agent-sdk-process-spawn.test.ts index a79821a55b3..65dbbbfaddc 100644 --- a/src/main/claude/claude-agent-sdk-process-spawn.test.ts +++ b/src/main/claude/claude-agent-sdk-process-spawn.test.ts @@ -90,6 +90,25 @@ describe('claude agent SDK process spawn', () => { expect(spawn.managed?.stderrTail().length).toBe(8192) }) + it('keeps native chat identity after SDK and configured environment defaults', () => { + const process = fakeSpawn() + createClaudeCodeProcessSpawn(process.spawnImpl, 'win32').spawn( + sdkOptions({ + env: { + CLAUDE_CODE_ENTRYPOINT: 'sdk-ts', + claude_code_entrypoint: 'account', + PATH: 'C:\\bin' + } + }) + ) + expect(process.specs[0]?.env).toMatchObject({ CLAUDE_CODE_ENTRYPOINT: 'orca', PATH: 'C:\\bin' }) + expect( + Object.keys(process.specs[0]?.env ?? {}).filter( + (key) => key.toUpperCase() === 'CLAUDE_CODE_ENTRYPOINT' + ) + ).toEqual(['CLAUDE_CODE_ENTRYPOINT']) + }) + it('preserves a Windows .cmd shim and its arguments for the host spawner', () => { const process = fakeSpawn() createClaudeCodeProcessSpawn(process.spawnImpl, 'win32').spawn( diff --git a/src/main/claude/claude-agent-sdk-process-spawn.ts b/src/main/claude/claude-agent-sdk-process-spawn.ts index a5eb7f49e55..71b6adcd9e3 100644 --- a/src/main/claude/claude-agent-sdk-process-spawn.ts +++ b/src/main/claude/claude-agent-sdk-process-spawn.ts @@ -1,3 +1,4 @@ +import { withOrcaClaudeChatEntrypoint } from '../../shared/agent-launch/startup/claude-chat-entrypoint' import type { ChildProcessWithoutNullStreams } from 'node:child_process' import type { PipedProcessSpawner } from '@orca/process-host/process-spec' import type { SpawnOptions as ClaudeAgentSdkSpawnOptions } from '@anthropic-ai/claude-agent-sdk' @@ -70,7 +71,7 @@ export function createClaudeCodeProcessSpawn( { spawnImpl, platform, - inheritedEnv: definedEnv(options.env), + inheritedEnv: withOrcaClaudeChatEntrypoint(definedEnv(options.env), platform), site: 'claude-stream-json-teardown', policy: (supervised) => claudeChildClosePolicy(supervised, platform), acceptClose: claudeChildCloseProven diff --git a/src/main/claude/claude-model-catalog-probe.ts b/src/main/claude/claude-model-catalog-probe.ts index e58d16209ea..cac6371c9d1 100644 --- a/src/main/claude/claude-model-catalog-probe.ts +++ b/src/main/claude/claude-model-catalog-probe.ts @@ -1,3 +1,4 @@ +import { withOrcaClaudeChatEntrypoint } from '../../shared/agent-launch/startup/claude-chat-entrypoint' import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' import { assertStructuredAgentResolutionCurrent, @@ -88,7 +89,11 @@ export async function runClaudeListing( stdin: request.stdin, ...(request.cwd ? { cwd: request.cwd } : {}) }, - { site: request.site, inheritedEnv: env, signal: request.signal } + { + site: request.site, + inheritedEnv: withOrcaClaudeChatEntrypoint(env, process.platform), + signal: request.signal + } ) } const result = await runClaudeBackgroundAttempts({ @@ -197,7 +202,10 @@ export function createClaudeModelCatalogProbe( { site: 'claude-model-catalog-probe', // The listing runs from the account folder; relative PATH entries still mean the chat's. - inheritedEnv: launchDirectory ? envWithPathRelativeTo(env, launchDirectory) : env, + inheritedEnv: withOrcaClaudeChatEntrypoint( + launchDirectory ? envWithPathRelativeTo(env, launchDirectory) : env, + process.platform + ), signal, partialOutput: { timeoutMs: 2_000, diff --git a/src/main/claude/claude-stream-json-connection.ts b/src/main/claude/claude-stream-json-connection.ts index df808c208e2..ae39fdfb007 100644 --- a/src/main/claude/claude-stream-json-connection.ts +++ b/src/main/claude/claude-stream-json-connection.ts @@ -1,3 +1,4 @@ +import { withOrcaClaudeChatEntrypoint } from '../../shared/agent-launch/startup/claude-chat-entrypoint' import { claudeStartupAnswerObservation } from './claude-startup-answer-observation' import type { PipedProcessSpawner } from '@orca/process-host/process-spec' import type * as ClaudeAgentSdk from '@anthropic-ai/claude-agent-sdk' @@ -123,7 +124,7 @@ export async function openClaudeStreamJsonConnection( options: { ...launch.options, cwd: launch.cwd, - env, + env: withOrcaClaudeChatEntrypoint(env, process.platform), pathToClaudeCodeExecutable: launch.pathToClaudeCodeExecutable, spawnClaudeCodeProcess: spawner.spawn, ...(handlers.canUseTool ? { canUseTool: handlers.canUseTool } : {}), diff --git a/src/main/claude/structured/launch/claude-structured-child-env.ts b/src/main/claude/structured/launch/claude-structured-child-env.ts index 84cb638c262..64d70bf7717 100644 --- a/src/main/claude/structured/launch/claude-structured-child-env.ts +++ b/src/main/claude/structured/launch/claude-structured-child-env.ts @@ -1,3 +1,4 @@ +import { withOrcaClaudeChatEntrypoint } from '../../../../shared/agent-launch/startup/claude-chat-entrypoint' import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' import { assertStructuredAgentResolutionCurrent, @@ -91,24 +92,6 @@ async function readClaudeChildEnvSources(deps: ClaudeEnvDeps): Promise, - overlay: Record | undefined, - platform: NodeJS.Platform -): Record { - const inherited = { ...inheritedEnv } - stripInheritedClaudeSessionEnv(inherited, { platform }) - // The SDK reads only the exact name and otherwise adds its own default, which Windows would pick. - return overlayEnvironmentVariables( - { ...inherited, [CLAUDE_ENTRYPOINT_ENV]: 'orca' }, - overlay, - platform - ) -} - // Merge onto the shell environment to retain PATH and ambient Anthropic auth. export function claudeChildEnv( sources: ClaudeChildEnvSources, @@ -116,13 +99,9 @@ export function claudeChildEnv( /** False when the session's seal pairs the CLI runtime itself, behind this app's CLI. */ { runtimeOnPath = true }: { runtimeOnPath?: boolean } = {} ): Record { - const env = decorateEnv( - withOrcaClaudeEntrypoint( - withoutInheritedClaudeConfigDir(sources.inheritedEnv, process.platform), - sources.overlay, - process.platform - ) - ) + const inherited = withoutInheritedClaudeConfigDir(sources.inheritedEnv, process.platform) + stripInheritedClaudeSessionEnv(inherited) + const env = decorateEnv(overlayEnvironmentVariables(inherited, sources.overlay, process.platform)) return runtimeOnPath ? withCliRuntimeOnPath(sources.command, env, { platform: process.platform }) : env @@ -130,12 +109,12 @@ export function claudeChildEnv( // Version probes need the launch runtime and PATH, without auth credentials. export function claudeProbeEnv(sources: ClaudeChildEnvSources): Record { - return applyClaudeEnvPatch( - claudeChildEnv(sources), - {}, - { - stripAuthEnv: true, - platform: process.platform - } + return withOrcaClaudeChatEntrypoint( + applyClaudeEnvPatch( + claudeChildEnv(sources), + {}, + { stripAuthEnv: true, platform: process.platform } + ), + process.platform ) } diff --git a/src/main/ipc/hooks/register-worktree-hook-check-handler.ts b/src/main/ipc/hooks/register-worktree-hook-check-handler.ts index fae4e6ce384..ae5ac61df6f 100644 --- a/src/main/ipc/hooks/register-worktree-hook-check-handler.ts +++ b/src/main/ipc/hooks/register-worktree-hook-check-handler.ts @@ -1,5 +1,10 @@ import { ipcMain } from 'electron' -import { getRepoDialableSshTargetId, type ExecutionHostId } from '../../../shared/execution-host' +import { + getRepoDialableSshTargetId, + isRepoOnCatalogHost, + type ExecutionHostId +} from '../../../shared/execution-host' +import { scopeHooksToRepoKind } from '../../../shared/folder-workspace-hooks' import { isFolderRepo } from '../../../shared/repo-kind' import { hasHooksFile, loadHooks, hasUnrecognizedOrcaYamlKeys } from '../../workspace-hooks/hooks' import { resolveRepoForExecutionHost } from '../worktrees/repo-host-ownership' @@ -23,7 +28,8 @@ export function registerWorktreeHookCheckHandler(context: WorktreeIpcContext): v mayNeedUpdate: false } } - if (isFolderRepo(repo)) { + // A folder owned by another host has no hooks here; its own host reports them. + if (isFolderRepo(repo) && !isRepoOnCatalogHost(repo)) { return { status: 'ok', hasHooks: false, hooks: null, mayNeedUpdate: false } } @@ -53,7 +59,7 @@ export function registerWorktreeHookCheckHandler(context: WorktreeIpcContext): v } const has = hasHooksFile(repo.path) - const hooks = has ? loadHooks(repo.path) : null + const hooks = scopeHooksToRepoKind(repo, has ? loadHooks(repo.path) : null) // Well-formed unknown keys may come from a newer Orca; suggest updating instead of parse repair. const mayNeedUpdate = has && !hooks && hasUnrecognizedOrcaYamlKeys(repo.path) return { diff --git a/src/main/ipc/worktrees/create/folder-workspace-creation.ts b/src/main/ipc/worktrees/create/folder-workspace-creation.ts index b35dad3b48c..b3225c00f54 100644 --- a/src/main/ipc/worktrees/create/folder-workspace-creation.ts +++ b/src/main/ipc/worktrees/create/folder-workspace-creation.ts @@ -7,12 +7,17 @@ import type { CreateWorktreeArgsWithSystemProvenance } from '../ipc-context-sche import { getFolderWorkspaceInstanceId, mergeFolderWorkspace } from '../folder-workspace-model' import { resolveWorktreeCreateDisplayNameRequest } from '../../worktree-display-name' import { hostWorktreeTargetForRepo } from '../../../persistence/host-qualified-worktree-meta' +import { + isPreparedFolderSetup, + prepareFolderWorktreeSetup +} from '../../../runtime/workspaces/creation/runtime-folder-worktree-setup' +import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' -export function createFolderWorkspace( +export async function createFolderWorkspace( args: CreateWorktreeArgsWithSystemProvenance, repo: Repo, store: Store -): CreateWorktreeResult { +): Promise { const now = Date.now() const instanceId = randomUUID() const worktreeId = getFolderWorkspaceInstanceId(repo, instanceId) @@ -64,5 +69,22 @@ export function createFolderWorkspace( ? { linkedTaskSourceContext: args.linkedTaskSourceContext } : {}) }) - return { worktree: mergeFolderWorkspace(repo, worktreeId, meta) } + const worktree = mergeFolderWorkspace(repo, worktreeId, meta) + // The window opens the Setup tab from `setup`, as for a new worktree. + const prepared = await prepareFolderWorktreeSetup({ + // A desktop create is the user's act, as for a new worktree. + request: { ...args, wslUserAct: true }, + repo, + worktree, + settings: store.getSettings(), + runtimeTarget: () => getLocalProjectWorktreeGitOptions(store, repo), + shouldUseSetupRunner: true + }) + const setup = isPreparedFolderSetup(prepared) ? prepared : undefined + return { + worktree, + ...(setup?.setup ? { setup: setup.setup } : {}), + ...(setup?.setupTrustMismatch ? { setupTrustMismatch: setup.setupTrustMismatch } : {}), + ...(prepared?.warning ? { warning: prepared.warning } : {}) + } } diff --git a/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts b/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts index b8caf67061b..60a43933f42 100644 --- a/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts +++ b/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts @@ -67,8 +67,8 @@ export function registerWorktreeCreateHandlers(context: WorktreeIpcContext): voi try { // Track operational failures; malformed IPC rejected above is outside the creation funnel. if (isFolderRepo(repo)) { - // Folder creation only registers metadata, so it needs no filesystem host route. - result = createFolderWorkspace(createArgs, repo, store) + // Folder creation registers metadata; its setup prep checks ownership itself. + result = await createFolderWorkspace(createArgs, repo, store) } else { // Resolve executionHostId-only SSH ownership before any local Git operation. const createRoute = requireWorktreeCreateRoute(repo) diff --git a/src/main/ipc/worktrees/removal/execute-worktree-removal.ts b/src/main/ipc/worktrees/removal/execute-worktree-removal.ts index deed7b0be72..45cd106494f 100644 --- a/src/main/ipc/worktrees/removal/execute-worktree-removal.ts +++ b/src/main/ipc/worktrees/removal/execute-worktree-removal.ts @@ -179,7 +179,8 @@ export async function executeWorktreeRemoval( canonicalWorktreePath, repo, undefined, - localWorktreeGitOptions + localWorktreeGitOptions, + { identity: { worktreeId: args.worktreeId } } ) archiveHookOverride = gateWorktreeRemovalOnArchiveHook({ worktreePath: canonicalWorktreePath, diff --git a/src/main/ipc/worktrees/removal/remove-folder-workspace.ts b/src/main/ipc/worktrees/removal/remove-folder-workspace.ts index 18e01cf0e7a..67783f1742e 100644 --- a/src/main/ipc/worktrees/removal/remove-folder-workspace.ts +++ b/src/main/ipc/worktrees/removal/remove-folder-workspace.ts @@ -13,6 +13,12 @@ import { getFolderWorkspaceRootId } from '../folder-workspace-model' import { preservedBranchCleanupByScope } from './preserved-branch-cleanup' import { removeWorktreeMetadataAndTransientState } from './worktree-removal-ownership' import { teardownStops } from '../../../runtime/workspaces/removal/owned-session-teardown-policy' +import { + gateFolderWorkspaceRemovalOnArchiveHook, + removeFolderWorkspaceRunnerFiles +} from '../../../workspaces/removal/folder-workspace-archive-hook' +import { readWorktreeMetaForRepo } from '../../../persistence/host-qualified-worktree-meta' +import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' export async function removeFolderWorkspace( context: WorktreeIpcContext, @@ -25,6 +31,19 @@ export async function removeFolderWorkspace( if (args.worktreeId === getFolderWorkspaceRootId(repo)) { throw new Error('Cannot delete the project root workspace. Remove the folder project instead.') } + // Archive failure must refuse before watcher, PTY or metadata teardown (#19334). + const archiveHookOverride = await gateFolderWorkspaceRemovalOnArchiveHook({ + repo, + worktreeId: args.worktreeId, + displayName: + ( + readWorktreeMetaForRepo(store, args.worktreeId, repo) ?? + store.getWorktreeMeta(args.worktreeId) + )?.displayName ?? repo.displayName, + runArchive: !args.skipArchive, + allowFailure: args.allowFailedArchiveHook === true, + runtimeTarget: () => getLocalProjectWorktreeGitOptions(store, repo) + }) const ownerHost = parseExecutionHostId(removalHostId) const gate = await runtime.acquireFileWatcherRemoval( repo.path, @@ -62,8 +81,9 @@ export async function removeFolderWorkspace( preservedBranchCleanupByScope.delete( preservedBranchCleanupScopeKey({ worktreeId: args.worktreeId, hostId: removalHostId }) ) + removeFolderWorkspaceRunnerFiles(repo, args.worktreeId) notifyWorktreesChanged(mainWindow, repoId) - return {} + return archiveHookOverride ? { archiveHookOverride } : {} } finally { await gate.finish(false) } diff --git a/src/main/linear/issue-context/includes.test.ts b/src/main/linear/issue-context/includes.test.ts index bc32b1f7855..7d5498b4c22 100644 --- a/src/main/linear/issue-context/includes.test.ts +++ b/src/main/linear/issue-context/includes.test.ts @@ -57,6 +57,19 @@ function requestWithComments(): LinearIssueRequest { } } +function requestWithActivity(): LinearIssueRequest { + return { + include: { + comments: false, + children: false, + attachments: false, + relations: false, + activity: true + }, + depth: 2 + } +} + function result(): LinearIssueContextResult { return { issue: resolvedIssue().issue, @@ -127,4 +140,41 @@ describe('Linear issue context includes', () => { } ]) }) + + it('does not treat an activity page without pageInfo as a complete history', async () => { + plainRawRequest + .mockResolvedValueOnce({ + data: { + issue: { + history: { + nodes: [{ id: 'life-1' }, { id: 'life-2' }], + pageInfo: { hasNextPage: true, endCursor: 'next' } + } + } + } + }) + .mockResolvedValueOnce({ + data: { issue: { history: { nodes: [] } } } + }) + const { readOptionalIncludes } = await import('./includes') + const output = result() + + await readOptionalIncludes( + resolvedIssue(), + requestWithActivity(), + output, + output.meta.includeErrors, + output.meta.sections + ) + + expect(output.activity).toBeUndefined() + expect(output.meta.sections.activity).toBeUndefined() + expect(output.meta.includeErrors).toEqual([ + expect.objectContaining({ + include: 'activity', + code: 'linear_include_failed' + }) + ]) + expect(plainRawRequest).toHaveBeenCalledTimes(2) + }) }) diff --git a/src/main/linear/issue-context/pagination.ts b/src/main/linear/issue-context/pagination.ts index beb1480bb7d..bd40abf39e1 100644 --- a/src/main/linear/issue-context/pagination.ts +++ b/src/main/linear/issue-context/pagination.ts @@ -1,4 +1,5 @@ import { LINEAR_ISSUE_API_PAGE_SIZE_MAX } from '../../../shared/linear/issue-read-limits' +import { linearError } from './errors' export type LinearPageVariables = { first: number; after?: string } @@ -10,6 +11,24 @@ export type LinearConnection = { } } | null +export function linearConnectionHasNextPage( + connection: { pageInfo?: { hasNextPage?: unknown } | null } | null | undefined +): boolean { + // Why: a null connection is an empty read. A connection whose hasNextPage is + // not boolean is not evidence that the caller already has the full set. + if (connection == null) { + return false + } + const hasNext = connection.pageInfo?.hasNextPage + if (typeof hasNext !== 'boolean') { + throw linearError( + 'linear_partial', + 'Linear omitted pageInfo, so this read cannot be treated as complete.' + ) + } + return hasNext +} + export async function readConnectionPages( limit: number, loadConnection: (page: LinearPageVariables) => Promise>, @@ -25,7 +44,7 @@ export async function readConnectionPages( const connection = await loadConnection(after ? { first, after } : { first }) const pageNodes = connection?.nodes ?? [] nodes.push(...pageNodes.slice(0, limit - nodes.length)) - hasMore = Boolean(connection?.pageInfo?.hasNextPage) + hasMore = linearConnectionHasNextPage(connection) const nextCursor = connection?.pageInfo?.endCursor ?? undefined if (!hasMore || !nextCursor || nextCursor === after || pageNodes.length === 0) { diff --git a/src/main/linear/linear-custom-view-queries.ts b/src/main/linear/linear-custom-view-queries.ts index fe225e644d3..0788a14d244 100644 --- a/src/main/linear/linear-custom-view-queries.ts +++ b/src/main/linear/linear-custom-view-queries.ts @@ -30,6 +30,7 @@ import { } from './linear-project-models' import { readCollection, readConcreteCollection } from './linear-project-collection-read' import { readIssueConnectionPages } from './linear-project-issue-queries' +import { linearConnectionHasNextPage } from './issue-context/pagination' export async function listCustomViews( model: LinearCustomViewModel, @@ -53,7 +54,7 @@ export async function listCustomViews( items: (connection?.nodes ?? []) .map((view) => mapCustomViewForWorkspace(entry, view)) .filter((view): view is LinearCustomViewSummary => !!view && view.model === model), - hasMore: !!connection?.pageInfo?.hasNextPage + hasMore: linearConnectionHasNextPage(connection) } }, force @@ -161,7 +162,7 @@ export async function listCustomViewProjects( const connection = view?.projects return { items: (connection?.nodes ?? []).map((project) => mapProjectForWorkspace(entry, project)), - hasMore: !!connection?.pageInfo?.hasNextPage + hasMore: linearConnectionHasNextPage(connection) } }, force diff --git a/src/main/linear/linear-issue-listing.ts b/src/main/linear/linear-issue-listing.ts index 290f5eeb133..32312042ede 100644 --- a/src/main/linear/linear-issue-listing.ts +++ b/src/main/linear/linear-issue-listing.ts @@ -27,6 +27,7 @@ import { shouldThrowAuthError, sortLimitAndDescribeIssues } from './linear-issue-query-support' +import { linearConnectionHasNextPage } from './issue-context/pagination' export type LinearListFilter = 'assigned' | 'created' | 'all' | 'completed' | 'open' @@ -111,7 +112,7 @@ async function readIssueConnectionPage( const nodes = connection?.nodes ?? [] return { items: nodes.map((issue) => mapRawIssueForWorkspace(entry, issue)), - hasMore: Boolean(connection?.pageInfo?.hasNextPage), + hasMore: linearConnectionHasNextPage(connection), endCursor: connection?.pageInfo?.endCursor ?? undefined } } diff --git a/src/main/linear/linear-issue-query-support.ts b/src/main/linear/linear-issue-query-support.ts index b2daf98f271..a20ccc1ce85 100644 --- a/src/main/linear/linear-issue-query-support.ts +++ b/src/main/linear/linear-issue-query-support.ts @@ -16,6 +16,7 @@ import { } from './linear-issue-query-documents' import type { LinearClientForWorkspace } from './client' import type { LinearListFilter } from './linear-issue-listing' +import { linearConnectionHasNextPage } from './issue-context/pagination' export async function mapIssueForWorkspace( entry: LinearClientForWorkspace, @@ -109,7 +110,7 @@ export async function readIssueConnectionPages( const connection = await loadConnection(after ? { first, after } : { first }) const nodes = connection?.nodes ?? [] items.push(...nodes.map((issue) => mapRawIssueForWorkspace(entry, issue))) - hasMore = Boolean(connection?.pageInfo?.hasNextPage) + hasMore = linearConnectionHasNextPage(connection) const nextCursor = connection?.pageInfo?.endCursor ?? undefined if (!hasMore || !nextCursor || nextCursor === after || nodes.length === 0) { diff --git a/src/main/linear/linear-project-issue-queries.ts b/src/main/linear/linear-project-issue-queries.ts index 49e1b89dd5f..4834ae9a0a2 100644 --- a/src/main/linear/linear-project-issue-queries.ts +++ b/src/main/linear/linear-project-issue-queries.ts @@ -17,6 +17,7 @@ import type { } from './linear-project-nodes' import { mapIssueForWorkspace, normalizeConcreteWorkspaceId } from './linear-project-models' import { readConcreteCollection } from './linear-project-collection-read' +import { linearConnectionHasNextPage } from './issue-context/pagination' export async function readIssueConnectionPages( entry: LinearClientForWorkspace, @@ -36,7 +37,7 @@ export async function readIssueConnectionPages( const connection = await loadConnection(after ? { first, after } : { first }) const nodes = connection?.nodes ?? [] items.push(...nodes.map((issue) => mapIssueForWorkspace(entry, issue))) - hasMore = Boolean(connection?.pageInfo?.hasNextPage) + hasMore = linearConnectionHasNextPage(connection) const nextCursor = connection?.pageInfo?.endCursor ?? undefined if (!hasMore || !nextCursor || nextCursor === after || nodes.length === 0) { diff --git a/src/main/linear/linear-project-queries.ts b/src/main/linear/linear-project-queries.ts index 24fcd13fed2..7c18347637e 100644 --- a/src/main/linear/linear-project-queries.ts +++ b/src/main/linear/linear-project-queries.ts @@ -29,6 +29,7 @@ import { normalizeConcreteWorkspaceId } from './linear-project-models' import { readCollection } from './linear-project-collection-read' +import { linearConnectionHasNextPage } from './issue-context/pagination' export async function listProjects( query: string | undefined, @@ -52,7 +53,7 @@ export async function listProjects( const connection = trimmed ? result.data?.searchProjects : result.data?.projects return { items: (connection?.nodes ?? []).map((project) => mapProjectForWorkspace(entry, project)), - hasMore: !!connection?.pageInfo?.hasNextPage + hasMore: linearConnectionHasNextPage(connection) } }, force, @@ -103,10 +104,10 @@ export async function listProjectsByExactName( } const nextCursor = connection?.pageInfo?.endCursor ?? undefined if ( - connection?.pageInfo?.hasNextPage !== true || + !linearConnectionHasNextPage(connection) || !nextCursor || nextCursor === after || - (connection.nodes ?? []).length === 0 + (connection?.nodes ?? []).length === 0 ) { break } diff --git a/src/main/linear/linear-project-team-queries.ts b/src/main/linear/linear-project-team-queries.ts index 56dc948d884..50552de451f 100644 --- a/src/main/linear/linear-project-team-queries.ts +++ b/src/main/linear/linear-project-team-queries.ts @@ -6,6 +6,7 @@ import { getClients, isAuthError } from './client' import { PROJECT_TEAMS_QUERY } from './linear-project-graphql' import type { LinearRawVariables, ProjectTeamsResponse } from './linear-project-nodes' import { coalesce, normalizeConcreteWorkspaceId } from './linear-project-models' +import { linearConnectionHasNextPage } from './issue-context/pagination' export async function listProjectTeams( projectId: string, @@ -55,7 +56,7 @@ export async function listProjectTeams( ) const nextCursor = connection?.pageInfo?.endCursor ?? undefined if ( - !connection?.pageInfo?.hasNextPage || + !linearConnectionHasNextPage(connection) || !nextCursor || nextCursor === after || nodes.length === 0 diff --git a/src/main/linear/mcp-issue-list-page-info.test.ts b/src/main/linear/mcp-issue-list-page-info.test.ts new file mode 100644 index 00000000000..cd4e71b6e98 --- /dev/null +++ b/src/main/linear/mcp-issue-list-page-info.test.ts @@ -0,0 +1,67 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { rawRequest } = vi.hoisted(() => ({ rawRequest: vi.fn() })) + +vi.mock('./linear-request-concurrency', () => ({ + acquire: vi.fn().mockResolvedValue(undefined), + release: vi.fn() +})) + +vi.mock('./linear-token-store', () => ({ + clearToken: vi.fn() +})) + +vi.mock('./client', () => ({ + getClients: () => [ + { + workspace: { + id: 'workspace-1', + organizationId: 'workspace-1', + organizationName: 'Acme', + displayName: 'Ada', + email: 'ada@example.com' + }, + client: { client: { rawRequest } } + } + ], + getStatus: () => ({ workspaces: [] }), + isAuthError: () => false, + getPublicFileUrlClient: (entry: { client: unknown }) => entry.client +})) + +import { listMcpIssues } from './mcp-issue-list' + +function issueNode(id: string) { + return { + id, + identifier: id.toUpperCase(), + title: id, + url: `https://linear.app/acme/issue/${id}`, + labels: { nodes: [] }, + updatedAt: '2026-11-10T00:00:00.000Z' + } +} + +describe('Linear list pagination evidence', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('does not report a complete list when a later page omits pageInfo', async () => { + rawRequest + .mockResolvedValueOnce({ + data: { + issues: { + nodes: [issueNode('lin-1'), issueNode('lin-2')], + pageInfo: { hasNextPage: true, endCursor: 'next' } + } + } + }) + .mockResolvedValueOnce({ + data: { issues: { nodes: [] } } + }) + + await expect(listMcpIssues({})).rejects.toMatchObject({ code: 'linear_partial' }) + expect(rawRequest).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/main/linear/mcp-issue-list.ts b/src/main/linear/mcp-issue-list.ts index 6c43e4d510d..d96347127ab 100644 --- a/src/main/linear/mcp-issue-list.ts +++ b/src/main/linear/mcp-issue-list.ts @@ -11,6 +11,7 @@ import { type WorkspaceReadFailure } from './issue-context/fanout' import { ISSUE_FIELDS, mapIssue, type RawIssue } from './issue-context/raw' +import { linearConnectionHasNextPage } from './issue-context/pagination' import { resolveWorkspaceSelector } from './issue-context/workspaces' import { encodeIssueListCursor, resolveIssueListCursor } from './mcp-issue-list-cursor' import { buildIssueFilter } from './mcp-issue-list-filter' @@ -199,7 +200,7 @@ async function readIssueListWorkspace( workspace: { id: entry.workspace.id, name: entry.workspace.organizationName } }) } - hasMore = connection?.pageInfo?.hasNextPage === true + hasMore = linearConnectionHasNextPage(connection) nextCursor = connection?.pageInfo?.endCursor ?? undefined if (!hasMore || !nextCursor) { break diff --git a/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts b/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts index 9c45911318a..02c12808101 100644 --- a/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts +++ b/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts @@ -211,7 +211,8 @@ function resetRuntimeTestMocks(): void { vi.mocked(shouldRunSetupForCreate).mockReset() vi.mocked(shouldRunSetupForCreate).mockImplementation((_repo, decision) => decision === 'run') vi.mocked(getEffectiveHooks).mockReturnValue(null) - vi.mocked(getEffectiveHooksFromConfig).mockReturnValue(null) + // Setup derives effective hooks from the parsed orca.yaml; tests steer it through getEffectiveHooks. + vi.mocked(getEffectiveHooksFromConfig).mockImplementation((repo) => getEffectiveHooks(repo)) vi.mocked(getDefaultTabsLaunch).mockReturnValue(undefined) vi.mocked(loadHooks).mockReturnValue(null) vi.mocked(resolveSetupRunnerShell).mockReturnValue(undefined) diff --git a/src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts index 782d9eea2c3..e6afa712318 100644 --- a/src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts @@ -9,8 +9,11 @@ import { ensurePathWithinWorkspaceMock } from '../orca-runtime-test-mocks/setup.spec' import { createSetupRunnerScript } from '../../workspace-hooks/worktree-runner-script' -import { shouldRunSetupForCreate } from '../../workspace-hooks/effective-hook-config' -import { getEffectiveHooks } from '../../workspace-hooks/hooks' +import { + getEffectiveHooksFromConfig, + shouldRunSetupForCreate +} from '../../workspace-hooks/effective-hook-config' +import { getEffectiveHooks, loadHooks } from '../../workspace-hooks/hooks' import { listWorktrees } from '../../git/worktrees/catalog/worktree-scan-cache' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' import { @@ -144,6 +147,12 @@ describe('OrcaRuntimeService', () => { vi.mocked(getEffectiveHooks).mockImplementation((_repo, worktreePath) => worktreePath ? { scripts: { setup: 'pnpm worktree:setup' } } : null ) + vi.mocked(loadHooks).mockImplementation((path) => + path === '/tmp/workspaces/runtime-branch-added-setup' + ? { scripts: { setup: 'pnpm worktree:setup' } } + : null + ) + vi.mocked(getEffectiveHooksFromConfig).mockImplementation((_repo, yamlHooks) => yamlHooks) // Model an ask-policy repo that refuses an undecided create. vi.mocked(shouldRunSetupForCreate).mockImplementation((_repo, decision) => { if (decision === 'run' || decision === 'skip') { diff --git a/src/main/runtime/repositories/runtime-repository-hooks-commands.ts b/src/main/runtime/repositories/runtime-repository-hooks-commands.ts index fd36b658d24..844dc691151 100644 --- a/src/main/runtime/repositories/runtime-repository-hooks-commands.ts +++ b/src/main/runtime/repositories/runtime-repository-hooks-commands.ts @@ -1,4 +1,5 @@ -import { getRepoDialableSshTargetId } from '../../../shared/execution-host' +import { getRepoDialableSshTargetId, isRepoOnCatalogHost } from '../../../shared/execution-host' +import { scopeHooksToRepoKind } from '../../../shared/folder-workspace-hooks' import { windowsFsPath } from '../../wsl/filesystem/wsl-unc-drive-fs-path' import { readFile } from 'node:fs/promises' import type { Repo } from '../../../shared/repo-types' @@ -29,8 +30,8 @@ export class RuntimeRepositoryHooksCommands { async getRepoHooks(repoSelector: string) { const repo = await this.deps.resolveRepo(repoSelector) const connectionId = getRepoDialableSshTargetId(repo) - // Why: an `ssh:` repo is not served here; it reports no hooks file. - if (connectionId) { + // Why: an `ssh:` repo is not served here, nor a folder another host owns; neither reports hooks. + if (connectionId || (isFolderRepo(repo) && !isRepoOnCatalogHost(repo))) { return { hasHooksFile: false, hooks: null, @@ -40,8 +41,8 @@ export class RuntimeRepositoryHooksCommands { } const hasFile = hasHooksFile(repo.path) const hooks = getEffectiveHooks(repo) - const sharedHooks = hasFile ? loadHooks(repo.path) : null - const setupConfig = isFolderRepo(repo) ? null : getSetupConfig(repo, sharedHooks) + const sharedHooks = scopeHooksToRepoKind(repo, hasFile ? loadHooks(repo.path) : null) + const setupConfig = getSetupConfig(repo, sharedHooks) return { hasHooksFile: hasFile, hooks, @@ -61,7 +62,7 @@ export class RuntimeRepositoryHooksCommands { async checkRepoHooks(repoSelector: string, options: { background?: boolean } = {}) { const repo = await this.deps.resolveRepo(repoSelector) - if (isFolderRepo(repo)) { + if (isFolderRepo(repo) && !isRepoOnCatalogHost(repo)) { return { status: 'ok' as const, hasHooks: false, hooks: null, mayNeedUpdate: false } } const connectionId = getRepoDialableSshTargetId(repo) @@ -83,7 +84,7 @@ export class RuntimeRepositoryHooksCommands { } } const has = hasHooksFile(repo.path) - const hooks = has ? loadHooks(repo.path) : null + const hooks = scopeHooksToRepoKind(repo, has ? loadHooks(repo.path) : null) return { status: 'ok' as const, hasHooks: has, @@ -123,10 +124,6 @@ function archiveTrust( repo: Repo, sharedHooks: OrcaHooks | null ): { contentHash: string; scriptContent: string } | null { - // Folder removal never runs hooks. - if (isFolderRepo(repo)) { - return null - } const localArchive = repo.hookSettings?.scripts.archive?.trim() const policy = resolveHookCommandSourcePolicy(repo.hookSettings?.commandSourcePolicy, { hasLocalScript: Boolean(localArchive) diff --git a/src/main/runtime/workspaces/creation/created-worktree-approved-setup.test.ts b/src/main/runtime/workspaces/creation/created-worktree-approved-setup.test.ts index f9d48b5b9a5..00a59d16492 100644 --- a/src/main/runtime/workspaces/creation/created-worktree-approved-setup.test.ts +++ b/src/main/runtime/workspaces/creation/created-worktree-approved-setup.test.ts @@ -22,7 +22,12 @@ let repo: Repo const provisionManagedWorktreeTerminals = vi.fn() function runtimeFor() { - const worktree = { id: `repo::${worktreePath}`, repoId: 'repo', path: worktreePath } + const worktree = { + id: `repo::${worktreePath}`, + repoId: 'repo', + path: worktreePath, + displayName: 'w' + } return { showManagedWorktree: vi.fn(async () => worktree), requireStore: () => ({ diff --git a/src/main/runtime/workspaces/creation/created-worktree-approved-setup.ts b/src/main/runtime/workspaces/creation/created-worktree-approved-setup.ts index e8edb207a0c..7147cc3b6c3 100644 --- a/src/main/runtime/workspaces/creation/created-worktree-approved-setup.ts +++ b/src/main/runtime/workspaces/creation/created-worktree-approved-setup.ts @@ -1,4 +1,6 @@ import { isFolderRepo } from '../../../../shared/repo-kind' +import { isRepoOnCatalogHost } from '../../../../shared/execution-host' +import { scopeHooksToRepoKind } from '../../../../shared/folder-workspace-hooks' import { getSetupRunnerCommandPlatformForPath } from '../../../../shared/agent-launch/startup/setup-runner-command' import type { RunApprovedWorktreeSetupResult } from '../../../../shared/worktree/create-types' import { @@ -20,7 +22,9 @@ import type { RuntimeStore } from '../../construction/runtime-store-contract' import type { WorktreeTerminalProvisioningArgs } from '../startup/runtime-worktree-terminal-provisioning' type ApprovedSetupRuntime = { - showManagedWorktree: (selector: string) => Promise> + showManagedWorktree: ( + selector: string + ) => Promise> requireStore: () => Pick provisionManagedWorktreeTerminals: (args: WorktreeTerminalProvisioningArgs) => Promise } @@ -38,10 +42,10 @@ export async function runApprovedCreatedWorktreeSetup( const worktree = await runtime.showManagedWorktree(worktreeSelector) const store = runtime.requireStore() const repo = store.getRepo(worktree.repoId) - if (!repo || isFolderRepo(repo)) { + if (!repo || (isFolderRepo(repo) && !isRepoOnCatalogHost(repo))) { return { status: 'not_configured' } } - const yamlHooks = loadHooks(worktree.path) + const yamlHooks = scopeHooksToRepoKind(repo, loadHooks(worktree.path)) const mismatch = checkCreatedWorktreeSetupTrust(repo, yamlHooks, 'run', { approvedSetupHash }) if (mismatch) { return { status: 'mismatch', setupTrustMismatch: mismatch } @@ -54,7 +58,8 @@ export async function runApprovedCreatedWorktreeSetup( setupScript, getLocalProjectWorktreeGitOptions(store, repo), resolveSetupRunnerShell(store.getSettings()), - yamlHooks?.setupAgentStartupPolicy + yamlHooks?.setupAgentStartupPolicy, + { worktreeId: worktree.id, displayName: worktree.displayName } ) : undefined // The create already opened the command-less default tabs. diff --git a/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts b/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts index 7cf2c36ab43..1aecde1f210 100644 --- a/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts +++ b/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts @@ -7,7 +7,6 @@ import { shouldSeedWorktreePrimaryTerminal } from '../../../../shared/worktree-f import { randomUUID } from 'node:crypto' import { getProjectHostSetupWorktreeMeta } from '../../../../shared/project-host-setup-lookup' import { resolveWorktreeCreateDisplayNameRequest } from '../../../ipc/worktree-display-name' -import type { RuntimeTerminalCreate } from '../../../../shared/runtime-terminal-create-contract' import type { CreateWorktreeResult } from '../../../../shared/worktree/create-types' import type { Repo } from '../../../../shared/repo-types' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' @@ -19,27 +18,24 @@ import { } from '../catalog/runtime-folder-workspace' import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types' import type { RuntimeStore } from '../../construction/runtime-store-contract' -import type { TerminalCreateOptions } from '../../terminal/launch/terminal-create-options' import type { WorktreeStartupDraftPaste, WorktreeStartupFollowup } from '../startup/runtime-worktree-agent-startup' import { hostWorktreeTargetForRepo } from '../../../persistence/host-qualified-worktree-meta' +import type { RuntimeLocalWorktreeTerminalPorts } from '../startup/runtime-local-worktree-terminal-startup' +import { + isPreparedFolderSetup, + prepareFolderWorktreeSetup, + startRuntimeFolderWorktreeSetupTerminals, + type RuntimeFolderWorktreeSetupDeps +} from './runtime-folder-worktree-setup' +import { buildRuntimeSetupReceipt } from './runtime-local-worktree-setup' type RuntimeFolderWorktreeCreateDeps = { store: RuntimeStore - ptySpawnAvailable: boolean - provisionInBackground?: () => boolean - createTerminal: ( - selector: string, - options: TerminalCreateOptions - ) => Promise - pasteDraft: (handle: string, draft: WorktreeStartupDraftPaste) => void - sendFollowup: ( - handle: string, - followup: WorktreeStartupFollowup, - terminal: RuntimeTerminalCreate - ) => void + /** The same terminal operations a worktree create uses; folder startup and setup share them. */ + terminals: RuntimeLocalWorktreeTerminalPorts invalidateResolvedWorktrees: () => void notifyWorktreesChanged: (repoId: string) => void emitCreated: (event: { @@ -55,6 +51,8 @@ type RuntimeFolderWorktreeCreateDeps = { startup?: WorktreeStartupLaunch, providesInitialSurface?: boolean ) => void + /** Absent where this host can't run the folder's setup script. */ + setup?: RuntimeFolderWorktreeSetupDeps } export async function createRuntimeFolderWorktree(args: { @@ -150,18 +148,47 @@ export async function createRuntimeFolderWorktree(args: { path: worktree.path, branch: worktree.branch }) + const setupResult = deps.setup + ? await prepareFolderWorktreeSetup({ + request, + repo, + worktree, + settings, + runtimeTarget: deps.setup.runtimeTarget, + shouldUseSetupRunner: deps.setup.shouldUseSetupRunner + }) + : undefined + const preparedSetup = isPreparedFolderSetup(setupResult) ? setupResult : undefined + if (preparedSetup?.setup && deps.setup) { + return { + worktree: folderCreateResultWorktree(worktree), + ...(await startRuntimeFolderWorktreeSetupTerminals({ + request, + repo, + worktree, + prepared: preparedSetup, + startup: args.startup, + startupFollowup: args.startupFollowup, + startupLaunchRuntime: args.startupLaunchRuntime, + createdWithAgent: args.createdWithAgent, + promisedAgentChat: args.promisedAgentChat, + draftPaste: args.draftPaste, + terminals: deps.terminals + })) + } + } const shouldActivate = request.activate === true || request.runHooks === true - let warning: string | undefined + let warning: string | undefined = setupResult?.warning let didSpawnStartup = false let startupTerminal: CreateWorktreeResult['startupTerminal'] // Main owns failed agent startup too, so its pane can show the reason without a terminal service. - if (args.startup && (deps.ptySpawnAvailable || ORCA_LAYOUT_OWNER_IS_MAIN)) { + if (args.startup && (deps.terminals.canSpawn || ORCA_LAYOUT_OWNER_IS_MAIN)) { try { const launchRuntime = args.startupLaunchRuntime if (launchRuntime instanceof Error && !ORCA_LAYOUT_OWNER_IS_MAIN) { throw launchRuntime } - const terminal = await deps.createTerminal(`id:${worktree.id}`, { + const terminal = await deps.terminals.createTerminal(`id:${worktree.id}`, { command: args.startup.command, ...(request.startupCwd ? { cwd: request.startupCwd } : {}), ...paneIdentity(request.startupPaneKey), @@ -182,10 +209,10 @@ export async function createRuntimeFolderWorktree(args: { }) request.onStartupTerminalCreated?.(terminal) if (args.draftPaste) { - deps.pasteDraft(terminal.handle, args.draftPaste) + deps.terminals.pasteDraft(terminal.handle, args.draftPaste) } if (args.startupFollowup) { - deps.sendFollowup(terminal.handle, args.startupFollowup, terminal) + deps.terminals.sendFollowup(terminal.handle, args.startupFollowup, terminal) } didSpawnStartup = true startupTerminal = { @@ -220,8 +247,8 @@ export async function createRuntimeFolderWorktree(args: { ) } if ( - (!shouldActivate || deps.provisionInBackground?.() === true) && - deps.ptySpawnAvailable && + (!shouldActivate || deps.terminals.provisionInBackground?.() === true) && + deps.terminals.canSpawn && shouldSeedWorktreePrimaryTerminal({ // Failed agents retain their panes; do not seed a shell beside them. hasPrimarySurface: didSpawnStartup || (ORCA_LAYOUT_OWNER_IS_MAIN && Boolean(args.startup)), @@ -230,7 +257,7 @@ export async function createRuntimeFolderWorktree(args: { }) ) { try { - await deps.createTerminal(`id:${worktree.id}`, { surfaceOwner: false }) + await deps.terminals.createTerminal(`id:${worktree.id}`, { surfaceOwner: false }) } catch (error) { const message = readableWslDistroHoldText( formatTerminalStartFailure(error) ?? @@ -244,20 +271,33 @@ export async function createRuntimeFolderWorktree(args: { } } return { - worktree: { - ...worktree, - parentWorktreeId: null, - childWorktreeIds: [], - lineage: null, - git: { - path: worktree.path, - head: worktree.head, - branch: worktree.branch, - isBare: worktree.isBare, - isMainWorktree: worktree.isMainWorktree - } - }, + worktree: folderCreateResultWorktree(worktree), ...(startupTerminal ? { startupTerminal } : {}), + ...(preparedSetup && request.awaitTerminalProvisioning + ? { setupReceipt: buildRuntimeSetupReceipt(preparedSetup, false, null) } + : {}), + // The window re-asks with this content, then runs the approved setup. + ...(preparedSetup?.setupTrustMismatch + ? { setupTrustMismatch: preparedSetup.setupTrustMismatch } + : {}), ...(warning ? { warning } : {}) } } + +function folderCreateResultWorktree( + worktree: ReturnType +): CreateWorktreeResult['worktree'] { + return { + ...worktree, + parentWorktreeId: null, + childWorktreeIds: [], + lineage: null, + git: { + path: worktree.path, + head: worktree.head, + branch: worktree.branch, + isBare: worktree.isBare, + isMainWorktree: worktree.isMainWorktree + } + } +} diff --git a/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts b/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts new file mode 100644 index 00000000000..7e1595156b6 --- /dev/null +++ b/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts @@ -0,0 +1,132 @@ +import { isRepoOnCatalogHost } from '../../../../shared/execution-host' +import type { Repo } from '../../../../shared/repo-types' +import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' +import type { AgentLaunchRuntime } from '../../../../shared/agent-launch/startup/agent-launch-runtime' +import type { CreateWorktreeResult } from '../../../../shared/worktree/create-types' +import type { Worktree } from '../../../../shared/worktree/types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import { + startRuntimeLocalWorktreeTerminals, + type RuntimeLocalWorktreeTerminalPorts +} from '../startup/runtime-local-worktree-terminal-startup' +import type { + WorktreeStartupDraftPaste, + WorktreeStartupFollowup +} from '../startup/runtime-worktree-agent-startup' +import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types' +import { + buildRuntimeSetupReceipt, + prepareRuntimeLocalWorktreeSetup, + resolveRuntimeSetupDecision +} from './runtime-local-worktree-setup' +import { blockedWslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' + +export type RuntimeFolderWorktreeSetupDeps = { + runtimeTarget: () => { wslDistro?: string } | undefined + shouldUseSetupRunner: boolean +} + +type PreparedFolderSetup = Awaited> + +/** + * Only the host whose catalog holds the folder may read its orca.yaml or write runners there. + * The workspace already exists, so a setup problem becomes a warning, never a failed create. + */ +export async function prepareFolderWorktreeSetup(args: { + request: Parameters[0]['request'] & { + wslUserAct?: true + } + repo: Repo + worktree: Pick + settings: ReturnType + runtimeTarget: () => { wslDistro?: string } | undefined + shouldUseSetupRunner: boolean +}): Promise { + const { repo, worktree, request } = args + // A skipped setup needs no file access, so metadata-only creates stay metadata-only. + if (!isRepoOnCatalogHost(repo) || resolveRuntimeSetupDecision(request) === 'skip') { + return undefined + } + // Only a create someone started may start the folder's stopped WSL distro. + if (!request.wslUserAct && (await blockedWslDistroForPath(repo.path))) { + return { warning: "Setup did not run because the folder's WSL distro isn't running." } + } + try { + return await prepareRuntimeLocalWorktreeSetup({ + request: args.request, + repo, + worktreePath: worktree.path, + settings: args.settings, + runtimeTarget: args.runtimeTarget(), + shouldUseSetupRunner: args.shouldUseSetupRunner, + identity: { worktreeId: worktree.id, displayName: worktree.displayName } + }) + } catch (error) { + console.error(`[hooks] setup preparation failed for ${worktree.path}:`, error) + const message = error instanceof Error ? error.message : String(error) + return { warning: `Setup did not run for this folder workspace: ${message}` } + } +} + +export function isPreparedFolderSetup( + value: PreparedFolderSetup | { warning: string } | undefined +): value is PreparedFolderSetup { + return value !== undefined && 'effectiveDecision' in value +} + +/** Folder workspaces start setup and agents exactly as worktrees do, Setup-before-agent order included. */ +export async function startRuntimeFolderWorktreeSetupTerminals(args: { + request: RuntimeManagedWorktreeCreateArgs + repo: Repo + worktree: Worktree + prepared: PreparedFolderSetup + startup?: WorktreeStartupLaunch + startupFollowup?: WorktreeStartupFollowup + startupLaunchRuntime?: AgentLaunchRuntime | Error + createdWithAgent?: TuiAgent + promisedAgentChat?: boolean + draftPaste?: WorktreeStartupDraftPaste + terminals: RuntimeLocalWorktreeTerminalPorts +}): Promise> { + const { request, prepared } = args + const started = await startRuntimeLocalWorktreeTerminals({ + request, + repo: args.repo, + worktree: args.worktree, + setup: prepared.setup, + startup: args.startup, + startupFollowup: args.startupFollowup, + startupLaunchRuntime: args.startupLaunchRuntime, + createdWithAgent: args.createdWithAgent, + promisedAgentChat: args.promisedAgentChat, + draftPaste: args.draftPaste, + warning: prepared.warning, + ports: args.terminals + }) + return { + ...(started.returnedSetup ? { setup: started.returnedSetup } : {}), + ...(request.awaitTerminalProvisioning + ? { + setupReceipt: buildRuntimeSetupReceipt( + prepared, + started.didSpawnSetup, + started.setupTerminalHandle + ) + } + : {}), + ...(started.didSpawnStartup && started.startupTerminalHandle + ? { + startupTerminal: { + spawned: true, + handle: started.startupTerminalHandle, + ...(started.startupTerminalTabId ? { tabId: started.startupTerminalTabId } : {}), + ...(started.startupTerminalPaneKey ? { paneKey: started.startupTerminalPaneKey } : {}), + ...(started.startupTerminalPtyId ? { ptyId: started.startupTerminalPtyId } : {}), + surface: 'background' as const + } + } + : {}), + ...(started.warning ? { warning: started.warning } : {}) + } +} diff --git a/src/main/runtime/workspaces/creation/runtime-local-worktree-setup-trust.test.ts b/src/main/runtime/workspaces/creation/runtime-local-worktree-setup-trust.test.ts index fbc1ac7d2e7..97ce8e12fcb 100644 --- a/src/main/runtime/workspaces/creation/runtime-local-worktree-setup-trust.test.ts +++ b/src/main/runtime/workspaces/creation/runtime-local-worktree-setup-trust.test.ts @@ -21,8 +21,6 @@ const repo: Repo = { id: 'repo', path: '/primary', displayName: 'r', badgeColor: function prepare(approvedSetupHash?: string, approvedSetupHashes?: string[]) { return prepareRuntimeLocalWorktreeSetup({ request: { - repoSelector: 'id:repo', - name: 'w', setupDecision: 'run', ...(approvedSetupHash !== undefined ? { approvedSetupHash } : {}), ...(approvedSetupHashes ? { approvedSetupHashes } : {}) @@ -82,4 +80,42 @@ describe('created worktree setup trust', () => { expect(runner.createSetupRunnerScript).toHaveBeenCalledOnce() expect(result.setupTrustMismatch).toBeUndefined() }) + + describe('folder projects', () => { + const folderRepo: Repo = { ...repo, kind: 'folder' } + const identity = { worktreeId: 'repo::/acme::workspace:1', displayName: 'Fix login' } + const prepareFolder = (setupDecision: 'run' | 'inherit', approvedSetupHash?: string) => + prepareRuntimeLocalWorktreeSetup({ + request: { + setupDecision, + ...(approvedSetupHash !== undefined ? { approvedSetupHash } : {}) + }, + repo: folderRepo, + worktreePath, + settings: getDefaultSettings(tmpdir()), + runtimeTarget: undefined, + shouldUseSetupRunner: true, + identity + }) + + it('skips shared setup from an older client that sent no approval', async () => { + writeFileSync(join(worktreePath, 'orca.yaml'), 'scripts:\n setup: make bootstrap\n') + const result = await prepareFolder('inherit') + expect(runner.createSetupRunnerScript).not.toHaveBeenCalled() + expect(result.setup).toBeUndefined() + expect(result.warning).toContain('pass --setup run') + }) + + it('runs approved shared setup for the workspace, without default tabs', async () => { + writeFileSync( + join(worktreePath, 'orca.yaml'), + 'scripts:\n setup: make bootstrap\ndefaultTabs:\n - title: dev\n command: pnpm dev\n' + ) + const result = await prepareFolder('run', sha256('make bootstrap')) + expect(runner.createSetupRunnerScript).toHaveBeenCalledOnce() + expect(runner.createSetupRunnerScript.mock.calls[0][6]).toEqual(identity) + expect(result.defaultTabs).toBeUndefined() + expect(result.setupTrustMismatch).toBeUndefined() + }) + }) }) diff --git a/src/main/runtime/workspaces/creation/runtime-local-worktree-setup.ts b/src/main/runtime/workspaces/creation/runtime-local-worktree-setup.ts index 794d1b1de73..48ac76b6585 100644 --- a/src/main/runtime/workspaces/creation/runtime-local-worktree-setup.ts +++ b/src/main/runtime/workspaces/creation/runtime-local-worktree-setup.ts @@ -4,19 +4,24 @@ import type { SetupTrustMismatch } from '../../../../shared/worktree/create-types' import type { Repo } from '../../../../shared/repo-types' -import { getEffectiveHooks, loadHooks, runHook } from '../../../workspace-hooks/hooks' +import { loadHooks, runHook } from '../../../workspace-hooks/hooks' import { createSetupRunnerScript, resolveSetupRunnerShell } from '../../../workspace-hooks/worktree-runner-script' import { getDefaultTabsLaunch, + getEffectiveHooksFromConfig, shouldRunSetupForCreate } from '../../../workspace-hooks/effective-hook-config' import { checkCreatedWorktreeSetupTrust, - defaultTabsWithoutCommands + defaultTabsWithoutCommands, + folderSharedSetupLacksApproval } from '../../../workspace-hooks/created-worktree-setup-trust' +import type { HookWorkspaceIdentity } from '../../../workspace-hooks/setup-hook-env-vars' +import { scopeHooksToRepoKind } from '../../../../shared/folder-workspace-hooks' +import { isFolderRepo } from '../../../../shared/repo-kind' import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types' import type { RuntimeStore } from '../../construction/runtime-store-contract' @@ -28,13 +33,18 @@ export function resolveRuntimeSetupDecision( } export async function prepareRuntimeLocalWorktreeSetup(args: { - request: RuntimeManagedWorktreeCreateArgs + request: Pick< + RuntimeManagedWorktreeCreateArgs, + 'runHooks' | 'setupDecision' | 'approvedSetupHash' | 'approvedSetupHashes' + > repo: Repo worktreePath: string settings: ReturnType runtimeTarget: { wslDistro?: string } | undefined shouldUseSetupRunner: boolean warning?: string + /** Required for folder workspaces, whose shared directory can't name the workspace. */ + identity?: HookWorkspaceIdentity }): Promise<{ setup?: CreateWorktreeResult['setup'] defaultTabs?: CreateWorktreeResult['defaultTabs'] @@ -48,8 +58,9 @@ export async function prepareRuntimeLocalWorktreeSetup(args: { const { request, repo, worktreePath, settings } = args let warning = args.warning let setup: CreateWorktreeResult['setup'] - const yamlHooks = loadHooks(worktreePath) - const hooks = getEffectiveHooks(repo, worktreePath) + const yamlHooks = scopeHooksToRepoKind(repo, loadHooks(worktreePath)) + // One parse feeds both the trust check and the runner, so approved bytes are the bytes that run. + const hooks = getEffectiveHooksFromConfig(repo, yamlHooks) const effectiveDecision = resolveRuntimeSetupDecision(request) const setupTrustMismatch = checkCreatedWorktreeSetupTrust( repo, @@ -57,12 +68,20 @@ export async function prepareRuntimeLocalWorktreeSetup(args: { effectiveDecision, request ) + const lacksFolderApproval = + isFolderRepo(repo) && + folderSharedSetupLacksApproval(repo, yamlHooks, effectiveDecision, request) // Only the approved content may run; the client re-prompts with the branch's. - const runDecision = setupTrustMismatch ? 'skip' : effectiveDecision + const runDecision = setupTrustMismatch || lacksFolderApproval ? 'skip' : effectiveDecision if (setupTrustMismatch) { // Automations have no prompt to re-ask; the host log is their record of the skip. console.warn(`[hooks] setup skipped for ${worktreePath}: it differs from the approved content`) } + if (lacksFolderApproval) { + const skipped = + 'orca.yaml setup skipped for this folder workspace because it was not approved; pass --setup run to run it.' + warning = warning ? `${warning} Also ${skipped}` : skipped + } let defaultTabs: CreateWorktreeResult['defaultTabs'] try { const launch = getDefaultTabsLaunch(yamlHooks, repo, runDecision) @@ -92,14 +111,21 @@ export async function prepareRuntimeLocalWorktreeSetup(args: { hooks.scripts.setup, args.runtimeTarget, resolveSetupRunnerShell(settings), - yamlHooks?.setupAgentStartupPolicy + yamlHooks?.setupAgentStartupPolicy, + args.identity ) } catch (error) { console.error(`[hooks] Failed to prepare setup runner for ${worktreePath}:`, error) + if (isFolderRepo(repo)) { + const failed = `Setup did not run: Orca could not write its setup file in ${worktreePath}.` + warning = warning ? `${warning} Also ${failed}` : failed + } } } else { didStartInProcessSetupHook = true - void runHook('setup', worktreePath, repo, worktreePath, args.runtimeTarget).then((result) => { + void runHook('setup', worktreePath, repo, worktreePath, args.runtimeTarget, { + identity: args.identity + }).then((result) => { if (!result.success) { console.error(`[hooks] setup hook failed for ${worktreePath}:`, result.output) } diff --git a/src/main/runtime/workspaces/creation/workspace-creation.ts b/src/main/runtime/workspaces/creation/workspace-creation.ts index 6dea38dd8f6..c921f5bc2f5 100644 --- a/src/main/runtime/workspaces/creation/workspace-creation.ts +++ b/src/main/runtime/workspaces/creation/workspace-creation.ts @@ -15,6 +15,8 @@ import { resolveWorktreeCreateRoute } from '../../../workspaces/creation/worktre import { ExecutionHostNotDispatchableError } from '../../../providers/execution-host-provider-dispatch' import { SshHostNotServedError } from '../../../providers/ssh-host-not-served-error' import { createRuntimeFolderWorktree } from './runtime-folder-worktree-create' +import type { RuntimeNavigationTarget } from '../../../../shared/runtime-navigation' +import type { Worktree } from '../../../../shared/worktree/types' import { createRuntimeLocalManagedWorktree } from './runtime-local-worktree-create' import type { PreparationRearmHolder } from '../../../workspaces/creation/preparation/worktree-create-preparation' import { @@ -22,7 +24,10 @@ import { prepareRuntimeLocalWorktreeSetup } from './runtime-local-worktree-setup' import { invalidateAuthorizedRootsCacheForRepo } from '../../../ipc/worktrees/removal/registered-worktree-roots-scoped-invalidation' -import { startRuntimeLocalWorktreeTerminals } from '../startup/runtime-local-worktree-terminal-startup' +import { + startRuntimeLocalWorktreeTerminals, + type RuntimeLocalWorktreeTerminalPorts +} from '../startup/runtime-local-worktree-terminal-startup' import { trackRuntimeWorkspaceCreate } from '../../../workspaces/creation/workspace-create-telemetry' import type { RuntimeWorkspaceCreateEvents } from '../../../workspaces/creation/workspace-create-telemetry' import { @@ -128,17 +133,15 @@ export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWi draftPaste: effectiveDraftPaste, deps: { store, - ptySpawnAvailable: Boolean(this.ptyController?.spawn), - provisionInBackground: () => this.shouldProvisionWorktreeInBackground(args.navigation), - createTerminal: (selector, options) => - this.createTerminal(selector, { ...options, ...wslUserAct(args) }), - pasteDraft: (handle, draft) => this.pasteStartupDraftWhenReady(handle, draft), - sendFollowup: (handle, followup, terminal) => - void this.deliverStartupFollowup(handle, followup, { terminalCreation: terminal }), + terminals: this.localWorktreeTerminalPorts(args, activationCallbacks.local), invalidateResolvedWorktrees: () => this.invalidateResolvedWorktreeCache(), notifyWorktreesChanged: (repoId) => this.notifyWorktreesChanged(repoId), emitCreated: (event) => this.emitWorktreeLifecycle(event), - activate: activationCallbacks.folder + activate: activationCallbacks.folder, + setup: { + runtimeTarget: () => this.getLocalGitExecutionOptionArgs(repo)[0], + shouldUseSetupRunner: this.canUseSetupRunner(effectiveStartup) + } } }) } @@ -195,10 +198,7 @@ export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWi worktreePath, settings: createSettings, runtimeTarget: this.getLocalGitExecutionOptionArgs(repo)[0], - shouldUseSetupRunner: - this.authoritativeWindowId !== null || - Boolean(effectiveStartup) || - Boolean(this.ptyController?.spawn), + shouldUseSetupRunner: this.canUseSetupRunner(effectiveStartup), warning: [includeCopyWarning, addResult.upstreamWarning].filter(Boolean).join(' ') || undefined }) @@ -234,18 +234,7 @@ export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWi promisedAgentChat: args.promisedAgentChat, draftPaste: effectiveDraftPaste, warning, - ports: { - canSpawn: Boolean(this.ptyController?.spawn), - provisionInBackground: () => this.shouldProvisionWorktreeInBackground(args.navigation), - createTerminal: (selector, options) => - this.createTerminal(selector, { ...options, ...wslUserAct(args) }, worktree), - pasteDraft: (handle, draft) => this.pasteStartupDraftWhenReady(handle, draft), - sendFollowup: (handle, followup, terminal) => - void this.deliverStartupFollowup(handle, followup, { terminalCreation: terminal }), - provision: (options) => - this.provisionManagedWorktreeTerminals({ ...options, ...wslUserAct(args) }, worktree), - activate: activationCallbacks.local - } + ports: this.localWorktreeTerminalPorts(args, activationCallbacks.local, worktree) }) warning = terminalWarning this.emitWorktreeLifecycle({ @@ -298,4 +287,32 @@ export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWi : {}) } } + + // A window, an agent or a PTY host can show setup in a terminal; otherwise it runs in-process. + private canUseSetupRunner(startup: unknown): boolean { + return ( + this.authoritativeWindowId !== null || Boolean(startup) || Boolean(this.ptyController?.spawn) + ) + } + + private localWorktreeTerminalPorts( + args: { navigation?: RuntimeNavigationTarget; wslUserAct?: true }, + activate: RuntimeLocalWorktreeTerminalPorts['activate'], + worktree?: Worktree + ): RuntimeLocalWorktreeTerminalPorts { + return { + canSpawn: Boolean(this.ptyController?.spawn), + provisionInBackground: () => this.shouldProvisionWorktreeInBackground(args.navigation), + createTerminal: (selector, options) => + worktree + ? this.createTerminal(selector, { ...options, ...wslUserAct(args) }, worktree) + : this.createTerminal(selector, { ...options, ...wslUserAct(args) }), + pasteDraft: (handle, draft) => this.pasteStartupDraftWhenReady(handle, draft), + sendFollowup: (handle, followup, terminal) => + void this.deliverStartupFollowup(handle, followup, { terminalCreation: terminal }), + provision: (options) => + this.provisionManagedWorktreeTerminals({ ...options, ...wslUserAct(args) }, worktree), + activate + } + } } diff --git a/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts b/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts index 3ef174772f6..cb942c3efbb 100644 --- a/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts +++ b/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts @@ -101,7 +101,8 @@ async function acceptRuntimeRegisteredLocalWorktreeRemoval(args: { canonicalPath, repo, undefined, - args.hasLocalOptions ? localOptions : undefined + args.hasLocalOptions ? localOptions : undefined, + { identity: { worktreeId: args.target.id } } ) archiveHookOverride = gateWorktreeRemovalOnArchiveHook({ worktreePath: canonicalPath, diff --git a/src/main/runtime/workspaces/removal/workspace-registration-removal.ts b/src/main/runtime/workspaces/removal/workspace-registration-removal.ts index f4f502f1233..2a8c12a6d04 100644 --- a/src/main/runtime/workspaces/removal/workspace-registration-removal.ts +++ b/src/main/runtime/workspaces/removal/workspace-registration-removal.ts @@ -5,7 +5,16 @@ import type { Repo } from '../../../../shared/repo-types' import type { ExecutionHostId } from '../../../../shared/execution-host' import type { WorktreeTeardownRuntime } from './worktree-teardown' import { splitWorktreeId, splitWorktreeIdForFilesystem } from '../../../../shared/worktree/id' -import { parseExecutionHostId } from '../../../../shared/execution-host' +import { isRepoOnCatalogHost, parseExecutionHostId } from '../../../../shared/execution-host' +import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' +import { readWorktreeMetaForRepo } from '../../../persistence/host-qualified-worktree-meta' +import { getEffectiveHooks } from '../../../workspace-hooks/hooks' +import { blockedWslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' +import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' +import { + gateFolderWorkspaceRemovalOnArchiveHook, + removeFolderWorkspaceRunnerFiles +} from '../../../workspaces/removal/folder-workspace-archive-hook' import { invalidateAuthorizedRootsCache } from '../../../ipc/worktrees/removal/registered-worktree-roots-cache' import { isFolderRepo } from '../../../../shared/repo-kind' import { getRuntimeFolderWorkspaceRootId } from '../catalog/runtime-folder-workspace' @@ -33,7 +42,8 @@ export async function removeOrphanOrFolderWorktree({ removalTarget, cleanupHostId, removalHostId, - repo + repo, + archive }: { runtime: WorkspaceRegistrationRemovalRuntime store: RuntimeStore @@ -41,7 +51,9 @@ export async function removeOrphanOrFolderWorktree({ cleanupHostId?: ExecutionHostId removalHostId?: ExecutionHostId repo?: Repo -}): Promise<{ warning?: string } | undefined> { + /** Same opt-in as worktree removal: archive runs only when the caller asked for hooks. */ + archive: { runHooks: boolean; allowFailedArchiveHook: boolean } +}): Promise<(RemoveWorktreeResult & { warning?: string }) | undefined> { if (!repo) { const orphanHost = parseExecutionHostId(store.getWorktreeMeta(removalTarget.id)?.hostId) if (cleanupHostId && orphanHost?.id !== cleanupHostId) { @@ -106,6 +118,25 @@ export async function removeOrphanOrFolderWorktree({ if (removalTarget.id === getRuntimeFolderWorkspaceRootId(repo)) { throw new Error('Cannot delete the project root workspace. Remove the folder project instead.') } + // Archive failure must refuse before watcher, PTY or metadata teardown (#19334). + const archiveHookOverride = await gateFolderWorkspaceRemovalOnArchiveHook({ + repo, + worktreeId: removalTarget.id, + displayName: + ( + readWorktreeMetaForRepo(store, removalTarget.id, repo) ?? + store.getWorktreeMeta(removalTarget.id) + )?.displayName ?? repo.displayName, + runArchive: archive.runHooks, + allowFailure: archive.allowFailedArchiveHook, + runtimeTarget: () => getLocalProjectWorktreeGitOptions(store, repo) + }) + // Without --run-hooks, look at the folder only to warn, and never start its stopped WSL distro for that. + const archiveSkipped = + !archive.runHooks && + isRepoOnCatalogHost(repo) && + !(await blockedWslDistroForPath(repo.path)) && + Boolean(getEffectiveHooks(repo)?.scripts.archive) // Use the resolved SSH owner, including executionHostId-only rows; runtime-nested targets belong to that environment's namespace. const folderHost = parseExecutionHostId(removalHostId) const folderConnectionId = folderHost?.kind === 'ssh' ? folderHost.targetId : null @@ -121,10 +152,19 @@ export async function removeOrphanOrFolderWorktree({ folderConnectionId ) await runtime.removeWorktreeMetadataAndHistory(store, removalTarget.id, removalHostId) + removeFolderWorkspaceRunnerFiles(repo, removalTarget.id) runtime.preservedBranchCleanup.delete(removalTarget.id, cleanupHostId) runtime.invalidateResolvedWorktreeCache() runtime.notifyWorktreesChanged(repo.id) - return {} + return { + ...(archiveHookOverride ? { archiveHookOverride } : {}), + ...(archiveSkipped + ? { + warning: + 'orca.yaml archive hook skipped for this folder workspace; pass --run-hooks to run it.' + } + : {}) + } } finally { await gate.finish(false) } diff --git a/src/main/runtime/workspaces/removal/workspace-removal.ts b/src/main/runtime/workspaces/removal/workspace-removal.ts index 110f3210a12..f4b8967642b 100644 --- a/src/main/runtime/workspaces/removal/workspace-removal.ts +++ b/src/main/runtime/workspaces/removal/workspace-removal.ts @@ -77,10 +77,7 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends RuntimeWorksp allowFailedArchiveHook = false, hostId } = options - if (!this.store) { - throw new Error('runtime_unavailable') - } - const store = this.store + const store = this.requireStore() const cleanupHostId = parseExecutionHostId(hostId)?.id const removalTarget = await this.resolveWorktreeRemovalTarget(worktreeSelector, cleanupHostId) // The repo row names the host; a caller may omit hostId for a worktree on another host. @@ -144,7 +141,8 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends RuntimeWorksp removalTarget, cleanupHostId, removalHostId, - repo + repo, + archive: { runHooks, allowFailedArchiveHook } }) if (orphanOrFolderResult) { return orphanOrFolderResult diff --git a/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts b/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts index 0e2ee76b7d1..dade1601abc 100644 --- a/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts +++ b/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts @@ -23,7 +23,7 @@ import type { WorktreeTerminalProvisioningArgs } from './runtime-worktree-terminal-provisioning' -type Ports = { +export type RuntimeLocalWorktreeTerminalPorts = { canSpawn: boolean provisionInBackground?: () => boolean createTerminal: ( @@ -76,7 +76,7 @@ export async function startRuntimeLocalWorktreeTerminals(args: { promisedAgentChat?: boolean draftPaste?: WorktreeStartupDraftPaste warning?: string - ports: Ports + ports: RuntimeLocalWorktreeTerminalPorts }): Promise { const { request, repo, worktree, defaultTabs, startup, ports } = args let { setup } = args diff --git a/src/main/workspace-hooks/created-worktree-setup-trust.ts b/src/main/workspace-hooks/created-worktree-setup-trust.ts index 9cd6393cf5d..f9b4fdcd706 100644 --- a/src/main/workspace-hooks/created-worktree-setup-trust.ts +++ b/src/main/workspace-hooks/created-worktree-setup-trust.ts @@ -39,6 +39,28 @@ export function checkCreatedWorktreeSetupTrust( return matches ? undefined : { contentHash, scriptContent } } +/** + * Older clients send no approval hash. A folder's shared setup never ran before folder setup + * existed, so it needs an approval or an explicit run rather than starting unseen. + */ +export function folderSharedSetupLacksApproval( + repo: Repo, + createdYamlHooks: OrcaHooks | null, + decision: SetupDecision | undefined, + approved: ApprovedSetupHashes +): boolean { + if (approved.approvedSetupHash !== undefined || approved.approvedSetupHashes !== undefined) { + return false + } + if (decision === 'run') { + return false + } + const policy = resolveHookCommandSourcePolicy(repo.hookSettings?.commandSourcePolicy, { + hasLocalScript: Boolean(repo.hookSettings?.scripts.setup?.trim()) + }) + return policy !== 'local-only' && Boolean(getSetupTrustContent(createdYamlHooks)) +} + function wouldRunSetup(repo: Repo, decision: SetupDecision | undefined): boolean { try { return shouldRunSetupForCreate(repo, decision) diff --git a/src/main/workspace-hooks/folder-setup-runner-files.test.ts b/src/main/workspace-hooks/folder-setup-runner-files.test.ts new file mode 100644 index 00000000000..b022c63c532 --- /dev/null +++ b/src/main/workspace-hooks/folder-setup-runner-files.test.ts @@ -0,0 +1,46 @@ +import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { newFolderSetupRunnerPath, removeFolderSetupRunnerFiles } from './folder-setup-runner-files' + +const WORKSPACE_A = 'repo::/acme::workspace:11111111-1111-4111-8111-111111111111' +const WORKSPACE_B = 'repo::/acme::workspace:22222222-2222-4222-8222-222222222222' + +let folder: string + +beforeEach(() => { + folder = mkdtempSync(join(tmpdir(), 'orca-folder-runner-')) +}) + +afterEach(() => { + rmSync(folder, { recursive: true, force: true }) +}) + +function writeRunner(worktreeId: string): string { + const path = newFolderSetupRunnerPath(folder, worktreeId, 'sh') + mkdirSync(dirname(path), { recursive: true }) + writeFileSync(path, 'echo setup\n') + return path +} + +describe('folder setup runner files', () => { + it('gives every launch its own file, so a later launch never rewrites a running script', () => { + const first = writeRunner(WORKSPACE_A) + const second = writeRunner(WORKSPACE_A) + expect(first).not.toBe(second) + expect(dirname(first)).toBe(dirname(second)) + }) + + it("removes only the removed workspace's runners", async () => { + writeRunner(WORKSPACE_A) + writeRunner(WORKSPACE_A) + const kept = writeRunner(WORKSPACE_B) + writeFileSync(join(folder, '.orca', 'issue-command'), 'claude') + await removeFolderSetupRunnerFiles(folder, WORKSPACE_A) + expect(readdirSync(join(folder, '.orca')).sort()).toEqual( + ['issue-command', dirname(kept).split(/[\\/]/).pop()!].sort() + ) + expect(readdirSync(dirname(kept))).toEqual([kept.split(/[\\/]/).pop()!]) + }) +}) diff --git a/src/main/workspace-hooks/folder-setup-runner-files.ts b/src/main/workspace-hooks/folder-setup-runner-files.ts new file mode 100644 index 00000000000..0986d8ed473 --- /dev/null +++ b/src/main/workspace-hooks/folder-setup-runner-files.ts @@ -0,0 +1,49 @@ +import { randomUUID } from 'node:crypto' +import { rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR } from '../../shared/worktree/id' +import { windowsFsPath } from '../wsl/filesystem/wsl-unc-drive-fs-path' + +const FOLDER_RUNNER_DIR = '.orca' + +// One directory per workspace, so removal deletes it without listing its siblings' runners. +function runnerDirName(worktreeId: string): string { + const separatorIdx = worktreeId.lastIndexOf(FOLDER_WORKSPACE_INSTANCE_SEPARATOR) + const instance = + separatorIdx === -1 + ? 'root' + : worktreeId.slice(separatorIdx + FOLDER_WORKSPACE_INSTANCE_SEPARATOR.length) + return `setup-runner-${instance.replace(/[^A-Za-z0-9-]/g, '_')}` +} + +/** A fresh file per launch: workspaces share the folder, and bash/cmd re-read a runner by offset while it runs. */ +export function newFolderSetupRunnerPath( + folderPath: string, + worktreeId: string, + extension: 'sh' | 'cmd' +): string { + return join( + folderPath, + FOLDER_RUNNER_DIR, + runnerDirName(worktreeId), + `${randomUUID()}.${extension}` + ) +} + +/** A folder may itself be a Git checkout; keep its runners out of `git status` without editing its files. */ +export async function ignoreFolderSetupRunners(orcaDirFsPath: string): Promise { + await writeFile(join(orcaDirFsPath, '.gitignore'), 'setup-runner-*\n.gitignore\n', { + flag: 'wx' + }).catch(() => undefined) +} + +/** Call after the workspace's processes stopped, so no running script loses its file. */ +export async function removeFolderSetupRunnerFiles( + folderPath: string, + worktreeId: string +): Promise { + const dir = windowsFsPath(join(folderPath, FOLDER_RUNNER_DIR, runnerDirName(worktreeId))) + await rm(dir, { recursive: true, force: true }).catch((error: unknown) => { + console.warn(`[hooks] could not remove setup runners in ${dir}:`, error) + }) +} diff --git a/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts b/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts index 7a22d7f5c61..c81ae6d2897 100644 --- a/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts +++ b/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts @@ -15,7 +15,7 @@ async function runArchive(script: string, timeoutMs = 400) { const dir = mkdtempSync(join(tmpdir(), 'orca-hook-deadline-')) writeFileSync(join(dir, 'orca.yaml'), `scripts:\n archive: |\n ${script}\n`) try { - return await runHook('archive', dir, REPO, dir, undefined, timeoutMs) + return await runHook('archive', dir, REPO, dir, undefined, { timeoutMs }) } finally { rmSync(dir, { recursive: true, force: true }) } diff --git a/src/main/workspace-hooks/hook-orca-cli-env.ts b/src/main/workspace-hooks/hook-orca-cli-env.ts new file mode 100644 index 00000000000..503f1c84e36 --- /dev/null +++ b/src/main/workspace-hooks/hook-orca-cli-env.ts @@ -0,0 +1,72 @@ +import { getAppEnvironment, hasAppEnvironment } from '../../shared/app-environment' +import { toLinuxPath } from '../../shared/wsl-paths' +import { prependOrcaCliDirToChildPath } from '../cli/orca-cli-child-path' +import { getManagedWslCliDir, getWslCliCommandName } from '../cli/wsl-managed-cli' +import { WSL_MANAGED_CLI_PATH_RESTORE } from '../wsl/execution/wsl-managed-cli-path-restore' + +// A hook isn't a pane: an Orca started from an Orca terminal must not lend that pane's identity. +const INHERITED_PANE_IDENTITY_KEYS = [ + 'ORCA_TERMINAL_HANDLE', + 'ORCA_PANE_KEY', + 'ORCA_TAB_ID', + 'ORCA_AGENT_LAUNCH_TOKEN', + 'ORCA_WORKSPACE_ID', + 'ORCA_WORKTREE_ID' +] as const + +/** Give an in-process hook this app's `orca` CLI, as terminals get it. */ +export function applyHostHookOrcaCliEnv(env: Record): void { + for (const key of INHERITED_PANE_IDENTITY_KEYS) { + delete env[key] + } + if (!hasAppEnvironment()) { + return + } + const app = getAppEnvironment() + const userDataPath = app.getPath('userData') + const childEnv = Object.fromEntries( + Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined) + ) + childEnv.ORCA_USER_DATA_PATH = userDataPath + prependOrcaCliDirToChildPath(childEnv, { + isPackaged: app.isPackaged(), + userDataPath, + resourcesPath: process.resourcesPath ?? null + }) + for (const key of Object.keys(env)) { + if (!(key in childEnv)) { + delete env[key] + } + } + Object.assign(env, childEnv) +} + +/** + * The guest env and a script prefix that puts the managed WSL CLI first on PATH. Inherited pane + * identity is blanked, since wsl.exe would otherwise carry the host's values in through WSLENV. + */ +export function wslHookOrcaCliEnv(): { env: Record; scriptPrefix: string } { + const blankedIdentity = Object.fromEntries(INHERITED_PANE_IDENTITY_KEYS.map((key) => [key, ''])) + if (!hasAppEnvironment()) { + return { env: blankedIdentity, scriptPrefix: '' } + } + const app = getAppEnvironment() + const userDataPath = app.getPath('userData') + const managedCliDir = getManagedWslCliDir({ + isPackaged: app.isPackaged(), + userDataPath, + ...(process.resourcesPath ? { resourcesPath: process.resourcesPath } : {}) + }) + if (!managedCliDir) { + return { env: blankedIdentity, scriptPrefix: '' } + } + return { + env: { + ...blankedIdentity, + ORCA_WSL_CLI_DIR: toLinuxPath(managedCliDir), + ORCA_CLI_COMMAND: getWslCliCommandName(app.isPackaged()), + ORCA_USER_DATA_PATH: toLinuxPath(userDataPath) + }, + scriptPrefix: `${WSL_MANAGED_CLI_PATH_RESTORE}\n` + } +} diff --git a/src/main/workspace-hooks/hook-termination-real-process.test.ts b/src/main/workspace-hooks/hook-termination-real-process.test.ts index fc8d02cce38..fc4123fd6e5 100644 --- a/src/main/workspace-hooks/hook-termination-real-process.test.ts +++ b/src/main/workspace-hooks/hook-termination-real-process.test.ts @@ -27,7 +27,7 @@ async function survivorsAfterDeadline( ) let pids: number[] = [] try { - const result = await runHook('archive', dir, REPO, dir, undefined, 400) + const result = await runHook('archive', dir, REPO, dir, undefined, { timeoutMs: 400 }) expect(result.success).toBe(false) expect(existsSync(pidFile)).toBe(true) pids = readFileSync(pidFile, 'utf8').trim().split(/\s+/).map(Number) diff --git a/src/main/workspace-hooks/hooks.ts b/src/main/workspace-hooks/hooks.ts index 94a74cc949d..6194e841958 100644 --- a/src/main/workspace-hooks/hooks.ts +++ b/src/main/workspace-hooks/hooks.ts @@ -4,7 +4,8 @@ import { parseOrcaYaml } from '../../shared/orca-yaml' import { resolveHookCommandSourcePolicy } from '../../shared/hook-command-source-policy' import { getEffectiveHooksFromConfig } from './effective-hook-config' import { getHookRuntimeTarget, getHookWslContext } from './hook-runtime-target' -import { getSetupEnvVars } from './setup-hook-env-vars' +import { getSetupEnvVars, type HookWorkspaceIdentity } from './setup-hook-env-vars' +import { applyHostHookOrcaCliEnv, wslHookOrcaCliEnv } from './hook-orca-cli-env' import { iterateLfScriptLines } from './setup-runner-script-text' import { promptGuardShellEnv } from '../git/command-runner/git-process-env' import { dropIncoherentCondaActivationEnv } from '../pty/shell-startup/conda-activation-env' @@ -185,10 +186,12 @@ export function runHook( repo: Repo, hooksPath?: string, projectRuntime?: ProjectExecutionRuntimeResolution | HookRuntimeTarget, - timeoutMs: number = HOOK_TIMEOUT + options: { identity?: HookWorkspaceIdentity; timeoutMs?: number; hooks?: OrcaHooks } = {} // Failed hooks without an observed exit are unverifiable to the removal gate (#19334). ): Promise<{ success: boolean; output: string; exitCode?: number }> { - const hooks = getEffectiveHooks(repo, hooksPath) + const timeoutMs = options.timeoutMs ?? HOOK_TIMEOUT + // A caller that already resolved the hooks passes them, so orca.yaml is read once. + const hooks = options.hooks ?? getEffectiveHooks(repo, hooksPath) const script = hooks?.scripts[hookName] if (!script) { @@ -200,14 +203,15 @@ export function runHook( if (wslInfo) { // WSL hooks need Linux paths for ORCA_* values, including Windows UNC paths. - const envVars = getSetupEnvVars(repo, cwd) + const envVars = getSetupEnvVars(repo, cwd, options.identity) const wslEnv: Record = {} for (const [key, value] of Object.entries(envVars)) { wslEnv[key] = toLinuxPath(value) } // Forward unattended Git flags to WSL; keep host askpass out of the guest. const guardedEnv = promptGuardShellEnv(wslEnv) - const guestEnv: Record = { ...wslEnv } + const wslCli = wslHookOrcaCliEnv() + const guestEnv: Record = { ...wslCli.env, ...wslEnv } for (const [key, value] of Object.entries(guardedEnv)) { if (value !== undefined && (key === 'GIT_TERMINAL_PROMPT' || key === 'GCM_INTERACTIVE')) { guestEnv[key] = value @@ -217,7 +221,7 @@ export function runHook( return runWslProcess({ distro: wslInfo.distro ?? undefined, loginPath: 'preferred', - script, + script: `${wslCli.scriptPrefix}${script}`, // Match native Bash hook semantics; sh would reject Bash-only scripts inside WSL. shell: 'bash', cwd: wslInfo.linuxPath, @@ -228,7 +232,9 @@ export function runHook( .catch((error: unknown) => hookSpawnFailure(error, { hookName, cwd })) } - const shellHookEnv: NodeJS.ProcessEnv = { ...process.env, ...getSetupEnvVars(repo, cwd) } + const shellHookEnv: NodeJS.ProcessEnv = { ...process.env } + applyHostHookOrcaCliEnv(shellHookEnv) + Object.assign(shellHookEnv, getSetupEnvVars(repo, cwd, options.identity)) dropIncoherentCondaActivationEnv(shellHookEnv) return new Promise((resolve) => { diff --git a/src/main/workspace-hooks/setup-hook-env-vars.ts b/src/main/workspace-hooks/setup-hook-env-vars.ts index 337bdc20322..81211369da7 100644 --- a/src/main/workspace-hooks/setup-hook-env-vars.ts +++ b/src/main/workspace-hooks/setup-hook-env-vars.ts @@ -1,6 +1,14 @@ import { getRuntimePathBasename } from '../../shared/cross-platform-path' import { TERMINAL_GIT_CREDENTIAL_GUARD_POLICY_ENV } from '../../shared/shell/launch/terminal-git-credential-guard' import type { Repo } from '../../shared/repo-types' +import { isFolderRepo } from '../../shared/repo-kind' + +/** The workspace a hook runs for; folder workspaces share one directory, so the path can't name them. */ +export type HookWorkspaceIdentity = { + worktreeId: string + /** Names a folder workspace; a worktree's name is its directory's. */ + displayName?: string +} // Path-valued keys only, so WSL and posix-shell launches translate them; names are not paths. export const SETUP_RUNNER_PATH_ENV_KEYS = [ @@ -12,24 +20,37 @@ export const SETUP_RUNNER_PATH_ENV_KEYS = [ ] as const export function getSetupEnvVars( - repo: Pick, - worktreePath: string + repo: Pick, + worktreePath: string, + identity?: HookWorkspaceIdentity ): Record { + const workspaceName = + identity?.displayName && isFolderRepo(repo) + ? identity.displayName + : getRuntimePathBasename(worktreePath) return { ORCA_ROOT_PATH: repo.path, ORCA_WORKTREE_PATH: worktreePath, - ORCA_WORKSPACE_NAME: getRuntimePathBasename(worktreePath), + ORCA_WORKSPACE_NAME: workspaceName, + // Same values a pane sets, so `orca worktree create` in the hook attaches to this workspace. + ...(identity + ? { ORCA_WORKSPACE_ID: identity.worktreeId, ORCA_WORKTREE_ID: identity.worktreeId } + : {}), // Imported Conductor scripts read these names. CONDUCTOR_ROOT_PATH: repo.path, CONDUCTOR_WORKSPACE_PATH: worktreePath, - CONDUCTOR_WORKSPACE_NAME: getRuntimePathBasename(worktreePath), + CONDUCTOR_WORKSPACE_NAME: workspaceName, GHOSTX_ROOT_PATH: repo.path } } -export function getSetupRunnerEnvVars(repo: Repo, worktreePath: string): Record { +export function getSetupRunnerEnvVars( + repo: Repo, + worktreePath: string, + identity?: HookWorkspaceIdentity +): Record { return { - ...getSetupEnvVars(repo, worktreePath), + ...getSetupEnvVars(repo, worktreePath, identity), // Unattended setup always needs credential protection, regardless of user opt-out. [TERMINAL_GIT_CREDENTIAL_GUARD_POLICY_ENV]: 'guard' } diff --git a/src/main/workspace-hooks/worktree-runner-script.ts b/src/main/workspace-hooks/worktree-runner-script.ts index cc3ca4c067d..e7dd4ef7288 100644 --- a/src/main/workspace-hooks/worktree-runner-script.ts +++ b/src/main/workspace-hooks/worktree-runner-script.ts @@ -1,4 +1,4 @@ -import { mkdirSync, writeFileSync, chmodSync } from 'node:fs' +import { chmod, mkdir, writeFile } from 'node:fs/promises' import { dirname } from 'node:path' import { shouldWaitForSetupBeforeAgentStartup } from '../../shared/agent-launch/startup/setup-agent-startup-policy' import { @@ -14,13 +14,20 @@ import { readWorktreeGitPath } from '../git/worktrees/catalog/worktree-git-path' import { resolveWslWorktreeGitPath } from '../git/worktrees/catalog/wsl-worktree-git-path' import { knownWslAutomountRoots } from '../wsl/filesystem/wsl-automount-root' import { isWslPath } from '../wsl/filesystem/unc-path-access' +import { windowsFsPath } from '../wsl/filesystem/wsl-unc-drive-fs-path' import { toWindowsWslPath, toLinuxPath } from '../../shared/wsl-paths' import { getHookRuntimeTarget, getHookWslContext, type HookRuntimeTarget } from './hook-runtime-target' -import { SETUP_RUNNER_PATH_ENV_KEYS, getSetupRunnerEnvVars } from './setup-hook-env-vars' +import { + SETUP_RUNNER_PATH_ENV_KEYS, + getSetupRunnerEnvVars, + type HookWorkspaceIdentity +} from './setup-hook-env-vars' +import { ignoreFolderSetupRunners, newFolderSetupRunnerPath } from './folder-setup-runner-files' +import { isFolderRepo } from '../../shared/repo-kind' import { buildPosixRunnerScript, buildWindowsRunnerScript } from './setup-runner-script-text' import type { Repo } from '../../shared/repo-types' @@ -44,9 +51,11 @@ export async function createSetupRunnerScript( script: string, projectRuntime?: ProjectExecutionRuntimeResolution | HookRuntimeTarget, setupShell?: SetupRunnerShell, - projectStartupPolicy?: SetupAgentStartupPolicy + projectStartupPolicy?: SetupAgentStartupPolicy, + identity?: HookWorkspaceIdentity ): Promise { return createWorktreeRunnerScript({ + identity, repo, worktreePath, script, @@ -68,6 +77,7 @@ async function createWorktreeRunnerScript(args: { runtimeTarget?: HookRuntimeTarget waitForAgentStartup?: boolean setupShell?: SetupRunnerShell + identity?: HookWorkspaceIdentity }): Promise { const { repo, @@ -76,9 +86,10 @@ async function createWorktreeRunnerScript(args: { runnerBaseName, runtimeTarget, waitForAgentStartup, - setupShell + setupShell, + identity } = args - const envVars = getSetupRunnerEnvVars(repo, worktreePath) + const envVars = getSetupRunnerEnvVars(repo, worktreePath, identity) const wslWorktree = isWslPath(worktreePath) || Boolean(runtimeTarget?.wslDistro) const nativeWindowsWorktree = process.platform === 'win32' && !wslWorktree // Preserve existing Windows cmd script syntax; only a shebang opts into bash, regardless of terminal preference. @@ -93,34 +104,28 @@ async function createWorktreeRunnerScript(args: { : process.platform === 'win32' && runtimeTarget?.wslDistro ? { family: 'posix', executable: 'wsl.exe' } : undefined - // Linked worktrees have .git files; resolve the per-worktree gitdir through Git. const runnerExtension = runnerShell.family === 'cmd' ? 'cmd' : 'sh' - const gitRelPath = `orca/${runnerBaseName}.${runnerExtension}` - // Read the link with the D1c Git router (if WSL Git made the worktree, host Git can't). A worktree - // inside a distro never runs synchronous Git: that would be a synchronous wsl.exe on the main thread. - const fromLink = isWslPath(worktreePath) - ? await resolveWslWorktreeGitPath(worktreePath, gitRelPath) - : isLocalGitRuntimeRouterInstalled() - ? readWorktreeGitPath(worktreePath, gitRelPath, knownWslAutomountRoots()) - : null - let runnerScriptPath = fromLink ?? getGitPath(worktreePath, gitRelPath) + const runnerScriptPath = isFolderRepo(repo) + ? newFolderSetupRunnerPath( + worktreePath, + requireFolderIdentity(identity).worktreeId, + runnerExtension + ) + : await resolveGitRunnerScriptPath(worktreePath, runnerBaseName, runnerExtension, runtimeTarget) - // Convert WSL Git's Linux path to a path Windows filesystem calls can reach. - if (wslWorktree && !fromLink) { - const wslInfo = getHookWslContext(worktreePath, runtimeTarget) - if (wslInfo?.distro) { - runnerScriptPath = toWindowsWslPath(runnerScriptPath.trim(), wslInfo.distro) - } + // Write through the drive path when WSL refuses its drive mounts over UNC; launch keeps the UNC spelling. + const runnerFsPath = windowsFsPath(runnerScriptPath) + await mkdir(dirname(runnerFsPath), { recursive: true }) + if (isFolderRepo(repo)) { + await ignoreFolderSetupRunners(dirname(dirname(runnerFsPath))) } - mkdirSync(dirname(runnerScriptPath), { recursive: true }) - if (runnerShell.family === 'cmd') { - writeFileSync(runnerScriptPath, buildWindowsRunnerScript(script), 'utf-8') + await writeFile(runnerFsPath, buildWindowsRunnerScript(script), 'utf-8') } else { - writeFileSync(runnerScriptPath, buildPosixRunnerScript(script), 'utf-8') + await writeFile(runnerFsPath, buildPosixRunnerScript(script), 'utf-8') if (!nativeWindowsWorktree) { - chmodSync(runnerScriptPath, 0o755) + await chmod(runnerFsPath, 0o755) } } @@ -148,6 +153,41 @@ async function createWorktreeRunnerScript(args: { } } +function requireFolderIdentity(identity: HookWorkspaceIdentity | undefined): HookWorkspaceIdentity { + if (!identity) { + throw new Error('A folder workspace setup runner needs the workspace it runs for.') + } + return identity +} + +async function resolveGitRunnerScriptPath( + worktreePath: string, + runnerBaseName: 'setup-runner', + runnerExtension: 'sh' | 'cmd', + runtimeTarget: HookRuntimeTarget | undefined +): Promise { + const wslWorktree = isWslPath(worktreePath) || Boolean(runtimeTarget?.wslDistro) + // Linked worktrees have .git files; resolve the per-worktree gitdir through Git. + const gitRelPath = `orca/${runnerBaseName}.${runnerExtension}` + // Read the link with the D1c Git router (if WSL Git made the worktree, host Git can't). A worktree + // inside a distro never runs synchronous Git: that would be a synchronous wsl.exe on the main thread. + const fromLink = isWslPath(worktreePath) + ? await resolveWslWorktreeGitPath(worktreePath, gitRelPath) + : isLocalGitRuntimeRouterInstalled() + ? readWorktreeGitPath(worktreePath, gitRelPath, knownWslAutomountRoots()) + : null + let runnerScriptPath = fromLink ?? getGitPath(worktreePath, gitRelPath) + + // Convert WSL Git's Linux path to a path Windows filesystem calls can reach. + if (wslWorktree && !fromLink) { + const wslInfo = getHookWslContext(worktreePath, runtimeTarget) + if (wslInfo?.distro) { + runnerScriptPath = toWindowsWslPath(runnerScriptPath.trim(), wslInfo.distro) + } + } + return runnerScriptPath +} + export function resolveSetupRunnerShell( settings: SetupRunnerShellSettings, platform: NodeJS.Platform = process.platform, diff --git a/src/main/workspaces/removal/folder-workspace-archive-hook.ts b/src/main/workspaces/removal/folder-workspace-archive-hook.ts new file mode 100644 index 00000000000..987e1f89c56 --- /dev/null +++ b/src/main/workspaces/removal/folder-workspace-archive-hook.ts @@ -0,0 +1,52 @@ +import { isRepoOnCatalogHost } from '../../../shared/execution-host' +import type { Repo } from '../../../shared/repo-types' +import type { ArchiveHookOverride } from '../../../shared/worktree/archive-hook-removal-gate' +import { removeFolderSetupRunnerFiles } from '../../workspace-hooks/folder-setup-runner-files' +import { getEffectiveHooks, runHook } from '../../workspace-hooks/hooks' +import type { HookRuntimeTarget } from '../../workspace-hooks/hook-runtime-target' +import { gateWorktreeRemovalOnArchiveHook } from './worktree-archive-hook-gate' +import { blockedWslDistroForPath } from '../../wsl/filesystem/wsl-unc-access-gate' + +/** + * Run a folder workspace's archive script before anything is torn down, as worktree removal does. + * Only the host holding the folder runs it; others own no files there. + */ +export async function gateFolderWorkspaceRemovalOnArchiveHook(args: { + repo: Repo + worktreeId: string + displayName: string + runArchive: boolean + allowFailure: boolean + runtimeTarget: () => HookRuntimeTarget | undefined +}): Promise { + const { repo } = args + if (!args.runArchive || !isRepoOnCatalogHost(repo)) { + return undefined + } + const hooks = getEffectiveHooks(repo) + if (!hooks?.scripts.archive) { + return undefined + } + const result = await runHook('archive', repo.path, repo, repo.path, args.runtimeTarget(), { + identity: { worktreeId: args.worktreeId, displayName: args.displayName }, + hooks + }) + return gateWorktreeRemovalOnArchiveHook({ + worktreePath: repo.path, + result, + allowFailure: args.allowFailure + }) +} + +/** Runner files are per launch; drop this workspace's once its processes have stopped. */ +export function removeFolderWorkspaceRunnerFiles(repo: Repo, worktreeId: string): void { + if (!isRepoOnCatalogHost(repo)) { + return + } + // A stopped distro keeps its leftover runners rather than starting for cleanup. + void blockedWslDistroForPath(repo.path) + .then((blocked) => (blocked ? undefined : removeFolderSetupRunnerFiles(repo.path, worktreeId))) + .catch((error: unknown) => { + console.warn(`[hooks] could not clean setup runners in ${repo.path}:`, error) + }) +} diff --git a/src/renderer/src/components/settings/navigation/use-settings-repo-scroll-effects.ts b/src/renderer/src/components/settings/navigation/use-settings-repo-scroll-effects.ts index ac0c11e4338..5843d2b33b0 100644 --- a/src/renderer/src/components/settings/navigation/use-settings-repo-scroll-effects.ts +++ b/src/renderer/src/components/settings/navigation/use-settings-repo-scroll-effects.ts @@ -1,7 +1,6 @@ import { resolveGeneralSubPage } from '../general/general-sub-pages' import { useEffect, useRef, useState } from 'react' import type { OrcaHooks } from '../../../../../shared/orca-yaml-hook-types' -import { isFolderRepo } from '../../../../../shared/repo-kind' import { getRepoExecutionHostId } from '../../../../../shared/execution-host' import { checkRuntimeHooks } from '@/runtime/repo-hooks/runtime-hooks-client' import { getRepoHostIdentity } from '../../../../../shared/repo-host-identity' @@ -102,18 +101,6 @@ export function useSettingsRepoScrollEffects( .filter((repo) => !retryOnly || retryOnly.has(getRepoHostIdentity(repo))) .map(async (repo) => { const repoHostIdentity = getRepoHostIdentity(repo) - if (isFolderRepo(repo)) { - setRepoHooksMap((previous) => { - if (previous[repoHostIdentity]) { - return previous - } - return { - ...previous, - [repoHostIdentity]: { hasHooks: false, hooks: null, mayNeedUpdate: false } - } - }) - return - } try { const hostId = getRepoExecutionHostId(repo) // Showing Settings is no act on the repo's WSL distro (E9). diff --git a/src/renderer/src/components/settings/repository/RepositoryPane.search.test.tsx b/src/renderer/src/components/settings/repository/RepositoryPane.search.test.tsx index 54efbcf0749..63d93760289 100644 --- a/src/renderer/src/components/settings/repository/RepositoryPane.search.test.tsx +++ b/src/renderer/src/components/settings/repository/RepositoryPane.search.test.tsx @@ -68,3 +68,53 @@ it('keeps a searched repository section editable when the query does not name th }) ) }) + +it.each([ + ['folder', 'new workspace', 'Setup script'], + ['folder', 'workspace is removed', 'Archive script'], + ['git', 'new worktree', 'Setup script'], + ['git', 'worktree is archived', 'Archive script'] +] as const)('finds editable %s hooks for %s', (kind, query, scriptLabel) => { + const repo: Repo = { + id: 'project-1', + path: '/tmp/sample-project', + displayName: 'Sample project', + badgeColor: '', + addedAt: 0, + ...(kind === 'folder' ? { kind: 'folder' as const } : {}) + } + const updateRepo = vi.fn() + useAppStore.setState({ + settings: getDefaultSettings('/tmp'), + settingsSearchQuery: query, + repos: [repo] + }) + render( + + + + ) + + const editor = screen.getByRole('textbox', { name: scriptLabel }) + fireEvent.change(editor, { target: { value: 'echo workspace-hook' } }) + fireEvent.blur(editor) + expect(updateRepo).toHaveBeenCalledWith( + 'project-1', + expect.objectContaining({ + hookSettings: expect.objectContaining({ + scripts: expect.objectContaining({ + [scriptLabel === 'Setup script' ? 'setup' : 'archive']: 'echo workspace-hook' + }) + }) + }), + expect.anything() + ) +}) diff --git a/src/renderer/src/components/settings/repository/RepositoryPane.tsx b/src/renderer/src/components/settings/repository/RepositoryPane.tsx index b37230507f2..7d2b6f25915 100644 --- a/src/renderer/src/components/settings/repository/RepositoryPane.tsx +++ b/src/renderer/src/components/settings/repository/RepositoryPane.tsx @@ -5,6 +5,7 @@ import type { Project, ProjectUpdateArgs } from '../../../../../shared/project-t import type { Repo } from '../../../../../shared/repo-types' import type { SourceControlAiSettingsPatch } from '../../../../../shared/source-control/ai/settings/source-control-ai-settings-types' import { getRepoKindLabel, isFolderRepo } from '../../../../../shared/repo-kind' +import { useFolderSetupSupport } from '@/lib/use-folder-setup-supported' import { getRepoExecutionHostId, type ExecutionHostId } from '../../../../../shared/execution-host' import { Label } from '../../ui/label' import { useShallow } from 'zustand/react/shallow' @@ -101,6 +102,7 @@ export function RepositoryPane({ }: RepositoryPaneProps): React.JSX.Element { const t = useTranslate() const isFolder = isFolderRepo(repo) + const hooksSupported = useFolderSetupSupport(repo) === 'supported' // Bind writes to the switcher-selected owner; same-ID/self-paired repos must not use focused-host fallback. const selectedHostId = getRepoExecutionHostId(repo) const updateSelectedRepo = useCallback( @@ -187,7 +189,8 @@ export function RepositoryPane({ } = getRepositoryPaneSearchMetadata(repo, { isLocalWindowsProject }, t) const hooksSection = - !isFolder && (forceFullPaneForRepoMatch || matchesSettingsSearch(searchQuery, hooksEntries)) ? ( + hooksSupported && + (forceFullPaneForRepoMatch || matchesSettingsSearch(searchQuery, hooksEntries)) ? ( void @@ -121,10 +123,15 @@ export function RepositorySetupPolicySetting({ {t('auto.components.settings.RepositoryHooksSection.793dcee97d', 'When to run')}

- {t( - 'auto.components.settings.RepositoryHooksSection.21fb607a87', - 'Default behavior when a new worktree is created.' - )} + {isFolder + ? t( + 'components.settings.RepositoryHooksSection.folderRunPolicyDescription', + 'Default behavior when a new workspace is created.' + ) + : t( + 'auto.components.settings.RepositoryHooksSection.21fb607a87', + 'Default behavior when a new worktree is created.' + )}

@@ -172,10 +179,7 @@ export function RepositoryHooksSection({ ) : null} - - - + {isFolder ? null : ( + + )} ) } + +/** The issue command needs a GitHub repo, so only Git projects mount its file inspection. */ +function RepositoryIssueCommandRow({ + repo, + repoHostIdentity, + forceVisible +}: { + repo: Repo + repoHostIdentity: string + forceVisible: boolean +}): React.JSX.Element { + const t = useTranslate() + const issueCommand = useRepositoryIssueCommand({ + repoId: repo.id, + repoHostIdentity, + selectedHostId: getRepoExecutionHostId(repo) + }) + return ( + + + + ) +} diff --git a/src/renderer/src/components/settings/repository/hooks/repository-git-hooks-search-entries.ts b/src/renderer/src/components/settings/repository/hooks/repository-git-hooks-search-entries.ts index 3ac5817edaf..5a4fc12d4df 100644 --- a/src/renderer/src/components/settings/repository/hooks/repository-git-hooks-search-entries.ts +++ b/src/renderer/src/components/settings/repository/hooks/repository-git-hooks-search-entries.ts @@ -1,9 +1,37 @@ import type { Repo } from '../../../../../../shared/repo-types' +import { isFolderRepo } from '../../../../../../shared/repo-kind' import type { SettingsSearchEntry } from '../../search/settings-search' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { searchKeywordTranslator } from '../../search/settings-search-keywords' +export function getRepositoryHookScriptDescription( + repo: Repo, + hook: 'setup' | 'archive', + t: Translate +): string { + if (hook === 'setup') { + return isFolderRepo(repo) + ? t( + 'components.settings.RepositoryHooksSection.folderSetupDescription', + 'Local and shared scripts that run after a new workspace is created.' + ) + : t( + 'auto.components.settings.RepositoryHooksSection.30d555acd2', + 'Local and shared scripts that run after a new worktree is created.' + ) + } + return isFolderRepo(repo) + ? t( + 'components.settings.RepositoryHooksSection.folderArchiveDescription', + 'Local and shared scripts that run before a workspace is removed.' + ) + : t( + 'auto.components.settings.RepositoryHooksSection.b91a0f297d', + 'Local and shared scripts that run before a worktree is archived.' + ) +} + export function getRepositoryGitHooksSearchEntries( repo: Repo, t: Translate = translate @@ -12,10 +40,7 @@ export function getRepositoryGitHooksSearchEntries( return [ { title: t('auto.components.settings.repository.search.810b9f4106', 'Setup script'), - description: t( - 'auto.components.settings.repository.search.baaf70bb37', - 'Local and shared scripts that run after a new worktree is created.' - ), + description: getRepositoryHookScriptDescription(repo, 'setup', t), keywords: [ repo.displayName, ...translateSearchKeyword('auto.components.settings.repository.search.8655e3387b', 'hooks'), @@ -41,10 +66,7 @@ export function getRepositoryGitHooksSearchEntries( }, { title: t('auto.components.settings.repository.search.1617bc353d', 'Archive script'), - description: t( - 'auto.components.settings.repository.search.acd1157f0c', - 'Local and shared scripts that run before a worktree is archived.' - ), + description: getRepositoryHookScriptDescription(repo, 'archive', t), keywords: [ repo.displayName, ...translateSearchKeyword('auto.components.settings.repository.search.8655e3387b', 'hooks'), @@ -134,42 +156,46 @@ export function getRepositoryGitHooksSearchEntries( ) ] }, - { - title: t( - 'auto.components.settings.repository.search.aced2fc1be', - 'Custom GitHub issue command' - ), - description: t( - 'auto.components.settings.repository.search.d42d1e49c0', - 'File-based linked-issue command configured via orca.yaml and optional local override.' - ), - keywords: [ - repo.displayName, - ...translateSearchKeyword( - 'auto.components.settings.repository.search.2011a6a4f2', - 'github issue command' - ), - ...translateSearchKeyword( - 'auto.components.settings.repository.search.66b584bd6c', - 'issue command' - ), - ...translateSearchKeyword( - 'auto.components.settings.repository.search.ec70364df2', - 'workflow' - ), - ...translateSearchKeyword( - 'auto.components.settings.repository.search.9dc60d7f6d', - 'github' - ), - ...translateSearchKeyword( - 'auto.components.settings.repository.search.603c68b68c', - 'orca.yaml' - ), - ...translateSearchKeyword( - 'auto.components.settings.repository.search.bc7e504b8e', - '.orca/issue-command' - ) - ] - } + ...(isFolderRepo(repo) + ? [] + : [ + { + title: t( + 'auto.components.settings.repository.search.aced2fc1be', + 'Custom GitHub issue command' + ), + description: t( + 'auto.components.settings.repository.search.d42d1e49c0', + 'File-based linked-issue command configured via orca.yaml and optional local override.' + ), + keywords: [ + repo.displayName, + ...translateSearchKeyword( + 'auto.components.settings.repository.search.2011a6a4f2', + 'github issue command' + ), + ...translateSearchKeyword( + 'auto.components.settings.repository.search.66b584bd6c', + 'issue command' + ), + ...translateSearchKeyword( + 'auto.components.settings.repository.search.ec70364df2', + 'workflow' + ), + ...translateSearchKeyword( + 'auto.components.settings.repository.search.9dc60d7f6d', + 'github' + ), + ...translateSearchKeyword( + 'auto.components.settings.repository.search.603c68b68c', + 'orca.yaml' + ), + ...translateSearchKeyword( + 'auto.components.settings.repository.search.bc7e504b8e', + '.orca/issue-command' + ) + ] + } + ]) ] } diff --git a/src/renderer/src/components/settings/repository/hooks/repository-hook-settings-draft.ts b/src/renderer/src/components/settings/repository/hooks/repository-hook-settings-draft.ts index fc4b58d2c50..41533879de1 100644 --- a/src/renderer/src/components/settings/repository/hooks/repository-hook-settings-draft.ts +++ b/src/renderer/src/components/settings/repository/hooks/repository-hook-settings-draft.ts @@ -20,16 +20,22 @@ export type HookSettingsPolicyDraft = Partial< > export function getLocalHookFields( - t: Translate = translate + t: Translate = translate, + isFolder = false ): readonly [LocalHookField, LocalHookField] { return [ { name: 'setup', label: t('auto.components.settings.RepositoryHooksSection.1ecf0b115a', 'Setup script'), - description: t( - 'auto.components.settings.RepositoryHooksSection.f0710e1c83', - 'Runs after a new worktree is created; install deps, copy env files, run migrations.' - ), + description: isFolder + ? t( + 'components.settings.RepositoryHooksSection.folderSetupFieldDescription', + 'Runs after a new workspace is created; create child worktrees, install deps, copy env files.' + ) + : t( + 'auto.components.settings.RepositoryHooksSection.f0710e1c83', + 'Runs after a new worktree is created; install deps, copy env files, run migrations.' + ), placeholder: t( 'auto.components.settings.RepositoryHooksSection.a3fc966677', '# e.g. pnpm install cp "$ORCA_ROOT_PATH/.env" "$ORCA_WORKTREE_PATH/.env"' @@ -38,10 +44,15 @@ export function getLocalHookFields( { name: 'archive', label: t('auto.components.settings.RepositoryHooksSection.bfdb1266ce', 'Archive script'), - description: t( - 'auto.components.settings.RepositoryHooksSection.6f90ebe3fd', - 'Runs before a worktree is archived or removed.' - ), + description: isFolder + ? t( + 'components.settings.RepositoryHooksSection.folderArchiveFieldDescription', + 'Runs before a workspace is removed.' + ) + : t( + 'auto.components.settings.RepositoryHooksSection.6f90ebe3fd', + 'Runs before a worktree is archived or removed.' + ), placeholder: t( 'auto.components.settings.RepositoryHooksSection.9b821fa19d', '# e.g. echo "Cleaning up $ORCA_WORKSPACE_NAME"' diff --git a/src/renderer/src/components/settings/repository/repository-search.ts b/src/renderer/src/components/settings/repository/repository-search.ts index e3356ab4ec7..c31669a4c16 100644 --- a/src/renderer/src/components/settings/repository/repository-search.ts +++ b/src/renderer/src/components/settings/repository/repository-search.ts @@ -229,7 +229,7 @@ function getRepositorySearchParts( removeProject, sourceControlAi: isFolder ? undefined : getRepositoryGitAuthorSearchEntries(repo, t), mcp: isFolder ? undefined : getRepositoryMcpConfigSearchEntries(repo, t), - hooks: isFolder ? undefined : getRepositoryGitHooksSearchEntries(repo, t) + hooks: getRepositoryGitHooksSearchEntries(repo, t) } } diff --git a/src/renderer/src/hooks/composer-state/composer-external-sync.ts b/src/renderer/src/hooks/composer-state/composer-external-sync.ts index 8ab3bd9aa86..38e8c36f867 100644 --- a/src/renderer/src/hooks/composer-state/composer-external-sync.ts +++ b/src/renderer/src/hooks/composer-state/composer-external-sync.ts @@ -24,7 +24,6 @@ export function useComposerExternalSync(target: ComposerTargetState): ComposerEx selectedRepoConnectionIdRef: target.asyncComposerState.selectedRepoConnectionIdRef, selectedRepoExecutionHostId: target.runtimeTargetSelection.selectedRepoExecutionHostId, selectedRepoHookContextKey: target.runtimeTargetSelection.selectedRepoHookContextKey, - selectedRepoIsGit: target.runtimeTargetSelection.selectedRepoIsGit, selectedRepoSshStatus: target.runtimeTargetSelection.selectedRepoSshStatus, setTuiAgent: target.workspaceIdentityState.setTuiAgent, settings: target.composerTargetStore.settings, diff --git a/src/renderer/src/hooks/composer-state/composer-submit-orchestration.ts b/src/renderer/src/hooks/composer-state/composer-submit-orchestration.ts index e7405c10b49..0d0b627774c 100644 --- a/src/renderer/src/hooks/composer-state/composer-submit-orchestration.ts +++ b/src/renderer/src/hooks/composer-state/composer-submit-orchestration.ts @@ -87,6 +87,7 @@ export function useComposerSubmitOrchestration( revealSetupChoice: target.asyncComposerState.revealSetupChoice, settings: target.composerTargetStore.settings, setupConfig: target.derivedComposerState.setupConfig, + setupSupport: target.derivedComposerState.setupSupport, setupDecision: target.asyncComposerState.setupDecision, setupPolicy: target.derivedComposerState.setupPolicy, smartNameMode: target.workspaceIdentityState.smartNameMode diff --git a/src/renderer/src/hooks/composer-state/derived-composer-state.ts b/src/renderer/src/hooks/composer-state/derived-composer-state.ts index de1454cacca..e527ee04afd 100644 --- a/src/renderer/src/hooks/composer-state/derived-composer-state.ts +++ b/src/renderer/src/hooks/composer-state/derived-composer-state.ts @@ -1,3 +1,4 @@ +import { useFolderSetupSupport } from '@/lib/use-folder-setup-supported' import type { DerivedComposerStateInput } from './composer-target-input-contracts' import { useMemo } from 'react' @@ -122,14 +123,18 @@ export function useDerivedComposerState(input: DerivedComposerStateInput) { const currentYamlHooks = checkedHooksContextKey === selectedRepoHookContextKey ? yamlHooks : null + const setupSupport = useFolderSetupSupport(selectedRepo) + const setupSupported = setupSupport === 'supported' const setupConfig = useMemo( - () => (selectedRepoIsGit ? getSetupConfig(selectedRepo, currentYamlHooks) : null), - [currentYamlHooks, selectedRepo, selectedRepoIsGit] + () => (selectedRepo && setupSupported ? getSetupConfig(selectedRepo, currentYamlHooks) : null), + [currentYamlHooks, selectedRepo, setupSupported] ) const isSetupCheckPending = - selectedRepoIsGit && - Boolean(selectedRepoHookContextKey) && - checkedHooksContextKey !== selectedRepoHookContextKey + setupSupport === 'pending' || + (setupSupported && + Boolean(selectedRepo) && + Boolean(selectedRepoHookContextKey) && + checkedHooksContextKey !== selectedRepoHookContextKey) const { setupPolicy, requiresExplicitSetupChoice, @@ -139,7 +144,7 @@ export function useDerivedComposerState(input: DerivedComposerStateInput) { selectedRepo, setupConfig, setupDecision, - selectedRepoIsGit, + setupSupport !== 'unsupported', isSetupCheckPending ) const linkedWorkItemProvider = linkedWorkItem ? getWorkspaceSourceProvider(linkedWorkItem) : null @@ -242,6 +247,7 @@ export function useDerivedComposerState(input: DerivedComposerStateInput) { effectiveLinkedPR, currentYamlHooks, setupConfig, + setupSupport, setupPolicy, linkedWorkItemProvider, requiresExplicitSetupChoice, diff --git a/src/renderer/src/hooks/composer-state/derived-model.ts b/src/renderer/src/hooks/composer-state/derived-model.ts index 1c4270b3568..f223d746d05 100644 --- a/src/renderer/src/hooks/composer-state/derived-model.ts +++ b/src/renderer/src/hooks/composer-state/derived-model.ts @@ -1,3 +1,4 @@ +import type { FolderSetupSupport } from '@/lib/use-folder-setup-supported' import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' import type { OrcaHooks, SetupRunPolicy } from '../../../../shared/orca-yaml-hook-types' import type { SparsePreset } from '../../../../shared/worktree/create-types' @@ -15,6 +16,8 @@ export type ComposerDerivedModel = { effectiveLinkedPR: number | null currentYamlHooks: OrcaHooks | null setupConfig: SetupConfig | null + /** False for a folder project whose host predates folder setup; its setup controls stay hidden. */ + setupSupport: FolderSetupSupport setupPolicy: SetupRunPolicy linkedWorkItemProvider: 'github' | 'gitlab' | 'linear' | 'jira' | null requiresExplicitSetupChoice: boolean diff --git a/src/renderer/src/hooks/composer-state/host-runtime-effects.ts b/src/renderer/src/hooks/composer-state/host-runtime-effects.ts index 725d9e02ede..960c57adc35 100644 --- a/src/renderer/src/hooks/composer-state/host-runtime-effects.ts +++ b/src/renderer/src/hooks/composer-state/host-runtime-effects.ts @@ -19,7 +19,6 @@ type HostRuntimeEffectsInput = Pick< | 'selectedRepoConnectionIdRef' | 'selectedRepoExecutionHostId' | 'selectedRepoHookContextKey' - | 'selectedRepoIsGit' | 'selectedRepoSshStatus' | 'setTuiAgent' | 'settings' @@ -67,7 +66,6 @@ export function useHostRuntimeEffects(input: HostRuntimeEffectsInput) { selectedRepoConnectionIdRef, selectedRepoExecutionHostId, selectedRepoHookContextKey, - selectedRepoIsGit, selectedRepoSshStatus, setTuiAgent, settings, @@ -115,7 +113,8 @@ export function useHostRuntimeEffects(input: HostRuntimeEffectsInput) { ]) useEffect(() => { - if (!repoId || !selectedRepoIsGit || !selectedRepoHookContextKey) { + // Folder projects have setup scripts too; hosts without folder setup report none for them. + if (!repoId || !selectedRepoHookContextKey) { return } @@ -140,7 +139,6 @@ export function useHostRuntimeEffects(input: HostRuntimeEffectsInput) { loadHookCheckForRepo, repoId, selectedRepoHookContextKey, - selectedRepoIsGit, runtimeEnvironmentId ]) diff --git a/src/renderer/src/hooks/composer-state/quick-submit-input-contract.ts b/src/renderer/src/hooks/composer-state/quick-submit-input-contract.ts index 9c32fa93329..da3cb80dd99 100644 --- a/src/renderer/src/hooks/composer-state/quick-submit-input-contract.ts +++ b/src/renderer/src/hooks/composer-state/quick-submit-input-contract.ts @@ -22,6 +22,7 @@ export type QuickSubmitPreparationInput = Pick< | 'revealSetupChoice' | 'settings' | 'setupConfig' + | 'setupSupport' | 'setupDecision' | 'setupPolicy' | 'smartNameMode' diff --git a/src/renderer/src/hooks/composer-state/quick-submit-preparation.ts b/src/renderer/src/hooks/composer-state/quick-submit-preparation.ts index c9aaaf2b635..be2cf931346 100644 --- a/src/renderer/src/hooks/composer-state/quick-submit-preparation.ts +++ b/src/renderer/src/hooks/composer-state/quick-submit-preparation.ts @@ -13,6 +13,8 @@ import { import type { SetupDecision } from '../../../../shared/worktree/create-types' import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation' import { resolveComposerBranchNameOverrideForCreate } from '../composer-branch-selection' +import { resolveFolderSetupSupported } from '@/lib/use-folder-setup-supported' +import { translate } from '@/i18n/i18n' import { resolveWorktreeCreateBaseBranch } from '@/runtime/source-control/worktree-creation/worktree-create-base' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import type { PendingSmartGitHubSubmitResolution } from './source-selection-decisions' @@ -39,6 +41,7 @@ export function useQuickSubmitPreparation(input: QuickSubmitPreparationInput) { revealSetupChoice, settings, setupConfig, + setupSupport, setupDecision, setupPolicy, smartNameMode @@ -74,11 +77,31 @@ export function useQuickSubmitPreparation(input: QuickSubmitPreparationInput) { let submitResolvedSetupDecision = resolvedSetupDecision + // Create re-asks the host so a pending or stale answer can't drop an ask-policy prompt. + const supportSettlement = await settleComposerSubmit( + resolveFolderSetupSupported(selectedRepo).catch(() => { + throw new Error( + translate( + 'auto.hooks.useComposerState.folderSetupSupportCheckFailed', + "Couldn't confirm whether this host runs folder setup scripts. Try again." + ) + ) + }), + isSubmissionCancelled + ) + if (supportSettlement.status === 'cancelled') { + return null + } + const submitSetupSupported = supportSettlement.value + if (!submitSetupSupported) { + submitSetupConfig = null + } + if ( - selectedRepoIsGit && - setupPolicy === 'ask' && + submitSetupSupported && + (setupSupport !== 'supported' || setupPolicy === 'ask') && selectedRepoHookContextKey && - checkedHooksContextKey !== selectedRepoHookContextKey + (setupSupport !== 'supported' || checkedHooksContextKey !== selectedRepoHookContextKey) ) { const outcome = await readWorkspaceSetupInspection( () => loadHookCheckForRepo(repoId), @@ -97,34 +120,33 @@ export function useQuickSubmitPreparation(input: QuickSubmitPreparationInput) { submitResolvedSetupDecision = submitSetup.resolvedSetupDecision } - if (selectedRepoIsGit && submitSetupConfig && setupPolicy === 'ask' && !setupDecision) { + if (submitSetupConfig && setupPolicy === 'ask' && !setupDecision) { revealSetupChoice() return null } - const effectiveSetupDecision: SetupDecision = selectedRepoIsGit - ? (submitResolvedSetupDecision ?? 'inherit') - : 'skip' + // Hosts that predate folder setup ignore the decision for folders. + const effectiveSetupDecision: SetupDecision = submitResolvedSetupDecision ?? 'inherit' const submitLinkedWorkItemProvider = submitLinkedWorkItem ? getWorkspaceSourceProvider(submitLinkedWorkItem) : null - const hookPreparation: WorktreeCreationRequest['hookPreparation'] = selectedRepoIsGit - ? { - executionHostId: selectedRepoExecutionHostId ?? undefined, - issueCommand: - enableIssueAutomation && - submitLinkedIssueNumber !== null && - canUseIssueCommandForLinkedItemProvider(submitLinkedWorkItemProvider) && - selectedRepoExecutionHostId && - selectedRepoHookContextKey - ? { - provider: submitLinkedWorkItemProvider, - issueNumber: submitLinkedIssueNumber, - artifactUrl: submitLinkedWorkItem?.url ?? null - } - : undefined - } - : undefined + // Setup trust applies to folder projects too; the issue command needs a Git repo. + const hookPreparation: WorktreeCreationRequest['hookPreparation'] = { + executionHostId: selectedRepoExecutionHostId ?? undefined, + issueCommand: + selectedRepoIsGit && + enableIssueAutomation && + submitLinkedIssueNumber !== null && + canUseIssueCommandForLinkedItemProvider(submitLinkedWorkItemProvider) && + selectedRepoExecutionHostId && + selectedRepoHookContextKey + ? { + provider: submitLinkedWorkItemProvider, + issueNumber: submitLinkedIssueNumber, + artifactUrl: submitLinkedWorkItem?.url ?? null + } + : undefined + } const linkedLinearIssue = submitLinkedWorkItem && submitLinkedWorkItemProvider === 'linear' @@ -219,6 +241,7 @@ export function useQuickSubmitPreparation(input: QuickSubmitPreparationInput) { revealSetupChoice, settings, setupConfig, + setupSupport, setupDecision, setupPolicy, smartNameMode, diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 0f83c6e7b9e..c1ff4d55106 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -10733,11 +10733,9 @@ "fbfd2386e8": "Archivierungsskript", "4c17787d7b": "Archivieren", "8655e3387b": "Hooks", - "acd1157f0c": "Lokale und gemeinsame Skripte, die vor dem Archivieren eines Worktrees ausgeführt werden.", "491b05d6e6": "Einrichtungsbefehl", "a31b43a7f8": "Einrichtungsskript", "5590388dfa": "Einrichtung", - "baaf70bb37": "Lokale und gemeinsame Skripte, die nach dem Erstellen eines neuen Worktrees ausgeführt werden.", "d73fb47b45": ".claude/mcp.json", "db11b337c4": ".claude.json", "26f42fe773": ".cursor/mcp.json", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 25d5e6475c1..6f55aa8537b 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -2266,7 +2266,8 @@ "setupAgentStartupPolicySaveFailed": "Failed to save setup startup behavior.", "5f3d2c8a1b": "Failed to resolve MR base.", "dropPartiallyAttached_one": "{{failureCount}} of {{count}} item could not be attached.", - "dropPartiallyAttached_other": "{{failureCount}} of {{count}} items could not be attached." + "dropPartiallyAttached_other": "{{failureCount}} of {{count}} items could not be attached.", + "folderSetupSupportCheckFailed": "Couldn't confirm whether this host runs folder setup scripts. Try again." }, "useGlobalFileDrop": { "38c9f034ff": "Failed to upload dropped files.", @@ -11188,11 +11189,9 @@ "fbfd2386e8": "archive script", "4c17787d7b": "archive", "8655e3387b": "hooks", - "acd1157f0c": "Local and shared scripts that run before a worktree is archived.", "491b05d6e6": "setup command", "a31b43a7f8": "setup script", "5590388dfa": "setup", - "baaf70bb37": "Local and shared scripts that run after a new worktree is created.", "d73fb47b45": ".claude/mcp.json", "db11b337c4": ".claude.json", "26f42fe773": ".cursor/mcp.json", @@ -21610,6 +21609,15 @@ }, "repositoryHooks": { "availableEnvVars": "Available environment variables" + }, + "RepositoryHooksSection": { + "folderRunPolicyDescription": "Default behavior when a new workspace is created.", + "folderTitle": "Workspace hooks", + "folderDescription": "Scripts that run in this folder when a workspace is created or removed. Every workspace shares the folder. Local scripts are stored on this machine; `orca.yaml` scripts are shared with your team.", + "folderSetupDescription": "Local and shared scripts that run after a new workspace is created.", + "folderArchiveDescription": "Local and shared scripts that run before a workspace is removed.", + "folderSetupFieldDescription": "Runs after a new workspace is created; create child worktrees, install deps, copy env files.", + "folderArchiveFieldDescription": "Runs before a workspace is removed." } }, "agentChildRow": { diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 5cf956905e3..ccf9c77f2ad 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -10312,11 +10312,9 @@ "fbfd2386e8": "script de archivado", "4c17787d7b": "archivar", "8655e3387b": "hooks", - "acd1157f0c": "Scripts locales y compartidos que se ejecutan antes de archivar un worktree.", "491b05d6e6": "comando de configuración", "a31b43a7f8": "script de configuración", "5590388dfa": "configuración", - "baaf70bb37": "Scripts locales y compartidos que se ejecutan después de crear un nuevo worktree.", "d73fb47b45": ".claude/mcp.json", "db11b337c4": ".claude.json", "26f42fe773": ".cursor/mcp.json", diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index a4ca29930f0..11bcd049e30 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -10601,11 +10601,9 @@ "fbfd2386e8": "script d'archive", "4c17787d7b": "archiver", "8655e3387b": "hooks", - "acd1157f0c": "Scripts locaux et partagés exécutés avant l'archivage d'un worktree.", "491b05d6e6": "commande de setup", "a31b43a7f8": "script de setup", "5590388dfa": "configuration", - "baaf70bb37": "Scripts locaux et partagés exécutés après la création d'un nouveau worktree.", "d73fb47b45": ".claude/mcp.json", "db11b337c4": ".claude.json", "26f42fe773": ".cursor/mcp.json", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 50f5d2ff9f3..6d0e225625c 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -10071,11 +10071,9 @@ "fbfd2386e8": "アーカイブスクリプト", "4c17787d7b": "アーカイブ", "8655e3387b": "フック", - "acd1157f0c": "ワークツリーがアーカイブされる前に実行されるローカルおよび共有スクリプト。", "491b05d6e6": "セットアップコマンド", "a31b43a7f8": "セットアップスクリプト", "5590388dfa": "セットアップ", - "baaf70bb37": "新規ワークツリーの作成後に実行されるローカルおよび共有スクリプト。", "d73fb47b45": ".claude/mcp.json", "db11b337c4": ".claude.json", "26f42fe773": ".cursor/mcp.json", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index ba9d0af0d23..1bc9f6dea18 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -10034,11 +10034,9 @@ "fbfd2386e8": "아카이브 스크립트", "4c17787d7b": "보관소", "8655e3387b": "훅", - "acd1157f0c": "작업 트리가 보관되기 전에 실행되는 로컬 및 공유 스크립트입니다.", "491b05d6e6": "설정 명령", "a31b43a7f8": "설정 스크립트", "5590388dfa": "설정", - "baaf70bb37": "새 작업 트리가 생성된 후 실행되는 로컬 및 공유 스크립트입니다.", "d73fb47b45": ".claude/mcp.json", "db11b337c4": ".claude.json", "26f42fe773": ".cursor/mcp.json", diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 81a0ed531de..d6a9f26f7dc 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -4423,11 +4423,9 @@ "fbfd2386e8": "script de arquivamento", "4c17787d7b": "arquivar", "8655e3387b": "hooks", - "acd1157f0c": "Scripts locais e compartilhados executados antes de uma worktree ser arquivada.", "491b05d6e6": "comando de configuração", "a31b43a7f8": "script de configuração", "5590388dfa": "configuração", - "baaf70bb37": "Scripts locais e compartilhados executados após a criação de uma nova worktree.", "d73fb47b45": ".claude/mcp.json", "db11b337c4": ".claude.json", "26f42fe773": ".cursor/mcp.json", diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index f02636341bf..263afc7c280 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -11085,11 +11085,9 @@ "fbfd2386e8": "скрипт архивации", "4c17787d7b": "архивировать", "8655e3387b": "хуки", - "acd1157f0c": "Локальные и общие скрипты перед архивацией рабочего дерева.", "491b05d6e6": "команда настройки", "a31b43a7f8": "скрипт настройки", "5590388dfa": "настройка", - "baaf70bb37": "Локальные и общие скрипты после создания рабочего дерева.", "d73fb47b45": ".claude/mcp.json", "db11b337c4": ".claude.json", "26f42fe773": ".cursor/mcp.json", diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index e0eeafa1fe6..71c4f37cc42 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -10717,11 +10717,9 @@ "fbfd2386e8": "arşiv betiği", "4c17787d7b": "arşiv", "8655e3387b": "hook'lar", - "acd1157f0c": "Bir worktree arşivlenmeden önce çalışan yerel ve paylaşılan betikler.", "491b05d6e6": "kurulum komutu", "a31b43a7f8": "kurulum betiği", "5590388dfa": "kurulum", - "baaf70bb37": "Yeni bir worktree oluşturulduktan sonra çalışan yerel ve paylaşılan betikler.", "d73fb47b45": ".claude/mcp.json", "db11b337c4": ".claude.json", "26f42fe773": ".cursor/mcp.json", diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 12749b0ded7..68e7f0ba2ae 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -10554,11 +10554,9 @@ "fbfd2386e8": "封存指令碼", "4c17787d7b": "封存", "8655e3387b": "鉤子", - "acd1157f0c": "在封存工作樹之前執行的本機和共用指令碼。", "491b05d6e6": "設定命令", "a31b43a7f8": "設定指令碼", "5590388dfa": "設定", - "baaf70bb37": "建立新工作樹後執行的本機和共用指令碼。", "d73fb47b45": ".claude/mcp.json", "db11b337c4": ".claude.json", "26f42fe773": ".cursor/mcp.json", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index b3f2f5f5a54..a2a9b61bbe6 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -10034,11 +10034,9 @@ "fbfd2386e8": "存档脚本", "4c17787d7b": "档案", "8655e3387b": "钩子", - "acd1157f0c": "在归档工作树之前运行的本地和共享脚本。", "491b05d6e6": "设置命令", "a31b43a7f8": "设置脚本", "5590388dfa": "设置", - "baaf70bb37": "创建新工作树后运行的本地和共享脚本。", "d73fb47b45": ".claude/mcp.json", "db11b337c4": ".claude.json", "26f42fe773": ".cursor/mcp.json", diff --git a/src/renderer/src/lib/use-folder-setup-supported.test.tsx b/src/renderer/src/lib/use-folder-setup-supported.test.tsx new file mode 100644 index 00000000000..00cabb6f55d --- /dev/null +++ b/src/renderer/src/lib/use-folder-setup-supported.test.tsx @@ -0,0 +1,255 @@ +// @vitest-environment happy-dom + +import { act, cleanup, renderHook } from '@testing-library/react' +import { useState } from 'react' +import { afterEach, expect, it, vi } from 'vitest' +import type { Repo } from '../../../shared/repo-types' +import { useDerivedComposerState } from '@/hooks/composer-state/derived-composer-state' +import { useLinkedItemLookupEffects } from '@/hooks/composer-state/linked-item-lookup-effects' +import { useQuickSubmitPreparation } from '@/hooks/composer-state/quick-submit-preparation' +import { resolveFolderSetupSupported, useFolderSetupSupport } from './use-folder-setup-supported' + +const { supportsCapability } = vi.hoisted(() => ({ supportsCapability: vi.fn() })) +vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', () => ({ + runtimeEnvironmentSupportsCapability: supportsCapability +})) +vi.mock('@/hooks/useRetiredWorktreeNames', () => { + const retiredNames = { names: [], exhaustedTiers: 0 } + return { useRetiredWorktreeNames: () => retiredNames } +}) + +afterEach(() => { + cleanup() + vi.resetAllMocks() +}) + +function folderRepo(id: string): Repo { + return { + id, + path: `/folders/${id}`, + displayName: id, + badgeColor: 'blue', + addedAt: 0, + kind: 'folder', + executionHostId: `runtime:${id}` + } +} + +function deferred() { + let resolve!: (supported: boolean) => void + let reject!: (error: Error) => void + const promise = new Promise((resolvePromise, rejectPromise) => { + resolve = resolvePromise + reject = rejectPromise + }) + return { promise, resolve, reject } +} + +const noop = () => {} +const hooks = { scripts: { setup: 'echo setup' } } +const emptyWorktrees = {} +const branchAutoNameRef = { current: '' } + +function useSetupComposer(repo: Repo) { + const [setupDecision, setSetupDecision] = useState<'run' | 'skip' | null>(null) + const derived = useDerivedComposerState({ + agentPrompt: '', + checkedHooksContextKey: repo.id, + enableIssueAutomation: false, + hasLoadedIssueCommand: false, + issueCommandTemplate: '', + linkDebouncedQuery: '', + linkDirectItem: null, + linkItems: [], + linkedIssue: '', + linkedPR: null, + linkedWorkItem: null, + name: 'chosen', + repoId: repo.id, + selectedRepo: repo, + selectedRepoHookContextKey: repo.id, + selectedRepoIsGit: false, + selectedRepoSlug: null, + setupDecision, + sparseDirectories: '', + sparseEnabled: false, + sparsePresetsByRepo: {}, + sparseSelectedPresetId: null, + worktreesByRepo: emptyWorktrees, + yamlHooks: hooks + }) + useLinkedItemLookupEffects({ + baseBranch: '', + linkPopoverOpen: false, + linkQuery: '', + normalizedLinkQuery: derived.normalizedLinkQuery, + prefetchWorkItems: async () => {}, + prefetchWorktreeCreateBase: async () => {}, + repoId: repo.id, + selectedRepo: repo, + selectedRepoConnectionId: null, + selectedRepoGitHubSourceContext: null, + selectedRepoIsGit: false, + selectedRepoSshStatus: null, + setLinkDebouncedQuery: noop, + setLinkDirectItem: noop, + setLinkDirectLoading: noop, + setLinkItems: noop, + setLinkItemsLoading: noop, + setSetupDecision, + setupConfig: derived.setupConfig, + setupPolicy: derived.setupPolicy, + shouldWaitForSetupCheck: derived.shouldWaitForSetupCheck, + sshConnectedGeneration: 0 + }) + const { prepareQuickSubmit } = useQuickSubmitPreparation({ + branchAutoNameRef, + branchIntent: 'create-new', + branchNameOverridePreservesNameEdits: false, + checkedHooksContextKey: repo.id, + commitHookCheckIfCurrent: () => true, + enableIssueAutomation: false, + isSubmissionCancelled: () => false, + loadHookCheckForRepo: async () => ({ hasHooks: true, hooks, mayNeedUpdate: false }), + name: 'chosen', + note: '', + prepareQuickSubmitSource: () => ({ + submitLinkedWorkItem: null, + agent: null, + submitLinkedIssueNumber: null, + submitLinkedPR: null, + submitTitleName: null, + nameIsAutoManaged: false, + smartGitHubCreateNames: { workspaceName: 'chosen', displayName: undefined }, + workspaceName: 'chosen', + nameWasGenerated: false, + smartSubmitBaseBranch: undefined, + submitCompareBaseRef: undefined, + submitPushTarget: undefined, + submitBranchNameOverride: undefined + }), + repoId: repo.id, + resolvedSetupDecision: derived.resolvedSetupDecision, + selectedRepo: repo, + selectedRepoExecutionHostId: `runtime:${repo.id}`, + selectedRepoHookContextKey: repo.id, + selectedRepoIsGit: false, + revealSetupChoice: noop, + settings: null, + setupConfig: derived.setupConfig, + setupSupport: derived.setupSupport, + setupDecision, + setupPolicy: derived.setupPolicy, + smartNameMode: 'text' + }) + return { support: derived.setupSupport, setupDecision, setSetupDecision, prepareQuickSubmit } +} + +it('preserves Skip across detached host replies and retires observations with their last reader', async () => { + const requests = new Map[]>() + supportsCapability.mockImplementation((id: string) => { + const request = deferred() + const history = requests.get(id) ?? [] + history.push(request) + requests.set(id, history) + return request.promise + }) + function latest(id: string) { + const request = requests.get(id)?.at(-1) + if (!request) { + throw new Error(`No capability request for ${id}`) + } + return request + } + + const abandoned = Array.from({ length: 32 }, (_, index) => { + const repo = folderRepo(`abandoned-${index}`) + const consumer = renderHook(() => useFolderSetupSupport(repo)) + consumer.unmount() + return latest(repo.id) + }) + const repo = folderRepo('active') + const composer = renderHook(() => useSetupComposer(repo)) + const peer = renderHook(() => useFolderSetupSupport(repo)) + await act(async () => latest(repo.id).resolve(true)) + expect(peer.result.current).toBe('supported') + peer.unmount() + act(() => composer.result.current.setSetupDecision('skip')) + for (const request of abandoned) { + await act(async () => request.resolve(true)) + } + expect(composer.result.current.support).toBe('supported') + expect(composer.result.current.setupDecision).toBe('skip') + expect(requests.get(repo.id)).toHaveLength(1) + + await act(async () => { + const submission = composer.result.current.prepareQuickSubmit({ kind: 'none' }, null, 'chosen') + latest(repo.id).resolve(true) + expect((await submission)?.effectiveSetupDecision).toBe('skip') + }) + + let activeRenders = 0 + const survivor = renderHook(() => { + activeRenders += 1 + return useFolderSetupSupport(repo) + }) + await act(async () => latest(repo.id).resolve(true)) + composer.unmount() + const settledRenders = activeRenders + for (const population of [200, 2000]) { + for (let index = 0; index < population; index += 1) { + const other = folderRepo(`churn-${population}-${index}`) + const consumer = renderHook(() => useFolderSetupSupport(other)) + consumer.unmount() + await act(async () => latest(other.id).resolve(true)) + } + expect(survivor.result.current).toBe('supported') + expect(activeRenders - settledRenders).toBe(0) + } + + await act(async () => { + const refresh = resolveFolderSetupSupported(repo) + latest(repo.id).reject(new Error('offline')) + await expect(refresh).rejects.toThrow('offline') + }) + expect(survivor.result.current).toBe('supported') + await act(async () => { + const refresh = resolveFolderSetupSupported(repo) + latest(repo.id).resolve(false) + await refresh + }) + expect(survivor.result.current).toBe('unsupported') + + const retired = resolveFolderSetupSupported(repo) + const retiredRequest = latest(repo.id) + survivor.unmount() + const successor = renderHook(() => useFolderSetupSupport(repo)) + expect(successor.result.current).toBe('pending') + await act(async () => { + retiredRequest.resolve(true) + await retired + }) + expect(successor.result.current).toBe('pending') + await act(async () => latest(repo.id).reject(new Error('offline'))) + expect(successor.result.current).toBe('pending') + await act(async () => { + const retry = resolveFolderSetupSupported(repo) + latest(repo.id).resolve(true) + await retry + }) + expect(successor.result.current).toBe('supported') + successor.unmount() + supportsCapability.mockClear() + const nextVisit = renderHook(() => useFolderSetupSupport(repo)) + const nextPeer = renderHook(() => useFolderSetupSupport(repo)) + const visitRequest = latest(repo.id) + const joined = resolveFolderSetupSupported(repo) + expect(supportsCapability).toHaveBeenCalledTimes(1) + expect(nextVisit.result.current).toBe('pending') + await act(async () => { + visitRequest.resolve(false) + await joined + }) + expect(nextVisit.result.current).toBe('unsupported') + expect(nextPeer.result.current).toBe('unsupported') +}) diff --git a/src/renderer/src/lib/use-folder-setup-supported.ts b/src/renderer/src/lib/use-folder-setup-supported.ts new file mode 100644 index 00000000000..4015f887b8d --- /dev/null +++ b/src/renderer/src/lib/use-folder-setup-supported.ts @@ -0,0 +1,118 @@ +import { useCallback, useEffect, useSyncExternalStore } from 'react' +import { getRepoExecutionHostId, parseExecutionHostId } from '../../../shared/execution-host' +import { isFolderRepo } from '../../../shared/repo-kind' +import type { Repo } from '../../../shared/repo-types' +import { WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY } from '../../../shared/worktree-runtime-capabilities' +import { runtimeEnvironmentSupportsCapability } from '@/runtime/rpc/compatibility/runtime-capability-proof' + +export type FolderSetupSupport = 'supported' | 'unsupported' | 'pending' + +type FolderSetupHost = + | { kind: 'known'; supported: boolean } + | { kind: 'runtime'; environmentId: string } + +function folderSetupHost(repo: Repo | null | undefined): FolderSetupHost { + if (!repo || !isFolderRepo(repo)) { + return { kind: 'known', supported: true } + } + const host = parseExecutionHostId(getRepoExecutionHostId(repo)) + // An unserved SSH folder runs no hooks; its files aren't on a host Orca runs scripts on. + if (host?.kind === 'ssh') { + return { kind: 'known', supported: false } + } + return host?.kind === 'runtime' + ? { kind: 'runtime', environmentId: host.environmentId } + : { kind: 'known', supported: true } +} + +type FolderSetupObservation = { + answer: boolean | undefined + listeners: Set<() => void> + probe?: Promise +} + +// Active readers own answers; the runtime compatibility cache handles reuse after they leave. +const folderSetupObservations = new Map() + +function probeFolderSetup(environmentId: string): Promise { + const observation = folderSetupObservations.get(environmentId) + if (observation?.probe) { + return observation.probe + } + const probe = runtimeEnvironmentSupportsCapability( + environmentId, + WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY + ) + .then((supported) => { + if ( + observation && + folderSetupObservations.get(environmentId) === observation && + observation.answer !== supported + ) { + observation.answer = supported + observation.listeners.forEach((listener) => listener()) + } + return supported + }) + .finally(() => { + if (observation?.probe === probe) { + observation.probe = undefined + } + }) + if (observation) { + observation.probe = probe + } + return probe +} + +/** Folder setup runs only on hosts that report it; older hosts would save scripts that never run. Rejects when the host can't answer. */ +export function resolveFolderSetupSupported(repo: Repo | null | undefined): Promise { + const host = folderSetupHost(repo) + return host.kind === 'known' + ? Promise.resolve(host.supported) + : probeFolderSetup(host.environmentId) +} + +export function useFolderSetupSupport(repo: Repo | null | undefined): FolderSetupSupport { + const host = folderSetupHost(repo) + const environmentId = host.kind === 'runtime' ? host.environmentId : null + const subscribe = useCallback( + (listener: () => void) => { + if (!environmentId) { + return () => {} + } + let observation = folderSetupObservations.get(environmentId) + if (!observation) { + observation = { answer: undefined, listeners: new Set() } + folderSetupObservations.set(environmentId, observation) + } + observation.listeners.add(listener) + return () => { + observation.listeners.delete(listener) + if ( + observation.listeners.size === 0 && + folderSetupObservations.get(environmentId) === observation + ) { + folderSetupObservations.delete(environmentId) + } + } + }, + [environmentId] + ) + const answer = useSyncExternalStore(subscribe, () => + environmentId ? folderSetupObservations.get(environmentId)?.answer : undefined + ) + useEffect(() => { + // Re-asked on mount so an in-place host upgrade shows; a failure stays pending for Create to retry. + if (environmentId) { + probeFolderSetup(environmentId).catch(() => {}) + } + }, [environmentId]) + if (host.kind === 'known') { + return host.supported ? 'supported' : 'unsupported' + } + if (answer === undefined) { + return 'pending' + } + return answer ? 'supported' : 'unsupported' +} diff --git a/src/renderer/src/lib/workspace-setup-trust.test.ts b/src/renderer/src/lib/workspace-setup-trust.test.ts new file mode 100644 index 00000000000..7c273defcc5 --- /dev/null +++ b/src/renderer/src/lib/workspace-setup-trust.test.ts @@ -0,0 +1,52 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { AppState } from '@/store/types' +import { __resetTrustPromptChainForTests } from '../runtime/repo-hooks/ensure-hooks-confirmed' +import { confirmWorkspaceSetupDecision } from './workspace/creation/setup/workspace-setup-trust' + +const hooksCheckMock = vi.fn() + +function stateWithRepoWideTrust(kind: 'git' | 'folder'): AppState { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the trust check reads only trustedOrcaHooks, repos and openModal + return { + trustedOrcaHooks: { 'repo-1': { all: { approvedAt: 1 } } }, + repos: [{ id: 'repo-1', displayName: 'acme', kind }], + openModal: () => { + throw new Error('repo-wide trust must not prompt') + } + } as unknown as AppState +} + +describe('confirmWorkspaceSetupDecision under whole-project trust', () => { + beforeEach(() => { + hooksCheckMock.mockReset().mockResolvedValue({ + status: 'ok', + hasHooks: true, + hooks: { scripts: { setup: 'make bootstrap' } }, + mayNeedUpdate: false + }) + vi.stubGlobal('window', { api: { hooks: { check: hooksCheckMock } } }) + __resetTrustPromptChainForTests() + }) + + it('asks a folder host to run setup outright, since the trust carries no content hash', async () => { + const result = await confirmWorkspaceSetupDecision( + stateWithRepoWideTrust('folder'), + 'repo-1', + 'inherit', + 'local', + () => false + ) + expect(result).toMatchObject({ setupDecision: 'run', trustDecision: 'run' }) + }) + + it('leaves a git create on the project policy', async () => { + const result = await confirmWorkspaceSetupDecision( + stateWithRepoWideTrust('git'), + 'repo-1', + 'inherit', + 'local', + () => false + ) + expect(result).toMatchObject({ setupDecision: 'inherit', trustDecision: 'run' }) + }) +}) diff --git a/src/renderer/src/lib/workspace/activation/initial-surface/worktree-initial-terminal-seeding.ts b/src/renderer/src/lib/workspace/activation/initial-surface/worktree-initial-terminal-seeding.ts index c1166b266b8..f3e5c2e736e 100644 --- a/src/renderer/src/lib/workspace/activation/initial-surface/worktree-initial-terminal-seeding.ts +++ b/src/renderer/src/lib/workspace/activation/initial-surface/worktree-initial-terminal-seeding.ts @@ -226,21 +226,22 @@ export function ensureWorktreeHasInitialTerminal( const shouldCreateNewStartupTerminal = opts?.createNewTerminalForStartup === true && sequencedStartup !== undefined if (!shouldAutoCreate && !shouldCreateForExplicitWork && !shouldCreateNewStartupTerminal) { - const existingTerminalTabId = store.tabsByWorktree[worktreeId]?.[0]?.id - if (existingTerminalTabId && (setup || issueCommand)) { - // Main can adopt the startup tab yet fail setup spawn; renderer still runs returned fallback setup. + const existingTerminalTabId = store.tabsByWorktree[worktreeId]?.[0]?.id ?? null + const queuedOnExisting = existingTerminalTabId !== null && Boolean(setup || issueCommand) + // Main can adopt the startup tab yet fail setup spawn; renderer still runs returned fallback + // setup. Editor- or browser-only workspaces run it in its own tab. + if (queuedOnExisting || setup) { queueSetupAndIssueCommands( store, worktreeId, existingTerminalTabId, setup, - issueCommand, + existingTerminalTabId ? issueCommand : undefined, wrappedSetupCommandStr, opts ) - return existingTerminalTabId } - return null + return queuedOnExisting ? existingTerminalTabId : null } const templatedTabId = applyDefaultTerminalTabs( diff --git a/src/renderer/src/lib/workspace/creation/setup/workspace-setup-trust.ts b/src/renderer/src/lib/workspace/creation/setup/workspace-setup-trust.ts index f437f3d4cea..574787ec466 100644 --- a/src/renderer/src/lib/workspace/creation/setup/workspace-setup-trust.ts +++ b/src/renderer/src/lib/workspace/creation/setup/workspace-setup-trust.ts @@ -1,5 +1,9 @@ import type { AppState } from '@/store/types' -import type { ExecutionHostId } from '../../../../../../shared/execution-host' +import { + getRepoExecutionHostId, + type ExecutionHostId +} from '../../../../../../shared/execution-host' +import { isFolderRepo } from '../../../../../../shared/repo-kind' import type { SetupDecision } from '../../../../../../shared/worktree/create-types' import type { ApprovedSetupHashes } from '../../../../../../shared/worktree/approved-setup-hashes' import { approvedOrcaHookContentHashes } from '../../../../../../shared/orca-hook-trust-entries' @@ -14,7 +18,8 @@ export async function confirmWorkspaceSetupDecision boolean, signal?: AbortSignal ): Promise< - ({ setupDecision: T | 'skip'; trustDecision: 'run' | 'skip' } & ApprovedSetupHashes) | 'cancelled' + | ({ setupDecision: T | 'skip' | 'run'; trustDecision: 'run' | 'skip' } & ApprovedSetupHashes) + | 'cancelled' > { const trust = await settleComposerSubmit( ensureHooksApproved( @@ -32,11 +37,17 @@ export async function confirmWorkspaceSetupDecision 0 ? { approvedSetupHashes } : {}) } } + +/** + * Whole-project trust carries no content hash, and a folder host skips unhashed shared setup as an + * older client's. Say "run" outright where the project's policy would run it anyway. + */ +function explicitFolderRunUnderRepoTrust( + state: AppState, + repoId: string, + ownerHostId: ExecutionHostId | undefined, + decision: T +): T | 'run' { + if (decision !== undefined && decision !== 'inherit') { + return decision + } + const repo = state.repos.find( + (candidate) => + candidate.id === repoId && (!ownerHostId || getRepoExecutionHostId(candidate) === ownerHostId) + ) + return repo && + isFolderRepo(repo) && + (repo.hookSettings?.setupRunPolicy ?? 'run-by-default') === 'run-by-default' + ? 'run' + : decision +} diff --git a/src/renderer/src/lib/workspace/creation/worktree-creation-initial-tabs.ts b/src/renderer/src/lib/workspace/creation/worktree-creation-initial-tabs.ts index 7ff4ddd89b3..bedf41e524b 100644 --- a/src/renderer/src/lib/workspace/creation/worktree-creation-initial-tabs.ts +++ b/src/renderer/src/lib/workspace/creation/worktree-creation-initial-tabs.ts @@ -27,7 +27,8 @@ export function prepareCreatedWorktreeActivation({ }): { primaryTabId: string | null; options: WorktreeActivationOptions } { const onCreationHost = executionHostId ? { executionHostId } : {} let primaryTabId: string | null = null - if (isInstantFolderWorktreeCreation(useAppStore.getState(), request)) { + const instantFolder = isInstantFolderWorktreeCreation(useAppStore.getState(), request) + if (instantFolder) { // Metadata is not a destination surface; build the selected ordinary tabs before navigation. primaryTabId = ensureWorktreeHasInitialTerminal( useAppStore.getState(), @@ -53,7 +54,8 @@ export function prepareCreatedWorktreeActivation({ ...(primaryTabId ? { worktreeCreationId: creationId, providesInitialSurface: true } : { - ...(result.setup ? { setup: result.setup } : {}), + // Seeding above owns setup delivery; passing it again opens a second Setup tab. + ...(result.setup && !instantFolder ? { setup: result.setup } : {}), ...(defaultTabs ? { defaultTabs } : {}), ...(windowStartup.startup ? { startup: windowStartup.startup } : {}), ...(request.issueCommand ? { issueCommand: request.issueCommand } : {}), diff --git a/src/shared/agent-launch/startup/claude-chat-entrypoint.test.ts b/src/shared/agent-launch/startup/claude-chat-entrypoint.test.ts new file mode 100644 index 00000000000..79280bc9271 --- /dev/null +++ b/src/shared/agent-launch/startup/claude-chat-entrypoint.test.ts @@ -0,0 +1,20 @@ +import { expect, it } from 'vitest' +import { withOrcaClaudeChatEntrypoint } from './claude-chat-entrypoint' + +it('gives the SDK one exact chat identity after differently cased configured values', () => { + expect( + withOrcaClaudeChatEntrypoint( + { + CLAUDE_CODE_ENTRYPOINT: 'sdk-ts', + claude_code_entrypoint: 'configured', + PATH: 'C:\\bin', + CLAUDE_CODE_SESSION_ID: 'deliberate' + }, + 'win32' + ) + ).toEqual({ + CLAUDE_CODE_ENTRYPOINT: 'orca', + PATH: 'C:\\bin', + CLAUDE_CODE_SESSION_ID: 'deliberate' + }) +}) diff --git a/src/shared/agent-launch/startup/claude-chat-entrypoint.ts b/src/shared/agent-launch/startup/claude-chat-entrypoint.ts new file mode 100644 index 00000000000..92eb33278cf --- /dev/null +++ b/src/shared/agent-launch/startup/claude-chat-entrypoint.ts @@ -0,0 +1,16 @@ +import { overlayEnvironmentVariables } from '../../environment-overlay' + +export const CLAUDE_ENTRYPOINT_ENV = 'CLAUDE_CODE_ENTRYPOINT' +const ORCA_CLAUDE_CHAT_ENTRYPOINT = 'orca' + +/** Only structured chats own this identity; other Claude processes retain their CLI default. */ +export function withOrcaClaudeChatEntrypoint( + env: Readonly>, + platform: NodeJS.Platform +): Record { + return overlayEnvironmentVariables( + env, + { [CLAUDE_ENTRYPOINT_ENV]: ORCA_CLAUDE_CHAT_ENTRYPOINT }, + platform + ) +} diff --git a/src/shared/agent-launch/startup/claude-parent-session-env.ts b/src/shared/agent-launch/startup/claude-parent-session-env.ts index 309f9f8a3cb..5d67d327356 100644 --- a/src/shared/agent-launch/startup/claude-parent-session-env.ts +++ b/src/shared/agent-launch/startup/claude-parent-session-env.ts @@ -1,3 +1,5 @@ +import { CLAUDE_ENTRYPOINT_ENV } from './claude-chat-entrypoint' + // A launching Claude's identity and messaging access do not belong to independent processes. export const CLAUDE_CHILD_SESSION_STAMP_ENV_KEYS = [ 'CLAUDECODE', @@ -9,7 +11,7 @@ export const CLAUDE_CHILD_SESSION_STAMP_ENV_KEYS = [ 'CLAUDE_CODE_MESSAGING_SOCKET', 'CLAUDE_CODE_MESSAGING_TOKEN', 'CLAUDE_CODE_EXECPATH', - 'CLAUDE_CODE_ENTRYPOINT', + CLAUDE_ENTRYPOINT_ENV, 'CLAUDE_CODE_DESKTOP_APP_VERSION', 'CLAUDE_EFFORT', 'CLAUDE_PID', diff --git a/src/shared/folder-workspace-hooks.ts b/src/shared/folder-workspace-hooks.ts new file mode 100644 index 00000000000..6e24bd564f0 --- /dev/null +++ b/src/shared/folder-workspace-hooks.ts @@ -0,0 +1,14 @@ +import type { OrcaHooks } from './orca-yaml-hook-types' +import type { Repo } from './repo-types' +import { isFolderRepo } from './repo-kind' + +/** Folder workspaces share one directory, so orca.yaml default tabs would start again for every one. */ +export function scopeHooksToRepoKind( + repo: Pick, + hooks: OrcaHooks | null +): OrcaHooks | null { + if (!hooks || !isFolderRepo(repo) || !hooks.defaultTabs) { + return hooks + } + return { ...hooks, defaultTabs: undefined } +} diff --git a/src/shared/worktree-runtime-capabilities.ts b/src/shared/worktree-runtime-capabilities.ts index 989d5a3359f..e1e7bacdbab 100644 --- a/src/shared/worktree-runtime-capabilities.ts +++ b/src/shared/worktree-runtime-capabilities.ts @@ -102,6 +102,9 @@ export const WORKSPACE_SELECTOR_FOLDER_MATCH_RUNTIME_CAPABILITY = export const WORKTREE_RUN_APPROVED_SETUP_RUNTIME_CAPABILITY = 'worktree.run-approved-setup.v1' as const +// Hosts that run a folder project's setup and archive scripts when its workspaces are created and removed. +export const WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY = 'worktree.folder-setup.v1' as const + // Hosts that honor branchIntent 'create-exact': the unsuffixed new branch, or a coded refusal. export const WORKTREE_CREATE_EXACT_NAME_RUNTIME_CAPABILITY = 'worktree.create.exact-name.v1' as const @@ -135,6 +138,7 @@ export const WORKTREE_RUNTIME_CAPABILITIES = [ WORKTREE_SET_FOLDER_PARENT_RUNTIME_CAPABILITY, WORKSPACE_SELECTOR_FOLDER_MATCH_RUNTIME_CAPABILITY, WORKTREE_RUN_APPROVED_SETUP_RUNTIME_CAPABILITY, + WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY, WORKTREE_CREATE_EXACT_NAME_RUNTIME_CAPABILITY, ...(ORCA_SIDEBAR_INPUTS_IS_MAIN ? [] : [WORKTREE_ROWS_CHANGED_EVENT_RUNTIME_CAPABILITY]) ] as const