Merge origin/main into nwparker/expo-58-upgrade

This commit is contained in:
Kelvin Amoaba
2026-11-10 18:35:17 +00:00
106 changed files with 2770 additions and 572 deletions
@@ -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
@@ -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
@@ -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
@@ -0,0 +1,6 @@
id: claude-chat-entrypoint-callers
valid:
- 'stripInheritedClaudeSessionEnv(env)'
invalid:
- 'withOrcaClaudeChatEntrypoint(env, platform)'
- "import { withOrcaClaudeChatEntrypoint as stamp } from './claude-chat-entrypoint'"
@@ -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'"
@@ -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'"
@@ -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$'
-1
View File
@@ -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
+4 -4
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="113" height="20" role="img" aria-label="downloads: 164m">
<title>downloads: 164m</title>
<svg xmlns="http://www.w3.org/2000/svg" width="113" height="20" role="img" aria-label="downloads: 168m">
<title>downloads: 168m</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
@@ -15,7 +15,7 @@
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="11">
<text x="37" y="15" fill="#010101" fill-opacity=".3">downloads</text>
<text x="37" y="14">downloads</text>
<text x="93.5" y="15" fill="#010101" fill-opacity=".3">164m</text>
<text x="93.5" y="14">164m</text>
<text x="93.5" y="15" fill="#010101" fill-opacity=".3">168m</text>
<text x="93.5" y="14">168m</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 943 B

After

Width:  |  Height:  |  Size: 943 B

