From 80deb09aa93ccb65622b83e3531ddd94eb873175 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Mon, 9 Nov 2026 07:04:54 +0000 Subject: [PATCH 01/10] feat(dictation): fixed-size dictation pill with cancel, timer and finish (#40155) * feat(dictation): fixed-size dictation pill with cancel, timer and finish * fix(dictation): abort a cloud upload cancelled while finishing; time recorded audio * refactor(dictation): reuse Esc/IME helpers, keep the pane on the target, isolate meter renders * fix(dictation): pause the pill timer while hidden; compile under React Compiler --- src/main/ipc/speech.ts | 26 +- src/main/speech/stt-session-stop.ts | 4 + src/preload/api/speech-api.ts | 2 + src/preload/api/speech-bridge.ts | 5 + .../dictation/DictationController.tsx | 46 +++- .../components/dictation/DictationGrapes.tsx | 8 +- .../dictation/DictationIndicator.fixture.tsx | 56 ++++ .../dictation/DictationIndicator.tsx | 253 ++++++++++++------ .../dictation/dictation-control-events.ts | 2 +- .../dictation/dictation-insertion-target.ts | 12 +- .../dictation/dictation-pill-anchor.ts | 63 +++++ .../use-floating-terminal-focus-lifecycle.ts | 8 +- .../regular-terminal-focus-ownership.test.ts | 25 ++ .../focus/regular-terminal-focus-ownership.ts | 6 +- src/renderer/src/components/ui/button.tsx | 2 + src/renderer/src/i18n/locales/de.json | 8 +- src/renderer/src/i18n/locales/en.json | 10 +- src/renderer/src/i18n/locales/es.json | 8 +- src/renderer/src/i18n/locales/fr.json | 8 +- src/renderer/src/i18n/locales/ja.json | 8 +- src/renderer/src/i18n/locales/ko.json | 8 +- src/renderer/src/i18n/locales/pt.json | 8 +- src/renderer/src/i18n/locales/ru.json | 8 +- src/renderer/src/i18n/locales/tr.json | 8 +- src/renderer/src/i18n/locales/zh-Hant.json | 8 +- src/renderer/src/i18n/locales/zh.json | 8 +- .../src/lib/app-keyboard-router.test.ts | 16 ++ src/renderer/src/lib/app-keyboard-router.ts | 13 +- src/renderer/src/lib/focus-keeping-press.ts | 6 + .../src/web/preload-api/web-speech-api.ts | 16 ++ src/shared/dictation-session-machine.test.ts | 6 + src/shared/dictation-session-machine.ts | 9 +- 32 files changed, 487 insertions(+), 187 deletions(-) create mode 100644 src/renderer/src/components/dictation/DictationIndicator.fixture.tsx create mode 100644 src/renderer/src/components/dictation/dictation-pill-anchor.ts create mode 100644 src/renderer/src/lib/focus-keeping-press.ts diff --git a/src/main/ipc/speech.ts b/src/main/ipc/speech.ts index feded50d21b..42f92f7445e 100644 --- a/src/main/ipc/speech.ts +++ b/src/main/ipc/speech.ts @@ -1,4 +1,10 @@ -import { ipcMain, BrowserWindow, systemPreferences, type MessagePortMain } from 'electron' +import { + ipcMain, + BrowserWindow, + systemPreferences, + type IpcMainInvokeEvent, + type MessagePortMain +} from 'electron' import { abortWhenRendererGone } from './renderer-lifetime-abort' import { join } from 'node:path' import { writeFile, unlink } from 'node:fs/promises' @@ -260,12 +266,16 @@ export function registerSpeechHandlers(store: Store): void { } ) - ipcMain.handle('speech:stopDictation', async (_event, sessionId = 'desktop') => { - const owner = getDesktopOwner(_event.sender.id, sessionId) - const listener = dictationListeners.get(_event.sender.id) - await getSpeechSttService(store).stopDictation(owner) - if (listener?.owner === owner) { - listener.cleanup() + const handleStop = + (discard: boolean) => + async (event: IpcMainInvokeEvent, sessionId = 'desktop'): Promise => { + const owner = getDesktopOwner(event.sender.id, sessionId) + const listener = dictationListeners.get(event.sender.id) + await getSpeechSttService(store).stopDictation(owner, { discard }) + if (listener?.owner === owner) { + listener.cleanup() + } } - }) + ipcMain.handle('speech:stopDictation', handleStop(false)) + ipcMain.handle('speech:cancelDictation', handleStop(true)) } diff --git a/src/main/speech/stt-session-stop.ts b/src/main/speech/stt-session-stop.ts index a1154526e37..1480be40b54 100644 --- a/src/main/speech/stt-session-stop.ts +++ b/src/main/speech/stt-session-stop.ts @@ -27,6 +27,10 @@ export function stopSttDictation( return Promise.resolve() } if (session.phase === 'stopping') { + // A cancel after Finish still aborts the cloud upload whose text it would throw away. + if (options.discard) { + session.cloud?.cancel() + } return session.stopPromise ?? Promise.resolve() } session.phase = 'stopping' diff --git a/src/preload/api/speech-api.ts b/src/preload/api/speech-api.ts index 2acb2d35da1..8acba71dcc2 100644 --- a/src/preload/api/speech-api.ts +++ b/src/preload/api/speech-api.ts @@ -27,6 +27,8 @@ export type SpeechApi = { /** Resolves true when this chunk filled a cloud session's upload cap. */ feedAudio: (samples: Float32Array, sampleRate: number, sessionId?: string) => Promise stopDictation: (sessionId?: string) => Promise + /** Drops the session's audio and any text it hasn't returned yet, without transcribing the rest. */ + cancelDictation: (sessionId: string) => Promise onPartialTranscript: (callback: (data: SpeechTranscriptEvent) => void) => () => void onFinalTranscript: (callback: (data: SpeechTranscriptEvent) => void) => () => void onDownloadProgress: ( diff --git a/src/preload/api/speech-bridge.ts b/src/preload/api/speech-bridge.ts index 8222c564422..a0b38154039 100644 --- a/src/preload/api/speech-bridge.ts +++ b/src/preload/api/speech-bridge.ts @@ -84,6 +84,11 @@ export const speechApi = { } return ipcRenderer.invoke('speech:stopDictation', sessionId) }, + cancelDictation: (sessionId: string): Promise => { + audioPorts.get(sessionId)?.close() + audioPorts.delete(sessionId) + return ipcRenderer.invoke('speech:cancelDictation', sessionId) + }, onPartialTranscript: (callback: (data: SpeechTranscriptEvent) => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, data: SpeechTranscriptEvent): void => diff --git a/src/renderer/src/components/dictation/DictationController.tsx b/src/renderer/src/components/dictation/DictationController.tsx index d509b0ef504..be1f066e7da 100644 --- a/src/renderer/src/components/dictation/DictationController.tsx +++ b/src/renderer/src/components/dictation/DictationController.tsx @@ -4,6 +4,10 @@ import { useAudioCapture } from '@/hooks/use-audio-capture' import { toast } from 'sonner' import { DictationIndicator } from './DictationIndicator' import { captureInsertionTarget } from './dictation-insertion-target' +import { dictationPillAnchorFor, type DictationPillAnchor } from './dictation-pill-anchor' +import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router' +import { isImeOwnedKeyboardEvent } from '@/lib/ime-composition-keyboard-event' +import { isPlainEscapeKeyEvent } from '../terminal-pane/input/keyboard/agent-interrupt-key-event' import { createDictationTranscriptDelivery } from './dictation-transcript-delivery' import { recordStoppedSession, waitForStoppedSession } from './dictation-stopped-sessions' import { translate } from '@/i18n/i18n' @@ -24,6 +28,7 @@ import { useDictationSpeechEvents } from './use-dictation-speech-events' import { canStartDictation, initialDictationSession, + isDictationPillShown, isDictationUnderway, transitionDictationSession, type DictationSession, @@ -56,6 +61,8 @@ export function DictationController() { // Push-to-talk restarts per utterance; report a missing preferred microphone once per preference. const micFallbackNotifiedForRef = useRef(null) const [captureLive, setCaptureLive] = useState(false) + // Holds the target pane only while the pill shows, so a closed pane isn't kept alive. + const [pillAnchor, setPillAnchor] = useState(null) const dispatch = useCallback( (event: DictationSessionEvent): DictationSession => { @@ -69,6 +76,7 @@ export function DictationController() { setDictationState(next.phase) if (next.phase === 'idle') { setPartialTranscript('') + setPillAnchor(null) } } return next @@ -113,6 +121,17 @@ export function DictationController() { [dispatch, finishCapture, getCapturedChunkCount] ) + // Words that already landed stay; the engine drops the rest instead of transcribing it. + const cancelDictation = useCallback(() => { + const previous = sessionRef.current + if (dispatch({ type: 'cancel' }) === previous || previous.sessionId === null) { + return + } + stopCapture() + void window.api.speech.cancelDictation(previous.sessionId).catch(() => undefined) + drainStoppedSession(previous.sessionId) + }, [dispatch, stopCapture, drainStoppedSession]) + const stopDictation = useCallback(async () => { const previous = sessionRef.current const next = dispatch({ type: 'stop' }) @@ -152,6 +171,7 @@ export function DictationController() { const deliver = createDictationTranscriptDelivery() deliverRef.current = (text) => deliver(text, insertionTarget) setCaptureLive(false) + setPillAnchor(dictationPillAnchorFor(insertionTarget)) // A stop that arrived while starting is still this run's stop. const stopQueued = (): boolean => isCurrent() && sessionRef.current.phase === 'stopping' @@ -161,7 +181,7 @@ export function DictationController() { stopCapture() } if (engineStarted) { - await window.api.speech.stopDictation(sessionId).catch(() => undefined) + await window.api.speech.cancelDictation(sessionId).catch(() => undefined) drainStoppedSession(sessionId) } } @@ -281,13 +301,33 @@ export function DictationController() { void startDictation() } else if (action === 'stop') { void stopDictation() + } else if (action === 'cancel') { + cancelDictation() } else { toggleDictation() } } document.addEventListener(DICTATION_CONTROL_EVENT, handleControl) return () => document.removeEventListener(DICTATION_CONTROL_EVENT, handleControl) - }, [settings?.voice?.enabled, startDictation, stopDictation, toggleDictation]) + }, [settings?.voice?.enabled, startDictation, stopDictation, cancelDictation, toggleDictation]) + + // Esc cancels while the pill shows and goes no further, so it can't also interrupt the agent. + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent): void => { + if ( + !isPlainEscapeKeyEvent(event) || + isImeOwnedKeyboardEvent(event) || + !isDictationPillShown(sessionRef.current.phase) + ) { + return + } + event.preventDefault() + event.stopImmediatePropagation() + cancelDictation() + } + addAppKeyListener('keydown', handleKeyDown, { first: true }) + return () => removeAppKeyListener('keydown', handleKeyDown) + }, [cancelDictation]) useDictationSilenceStop( dictationState === 'listening', @@ -334,5 +374,5 @@ export function DictationController() { } }) - return + return } diff --git a/src/renderer/src/components/dictation/DictationGrapes.tsx b/src/renderer/src/components/dictation/DictationGrapes.tsx index a2629bf6392..8b80331c9b0 100644 --- a/src/renderer/src/components/dictation/DictationGrapes.tsx +++ b/src/renderer/src/components/dictation/DictationGrapes.tsx @@ -3,11 +3,12 @@ import { DICTATION_GRAPES } from '../../../../shared/dictation-audio-meter' type DictationGrapesProps = { level: number + /** Moves with the voice; otherwise the grapes rest and pulse. */ active: boolean - transitioning: boolean + className?: string } -export function DictationGrapes({ level, active, transitioning }: DictationGrapesProps) { +export function DictationGrapes({ level, active, className }: DictationGrapesProps) { const normalizedLevel = Math.min(1, Math.max(0, level)) return ( @@ -16,7 +17,8 @@ export function DictationGrapes({ level, active, transitioning }: DictationGrape aria-hidden="true" className={cn( 'flex h-6 w-11 shrink-0 items-center justify-center gap-px overflow-hidden', - transitioning && 'animate-pulse motion-reduce:animate-none' + !active && 'animate-pulse motion-reduce:animate-none', + className )} > {DICTATION_GRAPES.map((grape, index) => { diff --git a/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx b/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx new file mode 100644 index 00000000000..bfffcc98cd5 --- /dev/null +++ b/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx @@ -0,0 +1,56 @@ +import { useMemo, useState } from 'react' +import { defineFixture } from '../../component-fixtures/component-fixture' +import { DictationIndicator } from './DictationIndicator' +import { publishDictationMeter, resetDictationMeter } from './dictation-meter-store' + +function PaneWithPill({ captureLive = true }: { captureLive?: boolean }) { + const [pane, setPane] = useState(null) + const anchor = useMemo( + () => (pane ? { element: pane, placement: 'over' as const } : null), + [pane] + ) + return ( +
+ {anchor ? : null} +
+ ) +} + +export const listening = defineFixture({ + width: 520, + store: { dictationState: 'listening' }, + setup: () => publishDictationMeter({ level: 0.5, isSpeaking: true, isClipping: false }), + render: () => +}) + +export const startingBeforeMic = defineFixture({ + width: 520, + store: { dictationState: 'starting' }, + setup: resetDictationMeter, + render: () => +}) + +export const liveText = defineFixture({ + width: 520, + store: { + dictationState: 'listening', + partialTranscript: + 'It should go back to the page you came from. Check where returnTo gets dropped' + }, + setup: () => publishDictationMeter({ level: 0.6, isSpeaking: true, isClipping: false }), + render: () => +}) + +export const tooLoud = defineFixture({ + width: 520, + store: { dictationState: 'listening' }, + setup: () => publishDictationMeter({ level: 1, isSpeaking: true, isClipping: true }), + render: () => +}) + +export const finishing = defineFixture({ + width: 520, + store: { dictationState: 'stopping' }, + setup: resetDictationMeter, + render: () => +}) diff --git a/src/renderer/src/components/dictation/DictationIndicator.tsx b/src/renderer/src/components/dictation/DictationIndicator.tsx index a231abedecf..3e396e959e1 100644 --- a/src/renderer/src/components/dictation/DictationIndicator.tsx +++ b/src/renderer/src/components/dictation/DictationIndicator.tsx @@ -1,114 +1,197 @@ +import { useEffect, useRef, useState } from 'react' import { ShortcutKeyCombo } from '@/components/ShortcutKeyCombo' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useShortcutKeyDetails } from '@/hooks/useShortcutLabel' import { useTranslate } from '@/i18n/use-translate' +import { KEEPS_FOCUS_ATTRIBUTE } from '@/lib/focus-keeping-press' +import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' import { cn } from '@/lib/utils' import { useAppStore } from '@/store' -import { Square } from 'lucide-react' +import { Check, Loader2, X } from 'lucide-react' +import { isDictationPillShown } from '../../../../shared/dictation-session-machine' import { dispatchDictationControl } from './dictation-control-events' import { DictationGrapes } from './DictationGrapes' import { useDictationMeter } from './dictation-meter-store' +import { useDictationPillBox, type DictationPillAnchor } from './dictation-pill-anchor' -// captureLive: the mic is recording (and buffering) while the speech engine is still starting. -export function DictationIndicator({ captureLive }: { captureLive: boolean }) { +// The finish button turns into a spinner only when finishing is slow enough to notice. +const FINISH_SPINNER_DELAY_MS = 200 + +type DictationIndicatorProps = { + /** The mic is recording (and buffering) while the speech engine is still starting. */ + captureLive: boolean + anchor: DictationPillAnchor | null +} + +export function DictationIndicator(props: DictationIndicatorProps) { + const dictationState = useAppStore((state) => state.dictationState) + return isDictationPillShown(dictationState) ? : null +} + +function formatElapsed(seconds: number): string { + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}` +} + +/** Seconds since `running` first turned on; holds still once it turns off. */ +function useElapsedSeconds(running: boolean): number { + const startedAtRef = useRef(null) + const [seconds, setSeconds] = useState(0) + useEffect(() => { + if (!running) { + return + } + if (startedAtRef.current === null) { + startedAtRef.current = performance.now() + } + const startedAt = startedAtRef.current + // Measured from the start, so ticks skipped while the window is hidden don't drift it. + return installWindowVisibilityInterval({ + run: () => setSeconds(Math.floor((performance.now() - startedAt) / 1000)), + intervalMs: 250 + }) + }, [running]) + return seconds +} + +function useDelayedFlag(on: boolean, delayMs: number): boolean { + const [delayed, setDelayed] = useState(false) + useEffect(() => { + if (!on) { + setDelayed(false) + return + } + const id = window.setTimeout(() => setDelayed(true), delayMs) + return () => window.clearTimeout(id) + }, [on, delayMs]) + return delayed +} + +// Only this re-renders per meter tick, not the whole pill. +function DictationPillMeter({ recording, status }: { recording: boolean; status: string }) { + const t = useTranslate() + const meter = useDictationMeter() + const clipping = recording && meter.isClipping + return ( + <> + + {clipping + ? t('auto.components.dictation.DictationIndicator.4977162383', 'Too loud') + : status} + + + + ) +} + +// Presses on the pill keep focus where the words are going. +const keepFocus = (event: React.MouseEvent): void => event.preventDefault() +const keepFocusProps = { [KEEPS_FOCUS_ATTRIBUTE]: '', onMouseDown: keepFocus } + +function DictationPill({ captureLive, anchor }: DictationIndicatorProps) { const t = useTranslate() const dictationState = useAppStore((state) => state.dictationState) const partialTranscript = useAppStore((state) => state.partialTranscript) - const dictationMeter = useDictationMeter() const isHoldMode = useAppStore((state) => state.settings?.voice?.dictationMode === 'hold') const shortcut = useShortcutKeyDetails('voice.dictation') + const box = useDictationPillBox(anchor) - const isVisible = ['listening', 'starting', 'stopping'].includes(dictationState) - if (!isVisible) { - return null - } - - const isLoadingModel = dictationState === 'starting' && captureLive - const isListening = dictationState === 'listening' || isLoadingModel - const isClipping = isListening && dictationMeter.isClipping - const isSpeaking = isListening && dictationMeter.isSpeaking && !isClipping - const lifecycleLabel = isListening - ? t('auto.components.dictation.DictationIndicator.3de5a129e7', 'Listening') - : dictationState === 'starting' - ? t('auto.components.dictation.DictationIndicator.7f3660a7ba', 'Starting mic…') - : t('auto.components.dictation.DictationIndicator.f082d0cb9d', 'Processing…') - const label = isClipping - ? t('auto.components.dictation.DictationIndicator.4977162383', 'Too loud') - : isSpeaking - ? t('auto.components.dictation.DictationIndicator.25f2b7a6a5', 'Speaking') - : lifecycleLabel - const announcedLabel = isClipping ? label : lifecycleLabel - const canStop = dictationState !== 'stopping' - const showShortcut = !isHoldMode && shortcut.keys.length > 0 + const finishing = dictationState === 'stopping' + const recording = dictationState === 'listening' || (dictationState === 'starting' && captureLive) + // Counts recorded time, so it waits for the mic to open. + const seconds = useElapsedSeconds(recording) + const showSpinner = useDelayedFlag(finishing, FINISH_SPINNER_DELAY_MS) const transcript = partialTranscript.trim() - const stopLabel = t('auto.components.dictation.DictationIndicator.335e1bc6cb', 'Stop dictation') + const status = finishing + ? t('auto.components.dictation.DictationIndicator.finishing', 'Finishing…') + : t('auto.components.dictation.DictationIndicator.listening', 'Listening…') + const cancelLabel = t('auto.components.dictation.DictationIndicator.cancel', 'Cancel') + const finishLabel = t('auto.components.dictation.DictationIndicator.finish', 'Finish') return (
-
- - - {label} - - {isLoadingModel ? ( - - {t( - 'auto.components.dictation.DictationIndicator.loadingModel', - 'Loading speech model…' - )} - - ) : null} - - {announcedLabel} - - {canStop ? ( - <> - - - - - - - {stopLabel} - {showShortcut ? ( - - ) : null} - - - - ) : null} -
+ + + + + + {cancelLabel} + + + {transcript ? ( -

- {transcript} -

- ) : null} + + {transcript} + + ) : ( + + {status} + + )} + + {formatElapsed(seconds)} + + {finishing ? ( + + {showSpinner ? ( + + ) : ( + + )} + + ) : ( + + + + + + + {finishLabel} + {!isHoldMode && shortcut.keys.length > 0 ? ( + + ) : null} + + + + )}
) } diff --git a/src/renderer/src/components/dictation/dictation-control-events.ts b/src/renderer/src/components/dictation/dictation-control-events.ts index df9ed811340..9dea9e131b3 100644 --- a/src/renderer/src/components/dictation/dictation-control-events.ts +++ b/src/renderer/src/components/dictation/dictation-control-events.ts @@ -3,7 +3,7 @@ export const DICTATION_CONTROL_EVENT = 'dictation:control' /** Dictation started with no text field focused; the pane that owns typing focuses its input. */ export const DICTATION_FOCUS_INPUT_EVENT = 'dictation:focusInput' -export type DictationControlAction = 'toggle' | 'start' | 'stop' +export type DictationControlAction = 'toggle' | 'start' | 'stop' | 'cancel' export function dispatchDictationControl(action: DictationControlAction): void { document.dispatchEvent( diff --git a/src/renderer/src/components/dictation/dictation-insertion-target.ts b/src/renderer/src/components/dictation/dictation-insertion-target.ts index ff4ff69141c..ace14f22e96 100644 --- a/src/renderer/src/components/dictation/dictation-insertion-target.ts +++ b/src/renderer/src/components/dictation/dictation-insertion-target.ts @@ -16,8 +16,8 @@ type ComposerInsert = (text: string) => boolean type TerminalInsert = (text: string, paneId: number) => Promise export type DictationInsertionTarget = - | { kind: 'composer'; insert: ComposerInsert } - | { kind: 'terminal'; tabId: string; paneId: number } + | { kind: 'composer'; insert: ComposerInsert; root: HTMLElement } + | { kind: 'terminal'; tabId: string; paneId: number; pane: HTMLElement } | { kind: 'text'; element: HTMLInputElement | HTMLTextAreaElement } | { kind: 'contentEditable'; element: HTMLElement } @@ -65,8 +65,8 @@ function readFocusedInsertionTarget(): DictationInsertionTarget | null { for (let root: Element | null = activeElement; root; root = root.parentElement) { const insert = root instanceof HTMLElement ? composerTargets.get(root) : undefined - if (insert) { - return { kind: 'composer', insert } + if (insert && root instanceof HTMLElement) { + return { kind: 'composer', insert, root } } } @@ -75,8 +75,8 @@ function readFocusedInsertionTarget(): DictationInsertionTarget | null { const tabElement = activeElement.closest('[data-terminal-tab-id]') as HTMLElement | null const paneId = Number(paneElement?.dataset.paneId) const tabId = tabElement?.dataset.terminalTabId - if (tabId && Number.isFinite(paneId)) { - return { kind: 'terminal', tabId, paneId } + if (paneElement && tabId && Number.isFinite(paneId)) { + return { kind: 'terminal', tabId, paneId, pane: paneElement } } return null } diff --git a/src/renderer/src/components/dictation/dictation-pill-anchor.ts b/src/renderer/src/components/dictation/dictation-pill-anchor.ts new file mode 100644 index 00000000000..5fff470ecb1 --- /dev/null +++ b/src/renderer/src/components/dictation/dictation-pill-anchor.ts @@ -0,0 +1,63 @@ +import { useLayoutEffect, useState } from 'react' +import type { DictationInsertionTarget } from './dictation-insertion-target' + +/** The pane the words go to; the pill floats over its bottom edge, or just above a chat composer. */ +export type DictationPillAnchor = { element: HTMLElement; placement: 'over' | 'above' } + +/** Fixed-position box: `left` is the pill's centre, `bottom` its distance from the window's bottom edge. */ +type DictationPillBox = { left: number; bottom: number; width: number } + +const PILL_MAX_WIDTH = 440 +const PANE_INSET = 16 +const OVER_GAP = 12 +const ABOVE_GAP = 8 + +export function dictationPillAnchorFor( + target: DictationInsertionTarget | null +): DictationPillAnchor | null { + if (target?.kind === 'composer') { + return { element: target.root, placement: 'above' } + } + if (target?.kind === 'terminal') { + return { element: target.pane, placement: 'over' } + } + return null +} + +function readPillBox(anchor: DictationPillAnchor): DictationPillBox | null { + const { element, placement } = anchor + if (!element.isConnected || !element.checkVisibility({ visibilityProperty: true })) { + return null + } + const rect = element.getBoundingClientRect() + if (rect.width <= PANE_INSET * 2 || rect.height === 0) { + return null + } + const edge = placement === 'above' ? rect.top - ABOVE_GAP : rect.bottom - OVER_GAP + return { + left: rect.left + rect.width / 2, + bottom: window.innerHeight - edge, + width: Math.min(PILL_MAX_WIDTH, rect.width - PANE_INSET * 2) + } +} + +/** Follows the anchor pane's size; once it's hidden or gone, null puts the pill at the window's bottom centre. */ +export function useDictationPillBox(anchor: DictationPillAnchor | null): DictationPillBox | null { + const [box, setBox] = useState(null) + useLayoutEffect(() => { + if (!anchor) { + setBox(null) + return + } + const update = (): void => setBox(readPillBox(anchor)) + update() + const observer = new ResizeObserver(update) + observer.observe(anchor.element) + window.addEventListener('resize', update) + return () => { + observer.disconnect() + window.removeEventListener('resize', update) + } + }, [anchor]) + return box +} diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-focus-lifecycle.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-focus-lifecycle.ts index b3091e66d6c..eee2d5b02b4 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-focus-lifecycle.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-focus-lifecycle.ts @@ -1,5 +1,6 @@ import { useEffect } from 'react' import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' +import { isFocusKeepingPress } from '@/lib/focus-keeping-press' import { clearFloatingPanelReclaimIntent } from '@/lib/floating-workspace-focus-reclaim' import { isFloatingWorkspaceTerminalInputTarget } from '@/lib/floating-workspace-terminal-actions' import { reportFloatingFocus } from './floating-terminal-focus-reporting' @@ -34,7 +35,12 @@ export function useFloatingTerminalFocusLifecycle({ } const handleOutsidePointerDown = (event: PointerEvent): void => { const panel = panelRef.current - if (!panel || !(event.target instanceof Node) || panel.contains(event.target)) { + if ( + !panel || + !(event.target instanceof Node) || + panel.contains(event.target) || + isFocusKeepingPress(event.target) + ) { return } reportFloatingFocus(null, true) diff --git a/src/renderer/src/components/terminal-pane/input/focus/regular-terminal-focus-ownership.test.ts b/src/renderer/src/components/terminal-pane/input/focus/regular-terminal-focus-ownership.test.ts index 99636a94030..5ca21a867ad 100644 --- a/src/renderer/src/components/terminal-pane/input/focus/regular-terminal-focus-ownership.test.ts +++ b/src/renderer/src/components/terminal-pane/input/focus/regular-terminal-focus-ownership.test.ts @@ -1,7 +1,9 @@ // @vitest-environment happy-dom import { beforeEach, describe, expect, it, vi } from 'vitest' +import { KEEPS_FOCUS_ATTRIBUTE } from '@/lib/focus-keeping-press' import { REGULAR_TERMINAL_INPUT_FOCUSED_ATTRIBUTE, + releaseTerminalFocusForOutsidePointerDown, releaseTerminalFocusForWindowBlur, resyncTerminalFocusForWindowFocus } from './regular-terminal-focus-ownership' @@ -25,6 +27,29 @@ describe('regular terminal focus ownership', () => { document.documentElement.removeAttribute(REGULAR_TERMINAL_INPUT_FOCUSED_ATTRIBUTE) }) + it('keeps terminal focus for a press on a focus-keeping control, and releases it elsewhere', () => { + const pane = appendPane() + const helper = appendHelper(pane) + const pill = document.createElement('div') + pill.setAttribute(KEEPS_FOCUS_ATTRIBUTE, '') + const pillButton = document.createElement('button') + pill.appendChild(pillButton) + document.body.append(pill) + helper.focus() + const press = (pointerTarget: EventTarget) => + releaseTerminalFocusForOutsidePointerDown({ + container: pane, + activeElement: document.activeElement, + pointerTarget, + syncFocused: vi.fn() + }) + + expect(press(pillButton)).toBe(false) + expect(document.activeElement).toBe(helper) + expect(press(document.body)).toBe(true) + expect(document.activeElement).not.toBe(helper) + }) + it('reclaims the exact split helper that was released, not the first one in the container', () => { // Split helpers are siblings in one container; first-match lookup would reclaim the wrong pane. const pane = appendPane() diff --git a/src/renderer/src/components/terminal-pane/input/focus/regular-terminal-focus-ownership.ts b/src/renderer/src/components/terminal-pane/input/focus/regular-terminal-focus-ownership.ts index 8ce8155a92d..a321e5be807 100644 --- a/src/renderer/src/components/terminal-pane/input/focus/regular-terminal-focus-ownership.ts +++ b/src/renderer/src/components/terminal-pane/input/focus/regular-terminal-focus-ownership.ts @@ -1,3 +1,4 @@ +import { isFocusKeepingPress } from '@/lib/focus-keeping-press' import { isDocumentBodyOrNull, refreshTerminalImeInputContext, @@ -40,7 +41,10 @@ export function releaseTerminalFocusForOutsidePointerDown(args: { return false } - if (isNode(args.pointerTarget) && args.container.contains(args.pointerTarget)) { + if ( + (isNode(args.pointerTarget) && args.container.contains(args.pointerTarget)) || + isFocusKeepingPress(args.pointerTarget) + ) { return false } diff --git a/src/renderer/src/components/ui/button.tsx b/src/renderer/src/components/ui/button.tsx index 2be6f6289e7..a6a3d71a5df 100644 --- a/src/renderer/src/components/ui/button.tsx +++ b/src/renderer/src/components/ui/button.tsx @@ -39,6 +39,8 @@ const buttonVariants = cva( lg: 'h-10 rounded-md px-6 has-[>svg]:px-4', icon: 'size-9', 'icon-xs': "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3", + // The dictation pill's round finish button. + 'icon-xs-round': "size-6 rounded-full [&_svg:not([class*='size-'])]:size-3", 'icon-sm': 'size-8', 'icon-lg': 'size-10', // As tall as the composer's round Send button, so swapping between them keeps the row's height. diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 367bdc35b79..19efd403491 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -16983,13 +16983,7 @@ "lost": "Das Diktat konnte weder eingefügt noch kopiert werden." }, "DictationIndicator": { - "335e1bc6cb": "Diktat stoppen", - "7f3660a7ba": "Mikrofon wird gestartet…", - "f082d0cb9d": "Wird verarbeitet…", - "3de5a129e7": "Hört zu", - "4977162383": "Zu laut", - "25f2b7a6a5": "Sprache erkannt", - "loadingModel": "Sprachmodell wird geladen…" + "4977162383": "Zu laut" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 833c167c175..54fb1287966 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -17403,13 +17403,11 @@ "lost": "Dictation couldn't be inserted or copied." }, "DictationIndicator": { - "335e1bc6cb": "Stop dictation", - "7f3660a7ba": "Starting mic…", - "f082d0cb9d": "Processing…", - "3de5a129e7": "Listening", "4977162383": "Too loud", - "25f2b7a6a5": "Speaking", - "loadingModel": "Loading speech model…" + "finishing": "Finishing…", + "listening": "Listening…", + "cancel": "Cancel", + "finish": "Finish" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 6034484db33..c9374061e0a 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -16710,13 +16710,7 @@ "lost": "No se pudo insertar ni copiar el dictado." }, "DictationIndicator": { - "335e1bc6cb": "Detener dictado", - "7f3660a7ba": "Iniciando micrófono…", - "f082d0cb9d": "Procesando…", - "3de5a129e7": "Escuchando", - "4977162383": "Volumen demasiado alto", - "25f2b7a6a5": "Hablando", - "loadingModel": "Cargando modelo de voz…" + "4977162383": "Volumen demasiado alto" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index df636858aa9..0cc2a499b89 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -16935,13 +16935,7 @@ "lost": "La dictée n'a pu être ni insérée ni copiée." }, "DictationIndicator": { - "335e1bc6cb": "Arrêter la dictée", - "7f3660a7ba": "Démarrage du micro…", - "f082d0cb9d": "Traitement…", - "3de5a129e7": "Écoute en cours", - "4977162383": "Trop fort", - "25f2b7a6a5": "Vous parlez", - "loadingModel": "Chargement du modèle vocal…" + "4977162383": "Trop fort" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index c313f761432..b8623ebda27 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -16307,13 +16307,7 @@ "lost": "音声入力を挿入もコピーもできませんでした。" }, "DictationIndicator": { - "335e1bc6cb": "ディクテーションを停止する", - "7f3660a7ba": "マイクを起動中…", - "f082d0cb9d": "処理中…", - "3de5a129e7": "聞き取り中", - "4977162383": "音量が大きすぎます", - "25f2b7a6a5": "発話中", - "loadingModel": "音声モデルを読み込み中…" + "4977162383": "音量が大きすぎます" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index a0b346b5d35..72076ace398 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -16307,13 +16307,7 @@ "lost": "받아쓰기를 삽입하거나 복사할 수 없습니다." }, "DictationIndicator": { - "335e1bc6cb": "받아쓰기 중지", - "7f3660a7ba": "마이크 시작 중…", - "f082d0cb9d": "처리 중…", - "3de5a129e7": "듣는 중", - "4977162383": "음량이 너무 큽니다", - "25f2b7a6a5": "말하는 중", - "loadingModel": "음성 모델 불러오는 중…" + "4977162383": "음량이 너무 큽니다" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 98e2337c57f..140f629d103 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -19268,13 +19268,7 @@ "lost": "Não foi possível inserir nem copiar o ditado." }, "DictationIndicator": { - "335e1bc6cb": "Parar ditado", - "7f3660a7ba": "Iniciando microfone…", - "f082d0cb9d": "Processando…", - "3de5a129e7": "Ouvindo", - "4977162383": "Muito alto", - "25f2b7a6a5": "Falando", - "loadingModel": "Carregando modelo de fala…" + "4977162383": "Muito alto" } }, "link": { diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 045d9c4b614..f717776e4f7 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -17481,13 +17481,7 @@ "lost": "Не удалось ни вставить, ни скопировать диктовку." }, "DictationIndicator": { - "335e1bc6cb": "Остановить диктовку", - "7f3660a7ba": "Включение микрофона…", - "f082d0cb9d": "Обработка…", - "3de5a129e7": "Прослушивание", - "4977162383": "Слишком громко", - "25f2b7a6a5": "Речь", - "loadingModel": "Загрузка модели речи…" + "4977162383": "Слишком громко" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 80cec422bfa..a1ed138def4 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -16967,13 +16967,7 @@ "lost": "Dikte eklenemedi ve kopyalanamadı." }, "DictationIndicator": { - "335e1bc6cb": "Dikteyi durdur", - "7f3660a7ba": "Mikrofon başlatılıyor…", - "f082d0cb9d": "İşleniyor…", - "3de5a129e7": "Dinliyor", - "4977162383": "Çok yüksek sesli", - "25f2b7a6a5": "Konuşuyor", - "loadingModel": "Konuşma modeli yükleniyor…" + "4977162383": "Çok yüksek sesli" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index b41c6393219..2b2f51a0d7c 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -16756,13 +16756,7 @@ "lost": "無法插入或複製聽寫內容。" }, "DictationIndicator": { - "335e1bc6cb": "停止聽寫", - "7f3660a7ba": "啟動麥克風...", - "f082d0cb9d": "正在處理…", - "3de5a129e7": "正在聆聽", - "4977162383": "聲音太大", - "25f2b7a6a5": "正在說話", - "loadingModel": "正在載入語音模型…" + "4977162383": "聲音太大" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index d0d9d11b70d..1e0ae4fc103 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -16307,13 +16307,7 @@ "lost": "无法插入或复制听写内容。" }, "DictationIndicator": { - "335e1bc6cb": "停止听写", - "7f3660a7ba": "正在启动麦克风…", - "f082d0cb9d": "正在处理…", - "3de5a129e7": "正在聆听", - "4977162383": "音量过大", - "25f2b7a6a5": "正在说话", - "loadingModel": "正在加载语音模型…" + "4977162383": "音量过大" } }, "dashboard": { diff --git a/src/renderer/src/lib/app-keyboard-router.test.ts b/src/renderer/src/lib/app-keyboard-router.test.ts index f8887db1767..5e5ef74f943 100644 --- a/src/renderer/src/lib/app-keyboard-router.test.ts +++ b/src/renderer/src/lib/app-keyboard-router.test.ts @@ -77,6 +77,22 @@ describe('app keyboard router', () => { ]) }) + it('runs a first owner ahead of owners registered before it', () => { + const seen: string[] = [] + onApp((event) => { + seen.push('overlay') + event.stopImmediatePropagation() + }) + const dictation = (event: KeyboardEvent): void => { + seen.push('dictation') + event.stopImmediatePropagation() + } + addAppKeyListener('keydown', dictation, { first: true }) + cleanups.push(() => removeAppKeyListener('keydown', dictation)) + const tail = press() + expect([...seen, ...tail]).toEqual(['dictation']) + }) + it('keeps native stop semantics between app owners', () => { const seen: string[] = [] onApp((event) => { diff --git a/src/renderer/src/lib/app-keyboard-router.ts b/src/renderer/src/lib/app-keyboard-router.ts index 261cb5e1bcd..c1e1721b815 100644 --- a/src/renderer/src/lib/app-keyboard-router.ts +++ b/src/renderer/src/lib/app-keyboard-router.ts @@ -57,13 +57,22 @@ export function replayAppKeyDown(event: KeyboardEvent): void { dispatch('keydown', event) } -export function addAppKeyListener(type: AppKeyEventType, listener: AppKeyListener): void { +/** `first` runs the owner ahead of every other one, for a key that must win wherever focus is. */ +export function addAppKeyListener( + type: AppKeyEventType, + listener: AppKeyListener, + options: { first?: boolean } = {} +): void { installAppKeyboardRouter(installedOn ?? window) const list = registrations[type] if (list.some((registration) => registration.active && registration.listener === listener)) { return } - list.push({ listener, active: true }) + if (options.first) { + list.unshift({ listener, active: true }) + } else { + list.push({ listener, active: true }) + } } export function removeAppKeyListener(type: AppKeyEventType, listener: AppKeyListener): void { diff --git a/src/renderer/src/lib/focus-keeping-press.ts b/src/renderer/src/lib/focus-keeping-press.ts new file mode 100644 index 00000000000..6ec99999288 --- /dev/null +++ b/src/renderer/src/lib/focus-keeping-press.ts @@ -0,0 +1,6 @@ +/** Marks a control whose presses leave focus where it is, so outside-press focus release skips it. */ +export const KEEPS_FOCUS_ATTRIBUTE = 'data-keeps-focus' + +export function isFocusKeepingPress(target: EventTarget | null): boolean { + return target instanceof Element && target.closest(`[${KEEPS_FOCUS_ATTRIBUTE}]`) !== null +} diff --git a/src/renderer/src/web/preload-api/web-speech-api.ts b/src/renderer/src/web/preload-api/web-speech-api.ts index 0ef25a5bfa8..a4c0152ba1d 100644 --- a/src/renderer/src/web/preload-api/web-speech-api.ts +++ b/src/renderer/src/web/preload-api/web-speech-api.ts @@ -84,6 +84,7 @@ export function createWebSpeechApi(): Pick< | 'startDictation' | 'feedAudio' | 'stopDictation' + | 'cancelDictation' | 'onPartialTranscript' | 'onFinalTranscript' | 'onStopped' @@ -152,6 +153,10 @@ export function createWebSpeechApi(): Pick< active = dictation try { await callRuntimeResult('speech.dictation.start', { dictationId: dictation.dictationId }) + // A cancel that landed while the host was starting couldn't reach this dictation yet. + if (active !== dictation) { + void cancelOnHost(dictation) + } } catch (error) { if (active === dictation) { active = null @@ -213,6 +218,17 @@ export function createWebSpeechApi(): Pick< emit(stoppedListeners, { sessionId }) } }, + cancelDictation: async (sessionId) => { + const dictation = active?.sessionId === sessionId ? active : null + if (!dictation) { + return + } + active = null + dictation.failed = true + dictation.pending = [] + await cancelOnHost(dictation) + emit(stoppedListeners, { sessionId }) + }, onPartialTranscript: (callback) => subscribe(partialListeners, callback), onFinalTranscript: (callback) => subscribe(finalListeners, callback), onStopped: (callback) => subscribe(stoppedListeners, callback), diff --git a/src/shared/dictation-session-machine.test.ts b/src/shared/dictation-session-machine.test.ts index 7aa45c3e0f7..975f586efe1 100644 --- a/src/shared/dictation-session-machine.test.ts +++ b/src/shared/dictation-session-machine.test.ts @@ -31,4 +31,10 @@ describe('transitionDictationSession', () => { expect(restarted.phase).toBe('starting') expect(restarted.sessionId).not.toBe(listening.sessionId) }) + + it('ignores a cancel once an engine error dropped the session, so no start races its teardown', () => { + const abandoned = run('start', 'engine-ready', 'abandon') + expect(transitionDictationSession(abandoned, { type: 'cancel' })).toBe(abandoned) + expect(run('start', 'engine-ready', 'cancel')).toMatchObject({ phase: 'idle', sessionId: null }) + }) }) diff --git a/src/shared/dictation-session-machine.ts b/src/shared/dictation-session-machine.ts index 79c300c42db..22ceabc346c 100644 --- a/src/shared/dictation-session-machine.ts +++ b/src/shared/dictation-session-machine.ts @@ -20,7 +20,7 @@ export type DictationSessionEvent = | { type: 'abandon' } /** Starting failed: drop the session and show the error. */ | { type: 'fail' } - /** Drop the session without finishing it. */ + /** Drop the live session without finishing it; its words still in flight are never inserted. */ | { type: 'cancel' } /** Teardown finished; back to idle. */ | { type: 'ended' } @@ -40,6 +40,11 @@ export function isDictationUnderway(phase: DictationState): boolean { return phase === 'starting' || phase === 'listening' } +/** The pill shows from start until the last words land, including while a dropped session tears down. */ +export function isDictationPillShown(phase: DictationState): boolean { + return isDictationUnderway(phase) || phase === 'stopping' +} + /** Returns the same object when the event does not apply, so callers can skip its effects. */ export function transitionDictationSession( session: DictationSession, @@ -64,6 +69,8 @@ export function transitionDictationSession( case 'fail': return dropSession(session, 'error') case 'cancel': + // A dropped session is already tearing down; idle comes with its 'ended'. + return session.sessionId === null ? session : dropSession(session, 'idle') case 'ended': return dropSession(session, 'idle') } From f36751f79ff58a925003089a626243966e543322 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:10:35 -0800 Subject: [PATCH 02/10] Revert "feat(cli): create workspaces on environment recipes (#40108)" (#40184) This reverts commit 862d315575526dab1d3658e04f2076ec117edc3f. --- skill-guides/orca-cli.md | 12 - src/cli/bundled-skill-guides.ts | 12 - src/cli/handlers/vm-recipe-list.ts | 54 --- src/cli/handlers/worktree-create-recipe.ts | 191 --------- .../handlers/worktree-create-startup-agent.ts | 20 - src/cli/handlers/worktree.ts | 24 +- src/cli/host-handler-groups.ts | 5 - src/cli/index-worktree-create-recipe.test.ts | 330 --------------- src/cli/root-help-text-primary.ts | 1 - src/cli/runtime/client.ts | 3 +- src/cli/runtime/transport.test.ts | 42 -- src/cli/runtime/transport.ts | 11 +- src/cli/runtime/types.ts | 5 +- src/cli/specs/vm.ts | 14 +- src/cli/specs/worktree-create.ts | 8 +- src/main/ephemeral-vm/cli-workspace-create.ts | 179 -------- .../environment-provision-repo.test.ts | 40 -- .../ephemeral-vm/environment-provision.ts | 234 ----------- .../ephemeral-vm/owned-runtime-cleanup.ts | 82 ---- .../recipe-workspace-create-params.ts | 100 ----- .../recipe-workspace-create.test.ts | 387 ------------------ .../ephemeral-vm/recipe-workspace-create.ts | 248 ----------- src/main/ipc/ephemeral-vm-runtime-handlers.ts | 79 +++- src/main/ipc/ephemeral-vm.ts | 215 +++++++++- src/main/runtime/hosts/runtime-status.ts | 11 +- .../runtime-remote-fetch-operations.ts | 4 +- src/main/runtime/rpc/core.ts | 3 - .../runtime/rpc/dispatcher-stream-options.ts | 2 - src/main/runtime/rpc/errors.ts | 20 +- .../agent-launch-target-authorization.ts | 13 +- .../workspaces/vm-recipe-list-method.ts | 12 - .../worktree-provisioned-root-method.ts | 15 +- .../worktree-recipe-create-method.test.ts | 107 ----- .../rpc/methods/workspaces/worktree.ts | 20 - .../rpc/server/runtime-rpc-long-poll.ts | 9 - .../server/runtime-rpc-request-admission.ts | 1 - src/main/runtime/rpc/transport.ts | 4 - .../runtime/rpc/unix-socket-transport.test.ts | 21 - src/main/runtime/rpc/unix-socket-transport.ts | 11 +- .../runtime-recipe-workspace-creation.ts | 77 ---- .../startup/main-process-runtime-service.ts | 16 - .../catalog/provisioned-root-checkout.ts | 8 +- src/shared/host-runtime-capabilities.ts | 2 - .../recipe-workspace-create-progress.ts | 53 --- .../rpc-params-catalog.generated.ts | 2 - src/shared/rpc-contract/vm-recipe-params.ts | 5 - .../rpc-contract/worktree-create-params.ts | 1 - .../worktree-provisioned-root-params.ts | 1 - src/shared/runtime-rpc-envelope.ts | 8 +- 49 files changed, 320 insertions(+), 2402 deletions(-) delete mode 100644 src/cli/handlers/vm-recipe-list.ts delete mode 100644 src/cli/handlers/worktree-create-recipe.ts delete mode 100644 src/cli/handlers/worktree-create-startup-agent.ts delete mode 100644 src/cli/index-worktree-create-recipe.test.ts delete mode 100644 src/main/ephemeral-vm/cli-workspace-create.ts delete mode 100644 src/main/ephemeral-vm/environment-provision-repo.test.ts delete mode 100644 src/main/ephemeral-vm/environment-provision.ts delete mode 100644 src/main/ephemeral-vm/owned-runtime-cleanup.ts delete mode 100644 src/main/ephemeral-vm/recipe-workspace-create-params.ts delete mode 100644 src/main/ephemeral-vm/recipe-workspace-create.test.ts delete mode 100644 src/main/ephemeral-vm/recipe-workspace-create.ts delete mode 100644 src/main/runtime/rpc/methods/workspaces/vm-recipe-list-method.ts delete mode 100644 src/main/runtime/rpc/methods/workspaces/worktree-recipe-create-method.test.ts delete mode 100644 src/main/runtime/workspaces/creation/runtime-recipe-workspace-creation.ts delete mode 100644 src/shared/recipe-workspace-create-progress.ts delete mode 100644 src/shared/rpc-contract/vm-recipe-params.ts diff --git a/skill-guides/orca-cli.md b/skill-guides/orca-cli.md index bbf93088124..523f0ec335b 100644 --- a/skill-guides/orca-cli.md +++ b/skill-guides/orca-cli.md @@ -153,18 +153,6 @@ Lineage rules: - To move an existing worktree under a different parent, or make it top-level, use `worktree set` with `--parent-worktree ` or `--no-parent`. - `--no-parent` only controls Orca lineage; it does not choose the Git base. For independent top-level work, omit `--base-branch` so Orca uses the repo default base, or explicitly pass the repo default base. Never base it on the current feature branch unless the user asks for stacked work or "branch from current". -Per-workspace environment recipes: `ORCA vm recipe list --repo id: --json` lists the -recipes `--recipe` accepts. `ORCA worktree create --name task --recipe --no-parent --json` -runs the recipe's create step and creates the workspace on the new environment's Orca server. Run -it on the computer whose Orca desktop app owns the recipe; omit `--environment` and `--pairing-code`. -It can take minutes; without `--json`, named progress steps print to stderr. Provisioned-root recipes -own setup, so `--setup run` and `--run-hooks` are refused for them. Add `--agent`, `--prompt`, -`--model`, or `--effort` to launch on the new environment. The result's `recipe.environmentId` is the -environment for follow-up commands (`--environment id:`). On failure the error code is -`recipe_workspace_create_failed`; `data.phase` names the failed step and `data.environment` says -whether Orca destroyed the new environment. Never retry with `--retry-launch`; after a failed agent -launch, use the returned `agent launch` recovery command against the existing workspace. - Agent/setup flags: ```text diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 4d3bb13d694..c5d92714523 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -381,18 +381,6 @@ const ORCA_CLI_MARKDOWN = [ "- To move an existing worktree under a different parent, or make it top-level, use `worktree set` with `--parent-worktree ` or `--no-parent`.", "- `--no-parent` only controls Orca lineage; it does not choose the Git base. For independent top-level work, omit `--base-branch` so Orca uses the repo default base, or explicitly pass the repo default base. Never base it on the current feature branch unless the user asks for stacked work or \"branch from current\".", "", - "Per-workspace environment recipes: `ORCA vm recipe list --repo id: --json` lists the", - "recipes `--recipe` accepts. `ORCA worktree create --name task --recipe --no-parent --json`", - "runs the recipe's create step and creates the workspace on the new environment's Orca server. Run", - "it on the computer whose Orca desktop app owns the recipe; omit `--environment` and `--pairing-code`.", - "It can take minutes; without `--json`, named progress steps print to stderr. Provisioned-root recipes", - "own setup, so `--setup run` and `--run-hooks` are refused for them. Add `--agent`, `--prompt`,", - "`--model`, or `--effort` to launch on the new environment. The result's `recipe.environmentId` is the", - "environment for follow-up commands (`--environment id:`). On failure the error code is", - "`recipe_workspace_create_failed`; `data.phase` names the failed step and `data.environment` says", - "whether Orca destroyed the new environment. Never retry with `--retry-launch`; after a failed agent", - "launch, use the returned `agent launch` recovery command against the existing workspace.", - "", "Agent/setup flags:", "", "```text", diff --git a/src/cli/handlers/vm-recipe-list.ts b/src/cli/handlers/vm-recipe-list.ts deleted file mode 100644 index f481fcebb49..00000000000 --- a/src/cli/handlers/vm-recipe-list.ts +++ /dev/null @@ -1,54 +0,0 @@ -import type { CommandHandler } from '../dispatch' -import type { RecipeCatalogListing } from '../../shared/recipe-workspace-create-progress' -import { assertRecipeHost } from './worktree-create-recipe' -import { getOptionalStringFlag } from '../flags' -import { printResult } from '../format' - -export function formatRecipeListing(result: { repos: RecipeCatalogListing[] }): string { - if (result.repos.length === 0) { - return 'No environment recipes. Add environmentRecipes to a repo orca.yaml.' - } - const lines: string[] = [] - for (const repo of result.repos) { - lines.push(`${repo.repoName} (${repo.repoPath})`) - if (repo.recipes.length === 0) { - lines.push(' no recipes') - } - for (const recipe of repo.recipes) { - const destroy = recipe.destroyDisabled - ? 'destroy disabled' - : recipe.steps.includes('destroy') - ? 'destroys on removal' - : 'no destroy step' - const timeouts = recipe.timeoutSeconds - ? Object.entries(recipe.timeoutSeconds) - .map(([step, seconds]) => `${step} ${seconds}s`) - .join(', ') - : '' - lines.push( - ` ${recipe.id} ${recipe.name} [${recipe.checkoutMode}; ${destroy}${timeouts ? `; timeouts ${timeouts}` : ''}]` - ) - if (recipe.description) { - lines.push(` ${recipe.description}`) - } - } - for (const diagnostic of repo.diagnostics) { - lines.push( - ` warning: environmentRecipes[${diagnostic.index}]${diagnostic.field ? `.${diagnostic.field}` : ''}: ${diagnostic.message}` - ) - } - } - return lines.join('\n') -} - -export const VM_RECIPE_LIST_HANDLERS: Record = { - 'vm recipe list': async ({ flags, client, json }) => { - await assertRecipeHost(client) - const repo = getOptionalStringFlag(flags, 'repo') - const result = await client.call<{ repos: RecipeCatalogListing[] }>( - 'vmRecipe.list', - repo ? { repo } : {} - ) - printResult(result, json, formatRecipeListing) - } -} diff --git a/src/cli/handlers/worktree-create-recipe.ts b/src/cli/handlers/worktree-create-recipe.ts deleted file mode 100644 index 5082f02f2ea..00000000000 --- a/src/cli/handlers/worktree-create-recipe.ts +++ /dev/null @@ -1,191 +0,0 @@ -import type { RuntimeStatus, RuntimeWorktreeCreateResult } from '../../shared/runtime-types' -import { WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY } from '../../shared/host-runtime-capabilities' -import { - RECIPE_WORKSPACE_CREATE_FAILED_CODE, - RECIPE_WORKSPACE_CREATE_PHASES, - isRecipeWorkspaceCreatePhase -} from '../../shared/recipe-workspace-create-progress' -import { RuntimeClient, RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client' -import { - callAgentLaunch, - formatAgentLaunch, - getAgentLaunchCapabilities, - type CliAgentLaunch -} from '../agent-launch-request' -import { formatWorktreeShow, printResult } from '../format' -import { printHookWarning } from './worktree-removal-warnings' -import { printLineageSummary } from './worktree-lineage-summary' - -// Idle bound only: the host sends a keepalive every few seconds while the recipe runs, and the -// recipe's own timeoutSeconds (orca.yaml) bounds the whole create. -const RECIPE_CREATE_IDLE_TIMEOUT_MS = 600_000 - -type RecipeWorktreeCreateResult = RuntimeWorktreeCreateResult & { - recipe: { id: string; runtimeId: string; environmentId: string; checkoutMode: string } - environmentWarnings?: string[] -} - -function formatRecipeCreated(value: RecipeWorktreeCreateResult): string { - return [ - formatWorktreeShow(value), - `recipe: ${value.recipe.id} (${value.recipe.checkoutMode})`, - `environment: ${value.recipe.environmentId}`, - ...(value.environmentWarnings ?? []).map((warning) => `warning: ${warning}`) - ].join('\n') -} - -/** Recipes run only where the Orca desktop app owns them; refuse before anything is created. */ -export async function assertRecipeHost(client: RuntimeClient): Promise { - if (client.isRemote) { - throw new RuntimeClientError( - 'invalid_argument', - 'Run recipe commands on the computer whose Orca provisions the recipe, without --environment or --pairing-code.' - ) - } - const status = await client.call('status.get') - if (!status.result.capabilities?.includes(WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY)) { - throw new RuntimeClientError( - 'incompatible_runtime', - 'This Orca cannot create workspaces from recipes. Use the Orca desktop app on this computer, updated to the latest version.' - ) - } -} - -/** `orca worktree create --recipe`: the host that owns the recipe provisions, then adopts. */ -export async function createWorktreeOnRecipe(args: { - client: RuntimeClient - flags: Map - create: Record - recipeId: string - launch?: CliAgentLaunch - json: boolean -}): Promise { - const { client, create, recipeId, launch, json, flags } = args - const parentFlag = ['parent-worktree', 'parent-environment'].find((name) => flags.has(name)) - if (parentFlag) { - throw new RuntimeClientError( - 'invalid_argument', - `--${parentFlag} is not supported with --recipe yet: the new workspace lives on another host, so Orca records no parent for it.` - ) - } - if (flags.get('activate') === true) { - throw new RuntimeClientError( - 'invalid_argument', - '--activate is not supported with --recipe yet; open the new workspace from the Orca sidebar.' - ) - } - if (launch?.operationId) { - throw new RuntimeClientError( - 'invalid_argument', - 'Retry the agent with `orca agent launch` on the recipe environment and existing workspace; --retry-launch would provision another machine.' - ) - } - await assertRecipeHost(client) - if (!json) { - console.error( - `Creating "${String(create.name)}" on a new environment from recipe "${recipeId}". This can take several minutes; Ctrl+C stops it.` - ) - } - let created: RuntimeRpcSuccess - try { - created = await client.call( - 'worktree.create', - { - // --run-hooks implies activation, which a recipe workspace on another host cannot do yet. - ...create, - activate: false, - navigation: undefined, - recipeId, - ...(launch ? { createdWithAgent: launch.agent } : {}) - }, - { - timeoutMs: RECIPE_CREATE_IDLE_TIMEOUT_MS, - onProgress: ({ phase }) => { - if (!json && isRecipeWorkspaceCreatePhase(phase)) { - console.error(`- ${RECIPE_WORKSPACE_CREATE_PHASES[phase]}...`) - } - } - } - ) - } catch (error) { - if (error instanceof RuntimeClientError && error.code === RECIPE_WORKSPACE_CREATE_FAILED_CODE) { - throw new RuntimeClientError(error.code, error.message, { - ...(typeof error.data === 'object' && error.data !== null ? error.data : {}), - nextSteps: [ - `Validate the recipe with \`orca vm recipe doctor ${recipeId}\`.`, - 'Check Settings > Cloud VMs in Orca for an environment that still needs cleanup.' - ] - }) - } - throw error - } - printHookWarning(created.result, json) - if (!launch) { - printLineageSummary(created.result, json) - printResult(created, json, formatRecipeCreated) - return - } - const environmentId = created.result.recipe.environmentId - const worktree = `id:${created.result.worktree.id}` - const remote = new RuntimeClient( - client.userDataPath, - RECIPE_CREATE_IDLE_TIMEOUT_MS, - null, - `id:${environmentId}` - ) - const recoveryArgs = [ - 'agent', - 'launch', - '--agent', - launch.agent, - '--worktree', - worktree, - '--environment', - `id:${environmentId}` - ] - for (const name of ['model', 'effort', 'surface']) { - const value = flags.get(name) - if (typeof value === 'string') { - recoveryArgs.push(`--${name}`, value) - } - } - if (launch.prompt) { - recoveryArgs.push('--prompt', launch.prompt.text) - } - try { - const capabilities = await getAgentLaunchCapabilities(remote) - if (!capabilities) { - throw new RuntimeClientError( - 'incompatible_runtime', - 'Update Orca on the recipe-created environment to launch an agent.' - ) - } - const launched = await callAgentLaunch( - remote, - launch, - { - target: { kind: 'existing', worktree }, - presentation: 'background' - }, - capabilities, - recoveryArgs - ) - const result = { ...created.result, launch: launched.result } - printLineageSummary(result, json) - printResult( - { ...created, result }, - json, - (value) => `${formatRecipeCreated(value)}\n${formatAgentLaunch(value.launch)}` - ) - } catch (error) { - // The workspace and its environment exist; say so instead of implying nothing happened. - if (error instanceof RuntimeClientError) { - throw new RuntimeClientError(error.code, error.message, { - ...(typeof error.data === 'object' && error.data !== null ? error.data : {}), - recipeEnvironmentId: environmentId, - worktreeId: created.result.worktree.id - }) - } - throw error - } -} diff --git a/src/cli/handlers/worktree-create-startup-agent.ts b/src/cli/handlers/worktree-create-startup-agent.ts deleted file mode 100644 index 0bb226549af..00000000000 --- a/src/cli/handlers/worktree-create-startup-agent.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import { parseCliAgent } from '../agent-launch-request' -import { getPresentStringFlag } from '../flags' -import { RuntimeClientError } from '../runtime-client' - -export function getOptionalStartupAgent( - flags: Map -): TuiAgent | undefined { - const agent = getPresentStringFlag(flags, 'agent') - if (agent === undefined) { - const needsAgent = ['prompt', 'model', 'effort', 'surface', 'retry-launch'].find((name) => - flags.has(name) - ) - if (needsAgent) { - throw new RuntimeClientError('invalid_argument', `--${needsAgent} requires --agent`) - } - return undefined - } - return parseCliAgent(agent) -} diff --git a/src/cli/handlers/worktree.ts b/src/cli/handlers/worktree.ts index 14962514d51..d1ff9d7bf72 100644 --- a/src/cli/handlers/worktree.ts +++ b/src/cli/handlers/worktree.ts @@ -28,9 +28,8 @@ import { resolveWorktreeCreateCwdContext, resolveCurrentWorktreeSelector } from '../selectors' -import { readCliAgentLaunch } from '../agent-launch-request' -import { getOptionalStartupAgent } from './worktree-create-startup-agent' -import { createWorktreeOnRecipe } from './worktree-create-recipe' +import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' +import { parseCliAgent, readCliAgentLaunch } from '../agent-launch-request' import { createWorktreeWithAgent } from './worktree-create-agent-launch' import { printLineageSummary, printSetParentLine } from './worktree-lineage-summary' import { resolveCreateParentFields, resolveSetParentFields } from './worktree-parent-fields' @@ -63,6 +62,20 @@ import { resolveReferenceInputs } from '../reference-input' +function getOptionalStartupAgent(flags: Map): TuiAgent | undefined { + const agent = getPresentStringFlag(flags, 'agent') + if (agent === undefined) { + const needsAgent = ['prompt', 'model', 'effort', 'surface', 'retry-launch'].find((name) => + flags.has(name) + ) + if (needsAgent) { + throw new RuntimeClientError('invalid_argument', `--${needsAgent} requires --agent`) + } + return undefined + } + return parseCliAgent(agent) +} + export const WORKTREE_HANDLERS: Record = { 'worktree ps': async ({ flags, client, json }) => { const result = await client.call>( @@ -105,7 +118,6 @@ export const WORKTREE_HANDLERS: Record = { }, 'worktree create': async (context) => { const { flags, client, cwd, json, rawArgs } = context - const recipeId = flags.has('recipe') ? getRequiredStringFlag(flags, 'recipe') : undefined const referenceInputs = getCreateReferenceInputs(flags) assertWorktreeParentFlagsCompatible(flags) assertWorkspaceTargetFlagsCompatible(flags) @@ -188,10 +200,6 @@ export const WORKTREE_HANDLERS: Record = { // Always request CLI provenance, including hand-typed creates without a terminal handle. cliProvenanceRequest: callerTerminalHandle ? { callerTerminalHandle } : {} } - if (recipeId) { - await createWorktreeOnRecipe({ client, flags, create, recipeId, launch: agentLaunch, json }) - return - } if (agentLaunch) { await createWorktreeWithAgent({ client, flags, create, launch: agentLaunch, json, rawArgs }) return diff --git a/src/cli/host-handler-groups.ts b/src/cli/host-handler-groups.ts index 80055c0c2e5..160656e60ba 100644 --- a/src/cli/host-handler-groups.ts +++ b/src/cli/host-handler-groups.ts @@ -33,10 +33,5 @@ export const HOST_HANDLER_GROUPS: readonly HandlerGroup[] = [ name: 'vm', keys: ['vm recipe doctor'], load: async () => (await import('./handlers/vm.js')).VM_HANDLERS - }, - { - name: 'vm-recipe-list', - keys: ['vm recipe list'], - load: async () => (await import('./handlers/vm-recipe-list.js')).VM_RECIPE_LIST_HANDLERS } ] diff --git a/src/cli/index-worktree-create-recipe.test.ts b/src/cli/index-worktree-create-recipe.test.ts deleted file mode 100644 index a683f2c606a..00000000000 --- a/src/cli/index-worktree-create-recipe.test.ts +++ /dev/null @@ -1,330 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -} = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), - addEnvironmentFromPairingCodeMock: vi.fn(), - listEnvironmentsMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') - return createRuntimeClientModuleMock({ - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock - }) -}) - -vi.mock('./runtime/environments', () => ({ - addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, - listEnvironments: listEnvironmentsMock, - removeEnvironment: vi.fn(), - resolveEnvironment: vi.fn() -})) - -vi.mock('child_process', async () => { - const { createChildProcessModuleMock } = await import('./index-test-harness.js') - return createChildProcessModuleMock(spawnMock) -}) - -import { main } from './index' -import { buildWorktree, okFixture, queueFixtures } from './test-fixtures' -import { useWorktreeAwarenessEnvironment } from './index-test-harness' - -import { agentLaunchFixture, agentLaunchHostFixture } from './agent-launch-test-fixtures' -import { WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY } from '../shared/host-runtime-capabilities' - -// main() never clears exitCode, so a failing test would otherwise satisfy later exitCode checks. -const originalExitCode = process.exitCode -beforeEach(() => { - process.exitCode = undefined -}) -afterEach(() => { - process.exitCode = originalExitCode -}) - -describe('CLI worktree create --recipe', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - const command = [ - 'worktree', - 'create', - '--repo', - 'id:source', - '--name', - 'task', - '--recipe', - 'sandbox', - '--no-parent', - '--json' - ] - const sourceStatus = () => - okFixture('source', { capabilities: [WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY] }) - const created = () => - okFixture('create', { - worktree: buildWorktree('/checkout', 'task', 'head', 'remote'), - recipe: { - id: 'sandbox', - runtimeId: 'vm', - environmentId: 'env-vm', - checkoutMode: 'orca-worktree' - } - }) - - it('selects the recipe only after verifying the provisioning host supports it', async () => { - queueFixtures(callMock, sourceStatus(), created()) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - await main(command, '/outside') - expect(callMock).toHaveBeenNthCalledWith(1, 'status.get') - expect(callMock).toHaveBeenNthCalledWith( - 2, - 'worktree.create', - expect.objectContaining({ repo: 'id:source', recipeId: 'sandbox' }), - expect.objectContaining({ timeoutMs: 600_000, onProgress: expect.any(Function) }) - ) - expect(log.mock.calls.flat().join('')).toContain('"environmentId": "env-vm"') - }) - it('prints named progress steps to stderr without touching stdout', async () => { - callMock.mockImplementationOnce(async () => sourceStatus()) - callMock.mockImplementationOnce( - async ( - _method: string, - _params: unknown, - options?: { onProgress?: (p: unknown) => void } - ) => { - options?.onProgress?.({ phase: 'running-create' }) - options?.onProgress?.({ phase: 'not-a-known-phase' }) - return created() - } - ) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const error = vi.spyOn(console, 'error').mockImplementation(() => {}) - await main( - command.filter((arg) => arg !== '--json'), - '/outside' - ) - const stderr = error.mock.calls.flat().join('\n') - expect(stderr).toContain('from recipe "sandbox"') - expect(stderr).toContain("- Running the recipe's create step...") - expect(stderr).not.toContain('not-a-known-phase') - expect(log.mock.calls.flat().join('')).toContain('environment: env-vm') - }) - it('adds next steps to a failed create and keeps the failure data', async () => { - callMock.mockImplementationOnce(async () => sourceStatus()) - callMock.mockImplementationOnce(async () => { - const { RuntimeClientError } = await import('./runtime-client.js') - throw new RuntimeClientError( - 'recipe_workspace_create_failed', - 'Boom. Orca destroyed the new environment.', - { - phase: 'checking-host', - environment: 'destroyed' - } - ) - }) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - await main(command, '/outside') - expect(process.exitCode).toBe(1) - const output = log.mock.calls.flat().join('') - expect(output).toContain('recipe_workspace_create_failed') - expect(output).toContain('checking-host') - expect(output).toContain('orca vm recipe doctor sandbox') - }) - it('refuses an older host before creating a local checkout', async () => { - queueFixtures(callMock, okFixture('old', { capabilities: [] })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - await main(command, '/outside') - expect(process.exitCode).toBe(1) - expect(callMock.mock.calls.some(([method]) => method === 'worktree.create')).toBe(false) - }) - it.each([{ recipe: ['--recipe'] }, { recipe: ['--recipe', ''] }])( - 'rejects a missing recipe value: %j', - async ({ recipe }) => { - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - await main( - [ - 'worktree', - 'create', - '--repo', - 'id:source', - '--name', - 'task', - '--no-parent', - ...recipe, - '--json' - ], - '/outside' - ) - expect(process.exitCode).toBe(1) - expect(callMock).not.toHaveBeenCalled() - } - ) - it('launches the agent on the new environment using the adopted workspace', async () => { - queueFixtures( - callMock, - sourceStatus(), - created(), - agentLaunchHostFixture(), - agentLaunchFixture('remote::/checkout') - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - await main( - [ - ...command, - '--agent', - 'codex', - '--model', - 'gpt-6-astra', - '--effort', - 'high', - '--prompt', - 'Work here' - ], - '/outside' - ) - expect(runtimeClientConstructorMock).toHaveBeenCalledWith(null, 'id:env-vm') - const launch = callMock.mock.calls.find( - ([method]) => method === 'agent.launch' || method === 'agent.launchReplay' - ) - expect(launch?.[1]).toMatchObject({ - agent: 'codex', - target: { kind: 'existing', worktree: 'id:remote::/checkout' }, - prompt: { text: 'Work here' } - }) - }) -}) - -describe('CLI vm recipe list', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - const listing = { - repos: [ - { - repoId: 'source', - repoName: 'orca', - repoPath: '/src/orca', - recipes: [ - { - id: 'sandbox', - name: 'Sandbox', - checkoutMode: 'orca-worktree', - steps: ['destroy'], - destroyDisabled: false, - timeoutSeconds: { create: 600 } - } - ], - diagnostics: [{ index: 1, field: 'create', message: 'Missing create command.' }] - } - ] - } - - it('lists one repo after checking the host can run recipes', async () => { - queueFixtures( - callMock, - okFixture('host', { capabilities: [WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY] }), - okFixture('list', listing) - ) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - await main(['vm', 'recipe', 'list', '--repo', 'id:source'], '/outside') - expect(callMock).toHaveBeenNthCalledWith(2, 'vmRecipe.list', { repo: 'id:source' }) - const output = log.mock.calls.flat().join('\n') - expect(output).toContain( - 'sandbox Sandbox [orca-worktree; destroys on removal; timeouts create 600s]' - ) - expect(output).toContain('warning: environmentRecipes[1].create: Missing create command.') - }) - - it('refuses a host that cannot run recipes without calling the list method', async () => { - queueFixtures(callMock, okFixture('old', { capabilities: [] })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - await main(['vm', 'recipe', 'list', '--json'], '/outside') - expect(process.exitCode).toBe(1) - expect(callMock.mock.calls.some(([method]) => method === 'vmRecipe.list')).toBe(false) - }) -}) - -describe('CLI worktree create --recipe refusals', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - - it('refuses an explicit parent, which another host cannot record', async () => { - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - await main( - [ - 'worktree', - 'create', - '--repo', - 'id:source', - '--name', - 'task', - '--recipe', - 'sandbox', - '--parent-worktree', - 'active', - '--json' - ], - '/outside' - ) - expect(process.exitCode).toBe(1) - expect(callMock.mock.calls.some(([method]) => method === 'worktree.create')).toBe(false) - }) - it('refuses --activate before asking the host anything', async () => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - await main( - [ - 'worktree', - 'create', - '--repo', - 'id:source', - '--name', - 'task', - '--recipe', - 'sandbox', - '--no-parent', - '--activate', - '--json' - ], - '/outside' - ) - expect(process.exitCode).toBe(1) - expect(log.mock.calls.flat().join('')).toContain('--activate is not supported with --recipe') - expect(callMock.mock.calls.some(([method]) => method === 'worktree.create')).toBe(false) - }) -}) diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index b3afbce38f9..6ad30800fca 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -77,7 +77,6 @@ export const ROOT_HELP_TEXT_PRIMARY = [ ' plugin dev unload Remove a development folder', '', 'Environment Recipes:', - ' vm recipe list List environment recipes for worktree create --recipe', ' vm recipe doctor Validate a per-workspace environment recipe', '', 'Automations:', diff --git a/src/cli/runtime/client.ts b/src/cli/runtime/client.ts index ca4647c5435..1425d23af36 100644 --- a/src/cli/runtime/client.ts +++ b/src/cli/runtime/client.ts @@ -194,8 +194,7 @@ export class RuntimeClient { effectiveTimeoutMs, envelope, expectedRuntimeSource, - // Only requestSelection and onProgress reach the socket; the rest shaped the envelope above. - options + options?.requestSelection ? { requestSelection: options.requestSelection } : undefined ) } catch (error) { // A pre-send refusal has no outcome to recover; retry advice would resend the same bytes. diff --git a/src/cli/runtime/transport.test.ts b/src/cli/runtime/transport.test.ts index 077bb13a588..31871e1b96f 100644 --- a/src/cli/runtime/transport.test.ts +++ b/src/cli/runtime/transport.test.ts @@ -349,48 +349,6 @@ describe.skipIf(process.platform === 'win32')('runtime transport', () => { expect(vi.getTimerCount()).toBe(0) }) - it('hands progress notes on keepalive frames to the caller and ignores malformed ones', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-transport-')) - roots.push(userDataPath) - const endpoint = join(userDataPath, 'runtime.sock') - const server = createServer((socket) => { - sockets.add(socket) - socket.once('close', () => sockets.delete(socket)) - socket.once('data', (data) => { - const request: { id: string } = JSON.parse(String(data).trim()) - socket.write('{"_keepalive":true,"progress":{"phase":"running-create"}}\n') - socket.write('{"_keepalive":true,"progress":{"phase":42}}\n') - socket.write('{"_keepalive":true}\n') - socket.write( - `${JSON.stringify({ id: request.id, ok: true, result: { created: true }, _meta: { runtimeId: 'runtime-1' } })}\n` - ) - }) - }) - servers.add(server) - await new Promise((resolve) => server.listen(endpoint, resolve)) - const metadata: RuntimeMetadata = { - runtimeId: 'runtime-1', - pid: 123, - transports: [{ kind: 'unix', endpoint }], - authToken: 'token', - startedAt: 1 - } - const onProgress = vi.fn() - const response = await sendRequest( - metadata, - 'worktree.create', - {}, - 60_000, - undefined, - undefined, - { - onProgress - } - ) - expect(response).toMatchObject({ ok: true, result: { created: true } }) - expect(onProgress.mock.calls).toEqual([[{ phase: 'running-create' }]]) - }) - it('rejects promptly when the runtime closes the socket before responding', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-transport-')) roots.push(userDataPath) diff --git a/src/cli/runtime/transport.ts b/src/cli/runtime/transport.ts index afb9f7c8835..eafc4672ff8 100644 --- a/src/cli/runtime/transport.ts +++ b/src/cli/runtime/transport.ts @@ -4,8 +4,7 @@ import { findTransport, type RuntimeMetadata } from '../../shared/runtime-bootst import type { ExpectedRuntimeSource, RuntimeOrchestrationEnvelope, - RuntimeRequestSelection, - RuntimeRpcProgress + RuntimeRequestSelection } from '../../shared/runtime-rpc-envelope' import { isKeepaliveFrame, RuntimeRpcEnvelopeSchema } from './envelope-schema' import { RuntimeClientError, RuntimeRpcFailureError, type RuntimeRpcResponse } from './types' @@ -25,10 +24,9 @@ export async function sendRequest( options: { classifySocketError?: (error: Error) => RuntimeClientError | null requestSelection?: RuntimeRequestSelection - onProgress?: (progress: RuntimeRpcProgress) => void } = {} ): Promise> { - const { classifySocketError = runtimeAccessDeniedError, requestSelection, onProgress } = options + const { classifySocketError = runtimeAccessDeniedError, requestSelection } = options if (!isSafeTimerDelayMs(timeoutMs)) { throw new RuntimeClientError( 'invalid_argument', @@ -158,11 +156,6 @@ export async function sendRequest( // Keepalives refresh the idle timeout without a full envelope validation. if (isKeepaliveFrame(raw)) { timeout.refresh() - // Parse only for a caller that listens; every other long poll skips the work. - const progress = onProgress ? RuntimeRpcEnvelopeSchema.safeParse(raw) : null - if (progress?.success && 'progress' in progress.data && progress.data.progress) { - onProgress?.(progress.data.progress) - } continue } diff --git a/src/cli/runtime/types.ts b/src/cli/runtime/types.ts index 6791da106c4..2a48c7bfc99 100644 --- a/src/cli/runtime/types.ts +++ b/src/cli/runtime/types.ts @@ -1,8 +1,7 @@ import type { RuntimeOrchestrationEnvelope, RuntimeRequestSelection, - RuntimeRpcFailure, - RuntimeRpcProgress + RuntimeRpcFailure } from '../../shared/runtime-rpc-envelope' import { redactOrchestrationCompatibilitySecrets } from '../../shared/orchestration/orchestration-compatibility-evidence' @@ -17,8 +16,6 @@ export type RuntimeCallOptions = { legacyTerminalPrompt?: true terminalPromptPreflight?: { runtimeId: string | null } requestSelection?: RuntimeRequestSelection - /** Local socket only: named steps a long-running request reports while it runs. */ - onProgress?: (progress: RuntimeRpcProgress) => void } & RuntimeOrchestrationEnvelope export class RuntimeClientError extends Error { diff --git a/src/cli/specs/vm.ts b/src/cli/specs/vm.ts index ed687b218fc..fb98c7d7674 100644 --- a/src/cli/specs/vm.ts +++ b/src/cli/specs/vm.ts @@ -1,19 +1,7 @@ import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS, LOCAL_COMMAND_FLAGS } from '../args' +import { LOCAL_COMMAND_FLAGS } from '../args' export const VM_COMMAND_SPECS: CommandSpec[] = [ - { - path: ['vm', 'recipe', 'list'], - summary: 'List the environment recipes `orca worktree create --recipe` can use', - usage: 'orca vm recipe list [--repo ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'repo'], - notes: [ - "Lists recipes from each repo's orca.yaml plus approved plugin recipes, as the Orca desktop app on this computer sees them. Pass --repo to list one repo.", - 'Each recipe shows its checkout mode, whether removing its workspace destroys the environment, and any per-step timeouts from timeoutSeconds.', - 'orca.yaml problems that hid a recipe are listed as warnings; run `orca vm recipe doctor ` for details.' - ], - examples: ['orca vm recipe list', 'orca vm recipe list --repo id: --json'] - }, { path: ['vm', 'recipe', 'doctor'], summary: 'Validate a per-workspace environment recipe without provisioning by default', diff --git a/src/cli/specs/worktree-create.ts b/src/cli/specs/worktree-create.ts index e620cd05832..743f4b68504 100644 --- a/src/cli/specs/worktree-create.ts +++ b/src/cli/specs/worktree-create.ts @@ -6,7 +6,7 @@ export const WORKTREE_CREATE_COMMAND_SPEC: CommandSpec = { repeatableFlags: ['reference'], summary: 'Create a new Orca-managed worktree', usage: - 'orca worktree create --name [--repo |--project [--host ]|--project-host-setup ] [--recipe ] [--agent ] [--prompt ] [--model ] [--effort ] [--surface chat|terminal] [--setup run|skip|inherit] [--base-branch ] [--branch ] [--reference ...] [--reference-site ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--parent-worktree [--parent-environment ]] [--no-parent] [--run-hooks] [--activate] [--retry-launch ] [--json]', + 'orca worktree create --name [--repo |--project [--host ]|--project-host-setup ] [--agent ] [--prompt ] [--model ] [--effort ] [--surface chat|terminal] [--setup run|skip|inherit] [--base-branch ] [--branch ] [--reference ...] [--reference-site ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--parent-worktree [--parent-environment ]] [--no-parent] [--run-hooks] [--activate] [--retry-launch ] [--json]', allowedFlags: [ ...GLOBAL_FLAGS, 'repo', @@ -14,7 +14,6 @@ export const WORKTREE_CREATE_COMMAND_SPEC: CommandSpec = { 'host', 'project-host-setup', 'name', - 'recipe', 'agent', 'prompt', 'model', @@ -58,8 +57,6 @@ export const WORKTREE_CREATE_COMMAND_SPEC: CommandSpec = { 'Repo-defined setup hooks follow the repository setup policy; pass --setup run to force them.', 'Pass --activate when the CLI caller intentionally wants to reveal the new worktree in the app.', 'Passing --run-hooks is kept as a legacy alias for --setup run and reveals the worktree.', - "Pass --recipe to create the workspace on a new environment from one of the repo's environment recipes (`orca vm recipe list` shows them). The Orca desktop app on this computer runs the recipe's create step, then creates the workspace on the environment's own Orca server; progress steps print to stderr and --json prints only the result. Ctrl+C stops it and destroys an environment that finished its create step; one interrupted mid-create stays in Settings > Cloud VMs for you to destroy. The recipe's timeoutSeconds bounds each step. If a later step fails, Orca destroys the new environment and the error (code recipe_workspace_create_failed) says which step failed and whether the destroy finished.", - '--recipe runs from the provisioning computer only: it cannot be combined with --environment, --pairing-code or --retry-launch. With --agent, the agent starts on the new environment after creation. --activate, --parent-worktree and --parent-environment are not supported with --recipe yet, and the workspace is recorded without a parent. Provisioned-root recipes run setup in their create step, so --setup run, --run-hooks and sparse checkout are refused for them.', 'Use --pr for GitHub pull requests; --gitlab-issue and --gitlab-mr write separate GitLab links. GitLab URLs must match the stored source project or remote; they cannot select a foreign project.' ], examples: [ @@ -72,7 +69,6 @@ export const WORKTREE_CREATE_COMMAND_SPEC: CommandSpec = { 'orca worktree create --repo id: --name folder-child --parent-worktree folder: --json', 'orca worktree create --repo id: --name related-task --parent-worktree active --json', 'orca worktree create --environment --repo id: --name child --parent-environment local --parent-worktree folder: --json', - 'orca worktree create --repo id: --name independent-task --no-parent --json', - 'orca worktree create --repo id: --name sandboxed-task --recipe cloud-sandbox --agent codex --prompt "hi" --json' + 'orca worktree create --repo id: --name independent-task --no-parent --json' ] } diff --git a/src/main/ephemeral-vm/cli-workspace-create.ts b/src/main/ephemeral-vm/cli-workspace-create.ts deleted file mode 100644 index 4bf16c62855..00000000000 --- a/src/main/ephemeral-vm/cli-workspace-create.ts +++ /dev/null @@ -1,179 +0,0 @@ -import type { Store } from '../persistence/loading-store/store' -import type { Repo } from '../../shared/repo-types' -import { getRepoExecutionHostId } from '../../shared/execution-host' -import { isFolderRepo } from '../../shared/repo-kind' -import { getProjectHostSetupForRepo } from '../../shared/project-host-setup-lookup' -import { getProjectIdentityKey } from '../../shared/project-host-setup-projection' -import type { - RecipeCatalogListing, - RecipeWorkspaceCreatePhase -} from '../../shared/recipe-workspace-create-progress' -import { sanitizeWorktreeName } from '../ipc/worktree-logic' -import { resolveCreateBranchName } from '../runtime/workspaces/creation/runtime-worktree-create-git' -import { resolveLocalGitUsername } from '../git/git-username' -import { getLocalProjectGitExecOptions } from '../workspaces/execution-host/project-runtime-git-options' -import { - listRecipeCatalog, - listRecipes, - resolveRecipeForRepo -} from '../ipc/ephemeral-vm-recipe-context' -import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' -import { getApprovedPluginVmRecipes } from '../plugins/plugin-approved-vm-recipes' -import type { PluginService } from '../plugins/plugin-service' -import { callRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-transport-routing' -import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root' -import { provisionRecipeEnvironment } from './environment-provision' -import { attachEphemeralVmRuntimeToWorkspace } from './runtime-attachment' -import { cleanupOwnedEphemeralVmRuntime } from './owned-runtime-cleanup' -import { - createProvisionedRecipeWorkspace, - type RecipeWorkspaceCreateParams, - type RecipeWorkspaceCreation -} from './recipe-workspace-create' - -// Each call to the new environment's Orca is one short step; the recipe's own timeouts bound the create. -const ENVIRONMENT_STEP_TIMEOUT_MS = 600_000 - -/** `worktree.create` with a recipe id: the host that owns the recipe provisions and adopts. */ -export async function createCliRecipeWorkspace(args: { - store: Store - userDataPath: string - repo: Repo - params: RecipeWorkspaceCreateParams - pluginService: PluginService | null - signal?: AbortSignal - onPhase?: (phase: RecipeWorkspaceCreatePhase) => void -}): Promise { - const { store, userDataPath, repo, params } = args - if (isFolderRepo(repo) || getRepoExecutionHostId(repo) !== 'local') { - throw new Error('Environment recipes need a Git checkout on this computer.') - } - const pluginRecipes = await getApprovedPluginVmRecipes(args.pluginService ?? undefined) - const recipe = params.recipeId - ? resolveRecipeForRepo(repo.path, params.recipeId, pluginRecipes) - : null - if (!recipe) { - throw new Error( - `Recipe not found: ${params.recipeId ?? ''}. Run \`orca vm recipe list\` to see this repo's recipes.` - ) - } - const checkoutMode = recipe.checkoutMode ?? 'orca-worktree' - let branchName: string | undefined - if (checkoutMode === 'provisioned-root') { - const settings = store.getSettings() - const username = - settings.branchPrefix === 'git-username' ? await resolveLocalGitUsername(repo.path) : '' - branchName = await resolveCreateBranchName( - repo.path, - params.branchNameOverride, - sanitizeWorktreeName(params.name ?? ''), - settings, - username, - getLocalProjectGitExecOptions(store, repo) - ) - } - // Same project identity the desktop's recipe flow gives the environment: the portable GitHub key when there is one. - const portableProjectId = getProjectIdentityKey(repo) - const projectId = portableProjectId.startsWith('github:') - ? portableProjectId - : getProjectHostSetupForRepo(store.getProjectHostSetups(), repo).projectId - return createProvisionedRecipeWorkspace( - { - params, - recipeId: recipe.id, - checkoutMode, - ...(branchName ? { branchName } : {}), - projectId, - ...(args.signal ? { signal: args.signal } : {}), - ...(args.onPhase ? { onPhase: args.onPhase } : {}) - }, - { - provision: (onPhase) => - provisionRecipeEnvironment( - store, - userDataPath, - { - repoId: repo.id, - recipeId: recipe.id, - workspaceName: params.name, - projectId, - ...(branchName ? { branch: branchName } : {}), - ...(checkoutMode === 'provisioned-root' && params.baseBranch - ? { ref: params.baseBranch } - : {}) - }, - pluginRecipes, - { repo, recipe, signal: args.signal, onPhase } - ), - call: (environmentId, method, payload) => - callRuntimeEnvironment( - getRuntimeEnvironmentRegistryRoot(), - `id:${environmentId}`, - method, - payload, - ENVIRONMENT_STEP_TIMEOUT_MS, - undefined, - undefined, - // Ctrl+C on the CLI stops the step in flight, so the VM is destroyed right away. - args.signal ? { signal: args.signal } : undefined - ), - attach: (runtimeId, workspaceId) => { - attachEphemeralVmRuntimeToWorkspace({ userDataPath, runtimeId, workspaceId }) - }, - cleanup: async (runtimeId) => { - const runtime = await cleanupOwnedEphemeralVmRuntime(store, userDataPath, runtimeId) - if (runtime.status === 'cleaned') { - // A recipe without a destroy step is marked cleaned without running anything. - return { outcome: runtime.cleanupStatus === 'disabled' ? 'disabled' : 'destroyed' } - } - return { - outcome: 'failed', - ...(runtime.cleanupLastError ? { error: runtime.cleanupLastError } : {}) - } - } - } - ) -} - -function toListedRecipe(recipe: OrcaVmRecipe): RecipeCatalogListing['recipes'][number] { - return { - id: recipe.id, - name: recipe.name, - ...(recipe.description ? { description: recipe.description } : {}), - checkoutMode: recipe.checkoutMode ?? 'orca-worktree', - steps: (['suspend', 'resume', 'destroy'] as const).filter((step) => Boolean(recipe[step])), - destroyDisabled: recipe.destroyDisabled === true, - ...(recipe.timeoutSeconds ? { timeoutSeconds: recipe.timeoutSeconds } : {}) - } -} - -/** The recipes `worktree create --recipe` accepts: orca.yaml plus approved plugin recipes. */ -export async function listCliEnvironmentRecipes( - store: Store, - repo: Repo | null, - pluginService: PluginService | null -): Promise { - const pluginRecipes = await getApprovedPluginVmRecipes(pluginService ?? undefined) - if (repo) { - const listed = listRecipes(store, repo.id, pluginRecipes) - if (listed.status === 'error') { - throw new Error(listed.message ?? 'Could not read environment recipes for this repo.') - } - return [ - { - repoId: repo.id, - repoName: repo.displayName, - repoPath: repo.path, - recipes: listed.recipes.map(toListedRecipe), - diagnostics: listed.diagnostics ?? [] - } - ] - } - return listRecipeCatalog(store, pluginRecipes).map((entry) => ({ - repoId: entry.repoId, - repoName: entry.repoName, - repoPath: entry.repoPath, - recipes: entry.recipes.map(toListedRecipe), - diagnostics: entry.diagnostics ?? [] - })) -} diff --git a/src/main/ephemeral-vm/environment-provision-repo.test.ts b/src/main/ephemeral-vm/environment-provision-repo.test.ts deleted file mode 100644 index 119e89ae3fa..00000000000 --- a/src/main/ephemeral-vm/environment-provision-repo.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { provisionRecipeEnvironment } from './environment-provision' -import type { Repo } from '../../shared/repo-types' -import type { Store } from '../persistence/loading-store/store' - -function repoAt(path: string): Repo { - return { id: 'shared-id', path, displayName: 'Repo', badgeColor: '#000', addedAt: 0 } -} - -let userDataPath: string - -beforeEach(() => { - userDataPath = mkdtempSync(join(tmpdir(), 'orca-provision-repo-')) -}) - -afterEach(() => { - rmSync(userDataPath, { recursive: true, force: true }) -}) - -it('provisions against the repo the caller resolved, not another host’s twin with the same id', async () => { - const resolved: Repo = repoAt(join(userDataPath, 'resolved')) - const twin: Repo = repoAt(join(userDataPath, 'twin')) - const getRepo = vi.fn(() => twin) - - // No recipes exist at either path, so the run stops at recipe lookup after choosing its repo. - const result = await provisionRecipeEnvironment( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: provisioning reads only getRepo from the store before it stops at recipe lookup. - { getRepo } as unknown as Store, - userDataPath, - { repoId: 'shared-id', recipeId: 'missing' }, - [], - { repo: resolved } - ) - - expect(getRepo).not.toHaveBeenCalled() - expect(result).toMatchObject({ ok: false, errorCode: 'recipeNotFound' }) -}) diff --git a/src/main/ephemeral-vm/environment-provision.ts b/src/main/ephemeral-vm/environment-provision.ts deleted file mode 100644 index ba1d2f79694..00000000000 --- a/src/main/ephemeral-vm/environment-provision.ts +++ /dev/null @@ -1,234 +0,0 @@ -import type { Store } from '../persistence/loading-store/store' -import type { Repo } from '../../shared/repo-types' -import { getEphemeralVmRecipeResultConnection } from '../../shared/ephemeral-vm-recipes' -import { - getEphemeralVmRecipeResultWarnings, - redactEphemeralVmRecipeDiagnosticText, - type EphemeralVmRecipeResultWarning -} from '../../shared/ephemeral-vm-recipe-diagnostics' -import { getProvisionedRootRecipeRepoUrl } from '../../shared/ephemeral-vm-recipe-repo-url' -import { updateEphemeralVmRuntimeStatus } from '../../shared/ephemeral-vm-runtime-store' -import { - requireEphemeralVmRecipeResult, - type EphemeralVmProvisionedRuntimeRecord -} from '../../shared/ephemeral-vm-runtimes' -import { addEnvironmentFromPairingCode } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import { - redactRuntimeEnvironment, - type PublicKnownRuntimeEnvironment -} from '../../shared/remote-runtime/host-catalog/runtime-environments' -import { - ephemeralVmFailure, - pickEphemeralVmFailureCode, - type EphemeralVmFailure -} from '../../shared/ephemeral-vm-failure-copy' -import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' -import { getRecipeRepo, resolveRecipeForRepo } from '../ipc/ephemeral-vm-recipe-context' -import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root' -import { cleanupEphemeralVmRuntime, provisionEphemeralVmRuntime } from './runtime-service' -import { connectRuntimeOwnedSshTarget } from './runtime-ssh' -import { resolveProvisionedRootSource } from './provisioned-root-source' - -export type EphemeralVmProvisionIpcResult = - | { - ok: true - connectionType: 'orca-server' - runtime: EphemeralVmProvisionedRuntimeRecord - environment: PublicKnownRuntimeEnvironment - stderr: string - warnings: EphemeralVmRecipeResultWarning[] - } - | { - ok: true - connectionType: 'ssh' - runtime: EphemeralVmProvisionedRuntimeRecord - sshTargetId: string - /** The managed Orca server the host runs; its workspace lives there. */ - environmentId?: string - expectedRefHead?: string - stderr: string - warnings: EphemeralVmRecipeResultWarning[] - } - | ({ - ok: false - stderr: string - stdout: string - /** Set when the create step had already started a VM that this failure then destroyed. */ - runtimeId?: string - environmentCleanup?: 'destroyed' | 'failed' | 'disabled' - } & EphemeralVmFailure) - -/** Named steps of provisioning, reported to callers that show progress. */ -export type RecipeEnvironmentProvisionPhase = - | 'resolving-start-ref' - | 'running-create' - | 'connecting' - -export type RecipeEnvironmentProvisionArgs = { - repoId: string - recipeId: string - workspaceName?: string - projectId?: string - workspaceId?: string - branch?: string - ref?: string -} - -function provisionFailure(failure: EphemeralVmFailure): EphemeralVmProvisionIpcResult { - return { ok: false, ...failure, stdout: '', stderr: '' } -} - -/** Shared by the desktop IPC handler and CLI `worktree create --recipe`. */ -export async function provisionRecipeEnvironment( - store: Store, - userDataPath: string, - args: RecipeEnvironmentProvisionArgs, - pluginRecipes: readonly OrcaVmRecipe[], - options: { - /** A caller that already resolved the repo by host passes it; an id lookup could pick another host's twin. */ - repo?: Repo - /** A caller that already resolved the recipe passes it, so one orca.yaml read decides the run. */ - recipe?: OrcaVmRecipe - signal?: AbortSignal - onPhase?: (phase: RecipeEnvironmentProvisionPhase) => void - onStdout?: (chunk: string) => void - onStderr?: (chunk: string) => void - } = {} -): Promise { - const repo = options.repo - ? ({ ok: true, repo: options.repo } as const) - : getRecipeRepo(store, args.repoId) - if (!repo.ok) { - return provisionFailure(repo.failure) - } - const recipe = - options.recipe ?? resolveRecipeForRepo(repo.repo.path, args.recipeId, pluginRecipes) - if (!recipe) { - return provisionFailure(ephemeralVmFailure('recipeNotFound', { recipeId: args.recipeId })) - } - let recipeRepoUrl = repo.repo.gitRemoteIdentity?.remoteUrl - let sourceRef = args.ref - let expectedRefHead: string | undefined - if (recipe.checkoutMode === 'provisioned-root') { - options.onPhase?.('resolving-start-ref') - const source = await resolveProvisionedRootSource(store, repo.repo, args.ref, options.signal) - if (options.signal?.aborted) { - return provisionFailure(ephemeralVmFailure('provisionCancelled')) - } - if (!source) { - return provisionFailure( - args.ref - ? ephemeralVmFailure('startRefUnresolved', { ref: args.ref }) - : ephemeralVmFailure('defaultStartRefUnresolved') - ) - } - sourceRef = source.ref - expectedRefHead = source.head - recipeRepoUrl = source.remoteUrl ?? recipeRepoUrl - } - const repoUrl = getProvisionedRootRecipeRepoUrl(recipe.checkoutMode, recipeRepoUrl) - options.onPhase?.('running-create') - const result = await provisionEphemeralVmRuntime({ - userDataPath, - repoPath: repo.repo.path, - repoId: repo.repo.id, - recipe, - projectId: args.projectId, - workspaceId: args.workspaceId, - workspaceName: args.workspaceName, - ...(repoUrl ? { repoUrl } : {}), - ...(args.branch ? { branch: args.branch } : {}), - ...(sourceRef ? { ref: sourceRef } : {}), - ...(expectedRefHead ? { expectedRefHead } : {}), - ...(options.signal ? { signal: options.signal } : {}), - onStdout: options.onStdout, - onStderr: options.onStderr - }) - if (!result.ok) { - return { - ok: false, - error: result.start.error, - ...pickEphemeralVmFailureCode(result.start), - stdout: redactEphemeralVmRecipeDiagnosticText(result.start.stdout), - stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) - } - } - const cleanupAndFail = async (error: unknown): Promise => { - const cleaned = await cleanupEphemeralVmRuntime({ - userDataPath, - repoPath: repo.repo.path, - recipe, - runtimeId: result.runtime.id - }).catch(() => null) - return { - ok: false, - error: error instanceof Error ? error.message : String(error), - runtimeId: result.runtime.id, - environmentCleanup: !cleaned?.ok ? 'failed' : cleaned.skipped ? 'disabled' : 'destroyed', - stdout: redactEphemeralVmRecipeDiagnosticText(result.start.stdout), - stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) - } - } - options.onPhase?.('connecting') - const connection = getEphemeralVmRecipeResultConnection(result.start.result) - if (connection.type === 'ssh') { - try { - const ssh = await connectRuntimeOwnedSshTarget({ - runtimeId: result.runtime.id, - connection - }) - const runtime = requireEphemeralVmRecipeResult( - updateEphemeralVmRuntimeStatus(userDataPath, result.runtime.id, { - sshTargetId: ssh.targetId, - runtimeEnvironmentId: ssh.environmentId - }) - ) - return { - ok: true, - connectionType: 'ssh', - runtime, - sshTargetId: ssh.targetId, - environmentId: ssh.environmentId, - ...(expectedRefHead ? { expectedRefHead } : {}), - stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr), - warnings: getEphemeralVmRecipeResultWarnings(result.start.result) - } - } catch (error) { - return cleanupAndFail(error) - } - } - - let environment: ReturnType - try { - environment = addEnvironmentFromPairingCode(getRuntimeEnvironmentRegistryRoot(), { - name: buildEphemeralEnvironmentName(repo.repo.displayName, result.runtime.id), - pairingCode: connection.pairingCode, - source: 'ephemeral-vm' - }) - } catch (error) { - return cleanupAndFail(error) - } - let runtime: EphemeralVmProvisionedRuntimeRecord - try { - runtime = requireEphemeralVmRecipeResult( - updateEphemeralVmRuntimeStatus(userDataPath, result.runtime.id, { - runtimeEnvironmentId: environment.id - }) - ) - } catch (error) { - // The create step already started a VM; a failed record update must still destroy it. - return cleanupAndFail(error) - } - return { - ok: true, - connectionType: 'orca-server', - runtime, - environment: redactRuntimeEnvironment(environment), - stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr), - warnings: getEphemeralVmRecipeResultWarnings(result.start.result) - } -} - -function buildEphemeralEnvironmentName(repoName: string, runtimeId: string): string { - return `${repoName} VM ${runtimeId.slice(-8)}` -} diff --git a/src/main/ephemeral-vm/owned-runtime-cleanup.ts b/src/main/ephemeral-vm/owned-runtime-cleanup.ts deleted file mode 100644 index e15bc719d46..00000000000 --- a/src/main/ephemeral-vm/owned-runtime-cleanup.ts +++ /dev/null @@ -1,82 +0,0 @@ -import type { Store } from '../persistence/loading-store/store' -import { - listEphemeralVmRuntimes, - updateEphemeralVmRuntimeStatus -} from '../../shared/ephemeral-vm-runtime-store' -import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' -import { ephemeralVmFailureFromError } from '../../shared/ephemeral-vm-failure-copy' -import { getRuntimeRecipeContext } from '../ipc/ephemeral-vm-recipe-context' -import { invalidateRuntimeEnvironmentTransport } from '../ipc/runtime-environments/runtime-environments' -import { retireRemovedRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-removal-cleanup' -import { releaseEphemeralVmRuntimeEnvironments } from './runtime-environment-release' -import { cleanupEphemeralVmRuntime } from './runtime-service' -import { removeEphemeralVmRuntimeSshTarget } from './runtime-ssh-cleanup' -import { removeRuntimeOwnedSshTarget } from './runtime-ssh' -import { isEphemeralVmProvisionLive } from './runtime-provisioning-persistence' - -/** Destroys a recorded VM and releases what Orca holds for it. The one path for the desktop's - * cleanup and a failed CLI create; concurrent calls share one destroy run. */ -export async function cleanupOwnedEphemeralVmRuntime( - store: Store, - userDataPath: string, - runtimeId: string -): Promise { - const runtime = listEphemeralVmRuntimes(userDataPath).find((entry) => entry.id === runtimeId) - if (!runtime) { - throw new Error(`Unknown ephemeral VM runtime: ${runtimeId}`) - } - if (runtime.status === 'provisioning' && isEphemeralVmProvisionLive(runtime.id)) { - // Why: don't mark a create in flight as cleanup_failed; its own outcome settles the row. - throw new Error(`Ephemeral VM runtime is still provisioning: ${runtime.id}`) - } - let result - if (runtime.cleanupStatus === 'succeeded') { - result = { ok: true as const, runtime, skipped: false } - } else { - let resolved: ReturnType - try { - resolved = getRuntimeRecipeContext(store, userDataPath, runtime.id) - } catch (error) { - const failed = updateEphemeralVmRuntimeStatus(userDataPath, runtime.id, { - status: 'cleanup_failed', - cleanupStatus: 'failed', - cleanupLastAttemptAt: Date.now(), - cleanupLastError: ephemeralVmFailureFromError(error) - }) - return removeEphemeralVmRuntimeSshTarget({ - userDataPath, - runtime: failed, - removeTarget: removeRuntimeOwnedSshTarget - }) - } - result = await cleanupEphemeralVmRuntime({ - userDataPath, - repoPath: resolved.repoPath, - recipe: resolved.recipe, - runtimeId: runtime.id - }) - } - if (result.ok) { - try { - await releaseEphemeralVmRuntimeEnvironments(userDataPath, runtime, (environmentId) => { - void retireRemovedRuntimeEnvironment( - environmentId, - invalidateRuntimeEnvironmentTransport, - store, - userDataPath - ) - }) - } catch { - // Cleanup of provider resources matters more than hiding a stale local - // environment row; users can still remove that manually. - } - } - if (!result.ok) { - return result.runtime - } - return removeEphemeralVmRuntimeSshTarget({ - userDataPath, - runtime: result.runtime, - removeTarget: removeRuntimeOwnedSshTarget - }) -} diff --git a/src/main/ephemeral-vm/recipe-workspace-create-params.ts b/src/main/ephemeral-vm/recipe-workspace-create-params.ts deleted file mode 100644 index 4b545ca1da7..00000000000 --- a/src/main/ephemeral-vm/recipe-workspace-create-params.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { z } from 'zod' -import type { WorktreeCreate } from '../../shared/rpc-contract/worktree-create-params' -import type { EphemeralVmCheckoutMode } from '../../shared/orca-yaml-hook-types' - -// Kept apart from the orchestration so runtime types (and the mobile host-declaration program) -// do not pull in provisioning, the recipe runner and their imports. -export type RecipeWorkspaceCreateParams = z.infer - -export const RecipeWorkspaceResult = z - .object({ - worktree: z - .object({ - id: z.string().min(1), - repoId: z.string().min(1), - path: z.string().min(1), - branch: z.string(), - instanceId: z.string().optional() - }) - .passthrough() - }) - .passthrough() -export type RecipeWorkspaceCreation = z.infer & { - recipe: { - id: string - runtimeId: string - environmentId: string - checkoutMode: EphemeralVmCheckoutMode - } - environmentWarnings?: string[] -} - -// Fields a normal create on the environment's own Orca understands; lineage, activation and the -// caller's terminal stay on this host, which records them after the environment answers. -const FORWARDED_CREATE_FIELDS = [ - 'name', - 'nameWasGenerated', - 'displayName', - 'displayNameKind', - 'baseBranch', - 'compareBaseRef', - 'branchNameOverride', - 'linkedIssue', - 'linkedPR', - 'linkedLinearIssue', - 'linkedLinearIssueWorkspaceId', - 'linkedLinearIssueOrganizationUrlKey', - 'linkedGitLabMR', - 'linkedGitLabIssue', - 'linkedBitbucketPR', - 'linkedAzureDevOpsPR', - 'linkedGiteaPR', - 'linkedWorkItem', - 'linkedItems', - 'linkedTaskSourceContext', - 'comment', - 'workspaceStatus', - 'sparseCheckout', - 'pushTarget', - 'runHooks', - 'setupDecision', - 'createdWithAgent' -] as const satisfies readonly (keyof RecipeWorkspaceCreateParams)[] - -export function forwardedCreateFields( - params: RecipeWorkspaceCreateParams -): Record { - const forwarded: Record = {} - for (const field of FORWARDED_CREATE_FIELDS) { - if (params[field] !== undefined) { - forwarded[field] = params[field] - } - } - return forwarded -} - -/** Refuses what a recipe create cannot honor before any machine is started. */ -export function assertRecipeWorkspaceCreateSupported( - params: RecipeWorkspaceCreateParams, - checkoutMode: EphemeralVmCheckoutMode -): void { - if (!params.name?.trim()) { - throw new Error('A recipe workspace requires a name.') - } - if (params.startupAgent || params.startupCommand || params.startupDraft) { - throw new Error( - 'Launch the agent on the recipe-created workspace with agent.launch after creation.' - ) - } - if (params.automationProvenanceRequest) { - throw new Error('Recipe workspace creation does not support automation provenance requests.') - } - if (checkoutMode === 'provisioned-root') { - if (params.sparseCheckout) { - throw new Error('Provisioned-root recipes do not support sparse checkout.') - } - if (params.runHooks || params.setupDecision === 'run') { - throw new Error("Provisioned-root recipes run setup in the recipe's create step.") - } - } -} diff --git a/src/main/ephemeral-vm/recipe-workspace-create.test.ts b/src/main/ephemeral-vm/recipe-workspace-create.test.ts deleted file mode 100644 index 33a19b87617..00000000000 --- a/src/main/ephemeral-vm/recipe-workspace-create.test.ts +++ /dev/null @@ -1,387 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { WorktreeCreate } from '../../shared/rpc-contract/worktree-create-params' -import { - PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, - WORKTREE_PROVISIONED_ROOT_RUNTIME_CAPABILITY -} from '../../shared/protocol-version' -import type { EphemeralVmCheckoutMode } from '../../shared/orca-yaml-hook-types' -import type { RecipeWorkspaceCreatePhase } from '../../shared/recipe-workspace-create-progress' -import { - createProvisionedRecipeWorkspace, - RecipeWorkspaceCreateError -} from './recipe-workspace-create' -import type { EphemeralVmProvisionIpcResult } from './environment-provision' -import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' -import { mapRuntimeError } from '../runtime/rpc/errors' - -const runtimeRecord = { - id: 'vm', - recipeId: 'sandbox', - repoId: 'source', - status: 'running' as const, - cleanupStatus: 'not_started' as const, - createdAt: 1, - updatedAt: 1 -} -const provisionedRoot: EphemeralVmProvisionIpcResult = { - ok: true, - connectionType: 'ssh', - sshTargetId: 'runtime-ssh-vm', - environmentId: 'env-vm', - expectedRefHead: 'source-head', - stderr: '', - warnings: [], - runtime: { - ...runtimeRecord, - recipeResult: { - schemaVersion: 2, - checkoutMode: 'provisioned-root', - connection: { - type: 'ssh', - projectRoot: '/checkout', - target: { host: 'vm', label: 'VM', username: 'orca', port: 22 } - } - } - } -} -// A VM whose SSH host runs a managed Orca server, with an ordinary (orca-worktree) checkout. -const managedServer: EphemeralVmProvisionIpcResult = { - ok: true, - connectionType: 'ssh', - sshTargetId: 'runtime-ssh-vm', - environmentId: 'env-server', - stderr: '', - warnings: [{ id: 'note', message: 'Using a shared image.' }], - runtime: { - ...runtimeRecord, - recipeResult: { - schemaVersion: 1, - connection: { - type: 'ssh', - projectRoot: '/repo', - target: { host: 'vm', label: 'VM', username: 'orca', port: 22 } - } - } - } -} -const remoteCapabilities = [ - PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, - WORKTREE_PROVISIONED_ROOT_RUNTIME_CAPABILITY -] -function okCall( - _env: string, - method: string, - _params: unknown -): Promise> { - const result = - method === 'status.get' - ? { capabilities: remoteCapabilities } - : method === 'projectHostSetup.setupExistingFolder' - ? { result: { repo: { id: 'remote-repo', path: '/checkout' } } } - : { - worktree: { - id: 'remote-repo::/checkout', - repoId: 'remote-repo', - path: '/checkout', - branch: 'refs/heads/user/task', - instanceId: 'instance' - } - } - return Promise.resolve({ id: 'req', ok: true, result, _meta: { runtimeId: 'remote' } }) -} -function makePorts(provisioned: EphemeralVmProvisionIpcResult = provisionedRoot) { - return { - provision: vi.fn(async (onPhase: (phase: RecipeWorkspaceCreatePhase) => void) => { - onPhase('running-create') - onPhase('connecting') - return provisioned - }), - call: vi.fn(okCall), - attach: vi.fn(), - cleanup: vi.fn( - async (): Promise<{ outcome: 'destroyed' | 'failed' | 'disabled'; error?: string }> => ({ - outcome: 'destroyed' - }) - ) - } -} -let ports = makePorts() -function request( - extra: Record = {}, - checkoutMode: EphemeralVmCheckoutMode = 'provisioned-root' -) { - return { - params: WorktreeCreate.parse({ - repo: 'id:source', - name: 'task', - recipeId: 'sandbox', - ...extra - }), - recipeId: 'sandbox', - checkoutMode, - ...(checkoutMode === 'provisioned-root' ? { branchName: 'user/task' } : {}), - projectId: 'git:project' - } -} -async function failure(promise: Promise): Promise { - const error = await promise.then( - () => null, - (caught: unknown) => caught - ) - if (!(error instanceof RecipeWorkspaceCreateError)) { - throw new Error(`expected a RecipeWorkspaceCreateError, got ${String(error)}`) - } - return error -} -beforeEach(() => { - ports = makePorts() -}) - -describe('provisioned-root recipe workspace creation', () => { - it('registers and adopts the pinned root on its server, then attaches the owner record', async () => { - const result = await createProvisionedRecipeWorkspace(request({ comment: 'handoff' }), ports) - expect(ports.call).toHaveBeenNthCalledWith( - 2, - 'env-vm', - 'projectHostSetup.setupExistingFolder', - { - projectId: 'git:project', - hostId: 'local', - path: '/checkout', - kind: 'git', - setupMethod: 'imported-existing-folder' - } - ) - expect(ports.call).toHaveBeenNthCalledWith( - 3, - 'env-vm', - 'worktree.adoptProvisionedRoot', - expect.objectContaining({ - repo: 'id:remote-repo', - branchNameOverride: 'user/task', - expectedPath: '/checkout', - expectedRefHead: 'source-head' - }) - ) - expect(ports.call.mock.calls.map(([, method]) => method)).toEqual([ - 'status.get', - 'projectHostSetup.setupExistingFolder', - 'worktree.adoptProvisionedRoot' - ]) - expect(ports.call.mock.calls[2]?.[2]).toMatchObject({ comment: 'handoff' }) - expect(ports.attach).toHaveBeenCalledWith('vm', 'remote-repo::/checkout') - expect(result).toMatchObject({ - recipe: { - id: 'sandbox', - runtimeId: 'vm', - environmentId: 'env-vm', - checkoutMode: 'provisioned-root' - }, - worktree: { hostId: 'runtime:env-vm' } - }) - expect(ports.cleanup).not.toHaveBeenCalled() - }) - it.each([ - { sparseCheckout: { directories: ['src'] } }, - { runHooks: true }, - { setupDecision: 'run' }, - { startupAgent: 'codex' }, - { name: '' } - ])('refuses unsupported inputs before provisioning: %j', async (extra) => { - await expect(createProvisionedRecipeWorkspace(request(extra), ports)).rejects.toThrow() - expect(ports.provision).not.toHaveBeenCalled() - }) - it('keeps lineage and the caller terminal out of the payload sent to the environment', async () => { - await createProvisionedRecipeWorkspace( - request({ - linkedGitLabIssue: 42, - parentWorkspace: 'id:local-parent', - cliProvenanceRequest: { callerTerminalHandle: 'term-local' } - }), - ports - ) - const adopt = ports.call.mock.calls.find( - ([, method]) => method === 'worktree.adoptProvisionedRoot' - ) - expect(adopt?.[2]).toMatchObject({ linkedGitLabIssue: 42, cliProvenanceRequest: {} }) - expect(adopt?.[2]).not.toHaveProperty('parentWorkspace') - }) -}) - -describe('orca-worktree recipe workspace creation', () => { - it('creates an ordinary worktree on the environment server, with setup and sparse checkout allowed', async () => { - ports = makePorts(managedServer) - const result = await createProvisionedRecipeWorkspace( - request( - { setupDecision: 'run', sparseCheckout: { directories: ['src'] }, comment: 'c' }, - 'orca-worktree' - ), - ports - ) - expect(ports.call.mock.calls.map(([, method]) => method)).toEqual([ - 'status.get', - 'projectHostSetup.setupExistingFolder', - 'worktree.create' - ]) - expect(ports.call).toHaveBeenLastCalledWith( - 'env-server', - 'worktree.create', - expect.objectContaining({ - repo: 'id:remote-repo', - name: 'task', - setupDecision: 'run', - sparseCheckout: { directories: ['src'] }, - comment: 'c' - }) - ) - expect(ports.call.mock.calls.at(-1)?.[2]).not.toHaveProperty('recipeId') - expect(result).toMatchObject({ - recipe: { environmentId: 'env-server', checkoutMode: 'orca-worktree' }, - worktree: { hostId: 'runtime:env-server' }, - environmentWarnings: ['Using a shared image.'] - }) - expect(ports.attach).toHaveBeenCalledWith('vm', 'remote-repo::/checkout') - }) - it('refuses an environment without an Orca server and destroys it', async () => { - const sshOnly = { ...provisionedRoot, environmentId: undefined } - ports = makePorts(sshOnly) - const error = await failure(createProvisionedRecipeWorkspace(request(), ports)) - expect(error.message).toContain('only the desktop app') - expect(ports.cleanup).toHaveBeenCalledWith('vm') - }) -}) - -describe('recipe create failures', () => { - it('reaches RPC callers with its code and failure data intact', () => { - const data = { - phase: 'checking-host' as const, - recipeId: 'sandbox', - environment: 'destroyed' as const - } - const response = mapRuntimeError( - 'req', - { runtimeId: 'host' }, - new RecipeWorkspaceCreateError('Boom.', data) - ) - expect(response.error).toEqual({ - code: 'recipe_workspace_create_failed', - message: 'Boom.', - data - }) - }) - it('reports the recipe failure code from the create step without a destroy', async () => { - ports.provision.mockResolvedValueOnce({ - ok: false, - error: 'The recipe create step did not finish within 2 minutes.', - errorCode: 'recipeTimedOut', - errorParams: { mode: 'create', timeout: '2 minutes' }, - stdout: '', - stderr: '' - }) - const error = await failure(createProvisionedRecipeWorkspace(request(), ports)) - expect(error.data).toEqual({ - phase: 'running-create', - recipeId: 'sandbox', - failureCode: 'recipeTimedOut', - failureParams: { mode: 'create', timeout: '2 minutes' } - }) - expect(ports.cleanup).not.toHaveBeenCalled() - }) - it('says whether the VM survived when the connect step fails after create', async () => { - ports.provision.mockResolvedValueOnce({ - ok: false, - error: 'SSH connect refused', - runtimeId: 'vm', - environmentCleanup: 'failed', - stdout: '', - stderr: '' - }) - const error = await failure(createProvisionedRecipeWorkspace(request(), ports)) - expect(error.message).toMatch(/SSH connect refused.*runtime vm\) may still be running/) - expect(error.data).toMatchObject({ runtimeId: 'vm', environment: 'destroy-failed' }) - expect(ports.cleanup).not.toHaveBeenCalled() - }) - it('names the failed step and confirms the destroy when the server lacks adoption support', async () => { - ports.call.mockImplementation(async () => ({ - id: 'req', - ok: true, - result: { capabilities: [] }, - _meta: { runtimeId: 'old' } - })) - const phases: RecipeWorkspaceCreatePhase[] = [] - const error = await failure( - createProvisionedRecipeWorkspace( - { ...request(), onPhase: (phase) => phases.push(phase) }, - ports - ) - ) - expect(error.message).toMatch(/Update Orca.*destroyed the new environment/) - expect(error.data).toMatchObject({ - phase: 'checking-host', - runtimeId: 'vm', - environment: 'destroyed' - }) - expect(phases).toEqual([ - 'running-create', - 'connecting', - 'checking-host', - 'destroying-after-failure' - ]) - expect(ports.attach).not.toHaveBeenCalled() - }) - it('says the machine may still run when its destroy also fails', async () => { - ports.call.mockImplementationOnce(async () => ({ - id: 'req', - ok: false, - error: { code: 'unreachable', message: 'Remote host unavailable' } - })) - ports.cleanup.mockResolvedValueOnce({ outcome: 'failed', error: 'Destroy exited with code 1.' }) - const error = await failure(createProvisionedRecipeWorkspace(request(), ports)) - expect(error.message).toMatch( - /Remote host unavailable.*runtime vm\) may still be running.*Destroy exited with code 1/ - ) - expect(error.data).toMatchObject({ environment: 'destroy-failed', phase: 'checking-host' }) - }) - it('never claims a destroy for a recipe without a destroy step', async () => { - ports.call.mockImplementationOnce(async () => { - throw new Error('socket closed') - }) - ports.cleanup.mockResolvedValueOnce({ outcome: 'disabled' }) - const error = await failure(createProvisionedRecipeWorkspace(request(), ports)) - expect(error.message).toMatch(/no destroy step.*runtime vm\) is still running/) - expect(error.message).not.toContain('Orca destroyed') - expect(error.data.environment).toBe('destroy-disabled') - }) - it('treats a throwing destroy as a failed destroy, not a lost error', async () => { - ports.call.mockImplementationOnce(async () => { - throw new Error('socket closed') - }) - ports.cleanup.mockRejectedValueOnce(new Error('Unknown ephemeral VM runtime: vm')) - const error = await failure(createProvisionedRecipeWorkspace(request(), ports)) - expect(error.data).toMatchObject({ - environment: 'destroy-failed', - destroyError: 'Unknown ephemeral VM runtime: vm' - }) - }) - it('destroys the environment when the caller disconnects after provisioning', async () => { - const controller = new AbortController() - ports.provision.mockImplementationOnce(async () => { - controller.abort() - return provisionedRoot - }) - const error = await failure( - createProvisionedRecipeWorkspace({ ...request(), signal: controller.signal }, ports) - ) - expect(ports.call).not.toHaveBeenCalled() - expect(ports.cleanup).toHaveBeenCalledTimes(1) - expect(error.data.environment).toBe('destroyed') - }) - it('checks agent support on the created server before adopting an agent workspace', async () => { - const error = await failure( - createProvisionedRecipeWorkspace(request({ createdWithAgent: 'codex' }), ports) - ) - expect(error.message).toContain('Update Orca') - expect(ports.cleanup).toHaveBeenCalledWith('vm') - expect(ports.attach).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ephemeral-vm/recipe-workspace-create.ts b/src/main/ephemeral-vm/recipe-workspace-create.ts deleted file mode 100644 index 1c147fe3d52..00000000000 --- a/src/main/ephemeral-vm/recipe-workspace-create.ts +++ /dev/null @@ -1,248 +0,0 @@ -import { toRuntimeExecutionHostId } from '../../shared/execution-host' -import { AGENT_LAUNCH_RUNTIME_CAPABILITY } from '../../shared/agent-launch/contracts/agent-launch-runtime-capability' -import { z } from 'zod' -import { WorktreeAdoptProvisionedRoot } from '../../shared/rpc-contract/worktree-provisioned-root-params' -import type { EphemeralVmCheckoutMode } from '../../shared/orca-yaml-hook-types' -import { - getEphemeralVmRecipeResultProjectRoot, - getEphemeralVmRecipeResultCheckoutMode -} from '../../shared/ephemeral-vm-recipes' -import { redactEphemeralVmRecipeDiagnosticText } from '../../shared/ephemeral-vm-recipe-diagnostics' -import { - PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, - WORKTREE_PROVISIONED_ROOT_RUNTIME_CAPABILITY -} from '../../shared/protocol-version' -import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' -import { - assertRecipeWorkspaceCreateSupported, - forwardedCreateFields, - RecipeWorkspaceResult as WorkspaceResult, - type RecipeWorkspaceCreateParams, - type RecipeWorkspaceCreation -} from './recipe-workspace-create-params' -import { - RECIPE_WORKSPACE_CREATE_FAILED_CODE, - type RecipeWorkspaceCreateFailureData, - type RecipeWorkspaceCreatePhase -} from '../../shared/recipe-workspace-create-progress' -import type { EphemeralVmProvisionIpcResult } from './environment-provision' - -export type { RecipeWorkspaceCreateParams, RecipeWorkspaceCreation } -const ENVIRONMENT_OUTCOME = { - destroyed: 'destroyed', - failed: 'destroy-failed', - disabled: 'destroy-disabled' -} as const satisfies Record> - -/** Never claim a destroy that did not happen: a failed or disabled one leaves a billed machine. */ -function environmentOutcomeSentence( - environment: NonNullable, - runtimeId: string, - destroyError?: string -): string { - if (environment === 'destroyed') { - return 'Orca destroyed the new environment.' - } - if (environment === 'destroy-disabled') { - return `The recipe has no destroy step, so the environment (runtime ${runtimeId}) is still running; remove it with your provider.` - } - return `The environment (runtime ${runtimeId}) may still be running because destroying it failed${destroyError ? `: ${destroyError}` : ''}. Retry the cleanup from Settings > Cloud VMs in Orca.` -} - -/** A failed recipe create; `data` says which step failed and whether its VM was destroyed. */ -export class RecipeWorkspaceCreateError extends Error { - readonly code = RECIPE_WORKSPACE_CREATE_FAILED_CODE - readonly data: RecipeWorkspaceCreateFailureData - - constructor(message: string, data: RecipeWorkspaceCreateFailureData) { - super(message) - this.data = data - } -} - -/** - * Creates a workspace on a fresh recipe environment: provision (through the same main-side - * provisioning the desktop uses), register the project on the environment's Orca, then create or - * adopt the workspace there. Any failure after the VM exists destroys it before rethrowing. - */ -export async function createProvisionedRecipeWorkspace( - args: { - params: RecipeWorkspaceCreateParams - recipeId: string - checkoutMode: EphemeralVmCheckoutMode - /** Provisioned-root recipes receive the branch up front; orca-worktree ones pick it on the VM. */ - branchName?: string - projectId: string - signal?: AbortSignal - onPhase?: (phase: RecipeWorkspaceCreatePhase) => void - }, - ports: { - provision: ( - onPhase: (phase: RecipeWorkspaceCreatePhase) => void - ) => Promise - call: ( - environmentId: string, - method: string, - params: unknown - ) => Promise> - attach: (runtimeId: string, workspaceId: string) => void - /** Destroys the VM; `disabled` means the recipe has no destroy step, so nothing ran. */ - cleanup: ( - runtimeId: string - ) => Promise<{ outcome: 'destroyed' | 'failed' | 'disabled'; error?: string }> - } -): Promise { - const { params, recipeId } = args - assertRecipeWorkspaceCreateSupported(params, args.checkoutMode) - let phase: RecipeWorkspaceCreatePhase = 'running-create' - const enter = (next: RecipeWorkspaceCreatePhase): void => { - phase = next - args.onPhase?.(next) - } - const provisioned = await ports.provision(enter) - if (!provisioned.ok) { - const error = redactEphemeralVmRecipeDiagnosticText(provisioned.error) - const environment = provisioned.environmentCleanup - ? ENVIRONMENT_OUTCOME[provisioned.environmentCleanup] - : undefined - const data: RecipeWorkspaceCreateFailureData = { - phase, - recipeId, - ...(provisioned.errorCode ? { failureCode: provisioned.errorCode } : {}), - ...(provisioned.errorParams ? { failureParams: provisioned.errorParams } : {}), - ...(provisioned.runtimeId ? { runtimeId: provisioned.runtimeId } : {}), - ...(environment ? { environment } : {}) - } - throw new RecipeWorkspaceCreateError( - provisioned.runtimeId && environment - ? `${error} ${environmentOutcomeSentence(environment, provisioned.runtimeId)}` - : error, - data - ) - } - const runtimeId = provisioned.runtime.id - try { - const checkoutMode = getEphemeralVmRecipeResultCheckoutMode(provisioned.runtime.recipeResult) - const environmentId = - provisioned.connectionType === 'orca-server' - ? provisioned.environment.id - : provisioned.environmentId - if (!environmentId) { - throw new Error( - "This recipe's environment does not run an Orca server, so only the desktop app can create workspaces on it." - ) - } - if (checkoutMode === 'provisioned-root' && provisioned.connectionType !== 'ssh') { - throw new Error('Provisioned-root recipes currently require a direct SSH connection.') - } - const call = async (method: string, payload: unknown): Promise => { - args.signal?.throwIfAborted() - const response = await ports.call(environmentId, method, payload) - if (!response.ok) { - throw new Error(redactEphemeralVmRecipeDiagnosticText(response.error.message)) - } - return response.result - } - enter('checking-host') - const status = z - .object({ capabilities: z.array(z.string()) }) - .parse(await call('status.get', undefined)) - const requiredCapabilities = [ - PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, - ...(checkoutMode === 'provisioned-root' - ? [WORKTREE_PROVISIONED_ROOT_RUNTIME_CAPABILITY] - : []), - // The CLI checks prompt and presentation support itself when it launches the agent. - ...(params.createdWithAgent ? [AGENT_LAUNCH_RUNTIME_CAPABILITY] : []) - ] - if (!requiredCapabilities.every((capability) => status.capabilities.includes(capability))) { - throw new Error( - 'Update Orca on the recipe-created environment before creating this workspace.' - ) - } - enter('registering-project') - const projectRoot = getEphemeralVmRecipeResultProjectRoot(provisioned.runtime.recipeResult) - const setup = z - .object({ result: z.object({ repo: z.object({ id: z.string(), path: z.string() }) }) }) - .parse( - await call('projectHostSetup.setupExistingFolder', { - projectId: args.projectId, - hostId: 'local', - path: projectRoot, - kind: 'git', - setupMethod: 'imported-existing-folder' - }) - ) - enter('creating-workspace') - const repo = `id:${setup.result.repo.id}` - let result: z.infer - if (checkoutMode === 'provisioned-root') { - if ( - !args.branchName || - provisioned.connectionType !== 'ssh' || - !provisioned.expectedRefHead - ) { - throw new Error('The provisioned-root recipe did not report its checked-out start ref.') - } - result = WorkspaceResult.parse( - await call( - 'worktree.adoptProvisionedRoot', - WorktreeAdoptProvisionedRoot.parse({ - ...forwardedCreateFields(params), - repo, - branchNameOverride: args.branchName, - expectedPath: projectRoot, - expectedRefHead: provisioned.expectedRefHead, - cliProvenanceRequest: {} - }) - ) - ) - } else { - result = WorkspaceResult.parse( - await call('worktree.create', { - ...forwardedCreateFields(params), - repo, - cliProvenanceRequest: {} - }) - ) - } - ports.attach(runtimeId, result.worktree.id) - const warnings = provisioned.warnings.map((entry) => entry.message) - return { - ...result, - worktree: { - ...result.worktree, - hostId: toRuntimeExecutionHostId(environmentId), - runtimeOwnerEnvironmentId: environmentId - }, - recipe: { id: recipeId, runtimeId, environmentId, checkoutMode }, - ...(warnings.length > 0 ? { environmentWarnings: warnings } : {}) - } - } catch (error) { - const failedPhase = phase - const original = redactEphemeralVmRecipeDiagnosticText( - error instanceof Error ? error.message : String(error) - ) - enter('destroying-after-failure') - const cleaned = await ports.cleanup(runtimeId).then( - (result) => result, - (cleanupError: unknown) => ({ - outcome: 'failed' as const, - error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError) - }) - ) - const data: RecipeWorkspaceCreateFailureData = { - phase: failedPhase, - recipeId, - runtimeId, - environment: ENVIRONMENT_OUTCOME[cleaned.outcome], - ...(cleaned.error - ? { destroyError: redactEphemeralVmRecipeDiagnosticText(cleaned.error) } - : {}) - } - throw new RecipeWorkspaceCreateError( - `${original} ${environmentOutcomeSentence(data.environment ?? 'destroy-failed', runtimeId, data.destroyError)}`, - data - ) - } -} diff --git a/src/main/ipc/ephemeral-vm-runtime-handlers.ts b/src/main/ipc/ephemeral-vm-runtime-handlers.ts index af566602f62..95240974d55 100644 --- a/src/main/ipc/ephemeral-vm-runtime-handlers.ts +++ b/src/main/ipc/ephemeral-vm-runtime-handlers.ts @@ -5,16 +5,27 @@ import { updateEphemeralVmRuntimeStatus } from '../../shared/ephemeral-vm-runtime-store' import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' -import { cleanupOwnedEphemeralVmRuntime } from '../ephemeral-vm/owned-runtime-cleanup' +import { releaseEphemeralVmRuntimeEnvironments } from '../ephemeral-vm/runtime-environment-release' +import { cleanupEphemeralVmRuntime } from '../ephemeral-vm/runtime-service' import { stopEphemeralVmRuntimeCleanup } from '../ephemeral-vm/runtime-cleanup-control' +import { removeEphemeralVmRuntimeSshTarget } from '../ephemeral-vm/runtime-ssh-cleanup' import { buildEphemeralVmRecipeCleanupCommand, buildEphemeralVmRecipeCleanupPayload } from '../../shared/ephemeral-vm-recipe-lifecycle-payload' +import { removeRuntimeOwnedSshTarget } from '../ephemeral-vm/runtime-ssh' import { getRuntimeRecipeContext } from './ephemeral-vm-recipe-context' -import { ephemeralVmFailure } from '../../shared/ephemeral-vm-failure-copy' +import { + ephemeralVmFailure, + ephemeralVmFailureFromError +} from '../../shared/ephemeral-vm-failure-copy' +import { invalidateRuntimeEnvironmentTransport } from './runtime-environments/runtime-environments' +import { retireRemovedRuntimeEnvironment } from './runtime-environments/runtime-environment-removal-cleanup' import { attachEphemeralVmRuntimeToWorkspace } from '../ephemeral-vm/runtime-attachment' -import { forgetInterruptedEphemeralVmProvision } from '../ephemeral-vm/runtime-provisioning-persistence' +import { + forgetInterruptedEphemeralVmProvision, + isEphemeralVmProvisionLive +} from '../ephemeral-vm/runtime-provisioning-persistence' export type EphemeralVmCleanupCommandResult = { runtimeId: string @@ -50,7 +61,67 @@ export function registerEphemeralVmRuntimeHandlers(store: Store): void { ipcMain.handle( 'ephemeralVm:cleanup', async (_event, args: { runtimeId: string }): Promise => { - return cleanupOwnedEphemeralVmRuntime(store, app.getPath('userData'), args.runtimeId) + const userDataPath = app.getPath('userData') + const runtime = listEphemeralVmRuntimes(userDataPath).find( + (entry) => entry.id === args.runtimeId + ) + if (!runtime) { + throw new Error(`Unknown ephemeral VM runtime: ${args.runtimeId}`) + } + if (runtime.status === 'provisioning' && isEphemeralVmProvisionLive(runtime.id)) { + // Why: don't mark a create in flight as cleanup_failed; its own outcome settles the row. + throw new Error(`Ephemeral VM runtime is still provisioning: ${runtime.id}`) + } + let result + if (runtime.cleanupStatus === 'succeeded') { + result = { ok: true as const, runtime, skipped: false } + } else { + let resolved: ReturnType + try { + resolved = getRuntimeRecipeContext(store, userDataPath, runtime.id) + } catch (error) { + const failed = updateEphemeralVmRuntimeStatus(userDataPath, runtime.id, { + status: 'cleanup_failed', + cleanupStatus: 'failed', + cleanupLastAttemptAt: Date.now(), + cleanupLastError: ephemeralVmFailureFromError(error) + }) + return removeEphemeralVmRuntimeSshTarget({ + userDataPath, + runtime: failed, + removeTarget: removeRuntimeOwnedSshTarget + }) + } + result = await cleanupEphemeralVmRuntime({ + userDataPath, + repoPath: resolved.repoPath, + recipe: resolved.recipe, + runtimeId: runtime.id + }) + } + if (result.ok) { + try { + await releaseEphemeralVmRuntimeEnvironments(userDataPath, runtime, (environmentId) => { + void retireRemovedRuntimeEnvironment( + environmentId, + invalidateRuntimeEnvironmentTransport, + store, + userDataPath + ) + }) + } catch { + // Cleanup of provider resources matters more than hiding a stale local + // environment row; users can still remove that manually. + } + } + if (!result.ok) { + return result.runtime + } + return removeEphemeralVmRuntimeSshTarget({ + userDataPath, + runtime: result.runtime, + removeTarget: removeRuntimeOwnedSshTarget + }) } ) diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index 369a69d289e..e322668b02e 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -1,27 +1,78 @@ import { app, ipcMain } from 'electron' import type { Store } from '../persistence/loading-store/store' -import type { EphemeralVmRecipeDoctorResult } from '../../shared/ephemeral-vm-recipes' -import { redactEphemeralVmRecipeDiagnosticText } from '../../shared/ephemeral-vm-recipe-diagnostics' +import { + getEphemeralVmRecipeResultConnection, + type EphemeralVmRecipeDoctorResult +} from '../../shared/ephemeral-vm-recipes' +import { + getEphemeralVmRecipeResultWarnings, + redactEphemeralVmRecipeDiagnosticText, + type EphemeralVmRecipeResultWarning +} from '../../shared/ephemeral-vm-recipe-diagnostics' +import { getProvisionedRootRecipeRepoUrl } from '../../shared/ephemeral-vm-recipe-repo-url' // Import the Node-only doctor directly so browser consumers of the barrel do not bundle fs/path. import { doctorEphemeralVmRecipe } from '../../shared/ephemeral-vm-recipe-doctor' -import { reconcileInterruptedEphemeralVmProvisionsOnStartup } from '../ephemeral-vm/runtime-provisioning-persistence' +import { updateEphemeralVmRuntimeStatus } from '../../shared/ephemeral-vm-runtime-store' import { - provisionRecipeEnvironment, - type EphemeralVmProvisionIpcResult -} from '../ephemeral-vm/environment-provision' + requireEphemeralVmRecipeResult, + type EphemeralVmProvisionedRuntimeRecord +} from '../../shared/ephemeral-vm-runtimes' +import { addEnvironmentFromPairingCode } from '../../shared/remote-runtime/host-store/runtime-environment-store' +import { + redactRuntimeEnvironment, + type PublicKnownRuntimeEnvironment +} from '../../shared/remote-runtime/host-catalog/runtime-environments' +import { + cleanupEphemeralVmRuntime, + provisionEphemeralVmRuntime +} from '../ephemeral-vm/runtime-service' +import { connectRuntimeOwnedSshTarget } from '../ephemeral-vm/runtime-ssh' +import { reconcileInterruptedEphemeralVmProvisionsOnStartup } from '../ephemeral-vm/runtime-provisioning-persistence' import { getRecipeRepo, listRecipeCatalog, listRecipes, + resolveRecipeForRepo, type EphemeralVmRecipeCatalogEntry } from './ephemeral-vm-recipe-context' import { registerEphemeralVmRuntimeHandlers } from './ephemeral-vm-runtime-handlers' import type { PluginService } from '../plugins/plugin-service' import { getApprovedPluginVmRecipes } from '../plugins/plugin-approved-vm-recipes' +import { resolveProvisionedRootSource } from '../ephemeral-vm/provisioned-root-source' +import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/runtime-environment-registry-root' +import { + ephemeralVmFailure, + pickEphemeralVmFailureCode, + type EphemeralVmFailure +} from '../../shared/ephemeral-vm-failure-copy' const activeProvisionControllers = new Map() -export type { EphemeralVmProvisionIpcResult } +export type EphemeralVmProvisionIpcResult = + | { + ok: true + connectionType: 'orca-server' + runtime: EphemeralVmProvisionedRuntimeRecord + environment: PublicKnownRuntimeEnvironment + stderr: string + warnings: EphemeralVmRecipeResultWarning[] + } + | { + ok: true + connectionType: 'ssh' + runtime: EphemeralVmProvisionedRuntimeRecord + sshTargetId: string + /** The managed Orca server the host runs; its workspace lives there. */ + environmentId?: string + expectedRefHead?: string + stderr: string + warnings: EphemeralVmRecipeResultWarning[] + } + | ({ + ok: false + stderr: string + stdout: string + } & EphemeralVmFailure) export function registerEphemeralVmHandlers(store: Store, pluginService?: PluginService): void { ipcMain.removeHandler('ephemeralVm:listRecipes') @@ -78,6 +129,18 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin provisionId?: string } ): Promise => { + const repo = getRecipeRepo(store, args.repoId) + if (!repo.ok) { + return provisionFailure(repo.failure) + } + const recipe = resolveRecipeForRepo( + repo.repo.path, + args.recipeId, + await getApprovedPluginVmRecipes(pluginService) + ) + if (!recipe) { + return provisionFailure(ephemeralVmFailure('recipeNotFound', { recipeId: args.recipeId })) + } const controller = args.provisionId ? new AbortController() : null if (args.provisionId && controller) { activeProvisionControllers.set(args.provisionId, controller) @@ -94,17 +157,129 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin } // Retain cancellation registration until every signal-consuming provisioning phase settles. try { - return await provisionRecipeEnvironment( - store, - app.getPath('userData'), - args, - await getApprovedPluginVmRecipes(pluginService), - { - signal: controller?.signal, - onStdout: (chunk) => sendProvisionEvent('stdout', chunk), - onStderr: (chunk) => sendProvisionEvent('stderr', chunk) + let recipeRepoUrl = repo.repo.gitRemoteIdentity?.remoteUrl + let sourceRef = args.ref + let expectedRefHead: string | undefined + if (recipe.checkoutMode === 'provisioned-root') { + const source = await resolveProvisionedRootSource( + store, + repo.repo, + args.ref, + controller?.signal + ) + if (controller?.signal.aborted) { + return provisionFailure(ephemeralVmFailure('provisionCancelled')) } + if (!source) { + return provisionFailure( + args.ref + ? ephemeralVmFailure('startRefUnresolved', { ref: args.ref }) + : ephemeralVmFailure('defaultStartRefUnresolved') + ) + } + sourceRef = source.ref + expectedRefHead = source.head + recipeRepoUrl = source.remoteUrl ?? recipeRepoUrl + } + const repoUrl = getProvisionedRootRecipeRepoUrl(recipe.checkoutMode, recipeRepoUrl) + const result = await provisionEphemeralVmRuntime({ + userDataPath: app.getPath('userData'), + repoPath: repo.repo.path, + repoId: repo.repo.id, + recipe, + projectId: args.projectId, + workspaceId: args.workspaceId, + workspaceName: args.workspaceName, + ...(repoUrl ? { repoUrl } : {}), + ...(args.branch ? { branch: args.branch } : {}), + ...(sourceRef ? { ref: sourceRef } : {}), + ...(expectedRefHead ? { expectedRefHead } : {}), + ...(controller ? { signal: controller.signal } : {}), + onStdout: (chunk) => sendProvisionEvent('stdout', chunk), + onStderr: (chunk) => sendProvisionEvent('stderr', chunk) + }) + if (!result.ok) { + return { + ok: false, + error: result.start.error, + ...pickEphemeralVmFailureCode(result.start), + stdout: redactEphemeralVmRecipeDiagnosticText(result.start.stdout), + stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) + } + } + const connection = getEphemeralVmRecipeResultConnection(result.start.result) + if (connection.type === 'ssh') { + try { + const ssh = await connectRuntimeOwnedSshTarget({ + runtimeId: result.runtime.id, + connection + }) + const runtime = requireEphemeralVmRecipeResult( + updateEphemeralVmRuntimeStatus(app.getPath('userData'), result.runtime.id, { + sshTargetId: ssh.targetId, + runtimeEnvironmentId: ssh.environmentId + }) + ) + return { + ok: true, + connectionType: 'ssh', + runtime, + sshTargetId: ssh.targetId, + environmentId: ssh.environmentId, + ...(expectedRefHead ? { expectedRefHead } : {}), + stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr), + warnings: getEphemeralVmRecipeResultWarnings(result.start.result) + } + } catch (error) { + await cleanupEphemeralVmRuntime({ + userDataPath: app.getPath('userData'), + repoPath: repo.repo.path, + recipe, + runtimeId: result.runtime.id + }).catch(() => undefined) + return { + ok: false, + error: error instanceof Error ? error.message : String(error), + stdout: redactEphemeralVmRecipeDiagnosticText(result.start.stdout), + stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) + } + } + } + + let environment: ReturnType + try { + environment = addEnvironmentFromPairingCode(getRuntimeEnvironmentRegistryRoot(), { + name: buildEphemeralEnvironmentName(repo.repo.displayName, result.runtime.id), + pairingCode: connection.pairingCode, + source: 'ephemeral-vm' + }) + } catch (error) { + await cleanupEphemeralVmRuntime({ + userDataPath: app.getPath('userData'), + repoPath: repo.repo.path, + recipe, + runtimeId: result.runtime.id + }).catch(() => undefined) + return { + ok: false, + error: error instanceof Error ? error.message : String(error), + stdout: redactEphemeralVmRecipeDiagnosticText(result.start.stdout), + stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) + } + } + const runtime = requireEphemeralVmRecipeResult( + updateEphemeralVmRuntimeStatus(app.getPath('userData'), result.runtime.id, { + runtimeEnvironmentId: environment.id + }) ) + return { + ok: true, + connectionType: 'orca-server', + runtime, + environment: redactRuntimeEnvironment(environment), + stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr), + warnings: getEphemeralVmRecipeResultWarnings(result.start.result) + } } finally { if (args.provisionId) { activeProvisionControllers.delete(args.provisionId) @@ -126,3 +301,11 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin } ) } + +function buildEphemeralEnvironmentName(repoName: string, runtimeId: string): string { + return `${repoName} VM ${runtimeId.slice(-8)}` +} + +function provisionFailure(failure: EphemeralVmFailure): EphemeralVmProvisionIpcResult { + return { ok: false, ...failure, stdout: '', stderr: '' } +} diff --git a/src/main/runtime/hosts/runtime-status.ts b/src/main/runtime/hosts/runtime-status.ts index 88ea3651bc1..7126bd28a12 100644 --- a/src/main/runtime/hosts/runtime-status.ts +++ b/src/main/runtime/hosts/runtime-status.ts @@ -25,8 +25,7 @@ import { import { MANAGED_SERVER_RUNTIME_CAPABILITY, - REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY, - WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY + REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../shared/host-runtime-capabilities' import { SESSION_TABS_AUTHORITATIVE_INVENTORY_RUNTIME_CAPABILITY } from '../../../shared/session-tabs-runtime-capabilities' import { @@ -62,11 +61,6 @@ import { supportsDurableTerminalPromptDelivery } from '../terminal/input/durable import { RuntimeWorkspaceChangeEvents } from '../workspaces/catalog/runtime-workspace-change-events' export abstract class OrcaRuntimeWithGetStatus extends RuntimeWorkspaceChangeEvents { - /** Only a host wired with a recipe runner (the desktop) advertises recipe workspace creation. */ - supportsRecipeWorkspaceCreation(): boolean { - return false - } - getStatus(): RuntimeStatus { // Advertise screencast for renderer/offscreen backends; headless ownership prevents client-local fallback. const hasRenderer = Boolean(this.getAvailableAuthoritativeWindow()) @@ -99,9 +93,6 @@ export abstract class OrcaRuntimeWithGetStatus extends RuntimeWorkspaceChangeEve // Only hosts running their own usage poller can consume saved keys. (capability !== USAGE_CREDENTIALS_RUNTIME_CAPABILITY || this.getUsageRateLimits() !== null) ) - if (this.supportsRecipeWorkspaceCreation()) { - capabilities.push(WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY) - } if (hasOffscreen || hasHeadlessCommands) { capabilities.push(BROWSER_HEADLESS_RUNTIME_CAPABILITY) } diff --git a/src/main/runtime/repositories/runtime-remote-fetch-operations.ts b/src/main/runtime/repositories/runtime-remote-fetch-operations.ts index 7ffaf6644f5..dd805312c6b 100644 --- a/src/main/runtime/repositories/runtime-remote-fetch-operations.ts +++ b/src/main/runtime/repositories/runtime-remote-fetch-operations.ts @@ -1,8 +1,8 @@ import type { LocalGitExecOptions } from '../../git/repo-default-base-ref' import type { RemoteFetchResult, RemoteTrackingBase } from './runtime-remote-fetch-controller' -import { RuntimeRecipeWorkspaceCreation } from '../workspaces/creation/runtime-recipe-workspace-creation' +import { RuntimeProvisionedWorkspaceAdoption } from '../workspaces/creation/runtime-provisioned-workspace-adoption' -export abstract class RuntimeRemoteFetchOperations extends RuntimeRecipeWorkspaceCreation { +export abstract class RuntimeRemoteFetchOperations extends RuntimeProvisionedWorkspaceAdoption { async getCanonicalFetchKey( repoPath: string, remote: string, diff --git a/src/main/runtime/rpc/core.ts b/src/main/runtime/rpc/core.ts index 27e129a00cc..e252387ad04 100644 --- a/src/main/runtime/rpc/core.ts +++ b/src/main/runtime/rpc/core.ts @@ -2,7 +2,6 @@ import type { RuntimeClientCapabilities } from './runtime-client-capabilities' import type { ZodError, ZodType } from 'zod' import type { TerminalStreamFrame } from '../../../shared/terminal/stream/terminal-stream-protocol' import type { OrcaRuntimeService } from '../orca-runtime' -import type { RuntimeRpcProgress } from '../../../shared/runtime-rpc-envelope' import type { OrchestrationCompatibilityCallerAuthority } from '../orchestration/terminal-authority/orchestration-compatibility-authority' import type { StructuredAgentCliSourceEvidence } from '../../native-chat/structured-agent-cli-source' import type { @@ -137,8 +136,6 @@ export type RpcContext = { markWorkerDoneMutationEffectFree?: () => void // Prompt retries stop once PTY write effects become ambiguous. markMutationEffectPossible?: () => void - // Long polls on a local socket may report named progress steps to the waiting client. - reportProgress?: (progress: RuntimeRpcProgress) => void // Commit operation identity with worker-start so crash recovery can inspect it. orchestrationMutation?: { callerFingerprint: string diff --git a/src/main/runtime/rpc/dispatcher-stream-options.ts b/src/main/runtime/rpc/dispatcher-stream-options.ts index b4b8f7db0e3..551b7db074d 100644 --- a/src/main/runtime/rpc/dispatcher-stream-options.ts +++ b/src/main/runtime/rpc/dispatcher-stream-options.ts @@ -27,7 +27,6 @@ export type RpcDispatchStreamingOptions = Pick< | 'sendBinary' | 'registerBinaryStreamHandler' | 'registerBinaryMessageHandler' - | 'reportProgress' > & { /** What the transport proved the caller may do; absent means this host's owner. */ callerScope?: RpcCallerScope @@ -81,7 +80,6 @@ export function rpcContextFromTransport( sendBinary: options?.sendBinary, registerBinaryStreamHandler: options?.registerBinaryStreamHandler, registerBinaryMessageHandler: options?.registerBinaryMessageHandler, - reportProgress: options?.reportProgress, orchestrationCaller } } diff --git a/src/main/runtime/rpc/errors.ts b/src/main/runtime/rpc/errors.ts index 38504a90d6a..4fe418b297c 100644 --- a/src/main/runtime/rpc/errors.ts +++ b/src/main/runtime/rpc/errors.ts @@ -40,7 +40,6 @@ import { PLUGIN_CLI_ERROR_CODES } from '../../../shared/plugins/approval/plugin- import { GIT_DIFF_TOO_LARGE_CODE } from '../../../shared/git/diff/git-diff-transport-budget' import { AUTOMATION_OWNER_CONFLICT_CODES } from '../../../shared/automations/ownership/automation-owner-conflict' import { ARCHIVE_HOOK_FAILED_REMOVAL_CODE } from '../../../shared/worktree/archive-hook-removal-gate' -import { RECIPE_WORKSPACE_CREATE_FAILED_CODE } from '../../../shared/recipe-workspace-create-progress' import { NESTED_WORKER_DEPTH_EXCEEDED_CODE } from '../../../shared/orchestration/workers/nested-worker-depth' import { PROJECT_RUNTIME_REPAIR_REQUIRED_CODE } from '../../../shared/project-runtime-repair-message' import { @@ -176,8 +175,6 @@ const STRUCTURED_RUNTIME_PASSTHROUGH_CODES: ReadonlySet = new Set([ 'invalid_argument', // Preserve archive-hook failure so callers can retry, waive or skip it (#19334). ARCHIVE_HOOK_FAILED_REMOVAL_CODE, - // The failed step, the recipe failure code and whether the new VM was destroyed ride in data. - RECIPE_WORKSPACE_CREATE_FAILED_CODE, // Paired-only method refusal must match the mobile transport allowlist's forbidden code. 'forbidden', NESTED_WORKER_DEPTH_EXCEEDED_CODE, @@ -242,8 +239,21 @@ export function mapRuntimeError(id: string, meta: RpcEnvelopeMeta, error: unknow error instanceof Error && 'code' in error && typeof (error as { code: unknown }).code === 'string' && - (LINEAR_PASSTHROUGH_CODES.has((error as { code: string }).code) || - STRUCTURED_RUNTIME_PASSTHROUGH_CODES.has((error as { code: string }).code)) + LINEAR_PASSTHROUGH_CODES.has((error as { code: string }).code) + ) { + return errorResponse( + id, + meta, + (error as { code: string }).code, + message, + (error as { data?: unknown }).data + ) + } + if ( + error instanceof Error && + 'code' in error && + typeof (error as { code: unknown }).code === 'string' && + STRUCTURED_RUNTIME_PASSTHROUGH_CODES.has((error as { code: string }).code) ) { return errorResponse( id, diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-target-authorization.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-target-authorization.ts index 1e6c8d13ca8..d511aa5067a 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-target-authorization.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-target-authorization.ts @@ -12,20 +12,9 @@ const CREATE_METHOD_BY_TARGET_KIND = { } as const satisfies Record, string> export function assertAgentLaunchTargetAuthorized( - target: Pick & { create?: unknown }, + target: Pick, context: Pick ): void { - if ( - target.kind === 'create-worktree' && - typeof target.create === 'object' && - target.create !== null && - 'recipeId' in target.create && - target.create.recipeId !== undefined - ) { - throw new Error( - 'Create the recipe workspace first, then launch the agent on its execution host.' - ) - } // `clientKind` is the paired device's scope, stamped from its validated token. if (target.kind === 'existing' || context.clientKind !== 'mobile') { return diff --git a/src/main/runtime/rpc/methods/workspaces/vm-recipe-list-method.ts b/src/main/runtime/rpc/methods/workspaces/vm-recipe-list-method.ts deleted file mode 100644 index 0f7073b5f4e..00000000000 --- a/src/main/runtime/rpc/methods/workspaces/vm-recipe-list-method.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { VmRecipeList } from '../../../../../shared/rpc-contract/vm-recipe-params' -import { defineMethod } from '../../core' - -/** The environment recipes `worktree.create` with `recipeId` accepts on this host. */ -export const VM_RECIPE_LIST_METHOD = defineMethod({ - name: 'vmRecipe.list', - permission: 'workspace', - params: VmRecipeList, - handler: async (params, { runtime }) => ({ - repos: await runtime.listEnvironmentRecipes(params.repo) - }) -}) diff --git a/src/main/runtime/rpc/methods/workspaces/worktree-provisioned-root-method.ts b/src/main/runtime/rpc/methods/workspaces/worktree-provisioned-root-method.ts index 0de28320769..d5f43b17663 100644 --- a/src/main/runtime/rpc/methods/workspaces/worktree-provisioned-root-method.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree-provisioned-root-method.ts @@ -1,4 +1,3 @@ -import { buildCliWorkspaceProvenance } from '../../../../../shared/cli-workspace-provenance' import { getLocalWorktreeCatalogVersion } from '../../../../workspaces/catalog/local-worktree-scan-generation' import { WorktreeAdoptProvisionedRoot } from '../../../../../shared/rpc-contract/worktree-provisioned-root-params' import { defineMethod } from '../../core' @@ -8,22 +7,10 @@ export const WORKTREE_PROVISIONED_ROOT_METHOD = defineMethod({ permission: 'workspace', params: WorktreeAdoptProvisionedRoot, handler: async (params, { runtime }) => { - const { - repo, - linkedIssue, - linkedPR, - linkedGitLabMR, - linkedGitLabIssue, - cliProvenanceRequest, - ...request - } = params + const { repo, linkedIssue, linkedPR, linkedGitLabMR, linkedGitLabIssue, ...request } = params // Why: null clears a link on update; a fresh adoption has nothing to clear. const result = await runtime.adoptManagedProvisionedRoot(repo, { ...request, - cliProvenance: buildCliWorkspaceProvenance(cliProvenanceRequest, { - startupAgent: request.createdWithAgent, - createdAt: Date.now() - }), linkedIssue: linkedIssue ?? undefined, linkedPR: linkedPR ?? undefined, linkedGitLabMR: linkedGitLabMR ?? undefined, diff --git a/src/main/runtime/rpc/methods/workspaces/worktree-recipe-create-method.test.ts b/src/main/runtime/rpc/methods/workspaces/worktree-recipe-create-method.test.ts deleted file mode 100644 index 6084c9bd658..00000000000 --- a/src/main/runtime/rpc/methods/workspaces/worktree-recipe-create-method.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import '../../unused-default-rpc-methods.test-fixture' -import { expect, it, vi } from 'vitest' -import { RpcDispatcher } from '../../dispatcher' -import type { OrcaRuntimeService } from '../../../orca-runtime' -import { WORKTREE_METHODS } from './worktree' -import { assertAgentLaunchTargetAuthorized } from '../agent-launch/agent-launch-target-authorization' -import { classifyRuntimeLongPoll } from '../../server/runtime-rpc-long-poll' - -function makeRuntime() { - const createManagedRecipeWorkspace = vi.fn( - async (_params: unknown, options: { onPhase?: (phase: string) => void }) => { - options.onPhase?.('running-create') - return { recipe: { environmentId: 'vm-host' } } - } - ) - const createManagedWorktree = vi.fn() - const dedupeWorktreeCreate = vi.fn( - async (_repo: string, _mutation: string | undefined, run: () => Promise) => run() - ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this branch only reads the runtime id, deduplication and recipe creation ports supplied below. - const runtime = { - getRuntimeId: () => 'source-host', - dedupeWorktreeCreate, - createManagedRecipeWorkspace, - createManagedWorktree - } as unknown as OrcaRuntimeService - return { runtime, createManagedRecipeWorkspace, createManagedWorktree } -} - -const recipeCreate = { - id: 'req', - authToken: 'token', - method: 'worktree.create', - params: { repo: 'id:source', name: 'task', recipeId: 'sandbox' } -} - -it('reports named progress steps to a local caller', async () => { - const { runtime } = makeRuntime() - const reportProgress = vi.fn() - const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }) - await dispatcher.dispatch(recipeCreate, { reportProgress }) - expect(reportProgress).toHaveBeenCalledWith({ phase: 'running-create' }) -}) - -it('refuses a recipe create from a paired device before provisioning', async () => { - const { runtime, createManagedRecipeWorkspace, createManagedWorktree } = makeRuntime() - const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }) - const response = await dispatcher.dispatch(recipeCreate, { clientKind: 'mobile' }) - expect(response).toMatchObject({ ok: false, error: { code: 'forbidden' } }) - expect(createManagedRecipeWorkspace).not.toHaveBeenCalled() - expect(createManagedWorktree).not.toHaveBeenCalled() -}) - -it('dispatches recipe creation through the host recipe service and deduplicates it', async () => { - const createManagedRecipeWorkspace = vi - .fn() - .mockResolvedValue({ recipe: { environmentId: 'vm-host' } }) - const createManagedWorktree = vi.fn() - const dedupeWorktreeCreate = vi.fn( - async (_repo: string, _mutation: string | undefined, run: () => Promise) => run() - ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this branch only reads the runtime id, deduplication and recipe creation ports supplied below. - const runtime = { - getRuntimeId: () => 'source-host', - dedupeWorktreeCreate, - createManagedRecipeWorkspace, - createManagedWorktree - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }) - const response = await dispatcher.dispatch({ - id: 'req', - authToken: 'token', - method: 'worktree.create', - params: { - repo: 'id:source', - name: 'task', - recipeId: 'sandbox', - clientMutationId: 'create-1' - } - }) - expect(response).toMatchObject({ ok: true, result: { recipe: { environmentId: 'vm-host' } } }) - expect(dedupeWorktreeCreate).toHaveBeenCalledWith( - expect.objectContaining({ repo: 'id:source' }), - 'create-1', - expect.any(Function) - ) - expect(createManagedRecipeWorkspace).toHaveBeenCalledWith( - expect.objectContaining({ recipeId: 'sandbox' }), - expect.any(Object) - ) - expect(createManagedWorktree).not.toHaveBeenCalled() -}) - -it('refuses a recipe embedded in agent.launch before it can become an ordinary local create', () => { - expect(() => - assertAgentLaunchTargetAuthorized( - { kind: 'create-worktree', create: { recipeId: 'sandbox' } }, - {} - ) - ).toThrow('Create the recipe workspace first') -}) - -it('keeps provisioning alive while preserving the ordinary create transport policy', () => { - const request = { id: 'req', authToken: 'token', method: 'worktree.create' } - expect(classifyRuntimeLongPoll({ ...request, params: { recipeId: 'sandbox' } })).toBe('wait') - expect(classifyRuntimeLongPoll({ ...request, params: { repo: 'id:repo' } })).toBeNull() -}) diff --git a/src/main/runtime/rpc/methods/workspaces/worktree.ts b/src/main/runtime/rpc/methods/workspaces/worktree.ts index 67ad6037d56..4e408df70a0 100644 --- a/src/main/runtime/rpc/methods/workspaces/worktree.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree.ts @@ -34,7 +34,6 @@ import { } from '../../../../../shared/rpc-contract/worktree-params' import { WORKTREE_CATALOG_METHODS } from './worktree-catalog-methods' import { WORKTREE_PROVISIONED_ROOT_METHOD } from './worktree-provisioned-root-method' -import { VM_RECIPE_LIST_METHOD } from './vm-recipe-list-method' import { waitsForWorktreeRemoval } from '../../worktree-removal-marker-projection' import { queueWorkspaceDelete } from '../../../workspaces/lifecycle/workspace-lifecycle-commands' import { WORKTREE_SLEEP_METHOD } from './worktree-sleep-method' @@ -122,24 +121,6 @@ export const WORKTREE_METHODS = [ // Mobile retries after migration share clientMutationId; return the same pending/created worktree. Desktop/CLI without keys run plainly. context.runtime.dedupeWorktreeCreate(params, params.clientMutationId, async () => { const { runtime } = context - if (params.recipeId !== undefined) { - // Why: a recipe starts a billed machine from this computer's orca.yaml; paired devices - // do not get to start one until they have their own UI and confirmation for it. - if (context.clientKind !== undefined) { - throw Object.assign( - new Error( - "Recipe workspaces are created from this computer's Orca app or CLI, not from a paired device." - ), - { code: 'forbidden' } - ) - } - return runtime.createManagedRecipeWorkspace(params, { - ...(context.signal ? { signal: context.signal } : {}), - ...(context.reportProgress - ? { onPhase: (phase) => context.reportProgress?.({ phase }) } - : {}) - }) - } const repo = await runtime.showRepo(worktreeCreateRepoSelector(params)) const automationProvenance = resolveAutomationWorkspaceProvenance({ @@ -184,7 +165,6 @@ export const WORKTREE_METHODS = [ }) }), WORKTREE_PROVISIONED_ROOT_METHOD, - VM_RECIPE_LIST_METHOD, defineMethod({ name: 'worktree.prefetchCreateBase', permission: 'workspace', diff --git a/src/main/runtime/rpc/server/runtime-rpc-long-poll.ts b/src/main/runtime/rpc/server/runtime-rpc-long-poll.ts index 37e078c80c4..13188f287ae 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-long-poll.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-long-poll.ts @@ -73,14 +73,5 @@ export function classifyRuntimeLongPoll(request: RpcRequest): RuntimeLongPollCla const params = request.params as { wait?: unknown } | undefined return params?.wait === true ? 'wait' : null } - if ( - request.method === 'worktree.create' && - typeof request.params === 'object' && - request.params !== null && - 'recipeId' in request.params && - typeof request.params.recipeId === 'string' - ) { - return 'wait' - } return null } diff --git a/src/main/runtime/rpc/server/runtime-rpc-request-admission.ts b/src/main/runtime/rpc/server/runtime-rpc-request-admission.ts index d19ad647b61..beb2c564224 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-request-admission.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-request-admission.ts @@ -52,7 +52,6 @@ export class RuntimeRpcRequestAdmission extends RuntimeRpcBinaryRouting { ? context?.signal : undefined, connectionSignal: context?.signal, - ...(longPoll && context?.reportProgress ? { reportProgress: context.reportProgress } : {}), caller: LOCAL_CLI_RPC_CALLER, callerScope, pairingOffers: callerScope.kind === 'owner' ? this.ownerPairingOffers() : undefined diff --git a/src/main/runtime/rpc/transport.ts b/src/main/runtime/rpc/transport.ts index 1bf2351737a..94ab65d151e 100644 --- a/src/main/runtime/rpc/transport.ts +++ b/src/main/runtime/rpc/transport.ts @@ -1,5 +1,3 @@ -import type { RuntimeRpcProgress } from '../../../shared/runtime-rpc-envelope' - // Transports own connection lifecycle; RPC binds messages across Unix sockets, WebSockets and named pipes. // Rich message context (abort signals, authenticated sockets) requires each concrete transport type. @@ -7,8 +5,6 @@ import type { RuntimeRpcProgress } from '../../../shared/runtime-rpc-envelope' export type RpcMessageContext = { signal: AbortSignal startKeepalive: () => void - /** Long polls only: piggybacks a progress note on a keepalive frame; older clients ignore it. */ - reportProgress?: (progress: RuntimeRpcProgress) => void } export type RpcTransport = { diff --git a/src/main/runtime/rpc/unix-socket-transport.test.ts b/src/main/runtime/rpc/unix-socket-transport.test.ts index dc5ecad6347..2fe81c1a59b 100644 --- a/src/main/runtime/rpc/unix-socket-transport.test.ts +++ b/src/main/runtime/rpc/unix-socket-transport.test.ts @@ -102,27 +102,6 @@ describe('UnixSocketTransport', () => { expect(received).toEqual([oversized ? '' : message]) }) - it('writes progress as keepalive frames only until the reply is sent', () => { - const transport = new UnixSocketTransport({ - endpoint: '/tmp/orca-runtime-rpc-test.sock', - kind: 'unix' - }) - const socket = new FakeSocket() - transport.onMessage((_msg, reply, context) => { - context?.reportProgress?.({ phase: 'running-create' }) - reply('{"id":"req","ok":true}') - context?.reportProgress?.({ phase: 'too-late' }) - }) - ;(transport as unknown as UnixSocketTransportInternals).handleConnection( - socket as unknown as Socket - ) - socket.emit('data', '{"id":"req","method":"worktree.create"}\n') - expect(socket.writes).toEqual([ - '{"_keepalive":true,"progress":{"phase":"running-create"}}\n', - '{"id":"req","ok":true}\n' - ]) - }) - it('clears request keepalive timers when the socket closes before a reply', () => { const transport = new UnixSocketTransport({ endpoint: '/tmp/orca-runtime-rpc-test.sock', diff --git a/src/main/runtime/rpc/unix-socket-transport.ts b/src/main/runtime/rpc/unix-socket-transport.ts index d9bd7c8abee..01eaa2c36b2 100644 --- a/src/main/runtime/rpc/unix-socket-transport.ts +++ b/src/main/runtime/rpc/unix-socket-transport.ts @@ -3,7 +3,6 @@ import { createServer, type Server, type Socket } from 'node:net' import { chmodSync, existsSync, rmSync } from 'node:fs' import type { RpcMessageContext, RpcTransport } from './transport' -import type { RuntimeRpcProgress } from '../../../shared/runtime-rpc-envelope' import { MAX_LOCAL_RUNTIME_RPC_MESSAGE_BYTES } from '../../../shared/local-runtime-rpc-limits' const RUNTIME_RPC_SOCKET_IDLE_TIMEOUT_MS = 30_000 @@ -215,17 +214,9 @@ export class UnixSocketTransport implements RpcTransport { } } - const reportProgress = (progress: RuntimeRpcProgress): void => { - if (replied || socket.destroyed || !socket.writable) { - return - } - socket.write(`${JSON.stringify({ _keepalive: true, progress })}\n`) - } - this.messageHandler?.(rawMessage, reply, { signal: abortController.signal, - startKeepalive, - reportProgress + startKeepalive }) } } diff --git a/src/main/runtime/workspaces/creation/runtime-recipe-workspace-creation.ts b/src/main/runtime/workspaces/creation/runtime-recipe-workspace-creation.ts deleted file mode 100644 index 9e4afdaf5f1..00000000000 --- a/src/main/runtime/workspaces/creation/runtime-recipe-workspace-creation.ts +++ /dev/null @@ -1,77 +0,0 @@ -import type { Repo } from '../../../../shared/repo-types' -import type { - RecipeCatalogListing, - RecipeWorkspaceCreatePhase -} from '../../../../shared/recipe-workspace-create-progress' -import type { - RecipeWorkspaceCreateParams, - RecipeWorkspaceCreation -} from '../../../ephemeral-vm/recipe-workspace-create-params' -import { worktreeCreateRepoSelector } from '../../rpc/methods/workspaces/worktree-create-args' -import { RuntimeProvisionedWorkspaceAdoption } from './runtime-provisioned-workspace-adoption' - -export type RecipeWorkspaceCreateOptions = { - /** Aborts provisioning (and destroys a started VM) when the caller goes away. */ - signal?: AbortSignal - onPhase?: (phase: RecipeWorkspaceCreatePhase) => void -} - -/** Desktop-only wiring: orcad has no recipe runner, so it never sets one and never advertises it. */ -export type RecipeWorkspaceService = { - create: ( - params: RecipeWorkspaceCreateParams, - repo: Repo, - options: RecipeWorkspaceCreateOptions - ) => Promise - /** One repo's recipes, or every local repo that has any. */ - list: (repo: Repo | null) => Promise -} - -export abstract class RuntimeRecipeWorkspaceCreation extends RuntimeProvisionedWorkspaceAdoption { - private recipeWorkspaceService: RecipeWorkspaceService | null = null - - setRecipeWorkspaceService(service: RecipeWorkspaceService): void { - this.recipeWorkspaceService = service - } - - override supportsRecipeWorkspaceCreation(): boolean { - return this.recipeWorkspaceService !== null - } - - async listEnvironmentRecipes(repoSelector: string | undefined): Promise { - if (!this.recipeWorkspaceService) { - throw new Error('This Orca host cannot create workspaces from environment recipes.') - } - const repo = repoSelector ? await this.resolveRepoSelector(repoSelector) : null - return this.recipeWorkspaceService.list(repo) - } - - async createManagedRecipeWorkspace( - params: RecipeWorkspaceCreateParams, - options: RecipeWorkspaceCreateOptions = {} - ): Promise { - if (!this.recipeWorkspaceService) { - throw new Error('This Orca host cannot create workspaces from environment recipes.') - } - const repo = await this.resolveRepoSelector(worktreeCreateRepoSelector(params)) - const result = await this.recipeWorkspaceService.create(params, repo, options) - this.notifyReposChanged() - this.notifyWorktreesChanged(result.worktree.repoId) - // No lifecycle event: plugin events carry `path` as a path on this machine, and this one is inside the VM. - // No activation either: this host's window cannot resolve a workspace that lives on another host. - // No lineage: this host's store would record a parent edge to a workspace it does not hold, - // which the sidebar reads as a missing parent. - return { - ...result, - lineage: null, - workspaceLineage: null, - warnings: [], - worktree: { - ...result.worktree, - parentWorktreeId: null, - lineage: null, - workspaceLineage: null - } - } - } -} diff --git a/src/main/startup/main-process-runtime-service.ts b/src/main/startup/main-process-runtime-service.ts index a8adba0c0b6..bcc8198f35e 100644 --- a/src/main/startup/main-process-runtime-service.ts +++ b/src/main/startup/main-process-runtime-service.ts @@ -61,10 +61,6 @@ import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-b import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root' import { openOffscreenBrowserPageLink } from '../runtime/browser/commands/offscreen-browser-page-link' -import { - createCliRecipeWorkspace, - listCliEnvironmentRecipes -} from '../ephemeral-vm/cli-workspace-create' export function getDesktopWindowStatus(): RuntimeDesktopWindowStatus { const activation = state.desktopActivationGate @@ -149,18 +145,6 @@ export function initializeMainProcessRuntime(): OrcaRuntimeService { applySessionSearchSettings: applySessionSearchSettingsChange, skillTransactionRecovery: state.skillTransactionRecovery }) - runtime.setRecipeWorkspaceService({ - create: (params, repo, options) => - createCliRecipeWorkspace({ - store, - userDataPath: app.getPath('userData'), - repo, - params, - pluginService: state.pluginService, - ...options - }), - list: (repo) => listCliEnvironmentRecipes(store, repo, state.pluginService) - }) // Both desktop and headless serve own a host-local search service. const sessionSearch = installChildSessionSearchService({ dataRoot: getCanonicalUserDataPath(), diff --git a/src/main/workspaces/catalog/provisioned-root-checkout.ts b/src/main/workspaces/catalog/provisioned-root-checkout.ts index c1a9615f963..0243d931385 100644 --- a/src/main/workspaces/catalog/provisioned-root-checkout.ts +++ b/src/main/workspaces/catalog/provisioned-root-checkout.ts @@ -8,11 +8,7 @@ import type { CrossStoreParentRef } from '../../../shared/worktree/lineage-types' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import type { - AutomationWorkspaceProvenance, - CliWorkspaceProvenance, - GitWorktreeInfo -} from '../../../shared/worktree/types' +import type { AutomationWorkspaceProvenance, GitWorktreeInfo } from '../../../shared/worktree/types' import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' import { getProjectHostSetupWorktreeMeta } from '../../../shared/project-host-setup-lookup' import { isTuiAgent } from '../../../shared/agent-launch/catalog/tui-agent-config' @@ -59,7 +55,6 @@ export type ProvisionedRootRequest = Pick< crossStoreParentInferredFrom?: CrossStoreInferredSource expectedRefHead?: string automationProvenance?: AutomationWorkspaceProvenance - cliProvenance?: CliWorkspaceProvenance } export function provisionedRootPathsEqual(left: string, right: string): boolean { @@ -149,7 +144,6 @@ export function buildProvisionedRootMeta( orcaCreatedAt: now, orcaCreationSource: options.source, creatorProvenance: { kind: 'host' }, - ...(args.cliProvenance ? { cliProvenance: args.cliProvenance } : {}), orcaCreationWorkspaceLayout: getWorktreeCreationLayout(repo, store.getSettings()), ...(args.automationProvenance ? { automationProvenance: args.automationProvenance } : {}), ...(args.compareBaseRef || args.baseBranch diff --git a/src/shared/host-runtime-capabilities.ts b/src/shared/host-runtime-capabilities.ts index aeae5a3b9d2..2469c5f9952 100644 --- a/src/shared/host-runtime-capabilities.ts +++ b/src/shared/host-runtime-capabilities.ts @@ -8,8 +8,6 @@ import { SSH_TARGET_MANAGEMENT_RUNTIME_CAPABILITY } from './ssh-target-managemen export const REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY = 'remote-runtime.shared-control.v1' as const // Why conditional: only a desktop runtime holds the SSH registry managed servers are run from. export const MANAGED_SERVER_RUNTIME_CAPABILITY = 'managedServer.v1' as const -// Why conditional: only a host with a registered recipe creator can provision recipe VMs. -export const WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY = 'worktree.recipe-create.v1' as const // Why: clients offer "Resume automatic restores" only on hosts that can clear a recorded pause. export const RUNTIME_AUTOMATIC_WORK_RUNTIME_CAPABILITY = 'runtime.automatic-work.v1' as const // Hosts without this capability ignore a request's expectedRuntimeSource; the CLI's pre-send probe diff --git a/src/shared/recipe-workspace-create-progress.ts b/src/shared/recipe-workspace-create-progress.ts deleted file mode 100644 index fbc667a4006..00000000000 --- a/src/shared/recipe-workspace-create-progress.ts +++ /dev/null @@ -1,53 +0,0 @@ -/** Named steps of creating a workspace on a fresh recipe environment, in the order they run. */ -export const RECIPE_WORKSPACE_CREATE_PHASES = { - 'resolving-start-ref': 'Resolving the start ref', - 'running-create': "Running the recipe's create step", - connecting: 'Connecting to the new environment', - 'checking-host': 'Checking Orca on the environment', - 'registering-project': 'Registering the project on the environment', - 'creating-workspace': 'Creating the workspace', - 'destroying-after-failure': 'Destroying the environment after a failure' -} as const - -export type RecipeWorkspaceCreatePhase = keyof typeof RECIPE_WORKSPACE_CREATE_PHASES - -export function isRecipeWorkspaceCreatePhase(value: unknown): value is RecipeWorkspaceCreatePhase { - return typeof value === 'string' && Object.hasOwn(RECIPE_WORKSPACE_CREATE_PHASES, value) -} - -/** RPC error code for a failed recipe create; `data` is RecipeWorkspaceCreateFailureData. */ -export const RECIPE_WORKSPACE_CREATE_FAILED_CODE = 'recipe_workspace_create_failed' as const - -export type RecipeWorkspaceCreateFailureData = { - /** The step that failed. */ - phase: RecipeWorkspaceCreatePhase - recipeId: string - /** The recipe failure catalog code (see ephemeral-vm-failure-copy), when the recipe itself failed. */ - failureCode?: string - failureParams?: Record - /** Present once a VM record exists. */ - runtimeId?: string - /** What happened to a VM the failed create had started: destroyed, left for a manual retry, or - * left running because the recipe has no destroy step. */ - environment?: 'destroyed' | 'destroy-failed' | 'destroy-disabled' - destroyError?: string -} - -/** One repo's recipes as `orca vm recipe list` shows them. */ -export type RecipeCatalogListing = { - repoId: string - repoName: string - repoPath: string - recipes: { - id: string - name: string - description?: string - checkoutMode: 'orca-worktree' | 'provisioned-root' - /** Lifecycle steps the recipe defines besides create. */ - steps: ('suspend' | 'resume' | 'destroy')[] - destroyDisabled: boolean - timeoutSeconds?: Partial> - }[] - /** orca.yaml problems that hid or changed a recipe. */ - diagnostics: { index: number; field?: string; message: string }[] -} diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index e1924b43ead..7a3d4daf21b 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -714,7 +714,6 @@ import { UsageCredentialSessionCookieParams } from './usage-credentials-params' import { CancelUsageLimitContinueParams } from './usage-limit-continue-params' -import { VmRecipeList } from './vm-recipe-params' import { LayoutReopenHeldPanesParams } from './workspace-layout-held-panes-params' import { LayoutApplyParams, @@ -1600,7 +1599,6 @@ export const RPC_PARAMS_BY_METHOD = { 'updater.download': null, 'updater.getStatus': null, 'updater.install': null, - 'vmRecipe.list': VmRecipeList, 'workspacePorts.kill': WorkspacePortKillParams, 'workspacePorts.killHost': WorkspacePortKillHostParams, 'workspacePorts.probePage': WorkspacePortProbePageParams, diff --git a/src/shared/rpc-contract/vm-recipe-params.ts b/src/shared/rpc-contract/vm-recipe-params.ts deleted file mode 100644 index d045dccf584..00000000000 --- a/src/shared/rpc-contract/vm-recipe-params.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { z } from 'zod' -import { OptionalString } from './rpc-param-primitives' - -/** `vmRecipe.list`: one repo's environment recipes, or every local repo's when omitted. */ -export const VmRecipeList = z.object({ repo: OptionalString }) diff --git a/src/shared/rpc-contract/worktree-create-params.ts b/src/shared/rpc-contract/worktree-create-params.ts index ad01f00fb38..b85be2428c6 100644 --- a/src/shared/rpc-contract/worktree-create-params.ts +++ b/src/shared/rpc-contract/worktree-create-params.ts @@ -33,7 +33,6 @@ export const WorktreeCreate = z /** Scope same-ID repo copies by host; absent retains legacy selector lookup, which refuses ambiguous IDs. */ repoHostId: OptionalExecutionHostId, name: OptionalString, - recipeId: z.string().min(1).optional(), /** Generated names may skip/retire candidates; absent means user-typed and bypasses that policy. */ nameWasGenerated: z.boolean().optional(), baseBranch: OptionalString, diff --git a/src/shared/rpc-contract/worktree-provisioned-root-params.ts b/src/shared/rpc-contract/worktree-provisioned-root-params.ts index 4ccb806fdcc..30a7b91b9f4 100644 --- a/src/shared/rpc-contract/worktree-provisioned-root-params.ts +++ b/src/shared/rpc-contract/worktree-provisioned-root-params.ts @@ -36,7 +36,6 @@ export const WorktreeAdoptProvisionedRoot = z.object({ parentWorkspaceOrigin: create.parentWorkspaceOrigin, crossStoreParent: create.crossStoreParent, crossStoreParentInferredFrom: create.crossStoreParentInferredFrom, - cliProvenanceRequest: create.cliProvenanceRequest, name: z.string().min(1, 'Missing workspace name'), expectedPath: z.string().min(1, 'Missing provisioned project root'), expectedRefHead: OptionalString diff --git a/src/shared/runtime-rpc-envelope.ts b/src/shared/runtime-rpc-envelope.ts index fe0f93bdbea..5eb43892d1a 100644 --- a/src/shared/runtime-rpc-envelope.ts +++ b/src/shared/runtime-rpc-envelope.ts @@ -40,18 +40,12 @@ const Failure = z }) .strip() -const Progress = z.object({ phase: z.string().min(1).max(200) }).strip() - const Keepalive = z .object({ - _keepalive: z.literal(true), - // Optional named step of a long poll; clients that predate it strip the field. - progress: Progress.optional() + _keepalive: z.literal(true) }) .strip() -export type RuntimeRpcProgress = z.infer - export const RuntimeRpcEnvelopeSchema = z.union([Success, Failure, Keepalive]) export type RuntimeRpcSuccess = { From a489ef5ba31922d119de8d5b412973320cba6798 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sun, 8 Nov 2026 23:19:51 -0800 Subject: [PATCH 03/10] test: reconcile approved test removals with current main (#40176) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .github/workflows/performance-contracts.yml | 1 - config/mobile-ci.vitest.config.mjs | 1 - config/reliability-gates.jsonc | 5 +- config/vitest.performance.config.ts | 1 - .../scripts/check-tests-typecheck-ratchet.mjs | 7 +- .../check-tests-typecheck-ratchet.test.ts | 9 - ...obile-accounts-screen-reset-credit.test.ts | 253 ------------------ .../agent-history-scope-paths.test.ts | 26 -- ...ser-screencast-budget-at-the-shell.test.ts | 88 ------ .../browser/browser-screencast-request.web.ts | 2 +- .../MobileMarkdown.rendering.test.tsx | 115 -------- ...WorktreeAgentList.runtime-lineage.test.tsx | 90 ------- .../mobile-markdown-visual-lines.test.ts | 92 ------- .../pr-sidebar/pr-actions-state.test.ts | 70 ----- .../pr-sidebar/pr-checks-presentation.test.ts | 25 -- .../use-connected-host-picker.test.ts | 15 -- .../use-detail-card-scope.web.test.tsx | 193 ------------- .../connection/connection-log-buffer.test.ts | 58 ---- .../native-diagnostics-operations.test.ts | 19 -- .../src/diagnostics/native-render-log.test.ts | 41 --- .../use-troubleshoot-diagnostics.test.tsx | 50 ---- ...use-mobile-dictation-silence-stop.test.tsx | 56 ---- .../files/MobileMarkdownPreviewImage.test.tsx | 56 ---- .../review/mobile-diff-review-state.test.ts | 10 - .../review/optimistic-write-sequence.test.ts | 26 -- mobile/src/stats/home-stats-total.test.ts | 43 --- mobile/src/tasks/github-pr-file-diff.test.ts | 38 --- .../src/tasks/jira-mobile-connection.test.ts | 25 -- .../src/tasks/mobile-jira-task-source.test.ts | 15 -- mobile/src/tasks/setup-hook-trust.test.ts | 14 - .../tasks/smart-source-paste-intent.test.ts | 20 -- .../src/tasks/worktree-create-retry.test.ts | 60 ----- .../mobile-terminal-query-reply.test.ts | 86 ------ .../mobile-terminal-inventory-request.test.ts | 13 - mobile/tsconfig.test.json | 1 - ...nticatedConnectionHangupMonitorTests.swift | 98 ------- .../SyntheticMouseClickDeliveryTests.swift | 231 ---------------- ...er-session-partition-proxy-install.test.ts | 1 + ...d-agent-session-message-projection.test.ts | 123 --------- .../routing/native-chat-open-wake.test.ts | 38 --- .../linear-issue-workspace-attachment.test.ts | 62 ----- .../worktree-creation-initial-surface.test.ts | 51 ---- .../ownership/worktree-runtime-owner.test.ts | 32 --- .../runtime-directory-page-client.test.ts | 47 ---- .../files/reads/runtime-file-client.test.ts | 56 ---- .../jira/runtime-jira-payload-stream.test.ts | 51 ---- .../store-identity-churn-probe.test.ts | 63 ----- .../workspace-cleanup-browse.test.ts | 54 ---- ...orktrees-git-identity-branch-title.test.ts | 71 ----- .../work-items/task-source-context.test.ts | 45 +--- .../workspace-layout-resume-record.test.ts | 17 -- src/shared/workspace-review-checks.test.ts | 85 ------ 52 files changed, 7 insertions(+), 2742 deletions(-) delete mode 100644 mobile/src/accounts/mobile-accounts-screen-reset-credit.test.ts delete mode 100644 mobile/src/agent-history/agent-history-scope-paths.test.ts delete mode 100644 mobile/src/browser/browser-screencast-budget-at-the-shell.test.ts delete mode 100644 mobile/src/components/MobileMarkdown.rendering.test.tsx delete mode 100644 mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx delete mode 100644 mobile/src/components/mobile-markdown-visual-lines.test.ts delete mode 100644 mobile/src/components/pr-sidebar/pr-actions-state.test.ts delete mode 100644 mobile/src/components/pr-sidebar/pr-checks-presentation.test.ts delete mode 100644 mobile/src/components/use-detail-card-scope.web.test.tsx delete mode 100644 mobile/src/diagnostics/use-troubleshoot-diagnostics.test.tsx delete mode 100644 mobile/src/dictation/use-mobile-dictation-silence-stop.test.tsx delete mode 100644 mobile/src/files/MobileMarkdownPreviewImage.test.tsx delete mode 100644 mobile/src/source-control/review/optimistic-write-sequence.test.ts delete mode 100644 mobile/src/stats/home-stats-total.test.ts delete mode 100644 mobile/src/tasks/jira-mobile-connection.test.ts delete mode 100644 mobile/src/tasks/setup-hook-trust.test.ts delete mode 100644 mobile/src/tasks/smart-source-paste-intent.test.ts delete mode 100644 mobile/src/tasks/worktree-create-retry.test.ts delete mode 100644 mobile/src/terminal/mobile-terminal-query-reply.test.ts delete mode 100644 native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/SyntheticMouseClickDeliveryTests.swift delete mode 100644 src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.test.ts delete mode 100644 src/renderer/src/components/native-chat/pane/routing/native-chat-open-wake.test.ts delete mode 100644 src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.test.ts delete mode 100644 src/renderer/src/lib/workspace/creation/worktree-creation-initial-surface.test.ts delete mode 100644 src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts delete mode 100644 src/renderer/src/runtime/files/reads/runtime-directory-page-client.test.ts delete mode 100644 src/renderer/src/runtime/files/reads/runtime-file-client.test.ts delete mode 100644 src/renderer/src/runtime/jira/runtime-jira-payload-stream.test.ts delete mode 100644 src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts delete mode 100644 src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-browse.test.ts delete mode 100644 src/renderer/src/store/slices/worktrees/metadata/worktrees-git-identity-branch-title.test.ts diff --git a/.github/workflows/performance-contracts.yml b/.github/workflows/performance-contracts.yml index cd3ba1dfa3a..2af8bb94c6f 100644 --- a/.github/workflows/performance-contracts.yml +++ b/.github/workflows/performance-contracts.yml @@ -31,7 +31,6 @@ on: - 'src/main/usage/jsonl-file-reader.test.ts' - 'src/main/usage/jsonl-file-snapshot.test.ts' - 'src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts' - - 'src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts' - 'src/main/claude-usage/scanner-incremental-append.test.ts' - 'src/main/claude-usage/store-checkpoint-persistence.test.ts' - 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx' diff --git a/config/mobile-ci.vitest.config.mjs b/config/mobile-ci.vitest.config.mjs index 23b80145a37..61ddb17f32e 100644 --- a/config/mobile-ci.vitest.config.mjs +++ b/config/mobile-ci.vitest.config.mjs @@ -3,7 +3,6 @@ import original from '../mobile/vitest.config.ts' // Keep real process, native, and runtime-specific contracts on Node. const nodeFiles = [ - 'src/components/WorktreeAgentList.runtime-lineage.test.tsx', 'scripts/check-tests-typecheck-incremental-cache.test.ts', 'src/mock-server-key-pair.test.ts', 'src/mobile-release/prepare-android-release-script.test.ts', diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index faed2105a46..76de250ab2b 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -7676,7 +7676,7 @@ "oracle": "Audit2371 reduces all-host-folder-workspace-catalogs.test.ts by removing the repeated offline compatibility-probe budget and its incidental local-fallback/restored-owner samples, and catalog-settlement-notifications.test.ts by removing the four-route ten-equal-refresh notification/reference matrix. Those probe, quietness, identity and fallback alarms are intentionally lost. Remaining stale-response and revision-fencing examples do not supply equivalent replacement coverage. No fresh execution or red/green evidence validates the reduced sources; the four unrelated physical selected-runtime E2E receipts retain their original commands and scope. Historical prior account (preserved verbatim): Audit2360 removes src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts and its exclusive fake-effect harness. Lose local default-runtime persistence across navigation; focused/background terminal request/create/reveal and no-focus recovery; startup cwd/config/agent/view-mode forwarding; explicit runtime-session routing; remote/ambiguous/missing owner refusal; history focus; existing PTY reuse/title preservation; pending tab PTY/layout/identity adoption; split tree, focus, identity and telemetry samples. No equivalent replacement claimed. Changed selectors have no fresh execution or red/green credit. Unrelated retained receipt objects keep their original narrow scope. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/store/project-groups/nested-repository-operations.test.ts: routes local nested scan progress by scanId and unsubscribes after completion. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Start with Active Server=Local desktop, connect and navigate Windows 2, then reveal a local terminal and assert it succeeds while the persisted preference remains local before and after restart. Repeat transient routing and selected-runtime Add Project operations with exact-ID host decoys and completion reordering. Separately pair the real web client to an isolated headed host, then make its sole still-listed runtime compatibility-blocked and unavailable. Require a null authoritative selection, a disabled host option, and disabled Browse, Clone, and Create actions with no local fallback. Repeat against headless serve. Run the byte-identical selector/action contract on latest main, candidate, and candidate with the eligibility seam disabled.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts src/renderer/src/store/slices/settings/settings.test.ts src/renderer/src/store/slices/browser/hosts/browser-session-host-selection.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts --maxWorkers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/all-host-folder-workspace-catalogs.test.ts src/renderer/src/store/host-catalog/catalog-settlement-notifications.test.ts src/renderer/src/store/repos/repos-stale-fetch.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-routing.test.ts src/renderer/src/store/repos/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/worktrees/session/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts --maxWorkers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/all-host-folder-workspace-catalogs.test.ts src/renderer/src/store/host-catalog/catalog-settlement-notifications.test.ts src/renderer/src/store/repos/repos-stale-fetch.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-routing.test.ts src/renderer/src/store/repos/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/worktrees/session/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx --maxWorkers=1", "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" @@ -7689,7 +7689,6 @@ "src/renderer/src/web/web-preload-api-runtime-environment.test.ts", "src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx", "src/renderer/src/lib/resolved-worktree-execution-host.test.ts", - "src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts", "src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts", "src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts", "src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts", @@ -7809,6 +7808,8 @@ "Run the paired Add Project journey on Linux and native Windows, plus live SSH and WSL hosts." ], "knownGaps": [ + "Audit2680: Delete the whole supplied-state worktree-runtime-owner suite. Lose immutable collection-reference invalidation and per-worktree override/folder inheritance lookup alarms without replacement. Remove its prospective selector and file membership; unchanged independent Electron evidenceRuns remain historical and do not validate the reduced selector. No fresh execution or equivalent replacement is claimed.", + "Audit2680 historical original selector metadata, preserved verbatim; not current evidence: {\"command\":\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/all-host-folder-workspace-catalogs.test.ts src/renderer/src/store/host-catalog/catalog-settlement-notifications.test.ts src/renderer/src/store/repos/repos-stale-fetch.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-routing.test.ts src/renderer/src/store/repos/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/worktrees/session/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts --maxWorkers=1\",\"testFiles\":\"src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts\"}", "Audit2360 removes src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts and its exclusive fake-effect harness. Lose local default-runtime persistence across navigation; focused/background terminal request/create/reveal and no-focus recovery; startup cwd/config/agent/view-mode forwarding; explicit runtime-session routing; remote/ambiguous/missing owner refusal; history focus; existing PTY reuse/title preservation; pending tab PTY/layout/identity adoption; split tree, focus, identity and telemetry samples. No equivalent replacement claimed. Changed selectors have no fresh execution or red/green credit. Unrelated retained receipt objects keep their original narrow scope. Retired assertion reference verbatim: {\n \"file\": \"src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts\",\n \"assertions\": [\n \"Local desktop remains the durable default after transient Windows 2 navigation and a focused local terminal reveal succeeds\",\n \"local and remote terminal create route by target workspace ownership instead of the durable preference\"\n ]\n }", "Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "The exact journey is deterministic contract coverage, not a packaged Windows UI automation run.", diff --git a/config/vitest.performance.config.ts b/config/vitest.performance.config.ts index 00967828447..a29424675e5 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -19,7 +19,6 @@ const contracts = [ 'src/main/usage/jsonl-file-reader.test.ts', 'src/main/usage/jsonl-file-snapshot.test.ts', 'src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts', - 'src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts', 'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs', 'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs', 'src/main/claude-usage/scanner-incremental-append.test.ts', diff --git a/mobile/scripts/check-tests-typecheck-ratchet.mjs b/mobile/scripts/check-tests-typecheck-ratchet.mjs index 8066911e602..b4545dc56ef 100644 --- a/mobile/scripts/check-tests-typecheck-ratchet.mjs +++ b/mobile/scripts/check-tests-typecheck-ratchet.mjs @@ -14,12 +14,7 @@ const ERROR_LINE = /^(\S.*?)\(\d+,\d+\): error TS\d+:/ // Tests outside the RN program. Checked transfers are the roots of tsconfig.test.node.json and must pass // that strict program; the rest are legacy runtime-only allowances whose bodies nothing typechecks. -export const TESTS_OUTSIDE_PROGRAM = new Map([ - [ - 'src/components/WorktreeAgentList.runtime-lineage.test.tsx', - 'Legacy runtime-only: the test body is not typechecked anywhere; it imports the desktop SQLite assignment projection, which does not check against RN libs, and its implementation sources keep their normal checks' - ] -]) +export const TESTS_OUTSIDE_PROGRAM = new Map([]) // Normalize tsc’s host separators to POSIX baseline paths or Windows reports every entry stale and added. const toPosix = (filePath) => filePath.replaceAll('\\', '/') diff --git a/mobile/scripts/check-tests-typecheck-ratchet.test.ts b/mobile/scripts/check-tests-typecheck-ratchet.test.ts index e0d100035c6..cb326066f34 100644 --- a/mobile/scripts/check-tests-typecheck-ratchet.test.ts +++ b/mobile/scripts/check-tests-typecheck-ratchet.test.ts @@ -59,15 +59,6 @@ describe('the @ts-nocheck guard', () => { }) describe('checked transfers', () => { - it('accepts an empty checked cohort while retaining legacy runtime allowances', () => { - expect( - checkTransfers( - { ok: true, expected: [], programTestFiles: [], failures: [], problems: [] }, - new Map([['legacy.test.ts', 'Legacy runtime-only: no checked transfer']]) - ) - ).toEqual([]) - }) - it('rejects a declared checked transfer missing from the configured roots', () => { expect( checkTransfers( diff --git a/mobile/src/accounts/mobile-accounts-screen-reset-credit.test.ts b/mobile/src/accounts/mobile-accounts-screen-reset-credit.test.ts deleted file mode 100644 index 409b2896269..00000000000 --- a/mobile/src/accounts/mobile-accounts-screen-reset-credit.test.ts +++ /dev/null @@ -1,253 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ConfirmModal } from '../components/ConfirmModal' -import { MobileAccountsScreen } from './MobileAccountsScreen' - -const dependencies = vi.hoisted(() => ({ - back: vi.fn(), - loadHosts: vi.fn(), - uuid: vi.fn<() => string>(), - resetRequest: vi.fn(), - selectRequest: vi.fn(), - statusCapabilities: vi.fn(), - subscriptionListeners: new Array<(payload: unknown) => void>() -})) - -vi.mock('react-native', () => ({ - ActivityIndicator: 'ActivityIndicator', - Animated: { View: 'View' }, - AppState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) }, - Platform: { OS: 'ios' }, - Pressable: 'Pressable', - RefreshControl: 'RefreshControl', - ScrollView: 'ScrollView', - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - Text: 'Text', - View: 'View' -})) - -vi.mock('react-native-safe-area-context', () => ({ - SafeAreaView: 'SafeAreaView', - useSafeAreaInsets: () => ({ bottom: 0, left: 0, right: 0, top: 0 }) -})) - -vi.mock('expo-router', async () => { - const React = await import('react') - return { - useFocusEffect(effect: () => void | (() => void)): void { - React.useEffect(effect, [effect]) - }, - useLocalSearchParams: () => ({ hostId: 'host-1' }) - } -}) - -// The page's Back: the handoff pops the shell's stack, where expo-router's own `back()` goes nowhere. -vi.mock('../navigation/route-handoff', () => ({ - useRouteHandoff: () => ({ back: dependencies.back }) -})) - -// The dialogs are read off `ConfirmModal`'s props; the drawer under them needs a native runtime. -vi.mock('../components/bottom-drawer/BottomDrawer', () => ({ BottomDrawer: () => null })) - -vi.mock('../platform/random-v4-uuid', () => ({ randomV4Uuid: dependencies.uuid })) - -vi.mock('lucide-react-native', () => ({ - Check: 'Check', - ChevronLeft: 'ChevronLeft', - RefreshCw: 'RefreshCw', - RotateCcw: 'RotateCcw', - User: 'User' -})) - -vi.mock('../transport/hosts/host-store', () => ({ - loadHosts: dependencies.loadHosts, - peekHosts: () => null -})) - -vi.mock('../transport/connection/host-client-hooks', () => { - const client = { - sendRequest: async (method: string, params?: unknown, options?: unknown) => { - if (method === 'status.get') { - return { - id: 'status', - ok: true, - result: { capabilities: dependencies.statusCapabilities() }, - _meta: { runtimeId: 'runtime-1' } - } - } - if (method === 'accounts.consumeCodexResetCredit') { - return dependencies.resetRequest(params, options) - } - if ( - method === 'accounts.selectCodex' || - method === 'accounts.selectCodexForTarget' || - method === 'accounts.selectClaude' - ) { - return dependencies.selectRequest(method, params) - } - if (method === 'accounts.list') { - return { id: 'list', ok: true, result: AVAILABLE_SNAPSHOT } - } - throw new Error(`Unexpected request: ${method}`) - }, - subscribe: (_method: string, _params: unknown, onData: (payload: unknown) => void) => { - dependencies.subscriptionListeners.push(onData) - onData({ type: 'ready', snapshot: AVAILABLE_SNAPSHOT }) - return vi.fn() - } - } - return { - useForceReconnect: () => null, - useHostClient: () => ({ client, state: 'connected' }) - } -}) - -vi.mock('../components/AgentIcons', () => ({ - ClaudeIcon: 'ClaudeIcon', - OpenAIIcon: 'OpenAIIcon' -})) - -const AVAILABLE_SNAPSHOT = { - claude: { accounts: [], activeAccountId: null }, - codex: { - accounts: [ - { - id: 'codex-1', - email: 'dev@example.com', - managedHomeRuntime: 'host', - wslDistro: null, - updatedAt: 10 - } - ], - activeAccountId: 'codex-1', - activeAccountIdsByRuntime: { host: 'codex-1', wsl: {} } - }, - rateLimits: { - claude: null, - codex: { - provider: 'codex', - session: { - usedPercent: 100, - windowMinutes: 300, - resetsAt: 2_000_000_000_000, - resetDescription: null - }, - weekly: null, - rateLimitResetCredits: { availableCount: 1, nextExpiresAt: null }, - updatedAt: 100, - error: null, - status: 'ok' - }, - claudeTarget: { runtime: 'host', wslDistro: null }, - codexTarget: { runtime: 'host', wslDistro: null }, - inactiveClaudeAccounts: [], - inactiveCodexAccounts: [] - } -} as const - -const RESET_SNAPSHOT = { - ...AVAILABLE_SNAPSHOT, - rateLimits: { - ...AVAILABLE_SNAPSHOT.rateLimits, - codex: { - ...AVAILABLE_SNAPSHOT.rateLimits.codex, - session: { ...AVAILABLE_SNAPSHOT.rateLimits.codex.session, usedPercent: 0 }, - rateLimitResetCredits: { availableCount: 0, nextExpiresAt: null }, - updatedAt: 101 - } - } -} as const - -async function renderAccountsRoute(): Promise { - let renderer: ReactTestRenderer | null = null - await act(async () => { - renderer = create(createElement(MobileAccountsScreen)) - await Promise.resolve() - }) - if (!renderer) { - throw new Error('Accounts route did not render') - } - return renderer -} - -/** Host components are strings under the mock above, so they are found by what they carry. */ -function pressables(renderer: ReactTestRenderer, label: string) { - return renderer.root.findAll( - (node) => String(node.type) === 'Pressable' && node.props.accessibilityLabel === label - ) -} - -function resetButtons(renderer: ReactTestRenderer) { - return pressables(renderer, 'Use Codex rate-limit reset') -} - -async function findResetButton(renderer: ReactTestRenderer) { - await vi.waitFor(() => expect(resetButtons(renderer)).toHaveLength(1)) - return resetButtons(renderer)[0]! -} - -/** The open dialog, read off `ConfirmModal` the way a user reads the drawer. */ -function openDialog(renderer: ReactTestRenderer) { - const open = renderer.root - .findAllByType(ConfirmModal) - .map((node) => node.props) - .filter((props) => props.visible) - if (open.length > 1) { - throw new Error(`expected at most one open dialog, found ${open.length}`) - } - return open[0] ?? null -} - -/** Presses the dialog's confirm button, which closes it after its action as `ConfirmContent` does. */ - -const KEY = '11111111-1111-4111-8111-111111111111' - -describe('accounts route Codex reset credit', () => { - beforeEach(() => { - dependencies.loadHosts.mockReset().mockResolvedValue([ - { - id: 'host-1', - name: 'Desk', - endpoint: 'ws://127.0.0.1:6768', - deviceToken: 'token', - publicKeyB64: 'public-key', - lastConnected: 1 - } - ]) - dependencies.uuid.mockReset().mockReturnValue(KEY) - dependencies.back.mockReset() - dependencies.statusCapabilities.mockReset().mockReturnValue(['accounts.codex-reset-credit.v1']) - dependencies.resetRequest.mockReset().mockImplementation((params) => ({ - id: 'reset', - ok: true, - result: { - outcome: 'reset', - scope: (params as { expectedScope: unknown }).expectedScope, - snapshot: RESET_SNAPSHOT - }, - _meta: { runtimeId: 'runtime-1' } - })) - dependencies.selectRequest.mockReset().mockResolvedValue({ - id: 'select', - ok: true, - result: AVAILABLE_SNAPSHOT.codex - }) - dependencies.subscriptionListeners.length = 0 - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it('sends nothing when the confirmation is cancelled', async () => { - const renderer = await renderAccountsRoute() - const button = await findResetButton(renderer) - await act(async () => button.props.onPress()) - act(() => openDialog(renderer)?.onCancel()) - - expect(openDialog(renderer)).toBeNull() - expect(dependencies.resetRequest).not.toHaveBeenCalled() - act(() => renderer.unmount()) - }) -}) diff --git a/mobile/src/agent-history/agent-history-scope-paths.test.ts b/mobile/src/agent-history/agent-history-scope-paths.test.ts deleted file mode 100644 index 018129e9013..00000000000 --- a/mobile/src/agent-history/agent-history-scope-paths.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - deriveMobileAiVaultScopePaths, - mobileAiVaultScanScopeArgs -} from './agent-history-scope-paths' - -const worktree = (worktreeId: string, path: string) => ({ worktreeId, path, repoId: 'repo-1' }) - -describe('mobile AI Vault scope paths', () => { - const active = worktree('w1', '/Users/ada/repo/app') - const siblings = Array.from({ length: 200 }, (_, index) => - worktree(`w-sib-${index}`, `/Users/ada/repo/app-${index}`) - ) - - it('caps only the scan hints, so an older host accepts them and Project still shows every sibling', () => { - const scopePaths = deriveMobileAiVaultScopePaths('project', active, [active, ...siblings]) - const scan = mobileAiVaultScanScopeArgs('project', scopePaths) - - expect(scopePaths).toHaveLength(201) - expect(scan.scopePaths).toHaveLength(64) - // Active worktree is seeded first, so it survives truncation. - expect(scan.scopePaths?.[0]).toBe('/Users/ada/repo/app') - // A capped scope can't answer alone, so the host keeps its recency scan. - expect(scan.scopeOnly).toBeUndefined() - }) -}) diff --git a/mobile/src/browser/browser-screencast-budget-at-the-shell.test.ts b/mobile/src/browser/browser-screencast-budget-at-the-shell.test.ts deleted file mode 100644 index dfceecbc797..00000000000 --- a/mobile/src/browser/browser-screencast-budget-at-the-shell.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { utf8ByteLength } from '../mobile-web-shell/bridge/bridge-caps' -import { clientFrame } from '../mobile-web-shell/bridge-host-test-fakes' -import { harness, ID } from '../mobile-web-shell/bridge-host-test-harness' -import { BrowserScreencastOpcode, type BrowserScreencastFrame } from './browser-screencast-protocol' -import { - binaryEventEnvelopeBytes, - mobileBrowserFrameAreaBudget, - WORST_CASE_JPEG_BYTES_PER_PIXEL -} from './browser-screencast-request.web' - -// Use all nine Chromium metadata fields and real epoch/microsecond timestamp; toy integer understates envelope width. -const CDP_METADATA = { - offsetTop: 0, - pageScaleFactor: 1, - deviceWidth: 390, - deviceHeight: 712, - imageWidth: 780, - imageHeight: 1424, - scrollOffsetX: 0, - scrollOffsetY: 2048.5, - timestamp: 1_758_326_400.123456 -} - -// Deterministic unstructured noise exercises JPEG worst case reproducibly. -function noise(byteLength: number): Uint8Array { - const bytes = new Uint8Array(byteLength) - let state = 0x9e37_79b9 - for (let index = 0; index < byteLength; index += 1) { - state = (Math.imul(state, 1_664_525) + 1_013_904_223) >>> 0 - bytes[index] = (state >>> 24) & 0xff - } - return bytes -} - -function screencastFrame(image: Uint8Array): BrowserScreencastFrame { - return { - opcode: BrowserScreencastOpcode.Frame, - seq: FRAME_SEQ, - format: 'jpeg', - metadata: CDP_METADATA, - image - } -} - -// Exercise a noninitial screencast frame counter. -const FRAME_SEQ = 4_096 - -/** The one frame the shell posted for this image, and what it cost besides the image. */ -function postedFrame(image: Uint8Array): { bytes: number; envelope: number; posts: number } { - const bridge = harness({ ready: true }) - bridge.host.receive( - clientFrame({ - type: 'subscribe', - id: ID, - method: 'browser.screencast', - params: { worktree: 'id:w', page: 'p' }, - wantsBinary: true - }) - ) - const before = bridge.posted.length - // Fail if no binary lane opened; optional chaining would otherwise look like a correctly dropped frame. - const emitBinary = bridge.client.streams[0]?.emitBinary - if (emitBinary === null || emitBinary === undefined) { - throw new Error('the subscribe opened no binary stream') - } - emitBinary(screencastFrame(image)) - const json = bridge.posted.at(-1) ?? '' - const posts = bridge.posted.length - before - const event = posts === 0 ? null : bridge.last() - const b64 = event !== null && 'binary' in event ? event.binary.b64 : '' - return { bytes: utf8ByteLength(json), envelope: utf8ByteLength(json) - b64.length, posts } -} - -// These synthetic bytes prove base64 arithmetic/drop rules, not JPEG bytes-per-pixel assumption. -describe('a frame at exactly the budgeted area', () => { - /** The image the budget says the mobile view's worst case produces, to the byte. */ - const BUDGETED_IMAGE_BYTES = Math.floor( - mobileBrowserFrameAreaBudget() * WORST_CASE_JPEG_BYTES_PER_PIXEL - ) - - it('is a ceiling: an image past it is dropped by the shell, not sent over the cap', () => { - // Unexpected worst-case overflow must be dropped at shell boundary (C6 ruling 1). - const { posts } = postedFrame(noise(BUDGETED_IMAGE_BYTES + binaryEventEnvelopeBytes())) - - expect(posts).toBe(0) - }) -}) diff --git a/mobile/src/browser/browser-screencast-request.web.ts b/mobile/src/browser/browser-screencast-request.web.ts index 30dfe33a956..dacb72fb90e 100644 --- a/mobile/src/browser/browser-screencast-request.web.ts +++ b/mobile/src/browser/browser-screencast-request.web.ts @@ -37,7 +37,7 @@ const WIDEST_JSON_DOUBLE_CHARS = 25 const NARROWEST_JSON_DOUBLE_CHARS = 1 // Derive envelope bound from real protocol shape: longest correlation id, MAX_SAFE_INTEGER counters and every metadata field widened to finite-double maximum. -// Budget cannot predict unknown loose metadata or letterboxed web frames; shell drops over-cap frames. browser-screencast-budget-at-the-shell.test.ts reconstructs bound from real encoded/serialized event. +// Budget cannot predict unknown loose metadata or letterboxed web frames; shell drops over-cap frames. export function binaryEventEnvelopeBytes(): number { const skeleton = JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, diff --git a/mobile/src/components/MobileMarkdown.rendering.test.tsx b/mobile/src/components/MobileMarkdown.rendering.test.tsx deleted file mode 100644 index b01e4830d69..00000000000 --- a/mobile/src/components/MobileMarkdown.rendering.test.tsx +++ /dev/null @@ -1,115 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { MobileMarkdown } from './MobileMarkdown' -import { MarkdownLinkHandlerContext } from './markdown-link-handler' - -const openURL = vi.fn((_url: string) => Promise.resolve()) - -vi.mock('react-native', () => ({ - Linking: { openURL: (url: string) => openURL(url) }, - Platform: { OS: 'ios' }, - Pressable: 'Pressable', - ScrollView: 'ScrollView', - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - Text: 'Text', - View: 'View' -})) -vi.mock('./pr-sidebar/MermaidDiagram', () => ({ MermaidDiagram: 'MermaidDiagram' })) -vi.mock('./MobileSourceCopyButton', () => ({ MobileSourceCopyButton: 'MobileSourceCopyButton' })) - -let renderer: ReactTestRenderer | null = null - -afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - openURL.mockClear() -}) - -function render(content: string, growing = false): ReactTestRenderer { - act(() => { - renderer = create(createElement(MobileMarkdown, { content, growing })) - }) - return renderer! -} - -function flatten(node: ReactTestInstance | string): string { - return typeof node === 'string' ? node : node.children.map(flatten).join('') -} - -const isText = (node: ReactTestInstance): boolean => String(node.type) === 'Text' - -/** Every Text not inside another Text, in reading order: what the reader sees, block by block. */ -function texts(tree: ReactTestRenderer): string[] { - return tree.root - .findAll((node) => isText(node) && !(node.parent && hasTextAncestor(node.parent))) - .map(flatten) -} - -function hasTextAncestor(node: ReactTestInstance): boolean { - return isText(node) || (node.parent !== null && hasTextAncestor(node.parent)) -} - -function press(tree: ReactTestRenderer, label: string): void { - const target = tree.root.find( - (node) => isText(node) && typeof node.props.onPress === 'function' && flatten(node) === label - ) - act(() => target.props.onPress()) -} - -describe('MobileMarkdown rendering', () => { - it('C21: closes open markup while a reply grows, and never links a half-written address', () => { - expect(texts(render('2 * 3 is six.\n\nRead **src/main/ses', true))).toEqual([ - '2 * 3 is six.', - 'Read src/main/ses' - ]) - const tree = render('See [config loader](https://exa', true) - expect(texts(tree)).toEqual(['See config loader']) - expect(tree.root.findAll((node) => typeof node.props.onPress === 'function')).toEqual([]) - }) - - it('hands a web link to the screen that offers choices; mail and file links still open directly', () => { - const onOpenLink = vi.fn() - const onOpenFile = vi.fn() - act(() => { - renderer = create( - createElement( - MarkdownLinkHandlerContext.Provider, - { value: onOpenLink }, - createElement(MobileMarkdown, { - content: '[docs](https://x.com/a), [mail](mailto:a@x.com) and [file](src/a.ts)', - onOpenFile - }) - ) - ) - }) - press(renderer!, 'docs') - press(renderer!, 'mail') - press(renderer!, 'file') - - expect(onOpenLink).toHaveBeenCalledTimes(1) - expect(onOpenLink).toHaveBeenCalledWith('https://x.com/a') - expect(openURL).toHaveBeenCalledTimes(1) - expect(openURL).toHaveBeenCalledWith('mailto:a@x.com') - expect(onOpenFile).toHaveBeenCalledWith('src/a.ts') - }) -}) - -it('draws every image in a paragraph and keeps the text around them, leaving declined images as links', () => { - const renderImage = vi.fn((href: string, alt: string) => - href.startsWith('/') ? createElement('View', { testID: `image:${href}`, alt }) : null - ) - act(() => { - renderer = create( - createElement(MobileMarkdown, { - content: - 'Before and after: \n![one](/tmp/a.png)\n![two](/tmp/b.png)\n![three](rel.png) done', - renderImage - }) - ) - }) - const images = renderer!.root.findAll((node) => String(node.props.testID).startsWith('image:')) - expect(images.map((node) => node.props.testID)).toEqual(['image:/tmp/a.png', 'image:/tmp/b.png']) - expect(texts(renderer!)).toEqual(['Before and after:', 'three done']) -}) diff --git a/mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx b/mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx deleted file mode 100644 index a8043236b5d..00000000000 --- a/mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx +++ /dev/null @@ -1,90 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { beforeEach, expect, it, vi } from 'vitest' -import { clearDisclosuresForTests } from '../worktree/agent-child-disclosure' -import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' -import { WorktreeAgentSummary } from './WorktreeAgentSummary' -import { WorktreeAgentList } from './WorktreeAgentList' - -// Disclosures persist in a module cache across list remounts; isolate each test. -beforeEach(clearDisclosuresForTests) - -vi.mock('react-native', () => ({ - AppState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) }, - Pressable: 'Pressable', - StyleSheet: { create: (styles: T) => styles }, - Text: 'Text', - View: 'View' -})) -vi.mock('lucide-react-native', () => ({ - ChevronDown: 'ChevronDown', - ChevronRight: 'ChevronRight' -})) -vi.mock('./AgentStateDot', () => ({ AgentStateDot: () => null })) -vi.mock('./MobileAgentIcon', () => ({ MobileAgentIcon: () => null })) - -it('renders production-built canonical assignments as nested rows and groups only roots', async () => { - const clock = vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000) - const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = - await import('../../../src/main/runtime/workspaces/process-listing/runtime-agent-lineage.test-fixture') - const { flattenAgentRowLineage } = await import('../worktree/agent-row-lineage') - const f = publicLineageFixture() - let tree: ReactTestRenderer | undefined - try { - const agents = f.build().agents - expect(flattenAgentRowLineage(agents).map((node) => [node.row.paneKey, node.depth])).toEqual([ - [canonicalChatRow(LINEAGE_PARENT), 0], - [canonicalChatRow(LINEAGE_CHILD), 1] - ]) - await act(async () => { - tree = create( - createElement(WorktreeAgentList, { - agents, - unvisited: false, - statusLive: true - }) - ) - }) - const toggle = tree?.root.find( - (node) => node.props.accessibilityLabel === 'Show 1 child agent' && node.props.onPress - ) - await act(async () => toggle?.props.onPress({ stopPropagation: vi.fn() })) - expect( - tree?.root - .findAll((node) => node.props.agent !== undefined) - .map((node) => [node.props.agent.paneKey, node.props.depth]) - ).toEqual([ - [canonicalChatRow(LINEAGE_PARENT), 0], - [canonicalChatRow(LINEAGE_CHILD), 1] - ]) - expect(tree?.root.findAllByType(WorktreeAgentSummary)).toHaveLength(0) - expect(agents[1].taskTitle).toBe('Build the worker result') - expect(JSON.stringify(tree?.toJSON())).toContain('Coordinate work') - expect(JSON.stringify(tree?.toJSON())).toContain('Implement work') - expect(JSON.stringify(tree?.toJSON())).not.toContain('2 agents') - expect(JSON.stringify(tree?.toJSON())).not.toContain(f.privateHandle) - expect(JSON.stringify(tree?.toJSON())).not.toContain(f.privatePane) - const orphan = { - ...agents[1], - paneKey: 'missing-parent-worker', - parentPaneKey: 'missing-parent' - } - await act(async () => - tree?.update( - createElement(WorktreeAgentList, { - agents: [...agents, orphan], - unvisited: false - }) - ) - ) - expect( - tree?.root - .findByType(WorktreeAgentSummary) - .props.agents.map((row: RuntimeWorktreeAgentRow) => row.paneKey) - ).toEqual([canonicalChatRow(LINEAGE_PARENT), orphan.paneKey]) - } finally { - await act(async () => tree?.unmount()) - f.db.close() - clock.mockRestore() - } -}) diff --git a/mobile/src/components/mobile-markdown-visual-lines.test.ts b/mobile/src/components/mobile-markdown-visual-lines.test.ts deleted file mode 100644 index 62dd3318518..00000000000 --- a/mobile/src/components/mobile-markdown-visual-lines.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE } from '../../../src/shared/native-chat/native-chat-visual-directive' -import { plainText } from './mobile-markdown-plain-text' -import { parseMobileMarkdownTree } from './mobile-markdown-tree' -import { - mobileMarkdownVisualPlaceholderIndex, - protectMobileMarkdownVisualLines -} from './mobile-markdown-visual-lines' - -/** The top-level blocks drawn, with a lone placeholder paragraph read as its visual. */ -function topLevelBlocks(text: string, visualCount: number) { - return parseMobileMarkdownTree(text, false).children.map((node) => { - const visual = - node.type === 'paragraph' - ? mobileMarkdownVisualPlaceholderIndex(plainText(node), visualCount) - : null - if (visual !== null) { - return { type: 'visual', index: visual } - } - return node.type === 'code' - ? { type: 'code', text: node.value, language: node.lang } - : { type: node.type, text: plainText(node) } - }) -} - -/** The same steps MobileMarkdown runs when a transcript renders visuals. */ -function blocksOf(content: string) { - const { text, directives } = protectMobileMarkdownVisualLines(content) - return { directives, blocks: topLevelBlocks(text, directives.length) } -} - -describe('native-chat visual lines in mobile markdown', () => { - it('turns a directive line into its own block between prose', () => { - const { directives, blocks } = blocksOf( - 'Here is the chart.\n::orca-visual{file="usage-3f2a.html" title="Usage"}\nIt shows a dip.' - ) - expect(directives).toEqual([{ file: 'usage-3f2a.html', title: 'Usage' }]) - expect(blocks).toEqual([ - { type: 'paragraph', text: 'Here is the chart.' }, - { type: 'visual', index: 0 }, - { type: 'paragraph', text: 'It shows a dip.' } - ]) - }) - - it('keeps the title exactly as written, before entity decoding and tag stripping', () => { - const { directives } = blocksOf('::orca-visual{file="a.html" title="Q1 & Q2"}') - expect(directives).toEqual([{ file: 'a.html', title: 'Q1 & Q2' }]) - }) - - it('accepts CRLF line endings and up to three leading spaces', () => { - const { blocks } = blocksOf('intro\r\n ::orca-visual{file="a.html"}\r\nend') - expect(blocks.map((block) => block.type)).toEqual(['paragraph', 'visual', 'paragraph']) - }) - - it('leaves directives inside fenced code, quotes, list items and inline code as text', () => { - const fenced = blocksOf('```md\n::orca-visual{file="a.html"}\n```') - expect(fenced.directives).toEqual([]) - expect(fenced.blocks).toEqual([ - { type: 'code', text: '::orca-visual{file="a.html"}', language: 'md' } - ]) - expect(blocksOf('> ::orca-visual{file="a.html"}').directives).toEqual([]) - expect(blocksOf('- ::orca-visual{file="a.html"}').directives).toEqual([]) - expect(blocksOf('see `::orca-visual{file="a.html"}`').directives).toEqual([]) - expect(blocksOf(' ::orca-visual{file="a.html"}').directives).toEqual([]) - }) - - it('resumes recognizing directives after a fence closes', () => { - const { directives } = blocksOf('```\ncode\n```\n::orca-visual{file="after.html"}') - expect(directives).toEqual([{ file: 'after.html', title: null }]) - }) - - it('renders directives past the per-message cap as text', () => { - const lines = Array.from( - { length: NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE + 1 }, - (_, index) => `::orca-visual{file="v${index}.html"}` - ) - const { directives, blocks } = blocksOf(lines.join('\n')) - expect(directives).toHaveLength(NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE) - expect(blocks.at(-1)).toEqual({ type: 'paragraph', text: lines.at(-1) }) - }) - - it('renders no visuals for text that already spells a placeholder', () => { - const { directives } = blocksOf('\uE000ORCA_VISUAL_0\uE000\n::orca-visual{file="a.html"}') - expect(directives).toEqual([]) - }) - - it('never treats a placeholder-looking line as a visual when none were protected', () => { - expect(topLevelBlocks('\uE000ORCA_VISUAL_0\uE000', 0)).toEqual([ - { type: 'paragraph', text: '\uE000ORCA_VISUAL_0\uE000' } - ]) - }) -}) diff --git a/mobile/src/components/pr-sidebar/pr-actions-state.test.ts b/mobile/src/components/pr-sidebar/pr-actions-state.test.ts deleted file mode 100644 index dfc489ea490..00000000000 --- a/mobile/src/components/pr-sidebar/pr-actions-state.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { summarizeProviderChecks } from '../../../../src/shared/source-control/checks/provider-check-summary' -import { describe, expect, it } from 'vitest' -import type { PRInfo } from '../../../../src/shared/github/pull-request-types' -import { presentPrMerge } from './pr-actions-state' - -describe('presentPrMerge', () => { - const pr: PRInfo = { - number: 202, - title: 'API', - state: 'open', - url: 'https://example.test/202', - checksStatus: 'success', - updatedAt: '', - mergeable: 'CONFLICTING' - } - const entry = { - title: '', - url: '', - state: 'open' as const, - checksStatus: 'success' as const, - mergeable: 'MERGEABLE' as const - } - - it('lets a complete stack merge through, and names a blocking downstack PR', () => { - const stack = { - number: 51, - position: 2, - size: 3, - baseRefName: 'main', - entries: [ - { ...entry, position: 1, number: 201 }, - { ...entry, position: 2, number: 202 } - ] - } - expect(presentPrMerge({ ...pr, stack }, 'squash')).toMatchObject({ - enabled: true, - label: 'Merge through #202 · 2 PRs' - }) - const blocked = { - ...stack, - entries: [{ ...entry, position: 1, number: 201, state: 'draft' as const }, stack.entries[1]] - } - expect(presentPrMerge({ ...pr, stack: blocked }, 'squash')).toMatchObject({ - enabled: false, - hint: '#201 is still a draft.' - }) - }) - it('keeps the provider-authorized merge action available with cancelled checks', () => { - const checksSummary = summarizeProviderChecks([ - { status: 'completed', conclusion: 'success' }, - { status: 'completed', conclusion: 'cancelled' } - ]) - expect( - presentPrMerge( - { - ...pr, - mergeable: 'MERGEABLE', - mergeStateStatus: 'CLEAN', - checksStatus: 'failure', - checksSummary - }, - 'squash' - ) - ).toMatchObject({ - label: 'Squash and merge', - hint: null, - enabled: true - }) - }) -}) diff --git a/mobile/src/components/pr-sidebar/pr-checks-presentation.test.ts b/mobile/src/components/pr-sidebar/pr-checks-presentation.test.ts deleted file mode 100644 index f34823dcdf1..00000000000 --- a/mobile/src/components/pr-sidebar/pr-checks-presentation.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { expect, it } from 'vitest' -import type { PRCheckDetail } from '../../../../src/shared/github/check-types' -import { summarizePRChecks } from './pr-checks-presentation' - -function check(over: Partial): PRCheckDetail { - return { - name: 'ci', - status: 'completed', - conclusion: 'success', - url: null, - ...over - } -} - -it('presents cancellations without hiding real failure or pending checks', () => { - const cancelled = check({ conclusion: 'cancelled' }) - expect(summarizePRChecks([cancelled, check({})])).toMatchObject({ - outcome: 'cancelled', - failed: 0, - cancelled: 1, - label: '1 Cancelled · 1 passed' - }) - expect(summarizePRChecks([cancelled, check({ conclusion: 'pending' })]).outcome).toBe('pending') - expect(summarizePRChecks([cancelled, check({ conclusion: 'failure' })]).outcome).toBe('failure') -}) diff --git a/mobile/src/components/use-connected-host-picker.test.ts b/mobile/src/components/use-connected-host-picker.test.ts index 40e23a8f684..052c1b4a5f2 100644 --- a/mobile/src/components/use-connected-host-picker.test.ts +++ b/mobile/src/components/use-connected-host-picker.test.ts @@ -50,21 +50,6 @@ describe('useConnectedHostPicker', () => { act(() => handle.current!.pickHost(action, hosts)) } - it('disambiguates path-routed hosts without exposing endpoint paths', () => { - render([ - host('desk-a', 'Desk', 'wss://gateway.example.com/v1/connect/bearer-secret-a'), - host('desk-b', 'Desk', 'wss://gateway.example.com/v1/connect/bearer-secret-b') - ]) - - pickHost(vi.fn()) - - expect(picker().options).toEqual([ - { value: 'desk-a', label: 'Desk', subtitle: 'gateway.example.com · desk-a' }, - { value: 'desk-b', label: 'Desk', subtitle: 'gateway.example.com · desk-b' } - ]) - expect(JSON.stringify(picker().options)).not.toContain('bearer-secret') - }) - it('closes a stale picker when an offered host disconnects', () => { const rerender = render([desk, laptop]) diff --git a/mobile/src/components/use-detail-card-scope.web.test.tsx b/mobile/src/components/use-detail-card-scope.web.test.tsx deleted file mode 100644 index e615d52d926..00000000000 --- a/mobile/src/components/use-detail-card-scope.web.test.tsx +++ /dev/null @@ -1,193 +0,0 @@ -// @vitest-environment happy-dom -import { act, useRef } from 'react' -import { createRoot } from 'react-dom/client' -import { expect, it, vi } from 'vitest' -import { - DetailCardHostProvider, - DetailCardLayer, - DetailCardFocusBoundary -} from './detail-card-host.web' -import { useDetailCardScope } from './use-detail-card-scope.web' - -it('keeps outside actions and finite focus order while releasing a retained visual', () => { - const root = document.createElement('div') - document.body.append(root) - const node = (id: string) => { - const value = document.getElementById(id) - if (!(value instanceof HTMLElement)) { - throw new Error(id) - } - return value - } - const renderer = createRoot(root) - const dismiss = vi.fn() - const action = vi.fn() - function Scope({ active, obscured = false }: { active: boolean; obscured?: boolean }) { - const contentRef = useRef(null) - const boundaryRefs = useRef([]) - const openerRef = useRef(null) - const backRef = useRef(null) - useDetailCardScope({ active, obscured, openerRef, backRef, contentRef, boundaryRefs, dismiss }) - return ( - <> - - - - - - - - -
-
- Details -
-
- -
- - ) - } - const render = (active: boolean, obscured = false) => - act(() => - renderer.render( - - - - ) - ) - const focusBoundary = (id: string, backwards: boolean) => { - const boundary = backwards ? node(id).previousElementSibling : node(id).nextElementSibling - if (!(boundary instanceof HTMLElement)) { - throw new Error(`Missing focus boundary beside ${id}`) - } - boundary.focus() - } - - const key = (type: string, name: string, shiftKey = false) => - document.activeElement?.dispatchEvent( - new KeyboardEvent(type, { key: name, shiftKey, bubbles: true, cancelable: true }) - ) - const terminalKeys = vi.fn() - window.addEventListener('keydown', terminalKeys) - try { - render(false) - expect(document.activeElement).toBe(document.body) - const opener = node('opener') - const host = node('card').parentElement - expect(host?.parentElement).toBe(document.body) - node('terminal').focus() - render(true) - expect(node('terminal').inert).toBe(false) - expect(document.activeElement).toBe(node('terminal')) - node('back').click() - expect(dismiss).not.toHaveBeenCalled() - key('keydown', 'Escape') - key('keyup', 'Escape') - expect(terminalKeys).not.toHaveBeenCalled() - key('keydown', 'a') - expect(terminalKeys).toHaveBeenCalledTimes(1) - render(false) - expect(node('card').inert).toBe(true) - expect(opener.previousElementSibling).toBe(node('back')) - expect(opener.nextElementSibling).toBe(node('files')) - expect(node('card').nextElementSibling).toBeNull() - expect(document.activeElement).toBe(node('terminal')) - render(true) - key('keydown', 'Tab') - focusBoundary('opener', false) - expect(document.activeElement).toBe(node('scroll')) - key('keydown', 'Tab', true) - focusBoundary('card', true) - expect(document.activeElement).toBe(opener) - key('keydown', 'Tab', true) - focusBoundary('opener', true) - expect(document.activeElement).toBe(node('back')) - render(false) - render(true) - key('keydown', 'Tab') - focusBoundary('card', false) - expect(document.activeElement).toBe(node('files')) - expect(dismiss).toHaveBeenCalledTimes(3) - render(false) - render(true) - node('files').click() - expect(action).toHaveBeenCalledTimes(1) - expect(dismiss).toHaveBeenCalledTimes(4) - node('files').focus() - render(false) - expect(document.activeElement).toBe(node('files')) - render(true) - node('files').focus() - expect(dismiss).toHaveBeenCalledTimes(5) - render(false) - expect(document.activeElement).toBe(node('files')) - render(true) - render(false, true) - expect(node('card').inert).toBe(true) - expect(node('opener')).toBe(opener) - act(() => renderer.unmount()) - expect(host?.isConnected).toBe(false) - } finally { - window.removeEventListener('keydown', terminalKeys) - root.remove() - } -}) - -it('yields to a higher sheet while an earlier card contact is still in flight', () => { - const root = document.createElement('div') - document.body.append(root) - const mount = document.createElement('div') - root.append(mount) - const renderer = createRoot(mount) - const dismiss = vi.fn() - const action = vi.fn() - const openerRef = { current: document.createElement('button') } - const contentRef = { current: document.createElement('div') } - const backRef = { current: document.createElement('button') } - const boundaryRefs = { current: [] } - const sheet = document.createElement('button') - contentRef.current.tabIndex = -1 - sheet.addEventListener('click', action) - root.append(openerRef.current, backRef.current, contentRef.current, sheet) - function Scope({ obscured }: { obscured: boolean }) { - useDetailCardScope({ - active: !obscured, - obscured, - openerRef, - contentRef, - backRef, - boundaryRefs, - dismiss - }) - return null - } - const contact = (target: HTMLElement, type: string, pointerId: number) => - target.dispatchEvent( - new PointerEvent(type, { pointerId, pointerType: 'touch', bubbles: true, cancelable: true }) - ) - try { - openerRef.current.focus() - act(() => renderer.render()) - expect(contact(contentRef.current, 'pointerdown', 1)).toBe(true) - act(() => renderer.render()) - sheet.focus() - expect(contentRef.current.inert).toBe(true) - expect(contact(sheet, 'pointerdown', 2)).toBe(true) - expect(contact(contentRef.current, 'pointerup', 1)).toBe(true) - expect(contact(sheet, 'pointerup', 2)).toBe(true) - sheet.click() - expect(action).toHaveBeenCalledTimes(1) - expect(dismiss).not.toHaveBeenCalled() - expect(document.activeElement).toBe(sheet) - } finally { - act(() => renderer.unmount()) - root.remove() - } -}) diff --git a/mobile/src/diagnostics/connection/connection-log-buffer.test.ts b/mobile/src/diagnostics/connection/connection-log-buffer.test.ts index 631d5af747b..39712e28e54 100644 --- a/mobile/src/diagnostics/connection/connection-log-buffer.test.ts +++ b/mobile/src/diagnostics/connection/connection-log-buffer.test.ts @@ -31,64 +31,6 @@ describe('connection log buffer', () => { expect(JSON.stringify(save.mock.calls)).not.toContain('legacy-secret') }) - it('redacts quoted credential values when the object key is unquoted', async () => { - const store = createConnectionLogStore(3, { load: async () => [], save: async () => {} }) - - store.append('host-a', { - ...entry(1), - detail: `resumeToken: 'secret-one' deviceToken="secret-two"` - }) - await store.hydrate('host-a') - - expect(store.get('host-a')[0]?.detail).toBe( - `resumeToken: '[redacted]' deviceToken="[redacted]"` - ) - }) - - it('redacts the full quoted credential when its value contains an escaped quote', async () => { - const store = createConnectionLogStore(3, { load: async () => [], save: async () => {} }) - - store.append('host-a', { - ...entry(1), - detail: String.raw`{"token":"secret\"tail"} token: 'secret\'tail'` - }) - await store.hydrate('host-a') - - expect(store.get('host-a')[0]?.detail).toBe(`{"token":"[redacted]"} token: '[redacted]'`) - }) - - it('redacts unterminated quoted credentials', async () => { - const store = createConnectionLogStore(3, { load: async () => [], save: async () => {} }) - - store.append('host-a', { - ...entry(1), - message: 'token="secret', - detail: '{"authorization":"Bearer also-secret' - }) - await store.hydrate('host-a') - - expect(store.get('host-a')[0]).toMatchObject({ - message: 'token="[redacted]', - detail: '{"authorization":"[redacted]' - }) - }) - - it('redacts URL userinfo through the last authority separator', async () => { - const store = createConnectionLogStore(3, { load: async () => [], save: async () => {} }) - - store.append('host-a', { - ...entry(1), - message: 'wss://user:p@ss@example.com/x', - detail: 'https://user:pass@example.com/x' - }) - await store.hydrate('host-a') - - expect(store.get('host-a')[0]).toMatchObject({ - message: 'wss://[redacted]@example.com/x', - detail: 'https://[redacted]@example.com/x' - }) - }) - it('does not overwrite persisted history when hydration fails and retries later', async () => { const load = vi .fn<() => Promise>() diff --git a/mobile/src/diagnostics/native-diagnostics-operations.test.ts b/mobile/src/diagnostics/native-diagnostics-operations.test.ts index f87c0f062bc..38cbb6e3ab2 100644 --- a/mobile/src/diagnostics/native-diagnostics-operations.test.ts +++ b/mobile/src/diagnostics/native-diagnostics-operations.test.ts @@ -60,23 +60,4 @@ describe('native connection diagnostic reports', () => { expect(report).toContain('Host Orca version: unknown') expect(report).not.toContain('1.4.197') }) - - it('does not promote a disconnected version when a connection opens during hydration', async () => { - let finishHydration = () => {} - logStore.hydrate.mockReturnValue( - new Promise((resolve) => { - finishHydration = resolve - }) - ) - const context = createContext() - context.setConnection('disconnected', 1_000) - const device = createNativeDiagnosticsOperations(host, context, '1.4.197') - const pendingReport = device.report() - context.setConnection('connected', 1_000) - finishHydration() - const { report } = await pendingReport - expect(report).toContain('State: connected') - expect(report).toContain('Host Orca version: unknown') - expect(report).not.toContain('1.4.197') - }) }) diff --git a/mobile/src/diagnostics/native-render-log.test.ts b/mobile/src/diagnostics/native-render-log.test.ts index b6a82eb4b6f..fb00974e5af 100644 --- a/mobile/src/diagnostics/native-render-log.test.ts +++ b/mobile/src/diagnostics/native-render-log.test.ts @@ -1,6 +1,5 @@ import AsyncStorage from '@react-native-async-storage/async-storage' import { beforeEach, expect, it, vi } from 'vitest' -import type { HostProfile } from '../transport/hosts/host-profile' vi.mock('react-native', () => ({ Platform: { OS: 'ios', Version: '27' } })) vi.mock('expo-constants', () => ({ default: { expoConfig: { version: '0.0.60' } } })) @@ -8,22 +7,6 @@ vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: vi.fn(), setItem: vi.fn() } })) -const context = { - getState: () => 'disconnected' as const, - getReconnectAttempt: () => 0, - getLastConnectedAt: () => null, - getActivePath: () => 'lan' as const, - getPendingPath: () => null -} -const pairedHost: HostProfile = { - id: 'desktop', - name: 'Desktop', - endpoint: 'ws://desktop.invalid:6768', - deviceToken: 'device-secret', - publicKeyB64: 'key', - lastConnected: 0 -} - beforeEach(() => { vi.resetModules() const storage = new Map() @@ -33,30 +16,6 @@ beforeEach(() => { }) }) -it.each([null, pairedHost])( - 'retains a native render failure in the copied report after restart, host %s', - async (host) => { - const { recordNativeRenderError, NATIVE_APP_LOG_ID } = await import('./native-render-log') - const { connectionLogStore } = await import('./connection/persisted-connection-log-store') - const failure = new Error('Private prompt\n at PRIVATE PROMPT\ntoken=do-not-share') - failure.stack = `${failure.name}: ${failure.message}\n at UnauthorizedAboutRoute (/Users/private/project/about.tsx:12:3)` - recordNativeRenderError(failure, 'about') - await connectionLogStore.hydrate(NATIVE_APP_LOG_ID) - await connectionLogStore.flush() - vi.resetModules() - - const { createNativeDiagnosticsOperations } = await import('./native-diagnostics-operations') - const { report, incidentId } = await createNativeDiagnosticsOperations(host, context).report() - expect(report).toContain('Native screen failed to render') - expect(report).toContain('UnauthorizedAboutRoute') - expect(report).not.toContain('Private prompt') - expect(report).not.toContain('PRIVATE PROMPT') - expect(report).not.toContain('do-not-share') - expect(report).not.toContain('/Users/private') - expect(incidentId).toBeNull() - } -) - it('keeps a log entry when the thrown error has an unreadable stack', async () => { const { recordNativeRenderError, NATIVE_APP_LOG_ID } = await import('./native-render-log') const failure = new Error('bad stack') diff --git a/mobile/src/diagnostics/use-troubleshoot-diagnostics.test.tsx b/mobile/src/diagnostics/use-troubleshoot-diagnostics.test.tsx deleted file mode 100644 index b1c00c11225..00000000000 --- a/mobile/src/diagnostics/use-troubleshoot-diagnostics.test.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as HostReachability from './host-reachability' - -const hosts = vi.hoisted(() => ({ - catalog: vi.fn<() => Promise<{ endpoint: string }[]>>(), - profiles: vi.fn<() => Promise<{ name: string; endpoint: string }[]>>() -})) -vi.mock('react-native', () => ({ Platform: { OS: 'ios', Version: '27' } })) -vi.mock('../transport/hosts/host-store', () => ({ - loadHostCatalog: hosts.catalog, - loadHosts: hosts.profiles -})) -vi.mock('./host-reachability', async (importOriginal) => ({ - ...(await importOriginal()), - testHostReachability: async () => true -})) - -import { useTroubleshootDiagnostics } from './use-troubleshoot-diagnostics' - -let tree: ReactTestRenderer | undefined -const state: { current: ReturnType | null } = { current: null } -function Harness() { - state.current = useTroubleshootDiagnostics() - return null -} - -afterEach(async () => { - await act(async () => tree?.unmount()) - state.current = null - vi.resetAllMocks() - vi.unstubAllGlobals() -}) - -describe('troubleshooting paired endpoints', () => { - it('retains saved port advice after a run when the host credential is unavailable', async () => { - hosts.catalog.mockResolvedValue([{ endpoint: 'ws://desktop.local:6769' }]) - hosts.profiles.mockResolvedValue([]) - vi.stubGlobal('fetch', async () => ({ ok: true })) - await act(async () => { - tree = create(createElement(Harness)) - }) - expect(state.current?.hostEndpoints).toEqual(['ws://desktop.local:6769']) - await act(async () => { - await state.current?.runDiagnostics() - }) - expect(state.current?.hostEndpoints).toEqual(['ws://desktop.local:6769']) - }) -}) diff --git a/mobile/src/dictation/use-mobile-dictation-silence-stop.test.tsx b/mobile/src/dictation/use-mobile-dictation-silence-stop.test.tsx deleted file mode 100644 index 89981c8538c..00000000000 --- a/mobile/src/dictation/use-mobile-dictation-silence-stop.test.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createMobileDictationMeter } from '../hooks/mobile-dictation-meter' -import { useMobileDictationSilenceStop } from './use-mobile-dictation-silence-stop' - -// 16 kHz 16-bit little-endian PCM, as both shells deliver it. -function pcm(milliseconds: number, amplitude: number): Uint8Array { - const samples = (16_000 * milliseconds) / 1000 - const bytes = new Uint8Array(samples * 2) - const view = new DataView(bytes.buffer) - for (let index = 0; index < samples; index += 1) { - view.setInt16(index * 2, index % 2 === 0 ? amplitude : -amplitude, true) - } - return bytes -} - -function record(dictationMode: string) { - const meter = createMobileDictationMeter() - meter.start() - const dictation = { isRecording: true, meter } - const stop = vi.fn() - const showToast = vi.fn() - function Probe() { - useMobileDictationSilenceStop(dictation, dictationMode, stop, showToast) - return null - } - let renderer: ReactTestRenderer | undefined - act(() => { - renderer = create(createElement(Probe)) - }) - // Feed the mic the way the page shell drains it: 500 ms batches at the given amplitude. - const play = (seconds: number, amplitude: number) => { - for (let batch = 0; batch < seconds * 2; batch += 1) { - act(() => { - meter.push(pcm(500, amplitude)) - vi.advanceTimersByTime(500) - }) - } - } - return { stop, showToast, play, unmount: () => act(() => renderer?.unmount()) } -} - -describe('dictation silence stop', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => vi.useRealTimers()) - - it('never stops a hold-mode recording', () => { - const { stop, unmount } = record('hold') - act(() => { - vi.advanceTimersByTime(120_000) - }) - expect(stop).not.toHaveBeenCalled() - unmount() - }) -}) diff --git a/mobile/src/files/MobileMarkdownPreviewImage.test.tsx b/mobile/src/files/MobileMarkdownPreviewImage.test.tsx deleted file mode 100644 index 3bd696f63bd..00000000000 --- a/mobile/src/files/MobileMarkdownPreviewImage.test.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import { createElement } from 'react' -import type { ImageProps } from 'react-native' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, expect, it, vi } from 'vitest' -import { MobileMarkdownPreviewImage } from './MobileMarkdownPreviewImage' - -vi.mock('react-native', () => ({ - ActivityIndicator: 'ActivityIndicator', - Image: Object.assign((props: ImageProps) => createElement('Image', props), { - getSize: (_uri: string, loaded: (width: number, height: number) => void) => loaded(600, 220) - }), - Pressable: 'Pressable', - StyleSheet: { create: (styles: unknown) => styles }, - Text: 'Text', - View: 'View' -})) -vi.mock('../components/MobileStateView', () => ({ MobileLoadErrorState: 'LoadError' })) -vi.mock('../session/native-chat/visual/MobileNativeChatImageViewer', () => ({ - MobileNativeChatImageViewer: 'ImageViewer' -})) -vi.mock('../session/native-chat/visual/MobileImageViewerActions', () => ({ - MobileImageViewerActions: 'ImageViewerActions' -})) -const loader = vi.hoisted(() => vi.fn()) -vi.mock('./mobile-markdown-image-source', () => ({ loadMarkdownPreviewImage: loader })) -let tree: ReactTestRenderer | null = null -afterEach(() => { - act(() => tree?.unmount()) - tree = null - vi.resetAllMocks() -}) -const props = { - client: null, - worktreeId: 'wt', - documentPath: 'notes.md', - href: 'a.png', - alt: 'Architecture' -} - -it('retries a refused image without hiding the surrounding document', async () => { - loader - .mockRejectedValueOnce(new Error('Unable to reach the desktop filesystem')) - .mockResolvedValueOnce('data:image/png;base64,cG5n') - await act(async () => { - tree = create(createElement(MobileMarkdownPreviewImage, props)) - }) - expect(tree!.root.find((node) => String(node.type) === 'LoadError').props.error).toContain( - 'Unable to reach' - ) - await act(async () => - tree!.root.find((node) => String(node.type) === 'LoadError').props.onRetry() - ) - expect(tree!.root.find((node) => String(node.type) === 'Image').props.source.uri).toBe( - 'data:image/png;base64,cG5n' - ) -}) diff --git a/mobile/src/source-control/review/mobile-diff-review-state.test.ts b/mobile/src/source-control/review/mobile-diff-review-state.test.ts index e5a4fbdd4a3..20e73ecedc3 100644 --- a/mobile/src/source-control/review/mobile-diff-review-state.test.ts +++ b/mobile/src/source-control/review/mobile-diff-review-state.test.ts @@ -31,14 +31,4 @@ describe('mobile diff review state', () => { expect(merged.completedAt).toBeUndefined() }) - - it('keeps completion when refreshed identities are unchanged', () => { - const reviewed = markMobileDiffReviewFileReviewed(createMobileDiffReviewState(1), descriptor, 5) - const completed = completeMobileDiffReviewState(reviewed, 6) - - const merged = mergeMobileDiffReviewState(completed, [descriptor], 8) - - expect(merged.completedAt).toBe(6) - expect(merged.files[descriptor.key]?.reviewedAt).toBe(5) - }) }) diff --git a/mobile/src/source-control/review/optimistic-write-sequence.test.ts b/mobile/src/source-control/review/optimistic-write-sequence.test.ts deleted file mode 100644 index 68e619cf5ad..00000000000 --- a/mobile/src/source-control/review/optimistic-write-sequence.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createOptimisticField } from './optimistic-write-sequence' - -describe('OptimisticField — last-intent-wins', () => { - it('reverts only the latest write on failure', () => { - const field = createOptimisticField() - const seqA = field.begin(true) - const seqB = field.begin(false) - expect(field.resolve(false)).toBe(false) - - expect(field.settleFailure(seqA)).toBe(false) - expect(field.resolve(false)).toBe(false) - - expect(field.settleFailure(seqB)).toBe(true) - expect(field.resolve(true)).toBe(true) - }) - - it('a stale failure does not clear a newer optimistic value', () => { - const field = createOptimisticField() - const seqOld = field.begin('old') - field.begin('new') - expect(field.resolve('auth')).toBe('new') - expect(field.settleFailure(seqOld)).toBe(false) - expect(field.resolve('auth')).toBe('new') - }) -}) diff --git a/mobile/src/stats/home-stats-total.test.ts b/mobile/src/stats/home-stats-total.test.ts deleted file mode 100644 index daff818e1fa..00000000000 --- a/mobile/src/stats/home-stats-total.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { totalHomeStats } from './home-stats-total' - -describe('totalHomeStats', () => { - it('sums every desktop instead of letting the last reply win', () => { - const total = totalHomeStats( - { - 'host-1': { totalAgentsSpawned: 10, totalPRsCreated: 2, totalAgentTimeMs: 60_000 }, - 'host-2': { totalAgentsSpawned: 5, totalPRsCreated: 1, totalAgentTimeMs: 30_000 } - }, - ['host-1', 'host-2'] - ) - expect(total).toEqual({ totalAgentsSpawned: 15, totalPRsCreated: 3, totalAgentTimeMs: 90_000 }) - }) - - it('leaves out a desktop that is no longer paired', () => { - const byHost = { - 'host-1': { totalAgentsSpawned: 10, totalPRsCreated: 2, totalAgentTimeMs: 60_000 }, - 'host-2': { totalAgentsSpawned: 5, totalPRsCreated: 1, totalAgentTimeMs: 30_000 } - } - expect(totalHomeStats(byHost, ['host-1'])?.totalAgentsSpawned).toBe(10) - expect(totalHomeStats(byHost, [])).toBeNull() - }) - - it('has no stats until a desktop sends a number', () => { - expect(totalHomeStats({}, ['host-1'])).toBeNull() - // A desktop without stats answers `{}`; that is not a row of zeros. - expect(totalHomeStats({ 'host-1': {} }, ['host-1'])).toBeNull() - }) - - it('skips a malformed reply and keeps the other desktops', () => { - const total = totalHomeStats( - { - 'host-1': { totalAgentsSpawned: 10, totalPRsCreated: 2, totalAgentTimeMs: 60_000 }, - 'host-2': null, - 'host-3': { totalAgentsSpawned: 'lots' }, - 'host-4': { totalAgentsSpawned: Number.NaN, totalPRsCreated: 1 } - }, - ['host-1', 'host-2', 'host-3', 'host-4'] - ) - expect(total).toEqual({ totalAgentsSpawned: 10, totalPRsCreated: 3, totalAgentTimeMs: 60_000 }) - }) -}) diff --git a/mobile/src/tasks/github-pr-file-diff.test.ts b/mobile/src/tasks/github-pr-file-diff.test.ts index 99e1f0ac6c4..5120187262b 100644 --- a/mobile/src/tasks/github-pr-file-diff.test.ts +++ b/mobile/src/tasks/github-pr-file-diff.test.ts @@ -3,44 +3,6 @@ import { describe, expect, it } from 'vitest' import { buildGitHubPrFileDiffLines, buildGitHubPrFileDiffPreview } from './github-pr-file-diff' describe('buildGitHubPrFileDiffLines', () => { - it('preserves context and marks added and removed lines', () => { - expect(buildGitHubPrFileDiffLines('one\ntwo\nthree\n', 'one\ntoo\nthree\n')).toEqual([ - { - key: '0:context:1:1', - kind: 'context', - oldLineNumber: 1, - newLineNumber: 1, - text: 'one' - }, - { - key: '1:removed:2', - kind: 'removed', - oldLineNumber: 2, - text: 'two' - }, - { - key: '2:added:2', - kind: 'added', - newLineNumber: 2, - text: 'too' - }, - { - key: '3:context:3:3', - kind: 'context', - oldLineNumber: 3, - newLineNumber: 3, - text: 'three' - } - ]) - }) - - it('shows added files without a fake empty original line', () => { - expect(buildGitHubPrFileDiffLines('', 'first\nsecond')).toEqual([ - { key: '0:added:1', kind: 'added', newLineNumber: 1, text: 'first' }, - { key: '1:added:2', kind: 'added', newLineNumber: 2, text: 'second' } - ]) - }) - it('keeps all lines for large files without exact diff truncation', () => { const original = Array.from({ length: 500 }, (_, index) => `old-${index}`).join('\n') const modified = Array.from({ length: 500 }, (_, index) => `new-${index}`).join('\n') diff --git a/mobile/src/tasks/jira-mobile-connection.test.ts b/mobile/src/tasks/jira-mobile-connection.test.ts deleted file mode 100644 index d6674d69455..00000000000 --- a/mobile/src/tasks/jira-mobile-connection.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { extractJiraConnection, reconcileJiraConnection } from './jira-mobile-connection' - -const siteA = { - id: 'site-a', - siteUrl: 'https://a.atlassian.net', - email: 'me@example.com', - displayName: 'Site A', - accountId: 'acc-1' -} -const siteB = { ...siteA, id: 'site-b', siteUrl: 'https://b.atlassian.net', displayName: 'Site B' } - -describe('Jira connection compatibility', () => { - it('keeps the phone selection when desktop status is refreshed', () => { - const next = extractJiraConnection({ - connected: true, - sites: [siteA, siteB], - selectedSiteId: 'site-a' - }) - expect(reconcileJiraConnection({ ...next, selection: 'site-b' }, next).selection).toBe('site-b') - expect(reconcileJiraConnection({ ...next, selection: 'all' }, next).selection).toBe('all') - expect(reconcileJiraConnection({ ...next, selection: 'gone' }, next).selection).toBe('site-a') - }) -}) diff --git a/mobile/src/tasks/mobile-jira-task-source.test.ts b/mobile/src/tasks/mobile-jira-task-source.test.ts index 80d09b629f6..7056fbe0009 100644 --- a/mobile/src/tasks/mobile-jira-task-source.test.ts +++ b/mobile/src/tasks/mobile-jira-task-source.test.ts @@ -40,19 +40,4 @@ describe('mobile Jira task requests', () => { ).resolves.toEqual({ issue, comments: [] }) } }) - - it('surfaces issue failures even when comments can be read', async () => { - const sendRequest = vi.fn(async (method: string) => - method === 'jira.getIssue' - ? { - id: 'jira-test', - ok: false as const, - error: { code: 'UNAVAILABLE', message: 'Issue permission denied' } - } - : { id: 'jira-test', ok: true as const, result: [] } - ) - await expect(fetchJiraIssueDetail({ sendRequest }, { key: issue.key })).rejects.toThrow( - 'Issue permission denied' - ) - }) }) diff --git a/mobile/src/tasks/setup-hook-trust.test.ts b/mobile/src/tasks/setup-hook-trust.test.ts deleted file mode 100644 index 326cd96862b..00000000000 --- a/mobile/src/tasks/setup-hook-trust.test.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { isSetupHookTrusted } from './setup-hook-trust' -import type { PersistedTrustedOrcaHooks } from '../../../src/shared/orca-yaml-hook-types' - -describe('setup hook trust', () => { - it('trusts a setup script only when the approved hash matches', () => { - const trust: PersistedTrustedOrcaHooks = { - 'repo-1': { setup: { contentHash: 'hash-1', approvedAt: 1000 } } - } - - expect(isSetupHookTrusted(trust, [{ id: 'repo-1' }], 'repo-1', 'hash-1')).toBe(true) - expect(isSetupHookTrusted(trust, [{ id: 'repo-1' }], 'repo-1', 'hash-2')).toBe(false) - }) -}) diff --git a/mobile/src/tasks/smart-source-paste-intent.test.ts b/mobile/src/tasks/smart-source-paste-intent.test.ts deleted file mode 100644 index 39c53a499b7..00000000000 --- a/mobile/src/tasks/smart-source-paste-intent.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { deriveRepoSlug, resolvePasteIntent } from './smart-source-paste-intent' - -describe('resolvePasteIntent', () => { - it('rejects oversized paste intents before any exact lookup', () => { - expect( - resolvePasteIntent(`https://github.com/acme/widgets/issues/12/${'x'.repeat(2048)}`) - ).toBeNull() - }) -}) - -describe('deriveRepoSlug', () => { - it('preserves an Enterprise upstream host', () => { - expect( - deriveRepoSlug({ - upstream: { owner: 'up', repo: 'stream', host: 'github.corp.example' } - }) - ).toEqual({ owner: 'up', repo: 'stream', host: 'github.corp.example' }) - }) -}) diff --git a/mobile/src/tasks/worktree-create-retry.test.ts b/mobile/src/tasks/worktree-create-retry.test.ts deleted file mode 100644 index ab2cb0702af..00000000000 --- a/mobile/src/tasks/worktree-create-retry.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' - -import { createWorktreeWithNameRetry } from './worktree-create-retry' - -type Attempt = { method: string; params: unknown } - -function scriptedClient( - outcomes: ({ id: string; displayName?: string; warning?: string } | { errorMessage: string })[], - attempts: Attempt[] -): RpcClient { - let call = 0 - const client = new FakeSession('connected') - client.sendRequest.mockImplementation(async (method: string, params?: unknown) => { - attempts.push({ method, params: params ?? {} }) - const outcome = outcomes[Math.min(call, outcomes.length - 1)]! - call += 1 - if ('errorMessage' in outcome) { - return { - id: '1', - ok: false, - error: { code: 'x', message: outcome.errorMessage }, - _meta: { runtimeId: 'r' } - } - } - return { - id: '1', - ok: true, - result: { - worktree: { - id: outcome.id, - ...(outcome.displayName !== undefined ? { displayName: outcome.displayName } : {}) - }, - ...(outcome.warning !== undefined ? { warning: outcome.warning } : {}) - }, - _meta: { runtimeId: 'r' } - } - }) - return client -} - -describe('createWorktreeWithNameRetry', () => { - it('falls back to the client candidate when an older host omits displayName', async () => { - const attempts: Attempt[] = [] - const client = scriptedClient( - [{ errorMessage: 'already exists locally' }, { id: 'wt-legacy' }], - attempts - ) - - await expect( - createWorktreeWithNameRetry({ - client, - baseName: 'topic', - buildParams: (name) => ({ repo: 'id:r', name }), - worktreeCreateIdempotency: false - }) - ).resolves.toEqual({ worktreeId: 'wt-legacy', name: 'topic-2' }) - }) -}) diff --git a/mobile/src/terminal/mobile-terminal-query-reply.test.ts b/mobile/src/terminal/mobile-terminal-query-reply.test.ts deleted file mode 100644 index 2bda14d11d5..00000000000 --- a/mobile/src/terminal/mobile-terminal-query-reply.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' - -import { PROGRAM_STATUS_QUERY_REPLY } from '../../../src/shared/program-status/protocol' -import { sendMobileTerminalQueryReply } from './mobile-terminal-query-reply' - -function createClient() { - return { - sendRequest: vi.fn().mockResolvedValue({ - id: '1', - ok: true, - result: { send: { accepted: true, bytesWritten: 6 } }, - _meta: { runtimeId: 'runtime-1' } - }), - subscribe: () => () => {}, - updateTerminalSubscriptionViewport: () => {}, - getState: () => 'connected', - getReconnectAttempt: () => 0, - getLastConnectedAt: () => null, - onStateChange: () => () => {}, - notifyForeground: () => {}, - close: () => {} - } satisfies RpcClient -} - -describe('sendMobileTerminalQueryReply', () => { - it.each([ - ['disconnected', false, new Set(['terminal-1']), '\x1b[3;4R', 'terminal-1'], - ['unsubscribed', true, new Set(), '\x1b[3;4R', 'terminal-1'], - ['stale handle', true, new Set(['terminal-2']), '\x1b[3;4R', 'terminal-1'], - ['ordinary input', true, new Set(['terminal-1']), 'a', 'terminal-1'] - ])('does not send %s data', async (_case, connected, subscribedTerminals, bytes, handle) => { - const client = createClient() - - await expect( - sendMobileTerminalQueryReply({ - bytes, - client, - clientId: 'mobile-1', - connected, - handle, - hostSupportsQueryReplyInput: true, - hostSupportsProgramStatus: true, - subscribedTerminals - }) - ).resolves.toBe(false) - expect(client.sendRequest).not.toHaveBeenCalled() - }) - - // Older hosts strip inputKind and would treat query replies as floor-taking user input. - it('does not send to a host that has not advertised query-reply input support', async () => { - const client = createClient() - - await expect( - sendMobileTerminalQueryReply({ - bytes: '\x1b[3;4R', - client, - clientId: 'mobile-1', - connected: true, - handle: 'terminal-1', - hostSupportsQueryReplyInput: false, - hostSupportsProgramStatus: true, - subscribedTerminals: new Set(['terminal-1']) - }) - ).resolves.toBe(false) - expect(client.sendRequest).not.toHaveBeenCalled() - }) - - it('does not answer program status for a host that cannot read its reports', async () => { - const client = createClient() - - await expect( - sendMobileTerminalQueryReply({ - bytes: PROGRAM_STATUS_QUERY_REPLY, - client, - clientId: 'mobile-1', - connected: true, - handle: 'terminal-1', - hostSupportsQueryReplyInput: true, - hostSupportsProgramStatus: false, - subscribedTerminals: new Set(['terminal-1']) - }) - ).resolves.toBe(false) - expect(client.sendRequest).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/terminal/session/mobile-terminal-inventory-request.test.ts b/mobile/src/terminal/session/mobile-terminal-inventory-request.test.ts index 63611774fef..9b22756d32f 100644 --- a/mobile/src/terminal/session/mobile-terminal-inventory-request.test.ts +++ b/mobile/src/terminal/session/mobile-terminal-inventory-request.test.ts @@ -6,19 +6,6 @@ describe('MobileTerminalInventoryRequest', () => { vi.restoreAllMocks() }) - it('starts fresh after the shared request settles or rejects', async () => { - const requests = new MobileTerminalInventoryRequest() - const failure = new Error('transport lost') - - await expect( - requests.run(true, async () => { - throw failure - }) - ).rejects.toBe(failure) - await expect(requests.run(true, async () => true)).resolves.toBe(true) - await expect(requests.run(true, async () => false)).resolves.toBe(false) - }) - it('fences a response after its route activation is replaced', async () => { const oldResponse = Promise.withResolvers() const applied: string[] = [] diff --git a/mobile/tsconfig.test.json b/mobile/tsconfig.test.json index 2ccc0961a28..95df069b933 100644 --- a/mobile/tsconfig.test.json +++ b/mobile/tsconfig.test.json @@ -8,7 +8,6 @@ // Outside this RN program: RN's numeric timers and Expo's process.env break the desktop graphs these // tests import. The roots of tsconfig.test.node.json are checked there against emitted // declarations; the others are legacy runtime-only coverage whose test bodies nothing typechecks. - "src/components/WorktreeAgentList.runtime-lineage.test.tsx", "src/transport/mobile-relay-browser-cancel-budget.test.ts" ] } diff --git a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AuthenticatedConnectionHangupMonitorTests.swift b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AuthenticatedConnectionHangupMonitorTests.swift index b9987fb3521..e848fe93135 100644 --- a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AuthenticatedConnectionHangupMonitorTests.swift +++ b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AuthenticatedConnectionHangupMonitorTests.swift @@ -5,21 +5,6 @@ import XCTest final class AuthenticatedConnectionHangupMonitorTests: XCTestCase { - func testRegistrationFailureClosesEventQueueOnce() { - let closes = DescriptorCloseRecorder() - - XCTAssertThrowsError( - try AuthenticatedConnectionHangupMonitor( - fileDescriptor: 42, - registerEvents: { _, _, _ in .EBADF }, - closeDescriptor: { descriptor in - closes.recordAndClose(descriptor) - }, - onHangup: {} - ) - ) - XCTAssertEqual(closes.count, 1) - } func testReportsPeerCloseWhileRequestHandlingIsBlocked() throws { let descriptors = try makeSocketPair() @@ -52,54 +37,7 @@ final class AuthenticatedConnectionHangupMonitorTests: XCTestCase { close(descriptors.local) } - func testReadableDataDoesNotLookLikeHangup() throws { - let descriptors = try makeSocketPair() - let hangup = expectation(description: "peer hangup") - let callbacks = CallbackRecorder() - let events = CallbackRecorder() - let monitor = try AuthenticatedConnectionHangupMonitor( - fileDescriptor: descriptors.local, - onEvent: { - events.record() - }, - onHangup: { - callbacks.record() - hangup.fulfill() - } - ) - monitor.start() - var byte: UInt8 = 7 - XCTAssertEqual(write(descriptors.peer, &byte, 1), 1) - usleep(50_000) - XCTAssertEqual(callbacks.count, 0) - XCTAssertEqual(events.count, 0) - close(descriptors.peer) - wait(for: [hangup], timeout: 1) - XCTAssertEqual(events.count, 1) - - monitor.cancel() - close(descriptors.local) - } - - func testCancelPreventsLaterHangupCallback() throws { - let descriptors = try makeSocketPair() - let hangup = expectation(description: "peer hangup") - hangup.isInverted = true - let monitor = try AuthenticatedConnectionHangupMonitor( - fileDescriptor: descriptors.local, - onHangup: { - hangup.fulfill() - } - ) - monitor.start() - - monitor.cancel() - close(descriptors.peer) - - wait(for: [hangup], timeout: 0.1) - close(descriptors.local) - } func testStartReportsHangupQueuedAfterSuccessfulSetup() throws { let descriptors = try makeSocketPair() @@ -120,43 +58,7 @@ final class AuthenticatedConnectionHangupMonitorTests: XCTestCase { } } -private final class CallbackRecorder: @unchecked Sendable { - private let lock = NSLock() - private var recordedCount = 0 - var count: Int { - lock.lock() - defer { lock.unlock() } - return recordedCount - } - - func record() { - lock.lock() - recordedCount += 1 - lock.unlock() - } -} - -private final class DescriptorCloseRecorder: @unchecked Sendable { - private let lock = NSLock() - private var closeCount = 0 - - var count: Int { - lock.lock() - defer { lock.unlock() } - return closeCount - } - - func recordAndClose(_ descriptor: Int32) { - lock.lock() - closeCount += 1 - let shouldClose = closeCount == 1 - lock.unlock() - if shouldClose { - close(descriptor) - } - } -} private func makeSocketPair() throws -> (local: Int32, peer: Int32) { var descriptors: [Int32] = [0, 0] diff --git a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/SyntheticMouseClickDeliveryTests.swift b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/SyntheticMouseClickDeliveryTests.swift deleted file mode 100644 index 4a512b7bd58..00000000000 --- a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/SyntheticMouseClickDeliveryTests.swift +++ /dev/null @@ -1,231 +0,0 @@ -import XCTest -@testable import OrcaComputerUseMacOSCore - -final class SyntheticMouseClickDeliveryTests: XCTestCase { - func testScrollAndDragFenceTheOriginBeforeMoveAndBeforeMutation() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - let sibling = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 202) - for drag in [false, true] { - for loss in [SyntheticMouseClickDelivery.RecipientObservation.focused(sibling), .unavailable, .dismissed] { - for afterMove in [false, true] { - var observations: [SyntheticMouseClickDelivery.RecipientObservation] = afterMove ? [.focused(target), loss] : [loss] - var posted: [String] = [] - let observe = { observations.isEmpty ? .unavailable : observations.removeFirst() } - XCTAssertThrowsError(try { - if drag { - try SyntheticMouseClickDelivery.deliverDrag( - move: "move", down: "down", dragged: ["drag"], up: "up", - target: target, currentObservation: observe, - post: { posted.append($0) }, pause: { _ in } - ) - } else { - try SyntheticMouseClickDelivery.deliverScroll( - move: "move", wheel: "wheel", - target: target, currentObservation: observe, - post: { posted.append($0) }, pause: { _ in } - ) - } - }()) - XCTAssertEqual(posted, afterMove ? ["move"] : []) - } - } - } - } - - func testRecipientChangeBeforeMouseDownPostsNoClickAndReportsBothWindows() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - let intruder = SyntheticMouseClickDelivery.Recipient(ownerPID: 52, windowID: 202) - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError( - try SyntheticMouseClickDelivery.deliver( - clickCount: 1, - target: target, - currentObservation: { .focused(intruder) }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - ) { error in - XCTAssertEqual( - error as? SyntheticMouseClickDelivery.FenceFailure, - .recipientChanged(expected: target, actual: intruder, deliveredPresses: 0) - ) - } - XCTAssertEqual(posted, [.move]) - } - - func testFinalMouseUpMayDismissTheTargetWithoutFailingTheClick() throws { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - var observations: [SyntheticMouseClickDelivery.RecipientObservation] = [.focused(target), .dismissed] - var posted: [SyntheticMouseClickDelivery.Step] = [] - - try SyntheticMouseClickDelivery.deliver( - clickCount: 1, - target: target, - currentObservation: { observations.removeFirst() }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - - XCTAssertEqual(posted, [.move, .buttonDown(pressIndex: 1), .buttonUp(pressIndex: 1)]) - } - - func testFinalUnavailableObservationRemainsFailClosed() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - var observations: [SyntheticMouseClickDelivery.RecipientObservation] = [.focused(target), .unavailable] - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError( - try SyntheticMouseClickDelivery.deliver( - clickCount: 1, - target: target, - currentObservation: { observations.removeFirst() }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - ) { error in - XCTAssertEqual( - error as? SyntheticMouseClickDelivery.FenceFailure, - .recipientChanged(expected: target, actual: nil, deliveredPresses: 1) - ) - } - XCTAssertEqual(posted, [.move, .buttonDown(pressIndex: 1), .buttonUp(pressIndex: 1)]) - } - - func testFinalMouseUpRejectsADifferentFocusedRecipient() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - let intruder = SyntheticMouseClickDelivery.Recipient(ownerPID: 52, windowID: 202) - var recipients: [SyntheticMouseClickDelivery.Recipient?] = [target, intruder] - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError( - try SyntheticMouseClickDelivery.deliver( - clickCount: 1, - target: target, - currentObservation: { - recipients.removeFirst().map(SyntheticMouseClickDelivery.RecipientObservation.focused) ?? .dismissed - }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - ) { error in - XCTAssertEqual( - error as? SyntheticMouseClickDelivery.FenceFailure, - .recipientChanged(expected: target, actual: intruder, deliveredPresses: 1) - ) - } - XCTAssertEqual(posted, [.move, .buttonDown(pressIndex: 1), .buttonUp(pressIndex: 1)]) - } - - func testRecipientChangeBeforeLaterPressReportsCompletedPresses() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - let intruder = SyntheticMouseClickDelivery.Recipient(ownerPID: 52, windowID: 202) - var recipients = [target, target, intruder] - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError( - try SyntheticMouseClickDelivery.deliver( - clickCount: 2, - target: target, - currentObservation: { - .focused(recipients.removeFirst()) - }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - ) { error in - XCTAssertEqual( - error as? SyntheticMouseClickDelivery.FenceFailure, - .recipientChanged(expected: target, actual: intruder, deliveredPresses: 1) - ) - } - XCTAssertEqual(posted, [ - .move, - .buttonDown(pressIndex: 1), - .buttonUp(pressIndex: 1), - ]) - } - - func testRecipientChangeAfterIntermediateMouseUpStopsBeforeNextPress() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - let intruder = SyntheticMouseClickDelivery.Recipient(ownerPID: 52, windowID: 202) - var recipients: [SyntheticMouseClickDelivery.Recipient?] = [target, intruder] - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError( - try SyntheticMouseClickDelivery.deliver( - clickCount: 2, - target: target, - currentObservation: { - recipients.removeFirst().map(SyntheticMouseClickDelivery.RecipientObservation.focused) ?? .dismissed - }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - ) { error in - XCTAssertEqual( - error as? SyntheticMouseClickDelivery.FenceFailure, - .recipientChanged(expected: target, actual: intruder, deliveredPresses: 1) - ) - } - XCTAssertEqual(posted, [ - .move, - .buttonDown(pressIndex: 1), - .buttonUp(pressIndex: 1), - ]) - } - - func testIntermediateMouseUpDismissalStopsBeforeNextPress() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - var recipients: [SyntheticMouseClickDelivery.Recipient?] = [target, nil] - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError( - try SyntheticMouseClickDelivery.deliver( - clickCount: 2, - target: target, - currentObservation: { - recipients.removeFirst().map(SyntheticMouseClickDelivery.RecipientObservation.focused) ?? .dismissed - }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - ) { error in - XCTAssertEqual( - error as? SyntheticMouseClickDelivery.FenceFailure, - .recipientChanged(expected: target, actual: nil, deliveredPresses: 1) - ) - } - XCTAssertEqual(posted, [ - .move, - .buttonDown(pressIndex: 1), - .buttonUp(pressIndex: 1), - ]) - } - - func testButtonPairIsPreparedBeforeMouseDownPosts() { - enum PreparationFailure: Error { case mouseUp } - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError(try SyntheticMouseClickDelivery.deliver( - clickCount: 1, - target: target, - currentObservation: { .focused(target) }, - makeEvent: { step in - if case .buttonUp = step { throw PreparationFailure.mouseUp } - return step - }, - post: { posted.append($0) }, - pause: { _ in } - )) - XCTAssertEqual(posted, [.move]) - } -} diff --git a/src/main/browser/sessions/partition-policies/browser-session-partition-proxy-install.test.ts b/src/main/browser/sessions/partition-policies/browser-session-partition-proxy-install.test.ts index 58e39a1df16..edccd0a8004 100644 --- a/src/main/browser/sessions/partition-policies/browser-session-partition-proxy-install.test.ts +++ b/src/main/browser/sessions/partition-policies/browser-session-partition-proxy-install.test.ts @@ -106,6 +106,7 @@ describe('installBrowserSessionPartitionPolicies proxy wiring', () => { }) afterEach(() => { + setBrowserNetworkProxySettingsResolver(null) vi.unstubAllEnvs() identityState.unavailable = false }) diff --git a/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.test.ts b/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.test.ts deleted file mode 100644 index a8eb0930cac..00000000000 --- a/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { - AgentJournalRenderItem, - AgentJournalSubmission -} from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import { agentJournalSubmissionKey } from '../../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { StructuredAgentSessionOptimisticMessage } from '../../../../../../shared/agent-session/view/structured-agent-session-message-projection' -import { structuredAgentSessionSendBody } from '../../../../../../shared/agent-session/requests/structured-agent-session-send-mutation' -import { projectStructuredAgentSessionMessages } from './structured-agent-session-message-projection' - -function optimisticMessage(args: { - clientMessageId: string - sessionId?: string - text: string - attachments: readonly { path: string; previewUri: string }[] - queuedAt: number -}): StructuredAgentSessionOptimisticMessage { - return { - clientMessageId: args.clientMessageId, - body: structuredAgentSessionSendBody(args.text, args.attachments), - queuedAt: args.queuedAt - } -} - -function submission(index: number): AgentJournalSubmission { - return { - clientMessageId: `client-${index}`, - fence: 1, - payloadFingerprint: `fingerprint-${index}`, - dispatchState: 'accepted', - providerItemId: `provider-${index}`, - reason: null, - submittedAt: index, - resolvedAt: index - } -} - -function item(index: number): AgentJournalRenderItem { - return { - itemId: `journal-${index}`, - revision: 1, - sequence: index, - observedAt: index, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: `send ${index}` }] } - } -} - -describe('structured agent session message projection', () => { - it("draws a send the host rejected from the host's row, not the outbox copy", () => { - const rejected = { ...submission(0), dispatchState: 'rejected' as const, providerItemId: null } - const refusedItem = { ...item(0), itemId: agentJournalSubmissionKey(rejected.clientMessageId) } - const draft = optimisticMessage({ - clientMessageId: rejected.clientMessageId, - sessionId: 'session-1', - text: 'An unsent draft', - attachments: [], - queuedAt: 1 - }) - expect(projectStructuredAgentSessionMessages([refusedItem], [draft], [rejected])).toEqual([ - expect.objectContaining({ - id: refusedItem.itemId, - blocks: [{ type: 'text', text: 'send 0' }], - unsent: true - }) - ]) - }) - - it.each([5, 10])('renders %i rapid accepted desktop sends exactly once', (sendCount) => { - const outbox = Array.from({ length: sendCount }, (_, index) => - optimisticMessage({ - clientMessageId: `client-${index}`, - sessionId: 'session-1', - text: `send ${index}`, - attachments: [], - queuedAt: index - }) - ) - const messages = projectStructuredAgentSessionMessages( - Array.from({ length: sendCount }, (_, index) => item(index)), - outbox, - Array.from({ length: sendCount }, (_, index) => submission(sendCount - index - 1)) - ) - - expect(messages.filter((message) => message.role === 'user')).toHaveLength(sendCount) - expect(messages.map((message) => message.id)).toEqual( - Array.from({ length: sendCount }, (_, index) => `journal-${index}`) - ) - }) - - it('renders one bubble while the submission is still dispatching', () => { - const outbox = [ - optimisticMessage({ - clientMessageId: 'client-pending', - sessionId: 'session-1', - text: 'Ok thanks', - attachments: [], - queuedAt: 1 - }) - ] - // The host's WAL row is on screen while the provider round trip is in flight. - const walItem: AgentJournalRenderItem = { - itemId: agentJournalSubmissionKey('client-pending'), - revision: 0, - sequence: 1, - observedAt: 1, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Ok thanks' }] } - } - const pending: AgentJournalSubmission = { - ...submission(0), - clientMessageId: 'client-pending', - dispatchState: 'pending', - providerItemId: null, - resolvedAt: null - } - - const messages = projectStructuredAgentSessionMessages([walItem], outbox, [pending]) - const optimistic = projectStructuredAgentSessionMessages([], outbox, []) - - expect(messages.filter((message) => message.role === 'user')).toHaveLength(1) - expect(messages.map((message) => message.id)).toEqual([walItem.itemId]) - expect(optimistic[0]?.id).toBe(messages[0]?.id) - }) -}) diff --git a/src/renderer/src/components/native-chat/pane/routing/native-chat-open-wake.test.ts b/src/renderer/src/components/native-chat/pane/routing/native-chat-open-wake.test.ts deleted file mode 100644 index fddfb09510a..00000000000 --- a/src/renderer/src/components/native-chat/pane/routing/native-chat-open-wake.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import type { AppState } from '@/store/types' -import { - noteUserWorkspaceSwitch, - resetWorkspaceSwitchUserActsForTests -} from '@/lib/workspace-switch-user-act' -import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' -import { takeNativeChatOpenWake } from './native-chat-open-wake' - -const LEAF = '11111111-1111-4111-8111-111111111111' - -function tabs(entries: Record): AppState['tabsByWorktree'] { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the wake only reads each tab's id. - return Object.fromEntries( - Object.entries(entries).map(([worktreeId, ids]) => [worktreeId, ids.map((id) => ({ id }))]) - ) as unknown as AppState['tabsByWorktree'] -} - -describe('takeNativeChatOpenWake (E9)', () => { - beforeEach(() => resetWorkspaceSwitchUserActsForTests()) - - it('a chat in another workspace mounting inside the switch window neither wakes nor spends the switch', () => { - const byWorktree = tabs({ 'wt-a': ['tab-a'], 'wt-b': ['tab-b'] }) - noteUserWorkspaceSwitch('wt-a') - expect(takeNativeChatOpenWake(makePaneKey('tab-b', LEAF), 'chat-b', byWorktree)).toBe(false) - expect(takeNativeChatOpenWake(makePaneKey('tab-a', LEAF), 'chat-a', byWorktree)).toBe(true) - // Once per switch: a remount of the same chat does not wake again. - expect(takeNativeChatOpenWake(makePaneKey('tab-a', LEAF), 'chat-a', byWorktree)).toBe(false) - }) - - it('a chat whose tab belongs to no workspace never wakes', () => { - noteUserWorkspaceSwitch('wt-a') - expect(takeNativeChatOpenWake(makePaneKey('tab-x', LEAF), 'chat-x', tabs({}))).toBe(false) - expect(takeNativeChatOpenWake('not-a-pane-key', 'chat-x', tabs({ 'wt-a': ['tab-a'] }))).toBe( - false - ) - }) -}) diff --git a/src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.test.ts b/src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.test.ts deleted file mode 100644 index 47bc27dad82..00000000000 --- a/src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { - buildLinearIssueWorkspaceAttachmentIndex, - findLinearIssueWorkspaceAttachmentInIndex -} from './linear-issue-workspace-attachment' -import type { Worktree } from '../../../../../shared/worktree/types' - -function worktree(overrides: Partial = {}): Worktree { - return { - id: overrides.id ?? 'wt-1', - repoId: overrides.repoId ?? 'repo-1', - path: overrides.path ?? '/tmp/repo-1/wt-1', - head: 'abc123', - branch: overrides.branch ?? 'refs/heads/feature/linear-attachment', - isBare: false, - isMainWorktree: false, - displayName: overrides.displayName ?? 'Linear workspace', - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: overrides.linkedLinearIssue ?? null, - linkedLinearIssueWorkspaceId: overrides.linkedLinearIssueWorkspaceId, - linkedLinearIssueOrganizationUrlKey: overrides.linkedLinearIssueOrganizationUrlKey, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - ...overrides - } -} - -describe('multiple Linear attachments', () => { - it('indexes secondary identifiers and keeps organization scope', () => { - const attached = worktree({ - linkedLinearIssue: 'STA-1', - linkedItems: [ - { - provider: 'linear', - type: 'issue', - number: 0, - identifier: 'STA-2', - linearOrganizationUrlKey: 'acme' - } - ] - }) - const index = buildLinearIssueWorkspaceAttachmentIndex([attached]) - expect( - findLinearIssueWorkspaceAttachmentInIndex(index, { - identifier: 'STA-2', - url: 'https://linear.app/acme/issue/STA-2' - }) - ).toBe(attached) - expect( - findLinearIssueWorkspaceAttachmentInIndex(index, { - identifier: 'STA-2', - url: 'https://linear.app/other/issue/STA-2' - }) - ).toBeNull() - }) -}) diff --git a/src/renderer/src/lib/workspace/creation/worktree-creation-initial-surface.test.ts b/src/renderer/src/lib/workspace/creation/worktree-creation-initial-surface.test.ts deleted file mode 100644 index 102ba54b5b9..00000000000 --- a/src/renderer/src/lib/workspace/creation/worktree-creation-initial-surface.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { useAppStore } from '@/store/index' -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import type { PendingWorktreeCreation } from './pending-worktree-creation' -import { activateAndRevealWorktree } from '../activation/worktree-activation' -import '../activation/initial-surface/worktree-initial-terminal-seeding' -import { registerWorktreeActivationReset } from '../activation/worktree-activation.test-fixture' - -registerWorktreeActivationReset() - -function creatingEntry(): PendingWorktreeCreation { - return { - creationId: 'creation-1', - worktreeId: 'wt-1', - phase: 'creating', - status: 'creating', - startedAt: 1, - indeterminate: false, - loaderVisible: true, - request: { - repoId: 'repo-1', - name: 'workspace', - setupDecision: 'inherit', - agent: 'codex', - pendingFirstAgentMessageRename: false, - note: '', - startupPlan: null, - quickPrompt: '', - quickTelemetry: null - } - } -} - -describe('initial surface during worktree creation', () => { - it('shows the creation panel instead of an empty workspace when the row is opened early', () => { - useAppStore.setState({ - activeView: 'tasks', - activePendingCreationId: null, - worktreesByRepo: { 'repo-1': [makeWorktree({ id: 'wt-1', repoId: 'repo-1' })] }, - pendingWorktreeCreations: { 'creation-1': { ...creatingEntry(), loaderVisible: false } } - }) - - expect(activateAndRevealWorktree('wt-1')).toEqual({ primaryTabId: null }) - - const state = useAppStore.getState() - expect(state.activePendingCreationId).toBe('creation-1') - expect(state.activeView).toBe('terminal') - expect(state.activeWorktreeId).not.toBe('wt-1') - expect(state.pendingWorktreeCreations['creation-1']?.loaderVisible).toBe(true) - }) -}) diff --git a/src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts b/src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts deleted file mode 100644 index 538fd81a1e6..00000000000 --- a/src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, it } from 'vitest' -import '../../../../../shared/constants' -import { runtimeEnvironmentIdOrLocalUnlessTwin } from './worktree-runtime-owner' -import '../../terminal-worktree-route' -import '../../runtime-session-mirror-owners' -import type { WorktreeRuntimeOwnerState } from './worktree-runtime-owner-state' - -/** The owner's paired server, as production callers read it; null for this app or a twin. */ - -describe('runtime owner identity indexes', () => { - it('rebuilds owner indexes when immutable collection references change', () => { - const first: WorktreeRuntimeOwnerState = { - repos: [{ id: 'repo', connectionId: null, executionHostId: 'runtime:repo-one' }], - worktreesByRepo: { repo: [{ id: 'worktree', repoId: 'repo' }] }, - folderWorkspaces: [{ id: 'folder', projectGroupId: 'group' }], - projectGroups: [{ id: 'group', connectionId: null, executionHostId: 'runtime:folder-one' }] - } - expect(runtimeEnvironmentIdOrLocalUnlessTwin(first, 'worktree')).toBe('repo-one') - expect(runtimeEnvironmentIdOrLocalUnlessTwin(first, 'folder:folder')).toBe('folder-one') - - const second: WorktreeRuntimeOwnerState = { - repos: [{ id: 'repo', connectionId: null, executionHostId: 'runtime:repo-two' }], - worktreesByRepo: { - repo: [{ id: 'worktree', repoId: 'repo', hostId: 'runtime:worktree-two' }] - }, - folderWorkspaces: [{ id: 'folder', projectGroupId: 'group' }], - projectGroups: [{ id: 'group', connectionId: null, executionHostId: 'runtime:folder-two' }] - } - expect(runtimeEnvironmentIdOrLocalUnlessTwin(second, 'worktree')).toBe('worktree-two') - expect(runtimeEnvironmentIdOrLocalUnlessTwin(second, 'folder:folder')).toBe('folder-two') - }) -}) diff --git a/src/renderer/src/runtime/files/reads/runtime-directory-page-client.test.ts b/src/renderer/src/runtime/files/reads/runtime-directory-page-client.test.ts deleted file mode 100644 index b62aa57a043..00000000000 --- a/src/renderer/src/runtime/files/reads/runtime-directory-page-client.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { FILE_READ_DIR_PAGED_RUNTIME_CAPABILITY } from '../../../../../shared/file-access/files-runtime-capabilities' - -const callRuntimeRpc = vi.fn() -const readRuntimeDirectory = vi.fn() -let statuses = new Map() - -vi.mock('../../rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: (...args: unknown[]) => callRuntimeRpc(...args) -})) -vi.mock('./runtime-directory-read', () => ({ - readRuntimeDirectory: (...args: unknown[]) => readRuntimeDirectory(...args) -})) -vi.mock('@/store/index', () => ({ - useAppStore: { getState: () => ({ runtimeStatusByEnvironmentId: statuses }) } -})) - -import { readRuntimeDirectoryPage } from './runtime-directory-page-client' - -const REMOTE = { - target: { kind: 'environment' as const, environmentId: 'env-1' }, - worktreeId: 'wt-1', - worktreePath: '/srv/repo' -} -const entry = (name: string) => ({ name, isDirectory: false, isSymlink: false }) -const AFTER_A = { name: 'a', isDirectory: false } - -function hostWithCapabilities(capabilities: string[]): void { - statuses = new Map([['env-1', { status: { capabilities } }]]) -} - -describe('readRuntimeDirectoryPage', () => { - beforeEach(() => { - callRuntimeRpc.mockReset() - readRuntimeDirectory.mockReset() - statuses = new Map() - }) - - it('takes the whole folder from a host that ignored the page fields', async () => { - hostWithCapabilities([FILE_READ_DIR_PAGED_RUNTIME_CAPABILITY]) - callRuntimeRpc.mockResolvedValueOnce([entry('c'), entry('a'), entry('b')]) - - await expect( - readRuntimeDirectoryPage(REMOTE, '/srv/repo/big', { after: AFTER_A, limit: 1 }) - ).resolves.toEqual({ entries: [entry('b'), entry('c')], total: 3, hasMore: false }) - }) -}) diff --git a/src/renderer/src/runtime/files/reads/runtime-file-client.test.ts b/src/renderer/src/runtime/files/reads/runtime-file-client.test.ts deleted file mode 100644 index b643f9d39ac..00000000000 --- a/src/renderer/src/runtime/files/reads/runtime-file-client.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readRuntimeFileContent } from './runtime-file-read-client' -import { - fsReadFile, - runtimeEnvironmentCall, - installRuntimeFileClientEnvironment -} from '../runtime-file-client-test-harness' - -installRuntimeFileClientEnvironment() - -describe('runtime file client', () => { - it('classifies an unlisted binary an older host sent as text', async () => { - runtimeEnvironmentCall.mockImplementation((args: { method: string }) => - Promise.resolve( - args.method === 'files.read' - ? { - id: 'rpc-read', - ok: true, - result: { content: '\u007fELF\u0002\u0000\u0001', truncated: true, byteLength: 7 }, - _meta: { runtimeId: 'remote-runtime' } - } - : { id: 'rpc-other', ok: false, error: { code: 'runtime_error', message: 'unexpected' } } - ) - ) - - await expect( - readRuntimeFileContent({ - target: { kind: 'environment' as const, environmentId: 'env-1' }, - filePath: '/remote/repo/libfoo.so', - relativePath: 'libfoo.so', - worktreeId: 'wt-1' - }) - ).resolves.toEqual({ content: '', isBinary: true }) - }) - - describe('remote audio and video', () => { - it('opens an SVG as editable markup even when a viewer asks for a URL', async () => { - const markup = 'café' - fsReadFile.mockResolvedValue({ - content: Buffer.from(markup).toString('base64'), - isBinary: true, - isImage: true, - mimeType: 'image/svg+xml' - }) - await expect( - readRuntimeFileContent({ - target: { kind: 'local' as const }, - filePath: '/repo/logo.svg', - relativePath: 'logo.svg', - worktreeId: 'wt-1', - pageOversizedBinary: true - }) - ).resolves.toEqual({ content: markup, isBinary: false }) - }) - }) -}) diff --git a/src/renderer/src/runtime/jira/runtime-jira-payload-stream.test.ts b/src/renderer/src/runtime/jira/runtime-jira-payload-stream.test.ts deleted file mode 100644 index 727eb9267d2..00000000000 --- a/src/renderer/src/runtime/jira/runtime-jira-payload-stream.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { readRuntimeJiraPayload } from './runtime-jira-payload-stream' -import { stubRuntimeEnvironmentBridge } from '../rpc/testing/runtime-environment-bridge-fixture' - -type RuntimeEnvironmentSubscribeCallbacks = Parameters< - typeof window.api.runtimeEnvironments.subscribe ->[1] - -afterEach(() => { - vi.unstubAllGlobals() -}) - -describe('readRuntimeJiraPayload', () => { - it('reassembles JSON chunks when the stream ends', async () => { - const unsubscribe = vi.fn() - const subscribe = vi.fn( - async (_args: unknown, callbacks: RuntimeEnvironmentSubscribeCallbacks) => { - callbacks.onResponse({ - id: 'rpc-1', - ok: true, - result: { type: 'chunk', content: '{"key":' }, - _meta: { runtimeId: 'runtime-1' } - }) - callbacks.onResponse({ - id: 'rpc-1', - ok: true, - result: { type: 'chunk', content: '"ABC-3"}' }, - _meta: { runtimeId: 'runtime-1' } - }) - callbacks.onResponse({ - id: 'rpc-1', - ok: true, - result: { type: 'end' }, - _meta: { runtimeId: 'runtime-1' } - }) - return { unsubscribe, sendBinary: vi.fn() } - } - ) - stubRuntimeEnvironmentBridge({ subscribe }) - - await expect( - readRuntimeJiraPayload<{ key: string }>( - { kind: 'environment', environmentId: 'env-1' }, - 'jira.getIssueStream', - { key: 'ABC-3' } - ) - ).resolves.toEqual({ key: 'ABC-3' }) - }) -}) diff --git a/src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts b/src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts deleted file mode 100644 index 79b44d90382..00000000000 --- a/src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import { create } from 'zustand' -import './react-commit-cascade-write-probe' -import { - armStoreIdentityChurnProbe, - disarmStoreIdentityChurnProbe, - readStoreIdentityChurnReport, - withStoreIdentityChurnProbe -} from './store-identity-churn-probe' - -type ProbeState = { - rows: { id: string; label: string }[] - entries: Record - counter: number - refresh: (rows: { id: string; label: string }[]) => void - touch: (id: string, status: string) => void - bump: () => void -} - -function createProbeStore() { - return create()( - withStoreIdentityChurnProbe((set) => ({ - rows: [{ id: 'a', label: 'A' }], - entries: { a: { status: 'idle' } }, - counter: 0, - refresh: (rows) => set({ rows }), - touch: (id, status) => set((state) => ({ entries: { ...state.entries, [id]: { status } } })), - bump: () => set((state) => ({ counter: state.counter + 1 })) - })) - ) -} - -function churnFor(field: string): number { - return readStoreIdentityChurnReport().find((row) => row.field === field)?.churnedWrites ?? 0 -} - -describe('store identity churn probe', () => { - beforeEach(() => { - // Arming resets the counters; disarming immediately leaves a clean, off probe. - armStoreIdentityChurnProbe() - disarmStoreIdentityChurnProbe() - }) - - it('leaves a functional updater to zustand: called once, with the live state', () => { - const store = createProbeStore() - const seen: unknown[] = [] - armStoreIdentityChurnProbe() - - store.setState((state) => { - seen.push(state) - return { counter: state.counter + 1 } - }) - store.setState((state) => { - seen.push(state) - return { rows: [{ ...state.rows[0] }] } - }) - - expect(seen).toHaveLength(2) - expect(seen[1]).toMatchObject({ counter: 1 }) - expect(store.getState().counter).toBe(1) - expect(churnFor('rows')).toBe(1) - }) -}) diff --git a/src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-browse.test.ts b/src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-browse.test.ts deleted file mode 100644 index f6fa66856c6..00000000000 --- a/src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-browse.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { create } from 'zustand' -import type { AppState } from '../../types' -import { - createWorkspaceCleanupBrowseSlice, - resetWorkspaceCleanupBrowsePersistTimer, - WORKSPACE_CLEANUP_BROWSE_PERSIST_DEBOUNCE_MS -} from './workspace-cleanup-browse' -import { createDefaultWorkspaceCleanupBrowseState } from '../../../../../shared/workspace-cleanup/workspace-cleanup-browse-state' - -const DISMISSAL = { - worktreeId: 'wt-1', - dismissedAt: 1700000000000, - fingerprint: 'fp-1', - classifierVersion: 2 -} - -function createStore(uiSet: ReturnType) { - ;(globalThis as { window: unknown }).window = { api: { ui: { set: uiSet } } } - return create()( - (...a) => - ({ - workspaceCleanupDismissals: { 'wt-1': DISMISSAL }, - ...createWorkspaceCleanupBrowseSlice(...a) - }) as unknown as AppState - ) -} - -describe('workspace cleanup browse slice', () => { - beforeEach(() => { - vi.useFakeTimers() - }) - - afterEach(() => { - resetWorkspaceCleanupBrowsePersistTimer() - vi.useRealTimers() - }) - - it('coalesces a burst of edits into one write carrying the newest state', async () => { - const uiSet = vi.fn().mockResolvedValue(undefined) - const store = createStore(uiSet) - - for (const query of ['s', 'st', 'sta']) { - const next = createDefaultWorkspaceCleanupBrowseState() - next.filters.query = query - store.getState().updateWorkspaceCleanupBrowseState(next) - await vi.advanceTimersByTimeAsync(WORKSPACE_CLEANUP_BROWSE_PERSIST_DEBOUNCE_MS - 1) - } - await vi.advanceTimersByTimeAsync(WORKSPACE_CLEANUP_BROWSE_PERSIST_DEBOUNCE_MS) - - expect(uiSet).toHaveBeenCalledTimes(1) - expect(uiSet.mock.calls[0][0].workspaceCleanup.browse.filters.query).toBe('sta') - }) -}) diff --git a/src/renderer/src/store/slices/worktrees/metadata/worktrees-git-identity-branch-title.test.ts b/src/renderer/src/store/slices/worktrees/metadata/worktrees-git-identity-branch-title.test.ts deleted file mode 100644 index b4abc27e162..00000000000 --- a/src/renderer/src/store/slices/worktrees/metadata/worktrees-git-identity-branch-title.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { AppState } from '../../../types' -import { resetHostedReviewLinkMutationGenerationForTests } from './hosted-review-link-mutation' -import { makeWorktree } from '../worktree.test-fixture' -import { - createTestStore, - resetRemoteRuntimeMocks, - resetWorktreeSliceModuleMemory -} from '../worktrees-slice-test-harness' - -const requestWorktreeBaseFallbackNotice = vi.hoisted(() => vi.fn()) - -vi.mock('sonner', () => ({ - toast: { - warning: vi.fn(), - info: vi.fn(), - success: vi.fn(), - error: vi.fn(), - dismiss: vi.fn() - } -})) - -vi.mock('@/components/worktree-base-fallback-notice', () => ({ - requestWorktreeBaseFallbackNotice -})) - -beforeEach(resetWorktreeSliceModuleMemory) - -describe('updateWorktreeGitIdentity', () => { - beforeEach(() => { - vi.clearAllMocks() - resetRemoteRuntimeMocks() - resetHostedReviewLinkMutationGenerationForTests() - }) - - it('resumes following branch names after an auto-derived title crosses detached HEAD', () => { - const store = createTestStore() - const existing = makeWorktree({ - id: 'repo1::/path/wt1', - repoId: 'repo1', - path: '/path/wt1', - head: 'old-head', - branch: 'refs/heads/review-branch', - displayName: 'review-branch' - }) - - store.setState({ worktreesByRepo: { repo1: [existing] } } as Partial) - - store.getState().updateWorktreeGitIdentity( - 'repo1::/path/wt1', - { - head: 'detached-head', - branch: null - }, - null - ) - store.getState().updateWorktreeGitIdentity( - 'repo1::/path/wt1', - { - head: 'reattached-head', - branch: 'refs/heads/main' - }, - null - ) - - expect(store.getState().worktreesByRepo.repo1[0]).toMatchObject({ - branch: 'refs/heads/main', - displayName: 'main' - }) - }) -}) diff --git a/src/shared/work-items/task-source-context.test.ts b/src/shared/work-items/task-source-context.test.ts index 0644630b24f..1780a8f1b96 100644 --- a/src/shared/work-items/task-source-context.test.ts +++ b/src/shared/work-items/task-source-context.test.ts @@ -1,49 +1,6 @@ import { describe, expect, it } from 'vitest' -import { - areTaskSourceContextsEqual, - normalizeStoredTaskSourceContext, - normalizeTaskSourceContext, - type TaskSourceContext -} from './task-source-context' -import { TaskSourceContextSchema } from './task-source-context-schema' - -describe('task source context', () => { - it('drops provider identities that do not match the source provider', () => { - expect( - normalizeTaskSourceContext({ - provider: 'gitlab', - projectId: 'project-1', - providerIdentity: { provider: 'github', owner: 'stablyai', repo: 'orca' } - })?.providerIdentity - ).toBeNull() - }) - - it('rejects malformed stored scalar and provider-identity fields without throwing', () => { - const valid = { - kind: 'task-source', - provider: 'jira', - projectId: 'project-1', - hostId: 'local', - providerIdentity: { - provider: 'jira', - siteId: 'site-1', - siteUrl: 'https://example.atlassian.net', - projectKey: 'OPS' - } - } - for (const malformed of [ - { ...valid, accountLabel: 44 }, - { ...valid, hostId: { runtime: 'env-1' } }, - { ...valid, providerIdentity: { ...valid.providerIdentity, siteId: 44 } }, - { ...valid, providerIdentity: { ...valid.providerIdentity, projectKey: [] } } - ]) { - expect(() => TaskSourceContextSchema.safeParse(malformed)).not.toThrow() - expect(TaskSourceContextSchema.safeParse(malformed).success).toBe(false) - expect(normalizeStoredTaskSourceContext(malformed)).toBeNull() - } - }) -}) +import { areTaskSourceContextsEqual, type TaskSourceContext } from './task-source-context' describe('areTaskSourceContextsEqual', () => { const base: TaskSourceContext = { diff --git a/src/shared/workspace-layout/workspace-layout-resume-record.test.ts b/src/shared/workspace-layout/workspace-layout-resume-record.test.ts index ee6a3c547d9..3ea38f5098f 100644 --- a/src/shared/workspace-layout/workspace-layout-resume-record.test.ts +++ b/src/shared/workspace-layout/workspace-layout-resume-record.test.ts @@ -15,7 +15,6 @@ import { GIT_KEY, leaf } from './workspace-layout-session.test-fixture' import type { WorkspaceSessionState } from '../workspace-session/workspace-session-state-types' type Origin = SleepingAgentSessionRecord['origin'] -const ORIGINS: readonly Origin[] = ['live', 'quit', 'worktree-sleep', undefined] function withOrigin(record: SleepingAgentSessionRecord, origin: Origin) { const { origin: _stored, ...rest } = record @@ -42,23 +41,7 @@ function load(session: WorkspaceSessionState): LoadedWorkspaceLayout { const leafOf = (model: WorkspaceLayoutModel, leafId: string): LayoutLeaf | undefined => model.workspaces[GIT_KEY]!.leaves?.[leafId] -const isSleep = (origin: Origin) => origin === undefined || origin === 'worktree-sleep' - describe("a pane's resume record through load and save", () => { - it.each(ORIGINS)('loads a %s record to the one holder its origin names', (origin) => { - const agent = leafOf(load(sessionWith(origin)).layout, leaf(3))! - expect(agent.sleeping !== undefined).toBe(isSleep(origin)) - expect(agent.resume !== undefined).toBe(!isSleep(origin)) - }) - - it.each(ORIGINS)('saves a %s record byte for byte as stored', (origin) => { - const session = sessionWith(origin) - const saved = saveWorkspaceLayout(load(session)) - expect(JSON.stringify(saved.sleepingAgentSessionsByPaneKey)).toBe( - JSON.stringify(session.sleepingAgentSessionsByPaneKey) - ) - }) - it('never publishes either record to a layout frame', () => { const { layout } = load(sessionWith('live')) const frame = JSON.stringify( diff --git a/src/shared/workspace-review-checks.test.ts b/src/shared/workspace-review-checks.test.ts index 60d9df87954..fb721a6543c 100644 --- a/src/shared/workspace-review-checks.test.ts +++ b/src/shared/workspace-review-checks.test.ts @@ -1,10 +1,5 @@ -import { - getProviderChecksOutcome, - summarizeProviderChecks -} from './source-control/checks/provider-check-summary' import { describe, expect, it } from 'vitest' import type { WorkspaceAttachment } from './worktree/types' -import type { HostedReviewState } from './source-control/hosted-review/hosted-review-contracts' import { getWorkspaceAttachmentKey } from './workspace-attachments/workspace-attachment-normalization' import { summarizeWorkspaceReviewChecks, @@ -38,45 +33,6 @@ function map( } describe('all workspace review checks', () => { - it.each<{ states: (HostedReviewState | undefined)[]; expected: HostedReviewState | undefined }>([ - { states: ['merged', 'merged'], expected: 'merged' }, - { states: ['draft', 'draft'], expected: 'draft' }, - { states: ['closed', 'closed'], expected: 'closed' }, - { states: ['merged', 'open'], expected: 'open' }, - { states: ['merged', 'draft'], expected: 'open' }, - { states: ['merged', 'closed'], expected: 'closed' }, - { states: ['merged', undefined], expected: undefined }, - { states: ['draft', undefined], expected: 'open' }, - { states: [undefined, undefined], expected: undefined } - ])( - 'derives collection lifecycle $states independently of passing checks', - ({ states, expected }) => { - const items = states.map((_, index) => - attachment(index + 1, index === 0 ? 'github' : 'gitlab') - ) - const entries: [WorkspaceAttachment, WorkspaceReviewCheckDetails][] = items.map( - (item, index) => [ - item, - { - review: { - provider: item.provider, - number: item.number, - url: item.url, - state: states[index], - status: 'success' - } - } - ] - ) - const summary = summarizeWorkspaceReviewChecks(items, map(entries)) - expect(summary.reviewState).toBe(expected) - expect(summary).toMatchObject({ - state: 'success', - passed: items.length - }) - } - ) - it('retains matched lifecycle and staleness without check results and rejects foreign details', () => { const item = attachment(1) const retained = { @@ -166,44 +122,3 @@ describe('all workspace review checks', () => { expect(summarizeWorkspaceReviewChecks([task], {})).toMatchObject({ state: 'none', total: 0 }) }) }) - -it('counts nested cancelled and pending review outcomes once per review', () => { - const first = attachment(1) - const second = attachment(2) - const summaryFor = (...conclusions: string[]) => - summarizeProviderChecks(conclusions.map((conclusion) => ({ status: 'completed', conclusion }))) - const mixed = { - ...details(first, 'failure'), - review: { - ...details(first, 'failure').review!, - checksSummary: summaryFor('cancelled', 'pending') - } - } - const cancelled = { - ...details(second, 'failure'), - review: { - ...details(second, 'failure').review!, - checksSummary: summaryFor('cancelled', 'cancelled') - } - } - const alone = summarizeWorkspaceReviewChecks([first], map([[first, mixed]])) - expect(alone).toMatchObject({ total: 1, pending: 1, failed: 0, cancelled: 0 }) - expect(getProviderChecksOutcome(alone)).toBe('pending') - const combined = summarizeWorkspaceReviewChecks( - [first, second], - map([ - [first, mixed], - [second, cancelled] - ]) - ) - expect(combined).toMatchObject({ total: 2, failed: 1, cancelled: 1, pending: 1 }) - expect(getProviderChecksOutcome(combined)).toBe('pending') - expect( - getProviderChecksOutcome(summarizeWorkspaceReviewChecks([second], map([[second, cancelled]]))) - ).toBe('cancelled') - expect( - getProviderChecksOutcome( - summarizeWorkspaceReviewChecks([first, second], map([[second, cancelled]])) - ) - ).not.toBe('success') -}) From 0cb357a83c88167cc3e679d03b95b734c63c50bf Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:22:34 -0800 Subject: [PATCH 04/10] feat(setup): slim the setup-script import card and fit long scripts in review (#40180) * feat(setup): slim the setup-script prompt and make long imported scripts collapsible * fix(setup): require the full imported script on screen before saving * style(setup): use the ghost button colour for the script toggle * style(setup): keep the source path readable in the narrow prompt card * feat(setup): title imports, restore the package-manager card, keep the review dialog inside the viewport * fix(setup): count every script line, keep the e2e import spec in step with the new copy --- .../sidebar/SetupScriptCodeBlock.test.tsx | 36 +++++ .../sidebar/SetupScriptCodeBlock.tsx | 98 +++++++++++++ .../sidebar/SetupScriptPromptCard.tsx | 21 +-- .../SetupScriptPromptCardShell.fixture.tsx | 135 ++++++++++++++---- .../sidebar/SetupScriptPromptCardShell.tsx | 21 +-- .../sidebar/SetupScriptPromptCardViews.tsx | 84 ++++------- .../sidebar/SetupScriptReviewDialog.tsx | 98 +++++++------ .../src/i18n/en-runtime-required.json | 14 +- src/renderer/src/i18n/locales/de.json | 9 +- src/renderer/src/i18n/locales/en.json | 23 +-- src/renderer/src/i18n/locales/es.json | 10 +- src/renderer/src/i18n/locales/fr.json | 10 +- src/renderer/src/i18n/locales/ja.json | 9 +- src/renderer/src/i18n/locales/ko.json | 9 +- src/renderer/src/i18n/locales/pt.json | 10 +- src/renderer/src/i18n/locales/ru.json | 11 +- src/renderer/src/i18n/locales/tr.json | 9 +- src/renderer/src/i18n/locales/zh-Hant.json | 9 +- src/renderer/src/i18n/locales/zh.json | 9 +- src/renderer/src/lib/script-textarea-rows.ts | 14 ++ src/renderer/src/lib/setup-script-prompt.ts | 12 +- tests/e2e/setup-script-import.spec.ts | 24 ++-- 22 files changed, 423 insertions(+), 252 deletions(-) create mode 100644 src/renderer/src/components/sidebar/SetupScriptCodeBlock.test.tsx create mode 100644 src/renderer/src/components/sidebar/SetupScriptCodeBlock.tsx diff --git a/src/renderer/src/components/sidebar/SetupScriptCodeBlock.test.tsx b/src/renderer/src/components/sidebar/SetupScriptCodeBlock.test.tsx new file mode 100644 index 00000000000..ade3681d1b0 --- /dev/null +++ b/src/renderer/src/components/sidebar/SetupScriptCodeBlock.test.tsx @@ -0,0 +1,36 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it } from 'vitest' +import { SetupScriptCodeBlock } from './SetupScriptCodeBlock' + +afterEach(cleanup) + +function script(lines: number): string { + return Array.from({ length: lines }, (_, index) => `echo step-${index + 1}`).join('\n') +} + +it('collapses a long script and toggles it open and closed', () => { + render() + const code = screen.getByLabelText('Setup script') + expect(code).toHaveTextContent('echo step-40') + + const toggle = screen.getByRole('button', { name: 'Show 35 more lines' }) + expect(toggle).toHaveAttribute('aria-expanded', 'false') + expect(toggle).toHaveAttribute('aria-controls', code.id) + + fireEvent.click(toggle) + expect(toggle).toHaveAttribute('aria-expanded', 'true') + + code.scrollTop = 200 + fireEvent.click(toggle) + expect(toggle).toHaveAttribute('aria-expanded', 'false') + expect(code.scrollTop).toBe(0) +}) + +it('shows a short script in full with no toggle', () => { + render() + expect(screen.getByLabelText('Setup script')).toHaveTextContent('echo step-5') + expect(screen.queryByRole('button')).toBeNull() +}) diff --git a/src/renderer/src/components/sidebar/SetupScriptCodeBlock.tsx b/src/renderer/src/components/sidebar/SetupScriptCodeBlock.tsx new file mode 100644 index 00000000000..5b56439d5a8 --- /dev/null +++ b/src/renderer/src/components/sidebar/SetupScriptCodeBlock.tsx @@ -0,0 +1,98 @@ +import React, { useId, useMemo, useRef, useState } from 'react' +import { ChevronDown } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { cn } from '@/lib/utils' +import { useTranslate } from '@/i18n/use-translate' +import { countScriptLines } from '@/lib/script-textarea-rows' + +export const SETUP_SCRIPT_COLLAPSED_LINES = 5 +const LINE_HEIGHT_PX = 20 +// py-1.5 plus room for a horizontal scrollbar, so the last line is never clipped. +const BLOCK_PADDING_PX = 20 + +export function SetupScriptCodeBlock({ + heading, + script +}: { + heading: string + script: string +}): React.JSX.Element { + const t = useTranslate() + const contentId = useId() + const lineCount = useMemo(() => countScriptLines(script), [script]) + const collapsible = lineCount > SETUP_SCRIPT_COLLAPSED_LINES + const [expanded, setExpanded] = useState(false) + const collapsed = collapsible && !expanded + const preRef = useRef(null) + + const toggleExpanded = (): void => { + if (expanded && preRef.current) { + // Collapsing keeps the scroll offset, so reset it to show the script's first lines. + preRef.current.scrollTop = 0 + } + setExpanded(!expanded) + } + + return ( +
+

+ {heading} +

+
+ {/* An exact target height keeps the max-height transition in step with the content; long scripts scroll inside 40vh so two blocks still fit. */} +
+          {script}
+        
+ {collapsed ? ( +
+ ) : null} +
+ {collapsible ? ( +
+ +
+ ) : null} +
+ ) +} diff --git a/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx b/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx index aeefe981a94..841eac011d4 100644 --- a/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx +++ b/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx @@ -238,24 +238,13 @@ function SetupScriptPromptCard(): React.JSX.Element | null { } if (mountedRef.current) { setPromptState((current) => markSetupScriptPromptSaved(current, importedRepoHostIdentity)) - const skippedCount = candidate.unsupportedFields?.length ?? 0 + // Skipped fields were listed in the review dialog before saving; the toast only confirms. showSavedInProjectSettingsToast({ onOpenSettings: () => openLocalCommandSettings(importedRepoId, importedHostId), - description: - skippedCount > 0 - ? translate( - 'auto.components.sidebar.SetupScriptPromptCard.savedWithSkippedFields', - '{{count}} unsupported fields skipped. Saved the setup command.', - { - count: skippedCount, - defaultValue_one: - '{{count}} unsupported field skipped. Saved the setup command.' - } - ) - : translate( - 'auto.components.sidebar.SetupScriptPromptCard.savedSetupCommand', - 'Saved the setup command.' - ) + description: translate( + 'auto.components.sidebar.SetupScriptPromptCard.savedSetupCommand', + 'Saved the setup command.' + ) }) } } catch (error) { diff --git a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.fixture.tsx b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.fixture.tsx index 95ca136860f..c61e94e88f0 100644 --- a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.fixture.tsx +++ b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.fixture.tsx @@ -3,18 +3,20 @@ import { SetupScriptPromptCardShell } from './SetupScriptPromptCardShell' const noop = (): void => {} -const longSetup = [ - 'corepack enable', - 'pnpm install --frozen-lockfile --prefer-offline --reporter=append-only --filter "./packages/**" --filter "./apps/web"', - 'cp "$CONDUCTOR_ROOT_PATH/.env.local" .env.local', - 'pnpm --filter @acme/db run migrate:dev -- --skip-seed', - 'pnpm --filter @acme/web run build:icons', - 'docker compose -f infra/docker-compose.dev.yml up -d postgres redis minio', - 'until pg_isready -h localhost -p 5432; do sleep 1; done', - 'pnpm --filter @acme/db run seed -- --profile=small', - 'pnpm --filter @acme/web exec playwright install chromium', - 'echo "Workspace ready on port $CONDUCTOR_PORT"' -].join('\n') +const shortSetup = ['pnpm install', 'cp "$CONDUCTOR_ROOT_PATH/.env.local" .env.local'].join('\n') + +const longSetup = Array.from({ length: 40 }, (_, index) => { + const step = index + 1 + return step % 7 === 0 + ? `docker compose -f infra/docker-compose.dev.yml run --rm --service-ports --name step-${step} toolbox ./scripts/bootstrap.sh --profile=full --skip-seed` + : `pnpm --filter @acme/pkg-${step} run setup` +}).join('\n') + +const hugeSetup = Array.from( + { length: 2000 }, + (_, index) => + `echo "step ${index + 1}" && ./scripts/run-step.sh --index=${index + 1} ${'--flag=value '.repeat(20)}` +).join('\n') const base = { repoBadgeColor: '#7c3aed', @@ -34,6 +36,21 @@ function Frame({ children }: { children: React.ReactNode }): React.JSX.Element { return
{children}
} +function clickButton(frame: HTMLElement | Document, label: string): void { + Array.from(frame.querySelectorAll('button')) + .find((button) => button.textContent?.includes(label)) + ?.click() +} + +async function openReview(frame: HTMLElement): Promise { + clickButton(frame, 'Review setup script') + // A mouse click never shows the auto-focus ring; drop the one a synthetic click leaves. + await new Promise((resolve) => requestAnimationFrame(resolve)) + if (document.activeElement instanceof HTMLElement) { + document.activeElement.blur() + } +} + export const conductor = defineFixture({ width: 303, render: () => ( @@ -41,12 +58,13 @@ export const conductor = defineFixture({ @@ -56,16 +74,74 @@ export const conductor = defineFixture({ export const conductorReview = defineFixture({ ...conductor, width: 720, - interact: async (frame) => { - Array.from(frame.querySelectorAll('button')) - .find((button) => button.textContent?.includes('Review setup script')) - ?.click() - // A mouse click never shows the auto-focus ring; drop the one a synthetic click leaves. - await new Promise((resolve) => requestAnimationFrame(resolve)) - if (document.activeElement instanceof HTMLElement) { - document.activeElement.blur() - } + interact: openReview +}) + +export const devcontainer = defineFixture({ + width: 303, + render: () => ( + + + + ) +}) + +export const devcontainerReview = defineFixture({ + ...devcontainer, + width: 720, + interact: openReview +}) + +async function openReviewExpanded(frame: HTMLElement): Promise { + await openReview(frame) + for (const toggle of document.querySelectorAll( + 'button[aria-expanded="false"][aria-controls]' + )) { + toggle.click() } + await new Promise((resolve) => setTimeout(resolve, 400)) + if (document.activeElement instanceof HTMLElement) { + document.activeElement.blur() + } +} + +export const devcontainerReviewExpanded = defineFixture({ + ...devcontainer, + width: 720, + interact: openReviewExpanded +}) + +// 2,000 long lines in setup and archive: the dialog must stay within the viewport with Save visible. +export const hugeReviewExpanded = defineFixture({ + width: 720, + render: () => ( + + `steps.${index}.uses`) + }} + /> + + ), + interact: openReviewExpanded }) export const packageManager = defineFixture({ @@ -77,7 +153,12 @@ export const packageManager = defineFixture({ isPackageManagerSuggestion candidateSource="package manager (pnpm-lock.yaml)" candidateProvenance="pnpm-lock.yaml" - detectedSetupPreview={{ setup: 'pnpm install', archive: null, editable: true }} + detectedSetupPreview={{ + setup: 'pnpm install', + archive: null, + editable: true, + skippedFields: [] + }} /> ) diff --git a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx index 49b588f882d..dbedf0b4257 100644 --- a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx +++ b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx @@ -3,7 +3,6 @@ import { RepoBadgeMark } from '@/components/repo/RepoBadgeLabel' import { ConfigureOnlyAction, DetectedSetupPreview, - DetectedSetupSummary, DismissButton, InspectionErrorActions, PackageManagerActions, @@ -52,6 +51,7 @@ export function SetupScriptPromptCardShell({ const t = useTranslate() const [reviewOpen, setReviewOpen] = useState(false) const showDetected = !isInspectionError && !sharedSetupIgnored && detectedSetupPreview !== null + const isImport = showDetected && !detectedSetupPreview.editable return (

- {t('auto.components.sidebar.SetupScriptPromptCard.ff1e819a11', 'Add a setup script')} + {isImport + ? t( + 'auto.components.sidebar.SetupScriptPromptCard.importTitle', + 'Import setup script' + ) + : t('auto.components.sidebar.SetupScriptPromptCard.ff1e819a11', 'Add a setup script')}

@@ -75,7 +80,7 @@ export function SetupScriptPromptCardShell({ isInspectionError={isInspectionError} sharedSetupIgnored={sharedSetupIgnored} isPackageManagerSuggestion={isPackageManagerSuggestion} - candidateSource={candidateSource} + candidateSource={candidateProvenance ?? candidateSource} />

@@ -85,11 +90,6 @@ export function SetupScriptPromptCardShell({ onSetupChange={onSetupDraftChange} provenance={candidateProvenance} /> - ) : showDetected ? ( - ) : null} {isInspectionError ? ( @@ -108,14 +108,15 @@ export function SetupScriptPromptCardShell({ ) : null}
- {/* Imported scripts are saved verbatim, so saving only happens after the full text is on screen. */} - {showDetected && !detectedSetupPreview.editable ? ( + {/* Imported scripts are saved verbatim, so saving happens from a dialog that can show all of the text. */} + {isImport ? ( void @@ -45,38 +44,7 @@ export type DetectedSetupPreviewProps = { provenance: string | null } -function DetectedSetupSection({ - provenance, - children -}: { - provenance: string | null - children: React.ReactNode -}): React.JSX.Element { - const t = useTranslate() - return ( -
-
- - {t('auto.components.sidebar.SetupScriptPromptCardViews.7275f674cc', 'Detected setup')} -
- {children} - {provenance ? ( -

- {{source}}' - )} - values={{ source: provenance }} - components={{ source: }} - /> -

- ) : null} -
- ) -} - +// Package-manager guesses only: imports are summarized in one line and reviewed in a dialog. export function DetectedSetupPreview({ setup, onSetupChange, @@ -84,7 +52,11 @@ export function DetectedSetupPreview({ }: DetectedSetupPreviewProps): React.JSX.Element { const t = useTranslate() return ( - +
+
+ + {t('auto.components.sidebar.SetupScriptPromptCardViews.7275f674cc', 'Detected setup')} +