+6 -1
View File
@@ -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: ",
@@ -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<typeof MobileNativeChatAsk>[0]['onAnswer']
function mount(value: AskPrompt): Mock<Answer> {
const onAnswer = vi.fn<Answer>(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)
})
@@ -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
}
}))
@@ -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<number | null>(null)
const [selections, setSelections] = useState<number[][]>(() => prompt.questions.map(() => []))
const [otherText, setOtherText] = useState<string[]>(() =>
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({
</ScrollView>
) : null}
<ScrollView {...scrollViewProps} style={styles.scroll} keyboardShouldPersistTaps="always">
<ScrollView
ref={scrollRef}
onLayout={onViewportLayout}
style={styles.scroll}
keyboardShouldPersistTaps="always"
>
<View style={styles.questionRow}>
<MobileNativeChatQuestionText title content={q.question} style={styles.questionText} />
<MobileNativeChatCardHeaderAction
@@ -272,7 +279,12 @@ export function MobileNativeChatAsk({
label={opt.label}
description={opt.description}
preview={opt.preview}
onPreviewLayout={revealContent}
onPreview={() => {
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({
</Text>
</Pressable>
</View>
<MobileNativeChatOptionPreviewSheet
options={q.options}
viewedIndex={viewedOption}
selected={selections[index] ?? []}
disabled={submitting}
onView={setViewedOption}
onClose={() => setViewedOption(null)}
onChoose={(optionIndex) => {
setViewedOption(null)
toggle(index, optionIndex, q.multiSelect, true)
}}
/>
</View>
)
}
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
}
}))
@@ -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 = (
<Pressable
accessibilityRole={multi ? 'checkbox' : 'radio'}
@@ -40,6 +41,7 @@ export function MobileNativeChatAskOptionRow({
style={({ pressed }) => [
styles.option,
selected && styles.optionSelected,
hasPreview && styles.optionWithPreview,
pressed && pressedStyle
]}
disabled={disabled}
@@ -65,29 +67,15 @@ export function MobileNativeChatAskOptionRow({
</View>
</Pressable>
)
// One root shape whether or not the preview shows, so selecting never remounts the row.
return (
<>
return hasPreview ? (
<View style={[styles.optionCard, selected && styles.optionSelected]}>
{row}
{preview && selected ? (
<View
style={styles.preview}
onLayout={(event: LayoutChangeEvent) => {
const { y, height } = event.nativeEvent.layout
onPreviewLayout?.(y, y + height)
}}
>
<ScrollView nestedScrollEnabled showsVerticalScrollIndicator>
{/* Mockups are drawn in columns, so they scroll sideways instead of wrapping at phone width. */}
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
<Text selectable style={styles.previewText}>
{preview}
</Text>
</ScrollView>
</ScrollView>
</View>
) : null}
</>
<View style={styles.previewInset}>
<MobileNativeChatOptionThumbnail label={label} preview={preview!} onPress={onPreview!} />
</View>
</View>
) : (
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
}
}))
@@ -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 (
<KeyedBottomDrawer
sheet={viewedIndex}
sheetKey={sheetKey}
onClose={onClose}
fillAvailable
contentScrollable={false}
dragContentToDismiss={false}
>
{(index) => {
const option = options[index]!
return (
<>
<SheetHeader
title={option.label}
subtitle={t('chat.ask.previewPosition', '{{current}} of {{total}}', {
current: previews.findIndex((item) => item.index === index) + 1,
total: previews.length
})}
onClose={onClose}
/>
<ReadablePreview
// oxlint-disable-next-line react-doctor/no-array-index-as-key -- Option indices are immutable answer identities; changing pages resets both scroll axes.
key={index}
preview={option.preview ?? ''}
/>
{previews.length > 1 ? (
<ScrollView
horizontal
style={styles.pages}
contentContainerStyle={styles.pageContent}
>
{previews.map((item) => (
<Pressable
key={item.index}
accessibilityRole="button"
accessibilityLabel={t('chat.ask.optionPreview', '{{option}} preview', {
option: item.option.label
})}
accessibilityState={{ selected: item.index === index }}
onPress={() => onView(item.index)}
style={({ pressed }) => [styles.page, pressed && pressedStyle]}
>
<View style={[styles.dot, item.index === index && styles.currentDot]} />
</Pressable>
))}
</ScrollView>
) : null}
<SheetPrimaryButton
label={
selected.includes(index)
? t('chat.ask.chosen', 'Chosen')
: t('chat.ask.chooseThis', 'Choose this')
}
disabled={disabled}
onPress={() => onChoose(index)}
/>
</>
)
}}
</KeyedBottomDrawer>
)
}
function ReadablePreview({ preview }: { preview: string }): React.JSX.Element {
useMobileColorScheme()
return (
<ScrollView style={styles.preview} showsVerticalScrollIndicator nestedScrollEnabled>
<ScrollView horizontal showsHorizontalScrollIndicator nestedScrollEnabled>
<Text selectable style={styles.text}>
{preview}
</Text>
</ScrollView>
</ScrollView>
)
}
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 }
}))
@@ -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 (
<MeasuredPreviewThumbnail key={preview} label={label} preview={preview} onPress={onPress} />
)
}
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 (
<Pressable
accessibilityRole="button"
accessibilityLabel={t('chat.ask.optionPreview', '{{option}} preview', { option: label })}
onPress={onPress}
style={({ pressed }) => [styles.thumbnail, pressed && pressedStyle]}
>
<View
pointerEvents="none"
onLayout={(event) => setWidth(event.nativeEvent.layout.width)}
style={[styles.image, { height }]}
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
>
<Text
allowFontScaling={false}
onLayout={(event) => {
const { width, height } = event.nativeEvent.layout
setBounds((previous) =>
previous?.width === width && previous.height === height ? previous : { width, height }
)
}}
style={[styles.text, { transform: [{ scale }] }]}
>
{preview}
</Text>
{height >= MAX_HEIGHT ? <MobileEdgeFade edge="bottom" /> : null}
</View>
<Text style={styles.view}>{t('chat.ask.viewPreview', 'View')}</Text>
</Pressable>
)
}
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
}
}))
@@ -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
})
@@ -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<ScrollViewInstance>(null)
const inputRef = useRef<MobileTextInputHandle>(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<NativeScrollEvent>): 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 }
}
@@ -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<string | null> {
const setupRequested = create.setupDecision === 'run' || create.runHooks === true
if (!setupRequested || !worktreeId?.includes(FOLDER_WORKSPACE_INSTANCE_SEPARATOR)) {
return null
}
const status = await client.call<RuntimeStatus>('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<T> {
const warning = await folderSetupUnsupportedWarning(client, result.worktree?.id, create)
return warning
? { ...result, warning: result.warning ? `${result.warning} ${warning}` : warning }
: result
}
@@ -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<RuntimeWorktreeCreateResult>('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
? {
+8 -3
View File
@@ -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<string, CommandHandler> = {
const result = await withSetupDecisionRecovery(
callNamingParentEnvironment<RuntimeWorktreeCreateResult>(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(
@@ -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.
@@ -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.'
}
})
])
)
})
+11
View File
@@ -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,
+6 -12
View File
@@ -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 ||
@@ -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(
@@ -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
+10 -2
View File
@@ -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,
@@ -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 } : {}),
@@ -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<ClaudeChi
return { ...invocation, overlay: overlay ? cloneDefinedEnv(overlay) : undefined, inheritedEnv }
}
const CLAUDE_ENTRYPOINT_ENV = 'CLAUDE_CODE_ENTRYPOINT'
// Name Orca as the client instead of the SDK's sdk-ts default or a launching Claude's value.
export function withOrcaClaudeEntrypoint(
inheritedEnv: Record<string, string>,
overlay: Record<string, string> | undefined,
platform: NodeJS.Platform
): Record<string, string> {
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<string, string> {
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<string, string> {
return applyClaudeEnvPatch(
claudeChildEnv(sources),
{},
{
stripAuthEnv: true,
platform: process.platform
}
return withOrcaClaudeChatEntrypoint(
applyClaudeEnvPatch(
claudeChildEnv(sources),
{},
{ stripAuthEnv: true, platform: process.platform }
),
process.platform
)
}
@@ -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 {
@@ -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<CreateWorktreeResult> {
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 } : {})
}
}
@@ -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)
@@ -179,7 +179,8 @@ export async function executeWorktreeRemoval(
canonicalWorktreePath,
repo,
undefined,
localWorktreeGitOptions
localWorktreeGitOptions,
{ identity: { worktreeId: args.worktreeId } }
)
archiveHookOverride = gateWorktreeRemovalOnArchiveHook({
worktreePath: canonicalWorktreePath,
@@ -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)
}
@@ -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)
})
})
+20 -1
View File
@@ -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<T> = {
}
} | 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<T>(
limit: number,
loadConnection: (page: LinearPageVariables) => Promise<LinearConnection<T>>,
@@ -25,7 +44,7 @@ export async function readConnectionPages<T>(
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) {
@@ -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
+2 -1
View File
@@ -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
}
}
@@ -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) {
@@ -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) {
+4 -3
View File
@@ -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
}
@@ -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
@@ -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)
})
})
+2 -1
View File
@@ -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
@@ -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)
@@ -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') {
@@ -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)
@@ -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: () => ({
@@ -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<Pick<Worktree, 'id' | 'repoId' | 'path'>>
showManagedWorktree: (
selector: string
) => Promise<Pick<Worktree, 'id' | 'repoId' | 'path' | 'displayName'>>
requireStore: () => Pick<RuntimeStore, 'getRepo' | 'getSettings'>
provisionManagedWorktreeTerminals: (args: WorktreeTerminalProvisioningArgs) => Promise<unknown>
}
@@ -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.
@@ -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<RuntimeTerminalCreate>
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<typeof mergeRuntimeFolderWorkspace>
): 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
}
}
}
@@ -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<ReturnType<typeof prepareRuntimeLocalWorktreeSetup>>
/**
* 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<typeof prepareRuntimeLocalWorktreeSetup>[0]['request'] & {
wslUserAct?: true
}
repo: Repo
worktree: Pick<Worktree, 'id' | 'path' | 'displayName'>
settings: ReturnType<RuntimeStore['getSettings']>
runtimeTarget: () => { wslDistro?: string } | undefined
shouldUseSetupRunner: boolean
}): Promise<PreparedFolderSetup | { warning: string } | undefined> {
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<Pick<CreateWorktreeResult, 'setup' | 'setupReceipt' | 'startupTerminal' | 'warning'>> {
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 } : {})
}
}
@@ -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()
})
})
})
@@ -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<RuntimeStore['getSettings']>
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)
}
@@ -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
}
}
}
@@ -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,
@@ -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)
}
@@ -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
@@ -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<RuntimeLocalWorktreeTerminalStartupResult> {
const { request, repo, worktree, defaultTabs, startup, ports } = args
let { setup } = args
@@ -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)
@@ -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()!])
})
})
@@ -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<void> {
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<void> {
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)
})
}
@@ -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 })
}
@@ -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<string, string | undefined>): 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<string, string>; 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`
}
}
@@ -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)
+13 -7
View File
@@ -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<string, string> = {}
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<string, string> = { ...wslEnv }
const wslCli = wslHookOrcaCliEnv()
const guestEnv: Record<string, string> = { ...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<HookProcessOutcome>((resolve) => {
@@ -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<Repo, 'path'>,
worktreePath: string
repo: Pick<Repo, 'path' | 'kind'>,
worktreePath: string,
identity?: HookWorkspaceIdentity
): Record<string, string> {
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<string, string> {
export function getSetupRunnerEnvVars(
repo: Repo,
worktreePath: string,
identity?: HookWorkspaceIdentity
): Record<string, string> {
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'
}
@@ -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<WorktreeSetupLaunch> {
return createWorktreeRunnerScript({
identity,
repo,
worktreePath,
script,
@@ -68,6 +77,7 @@ async function createWorktreeRunnerScript(args: {
runtimeTarget?: HookRuntimeTarget
waitForAgentStartup?: boolean
setupShell?: SetupRunnerShell
identity?: HookWorkspaceIdentity
}): Promise<WorktreeSetupLaunch> {
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<string> {
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,
@@ -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<ArchiveHookOverride | undefined> {
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)
})
}
@@ -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).
@@ -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(
<TooltipProvider>
<RepositoryPane
repo={repo}
yamlHooks={null}
hasHooksFile={false}
hooksInspectionReady
mayNeedUpdate={false}
updateRepo={updateRepo}
removeProject={vi.fn()}
/>
</TooltipProvider>
)
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()
)
})
@@ -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)) ? (
<RepositoryHooksSection
key="hooks"
repo={repo}
@@ -101,11 +101,13 @@ function getCommandSourcePolicyOptions(
}
export function RepositorySetupPolicySetting({
isFolder = false,
setupRunPolicy,
setupAgentStartupPolicy,
onRunPolicyChange,
onStartupPolicyChange
}: {
isFolder?: boolean
setupRunPolicy: SetupRunPolicy
setupAgentStartupPolicy: SetupAgentStartupPolicy
onRunPolicyChange: (policy: SetupRunPolicy) => void
@@ -121,10 +123,15 @@ export function RepositorySetupPolicySetting({
{t('auto.components.settings.RepositoryHooksSection.793dcee97d', 'When to run')}
</h5>
<p className="text-xs text-muted-foreground">
{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.'
)}
</p>
</div>
<SegmentedPolicyToggle
@@ -9,6 +9,7 @@ import type {
} from '../../../../../../shared/orca-yaml-hook-types'
import type { Repo } from '../../../../../../shared/repo-types'
import { getRepoExecutionHostId } from '../../../../../../shared/execution-host'
import { isFolderRepo } from '../../../../../../shared/repo-kind'
import { resolveHookCommandSourcePolicy } from '../../../../../../shared/hook-command-source-policy'
import { useAppStore } from '@/store/index'
import { useTranslate } from '@/i18n/use-translate'
@@ -30,6 +31,7 @@ import {
import { RepositoryIssueCommandSetting } from './RepositoryIssueCommandSetting'
import { useRepositoryHookSettingsDraft } from './use-repository-hook-settings-draft'
import { useRepositoryIssueCommand } from './use-repository-issue-command'
import { getRepositoryHookScriptDescription } from './repository-git-hooks-search-entries'
type RepositoryHooksSectionProps = {
repo: Repo
@@ -73,12 +75,8 @@ export function RepositoryHooksSection({
flushScriptDraftOnUnmount,
updateHookSettingsPolicyDraft
} = useRepositoryHookSettingsDraft({ repo, repoHostIdentity, onUpdateHookSettings })
const issueCommand = useRepositoryIssueCommand({
repoId: repo.id,
repoHostIdentity,
selectedHostId
})
const localHookFields = getLocalHookFields(t)
const isFolder = isFolderRepo(repo)
const localHookFields = getLocalHookFields(t, isFolder)
const selectedSetupRunPolicy: SetupRunPolicy =
hookSettingsDraft.setupRunPolicy ?? 'run-by-default'
const selectedSetupAgentStartupPolicy: SetupAgentStartupPolicy =
@@ -110,18 +108,26 @@ export function RepositoryHooksSection({
return (
<div ref={flushScriptDraftOnUnmount}>
<SettingsGroup
title={t('auto.components.settings.RepositoryHooksSection.01bdba296f', 'Worktree hooks')}
description={t(
'auto.components.settings.RepositoryHooksSection.8567127a40',
'Scripts that run when worktrees are created or archived. Local scripts are stored on this machine; `orca.yaml` scripts are shared with your team.'
)}
title={
isFolder
? t('components.settings.RepositoryHooksSection.folderTitle', 'Workspace hooks')
: t('auto.components.settings.RepositoryHooksSection.01bdba296f', 'Worktree hooks')
}
description={
isFolder
? t(
'components.settings.RepositoryHooksSection.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.'
)
: t(
'auto.components.settings.RepositoryHooksSection.8567127a40',
'Scripts that run when worktrees are created or archived. Local scripts are stored on this machine; `orca.yaml` scripts are shared with your team.'
)
}
>
<SearchableSetting
title={t('auto.components.settings.RepositoryHooksSection.1ecf0b115a', 'Setup script')}
description={t(
'auto.components.settings.RepositoryHooksSection.30d555acd2',
'Local and shared scripts that run after a new worktree is created.'
)}
description={getRepositoryHookScriptDescription(repo, 'setup', t)}
className="py-4"
forceVisible={forceVisible}
keywords={[
@@ -160,6 +166,7 @@ export function RepositoryHooksSection({
keywords={['setup run policy', 'ask', 'run by default', 'skip by default']}
>
<RepositorySetupPolicySetting
isFolder={isFolder}
setupRunPolicy={selectedSetupRunPolicy}
setupAgentStartupPolicy={selectedSetupAgentStartupPolicy}
onRunPolicyChange={(setupRunPolicy) =>
@@ -172,10 +179,7 @@ export function RepositoryHooksSection({
</SearchableSetting>
<SearchableSetting
title={t('auto.components.settings.RepositoryHooksSection.bfdb1266ce', 'Archive script')}
description={t(
'auto.components.settings.RepositoryHooksSection.b91a0f297d',
'Local and shared scripts that run before a worktree is archived.'
)}
description={getRepositoryHookScriptDescription(repo, 'archive', t)}
className="py-4"
forceVisible={forceVisible}
keywords={[
@@ -209,21 +213,13 @@ export function RepositoryHooksSection({
/>
</div>
) : null}
<SearchableSetting
title={t(
'auto.components.settings.RepositoryHooksSection.da00f141c2',
'Custom GitHub issue command'
)}
description={t(
'auto.components.settings.RepositoryHooksSection.2cc27dc12b',
'Optional per-user override for the linked-issue command.'
)}
className="py-4"
forceVisible={forceVisible}
keywords={['github issue command', 'issue command', 'workflow', 'agent', 'github']}
>
<RepositoryIssueCommandSetting {...issueCommand} />
</SearchableSetting>
{isFolder ? null : (
<RepositoryIssueCommandRow
repo={repo}
repoHostIdentity={repoHostIdentity}
forceVisible={forceVisible}
/>
)}
<SearchableSetting
title={t('auto.components.settings.RepositoryHooksSection.c9bc1bfd8f', 'Advanced')}
description={t(
@@ -260,3 +256,38 @@ export function RepositoryHooksSection({
</div>
)
}
/** 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 (
<SearchableSetting
title={t(
'auto.components.settings.RepositoryHooksSection.da00f141c2',
'Custom GitHub issue command'
)}
description={t(
'auto.components.settings.RepositoryHooksSection.2cc27dc12b',
'Optional per-user override for the linked-issue command.'
)}
className="py-4"
forceVisible={forceVisible}
keywords={['github issue command', 'issue command', 'workflow', 'agent', 'github']}
>
<RepositoryIssueCommandSetting {...issueCommand} />
</SearchableSetting>
)
}
@@ -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'
)
]
}
])
]
}
@@ -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"'
@@ -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)
}
}
@@ -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,
@@ -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
@@ -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,
@@ -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
@@ -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
])
@@ -22,6 +22,7 @@ export type QuickSubmitPreparationInput = Pick<
| 'revealSetupChoice'
| 'settings'
| 'setupConfig'
| 'setupSupport'
| 'setupDecision'
| 'setupPolicy'
| 'smartNameMode'
@@ -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,
-2
View File
@@ -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",
+11 -3
View File
@@ -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": {
-2
View File
@@ -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",
-2
View File
@@ -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",
-2
View File
@@ -10071,11 +10071,9 @@
"fbfd2386e8": "アーカイブスクリプト",
"4c17787d7b": "アーカイブ",
"8655e3387b": "フック",
"acd1157f0c": "ワークツリーがアーカイブされる前に実行されるローカルおよび共有スクリプト。",
"491b05d6e6": "セットアップコマンド",
"a31b43a7f8": "セットアップスクリプト",
"5590388dfa": "セットアップ",
"baaf70bb37": "新規ワークツリーの作成後に実行されるローカルおよび共有スクリプト。",
"d73fb47b45": ".claude/mcp.json",
"db11b337c4": ".claude.json",
"26f42fe773": ".cursor/mcp.json",
-2
View File
@@ -10034,11 +10034,9 @@
"fbfd2386e8": "아카이브 스크립트",
"4c17787d7b": "보관소",
"8655e3387b": "훅",
"acd1157f0c": "작업 트리가 보관되기 전에 실행되는 로컬 및 공유 스크립트입니다.",
"491b05d6e6": "설정 명령",
"a31b43a7f8": "설정 스크립트",
"5590388dfa": "설정",
"baaf70bb37": "새 작업 트리가 생성된 후 실행되는 로컬 및 공유 스크립트입니다.",
"d73fb47b45": ".claude/mcp.json",
"db11b337c4": ".claude.json",
"26f42fe773": ".cursor/mcp.json",
-2
View File
@@ -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",
-2
View File
@@ -11085,11 +11085,9 @@
"fbfd2386e8": "скрипт архивации",
"4c17787d7b": "архивировать",
"8655e3387b": "хуки",
"acd1157f0c": "Локальные и общие скрипты перед архивацией рабочего дерева.",
"491b05d6e6": "команда настройки",
"a31b43a7f8": "скрипт настройки",
"5590388dfa": "настройка",
"baaf70bb37": "Локальные и общие скрипты после создания рабочего дерева.",
"d73fb47b45": ".claude/mcp.json",
"db11b337c4": ".claude.json",
"26f42fe773": ".cursor/mcp.json",
-2
View File
@@ -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",
@@ -10554,11 +10554,9 @@
"fbfd2386e8": "封存指令碼",
"4c17787d7b": "封存",
"8655e3387b": "鉤子",
"acd1157f0c": "在封存工作樹之前執行的本機和共用指令碼。",
"491b05d6e6": "設定命令",
"a31b43a7f8": "設定指令碼",
"5590388dfa": "設定",
"baaf70bb37": "建立新工作樹後執行的本機和共用指令碼。",
"d73fb47b45": ".claude/mcp.json",
"db11b337c4": ".claude.json",
"26f42fe773": ".cursor/mcp.json",
-2
View File
@@ -10034,11 +10034,9 @@
"fbfd2386e8": "存档脚本",
"4c17787d7b": "档案",
"8655e3387b": "钩子",
"acd1157f0c": "在归档工作树之前运行的本地和共享脚本。",
"491b05d6e6": "设置命令",
"a31b43a7f8": "设置脚本",
"5590388dfa": "设置",
"baaf70bb37": "创建新工作树后运行的本地和共享脚本。",
"d73fb47b45": ".claude/mcp.json",
"db11b337c4": ".claude.json",
"26f42fe773": ".cursor/mcp.json",
@@ -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<boolean>((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<string, ReturnType<typeof deferred>[]>()
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')
})
@@ -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<boolean>
}
// Active readers own answers; the runtime compatibility cache handles reuse after they leave.
const folderSetupObservations = new Map<string, FolderSetupObservation>()
function probeFolderSetup(environmentId: string): Promise<boolean> {
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<boolean> {
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'
}
@@ -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' })
})
})
@@ -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(
@@ -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<T extends SetupDecision | un
isCancelled: () => 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<T extends SetupDecision | un
return 'cancelled'
}
const { decision: trustDecision, approvedContentHash } = trust.value
const state = typeof stateOrGetter === 'function' ? stateOrGetter() : stateOrGetter
if (trustDecision !== 'run' || approvedContentHash === undefined) {
return { setupDecision: trustDecision === 'skip' ? 'skip' : decision, trustDecision }
return {
setupDecision:
trustDecision === 'skip'
? 'skip'
: explicitFolderRunUnderRepoTrust(state, repoId, ownerHostId, decision),
trustDecision
}
}
// The host runs shared setup only if the created branch's content hashes to one of these.
const state = typeof stateOrGetter === 'function' ? stateOrGetter() : stateOrGetter
const approvedSetupHashes = approvedOrcaHookContentHashes(
state.trustedOrcaHooks,
repoId,
@@ -49,3 +60,27 @@ export async function confirmWorkspaceSetupDecision<T extends SetupDecision | un
...(approvedSetupHashes.length > 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<T extends SetupDecision | undefined>(
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
}

Some files were not shown because too many files have changed in this diff Show More