From ad0dfec9d4c0f95cd0c99f18e17a0b4214fc9eb0 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:41:53 -0800 Subject: [PATCH 01/17] fix(ime): keep plain-committed Hangul so macOS 2-Set can rebuild it in place (#41884) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(ime): keep plain-committed Hangul so macOS 2-Set can rebuild it in place Right after an input-source switch, macOS 2-Set can commit a lone jamo as plain text and then rebuild it (ㅇ + ㅏ → 아) by replacing that committed range. The native text forwarder emptied the field after every commit, so the replacement had nothing to land on and the vowel was dropped (#9738). Keep Hangul commits in the field (Latin commits still clear for #11504), and erase replaced text from the PTY before the replacement is sent. * fix(ime): only erase retained Hangul when the replacement is forwarded and still at the PTY cursor Drop retention on blur, on any composition start, and on chord/named keydowns the pane handles before the forwarder (macOS Ctrl+C, non-Latin control chords). Erase only for insertText/composition replacements that end at the field tail. * ci(e2e): route terminal IME changes to IME specs again after the input/ owner move #39113 moved IME and keyboard policy files under terminal-pane/input/, but the native IBus and synthetic IME routes still matched the old paths, so IME changes selected neither lane. --- .../source-routing/pr-e2e-source-routing.mjs | 5 +- .../ime/terminal-ime-native-text-forwarder.ts | 12 +- ...erminal-ime-retained-hangul-commit.test.ts | 127 ++++++++++++++++ .../terminal-ime-retained-hangul-commit.ts | 138 ++++++++++++++++++ 4 files changed, 279 insertions(+), 3 deletions(-) create mode 100644 src/renderer/src/components/terminal-pane/input/ime/terminal-ime-retained-hangul-commit.test.ts create mode 100644 src/renderer/src/components/terminal-pane/input/ime/terminal-ime-retained-hangul-commit.ts diff --git a/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs b/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs index 185f388ef22..418312cf2d3 100644 --- a/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs +++ b/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs @@ -19,8 +19,9 @@ const isProductSource = (file) => !/\.test\.tsx?$/.test(file) && !isUnitTestSupp const XTERM_CORE_PATCH = /^config\/patches\/(?:@xterm__xterm@[^/]+\.patch|xterm-src\/@xterm__xterm@[^/]+\.src\.patch)$/ +// Paths follow the input/ime and input/keyboard owners (#39113); the pre-move paths matched nothing. const NATIVE_IME_PRODUCT_SOURCE = - /^(?:src\/shared\/terminal-unicode-provider\.ts$|src\/renderer\/src\/lib\/pane-manager\/terminal-ime-|src\/renderer\/src\/components\/terminal-pane\/(?:terminal-ime-|terminal-ios-hangul-|xterm-bypass-policy))/ + /^(?:src\/shared\/terminal-unicode-provider\.ts$|src\/renderer\/src\/lib\/pane-manager\/terminal-input\/terminal-ime-|src\/renderer\/src\/components\/terminal-pane\/input\/(?:ime\/|keyboard\/xterm-bypass-policy|terminal-pane-pane-input\.ts$))/ /** The harness itself: the session runner, the boundary probes, and the native specs. */ const NATIVE_IME_HARNESS = @@ -401,7 +402,7 @@ export const PR_E2E_SOURCE_ROUTES = [ matches: (file) => isProductSource(file) && (XTERM_CORE_PATCH.test(file) || - /^src\/renderer\/src\/components\/terminal-pane\/(?:terminal-ime-|use-terminal-pane-lifecycle|xterm-bypass-policy|terminal-option-shortcut-policy)/.test( + /^src\/renderer\/src\/components\/terminal-pane\/(?:input\/ime\/terminal-ime-|controller\/use-terminal-pane-lifecycle|input\/keyboard\/(?:xterm-bypass-policy|terminal-option-shortcut-policy))/.test( file )) }, diff --git a/src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.ts b/src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.ts index b4d9f4a3c10..ac4a8b58577 100644 --- a/src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.ts +++ b/src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.ts @@ -6,6 +6,7 @@ import { type ImeReleaseKeyEvent } from './terminal-ime-kitty-commit-encoding' import { getLayoutCharacterForCode } from '../../../../lib/keyboard-layout/layout-base-character' +import { installTerminalImeRetainedHangulCommit } from './terminal-ime-retained-hangul-commit' // Claim plain printable keydowns so native input commits supply substituted text before xterm can cancel it; Linux fcitx4 candidate picks need the same path (#28213). Match key length, never source identity or character tables. @@ -115,6 +116,11 @@ export function installTerminalImeNativeTextForwarder(args: { let pendingCommit: PendingCommit | null = null // Rollover and repeat leave multiple keys held; each needs its own release record. const claimedKeyRecords = new Map() + const retainedHangulCommit = installTerminalImeRetainedHangulCommit({ + terminalElement, + sendInput: args.sendInput, + getKittyKeyboardFlags: () => args.getKittyKeyboardFlags?.() ?? 0 + }) const findClaimedRecordId = (event: ImeNativeTextKeyEvent): string | null => { const direct = claimedKeyId(event) @@ -294,7 +300,10 @@ export function installTerminalImeNativeTextForwarder(args: { } event.stopImmediatePropagation() // Clear committed text: macOS reads preceding field contents for double-space period substitution (#11504). - if (event.target instanceof HTMLTextAreaElement) { + if ( + event.target instanceof HTMLTextAreaElement && + !(event.data && retainedHangulCommit.retain(event.target, event.data)) + ) { event.target.value = '' } } @@ -323,6 +332,7 @@ export function installTerminalImeNativeTextForwarder(args: { claimKeyEvent, dispose: () => { cancelPending() + retainedHangulCommit.dispose() terminalElement.removeEventListener( XTERM_COMPOSITION_TRANSACTION_ACCEPTED_EVENT, markCompositionTransactionAccepted, diff --git a/src/renderer/src/components/terminal-pane/input/ime/terminal-ime-retained-hangul-commit.test.ts b/src/renderer/src/components/terminal-pane/input/ime/terminal-ime-retained-hangul-commit.test.ts new file mode 100644 index 00000000000..c61dd906d7e --- /dev/null +++ b/src/renderer/src/components/terminal-pane/input/ime/terminal-ime-retained-hangul-commit.test.ts @@ -0,0 +1,127 @@ +// @vitest-environment happy-dom +/** macOS 2-Set right after an input-source switch: plain-commits ㅇ, then rebuilds it as 아 by replacing it (#9738, m4air trace). */ +import { Terminal } from '@xterm/xterm' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { installTerminalImeNativeTextForwarder } from './terminal-ime-native-text-forwarder' + +function open() { + const container = document.createElement('div') + document.body.appendChild(container) + const terminal = new Terminal() + terminal.open(container) + const textarea = terminal.textarea! + const forwarder = installTerminalImeNativeTextForwarder({ + terminalElement: terminal.element, + isComposing: () => false, + sendInput: (data) => terminal.input(data), + getKittyKeyboardFlags: () => 0 + }) + terminal.attachCustomKeyEventHandler((event) => !forwarder.claimKeyEvent(event)) + const emitted: string[] = [] + terminal.onData((d) => emitted.push(d)) + return { emitted, terminal, textarea, forwarder, container } +} + +function keydown(textarea: HTMLTextAreaElement, key: string, code: string, keyCode: number) { + textarea.dispatchEvent(new KeyboardEvent('keydown', { key, code, keyCode, bubbles: true })) +} + +function plainCommit(textarea: HTMLTextAreaElement, data: string) { + textarea.setRangeText(data, textarea.selectionStart, textarea.selectionEnd, 'end') + textarea.dispatchEvent(new InputEvent('input', { data, inputType: 'insertText', bubbles: true })) +} + +// Blink selects the replacement range, fires beforeinput, then writes the text. +function replacingCommit(textarea: HTMLTextAreaElement, start: number, end: number, data: string) { + textarea.setSelectionRange(start, end) + textarea.dispatchEvent( + new InputEvent('beforeinput', { data, inputType: 'insertText', bubbles: true }) + ) + plainCommit(textarea, data) +} + +describe('#9738 plain-committed jamo rebuilt in place', () => { + let pane: ReturnType + + beforeEach(() => { + // happy-dom has no canvas, and xterm measures text on open(). + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: xterm only calls measureText on this stub. + vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ + measureText: () => ({ width: 10 }) + } as unknown as CanvasRenderingContext2D) + pane = open() + }) + + afterEach(() => { + pane.forwarder.dispose() + pane.terminal.dispose() + pane.container.remove() + vi.restoreAllMocks() + }) + + it('keeps the jamo for the rebuild and erases it from the PTY when replaced', () => { + keydown(pane.textarea, 'ㅇ', 'KeyD', 68) + plainCommit(pane.textarea, 'ㅇ') + expect(pane.textarea.value).toBe('ㅇ') + + keydown(pane.textarea, 'ㅏ', 'KeyK', 75) + replacingCommit(pane.textarea, 0, 1, '아') + + expect(pane.emitted.join('')).toBe('ㅇ\x7f아') + }) + + it('erases the jamo before a composition that replaces it begins', () => { + keydown(pane.textarea, 'ㅇ', 'KeyD', 68) + plainCommit(pane.textarea, 'ㅇ') + + pane.textarea.setSelectionRange(0, 1) + pane.textarea.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true })) + + expect(pane.emitted.join('')).toBe('ㅇ\x7f') + }) + + it('does not erase for an edit whose replacement never reaches the PTY', () => { + keydown(pane.textarea, 'ㅇ', 'KeyD', 68) + plainCommit(pane.textarea, 'ㅇ') + + pane.textarea.setSelectionRange(0, 1) + pane.textarea.dispatchEvent( + new InputEvent('beforeinput', { inputType: 'insertReplacementText', bubbles: true }) + ) + + expect(pane.emitted.join('')).toBe('ㅇ') + }) + + it('does not erase once an ordinary composition has begun after the jamo', () => { + keydown(pane.textarea, 'ㅇ', 'KeyD', 68) + plainCommit(pane.textarea, 'ㅇ') + + pane.textarea.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true })) + pane.textarea.setSelectionRange(0, 1) + pane.textarea.dispatchEvent( + new InputEvent('beforeinput', { inputType: 'insertCompositionText', bubbles: true }) + ) + + expect(pane.emitted.join('')).toBe('ㅇ') + }) + + it('removes the jamo from the field on Ctrl+C the pane handles ahead of the forwarder', () => { + pane.terminal.attachCustomKeyEventHandler( + (event) => !event.ctrlKey && !pane.forwarder.claimKeyEvent(event) + ) + keydown(pane.textarea, 'ㅇ', 'KeyD', 68) + plainCommit(pane.textarea, 'ㅇ') + + pane.textarea.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'c', + code: 'KeyC', + keyCode: 67, + ctrlKey: true, + bubbles: true + }) + ) + + expect(pane.textarea.value).toBe('') + }) +}) diff --git a/src/renderer/src/components/terminal-pane/input/ime/terminal-ime-retained-hangul-commit.ts b/src/renderer/src/components/terminal-pane/input/ime/terminal-ime-retained-hangul-commit.ts new file mode 100644 index 00000000000..2d15f07fa24 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/input/ime/terminal-ime-retained-hangul-commit.ts @@ -0,0 +1,138 @@ +import { + KITTY_REPORT_EVENT_TYPES, + kittyReportsAllKeysAsEscapeCodes +} from '../../../../../../shared/terminal/protocol/input-modes/terminal-kitty-keyboard-flags' + +// Hangul jamo blocks plus precomposed syllables: text a Korean input method may later rebuild in place. +const HANGUL_TEXT = /[ᄀ-ᇿ㄰-㆏ꥠ-꥿가-힣ힰ-퟿ᅠ-ᅵ]/u + +type RetainedRange = { + textarea: HTMLTextAreaElement + start: number + end: number + text: string +} + +/** + * macOS 2-Set can commit a lone jamo as plain text and then rebuild it in place (ㅇ + ㅏ → 아) by + * replacing that committed range (#9738). The forwarder has already sent the jamo, so keep it in the + * field for the replacement to land, and erase it from the PTY when the input method replaces it. + */ +export type TerminalImeRetainedHangulCommit = { + /** Returns true when the commit stays in the field instead of being cleared. */ + retain: (textarea: HTMLTextAreaElement, committedText: string) => boolean + dispose: () => void +} + +// Only these replacements are forwarded to the PTY afterwards; erasing for any other edit would lose text. +const FORWARDED_REPLACEMENT_INPUT_TYPES = new Set(['insertText', 'insertCompositionText']) +const MODIFIER_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'CapsLock', 'AltGraph', 'Fn']) + +function encodeBackspace(kittyKeyboardFlags: number): string { + if (!kittyReportsAllKeysAsEscapeCodes(kittyKeyboardFlags)) { + return '\x7f' + } + return (kittyKeyboardFlags & KITTY_REPORT_EVENT_TYPES) !== 0 + ? '\x1b[127u\x1b[127;1:3u' + : '\x1b[127u' +} + +function isIntact(range: RetainedRange): boolean { + return range.textarea.value.slice(range.start, range.end) === range.text +} + +export function installTerminalImeRetainedHangulCommit(args: { + terminalElement: HTMLElement + sendInput: (data: string) => void + getKittyKeyboardFlags: () => number +}): TerminalImeRetainedHangulCommit { + let retained: RetainedRange | null = null + + const retain = (textarea: HTMLTextAreaElement, committedText: string): boolean => { + if (!HANGUL_TEXT.test(committedText) || textarea.selectionStart !== textarea.selectionEnd) { + retained = null + return false + } + const end = textarea.selectionEnd + const start = end - committedText.length + if (start < 0 || textarea.value.slice(start, end) !== committedText) { + retained = null + return false + } + // Consecutive commits extend one range so a rebuild spanning both still erases both. + retained = + retained && retained.textarea === textarea && retained.end === start && isIntact(retained) + ? { textarea, start: retained.start, end, text: retained.text + committedText } + : { textarea, start, end, text: committedText } + return true + } + + // Capture runs before xterm or the forwarder sends the replacement, so the PTY erases it first. + const eraseReplacedRange = (event: Event): void => { + const range = retained + if (!range || event.target !== range.textarea) { + return + } + if (event instanceof InputEvent && !FORWARDED_REPLACEMENT_INPUT_TYPES.has(event.inputType)) { + return + } + const { selectionStart, selectionEnd } = range.textarea + const replacesRetainedTail = + isIntact(range) && + selectionStart < selectionEnd && + selectionStart >= range.start && + // Backspace erases from the PTY cursor, so the replaced text must be the last text sent. + selectionEnd === range.end && + selectionEnd === range.textarea.value.length + // A composition owns the field from here; its clause selections must not read as rebuilds. + if (replacesRetainedTail || event.type === 'compositionstart' || !isIntact(range)) { + retained = null + } + if (!replacesRetainedTail) { + return + } + const replaced = Array.from(range.textarea.value.slice(selectionStart, selectionEnd)).length + args.sendInput(encodeBackspace(args.getKittyKeyboardFlags()).repeat(replaced)) + } + + // Chords and named keys (Backspace, Enter, Ctrl+C) edit the PTY without the input method's text; observed here because the pane handles some before the forwarder sees them. + const dropOnNonTextKeydown = (event: KeyboardEvent): void => { + const range = retained + const isPlainText = event.key.length === 1 && !event.ctrlKey && !event.altKey && !event.metaKey + if ( + !range || + isPlainText || + event.keyCode === 229 || + event.isComposing || + MODIFIER_KEYS.has(event.key) + ) { + return + } + retained = null + // Mirror the PTY edit in the field so the input method stops rebuilding text it no longer owns. + if (isIntact(range) && range.end === range.textarea.value.length) { + range.textarea.value = range.textarea.value.slice(0, range.start) + } + } + + // xterm empties the field on blur. + const drop = (): void => { + retained = null + } + + args.terminalElement.addEventListener('compositionstart', eraseReplacedRange, true) + args.terminalElement.addEventListener('beforeinput', eraseReplacedRange, true) + args.terminalElement.addEventListener('keydown', dropOnNonTextKeydown, true) + args.terminalElement.addEventListener('blur', drop, true) + + return { + retain, + dispose: () => { + retained = null + args.terminalElement.removeEventListener('keydown', dropOnNonTextKeydown, true) + args.terminalElement.removeEventListener('blur', drop, true) + args.terminalElement.removeEventListener('compositionstart', eraseReplacedRange, true) + args.terminalElement.removeEventListener('beforeinput', eraseReplacedRange, true) + } + } +} From e7288d7ea5387b279ddf5663d1004f04a1bd793f Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:46:08 -0800 Subject: [PATCH 02/17] refactor: group new-workspace modules by domain (#41905) --- config/focus-setting-read-baseline.txt | 12 +- config/react-compiler-bailout-baseline.txt | 12 +- config/react-compiler-uncompiled-files.txt | 4 +- .../scripts/ci/sharding/ci-shard-timings.json | 22 ++-- .../components/NewWorkspaceComposerCard.tsx | 33 +++--- .../components/NewWorkspaceComposerModal.tsx | 6 +- ...ithub-duplicate-issue-candidates.test.tsx} | 0 .../jira-issue-assignee-control.tsx | 2 +- .../tree/NativeChatResumeOnRestartGroups.tsx | 2 +- .../native-chat-composer-drop-scope.test.tsx | 17 +-- .../SmartWorkspaceNameField.fixture.tsx | 2 +- .../new-workspace/SmartWorkspaceNameField.tsx | 6 +- .../ComposerBaseRefPicker.tsx | 2 +- .../ComposerBranchChoice.tsx | 0 .../ComposerParentWorktreePicker.fixture.tsx | 6 +- .../ComposerParentWorktreePicker.test.tsx | 11 +- .../ComposerParentWorktreePicker.tsx | 48 +++----- .../base-ref-picker-visibility.ts | 4 +- .../composer-parent-worktree-picker-props.ts | 21 ++++ .../NewWorkspaceComposerAdvancedSection.tsx | 8 +- .../NewWorkspaceComposerAgentSection.tsx | 0 .../NewWorkspaceComposerFooter.tsx | 0 ...ewWorkspaceComposerNameSection.fixture.tsx | 4 +- .../NewWorkspaceComposerNameSection.test.tsx | 0 .../NewWorkspaceComposerNameSection.tsx | 6 +- ...orkspaceComposerProjectSection.fixture.tsx | 2 +- .../NewWorkspaceComposerProjectSection.tsx | 21 ++-- .../{ => composer}/composer-modal-data.ts | 12 +- .../new-workspace-composer-card-props.ts | 42 +++---- .../new-workspace-composer-ssh-status.ts | 2 +- .../use-composer-file-drag-over.ts | 0 .../use-new-workspace-composer-file-drop.ts | 2 +- .../smart-workspace-cross-repo-dialog.tsx | 0 .../smart-workspace-name-field-copy.ts | 2 +- .../smart-workspace-name-field-model.ts | 16 +-- .../smart-workspace-name-field-surface.tsx | 4 +- .../smart-workspace-name-input-surface.tsx | 6 +- .../smart-workspace-source-popover-focus.ts | 0 ...smart-workspace-source-results-surface.tsx | 6 +- ...se-smart-workspace-field-focus-controls.ts | 2 +- .../use-smart-workspace-name-field-actions.ts | 12 +- ...e-smart-workspace-name-field-controller.ts | 4 +- .../SetProjectLocationDialog.test.tsx | 0 .../SetProjectLocationDialog.tsx | 8 +- .../SetProjectLocationForms.tsx | 6 +- .../pick-local-project-folder.ts | 0 .../ProjectCombobox.dialog-handoff.test.tsx | 110 +----------------- .../ProjectCombobox.tsx | 9 +- .../ProjectComboboxAddProjectOption.tsx | 2 +- .../ProjectComboboxRow.tsx | 0 .../composer-add-project-default-host.ts | 2 +- .../project-combobox-localized-copy.ts | 0 .../project-combobox-matching.ts | 0 .../use-composer-hosted-add-project.ts | 0 .../use-recent-project-ids.test.ts | 2 +- .../use-recent-project-ids.ts | 2 +- .../RunTargetCombobox.fixture.tsx | 2 +- .../{ => run-target}/RunTargetCombobox.tsx | 6 +- .../{ => run-target}/RunTargetComboboxRow.tsx | 5 +- .../{ => run-target}/RunTargetField.tsx | 6 +- .../{ => run-target}/RunTargetRowActions.tsx | 4 +- .../{ => run-target}/RunTargetRowList.tsx | 3 +- .../{ => run-target}/RunTargetSubmenus.tsx | 5 +- .../{ => run-target}/run-target-options.ts | 2 +- .../DirectWorkItemSetupDialog.test.tsx | 0 .../{ => setup}/DirectWorkItemSetupDialog.tsx | 0 .../{ => setup}/SetupCommandPreview.tsx | 0 .../{ => setup}/WorkspaceSetupChoice.test.tsx | 0 .../{ => setup}/WorkspaceSetupChoice.tsx | 0 .../{ => setup}/WorkspaceSetupSection.tsx | 6 +- .../direct-work-item-setup-copy.ts | 0 .../workspace-setup-composer-copy.ts | 0 .../workspace-setup-section-model.ts | 2 +- .../smart-workspace-command-value.ts | 1 - .../SmartWorkspaceSourceResultList.tsx | 4 +- .../SmartWorkspaceSourceTabs.fixture.tsx | 4 +- .../SmartWorkspaceSourceTabs.tsx | 0 .../jira-source-status-message.ts | 0 .../smart-workspace-empty-hint.ts | 2 +- ...smart-workspace-github-direct-link.test.ts | 4 +- .../smart-workspace-github-direct-link.ts | 8 +- .../smart-workspace-localized-options.tsx | 2 +- .../smart-workspace-provider-availability.ts | 2 +- .../smart-workspace-repo-slug.ts | 8 +- .../smart-workspace-source-row-content.tsx | 9 +- .../use-composer-source-scope.ts | 6 +- .../use-jira-composer-project.ts | 12 +- .../use-jira-source-connection.test.tsx | 4 +- .../use-jira-source-connection.ts | 4 +- .../use-jira-url-source.test.tsx | 8 +- .../use-jira-url-source.ts | 12 +- .../use-linear-source-connection.ts | 4 +- ...smart-workspace-field-availability.test.ts | 0 .../use-smart-workspace-field-availability.ts | 8 +- .../use-smart-workspace-github-search.ts | 8 +- .../use-smart-workspace-gitlab-search.ts | 6 +- ...pace-name-field-foundation.source.test.tsx | 12 +- .../use-smart-workspace-secondary-searches.ts | 18 +-- .../use-work-item-source-foundation.ts | 12 +- .../use-work-item-source-presentation.ts | 16 +-- .../use-work-item-source-search.ts | 10 +- .../use-work-item-source-state.ts | 14 +-- .../work-item-source-selection.ts | 14 +-- .../type-ahead-combobox-styles.ts | 0 .../use-type-ahead-combobox.ts | 0 .../{ => type-ahead}/use-wheel-scrollable.ts | 0 .../menu/AddProjectMenu.fixture.tsx | 2 +- .../menu/AddProjectMenu.test.tsx | 4 +- .../review/WorkspaceAttachmentSearch.tsx | 8 +- .../WorkspaceAttachmentSourceStatus.tsx | 4 +- .../folder-workspace-source-selection.ts | 2 +- .../composer-state/composer-source-model.ts | 2 +- .../composer-state/issue-source-actions.ts | 2 +- .../launch-work-item-direct-setup.test.tsx | 2 +- .../smart-workspace-source-results.test.ts | 4 +- ...rt-workspace-linear-read-test-fixtures.tsx | 22 ++-- 116 files changed, 345 insertions(+), 462 deletions(-) rename src/renderer/src/components/{new-workspace/github-source-consumers.test.tsx => github/github-duplicate-issue-candidates.test.tsx} (100%) rename src/renderer/src/components/new-workspace/{ => branch-selection}/ComposerBaseRefPicker.tsx (96%) rename src/renderer/src/components/new-workspace/{ => branch-selection}/ComposerBranchChoice.tsx (100%) rename src/renderer/src/components/new-workspace/{ => branch-selection}/ComposerParentWorktreePicker.fixture.tsx (89%) rename src/renderer/src/components/new-workspace/{ => branch-selection}/ComposerParentWorktreePicker.test.tsx (96%) rename src/renderer/src/components/new-workspace/{ => branch-selection}/ComposerParentWorktreePicker.tsx (92%) rename src/renderer/src/components/new-workspace/{ => branch-selection}/base-ref-picker-visibility.ts (83%) create mode 100644 src/renderer/src/components/new-workspace/branch-selection/composer-parent-worktree-picker-props.ts rename src/renderer/src/components/new-workspace/{ => composer}/NewWorkspaceComposerAdvancedSection.tsx (97%) rename src/renderer/src/components/new-workspace/{ => composer}/NewWorkspaceComposerAgentSection.tsx (100%) rename src/renderer/src/components/new-workspace/{ => composer}/NewWorkspaceComposerFooter.tsx (100%) rename src/renderer/src/components/new-workspace/{ => composer}/NewWorkspaceComposerNameSection.fixture.tsx (93%) rename src/renderer/src/components/new-workspace/{ => composer}/NewWorkspaceComposerNameSection.test.tsx (100%) rename src/renderer/src/components/new-workspace/{ => composer}/NewWorkspaceComposerNameSection.tsx (96%) rename src/renderer/src/components/new-workspace/{ => composer}/NewWorkspaceComposerProjectSection.fixture.tsx (98%) rename src/renderer/src/components/new-workspace/{ => composer}/NewWorkspaceComposerProjectSection.tsx (92%) rename src/renderer/src/components/new-workspace/{ => composer}/composer-modal-data.ts (75%) rename src/renderer/src/components/new-workspace/{ => composer}/new-workspace-composer-card-props.ts (78%) rename src/renderer/src/components/new-workspace/{ => composer}/new-workspace-composer-ssh-status.ts (94%) rename src/renderer/src/components/new-workspace/{ => composer}/use-composer-file-drag-over.ts (100%) rename src/renderer/src/components/new-workspace/{ => composer}/use-new-workspace-composer-file-drop.ts (98%) rename src/renderer/src/components/new-workspace/{ => name-field}/smart-workspace-cross-repo-dialog.tsx (100%) rename src/renderer/src/components/new-workspace/{ => name-field}/smart-workspace-name-field-copy.ts (97%) rename src/renderer/src/components/new-workspace/{ => name-field}/smart-workspace-name-field-model.ts (84%) rename src/renderer/src/components/new-workspace/{ => name-field}/smart-workspace-name-field-surface.tsx (96%) rename src/renderer/src/components/new-workspace/{ => name-field}/smart-workspace-name-input-surface.tsx (97%) rename src/renderer/src/components/new-workspace/{ => name-field}/smart-workspace-source-popover-focus.ts (100%) rename src/renderer/src/components/new-workspace/{ => name-field}/smart-workspace-source-results-surface.tsx (93%) rename src/renderer/src/components/new-workspace/{ => name-field}/use-smart-workspace-field-focus-controls.ts (97%) rename src/renderer/src/components/new-workspace/{ => name-field}/use-smart-workspace-name-field-actions.ts (92%) rename src/renderer/src/components/new-workspace/{ => name-field}/use-smart-workspace-name-field-controller.ts (95%) rename src/renderer/src/components/new-workspace/{ => project-location}/SetProjectLocationDialog.test.tsx (100%) rename src/renderer/src/components/new-workspace/{ => project-location}/SetProjectLocationDialog.tsx (96%) rename src/renderer/src/components/new-workspace/{ => project-location}/SetProjectLocationForms.tsx (96%) rename src/renderer/src/components/new-workspace/{ => project-location}/pick-local-project-folder.ts (100%) rename src/renderer/src/components/new-workspace/{ => project-selection}/ProjectCombobox.dialog-handoff.test.tsx (51%) rename src/renderer/src/components/new-workspace/{ => project-selection}/ProjectCombobox.tsx (98%) rename src/renderer/src/components/new-workspace/{ => project-selection}/ProjectComboboxAddProjectOption.tsx (98%) rename src/renderer/src/components/new-workspace/{ => project-selection}/ProjectComboboxRow.tsx (100%) rename src/renderer/src/components/new-workspace/{ => project-selection}/composer-add-project-default-host.ts (94%) rename src/renderer/src/components/new-workspace/{ => project-selection}/project-combobox-localized-copy.ts (100%) rename src/renderer/src/components/new-workspace/{ => project-selection}/project-combobox-matching.ts (100%) rename src/renderer/src/components/new-workspace/{ => project-selection}/use-composer-hosted-add-project.ts (100%) rename src/renderer/src/components/new-workspace/{ => project-selection}/use-recent-project-ids.test.ts (94%) rename src/renderer/src/components/new-workspace/{ => project-selection}/use-recent-project-ids.ts (94%) rename src/renderer/src/components/new-workspace/{ => run-target}/RunTargetCombobox.fixture.tsx (96%) rename src/renderer/src/components/new-workspace/{ => run-target}/RunTargetCombobox.tsx (97%) rename src/renderer/src/components/new-workspace/{ => run-target}/RunTargetComboboxRow.tsx (95%) rename src/renderer/src/components/new-workspace/{ => run-target}/RunTargetField.tsx (95%) rename src/renderer/src/components/new-workspace/{ => run-target}/RunTargetRowActions.tsx (96%) rename src/renderer/src/components/new-workspace/{ => run-target}/RunTargetRowList.tsx (97%) rename src/renderer/src/components/new-workspace/{ => run-target}/RunTargetSubmenus.tsx (97%) rename src/renderer/src/components/new-workspace/{ => run-target}/run-target-options.ts (98%) rename src/renderer/src/components/new-workspace/{ => setup}/DirectWorkItemSetupDialog.test.tsx (100%) rename src/renderer/src/components/new-workspace/{ => setup}/DirectWorkItemSetupDialog.tsx (100%) rename src/renderer/src/components/new-workspace/{ => setup}/SetupCommandPreview.tsx (100%) rename src/renderer/src/components/new-workspace/{ => setup}/WorkspaceSetupChoice.test.tsx (100%) rename src/renderer/src/components/new-workspace/{ => setup}/WorkspaceSetupChoice.tsx (100%) rename src/renderer/src/components/new-workspace/{ => setup}/WorkspaceSetupSection.tsx (94%) rename src/renderer/src/components/new-workspace/{ => setup}/direct-work-item-setup-copy.ts (100%) rename src/renderer/src/components/new-workspace/{ => setup}/workspace-setup-composer-copy.ts (100%) rename src/renderer/src/components/new-workspace/{ => setup}/workspace-setup-section-model.ts (89%) delete mode 100644 src/renderer/src/components/new-workspace/smart-workspace-command-value.ts rename src/renderer/src/components/new-workspace/{ => source-search}/SmartWorkspaceSourceResultList.tsx (98%) rename src/renderer/src/components/new-workspace/{ => source-search}/SmartWorkspaceSourceTabs.fixture.tsx (85%) rename src/renderer/src/components/new-workspace/{ => source-search}/SmartWorkspaceSourceTabs.tsx (100%) rename src/renderer/src/components/new-workspace/{ => source-search}/jira-source-status-message.ts (100%) rename src/renderer/src/components/new-workspace/{ => source-search}/smart-workspace-empty-hint.ts (92%) rename src/renderer/src/components/new-workspace/{ => source-search}/smart-workspace-github-direct-link.test.ts (90%) rename src/renderer/src/components/new-workspace/{ => source-search}/smart-workspace-github-direct-link.ts (92%) rename src/renderer/src/components/new-workspace/{ => source-search}/smart-workspace-localized-options.tsx (96%) rename src/renderer/src/components/new-workspace/{ => source-search}/smart-workspace-provider-availability.ts (93%) rename src/renderer/src/components/new-workspace/{ => source-search}/smart-workspace-repo-slug.ts (83%) rename src/renderer/src/components/new-workspace/{ => source-search}/smart-workspace-source-row-content.tsx (95%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-composer-source-scope.ts (74%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-jira-composer-project.ts (61%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-jira-source-connection.test.tsx (93%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-jira-source-connection.ts (96%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-jira-url-source.test.tsx (96%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-jira-url-source.ts (95%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-linear-source-connection.ts (97%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-smart-workspace-field-availability.test.ts (100%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-smart-workspace-field-availability.ts (94%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-smart-workspace-github-search.ts (95%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-smart-workspace-gitlab-search.ts (94%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-smart-workspace-name-field-foundation.source.test.tsx (91%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-smart-workspace-secondary-searches.ts (92%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-work-item-source-foundation.ts (95%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-work-item-source-presentation.ts (92%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-work-item-source-search.ts (93%) rename src/renderer/src/components/new-workspace/{ => source-search}/use-work-item-source-state.ts (79%) rename src/renderer/src/components/new-workspace/{ => source-search}/work-item-source-selection.ts (86%) rename src/renderer/src/components/new-workspace/{ => type-ahead}/type-ahead-combobox-styles.ts (100%) rename src/renderer/src/components/new-workspace/{ => type-ahead}/use-type-ahead-combobox.ts (100%) rename src/renderer/src/components/new-workspace/{ => type-ahead}/use-wheel-scrollable.ts (100%) rename src/{renderer/src/components => shared}/new-workspace/smart-workspace-source-results.test.ts (96%) diff --git a/config/focus-setting-read-baseline.txt b/config/focus-setting-read-baseline.txt index 00962b987d8..84559a65d66 100644 --- a/config/focus-setting-read-baseline.txt +++ b/config/focus-setting-read-baseline.txt @@ -64,12 +64,12 @@ 1 src/renderer/src/components/linear-item-drawer-edit-section.tsx 1 src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx 1 src/renderer/src/components/native-chat/media/visuals/NativeChatVisualFrame.tsx -1 src/renderer/src/components/new-workspace/use-jira-source-connection.ts -7 src/renderer/src/components/new-workspace/use-linear-source-connection.ts -1 src/renderer/src/components/new-workspace/use-smart-workspace-name-field-controller.ts -1 src/renderer/src/components/new-workspace/use-smart-workspace-secondary-searches.ts -6 src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts -1 src/renderer/src/components/new-workspace/use-work-item-source-search.ts +1 src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.ts +7 src/renderer/src/components/new-workspace/source-search/use-linear-source-connection.ts +1 src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-controller.ts +1 src/renderer/src/components/new-workspace/source-search/use-smart-workspace-secondary-searches.ts +6 src/renderer/src/components/new-workspace/source-search/use-work-item-source-foundation.ts +1 src/renderer/src/components/new-workspace/source-search/use-work-item-source-search.ts 1 src/renderer/src/components/provider-accounts/provider-account-scope.ts 2 src/renderer/src/components/right-sidebar/checks-panel/review-actions/checks-panel-hosted-review-click-routing.ts 1 src/renderer/src/components/right-sidebar/hosted-review/creation/use-create-pull-request-base-ref-discovery.ts diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index a0db79c5703..643bcde57d2 100644 --- a/config/react-compiler-bailout-baseline.txt +++ b/config/react-compiler-bailout-baseline.txt @@ -260,12 +260,12 @@ 2 src/renderer/src/components/native-chat/viewport/virtualization/NativeChatTranscriptItems.tsx 1 src/renderer/src/components/native-chat/viewport/virtualization/use-native-chat-transcript-window.ts 1 src/renderer/src/components/network/CustomAddressDialog.tsx -1 src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx -1 src/renderer/src/components/new-workspace/RunTargetCombobox.tsx -3 src/renderer/src/components/new-workspace/SetProjectLocationDialog.tsx -2 src/renderer/src/components/new-workspace/use-smart-workspace-name-field-actions.ts -1 src/renderer/src/components/new-workspace/use-smart-workspace-name-field-controller.ts -1 src/renderer/src/components/new-workspace/use-smart-workspace-secondary-searches.ts +1 src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.tsx +1 src/renderer/src/components/new-workspace/run-target/RunTargetCombobox.tsx +3 src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.tsx +2 src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-actions.ts +1 src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-controller.ts +1 src/renderer/src/components/new-workspace/source-search/use-smart-workspace-secondary-searches.ts 2 src/renderer/src/components/onboarding/AgentStep.tsx 2 src/renderer/src/components/onboarding/NotificationStep.tsx 8 src/renderer/src/components/onboarding/OnboardingFlow.tsx diff --git a/config/react-compiler-uncompiled-files.txt b/config/react-compiler-uncompiled-files.txt index f542bc6648a..a78f7b1b07a 100644 --- a/config/react-compiler-uncompiled-files.txt +++ b/config/react-compiler-uncompiled-files.txt @@ -7,8 +7,8 @@ src/renderer/src/components/feature-wall/setup/FeatureWallSetupChecklist.tsx src/renderer/src/components/feature-wall/setup/integrations/use-integration-connection-status.ts src/renderer/src/components/integrations/task-trackers/jira-integration-card.tsx src/renderer/src/components/integrations/task-trackers/linear-integration-card.tsx -src/renderer/src/components/new-workspace/use-jira-source-connection.ts -src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts +src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.ts +src/renderer/src/components/new-workspace/source-search/use-work-item-source-foundation.ts src/renderer/src/components/settings/skills/linear/LinearAgentSkillPane.tsx src/renderer/src/components/settings/tasks/use-task-source-provider-readiness.ts src/renderer/src/components/sidebar/workspace-card/details/use-worktree-card-review-details.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index c48decce4df..8df7deddb60 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -4755,21 +4755,21 @@ "src/renderer/src/components/native-chat/session/structured/use-structured-agent-session.clear-send.test.tsx": 2804, "src/renderer/src/components/native-chat/pane/actions/use-structured-native-chat-submit-reveal.test.ts": 2304, "src/renderer/src/components/network/CustomAddressDialog.test.tsx": 568, - "src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.test.tsx": 870, - "src/renderer/src/components/new-workspace/DirectWorkItemSetupDialog.test.tsx": 5296, - "src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.test.tsx": 2493, - "src/renderer/src/components/new-workspace/ProjectCombobox.dialog-handoff.test.tsx": 1043, + "src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.test.tsx": 870, + "src/renderer/src/components/new-workspace/setup/DirectWorkItemSetupDialog.test.tsx": 5296, + "src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.test.tsx": 2493, + "src/renderer/src/components/new-workspace/project-selection/ProjectCombobox.dialog-handoff.test.tsx": 1043, "src/renderer/src/components/new-workspace/RunTargetCombobox.host-identity.test.tsx": 856, "src/renderer/src/components/new-workspace/SetProjectLocationDialog.host-identity.test.tsx": 1094, - "src/renderer/src/components/new-workspace/SetProjectLocationDialog.test.tsx": 1387, + "src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.test.tsx": 1387, "src/renderer/src/components/new-workspace/SmartWorkspaceNameField-repo-slug-routing.test.ts": 342, - "src/renderer/src/components/new-workspace/smart-workspace-github-direct-link.test.ts": 347, - "src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts": 136, - "src/renderer/src/components/new-workspace/use-jira-source-connection.test.tsx": 278, - "src/renderer/src/components/new-workspace/use-jira-url-source.test.tsx": 419, + "src/renderer/src/components/new-workspace/source-search/smart-workspace-github-direct-link.test.ts": 347, + "src/shared/new-workspace/smart-workspace-source-results.test.ts": 136, + "src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.test.tsx": 278, + "src/renderer/src/components/new-workspace/source-search/use-jira-url-source.test.tsx": 419, "src/renderer/src/components/new-workspace/use-linear-source-connection.test.tsx": 1335, - "src/renderer/src/components/new-workspace/use-recent-project-ids.test.ts": 1730, - "src/renderer/src/components/new-workspace/use-smart-workspace-name-field-foundation.source.test.tsx": 2290, + "src/renderer/src/components/new-workspace/project-selection/use-recent-project-ids.test.ts": 1730, + "src/renderer/src/components/new-workspace/source-search/use-smart-workspace-name-field-foundation.source.test.tsx": 2290, "src/renderer/src/components/new-workspace/work-item-source-selection.test.ts": 1736, "src/renderer/src/components/onboarding/OnboardingLanguageLoading.test.tsx": 2167, "src/renderer/src/components/pet/pet-blob-cache.test.ts": 64, diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.tsx index 7bed3f4f77a..bbc6a2743ad 100644 --- a/src/renderer/src/components/NewWorkspaceComposerCard.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerCard.tsx @@ -12,7 +12,7 @@ import { type AddRemoteHostMode } from '@/components/sidebar/host-admission/ssh/AddRemoteHostDialog' import { lazyWithRetry } from '@/app-shell/startup/lazy-with-retry' -import type * as SetProjectLocationDialogModule from '@/components/new-workspace/SetProjectLocationDialog' +import type * as SetProjectLocationDialogModule from '@/components/new-workspace/project-location/SetProjectLocationDialog' import { unwrapRuntimeRpcResult } from '@/runtime/rpc/calls/runtime-rpc-result' import { withUiConnectTimeout } from '@/ssh/ssh-connect-ui-timeout' import { isSshConnectInFlight, trackSshConnect } from '@/ssh/ssh-connect-in-flight' @@ -25,26 +25,26 @@ import { import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' import type { AddRepoDialogEntryRequest } from '@/components/sidebar/project-admission/dialog/add-repo-dialog-types' import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' -import { NewWorkspaceComposerAdvancedSection } from './new-workspace/NewWorkspaceComposerAdvancedSection' -import { NewWorkspaceComposerAgentSection } from './new-workspace/NewWorkspaceComposerAgentSection' -import { NewWorkspaceComposerFooter } from './new-workspace/NewWorkspaceComposerFooter' -import { NewWorkspaceComposerNameSection } from './new-workspace/NewWorkspaceComposerNameSection' -import { NewWorkspaceComposerProjectSection } from './new-workspace/NewWorkspaceComposerProjectSection' +import { NewWorkspaceComposerAdvancedSection } from './new-workspace/composer/NewWorkspaceComposerAdvancedSection' +import { NewWorkspaceComposerAgentSection } from './new-workspace/composer/NewWorkspaceComposerAgentSection' +import { NewWorkspaceComposerFooter } from './new-workspace/composer/NewWorkspaceComposerFooter' +import { NewWorkspaceComposerNameSection } from './new-workspace/composer/NewWorkspaceComposerNameSection' +import { NewWorkspaceComposerProjectSection } from './new-workspace/composer/NewWorkspaceComposerProjectSection' import { EMPTY_EPHEMERAL_VM_RECIPES, EMPTY_PROJECT_HOST_SETUP_OPTIONS, EMPTY_PROJECT_OPTIONS, - type NeedsProjectHostOption, type NewWorkspaceComposerCardProps -} from './new-workspace/new-workspace-composer-card-props' -import { getSshStatusLabel } from './new-workspace/new-workspace-composer-ssh-status' -import { useNewWorkspaceComposerFileDrop } from './new-workspace/use-new-workspace-composer-file-drop' -import { useComposerFileDragOver } from './new-workspace/use-composer-file-drag-over' +} from './new-workspace/composer/new-workspace-composer-card-props' +import type { NeedsSetupProjectHostOption } from '../lib/workspace/creation/project-host-setup-options' +import { getSshStatusLabel } from './new-workspace/composer/new-workspace-composer-ssh-status' +import { useNewWorkspaceComposerFileDrop } from './new-workspace/composer/use-new-workspace-composer-file-drop' +import { useComposerFileDragOver } from './new-workspace/composer/use-composer-file-drag-over' import { buildDefaultAgentSettingsUpdate } from '../../../shared/agent-launch/choices/default-agent-settings' // Lazy-load the project-location browser outside boot; warming shares this module entry with the click. const loadSetProjectLocationDialog = (): Promise => - import('@/components/new-workspace/SetProjectLocationDialog') + import('@/components/new-workspace/project-location/SetProjectLocationDialog') const SetProjectLocationDialog = lazyWithRetry( () => @@ -119,9 +119,8 @@ export default function NewWorkspaceComposerCard( }, [onNestedDialogOpenChange] ) - const [setLocationOption, setSetLocationOption] = React.useState( - null - ) + const [setLocationOption, setSetLocationOption] = + React.useState(null) // Retain the dialog while its cleared option drives the close animation. const [setLocationDialogMounted, setSetLocationDialogMounted] = React.useState(false) @@ -217,7 +216,7 @@ export default function NewWorkspaceComposerCard( [onAddProjectEntryRequest, openModal] ) const handleSetLocation = React.useCallback( - (option: NeedsProjectHostOption): void => { + (option: NeedsSetupProjectHostOption): void => { setSetLocationDialogMounted(true) setSetLocationOption(option) onNestedDialogOpenChange?.(true) @@ -236,7 +235,7 @@ export default function NewWorkspaceComposerCard( [handleSetLocationClose, onProjectHostSetupChange] ) const handleConnectRunTargetHost = React.useCallback( - async (option: NeedsProjectHostOption): Promise => { + async (option: NeedsSetupProjectHostOption): Promise => { const action = option.connectAction if (!action) { return diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index 2951903acf4..42ec4a66bab 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -1,4 +1,4 @@ -import type { ComposerModalData } from './new-workspace/composer-modal-data' +import type { ComposerModalData } from './new-workspace/composer/composer-modal-data' import { toast } from 'sonner' import { formatWorkspaceCreateError, @@ -8,7 +8,7 @@ import type { AgentPickerDraft, AgentPickerEntry } from '../../../shared/agent-launch/picker/agent-launch-picker' -import { DirectWorkItemSetupDialog } from './new-workspace/DirectWorkItemSetupDialog' +import { DirectWorkItemSetupDialog } from './new-workspace/setup/DirectWorkItemSetupDialog' import { agentChoicePending } from '@/lib/agent-session/launch/inventory/host-chat-program' import type { AgentLaunchSurface } from '@/lib/agent-session/launch/routing/agent-session-launch-plan' import React, { Suspense, useCallback, useEffect, useRef, useState } from 'react' @@ -25,7 +25,7 @@ import NewWorkspaceComposerCard from '@/components/NewWorkspaceComposerCard' import AgentSettingsDialog, { restoreAgentSettingsInvoker } from '@/components/agent/AgentSettingsDialog' -import { useComposerHostedAddProject } from './new-workspace/use-composer-hosted-add-project' +import { useComposerHostedAddProject } from './new-workspace/project-selection/use-composer-hosted-add-project' import { useComposerState } from '@/hooks/useComposerState' import { composerLaunchWorkspace, diff --git a/src/renderer/src/components/new-workspace/github-source-consumers.test.tsx b/src/renderer/src/components/github/github-duplicate-issue-candidates.test.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/github-source-consumers.test.tsx rename to src/renderer/src/components/github/github-duplicate-issue-candidates.test.tsx diff --git a/src/renderer/src/components/jira-issue-assignee-control.tsx b/src/renderer/src/components/jira-issue-assignee-control.tsx index 781f32ca0f9..97f8801d89d 100644 --- a/src/renderer/src/components/jira-issue-assignee-control.tsx +++ b/src/renderer/src/components/jira-issue-assignee-control.tsx @@ -2,7 +2,7 @@ import { useCallback } from 'react' import { Button } from '@/components/ui/button' import { JiraUserPicker } from '@/components/jira-user-picker' import { getJiraSelfUser } from '@/components/jira-self-user' -import { useJiraSourceConnection } from '@/components/new-workspace/use-jira-source-connection' +import { useJiraSourceConnection } from '@/components/new-workspace/source-search/use-jira-source-connection' import { useAppStore } from '@/store' import { compareBaseSensitivityLocaleText } from '../../../shared/locale-text-collators' import { jiraListAssignableUsersForTarget } from '@/runtime/jira/runtime-jira-user-fields-client' diff --git a/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx b/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx index 4a7880e3107..fbcfcd4880a 100644 --- a/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx +++ b/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx @@ -1,7 +1,7 @@ import { useMemo } from 'react' import { Folder, FolderTree, GitBranch, Monitor } from 'lucide-react' import { RepoIconGlyph } from '@/components/repo/repo-icon' -import { ProjectOptionDetail } from '@/components/new-workspace/ProjectComboboxRow' +import { ProjectOptionDetail } from '@/components/new-workspace/project-selection/ProjectComboboxRow' import { WorktreeHostContextBadge } from '@/components/sidebar/workspace-card/host/WorktreeHostContextBadge' import { useSidebarHostScopeOptions } from '@/components/sidebar/worktree-list/controls/use-sidebar-host-scope-options' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/native-chat/attachments/intake/native-chat-composer-drop-scope.test.tsx b/src/renderer/src/components/native-chat/attachments/intake/native-chat-composer-drop-scope.test.tsx index d9c3e97229d..ffa39d74881 100644 --- a/src/renderer/src/components/native-chat/attachments/intake/native-chat-composer-drop-scope.test.tsx +++ b/src/renderer/src/components/native-chat/attachments/intake/native-chat-composer-drop-scope.test.tsx @@ -9,7 +9,7 @@ import type { NativeChatComposerInput } from '../../composer/editor/native-chat- import { NativeChatPromptEditor } from '../../composer/editor/NativeChatPromptEditor' import { useNativeChatFileDrops } from './use-native-chat-file-drops' import { NativeChatPaneFileDropSurface } from './NativeChatPaneFileDropSurface' -import '../../../new-workspace/use-new-workspace-composer-file-drop' +import '../../../new-workspace/composer/use-new-workspace-composer-file-drop' import { NativeChatImageAttachmentPreview } from '../chips/NativeChatImageAttachmentPreview' import '../../../editor/document-images/useLocalImageSrc' import { resetLocalImageCacheState as resetLocalImageSrcStateForTests } from '../../../editor/document-images/local-image-src-cache' @@ -221,21 +221,6 @@ describe('native chat composer drop scoping', () => { expect(intake.stat).not.toHaveBeenCalled() }) - it('notices an OS drop whose owner changes while checking the files', async () => { - intake.stat.mockImplementation(async () => { - intake.owner = { kind: 'remote' } - }) - const view = render() - - await dropTwoImages(view.container.querySelector('[data-pane="chat-a"] .ProseMirror')!) - await settleAttachments() - - expect(view.container.querySelector('[data-notice="chat-a"]')?.textContent).toBe( - 'This workspace changed hosts while attaching — drop the files again.' - ) - expect(readNativeChatAttachmentCache('chat-a')).toEqual([]) - }) - it('attaches only to the dropped pane and leaves a hidden pane clean on remount', async () => { const view = render( <> diff --git a/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.fixture.tsx b/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.fixture.tsx index 9a6d38bda2f..c4ecfc138e7 100644 --- a/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.fixture.tsx +++ b/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.fixture.tsx @@ -16,7 +16,7 @@ import type { LinearIssue } from '../../../../shared/linear/issue-types' import type { LinearConnectionStatus } from '../../../../shared/linear/workspace-types' import type { Repo } from '../../../../shared/repo-types' import SmartWorkspaceNameField from './SmartWorkspaceNameField' -import type { SmartWorkspaceNameFieldProps } from './smart-workspace-name-field-model' +import type { SmartWorkspaceNameFieldProps } from './name-field/smart-workspace-name-field-model' const repo: Repo = { id: 'repo-orca', diff --git a/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx b/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx index 2f5456b6dba..9357baf49db 100644 --- a/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx +++ b/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx @@ -1,7 +1,7 @@ import React from 'react' -import { renderSmartWorkspaceNameField } from './smart-workspace-name-field-surface' -import type { SmartWorkspaceNameFieldProps } from './smart-workspace-name-field-model' -import { useSmartWorkspaceNameFieldController } from './use-smart-workspace-name-field-controller' +import { renderSmartWorkspaceNameField } from './name-field/smart-workspace-name-field-surface' +import type { SmartWorkspaceNameFieldProps } from './name-field/smart-workspace-name-field-model' +import { useSmartWorkspaceNameFieldController } from './name-field/use-smart-workspace-name-field-controller' import { useTranslate } from '../../i18n/use-translate' export default function SmartWorkspaceNameField( diff --git a/src/renderer/src/components/new-workspace/ComposerBaseRefPicker.tsx b/src/renderer/src/components/new-workspace/branch-selection/ComposerBaseRefPicker.tsx similarity index 96% rename from src/renderer/src/components/new-workspace/ComposerBaseRefPicker.tsx rename to src/renderer/src/components/new-workspace/branch-selection/ComposerBaseRefPicker.tsx index a5229577277..753925bf5d2 100644 --- a/src/renderer/src/components/new-workspace/ComposerBaseRefPicker.tsx +++ b/src/renderer/src/components/new-workspace/branch-selection/ComposerBaseRefPicker.tsx @@ -3,7 +3,7 @@ import { CreateFromPicker } from '@/components/repo/CreateFromPicker' import { useAppStore } from '@/store' import { useRepoMap } from '@/store/repos/use-repository-catalog' import { useWorktreesForRepo } from '@/store/slices/worktrees/listing/use-worktree-catalog' -import { getRepoExecutionHostId } from '../../../../shared/execution-host' +import { getRepoExecutionHostId } from '../../../../../shared/execution-host' import { toast } from 'sonner' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/new-workspace/ComposerBranchChoice.tsx b/src/renderer/src/components/new-workspace/branch-selection/ComposerBranchChoice.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/ComposerBranchChoice.tsx rename to src/renderer/src/components/new-workspace/branch-selection/ComposerBranchChoice.tsx diff --git a/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.fixture.tsx b/src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.fixture.tsx similarity index 89% rename from src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.fixture.tsx rename to src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.fixture.tsx index 7191c1cb52e..f9d5fb85dc4 100644 --- a/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.fixture.tsx +++ b/src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.fixture.tsx @@ -1,6 +1,6 @@ -import { defineFixture } from '../../component-fixtures/component-fixture' -import type { Repo } from '../../../../shared/repo-types' -import type { Worktree } from '../../../../shared/worktree/types' +import { defineFixture } from '../../../component-fixtures/component-fixture' +import type { Repo } from '../../../../../shared/repo-types' +import type { Worktree } from '../../../../../shared/worktree/types' import { ComposerParentWorktreePicker } from './ComposerParentWorktreePicker' function repo(id: string, displayName: string, executionHostId?: Repo['executionHostId']): Repo { diff --git a/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.test.tsx b/src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.test.tsx similarity index 96% rename from src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.test.tsx rename to src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.test.tsx index 5fe6028bf60..80b98f5f36d 100644 --- a/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.test.tsx +++ b/src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.test.tsx @@ -3,10 +3,13 @@ import type React from 'react' import { cleanup, fireEvent, render } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import type { WorkspaceLineage, WorktreeLineage } from '../../../../shared/worktree/lineage-types' -import type { Worktree } from '../../../../shared/worktree/types' -import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../../shared/workspace-scope' +import type { Repo } from '../../../../../shared/repo-types' +import type { + WorkspaceLineage, + WorktreeLineage +} from '../../../../../shared/worktree/lineage-types' +import type { Worktree } from '../../../../../shared/worktree/types' +import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../../../shared/workspace-scope' type FakeStoreState = { worktreesByRepo: Record diff --git a/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx b/src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.tsx similarity index 92% rename from src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx rename to src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.tsx index 47c245cc8fb..cb662a32ec6 100644 --- a/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx +++ b/src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.tsx @@ -1,4 +1,4 @@ -import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility' +import { isWorktreeRetiredByRemoval } from '../../../../../shared/worktree/removal-visibility' import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import { Check, ChevronsUpDown, GitBranch } from 'lucide-react' @@ -17,7 +17,7 @@ import { import { compareWorktreeDisplayName } from '@/lib/workspace/display/worktree-display-name-order' import '@/components/sidebar/workspace-card/activity/worktree-card-empty-inputs' import { branchDisplayName } from '@/components/sidebar/workspace-card/identity/worktree-branch-display' -import { getCyclicProjectedWorktreeLineageIds } from '../../../../shared/sidebar-list/worktree-lineage-projection' +import { getCyclicProjectedWorktreeLineageIds } from '../../../../../shared/sidebar-list/worktree-lineage-projection' import { clampWorktreeParentPickerIndex, filterWorktreeParentCandidates @@ -31,19 +31,21 @@ import { getLineageChildrenByParentId, getLineageChildWorktree } from '@/components/right-sidebar/folder-workspace-attached-worktrees' -import { COMBOBOX_POPOVER_SURFACE } from './type-ahead-combobox-styles' +import { COMBOBOX_POPOVER_SURFACE } from '../type-ahead/type-ahead-combobox-styles' import { sharesWorktreeLineageBoundary, type WorktreeLineageBoundary -} from '../../../../shared/resolved-worktree-lineage' -import { folderWorkspaceKey } from '../../../../shared/workspace-scope' -import type { WorkspaceLineage, WorktreeLineage } from '../../../../shared/worktree/lineage-types' -import type { Worktree } from '../../../../shared/worktree/types' +} from '../../../../../shared/resolved-worktree-lineage' +import { folderWorkspaceKey } from '../../../../../shared/workspace-scope' +import type { + WorkspaceLineage, + WorktreeLineage +} from '../../../../../shared/worktree/lineage-types' +import type { Worktree } from '../../../../../shared/worktree/types' import { getRepoExecutionHostId, - getWorktreeExecutionHostId, - type ExecutionHostId -} from '../../../../shared/execution-host' + getWorktreeExecutionHostId +} from '../../../../../shared/execution-host' import { useRepoMap } from '@/store/repos/use-repository-catalog' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' import { isCrossStoreCreateParent } from '@/components/sidebar/workspace-actions/parenting/worktree-parent-candidates' @@ -51,32 +53,16 @@ import { ParentMachineBadge } from '@/components/sidebar/workspace-actions/paren import { getWorktreeHostIdentity, isWorktreeHostIdentity -} from '../../../../shared/worktree/host-qualified-identity' +} from '../../../../../shared/worktree/host-qualified-identity' +import type { + ComposerParentWorktreePickerProps, + ParentWorktreeCandidateListProps +} from './composer-parent-worktree-picker-props' /** 20px text leading plus py-2 matches the explicit row height. */ const NO_PARENT_ROW_HEIGHT = 36 const NO_PARENT_ROW_KEY = 'no-parent' -type ComposerParentWorktreePickerProps = { - repoId: string - /** The child's destination host; parents on it nest as usual, others by a cross-machine link. */ - executionHostId?: ExecutionHostId | null - projectId?: string | null - value: string | null - onChange: (id: string | null) => void - disabled?: boolean - /** When the active workspace is a folder, restrict candidates to that folder's subtree. */ - activeFolderWorkspaceId?: string | null -} - -type ParentWorktreeCandidateListProps = Omit< - ComposerParentWorktreePickerProps, - 'onChange' | 'disabled' | 'activeFolderWorkspaceId' -> & { - activeFolderWorkspaceId: string | null - onSelect: (id: string | null) => void -} - /** Pick nesting without changing the base branch; enumerate only in Radix’s open-only list, leaving closed state a string selector. */ function ComposerParentWorktreePickerImpl({ repoId, diff --git a/src/renderer/src/components/new-workspace/base-ref-picker-visibility.ts b/src/renderer/src/components/new-workspace/branch-selection/base-ref-picker-visibility.ts similarity index 83% rename from src/renderer/src/components/new-workspace/base-ref-picker-visibility.ts rename to src/renderer/src/components/new-workspace/branch-selection/base-ref-picker-visibility.ts index 34e3970a928..aebe2f650c0 100644 --- a/src/renderer/src/components/new-workspace/base-ref-picker-visibility.ts +++ b/src/renderer/src/components/new-workspace/branch-selection/base-ref-picker-visibility.ts @@ -1,5 +1,5 @@ -import type { SmartWorkspaceNameSelection } from '@/components/new-workspace/smart-workspace-name-field-model' -import type { SmartNameMode } from '../../../../shared/new-workspace/smart-workspace-source-results' +import type { SmartWorkspaceNameSelection } from '@/components/new-workspace/name-field/smart-workspace-name-field-model' +import type { SmartNameMode } from '../../../../../shared/new-workspace/smart-workspace-source-results' /** Naming source and base ref are independent, except PR/MR/branch selections already carry their own base. */ export function shouldShowComposerBaseRefPicker(args: { diff --git a/src/renderer/src/components/new-workspace/branch-selection/composer-parent-worktree-picker-props.ts b/src/renderer/src/components/new-workspace/branch-selection/composer-parent-worktree-picker-props.ts new file mode 100644 index 00000000000..44783ac234c --- /dev/null +++ b/src/renderer/src/components/new-workspace/branch-selection/composer-parent-worktree-picker-props.ts @@ -0,0 +1,21 @@ +import type { ExecutionHostId } from '../../../../../shared/execution-host' + +export type ComposerParentWorktreePickerProps = { + repoId: string + /** The child's destination host; parents on it nest as usual, others by a cross-machine link. */ + executionHostId?: ExecutionHostId | null + projectId?: string | null + value: string | null + onChange: (id: string | null) => void + disabled?: boolean + /** When the active workspace is a folder, restrict candidates to that folder's subtree. */ + activeFolderWorkspaceId?: string | null +} + +export type ParentWorktreeCandidateListProps = Omit< + ComposerParentWorktreePickerProps, + 'onChange' | 'disabled' | 'activeFolderWorkspaceId' +> & { + activeFolderWorkspaceId: string | null + onSelect: (id: string | null) => void +} diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerAdvancedSection.tsx b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerAdvancedSection.tsx similarity index 97% rename from src/renderer/src/components/new-workspace/NewWorkspaceComposerAdvancedSection.tsx rename to src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerAdvancedSection.tsx index cf5053b0186..cd6ed571e5b 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerAdvancedSection.tsx +++ b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerAdvancedSection.tsx @@ -1,10 +1,10 @@ import React from 'react' -import { WorkspaceSetupSection } from './WorkspaceSetupSection' -import { selectWorkspaceSetupCopy } from './workspace-setup-section-model' +import { WorkspaceSetupSection } from '../setup/WorkspaceSetupSection' +import { selectWorkspaceSetupCopy } from '../setup/workspace-setup-section-model' import { getComposerWorkspaceSetupLabels, getComposerSetupStartupLabel -} from './workspace-setup-composer-copy' +} from '../setup/workspace-setup-composer-copy' import { toast } from 'sonner' import SparseCheckoutPresetSelect from '@/components/sparse/SparseCheckoutPresetSelect' import { cn } from '@/lib/class-names' @@ -16,7 +16,7 @@ import { } from '@/lib/text-input/paste/text-control-paste' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' -import { ComposerParentWorktreePicker } from './ComposerParentWorktreePicker' +import { ComposerParentWorktreePicker } from '../branch-selection/ComposerParentWorktreePicker' import type { NewWorkspaceComposerCardProps } from './new-workspace-composer-card-props' type NewWorkspaceComposerAdvancedSectionProps = Pick< diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerAgentSection.tsx b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerAgentSection.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/NewWorkspaceComposerAgentSection.tsx rename to src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerAgentSection.tsx diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerFooter.tsx b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerFooter.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/NewWorkspaceComposerFooter.tsx rename to src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerFooter.tsx diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.fixture.tsx b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.fixture.tsx similarity index 93% rename from src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.fixture.tsx rename to src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.fixture.tsx index e489aa76369..518a4ba5a2d 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.fixture.tsx +++ b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.fixture.tsx @@ -1,7 +1,7 @@ import { useState } from 'react' -import { defineFixture } from '../../component-fixtures/component-fixture' +import { defineFixture } from '../../../component-fixtures/component-fixture' import { NewWorkspaceComposerNameSection } from './NewWorkspaceComposerNameSection' -import { buildWorkspaceSourceSelection } from '../../../../shared/new-workspace/workspace-source' +import { buildWorkspaceSourceSelection } from '../../../../../shared/new-workspace/workspace-source' function BranchReusePreview({ busy = false, diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.test.tsx b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.test.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.test.tsx rename to src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.test.tsx diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.tsx b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.tsx similarity index 96% rename from src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.tsx rename to src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.tsx index 9cd7c265664..b47fca97545 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.tsx +++ b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.tsx @@ -3,9 +3,9 @@ import { AlertTriangle } from 'lucide-react' import SmartWorkspaceNameField from '@/components/new-workspace/SmartWorkspaceNameField' import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' -import { shouldShowComposerBaseRefPicker } from './base-ref-picker-visibility' -import { ComposerBaseRefPicker } from './ComposerBaseRefPicker' -import { ComposerBranchChoice } from './ComposerBranchChoice' +import { shouldShowComposerBaseRefPicker } from '../branch-selection/base-ref-picker-visibility' +import { ComposerBaseRefPicker } from '../branch-selection/ComposerBaseRefPicker' +import { ComposerBranchChoice } from '../branch-selection/ComposerBranchChoice' import type { NewWorkspaceComposerCardProps } from './new-workspace-composer-card-props' type NewWorkspaceComposerNameSectionProps = Pick< diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerProjectSection.fixture.tsx similarity index 98% rename from src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx rename to src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerProjectSection.fixture.tsx index 974ea83f78b..3384bd557c1 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.fixture.tsx +++ b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerProjectSection.fixture.tsx @@ -1,5 +1,5 @@ import { useState } from 'react' -import { defineFixture } from '../../component-fixtures/component-fixture' +import { defineFixture } from '../../../component-fixtures/component-fixture' import type { NewWorkspaceProjectOption } from '@/lib/workspace/creation/new-workspace-project-options' import { getProjectHostSetupSelectionKey, diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerProjectSection.tsx similarity index 92% rename from src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx rename to src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerProjectSection.tsx index b564499c21a..b84320b08b6 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx +++ b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerProjectSection.tsx @@ -5,19 +5,16 @@ import type { AddRepoDialogEntryRequest } from '@/components/sidebar/project-adm import { AddProjectMenu } from '@/components/sidebar/project-admission/menu/AddProjectMenu' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import ProjectCombobox, { - type ProjectComboboxAddProjectMenu -} from '@/components/new-workspace/ProjectCombobox' -import RunTargetCombobox from '@/components/new-workspace/RunTargetCombobox' +import ProjectCombobox from '@/components/new-workspace/project-selection/ProjectCombobox' +import type { ProjectComboboxAddProjectMenu } from '../project-selection/ProjectComboboxAddProjectOption' +import RunTargetCombobox from '@/components/new-workspace/run-target/RunTargetCombobox' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/class-names' import { getSelectedNewWorkspaceProjectOptionId } from '@/lib/workspace/creation/new-workspace-project-options' -import { resolveComposerAddProjectDefaultHostId } from './composer-add-project-default-host' -import type { - EphemeralVmRecipeOption, - NeedsProjectHostOption, - NewWorkspaceComposerCardProps -} from './new-workspace-composer-card-props' +import { resolveComposerAddProjectDefaultHostId } from '../project-selection/composer-add-project-default-host' +import type { EphemeralVmRecipeOption } from '../run-target/run-target-options' +import type { NeedsSetupProjectHostOption } from '../../../lib/workspace/creation/project-host-setup-options' +import type { NewWorkspaceComposerCardProps } from './new-workspace-composer-card-props' import { EMPTY_PROJECT_OPTIONS } from './new-workspace-composer-card-props' type NewWorkspaceComposerProjectSectionProps = Pick< @@ -52,8 +49,8 @@ type NewWorkspaceComposerProjectSectionProps = Pick< handleProjectHostSetupChange: (setupId: string) => void handleAddSshHost: () => void handleAddRemoteServer: () => void - handleConnectRunTargetHost: (option: NeedsProjectHostOption) => Promise - handleSetLocation: (option: NeedsProjectHostOption) => void + handleConnectRunTargetHost: (option: NeedsSetupProjectHostOption) => Promise + handleSetLocation: (option: NeedsSetupProjectHostOption) => void sshStatusLabel: string connectButtonLabel: string selectedProjectName: string diff --git a/src/renderer/src/components/new-workspace/composer-modal-data.ts b/src/renderer/src/components/new-workspace/composer/composer-modal-data.ts similarity index 75% rename from src/renderer/src/components/new-workspace/composer-modal-data.ts rename to src/renderer/src/components/new-workspace/composer/composer-modal-data.ts index 65f375110b3..5beb130b5e4 100644 --- a/src/renderer/src/components/new-workspace/composer-modal-data.ts +++ b/src/renderer/src/components/new-workspace/composer/composer-modal-data.ts @@ -1,15 +1,15 @@ import type { AgentPickerDraft, AgentPickerEntry -} from '../../../../shared/agent-launch/picker/agent-launch-picker' +} from '../../../../../shared/agent-launch/picker/agent-launch-picker' import type { AgentLaunchSurface } from '@/lib/agent-session/launch/routing/agent-session-launch-plan' import type { DirectWorkItemSetupRequest } from '@/lib/workspace/creation/work-item/direct-work-item-setup' import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' -import type { GitHubWorkItem } from '../../../../shared/github/work-items/work-item-types' -import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import type { WorkspaceSource as WorkspaceCreateTelemetrySource } from '../../../../shared/workspace-source' -import type { WorkspaceStatus } from '../../../../shared/worktree/types' -import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' +import type { GitHubWorkItem } from '../../../../../shared/github/work-items/work-item-types' +import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' +import type { WorkspaceSource as WorkspaceCreateTelemetrySource } from '../../../../../shared/workspace-source' +import type { WorkspaceStatus } from '../../../../../shared/worktree/types' +import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context' import type { WorkspaceCreationTargetHint } from '@/lib/workspace/creation/project-host-workspace-target' export type ComposerModalData = { diff --git a/src/renderer/src/components/new-workspace/new-workspace-composer-card-props.ts b/src/renderer/src/components/new-workspace/composer/new-workspace-composer-card-props.ts similarity index 78% rename from src/renderer/src/components/new-workspace/new-workspace-composer-card-props.ts rename to src/renderer/src/components/new-workspace/composer/new-workspace-composer-card-props.ts index b21ea6202a2..da3c61d66b2 100644 --- a/src/renderer/src/components/new-workspace/new-workspace-composer-card-props.ts +++ b/src/renderer/src/components/new-workspace/composer/new-workspace-composer-card-props.ts @@ -1,34 +1,32 @@ import type { AgentPickerDraft, AgentPickerEntry -} from '../../../../shared/agent-launch/picker/agent-launch-picker' +} from '../../../../../shared/agent-launch/picker/agent-launch-picker' import type { AgentComboboxSurfaceRows } from '@/components/agent/agent-combobox-surface-items' import type { ComposerAgentRows } from '@/hooks/composer-state/composer-agent-rows-target' import type RepoCombobox from '@/components/repo/RepoCombobox' import type { NewWorkspaceProjectOption } from '@/lib/workspace/creation/new-workspace-project-options' -import type { - NeedsSetupProjectHostOption, - ProjectHostSetupOption -} from '@/lib/workspace/creation/project-host-setup-options' -import type { SetupConfig } from '../../../../shared/orca-hook-setup-config' +import type { ProjectHostSetupOption } from '@/lib/workspace/creation/project-host-setup-options' +import type { SetupConfig } from '../../../../../shared/orca-hook-setup-config' import type { WorkspaceCreateErrorDisplay } from '@/lib/workspace/creation/workspace-create-error-format' -import type { SmartNameMode } from '../../../../shared/new-workspace/smart-workspace-source-results' -import type SmartWorkspaceNameField from './SmartWorkspaceNameField' -import type { SmartWorkspaceNameSelection } from '@/components/new-workspace/smart-workspace-name-field-model' -import type { GitHubWorkItem } from '../../../../shared/github/work-items/work-item-types' -import type { GitLabWorkItem } from '../../../../shared/gitlab-types' -import type { JiraIssue } from '../../../../shared/jira/jira-types' -import type { LinearIssue } from '../../../../shared/linear/issue-types' -import type { OrcaHooks, SetupAgentStartupPolicy } from '../../../../shared/orca-yaml-hook-types' -import type { SparsePreset } from '../../../../shared/worktree/create-types' -import type { SshConnectionStatus } from '../../../../shared/ssh-types' -import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' +import type { SmartNameMode } from '../../../../../shared/new-workspace/smart-workspace-source-results' + +import type { SmartWorkspaceNameSelection } from '@/components/new-workspace/name-field/smart-workspace-name-field-model' +import type { GitHubWorkItem } from '../../../../../shared/github/work-items/work-item-types' +import type { GitLabWorkItem } from '../../../../../shared/gitlab-types' +import type { JiraIssue } from '../../../../../shared/jira/jira-types' +import type { LinearIssue } from '../../../../../shared/linear/issue-types' +import type { SetupAgentStartupPolicy } from '../../../../../shared/orca-yaml-hook-types' +import type { SparsePreset } from '../../../../../shared/worktree/create-types' +import type { SshConnectionStatus } from '../../../../../shared/ssh-types' +import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context' import type { AddRepoDialogEntryRequest } from '@/components/sidebar/project-admission/dialog/add-repo-dialog-types' -import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' +import type { ExecutionHostId } from '../../../../../shared/execution-host' + +import type { EphemeralVmRecipeOption } from '../run-target/run-target-options' export type RepoOption = React.ComponentProps['repos'][number] -export type EphemeralVmRecipeOption = NonNullable[number] export const EMPTY_PROJECT_OPTIONS: NewWorkspaceProjectOption[] = [] export const EMPTY_PROJECT_HOST_SETUP_OPTIONS: ProjectHostSetupOption[] = [] @@ -149,7 +147,3 @@ export type NewWorkspaceComposerCardProps = { onAddProjectEntryRequest?: (request: AddRepoDialogEntryRequest) => void onNestedDialogOpenChange?: (open: boolean) => void } - -export type NeedsProjectHostOption = NeedsSetupProjectHostOption -export type ReadyProjectHostOption = Extract -export type SmartWorkspaceNameFieldProps = React.ComponentProps diff --git a/src/renderer/src/components/new-workspace/new-workspace-composer-ssh-status.ts b/src/renderer/src/components/new-workspace/composer/new-workspace-composer-ssh-status.ts similarity index 94% rename from src/renderer/src/components/new-workspace/new-workspace-composer-ssh-status.ts rename to src/renderer/src/components/new-workspace/composer/new-workspace-composer-ssh-status.ts index 08a8375e4d4..8459f54a8b7 100644 --- a/src/renderer/src/components/new-workspace/new-workspace-composer-ssh-status.ts +++ b/src/renderer/src/components/new-workspace/composer/new-workspace-composer-ssh-status.ts @@ -1,5 +1,5 @@ import { translate } from '@/i18n/i18n' -import type { SshConnectionStatus } from '../../../../shared/ssh-types' +import type { SshConnectionStatus } from '../../../../../shared/ssh-types' const SSH_STATUS_LABELS: Partial> = { get disconnected() { diff --git a/src/renderer/src/components/new-workspace/use-composer-file-drag-over.ts b/src/renderer/src/components/new-workspace/composer/use-composer-file-drag-over.ts similarity index 100% rename from src/renderer/src/components/new-workspace/use-composer-file-drag-over.ts rename to src/renderer/src/components/new-workspace/composer/use-composer-file-drag-over.ts diff --git a/src/renderer/src/components/new-workspace/use-new-workspace-composer-file-drop.ts b/src/renderer/src/components/new-workspace/composer/use-new-workspace-composer-file-drop.ts similarity index 98% rename from src/renderer/src/components/new-workspace/use-new-workspace-composer-file-drop.ts rename to src/renderer/src/components/new-workspace/composer/use-new-workspace-composer-file-drop.ts index e348669eef6..76f36b3512f 100644 --- a/src/renderer/src/components/new-workspace/use-new-workspace-composer-file-drop.ts +++ b/src/renderer/src/components/new-workspace/composer/use-new-workspace-composer-file-drop.ts @@ -4,7 +4,7 @@ import { createOsFileDropSequence, useOsFileDropOwner } from '@/hooks/use-os-fil import { getNativeFileDropRejectionMessage } from '@/lib/files/drop/native-file-drop-rejection-message' import { useMountedRef } from '@/hooks/useMountedRef' import { useAppStore } from '@/store' -import { parseExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' +import { parseExecutionHostId, type ExecutionHostId } from '../../../../../shared/execution-host' type Args = { projectPath?: string | null diff --git a/src/renderer/src/components/new-workspace/smart-workspace-cross-repo-dialog.tsx b/src/renderer/src/components/new-workspace/name-field/smart-workspace-cross-repo-dialog.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/smart-workspace-cross-repo-dialog.tsx rename to src/renderer/src/components/new-workspace/name-field/smart-workspace-cross-repo-dialog.tsx diff --git a/src/renderer/src/components/new-workspace/smart-workspace-name-field-copy.ts b/src/renderer/src/components/new-workspace/name-field/smart-workspace-name-field-copy.ts similarity index 97% rename from src/renderer/src/components/new-workspace/smart-workspace-name-field-copy.ts rename to src/renderer/src/components/new-workspace/name-field/smart-workspace-name-field-copy.ts index f1386cf2ebb..4d7c6415094 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-name-field-copy.ts +++ b/src/renderer/src/components/new-workspace/name-field/smart-workspace-name-field-copy.ts @@ -1,6 +1,6 @@ import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import type { SmartNameMode } from '../../../../shared/new-workspace/smart-workspace-source-results' +import type { SmartNameMode } from '../../../../../shared/new-workspace/smart-workspace-source-results' export function getSmartWorkspaceNameFieldCopy( { diff --git a/src/renderer/src/components/new-workspace/smart-workspace-name-field-model.ts b/src/renderer/src/components/new-workspace/name-field/smart-workspace-name-field-model.ts similarity index 84% rename from src/renderer/src/components/new-workspace/smart-workspace-name-field-model.ts rename to src/renderer/src/components/new-workspace/name-field/smart-workspace-name-field-model.ts index ef146f2b404..4d0a08bbc27 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-name-field-model.ts +++ b/src/renderer/src/components/new-workspace/name-field/smart-workspace-name-field-model.ts @@ -1,16 +1,16 @@ import type React from 'react' import type { useAppStore } from '@/store' -import type { parseGitHubIssueOrPRLink } from '../../../../shared/github/repositories/links' -import type { GitHubWorkItem } from '../../../../shared/github/work-items/work-item-types' -import type { GitLabWorkItem } from '../../../../shared/gitlab-types' -import type { JiraIssue, JiraSite } from '../../../../shared/jira/jira-types' -import type { LinearIssue } from '../../../../shared/linear/issue-types' -import type { BaseRefSearchResult } from '../../../../shared/repo-types' -import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' +import type { parseGitHubIssueOrPRLink } from '../../../../../shared/github/repositories/links' +import type { GitHubWorkItem } from '../../../../../shared/github/work-items/work-item-types' +import type { GitLabWorkItem } from '../../../../../shared/gitlab-types' +import type { JiraIssue, JiraSite } from '../../../../../shared/jira/jira-types' +import type { LinearIssue } from '../../../../../shared/linear/issue-types' +import type { BaseRefSearchResult } from '../../../../../shared/repo-types' +import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context' import type { SmartNameMode, SmartWorkspaceSourceRow -} from '../../../../shared/new-workspace/smart-workspace-source-results' +} from '../../../../../shared/new-workspace/smart-workspace-source-results' export type RepoOption = ReturnType['repos'][number] diff --git a/src/renderer/src/components/new-workspace/smart-workspace-name-field-surface.tsx b/src/renderer/src/components/new-workspace/name-field/smart-workspace-name-field-surface.tsx similarity index 96% rename from src/renderer/src/components/new-workspace/smart-workspace-name-field-surface.tsx rename to src/renderer/src/components/new-workspace/name-field/smart-workspace-name-field-surface.tsx index ba3ddbab71a..1574e9c44a5 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-name-field-surface.tsx +++ b/src/renderer/src/components/new-workspace/name-field/smart-workspace-name-field-surface.tsx @@ -2,7 +2,7 @@ import React from 'react' import { Button } from '@/components/ui/button' import { Command } from '@/components/ui/command' import { Popover, PopoverAnchor } from '@/components/ui/popover' -import { SmartWorkspaceSourceTabs } from './SmartWorkspaceSourceTabs' +import { SmartWorkspaceSourceTabs } from '../source-search/SmartWorkspaceSourceTabs' import { cn } from '@/lib/class-names' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' @@ -10,7 +10,7 @@ import { WorkspaceEmojiSuggestionPopover } from '@/components/workspace-emoji/Wo import { renderSmartWorkspaceCrossRepoDialog } from './smart-workspace-cross-repo-dialog' import { renderSmartWorkspaceNameInput } from './smart-workspace-name-input-surface' import { renderSmartWorkspaceSourceResults } from './smart-workspace-source-results-surface' -import { getJiraSourceStatusMessage } from './jira-source-status-message' +import { getJiraSourceStatusMessage } from '../source-search/jira-source-status-message' import type { SmartWorkspaceNameFieldController } from './use-smart-workspace-name-field-controller' export function renderSmartWorkspaceNameField( diff --git a/src/renderer/src/components/new-workspace/smart-workspace-name-input-surface.tsx b/src/renderer/src/components/new-workspace/name-field/smart-workspace-name-input-surface.tsx similarity index 97% rename from src/renderer/src/components/new-workspace/smart-workspace-name-input-surface.tsx rename to src/renderer/src/components/new-workspace/name-field/smart-workspace-name-input-surface.tsx index 9158baa9aa1..20faceabe68 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-name-input-surface.tsx +++ b/src/renderer/src/components/new-workspace/name-field/smart-workspace-name-input-surface.tsx @@ -5,14 +5,14 @@ import { Input } from '@/components/ui/input' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { WorkspaceEmojiPickerButton } from '@/components/workspace-emoji/WorkspaceEmojiPickerButton' import { isImeCompositionKeyDown } from '@/lib/text-input/ime/ime-composition-keyboard-event' -import { isBlockingJiraUrlIntent } from '../../../../shared/new-workspace/smart-workspace-source-results' -import { isBlockingLinearUrlIntent } from '../../../../shared/new-workspace/smart-workspace-linear-intent' +import { isBlockingJiraUrlIntent } from '../../../../../shared/new-workspace/smart-workspace-source-results' +import { isBlockingLinearUrlIntent } from '../../../../../shared/new-workspace/smart-workspace-linear-intent' import { isComposerFieldToFieldFocus } from './smart-workspace-source-popover-focus' import { replaceCompletedWorkspaceEmojiShortcode } from '@/lib/workspace/display/workspace-emoji-shortcodes' import { cn } from '@/lib/class-names' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import { SelectionIcon } from './smart-workspace-source-row-content' +import { SelectionIcon } from '../source-search/smart-workspace-source-row-content' import type { SmartWorkspaceNameFieldController } from './use-smart-workspace-name-field-controller' export function renderSmartWorkspaceNameInput( diff --git a/src/renderer/src/components/new-workspace/smart-workspace-source-popover-focus.ts b/src/renderer/src/components/new-workspace/name-field/smart-workspace-source-popover-focus.ts similarity index 100% rename from src/renderer/src/components/new-workspace/smart-workspace-source-popover-focus.ts rename to src/renderer/src/components/new-workspace/name-field/smart-workspace-source-popover-focus.ts diff --git a/src/renderer/src/components/new-workspace/smart-workspace-source-results-surface.tsx b/src/renderer/src/components/new-workspace/name-field/smart-workspace-source-results-surface.tsx similarity index 93% rename from src/renderer/src/components/new-workspace/smart-workspace-source-results-surface.tsx rename to src/renderer/src/components/new-workspace/name-field/smart-workspace-source-results-surface.tsx index a34c48d7e9a..b48ccd09437 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-source-results-surface.tsx +++ b/src/renderer/src/components/new-workspace/name-field/smart-workspace-source-results-surface.tsx @@ -2,9 +2,9 @@ import React from 'react' import { PopoverContent } from '@/components/ui/popover' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import { JiraProjectPicker } from '../jira-project-picker' -import { LinearWorkspacePicker } from '../linear-workspace-picker' -import { SmartWorkspaceSourceResultList } from './SmartWorkspaceSourceResultList' +import { JiraProjectPicker } from '../../jira-project-picker' +import { LinearWorkspacePicker } from '../../linear-workspace-picker' +import { SmartWorkspaceSourceResultList } from '../source-search/SmartWorkspaceSourceResultList' import type { SmartWorkspaceNameFieldController } from './use-smart-workspace-name-field-controller' export function renderSmartWorkspaceSourceResults( diff --git a/src/renderer/src/components/new-workspace/use-smart-workspace-field-focus-controls.ts b/src/renderer/src/components/new-workspace/name-field/use-smart-workspace-field-focus-controls.ts similarity index 97% rename from src/renderer/src/components/new-workspace/use-smart-workspace-field-focus-controls.ts rename to src/renderer/src/components/new-workspace/name-field/use-smart-workspace-field-focus-controls.ts index 011244b4bf3..21043a591a2 100644 --- a/src/renderer/src/components/new-workspace/use-smart-workspace-field-focus-controls.ts +++ b/src/renderer/src/components/new-workspace/name-field/use-smart-workspace-field-focus-controls.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react' import type { SmartWorkspaceNameFieldProps } from './smart-workspace-name-field-model' -import type { SmartNameMode } from '../../../../shared/new-workspace/smart-workspace-source-results' +import type { SmartNameMode } from '../../../../../shared/new-workspace/smart-workspace-source-results' type FieldState = { mode: SmartNameMode; crossRepoPrompt?: unknown } diff --git a/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-actions.ts b/src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-actions.ts similarity index 92% rename from src/renderer/src/components/new-workspace/use-smart-workspace-name-field-actions.ts rename to src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-actions.ts index 411000ff244..2c45b46e110 100644 --- a/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-actions.ts +++ b/src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-actions.ts @@ -8,19 +8,19 @@ import { type WorkspaceEmojiReplacement, type getActiveWorkspaceEmojiShortcode } from '@/lib/workspace/display/workspace-emoji-shortcodes' -import type { StandardEmojiShortcodeEntry } from '../../../../shared/emoji-shortcode-catalog' -import type { GitHubWorkItem } from '../../../../shared/github/work-items/work-item-types' -import { buildTaskSourceContextFromRepo } from '../../../../shared/work-items/task-source-context' +import type { StandardEmojiShortcodeEntry } from '../../../../../shared/emoji-shortcode-catalog' +import type { GitHubWorkItem } from '../../../../../shared/github/work-items/work-item-types' +import { buildTaskSourceContextFromRepo } from '../../../../../shared/work-items/task-source-context' import type { RepoOption, RowEntry, SmartWorkspaceNameFieldProps } from './smart-workspace-name-field-model' -import { getRepoSlugCached, sameSlug } from './smart-workspace-repo-slug' -import type { useWorkItemSourceSearch } from './use-work-item-source-search' +import { getRepoSlugCached, sameSlug } from '../source-search/smart-workspace-repo-slug' +import type { useWorkItemSourceSearch } from '../source-search/use-work-item-source-search' import type { useSmartWorkspaceFieldFocusControls } from './use-smart-workspace-field-focus-controls' import { useAppStore } from '@/store/index' -import type { useWorkItemSourcePresentation } from './use-work-item-source-presentation' +import type { useWorkItemSourcePresentation } from '../source-search/use-work-item-source-presentation' import { openAppHttpLink } from '@/lib/browser/navigation/app-http-link-open' type Foundation = ReturnType & diff --git a/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-controller.ts b/src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-controller.ts similarity index 95% rename from src/renderer/src/components/new-workspace/use-smart-workspace-name-field-controller.ts rename to src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-controller.ts index 5c5e8e7967c..a416db319b4 100644 --- a/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-controller.ts +++ b/src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-controller.ts @@ -3,9 +3,9 @@ import { getActiveWorkspaceEmojiShortcode, searchWorkspaceEmojiShortcodes } from '@/lib/workspace/display/workspace-emoji-shortcodes' -import type { StandardEmojiShortcodeEntry } from '../../../../shared/emoji-shortcode-catalog' +import type { StandardEmojiShortcodeEntry } from '../../../../../shared/emoji-shortcode-catalog' import type { SmartWorkspaceNameFieldProps } from './smart-workspace-name-field-model' -import { useWorkItemSourceSearch } from './use-work-item-source-search' +import { useWorkItemSourceSearch } from '../source-search/use-work-item-source-search' import { useSmartWorkspaceFieldFocusControls } from './use-smart-workspace-field-focus-controls' import { useSmartWorkspaceNameFieldActions } from './use-smart-workspace-name-field-actions' import { getSmartWorkspaceNameFieldCopy } from './smart-workspace-name-field-copy' diff --git a/src/renderer/src/components/new-workspace/SetProjectLocationDialog.test.tsx b/src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.test.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/SetProjectLocationDialog.test.tsx rename to src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.test.tsx diff --git a/src/renderer/src/components/new-workspace/SetProjectLocationDialog.tsx b/src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.tsx similarity index 96% rename from src/renderer/src/components/new-workspace/SetProjectLocationDialog.tsx rename to src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.tsx index 34567bbe71a..644e210bf96 100644 --- a/src/renderer/src/components/new-workspace/SetProjectLocationDialog.tsx +++ b/src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef, useState, type RefObject } from 'react' -import { useCloneFolderOverride } from '../sidebar/project-admission/clone-folder/use-clone-folder-override' -import { getProjectCloneCheckTarget } from '../../store/projects/project-host-routing' +import { useCloneFolderOverride } from '../../sidebar/project-admission/clone-folder/use-clone-folder-override' +import { getProjectCloneCheckTarget } from '../../../store/projects/project-host-routing' import { Download, FolderOpen } from 'lucide-react' import { Dialog, @@ -16,8 +16,8 @@ import { getProjectHostSetupSelectionKey, type NeedsSetupProjectHostOption } from '@/lib/workspace/creation/project-host-setup-options' -import { parseExecutionHostId } from '../../../../shared/execution-host' -import type { RepoKind } from '../../../../shared/repo-types' +import { parseExecutionHostId } from '../../../../../shared/execution-host' +import type { RepoKind } from '../../../../../shared/repo-types' import { pickLocalProjectLocationFolder } from './pick-local-project-folder' import { CloneForm, ExistingFolderForm, LocationActionButton } from './SetProjectLocationForms' diff --git a/src/renderer/src/components/new-workspace/SetProjectLocationForms.tsx b/src/renderer/src/components/new-workspace/project-location/SetProjectLocationForms.tsx similarity index 96% rename from src/renderer/src/components/new-workspace/SetProjectLocationForms.tsx rename to src/renderer/src/components/new-workspace/project-location/SetProjectLocationForms.tsx index c49e27b6062..9da938d4af5 100644 --- a/src/renderer/src/components/new-workspace/SetProjectLocationForms.tsx +++ b/src/renderer/src/components/new-workspace/project-location/SetProjectLocationForms.tsx @@ -1,6 +1,6 @@ import { ArrowLeft, FolderOpen, LoaderCircle } from 'lucide-react' -import { CloneFolderNameField } from '../sidebar/project-admission/clone-folder/CloneFolderNameField' -import type { CloneFolderOverride } from '../sidebar/project-admission/clone-folder/use-clone-folder-override' +import { CloneFolderNameField } from '../../sidebar/project-admission/clone-folder/CloneFolderNameField' +import type { CloneFolderOverride } from '../../sidebar/project-admission/clone-folder/use-clone-folder-override' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { @@ -12,7 +12,7 @@ import { } from '@/components/ui/select' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/class-names' -import type { RepoKind } from '../../../../shared/repo-types' +import type { RepoKind } from '../../../../../shared/repo-types' export function ExistingFolderForm({ setupPath, diff --git a/src/renderer/src/components/new-workspace/pick-local-project-folder.ts b/src/renderer/src/components/new-workspace/project-location/pick-local-project-folder.ts similarity index 100% rename from src/renderer/src/components/new-workspace/pick-local-project-folder.ts rename to src/renderer/src/components/new-workspace/project-location/pick-local-project-folder.ts diff --git a/src/renderer/src/components/new-workspace/ProjectCombobox.dialog-handoff.test.tsx b/src/renderer/src/components/new-workspace/project-selection/ProjectCombobox.dialog-handoff.test.tsx similarity index 51% rename from src/renderer/src/components/new-workspace/ProjectCombobox.dialog-handoff.test.tsx rename to src/renderer/src/components/new-workspace/project-selection/ProjectCombobox.dialog-handoff.test.tsx index f573697d909..c5238a5c8c7 100644 --- a/src/renderer/src/components/new-workspace/ProjectCombobox.dialog-handoff.test.tsx +++ b/src/renderer/src/components/new-workspace/project-selection/ProjectCombobox.dialog-handoff.test.tsx @@ -2,58 +2,13 @@ import React, { act, Suspense, useEffect, useRef, useState } from 'react' import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog' import ProjectCombobox from './ProjectCombobox' import { TooltipProvider } from '@/components/ui/tooltip' vi.mock('./use-recent-project-ids', () => ({ useRecentProjectIds: () => [] })) -function Composer({ populated }: { populated: boolean }): React.JSX.Element { - const [adding, setAdding] = useState(false) - const nameRef = useRef(null) - return ( - - - New workspace - setAdding(true)} - /> - - - { - event.preventDefault() - nameRef.current?.focus() - }} - > - Add a project - - - - - - - ) -} - // Mirrors a lazily loaded creation dialog that focuses its primary action from a mount effect. let resolveLateDialog: () => void = () => {} const LateAddDialogBody = React.lazy( @@ -139,69 +94,6 @@ function addOption(): HTMLElement { )! } -describe.each([false, true])( - 'project selector to nested dialog handoff (populated: %s)', - (populated) => { - it.each(['mouse', 'keyboard'] as const)( - 'removes the selector before the creation dialog is active via %s', - async (input) => { - await act(async () => - root.render( - - - - ) - ) - await act(async () => projectField().click()) - expect(document.querySelector('[role="listbox"]')).not.toBeNull() - - await act(async () => { - if (input === 'mouse') { - addOption().dispatchEvent( - new MouseEvent('mousedown', { bubbles: true, cancelable: true }) - ) - addOption().click() - } else if (populated) { - projectField().dispatchEvent( - new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true, cancelable: true }) - ) - } - }) - if (input === 'keyboard') { - await act(async () => { - projectField().dispatchEvent( - new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }) - ) - }) - } - - expect(document.querySelector('[role="listbox"]')).toBeNull() - expect(document.querySelector('[data-slot="popover-content"]')).toBeNull() - expect(projectField().getAttribute('aria-expanded')).toBe('false') - expect(projectField().hasAttribute('aria-activedescendant')).toBe(false) - const path = document.querySelector('[aria-label="Project path"]')! - expect(document.activeElement).toBe(path) - expect(path.closest('[aria-hidden="true"]')).toBeNull() - expect(projectField().closest('[aria-hidden="true"]')).not.toBeNull() - - await act(async () => { - Array.from(document.querySelectorAll('button')) - .find((b) => b.textContent === 'Cancel')! - .click() - }) - await vi.waitFor(() => - expect(document.activeElement).toBe( - document.querySelector('[aria-label="Workspace name"]') - ) - ) - await act(async () => projectField().click()) - expect(projectField().getAttribute('aria-expanded')).toBe('true') - expect(document.querySelector('[role="listbox"]')).not.toBeNull() - } - ) - } -) - it('keeps the selector closed when a late creation dialog focuses before its trap mounts', async () => { await act(async () => root.render( diff --git a/src/renderer/src/components/new-workspace/ProjectCombobox.tsx b/src/renderer/src/components/new-workspace/project-selection/ProjectCombobox.tsx similarity index 98% rename from src/renderer/src/components/new-workspace/ProjectCombobox.tsx rename to src/renderer/src/components/new-workspace/project-selection/ProjectCombobox.tsx index 5dd73b325d7..31c4bcda0e8 100644 --- a/src/renderer/src/components/new-workspace/ProjectCombobox.tsx +++ b/src/renderer/src/components/new-workspace/project-selection/ProjectCombobox.tsx @@ -19,10 +19,11 @@ import { } from './ProjectComboboxAddProjectOption' import { ProjectOptionMark, ProjectOptionRow } from './ProjectComboboxRow' import { useRecentProjectIds } from './use-recent-project-ids' -import { isWithinComboboxRoot, useTypeAheadCombobox } from './use-type-ahead-combobox' -import { COMBOBOX_FIELD_SHELL, COMBOBOX_POPOVER_SURFACE } from './type-ahead-combobox-styles' - -export type { ProjectComboboxAddProjectMenu } +import { isWithinComboboxRoot, useTypeAheadCombobox } from '../type-ahead/use-type-ahead-combobox' +import { + COMBOBOX_FIELD_SHELL, + COMBOBOX_POPOVER_SURFACE +} from '../type-ahead/type-ahead-combobox-styles' type ProjectComboboxProps = { options: readonly NewWorkspaceProjectOption[] diff --git a/src/renderer/src/components/new-workspace/ProjectComboboxAddProjectOption.tsx b/src/renderer/src/components/new-workspace/project-selection/ProjectComboboxAddProjectOption.tsx similarity index 98% rename from src/renderer/src/components/new-workspace/ProjectComboboxAddProjectOption.tsx rename to src/renderer/src/components/new-workspace/project-selection/ProjectComboboxAddProjectOption.tsx index 901d3cfcce9..2394eeeff2e 100644 --- a/src/renderer/src/components/new-workspace/ProjectComboboxAddProjectOption.tsx +++ b/src/renderer/src/components/new-workspace/project-selection/ProjectComboboxAddProjectOption.tsx @@ -6,7 +6,7 @@ import { ADD_PROJECT_MENU_ATTRIBUTE } from '@/components/sidebar/project-admissi import { AddProjectMenu } from '@/components/sidebar/project-admission/menu/AddProjectMenu' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/class-names' -import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../../shared/execution-host' export type ProjectComboboxAddProjectMenu = { defaultHostId?: ExecutionHostId | null diff --git a/src/renderer/src/components/new-workspace/ProjectComboboxRow.tsx b/src/renderer/src/components/new-workspace/project-selection/ProjectComboboxRow.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/ProjectComboboxRow.tsx rename to src/renderer/src/components/new-workspace/project-selection/ProjectComboboxRow.tsx diff --git a/src/renderer/src/components/new-workspace/composer-add-project-default-host.ts b/src/renderer/src/components/new-workspace/project-selection/composer-add-project-default-host.ts similarity index 94% rename from src/renderer/src/components/new-workspace/composer-add-project-default-host.ts rename to src/renderer/src/components/new-workspace/project-selection/composer-add-project-default-host.ts index 2d295929f89..678b97456ca 100644 --- a/src/renderer/src/components/new-workspace/composer-add-project-default-host.ts +++ b/src/renderer/src/components/new-workspace/project-selection/composer-add-project-default-host.ts @@ -1,5 +1,5 @@ import type { ProjectHostSetupOption } from '@/lib/workspace/creation/project-host-setup-options' -import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../../shared/execution-host' /** Sync the Add project menu's initial host with the composer's active Run on host selection. */ export function resolveComposerAddProjectDefaultHostId({ diff --git a/src/renderer/src/components/new-workspace/project-combobox-localized-copy.ts b/src/renderer/src/components/new-workspace/project-selection/project-combobox-localized-copy.ts similarity index 100% rename from src/renderer/src/components/new-workspace/project-combobox-localized-copy.ts rename to src/renderer/src/components/new-workspace/project-selection/project-combobox-localized-copy.ts diff --git a/src/renderer/src/components/new-workspace/project-combobox-matching.ts b/src/renderer/src/components/new-workspace/project-selection/project-combobox-matching.ts similarity index 100% rename from src/renderer/src/components/new-workspace/project-combobox-matching.ts rename to src/renderer/src/components/new-workspace/project-selection/project-combobox-matching.ts diff --git a/src/renderer/src/components/new-workspace/use-composer-hosted-add-project.ts b/src/renderer/src/components/new-workspace/project-selection/use-composer-hosted-add-project.ts similarity index 100% rename from src/renderer/src/components/new-workspace/use-composer-hosted-add-project.ts rename to src/renderer/src/components/new-workspace/project-selection/use-composer-hosted-add-project.ts diff --git a/src/renderer/src/components/new-workspace/use-recent-project-ids.test.ts b/src/renderer/src/components/new-workspace/project-selection/use-recent-project-ids.test.ts similarity index 94% rename from src/renderer/src/components/new-workspace/use-recent-project-ids.test.ts rename to src/renderer/src/components/new-workspace/project-selection/use-recent-project-ids.test.ts index 3303787c731..38f04df6944 100644 --- a/src/renderer/src/components/new-workspace/use-recent-project-ids.test.ts +++ b/src/renderer/src/components/new-workspace/project-selection/use-recent-project-ids.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import type { Worktree } from '../../../../shared/worktree/types' +import type { Worktree } from '../../../../../shared/worktree/types' import { orderProjectIdsByRecency } from './use-recent-project-ids' function worktree(partial: Partial): Worktree { diff --git a/src/renderer/src/components/new-workspace/use-recent-project-ids.ts b/src/renderer/src/components/new-workspace/project-selection/use-recent-project-ids.ts similarity index 94% rename from src/renderer/src/components/new-workspace/use-recent-project-ids.ts rename to src/renderer/src/components/new-workspace/project-selection/use-recent-project-ids.ts index b444193e79a..cf3617104b2 100644 --- a/src/renderer/src/components/new-workspace/use-recent-project-ids.ts +++ b/src/renderer/src/components/new-workspace/project-selection/use-recent-project-ids.ts @@ -1,5 +1,5 @@ import { useMemo } from 'react' -import type { Worktree } from '../../../../shared/worktree/types' +import type { Worktree } from '../../../../../shared/worktree/types' import { useAllWorktrees } from '@/store/slices/worktrees/listing/use-worktree-catalog' import { NEW_WORKSPACE_PROJECT_GROUP_OPTION_PREFIX } from '@/lib/workspace/creation/new-workspace-project-options' diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx b/src/renderer/src/components/new-workspace/run-target/RunTargetCombobox.fixture.tsx similarity index 96% rename from src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx rename to src/renderer/src/components/new-workspace/run-target/RunTargetCombobox.fixture.tsx index 84fd7478975..b0b531166de 100644 --- a/src/renderer/src/components/new-workspace/RunTargetCombobox.fixture.tsx +++ b/src/renderer/src/components/new-workspace/run-target/RunTargetCombobox.fixture.tsx @@ -1,4 +1,4 @@ -import { defineFixture } from '../../component-fixtures/component-fixture' +import { defineFixture } from '../../../component-fixtures/component-fixture' import type { ProjectHostSetupOption } from '@/lib/workspace/creation/project-host-setup-options' import RunTargetCombobox from './RunTargetCombobox' diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx b/src/renderer/src/components/new-workspace/run-target/RunTargetCombobox.tsx similarity index 97% rename from src/renderer/src/components/new-workspace/RunTargetCombobox.tsx rename to src/renderer/src/components/new-workspace/run-target/RunTargetCombobox.tsx index 475a2672d29..bc72d466f7f 100644 --- a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx +++ b/src/renderer/src/components/new-workspace/run-target/RunTargetCombobox.tsx @@ -8,9 +8,9 @@ import { type ProjectHostSetupOption, type ReadyProjectHostSetupOption } from '@/lib/workspace/creation/project-host-setup-options' -import type { ExecutionHostId } from '../../../../shared/execution-host' -import { isWithinComboboxRoot, useTypeAheadCombobox } from './use-type-ahead-combobox' -import { COMBOBOX_POPOVER_SURFACE } from './type-ahead-combobox-styles' +import type { ExecutionHostId } from '../../../../../shared/execution-host' +import { isWithinComboboxRoot, useTypeAheadCombobox } from '../type-ahead/use-type-ahead-combobox' +import { COMBOBOX_POPOVER_SURFACE } from '../type-ahead/type-ahead-combobox-styles' import { buildRunTargetRows, getEphemeralVmLabel, diff --git a/src/renderer/src/components/new-workspace/RunTargetComboboxRow.tsx b/src/renderer/src/components/new-workspace/run-target/RunTargetComboboxRow.tsx similarity index 95% rename from src/renderer/src/components/new-workspace/RunTargetComboboxRow.tsx rename to src/renderer/src/components/new-workspace/run-target/RunTargetComboboxRow.tsx index 050a11dd2c9..2879d9d6a0c 100644 --- a/src/renderer/src/components/new-workspace/RunTargetComboboxRow.tsx +++ b/src/renderer/src/components/new-workspace/run-target/RunTargetComboboxRow.tsx @@ -1,10 +1,7 @@ import React from 'react' import { ChevronRight } from 'lucide-react' import { cn } from '@/lib/class-names' -import { ProjectOptionDetail } from './ProjectComboboxRow' -import { HostRowIcon } from '../host-row-icon' - -export { HostRowIcon } +import { ProjectOptionDetail } from '../project-selection/ProjectComboboxRow' /** Match the project picker with details below each target name. */ export function RunTargetRow({ diff --git a/src/renderer/src/components/new-workspace/RunTargetField.tsx b/src/renderer/src/components/new-workspace/run-target/RunTargetField.tsx similarity index 95% rename from src/renderer/src/components/new-workspace/RunTargetField.tsx rename to src/renderer/src/components/new-workspace/run-target/RunTargetField.tsx index ce81396509f..9315a445924 100644 --- a/src/renderer/src/components/new-workspace/RunTargetField.tsx +++ b/src/renderer/src/components/new-workspace/run-target/RunTargetField.tsx @@ -5,9 +5,9 @@ import { PopoverAnchor } from '@/components/ui/popover' import { cn } from '@/lib/class-names' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useTranslate } from '@/i18n/use-translate' -import type { ExecutionHostId } from '../../../../shared/execution-host' -import { HostRowIcon } from './RunTargetComboboxRow' -import { COMBOBOX_FIELD_SHELL } from './type-ahead-combobox-styles' +import type { ExecutionHostId } from '../../../../../shared/execution-host' +import { HostRowIcon } from '../../host-row-icon' +import { COMBOBOX_FIELD_SHELL } from '../type-ahead/type-ahead-combobox-styles' /** Overlay the committed selection while keeping the input ready to search. */ export default function RunTargetField({ diff --git a/src/renderer/src/components/new-workspace/RunTargetRowActions.tsx b/src/renderer/src/components/new-workspace/run-target/RunTargetRowActions.tsx similarity index 96% rename from src/renderer/src/components/new-workspace/RunTargetRowActions.tsx rename to src/renderer/src/components/new-workspace/run-target/RunTargetRowActions.tsx index a25909784b5..738dbdc9c07 100644 --- a/src/renderer/src/components/new-workspace/RunTargetRowActions.tsx +++ b/src/renderer/src/components/new-workspace/run-target/RunTargetRowActions.tsx @@ -2,9 +2,9 @@ import React from 'react' import { AlertTriangle, LoaderCircle } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../../shared/execution-host' import { useTranslate } from '@/i18n/use-translate' -import { HostRowIcon } from '../host-row-icon' +import { HostRowIcon } from '../../host-row-icon' /** Glyph for a host that can't run yet: connecting, broken, or merely dormant. */ export function NeedsSetupHostIcon({ diff --git a/src/renderer/src/components/new-workspace/RunTargetRowList.tsx b/src/renderer/src/components/new-workspace/run-target/RunTargetRowList.tsx similarity index 97% rename from src/renderer/src/components/new-workspace/RunTargetRowList.tsx rename to src/renderer/src/components/new-workspace/run-target/RunTargetRowList.tsx index b2b7d7d4195..7e46ee475c6 100644 --- a/src/renderer/src/components/new-workspace/RunTargetRowList.tsx +++ b/src/renderer/src/components/new-workspace/run-target/RunTargetRowList.tsx @@ -3,7 +3,8 @@ import type { NeedsSetupProjectHostOption, ReadyProjectHostSetupOption } from '@/lib/workspace/creation/project-host-setup-options' -import { HostRowIcon, RunTargetRow } from './RunTargetComboboxRow' +import { HostRowIcon } from '../../host-row-icon' +import { RunTargetRow } from './RunTargetComboboxRow' import { ConnectHostButton, NeedsSetupHostIcon, SetLocationButton } from './RunTargetRowActions' import { RecipesSubmenuRow } from './RunTargetSubmenus' import type { EphemeralVmRecipeOption, RunTargetRowModel } from './run-target-options' diff --git a/src/renderer/src/components/new-workspace/RunTargetSubmenus.tsx b/src/renderer/src/components/new-workspace/run-target/RunTargetSubmenus.tsx similarity index 97% rename from src/renderer/src/components/new-workspace/RunTargetSubmenus.tsx rename to src/renderer/src/components/new-workspace/run-target/RunTargetSubmenus.tsx index c27b157b661..5e3c9e2242e 100644 --- a/src/renderer/src/components/new-workspace/RunTargetSubmenus.tsx +++ b/src/renderer/src/components/new-workspace/run-target/RunTargetSubmenus.tsx @@ -7,10 +7,9 @@ import { RunTargetRow } from './RunTargetComboboxRow' import { getEphemeralVmLabel, getRecipeDetail, - RUN_TARGET_ADD_HOST_KEY, type EphemeralVmRecipeOption } from './run-target-options' -import { COMBOBOX_POPOVER_SURFACE } from './type-ahead-combobox-styles' +import { COMBOBOX_POPOVER_SURFACE } from '../type-ahead/type-ahead-combobox-styles' const SUBMENU_CONTENT = cn('w-72 p-1', COMBOBOX_POPOVER_SURFACE) @@ -185,5 +184,3 @@ export function AddHostSubmenuRow({ ) } - -export { RUN_TARGET_ADD_HOST_KEY } diff --git a/src/renderer/src/components/new-workspace/run-target-options.ts b/src/renderer/src/components/new-workspace/run-target/run-target-options.ts similarity index 98% rename from src/renderer/src/components/new-workspace/run-target-options.ts rename to src/renderer/src/components/new-workspace/run-target/run-target-options.ts index 620b0da9f32..0c4008c64e6 100644 --- a/src/renderer/src/components/new-workspace/run-target-options.ts +++ b/src/renderer/src/components/new-workspace/run-target/run-target-options.ts @@ -1,4 +1,4 @@ -import type { OrcaHooks } from '../../../../shared/orca-yaml-hook-types' +import type { OrcaHooks } from '../../../../../shared/orca-yaml-hook-types' import { getProjectHostSetupSelectionKey, type NeedsSetupProjectHostOption, diff --git a/src/renderer/src/components/new-workspace/DirectWorkItemSetupDialog.test.tsx b/src/renderer/src/components/new-workspace/setup/DirectWorkItemSetupDialog.test.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/DirectWorkItemSetupDialog.test.tsx rename to src/renderer/src/components/new-workspace/setup/DirectWorkItemSetupDialog.test.tsx diff --git a/src/renderer/src/components/new-workspace/DirectWorkItemSetupDialog.tsx b/src/renderer/src/components/new-workspace/setup/DirectWorkItemSetupDialog.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/DirectWorkItemSetupDialog.tsx rename to src/renderer/src/components/new-workspace/setup/DirectWorkItemSetupDialog.tsx diff --git a/src/renderer/src/components/new-workspace/SetupCommandPreview.tsx b/src/renderer/src/components/new-workspace/setup/SetupCommandPreview.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/SetupCommandPreview.tsx rename to src/renderer/src/components/new-workspace/setup/SetupCommandPreview.tsx diff --git a/src/renderer/src/components/new-workspace/WorkspaceSetupChoice.test.tsx b/src/renderer/src/components/new-workspace/setup/WorkspaceSetupChoice.test.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/WorkspaceSetupChoice.test.tsx rename to src/renderer/src/components/new-workspace/setup/WorkspaceSetupChoice.test.tsx diff --git a/src/renderer/src/components/new-workspace/WorkspaceSetupChoice.tsx b/src/renderer/src/components/new-workspace/setup/WorkspaceSetupChoice.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/WorkspaceSetupChoice.tsx rename to src/renderer/src/components/new-workspace/setup/WorkspaceSetupChoice.tsx diff --git a/src/renderer/src/components/new-workspace/WorkspaceSetupSection.tsx b/src/renderer/src/components/new-workspace/setup/WorkspaceSetupSection.tsx similarity index 94% rename from src/renderer/src/components/new-workspace/WorkspaceSetupSection.tsx rename to src/renderer/src/components/new-workspace/setup/WorkspaceSetupSection.tsx index 0ed897fab96..c374a167ac2 100644 --- a/src/renderer/src/components/new-workspace/WorkspaceSetupSection.tsx +++ b/src/renderer/src/components/new-workspace/setup/WorkspaceSetupSection.tsx @@ -1,7 +1,7 @@ import type { ReactNode } from 'react' -import type { SetupConfig } from '../../../../shared/orca-hook-setup-config' -import type { SetupDecision } from '../../../../shared/worktree/create-types' -import type { SetupAgentStartupPolicy } from '../../../../shared/orca-yaml-hook-types' +import type { SetupConfig } from '../../../../../shared/orca-hook-setup-config' +import type { SetupDecision } from '../../../../../shared/worktree/create-types' +import type { SetupAgentStartupPolicy } from '../../../../../shared/orca-yaml-hook-types' import { Switch } from '@/components/ui/switch' import { Button } from '@/components/ui/button' import { cn } from '@/lib/class-names' diff --git a/src/renderer/src/components/new-workspace/direct-work-item-setup-copy.ts b/src/renderer/src/components/new-workspace/setup/direct-work-item-setup-copy.ts similarity index 100% rename from src/renderer/src/components/new-workspace/direct-work-item-setup-copy.ts rename to src/renderer/src/components/new-workspace/setup/direct-work-item-setup-copy.ts diff --git a/src/renderer/src/components/new-workspace/workspace-setup-composer-copy.ts b/src/renderer/src/components/new-workspace/setup/workspace-setup-composer-copy.ts similarity index 100% rename from src/renderer/src/components/new-workspace/workspace-setup-composer-copy.ts rename to src/renderer/src/components/new-workspace/setup/workspace-setup-composer-copy.ts diff --git a/src/renderer/src/components/new-workspace/workspace-setup-section-model.ts b/src/renderer/src/components/new-workspace/setup/workspace-setup-section-model.ts similarity index 89% rename from src/renderer/src/components/new-workspace/workspace-setup-section-model.ts rename to src/renderer/src/components/new-workspace/setup/workspace-setup-section-model.ts index 488590bfa02..1ac8ad68a1f 100644 --- a/src/renderer/src/components/new-workspace/workspace-setup-section-model.ts +++ b/src/renderer/src/components/new-workspace/setup/workspace-setup-section-model.ts @@ -1,4 +1,4 @@ -import type { SetupConfig } from '../../../../shared/orca-hook-setup-config' +import type { SetupConfig } from '../../../../../shared/orca-hook-setup-config' export type WorkspaceSetupKindCopy = { configLabel: string diff --git a/src/renderer/src/components/new-workspace/smart-workspace-command-value.ts b/src/renderer/src/components/new-workspace/smart-workspace-command-value.ts deleted file mode 100644 index d0c201cce47..00000000000 --- a/src/renderer/src/components/new-workspace/smart-workspace-command-value.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '../../../../shared/new-workspace/smart-workspace-command-value' diff --git a/src/renderer/src/components/new-workspace/SmartWorkspaceSourceResultList.tsx b/src/renderer/src/components/new-workspace/source-search/SmartWorkspaceSourceResultList.tsx similarity index 98% rename from src/renderer/src/components/new-workspace/SmartWorkspaceSourceResultList.tsx rename to src/renderer/src/components/new-workspace/source-search/SmartWorkspaceSourceResultList.tsx index e1fe802d6c3..a2ade66aeef 100644 --- a/src/renderer/src/components/new-workspace/SmartWorkspaceSourceResultList.tsx +++ b/src/renderer/src/components/new-workspace/source-search/SmartWorkspaceSourceResultList.tsx @@ -1,12 +1,12 @@ import React from 'react' -import { isIntegrationCredentialDecryptionError } from '../../../../shared/integration-credential-errors' +import { isIntegrationCredentialDecryptionError } from '../../../../../shared/integration-credential-errors' import { Button } from '@/components/ui/button' import { CommandGroup, CommandItem, CommandList } from '@/components/ui/command' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/class-names' import { translateSmartWorkspaceEmptyHint } from './smart-workspace-empty-hint' import { RowIcon, RowLabel } from './smart-workspace-source-row-content' -import type { RowEntry } from './smart-workspace-name-field-model' +import type { RowEntry } from '../name-field/smart-workspace-name-field-model' import type { WorkItemSourceSearch } from './use-work-item-source-search' export function SmartWorkspaceSourceResultList({ diff --git a/src/renderer/src/components/new-workspace/SmartWorkspaceSourceTabs.fixture.tsx b/src/renderer/src/components/new-workspace/source-search/SmartWorkspaceSourceTabs.fixture.tsx similarity index 85% rename from src/renderer/src/components/new-workspace/SmartWorkspaceSourceTabs.fixture.tsx rename to src/renderer/src/components/new-workspace/source-search/SmartWorkspaceSourceTabs.fixture.tsx index ec381e94432..81bfa2d957a 100644 --- a/src/renderer/src/components/new-workspace/SmartWorkspaceSourceTabs.fixture.tsx +++ b/src/renderer/src/components/new-workspace/source-search/SmartWorkspaceSourceTabs.fixture.tsx @@ -1,8 +1,8 @@ import { useState } from 'react' -import { defineFixture } from '../../component-fixtures/component-fixture' +import { defineFixture } from '../../../component-fixtures/component-fixture' import { getSmartWorkspaceNameModes } from './smart-workspace-localized-options' import { SmartWorkspaceSourceTabs } from './SmartWorkspaceSourceTabs' -import type { SmartNameMode } from '../../../../shared/new-workspace/smart-workspace-source-results' +import type { SmartNameMode } from '../../../../../shared/new-workspace/smart-workspace-source-results' function Preview() { const [mode, setMode] = useState('smart') diff --git a/src/renderer/src/components/new-workspace/SmartWorkspaceSourceTabs.tsx b/src/renderer/src/components/new-workspace/source-search/SmartWorkspaceSourceTabs.tsx similarity index 100% rename from src/renderer/src/components/new-workspace/SmartWorkspaceSourceTabs.tsx rename to src/renderer/src/components/new-workspace/source-search/SmartWorkspaceSourceTabs.tsx diff --git a/src/renderer/src/components/new-workspace/jira-source-status-message.ts b/src/renderer/src/components/new-workspace/source-search/jira-source-status-message.ts similarity index 100% rename from src/renderer/src/components/new-workspace/jira-source-status-message.ts rename to src/renderer/src/components/new-workspace/source-search/jira-source-status-message.ts diff --git a/src/renderer/src/components/new-workspace/smart-workspace-empty-hint.ts b/src/renderer/src/components/new-workspace/source-search/smart-workspace-empty-hint.ts similarity index 92% rename from src/renderer/src/components/new-workspace/smart-workspace-empty-hint.ts rename to src/renderer/src/components/new-workspace/source-search/smart-workspace-empty-hint.ts index be815d42a24..9fbbdeca5cf 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-empty-hint.ts +++ b/src/renderer/src/components/new-workspace/source-search/smart-workspace-empty-hint.ts @@ -1,5 +1,5 @@ import { translate } from '@/i18n/i18n' -import type { SmartNameMode } from '../../../../shared/new-workspace/smart-workspace-source-results' +import type { SmartNameMode } from '../../../../../shared/new-workspace/smart-workspace-source-results' export function translateSmartWorkspaceEmptyHint(mode: SmartNameMode): string { switch (mode) { diff --git a/src/renderer/src/components/new-workspace/smart-workspace-github-direct-link.test.ts b/src/renderer/src/components/new-workspace/source-search/smart-workspace-github-direct-link.test.ts similarity index 90% rename from src/renderer/src/components/new-workspace/smart-workspace-github-direct-link.test.ts rename to src/renderer/src/components/new-workspace/source-search/smart-workspace-github-direct-link.test.ts index 87e6ae7c32d..c49dbdda1eb 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-github-direct-link.test.ts +++ b/src/renderer/src/components/new-workspace/source-search/smart-workspace-github-direct-link.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import { parseGitHubIssueOrPRLink } from '../../../../shared/github/repositories/links' -import type { RepoOption } from './smart-workspace-name-field-model' +import { parseGitHubIssueOrPRLink } from '../../../../../shared/github/repositories/links' +import type { RepoOption } from '../name-field/smart-workspace-name-field-model' import { resolveSmartWorkspaceGithubDirectLink } from './smart-workspace-github-direct-link' const slugs: Record = { diff --git a/src/renderer/src/components/new-workspace/smart-workspace-github-direct-link.ts b/src/renderer/src/components/new-workspace/source-search/smart-workspace-github-direct-link.ts similarity index 92% rename from src/renderer/src/components/new-workspace/smart-workspace-github-direct-link.ts rename to src/renderer/src/components/new-workspace/source-search/smart-workspace-github-direct-link.ts index 17cac1bfd7c..c1b58035893 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-github-direct-link.ts +++ b/src/renderer/src/components/new-workspace/source-search/smart-workspace-github-direct-link.ts @@ -1,20 +1,20 @@ import type React from 'react' -import type { parseGitHubIssueOrPRLink } from '../../../../shared/github/repositories/links' +import type { parseGitHubIssueOrPRLink } from '../../../../../shared/github/repositories/links' import { lookupGitHubWorkItemByOwnerRepoForSource, lookupGitHubWorkItemForSource } from '@/lib/work-items/github/github-work-item-source-lookup' import { lookupSmartGitHubSubmitItem } from '@/lib/work-items/github/smart-github-submit' -import type { GitHubWorkItem } from '../../../../shared/github/work-items/work-item-types' +import type { GitHubWorkItem } from '../../../../../shared/github/work-items/work-item-types' import { buildTaskSourceContextFromRepo, type TaskSourceContext -} from '../../../../shared/work-items/task-source-context' +} from '../../../../../shared/work-items/task-source-context' import type { CrossRepoPrompt, RepoBackedSearchTarget, RepoOption -} from './smart-workspace-name-field-model' +} from '../name-field/smart-workspace-name-field-model' import { findMatchingRepoForSlug, getRepoSlugCached, sameSlug } from './smart-workspace-repo-slug' type DirectLink = NonNullable> diff --git a/src/renderer/src/components/new-workspace/smart-workspace-localized-options.tsx b/src/renderer/src/components/new-workspace/source-search/smart-workspace-localized-options.tsx similarity index 96% rename from src/renderer/src/components/new-workspace/smart-workspace-localized-options.tsx rename to src/renderer/src/components/new-workspace/source-search/smart-workspace-localized-options.tsx index d4778066407..ad81585d733 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-localized-options.tsx +++ b/src/renderer/src/components/new-workspace/source-search/smart-workspace-localized-options.tsx @@ -4,7 +4,7 @@ import { CaseSensitive, GitBranch, Github, Gitlab, Sparkles } from 'lucide-react import { JiraIcon } from '@/components/icons/JiraIcon' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import type { SmartNameMode } from '../../../../shared/new-workspace/smart-workspace-source-results' +import type { SmartNameMode } from '../../../../../shared/new-workspace/smart-workspace-source-results' export type MrStateFilter = 'opened' | 'merged' | 'closed' | 'all' diff --git a/src/renderer/src/components/new-workspace/smart-workspace-provider-availability.ts b/src/renderer/src/components/new-workspace/source-search/smart-workspace-provider-availability.ts similarity index 93% rename from src/renderer/src/components/new-workspace/smart-workspace-provider-availability.ts rename to src/renderer/src/components/new-workspace/source-search/smart-workspace-provider-availability.ts index d10b78171c4..7973919b746 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-provider-availability.ts +++ b/src/renderer/src/components/new-workspace/source-search/smart-workspace-provider-availability.ts @@ -1,4 +1,4 @@ -import { parseExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' +import { parseExecutionHostId, type ExecutionHostId } from '../../../../../shared/execution-host' export function canUseGitLabSmartSource({ localGitlabAvailable, diff --git a/src/renderer/src/components/new-workspace/smart-workspace-repo-slug.ts b/src/renderer/src/components/new-workspace/source-search/smart-workspace-repo-slug.ts similarity index 83% rename from src/renderer/src/components/new-workspace/smart-workspace-repo-slug.ts rename to src/renderer/src/components/new-workspace/source-search/smart-workspace-repo-slug.ts index 3fa1ae993d0..ca7ed3c0617 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-repo-slug.ts +++ b/src/renderer/src/components/new-workspace/source-search/smart-workspace-repo-slug.ts @@ -1,15 +1,15 @@ -import type { RepoSlug } from '../../../../shared/github/repositories/links' +import type { RepoSlug } from '../../../../../shared/github/repositories/links' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' import { getGitHubRuntimeRepoId, getGitHubSourceRuntimeTarget } from '@/lib/work-items/github/github-source-runtime-context' -import { githubRepoIdentityKey } from '../../../../shared/github/repositories/repository-identity-key' +import { githubRepoIdentityKey } from '../../../../../shared/github/repositories/repository-identity-key' import { getTaskSourceCacheScope, type TaskSourceContext -} from '../../../../shared/work-items/task-source-context' -import type { RepoOption, RepoSlugTarget } from './smart-workspace-name-field-model' +} from '../../../../../shared/work-items/task-source-context' +import type { RepoOption, RepoSlugTarget } from '../name-field/smart-workspace-name-field-model' export function sameSlug(left: RepoSlug, right: RepoSlug): boolean { return githubRepoIdentityKey(left) === githubRepoIdentityKey(right) diff --git a/src/renderer/src/components/new-workspace/smart-workspace-source-row-content.tsx b/src/renderer/src/components/new-workspace/source-search/smart-workspace-source-row-content.tsx similarity index 95% rename from src/renderer/src/components/new-workspace/smart-workspace-source-row-content.tsx rename to src/renderer/src/components/new-workspace/source-search/smart-workspace-source-row-content.tsx index e22af1ec0e2..f7f6e9e341e 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-source-row-content.tsx +++ b/src/renderer/src/components/new-workspace/source-search/smart-workspace-source-row-content.tsx @@ -12,9 +12,12 @@ import { JiraIcon } from '@/components/icons/JiraIcon' import { Trans } from 'react-i18next' import { i18n } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' -import { branchRefLabel } from '../../../../shared/git/refs/branch-ref-label' -import type { JiraSite } from '../../../../shared/jira/jira-types' -import type { RowEntry, SmartWorkspaceNameSelection } from './smart-workspace-name-field-model' +import { branchRefLabel } from '../../../../../shared/git/refs/branch-ref-label' +import type { JiraSite } from '../../../../../shared/jira/jira-types' +import type { + RowEntry, + SmartWorkspaceNameSelection +} from '../name-field/smart-workspace-name-field-model' export function RowIcon({ row }: { row: RowEntry }): React.JSX.Element { if (row.kind === 'use-name') { diff --git a/src/renderer/src/components/new-workspace/use-composer-source-scope.ts b/src/renderer/src/components/new-workspace/source-search/use-composer-source-scope.ts similarity index 74% rename from src/renderer/src/components/new-workspace/use-composer-source-scope.ts rename to src/renderer/src/components/new-workspace/source-search/use-composer-source-scope.ts index f4c8686ebfa..993c6b716cb 100644 --- a/src/renderer/src/components/new-workspace/use-composer-source-scope.ts +++ b/src/renderer/src/components/new-workspace/source-search/use-composer-source-scope.ts @@ -1,7 +1,7 @@ import { useState } from 'react' -import type { Repo } from '../../../../shared/repo-types' -import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' -import { getRepoExecutionHostId } from '../../../../shared/execution-host' +import type { Repo } from '../../../../../shared/repo-types' +import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context' +import { getRepoExecutionHostId } from '../../../../../shared/execution-host' export function useComposerSourceScope( repo: Repo | null, diff --git a/src/renderer/src/components/new-workspace/use-jira-composer-project.ts b/src/renderer/src/components/new-workspace/source-search/use-jira-composer-project.ts similarity index 61% rename from src/renderer/src/components/new-workspace/use-jira-composer-project.ts rename to src/renderer/src/components/new-workspace/source-search/use-jira-composer-project.ts index d932249a15c..e0965c0f3f3 100644 --- a/src/renderer/src/components/new-workspace/use-jira-composer-project.ts +++ b/src/renderer/src/components/new-workspace/source-search/use-jira-composer-project.ts @@ -1,9 +1,9 @@ -import type { JiraProjectReference } from '../../../../shared/jira/jira-project-reference' -import type { Repo } from '../../../../shared/repo-types' -import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' -import { getRepoExecutionHostId } from '../../../../shared/execution-host' -import { resolveJiraSourceHostId } from '../../../../shared/jira/jira-source-host' -import { useJiraProjectInventory } from '../use-jira-project-inventory' +import type { JiraProjectReference } from '../../../../../shared/jira/jira-project-reference' +import type { Repo } from '../../../../../shared/repo-types' +import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context' +import { getRepoExecutionHostId } from '../../../../../shared/execution-host' +import { resolveJiraSourceHostId } from '../../../../../shared/jira/jira-source-host' +import { useJiraProjectInventory } from '../../use-jira-project-inventory' import { useComposerSourceScope } from './use-composer-source-scope' const LOCAL_SOURCE = { kind: 'local' } as const diff --git a/src/renderer/src/components/new-workspace/use-jira-source-connection.test.tsx b/src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.test.tsx similarity index 93% rename from src/renderer/src/components/new-workspace/use-jira-source-connection.test.tsx rename to src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.test.tsx index 5b2925b7346..7aa90ae9d67 100644 --- a/src/renderer/src/components/new-workspace/use-jira-source-connection.test.tsx +++ b/src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.test.tsx @@ -3,8 +3,8 @@ import { act, renderHook } from '@testing-library/react' import type * as React from 'react' import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' -import type { JiraConnectionStatus } from '../../../../shared/jira/jira-types' +import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context' +import type { JiraConnectionStatus } from '../../../../../shared/jira/jira-types' import { useJiraSourceConnection } from './use-jira-source-connection' const mocks = vi.hoisted(() => ({ diff --git a/src/renderer/src/components/new-workspace/use-jira-source-connection.ts b/src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.ts similarity index 96% rename from src/renderer/src/components/new-workspace/use-jira-source-connection.ts rename to src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.ts index 0ab50773d1a..0bef385179d 100644 --- a/src/renderer/src/components/new-workspace/use-jira-source-connection.ts +++ b/src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.ts @@ -4,8 +4,8 @@ import { getTaskSourceCacheScope, getTaskSourceRuntimeSettings, type TaskSourceContext -} from '../../../../shared/work-items/task-source-context' -import type { JiraConnectionStatus } from '../../../../shared/jira/jira-types' +} from '../../../../../shared/work-items/task-source-context' +import type { JiraConnectionStatus } from '../../../../../shared/jira/jira-types' import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' export type JiraSourceConnection = { diff --git a/src/renderer/src/components/new-workspace/use-jira-url-source.test.tsx b/src/renderer/src/components/new-workspace/source-search/use-jira-url-source.test.tsx similarity index 96% rename from src/renderer/src/components/new-workspace/use-jira-url-source.test.tsx rename to src/renderer/src/components/new-workspace/source-search/use-jira-url-source.test.tsx index 267127543d6..727adaf3a1a 100644 --- a/src/renderer/src/components/new-workspace/use-jira-url-source.test.tsx +++ b/src/renderer/src/components/new-workspace/source-search/use-jira-url-source.test.tsx @@ -2,8 +2,12 @@ import { act, renderHook } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { JiraConnectionStatus, JiraIssue, JiraSite } from '../../../../shared/jira/jira-types' -import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' +import type { + JiraConnectionStatus, + JiraIssue, + JiraSite +} from '../../../../../shared/jira/jira-types' +import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context' import { useJiraUrlSource } from './use-jira-url-source' const mocks = vi.hoisted(() => ({ diff --git a/src/renderer/src/components/new-workspace/use-jira-url-source.ts b/src/renderer/src/components/new-workspace/source-search/use-jira-url-source.ts similarity index 95% rename from src/renderer/src/components/new-workspace/use-jira-url-source.ts rename to src/renderer/src/components/new-workspace/source-search/use-jira-url-source.ts index 9baf170761a..f68286bb46e 100644 --- a/src/renderer/src/components/new-workspace/use-jira-url-source.ts +++ b/src/renderer/src/components/new-workspace/source-search/use-jira-url-source.ts @@ -7,16 +7,16 @@ import { isResolvedJiraIssueMatch, parseJiraIssueUrl, type ParsedJiraIssueUrl -} from '../../../../shared/jira/jira-issue-url' -import { getJiraSummaryLookupErrorCode } from '../../../../shared/jira/jira-summary-lookup' +} from '../../../../../shared/jira/jira-issue-url' +import { getJiraSummaryLookupErrorCode } from '../../../../../shared/jira/jira-summary-lookup' import { getTaskSourceCacheScope, normalizeTaskSourceContext, type TaskSourceContext -} from '../../../../shared/work-items/task-source-context' -import { parseExecutionHostId } from '../../../../shared/execution-host' -import { WORKTREE_LINKED_WORK_ITEM_CONTEXT_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' -import type { JiraIssue, JiraSite } from '../../../../shared/jira/jira-types' +} from '../../../../../shared/work-items/task-source-context' +import { parseExecutionHostId } from '../../../../../shared/execution-host' +import { WORKTREE_LINKED_WORK_ITEM_CONTEXT_RUNTIME_CAPABILITY } from '../../../../../shared/worktree-runtime-capabilities' +import type { JiraIssue, JiraSite } from '../../../../../shared/jira/jira-types' import { canReuseLoadedJiraStatus, type JiraSourceConnection } from './use-jira-source-connection' const LOOKUP_DEBOUNCE_MS = 200 diff --git a/src/renderer/src/components/new-workspace/use-linear-source-connection.ts b/src/renderer/src/components/new-workspace/source-search/use-linear-source-connection.ts similarity index 97% rename from src/renderer/src/components/new-workspace/use-linear-source-connection.ts rename to src/renderer/src/components/new-workspace/source-search/use-linear-source-connection.ts index 1cd9e6bd503..85252a07f39 100644 --- a/src/renderer/src/components/new-workspace/use-linear-source-connection.ts +++ b/src/renderer/src/components/new-workspace/source-search/use-linear-source-connection.ts @@ -13,8 +13,8 @@ import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provi import { getTaskSourceRuntimeSettings, type TaskSourceContext -} from '../../../../shared/work-items/task-source-context' -import type { LinearConnectionStatus } from '../../../../shared/linear/workspace-types' +} from '../../../../../shared/work-items/task-source-context' +import type { LinearConnectionStatus } from '../../../../../shared/linear/workspace-types' type LinearSourceConnection = { status: LinearConnectionStatus | null diff --git a/src/renderer/src/components/new-workspace/use-smart-workspace-field-availability.test.ts b/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-field-availability.test.ts similarity index 100% rename from src/renderer/src/components/new-workspace/use-smart-workspace-field-availability.test.ts rename to src/renderer/src/components/new-workspace/source-search/use-smart-workspace-field-availability.test.ts diff --git a/src/renderer/src/components/new-workspace/use-smart-workspace-field-availability.ts b/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-field-availability.ts similarity index 94% rename from src/renderer/src/components/new-workspace/use-smart-workspace-field-availability.ts rename to src/renderer/src/components/new-workspace/source-search/use-smart-workspace-field-availability.ts index d3cc9d4adeb..b8b0119ae07 100644 --- a/src/renderer/src/components/new-workspace/use-smart-workspace-field-availability.ts +++ b/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-field-availability.ts @@ -1,14 +1,14 @@ import { useEffect, useMemo } from 'react' -import { filterAvailableTaskProviders } from '../../../../shared/work-items/task-providers' -import type { ExecutionHostId } from '../../../../shared/execution-host' +import { filterAvailableTaskProviders } from '../../../../../shared/work-items/task-providers' +import type { ExecutionHostId } from '../../../../../shared/execution-host' import { getMrStateFilters, getSmartWorkspaceNameModes } from './smart-workspace-localized-options' import { SEARCH_DEBOUNCE_MS, type NormalizedWorkItemSourceSearchProps -} from './smart-workspace-name-field-model' +} from '../name-field/smart-workspace-name-field-model' import { canUseGitLabSmartSource } from './smart-workspace-provider-availability' import type { useWorkItemSourceState } from './use-work-item-source-state' -import { useTranslate } from '../../i18n/use-translate' +import { useTranslate } from '../../../i18n/use-translate' type FieldState = ReturnType diff --git a/src/renderer/src/components/new-workspace/use-smart-workspace-github-search.ts b/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-github-search.ts similarity index 95% rename from src/renderer/src/components/new-workspace/use-smart-workspace-github-search.ts rename to src/renderer/src/components/new-workspace/source-search/use-smart-workspace-github-search.ts index 65ff165b4ef..987f816a515 100644 --- a/src/renderer/src/components/new-workspace/use-smart-workspace-github-search.ts +++ b/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-github-search.ts @@ -1,14 +1,14 @@ import { useEffect, useMemo } from 'react' import { useAppStore } from '@/store' -import { normalizeGitHubLinkQuery } from '../../../../shared/new-workspace/github-links' -import { parseGitHubIssueOrPRLink } from '../../../../shared/github/repositories/links' +import { normalizeGitHubLinkQuery } from '../../../../../shared/new-workspace/github-links' +import { parseGitHubIssueOrPRLink } from '../../../../../shared/github/repositories/links' import { lookupGitHubWorkItemByOwnerRepoForSource, lookupGitHubWorkItemForSource } from '@/lib/work-items/github/github-work-item-source-lookup' import { lookupSmartGitHubSubmitItem } from '@/lib/work-items/github/smart-github-submit' -import type { GitHubWorkItem } from '../../../../shared/github/work-items/work-item-types' -import { RESULT_LIMIT } from './smart-workspace-name-field-model' +import type { GitHubWorkItem } from '../../../../../shared/github/work-items/work-item-types' +import { RESULT_LIMIT } from '../name-field/smart-workspace-name-field-model' import { resolveSmartWorkspaceGithubDirectLink } from './smart-workspace-github-direct-link' import type { useWorkItemSourceFoundation } from './use-work-item-source-foundation' diff --git a/src/renderer/src/components/new-workspace/use-smart-workspace-gitlab-search.ts b/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-gitlab-search.ts similarity index 94% rename from src/renderer/src/components/new-workspace/use-smart-workspace-gitlab-search.ts rename to src/renderer/src/components/new-workspace/source-search/use-smart-workspace-gitlab-search.ts index 62278de3bf5..55fca23aff7 100644 --- a/src/renderer/src/components/new-workspace/use-smart-workspace-gitlab-search.ts +++ b/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-gitlab-search.ts @@ -3,9 +3,9 @@ import { listGitLabWorkItemsForSource, lookupGitLabWorkItemByPathForSource } from '@/lib/work-items/gitlab/gitlab-work-item-source-lookup' -import { parseGitLabIssueOrMRLink } from '../../../../shared/new-workspace/gitlab-links' -import type { GitLabWorkItem } from '../../../../shared/gitlab-types' -import { RESULT_LIMIT } from './smart-workspace-name-field-model' +import { parseGitLabIssueOrMRLink } from '../../../../../shared/new-workspace/gitlab-links' +import type { GitLabWorkItem } from '../../../../../shared/gitlab-types' +import { RESULT_LIMIT } from '../name-field/smart-workspace-name-field-model' import type { useWorkItemSourceFoundation } from './use-work-item-source-foundation' type Foundation = ReturnType diff --git a/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-foundation.source.test.tsx b/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-name-field-foundation.source.test.tsx similarity index 91% rename from src/renderer/src/components/new-workspace/use-smart-workspace-name-field-foundation.source.test.tsx rename to src/renderer/src/components/new-workspace/source-search/use-smart-workspace-name-field-foundation.source.test.tsx index e1900287378..a8eb2ed5132 100644 --- a/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-foundation.source.test.tsx +++ b/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-name-field-foundation.source.test.tsx @@ -2,11 +2,11 @@ import { linearIssueReadFixture } from '@/store/slices/linear/linear-slice-test- import { act, cleanup, renderHook, waitFor } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { useWorkItemSourceSearch } from './use-work-item-source-search' -import { referenceLinearIssue } from '../sidebar/workspace-card/review/workspace-reference-fixtures.test-support' -import type { Repo } from '../../../../shared/repo-types' -import type { LinearIssue } from '../../../../shared/linear/issue-types' -import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' -import type { NormalizedWorkItemSourceSearchProps } from './smart-workspace-name-field-model' +import { referenceLinearIssue } from '../../sidebar/workspace-card/review/workspace-reference-fixtures.test-support' +import type { Repo } from '../../../../../shared/repo-types' +import type { LinearIssue } from '../../../../../shared/linear/issue-types' +import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context' +import type { NormalizedWorkItemSourceSearchProps } from '../name-field/smart-workspace-name-field-model' // @vitest-environment happy-dom const mocks = vi.hoisted(() => ({ @@ -60,7 +60,7 @@ vi.mock('./use-jira-source-connection', () => ({ useJiraSourceConnection: () => ({ status: null, loaded: false }) })) vi.mock('./use-jira-url-source', () => ({ useJiraUrlSource: mocks.readJiraSource })) -vi.mock('../use-jira-project-inventory', () => ({ +vi.mock('../../use-jira-project-inventory', () => ({ useJiraProjectInventory: () => ({ projects: [], connected: true, error: null, loading: false }) })) diff --git a/src/renderer/src/components/new-workspace/use-smart-workspace-secondary-searches.ts b/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-secondary-searches.ts similarity index 92% rename from src/renderer/src/components/new-workspace/use-smart-workspace-secondary-searches.ts rename to src/renderer/src/components/new-workspace/source-search/use-smart-workspace-secondary-searches.ts index 0b1ccd3a61a..c871451e331 100644 --- a/src/renderer/src/components/new-workspace/use-smart-workspace-secondary-searches.ts +++ b/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-secondary-searches.ts @@ -5,20 +5,20 @@ import { mapLinearIssueRead, type LinearIssueRead } from '@/store/slices/linear/linear-issue-read-lifecycle' -import type { LinearIssue } from '../../../../shared/linear/issue-types' -import type { LinearCollectionResult } from '../../../../shared/linear/workspace-types' +import type { LinearIssue } from '../../../../../shared/linear/issue-types' +import type { LinearCollectionResult } from '../../../../../shared/linear/workspace-types' import { linearIssueViewError } from '@/lib/work-items/linear/linear-read-error' -import { getRepoExecutionHostId } from '../../../../shared/execution-host' +import { getRepoExecutionHostId } from '../../../../../shared/execution-host' import { useEffect, useMemo, useRef } from 'react' import { searchRuntimeRepoBaseRefDetails } from '@/runtime/source-control/references/runtime-repo-client' import { lookupLinearIssueUrl } from '@/lib/work-items/linear/linear-issue-url-lookup' import { searchJiraIssuesByKeyOrText } from '@/components/jira-key-or-text-search' -import { linearWorkspaceScopeSignature } from '../../../../shared/linear/workspace-types' -import { isIntegrationCredentialDecryptionError } from '../../../../shared/integration-credential-errors' -import { getSmartWorkspaceLinearSearchQuery } from '../../../../shared/new-workspace/smart-workspace-linear-intent' -import { RESULT_LIMIT } from './smart-workspace-name-field-model' -import { restrictJiraQueryToProject } from '../../../../shared/jira/jira-project-reference' -import { getBranchSearchRequest } from '../../../../shared/new-workspace/smart-workspace-source-results' +import { linearWorkspaceScopeSignature } from '../../../../../shared/linear/workspace-types' +import { isIntegrationCredentialDecryptionError } from '../../../../../shared/integration-credential-errors' +import { getSmartWorkspaceLinearSearchQuery } from '../../../../../shared/new-workspace/smart-workspace-linear-intent' +import { RESULT_LIMIT } from '../name-field/smart-workspace-name-field-model' +import { restrictJiraQueryToProject } from '../../../../../shared/jira/jira-project-reference' +import { getBranchSearchRequest } from '../../../../../shared/new-workspace/smart-workspace-source-results' import type { useWorkItemSourceFoundation } from './use-work-item-source-foundation' export function useSmartWorkspaceSecondarySearches({ diff --git a/src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts b/src/renderer/src/components/new-workspace/source-search/use-work-item-source-foundation.ts similarity index 95% rename from src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts rename to src/renderer/src/components/new-workspace/source-search/use-work-item-source-foundation.ts index 667e097bae2..ada1373cb3e 100644 --- a/src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts +++ b/src/renderer/src/components/new-workspace/source-search/use-work-item-source-foundation.ts @@ -3,13 +3,13 @@ import { useLinearIssueResult } from '@/hooks/linear-issue-committed-state' import { getLinearSourceScope } from '@/store/slices/linear/linear-slice-scope' import { getSelectedWorkspaceId } from '@/store/slices/linear/linear-cache' import { defaultScopeSource } from '@/runtime/hosts/selection/default-creation-host' -import { parseBoundedSmartWorkspaceLinearIssueUrlIntent } from '../../../../shared/new-workspace/smart-workspace-linear-intent' -import { isSmartWorkspaceSourceQueryWithinLimit } from '../../../../shared/new-workspace/smart-workspace-source-results' +import { parseBoundedSmartWorkspaceLinearIssueUrlIntent } from '../../../../../shared/new-workspace/smart-workspace-linear-intent' +import { isSmartWorkspaceSourceQueryWithinLimit } from '../../../../../shared/new-workspace/smart-workspace-source-query' import React, { useMemo } from 'react' import { useShallow } from 'zustand/react/shallow' import { useAppStore } from '@/store/index' import { getLocalPreflightContext } from '@/runtime/hosts/preflight/local-preflight-context' -import { buildTaskSourceContextFromRepo } from '../../../../shared/work-items/task-source-context' +import { buildTaskSourceContextFromRepo } from '../../../../../shared/work-items/task-source-context' import { useJiraSourceConnection } from './use-jira-source-connection' import { useJiraUrlSource } from './use-jira-url-source' import { useLinearSourceConnection } from './use-linear-source-connection' @@ -19,12 +19,12 @@ import { useJiraComposerProject } from './use-jira-composer-project' import { useComposerSourceScope } from './use-composer-source-scope' import type { LinearIssueData } from '@/store/slices/linear/linear-issue-read' import type { LinearIssueView } from '@/store/slices/linear/linear-issue-read-lifecycle' -import type { LinearIssue } from '../../../../shared/linear/issue-types' -import { localPreflightContextKey } from '../../runtime/hosts/preflight/local-preflight-context-key' +import type { LinearIssue } from '../../../../../shared/linear/issue-types' +import { localPreflightContextKey } from '../../../runtime/hosts/preflight/local-preflight-context-key' import type { NormalizedWorkItemSourceSearchProps, RepoBackedSearchTarget -} from './smart-workspace-name-field-model' +} from '../name-field/smart-workspace-name-field-model' export function useWorkItemSourceFoundation(props: NormalizedWorkItemSourceSearchProps) { const { diff --git a/src/renderer/src/components/new-workspace/use-work-item-source-presentation.ts b/src/renderer/src/components/new-workspace/source-search/use-work-item-source-presentation.ts similarity index 92% rename from src/renderer/src/components/new-workspace/use-work-item-source-presentation.ts rename to src/renderer/src/components/new-workspace/source-search/use-work-item-source-presentation.ts index 6d28c7b02d4..52fc1aa595c 100644 --- a/src/renderer/src/components/new-workspace/use-work-item-source-presentation.ts +++ b/src/renderer/src/components/new-workspace/source-search/use-work-item-source-presentation.ts @@ -1,22 +1,22 @@ import { useEffect, useMemo } from 'react' import { CaseSensitive, LoaderCircle, Search } from 'lucide-react' -import { parseGitHubIssueOrPRLink } from '../../../../shared/github/repositories/links' -import { parseGitLabIssueOrMRLink } from '../../../../shared/new-workspace/gitlab-links' +import { parseGitHubIssueOrPRLink } from '../../../../../shared/github/repositories/links' +import { parseGitLabIssueOrMRLink } from '../../../../../shared/new-workspace/gitlab-links' import { isSmartWorkspaceLinearIssueIntentMatch, parseBoundedSmartWorkspaceLinearIssueInput, parseBoundedSmartWorkspaceLinearIssueUrlIntent, prioritizeSmartWorkspaceLinearIssueResults -} from '../../../../shared/new-workspace/smart-workspace-linear-intent' -import { resolveSmartWorkspaceCommandValue } from './smart-workspace-command-value' +} from '../../../../../shared/new-workspace/smart-workspace-linear-intent' +import { resolveSmartWorkspaceCommandValue } from '../../../../../shared/new-workspace/smart-workspace-command-value' import { buildSmartWorkspaceSourceRows, getVisibleBranchResults, getVisibleHeldProviderResults, - isBlockingTaskUrlResolution, - isSmartWorkspaceSourceQueryWithinLimit -} from '../../../../shared/new-workspace/smart-workspace-source-results' -import { RESULT_LIMIT, type RowEntry } from './smart-workspace-name-field-model' + isBlockingTaskUrlResolution +} from '../../../../../shared/new-workspace/smart-workspace-source-results' +import { isSmartWorkspaceSourceQueryWithinLimit } from '../../../../../shared/new-workspace/smart-workspace-source-query' +import { RESULT_LIMIT, type RowEntry } from '../name-field/smart-workspace-name-field-model' import type { useWorkItemSourceFoundation } from './use-work-item-source-foundation' type Foundation = ReturnType diff --git a/src/renderer/src/components/new-workspace/use-work-item-source-search.ts b/src/renderer/src/components/new-workspace/source-search/use-work-item-source-search.ts similarity index 93% rename from src/renderer/src/components/new-workspace/use-work-item-source-search.ts rename to src/renderer/src/components/new-workspace/source-search/use-work-item-source-search.ts index 98ee5f0f157..1ff9e36e07f 100644 --- a/src/renderer/src/components/new-workspace/use-work-item-source-search.ts +++ b/src/renderer/src/components/new-workspace/source-search/use-work-item-source-search.ts @@ -1,16 +1,14 @@ import { resolveWorkItemSourceRow } from './work-item-source-selection' import { useCallback, useEffect, useMemo } from 'react' import { useTranslation } from 'react-i18next' -import { - getJiraIssueSearchQuery, - isSmartWorkspaceSourceQueryWithinLimit -} from '../../../../shared/new-workspace/smart-workspace-source-results' -import { parseBoundedSmartWorkspaceLinearIssueUrlIntent } from '../../../../shared/new-workspace/smart-workspace-linear-intent' +import { getJiraIssueSearchQuery } from '../../../../../shared/new-workspace/smart-workspace-source-results' +import { isSmartWorkspaceSourceQueryWithinLimit } from '../../../../../shared/new-workspace/smart-workspace-source-query' +import { parseBoundedSmartWorkspaceLinearIssueUrlIntent } from '../../../../../shared/new-workspace/smart-workspace-linear-intent' import { EMPTY_REPO_SEARCH_REPOS, type NormalizedWorkItemSourceSearchProps, type WorkItemSourceSearchProps -} from './smart-workspace-name-field-model' +} from '../name-field/smart-workspace-name-field-model' import { useWorkItemSourceFoundation } from './use-work-item-source-foundation' import { useSmartWorkspaceGithubSearch } from './use-smart-workspace-github-search' import { useSmartWorkspaceGitlabSearch } from './use-smart-workspace-gitlab-search' diff --git a/src/renderer/src/components/new-workspace/use-work-item-source-state.ts b/src/renderer/src/components/new-workspace/source-search/use-work-item-source-state.ts similarity index 79% rename from src/renderer/src/components/new-workspace/use-work-item-source-state.ts rename to src/renderer/src/components/new-workspace/source-search/use-work-item-source-state.ts index 7447094f87b..079a73451f1 100644 --- a/src/renderer/src/components/new-workspace/use-work-item-source-state.ts +++ b/src/renderer/src/components/new-workspace/source-search/use-work-item-source-state.ts @@ -1,13 +1,13 @@ import { useGitHubTaskItems } from '@/hooks/useGitHubTaskItems' import { useRef, useState } from 'react' -import type { RepoSlug } from '../../../../shared/github/repositories/links' -import type { GitHubWorkItem } from '../../../../shared/github/work-items/work-item-types' -import type { GitLabWorkItem } from '../../../../shared/gitlab-types' -import type { JiraIssue } from '../../../../shared/jira/jira-types' -import type { BaseRefSearchResult } from '../../../../shared/repo-types' -import type { SmartNameMode } from '../../../../shared/new-workspace/smart-workspace-source-results' +import type { RepoSlug } from '../../../../../shared/github/repositories/links' +import type { GitHubWorkItem } from '../../../../../shared/github/work-items/work-item-types' +import type { GitLabWorkItem } from '../../../../../shared/gitlab-types' +import type { JiraIssue } from '../../../../../shared/jira/jira-types' +import type { BaseRefSearchResult } from '../../../../../shared/repo-types' +import type { SmartNameMode } from '../../../../../shared/new-workspace/smart-workspace-source-results' import type { MrStateFilter } from './smart-workspace-localized-options' -import type { CrossRepoPrompt } from './smart-workspace-name-field-model' +import type { CrossRepoPrompt } from '../name-field/smart-workspace-name-field-model' export function useWorkItemSourceState(textOnly: boolean, value: string) { const [mode, setMode] = useState(textOnly ? 'text' : 'smart') diff --git a/src/renderer/src/components/new-workspace/work-item-source-selection.ts b/src/renderer/src/components/new-workspace/source-search/work-item-source-selection.ts similarity index 86% rename from src/renderer/src/components/new-workspace/work-item-source-selection.ts rename to src/renderer/src/components/new-workspace/source-search/work-item-source-selection.ts index 7d4a4fa2efd..a76cd60255a 100644 --- a/src/renderer/src/components/new-workspace/work-item-source-selection.ts +++ b/src/renderer/src/components/new-workspace/source-search/work-item-source-selection.ts @@ -1,17 +1,17 @@ -import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' -import { getMatchingJiraSites, parseJiraIssueUrl } from '../../../../shared/jira/jira-issue-url' -import type { JiraSite } from '../../../../shared/jira/jira-types' +import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context' +import { getMatchingJiraSites, parseJiraIssueUrl } from '../../../../../shared/jira/jira-issue-url' +import type { JiraSite } from '../../../../../shared/jira/jira-types' import { buildGitHubWorkspaceSource, buildGitLabWorkspaceSource, buildLinearWorkspaceSource, buildJiraWorkspaceSource, type WorkspaceSourceLinkedItem -} from '../../../../shared/new-workspace/workspace-source' -import { parseGitHubIssueOrPRLink } from '../../../../shared/github/repositories/links' -import { parseGitLabIssueOrMRLink } from '../../../../shared/new-workspace/gitlab-links' +} from '../../../../../shared/new-workspace/workspace-source' +import { parseGitHubIssueOrPRLink } from '../../../../../shared/github/repositories/links' +import { parseGitLabIssueOrMRLink } from '../../../../../shared/new-workspace/gitlab-links' import { bindJiraIssueSourceContext } from './use-jira-url-source' -import type { RowEntry } from './smart-workspace-name-field-model' +import type { RowEntry } from '../name-field/smart-workspace-name-field-model' export type WorkItemSourceContexts = Record< 'github' | 'gitlab' | 'linear' | 'jira', diff --git a/src/renderer/src/components/new-workspace/type-ahead-combobox-styles.ts b/src/renderer/src/components/new-workspace/type-ahead/type-ahead-combobox-styles.ts similarity index 100% rename from src/renderer/src/components/new-workspace/type-ahead-combobox-styles.ts rename to src/renderer/src/components/new-workspace/type-ahead/type-ahead-combobox-styles.ts diff --git a/src/renderer/src/components/new-workspace/use-type-ahead-combobox.ts b/src/renderer/src/components/new-workspace/type-ahead/use-type-ahead-combobox.ts similarity index 100% rename from src/renderer/src/components/new-workspace/use-type-ahead-combobox.ts rename to src/renderer/src/components/new-workspace/type-ahead/use-type-ahead-combobox.ts diff --git a/src/renderer/src/components/new-workspace/use-wheel-scrollable.ts b/src/renderer/src/components/new-workspace/type-ahead/use-wheel-scrollable.ts similarity index 100% rename from src/renderer/src/components/new-workspace/use-wheel-scrollable.ts rename to src/renderer/src/components/new-workspace/type-ahead/use-wheel-scrollable.ts diff --git a/src/renderer/src/components/sidebar/project-admission/menu/AddProjectMenu.fixture.tsx b/src/renderer/src/components/sidebar/project-admission/menu/AddProjectMenu.fixture.tsx index 75f98c2decc..95ec5c47508 100644 --- a/src/renderer/src/components/sidebar/project-admission/menu/AddProjectMenu.fixture.tsx +++ b/src/renderer/src/components/sidebar/project-admission/menu/AddProjectMenu.fixture.tsx @@ -4,7 +4,7 @@ import { getDefaultSettings } from '../../../../../../shared/constants' import type { PublicKnownRuntimeEnvironment } from '../../../../../../shared/remote-runtime/host-catalog/runtime-environments' import type { NewWorkspaceProjectOption } from '@/lib/workspace/creation/new-workspace-project-options' import type { ProjectHostSetupOption } from '@/lib/workspace/creation/project-host-setup-options' -import { NewWorkspaceComposerProjectSection } from '@/components/new-workspace/NewWorkspaceComposerProjectSection' +import { NewWorkspaceComposerProjectSection } from '@/components/new-workspace/composer/NewWorkspaceComposerProjectSection' import { SidebarHeaderActions } from '../../sidebar-header-actions' const ubuntuRuntime: PublicKnownRuntimeEnvironment = { diff --git a/src/renderer/src/components/sidebar/project-admission/menu/AddProjectMenu.test.tsx b/src/renderer/src/components/sidebar/project-admission/menu/AddProjectMenu.test.tsx index 447ae4083c3..5462d37a07b 100644 --- a/src/renderer/src/components/sidebar/project-admission/menu/AddProjectMenu.test.tsx +++ b/src/renderer/src/components/sidebar/project-admission/menu/AddProjectMenu.test.tsx @@ -12,11 +12,11 @@ import { getProjectHostSetupSelectionKey, type ProjectHostSetupOption } from '@/lib/workspace/creation/project-host-setup-options' -import { NewWorkspaceComposerProjectSection } from '@/components/new-workspace/NewWorkspaceComposerProjectSection' +import { NewWorkspaceComposerProjectSection } from '@/components/new-workspace/composer/NewWorkspaceComposerProjectSection' import { SidebarHeaderActions } from '../../sidebar-header-actions' import type { AddRepoDialogEntryRequest } from '../dialog/add-repo-dialog-types' -vi.mock('@/components/new-workspace/use-recent-project-ids', () => ({ +vi.mock('@/components/new-workspace/project-selection/use-recent-project-ids', () => ({ useRecentProjectIds: () => [] })) vi.mock('@/components/sidebar/host-admission/ssh/AddRemoteHostDialog', () => ({ diff --git a/src/renderer/src/components/sidebar/workspace-card/review/WorkspaceAttachmentSearch.tsx b/src/renderer/src/components/sidebar/workspace-card/review/WorkspaceAttachmentSearch.tsx index 233e5038831..c490573bfda 100644 --- a/src/renderer/src/components/sidebar/workspace-card/review/WorkspaceAttachmentSearch.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/review/WorkspaceAttachmentSearch.tsx @@ -12,11 +12,11 @@ import { import { useTranslate } from '@/i18n/use-translate' import { isScreenSubmitShortcut } from '@/lib/keyboard/screen-submit-shortcut' import type { WorkspaceAttachment } from '../../../../../../shared/worktree/types' -import type { RowEntry } from '../../../new-workspace/smart-workspace-name-field-model' +import type { RowEntry } from '../../../new-workspace/name-field/smart-workspace-name-field-model' import type { SmartNameMode } from '../../../../../../shared/new-workspace/smart-workspace-source-results' -import { useWorkItemSourceSearch } from '../../../new-workspace/use-work-item-source-search' -import { SmartWorkspaceSourceTabs } from '../../../new-workspace/SmartWorkspaceSourceTabs' -import { SmartWorkspaceSourceResultList } from '../../../new-workspace/SmartWorkspaceSourceResultList' +import { useWorkItemSourceSearch } from '../../../new-workspace/source-search/use-work-item-source-search' +import { SmartWorkspaceSourceTabs } from '../../../new-workspace/source-search/SmartWorkspaceSourceTabs' +import { SmartWorkspaceSourceResultList } from '../../../new-workspace/source-search/SmartWorkspaceSourceResultList' import { getWorkspaceAttachmentKey } from '../../../../../../shared/workspace-attachments/workspace-attachment-normalization' import { ATTACHMENT_INPUT_KINDS, diff --git a/src/renderer/src/components/sidebar/workspace-card/review/WorkspaceAttachmentSourceStatus.tsx b/src/renderer/src/components/sidebar/workspace-card/review/WorkspaceAttachmentSourceStatus.tsx index c69720e6f95..2e76ce0f280 100644 --- a/src/renderer/src/components/sidebar/workspace-card/review/WorkspaceAttachmentSourceStatus.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/review/WorkspaceAttachmentSourceStatus.tsx @@ -1,8 +1,8 @@ import type React from 'react' import { Button } from '@/components/ui/button' import { useTranslate } from '@/i18n/use-translate' -import { getJiraSourceStatusMessage } from '../../../new-workspace/jira-source-status-message' -import type { WorkItemSourceSearch } from '../../../new-workspace/use-work-item-source-search' +import { getJiraSourceStatusMessage } from '../../../new-workspace/source-search/jira-source-status-message' +import type { WorkItemSourceSearch } from '../../../new-workspace/source-search/use-work-item-source-search' export function WorkspaceAttachmentSourceStatus({ controller, diff --git a/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-source-selection.ts b/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-source-selection.ts index c694d72f11f..46fd00eae1a 100644 --- a/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-source-selection.ts +++ b/src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-source-selection.ts @@ -10,7 +10,7 @@ import '../../../../../../shared/project-groups' import '../../../../../../shared/repo-kind' import type { FolderWorkspace } from '../../../../../../shared/folder-workspaces/folder-workspace-types' -import type { SmartWorkspaceNameSelection } from '@/components/new-workspace/smart-workspace-name-field-model' +import type { SmartWorkspaceNameSelection } from '@/components/new-workspace/name-field/smart-workspace-name-field-model' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import './folder-workspace-source-repos' diff --git a/src/renderer/src/hooks/composer-state/composer-source-model.ts b/src/renderer/src/hooks/composer-state/composer-source-model.ts index 8ccc0f8b7a6..cd6d1339fcc 100644 --- a/src/renderer/src/hooks/composer-state/composer-source-model.ts +++ b/src/renderer/src/hooks/composer-state/composer-source-model.ts @@ -6,7 +6,7 @@ import type { TaskSourceContext } from '../../../../shared/work-items/task-sourc import type { LinearIssue } from '../../../../shared/linear/issue-types' import type { SparsePreset } from '../../../../shared/worktree/create-types' import type { PendingSmartGitHubSubmitResolution } from './source-selection-decisions' -import type { SmartWorkspaceNameSelection } from '@/components/new-workspace/smart-workspace-name-field-model' +import type { SmartWorkspaceNameSelection } from '@/components/new-workspace/name-field/smart-workspace-name-field-model' export type ComposerSourceModel = { addComposerAttachments: (paths: string[]) => void applyLinkedGitLabWorkItem: (item: GitLabWorkItem) => void diff --git a/src/renderer/src/hooks/composer-state/issue-source-actions.ts b/src/renderer/src/hooks/composer-state/issue-source-actions.ts index 2af025914fd..c3264f93677 100644 --- a/src/renderer/src/hooks/composer-state/issue-source-actions.ts +++ b/src/renderer/src/hooks/composer-state/issue-source-actions.ts @@ -54,7 +54,7 @@ import { import { getJiraIssueKeyCasingSeedOptions } from '@/lib/work-items/jira/jira-issue-key-casing' import '@/lib/workspace/creation/new-workspace' import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' -import type { SmartWorkspaceNameSelection } from '@/components/new-workspace/smart-workspace-name-field-model' +import type { SmartWorkspaceNameSelection } from '@/components/new-workspace/name-field/smart-workspace-name-field-model' import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' export function useIssueSourceActions(input: IssueSourceActionsInput) { diff --git a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-setup.test.tsx b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-setup.test.tsx index 5ecc1b4bf8f..6c373140871 100644 --- a/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-setup.test.tsx +++ b/src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-setup.test.tsx @@ -12,7 +12,7 @@ const { launchWorkItemDirect } = await import('./launch-work-item-direct') const { __resetTrustPromptChainForTests } = await import('../../../../runtime/repo-hooks/ensure-hooks-confirmed') const { DirectWorkItemSetupDialog } = - await import('@/components/new-workspace/DirectWorkItemSetupDialog') + await import('@/components/new-workspace/setup/DirectWorkItemSetupDialog') const hooks = { scripts: { setup: 'echo prepared' } } const args = { diff --git a/src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts b/src/shared/new-workspace/smart-workspace-source-results.test.ts similarity index 96% rename from src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts rename to src/shared/new-workspace/smart-workspace-source-results.test.ts index aa29dc0bb3c..e4505f69699 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts +++ b/src/shared/new-workspace/smart-workspace-source-results.test.ts @@ -3,12 +3,12 @@ import { buildSmartWorkspaceSourceRows, getVisibleBranchResults, shouldHoldSourceResultsForQuery -} from '../../../../shared/new-workspace/smart-workspace-source-results' +} from './smart-workspace-source-results' import { isSmartWorkspaceLinearIssueIntentMatch, parseBoundedSmartWorkspaceLinearIssueInput, prioritizeSmartWorkspaceLinearIssueResults -} from '../../../../shared/new-workspace/smart-workspace-linear-intent' +} from './smart-workspace-linear-intent' describe('Branch source results', () => { it('hides held branch results when the live query diverges from the settled query', () => { diff --git a/tests/e2e/smart-workspace-linear-read-test-fixtures.tsx b/tests/e2e/smart-workspace-linear-read-test-fixtures.tsx index 210a20e7aef..c8c28dc8d50 100644 --- a/tests/e2e/smart-workspace-linear-read-test-fixtures.tsx +++ b/tests/e2e/smart-workspace-linear-read-test-fixtures.tsx @@ -12,8 +12,8 @@ import { referenceLinearIssue, referenceRepo } from '../../src/renderer/src/components/sidebar/workspace-card/review/workspace-reference-fixtures.test-support' -import { SmartWorkspaceSourceResultList } from '../../src/renderer/src/components/new-workspace/SmartWorkspaceSourceResultList' -import { useWorkItemSourceSearch } from '../../src/renderer/src/components/new-workspace/use-work-item-source-search' +import { SmartWorkspaceSourceResultList } from '../../src/renderer/src/components/new-workspace/source-search/SmartWorkspaceSourceResultList' +import { useWorkItemSourceSearch } from '../../src/renderer/src/components/new-workspace/source-search/use-work-item-source-search' import type * as MainLinearClient from '../../src/main/linear/accounts/linear-account-client' import type * as RuntimeLinearClient from '@/runtime/linear/runtime-linear-client' import type * as RuntimeLinearIssueMutations from '@/runtime/linear/runtime-linear-issue-client' @@ -216,12 +216,18 @@ vi.mock('@/runtime/hosts/preflight/local-preflight-context-key', () => ({ localPreflightContextKey: () => 'test' })) vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) -vi.mock('../../src/renderer/src/components/new-workspace/use-jira-source-connection', () => ({ - useJiraSourceConnection: () => ({ status: null, loaded: false }) -})) -vi.mock('../../src/renderer/src/components/new-workspace/use-jira-url-source', () => ({ - useJiraUrlSource: () => ({ intent: false }) -})) +vi.mock( + '../../src/renderer/src/components/new-workspace/source-search/use-jira-source-connection', + () => ({ + useJiraSourceConnection: () => ({ status: null, loaded: false }) + }) +) +vi.mock( + '../../src/renderer/src/components/new-workspace/source-search/use-jira-url-source', + () => ({ + useJiraUrlSource: () => ({ intent: false }) + }) +) vi.mock('../../src/renderer/src/components/use-jira-project-inventory', () => ({ useJiraProjectInventory: () => ({ projects: [], connected: true, error: null, loading: false }) })) From 4a81270d6f12deca4903795c5cfe62ed4069b338 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 13 Nov 2026 00:47:44 -0800 Subject: [PATCH 03/17] test: remove duplicate language wrapper and orphan host teardown (#41909) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../scripts/ci/sharding/ci-shard-timings.json | 1 - ...uctured-agent-session-host-test-abandon.ts | 16 ----- .../plugin-language-pack-registry.test.ts | 60 ------------------- 3 files changed, 77 deletions(-) delete mode 100644 src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-abandon.ts delete mode 100644 src/main/plugins/contributions/plugin-language-pack-registry.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 8df7deddb60..def8b154703 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -2642,7 +2642,6 @@ "src/main/plugins/catalog/plugin-update-review-notices.test.ts": 175, "src/main/plugins/contributions/plugin-content-pack-registry.test.ts": 589, "src/main/plugins/contributions/plugin-icon-theme-registry.test.ts": 268, - "src/main/plugins/contributions/plugin-language-pack-registry.test.ts": 587, "src/main/plugins/contributions/plugin-syntax-registry.test.ts": 221, "src/main/plugins/contributions/plugin-theme-registries.test.ts": 250, "src/main/plugins/hooks/plugin-agent-hook-sites.test.ts": 279, diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-abandon.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-abandon.ts deleted file mode 100644 index b26fbff2522..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-abandon.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Simulate crash without releasing ownership. Stop delivery/renewals and drain in-flight writes -// before closing test databases so pending producers cannot commit after cleanup. - -import type { StructuredAgentSessionHost } from '../structured-agent-session-host' - -export async function abandonStructuredAgentSessionHost( - host: StructuredAgentSessionHost -): Promise { - // Stop admission before draining to prevent new delivery steps. - host['conversationDelivery'].dispose() - host['lifetime'].dispose() - await host['runtimeState'].stopLeaseRenewal() - await host['tasks'].drainAttaches() - await Promise.all([...host['sessions'].values()].map((session) => session.journal.close())) - host['sessions'].clear() -} diff --git a/src/main/plugins/contributions/plugin-language-pack-registry.test.ts b/src/main/plugins/contributions/plugin-language-pack-registry.test.ts deleted file mode 100644 index 0449989ed40..00000000000 --- a/src/main/plugins/contributions/plugin-language-pack-registry.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { fingerprintPluginConsent } from '../../../shared/plugins/approval/plugin-consent-fingerprint' -import { pluginManifestSchema } from '../../../shared/plugins/manifest/plugin-manifest' -import { PluginContentVerifier } from '../plugin-content-integrity' -import type { ValidDiscoveredPlugin } from '../plugin-discovery' -import { PluginLanguagePackRegistry } from './plugin-language-pack-registry' - -const roots: string[] = [] - -async function pluginWithCatalog(catalog: unknown): Promise { - const rootDir = await mkdtemp(join(tmpdir(), 'orca-plugin-language-registry-')) - roots.push(rootDir) - await mkdir(join(rootDir, 'locales')) - await writeFile(join(rootDir, 'locales', 'pt-BR.json'), JSON.stringify(catalog)) - const manifest = pluginManifestSchema.parse({ - manifestVersion: 1, - id: 'portuguese', - publisher: 'samples', - name: 'Portuguese', - version: '1.0.0', - engines: { orca: '>=1.0.0' }, - pluginApi: 1, - contributes: { - languagePacks: [{ locale: 'pt-BR', path: 'locales/pt-BR.json' }] - }, - capabilities: [] - }) - return { - pluginKey: 'samples.portuguese', - rootDir, - manifest, - consentFingerprint: fingerprintPluginConsent(manifest), - contentHash: null, - isDev: true - } -} - -afterEach(async () => { - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -describe('PluginLanguagePackRegistry', () => { - it('loads a pack that covers protected security copy, leaving that copy in English', async () => { - const plugin = await pluginWithCatalog({ - common: { save: 'Sávé' }, - auto: { components: { settings: { PluginConsentDialog: { disclaimer: 'Safe' } } } } - }) - const registry = new PluginLanguagePackRegistry(new PluginContentVerifier()) - - await registry.reconcile([plugin], () => true) - expect(registry.error(plugin.pluginKey)).toBeNull() - expect(registry.list()[0]?.catalog).toEqual({ - common: { save: 'Sávé' }, - auto: { components: { settings: {} } } - }) - }) -}) From 28e0a0243c364e0292d59a5076a29b4d7ec68eda Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:58:30 -0800 Subject: [PATCH 04/17] perf(sidebar): reuse tab ownership across activity projections (#41060) * perf(sidebar): reuse tab ownership index for activity summaries * perf(sidebar): share tab ownership across activity projections --------- Co-authored-by: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> --- .../worktree-agent-activity-summary.ts | 9 ++----- .../activity/worktree-agent-row-selectors.ts | 19 ++------------- .../activity/worktree-activity-state.ts | 8 ++----- .../lib/workspace/tabs/tab-worktree-index.ts | 24 +++++++++++++++++++ 4 files changed, 30 insertions(+), 30 deletions(-) create mode 100644 src/renderer/src/lib/workspace/tabs/tab-worktree-index.ts diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-activity-summary.ts b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-activity-summary.ts index 65dd3bcf182..f945ab011d1 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-activity-summary.ts +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-activity-summary.ts @@ -18,6 +18,7 @@ import { import type { AgentStatusOrchestrationContext } from '../../../../../../shared/agent-status/contracts/agent-status-types' import { agentVerdictDisplayMark } from '../../../../../../shared/agent-status/lifecycle/agent-main-agent-verdict' import { applyAgentPaneActivityFlags } from '../../../../../../shared/worktree-status-rollup' +import { getTabIdToWorktreeId } from '@/lib/workspace/tabs/tab-worktree-index' export type WorktreeAgentActivitySummary = { hasPermission: boolean @@ -105,13 +106,7 @@ function getWorktreeAgentActivitySummaries( return agentActivityCache.summaries } - // Index tabs once per snapshot so per-card summaries cost O(worktrees + agents). - const tabIdToWorktreeId = new Map() - for (const [worktreeId, tabs] of Object.entries(state.tabsByWorktree)) { - for (const tab of tabs) { - tabIdToWorktreeId.set(tab.id, worktreeId) - } - } + const tabIdToWorktreeId = getTabIdToWorktreeId(state.tabsByWorktree) const summaries = new Map() const summaryForWorktree = (worktreeId: string): WorktreeAgentActivitySummary => { diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-row-selectors.ts b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-row-selectors.ts index 12b6f915d6c..958474fd018 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-row-selectors.ts +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-row-selectors.ts @@ -1,6 +1,7 @@ import { getStructuredAgentSessionTabsByPaneKey } from '@/components/native-chat/session/status/structured-agent-session-tabs' import type { RetainedAgentEntry } from '@/store/slices/agent-status/agent-status-contract' import type { AppState } from '@/store/types' +import { getTabIdToWorktreeId } from '@/lib/workspace/tabs/tab-worktree-index' import type { AgentStatusEntry } from '../../../../../../shared/agent-status/contracts/agent-status-types' import type { MigrationUnsupportedPtyEntry } from '../../../../../../shared/agent-status/contracts/agent-status-ipc-payload' import { parsePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' @@ -55,7 +56,6 @@ type RetainedEntriesByWorktreeCache = { entriesByWorktree: Map } -let tabWorktreeIndexCache: TabWorktreeIndexCache | null = null let liveTabWorktreeIndexCache: LiveTabWorktreeIndexCache | null = null let liveEntriesByWorktreeCache: LiveEntriesByWorktreeCache | null = null let migrationUnsupportedByWorktreeCache: MigrationUnsupportedByWorktreeCache | null = null @@ -74,22 +74,7 @@ export function reuseArrayIfEqual(previous: T[] | undefined, next: T[]): T[] return previous } -// Settings reuses this tab index to avoid rescanning every bucket on each store write. -export function getTabIdToWorktreeId( - tabsByWorktree: WorktreeAgentRowsState['tabsByWorktree'] -): Map { - if (tabWorktreeIndexCache?.tabsByWorktree === tabsByWorktree) { - return tabWorktreeIndexCache.tabIdToWorktreeId - } - const tabIdToWorktreeId = new Map() - for (const [worktreeId, tabs] of Object.entries(tabsByWorktree)) { - for (const tab of tabs) { - tabIdToWorktreeId.set(tab.id, worktreeId) - } - } - tabWorktreeIndexCache = { tabsByWorktree, tabIdToWorktreeId } - return tabIdToWorktreeId -} +export { getTabIdToWorktreeId } function getLiveTabIdToWorktreeId( tabsByWorktree: WorktreeAgentRowsState['tabsByWorktree'], diff --git a/src/renderer/src/lib/workspace/activity/worktree-activity-state.ts b/src/renderer/src/lib/workspace/activity/worktree-activity-state.ts index b7f4d8d816f..a2ff6739af1 100644 --- a/src/renderer/src/lib/workspace/activity/worktree-activity-state.ts +++ b/src/renderer/src/lib/workspace/activity/worktree-activity-state.ts @@ -1,4 +1,5 @@ import type { AppState } from '@/store/types' +import { getTabIdToWorktreeId } from '../tabs/tab-worktree-index' import { createAgentStatusEpochSelector } from '../../agent-status/evidence/agent-status-epoch-selector' import { tabHasLivePty } from '../../../../../shared/tab-has-live-pty' import type { TerminalTab } from '../../../../../shared/workspace-layout/terminal-tab-types' @@ -50,12 +51,7 @@ export function getLiveAgentStatusByWorktreeId( if (entries.length === 0) { return new Map() } - const worktreeIdByTabId = new Map() - for (const [worktreeId, tabs] of Object.entries(tabsByWorktree ?? {})) { - for (const tab of tabs) { - worktreeIdByTabId.set(tab.id, worktreeId) - } - } + const worktreeIdByTabId = getTabIdToWorktreeId(tabsByWorktree) const result = new Map() for (const entry of entries) { const worktreeId = resolveAgentStatusWorktreeId(entry, worktreeIdByTabId) diff --git a/src/renderer/src/lib/workspace/tabs/tab-worktree-index.ts b/src/renderer/src/lib/workspace/tabs/tab-worktree-index.ts new file mode 100644 index 00000000000..57ba419cde7 --- /dev/null +++ b/src/renderer/src/lib/workspace/tabs/tab-worktree-index.ts @@ -0,0 +1,24 @@ +export type TabOwnershipRows = Record + +// Keep full and projected catalogs cached without retaining replaced snapshots. +const tabWorktreeIndexes = new WeakMap>() + +export function getTabIdToWorktreeId( + tabsByWorktree: TabOwnershipRows | null | undefined +): Map { + if (!tabsByWorktree) { + return new Map() + } + const cached = tabWorktreeIndexes.get(tabsByWorktree) + if (cached) { + return cached + } + const index = new Map() + for (const [worktreeId, tabs] of Object.entries(tabsByWorktree)) { + for (const tab of tabs) { + index.set(tab.id, worktreeId) + } + } + tabWorktreeIndexes.set(tabsByWorktree, index) + return index +} From 2850c00006847196dc3625587265e00d3b84d117 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 13 Nov 2026 01:17:39 -0800 Subject: [PATCH 05/17] test: remove low-value smoke, wrapper, and copy assertions (#41925) * test: remove prebuilt declarative demo smoke suite * test: remove static Box summary copy assertion * test: remove redundant wrapper cases and copied assertions --------- Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../scripts/ci/sharding/ci-shard-timings.json | 1 - .../native-chat-link-peek-context.test.tsx | 5 -- .../listing/detected-worktree-meta.test.ts | 62 --------------- .../catalog/plugin-catalog-release.test.ts | 14 ---- .../plugin-declarative-catalog-rich.test.ts | 3 - .../plugin-declarative-example.test.ts | 79 ------------------- .../plugin-declarative-tree.test.ts | 10 +-- .../testing/orca-testing-box.test.ts | 5 -- .../testing/orca-testing-hooks.test.ts | 24 ------ .../testing/testing-editor-host.test.ts | 17 ---- 10 files changed, 2 insertions(+), 218 deletions(-) delete mode 100644 src/shared/plugins/declarative/plugin-declarative-example.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index def8b154703..6e57540494d 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -6518,7 +6518,6 @@ "src/shared/plugins/contributions/plugin-content-pack-contributions.test.ts": 227, "src/shared/plugins/contributions/plugin-custom-editor-contribution.test.ts": 238, "src/shared/plugins/declarative/plugin-declarative-catalog-rich.test.ts": 147, - "src/shared/plugins/declarative/plugin-declarative-example.test.ts": 198, "src/shared/plugins/declarative/plugin-declarative-tree.test.ts": 168, "src/shared/plugins/declarative/runtime/declarative-act-snapshot.test.ts": 64, "src/shared/plugins/declarative/runtime/declarative-error-location.test.ts": 63, diff --git a/src/renderer/src/components/native-chat/links/previews/native-chat-link-peek-context.test.tsx b/src/renderer/src/components/native-chat/links/previews/native-chat-link-peek-context.test.tsx index b5972eab6a1..62d314a06ad 100644 --- a/src/renderer/src/components/native-chat/links/previews/native-chat-link-peek-context.test.tsx +++ b/src/renderer/src/components/native-chat/links/previews/native-chat-link-peek-context.test.tsx @@ -32,11 +32,6 @@ it.each([ owner: { executionHostId: 'runtime:env' as const, connectionId: 'T' }, runtimeEnvironmentId: 'env', expectedHost: 'nested:env/T' - }, - { - owner: { executionHostId: 'runtime:env' as const, connectionId: 'U' }, - runtimeEnvironmentId: 'env', - expectedHost: 'nested:env/U' } ])( 'routes a folder chat preview through $expectedHost', diff --git a/src/renderer/src/store/slices/worktrees/listing/detected-worktree-meta.test.ts b/src/renderer/src/store/slices/worktrees/listing/detected-worktree-meta.test.ts index 2c85e16d7b3..cf3ac012d8e 100644 --- a/src/renderer/src/store/slices/worktrees/listing/detected-worktree-meta.test.ts +++ b/src/renderer/src/store/slices/worktrees/listing/detected-worktree-meta.test.ts @@ -1,76 +1,14 @@ import { describe, expect, it } from 'vitest' -import { hostWorktreeTarget } from '../../../../../../shared/worktree/host-qualified-identity' import { findKnownWorktreeById } from './detected-worktree-meta' import { makeFolderWorkspace, makeProjectGroup } from '../../../../components/sidebar/workspace-creation/folder/folder-workspace-composer-submit-fixtures' -import { findFolderWorkspaceOwner } from '@/lib/workspace/ownership/folder-workspace-runtime-owner' -import { selectWorkspaceByHostTarget } from '../../../workspaces/selection/workspace-host-target' -import { resolveWorkspaceDirectory } from '@/lib/workspace/paths/workspace-directory' import { resolveQualifiedFolderWorkspaceResult } from '../../../../../../shared/folder-workspaces/folder-workspace-execution-host' import type { Repo } from '../../../../../../shared/repo-types' -import { findIndexedFolderWorkspaceOwner } from '@/lib/workspace/ownership/worktree-runtime-owner-index' -import { folderWorkspaceToWorktree } from '../../../../../../shared/folder-workspaces/folder-workspace-worktree' -import { resolveNotificationTabOwner } from '@/attention/notification-subject-owner' -import { getWorktreeDeleteStateKey } from '../teardown/worktree-delete-state' describe('inherited folder consumer identity', () => { - it.each([false, true])( - 'keeps physical twins qualified through native owner, store and directory, reversed=%s', - (reverse) => { - const inherited = makeFolderWorkspace({ - id: 'same', - projectGroupId: 'inherited', - folderPath: '/remote' - }) - const local = makeFolderWorkspace({ - id: 'same', - executionHostId: 'local', - folderPath: '/local' - }) - const folderWorkspaces = reverse ? [inherited, local] : [local, inherited] - const state = { - folderWorkspaces, - projectGroups: [{ id: 'inherited', executionHostId: 'ssh:box' as const }], - repos: [], - worktreesByRepo: {}, - detectedWorktreesByRepo: {}, - floatingWorkspacePath: null - } - const raw = findIndexedFolderWorkspaceOwner(folderWorkspaces, 'same', 'ssh:box') - const converted = folderWorkspaceToWorktree(inherited) - const notification = resolveNotificationTabOwner(state, { - worktreeId: 'folder:same', - executionHostId: 'ssh:box' - }) - expect(resolveQualifiedFolderWorkspaceResult(state, 'same', 'ssh:box').kind).toBe('selected') - expect(findFolderWorkspaceOwner(state, 'same', 'ssh:box')).toBe(inherited) - const projected = findKnownWorktreeById(state, 'folder:same', 'ssh:box') - expect(projected).toMatchObject({ path: '/remote', hostId: 'ssh:box' }) - expect( - selectWorkspaceByHostTarget( - state, - hostWorktreeTarget({ id: 'folder:same', hostId: 'ssh:box' }) - ) - ).toBe(projected) - expect(resolveWorkspaceDirectory(state, 'folder:same', 'ssh:box')).toBe('/remote') - expect(findKnownWorktreeById(state, 'folder:same')).toBeUndefined() - expect(findIndexedFolderWorkspaceOwner(folderWorkspaces, 'same', 'ssh:box')).toBe(raw) - expect(folderWorkspaceToWorktree(inherited)).toEqual(converted) - expect( - resolveNotificationTabOwner(state, { - worktreeId: 'folder:same', - executionHostId: 'ssh:box' - }) - ).toEqual(notification) - expect(inherited.executionHostId).toBeUndefined() - expect(getWorktreeDeleteStateKey(state, 'folder:same', 'ssh:box')).not.toBe( - getWorktreeDeleteStateKey(state, 'folder:same', 'local') - ) - } - ) it.each(['group', 'repo'])( 'invalidates only a changed derived host projection from its %s catalog', (source) => { diff --git a/src/shared/plugins/catalog/plugin-catalog-release.test.ts b/src/shared/plugins/catalog/plugin-catalog-release.test.ts index e8929abdd25..07e8adb4085 100644 --- a/src/shared/plugins/catalog/plugin-catalog-release.test.ts +++ b/src/shared/plugins/catalog/plugin-catalog-release.test.ts @@ -5,7 +5,6 @@ import { pluginCatalogReleaseSchema, type PluginCatalogRelease } from './plugin-catalog-release' -import { pluginContributionSummary } from '../contributions/plugin-contribution-summary' import { parsePluginManifest, type PluginManifest } from '../manifest/plugin-manifest' const COMMIT = 'c'.repeat(40) @@ -111,13 +110,6 @@ describe('catalog releases', () => { expect(check(release({ types: ['syntax'], fileTypes: ['typ', 'gleam'] }), syntaxManifest)).toBe( 'file types do not match the catalog release' ) - // A newer catalog's odd entries are dropped instead of hiding the whole release. - expect( - pluginCatalogReleaseSchema.parse({ - ...release(), - fileTypes: ['.typ', 'typ', 7, 'typ', ...Array.from({ length: 40 }, (_, i) => `t${i}`)] - }).fileTypes - ).toEqual(['typ', ...Array.from({ length: 31 }, (_, i) => `t${i}`)]) expect(check(release({ types: ['syntax'], name: 'Other' }), syntaxManifest)).toBe( 'plugin name does not match the catalog release' ) @@ -132,12 +124,6 @@ describe('catalog release summaries', () => { }) const base = { manifest: themed, resolvedCommit: COMMIT, contentHash: HASH } const listed = release({ types: ['app-theme'] }) - expect( - pluginCatalogReleaseError({ - ...base, - release: { ...listed, contributes: pluginContributionSummary(themed), capabilities: [] } - }) - ).toBeNull() expect( pluginCatalogReleaseError({ ...base, diff --git a/src/shared/plugins/declarative/plugin-declarative-catalog-rich.test.ts b/src/shared/plugins/declarative/plugin-declarative-catalog-rich.test.ts index 116c32b85f2..623bc4022df 100644 --- a/src/shared/plugins/declarative/plugin-declarative-catalog-rich.test.ts +++ b/src/shared/plugins/declarative/plugin-declarative-catalog-rich.test.ts @@ -35,9 +35,6 @@ describe('catalog 2 components', () => { expect(result.tree?.children.map((child) => typeof child !== 'string' && child.type)).toEqual( ['Unsupported', 'Unsupported', 'Text'] ) - expect(result.warnings).toEqual( - expect.arrayContaining(['Table: ignored invalid rows', 'Tree: ignored invalid items']) - ) } }) }) diff --git a/src/shared/plugins/declarative/plugin-declarative-example.test.ts b/src/shared/plugins/declarative/plugin-declarative-example.test.ts deleted file mode 100644 index b3c1808ebeb..00000000000 --- a/src/shared/plugins/declarative/plugin-declarative-example.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import path from 'node:path' -import { pathToFileURL } from 'node:url' -import { afterAll, expect, it } from 'vitest' -import { parsePluginDeclarativeTree } from './plugin-declarative-tree' - -const ROOT = path.resolve(import.meta.dirname, '..', '..', '..', '..') -const RUNTIME = path.join(ROOT, 'resources', 'plugins', 'declarative', 'orca-runtime.mjs') -const EXAMPLE = path.join(ROOT, 'examples', 'plugins', 'hello-components', 'dist', 'panel.js') -const scratch = mkdtempSync(path.join(tmpdir(), 'orca-declarative-')) -afterAll(() => rmSync(scratch, { recursive: true, force: true })) - -it('runs the prebuilt sample against the shipped guest runtime, like the guest import map would', async () => { - // Why copies: a fresh module instance per test, with `orca` resolved the way the guest import map does. - const runtimeCopy = path.join(scratch, 'orca-runtime.mjs') - writeFileSync(runtimeCopy, readFileSync(RUNTIME)) - const runtimeUrl = pathToFileURL(runtimeCopy).href - const panel = readFileSync(EXAMPLE, 'utf8').replace( - /from "orca(?:\/jsx-runtime)?"/g, - `from ${JSON.stringify(runtimeUrl)}` - ) - const panelCopy = path.join(scratch, 'panel.mjs') - writeFileSync(panelCopy, panel) - - const orca = await import(/* @vite-ignore */ runtimeUrl) - const posted: { event: string; payload: { revision: number; tree: unknown } }[] = [] - const runtime = orca.installOrcaDeclarativeRuntime({ - post: (event: string, payload: { revision: number; tree: unknown }) => - posted.push({ event, payload }), - bridge: null - }) - await runtime.boot(await import(/* @vite-ignore */ pathToFileURL(panelCopy).href)) - const { document } = runtime - - const first = posted.at(-1)!.payload - const parsed = parsePluginDeclarativeTree(first.tree) - expect(parsed).toMatchObject({ ok: true, warnings: [] }) - expect(JSON.stringify(first.tree)).toContain( - '{"type":"Badge","key":"#1","props":{"tone":"accent"},"children":["1"," open"]}' - ) - - const input = JSON.stringify(first.tree).match(/"Input".*?"onChange":\{"\$callback":"([^"]+)"/) - expect(input).not.toBeNull() - expect( - runtime.dispatchEvent({ - document, - revision: first.revision, - callback: input![1], - args: ['Ship it'], - edit: 1 - }) - ).toBe(true) - runtime.flush() - const second = posted.at(-1)!.payload - const submit = JSON.stringify(second.tree).match(/"onSubmit":\{"\$callback":"([^"]+)"/) - expect( - runtime.dispatchEvent({ - document, - revision: second.revision, - callback: submit![1], - args: ['Ship it'] - }) - ).toBe(true) - runtime.flush() - const renders = posted.filter((entry) => entry.event === 'ui.render') - expect(JSON.stringify(renders.at(-1)!.payload.tree)).toContain('Ship it') - expect(parsePluginDeclarativeTree(renders.at(-1)!.payload.tree).ok).toBe(true) - // The list is a persisted atom: the change goes to Orca for the next run. - expect(posted.filter((entry) => entry.event === 'ui.persist')).toEqual([ - { - event: 'ui.persist', - payload: expect.objectContaining({ - entries: [expect.objectContaining({ scope: 'plugin', key: 'todos', version: 1 })] - }) - } - ]) - runtime.dispose() -}) diff --git a/src/shared/plugins/declarative/plugin-declarative-tree.test.ts b/src/shared/plugins/declarative/plugin-declarative-tree.test.ts index 79c8c6f9d88..ad287ecfe48 100644 --- a/src/shared/plugins/declarative/plugin-declarative-tree.test.ts +++ b/src/shared/plugins/declarative/plugin-declarative-tree.test.ts @@ -8,7 +8,7 @@ const node = (type: string, props: Record = {}, children: unkno }) describe('parsePluginDeclarativeTree', () => { - it('drops unknown props and enum values with a warning instead of refusing', () => { + it('drops unknown props and enum values instead of refusing', () => { const result = parsePluginDeclarativeTree( node('Stack', { className: 'p-4', gap: 'huge' }, [ node('Text', { tone: '#ff0000' }, ['x']), @@ -22,12 +22,6 @@ describe('parsePluginDeclarativeTree', () => { { type: 'IconButton', props: { icon: 'skull' } } ] }) - expect(result.ok && result.warnings).toEqual([ - 'Stack: ignored unknown prop "className"', - 'Stack: ignored invalid gap', - 'Text: ignored invalid tone', - 'IconButton: unknown icon "skull"; showing a fallback glyph' - ]) }) it('draws unknown components, and known ones missing a required prop, as placeholders', () => { @@ -45,7 +39,7 @@ describe('parsePluginDeclarativeTree', () => { }) describe('ui.* payloads', () => { - it('counts text children toward the node cap and charges each one', () => { + it('counts text children toward the aggregate node cap', () => { const many = (count: number) => ({ type: 'Text', props: {}, diff --git a/src/shared/plugins/declarative/testing/orca-testing-box.test.ts b/src/shared/plugins/declarative/testing/orca-testing-box.test.ts index 54bcbfb115b..7bea965299b 100644 --- a/src/shared/plugins/declarative/testing/orca-testing-box.test.ts +++ b/src/shared/plugins/declarative/testing/orca-testing-box.test.ts @@ -45,9 +45,4 @@ describe('orca/testing reads Box', () => { expect(panel.errors).toEqual([]) expect(panel.warnings).toEqual([]) }) - - it('summarizes what sits in Boxes, and danger or warning Boxes themselves', async () => { - panel = await mount({ default: Status }) - expect(panel.summary()).toEqual(['Heading "Services"', 'Box danger "billing Down"']) - }) }) diff --git a/src/shared/plugins/declarative/testing/orca-testing-hooks.test.ts b/src/shared/plugins/declarative/testing/orca-testing-hooks.test.ts index dbe2b415f1a..4944076da36 100644 --- a/src/shared/plugins/declarative/testing/orca-testing-hooks.test.ts +++ b/src/shared/plugins/declarative/testing/orca-testing-hooks.test.ts @@ -36,28 +36,4 @@ describe('orca/testing hooks', () => { event: send }) }) - - it('fires editor.save.before and returns the text the worker wrote', async () => { - const formatter = { - default(orca: { - hooks: { - on(hook: string, handler: (e: unknown, next: (e: unknown) => unknown) => unknown): unknown - } - }) { - orca.hooks.on('editor.save.before', (event, next) => - next({ ...Object(event), text: `${String(Object(event).text).trim()}\n` }) - ) - } - } - const worker = await mountWorker(formatter, { - events: [], - commands: [], - hooks: ['editor.save.before'] - }) - const save = { workspaceId: 'wt-1', path: 'src/a.ts', languageId: 'typescript', text: ' x ' } - await expect(worker.hooks.fire('editor.save.before', save)).resolves.toEqual({ - kind: 'continue', - event: { ...save, text: 'x\n' } - }) - }) }) diff --git a/src/shared/plugins/declarative/testing/testing-editor-host.test.ts b/src/shared/plugins/declarative/testing/testing-editor-host.test.ts index c449e6367b7..dd2c3c73d3f 100644 --- a/src/shared/plugins/declarative/testing/testing-editor-host.test.ts +++ b/src/shared/plugins/declarative/testing/testing-editor-host.test.ts @@ -36,20 +36,3 @@ describe('mockEditorHost', () => { doc.dispose() }) }) - -describe('mockEditorHost saves as Orca does', () => { - it('blocks a save after an oversized edit until a later edit lands', async () => { - host = mockEditorHost({ text: 'a' }) - const { document } = host.orca - const send = (text: string): Promise => - document.applyEdit({ baseVersion: 1, content: { kind: 'text', text } }) - await session() - await expect(send('x'.repeat(64 * 1024 * 1024 + 1))).rejects.toMatchObject({ - code: 'too_large' - }) - await expect(host.flush()).rejects.toThrow(/too large/) - await send('fits') - await expect(host.flush()).resolves.toBeUndefined() - expect(host.text).toBe('fits') - }) -}) From 799f88ec66452db91bb1e2e419ef08f186920a50 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 13 Nov 2026 01:20:39 -0800 Subject: [PATCH 06/17] perf: window expanded sidebar workspace families (#41237) * perf: virtualize individual sidebar workspace descendants * chore: combine sidebar identity imports * fix: preserve sidebar interactions with individual rows * perf: derive sidebar fallback lookups only when needed * test: document narrow sidebar geometry fixtures * chore: keep sidebar lookup compatible with React compiler * Dismiss lineage tooltips when toggling child workspaces * fix: use measured rows for sidebar collapse and scroll * test: exercise descendant deletion scroll takeover * fix: keep sidebar scroll marks compiler compatible * fix: complete sidebar reveal and folder surface integration --- src/renderer/src/assets/main.css | 18 ++ .../use-worktree-context-menu-commands.ts | 4 - .../worktree-context-menu-policy.ts | 15 +- .../sleep/sleep-worktree-sidebar-position.ts | 17 +- .../activity/WorktreeCardAgents.tsx | 31 +- .../identity/WorktreeLineageToggle.test.tsx | 52 ++++ .../worktree-lineage-toggle-handler-cache.ts | 1 - .../worktree-list/drag/drop-commit-context.ts | 5 + .../worktree-list/drag/pointer-commit.ts | 6 +- .../drag/project-group-header-drag.ts | 9 +- .../worktree-list/drag/project-header-drag.ts | 9 +- .../worktree-list/drag/use-document-drop.ts | 6 +- .../drag/use-drop-commit-context.ts | 2 + .../worktree-list/drag/use-header-drag.ts | 25 +- .../drag/use-lineage-drop-commit.ts | 58 +++- .../drag/use-native-autoscroll.ts | 6 + .../worktree-list/drag/use-native-drag.ts | 14 +- .../drag/use-pointer-autoscroll.ts | 6 + .../worktree-list/drag/use-pointer-drag.ts | 6 +- .../sidebar/worktree-list/drag/use-session.ts | 26 +- .../worktree-drag-preview-offsets.test.ts | 21 ++ .../drag/worktree-drag-preview-offsets.ts | 10 +- .../drag/worktree-lineage-drag-drop.test.ts | 32 +- .../drag/worktree-lineage-drag-drop.ts | 27 +- .../drag/worktree-sidebar-drag-autoscroll.ts | 1 + .../drag/worktree-sidebar-drop-preview.ts | 42 +-- ....lineage-agent-expansion-coupling.test.tsx | 17 +- .../listing/lineage-row-projection.ts | 215 +++++++++++++ .../worktree-list/listing/render-row.ts | 11 +- .../worktree-list/listing/renderable-rows.ts | 57 +--- .../navigation/active-descendant-option.ts | 31 +- .../navigation/mounted-row-reveal.ts | 32 +- .../navigation/pending-reveal-inputs.ts | 30 ++ .../navigation/render-row-lookup.ts | 21 +- .../navigation/use-pending-reveal.ts | 66 ++-- .../navigation/worktree-sidebar-reveal.ts | 20 +- .../sidebar/worktree-list/rows/folder-row.tsx | 18 +- .../sidebar/worktree-list/rows/item-row.tsx | 97 +----- .../rows/virtual-row-dispatch.tsx | 166 +++++----- .../viewport/VirtualizedWorktreeViewport.tsx | 92 +++--- .../viewport/sidebar-smooth-reveal.test.tsx | 170 ++++++++++ .../viewport/sidebar-smooth-reveal.ts | 90 ++++++ .../viewport/use-keyboard-navigation.ts | 30 ++ .../viewport/use-row-geometry.test.tsx | 159 ++++++++++ .../viewport/use-row-geometry.ts | 205 ++++++++++++ .../use-row-measurement.scroll.test.tsx | 291 ++++++++++++++++++ .../viewport/use-row-measurement.ts | 31 +- .../viewport/use-row-removal-animation.ts | 124 -------- .../viewport/use-scroll-suppression.ts | 77 +---- .../viewport/use-scroll-to-top.ts | 6 + .../worktree-list/viewport/use-virtualizer.ts | 64 ++-- .../viewport/use-visible-review-refresh.ts | 4 +- .../viewport/virtual-row-context.ts | 9 + .../worktree-list/viewport/virtual-rows.ts | 49 +-- .../requestVirtualizedScrollAnchorRecord.ts | 29 +- .../src/hooks/useVirtualizedScrollAnchor.ts | 18 +- 56 files changed, 1821 insertions(+), 857 deletions(-) create mode 100644 src/renderer/src/components/sidebar/workspace-card/identity/WorktreeLineageToggle.test.tsx create mode 100644 src/renderer/src/components/sidebar/worktree-list/drag/worktree-drag-preview-offsets.test.ts create mode 100644 src/renderer/src/components/sidebar/worktree-list/listing/lineage-row-projection.ts create mode 100644 src/renderer/src/components/sidebar/worktree-list/viewport/sidebar-smooth-reveal.test.tsx create mode 100644 src/renderer/src/components/sidebar/worktree-list/viewport/sidebar-smooth-reveal.ts create mode 100644 src/renderer/src/components/sidebar/worktree-list/viewport/use-keyboard-navigation.ts create mode 100644 src/renderer/src/components/sidebar/worktree-list/viewport/use-row-geometry.test.tsx create mode 100644 src/renderer/src/components/sidebar/worktree-list/viewport/use-row-geometry.ts create mode 100644 src/renderer/src/components/sidebar/worktree-list/viewport/use-row-measurement.scroll.test.tsx delete mode 100644 src/renderer/src/components/sidebar/worktree-list/viewport/use-row-removal-animation.ts diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index 6100df6a3fb..4a0ccb646b0 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -1673,6 +1673,7 @@ html.native-shell .app-layout { /* Why: the brighter border carries the selected state; a translucent wash keeps card text legible instead of lifting the surface toward the foreground color. */ +[data-worktree-family-segment='primary'], [data-worktree-card-surface][data-worktree-card-active='primary'] { border-color: var( --worktree-sidebar-active-border, @@ -1685,6 +1686,7 @@ html.native-shell .app-layout { box-shadow: 0 1px 2px color-mix(in srgb, var(--worktree-sidebar-foreground) 4%, transparent); } +.dark [data-worktree-family-segment='primary'], .dark [data-worktree-card-surface][data-worktree-card-active='primary'] { border-color: var( --worktree-sidebar-active-border, @@ -1710,18 +1712,34 @@ html.native-shell .app-layout { } } +[data-worktree-family-segment='secondary'], [data-worktree-card-surface][data-worktree-card-active='secondary'] { border-color: color-mix(in srgb, var(--sidebar-ring) 25%, transparent); background: color-mix(in srgb, var(--sidebar-accent) 45%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--sidebar-ring) 15%, transparent); } +.dark [data-worktree-family-segment='secondary'], .dark [data-worktree-card-surface][data-worktree-card-active='secondary'] { border-color: color-mix(in srgb, var(--sidebar-ring) 28%, transparent); background: color-mix(in srgb, var(--sidebar-accent) 34%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--sidebar-ring) 18%, transparent); } +/* Family paint owns the surface in both themes, including secondary occurrences. */ +.worktree-sidebar-family-root [data-worktree-card-surface][data-worktree-card-active], +.dark .worktree-sidebar-family-root [data-worktree-card-surface][data-worktree-card-active] { + background: transparent; + border-color: transparent; + box-shadow: none; +} + +/* Continuous segments must not cast a horizontal shadow at every virtual boundary. */ +[data-worktree-family-segment], +.dark [data-worktree-family-segment] { + box-shadow: none; +} + /* #19624: mix text tokens toward sidebar in oklab for theme-stable perceptual dimming; preserve unread amber at full brightness. */ [data-worktree-sleeping-dim] { color: color-mix(in oklab, var(--worktree-sidebar-foreground) 52%, var(--worktree-sidebar)); diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-commands.ts b/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-commands.ts index 82e0362fb2e..288728d5541 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-commands.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-commands.ts @@ -15,7 +15,6 @@ import { activateAndRevealWorktree } from '@/lib/workspace/activation/worktree-a import { resolveWorktreeDisplayName } from '@/lib/workspace/display/worktree-default-display-name' import { formatClipboardFilePath } from '@/lib/clipboard/clipboard-file-path' import { getWorktreeRowLocalPathOpenOwner } from '@/lib/workspace/ownership/worktree-row-open-in-owner' -import { VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT } from '@/hooks/useVirtualizedScrollAnchor' import { canCreateChildWorktree, planWorkspaceStatusAssignment, @@ -206,9 +205,6 @@ export function useWorktreeContextMenuCommands(args: { }, [args.worktree, args.subtreeSleepableWorktrees, sleepWorktreesAfterMenuClose]) const handleDelete = useCallback(() => { const restoreSidebarPosition = preserveDeleteSiblingPosition(args.scopeRef.current) - args.scopeRef.current - ?.closest('[data-worktree-sidebar]') - ?.dispatchEvent(new Event(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT)) const intent = createWorktreeContextMenuDeleteIntent({ worktree: args.worktree, batchDeleteWorktrees: args.batchDeleteWorktrees, diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/worktree-context-menu-policy.ts b/src/renderer/src/components/sidebar/workspace-actions/context-menu/worktree-context-menu-policy.ts index 17fef0348bc..30e4ee9b72d 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/context-menu/worktree-context-menu-policy.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/worktree-context-menu-policy.ts @@ -1,3 +1,7 @@ +import { + requestVirtualizedScrollAnchorRecord, + supersedeVirtualizedScrollAnchorRestore +} from '@/hooks/requestVirtualizedScrollAnchorRecord' import type { AppState } from '@/store/types' import type { Repo } from '../../../../../../shared/repo-types' import { isGitRepoKind } from '../../../../../../shared/repo-kind' @@ -203,6 +207,7 @@ export function preserveDeleteSiblingPosition(scope: HTMLElement | null): () => const previousScrollTop = sidebar.scrollTop const previousScrollHeight = sidebar.scrollHeight const desiredTop = row.getBoundingClientRect().top + supersedeVirtualizedScrollAnchorRestore(sidebar) return () => { let attempts = 0 @@ -216,6 +221,10 @@ export function preserveDeleteSiblingPosition(scope: HTMLElement | null): () => const currentAnchor = currentTarget ?? findSidebarVirtualRowByKey(currentSidebar, anchorKey) if (currentAnchor) { const delta = currentAnchor.getBoundingClientRect().top - desiredTop + supersedeVirtualizedScrollAnchorRestore( + currentSidebar, + Math.abs(delta) > 1 ? currentSidebar.scrollTop + delta : undefined + ) if (Math.abs(delta) > 1) { currentSidebar.scrollTop += delta stableFrames = 0 @@ -223,10 +232,12 @@ export function preserveDeleteSiblingPosition(scope: HTMLElement | null): () => stableFrames += 1 } } else { - currentSidebar.scrollTop = Math.max( + const target = Math.max( 0, previousScrollTop + currentSidebar.scrollHeight - previousScrollHeight ) + supersedeVirtualizedScrollAnchorRestore(currentSidebar, target) + currentSidebar.scrollTop = target stableFrames = 0 } attempts += 1 @@ -237,6 +248,8 @@ export function preserveDeleteSiblingPosition(scope: HTMLElement | null): () => }) ) { window.requestAnimationFrame(restore) + } else { + requestVirtualizedScrollAnchorRecord(currentSidebar) } } restore() diff --git a/src/renderer/src/components/sidebar/workspace-actions/sleep/sleep-worktree-sidebar-position.ts b/src/renderer/src/components/sidebar/workspace-actions/sleep/sleep-worktree-sidebar-position.ts index d8e49a3526c..22cc64823df 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/sleep/sleep-worktree-sidebar-position.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/sleep/sleep-worktree-sidebar-position.ts @@ -1,4 +1,7 @@ -import { VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT } from '@/hooks/useVirtualizedScrollAnchor' +import { + requestVirtualizedScrollAnchorRecord, + supersedeVirtualizedScrollAnchorRestore +} from '@/hooks/requestVirtualizedScrollAnchorRecord' function getSidebarWorktreeOptions(worktreeId: string): HTMLElement[] { return Array.from(document.querySelectorAll('[data-worktree-id]')).filter( @@ -44,10 +47,10 @@ export function preserveSidebarWorktreePosition(worktreeId: string): () => void if (!scroller || !row) { return () => {} } - scroller.dispatchEvent(new Event(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT)) const previousScrollTop = scroller.scrollTop const previousScrollHeight = scroller.scrollHeight const previousTop = row.getBoundingClientRect().top + supersedeVirtualizedScrollAnchorRestore(scroller) return () => { let attempts = 0 @@ -63,12 +66,18 @@ export function preserveSidebarWorktreePosition(worktreeId: string): () => void const nextRow = findSidebarWorktreeRow(worktreeId, activeRowKey) if (!nextRow) { // After remount or height changes, approximate the old viewport so the row mounts before correcting its DOM position. - currentScroller.scrollTop = Math.max( + const target = Math.max( 0, previousScrollTop + currentScroller.scrollHeight - previousScrollHeight ) + supersedeVirtualizedScrollAnchorRestore(currentScroller, target) + currentScroller.scrollTop = target } else { const delta = nextRow.getBoundingClientRect().top - previousTop + supersedeVirtualizedScrollAnchorRestore( + currentScroller, + Math.abs(delta) > 1 ? currentScroller.scrollTop + delta : undefined + ) if (Math.abs(delta) > 1) { currentScroller.scrollTop += delta } @@ -76,6 +85,8 @@ export function preserveSidebarWorktreePosition(worktreeId: string): () => void attempts += 1 if (attempts < 12) { window.requestAnimationFrame(restore) + } else { + requestVirtualizedScrollAnchorRecord(currentScroller) } } window.requestAnimationFrame(restore) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/WorktreeCardAgents.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/WorktreeCardAgents.tsx index 65f32fb5759..6120278a81e 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/WorktreeCardAgents.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/WorktreeCardAgents.tsx @@ -32,13 +32,6 @@ import { } from './worktree-card-idle-child-agents' import { recomputeOn } from '@/lib/recompute-on' -export const SUPPRESS_WORKTREE_LIST_SCROLL_ADJUSTMENT_EVENT = - 'orca-suppress-worktree-list-scroll-adjustment' - -const dispatchSuppressScrollAdjustment = () => { - window.dispatchEvent(new CustomEvent(SUPPRESS_WORKTREE_LIST_SCROLL_ADJUSTMENT_EVENT)) -} - type Props = { worktreeId: string agents?: DashboardAgentRowData[] @@ -173,8 +166,8 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ expandedLineageParents, expandedIdleChildGroups, compactRootListExpanded, - toggleLineageParent: toggleLineageParentState, - toggleIdleChildGroup: toggleIdleChildGroupState, + toggleLineageParent, + toggleIdleChildGroup, toggleCompactRootList } = useWorktreeAgentExpansionState(worktreeId) @@ -184,7 +177,6 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ const wasExpanded = previousCompactExpandedRef.current previousCompactExpandedRef.current = compactRootListExpanded if (!wasExpanded && compactRootListExpanded && agentActivityDisplayMode === 'compact') { - dispatchSuppressScrollAdjustment() // Defer reveal one frame to avoid synchronous sidebar layout during the opening animation. const handle = requestAnimationFrame(() => { revealCompactAgentCard(compactAgentListRootRef.current) @@ -193,20 +185,6 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ } return undefined }, [agentActivityDisplayMode, compactRootListExpanded]) - const toggleLineageParent = useCallback( - (paneKey: string) => { - dispatchSuppressScrollAdjustment() - toggleLineageParentState(paneKey) - }, - [toggleLineageParentState] - ) - const toggleIdleChildGroup = useCallback( - (parentPaneKey: string) => { - dispatchSuppressScrollAdjustment() - toggleIdleChildGroupState(parentPaneKey) - }, - [toggleIdleChildGroupState] - ) const sendTargetFor = (paneKey: string) => isAgentSendTargetModeActive @@ -402,10 +380,7 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ agents={summaryAgents} subjectLabel={subjectLabel} expanded={compactRootListExpanded} - onToggle={() => { - dispatchSuppressScrollAdjustment() - toggleCompactRootList() - }} + onToggle={toggleCompactRootList} /> {rootAgents.map((rootAgent) => diff --git a/src/renderer/src/components/sidebar/workspace-card/identity/WorktreeLineageToggle.test.tsx b/src/renderer/src/components/sidebar/workspace-card/identity/WorktreeLineageToggle.test.tsx new file mode 100644 index 00000000000..73355c73026 --- /dev/null +++ b/src/renderer/src/components/sidebar/workspace-card/identity/WorktreeLineageToggle.test.tsx @@ -0,0 +1,52 @@ +// @vitest-environment happy-dom +import '@testing-library/jest-dom/vitest' +import { useMemo, useState } from 'react' +import { cleanup, render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { WorktreeLineageToggle } from './WorktreeLineageToggle' +import { createLineageToggleHandlerCache } from './worktree-lineage-toggle-handler-cache' + +vi.mock('../activity/use-worktree-activity-statuses', () => ({ + useWorktreeActivityStatuses: () => new Map() +})) + +afterEach(cleanup) + +it('dismisses the disclosure tooltip on keyboard activation without selecting the card or losing focus', async () => { + const activateCard = vi.fn() + function Card() { + const [collapsed, setCollapsed] = useState(false) + const toggle = useMemo( + () => createLineageToggleHandlerCache(() => setCollapsed((value) => !value))('parent'), + [] + ) + return ( + +
+ + {!collapsed && Child workspace} +
+
+ ) + } + const user = userEvent.setup() + render() + const toggle = screen.getByRole('button', { name: 'Toggle child workspaces' }) + + await user.tab() + expect(await screen.findByRole('tooltip')).toBeInTheDocument() + await user.keyboard('{Enter}') + + expect(screen.queryByText('Child workspace')).not.toBeInTheDocument() + await waitFor(() => expect(screen.queryByRole('tooltip')).not.toBeInTheDocument()) + expect(toggle).toHaveFocus() + expect(activateCard).not.toHaveBeenCalled() +}) diff --git a/src/renderer/src/components/sidebar/workspace-card/identity/worktree-lineage-toggle-handler-cache.ts b/src/renderer/src/components/sidebar/workspace-card/identity/worktree-lineage-toggle-handler-cache.ts index 7188ad9065f..55caa323c5a 100644 --- a/src/renderer/src/components/sidebar/workspace-card/identity/worktree-lineage-toggle-handler-cache.ts +++ b/src/renderer/src/components/sidebar/workspace-card/identity/worktree-lineage-toggle-handler-cache.ts @@ -13,7 +13,6 @@ export const createLineageToggleHandlerCache = ( return cached } const handler: LineageToggleHandler = (event) => { - event.preventDefault() event.stopPropagation() toggleGroup(groupKey) } diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/drop-commit-context.ts b/src/renderer/src/components/sidebar/worktree-list/drag/drop-commit-context.ts index c73b8cc1666..28eb06ef19b 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/drop-commit-context.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/drop-commit-context.ts @@ -54,6 +54,11 @@ export type WorktreeDropCommitContext = { pickedCopies: DraggedWorktreeCopies, parentIdentity: string ) => boolean + captureFolderRetention?: ( + point: WorktreeReorderDropPoint | undefined, + pickedCopies: DraggedWorktreeCopies, + sourceGroupKey: string + ) => WorktreeReorderDropPoint | undefined clearReorderedWorktreeParents: (args: { draggedIds: readonly string[] sourceGroupKey: string diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/pointer-commit.ts b/src/renderer/src/components/sidebar/worktree-list/drag/pointer-commit.ts index 993dc6e1842..abb0dd66589 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/pointer-commit.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/pointer-commit.ts @@ -117,6 +117,10 @@ export function commitWorktreePointerDrop(args: PointerDropCommitArgs): void { } const drop = ctx.computeWorktreeDrop(event.clientY) if (drop) { + const rawDropPoint = getWorktreeReorderDropPoint(event, drop, ctx.scrollRef.current) + const dropPoint = + ctx.captureFolderRetention?.(rawDropPoint, drag.pickedCopies, drag.sourceGroupKey) ?? + rawDropPoint ctx.onReorderWorktrees({ groups: ctx.worktreeDragGroups, sourceGroupKey: drag.sourceGroupKey, @@ -131,7 +135,7 @@ export function commitWorktreePointerDrop(args: PointerDropCommitArgs): void { draggedIds: drag.draggedIds, sourceGroupKey: drag.sourceGroupKey, pickedCopies: drag.pickedCopies, - dropPoint: getWorktreeReorderDropPoint(event, drop, ctx.scrollRef.current) + dropPoint }) } else if (ctx.scrollRef.current) { const currentPreview = preferredStatusTarget.status diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/project-group-header-drag.ts b/src/renderer/src/components/sidebar/worktree-list/drag/project-group-header-drag.ts index 5f975395774..37ffd4d3547 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/project-group-header-drag.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/project-group-header-drag.ts @@ -1,3 +1,7 @@ +import { + requestVirtualizedScrollAnchorRecord, + supersedeVirtualizedScrollAnchorRestore +} from '@/hooks/requestVirtualizedScrollAnchorRecord' import { measureRootProjectHeaderDragRects } from './root-project-header-drop' import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' @@ -176,7 +180,9 @@ export function useProjectGroupHeaderDrag({ elapsedMs: frameTime - previousFrameTime }) if (autoscroll) { + supersedeVirtualizedScrollAnchorRestore(container, autoscroll.scrollTop) container.scrollTop = autoscroll.scrollTop + requestVirtualizedScrollAnchorRecord(container) refreshHeaderRects() } @@ -285,8 +291,7 @@ export function useProjectGroupHeaderDrag({ return } const body = document.body - const prevCursor = body.style.cursor - const prevUserSelect = body.style.userSelect + const { cursor: prevCursor, userSelect: prevUserSelect } = body.style body.style.cursor = 'grabbing' body.style.userSelect = 'none' return () => { diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/project-header-drag.ts b/src/renderer/src/components/sidebar/worktree-list/drag/project-header-drag.ts index bdddbe863c9..63a10e4bc39 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/project-header-drag.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/project-header-drag.ts @@ -1,3 +1,7 @@ +import { + requestVirtualizedScrollAnchorRecord, + supersedeVirtualizedScrollAnchorRestore +} from '@/hooks/requestVirtualizedScrollAnchorRecord' import { measureRootProjectHeaderDragRects } from './root-project-header-drop' import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' @@ -189,7 +193,9 @@ export function useRepoHeaderDrag({ elapsedMs: frameTime - previousFrameTime }) if (autoscroll) { + supersedeVirtualizedScrollAnchorRestore(container, autoscroll.scrollTop) container.scrollTop = autoscroll.scrollTop + requestVirtualizedScrollAnchorRecord(container) refreshHeaderRects() } @@ -290,8 +296,7 @@ export function useRepoHeaderDrag({ return } const body = document.body - const prevCursor = body.style.cursor - const prevUserSelect = body.style.userSelect + const { cursor: prevCursor, userSelect: prevUserSelect } = body.style body.style.cursor = 'grabbing' body.style.userSelect = 'none' return () => { diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/use-document-drop.ts b/src/renderer/src/components/sidebar/worktree-list/drag/use-document-drop.ts index 04a4eab1159..e32c742a196 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/use-document-drop.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/use-document-drop.ts @@ -71,6 +71,10 @@ export function useWorktreeDocumentDrop(args: { // Why: pointer still inside the source group means reorder, not status move; commit here and stop the capture handler. event.preventDefault() event.stopPropagation() + const rawDropPoint = getWorktreeReorderDropPoint(event, drop, ctx.scrollRef.current) + const dropPoint = + ctx.captureFolderRetention?.(rawDropPoint, session.pickedCopies, session.sourceGroupKey) ?? + rawDropPoint ctx.onReorderWorktrees({ groups: ctx.worktreeDragGroups, sourceGroupKey: session.sourceGroupKey, @@ -85,7 +89,7 @@ export function useWorktreeDocumentDrop(args: { draggedIds: session.draggedIds, sourceGroupKey: session.sourceGroupKey, pickedCopies: session.pickedCopies, - dropPoint: getWorktreeReorderDropPoint(event, drop, ctx.scrollRef.current) + dropPoint }) clearWorktreeDrag() } diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/use-drop-commit-context.ts b/src/renderer/src/components/sidebar/worktree-list/drag/use-drop-commit-context.ts index b362901d6dc..8d5c3942481 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/use-drop-commit-context.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/use-drop-commit-context.ts @@ -39,6 +39,7 @@ export function useWorktreeDropCommitContext(args: { refreshWorktreeDragSession: session.refreshWorktreeDragSession, getEligibleLineageDropTarget: lineageDrop.getEligibleLineageDropTarget, commitWorktreeLineageParentDrop: lineageDrop.commitWorktreeLineageParentDrop, + captureFolderRetention: lineageDrop.captureFolderRetention, clearReorderedWorktreeParents: lineageDrop.clearReorderedWorktreeParents, clearWorktreeDrag: runtime.clearWorktreeDrag, onMoveWorktreesToStatus: (worktreeIds, status) => @@ -59,6 +60,7 @@ export function useWorktreeDropCommitContext(args: { onReorderWorktrees, runtime.clearWorktreeDrag, scrollRef, + lineageDrop.captureFolderRetention, session.computeWorktreeDrop, session.computeWorktreeStatusDrop, session.refreshWorktreeDragSession, diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/use-header-drag.ts b/src/renderer/src/components/sidebar/worktree-list/drag/use-header-drag.ts index 0e8312bfafb..6d102996a91 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/use-header-drag.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/use-header-drag.ts @@ -24,7 +24,6 @@ import { useRepoHeaderDrag } from './project-header-drag' import { getSidebarOrderedRepoHeaderIdsByBucket } from './project-header-drop' import { useProjectGroupHeaderDrag } from './project-group-header-drag' import { getSidebarOrderedProjectGroupHeaderIdsByBucket } from './project-group-header-drop' -import { USER_SCROLL_MEASUREMENT_ADJUSTMENT_SUPPRESS_MS } from '../viewport/use-scroll-suppression' import { getRootProjectHeaderCountByOccurrenceKey, getSidebarRootProjectHeaderKeys @@ -68,8 +67,7 @@ export function useWorktreeSidebarHeaderDrag(args: { scrollRef: React.RefObject onReorderHostSections: (orderedHostIds: ExecutionHostId[]) => void onHostDragActiveChange: (active: boolean) => void - suppressMeasurementAdjustmentUntilRef: React.MutableRefObject - directScrollInputUntilRef: React.MutableRefObject + onScrollIntent: () => void }) { const { rows, @@ -83,8 +81,7 @@ export function useWorktreeSidebarHeaderDrag(args: { scrollRef, onReorderHostSections, onHostDragActiveChange, - suppressMeasurementAdjustmentUntilRef, - directScrollInputUntilRef + onScrollIntent } = args const reorderRepos = useAppStore((s) => s.reorderRepos) const moveProjectToGroup = useAppStore((s) => s.moveProjectToGroup) @@ -124,18 +121,12 @@ export function useWorktreeSidebarHeaderDrag(args: { return byGroupId }, [projectGroups]) - // Suppress anchor correction after manual header moves so it cannot chase the reordered row. - const suppressScrollCorrectionForHeaderCommit = useCallback(() => { - const suppressUntil = window.performance.now() + USER_SCROLL_MEASUREMENT_ADJUSTMENT_SUPPRESS_MS - suppressMeasurementAdjustmentUntilRef.current = suppressUntil - directScrollInputUntilRef.current = suppressUntil - }, [directScrollInputUntilRef, suppressMeasurementAdjustmentUntilRef]) const commitRepoReorder = useCallback( (orderedIds: string[]) => { - suppressScrollCorrectionForHeaderCommit() + onScrollIntent() reorderRepos(orderedIds) }, - [reorderRepos, suppressScrollCorrectionForHeaderCommit] + [reorderRepos, onScrollIntent] ) const orderedHostIds = useMemo( () => @@ -196,12 +187,12 @@ export function useWorktreeSidebarHeaderDrag(args: { if (!Number.isFinite(tabOrder)) { return } - suppressScrollCorrectionForHeaderCommit() + onScrollIntent() // Why: manual order persists on the group's own host; the focused host may not hold this row. const ownerHostId = projectGroupOwnerHostIdByGroupId.get(groupId) void updateProjectGroup(groupId, { tabOrder }, { hostId: ownerHostId ?? undefined }) }, - [projectGroupOwnerHostIdByGroupId, suppressScrollCorrectionForHeaderCommit, updateProjectGroup] + [projectGroupOwnerHostIdByGroupId, onScrollIntent, updateProjectGroup] ) const commitRootProjectOrder = useCallback( (visibleKeys: readonly string[], draggedKey: string, dropIndex: number) => { @@ -211,7 +202,7 @@ export function useWorktreeSidebarHeaderDrag(args: { visibleKeys, draggedKey, dropIndex, - onCommit: suppressScrollCorrectionForHeaderCommit + onCommit: onScrollIntent }) void save() .catch(() => false) @@ -226,7 +217,7 @@ export function useWorktreeSidebarHeaderDrag(args: { } }) }, - [suppressScrollCorrectionForHeaderCommit] + [onScrollIntent] ) // Drag applies only in manual order; still construct the controller inert for stable hook order. const repoDrag = useRepoHeaderDrag({ diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/use-lineage-drop-commit.ts b/src/renderer/src/components/sidebar/worktree-list/drag/use-lineage-drop-commit.ts index 32a1678d3de..f9327e0e7cf 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/use-lineage-drop-commit.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/use-lineage-drop-commit.ts @@ -15,7 +15,6 @@ import { getCyclicProjectedWorktreeLineageIds } from '../../../../../../shared/s import { getReorderedWorktreeIdsToUnnest, getReorderUnnestRows, - isReorderInsideFolderRow, type WorktreeReorderDropPoint } from './worktree-lineage-drag-drop' import { unnestWorktrees } from '../../workspace-actions/parenting/worktree-unnest' @@ -35,10 +34,51 @@ export function useWorktreeLineageDropCommit(args: { worktreeMap: Map worktreeLineageById: Record worktreeDragGroups: readonly WorktreeDragGroup[] + keepsFolderParent: (identity: string, point: WorktreeReorderDropPoint | undefined) => boolean + captureFolderRetention: ( + point: WorktreeReorderDropPoint | undefined, + folders: ReadonlySet + ) => WorktreeReorderDropPoint | undefined }) { - const { repoMap, worktreeMap, worktreeLineageById, worktreeDragGroups } = args + const { repoMap, worktreeMap, worktreeLineageById, worktreeDragGroups, keepsFolderParent } = args const worktrees = useAllWorktrees() const parentIdentities = useAppStore(selectSidebarLineageParentIdentities) + const folderParentOf = useCallback( + (identity: string) => { + const parent = parentIdentities?.get(identity) + return parent !== undefined && + parseWorkspaceKey(getWorktreeIdFromHostIdentity(parent))?.type === 'folder' + ? parent + : undefined + }, + [parentIdentities] + ) + const { captureFolderRetention: captureGeometry } = args + const captureFolderRetention = useCallback( + ( + point: WorktreeReorderDropPoint | undefined, + pickedCopies: DraggedWorktreeCopies, + sourceGroupKey: string + ) => { + const folders = new Set() + let members: readonly string[] | undefined + for (const copy of pickedCopies) { + const identity = getWorktreeHostIdentity(copy) + const parent = folderParentOf(identity) + if (parent) { + if (members === undefined) { + members = + worktreeDragGroups.find((group) => group.key === sourceGroupKey)?.worktreeIds ?? [] + } + if (members.includes(identity)) { + folders.add(parent) + } + } + } + return captureGeometry(point, folders) + }, + [captureGeometry, folderParentOf, worktreeDragGroups] + ) const assignWorktreeParent = useAppStore((s) => s.assignWorktreeParent) const assignCrossStoreWorktreeParent = useAppStore((s) => s.assignCrossStoreWorktreeParent) const updateWorktreeLineage = useAppStore((s) => s.updateWorktreeLineage) @@ -184,14 +224,8 @@ export function useWorktreeLineageDropCommit(args: { legacyIds, pickedCopies: unnestArgs.pickedCopies ?? [], sourceGroupIdentities: sourceGroup.worktreeIds, - folderParentOf: (identity) => { - const parent = parentIdentities?.get(identity) - return parent !== undefined && - parseWorkspaceKey(getWorktreeIdFromHostIdentity(parent))?.type === 'folder' - ? parent - : undefined - }, - keepsFolderParent: (folder) => isReorderInsideFolderRow(folder, unnestArgs.dropPoint) + folderParentOf, + keepsFolderParent: (folder) => keepsFolderParent(folder, unnestArgs.dropPoint) }) if (rows.length === 0) { return @@ -201,7 +235,8 @@ export function useWorktreeLineageDropCommit(args: { }, [ cyclicLineageIds, - parentIdentities, + keepsFolderParent, + folderParentOf, updateWorktreeLineage, worktreeDragGroups, worktreeLineageById, @@ -212,6 +247,7 @@ export function useWorktreeLineageDropCommit(args: { return { getEligibleLineageDropTarget, commitWorktreeLineageParentDrop, + captureFolderRetention, clearReorderedWorktreeParents } } diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/use-native-autoscroll.ts b/src/renderer/src/components/sidebar/worktree-list/drag/use-native-autoscroll.ts index 7820367d283..81b0d69bbc2 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/use-native-autoscroll.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/use-native-autoscroll.ts @@ -1,3 +1,7 @@ +import { + requestVirtualizedScrollAnchorRecord, + supersedeVirtualizedScrollAnchorRestore +} from '@/hooks/requestVirtualizedScrollAnchorRecord' import { useCallback } from 'react' import type React from 'react' import { getWorktreeSidebarDragAutoscroll } from './worktree-sidebar-drag-autoscroll' @@ -48,7 +52,9 @@ export function useWorktreeNativeDragAutoscroll(args: { }) if (autoscroll) { markScrollMovement() + supersedeVirtualizedScrollAnchorRestore(container, autoscroll.scrollTop) container.scrollTop = autoscroll.scrollTop + requestVirtualizedScrollAnchorRecord(container) if (!session.refreshWorktreeDragSession()) { clearWorktreeDrag() return diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/use-native-drag.ts b/src/renderer/src/components/sidebar/worktree-list/drag/use-native-drag.ts index 2949666f5fe..92b070c5f25 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/use-native-drag.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/use-native-drag.ts @@ -8,7 +8,6 @@ import { useCallback } from 'react' import type React from 'react' import { getWorkspaceKanbanSidebarDropTarget } from '../../workspace-board/drag/workspace-kanban-sidebar-drop' import { getFullDropIndexForWorktreeDragUnit } from './worktree-drag-units' -import { getWorktreeSidebarDragRectsForGroup } from './worktree-sidebar-drag-autoscroll' import { getWorktreeSidebarDragGrab } from './worktree-sidebar-drag-geometry' import { getPointerDropStatusTarget } from './status-target' import type { WorktreeDropCommitContext } from './drop-commit-context' @@ -72,9 +71,7 @@ export function useWorktreeNativeDrag(args: { sourceGroupKey, reorderDraggedKeys ) - const rects = scrollRef.current - ? getWorktreeSidebarDragRectsForGroup(scrollRef.current, sourceGroupKey) - : [] + const rects = scrollRef.current ? session.getRects(sourceGroupKey) : [] const sourceRect = event.currentTarget.getBoundingClientRect() session.worktreeDragSessionRef.current = { draggingWorktreeId: worktreeKey, @@ -232,6 +229,13 @@ export function useWorktreeNativeDrag(args: { return } event.preventDefault() + const rawDropPoint = getWorktreeReorderDropPoint(event, drop, ctx.scrollRef.current) + const dropPoint = + ctx.captureFolderRetention?.( + rawDropPoint, + dragSession.pickedCopies, + dragSession.sourceGroupKey + ) ?? rawDropPoint ctx.onReorderWorktrees({ groups: ctx.worktreeDragGroups, sourceGroupKey: dragSession.sourceGroupKey, @@ -246,7 +250,7 @@ export function useWorktreeNativeDrag(args: { draggedIds: dragSession.draggedIds, sourceGroupKey: dragSession.sourceGroupKey, pickedCopies: dragSession.pickedCopies, - dropPoint: getWorktreeReorderDropPoint(event, drop, ctx.scrollRef.current) + dropPoint }) clearWorktreeDrag() }, diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/use-pointer-autoscroll.ts b/src/renderer/src/components/sidebar/worktree-list/drag/use-pointer-autoscroll.ts index 2f608818add..a62486325e9 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/use-pointer-autoscroll.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/use-pointer-autoscroll.ts @@ -1,3 +1,7 @@ +import { + requestVirtualizedScrollAnchorRecord, + supersedeVirtualizedScrollAnchorRestore +} from '@/hooks/requestVirtualizedScrollAnchorRecord' import { useCallback } from 'react' import type React from 'react' import { getWorktreeSidebarDragAutoscroll } from './worktree-sidebar-drag-autoscroll' @@ -45,7 +49,9 @@ export function useWorktreePointerDragAutoscroll(args: { }) if (autoscroll) { markScrollMovement() + supersedeVirtualizedScrollAnchorRestore(container, autoscroll.scrollTop) container.scrollTop = autoscroll.scrollTop + requestVirtualizedScrollAnchorRecord(container) if (!session.refreshWorktreeDragSession()) { clearWorktreeDrag() return diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/use-pointer-drag.ts b/src/renderer/src/components/sidebar/worktree-list/drag/use-pointer-drag.ts index c07f17a7315..91a89f13fcb 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/use-pointer-drag.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/use-pointer-drag.ts @@ -8,7 +8,6 @@ import { isSidebarPointerDragBlocked, setSidebarPointerDragDocumentStyles } from './worktree-sidebar-pointer-drag-dom' -import { getWorktreeSidebarDragRectsForGroup } from './worktree-sidebar-drag-autoscroll' import { getWorktreeSidebarDragGrab } from './worktree-sidebar-drag-geometry' import { NOOP_WORKSPACE_BOARD_DRAG_PREVIEW_CALLBACK } from './drop-commit-context' import type { @@ -174,12 +173,13 @@ export function useWorktreePointerDrag(args: { if (!sourceGroupKey || !container) { return } - const rects = getWorktreeSidebarDragRectsForGroup(container, sourceGroupKey) + const rects = session.getRects(sourceGroupKey) const canPreviewWorkspaceBoardOnDrag = !workspaceBoardOpen && onWorkspaceBoardDragPreviewStart !== NOOP_WORKSPACE_BOARD_DRAG_PREVIEW_CALLBACK if ( - rects.length <= 1 && + (session.worktreeDragGroups.find((group) => group.key === sourceGroupKey)?.worktreeIds + .length ?? 0) <= 1 && !hasWorkspaceKanbanSidebarDropBoard() && !canPreviewWorkspaceBoardOnDrag ) { diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/use-session.ts b/src/renderer/src/components/sidebar/worktree-list/drag/use-session.ts index 0b7281d6653..19d08ca2f08 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/use-session.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/use-session.ts @@ -7,9 +7,8 @@ import { WORKTREE_SIDEBAR_VIRTUAL_ROW_GAP } from '../viewport/virtual-rows' import '../../workspace-status/presentation/workspace-status' import { getWorkspaceStatusGroupKey } from '../../../../../../shared/workspace-statuses' import { expandDraggedWorktreeIdsForVisibleLineage } from './worktree-manual-order' -import { getWorktreeDragUnitGroups } from './worktree-drag-units' +import type { WorktreeRowGeometry } from '../viewport/use-row-geometry' import { - getWorktreeSidebarDragRectsForGroup, refreshWorktreeSidebarDragSession, type WorktreeSidebarDragRect, type WorktreeSidebarDragSession @@ -23,7 +22,7 @@ import { computeWorktreeSidebarDropPreview, type WorktreeSidebarDropPreview } from './worktree-sidebar-drop-preview' -import { getWorktreeDragGroups, getWorktreeDragIndexes } from './groups' +import { getWorktreeDragGroups } from './groups' import type { WorktreeItemRow } from '../listing/renderable-rows' import { getNaturalWorktreeKeys } from '../listing/natural-worktree-keys' import { @@ -46,14 +45,16 @@ export type WorktreeDragSession = ReturnType export function useWorktreeDragSession(args: { rows: HostSectionRow[] scrollRef: React.RefObject + geometry: WorktreeRowGeometry }) { - const { rows, scrollRef } = args + const { rows, scrollRef, geometry } = args + const { getRects } = geometry const worktreeDragSessionRef = useRef(null) // Hold cross-group drop anchors separately so expanding target cards cannot move the line under a still pointer. const statusDropAnchorsRef = useRef>(new Map()) const worktreeDragGroups = useMemo(() => getWorktreeDragGroups(rows), [rows]) - const worktreeDragUnitGroups = useMemo(() => getWorktreeDragUnitGroups(rows), [rows]) + const worktreeDragUnitGroups = geometry.units const naturalDragWorktreeKeys = useMemo(() => getNaturalWorktreeKeys(rows), [rows]) const worktreeLineageDragRows = useMemo( () => @@ -103,10 +104,7 @@ export function useWorktreeDragSession(args: { }, [worktreeDragUnitGroups] ) - const { groupKeyByRowKey, groupIndexByRowKey } = useMemo( - () => getWorktreeDragIndexes(rows), - [rows] - ) + const { groupKeyByRowKey, groupIndexByRowKey } = geometry.indexes const refreshWorktreeDragSession = useCallback((): boolean => { const session = worktreeDragSessionRef.current const container = scrollRef.current @@ -118,11 +116,11 @@ export function useWorktreeDragSession(args: { session, groups: worktreeDragGroups, unitGroups: worktreeDragUnitGroups, - rects: getWorktreeSidebarDragRectsForGroup(container, session.sourceGroupKey) + rects: getRects(session.sourceGroupKey, session.reorderUnitDraggedKeys) }) worktreeDragSessionRef.current = refreshedSession return refreshedSession !== null - }, [scrollRef, worktreeDragGroups, worktreeDragUnitGroups]) + }, [scrollRef, worktreeDragGroups, worktreeDragUnitGroups, getRects]) const computeWorktreeDropForGroup = useCallback( (dropArgs: { pointerY: number @@ -210,7 +208,7 @@ export function useWorktreeDragSession(args: { const preview = computeWorktreeDropForGroup({ pointerY: request.pointerY, groupKey, - rects: getWorktreeSidebarDragRectsForGroup(container, groupKey), + rects: getRects(groupKey), draggedIds: request.draggedKeys, draggingWorktreeId: session?.draggingWorktreeId ?? null, grab: session?.grab ?? null, @@ -227,12 +225,13 @@ export function useWorktreeDragSession(args: { } return preview }, - [computeWorktreeDropForGroup, scrollRef] + [computeWorktreeDropForGroup, scrollRef, getRects] ) // Keep session callback identity stable for memoized cards. return useMemo( () => ({ + getRects, worktreeDragSessionRef, statusDropAnchorsRef, worktreeDragGroups, @@ -247,6 +246,7 @@ export function useWorktreeDragSession(args: { computeWorktreeStatusDrop }), [ + getRects, computeWorktreeDrop, computeWorktreeStatusDrop, getReorderDraggedCopies, diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/worktree-drag-preview-offsets.test.ts b/src/renderer/src/components/sidebar/worktree-list/drag/worktree-drag-preview-offsets.test.ts new file mode 100644 index 00000000000..906c085fb44 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/drag/worktree-drag-preview-offsets.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import { buildWorktreeDragPreviewOffsets } from './worktree-drag-preview-offsets' + +describe('virtualized workspace drag preview', () => { + it('opens the full insertion space when the source and target have unmounted units between them', () => { + const preview = buildWorktreeDragPreviewOffsets({ + groupIds: ['first', 'offscreen', 'picked'], + draggedIds: ['picked'], + draggingWorktreeId: 'picked', + draggedPreviewHeight: 40, + fallbackGap: 0, + dropIndex: 0, + rects: [ + { worktreeId: 'first', groupIndex: 0, top: 0, bottom: 100, layoutBottom: 106 }, + { worktreeId: 'picked', groupIndex: 2, top: 212, bottom: 312, layoutBottom: 318 } + ] + }) + expect(preview.offsets.get('first')).toBe(106) + expect(preview.placeholderTop).toBe(0) + }) +}) diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/worktree-drag-preview-offsets.ts b/src/renderer/src/components/sidebar/worktree-list/drag/worktree-drag-preview-offsets.ts index b334e7ceb96..fa345e3f908 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/worktree-drag-preview-offsets.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/worktree-drag-preview-offsets.ts @@ -5,6 +5,7 @@ export type WorktreeDragPreviewRect = { groupIndex: number top: number bottom: number + layoutBottom?: number } function arraysEqual(a: readonly string[], b: readonly string[]): boolean { @@ -82,6 +83,7 @@ export function buildWorktreeDragPreviewOffsets(args: { dropIndex: number rects: readonly WorktreeDragPreviewRect[] }): WorktreeDragPreviewLayout { + const rects = args.rects.map((rect) => ({ ...rect, bottom: rect.layoutBottom ?? rect.bottom })) const committedNextIds = moveWorktreeIdsWithinGroup( args.groupIds, args.draggedIds, @@ -108,7 +110,7 @@ export function buildWorktreeDragPreviewOffsets(args: { const groupIdSet = new Set(args.groupIds) const rectById = new Map() - for (const rect of args.rects) { + for (const rect of rects) { if (groupIdSet.has(rect.worktreeId)) { rectById.set(rect.worktreeId, rect) } @@ -120,8 +122,8 @@ export function buildWorktreeDragPreviewOffsets(args: { args.fallbackGap >= 0 ? args.fallbackGap : 0 - const fallbackStride = getFallbackStride(args.rects, defaultGap) - const fallbackGap = getFallbackGap(args.rects, defaultGap) + const fallbackStride = getFallbackStride(rects, defaultGap) + const fallbackGap = getFallbackGap(rects, defaultGap) const groupRects = args.groupIds.flatMap((id) => { const rect = rectById.get(id) return rect ? [rect] : [] @@ -179,7 +181,7 @@ export function buildWorktreeDragPreviewOffsets(args: { } const offsets = new Map() - for (const rect of args.rects) { + for (const rect of rects) { if (draggedSet.has(rect.worktreeId)) { continue } diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/worktree-lineage-drag-drop.test.ts b/src/renderer/src/components/sidebar/worktree-list/drag/worktree-lineage-drag-drop.test.ts index 85da2eba217..26cc5dcb855 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/worktree-lineage-drag-drop.test.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/worktree-lineage-drag-drop.test.ts @@ -5,7 +5,7 @@ import { describe, expect, it } from 'vitest' import { getReorderUnnestRows, getWorktreeLineageDropTargetIdentity, - isReorderInsideFolderRow + isReorderInsideFolderBounds } from './worktree-lineage-drag-drop' describe('getWorktreeLineageDropTargetIdentity', () => { @@ -64,26 +64,20 @@ describe('getWorktreeLineageDropTargetIdentity', () => { }) }) -describe('isReorderInsideFolderRow', () => { - it('keeps a reorder inside the folder card only when the pointer and the insertion line are in it', () => { - const folder = document.createElement('div') - folder.setAttribute('data-worktree-lineage-drop-row', '') - folder.setAttribute('data-worktree-host-identity', 'local|folder:f-1') - folder.getBoundingClientRect = () => new DOMRect(0, 100, 290, 200) - const card = document.createElement('div') - card.setAttribute('data-worktree-card-surface', 'true') - card.getBoundingClientRect = () => new DOMRect(15, 100, 265, 200) - folder.append(card) - document.body.append(folder) +describe('isReorderInsideFolderBounds', () => { + it('keeps first and last insertion gutters inside an offscreen folder, with an outer unnest escape', () => { + const bounds = { left: 15, right: 280, top: -100, bottom: 300 } const inside = { clientX: 140, clientY: 200, lineClientY: 180 } - expect(isReorderInsideFolderRow('local|folder:f-1', inside)).toBe(true) - expect(isReorderInsideFolderRow('local|folder:f-1', { ...inside, clientX: 900 })).toBe(false) - expect(isReorderInsideFolderRow('local|folder:f-1', { ...inside, clientX: 4 })).toBe(false) - expect(isReorderInsideFolderRow('local|folder:f-1', { ...inside, lineClientY: 320 })).toBe( - false + expect(isReorderInsideFolderBounds(inside, bounds)).toBe(true) + expect(isReorderInsideFolderBounds({ ...inside, clientY: 2, lineClientY: -3 }, bounds)).toBe( + true ) - expect(isReorderInsideFolderRow('local|folder:f-1', { ...inside, clientY: 340 })).toBe(false) - folder.remove() + expect(isReorderInsideFolderBounds({ ...inside, clientY: 295, lineClientY: 297 }, bounds)).toBe( + true + ) + expect(isReorderInsideFolderBounds({ ...inside, clientX: 4 }, bounds)).toBe(false) + expect(isReorderInsideFolderBounds({ ...inside, lineClientY: 303 }, bounds)).toBe(false) + expect(isReorderInsideFolderBounds({ ...inside, clientY: 340 }, bounds)).toBe(false) }) }) diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/worktree-lineage-drag-drop.ts b/src/renderer/src/components/sidebar/worktree-list/drag/worktree-lineage-drag-drop.ts index a055dacc7cc..567ade41906 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/worktree-lineage-drag-drop.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/worktree-lineage-drag-drop.ts @@ -91,7 +91,12 @@ export function getReorderedWorktreeIdsToUnnest(args: { } /** Where a reorder dropped: the pointer, and the insertion line it committed to, in client pixels. */ -export type WorktreeReorderDropPoint = { clientX: number; clientY: number; lineClientY: number } +export type WorktreeReorderDropPoint = { + clientX: number + clientY: number + lineClientY: number + retainedFolderIdentities?: ReadonlySet +} export function getWorktreeReorderDropPoint( pointer: { clientX: number; clientY: number }, @@ -109,23 +114,13 @@ export function getWorktreeReorderDropPoint( } } -/** Whether a reorder landed inside a folder workspace's card, which holds its nested rows: the - * pointer and the committed insertion line both within it. */ -export function isReorderInsideFolderRow( - folderIdentity: string, - point: WorktreeReorderDropPoint | undefined +/** The full logical folder surface, including unmounted descendants and closing padding. */ +export function isReorderInsideFolderBounds( + point: WorktreeReorderDropPoint | undefined, + rect: Pick | undefined ): boolean { - if (!point) { - return false - } - const row = document.querySelector( - `[data-worktree-lineage-drop-row][data-worktree-host-identity="${CSS.escape(folderIdentity)}"]` - ) - // The visible card, not the full-width row around it. - const rect = ( - row?.querySelector('[data-worktree-card-surface]') ?? row - )?.getBoundingClientRect() return ( + point !== undefined && rect !== undefined && point.clientX >= rect.left && point.clientX <= rect.right && diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/worktree-sidebar-drag-autoscroll.ts b/src/renderer/src/components/sidebar/worktree-list/drag/worktree-sidebar-drag-autoscroll.ts index 905beeaad03..587157bb3e0 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/worktree-sidebar-drag-autoscroll.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/worktree-sidebar-drag-autoscroll.ts @@ -23,6 +23,7 @@ export type WorktreeSidebarDragRect = { groupIndex: number top: number bottom: number + layoutBottom?: number } export type WorktreeSidebarDragSession = { diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/worktree-sidebar-drop-preview.ts b/src/renderer/src/components/sidebar/worktree-list/drag/worktree-sidebar-drop-preview.ts index 2419d7eabc8..d503602ea91 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/worktree-sidebar-drop-preview.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/worktree-sidebar-drop-preview.ts @@ -34,43 +34,6 @@ export type WorktreeSidebarTrackedStatusDropTarget = { const STATUS_DROP_TARGET_FALLBACK_TOLERANCE_PX = 6 -function getWorktreeSidebarDragUnitRects(args: { - rects: readonly WorktreeSidebarDragRect[] - groupIds: readonly string[] -}): WorktreeSidebarDragRect[] { - // Expanded lineage renders several child elements but moves as one parent drag unit. - const sortedRects = [...args.rects].sort((a, b) => a.top - b.top) - const rectByWorktreeId = new Map(sortedRects.map((rect) => [rect.worktreeId, rect])) - - return args.groupIds.flatMap((worktreeId, unitIndex) => { - const rootRect = rectByWorktreeId.get(worktreeId) - if (!rootRect) { - return [] - } - const nextRootTop = - args.groupIds - .slice(unitIndex + 1) - .flatMap((nextId) => { - const nextRect = rectByWorktreeId.get(nextId) - return nextRect ? [nextRect.top] : [] - }) - .at(0) ?? Number.POSITIVE_INFINITY - const unitBottom = sortedRects.reduce( - (bottom, rect) => - rect.top >= rootRect.top && rect.top < nextRootTop ? Math.max(bottom, rect.bottom) : bottom, - rootRect.bottom - ) - return [ - { - worktreeId, - groupIndex: unitIndex, - top: rootRect.top, - bottom: unitBottom - } - ] - }) -} - function hasWorktreeSidebarStatusDropTarget( target: WorktreeSidebarStatusDropTarget & { lineageParentIdentity?: string | null } ): boolean { @@ -169,10 +132,7 @@ export function computeWorktreeSidebarDropPreview(args: { // Hold the destination while the pointer stays still so card resizing cannot change the target. anchor?: WorktreeSidebarDropAnchor | null }): WorktreeSidebarDropPreview | null { - const rects = getWorktreeSidebarDragUnitRects({ - rects: args.rects, - groupIds: args.groupIds - }) + const rects = args.rects if (rects.length === 0 || args.groupIds.length === 0) { return null } diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx b/src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx index 082b64de180..a2e52f2294a 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx @@ -47,7 +47,7 @@ vi.mock('@/store', () => ({ ) })) -// Honor getItemKey so toggling standalone/lineage-group rows changes React keys and reproduces the card remount. +// Use the virtualizer keys when rendering the visible workspace rows. vi.mock('@tanstack/react-virtual', () => ({ defaultRangeExtractor: ({ startIndex, endIndex }: { startIndex: number; endIndex: number }) => Array.from({ length: endIndex - startIndex + 1 }, (_, index) => startIndex + index), @@ -413,15 +413,6 @@ function childWorktreeCardPresent(container: HTMLElement): boolean { return container.querySelector('[id="worktree-list-option-all%3A%7Cchild"]') !== null } -function parentVirtualRowKey(container: HTMLElement): string | null { - return ( - container - .querySelector('[data-worktree-id="parent"]') - ?.closest('[data-worktree-virtual-row]') - ?.getAttribute('data-worktree-virtual-row-key') ?? null - ) -} - async function click(el: Element): Promise { await act(async () => { el.dispatchEvent(new MouseEvent('click', { bubbles: true })) @@ -451,12 +442,10 @@ describe('WorktreeCard agent-list <-> child-worktrees expansion coupling', () => clearWorktreeAgentExpansionStateForTests() }) - it('[full mode] toggling CHILD WORKTREES still remounts the card but PRESERVES agent expansion (regression)', async () => { + it('[full mode] collapsing child worktrees preserves agent expansion', async () => { setAgentLineageState({ agentActivityDisplayMode: 'full' }) const { container, root } = await renderWorktreeList() - expect(parentVirtualRowKey(container)).toBe('lineage-group:all:lineage:parent') - await click(agentChildDisclosure(container)!) expect(agentChildDisclosure(container)!.getAttribute('aria-expanded')).toBe('true') @@ -464,8 +453,6 @@ describe('WorktreeCard agent-list <-> child-worktrees expansion coupling', () => expect(mockStore.state.toggleCollapsedGroup).toHaveBeenCalledWith('lineage:parent') await rerender(root) - // Verify the parent actually remounted under a different row key; otherwise persistence would pass without exercising the bug. - expect(parentVirtualRowKey(container)).toBe('wt:all:|parent') expect(childWorktreeCardPresent(container)).toBe(false) expect(agentChildDisclosure(container)!.getAttribute('aria-expanded')).toBe('true') diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/lineage-row-projection.ts b/src/renderer/src/components/sidebar/worktree-list/listing/lineage-row-projection.ts new file mode 100644 index 00000000000..1372c510946 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/listing/lineage-row-projection.ts @@ -0,0 +1,215 @@ +import { useAppStore } from '@/store' +import { useMemo } from 'react' +import type { ExecutionHostId } from '../../../../../../shared/execution-host' +import { getRenderRowKey, type RenderRow } from './render-row' +import { + composeWorktreeHostIdentity, + getWorktreeHostIdentity, + getWorktreeIdFromHostIdentity +} from '../../../../../../shared/worktree/host-qualified-identity' +import { getFolderWorkspaceHostIdentity } from '../../../../../../shared/folder-workspaces/folder-workspace-worktree' +import type { WorktreeGroupBy } from '../../../../../../shared/sidebar-list/row-types' +import { + getFolderWorkspaceRowGeometry, + getWorktreeCardContentIndent, + getWorktreeCardSurfaceInset, + FLUSH_CARD_CONTENT_PULLBACK, + NEW_CARD_STYLE_STATUS_LANE_EXTRA_PULLBACK, + FLUSH_CARD_MIN_CONTENT_INSET, + WORKTREE_CARD_SURFACE_MARGIN, + LINEAGE_CHILDREN_INLINE_OFFSET +} from '../rows/indentation' + +export type LineageRowFrame = { + parent: number | null + root: number + end: number + left: number + right: number + contentIndent: number + before: number + after: number + closing: number +} + +export type LineageRowProjection = ReturnType + +export function buildLineageRowProjection( + rows: readonly RenderRow[], + groupBy: WorktreeGroupBy, + newCardStyle: boolean, + statusLane = newCardStyle +) { + const rowIndexByKey = new Map() + const rowKeys: string[] = [] + const frames: LineageRowFrame[] = [] + const occurrencesByIdentity = new Map() + const stack: number[] = [] + const close = (next: number) => { + const index = stack.pop()! + frames[index].end = next - 1 + } + rows.forEach((row, index) => { + const key = getRenderRowKey(row) + rowKeys.push(key) + rowIndexByKey.set(key, index) + const isWorkspace = row.type === 'item' || row.type === 'folder-workspace' + while (stack.length > 0) { + const parent = rows[stack.at(-1)!] + if ( + isWorkspace && + (parent.type === 'item' || parent.type === 'folder-workspace') && + parent.depth < row.depth + ) { + break + } + close(index) + } + const parent = isWorkspace ? (stack.at(-1) ?? null) : null + const frame: LineageRowFrame = { + parent, + root: parent === null ? index : frames[parent].root, + end: index, + left: 0, + right: 0, + contentIndent: 0, + before: 0, + after: 6, + closing: 0 + } + if (isWorkspace) { + const geometry = + row.type === 'folder-workspace' + ? getFolderWorkspaceRowGeometry({ + experimentalNewWorktreeCardStyle: newCardStyle, + isFolderBackedWorkspaceChild: + groupBy === 'repo' && row.projectGroup.createdFrom === 'folder-scan', + isGrouped: groupBy !== 'none', + groupDepth: row.groupDepth, + lineageDepth: row.depth + }) + : { + surfaceInset: getWorktreeCardSurfaceInset({ + isGrouped: groupBy !== 'none', + groupDepth: row.groupDepth + }), + cardContentIndent: + getWorktreeCardContentIndent({ + isGrouped: groupBy !== 'none', + groupDepth: row.groupDepth, + lineageDepth: row.depth + }) - + getWorktreeCardSurfaceInset({ + isGrouped: groupBy !== 'none', + groupDepth: row.groupDepth + }) + } + frame.left = geometry.surfaceInset + frame.contentIndent = Math.max(0, geometry.cardContentIndent) + if (parent !== null) { + const ancestor = frames[parent] + const padding = Math.max( + FLUSH_CARD_MIN_CONTENT_INSET, + ancestor.contentIndent - + FLUSH_CARD_CONTENT_PULLBACK - + (statusLane ? NEW_CARD_STYLE_STATUS_LANE_EXTRA_PULLBACK : 0) + ) + frame.left = + ancestor.left + + WORKTREE_CARD_SURFACE_MARGIN + + 1 + + padding + + LINEAGE_CHILDREN_INLINE_OFFSET + frame.right = ancestor.right + 7 + frame.contentIndent = 0 + frame.before = parent === index - 1 ? (newCardStyle ? 6 : 12) : 4 + } + const identity = + row.type === 'item' + ? getWorktreeHostIdentity(row.worktree) + : getFolderWorkspaceHostIdentity(row.folderWorkspace) + const occurrences = occurrencesByIdentity.get(identity) + if (occurrences) { + occurrences.push(index) + } else { + occurrencesByIdentity.set(identity, [index]) + } + } + frames.push(frame) + if (isWorkspace) { + stack.push(index) + } + }) + while (stack.length > 0) { + close(rows.length) + } + frames.forEach((frame, index) => { + if (frame.end > index) { + frames[frame.end].closing += 7 + } + const next = frames[index + 1] + frame.after = next?.root === frame.root ? 0 : 6 + }) + return { frames, occurrencesByIdentity, rowIndexByKey, restoreSignal: JSON.stringify(rowKeys) } +} + +export function useDraggedSubtreeRanges( + projection: LineageRowProjection, + identity: string | null +): readonly { start: number; end: number }[] { + return useMemo( + () => + (identity ? (projection.occurrencesByIdentity.get(identity) ?? []) : []).map((start) => ({ + start, + end: projection.frames[start].end + })), + [projection, identity] + ) +} + +export function useLineageRowProjection(args: { + rows: RenderRow[] + groupBy: WorktreeGroupBy + newCardStyle: boolean + activeWorktreeId: string | null + activeWorkspaceExecutionHostId: ExecutionHostId | null +}) { + const { rows, groupBy, newCardStyle, activeWorktreeId, activeWorkspaceExecutionHostId } = args + const statusLane = useAppStore((s) => s.worktreeCardProperties.includes('status')) && newCardStyle + const projection = useMemo( + () => buildLineageRowProjection(rows, groupBy, newCardStyle, statusLane), + [rows, groupBy, newCardStyle, statusLane] + ) + const firstHeaderIndex = useMemo( + () => rows.findIndex((row) => row.type === 'header' || row.type === 'host-header'), + [rows] + ) + const activeFamilyRoots = useMemo(() => { + const roots = new Set() + if (activeWorktreeId) { + const addRoots = (occurrences: readonly number[]) => { + for (const index of occurrences) { + const root = projection.frames[index].root + if (projection.frames[root].end > root) { + roots.add(root) + } + } + } + if (activeWorkspaceExecutionHostId) { + addRoots( + projection.occurrencesByIdentity.get( + composeWorktreeHostIdentity(activeWorkspaceExecutionHostId, activeWorktreeId) + ) ?? [] + ) + } else { + for (const [identity, occurrences] of projection.occurrencesByIdentity) { + if (getWorktreeIdFromHostIdentity(identity) === activeWorktreeId) { + addRoots(occurrences) + } + } + } + } + return roots + }, [activeWorktreeId, activeWorkspaceExecutionHostId, projection]) + return { projection, activeFamilyRoots, firstHeaderIndex } +} diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/render-row.ts b/src/renderer/src/components/sidebar/worktree-list/listing/render-row.ts index 003318e9e29..03f59c77c23 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/render-row.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/render-row.ts @@ -1,12 +1,6 @@ import type { HostSectionRow } from '../../../../../../shared/sidebar-list/host-section-rows' -type WorktreeItemRow = Extract -type FolderWorkspaceItemRow = Extract -export type RenderRow = - | HostSectionRow - /** A parent card with its visible descendants. With `folder`, the folder is the parent and `rows` - * are only its descendants; otherwise `rows[0]` is the parent. */ - | { type: 'lineage-group'; key: string; rows: WorktreeItemRow[]; folder?: FolderWorkspaceItemRow } +export type RenderRow = HostSectionRow export function getRenderRowKey(row: RenderRow): string { if (row.type === 'host-header') { @@ -15,9 +9,6 @@ export function getRenderRowKey(row: RenderRow): string { if (row.type === 'header') { return row.hostId ? `hdr:${row.hostId}:${row.key}` : `hdr:${row.key}` } - if (row.type === 'lineage-group') { - return `lineage-group:${row.key}` - } if (row.type === 'imported-worktrees-card') { return `imported:${row.key}` } diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/renderable-rows.ts b/src/renderer/src/components/sidebar/worktree-list/listing/renderable-rows.ts index 7f3140394a7..93e34f26670 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/renderable-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/renderable-rows.ts @@ -1,7 +1,4 @@ -import { - PINNED_GROUP_KEY, - getWorktreeLineageGroupKey -} from '../../../../../../shared/sidebar-list/group-keys' +import { PINNED_GROUP_KEY } from '../../../../../../shared/sidebar-list/group-keys' import type { HostSectionRow } from '../../../../../../shared/sidebar-list/host-section-rows' import type { RenderRow } from './render-row' @@ -16,55 +13,7 @@ export function isPinnedWorktreeRow(row: WorktreeItemRow): boolean { return row.sectionKey === PINNED_GROUP_KEY } -// Collapse a parent and its visible lineage descendants into one virtual row so the card renders them inline. +// Each visible workspace owns a measured virtual slot, including expanded descendants. export function buildRenderableRows(rows: HostSectionRow[]): RenderRow[] { - const renderRows: RenderRow[] = [] - for (let index = 0; index < rows.length; index++) { - const row = rows[index] - if (row.type === 'folder-workspace') { - const descendants = getDescendantItemRows(rows, index, row.depth) - if (descendants.length > 0 && row.lineageGroupKey && !row.lineageCollapsed) { - renderRows.push({ type: 'lineage-group', key: row.key, rows: descendants, folder: row }) - index += descendants.length - } else { - renderRows.push(row) - } - continue - } - if ( - !isWorktreeItemRow(row) || - row.lineageChildCount === 0 || - row.lineageCollapsed || - rows[index + 1]?.type !== 'item' || - (rows[index + 1] as WorktreeItemRow).depth <= row.depth - ) { - renderRows.push(row) - continue - } - - const groupRows = [row, ...getDescendantItemRows(rows, index, row.depth)] - renderRows.push({ - type: 'lineage-group', - key: `${row.sectionKey}:${getWorktreeLineageGroupKey(row.worktree)}`, - rows: groupRows - }) - index += groupRows.length - 1 - } - return renderRows -} - -function getDescendantItemRows( - rows: readonly HostSectionRow[], - parentIndex: number, - parentDepth: number -): WorktreeItemRow[] { - const descendants: WorktreeItemRow[] = [] - for (let cursor = parentIndex + 1; cursor < rows.length; cursor++) { - const child = rows[cursor] - if (!isWorktreeItemRow(child) || child.depth <= parentDepth) { - break - } - descendants.push(child) - } - return descendants + return rows } diff --git a/src/renderer/src/components/sidebar/worktree-list/navigation/active-descendant-option.ts b/src/renderer/src/components/sidebar/worktree-list/navigation/active-descendant-option.ts index abc94161714..9ee53b713ae 100644 --- a/src/renderer/src/components/sidebar/worktree-list/navigation/active-descendant-option.ts +++ b/src/renderer/src/components/sidebar/worktree-list/navigation/active-descendant-option.ts @@ -1,9 +1,6 @@ import { getFolderWorkspaceHostIdentity } from '../../../../../../shared/folder-workspaces/folder-workspace-worktree' import type { RenderRow } from '../listing/render-row' -import { - getWorktreeExecutionHostId, - type ExecutionHostId -} from '../../../../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../../../shared/execution-host' import type { PinnedWorktreeDisplayPolicy } from '../../../../../../shared/sidebar-list/row-types' import { isPinnedWorktreeRow } from '../listing/renderable-rows' import { getRenderRowWorktreeItem, renderRowContainsWorktree } from './render-row-lookup' @@ -11,34 +8,12 @@ import { getWorktreeOptionId } from '../rows/option-dom' export function getRenderRowOptionId( row: RenderRow | undefined, - worktreeId?: string | null, - executionHostId?: ExecutionHostId + _worktreeId?: string | null, + _executionHostId?: ExecutionHostId ): string | undefined { if (!row) { return undefined } - if (row.type === 'lineage-group' && row.folder) { - const childOption = getRenderRowOptionId( - { ...row, folder: undefined }, - worktreeId, - executionHostId - ) - return row.rows.some((item) => item.worktree.id === worktreeId) - ? childOption - : getRenderRowOptionId(row.folder, worktreeId, executionHostId) - } - if (row.type === 'lineage-group') { - // Hostless legacy state cannot disambiguate, but an aria pointer should still target a row. - const targetRow = worktreeId - ? row.rows.find( - (item) => - item.worktree.id === worktreeId && - (executionHostId === undefined || - getWorktreeExecutionHostId(item.worktree, item.repo) === executionHostId) - ) - : null - return getWorktreeOptionId((targetRow ?? row.rows[0])?.rowKey ?? row.key) - } if (row.type === 'item') { return getWorktreeOptionId(row.rowKey) } diff --git a/src/renderer/src/components/sidebar/worktree-list/navigation/mounted-row-reveal.ts b/src/renderer/src/components/sidebar/worktree-list/navigation/mounted-row-reveal.ts index 59773a6daec..de21a0b6175 100644 --- a/src/renderer/src/components/sidebar/worktree-list/navigation/mounted-row-reveal.ts +++ b/src/renderer/src/components/sidebar/worktree-list/navigation/mounted-row-reveal.ts @@ -3,9 +3,13 @@ import { composeWorktreeHostIdentity } from '../../../../../../shared/worktree/h import { getRevealBoundsVisibility, getRevealTargetBounds, - revealElementInScrollContainer + revealElementInScrollContainer, + type SidebarRevealScroll } from './worktree-sidebar-reveal' import { getMountedWorktreeOptions, getWorktreeOptionId } from '../rows/option-dom' +import { getRenderRowOptionId } from './active-descendant-option' +import type { RenderRow } from '../listing/render-row' +import type { PendingSidebarWorktreeReveal } from '@/store/slices/ui/ui-slice-contract-core' // Pinned duplicates render twice; an on-screen copy beats jumping to its off-screen twin (#24852). export function findOnScreenWorktreeOption( @@ -35,12 +39,29 @@ export function findOnScreenWorktreeOption( return fullyVisible ?? partlyVisible } +export function getPreferredMountedWorktreeOptionId( + container: HTMLElement, + targetRow: RenderRow, + request: PendingSidebarWorktreeReveal +): string | undefined { + if (request.rowKey) { + return getWorktreeOptionId(request.rowKey) + } + const { worktreeId, executionHostId } = request + const targetOptionId = getRenderRowOptionId(targetRow, worktreeId, executionHostId) + return ( + findOnScreenWorktreeOption(container, worktreeId, executionHostId, targetOptionId)?.id ?? + targetOptionId + ) +} + export function revealMountedWorktreeElement( container: HTMLElement, worktreeId: string, behavior: ScrollBehavior, optionId?: string, - onScrollIssued?: (targetTop: number) => void + onScrollIssued?: (targetTop: number) => void, + scrollTo?: SidebarRevealScroll ): HTMLElement | null { const element = optionId ? document.getElementById(optionId) @@ -48,7 +69,7 @@ export function revealMountedWorktreeElement( if (!element || !container.contains(element)) { return null } - return revealElementInScrollContainer(container, element, behavior, onScrollIssued) + return revealElementInScrollContainer(container, element, behavior, onScrollIssued, scrollTo) ? element : null } @@ -57,13 +78,14 @@ export function revealMountedSidebarRowElement( container: HTMLElement, rowKey: string, behavior: ScrollBehavior, - onScrollIssued?: (targetTop: number) => void + onScrollIssued?: (targetTop: number) => void, + scrollTo?: SidebarRevealScroll ): HTMLElement | null { const element = document.getElementById(getWorktreeOptionId(rowKey)) if (!element || !container.contains(element)) { return null } - return revealElementInScrollContainer(container, element, behavior, onScrollIssued) + return revealElementInScrollContainer(container, element, behavior, onScrollIssued, scrollTo) ? element : null } diff --git a/src/renderer/src/components/sidebar/worktree-list/navigation/pending-reveal-inputs.ts b/src/renderer/src/components/sidebar/worktree-list/navigation/pending-reveal-inputs.ts index bae4eb2cd8d..678c6c59e91 100644 --- a/src/renderer/src/components/sidebar/worktree-list/navigation/pending-reveal-inputs.ts +++ b/src/renderer/src/components/sidebar/worktree-list/navigation/pending-reveal-inputs.ts @@ -1,3 +1,5 @@ +import { supersedeVirtualizedScrollAnchorRestore } from '@/hooks/requestVirtualizedScrollAnchorRecord' +import { getSidebarRowRevealAncestorKeys } from './reveal-ancestors' import type { WorktreeOccurrencePlan } from '../../../../../../shared/worktree-occurrence-plan' import type React from 'react' import type { Virtualizer } from '@tanstack/react-virtual' @@ -177,3 +179,31 @@ export function resolvePendingWorktreeRevealTarget( }) return { targetIndex, outcome } } + +export function preparePendingSidebarRowReveal( + args: PendingSidebarRevealArgs, + request: PendingSidebarRowReveal +): boolean { + const isProjectHeaderTarget = + request.rowKey.startsWith('project-group:') || + request.rowKey.startsWith('project:') || + request.rowKey.startsWith('repo:') + if (isProjectHeaderTarget && args.groupBy !== 'repo') { + return false + } + + supersedeVirtualizedScrollAnchorRestore(args.scrollRef.current) + let toggledAncestor = false + for (const groupKey of getSidebarRowRevealAncestorKeys({ + rowKey: request.rowKey, + repoMap: args.repoMap, + projectGroups: args.projectGroups, + projectGrouping: args.projectGrouping + })) { + if (args.collapsedGroups.has(groupKey)) { + args.toggleGroup(groupKey) + toggledAncestor = true + } + } + return !toggledAncestor +} diff --git a/src/renderer/src/components/sidebar/worktree-list/navigation/render-row-lookup.ts b/src/renderer/src/components/sidebar/worktree-list/navigation/render-row-lookup.ts index aac307e610d..eb10d3b9c7a 100644 --- a/src/renderer/src/components/sidebar/worktree-list/navigation/render-row-lookup.ts +++ b/src/renderer/src/components/sidebar/worktree-list/navigation/render-row-lookup.ts @@ -40,12 +40,6 @@ export function getRenderRowSidebarKey(row: RenderRow): string | null { } export function rowKeyMatchesRenderRow(row: RenderRow, rowKey: string): boolean { - if (row.type === 'lineage-group') { - return ( - row.rows.some((item) => item.rowKey === rowKey) || - (row.folder !== undefined && rowKeyMatchesRenderRow(row.folder, rowKey)) - ) - } if (row.type === 'folder-workspace' && rowKey === folderWorkspaceKey(row.folderWorkspace.id)) { return true } @@ -81,13 +75,6 @@ export function renderRowContainsWorktree( composeWorktreeHostIdentity(executionHostId, worktreeId)) ) } - if (row.type === 'lineage-group') { - return ( - row.rows.some((item) => itemMatchesWorktree(item, worktreeId, executionHostId)) || - (row.folder !== undefined && - renderRowContainsWorktree(row.folder, worktreeId, executionHostId)) - ) - } return row.type === 'item' && itemMatchesWorktree(row, worktreeId, executionHostId) } @@ -96,9 +83,6 @@ export function getRenderRowWorktreeItem( worktreeId: string, executionHostId?: ExecutionHostId ): WorktreeItemRow | null { - if (row.type === 'lineage-group') { - return row.rows.find((item) => itemMatchesWorktree(item, worktreeId, executionHostId)) ?? null - } return row.type === 'item' && itemMatchesWorktree(row, worktreeId, executionHostId) ? row : null } @@ -135,8 +119,7 @@ export function findPreferredRenderRowIndexForWorktreeIdentity( for (let index = 0; index < renderRows.length; index++) { const row = renderRows[index] // Host-qualified reveals include folder rows, not just worktree item rows. - const folderRow = - row.type === 'folder-workspace' ? row : row.type === 'lineage-group' ? row.folder : undefined + const folderRow = row.type === 'folder-workspace' ? row : undefined if ( folderRow && folderWorkspaceKey(folderRow.folderWorkspace.id) === worktree.id && @@ -148,7 +131,7 @@ export function findPreferredRenderRowIndexForWorktreeIdentity( if (row.type === 'folder-workspace') { continue } - const itemRows = row.type === 'lineage-group' ? row.rows : row.type === 'item' ? [row] : [] + const itemRows = row.type === 'item' ? [row] : [] const itemRow = itemRows.find( (candidate) => getWorktreeHostIdentity(candidate.worktree) === identity ) diff --git a/src/renderer/src/components/sidebar/worktree-list/navigation/use-pending-reveal.ts b/src/renderer/src/components/sidebar/worktree-list/navigation/use-pending-reveal.ts index 30f6f9b7ec8..081d80daf65 100644 --- a/src/renderer/src/components/sidebar/worktree-list/navigation/use-pending-reveal.ts +++ b/src/renderer/src/components/sidebar/worktree-list/navigation/use-pending-reveal.ts @@ -2,18 +2,20 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react import { toast } from 'sonner' import { useAppStore } from '@/store' import { translate } from '@/i18n/i18n' -import { getWorktreeOptionId } from '../rows/option-dom' -import { getRenderRowOptionId } from './active-descendant-option' +import { + requestVirtualizedScrollAnchorRecord, + supersedeVirtualizedScrollAnchorRestore +} from '@/hooks/requestVirtualizedScrollAnchorRecord' import { getRenderRowSidebarKey, rowKeyMatchesRenderRow } from './render-row-lookup' import { - findOnScreenWorktreeOption, + getPreferredMountedWorktreeOptionId, revealMountedSidebarRowElement, revealMountedWorktreeElement } from './mounted-row-reveal' -import { getSidebarRowRevealAncestorKeys } from './reveal-ancestors' import { expandGroupsForWorktreeReveal, MAX_REVEAL_RETRIES, + preparePendingSidebarRowReveal, resolvePendingWorktreeRevealTarget, type PendingSidebarRevealArgs } from './pending-reveal-inputs' @@ -48,6 +50,12 @@ export function usePendingSidebarReveal(args: PendingSidebarRevealArgs): void { pinnedDisplayPolicy } = args + const scrollToReveal = useCallback( + (top: number, behavior: ScrollBehavior) => + virtualizer.scrollToOffset(top, { behavior: behavior === 'smooth' ? 'smooth' : 'auto' }), + [virtualizer] + ) + const scheduleRetryTick = useCallback( (cancelled: () => boolean) => { schedulePendingRevealFrame(() => { @@ -67,6 +75,7 @@ export function usePendingSidebarReveal(args: PendingSidebarRevealArgs): void { return } const current = argsRef.current + supersedeVirtualizedScrollAnchorRestore(current.scrollRef.current) const isCurrent = () => useAppStore.getState().pendingRevealWorktree === pendingRevealWorktree if ( !pendingRevealWorktree.rowKey && @@ -85,13 +94,13 @@ export function usePendingSidebarReveal(args: PendingSidebarRevealArgs): void { return } const currentRows = argsRef.current.renderRows - const rowKey = pendingRevealWorktree.rowKey const { targetIndex, outcome } = resolvePendingWorktreeRevealTarget( argsRef.current, pendingRevealWorktree ) if (outcome === 'clear') { pendingRevealRetryRef.current = null + requestVirtualizedScrollAnchorRecord(argsRef.current.scrollRef.current) clearPendingRevealWorktreeId(pendingRevealWorktree) return } @@ -100,18 +109,14 @@ export function usePendingSidebarReveal(args: PendingSidebarRevealArgs): void { } const targetRow = currentRows[targetIndex] const container = argsRef.current.scrollRef.current - const { worktreeId, executionHostId } = pendingRevealWorktree - const targetOptionId = getRenderRowOptionId(targetRow, worktreeId, executionHostId) const revealedOption = container ? revealMountedWorktreeElement( container, - worktreeId, + pendingRevealWorktree.worktreeId, pendingRevealWorktree.behavior, - rowKey - ? getWorktreeOptionId(rowKey) - : (findOnScreenWorktreeOption(container, worktreeId, executionHostId, targetOptionId) - ?.id ?? targetOptionId), - markRevealScroll + getPreferredMountedWorktreeOptionId(container, targetRow, pendingRevealWorktree), + markRevealScroll, + scrollToReveal ) : null if (revealedOption) { @@ -129,11 +134,13 @@ export function usePendingSidebarReveal(args: PendingSidebarRevealArgs): void { }) } pendingRevealRetryRef.current = null + requestVirtualizedScrollAnchorRecord(argsRef.current.scrollRef.current) clearPendingRevealWorktreeId(pendingRevealWorktree) return } // Why: virtual indexing can leave the card edge clipped; stage it into the window, then retry the exact DOM reveal. + supersedeVirtualizedScrollAnchorRestore(argsRef.current.scrollRef.current) virtualizer.scrollToIndex(targetIndex, { align: 'auto', behavior: 'auto' }) if (!isCurrent()) { return @@ -150,6 +157,7 @@ export function usePendingSidebarReveal(args: PendingSidebarRevealArgs): void { return } pendingRevealRetryRef.current = null + requestVirtualizedScrollAnchorRecord(argsRef.current.scrollRef.current) clearPendingRevealWorktreeId(pendingRevealWorktree) }) return () => { @@ -183,6 +191,7 @@ export function usePendingSidebarReveal(args: PendingSidebarRevealArgs): void { flashRevealedRow, markRevealScroll, setRenamingWorktreeId, + scrollToReveal, schedulePendingRevealFrame, cancelPendingRevealFrames, scheduleRetryTick @@ -195,31 +204,10 @@ export function usePendingSidebarReveal(args: PendingSidebarRevealArgs): void { ) { return } - const current = argsRef.current const isCurrent = () => useAppStore.getState().pendingRevealSidebarRow === pendingRevealSidebarRow - const isProjectHeaderTarget = - pendingRevealSidebarRow.rowKey.startsWith('project-group:') || - pendingRevealSidebarRow.rowKey.startsWith('project:') || - pendingRevealSidebarRow.rowKey.startsWith('repo:') - if (isProjectHeaderTarget && current.groupBy !== 'repo') { - return - } - - let toggledAncestor = false - for (const groupKey of getSidebarRowRevealAncestorKeys({ - rowKey: pendingRevealSidebarRow.rowKey, - repoMap: current.repoMap, - projectGroups: current.projectGroups, - projectGrouping: current.projectGrouping - })) { - if (current.collapsedGroups.has(groupKey)) { - current.toggleGroup(groupKey) - toggledAncestor = true - } - } - if (toggledAncestor) { + if (!preparePendingSidebarRowReveal(argsRef.current, pendingRevealSidebarRow)) { return } @@ -250,6 +238,7 @@ export function usePendingSidebarReveal(args: PendingSidebarRevealArgs): void { return } pendingRowRevealRetryRef.current = null + requestVirtualizedScrollAnchorRecord(argsRef.current.scrollRef.current) clearPendingRevealSidebarRow(pendingRevealSidebarRow) toast.error( translate( @@ -266,7 +255,8 @@ export function usePendingSidebarReveal(args: PendingSidebarRevealArgs): void { container, pendingRevealSidebarRow.rowKey, pendingRevealSidebarRow.behavior, - markRevealScroll + markRevealScroll, + scrollToReveal ) : null if (revealedElement) { @@ -274,10 +264,12 @@ export function usePendingSidebarReveal(args: PendingSidebarRevealArgs): void { flashRevealedRow(pendingRevealSidebarRow.rowKey) } pendingRowRevealRetryRef.current = null + requestVirtualizedScrollAnchorRecord(argsRef.current.scrollRef.current) clearPendingRevealSidebarRow(pendingRevealSidebarRow) return } + supersedeVirtualizedScrollAnchorRestore(argsRef.current.scrollRef.current) virtualizer.scrollToIndex(targetIndex, { align: 'auto', behavior: 'auto' }) if (!isCurrent()) { return @@ -286,6 +278,7 @@ export function usePendingSidebarReveal(args: PendingSidebarRevealArgs): void { return } pendingRowRevealRetryRef.current = null + requestVirtualizedScrollAnchorRecord(argsRef.current.scrollRef.current) clearPendingRevealSidebarRow(pendingRevealSidebarRow) }) @@ -306,6 +299,7 @@ export function usePendingSidebarReveal(args: PendingSidebarRevealArgs): void { pendingRevealRetryTick, flashRevealedRow, markRevealScroll, + scrollToReveal, clearPendingRevealSidebarRow, schedulePendingRevealFrame, cancelPendingRevealFrames, diff --git a/src/renderer/src/components/sidebar/worktree-list/navigation/worktree-sidebar-reveal.ts b/src/renderer/src/components/sidebar/worktree-list/navigation/worktree-sidebar-reveal.ts index 2ba77737a3f..e8e996b7cc3 100644 --- a/src/renderer/src/components/sidebar/worktree-list/navigation/worktree-sidebar-reveal.ts +++ b/src/renderer/src/components/sidebar/worktree-list/navigation/worktree-sidebar-reveal.ts @@ -1,10 +1,16 @@ import { GROUP_HEADER_ROW_HEIGHT } from '../viewport/virtual-rows' import { motionSafeScrollBehavior } from '@/hooks/usePrefersReducedMotion' +import { + requestVirtualizedScrollAnchorRecord, + supersedeVirtualizedScrollAnchorRestore +} from '@/hooks/requestVirtualizedScrollAnchorRecord' const WORKTREE_REVEAL_TOP_CLEARANCE = 6 export const WORKTREE_SIDEBAR_REVEAL_TOP_INSET = GROUP_HEADER_ROW_HEIGHT + WORKTREE_REVEAL_TOP_CLEARANCE +export type SidebarRevealScroll = (top: number, behavior: ScrollBehavior) => void + type SidebarRevealBounds = { start: number end: number @@ -89,7 +95,8 @@ export function revealElementInScrollContainer( element: Element, behavior: ScrollBehavior, // Notify guards to defer competing scrollTop writes until this smooth reveal finishes. - onScrollIssued?: (targetTop: number) => void + onScrollIssued?: (targetTop: number) => void, + scrollTo?: SidebarRevealScroll ): boolean { if (!container.contains(element)) { return false @@ -104,11 +111,20 @@ export function revealElementInScrollContainer( WORKTREE_SIDEBAR_REVEAL_TOP_INSET ) if (nextScrollTop === null) { + supersedeVirtualizedScrollAnchorRestore(container) + requestVirtualizedScrollAnchorRecord(container) return true } const targetTop = Math.max(0, nextScrollTop) + supersedeVirtualizedScrollAnchorRestore(container, scrollTo ? undefined : targetTop) onScrollIssued?.(targetTop) - container.scrollTo({ top: targetTop, behavior: motionSafeScrollBehavior(behavior) }) + const scrollBehavior = motionSafeScrollBehavior(behavior) + if (scrollTo) { + scrollTo(targetTop, scrollBehavior) + } else { + container.scrollTo({ top: targetTop, behavior: scrollBehavior }) + } + requestVirtualizedScrollAnchorRecord(container) return true } diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/folder-row.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/folder-row.tsx index a0460ed7e55..1435ff21573 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/folder-row.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/rows/folder-row.tsx @@ -28,6 +28,7 @@ import { getFolderWorkspaceCardPrDisplay } from '../../workspace-card/review/fol import { FolderPathStatusIndicator } from './FolderPathStatusIndicator' import type { WorktreeItemRowContext } from './item-row' import type { FolderWorkspaceItemRow } from '../listing/renderable-rows' +import type { LineageRowFrame } from '../listing/lineage-row-projection' import { forwardOptionPressToCardSurface, getWorktreeOptionId } from './option-dom' export type FolderWorkspaceRowContext = { @@ -85,10 +86,11 @@ export function renderFolderWorkspaceOption(args: { ctx: FolderWorkspaceRowContext row: FolderWorkspaceItemRow vItem?: VirtualItem + frame?: LineageRowFrame measureVirtualRowElement?: (element: HTMLDivElement | null) => void lineage?: FolderRowLineage }): React.JSX.Element { - const { ctx, row, vItem, lineage } = args + const { ctx, row, vItem, lineage, frame } = args const folderWorktree = folderWorkspaceToWorktree(row.folderWorkspace) const folderWorktreeIdentity = getWorktreeHostIdentity(folderWorktree) const isActiveWorktree = isActiveSidebarWorkspace(folderWorktree, { @@ -113,7 +115,7 @@ export function renderFolderWorkspaceOption(args: { prCache: ctx.prCache, settings: ctx.settings }) - const { surfaceInset, cardContentIndent } = getFolderWorkspaceRowGeometry({ + const geometry = getFolderWorkspaceRowGeometry({ experimentalNewWorktreeCardStyle: ctx.newCardStyle, isFolderBackedWorkspaceChild: ctx.groupBy === 'repo' && row.projectGroup.createdFrom === 'folder-scan', @@ -121,6 +123,8 @@ export function renderFolderWorkspaceOption(args: { groupDepth: row.groupDepth, lineageDepth: row.depth }) + const surfaceInset = frame?.left ?? geometry.surfaceInset + const cardContentIndent = frame?.contentIndent ?? geometry.cardContentIndent return (
ctx.onRowPointerDown(event, folderWorktree, folderWorktreeIdentity)} > -
0 ? { paddingLeft: surfaceInset } : undefined} - > +
-
+
diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/item-row.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/item-row.tsx index 7cd22f008d3..e3e8706004e 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/item-row.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/rows/item-row.tsx @@ -10,15 +10,8 @@ import WorktreeCard from '../../workspace-card/surface/WorktreeCard' import type { ActiveSurfaceVariant } from '../../workspace-card/controller/worktree-card-model' import { PINNED_GROUP_KEY } from '../../../../../../shared/sidebar-list/group-keys' import type { WorktreeGroupBy } from '../../../../../../shared/sidebar-list/row-types' -import { - getLineageChildrenInlineStyle, - getWorktreeCardContentIndent, - getWorktreeCardSurfaceInset, - LINEAGE_CHILDREN_INLINE_OFFSET, - LINEAGE_NESTED_ROW_SURFACE_INSET -} from './indentation' import type { LineageToggleHandler } from '../../workspace-card/identity/worktree-lineage-toggle-handler-cache' -import { stopNestedWorktreeCardBubble } from './header-event-guards' +import type { LineageRowFrame } from '../listing/lineage-row-projection' import type { WorktreeItemRow } from '../listing/renderable-rows' import { forwardOptionPressToCardSurface, getWorktreeOptionId } from './option-dom' import type { WorktreeRowDragState } from '../drag/row-state' @@ -60,41 +53,13 @@ export type WorktreeItemRowContext = { onCardDragEnd: () => void } -// Handle plain rows and inherited lineage offsets separately. -function getWorktreeItemRowGeometry( - ctx: WorktreeItemRowContext, - itemRow: WorktreeItemRow, - nested: boolean -): { surfaceInset: number; cardContentIndent: number } { - // Why: the shared child wrapper already inherits the parent's group and content offsets. - if (nested) { - return { surfaceInset: LINEAGE_NESTED_ROW_SURFACE_INSET, cardContentIndent: 0 } - } - - const isGrouped = ctx.groupBy !== 'none' - const paddingLeft = getWorktreeCardContentIndent({ - isGrouped, - groupDepth: itemRow.groupDepth, - lineageDepth: itemRow.depth - }) - const surfaceInset = getWorktreeCardSurfaceInset({ isGrouped, groupDepth: itemRow.groupDepth }) - return { - surfaceInset, - cardContentIndent: Math.max(0, paddingLeft - surfaceInset) - } -} - export function renderWorktreeItemRow( ctx: WorktreeItemRowContext, itemRow: WorktreeItemRow, - nested: boolean, - lineageChildren?: React.ReactNode, + frame: LineageRowFrame, forceActiveSurface = false ): React.JSX.Element { - const { surfaceInset, cardContentIndent } = getWorktreeItemRowGeometry(ctx, itemRow, nested) - const lineageChildrenStyle = lineageChildren - ? getLineageChildrenInlineStyle(LINEAGE_CHILDREN_INLINE_OFFSET) - : undefined + const { left: surfaceInset, right, contentIndent: cardContentIndent } = frame const worktreeDragGroupKey = ctx.groupKeyByRowKey.get(itemRow.rowKey) const worktreeIdentity = getWorktreeHostIdentity(itemRow.worktree) const isMultiSelected = ctx.selectedWorktreeIds.has(worktreeIdentity) @@ -130,24 +95,14 @@ export function renderWorktreeItemRow( data-scroll-reveal-highlight={ ctx.highlightedRevealRowKey === itemRow.rowKey ? 'true' : undefined } - onClick={(event) => { - forwardOptionPressToCardSurface(event) - // Why: nested child cards live inside the parent's clickable body; bubbling would activate/edit the parent too. - if (nested) { - event.stopPropagation() - } - }} + onClick={forwardOptionPressToCardSurface} onClickCapture={ctx.onRowClickCapture} - onDoubleClick={nested ? stopNestedWorktreeCardBubble : undefined} - onDragStart={nested ? stopNestedWorktreeCardBubble : undefined} onPointerDown={(event) => { - if (nested) { - event.stopPropagation() - } ctx.onRowPointerDown(event, itemRow.worktree, itemRow.rowKey) }} style={{ - paddingLeft: surfaceInset > 0 ? `${surfaceInset}px` : undefined + paddingLeft: surfaceInset > 0 ? `${surfaceInset}px` : undefined, + paddingRight: right || undefined }} > ) } - -// Rebuild the visible lineage subtree so each card renders its own children inline. -export function renderWorktreeLineageDescendants( - ctx: WorktreeItemRowContext, - parent: { depth: number }, - descendants: readonly WorktreeItemRow[] -): React.ReactNode | undefined { - const childNodes: React.ReactNode[] = [] - let cursor = 0 - while (cursor < descendants.length) { - const child = descendants[cursor] - if (!child || child.depth !== parent.depth + 1) { - cursor++ - continue - } - - let nextSiblingIndex = cursor + 1 - while ( - nextSiblingIndex < descendants.length && - descendants[nextSiblingIndex]!.depth > child.depth - ) { - nextSiblingIndex++ - } - - const childLineageChildren = renderWorktreeLineageDescendants( - ctx, - child, - descendants.slice(cursor + 1, nextSiblingIndex) - ) - childNodes.push(renderWorktreeItemRow(ctx, child, true, childLineageChildren)) - cursor = nextSiblingIndex - } - return childNodes.length > 0 ? childNodes : undefined -} diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/virtual-row-dispatch.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/virtual-row-dispatch.tsx index 47b694954a7..048321be415 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/virtual-row-dispatch.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/rows/virtual-row-dispatch.tsx @@ -7,6 +7,7 @@ import type { } from '../../../../../../shared/worktree/types' import '../../workspace-status/presentation/workspace-status' import { getWorkspaceStatus } from '../../../../../../shared/workspace-statuses' +import { isActiveSidebarWorkspace } from '../../../../../../shared/sidebar-list/active-workspace' import type { WorktreeGroupBy } from '../../../../../../shared/sidebar-list/row-types' import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity' import { @@ -14,33 +15,30 @@ import { getWorktreeVirtualRowTransform, shouldUseHeaderTopSpacing } from '../viewport/virtual-rows' +import type { LineageRowProjection } from '../listing/lineage-row-projection' import type { RenderRow } from '../listing/render-row' import type { ImportedWorktreeCardActionState } from '../listing/imported-worktrees-card-actions' import type { NewExternalWorktreesInboxActionState } from '../listing/new-external-worktrees-inbox-actions' import type { useHostHeaderDrag } from '../drag/host-header-drag' import { HostSectionHeader } from './HostSectionHeader' -import { - renderFolderWorkspaceOption, - renderFolderWorkspaceVirtualRow, - type FolderWorkspaceRowContext -} from './folder-row' +import { renderFolderWorkspaceOption, type FolderWorkspaceRowContext } from './folder-row' import type { LineageToggleHandler } from '../../workspace-card/identity/worktree-lineage-toggle-handler-cache' import { renderImportedWorktreesVirtualRow, renderNewExternalWorktreesInboxVirtualRow, renderPendingCreationVirtualRow } from './notice-rows' -import { - renderWorktreeItemRow, - renderWorktreeLineageDescendants, - type WorktreeItemRowContext -} from './item-row' +import { renderWorktreeItemRow, type WorktreeItemRowContext } from './item-row' import { renderWorktreeSectionHeaderRow } from './SectionHeader' import type { SectionHeaderRowContext } from './section-header-row-context' import type { WorktreeRowDragState } from '../drag/row-state' import type { Translate } from '@/i18n/use-translate' export type WorktreeVirtualRowContext = { + dragUnitsByRow: ReadonlyMap + hiddenDragRanges: readonly { start: number; end: number }[] + projection: LineageRowProjection + activeFamilyRoots: ReadonlySet renderRows: RenderRow[] firstHeaderIndex: number activeStickyHeaderIndexRef: React.MutableRefObject @@ -119,63 +117,7 @@ function folderLineageToggle( return row.lineageGroupKey ? ctx.item.getLineageToggleHandler(row.lineageGroupKey) : undefined } -function renderLineageGroupVirtualRow( - ctx: WorktreeVirtualRowContext, - row: Extract, - vItem: VirtualItem -): React.JSX.Element { - const parent = row.folder ? undefined : row.rows[0] - const children = row.folder ? row.rows : row.rows.slice(1) - const childIsActive = children.some((child) => child.worktree.id === ctx.activeWorktreeId) - const parentKey = parent ? getWorktreeHostIdentity(parent.worktree) : null - const parentPreviewOffset = parentKey - ? (ctx.worktreeDragState.previewOffsetsByWorktreeId.get(parentKey) ?? 0) - : 0 - return ( -
-
- {row.folder - ? renderFolderWorkspaceOption({ - ctx: ctx.folderWorkspace, - row: row.folder, - lineage: { - onToggle: folderLineageToggle(ctx, row.folder), - children: renderWorktreeLineageDescendants(ctx.item, row.folder, children), - childIsActive - } - }) - : parent - ? renderWorktreeItemRow( - ctx.item, - parent, - false, - renderWorktreeLineageDescendants(ctx.item, parent, children), - childIsActive - ) - : null} -
-
- ) -} - -// Each row renderer owns its frame because sticky headers, lineage groups and plain cards position differently. +// Header frames retain sticky positioning; each workspace owns its measured slot. export function renderWorktreeVirtualRow( ctx: WorktreeVirtualRowContext, row: RenderRow, @@ -205,10 +147,6 @@ export function renderWorktreeVirtualRow( ) } - if (row.type === 'lineage-group') { - return renderLineageGroupVirtualRow(ctx, row, vItem) - } - if (row.type === 'imported-worktrees-card') { return renderImportedWorktreesVirtualRow({ row, @@ -239,22 +177,37 @@ export function renderWorktreeVirtualRow( }) } - if (row.type === 'folder-workspace') { - return renderFolderWorkspaceVirtualRow({ - ctx: ctx.folderWorkspace, - row, - vItem, - measureVirtualRowElement: ctx.measureVirtualRowElement, - lineage: { onToggle: folderLineageToggle(ctx, row) } - }) - } - + const frame = ctx.projection.frames[vItem.index] + const folder = row.type === 'folder-workspace' const itemWorkspaceStatus = - ctx.groupBy === 'workspace-status' + !folder && ctx.groupBy === 'workspace-status' ? getWorkspaceStatus(row.worktree, ctx.workspaceStatuses) : null - const itemKey = getWorktreeHostIdentity(row.worktree) - const itemPreviewOffset = ctx.worktreeDragState.previewOffsetsByWorktreeId.get(itemKey) ?? 0 + const itemKey = folder ? null : getWorktreeHostIdentity(row.worktree) + const sourceHidden = + itemKey !== null && + ctx.worktreeDragState.draggingWorktreeId !== null && + ctx.hiddenDragRanges.some(({ start, end }) => vItem.index >= start && vItem.index <= end) + const itemPreviewOffset = + (itemKey + ? ctx.worktreeDragState.previewOffsetsByWorktreeId.get( + ctx.dragUnitsByRow.get(vItem.index)?.identity ?? itemKey + ) + : 0) ?? 0 + const activeFamily = ctx.activeFamilyRoots.has(frame.root) + const rootFrame = ctx.projection.frames[frame.root] + const rootRow = ctx.renderRows[frame.root] + const familyHidden = ctx.hiddenDragRanges.some( + ({ start, end }) => frame.root >= start && frame.root <= end + ) + const familyVariant = + rootRow.type === 'item' && + isActiveSidebarWorkspace(rootRow.worktree, { + worktreeId: ctx.item.activeWorktreeId, + hostId: ctx.item.activeWorkspaceExecutionHostId + }) + ? ctx.item.getActiveSurfaceVariant(rootRow) + : 'primary' return (
ctx.onWorkspaceStatusDragOver(event, itemWorkspaceStatus) @@ -286,7 +241,44 @@ export function renderWorktreeVirtualRow( : undefined } > - {renderWorktreeItemRow(ctx.item, row, false)} +
+ {activeFamily && ( +
) } diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/VirtualizedWorktreeViewport.tsx b/src/renderer/src/components/sidebar/worktree-list/viewport/VirtualizedWorktreeViewport.tsx index 892f2e88d49..d9bfbdd7123 100644 --- a/src/renderer/src/components/sidebar/worktree-list/viewport/VirtualizedWorktreeViewport.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/VirtualizedWorktreeViewport.tsx @@ -1,5 +1,6 @@ import React, { useCallback, useMemo, useRef, useState } from 'react' import { useAppStore } from '@/store' +import { createProgrammaticScrollMarks } from '@/hooks/programmatic-scroll-marks' import { selectSidebarLineageParentIdentities } from '@/store/slices/worktrees/metadata/cross-store-lineage-parents' import { useProjectHeaderHostContexts } from './use-project-header-host-contexts' import { useTranslate } from '@/i18n/use-translate' @@ -8,7 +9,7 @@ import { WorktreeListScrollToTopButton } from './WorktreeListScrollToTopButton' import { renderWorktreeSidebarDropIndicators } from './drop-indicators' import { useWorktreeListScrollToTop } from './use-scroll-to-top' import { getActiveDescendantOptionId } from '../navigation/active-descendant-option' -import { buildRenderableRows } from '../listing/renderable-rows' +import { useDraggedSubtreeRanges, useLineageRowProjection } from '../listing/lineage-row-projection' import { useFolderWorkspacePathStatusRows } from '../listing/use-folder-path-statuses' import { useGroupToggleWithScrollAnchor } from './use-group-toggle' import { usePendingSidebarReveal } from '../navigation/use-pending-reveal' @@ -21,8 +22,9 @@ import { useWorktreeDragRuntime } from '../drag/use-runtime' import { useWorktreeDragSession } from '../drag/use-session' import { useWorktreeDocumentDrop } from '../drag/use-document-drop' import { useWorktreeLineageDropCommit } from '../drag/use-lineage-drop-commit' -import { resolveSidebarWorkspaceDeleteIntent } from '../navigation/sidebar-workspace-delete' -import { useWorktreeListKeyboardNavigation, withKeyboardPreview } from '../navigation/use-keyboard' +import { withKeyboardPreview } from '../navigation/use-keyboard' +import { useWorktreeViewportKeyboardNavigation } from './use-keyboard-navigation' +import { useWorktreeRowGeometry } from './use-row-geometry' import { useWorktreeListVirtualizer } from './use-virtualizer' import { useWorktreeNativeDrag } from '../drag/use-native-drag' import { useWorktreePointerDrag } from '../drag/use-pointer-drag' @@ -113,14 +115,23 @@ export const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktr const reveal = useSidebarRevealHighlight() const scrollSuppression = useWorktreeSidebarScrollSuppression(scrollRef) - const { markDirectScrollInput, markScrollMovement } = scrollSuppression + const { markDirectScrollInput } = scrollSuppression + const programmaticScrollMarks = useMemo(() => createProgrammaticScrollMarks(), []) - const renderRows = useMemo(() => buildRenderableRows(rows), [rows]) - const firstHeaderIndex = useMemo( - () => renderRows.findIndex((row) => row.type === 'header' || row.type === 'host-header'), - [renderRows] + const { handleContainerKeyDown, handleContainerKeyUp, handleContainerBlur, keyboardPreview } = + useWorktreeViewportKeyboardNavigation({ props, scrollRef, markDirectScrollInput }) + + const rowProps = useMemo( + () => withKeyboardPreview(props, keyboardPreview), + [keyboardPreview, props] ) + const renderRows = rows + const { projection, activeFamilyRoots, firstHeaderIndex } = useLineageRowProjection({ + ...rowProps, + newCardStyle + }) + const headerDrag = useWorktreeSidebarHeaderDrag({ rows, renderRows, @@ -133,16 +144,27 @@ export const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktr scrollRef, onReorderHostSections: props.onReorderHostSections, onHostDragActiveChange: props.onHostDragActiveChange, - suppressMeasurementAdjustmentUntilRef: scrollSuppression.suppressMeasurementAdjustmentUntilRef, - directScrollInputUntilRef: scrollSuppression.directScrollInputUntilRef + onScrollIntent: markDirectScrollInput }) - const session = useWorktreeDragSession({ rows, scrollRef }) + const virtualization = useWorktreeListVirtualizer({ + renderRows, + projection, + firstHeaderIndex, + scrollRef, + scrollOffsetRef, + programmaticScrollMarks + }) + const rowGeometry = useWorktreeRowGeometry({ rows, projection, virtualization, scrollRef }) + + const session = useWorktreeDragSession({ rows, scrollRef, geometry: rowGeometry }) const lineageDrop = useWorktreeLineageDropCommit({ repoMap, worktreeMap, worktreeLineageById, - worktreeDragGroups: session.worktreeDragGroups + worktreeDragGroups: session.worktreeDragGroups, + keepsFolderParent: rowGeometry.keepsFolderParent, + captureFolderRetention: rowGeometry.captureFolderRetention }) const runtime = useWorktreeDragRuntime({ worktreeDragSessionRef: session.worktreeDragSessionRef, @@ -170,14 +192,6 @@ export const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktr onUserScrollIntent: markDirectScrollInput }) - const virtualization = useWorktreeListVirtualizer({ - renderRows, - firstHeaderIndex, - scrollRef, - scrollOffsetRef, - suppressMeasurementAdjustmentUntilRef: scrollSuppression.suppressMeasurementAdjustmentUntilRef - }) - usePendingSidebarReveal({ occurrencePlan: props.occurrencePlan, pendingRevealWorktree: props.pendingRevealWorktree, @@ -216,7 +230,6 @@ export const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktr scrollRef, scrollOffsetRef, scrollAnchorRef, - hasDirectScrollInput: scrollSuppression.hasDirectScrollInput, shouldSkipScrollAnchorRestore: scrollSuppression.shouldSkipScrollAnchorRestore }) @@ -225,26 +238,6 @@ export const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktr toggleGroup }) - const { handleContainerKeyDown, handleContainerKeyUp, handleContainerBlur, keyboardPreview } = - useWorktreeListKeyboardNavigation({ - rows, - activeWorktreeId, - activeWorkspaceExecutionHostId: props.activeWorkspaceExecutionHostId, - pinnedDisplayPolicy, - scrollRef, - activeModal: props.activeModal, - markDirectScrollInput, - onKeyboardSelect: props.onKeyboardSelect, - focusedWorktree: props.focusedWorktree, - focusedWorkspaceExecutionHostId: props.focusedWorkspaceExecutionHostId, - resolveDeleteIntent: () => - resolveSidebarWorkspaceDeleteIntent({ - selectedWorktrees: props.selectedWorktrees, - focusedWorktree: props.focusedWorktree ?? null, - repoMap - }) - }) - const dropCtx = useWorktreeDropCommitContext({ scrollRef, workspaceStatuses, @@ -262,7 +255,7 @@ export const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktr session, runtime, scrollRef, - markScrollMovement, + markScrollMovement: scrollSuppression.cancelRevealScroll, selectedWorktreeIds: props.selectedWorktreeIds, selectedWorktrees: props.selectedWorktrees, workspaceBoardOpen: props.workspaceBoardOpen, @@ -276,7 +269,7 @@ export const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktr session, runtime, scrollRef, - markScrollMovement + markScrollMovement: scrollSuppression.cancelRevealScroll }) useWorktreeDocumentDrop({ ctx: dropCtx, @@ -340,12 +333,14 @@ export const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktr [markDirectScrollInput] ) - const rowProps = useMemo( - () => withKeyboardPreview(props, keyboardPreview), - [keyboardPreview, props] - ) + const draggingIdentity = runtime.worktreeDragState.draggingWorktreeId + const hiddenDragRanges = useDraggedSubtreeRanges(projection, draggingIdentity) const rowContext = buildWorktreeVirtualRowContext({ + dragUnitsByRow: rowGeometry.ranges.byRow, + hiddenDragRanges, props: rowProps, + projection, + activeFamilyRoots, renderRows, firstHeaderIndex, virtualization, @@ -396,8 +391,6 @@ export const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktr onKeyDown={handleContainerKeyDown} onKeyUp={handleContainerKeyUp} onBlur={handleContainerBlur} - // Why: trackpad momentum fires sparse scroll events after the input stream quiets; suppress correction until the viewport stops. - onScroll={markScrollMovement} onPointerDown={handleScrollPointerDown} onTouchMove={markDirectScrollInput} onWheel={markDirectScrollInput} @@ -408,6 +401,7 @@ export const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktr >
diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/sidebar-smooth-reveal.test.tsx b/src/renderer/src/components/sidebar/worktree-list/viewport/sidebar-smooth-reveal.test.tsx new file mode 100644 index 00000000000..b51299619e2 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/sidebar-smooth-reveal.test.tsx @@ -0,0 +1,170 @@ +// @vitest-environment happy-dom +import { act, useMemo } from 'react' +import { cleanup, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { createProgrammaticScrollMarks } from '@/hooks/programmatic-scroll-marks' +import type { VirtualizedScrollAnchor } from '@/hooks/useVirtualizedScrollAnchor' +import { supersedeVirtualizedScrollAnchorRestore } from '@/hooks/requestVirtualizedScrollAnchorRecord' +import { buildLineageRowProjection } from '../listing/lineage-row-projection' +import type { RenderRow } from '../listing/render-row' +import { repo, worktree } from '../grouping/worktree-list-groups-test-fixtures' +import { revealElementInScrollContainer } from '../navigation/worktree-sidebar-reveal' +import { useWorktreeListVirtualizer } from './use-virtualizer' +import { useVirtualRowMeasurementSync } from './use-row-measurement' +import { useWorktreeSidebarScrollSuppression } from './use-scroll-suppression' + +const caches = vi.hoisted(() => ({ prCache: {}, issueCache: {} })) +vi.mock('@/store', () => ({ + useAppStore: (selector: (state: typeof caches) => unknown) => selector(caches) +})) +beforeEach(() => { + vi.useFakeTimers() + vi.spyOn(window, 'requestAnimationFrame').mockReturnValue(1) + vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {}) +}) +afterEach(() => { + cleanup() + document.body.replaceChildren() + vi.restoreAllMocks() + vi.useRealTimers() +}) + +function setup() { + const scroller = document.createElement('div') + document.body.append(scroller) + Object.defineProperties(scroller, { + clientHeight: { value: 300 }, + offsetHeight: { value: 300 }, + offsetWidth: { value: 300 }, + scrollHeight: { value: 10000 } + }) + scroller.getBoundingClientRect = () => new DOMRect(0, 0, 300, 300) + scroller.scrollTo = (options?: ScrollToOptions | number) => { + if (typeof options === 'object' && options.behavior !== 'smooth') { + scroller.scrollTop = options.top ?? scroller.scrollTop + } + } + const rows: RenderRow[] = Array.from({ length: 60 }, (_, index) => ({ + type: 'item', + rowKey: String(index), + sectionKey: 'all', + repo, + worktree: { ...worktree, id: String(index) }, + depth: 0, + groupDepth: 0, + isLastLineageChild: false, + lineageChildCount: 0 + })) + const scrollRef = { current: scroller } + const scrollOffsetRef = { current: 0 } + const scrollAnchorRef: { current: VirtualizedScrollAnchor } = { current: null } + const marks = createProgrammaticScrollMarks() + const view = renderHook(() => { + const projection = useMemo(() => buildLineageRowProjection(rows, 'none', false), []) + const virtualization = useWorktreeListVirtualizer({ + renderRows: rows, + projection, + firstHeaderIndex: -1, + scrollRef, + scrollOffsetRef, + programmaticScrollMarks: marks + }) + const input = useWorktreeSidebarScrollSuppression(scrollRef) + useVirtualRowMeasurementSync({ + renderRows: rows, + virtualization, + scrollRef, + scrollOffsetRef, + scrollAnchorRef, + shouldSkipScrollAnchorRestore: input.shouldSkipScrollAnchorRestore + }) + return { ...virtualization, input } + }) + const mount = (index: number, height: number) => { + const element = document.createElement('div') + element.setAttribute('data-index', String(index)) + element.setAttribute('data-worktree-virtual-row', '') + element.setAttribute('data-worktree-virtual-row-key', `wt:${index}`) + Object.defineProperty(element, 'offsetHeight', { value: height }) + scroller.append(element) + act(() => view.result.current.virtualizer.measureElement(element)) + return element + } + return { scroller, view, mount, scrollAnchorRef } +} + +it('measures skipped mounted rows and new rows after late direct takeover without rewinding a stale offset', () => { + const { scroller, view, mount } = setup() + act(() => { + view.result.current.input.markRevealScroll(3000) + view.result.current.virtualizer.scrollToOffset(3000, { behavior: 'smooth' }) + }) + mount(0, 93) + vi.spyOn(window.performance, 'now').mockReturnValue(10000) + expect(view.result.current.input.shouldSkipScrollAnchorRestore()).toBe(false) + scroller.scrollTop = 50 + act(() => view.result.current.input.markDirectScrollInput()) + expect(scroller.scrollTop).toBe(50) + expect(view.result.current.virtualizer.measurementsCache[0].size).toBe(93) + mount(1, 115) + expect(view.result.current.virtualizer.measurementsCache[2].start).toBe(208) +}) + +it.each(['arrival', 'idle', 'replacement', 'no-op'] as const)( + 'releases measurement after %s instead of leaving the smooth target active', + (completion) => { + const { scroller, view, mount } = setup() + act(() => view.result.current.virtualizer.scrollToOffset(3000, { behavior: 'smooth' })) + mount(0, 93) + act(() => { + if (completion === 'replacement') { + view.result.current.virtualizer.scrollToIndex(0, { behavior: 'auto' }) + } else if (completion === 'no-op') { + view.result.current.virtualizer.scrollToOffset(0, { behavior: 'smooth' }) + } else { + scroller.scrollTop = completion === 'arrival' ? 3000 : 80 + scroller.dispatchEvent(new Event('scroll')) + if (completion === 'idle') { + vi.advanceTimersByTime(250) + } + } + }) + expect(view.result.current.virtualizer.measurementsCache[0].size).toBe(93) + mount(1, 115) + expect(view.result.current.virtualizer.measurementsCache[2].start).toBe(208) + view.unmount() + scroller.scrollTop = 37 + supersedeVirtualizedScrollAnchorRestore(scroller) + expect(scroller.scrollTop).toBe(37) + } +) + +it.each(['virtualizer', 'native'] as const)( + 'records later user movement back to a completed %s reveal destination', + (writer) => { + const { scroller, view, scrollAnchorRef } = setup() + const target = document.createElement('div') + target.getBoundingClientRect = () => new DOMRect(0, 350 - scroller.scrollTop, 300, 50) + scroller.append(target) + act(() => { + revealElementInScrollContainer( + scroller, + target, + 'auto', + undefined, + writer === 'virtualizer' + ? (top) => view.result.current.virtualizer.scrollToOffset(top, { behavior: 'auto' }) + : undefined + ) + scroller.dispatchEvent(new Event('scroll')) + }) + expect(scroller.scrollTop).toBe(100) + act(() => { + scroller.scrollTop = 20 + scroller.dispatchEvent(new Event('scroll')) + scroller.scrollTop = 100 + scroller.dispatchEvent(new Event('scroll')) + }) + expect(scrollAnchorRef.current?.offset).toBe(100) + } +) diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/sidebar-smooth-reveal.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/sidebar-smooth-reveal.ts new file mode 100644 index 00000000000..eda84f33e23 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/sidebar-smooth-reveal.ts @@ -0,0 +1,90 @@ +import { elementScroll, observeElementOffset, type Virtualizer } from '@tanstack/react-virtual' +import type { ProgrammaticScrollMarks } from '@/hooks/programmatic-scroll-marks' +import { VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT } from '@/hooks/useVirtualizedScrollAnchor' + +type SidebarVirtualizer = Virtualizer +type ScrollOptions = Parameters[1] + +export function createSidebarSmoothReveal(args: { + marks: ProgrammaticScrollMarks + onRetired: () => void +}) { + let owned: { target: number } | null = null + let retirement: 'abort' | 'settled' | null = null + + const retire = (instance: SidebarVirtualizer, offset: number, abort: boolean) => { + if (!owned) { + return + } + owned = null + retirement = abort ? 'abort' : 'settled' + try { + // Replace the library operation at the live position without clamp/layout reads. + instance.scrollBy(offset - (instance.scrollOffset ?? offset), { behavior: 'auto' }) + } finally { + retirement = null + } + args.onRetired() + } + + const scrollTo = (offset: number, options: ScrollOptions, instance: SidebarVirtualizer) => { + if (retirement) { + if (retirement === 'abort') { + elementScroll(offset, options, instance) + } + return + } + const element = instance.scrollElement + const target = offset + (options.adjustments ?? 0) + if (options.behavior === 'smooth' && element) { + owned = { target } + if (target === element.scrollTop) { + retire(instance, target, false) + return + } + } else if (options.behavior !== undefined && owned) { + owned = null + args.onRetired() + } + if (element?.scrollTop !== target) { + args.marks.mark(target) + } + elementScroll(offset, options, instance) + } + + const observeOffset = ( + instance: SidebarVirtualizer, + callback: (offset: number, isScrolling: boolean) => void + ) => { + const element = instance.scrollElement + const onTakeover = (event: Event) => { + if ( + owned && + event instanceof CustomEvent && + event.detail?.cancelRestore === true && + element + ) { + retire(instance, element.scrollTop, true) + } + } + element?.addEventListener(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT, onTakeover) + const cleanup = observeElementOffset(instance, (offset, isScrolling) => { + const observed = owned + callback(offset, isScrolling) + if ( + observed && + owned === observed && + (!isScrolling || Math.abs(offset - observed.target) < 1) + ) { + retire(instance, offset, false) + } + }) + return () => { + owned = null + element?.removeEventListener(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT, onTakeover) + cleanup?.() + } + } + + return { scrollTo, observeOffset } +} diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/use-keyboard-navigation.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/use-keyboard-navigation.ts new file mode 100644 index 00000000000..ff51d14bad3 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/use-keyboard-navigation.ts @@ -0,0 +1,30 @@ +import type React from 'react' +import { useWorktreeListKeyboardNavigation } from '../navigation/use-keyboard' +import { resolveSidebarWorkspaceDeleteIntent } from '../navigation/sidebar-workspace-delete' +import type { VirtualizedWorktreeViewportProps } from './viewport-props' + +export function useWorktreeViewportKeyboardNavigation(args: { + props: VirtualizedWorktreeViewportProps + scrollRef: React.RefObject + markDirectScrollInput: () => void +}) { + const { props, scrollRef, markDirectScrollInput } = args + return useWorktreeListKeyboardNavigation({ + rows: props.rows, + activeWorktreeId: props.activeWorktreeId, + activeWorkspaceExecutionHostId: props.activeWorkspaceExecutionHostId, + pinnedDisplayPolicy: props.pinnedDisplayPolicy, + scrollRef, + activeModal: props.activeModal, + markDirectScrollInput, + onKeyboardSelect: props.onKeyboardSelect, + focusedWorktree: props.focusedWorktree, + focusedWorkspaceExecutionHostId: props.focusedWorkspaceExecutionHostId, + resolveDeleteIntent: () => + resolveSidebarWorkspaceDeleteIntent({ + selectedWorktrees: props.selectedWorktrees, + focusedWorktree: props.focusedWorktree ?? null, + repoMap: props.repoMap + }) + }) +} diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-geometry.test.tsx b/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-geometry.test.tsx new file mode 100644 index 00000000000..e9f8e7667d2 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-geometry.test.tsx @@ -0,0 +1,159 @@ +// @vitest-environment happy-dom +import { cleanup, renderHook } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import type { RenderRow } from '../listing/render-row' +import { buildLineageRowProjection } from '../listing/lineage-row-projection' +import { getReorderUnnestRows } from '../drag/worktree-lineage-drag-drop' +import { useWorktreeRowGeometry } from './use-row-geometry' +import type { WorktreeListVirtualizer } from './use-virtualizer' + +vi.mock('@/store', () => ({ useAppStore: vi.fn() })) +afterEach(cleanup) + +it('unnests only the picked host copy outside the padded folder surface, even with its header offscreen', () => { + const child = { id: 'r::/child', hostId: 'ssh:box' as const } + const twin = { id: 'r::/child', hostId: 'local' as const } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Geometry reads only the identity, depth and grouping fields supplied here. + const rows = [ + { + type: 'folder-workspace', + key: 'folder', + depth: 0, + groupDepth: 0, + folderWorkspace: { id: 'f', executionHostId: 'ssh:box' }, + projectGroup: {} + }, + { + type: 'item', + rowKey: 'child', + sectionKey: 'all', + depth: 1, + groupDepth: 0, + worktree: child, + repo: { id: 'r' } + } + ] as unknown as RenderRow[] + const container = document.createElement('div') + container.scrollTop = 200 + container.getBoundingClientRect = () => new DOMRect(100, 100, 200, 400) + const content = document.createElement('div') + content.setAttribute('data-worktree-sidebar-content', '') + content.getBoundingClientRect = () => new DOMRect(104, -99, 188, 1000) + container.append(content) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Folder retention reads cached endpoints; drag-window methods are unused in this test. + const virtualization = { + virtualizer: { + measurementsCache: [ + { start: 0, end: 64 }, + { start: 64, end: 260 } + ] + } + } as unknown as WorktreeListVirtualizer + const { result } = renderHook(() => + useWorktreeRowGeometry({ + rows, + projection: buildLineageRowProjection(rows, 'none', false), + virtualization, + scrollRef: { current: container } + }) + ) + const folder = 'ssh:box|folder:f' + for (const [clientX, expected] of [ + [106, [child]], + [110, []], + [295, [child]] + ] as const) { + const snapshot = result.current.captureFolderRetention( + { clientX, clientY: 50, lineClientY: 48 }, + new Set([folder]) + ) + expect( + getReorderUnnestRows({ + legacyIds: [], + pickedCopies: [child, twin], + sourceGroupIdentities: ['ssh:box|r::/child', 'local|r::/child'], + folderParentOf: (identity) => (identity === 'ssh:box|r::/child' ? folder : undefined), + keepsFolderParent: (identity) => result.current.keepsFolderParent(identity, snapshot) + }) + ).toEqual(expected) + } +}) + +it('excludes a nested folder’s preceding gap and ancestor closing edge from its saved-parent surface', () => { + const child = { id: 'r::/child', hostId: 'ssh:box' as const } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The fixture supplies only the geometry and host-qualified identity fields read by the production projection and retention boundary. + const rows = [ + { + type: 'item', + rowKey: 'root', + sectionKey: 'all', + worktree: { id: 'root' }, + repo: { id: 'r' }, + depth: 0, + groupDepth: 0 + }, + { + type: 'folder-workspace', + key: 'nested-folder', + depth: 1, + groupDepth: 0, + folderWorkspace: { id: 'f', executionHostId: 'ssh:box' }, + projectGroup: {} + }, + { + type: 'item', + rowKey: 'child', + sectionKey: 'all', + worktree: child, + repo: { id: 'r' }, + depth: 2, + groupDepth: 0 + } + ] as unknown as RenderRow[] + const content = document.createElement('div') + content.setAttribute('data-worktree-sidebar-content', '') + content.getBoundingClientRect = () => new DOMRect(0, 0, 300, 400) + const container = document.createElement('div') + container.append(content) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This boundary reads only cached virtual endpoints; no mounted DOM or drag-window operation is used. + const virtualization = { + virtualizer: { + measurementsCache: [ + { start: 0, end: 100 }, + { start: 100, end: 200 }, + { start: 200, end: 320 } + ] + } + } as unknown as WorktreeListVirtualizer + const { result } = renderHook(() => + useWorktreeRowGeometry({ + rows, + projection: buildLineageRowProjection(rows, 'none', false), + virtualization, + scrollRef: { current: container } + }) + ) + const folder = 'ssh:box|folder:f' + // Surface is x25..293, y112..307: its own closing7 is included, ancestor7 and outer6 are excluded. + for (const [clientX, clientY, lineClientY, expected] of [ + [30, 105, 150, [child]], + [30, 120, 150, []], + [30, 310, 300, [child]], + [30, 305, 300, []], + [20, 120, 150, [child]] + ] as const) { + const snapshot = result.current.captureFolderRetention( + { clientX, clientY, lineClientY }, + new Set([folder]) + ) + expect( + getReorderUnnestRows({ + legacyIds: [], + pickedCopies: [child], + sourceGroupIdentities: ['ssh:box|r::/child'], + folderParentOf: () => folder, + keepsFolderParent: (identity) => result.current.keepsFolderParent(identity, snapshot) + }) + ).toEqual(expected) + } +}) diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-geometry.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-geometry.ts new file mode 100644 index 00000000000..c8666129c04 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-geometry.ts @@ -0,0 +1,205 @@ +import { useCallback, useMemo } from 'react' +import type React from 'react' +import type { RenderRow } from '../listing/render-row' +import type { LineageRowProjection } from '../listing/lineage-row-projection' +import type { WorktreeListVirtualizer } from './use-virtualizer' +import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity' +import { getWorktreeDragUnitGroups } from '../drag/worktree-drag-units' +import { getWorktreeDragIndexes } from '../drag/groups' +import type { WorktreeSidebarDragRect } from '../drag/worktree-sidebar-drag-autoscroll' +import { + isReorderInsideFolderBounds, + type WorktreeReorderDropPoint +} from '../drag/worktree-lineage-drag-drop' + +export type WorktreeRowGeometry = ReturnType + +export function useWorktreeRowGeometry(args: { + rows: RenderRow[] + projection: LineageRowProjection + virtualization: WorktreeListVirtualizer + scrollRef: React.RefObject +}) { + const { rows, projection, virtualization, scrollRef } = args + const units = useMemo(() => getWorktreeDragUnitGroups(rows), [rows]) + const indexes = useMemo(() => getWorktreeDragIndexes(rows), [rows]) + const ranges = useMemo(() => { + const rowByGroupIdentity = new Map>() + rows.forEach((row, index) => { + if (row.type !== 'item') { + return + } + const group = indexes.groupKeyByRowKey.get(row.rowKey) + if (!group) { + return + } + let members = rowByGroupIdentity.get(group) + if (!members) { + rowByGroupIdentity.set(group, (members = new Map())) + } + members.set(getWorktreeHostIdentity(row.worktree), index) + }) + const byRow = new Map< + number, + { + group: string + identity: string + groupIndex: number + first: number + last: number + trailing: number + next: number | undefined + } + >() + const byGroup = new Map>>>() + for (const group of units) { + const members = rowByGroupIdentity.get(group.key) + const ranges = new Map>>() + group.units.forEach((unit, groupIndex) => { + const first = members?.get(unit.worktreeId) + const last = members?.get(unit.worktreeIds.at(-1)!) + if (first === undefined || last === undefined) { + return + } + let trailing = 0 + let parent = projection.frames[first].parent + while (parent !== null) { + if (projection.frames[parent].end === last) { + trailing += 7 + } + parent = projection.frames[parent].parent + } + const range = { + group: group.key, + identity: unit.worktreeId, + groupIndex, + first, + last, + trailing, + next: members?.get(group.units[groupIndex + 1]?.worktreeId ?? '') + } + ranges.set(unit.worktreeId, range) + for (const identity of unit.worktreeIds) { + const index = members?.get(identity) + if (index !== undefined) { + byRow.set(index, range) + } + } + }) + byGroup.set(group.key, ranges) + } + return { byRow, byGroup } + }, [indexes, projection, rows, units]) + const getRects = useCallback( + (group: string, retained: readonly string[] = []): WorktreeSidebarDragRect[] => { + const selected = new Map>>() + for (const item of virtualization.virtualizer.getVirtualItems()) { + const range = ranges.byRow.get(item.index) + if (range?.group === group) { + selected.set(range.identity, range) + } + } + for (const identity of retained) { + const range = ranges.byGroup.get(group)?.get(identity) + if (range) { + selected.set(identity, range) + } + } + const measurements = virtualization.virtualizer.measurementsCache + return [...selected.values()] + .flatMap((range) => { + const first = measurements[range.first] + const last = measurements[range.last] + if (!first || !last) { + return [] + } + const frame = projection.frames[range.last] + const bottom = last.end - frame.after - range.trailing + const next = range.next === undefined ? undefined : measurements[range.next] + const gap = + next && range.next !== undefined + ? Math.max(0, next.start + projection.frames[range.next].before - bottom) + : projection.frames[range.first].parent === null + ? 6 + : 4 + return [ + { + worktreeId: range.identity, + groupIndex: range.groupIndex, + top: first.start + projection.frames[range.first].before, + bottom, + layoutBottom: bottom + gap + } + ] + }) + .sort((a, b) => a.top - b.top) + }, + [projection, ranges, virtualization.virtualizer] + ) + const keepsFolderParent = useCallback( + (identity: string, point: WorktreeReorderDropPoint | undefined, contentRect?: DOMRect) => { + if (point?.retainedFolderIdentities) { + return point.retainedFolderIdentities.has(identity) + } + const rect = + contentRect ?? + scrollRef.current?.querySelector('[data-worktree-sidebar-content]')?.getBoundingClientRect() + if (!point || !rect) { + return false + } + const measurements = virtualization.virtualizer.measurementsCache + return (projection.occurrencesByIdentity.get(identity) ?? []).some((index) => { + if (rows[index]?.type !== 'folder-workspace') { + return false + } + const frame = projection.frames[index] + const first = measurements[index] + const last = measurements[frame.end] + if (!first || !last) { + return false + } + const top = rect.top + first.start + frame.before + let trailing = 0 + let parent = frame.parent + while (parent !== null) { + const ancestor = projection.frames[parent] + if (ancestor.end === frame.end) { + trailing += 7 + } + parent = ancestor.parent + } + const bottom = rect.top + last.end - projection.frames[frame.end].after - trailing + return isReorderInsideFolderBounds(point, { + left: rect.left + frame.left + 4, + right: rect.right - frame.right, + top, + bottom + }) + }) + }, + [projection, rows, scrollRef, virtualization.virtualizer] + ) + const captureFolderRetention = useCallback( + (point: WorktreeReorderDropPoint | undefined, folderIdentities: ReadonlySet) => { + if (!point) { + return point + } + const retainedFolderIdentities = new Set() + if (folderIdentities.size > 0) { + const rect = scrollRef.current + ?.querySelector('[data-worktree-sidebar-content]') + ?.getBoundingClientRect() + if (rect) { + for (const identity of folderIdentities) { + if (keepsFolderParent(identity, point, rect)) { + retainedFolderIdentities.add(identity) + } + } + } + } + return { ...point, retainedFolderIdentities } + }, + [keepsFolderParent, scrollRef] + ) + return { units, indexes, ranges, getRects, keepsFolderParent, captureFolderRetention } +} diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-measurement.scroll.test.tsx b/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-measurement.scroll.test.tsx new file mode 100644 index 00000000000..c85326b2cfe --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-measurement.scroll.test.tsx @@ -0,0 +1,291 @@ +// @vitest-environment happy-dom +import { act, useMemo } from 'react' +import { cleanup, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { createProgrammaticScrollMarks } from '@/hooks/programmatic-scroll-marks' +import { requestVirtualizedScrollAnchorRecord } from '@/hooks/requestVirtualizedScrollAnchorRecord' +import type { VirtualizedScrollAnchor } from '@/hooks/useVirtualizedScrollAnchor' +import { buildLineageRowProjection } from '../listing/lineage-row-projection' +import type { RenderRow } from '../listing/render-row' +import { repo, worktree } from '../grouping/worktree-list-groups-test-fixtures' +import { revealElementInScrollContainer } from '../navigation/worktree-sidebar-reveal' +import { useVirtualRowMeasurementSync } from './use-row-measurement' +import { useWorktreeSidebarScrollSuppression } from './use-scroll-suppression' +import { preserveDeleteSiblingPosition } from '../../workspace-actions/context-menu/worktree-context-menu-policy' +import type { WorktreeListVirtualizer } from './use-virtualizer' + +const caches = vi.hoisted(() => ({ prCache: {}, issueCache: {} })) +vi.mock('@/store', () => ({ + useAppStore: (selector: (state: typeof caches) => unknown) => selector(caches) +})) + +const frames = new Map() +let nextFrame = 0 +beforeEach(() => { + vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => { + frames.set(++nextFrame, callback) + return nextFrame + }) + vi.spyOn(window, 'cancelAnimationFrame').mockImplementation((id) => frames.delete(id)) +}) +afterEach(() => { + cleanup() + frames.clear() + document.body.replaceChildren() + vi.restoreAllMocks() +}) + +function row(id: string): RenderRow { + return { + type: 'item', + rowKey: id, + sectionKey: 'all', + repo, + worktree: { ...worktree, id }, + depth: 0, + groupDepth: 0, + isLastLineageChild: false, + lineageChildCount: 0 + } +} + +function setup(interior = false) { + const scroller = document.createElement('div') + scroller.setAttribute('data-worktree-sidebar', '') + document.body.append(scroller) + Object.defineProperties(scroller, { + clientHeight: { value: 400 }, + scrollHeight: { value: 4000 } + }) + scroller.getBoundingClientRect = () => new DOMRect(0, 0, 300, 400) + scroller.scrollTop = 1000 + scroller.scrollTo = (options?: ScrollToOptions | number) => { + if (typeof options === 'object') { + scroller.scrollTop = options.top ?? 0 + } + } + const model = { + sizes: new Map(), + starts: new Map([ + ['a', 0], + ['b', 1000], + ['c', 2000], + ['d', 3000] + ]), + items: interior ? ['a', 'b', 'c', 'd'] : ['a', 'b', 'c'], + totalSize: 4000 + } + const mount = (id: string) => { + const element = document.createElement('div') + element.setAttribute('data-worktree-virtual-row', '') + element.setAttribute('data-worktree-virtual-row-key', `wt:${id}`) + element.getBoundingClientRect = () => + new DOMRect( + 0, + (model.starts.get(id) ?? 0) - scroller.scrollTop, + 300, + model.sizes.get(id) ?? 1000 + ) + scroller.append(element) + return element + } + const mounted = mount('b') + const virtualizer = { + elementsCache: new Map(), + getTotalSize: () => model.totalSize, + getVirtualItems: () => + model.items.map((id, index) => ({ + index, + key: `wt:${id}`, + start: model.starts.get(id) ?? 0, + end: (model.starts.get(id) ?? 0) + (model.sizes.get(id) ?? 1000), + size: model.sizes.get(id) ?? 1000, + lane: 0 + })), + measureElement: () => {}, + isScrolling: false, + scrollOffset: null, + scrollToIndex: () => { + scroller.scrollTop = 500 + } + } + const scrollRef = { current: scroller } + const scrollOffsetRef = { current: 1000 } + const scrollAnchorRef: { current: VirtualizedScrollAnchor } = { current: null } + const marks = createProgrammaticScrollMarks() + const view = renderHook( + ({ rows }: { rows: RenderRow[] }) => { + const projection = useMemo(() => buildLineageRowProjection(rows, 'none', false), [rows]) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The fixture supplies the geometry and virtualizer methods consumed by the production measurement/anchor integration. + const virtualization = { + virtualizer, + isCurrentVirtualRowElement: () => true, + stickyHeaderIndexes: [], + activeStickyHeaderIndexRef: { current: null }, + activeStickyHostIndexRef: { current: null }, + stickyRangeStartIndexRef: { current: 0 }, + rowIndexByKey: projection.rowIndexByKey, + restoreSignal: projection.restoreSignal, + programmaticScrollMarks: marks + } as unknown as WorktreeListVirtualizer + const input = useWorktreeSidebarScrollSuppression(scrollRef) + useVirtualRowMeasurementSync({ + renderRows: rows, + virtualization, + scrollRef, + scrollOffsetRef, + scrollAnchorRef, + shouldSkipScrollAnchorRestore: input.shouldSkipScrollAnchorRestore + }) + return input + }, + { + initialProps: { + rows: interior + ? [row('a'), { ...row('b'), depth: 1 }, { ...row('c'), depth: 1 }, row('d')] + : [row('a'), row('b'), row('c')] + } + } + ) + act(() => requestVirtualizedScrollAnchorRecord(scroller)) + return { scroller, model, mount, mounted, view } +} + +it('leaves height-only scroll correction to the virtualizer instead of restoring an older DOM position', () => { + const { scroller, model, view } = setup() + act(() => { + scroller.scrollTop = 1200 + scroller.dispatchEvent(new Event('scroll')) + }) + model.starts.set('b', 950) + model.totalSize = 3950 + view.rerender({ rows: [row('a'), row('b'), row('c')] }) + expect(scroller.scrollTop).toBe(1200) +}) + +it('preserves the visible occurrence when rows before it disappear', () => { + const { scroller, model, mounted, view } = setup() + act(() => { + scroller.scrollTop = 1020 + scroller.dispatchEvent(new Event('scroll')) + }) + model.starts.set('b', 0) + model.starts.set('c', 1000) + model.items = ['b', 'c'] + model.totalSize = 3000 + view.rerender({ rows: [row('b'), row('c')] }) + expect(scroller.scrollTop).toBe(20) + expect(mounted.getBoundingClientRect().top).toBe(-20) +}) + +it('lets an already-visible explicit reveal supersede a pending offscreen restore', () => { + const { scroller, model, mounted, mount, view } = setup() + mounted.remove() + model.items = [] + view.rerender({ rows: [row('b'), row('c')] }) + expect(scroller.scrollTop).toBe(500) + model.starts.set('c', 550) + const destination = mount('c') + destination.getBoundingClientRect = () => new DOMRect(0, 550 - scroller.scrollTop, 300, 100) + model.starts.set('b', 400) + model.sizes.set('b', 100) + const oldTarget = mount('b') + oldTarget.getBoundingClientRect = () => new DOMRect(0, 400 - scroller.scrollTop, 300, 100) + model.items = ['b', 'c'] + act(() => { + expect(revealElementInScrollContainer(scroller, destination, 'auto')).toBe(true) + const pendingFrames = [...frames] + for (const [id, callback] of pendingFrames) { + frames.delete(id) + callback(0) + } + }) + expect(scroller.scrollTop).toBe(500) + expect(destination.getBoundingClientRect().top).toBe(50) +}) + +function finishPositioning() { + act(() => { + for (let turn = 0; turn < 12 && frames.size; turn++) { + const pendingFrames = [...frames] + for (const [id, callback] of pendingFrames) { + frames.delete(id) + callback(0) + } + } + }) +} + +it('lets no-op direct input retire an old target and preserve position on a later insertion', () => { + const { scroller, model, mounted, mount, view } = setup() + mounted.remove() + model.items = [] + view.rerender({ rows: [row('b'), row('c')] }) + model.starts.set('b', 400) + model.sizes.set('b', 100) + const oldTarget = mount('b') + oldTarget.getBoundingClientRect = () => new DOMRect(0, 400 - scroller.scrollTop, 300, 100) + model.starts.set('c', 480) + const destination = mount('c') + model.items = ['b', 'c'] + act(() => view.result.current.markDirectScrollInput()) + finishPositioning() + expect(scroller.scrollTop).toBe(500) + expect(destination.getBoundingClientRect().top).toBe(-20) + model.starts.set('c', 680) + model.items = ['b', 'new', 'c'] + view.rerender({ rows: [row('b'), row('new'), row('c')] }) + expect(scroller.scrollTop).toBe(700) + expect(destination.getBoundingClientRect().top).toBe(-20) +}) + +it('keeps an interior descendant successor at the removed card position after action takeover', () => { + const { scroller, model, mounted, mount, view } = setup(true) + model.sizes.set('b', 200) + model.starts.set('c', 1200) + model.starts.set('d', 2200) + model.totalSize = 3200 + const successor = mount('c') + act(() => { + scroller.scrollTop = 1020 + scroller.dispatchEvent(new Event('scroll')) + }) + const position = preserveDeleteSiblingPosition(mounted) + // The real teardown boundary records the live viewport immediately before its row mutation. + act(() => requestVirtualizedScrollAnchorRecord(scroller)) + mounted.remove() + model.starts.set('c', 1000) + model.starts.set('d', 2000) + model.items = ['a', 'c', 'd'] + model.totalSize = 3000 + view.rerender({ rows: [row('a'), { ...row('c'), depth: 1 }, row('d')] }) + expect(scroller.scrollTop).toBe(1000) + act(position) + view.rerender({ rows: [row('a'), { ...row('c'), depth: 1 }, row('d')] }) + expect(scroller.scrollTop).toBe(1020) + finishPositioning() + expect(scroller.scrollTop).toBe(1020) + expect(successor.getBoundingClientRect().top).toBe(-20) +}) + +it('preserves the live viewport when delayed removal follows completed positioning and user scrolling', () => { + const { scroller, model, mounted, mount, view } = setup(true) + const successor = mount('c') + const position = preserveDeleteSiblingPosition(mounted) + act(position) + finishPositioning() + act(() => { + scroller.scrollTop = 2100 + scroller.dispatchEvent(new Event('scroll')) + requestVirtualizedScrollAnchorRecord(scroller) + }) + mounted.remove() + model.starts.set('c', 1000) + model.starts.set('d', 2000) + model.items = ['a', 'c', 'd'] + model.totalSize = 3000 + view.rerender({ rows: [row('a'), { ...row('c'), depth: 1 }, row('d')] }) + finishPositioning() + expect(scroller.scrollTop).toBe(1100) + expect(successor.getBoundingClientRect().top).toBe(-100) +}) diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-measurement.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-measurement.ts index 02889ddad96..171ae6e272b 100644 --- a/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-measurement.ts +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-measurement.ts @@ -6,7 +6,6 @@ import { type VirtualizedScrollAnchor } from '@/hooks/useVirtualizedScrollAnchor' import { - buildLineageRowRekeyMap, getActiveStickyIndexesForScroll, getVirtualRowKey, pruneStaleVirtualRowElementCache @@ -14,7 +13,6 @@ import { import { getRenderRowKey } from '../listing/render-row' import type { RenderRow } from '../listing/render-row' import type { WorktreeListVirtualizer } from './use-virtualizer' -import { useVirtualRowRemovalAnimation } from './use-row-removal-animation' const recordKeyCountCache = new WeakMap, number>() @@ -35,7 +33,6 @@ export function useVirtualRowMeasurementSync(args: { scrollRef: React.RefObject scrollOffsetRef: React.MutableRefObject scrollAnchorRef: React.MutableRefObject - hasDirectScrollInput: () => boolean shouldSkipScrollAnchorRestore: () => boolean }) { const { @@ -44,14 +41,15 @@ export function useVirtualRowMeasurementSync(args: { scrollRef, scrollOffsetRef, scrollAnchorRef, - hasDirectScrollInput, shouldSkipScrollAnchorRestore } = args const { virtualizer, isCurrentVirtualRowElement } = virtualization const prCacheLen = useAppStore((s) => countRecordKeysByReference(s.prCache)) const issueCacheLen = useAppStore((s) => countRecordKeysByReference(s.issueCache)) - const activeRenderRowKeys = useMemo(() => new Set(renderRows.map(getRenderRowKey)), [renderRows]) - const lineageRowRekeys = useMemo(() => buildLineageRowRekeyMap(renderRows), [renderRows]) + const activeRenderRowKeys = useMemo( + () => new Set(virtualization.rowIndexByKey.keys()), + [virtualization.rowIndexByKey] + ) const totalSize = virtualizer.getTotalSize() const virtualItems = virtualizer.getVirtualItems() const activeStickyIndexes = getActiveStickyIndexesForScroll({ @@ -95,29 +93,30 @@ export function useVirtualRowMeasurementSync(args: { measureMountedRows() const frameId = window.requestAnimationFrame(measureMountedRows) return () => window.cancelAnimationFrame(frameId) - }, [activeRenderRowKeys, prCacheLen, issueCacheLen, measureMountedRows, virtualizer]) + }, [ + activeRenderRowKeys, + prCacheLen, + issueCacheLen, + measureMountedRows, + virtualizer, + virtualization.smoothScrollRevision + ]) useVirtualizedScrollAnchor({ anchorRef: scrollAnchorRef, getItemElementKey: getVirtualRowKey, getRowKey: getRenderRowKey, itemElementSelector: '[data-worktree-virtual-row]', - rekeyedRowKeys: lineageRowRekeys, rows: renderRows, + rowIndexByKey: virtualization.rowIndexByKey, + restoreSignal: virtualization.restoreSignal, + programmaticScrollMarks: virtualization.programmaticScrollMarks, scrollElementRef: scrollRef, scrollOffsetRef, - hasDirectScrollInput, shouldSkipRestore: shouldSkipScrollAnchorRestore, totalSize, virtualizer }) - useVirtualRowRemovalAnimation({ - renderRows, - rekeyedRowKeys: lineageRowRekeys, - scrollRef, - virtualItems - }) - return { virtualItems, measureVirtualRowElement } } diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-removal-animation.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-removal-animation.ts deleted file mode 100644 index 59fb6468810..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/viewport/use-row-removal-animation.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { useLayoutEffect, useMemo, useRef } from 'react' -import type React from 'react' -import type { VirtualItem } from '@tanstack/react-virtual' -import type { RenderRow } from '../listing/render-row' -import { getRenderRowKey } from '../listing/render-row' - -export const WORKTREE_ROW_REMOVAL_ANIMATION_MS = 180 - -export type VirtualRowLayoutSnapshot = { - rowIdentityKeys: ReadonlySet - scrollTop: number - startsByKey: ReadonlyMap -} - -export type VirtualRowRemovalMotion = { - deltaY: number - key: string -} - -export function getSidebarRowIdentityKeys(rows: readonly RenderRow[]): ReadonlySet { - const keys = new Set() - for (const row of rows) { - if (row.type === 'lineage-group') { - row.rows.forEach((member) => keys.add(`wt:${member.rowKey}`)) - if (row.folder) { - keys.add(getRenderRowKey(row.folder)) - } - } else { - keys.add(getRenderRowKey(row)) - } - } - return keys -} - -export function buildVirtualRowRemovalMotions(args: { - previous: VirtualRowLayoutSnapshot | null - current: VirtualRowLayoutSnapshot - rekeyedRowKeys: ReadonlyMap -}): VirtualRowRemovalMotion[] { - const { previous, current, rekeyedRowKeys } = args - if (previous === null || previous.rowIdentityKeys === current.rowIdentityKeys) { - return [] - } - let removedRow = false - for (const key of previous.rowIdentityKeys) { - if (!current.rowIdentityKeys.has(key)) { - removedRow = true - break - } - } - if (!removedRow) { - return [] - } - - const previousKeyByCurrentKey = new Map() - rekeyedRowKeys.forEach((currentKey, previousKey) => { - previousKeyByCurrentKey.set(currentKey, previousKey) - }) - const motions: VirtualRowRemovalMotion[] = [] - current.startsByKey.forEach((currentStart, key) => { - const previousKey = previous.startsByKey.has(key) ? key : previousKeyByCurrentKey.get(key) - const previousStart = previousKey ? previous.startsByKey.get(previousKey) : undefined - if (previousStart === undefined) { - return - } - const deltaY = previousStart - previous.scrollTop - (currentStart - current.scrollTop) - if (Math.abs(deltaY) > 0.5) { - motions.push({ deltaY, key }) - } - }) - return motions -} - -export function useVirtualRowRemovalAnimation(args: { - renderRows: readonly RenderRow[] - rekeyedRowKeys: ReadonlyMap - scrollRef: React.RefObject - virtualItems: readonly VirtualItem[] -}): void { - const { renderRows, rekeyedRowKeys, scrollRef, virtualItems } = args - const previousSnapshotRef = useRef(null) - const rowIdentityKeys = useMemo(() => getSidebarRowIdentityKeys(renderRows), [renderRows]) - - useLayoutEffect(() => { - const scrollElement = scrollRef.current - if (!scrollElement) { - return - } - const current: VirtualRowLayoutSnapshot = { - rowIdentityKeys, - scrollTop: scrollElement.scrollTop, - startsByKey: new Map(virtualItems.map((item) => [String(item.key), item.start])) - } - const motions = buildVirtualRowRemovalMotions({ - previous: previousSnapshotRef.current, - current, - rekeyedRowKeys - }) - previousSnapshotRef.current = current - if (motions.length === 0 || window.matchMedia('(prefers-reduced-motion: reduce)').matches) { - return - } - - const elementsByKey = new Map( - Array.from( - scrollElement.querySelectorAll('[data-worktree-virtual-row-key]') - ).map((element) => [element.dataset.worktreeVirtualRowKey ?? '', element]) - ) - for (const motion of motions) { - const element = elementsByKey.get(motion.key) - if (!element || element.hasAttribute('data-worktree-sticky-header-active')) { - continue - } - const content = element.firstElementChild - if (!(content instanceof HTMLElement)) { - continue - } - content.animate([{ translate: `0 ${motion.deltaY}px` }, { translate: '0 0' }], { - duration: WORKTREE_ROW_REMOVAL_ANIMATION_MS, - easing: 'cubic-bezier(0.16, 1, 0.3, 1)' - }) - } - }, [rekeyedRowKeys, rowIdentityKeys, scrollRef, virtualItems]) -} diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-suppression.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-suppression.ts index 1a88429c1d9..7f3f08600da 100644 --- a/src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-suppression.ts +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-suppression.ts @@ -1,59 +1,33 @@ -import { useCallback, useEffect, useRef } from 'react' +import { + requestVirtualizedScrollAnchorRecord, + supersedeVirtualizedScrollAnchorRestore +} from '@/hooks/requestVirtualizedScrollAnchorRecord' +import { useCallback, useRef } from 'react' import type React from 'react' -import { SUPPRESS_WORKTREE_LIST_SCROLL_ADJUSTMENT_EVENT } from '../../workspace-card/activity/WorktreeCardAgents' import { createPendingRevealScroll, isRevealScrollSettling, type PendingRevealScroll } from '../navigation/worktree-sidebar-reveal-scroll-settle' -export const USER_SCROLL_MEASUREMENT_ADJUSTMENT_SUPPRESS_MS = 500 -export const EXPANDING_CARD_MEASUREMENT_ADJUSTMENT_SUPPRESS_MS = 300 - -export function shouldAdjustWorktreeSidebarMeasuredRowScroll(args: { - isScrolling: boolean - now: number - suppressUntil: number - itemStart: number - itemEnd: number - scrollOffset: number - isFirstMeasurement: boolean - scrollDirection: 'forward' | 'backward' | null -}): boolean { - if (args.isScrolling || args.now < args.suppressUntil) { - return false - } - // Preserve TanStack's fold rule so below-anchor growth cannot invent a scroll offset. - return args.isFirstMeasurement - ? args.itemStart < args.scrollOffset - : args.itemEnd <= args.scrollOffset && args.scrollDirection !== 'backward' -} - export type WorktreeSidebarScrollSuppression = ReturnType< typeof useWorktreeSidebarScrollSuppression > -// Track measurement suppression for all scrolling and anchor suppression for direct input or smooth reveals. +// Explicit input retires the previous target; smooth reveal owns its settling position. export function useWorktreeSidebarScrollSuppression( scrollRef: React.RefObject ) { - const suppressMeasurementAdjustmentUntilRef = useRef(0) - const directScrollInputUntilRef = useRef(0) const pendingRevealScrollRef = useRef(null) + const cancelRevealScroll = useCallback(() => { + pendingRevealScrollRef.current = null + }, []) - const markScrollMovement = useCallback(() => { - suppressMeasurementAdjustmentUntilRef.current = - window.performance.now() + USER_SCROLL_MEASUREMENT_ADJUSTMENT_SUPPRESS_MS - }, []) const markDirectScrollInput = useCallback(() => { - const suppressUntil = window.performance.now() + USER_SCROLL_MEASUREMENT_ADJUSTMENT_SUPPRESS_MS - suppressMeasurementAdjustmentUntilRef.current = suppressUntil - directScrollInputUntilRef.current = suppressUntil - }, []) - const hasDirectScrollInput = useCallback( - () => window.performance.now() < directScrollInputUntilRef.current, - [] - ) + supersedeVirtualizedScrollAnchorRestore(scrollRef.current) + cancelRevealScroll() + requestVirtualizedScrollAnchorRecord(scrollRef.current, { deferDomMeasurement: true }) + }, [cancelRevealScroll, scrollRef]) const markRevealScroll = useCallback((targetTop: number) => { pendingRevealScrollRef.current = createPendingRevealScroll(targetTop, window.performance.now()) }, []) @@ -68,32 +42,11 @@ export function useWorktreeSidebarScrollSuppression( } return settling }, [scrollRef]) - // Programmatic scrolling suppresses measurements; only direct input or an in-flight reveal blocks anchor restore. - const shouldSkipScrollAnchorRestore = useCallback( - () => - window.performance.now() < directScrollInputUntilRef.current || isRevealScrollSettlingNow(), - [isRevealScrollSettlingNow] - ) - - useEffect(() => { - const handleSuppress = () => { - // Why: let an expanding agent row grow in place instead of TanStack compensating scrollTop. - suppressMeasurementAdjustmentUntilRef.current = - window.performance.now() + EXPANDING_CARD_MEASUREMENT_ADJUSTMENT_SUPPRESS_MS - } - window.addEventListener(SUPPRESS_WORKTREE_LIST_SCROLL_ADJUSTMENT_EVENT, handleSuppress) - return () => { - window.removeEventListener(SUPPRESS_WORKTREE_LIST_SCROLL_ADJUSTMENT_EVENT, handleSuppress) - } - }, []) return { - suppressMeasurementAdjustmentUntilRef, - directScrollInputUntilRef, - markScrollMovement, + cancelRevealScroll, markDirectScrollInput, - hasDirectScrollInput, markRevealScroll, - shouldSkipScrollAnchorRestore + shouldSkipScrollAnchorRestore: isRevealScrollSettlingNow } } diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.ts index 0df493210ab..93b77a4c4b7 100644 --- a/src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.ts +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.ts @@ -1,3 +1,7 @@ +import { + requestVirtualizedScrollAnchorRecord, + supersedeVirtualizedScrollAnchorRestore +} from '@/hooks/requestVirtualizedScrollAnchorRecord' import { useCallback, useEffect, useRef, useState } from 'react' import { createHardScrollUpDetectorState, @@ -214,7 +218,9 @@ export function useWorktreeListScrollToTop({ clearIdleTimer() suppressDetectionUntilRef.current = window.performance.now() + HARD_SCROLL_UP.suppressAfterJumpMs + supersedeVirtualizedScrollAnchorRestore(scrollElement, 0) scrollElement.scrollTo({ top: 0, behavior: 'auto' }) + requestVirtualizedScrollAnchorRecord(scrollElement) scrollElement.focus({ preventScroll: true }) }, [clearIdleTimer, onUserScrollIntent, publishVisible, scrollElement]) diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/use-virtualizer.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/use-virtualizer.ts index 03809ab4d27..14d9e3699dc 100644 --- a/src/renderer/src/components/sidebar/worktree-list/viewport/use-virtualizer.ts +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/use-virtualizer.ts @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useRef } from 'react' +import { useCallback, useMemo, useReducer, useRef } from 'react' import type React from 'react' import { measureElement as measureVirtualElementSize, @@ -13,22 +13,22 @@ import { WORKTREE_SIDEBAR_VIRTUAL_ROW_GAP } from './virtual-rows' import { getRenderRowKey } from '../listing/render-row' +import type { LineageRowProjection } from '../listing/lineage-row-projection' import type { RenderRow } from '../listing/render-row' import { WORKTREE_SIDEBAR_REVEAL_TOP_INSET } from '../navigation/worktree-sidebar-reveal' -import { - shouldAdjustWorktreeSidebarMeasuredRowScroll, - USER_SCROLL_MEASUREMENT_ADJUSTMENT_SUPPRESS_MS -} from './use-scroll-suppression' +import type { ProgrammaticScrollMarks } from '@/hooks/programmatic-scroll-marks' +import { createSidebarSmoothReveal } from './sidebar-smooth-reveal' export type WorktreeListVirtualizer = ReturnType // Guard virtual row identity so recycled DOM nodes cannot overwrite another slot’s measured height. export function useWorktreeListVirtualizer(args: { + projection: LineageRowProjection renderRows: RenderRow[] firstHeaderIndex: number scrollRef: React.RefObject scrollOffsetRef: React.MutableRefObject - suppressMeasurementAdjustmentUntilRef: React.MutableRefObject + programmaticScrollMarks: ProgrammaticScrollMarks }) { const { renderRows, firstHeaderIndex, scrollRef, scrollOffsetRef } = args const stickyHeaderIndexes = useMemo(() => getStickyHeaderIndexes(renderRows), [renderRows]) @@ -97,21 +97,35 @@ export function useWorktreeListVirtualizer(args: { activeStickyHeaderIndexRef.current ) } - return measureVirtualElementSize(element, entry, instance) + const measured = measureVirtualElementSize(element, entry, instance) + const row = index === null ? undefined : renderRows[index] + return measured + (row?.type === 'item' || row?.type === 'folder-workspace' ? 0 : 6) }, [firstHeaderIndex, isCurrentVirtualRowElement, renderRows] ) + const [smoothScrollRevision, onRetired] = useReducer((revision: number) => revision + 1, 0) + const smoothReveal = useMemo( + () => createSidebarSmoothReveal({ marks: args.programmaticScrollMarks, onRetired }), + [args.programmaticScrollMarks, onRetired] + ) const virtualizer = useVirtualizer({ count: renderRows.length, getScrollElement: () => scrollRef.current, - estimateSize: (index) => - estimateRenderRowSize( - renderRows, - index, - firstHeaderIndex, - activeStickyHeaderIndexRef.current - ), + estimateSize: (index) => { + const frame = args.projection.frames[index] + return ( + estimateRenderRowSize( + renderRows, + index, + firstHeaderIndex, + activeStickyHeaderIndexRef.current + ) + + (renderRows[index]?.type === 'item' || renderRows[index]?.type === 'folder-workspace' + ? frame.before + frame.closing + frame.after + : 0) + ) + }, measureElement: measureCurrentVirtualRowElement, // Why: TanStack memoizes rangeExtractor by identity; header indexes must be deps or sticky slots go stale. rangeExtractor: useCallback( @@ -129,29 +143,19 @@ export function useWorktreeListVirtualizer(args: { gap: WORKTREE_SIDEBAR_VIRTUAL_ROW_GAP, // Why: the sticky group header lives inside the virtual list, so scroll math needs the same top inset as the DOM reveal. scrollPaddingStart: WORKTREE_SIDEBAR_REVEAL_TOP_INSET, - isScrollingResetDelay: USER_SCROLL_MEASUREMENT_ADJUSTMENT_SUPPRESS_MS, - // Why: sync-flushing rich card renders in the scroll listener stalls wheel input; async + overscan keeps rows filled. - useFlushSync: false, // Why: seed scrollOffset from the ref (not 0) so the first getVirtualItems() after remount picks the right rows. initialOffset: () => scrollOffsetRef.current, + scrollToFn: smoothReveal.scrollTo, + observeElementOffset: smoothReveal.observeOffset, getItemKey: getVirtualItemKey }) - // Why: TanStack's default correction writes scrollTop while cards remeasure mid-wheel, which feels like rubber-banding. - // TODO(scroll-origin-migration): wall-clock suppression misclassifies under jank; migrate to programmaticScrollMarks + restoreSignal (see CombinedDiffViewer). - virtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, _delta, instance) => - shouldAdjustWorktreeSidebarMeasuredRowScroll({ - isScrolling: instance.isScrolling, - now: window.performance.now(), - suppressUntil: args.suppressMeasurementAdjustmentUntilRef.current, - itemStart: item.start, - itemEnd: item.end, - scrollOffset: (instance.scrollOffset ?? scrollOffsetRef.current) + instance.scrollAdjustments, - isFirstMeasurement: !instance.itemSizeCache.has(item.key), - scrollDirection: instance.scrollDirection - }) return { virtualizer, + smoothScrollRevision, + programmaticScrollMarks: args.programmaticScrollMarks, + rowIndexByKey: args.projection.rowIndexByKey, + restoreSignal: args.projection.restoreSignal, isCurrentVirtualRowElement, stickyHeaderIndexes, activeStickyHeaderIndexRef, diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/use-visible-review-refresh.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/use-visible-review-refresh.ts index 540cbedaaac..e78ccc189ef 100644 --- a/src/renderer/src/components/sidebar/worktree-list/viewport/use-visible-review-refresh.ts +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/use-visible-review-refresh.ts @@ -46,9 +46,7 @@ export function visibleReviewCardIds(args: { return args.virtualItems .filter((item) => item.start < bottom && item.end > args.viewportTop) .map((item) => args.renderRows[item.index]) - .flatMap((row): WorktreeItemRow[] => - row?.type === 'lineage-group' ? row.rows : row?.type === 'item' ? [row] : [] - ) + .flatMap((row): WorktreeItemRow[] => (row?.type === 'item' ? [row] : [])) .filter( (row) => (row.repo?.kind ?? 'git') === 'git' && diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/virtual-row-context.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/virtual-row-context.ts index 366b582aa67..60718f2d76c 100644 --- a/src/renderer/src/components/sidebar/worktree-list/viewport/virtual-row-context.ts +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/virtual-row-context.ts @@ -2,6 +2,7 @@ import type React from 'react' import type { AppState } from '@/store/types' import type { ProjectGroup } from '../../../../../../shared/project-group-types' import type { Worktree } from '../../../../../../shared/worktree/types' +import type { LineageRowProjection } from '../listing/lineage-row-projection' import type { RenderRow } from '../listing/render-row' import type { LineageToggleHandler } from '../../workspace-card/identity/worktree-lineage-toggle-handler-cache' import type { SidebarRevealHighlight } from '../navigation/use-reveal-highlight' @@ -22,6 +23,10 @@ import type { ProjectHeaderHostContext } from '../rows/project-header-host-conte type BuildArgs = { props: VirtualizedWorktreeViewportProps projectGroups: readonly ProjectGroup[] + dragUnitsByRow: ReadonlyMap + hiddenDragRanges: readonly { start: number; end: number }[] + projection: LineageRowProjection + activeFamilyRoots: ReadonlySet renderRows: RenderRow[] firstHeaderIndex: number virtualization: WorktreeListVirtualizer @@ -51,6 +56,10 @@ type BuildArgs = { export function buildWorktreeVirtualRowContext(args: BuildArgs): WorktreeVirtualRowContext { const { props, runtime, session, statusDrag, headerDrag, primaryActive, reveal } = args return { + dragUnitsByRow: args.dragUnitsByRow, + hiddenDragRanges: args.hiddenDragRanges, + projection: args.projection, + activeFamilyRoots: args.activeFamilyRoots, renderRows: args.renderRows, firstHeaderIndex: args.firstHeaderIndex, activeStickyHeaderIndexRef: args.virtualization.activeStickyHeaderIndexRef, diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/virtual-rows.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/virtual-rows.ts index ff132e3d13f..dd54bae3d98 100644 --- a/src/renderer/src/components/sidebar/worktree-list/viewport/virtual-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/virtual-rows.ts @@ -1,51 +1,17 @@ import { defaultRangeExtractor } from '@tanstack/react-virtual' import type { Range, VirtualItem } from '@tanstack/react-virtual' -import { - PINNED_GROUP_KEY, - getWorktreeLineageGroupKey -} from '../../../../../../shared/sidebar-list/group-keys' -import { getRenderRowKey } from '../listing/render-row' +import { PINNED_GROUP_KEY } from '../../../../../../shared/sidebar-list/group-keys' import type { RenderRow } from '../listing/render-row' export const GROUP_HEADER_ROW_HEIGHT = 28 // Why: HostSectionHeader wraps its h-8 (32px) card in pt-1 (4px), so the row is 36px. export const HOST_HEADER_ROW_HEIGHT = 36 -export const WORKTREE_SIDEBAR_VIRTUAL_ROW_GAP = 6 +export const WORKTREE_SIDEBAR_VIRTUAL_ROW_GAP = 0 const SECONDARY_GROUP_HEADER_TOP_MARGIN = 4 const IMPORTED_WORKTREES_LINE_ROW_HEIGHT = 36 const PENDING_CREATION_ROW_HEIGHT = 56 const FOLDER_WORKSPACE_ROW_HEIGHT = 64 -/** Remap anchors when first/last child changes flip a parent between plain and lineage-group keys without moving it. */ -export function buildLineageRowRekeyMap(rows: readonly RenderRow[]): ReadonlyMap { - const rekeyed = new Map() - for (const row of rows) { - if (row.type === 'lineage-group') { - const groupKey = getRenderRowKey(row) - for (const member of row.rows) { - rekeyed.set(`wt:${member.rowKey}`, groupKey) - } - if (row.folder) { - rekeyed.set(getRenderRowKey(row.folder), groupKey) - } - continue - } - if (row.type === 'folder-workspace') { - rekeyed.set(`lineage-group:${row.key}`, getRenderRowKey(row)) - continue - } - if (row.type !== 'item') { - continue - } - // Map dissolved groups even with zero children because old anchors still hold their group key. - rekeyed.set( - `lineage-group:${row.sectionKey}:${getWorktreeLineageGroupKey(row.worktree)}`, - getRenderRowKey(row) - ) - } - return rekeyed -} - export function shouldUseHeaderTopSpacing(args: { rows: readonly RenderRow[] index: number @@ -67,6 +33,7 @@ export function estimateRenderRowSize( if (row?.type === 'host-header') { return ( HOST_HEADER_ROW_HEIGHT + + 6 + (shouldUseHeaderTopSpacing({ rows, index, @@ -79,6 +46,7 @@ export function estimateRenderRowSize( if (row?.type === 'header') { return ( GROUP_HEADER_ROW_HEIGHT + + 6 + (shouldUseHeaderTopSpacing({ rows, index, @@ -88,16 +56,11 @@ export function estimateRenderRowSize( : 0) ) } - if (row?.type === 'lineage-group') { - return row.folder - ? FOLDER_WORKSPACE_ROW_HEIGHT + row.rows.length * 96 - : 100 + Math.max(0, row.rows.length - 1) * 96 - } if (row?.type === 'imported-worktrees-card' || row?.type === 'new-external-worktrees-inbox') { - return IMPORTED_WORKTREES_LINE_ROW_HEIGHT + return IMPORTED_WORKTREES_LINE_ROW_HEIGHT + 6 } if (row?.type === 'pending-creation') { - return PENDING_CREATION_ROW_HEIGHT + return PENDING_CREATION_ROW_HEIGHT + 6 } if (row?.type === 'folder-workspace') { return FOLDER_WORKSPACE_ROW_HEIGHT diff --git a/src/renderer/src/hooks/requestVirtualizedScrollAnchorRecord.ts b/src/renderer/src/hooks/requestVirtualizedScrollAnchorRecord.ts index c6f6df07e5f..c697ee2bd0b 100644 --- a/src/renderer/src/hooks/requestVirtualizedScrollAnchorRecord.ts +++ b/src/renderer/src/hooks/requestVirtualizedScrollAnchorRecord.ts @@ -1,11 +1,32 @@ import { VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT } from './useVirtualizedScrollAnchor' /** Snapshot a mounted scroller’s live top-row anchor in the same tick as external row mutation, avoiding stale click-time anchors. */ -export function requestVirtualizedScrollAnchorRecord(scrollElementSelector: string): void { +export function requestVirtualizedScrollAnchorRecord( + scrollElement: string | Element | null, + options?: { deferDomMeasurement: boolean } +): void { if (typeof document === 'undefined') { return } - document - .querySelector(scrollElementSelector) - ?.dispatchEvent(new Event(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT)) + const element = + typeof scrollElement === 'string' ? document.querySelector(scrollElement) : scrollElement + element?.dispatchEvent( + options?.deferDomMeasurement + ? new CustomEvent(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT, { + detail: { deferDomMeasurement: true } + }) + : new Event(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT) + ) +} + +/** Explicit navigation replaces a pending saved/structural target, even when its scroll is a no-op. */ +export function supersedeVirtualizedScrollAnchorRestore( + scrollElement: Element | null, + targetOffset?: number +): void { + scrollElement?.dispatchEvent( + new CustomEvent(VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT, { + detail: { cancelRestore: true, targetOffset } + }) + ) } diff --git a/src/renderer/src/hooks/useVirtualizedScrollAnchor.ts b/src/renderer/src/hooks/useVirtualizedScrollAnchor.ts index 9015bfeda54..4ec0b62bbe1 100644 --- a/src/renderer/src/hooks/useVirtualizedScrollAnchor.ts +++ b/src/renderer/src/hooks/useVirtualizedScrollAnchor.ts @@ -213,9 +213,25 @@ export function useVirtualizedScrollAnchor< targetOffset: scrollOffsetRef.current, scrollOffsetRef }) - const recordRequestedAnchor = (): void => { + const recordRequestedAnchor = (event: Event): void => { cancelMountRestore() pendingRestoreRef.current = false + cancelScheduledRecord() + if (event instanceof CustomEvent && event.detail?.cancelRestore === true) { + anchorRef.current = null + scrollOffsetRef.current = el.scrollTop + const targetOffset: unknown = event.detail.targetOffset + if (typeof targetOffset === 'number' && targetOffset !== el.scrollTop) { + programmaticScrollMarksRef.current?.mark(targetOffset) + } + return + } + if (event instanceof CustomEvent && event.detail?.deferDomMeasurement === true) { + scrollOffsetRef.current = el.scrollTop + recordVirtualScrollAnchorRef.current(el.scrollTop) + scheduleRecordAnchor() + return + } recordCurrentAnchor() } From 96d2c0b0b6b5943a19096fb5a0653b6310d3cdfd Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:23:01 +0000 Subject: [PATCH 07/17] fix(opencode): attach @-mentioned files to OpenCode chat prompts (#41932) * fix(opencode): attach @-mentioned files to OpenCode chat prompts OpenCode's ACP agent reads a file only from a resource_link block and ignores @path text, so mentioned files never reached the model. Keep the text as typed and link each mentioned file inside the session folder. * fix(opencode): reuse the chat mention scanner and compare paths byte-exactly * fix(opencode): leave mentioned files over 20 MiB as text --- src/main/acp/acp-dialects/acp-dialect.ts | 2 + src/main/acp/acp-dialects/opencode-dialect.ts | 1 + .../acp/session/acp-structured-acquire.ts | 1 + .../acp-structured-session-contract.ts | 2 + .../session/children/acp-structured-child.ts | 1 + src/main/acp/turns/acp-file-mention-links.ts | 66 +++++++++++++++++++ src/main/acp/turns/acp-prompt-content.test.ts | 34 +++++++++- src/main/acp/turns/acp-prompt-content.ts | 28 ++++++-- 8 files changed, 127 insertions(+), 8 deletions(-) create mode 100644 src/main/acp/turns/acp-file-mention-links.ts diff --git a/src/main/acp/acp-dialects/acp-dialect.ts b/src/main/acp/acp-dialects/acp-dialect.ts index 25412f7547c..e283e6a7188 100644 --- a/src/main/acp/acp-dialects/acp-dialect.ts +++ b/src/main/acp/acp-dialects/acp-dialect.ts @@ -185,6 +185,8 @@ export type AcpDialect = { text(value: string): string reply(text: string): AcpModelCommandReply } + /** The agent reads a mentioned file only from a resource link, not from `@path` text. */ + linksFileMentions?: true /** Hide these commands and reject command-only prompts before dispatch. */ withheldCommands?: readonly string[] /** Which sign-in a not-signed-in chat needs; absent is the agent's usual one. */ diff --git a/src/main/acp/acp-dialects/opencode-dialect.ts b/src/main/acp/acp-dialects/opencode-dialect.ts index 4b0ad20e23d..d177f690405 100644 --- a/src/main/acp/acp-dialects/opencode-dialect.ts +++ b/src/main/acp/acp-dialects/opencode-dialect.ts @@ -111,6 +111,7 @@ export const OPENCODE_ACP_DIALECT: AcpDialect = { supported: (initialized) => initialized.agentCapabilities?.sessionCapabilities?.close != null }, effortChangesModel: true, + linksFileMentions: true, normalizeToolUpdate, notification: openCodeChildUpdate, promptFailure diff --git a/src/main/acp/session/acp-structured-acquire.ts b/src/main/acp/session/acp-structured-acquire.ts index 4fecd8a131d..c69ac58a884 100644 --- a/src/main/acp/session/acp-structured-acquire.ts +++ b/src/main/acp/session/acp-structured-acquire.ts @@ -256,6 +256,7 @@ export async function acquireAcpStructuredSession(input: { fence: acquire.fence, acquisitionGeneration: generation, spec, + cwd: launch.cwd, permissionModes, connection, lane: null, diff --git a/src/main/acp/session/acp-structured-session-contract.ts b/src/main/acp/session/acp-structured-session-contract.ts index 5af81feb4e2..cad258b796d 100644 --- a/src/main/acp/session/acp-structured-session-contract.ts +++ b/src/main/acp/session/acp-structured-session-contract.ts @@ -15,6 +15,8 @@ export type AcpStructuredSession = { fence: number acquisitionGeneration: string spec: AcpLaunchSpec + /** The session's folder on the agent's host. */ + cwd: string /** Session modes this launch reports as Orca's permission modes. */ permissionModes: Readonly>> | undefined childStops?: AcpChildStops diff --git a/src/main/acp/session/children/acp-structured-child.ts b/src/main/acp/session/children/acp-structured-child.ts index 0f26e9ba4b2..7f340c68c97 100644 --- a/src/main/acp/session/children/acp-structured-child.ts +++ b/src/main/acp/session/children/acp-structured-child.ts @@ -12,6 +12,7 @@ export type AcpStructuredChild = Pick< | 'fence' | 'acquisitionGeneration' | 'spec' + | 'cwd' | 'permissionModes' | 'connection' | 'closeRequested' diff --git a/src/main/acp/turns/acp-file-mention-links.ts b/src/main/acp/turns/acp-file-mention-links.ts new file mode 100644 index 00000000000..eaad4abf79f --- /dev/null +++ b/src/main/acp/turns/acp-file-mention-links.ts @@ -0,0 +1,66 @@ +import { realpath, stat } from 'node:fs/promises' +import { isAbsolute, relative, resolve, sep } from 'node:path' +import { pathToFileURL } from 'node:url' +import { nativeChatTextAttachmentParts } from '../../../shared/native-chat-text-attachment-references' +import type { ContentBlock } from '../generated/acp-protocol.generated' + +const TRAILING_PUNCTUATION = /[.,;:!?)\]}`"'*]+$/ + +/** The real path of a file inside `realRoot`; symlinks and `..` cannot leave it. */ +async function fileInside( + realRoot: string, + path: string, + maxBytes: number +): Promise { + const target = await realpath(resolve(realRoot, path)).catch(() => null) + // Byte-exact: Unicode or case folding would admit a sibling folder on Linux. + const inside = target ? relative(realRoot, target) : '' + if ( + !target || + !inside || + inside === '..' || + inside.startsWith(`..${sep}`) || + isAbsolute(inside) + ) { + return null + } + return (await stat(target).then( + (info) => info.isFile() && info.size <= maxBytes, + () => false + )) + ? target + : null +} + +/** One link per `@path` naming a file inside `root`; larger files stay text for the agent's own tools. */ +export async function acpFileMentionLinks( + texts: readonly string[], + root: string, + maxBytes: number +): Promise { + const paths = new Set( + texts.flatMap((text) => + nativeChatTextAttachmentParts(text, true, () => true).flatMap((part) => + part.path ? [part.path] : [] + ) + ) + ) + const realRoot = paths.size > 0 ? await realpath(root).catch(() => null) : null + if (!realRoot) { + return [] + } + const links = new Map() + for (const path of paths) { + // Punctuation after a mention belongs to the sentence unless the name itself exists. + const trimmed = path.replace(TRAILING_PUNCTUATION, '') + const literal = await fileInside(realRoot, path, maxBytes) + const name = literal ? path : trimmed + const target = + literal ?? + (trimmed && trimmed !== path ? await fileInside(realRoot, trimmed, maxBytes) : null) + if (target && !links.has(target)) { + links.set(target, { type: 'resource_link', uri: pathToFileURL(target).href, name }) + } + } + return [...links.values()] +} diff --git a/src/main/acp/turns/acp-prompt-content.test.ts b/src/main/acp/turns/acp-prompt-content.test.ts index 1d48824649f..b948f0de45f 100644 --- a/src/main/acp/turns/acp-prompt-content.test.ts +++ b/src/main/acp/turns/acp-prompt-content.test.ts @@ -1,6 +1,7 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { pathToFileURL } from 'node:url' import { afterAll, describe, expect, it } from 'vitest' import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types' @@ -64,4 +65,35 @@ describe('ACP prompt content', () => { attachment: { reason: 'totalTooLarge' } }) }) + + it('links mentioned files inside the session folder and keeps the text as typed', async () => { + const root = join(dir, 'project') + mkdirSync(join(root, 'my dir'), { recursive: true }) + writeFileSync(join(root, 'a.txt'), 'a') + writeFileSync(join(root, 'my dir', 'b.txt'), 'b') + writeFileSync(join(root, "it's.txt"), 'c') + writeFileSync(join(root, 'report!'), 'd') + writeFileSync(join(root, 'report'), 'e') + // OpenCode 2 fails the whole turn for a linked file over 20 MiB. + writeFileSync(join(root, 'big.log'), Buffer.alloc(20 * 1024 * 1024 + 1)) + mkdirSync(join(dir, 'outside')) + writeFileSync(join(dir, 'outside', 'c.txt'), 'secret') + // A junction needs no privilege on Windows. + symlinkSync(join(dir, 'outside'), join(root, 'escape'), 'junction') + const text = + 'Read @a.txt. and @"my dir/b.txt" @it\'s.txt, see:@report! not @../outside/c.txt @escape/c.txt @missing.txt @big.log' + const real = realpathSync(root) + + expect(await acpPromptBlocks(message({ type: 'text', text }), true, root)).toEqual([ + { type: 'text', text }, + { type: 'resource_link', uri: pathToFileURL(join(real, 'a.txt')).href, name: 'a.txt' }, + { + type: 'resource_link', + uri: pathToFileURL(join(real, 'my dir', 'b.txt')).href, + name: 'my dir/b.txt' + }, + { type: 'resource_link', uri: pathToFileURL(join(real, "it's.txt")).href, name: "it's.txt" }, + { type: 'resource_link', uri: pathToFileURL(join(real, 'report!')).href, name: 'report!' } + ]) + }) }) diff --git a/src/main/acp/turns/acp-prompt-content.ts b/src/main/acp/turns/acp-prompt-content.ts index 81a2db01b67..069a223f48d 100644 --- a/src/main/acp/turns/acp-prompt-content.ts +++ b/src/main/acp/turns/acp-prompt-content.ts @@ -26,13 +26,14 @@ import { acpAgentName } from '../session/acp-structured-agent-definitions' import type { AcpStructuredConnection } from '../process/acp-structured-connection' import { acpSessionAcceptsImages } from '../protocol/acp-image-capability' import type { ContentBlock } from '../generated/acp-protocol.generated' +import { acpFileMentionLinks } from './acp-file-mention-links' // Reserve space for the JSON-RPC envelope around the prompt blocks. const ACP_PROMPT_LINE_BUDGET = ACP_MAX_LINE_BYTES - 64 * 1024 // Budget raw images for base64's 4:3 expansion and leave room for text. const ACP_PROMPT_TOTAL_IMAGE_MAX_BYTES = Math.floor((ACP_PROMPT_LINE_BUDGET * 3) / 4) - 1024 * 1024 -// OpenCode 2 fails the turn for any attachment over 20 MiB. -const ACP_PROMPT_PER_IMAGE_MAX_BYTES = 20 * 1024 * 1024 +// OpenCode 2 fails the turn for any image or linked file over 20 MiB. +const ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES = 20 * 1024 * 1024 const MAX_IMAGE_COUNT = 20 const READ_TIMEOUT_MS = 15_000 @@ -74,8 +75,8 @@ async function imageBlock( if (bytes === 0) { throw attachmentProblem({ reason: 'empty' }) } - if (bytes > ACP_PROMPT_PER_IMAGE_MAX_BYTES) { - throw attachmentProblem({ reason: 'tooLarge', limit: ACP_PROMPT_PER_IMAGE_MAX_BYTES }) + if (bytes > ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES) { + throw attachmentProblem({ reason: 'tooLarge', limit: ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES }) } if (bytes > remainingBytes) { throw attachmentProblem({ reason: 'totalTooLarge', limit: ACP_PROMPT_TOTAL_IMAGE_MAX_BYTES }) @@ -91,7 +92,7 @@ async function imageBlock( block: { type: 'text' as const, text: formatNativeChatFileReference(path) }, bytes: 0 } - const maxBytes = Math.min(remainingBytes, ACP_PROMPT_PER_IMAGE_MAX_BYTES) + const maxBytes = Math.min(remainingBytes, ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES) if (!mimeType || maxBytes <= 0) { return fallback } @@ -119,9 +120,11 @@ async function imageBlock( return { block: { type: 'image', mimeType, data: data.toString('base64') }, bytes: data.length } } +/** `mentionRoot` links each `@path` there, for agents that read only linked files. */ export async function acpPromptBlocks( body: AgentJournalMessageItem, - acceptsImages: boolean + acceptsImages: boolean, + mentionRoot?: string ): Promise { // Reserve later text and file references before allocating image capacity. const blocks: ContentBlock[] = body.blocks.map((block) => { @@ -131,6 +134,12 @@ export async function acpPromptBlocks( const path = block.type === 'image-ref' ? hostImagePath(block) : null return { type: 'text', text: path ? formatNativeChatFileReference(path) : '' } }) + if (mentionRoot !== undefined) { + const texts = body.blocks.flatMap((block) => (block.type === 'text' ? [block.text] : [])) + blocks.push( + ...(await acpFileMentionLinks(texts, mentionRoot, ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES)) + ) + } const blockBytes = (block: ContentBlock): number => Buffer.byteLength(JSON.stringify(block)) let encodedBytes = 2 + Math.max(0, blocks.length - 1) + blocks.reduce((n, b) => n + blockBytes(b), 0) @@ -194,6 +203,7 @@ export async function acpDispatchPrompt( session: { spec: Pick connection: Pick + cwd: string } ): Promise { if (isWithheldCommand(body, session.spec.dialect.withheldCommands ?? [])) { @@ -203,7 +213,11 @@ export async function acpDispatchPrompt( }) } try { - return await acpPromptBlocks(body, await acpSessionAcceptsImages(session)) + return await acpPromptBlocks( + body, + await acpSessionAcceptsImages(session), + session.spec.dialect.linksFileMentions ? session.cwd : undefined + ) } catch (error) { if (error instanceof AcpPromptContentError) { return agentSessionFailureWords(error.failure, { From e4eecd847c598a887dfdc8885a2fd896dabbfafa Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 13 Nov 2026 01:31:41 -0800 Subject: [PATCH 08/17] test: remove low-value workspace wrapper and notice cases (#41938) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../scripts/ci/sharding/ci-shard-timings.json | 3 - .../appearance/notice-surface-tokens.test.ts | 47 +------ .../setup/FullDiskAccessSetupPrompt.test.ts | 1 - .../NewWorkspaceComposerNameSection.test.tsx | 104 --------------- .../ProjectCombobox.dialog-handoff.test.tsx | 120 ------------------ .../setup/DirectWorkItemSetupDialog.test.tsx | 36 ------ ...smart-workspace-field-availability.test.ts | 47 ------- 7 files changed, 1 insertion(+), 357 deletions(-) delete mode 100644 src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.test.tsx delete mode 100644 src/renderer/src/components/new-workspace/project-selection/ProjectCombobox.dialog-handoff.test.tsx delete mode 100644 src/renderer/src/components/new-workspace/setup/DirectWorkItemSetupDialog.test.tsx delete mode 100644 src/renderer/src/components/new-workspace/source-search/use-smart-workspace-field-availability.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 6e57540494d..a2b1f69743b 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -4755,9 +4755,6 @@ "src/renderer/src/components/native-chat/pane/actions/use-structured-native-chat-submit-reveal.test.ts": 2304, "src/renderer/src/components/network/CustomAddressDialog.test.tsx": 568, "src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.test.tsx": 870, - "src/renderer/src/components/new-workspace/setup/DirectWorkItemSetupDialog.test.tsx": 5296, - "src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.test.tsx": 2493, - "src/renderer/src/components/new-workspace/project-selection/ProjectCombobox.dialog-handoff.test.tsx": 1043, "src/renderer/src/components/new-workspace/RunTargetCombobox.host-identity.test.tsx": 856, "src/renderer/src/components/new-workspace/SetProjectLocationDialog.host-identity.test.tsx": 1094, "src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.test.tsx": 1387, diff --git a/src/renderer/src/app-shell/appearance/notice-surface-tokens.test.ts b/src/renderer/src/app-shell/appearance/notice-surface-tokens.test.ts index 79a1923a60c..e9c4e7936e4 100644 --- a/src/renderer/src/app-shell/appearance/notice-surface-tokens.test.ts +++ b/src/renderer/src/app-shell/appearance/notice-surface-tokens.test.ts @@ -1,8 +1,6 @@ -import { readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' -import { hexToRgb, rgbaToHex, type Rgba } from '../../../../shared/color/rgba-contrast' +import { hexToRgb, type Rgba } from '../../../../shared/color/rgba-contrast' import { noticeSurfaceTokens } from './notice-surface-tokens' -import { safePluginThemeTokens } from './plugin-theme-tokens' const DARK_BUILT_INS = { '--foreground': '#f0f0f0', @@ -71,16 +69,6 @@ function expectReadable(themeTokens: Record): void { } describe('noticeSurfaceTokens', () => { - it("paints Orca's dark notice colors for the built-in palette", () => { - expect(noticeSurfaceTokens({}, 'dark', DARK_BUILT_INS, probe)).toEqual({ - '--notice-surface': '#262626', - '--notice-secondary': '#3a3a3a', - '--notice-secondary-edge': 'transparent', - '--notice-muted': '#3a3a3a', - '--notice-muted-foreground': '#acacac' - }) - }) - // Popovers the theme validator accepts that once painted notice text under 4.5:1: #5a5a5a // through Chromium's color-mix rounding and an over-lifted 80% description, #383838 through hex // rounding, white-on-dark-base through dark muted panels, the rest unlifted. @@ -94,18 +82,6 @@ describe('noticeSurfaceTokens', () => { expectReadable(themeTokens) }) - it('keeps notice text 4.5:1 for every gray popover the validator accepts', () => { - const accepted = Array.from({ length: 256 }, (_, gray) => ({ - '--popover': rgbaToHex([gray, gray, gray, 1]) - })).filter( - (tokens) => safePluginThemeTokens(tokens, 'dark', DARK_BUILT_INS, probe)['--popover'] - ) - expect(accepted.length).toBeGreaterThan(50) - for (const tokens of accepted) { - expectReadable(tokens) - } - }) - it('outlines secondary buttons only when their fill is gone', () => { const tokensFor = (popoverForeground: string): Record => noticeSurfaceTokens( @@ -121,25 +97,4 @@ describe('noticeSurfaceTokens', () => { expect(filled['--notice-secondary']).not.toBe(filled['--notice-surface']) expect(filled['--notice-secondary-edge']).toBe('transparent') }) - - it('remaps the surface paired with every foreground the notice scope remaps', () => { - const css = readFileSync(new URL('../../assets/main.css', import.meta.url), 'utf8') - const scope = css.match( - /\[data-sonner-toaster\],\s*\.notification-card-stack\s*\{([^}]*)\}/ - )?.[1] - expect(scope).toBeDefined() - const remapped = new Set([...(scope ?? '').matchAll(/(--[\w-]+):/g)].map(([, name]) => name)) - // Why: a foreground remapped onto the popover's polarity over an unremapped surface (outline - // buttons: text-foreground on bg-background) paints light-on-light or dark-on-dark. - const pairs = [ - ['--foreground', '--background'], - ['--card-foreground', '--card'], - ['--secondary-foreground', '--secondary'], - ['--muted-foreground', '--muted'] - ] - for (const [foreground, surface] of pairs) { - expect(remapped.has(foreground), foreground).toBe(true) - expect(remapped.has(surface), `${surface} pairs with ${foreground}`).toBe(true) - } - }) }) diff --git a/src/renderer/src/components/feature-wall/setup/FullDiskAccessSetupPrompt.test.ts b/src/renderer/src/components/feature-wall/setup/FullDiskAccessSetupPrompt.test.ts index cf98f6efee3..6c6b954d0f1 100644 --- a/src/renderer/src/components/feature-wall/setup/FullDiskAccessSetupPrompt.test.ts +++ b/src/renderer/src/components/feature-wall/setup/FullDiskAccessSetupPrompt.test.ts @@ -107,7 +107,6 @@ describe('FullDiskAccessSetupPrompt state helpers', () => { expect(container.textContent).not.toContain('Full Disk Access') expect(getStatus).not.toHaveBeenCalled() - expect(window.api.developerPermissions.request).not.toHaveBeenCalled() root.unmount() }) }) diff --git a/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.test.tsx b/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.test.tsx deleted file mode 100644 index c410c3ca40a..00000000000 --- a/src/renderer/src/components/new-workspace/composer/NewWorkspaceComposerNameSection.test.tsx +++ /dev/null @@ -1,104 +0,0 @@ -// @vitest-environment happy-dom - -import React from 'react' -import { cleanup, render, screen, waitFor } from '@testing-library/react' -import userEvent from '@testing-library/user-event' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { NewWorkspaceComposerNameSection } from './NewWorkspaceComposerNameSection' - -vi.mock('@/components/new-workspace/SmartWorkspaceNameField', () => ({ - default: ({ value, selectedSource }: { value: string; selectedSource?: { label: string } }) => ( -
- {selectedSource?.label} - -
- ) -})) - -function branchProps(): React.ComponentProps { - return { - eligibleRepos: [], - repoId: 'repo', - onRepoChange: vi.fn(), - name: 'Payments review', - onNameValueChange: vi.fn(), - onSmartGitHubItemSelect: vi.fn(), - onSmartGitLabItemSelect: vi.fn(), - onSmartBranchSelect: vi.fn(), - onSmartLinearIssueSelect: vi.fn(), - smartNameSelection: { kind: 'branch', label: 'origin/feature/payments' }, - onClearSmartNameSelection: vi.fn(), - selectedRepoRequiresConnection: false, - selectedRepoIsGit: true, - branchesEnabled: true, - forkPushWarning: null, - canReuseSelectedBranch: true, - reuseEligibleBranch: 'feature/payments', - branchNameOverride: undefined, - onBranchNameOverrideChange: vi.fn(), - reuseSelectedBranch: true, - onReuseSelectedBranchChange: vi.fn(), - baseBranch: 'refs/remotes/origin/feature/payments', - onNamePlainEnter: vi.fn() - } -} - -afterEach(cleanup) - -describe('NewWorkspaceComposerNameSection branch reuse', () => { - it('chooses a new branch by pointer and the existing branch by keyboard without changing the source', async () => { - const user = userEvent.setup() - const props = branchProps() - const { rerender } = render() - - expect(screen.getByText('origin/feature/payments')).toBeTruthy() - expect(screen.getByText('feature/payments')).toBeTruthy() - expect(screen.queryByRole('textbox', { name: 'New branch name' })).toBeNull() - expect( - screen.getByRole('radio', { name: 'Existing branch' }).getAttribute('aria-checked') - ).toBe('true') - await user.click(screen.getByRole('radio', { name: 'New branch' })) - expect(props.onReuseSelectedBranchChange).toHaveBeenLastCalledWith(false) - - rerender() - expect( - screen.getByRole('radio', { name: 'Existing branch' }).getAttribute('aria-checked') - ).toBe('false') - expect(document.activeElement).toBe(screen.getByRole('textbox', { name: 'New branch name' })) - await user.paste('review/payments') - expect(props.onBranchNameOverrideChange).toHaveBeenLastCalledWith('review/payments') - await user.click(screen.getByRole('radio', { name: 'New branch' })) - expect(document.activeElement).toBe(screen.getByRole('textbox', { name: 'New branch name' })) - screen.getByRole('radio', { name: 'New branch' }).focus() - await user.keyboard('{ArrowUp>}') - await waitFor(() => expect(props.onReuseSelectedBranchChange).toHaveBeenLastCalledWith(true)) - await user.keyboard('{/ArrowUp}') - expect(props.onNameValueChange).not.toHaveBeenCalled() - expect(props.onClearSmartNameSelection).not.toHaveBeenCalled() - }) - - it('opens the existing workspace with the keyboard without submitting or changing branch intent', async () => { - const user = userEvent.setup() - const props = branchProps() - const openWorkspace = vi.fn() - const submit = vi.fn((event: React.FormEvent) => event.preventDefault()) - render( -
- - - ) - - const openButton = screen.getByRole('button', { name: 'Open existing workspace' }) - await user.tab() - await user.tab() - await user.tab() - expect(document.activeElement).toBe(openButton) - await user.keyboard('{Enter}') - - expect(openWorkspace).toHaveBeenCalledOnce() - expect(submit).not.toHaveBeenCalled() - expect(props.onReuseSelectedBranchChange).not.toHaveBeenCalled() - expect(props.onNameValueChange).not.toHaveBeenCalled() - expect(props.onClearSmartNameSelection).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/new-workspace/project-selection/ProjectCombobox.dialog-handoff.test.tsx b/src/renderer/src/components/new-workspace/project-selection/ProjectCombobox.dialog-handoff.test.tsx deleted file mode 100644 index c5238a5c8c7..00000000000 --- a/src/renderer/src/components/new-workspace/project-selection/ProjectCombobox.dialog-handoff.test.tsx +++ /dev/null @@ -1,120 +0,0 @@ -// @vitest-environment happy-dom - -import React, { act, Suspense, useEffect, useRef, useState } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog' -import ProjectCombobox from './ProjectCombobox' -import { TooltipProvider } from '@/components/ui/tooltip' - -vi.mock('./use-recent-project-ids', () => ({ useRecentProjectIds: () => [] })) - -// Mirrors a lazily loaded creation dialog that focuses its primary action from a mount effect. -let resolveLateDialog: () => void = () => {} -const LateAddDialogBody = React.lazy( - () => - new Promise<{ default: () => React.JSX.Element }>((resolve) => { - resolveLateDialog = () => - resolve({ - default: function Body(): React.JSX.Element { - const browseRef = useRef(null) - useEffect(() => browseRef.current?.focus(), []) - return - } - }) - }) -) - -function LateDialogComposer(): React.JSX.Element { - const [adding, setAdding] = useState(false) - return ( - - - New workspace - setAdding(true)} - /> - {adding ? ( - - - - Add a project - - - - - ) : null} - - - ) -} - -let container: HTMLDivElement -let root: Root - -beforeEach(() => { - // Radix Presence retains closing content when the production exit animation runs. - const getStyle = window.getComputedStyle.bind(window) - vi.spyOn(window, 'getComputedStyle').mockImplementation((element, ...args) => { - const style = getStyle(element, ...args) - if (element.getAttribute('data-slot') === 'popover-content') { - return new Proxy(style, { - get: (target, property) => - property === 'animationName' - ? element.getAttribute('data-state') === 'closed' - ? 'exit' - : 'enter' - : // oxlint-disable-next-line anti-slop/no-reflect-get -- Proxy `get` trap: raw string|symbol pass-through; the receiver stays the target on purpose. - Reflect.get(target, property) - }) - } - return style - }) - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) -}) - -afterEach(async () => { - await act(async () => root.unmount()) - container.remove() - vi.restoreAllMocks() -}) - -function projectField(): HTMLInputElement { - return document.querySelector('[role="combobox"][aria-label="Project"]')! -} - -function addOption(): HTMLElement { - return Array.from(document.querySelectorAll('[role="option"]')).find((option) => - option.textContent?.includes('Add project') - )! -} - -it('keeps the selector closed when a late creation dialog focuses before its trap mounts', async () => { - await act(async () => - root.render( - - - - ) - ) - // Dialog autofocus lands on the field, so the composer trap records it as last focused. - expect(document.activeElement).toBe(projectField()) - expect(document.querySelector('[role="listbox"]')).not.toBeNull() - - await act(async () => { - addOption().dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true })) - addOption().click() - }) - expect(document.querySelector('[role="listbox"]')).toBeNull() - // Let the closed selector release its focus scope before the lazy dialog arrives. - await act(async () => new Promise((resolve) => setTimeout(resolve, 0))) - await act(async () => resolveLateDialog()) - - expect(document.querySelector('[role="listbox"]')).toBeNull() - expect(projectField().getAttribute('aria-expanded')).toBe('false') -}) diff --git a/src/renderer/src/components/new-workspace/setup/DirectWorkItemSetupDialog.test.tsx b/src/renderer/src/components/new-workspace/setup/DirectWorkItemSetupDialog.test.tsx deleted file mode 100644 index 074fd0e043b..00000000000 --- a/src/renderer/src/components/new-workspace/setup/DirectWorkItemSetupDialog.test.tsx +++ /dev/null @@ -1,36 +0,0 @@ -// @vitest-environment happy-dom -import { readDirectSetupRequest } from '@/lib/workspace/creation/work-item/direct-work-item-setup-test-fixture' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, expect, it } from 'vitest' -import { i18n } from '@/i18n/i18n' -import { useAppStore } from '@/store' -import { - requestDirectWorkItemSetup, - type DirectWorkItemSetupRequest -} from '@/lib/workspace/creation/work-item/direct-work-item-setup' -import { DirectWorkItemSetupDialog } from './DirectWorkItemSetupDialog' -import type { WorkspaceSetupInspection as DirectSetupInspection } from '@/lib/workspace/creation/setup/workspace-setup-preparation' - -const initial = useAppStore.getState() -afterEach(async () => { - cleanup() - await i18n.changeLanguage('en') - useAppStore.getState().closeModal() - useAppStore.setState(initial, true) -}) -function request(): DirectWorkItemSetupRequest { - return readDirectSetupRequest(useAppStore.getState().modalData.directSetup) -} - -it('ignores recovery after cancellation without closing the replacement modal', async () => { - const retry = Promise.withResolvers() - const result = requestDirectWorkItemSetup('Repo', { kind: 'unavailable' }, () => retry.promise) - const old = request() - render() - fireEvent.click(screen.getByRole('button', { name: 'Retry' })) - useAppStore.getState().openModal('quick-open', { section: 'appearance' }) - await expect(result).resolves.toBe('cancelled') - await act(async () => retry.resolve({ kind: 'decided', decision: 'run' })) - expect(old.isPending()).toBe(false) - expect(useAppStore.getState().modalData).toEqual({ section: 'appearance' }) -}) diff --git a/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-field-availability.test.ts b/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-field-availability.test.ts deleted file mode 100644 index cf54f8a7fd5..00000000000 --- a/src/renderer/src/components/new-workspace/source-search/use-smart-workspace-field-availability.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { resolveLocalGitlabAvailable } from './use-smart-workspace-field-availability' - -describe('resolveLocalGitlabAvailable', () => { - const lastKnown = new Map([['host', true]]) - - it('uses the current preflight answer when it is for this context', () => { - expect( - resolveLocalGitlabAvailable({ - preflightStatusCurrent: true, - glabInstalled: false, - contextKey: 'host', - lastKnown - }) - ).toBe(false) - expect( - resolveLocalGitlabAvailable({ - preflightStatusCurrent: true, - glabInstalled: true, - contextKey: 'wsl:Ubuntu', - lastKnown - }) - ).toBe(true) - }) - - it('keeps the last known answer while this context is being re-checked', () => { - expect( - resolveLocalGitlabAvailable({ - preflightStatusCurrent: false, - glabInstalled: undefined, - contextKey: 'host', - lastKnown - }) - ).toBe(true) - }) - - it('stays hidden for a context that was never checked', () => { - expect( - resolveLocalGitlabAvailable({ - preflightStatusCurrent: false, - glabInstalled: undefined, - contextKey: 'wsl:Debian', - lastKnown - }) - ).toBe(false) - }) -}) From 616a5815751f33a5ca849d3ea5360fcd07f76288 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 13 Nov 2026 01:32:11 -0800 Subject: [PATCH 09/17] feat(usage): add a Claude usage polling switch (#41921) Add an on-by-default Claude usage polling switch with live-terminal-only behavior when disabled, cancellation and account attribution safeguards, and translations for all supported locales. Fixes #27151. Fixes #39502. Fixes #37037. Co-authored-by: Sibyl --- .../content/docs/agents/usage-tracking.mdx | 10 +- .../accounts/provider-account-services.ts | 13 ++ .../providers/claude/claude-usage-result.ts | 8 + .../rate-limits/service/rate-limit-service.ts | 26 +++ .../service/service-account-refresh.ts | 7 + .../service/service-fetch-policy.ts | 53 ++++- .../service/service-full-cycle-preparation.ts | 8 +- .../service/service-inactive-accounts.ts | 5 +- .../rate-limits/service/service-polling.ts | 1 + .../service/service-provider-cycles.ts | 9 +- .../service-refresh-orchestration.test.ts | 211 ++++++++++++++++++ src/main/rate-limits/service/service-state.ts | 10 +- src/main/rate-limits/service/service-types.ts | 1 + .../claude/accounts-pane-claude-section.tsx | 9 + .../claude-oauth-usage-setting.fixture.tsx | 42 ++++ .../claude/claude-oauth-usage-setting.tsx | 67 ++++++ src/renderer/src/i18n/locales/de.json | 5 + src/renderer/src/i18n/locales/en.json | 5 + src/renderer/src/i18n/locales/es.json | 5 + src/renderer/src/i18n/locales/fr.json | 5 + src/renderer/src/i18n/locales/ja.json | 5 + src/renderer/src/i18n/locales/ko.json | 5 + src/renderer/src/i18n/locales/pt.json | 5 + src/renderer/src/i18n/locales/ru.json | 7 +- src/renderer/src/i18n/locales/tr.json | 5 + src/renderer/src/i18n/locales/zh-Hant.json | 5 + src/renderer/src/i18n/locales/zh.json | 5 + src/shared/default-global-settings.ts | 1 + src/shared/global-settings-types.ts | 2 + 29 files changed, 530 insertions(+), 10 deletions(-) create mode 100644 src/renderer/src/components/settings/accounts/claude/claude-oauth-usage-setting.fixture.tsx create mode 100644 src/renderer/src/components/settings/accounts/claude/claude-oauth-usage-setting.tsx diff --git a/docs/site/content/docs/agents/usage-tracking.mdx b/docs/site/content/docs/agents/usage-tracking.mdx index f0d9b95daf2..6c1893bfd0e 100644 --- a/docs/site/content/docs/agents/usage-tracking.mdx +++ b/docs/site/content/docs/agents/usage-tracking.mdx @@ -14,7 +14,15 @@ Orca fetches usage for Claude Code, Codex, Gemini, OpenCode Go, Kimi Code, MiniM Orca asks each provider for your usage over the network, using the login that agent already has or a key or session cookie you add in Orca Settings. -For Claude, Orca requests `https://api.anthropic.com/api/oauth/usage` with the token from your existing Claude Code login; it does not ask for extra credentials. Triggers include: +### Claude usage polling + +**Settings → Accounts → Claude → Claude usage polling** is on by default. Turn it off to stop Orca's requests to `https://api.anthropic.com/api/oauth/usage`, including manual refreshes, account switching, inactive-account previews, and refreshes from mobile or web clients. Turning it off cancels pending usage requests and removes their cached figures while retaining live terminal readings. A request already sent cannot be recalled. + +With polling off, the meter uses Claude Code's [status-line data](https://code.claude.com/docs/en/statusline#rate-limit-usage): five-hour and weekly percentages and reset times. This requires a supported Claude Code version and Orca's status-line feed. Orca preserves a user-owned status line, so those sessions do not supply this feed. Without a reading, usage is unavailable until a terminal session reports it. Model-specific weekly windows, credits, and inactive-account readings require polling. + +The persisted setting is `claudeOAuthUsageEnabled: false` to disable polling. It applies on the host running the agents, including a headless Orca server; configure each host separately. Hiding the Claude status-bar item controls visibility independently. + +When polling is enabled, Orca uses the token from your existing Claude Code login. Triggers include: - Once the Orca window is active after startup, then about every 15 minutes while it stays visible and focused. - Bringing the window back to the front when the last check is more than 5 minutes old (sooner after a failed check). diff --git a/src/main/providers/accounts/provider-account-services.ts b/src/main/providers/accounts/provider-account-services.ts index a9cdb080fc9..65bcb2c0ca9 100644 --- a/src/main/providers/accounts/provider-account-services.ts +++ b/src/main/providers/accounts/provider-account-services.ts @@ -69,6 +69,18 @@ export function createProviderAccountServices( ) store.onSettingsChanged((updates, settings) => { void agentView.reconcile(settings) + if (updates.claudeOAuthUsageEnabled === false) { + rateLimits.discardClaudeOAuthUsage() + } else if (updates.claudeOAuthUsageEnabled === true) { + void rateLimits + .refreshClaudeForTarget(rateLimits.getState().claudeTarget) + .catch((error: unknown) => { + console.warn( + '[rate-limits] Failed to refresh Claude usage after enabling polling:', + error + ) + }) + } // Auto runtime selection remains live as provider settings change. void syncAccountRuntimeTargets(updates, settings).catch((error) => console.warn('[rate-limits] Failed to apply account runtime target:', error) @@ -137,6 +149,7 @@ export function createProviderAccountServices( apiKey: readZcodePlanApiKey() ?? '' })) rateLimits.setGeminiCliOAuthEnabledResolver(() => store.getSettings().geminiCliOAuthEnabled) + rateLimits.setClaudeOAuthUsageEnabledResolver(() => store.getSettings().claudeOAuthUsageEnabled) // Reuse the meter switch so hidden Antigravity usage does not spawn agy. rateLimits.setAntigravityUsageEnabledResolver(() => store.getUI().statusBarItems.includes('antigravity') diff --git a/src/main/rate-limits/providers/claude/claude-usage-result.ts b/src/main/rate-limits/providers/claude/claude-usage-result.ts index c729e503f78..06b33d52aa0 100644 --- a/src/main/rate-limits/providers/claude/claude-usage-result.ts +++ b/src/main/rate-limits/providers/claude/claude-usage-result.ts @@ -30,6 +30,14 @@ export function makeClaudeUsageResult( } } +// Not idle: the meter draws idle as pending, and nothing here will settle it. +export function claudeOAuthUsageDisabledResult(): ProviderRateLimits { + return makeClaudeUsageResult('unavailable', 'Usage appears when a Claude session runs.', { + failureKind: 'usage-unavailable', + attemptedSources: [] + }) +} + // Account rows explain host/profile failures; usage keeps its generic message. export function claudeUsageUnavailable(): ProviderRateLimits { return makeClaudeUsageResult('error', 'Claude usage is unavailable right now.', { diff --git a/src/main/rate-limits/service/rate-limit-service.ts b/src/main/rate-limits/service/rate-limit-service.ts index 9dcc556cc53..fd199a2bb73 100644 --- a/src/main/rate-limits/service/rate-limit-service.ts +++ b/src/main/rate-limits/service/rate-limit-service.ts @@ -19,6 +19,7 @@ import type { OpenCodeGoRateLimitConfig, MiniMaxRateLimitConfig, AntigravityUsageEnabledResolver, + ClaudeOAuthUsageEnabledResolver, MuseUsageEnabledResolver, ZcodePlanRateLimitConfig, GeminiCliOAuthEnabledResolver, @@ -73,6 +74,27 @@ export class RateLimitService extends RateLimitServiceAccountRefresh { this.geminiCliOAuthEnabledResolver = resolver } + setClaudeOAuthUsageEnabledResolver(resolver: ClaudeOAuthUsageEnabledResolver): void { + this.claudeOAuthUsageEnabledResolver = resolver + } + + // Retain only readings actually received from the terminal feed. + discardClaudeOAuthUsage(): void { + this.claudeUsageAbortController.abort() + this.claudeUsageAbortController = new AbortController() + this.claudeFetchGeneration += 1 + this.inactiveClaudeAccountsGeneration += 1 + this.inactiveClaudeCache.clear() + this.inactiveClaudeFetching.clear() + this.lastInactiveClaudeFetchAt = 0 + this.lastClaudeCheckCompletedAt = null + this.activeFailureStreakByProvider.claude = 0 + this.updateState({ ...this.state, claude: this.claudeUsageWithoutOAuth() }) + if (!this.lastClaudeAuthSnapshot) { + void this.fetchClaudeOnly({ force: true }) + } + } + setAntigravityUsageEnabledResolver(resolver: AntigravityUsageEnabledResolver): void { this.antigravityUsageEnabledResolver = resolver } @@ -162,6 +184,10 @@ export class RateLimitService extends RateLimitServiceAccountRefresh { void this.fetchAll() } else { this.scheduleDeferredStartupRefresh() + // Passive terminal usage needs account attribution even without a usage viewer. + if (!this.isClaudeOAuthUsageEnabled()) { + void this.fetchClaudeOnly({ force: true }) + } } this.startTimer() } diff --git a/src/main/rate-limits/service/service-account-refresh.ts b/src/main/rate-limits/service/service-account-refresh.ts index fdea05aff72..0cb65b2070f 100644 --- a/src/main/rate-limits/service/service-account-refresh.ts +++ b/src/main/rate-limits/service/service-account-refresh.ts @@ -57,6 +57,9 @@ export abstract class RateLimitServiceAccountRefresh extends RateLimitServiceIna provider: 'claude' | 'codex', options: { notWithinMs?: number } = {} ): boolean { + if (provider === 'claude' && !this.isClaudeOAuthUsageEnabled()) { + return false + } const limits = this.state[provider] const now = Date.now() if (this.isFetching || this.isRetryAfterActive(limits)) { @@ -230,6 +233,8 @@ export abstract class RateLimitServiceAccountRefresh extends RateLimitServiceIna this.activeFailureStreakByProvider.claude = 0 // Outgoing statusline posts must not land on the incoming account during the switch. this.lastClaudeAuthSnapshot = null + this.liveClaudeUsage = null + this.usageReadingAccounts.claude = undefined this.lastInactiveClaudeFetchAt = 0 this.updateState({ ...this.state, @@ -249,6 +254,8 @@ export abstract class RateLimitServiceAccountRefresh extends RateLimitServiceIna if (targetChanged) { // Outgoing target posts must not land on the incoming target during the switch. this.lastClaudeAuthSnapshot = null + this.liveClaudeUsage = null + this.usageReadingAccounts.claude = undefined } this.updateState({ ...this.state, diff --git a/src/main/rate-limits/service/service-fetch-policy.ts b/src/main/rate-limits/service/service-fetch-policy.ts index 8af5c4b22b0..32512ce90c0 100644 --- a/src/main/rate-limits/service/service-fetch-policy.ts +++ b/src/main/rate-limits/service/service-fetch-policy.ts @@ -15,10 +15,24 @@ import { isStaleClaudeUsageWindow, mapClaudeUsageWindow } from '../providers/claude/claude-usage-window' +import { claudeOAuthUsageDisabledResult } from '../providers/claude/claude-usage-result' import { readUserClaudeConfigDir } from '../../claude-accounts/profiles/claude-profile-paths' import { getClaudeProfileRouter } from '../../claude-accounts/profiles/routing/claude-profile-installed-router' export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchTargets { + protected isClaudeOAuthUsageEnabled(): boolean { + return this.claudeOAuthUsageEnabledResolver?.() ?? true + } + + protected claudeUsageFetchSignal(signal: AbortSignal): AbortSignal { + return AbortSignal.any([signal, this.claudeUsageAbortController.signal]) + } + + protected claudeUsageWithoutOAuth(): ProviderRateLimits { + const live = this.liveClaudeUsage ? withoutResetWindows(this.liveClaudeUsage, Date.now()) : null + return live?.session || live?.weekly ? live : claudeOAuthUsageDisabledResult() + } + protected getMiniMaxCredentialError(message: string): ProviderRateLimits { return { provider: 'minimax', @@ -44,6 +58,12 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT } } + protected claudeStateAtCycleStart(limits: ProviderRateLimits | null): ProviderRateLimits { + return this.isClaudeOAuthUsageEnabled() + ? this.withFetchingStatus(limits, 'claude') + : this.claudeUsageWithoutOAuth() + } + // Retry-After remains binding even when live posts restore ok display; early polls waste budget and prolong 429s. protected isRetryAfterActive(limits: ProviderRateLimits | null): boolean { return Boolean(limits?.usageMetadata?.retryAtMs && limits.usageMetadata.retryAtMs > Date.now()) @@ -70,6 +90,9 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT fresh: ProviderRateLimits, previous: ProviderRateLimits | null ): ProviderRateLimits { + if (!this.isClaudeOAuthUsageEnabled()) { + return this.claudeUsageWithoutOAuth() + } this.lastClaudeCheckCompletedAt = fresh.updatedAt // Failed OAuth must preserve newer live display while forwarding Retry-After to the poll gate. const current = this.state.claude @@ -94,15 +117,23 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT ) { return } - this.lastClaudeAuthSnapshot = { + const snapshot = { // System Default uses the user config folder without injecting a managed one. configDir: normalizeClaudeConfigDir( authPreparation?.envPatch.CLAUDE_CONFIG_DIR ?? getClaudeProfileRouter()?.userConfigDir() ?? readUserClaudeConfigDir(process.env) ), + home: authPreparation?.configDir, provenance: authPreparation?.provenance ?? 'system' } + if ( + snapshot.configDir !== this.lastClaudeAuthSnapshot?.configDir || + snapshot.provenance !== this.lastClaudeAuthSnapshot?.provenance + ) { + this.liveClaudeUsage = null + } + this.lastClaudeAuthSnapshot = snapshot } ingestLiveClaudeRateLimits(event: ClaudeStatusLineRateLimits): void { @@ -155,6 +186,26 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT ) { return } + const priorLive = this.liveClaudeUsage ? withoutResetWindows(this.liveClaudeUsage, now) : null + this.liveClaudeUsage = { + provider: 'claude', + session: freshSession ?? priorLive?.session ?? null, + weekly: freshWeekly ?? priorLive?.weekly ?? null, + updatedAt: now, + error: null, + status: 'ok', + usageMetadata: { + source: 'live-session', + lastSuccessfulSource: 'live-session', + authProvenance: snapshot.provenance + } + } + this.rememberUsageReadingAccount( + 'claude', + this.claudeFetchTarget, + snapshot.home, + snapshot.provenance + ) if ( previous?.status === 'ok' && previous.usageMetadata?.source === 'live-session' && diff --git a/src/main/rate-limits/service/service-full-cycle-preparation.ts b/src/main/rate-limits/service/service-full-cycle-preparation.ts index fc9c8186b05..b9ed5efd4e8 100644 --- a/src/main/rate-limits/service/service-full-cycle-preparation.ts +++ b/src/main/rate-limits/service/service-full-cycle-preparation.ts @@ -153,7 +153,7 @@ export abstract class RateLimitServiceFullCyclePreparation extends RateLimitServ this.updateState({ ...previousState, - claude: this.withFetchingStatus(previousState.claude, 'claude'), + claude: this.claudeStateAtCycleStart(previousState.claude), // A gated slot makes no attempt and cannot settle a fetching chip. codex: codexFetchGated ? codexStateBeforeFetch @@ -220,7 +220,9 @@ export abstract class RateLimitServiceFullCyclePreparation extends RateLimitServ // Live display does not waive automated Retry-After gates. const claudeFetchGated = - !options?.force && this.shouldSkipAutomatedFetch('claude', previousState.claude) + !this.isClaudeOAuthUsageEnabled() || + claudeGeneration !== this.claudeFetchGeneration || + (!options?.force && this.shouldSkipAutomatedFetch('claude', previousState.claude)) const [claudeResult, codexResult, geminiResult, opencodeGoResult, kimiResult, miniMaxResult] = await Promise.allSettled([ @@ -231,7 +233,7 @@ export abstract class RateLimitServiceFullCyclePreparation extends RateLimitServ allowPtyFallback: this.shouldAllowClaudePtyFallback(claudeAuthPreparation), allowUsagePanelSupplement: this.shouldAllowClaudeUsagePanelSupplement(), networkProxySettings: this.networkProxySettingsResolver?.(), - signal + signal: this.claudeUsageFetchSignal(signal) }), codexFetchGated ? Promise.resolve(previousState.codex as ProviderRateLimits) diff --git a/src/main/rate-limits/service/service-inactive-accounts.ts b/src/main/rate-limits/service/service-inactive-accounts.ts index ffcaba04f59..45c171dc0e6 100644 --- a/src/main/rate-limits/service/service-inactive-accounts.ts +++ b/src/main/rate-limits/service/service-inactive-accounts.ts @@ -6,6 +6,9 @@ import { delayUnlessAborted } from '../../../shared/abort-aware-delay' export abstract class RateLimitServiceInactiveAccounts extends RateLimitServicePolling { async fetchInactiveClaudeAccountsOnOpen(): Promise { + if (!this.isClaudeOAuthUsageEnabled()) { + return + } if (Date.now() - this.lastInactiveClaudeFetchAt < INACTIVE_FETCH_DEBOUNCE_MS) { return } @@ -21,7 +24,7 @@ export abstract class RateLimitServiceInactiveAccounts extends RateLimitServiceP } const fetchGeneration = this.inactiveClaudeAccountsGeneration const controller = this.beginFetchCycle() - const signal = controller.signal + const signal = this.claudeUsageFetchSignal(controller.signal) for (const account of accounts) { this.inactiveClaudeFetching.add(account.id) diff --git a/src/main/rate-limits/service/service-polling.ts b/src/main/rate-limits/service/service-polling.ts index 0a6e7421d3c..33da0aa57a8 100644 --- a/src/main/rate-limits/service/service-polling.ts +++ b/src/main/rate-limits/service/service-polling.ts @@ -87,6 +87,7 @@ export abstract class RateLimitServicePolling extends RateLimitServiceFetchQueue const museEnabled = this.museUsageEnabledResolver?.() ?? true return Object.entries(byProvider) .filter(([provider]) => provider !== 'muse' || museEnabled) + .filter(([provider]) => provider !== 'claude' || this.isClaudeOAuthUsageEnabled()) .map(([provider, limits]) => ({ provider: provider as ActiveRateLimitProvider, limits diff --git a/src/main/rate-limits/service/service-provider-cycles.ts b/src/main/rate-limits/service/service-provider-cycles.ts index 3218091ead4..42a8be46035 100644 --- a/src/main/rate-limits/service/service-provider-cycles.ts +++ b/src/main/rate-limits/service/service-provider-cycles.ts @@ -94,10 +94,15 @@ export abstract class RateLimitServiceProviderCycles extends RateLimitServiceFul // Why: capture before the resolver await so an account switch during it invalidates both the snapshot and the state apply. const claudeGeneration = this.claudeFetchGeneration const claudeAuthPreparation = await this.claudeAuthPreparationResolver?.(claudeTarget) - if (signal.aborted) { + if (signal.aborted || claudeGeneration !== this.claudeFetchGeneration) { return } this.rememberClaudeAuthSnapshot(claudeAuthPreparation, claudeGeneration, claudeTarget) + // After the snapshot: statusLine posts are dropped until one names the selected account. + if (!this.isClaudeOAuthUsageEnabled()) { + this.updateState({ ...this.state, claude: this.claudeUsageWithoutOAuth() }) + return + } const claudeProvenance = claudeAuthPreparation?.provenance ?? 'system' const previousState = this.state @@ -111,7 +116,7 @@ export abstract class RateLimitServiceProviderCycles extends RateLimitServiceFul allowPtyFallback: this.shouldAllowClaudePtyFallback(claudeAuthPreparation), allowUsagePanelSupplement: this.shouldAllowClaudeUsagePanelSupplement(), networkProxySettings: this.networkProxySettingsResolver?.(), - signal + signal: this.claudeUsageFetchSignal(signal) }).catch((err): ProviderRateLimits => ({ provider: 'claude', session: null, diff --git a/src/main/rate-limits/service/service-refresh-orchestration.test.ts b/src/main/rate-limits/service/service-refresh-orchestration.test.ts index 6f3ef84e67d..28afdea75ff 100644 --- a/src/main/rate-limits/service/service-refresh-orchestration.test.ts +++ b/src/main/rate-limits/service/service-refresh-orchestration.test.ts @@ -2,10 +2,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { ProviderRateLimits } from '../../../shared/rate-limit-types' import { RateLimitService } from './rate-limit-service' import { fetchActiveClaudeRateLimits } from '../providers/claude/claude-active-usage-fetch' +import { fetchInactiveClaudeAccountUsage } from '../providers/claude/claude-managed-account-usage' import { fetchCodexRateLimits } from '../providers/codex/codex-fetcher' import { deferred, flushMicrotasks, + mockFreshBackgroundProviderFetches, okProvider, resetRateLimitProviderMocks } from './rate-limit-service-test-harness' @@ -95,4 +97,213 @@ describe('RateLimitService', () => { await flushMicrotasks(60) expect(service.getState().claude?.session?.usedPercent).toBe(55) }) + + it('keeps live Claude usage through refreshes without reading OAuth usage when disabled', async () => { + mockFreshBackgroundProviderFetches() + const service = new RateLimitService() + service.setClaudeOAuthUsageEnabledResolver(() => false) + service.setInactiveClaudeAccountsResolver(() => [{ id: 'other' }]) + let home = '/claude/account-a' + service.setClaudeAuthPreparationResolver(async () => ({ + configDir: home, + envPatch: { CLAUDE_CONFIG_DIR: home }, + provenance: home + })) + service.start({ fetchImmediately: false }) + await flushMicrotasks(20) + service.stop() + expect(service.getState().claude).toMatchObject({ + session: null, + weekly: null, + status: 'unavailable' + }) + service.ingestLiveClaudeRateLimits({ + configDir: '/claude/account-a', + fiveHour: { used_percentage: 33 }, + sevenDay: { used_percentage: 62 } + }) + await service.refreshClaudeForTarget() + await service.refresh() + await service.fetchInactiveClaudeAccountsOnOpen() + + expect(service.getState().claude).toMatchObject({ + session: { usedPercent: 33 }, + weekly: { usedPercent: 62 }, + status: 'ok', + usageMetadata: { source: 'live-session' } + }) + expect(service.getState().inactiveClaudeAccounts).toEqual([]) + expect(service.usageReadingAccount('claude')).toEqual({ + home: '/claude/account-a', + provenance: '/claude/account-a' + }) + expect(service.requestUsageReading('claude')).toBe(false) + expect(fetchActiveClaudeRateLimits).not.toHaveBeenCalled() + expect(fetchInactiveClaudeAccountUsage).not.toHaveBeenCalled() + + home = '/claude/account-b' + await service.refreshForClaudeAccountChange('outgoing') + expect(service.getState().claude?.session).toBeNull() + expect(service.getState().claude?.status).toBe('unavailable') + service.ingestLiveClaudeRateLimits({ + configDir: '/claude/account-b', + fiveHour: { used_percentage: 12 }, + sevenDay: null + }) + expect(service.getState().claude?.session?.usedPercent).toBe(12) + expect(service.usageReadingAccount('claude')).toEqual({ + home: '/claude/account-b', + provenance: '/claude/account-b' + }) + }) + + it('cancels pending Claude usage and rejects its reply even after polling is enabled again', async () => { + mockFreshBackgroundProviderFetches() + const service = new RateLimitService() + let enabled = true + service.setClaudeOAuthUsageEnabledResolver(() => enabled) + const started = deferred() + const reply = deferred() + vi.mocked(fetchActiveClaudeRateLimits).mockImplementationOnce((options) => { + started.resolve(options?.signal) + return reply.promise + }) + const refresh = service.refresh() + const signal = await started.promise + + enabled = false + service.discardClaudeOAuthUsage() + expect(signal?.aborted).toBe(true) + service.ingestLiveClaudeRateLimits({ + configDir: null, + fiveHour: { used_percentage: 41 }, + sevenDay: null + }) + enabled = true + reply.resolve(okProvider('claude', 90)) + await refresh + + expect(service.getState().claude).toMatchObject({ + session: { usedPercent: 41 }, + status: 'ok', + usageMetadata: { source: 'live-session' } + }) + }) + + it('retains only terminal-observed windows when disabling OAuth-enriched usage', async () => { + mockFreshBackgroundProviderFetches() + const service = new RateLimitService() + let enabled = true + service.setClaudeOAuthUsageEnabledResolver(() => enabled) + vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValueOnce({ + ...okProvider('claude', 20), + weekly: { usedPercent: 50, windowMinutes: 10080, resetsAt: null, resetDescription: null }, + fableWeekly: { + usedPercent: 70, + windowMinutes: 10080, + resetsAt: null, + resetDescription: null + }, + extraUsage: { + unit: 'credits', + enabled: true, + balance: 100, + unlimited: false, + disabledReason: null, + resetsAt: null + } + }) + await service.refresh() + service.ingestLiveClaudeRateLimits({ + configDir: null, + fiveHour: { used_percentage: 35 }, + sevenDay: null + }) + expect(service.getState().claude?.weekly?.usedPercent).toBe(50) + + enabled = false + service.discardClaudeOAuthUsage() + await service.refresh() + + expect(service.getState().claude).toMatchObject({ + session: { usedPercent: 35 }, + weekly: null, + usageMetadata: { source: 'live-session' } + }) + expect(service.getState().claude?.fableWeekly).toBeFalsy() + expect(service.getState().claude?.extraUsage).toBeFalsy() + await service.refreshForClaudeAccountChange('outgoing') + expect(service.getState().claude?.session).toBeNull() + }) + + it('discards pending inactive-account usage when polling is disabled', async () => { + const service = new RateLimitService() + let enabled = true + service.setClaudeOAuthUsageEnabledResolver(() => enabled) + service.setInactiveClaudeAccountsResolver(() => [{ id: 'other' }, { id: 'another' }]) + const started = deferred() + const reply = deferred() + vi.mocked(fetchInactiveClaudeAccountUsage).mockImplementationOnce((_account, options) => { + started.resolve(options?.signal) + return reply.promise + }) + const refresh = service.fetchInactiveClaudeAccountsOnOpen() + const signal = await started.promise + + enabled = false + service.discardClaudeOAuthUsage() + expect(signal?.aborted).toBe(true) + enabled = true + reply.resolve(okProvider('claude', 90)) + await refresh + + expect(service.getState().inactiveClaudeAccounts).toEqual([]) + expect(service.getState().claude).toMatchObject({ + session: null, + weekly: null, + status: 'unavailable' + }) + }) + + it.each(['all', 'claude'] as const)( + 'does not revive a canceled %s request still preparing account attribution', + async (cycle) => { + mockFreshBackgroundProviderFetches() + const service = new RateLimitService() + let enabled = true + service.setClaudeOAuthUsageEnabledResolver(() => enabled) + const oldAuth = { configDir: '/claude/old', envPatch: {}, provenance: 'old' } + const preparation = deferred() + service.setClaudeAuthPreparationResolver( + vi + .fn() + .mockReturnValueOnce(preparation.promise) + .mockResolvedValue({ + configDir: '/claude/current', + envPatch: { CLAUDE_CONFIG_DIR: '/claude/current' }, + provenance: 'current' + }) + ) + const refresh = cycle === 'all' ? service.refresh() : service.refreshClaudeForTarget() + enabled = false + service.discardClaudeOAuthUsage() + enabled = true + preparation.resolve(oldAuth) + await refresh + + expect(fetchActiveClaudeRateLimits).not.toHaveBeenCalledWith( + expect.objectContaining({ authPreparation: oldAuth }) + ) + service.ingestLiveClaudeRateLimits({ + configDir: '/claude/current', + fiveHour: { used_percentage: 15 }, + sevenDay: null + }) + expect(service.getState().claude?.session?.usedPercent).toBe(15) + expect(service.usageReadingAccount('claude')).toEqual({ + home: '/claude/current', + provenance: 'current' + }) + } + ) }) diff --git a/src/main/rate-limits/service/service-state.ts b/src/main/rate-limits/service/service-state.ts index 3b0b3c0d35a..f847392189c 100644 --- a/src/main/rate-limits/service/service-state.ts +++ b/src/main/rate-limits/service/service-state.ts @@ -17,6 +17,7 @@ import { type OpenCodeGoRateLimitConfig, type MiniMaxRateLimitConfig, type AntigravityUsageEnabledResolver, + type ClaudeOAuthUsageEnabledResolver, type MuseUsageEnabledResolver, type ZcodePlanRateLimitConfig, type GeminiCliOAuthEnabledResolver, @@ -90,10 +91,16 @@ export abstract class RateLimitServiceState { protected fetchIdleResolvers: (() => void)[] = [] protected codexFetchGeneration = 0 protected claudeFetchGeneration = 0 + protected claudeUsageAbortController = new AbortController() + protected liveClaudeUsage: ProviderRateLimits | null = null // Why: cached display receipts cannot establish when the selected account was last checked. protected lastClaudeCheckCompletedAt: number | null = null // Capture account attribution once per cycle instead of rerunning auth preparation on every post. - protected lastClaudeAuthSnapshot: { configDir: string | null; provenance: string } | null = null + protected lastClaudeAuthSnapshot: { + configDir: string | null + home: string | undefined + provenance: string + } | null = null /** Where the applied host-runtime Claude/Codex readings were taken. */ protected usageReadingAccounts: Partial< Record<'claude' | 'codex', { home: string; provenance: string }> @@ -122,6 +129,7 @@ export abstract class RateLimitServiceState { protected miniMaxConfigResolver: (() => MiniMaxRateLimitConfig) | null = null protected zcodePlanConfigResolver: (() => ZcodePlanRateLimitConfig) | null = null protected geminiCliOAuthEnabledResolver: GeminiCliOAuthEnabledResolver | null = null + protected claudeOAuthUsageEnabledResolver: ClaudeOAuthUsageEnabledResolver | null = null protected antigravityUsageEnabledResolver: AntigravityUsageEnabledResolver | null = null protected antigravityFetchTarget: LocalAccountRuntimeTarget = { runtime: 'host', wslDistro: null } protected antigravityAccountUsageRecorder: AntigravityAccountUsageRecorder | null = null diff --git a/src/main/rate-limits/service/service-types.ts b/src/main/rate-limits/service/service-types.ts index c2c9b9e8c2b..bb67e283a65 100644 --- a/src/main/rate-limits/service/service-types.ts +++ b/src/main/rate-limits/service/service-types.ts @@ -62,6 +62,7 @@ export type ZcodePlanResolvedConfig = { export type GeminiCliOAuthEnabledResolver = () => boolean export type AntigravityUsageEnabledResolver = () => boolean +export type ClaudeOAuthUsageEnabledResolver = () => boolean export type MuseUsageEnabledResolver = () => boolean export type ActiveRateLimitProvider = ProviderRateLimits['provider'] export type ActiveProviderState = { diff --git a/src/renderer/src/components/settings/accounts/claude/accounts-pane-claude-section.tsx b/src/renderer/src/components/settings/accounts/claude/accounts-pane-claude-section.tsx index bc05589e570..9ad23092a2b 100644 --- a/src/renderer/src/components/settings/accounts/claude/accounts-pane-claude-section.tsx +++ b/src/renderer/src/components/settings/accounts/claude/accounts-pane-claude-section.tsx @@ -8,6 +8,7 @@ import { ButtonGroup } from '../../../ui/button-group' import { Label } from '../../../ui/label' import { ClaudeIcon } from '../../../status-bar/icons' import { SearchableSetting } from '../../section-layout/SearchableSetting' +import { ClaudeOAuthUsageSetting } from './claude-oauth-usage-setting' import { ClaudeRunningSessionSwitchSetting } from './claude-running-session-switch-setting' import { getProviderAccountRuntime, @@ -45,6 +46,7 @@ export function renderClaudeAccountsSection( claudeAccounts, claudeAction, isRemoteAccountScope, + recordFeatureInteraction, remoteAccountScopeNotice, runClaudeAccountAction, setRemoveClaudeTarget, @@ -383,6 +385,13 @@ export function renderClaudeAccountsSection( )}
+ {isRemoteAccountScope ? null : ( + + )} {isRemoteAccountScope ? null : ( )} diff --git a/src/renderer/src/components/settings/accounts/claude/claude-oauth-usage-setting.fixture.tsx b/src/renderer/src/components/settings/accounts/claude/claude-oauth-usage-setting.fixture.tsx new file mode 100644 index 00000000000..f01471848ca --- /dev/null +++ b/src/renderer/src/components/settings/accounts/claude/claude-oauth-usage-setting.fixture.tsx @@ -0,0 +1,42 @@ +import { defineFixture } from '../../../../component-fixtures/component-fixture' +import { getDefaultSettings } from '../../../../../../shared/constants' +import { useAppStore } from '../../../../store' +import { SettingsGroup } from '../../section-layout/SettingsGroup' +import { ClaudeOAuthUsageSetting } from './claude-oauth-usage-setting' + +function UsageSettingFixture(): React.JSX.Element | null { + const settings = useAppStore((state) => state.settings) + const updateSettings = useAppStore((state) => state.updateSettings) + if (!settings) { + return null + } + return ( +
+ + {}} + /> + +
+ ) +} + +export const on = defineFixture({ width: 720, render: () => }) + +export const off = defineFixture({ + ...on, + store: { settings: { ...getDefaultSettings('/fixture'), claudeOAuthUsageEnabled: false } } +}) + +export const narrow = defineFixture({ ...off, width: 360 }) + +export const infoTooltip = defineFixture({ + ...on, + interact: (frame) => { + frame + .querySelector('button[aria-label="About Claude usage polling"]') + ?.focus() + } +}) diff --git a/src/renderer/src/components/settings/accounts/claude/claude-oauth-usage-setting.tsx b/src/renderer/src/components/settings/accounts/claude/claude-oauth-usage-setting.tsx new file mode 100644 index 00000000000..5a8dc027100 --- /dev/null +++ b/src/renderer/src/components/settings/accounts/claude/claude-oauth-usage-setting.tsx @@ -0,0 +1,67 @@ +import { useTranslate } from '@/i18n/use-translate' +import { Info } from 'lucide-react' +import { Button } from '../../../ui/button' +import { Label } from '../../../ui/label' +import { Switch } from '../../../ui/switch' +import { Tooltip, TooltipContent, TooltipTrigger } from '../../../ui/tooltip' +import { SearchableSetting } from '../../section-layout/SearchableSetting' +import type { AccountsPaneSectionModel } from '../accounts-pane-types' + +type ClaudeOAuthUsageSettingProps = Pick< + AccountsPaneSectionModel, + 'settings' | 'updateSettings' | 'recordFeatureInteraction' +> + +export function ClaudeOAuthUsageSetting({ + settings, + updateSettings, + recordFeatureInteraction +}: ClaudeOAuthUsageSettingProps): React.JSX.Element { + const t = useTranslate() + const title = t('accounts.claude.oauthUsage.title', 'Claude usage polling') + const description = t( + 'accounts.claude.oauthUsage.description', + 'Uses your Claude Code sign-in to check usage, credits, and inactive accounts. Turn off to use live terminal readings only.' + ) + return ( + +
+ + + + + + + {description} + + +
+ + {description} + + { + recordFeatureInteraction('usage-tracking') + updateSettings({ claudeOAuthUsageEnabled: checked }) + }} + /> +
+ ) +} diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 6901410c75b..347472857df 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -21958,6 +21958,11 @@ "reasonSharedSession": "Auch in einem anderen Bereich geöffnet", "sharedOne": "1 Claude-Sitzung bleibt auf {{previous}}, weil dieselbe Unterhaltung in einem anderen Bereich geöffnet ist. Ein Neustart könnte die Unterhaltung des anderen Bereichs erneut öffnen.", "sharedOther": "{{count}} Claude-Sitzungen bleiben auf {{previous}}, weil dieselbe Unterhaltung in einem anderen Bereich geöffnet ist. Ein Neustart könnte die Unterhaltung des anderen Bereichs erneut öffnen." + }, + "oauthUsage": { + "title": "Claude-Nutzungsabfrage", + "description": "Verwendet deine Claude-Code-Anmeldung, um Nutzung, Guthaben und inaktive Konten abzufragen. Deaktiviere diese Option, um nur Live-Daten aus Terminalsitzungen zu verwenden.", + "about": "Über die Claude-Nutzungsabfrage" } }, "managedData": { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 0b43fa80a27..9795bf9aae0 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -23494,6 +23494,11 @@ "body_one": "{{count}} Claude session is still running on {{previous}}. Restarting continues the conversation on {{next}}. Busy sessions wait for idle before restarting.", "body_other": "{{count}} Claude sessions are still running on {{previous}}. Restarting continues each conversation on {{next}}. Busy sessions wait for idle before restarting.", "restartCount_one": "Restart {{count}} session" + }, + "oauthUsage": { + "title": "Claude usage polling", + "description": "Uses your Claude Code sign-in to check usage, credits, and inactive accounts. Turn off to use live terminal readings only.", + "about": "About Claude usage polling" } }, "managedData": { diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index b5e69c8f6db..f92aa988b2a 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -21566,6 +21566,11 @@ "reasonSharedSession": "También abierta en otro panel", "sharedOne": "1 sesión de Claude permanece en {{previous}} porque otro panel tiene abierta la misma conversación. Reiniciarla podría volver a abrir la conversación del otro panel.", "sharedOther": "{{count}} sesiones de Claude permanecen en {{previous}} porque otro panel tiene abierta la misma conversación. Reiniciarlas podría volver a abrir la conversación del otro panel." + }, + "oauthUsage": { + "title": "Consulta de uso de Claude", + "description": "Usa tu inicio de sesión de Claude Code para consultar el uso, los créditos y las cuentas inactivas. Desactívala para usar solo las lecturas en directo de las sesiones de terminal.", + "about": "Acerca de la consulta de uso de Claude" } }, "hostSignIn": { diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index adbc27e17f3..57e30149881 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -22234,6 +22234,11 @@ "reasonSharedSession": "Également ouverte dans un autre volet", "sharedOne": "1 session Claude reste sur {{previous}} car la même conversation est ouverte dans un autre volet. Un redémarrage pourrait rouvrir la conversation de l’autre volet.", "sharedOther": "{{count}} sessions Claude restent sur {{previous}} car la même conversation est ouverte dans un autre volet. Un redémarrage pourrait rouvrir la conversation de l’autre volet." + }, + "oauthUsage": { + "title": "Suivi de l’utilisation de Claude", + "description": "Utilise votre connexion Claude Code pour consulter l’utilisation, les crédits et les comptes inactifs. Désactivez cette option pour utiliser uniquement les données en direct des sessions de terminal.", + "about": "À propos du suivi de l’utilisation de Claude" } }, "hostSignIn": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index c3f93d47ebf..5913dbb8282 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -21561,6 +21561,11 @@ "reasonSharedSession": "別のペインでも開いています", "sharedOne": "別のペインで同じ会話が開いているため、1 件の Claude セッションは {{previous}} のままです。再起動すると別のペインの会話が再び開く可能性があります。", "sharedOther": "別のペインで同じ会話が開いているため、{{count}} 件の Claude セッションは {{previous}} のままです。再起動すると別のペインの会話が再び開く可能性があります。" + }, + "oauthUsage": { + "title": "Claude の使用量の定期取得", + "description": "Claude Code のログイン情報を使って、使用量、クレジット、非アクティブなアカウントを確認します。オフにすると、実行中のターミナルセッションからの使用量データのみを表示します。", + "about": "Claude の使用量の定期取得について" } }, "hostSignIn": { diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 2e312739034..268bfacdbe9 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -21553,6 +21553,11 @@ "reasonSharedSession": "다른 패널에서도 열려 있음", "sharedOne": "다른 패널에서 같은 대화를 열고 있어 Claude 세션 1개가 {{previous}}에 유지됩니다. 다시 시작하면 다른 패널의 대화가 다시 열릴 수 있습니다.", "sharedOther": "다른 패널에서 같은 대화를 열고 있어 Claude 세션 {{count}}개가 {{previous}}에 유지됩니다. 다시 시작하면 다른 패널의 대화가 다시 열릴 수 있습니다." + }, + "oauthUsage": { + "title": "Claude 사용량 주기적 조회", + "description": "Claude Code 로그인 정보로 사용량, 크레딧 및 비활성 계정을 확인합니다. 끄면 실행 중인 터미널 세션에서 제공하는 실시간 사용량만 표시합니다.", + "about": "Claude 사용량 주기적 조회 정보" } }, "hostSignIn": { diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 3e62a8c2f91..fbb12f430ee 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -22931,6 +22931,11 @@ "reasonSharedSession": "Também aberta em outro painel", "sharedOne": "1 sessão do Claude permanece em {{previous}} porque outro painel tem a mesma conversa aberta. Reiniciar pode reabrir a conversa do outro painel.", "sharedOther": "{{count}} sessões do Claude permanecem em {{previous}} porque outro painel tem a mesma conversa aberta. Reiniciar pode reabrir a conversa do outro painel." + }, + "oauthUsage": { + "title": "Consulta de uso do Claude", + "description": "Usa seu login do Claude Code para consultar o uso, os créditos e as contas inativas. Desative para usar apenas as leituras em tempo real das sessões do terminal.", + "about": "Sobre a consulta de uso do Claude" } }, "managedData": { diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 1af528a9f4c..d7f6518197e 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -22661,7 +22661,12 @@ "sharedOne": "1 сеанс Claude остаётся на {{previous}}, поскольку тот же разговор открыт в другой панели. При перезапуске может снова открыться разговор из другой панели.", "sharedOther": "Сеансы Claude ({{count}}) остаются на {{previous}}, поскольку тот же разговор открыт в другой панели. При перезапуске может снова открыться разговор из другой панели." }, - "unnamedAccount": "Учётная запись Claude" + "unnamedAccount": "Учётная запись Claude", + "oauthUsage": { + "title": "Опрос использования Claude", + "description": "Использует ваш вход в Claude Code для проверки использования, кредитов и неактивных аккаунтов. Отключите, чтобы получать данные только из активных сеансов терминала.", + "about": "Об опросе использования Claude" + } }, "managedData": { "description": "Добавляйте учётные записи этой командой в терминале сервера Orca. Выбор применяется к новым явным запускам агента на этом сервере; прямой SSH-ретранслятор и запуски WSL из Windows используют собственные учётные данные.", diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 9321f2c34d4..eccd93ad3a8 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -21928,6 +21928,11 @@ "reasonSharedSession": "Başka bir bölmede de açık", "sharedOne": "Aynı konuşma başka bir bölmede açık olduğu için 1 Claude oturumu {{previous}} üzerinde kalır. Yeniden başlatmak diğer bölmedeki konuşmayı yeniden açabilir.", "sharedOther": "Aynı konuşma başka bir bölmede açık olduğu için {{count}} Claude oturumu {{previous}} üzerinde kalır. Yeniden başlatmak diğer bölmedeki konuşmayı yeniden açabilir." + }, + "oauthUsage": { + "title": "Claude kullanımını sorgula", + "description": "Kullanımı, kredileri ve etkin olmayan hesapları kontrol etmek için Claude Code oturumunuzu kullanır. Yalnızca çalışan terminal oturumlarından gelen canlı verileri kullanmak için kapatın.", + "about": "Claude kullanım sorgulaması hakkında" } }, "managedData": { diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 0d592cf40c5..90b60ca6c21 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -21631,6 +21631,11 @@ "reasonSharedSession": "在另一個窗格中也已開啟", "sharedOne": "由於另一個窗格開啟了相同對話,1 個 Claude 工作階段會保留在 {{previous}}。重新啟動可能會重新開啟另一個窗格的對話。", "sharedOther": "由於另一個窗格開啟了相同對話,{{count}} 個 Claude 工作階段會保留在 {{previous}}。重新啟動可能會重新開啟另一個窗格的對話。" + }, + "oauthUsage": { + "title": "Claude 用量輪詢", + "description": "使用 Claude Code 登入憑證查詢用量、額度和非使用中帳戶。關閉後,僅顯示執行中終端機工作階段提供的即時用量。", + "about": "關於 Claude 用量輪詢" } }, "managedData": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index b68f1c671ae..c62d0c81d31 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -21901,6 +21901,11 @@ "reasonSharedSession": "在另一个窗格中也已打开", "sharedOne": "由于另一个窗格打开了同一对话,1 个 Claude 会话将保持在 {{previous}}。重新启动可能会重新打开另一个窗格的对话。", "sharedOther": "由于另一个窗格打开了同一对话,{{count}} 个 Claude 会话将保持在 {{previous}}。重新启动可能会重新打开另一个窗格的对话。" + }, + "oauthUsage": { + "title": "Claude 用量轮询", + "description": "使用 Claude Code 登录凭据检查用量、额度和非活跃账号。关闭后,仅显示运行中终端会话提供的实时用量。", + "about": "关于 Claude 用量轮询" } }, "hostSignIn": { diff --git a/src/shared/default-global-settings.ts b/src/shared/default-global-settings.ts index fe3326a7219..7403d95fa1c 100644 --- a/src/shared/default-global-settings.ts +++ b/src/shared/default-global-settings.ts @@ -249,6 +249,7 @@ export function buildDefaultSettings(args: { minimaxEndpoint: 'overseas', zcodePlanSite: 'zai', geminiCliOAuthEnabled: false, + claudeOAuthUsageEnabled: true, agentCmdOverrides: {}, // Arguments hold only the user's own text; the permission flag comes from the choice below. agentDefaultArgs: {}, diff --git a/src/shared/global-settings-types.ts b/src/shared/global-settings-types.ts index 0586388fcf9..85f4a02b995 100644 --- a/src/shared/global-settings-types.ts +++ b/src/shared/global-settings-types.ts @@ -375,6 +375,8 @@ export type GlobalSettings = GlobalSettingsBase & { zcodePlanSite?: ZcodePlanSite /** Extract OAuth credentials from the local Gemini CLI for rate-limit fetching. Off by default (explicit opt-in). */ geminiCliOAuthEnabled: boolean + /** Poll Claude usage with existing CLI credentials. Off uses live terminal readings only. */ + claudeOAuthUsageEnabled: boolean /** Per-agent CLI command overrides. A missing key means use the catalog default binary name. */ agentCmdOverrides: Partial> /** Off keeps each Codex home's history to itself: Orca links no sessions between accounts or From 3342284233b0dffb041c3b1b97799fa13352c789 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:33:08 +0000 Subject: [PATCH 10/17] fix(native-chat): an older browser run's Show button never opens another run's page (#41939) A run without --page fell back to the chat's latest agent page whenever it had no remembered page, which is every older run after a restart or once 500 runs push it out. The chat's browser activity now belongs only to its newest browser run, which remembers that page for when a newer run takes over. An older run that this renderer never saw as the newest shows no button. --- .../browser-agent-activity-state.ts | 31 ++--- .../runs/NativeChatBrowserPageButton.test.tsx | 128 +++++++++++++----- .../runs/NativeChatBrowserPageButton.tsx | 126 +++++++++++------ 3 files changed, 186 insertions(+), 99 deletions(-) diff --git a/src/renderer/src/components/browser-pane/agent-cursor/browser-agent-activity-state.ts b/src/renderer/src/components/browser-pane/agent-cursor/browser-agent-activity-state.ts index 98ce6117002..47046208acd 100644 --- a/src/renderer/src/components/browser-pane/agent-cursor/browser-agent-activity-state.ts +++ b/src/renderer/src/components/browser-pane/agent-cursor/browser-agent-activity-state.ts @@ -8,19 +8,15 @@ type BrowserAgentCursorSink = { setActive: (active: boolean) => void } -/** The page an agent in a worktree last drove; `revision` orders it against other activity. */ -type BrowserAgentActivityMark = { pageId: string; revision: number } - const activePageIds = new Set() /** The SSH host driving a page through the desktop browser bridge, by its label. */ const controllerHostByPage = new Map() /** Activity no chat claimed: older CLIs, remote hosts and terminal agents. */ -const lastUnclaimedActivityByWorktree = new Map() -const lastActivityByChatSession = new Map() +const lastUnclaimedPageIdByWorktree = new Map() +const lastPageIdByChatSession = new Map() const lastCursorByPage = new Map() const sinksByPage = new Map() const listeners = new Set<() => void>() -let revision = 0 function notify(): void { for (const listener of listeners) { @@ -43,18 +39,16 @@ export function setBrowserAgentPageActive( agentSessionId?: string ): void { if (active) { - revision += 1 activePageIds.add(browserPageId) if (controllerHostLabel) { controllerHostByPage.set(browserPageId, controllerHostLabel) } else { controllerHostByPage.delete(browserPageId) } - const mark = { pageId: browserPageId, revision } if (agentSessionId) { - lastActivityByChatSession.set(agentSessionId, mark) + lastPageIdByChatSession.set(agentSessionId, browserPageId) } else if (worktreeId) { - lastUnclaimedActivityByWorktree.set(worktreeId, mark) + lastUnclaimedPageIdByWorktree.set(worktreeId, browserPageId) } } else { activePageIds.delete(browserPageId) @@ -90,11 +84,6 @@ export function attachBrowserAgentCursorSink( } } -/** Activity that arrives later than this revision happened after the caller looked. */ -export function getBrowserAgentActivityRevision(): number { - return revision -} - export function useBrowserAgentDrivesAnyPage( browserPageIds: readonly (string | null | undefined)[] ): boolean { @@ -118,15 +107,15 @@ export function useBrowserAgentControllerHost( return useSyncExternalStore(subscribe, read, read) } -/** What this chat's agent drove most recently; until it has claimed any, what an unclaimed agent in its worktree did. */ -export function useLastBrowserAgentActivity( +/** The page this chat's agent drove most recently; until it has claimed any, what an unclaimed agent in its worktree drove. */ +export function useLastBrowserAgentPageId( worktreeId: string | null, chatSessionId: string | null -): BrowserAgentActivityMark | null { +): string | null { // A chat that claimed activity names itself on this host, so unclaimed activity is another agent's. - const read = (): BrowserAgentActivityMark | null => - (chatSessionId ? lastActivityByChatSession.get(chatSessionId) : undefined) ?? - (worktreeId ? lastUnclaimedActivityByWorktree.get(worktreeId) : undefined) ?? + const read = (): string | null => + (chatSessionId ? lastPageIdByChatSession.get(chatSessionId) : undefined) ?? + (worktreeId ? lastUnclaimedPageIdByWorktree.get(worktreeId) : undefined) ?? null return useSyncExternalStore(subscribe, read, read) } diff --git a/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.test.tsx b/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.test.tsx index 1ef00b0357f..2e91f23dc77 100644 --- a/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.test.tsx +++ b/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.test.tsx @@ -1,9 +1,10 @@ // @vitest-environment happy-dom -import { act, render, screen, within } from '@testing-library/react' +import { act, render, within } from '@testing-library/react' import type { ReactNode } from 'react' import { describe, expect, it, vi } from 'vitest' import type { BrowserPage } from '../../../../../../shared/browser-workspace-types' +import type { NativeChatToolCallBlock } from '../../../../../../shared/native-chat/native-chat-types' import { setBrowserAgentPageActive } from '../../../browser-pane/agent-cursor/browser-agent-activity-state' import { NativeChatVisualOwnerContext, @@ -34,6 +35,37 @@ vi.mock('@/store', () => ({ useAppStore: (select: (current: typeof state) => unknown) => select(state) })) +const transcript = vi.hoisted(() => { + const listeners = new Set<() => void>() + let snapshot: { current: boolean; state: { items: unknown[] } } = { + current: true, + state: { items: [] } + } + return { + owner: { + getSnapshot: () => snapshot, + subscribe: (listener: () => void) => { + listeners.add(listener) + return () => listeners.delete(listener) + } + }, + setCalls(calls: readonly NativeChatToolCallBlock[]) { + snapshot = { + current: true, + state: { items: calls.map((call) => ({ body: { ...call, kind: 'tool-call' } })) } + } + listeners.forEach((listener) => listener()) + }, + setCurrent(current: boolean) { + snapshot = { ...snapshot, current } + listeners.forEach((listener) => listener()) + } + } +}) +vi.mock('../../session/structured/read/structured-agent-session-read-owner-registry', () => ({ + findStructuredAgentSessionReadOwner: () => transcript.owner +})) + const OWNER: NativeChatVisualOwner = { target: { kind: 'local' }, sessionId: 'session-1', @@ -48,52 +80,74 @@ function wrapper({ children }: { children: ReactNode }): React.JSX.Element { ) } +function browserCall(callId: string, command = 'orca browser click @e1'): NativeChatToolCallBlock { + return { type: 'tool-call', name: 'Bash', input: { command }, callId } +} + +function shownTitle(container: HTMLElement): string | null { + return within(container).queryByRole('button')?.getAttribute('title') ?? null +} + describe('NativeChatBrowserRunPageButton', () => { - it('keeps the page a run drove after the agent moves to a newer page', () => { + it("keeps an older run's page after a newer run drives another page", () => { state.browserPagesByWorkspace = { 'ws-1': [page('p1', 'First'), page('p2', 'Second')] } - render( - , - { wrapper } - ) + const older = browserCall('run-a') + act(() => transcript.setCalls([older])) + const olderRun = render(, { wrapper }) + act(() => setBrowserAgentPageActive('p1', true, 'wt-1', undefined, 'session-1')) + expect(shownTitle(olderRun.container)).toBe('First') - act(() => setBrowserAgentPageActive('p1', true, 'wt-1')) - expect(screen.getByRole('button').getAttribute('title')).toBe('First') - - act(() => setBrowserAgentPageActive('p2', true, 'wt-1')) - expect(screen.getByRole('button').getAttribute('title')).toBe('First') + const newer = browserCall('run-b') + act(() => transcript.setCalls([older, newer])) + const newerRun = render(, { wrapper }) + act(() => setBrowserAgentPageActive('p2', true, 'wt-1', undefined, 'session-1')) + expect(shownTitle(olderRun.container)).toBe('First') + expect(shownTitle(newerRun.container)).toBe('Second') }) - it("ignores other agents driving a different page before this run's command lands", () => { + it('ignores other agents driving a different page', () => { state.browserPagesByWorkspace = { 'ws-1': [page('p1', 'Mine'), page('p2', 'Theirs')] } - // An earlier run in this chat, so it is known to claim its activity. + const call = browserCall('run-c') + act(() => transcript.setCalls([call])) setBrowserAgentPageActive('p1', true, 'wt-1', undefined, 'session-1') - const { container } = render( - , - { wrapper } - ) + const { container } = render(, { wrapper }) act(() => setBrowserAgentPageActive('p2', true, 'wt-1')) act(() => setBrowserAgentPageActive('p2', true, 'wt-1', undefined, 'session-2')) + expect(shownTitle(container)).toBe('Mine') + }) + + it('shows the page for the newest run even when its activity arrived before the run drew', () => { + state.browserPagesByWorkspace = { 'ws-1': [page('p1', 'Driven')] } + const call = browserCall('run-d') + setBrowserAgentPageActive('p1', true, 'wt-1', undefined, 'session-1') + act(() => transcript.setCalls([call])) + const { container } = render(, { wrapper }) + expect(shownTitle(container)).toBe('Driven') + }) + + it("never shows another run's page for an older run whose page this renderer never saw", () => { + state.browserPagesByWorkspace = { 'ws-1': [page('p1', 'Older'), page('p2', 'Newer')] } + const older = browserCall('run-restored') + const newer = browserCall('run-newest') + act(() => transcript.setCalls([older, newer])) + setBrowserAgentPageActive('p1', true, 'wt-1', undefined, 'session-1') + const { container } = render(, { wrapper }) + expect(shownTitle(container)).toBeNull() + + act(() => setBrowserAgentPageActive('p2', true, 'wt-1', undefined, 'session-1')) + expect(shownTitle(container)).toBeNull() + }) + + it('keeps a run off a newer page while the transcript is behind the agent', () => { + state.browserPagesByWorkspace = { 'ws-1': [page('p1', 'Mine'), page('p2', 'Unseen run')] } + const call = browserCall('run-e') + act(() => transcript.setCalls([call])) + const { container } = render(, { wrapper }) act(() => setBrowserAgentPageActive('p1', true, 'wt-1', undefined, 'session-1')) - act(() => setBrowserAgentPageActive('p2', true, 'wt-1')) - expect(within(container).getByRole('button').getAttribute('title')).toBe('Mine') + + act(() => transcript.setCurrent(false)) + act(() => setBrowserAgentPageActive('p2', true, 'wt-1', undefined, 'session-1')) + expect(shownTitle(container)).toBe('Mine') }) }) diff --git a/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.tsx b/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.tsx index d11c156f520..1c53ea2a44b 100644 --- a/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.tsx +++ b/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.tsx @@ -1,36 +1,82 @@ -import { useEffect, useState } from 'react' +import { useEffect, useState, useSyncExternalStore } from 'react' import { BrowserFavicon } from '@/components/browser-favicon' import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store' import { findPage } from '@/store/slices/browser/pages/browser-page-records' import { findBrowserWorkspaceForRemotePage } from '@/runtime/web-session-tabs-sync/mirrored-browser-tabs' import { activateBrowserPagePaletteResult } from '@/lib/browser/palette/browser-page-palette-activation' +import { useLastBrowserAgentPageId } from '../../../browser-pane/agent-cursor/browser-agent-activity-state' import { - getBrowserAgentActivityRevision, - useLastBrowserAgentActivity -} from '../../../browser-pane/agent-cursor/browser-agent-activity-state' -import { useNativeChatVisualOwner } from '../../media/visuals/native-chat-visual-owner' -import { nativeChatToolRunCategory } from '../../../../../../shared/native-chat/tools/native-chat-tool-icon' + useNativeChatVisualOwner, + type NativeChatVisualOwner +} from '../../media/visuals/native-chat-visual-owner' +import { findStructuredAgentSessionReadOwner } from '../../session/structured/read/structured-agent-session-read-owner-registry' +import { + nativeChatToolCategory, + nativeChatToolRunCategory +} from '../../../../../../shared/native-chat/tools/native-chat-tool-icon' import { nativeChatFullCommand } from '../../../../../../shared/native-chat/tools/native-chat-tool-input-text' import { parseOrcaBrowserCommand } from '../../../../../../shared/orca-browser-cli-commands' import type { NativeChatToolCallBlock } from '../../../../../../shared/native-chat/native-chat-types' +import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -// Without `--page` a run only knows the worktree's latest agent page, so each run keeps the -// page it first resolved to instead of following later runs to newer pages. +// A run's page outlives the run only here: no transcript records the page a command without +// `--page` drove, so a run seen while it was the chat's latest keeps that page in this renderer. const pageIdByRunCallId = new Map() const REMEMBERED_RUNS_MAX = 500 -// Why: state, not a render-time Map read, so React Compiler's caches see the remembered page. -function startRun(runCallId: string | null): { - runCallId: string | null - revision: number - rememberedPageId: string | undefined -} { - return { - runCallId, - revision: getBrowserAgentActivityRevision(), - rememberedPageId: runCallId ? pageIdByRunCallId.get(runCallId) : undefined +function commandPageId(call: NativeChatToolCallBlock | undefined): string | null { + return parseOrcaBrowserCommand(nativeChatFullCommand(call?.input) ?? '')?.pageId ?? null +} + +/** The page the run's newest call named or was remembered with. */ +function rememberedRunPageId(calls: readonly NativeChatToolCallBlock[]): string | null { + for (let index = calls.length - 1; index >= 0; index -= 1) { + const call = calls[index] + const pageId = commandPageId(call) ?? (call.callId ? pageIdByRunCallId.get(call.callId) : null) + if (pageId) { + return pageId + } } + return null +} + +const latestBrowserCallIdByItems = new WeakMap() + +function latestBrowserCallId(items: readonly AgentJournalRenderItem[]): string | null { + const cached = latestBrowserCallIdByItems.get(items) + if (cached !== undefined) { + return cached + } + let callId: string | null = null + for (let index = items.length - 1; index >= 0; index -= 1) { + const { body, itemId } = items[index] + if ( + body.kind === 'tool-call' && + nativeChatToolCategory(body.name, body.mcpIdentity, body.input) === 'browser' + ) { + // The same identity structuredAgentSessionToolCallBlock gives the rendered call. + callId = body.callId ?? itemId + break + } + } + latestBrowserCallIdByItems.set(items, callId) + return callId +} + +const NO_READ_OWNER = (): (() => void) => () => {} + +/** The chat's newest browser call: its agent's browser activity is that call's run's. */ +function useLatestBrowserCallId(owner: NativeChatVisualOwner | null): string | null { + const readOwner = owner + ? findStructuredAgentSessionReadOwner(owner.sessionId, owner.target) + : undefined + const read = (): string | null => { + const snapshot = readOwner?.getSnapshot() + // A transcript behind the host may lack the newer call that drove the latest activity. + return snapshot?.current ? latestBrowserCallId(snapshot.state.items) : null + } + return useSyncExternalStore(readOwner?.subscribe ?? NO_READ_OWNER, read, read) } /** Reveals the page a run of agent browser commands used; nothing for any other run. */ @@ -42,38 +88,36 @@ export function NativeChatBrowserRunPageButton({ if (nativeChatToolRunCategory(calls) !== 'browser') { return null } - const lastCall = calls.at(-1) - const lastCommand = nativeChatFullCommand(lastCall?.input) ?? '' - return ( - - ) + return } function BrowserPageButton({ - pageId, - runCallId + calls }: { - /** The page the command named with `--page`; otherwise the worktree's agent page. */ - pageId: string | null - runCallId: string | null + calls: readonly NativeChatToolCallBlock[] }): React.JSX.Element | null { const t = useTranslate() const owner = useNativeChatVisualOwner() - const latest = useLastBrowserAgentActivity(owner?.worktreeId ?? null, owner?.sessionId ?? null) - // A call appears before its command reaches the browser, so only later activity is its own. - const [baseline, setBaseline] = useState(() => startRun(runCallId)) - if (baseline.runCallId !== runCallId) { - setBaseline(startRun(runCallId)) + const lastCall = calls.at(-1) + const runCallId = lastCall?.callId ?? null + const latestPageId = useLastBrowserAgentPageId( + owner?.worktreeId ?? null, + owner?.sessionId ?? null + ) + const isLatestRun = useLatestBrowserCallId(owner) === runCallId && runCallId !== null + // Why: state, not a render-time Map read, so React Compiler's caches see the remembered page. + const [run, setRun] = useState(() => ({ runCallId, pageId: rememberedRunPageId(calls) })) + if (run.runCallId !== runCallId) { + setRun({ runCallId, pageId: rememberedRunPageId(calls) }) } - const ownActivityPageId = latest && latest.revision > baseline.revision ? latest.pageId : null - if (runCallId && !pageId && !baseline.rememberedPageId && ownActivityPageId) { - setBaseline({ ...baseline, rememberedPageId: ownActivityPageId }) + // Only the chat's newest browser run owns its agent's latest activity; older runs keep theirs. + const activityPageId = isLatestRun ? latestPageId : null + if (run.runCallId === runCallId && activityPageId && run.pageId !== activityPageId) { + setRun({ runCallId, pageId: activityPageId }) } - const rememberedPageId = baseline.rememberedPageId - const targetPageId = pageId ?? rememberedPageId ?? latest?.pageId ?? null + const rememberedPageId = run.runCallId === runCallId ? run.pageId : null + // Why: a run that can't name its page shows nothing rather than another run's page. + const targetPageId = commandPageId(lastCall) ?? rememberedPageId useEffect(() => { if (!runCallId || !rememberedPageId || pageIdByRunCallId.get(runCallId) === rememberedPageId) { return From d1bc6605c1862c08ddd7c9a5f99934171df5d6f4 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:39:16 +0000 Subject: [PATCH 11/17] fix(speech): correct near-miss spellings of dictionary terms, like Superbase to Supabase (#41703) * fix(speech): spell near misses of dictionary terms the term's way * fix(speech): ship the common-word list as a 2% Bloom filter to fit the phone page budget --- .../build-dictation-english-words.mjs | 115 ++++++++ resources/licenses/scowl/Copyright | 248 +++++++++++++++++ src/shared/dictation-dictionary.test.ts | 28 -- src/shared/dictation-dictionary.ts | 109 -------- src/shared/dictation-english-words.ts | 263 ++++++++++++++++++ src/shared/dictation-near-miss.ts | 103 +++++++ src/shared/dictation-term-spelling.test.ts | 82 ++++++ src/shared/dictation-term-spelling.ts | 134 +++++++++ src/shared/dictation-text-pipeline.ts | 5 +- src/shared/dictation-word-filter.ts | 31 +++ 10 files changed, 979 insertions(+), 139 deletions(-) create mode 100644 config/scripts/dictation/build-dictation-english-words.mjs create mode 100644 resources/licenses/scowl/Copyright delete mode 100644 src/shared/dictation-dictionary.test.ts create mode 100644 src/shared/dictation-english-words.ts create mode 100644 src/shared/dictation-near-miss.ts create mode 100644 src/shared/dictation-term-spelling.test.ts create mode 100644 src/shared/dictation-term-spelling.ts create mode 100644 src/shared/dictation-word-filter.ts diff --git a/config/scripts/dictation/build-dictation-english-words.mjs b/config/scripts/dictation/build-dictation-english-words.mjs new file mode 100644 index 00000000000..cf374a36cd9 --- /dev/null +++ b/config/scripts/dictation/build-dictation-english-words.mjs @@ -0,0 +1,115 @@ +// Regenerates src/shared/dictation-english-words.ts, the common-word filter dictation's near-miss matching +// checks before spelling a word as a dictionary term. Run: node config/scripts/dictation/build-dictation-english-words.mjs +import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { wordFilterSlots } from '../../../src/shared/dictation-word-filter.ts' + +const SOURCES = { + scowl: [ + 'https://downloads.sourceforge.net/project/wordlist/SCOWL/2020.12.07/scowl-2020.12.07.tar.gz', + '5587667caa20c4891390c2d42dbb4d5c4c3f41bee77af1457ece3ba23fb859cc' + ], + femaleFirst: [ + 'https://www2.census.gov/topics/genealogy/1990surnames/dist.female.first', + 'bd2f310fc4e5d5e5ea122c9d4342c9821145823118eb20db1647f305ec77b358' + ], + maleFirst: [ + 'https://www2.census.gov/topics/genealogy/1990surnames/dist.male.first', + '0a5078ef6effe3b483d15b0f7f95047662126c9bfb624ecd5e5b978fc0f2470b' + ], + last: [ + 'https://www2.census.gov/topics/genealogy/1990surnames/dist.all.last', + 'b0e2b3743ccbad641ca48b344c24cdebcd1d9a1f76dc6dbf05986f2919f0b4e1' + ] +} +// SCOWL sizes up to 60: everyday words plus the rarer ones ("bezel", "aslant") a term could sound like. +const SCOWL_MAX_SIZE = 60 +const LAST_NAMES = 1000 +const FALSE_POSITIVE_RATE = 0.02 +// Matching never looks up words shorter than this. +const MIN_WORD_LENGTH = 3 +const OUT = 'src/shared/dictation-english-words.ts' + +async function download([url, sha256]) { + const response = await fetch(url) + if (!response.ok) { + throw new Error(`${url}: HTTP ${response.status}`) + } + const bytes = Buffer.from(await response.arrayBuffer()) + const actual = createHash('sha256').update(bytes).digest('hex') + if (actual !== sha256) { + throw new Error(`${url}: sha256 ${actual}, expected ${sha256}`) + } + return bytes +} + +const work = mkdtempSync(join(tmpdir(), 'dictation-english-words-')) +try { + const words = new Set() + // Contractions add their stems ("doesn" of "doesn't"), since dictated text splits words at apostrophes. + const add = (entry) => { + for (const part of entry.split("'")) { + if (/^[A-Za-z]+$/.test(part) && part.length >= MIN_WORD_LENGTH) { + words.add(part.toLowerCase()) + } + } + } + writeFileSync(join(work, 'scowl.tar.gz'), await download(SOURCES.scowl)) + execFileSync('tar', ['-xzf', 'scowl.tar.gz'], { cwd: work }) + const final = join(work, 'scowl-2020.12.07', 'final') + for (const file of readdirSync(final)) { + const list = + /^(?:english|american|british|canadian|australian)-(?:words|upper|contractions)\.(\d+)$/.exec( + file + ) + if (list && Number(list[1]) <= SCOWL_MAX_SIZE) { + readFileSync(join(final, file), 'latin1').split('\n').forEach(add) + } + } + const names = async (source, limit) => + (await download(source)) + .toString('latin1') + .trim() + .split('\n') + .slice(0, limit) + .map((line) => line.split(/\s+/)[0]) + for (const name of [ + ...(await names(SOURCES.femaleFirst)), + ...(await names(SOURCES.maleFirst)), + ...(await names(SOURCES.last, LAST_NAMES)) + ]) { + add(name) + } + + const bits = Math.ceil((-words.size * Math.log(FALSE_POSITIVE_RATE)) / Math.LN2 ** 2 / 8) * 8 + const hashes = Math.round((bits / words.size) * Math.LN2) + const bytes = new Uint8Array(bits / 8) + for (const word of words) { + for (const slot of wordFilterSlots(word, bits, hashes)) { + bytes[slot >>> 3] |= 1 << (slot & 7) + } + } + // The whole SCOWL notice (Atkinson, WordNet, VarCon, Ispell and the rest) rides in every bundle that keeps legal comments. + const license = readFileSync('resources/licenses/scowl/Copyright', 'utf8').trimEnd().split('\n') + const notice = [ + `A filter of ${words.size} common English words and names: SCOWL 2020.12.07 words, capitalized words and`, + `contractions up to size ${SCOWL_MAX_SIZE} (english, american, british, canadian, australian), a-z only, lowercased,`, + `plus the 1990 US census first names and ${LAST_NAMES} most common last names (public domain). Generated by`, + 'config/scripts/dictation/build-dictation-english-words.mjs from these SCOWL notices:', + '', + ...license.map((line) => line.replaceAll('*/', '* /')) + ] + writeFileSync( + OUT, + `/*! @license\n${notice.map((line) => ` * ${line}`.trimEnd()).join('\n')}\n */\n` + + `import type { WordFilter } from './dictation-word-filter'\n\n` + + `export const COMMON_ENGLISH_WORDS: WordFilter = {\n bits: ${bits},\n hashes: ${hashes},\n` + + ` base64:\n '${Buffer.from(bytes).toString('base64')}'\n}\n` + ) + console.log(`${OUT}: ${words.size} words, ${bits} bits, ${hashes} hashes`) +} finally { + rmSync(work, { recursive: true, force: true }) +} diff --git a/resources/licenses/scowl/Copyright b/resources/licenses/scowl/Copyright new file mode 100644 index 00000000000..e49dc166490 --- /dev/null +++ b/resources/licenses/scowl/Copyright @@ -0,0 +1,248 @@ +The collective work is Copyright 2000-2018 by Kevin Atkinson as well +as any of the copyrights mentioned below: + + Copyright 2000-2018 by Kevin Atkinson + + Permission to use, copy, modify, distribute and sell these word + lists, the associated scripts, the output created from the scripts, + and its documentation for any purpose is hereby granted without fee, + provided that the above copyright notice appears in all copies and + that both that copyright notice and this permission notice appear in + supporting documentation. Kevin Atkinson makes no representations + about the suitability of this array for any purpose. It is provided + "as is" without express or implied warranty. + +Alan Beale also deserves special credit as he has, +in addition to providing the 12Dicts package and being a major +contributor to the ENABLE word list, given me an incredible amount of +feedback and created a number of special lists (those found in the +Supplement) in order to help improve the overall quality of SCOWL. + +The 10 level includes the 1000 most common English words (according to +the Moby (TM) Words II [MWords] package), a subset of the 1000 most +common words on the Internet (again, according to Moby Words II), and +frequently class 16 from Brian Kelk's "UK English Wordlist +with Frequency Classification". + +The MWords package was explicitly placed in the public domain: + + The Moby lexicon project is complete and has + been place into the public domain. Use, sell, + rework, excerpt and use in any way on any platform. + + Placing this material on internal or public servers is + also encouraged. The compiler is not aware of any + export restrictions so freely distribute world-wide. + + You can verify the public domain status by contacting + + Grady Ward + 3449 Martha Ct. + Arcata, CA 95521-4884 + + grady@netcom.com + grady@northcoast.com + +The "UK English Wordlist With Frequency Classification" is also in the +Public Domain: + + Date: Sat, 08 Jul 2000 20:27:21 +0100 + From: Brian Kelk + + > I was wondering what the copyright status of your "UK English + > Wordlist With Frequency Classification" word list as it seems to + > be lacking any copyright notice. + + There were many many sources in total, but any text marked + "copyright" was avoided. Locally-written documentation was one + source. An earlier version of the list resided in a filespace called + PUBLIC on the University mainframe, because it was considered public + domain. + + Date: Tue, 11 Jul 2000 19:31:34 +0100 + + > So are you saying your word list is also in the public domain? + + That is the intention. + +The 20 level includes frequency classes 7-15 from Brian's word list. + +The 35 level includes frequency classes 2-6 and words appearing in at +least 11 of 12 dictionaries as indicated in the 12Dicts package. All +words from the 12Dicts package have had likely inflections added via +my inflection database. + +The 12Dicts package and Supplement is in the Public Domain. + +The WordNet database, which was used in the creation of the +Inflections database, is under the following copyright: + + This software and database is being provided to you, the LICENSEE, + by Princeton University under the following license. By obtaining, + using and/or copying this software and database, you agree that you + have read, understood, and will comply with these terms and + conditions.: + + Permission to use, copy, modify and distribute this software and + database and its documentation for any purpose and without fee or + royalty is hereby granted, provided that you agree to comply with + the following copyright notice and statements, including the + disclaimer, and that the same appear on ALL copies of the software, + database and documentation, including modifications that you make + for internal use or for distribution. + + WordNet 1.6 Copyright 1997 by Princeton University. All rights + reserved. + + THIS SOFTWARE AND DATABASE IS PROVIDED "AS IS" AND PRINCETON + UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR + IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON + UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- + ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE + LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT INFRINGE ANY + THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. + + The name of Princeton University or Princeton may not be used in + advertising or publicity pertaining to distribution of the software + and/or database. Title to copyright in this software, database and + any associated documentation shall at all times remain with + Princeton University and LICENSEE agrees to preserve same. + +The 40 level includes words from Alan's 3esl list found in version 4.0 +of his 12dicts package. Like his other stuff the 3esl list is also in the +public domain. + +The 50 level includes Brian's frequency class 1, words appearing +in at least 5 of 12 of the dictionaries as indicated in the 12Dicts +package, and uppercase words in at least 4 of the previous 12 +dictionaries. A decent number of proper names is also included: The +top 1000 male, female, and Last names from the 1990 Census report; a +list of names sent to me by Alan Beale; and a few names that I added +myself. Finally a small list of abbreviations not commonly found in +other word lists is included. + +The name files form the Census report is a government document which I +don't think can be copyrighted. + +The file special-jargon.50 uses common.lst and word.lst from the +"Unofficial Jargon File Word Lists" which is derived from "The Jargon +File". All of which is in the Public Domain. This file also contain +a few extra UNIX terms which are found in the file "unix-terms" in the +special/ directory. + +The 55 level includes words from Alan's 2of4brif list found in version +4.0 of his 12dicts package. Like his other stuff the 2of4brif is also +in the public domain. + +The 60 level includes all words appearing in at least 2 of the 12 +dictionaries as indicated by the 12Dicts package. + +The 70 level includes Brian's frequency class 0 and the 74,550 common +dictionary words from the MWords package. The common dictionary words, +like those from the 12Dicts package, have had all likely inflections +added. The 70 level also included the 5desk list from version 4.0 of +the 12Dics package which is in the public domain. + +The 80 level includes the ENABLE word list, all the lists in the +ENABLE supplement package (except for ABLE), the "UK Advanced Cryptics +Dictionary" (UKACD), the list of signature words from the YAWL package, +and the 10,196 places list from the MWords package. + +The ENABLE package, mainted by M\Cooper , +is in the Public Domain: + + The ENABLE master word list, WORD.LST, is herewith formally released + into the Public Domain. Anyone is free to use it or distribute it in + any manner they see fit. No fee or registration is required for its + use nor are "contributions" solicited (if you feel you absolutely + must contribute something for your own peace of mind, the authors of + the ENABLE list ask that you make a donation on their behalf to your + favorite charity). This word list is our gift to the Scrabble + community, as an alternate to "official" word lists. Game designers + may feel free to incorporate the WORD.LST into their games. Please + mention the source and credit us as originators of the list. Note + that if you, as a game designer, use the WORD.LST in your product, + you may still copyright and protect your product, but you may *not* + legally copyright or in any way restrict redistribution of the + WORD.LST portion of your product. This *may* under law restrict your + rights to restrict your users' rights, but that is only fair. + +UKACD, by J Ross Beresford , is under the +following copyright: + + Copyright (c) J Ross Beresford 1993-1999. All Rights Reserved. + + The following restriction is placed on the use of this publication: + if The UK Advanced Cryptics Dictionary is used in a software package + or redistributed in any form, the copyright notice must be + prominently displayed and the text of this document must be included + verbatim. + + There are no other restrictions: I would like to see the list + distributed as widely as possible. + +The 95 level includes the 354,984 single words, 256,772 compound +words, 4,946 female names and the 3,897 male names, and 21,986 names +from the MWords package, ABLE.LST from the ENABLE Supplement, and some +additional words found in my part-of-speech database that were not +found anywhere else. + +Accent information was taken from UKACD. + +The VarCon package was used to create the American, British, Canadian, +and Australian word list. It is under the following copyright: + + Copyright 2000-2016 by Kevin Atkinson + + Permission to use, copy, modify, distribute and sell this array, the + associated software, and its documentation for any purpose is hereby + granted without fee, provided that the above copyright notice appears + in all copies and that both that copyright notice and this permission + notice appear in supporting documentation. Kevin Atkinson makes no + representations about the suitability of this array for any + purpose. It is provided "as is" without express or implied warranty. + + Copyright 2016 by Benjamin Titze + + Permission to use, copy, modify, distribute and sell this array, the + associated software, and its documentation for any purpose is hereby + granted without fee, provided that the above copyright notice appears + in all copies and that both that copyright notice and this permission + notice appear in supporting documentation. Benjamin Titze makes no + representations about the suitability of this array for any + purpose. It is provided "as is" without express or implied warranty. + + Since the original words lists come from the Ispell distribution: + + Copyright 1993, Geoff Kuenning, Granada Hills, CA + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. All modifications to the source code must be clearly marked as + such. Binary redistributions based on modified source code + must be clearly marked as modified versions in the documentation + and/or other materials provided with the distribution. + (clause 4 removed with permission from Geoff Kuenning) + 5. The name of Geoff Kuenning may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY GEOFF KUENNING AND CONTRIBUTORS ``AS IS'' AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL GEOFF KUENNING OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. diff --git a/src/shared/dictation-dictionary.test.ts b/src/shared/dictation-dictionary.test.ts deleted file mode 100644 index cb72fb380d3..00000000000 --- a/src/shared/dictation-dictionary.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createDictationDictionary } from './dictation-dictionary' - -const spell = (terms: Parameters[0], text: string): string => - createDictationDictionary(terms)!(text) - -describe('createDictationDictionary', () => { - // Parakeet v3's real output for the dev bench's code-term clips. - it('joins the words a model splits a code term into back into the term', () => { - const terms = [ - { term: 'useAudioCapture' }, - { term: 'usePcmWorklet' }, - { term: 'stt-worker.ts' }, - { term: 'numThreads' }, - { term: 'useMemo' }, - { term: 'onChange' } - ] - expect( - spell(terms, 'Rename use audio capture to use PCM worklet in the dictation controller.') - ).toBe('Rename useAudioCapture to usePcmWorklet in the dictation controller.') - expect(spell(terms, 'Open stt worker TS and set num threads to 4.')).toBe( - 'Open stt-worker.ts and set numThreads to 4.' - ) - expect(spell(terms, 'Wrap it in use memo and pass the on-change call back.')).toBe( - 'Wrap it in useMemo and pass the onChange call back.' - ) - }) -}) diff --git a/src/shared/dictation-dictionary.ts b/src/shared/dictation-dictionary.ts index ad448055809..44c7523f0f2 100644 --- a/src/shared/dictation-dictionary.ts +++ b/src/shared/dictation-dictionary.ts @@ -7,22 +7,6 @@ export type DictationTerm = { term: string; heardAs?: string; hint?: true } export const MAX_DICTATION_TERMS = 500 export const MAX_DICTATION_TERM_LENGTH = 100 -// Symbols that belong to a name ("C#", "C++", "@orca") count as part of a word, so a term never doubles them. -const WORD_RE = /[\p{L}\p{M}\p{N}#+@$&]+/gu -// Spaces, or one joiner as in "on-change" or "stt-worker.ts": what may sit between the words of one term. -const JOINING_GAP_RE = /^(?:\s+|[-_./])$/u -// A term's own leading or trailing joiners, as in ".NET", taken along when the text already has them. -const EDGE_JOINERS_RE = /^([-_./]*)[\s\S]*?([-_./]*)$/u -// Scripts written without spaces, where a phrase can only be found inside a longer run of letters. -const UNSPACED_SCRIPT_RE = - /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u -const MAX_WORDS_PER_TERM = 8 - -// "Use Audio Capture", "use-audio-capture" and "useAudioCapture" all key as "useaudiocapture". -function wordKey(text: string): string { - return (text.normalize('NFKC').toLowerCase().match(WORD_RE) ?? []).join('') -} - /** Well-formed, distinct entries only, trimmed and capped; undefined when the value isn't a list. */ export function normalizeDictationTerms(value: unknown): DictationTerm[] | undefined { if (!Array.isArray(value)) { @@ -69,99 +53,6 @@ export function dictationTermsFor( ] } -type Spelling = { term: string; lead: string; trail: string } - -function spelling(term: string): Spelling { - const [, lead = '', trail = ''] = EDGE_JOINERS_RE.exec(term) ?? [] - return { term, lead, trail } -} - -/** Rewrites words that key the same as a term (or its "heard as") to the term's spelling; null when there are none. */ -export function createDictationDictionary( - terms: readonly DictationTerm[] | undefined -): ((text: string) => string) | null { - const byKey = new Map() - const unspacedAliases: [heardAs: string, term: string][] = [] - const add = (key: string, term: string): void => { - if (key && !byKey.has(key)) { - byKey.set(key, spelling(term)) - } - } - // A "heard as" is what the user asked for, so it beats another term spelled the same. - for (const { term, heardAs } of terms ?? []) { - if (heardAs && UNSPACED_SCRIPT_RE.test(heardAs)) { - unspacedAliases.push([heardAs, term]) - } else if (heardAs) { - add(wordKey(heardAs), term) - } - } - for (const { term, hint } of terms ?? []) { - // A one-word repo name like "orca" would recase every "Orca"; only a name of several words joins. - if (!hint || (term.match(WORD_RE)?.length ?? 0) > 1) { - add(wordKey(term), term) - } - } - if (byKey.size === 0 && unspacedAliases.length === 0) { - return null - } - const longestKey = Math.max(0, ...[...byKey.keys()].map((key) => key.length)) - return (text) => { - for (const [alias, term] of unspacedAliases) { - text = text.split(alias).join(term) - } - return byKey.size > 0 ? replaceWordRuns(text, byKey, longestKey) : text - } -} - -// At each word, the longest run of joined words whose key is a term's becomes that term. -function replaceWordRuns(text: string, byKey: Map, longestKey: number): string { - const words = [...text.matchAll(WORD_RE)].map((word) => ({ - from: word.index, - to: word.index + word[0].length, - key: wordKey(word[0]) - })) - // joinsNext[i]: words i and i + 1 may belong to one term. - const joinsNext = words.map( - (word, i) => i + 1 < words.length && JOINING_GAP_RE.test(text.slice(word.to, words[i + 1].from)) - ) - let out = '' - let cursor = 0 - for (let start = 0; start < words.length;) { - let key = '' - let match: { end: number; spelling: Spelling } | null = null - for (let end = start; end < words.length && end - start < MAX_WORDS_PER_TERM; end++) { - if (end > start && !joinsNext[end - 1]) { - break - } - key += words[end].key - if (key.length > longestKey) { - break - } - const found = byKey.get(key) - if (found) { - match = { end, spelling: found } - } - } - if (!match) { - start++ - continue - } - const { term, lead, trail } = match.spelling - let from = words[start].from - let to = words[match.end].to - if (lead && from - lead.length >= cursor && text.slice(from - lead.length, from) === lead) { - from -= lead.length - } - if (trail && text.startsWith(trail, to)) { - to += trail.length - } - out += text.slice(cursor, from) + term - cursor = to - start = match.end + 1 - } - return out + text.slice(cursor) -} - /** The distinct spellings an engine that takes a context prompt is told to expect. */ export function dictationVocabulary(terms: readonly DictationTerm[] | undefined): string[] { return [...new Set((terms ?? []).map((entry) => entry.term))] diff --git a/src/shared/dictation-english-words.ts b/src/shared/dictation-english-words.ts new file mode 100644 index 00000000000..1cb6de43f84 --- /dev/null +++ b/src/shared/dictation-english-words.ts @@ -0,0 +1,263 @@ +/*! @license + * A filter of 89958 common English words and names: SCOWL 2020.12.07 words, capitalized words and + * contractions up to size 60 (english, american, british, canadian, australian), a-z only, lowercased, + * plus the 1990 US census first names and 1000 most common last names (public domain). Generated by + * config/scripts/dictation/build-dictation-english-words.mjs from these SCOWL notices: + * + * The collective work is Copyright 2000-2018 by Kevin Atkinson as well + * as any of the copyrights mentioned below: + * + * Copyright 2000-2018 by Kevin Atkinson + * + * Permission to use, copy, modify, distribute and sell these word + * lists, the associated scripts, the output created from the scripts, + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appears in all copies and + * that both that copyright notice and this permission notice appear in + * supporting documentation. Kevin Atkinson makes no representations + * about the suitability of this array for any purpose. It is provided + * "as is" without express or implied warranty. + * + * Alan Beale also deserves special credit as he has, + * in addition to providing the 12Dicts package and being a major + * contributor to the ENABLE word list, given me an incredible amount of + * feedback and created a number of special lists (those found in the + * Supplement) in order to help improve the overall quality of SCOWL. + * + * The 10 level includes the 1000 most common English words (according to + * the Moby (TM) Words II [MWords] package), a subset of the 1000 most + * common words on the Internet (again, according to Moby Words II), and + * frequently class 16 from Brian Kelk's "UK English Wordlist + * with Frequency Classification". + * + * The MWords package was explicitly placed in the public domain: + * + * The Moby lexicon project is complete and has + * been place into the public domain. Use, sell, + * rework, excerpt and use in any way on any platform. + * + * Placing this material on internal or public servers is + * also encouraged. The compiler is not aware of any + * export restrictions so freely distribute world-wide. + * + * You can verify the public domain status by contacting + * + * Grady Ward + * 3449 Martha Ct. + * Arcata, CA 95521-4884 + * + * grady@netcom.com + * grady@northcoast.com + * + * The "UK English Wordlist With Frequency Classification" is also in the + * Public Domain: + * + * Date: Sat, 08 Jul 2000 20:27:21 +0100 + * From: Brian Kelk + * + * > I was wondering what the copyright status of your "UK English + * > Wordlist With Frequency Classification" word list as it seems to + * > be lacking any copyright notice. + * + * There were many many sources in total, but any text marked + * "copyright" was avoided. Locally-written documentation was one + * source. An earlier version of the list resided in a filespace called + * PUBLIC on the University mainframe, because it was considered public + * domain. + * + * Date: Tue, 11 Jul 2000 19:31:34 +0100 + * + * > So are you saying your word list is also in the public domain? + * + * That is the intention. + * + * The 20 level includes frequency classes 7-15 from Brian's word list. + * + * The 35 level includes frequency classes 2-6 and words appearing in at + * least 11 of 12 dictionaries as indicated in the 12Dicts package. All + * words from the 12Dicts package have had likely inflections added via + * my inflection database. + * + * The 12Dicts package and Supplement is in the Public Domain. + * + * The WordNet database, which was used in the creation of the + * Inflections database, is under the following copyright: + * + * This software and database is being provided to you, the LICENSEE, + * by Princeton University under the following license. By obtaining, + * using and/or copying this software and database, you agree that you + * have read, understood, and will comply with these terms and + * conditions.: + * + * Permission to use, copy, modify and distribute this software and + * database and its documentation for any purpose and without fee or + * royalty is hereby granted, provided that you agree to comply with + * the following copyright notice and statements, including the + * disclaimer, and that the same appear on ALL copies of the software, + * database and documentation, including modifications that you make + * for internal use or for distribution. + * + * WordNet 1.6 Copyright 1997 by Princeton University. All rights + * reserved. + * + * THIS SOFTWARE AND DATABASE IS PROVIDED "AS IS" AND PRINCETON + * UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR + * IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON + * UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- + * ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE + * LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT INFRINGE ANY + * THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. + * + * The name of Princeton University or Princeton may not be used in + * advertising or publicity pertaining to distribution of the software + * and/or database. Title to copyright in this software, database and + * any associated documentation shall at all times remain with + * Princeton University and LICENSEE agrees to preserve same. + * + * The 40 level includes words from Alan's 3esl list found in version 4.0 + * of his 12dicts package. Like his other stuff the 3esl list is also in the + * public domain. + * + * The 50 level includes Brian's frequency class 1, words appearing + * in at least 5 of 12 of the dictionaries as indicated in the 12Dicts + * package, and uppercase words in at least 4 of the previous 12 + * dictionaries. A decent number of proper names is also included: The + * top 1000 male, female, and Last names from the 1990 Census report; a + * list of names sent to me by Alan Beale; and a few names that I added + * myself. Finally a small list of abbreviations not commonly found in + * other word lists is included. + * + * The name files form the Census report is a government document which I + * don't think can be copyrighted. + * + * The file special-jargon.50 uses common.lst and word.lst from the + * "Unofficial Jargon File Word Lists" which is derived from "The Jargon + * File". All of which is in the Public Domain. This file also contain + * a few extra UNIX terms which are found in the file "unix-terms" in the + * special/ directory. + * + * The 55 level includes words from Alan's 2of4brif list found in version + * 4.0 of his 12dicts package. Like his other stuff the 2of4brif is also + * in the public domain. + * + * The 60 level includes all words appearing in at least 2 of the 12 + * dictionaries as indicated by the 12Dicts package. + * + * The 70 level includes Brian's frequency class 0 and the 74,550 common + * dictionary words from the MWords package. The common dictionary words, + * like those from the 12Dicts package, have had all likely inflections + * added. The 70 level also included the 5desk list from version 4.0 of + * the 12Dics package which is in the public domain. + * + * The 80 level includes the ENABLE word list, all the lists in the + * ENABLE supplement package (except for ABLE), the "UK Advanced Cryptics + * Dictionary" (UKACD), the list of signature words from the YAWL package, + * and the 10,196 places list from the MWords package. + * + * The ENABLE package, mainted by M\Cooper , + * is in the Public Domain: + * + * The ENABLE master word list, WORD.LST, is herewith formally released + * into the Public Domain. Anyone is free to use it or distribute it in + * any manner they see fit. No fee or registration is required for its + * use nor are "contributions" solicited (if you feel you absolutely + * must contribute something for your own peace of mind, the authors of + * the ENABLE list ask that you make a donation on their behalf to your + * favorite charity). This word list is our gift to the Scrabble + * community, as an alternate to "official" word lists. Game designers + * may feel free to incorporate the WORD.LST into their games. Please + * mention the source and credit us as originators of the list. Note + * that if you, as a game designer, use the WORD.LST in your product, + * you may still copyright and protect your product, but you may *not* + * legally copyright or in any way restrict redistribution of the + * WORD.LST portion of your product. This *may* under law restrict your + * rights to restrict your users' rights, but that is only fair. + * + * UKACD, by J Ross Beresford , is under the + * following copyright: + * + * Copyright (c) J Ross Beresford 1993-1999. All Rights Reserved. + * + * The following restriction is placed on the use of this publication: + * if The UK Advanced Cryptics Dictionary is used in a software package + * or redistributed in any form, the copyright notice must be + * prominently displayed and the text of this document must be included + * verbatim. + * + * There are no other restrictions: I would like to see the list + * distributed as widely as possible. + * + * The 95 level includes the 354,984 single words, 256,772 compound + * words, 4,946 female names and the 3,897 male names, and 21,986 names + * from the MWords package, ABLE.LST from the ENABLE Supplement, and some + * additional words found in my part-of-speech database that were not + * found anywhere else. + * + * Accent information was taken from UKACD. + * + * The VarCon package was used to create the American, British, Canadian, + * and Australian word list. It is under the following copyright: + * + * Copyright 2000-2016 by Kevin Atkinson + * + * Permission to use, copy, modify, distribute and sell this array, the + * associated software, and its documentation for any purpose is hereby + * granted without fee, provided that the above copyright notice appears + * in all copies and that both that copyright notice and this permission + * notice appear in supporting documentation. Kevin Atkinson makes no + * representations about the suitability of this array for any + * purpose. It is provided "as is" without express or implied warranty. + * + * Copyright 2016 by Benjamin Titze + * + * Permission to use, copy, modify, distribute and sell this array, the + * associated software, and its documentation for any purpose is hereby + * granted without fee, provided that the above copyright notice appears + * in all copies and that both that copyright notice and this permission + * notice appear in supporting documentation. Benjamin Titze makes no + * representations about the suitability of this array for any + * purpose. It is provided "as is" without express or implied warranty. + * + * Since the original words lists come from the Ispell distribution: + * + * Copyright 1993, Geoff Kuenning, Granada Hills, CA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All modifications to the source code must be clearly marked as + * such. Binary redistributions based on modified source code + * must be clearly marked as modified versions in the documentation + * and/or other materials provided with the distribution. + * (clause 4 removed with permission from Geoff Kuenning) + * 5. The name of Geoff Kuenning may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY GEOFF KUENNING AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL GEOFF KUENNING OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ +import type { WordFilter } from './dictation-word-filter' + +export const COMMON_ENGLISH_WORDS: WordFilter = { + bits: 732472, + hashes: 6, + base64: + 'W1HV6wIOBvq0Ai7KuYtZwzCXynGQfFTMg2TNdRTGmq55mvOrlclJEMhBCV5onb4ySD7ZSZuwjFWx/98g/R1Opq087/GwtqjmMmmWOIRLrmcpoXIrhwcPsqx5TvucLOhzHVIcDVw4tjRxsoFHNvt3EcxzSWb81otRd4E9T1e7AqnG4542eCUJRvwT245zSvOz7jXuvHwZUVb5jBpbtK+u3vttCYXNs4gfQIR+OQtB7oHewU5tByRqNrKwUfEkdZDE+s0GtFJhJUtpyK4NUgcs+M+jpe8TVeOj9sjP8apcBqu2/axQh7MGhVlPa1yWFB6VwnaZUxXkZP8pT+texx1ZLMCIaDqYkr3uEnD/P+W6DRyPpINOsry7z7/Fvfx0aY24tNxiKd/j/jmvyTdahyvs1ALGwTWLqg/4bclq5cEAfWg1aAW632U1JoOmQYw/u6vR3uf22UJzZOX+pZtEc53//0iqxUNQHH55FkawRR+QC1ZayfftAHom7J/o+uOOyRDvqzINM6r+rUgqIDlhL38geQuOzq8Muv4TldrP77Tjx2wOtvUPFdwty9CkWjvQ4KaNPUU3vpP2TvOgK29nCRp26ckt6rRFxawHTbofz+NeOkkVna3Hv/Lkrsbzzo3F0epvCP4v91liiVltSutYIgV3NAOp4CC9bt2KLPcaSpe2Y7+H8TFz1dqhkwoGBca2CZm+l407iw3zLbrJll5Dybo6bc3Amo6Qg0CCbtNa2/mCEkeiD7AGi8bpZXQE7wtupxfZPX0DFDRCUzU99JXHRok+vWWZ++VQgZcuqdmYKnOYu2Whb0oBz0raVI+xP713ag8MSjwmjYSgk56+a32E/JqAfON8G5yoUzPhmzzNYfJc7VXmgIfYW56ZYod7Jen4GQTwyC6JZJ03Muoy1+KB1WNJvXcszri+yeBWu+YoX45bqeK/Wtcb/rTrPNV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jvZ9wMcaJhuTm8bRp7QZHtjvogOubNfec3+1wrCPEVdjFetEHZMDPOfNwvwmVKW9m/JropiR4vP7EMC0Hq5lSeHIZfkkWtvXxBEAfxJx10bLsTzXzKrX9FXnh56HKxqnSnGfedvUZq2uOc3JFeJ8hs3UDcfNE96W8UtLFNRmdhkUMug53vqfq2fnw/h7bS+5nAu/+yb6PdjBsS/uqdqlF1Gd2ikJ/A0GuXsy+sTshe8b+qYdXraCsAO+CInsWJsj8c4ph+n5g=' +} diff --git a/src/shared/dictation-near-miss.ts b/src/shared/dictation-near-miss.ts new file mode 100644 index 00000000000..d8268dacc41 --- /dev/null +++ b/src/shared/dictation-near-miss.ts @@ -0,0 +1,103 @@ +import { levenshtein } from './edit-distance' +import { createWordFilterLookup } from './dictation-word-filter' + +// Shorter terms sit too close to ordinary words ("Vite" and "vote", "Hono" and "honey"). +const MIN_TERM_KEY_LENGTH = 5 +const LATIN_LETTERS_RE = /^[a-z]+$/ + +// Only a dictionary with a term to near-miss loads the word filter; until then nothing near-misses. +let isCommonWord: ((word: string) => boolean) | undefined +let commonWordsLoad: Promise | undefined +function loadCommonWords(): void { + commonWordsLoad ??= import('./dictation-english-words.js').then( + ({ COMMON_ENGLISH_WORDS }) => { + isCommonWord = createWordFilterLookup(COMMON_ENGLISH_WORDS) + }, + () => { + commonWordsLoad = undefined + } + ) +} + +/** + * Roughly how a lowercase a-z key sounds: its consonants and where its vowels fall, after the spellings + * English writes one sound several ways ("ph", "c", "x") and the "r" non-rhotic accents drop ("super" as "supa"). + */ +function soundKey(key: string): string { + return key + .replace(/ph/g, 'f') + .replace(/c(?=[eiy])/g, 's') + .replace(/[cq]/g, 'k') + .replace(/x/g, 'ks') + .replace(/z/g, 's') + .replace(/(?<=[aeiouy])r(?![aeiouy])/g, '') + .replace(/[aeiouy]+/g, 'a') + .replace(/(.)\1+/g, '$1') +} + +type NearMissTerm = { key: string; consonants: number; term: T } + +/** For a text's word keys, the term each word is a near miss of, or null when none is or it may not be English. */ +export type NearMissMatcher = (keys: readonly string[]) => (T | undefined)[] | null + +/** + * Matches near misses of `terms` (by word key) in English text: text whose only language is English, or that + * reads as English; null when no term is long enough or English isn't among the known `languages`. + */ +export function createNearMissMatcher( + terms: readonly (readonly [key: string, term: T])[], + languages: readonly string[] | undefined +): NearMissMatcher | null { + const bySound = new Map[]>() + for (const [key, term] of terms) { + if (key.length >= MIN_TERM_KEY_LENGTH && LATIN_LETTERS_RE.test(key)) { + const sound = soundKey(key) + const consonants = sound.replaceAll('a', '').length + bySound.set(sound, [...(bySound.get(sound) ?? []), { key, consonants, term }]) + } + } + if (bySound.size === 0 || (languages && !languages.includes('en'))) { + return null + } + loadCommonWords() + const match = (key: string, isCommon: (word: string) => boolean): T | undefined => { + // An ordinary word or name is never a misheard term. + if (!LATIN_LETTERS_RE.test(key) || isCommon(key)) { + return undefined + } + let best: { term: T; distance: number } | undefined + for (const candidate of bySound.get(soundKey(key)) ?? []) { + // A term that is itself a word ("Drizzle") is heard right, so what sounds like it is another word. + if (isCommon(candidate.key)) { + continue + } + // Sounding the same and spelled close ("Versal" for "Vercel"), with fewer edits than the consonants + // that agree, since a term of few consonants ("Sonar") sounds like many words ("Sonner"). + const distance = levenshtein(key, candidate.key) + const allowed = Math.min( + Math.floor(Math.max(key.length, candidate.key.length) / 3), + candidate.consonants - 1 + ) + if (distance <= allowed && (!best || distance < best.distance)) { + best = { term: candidate.term, distance } + } + } + return best?.term + } + return (keys) => { + const isCommon = isCommonWord + const found = isCommon ? keys.map((key) => match(key, isCommon)) : [] + if (!isCommon || !found.some(Boolean)) { + return null + } + // A bilingual model ("zh-en") may have heard either language, so only an English-only one skips the check. + if (languages?.every((language) => language === 'en')) { + return found + } + // Short words ("I", "a") and the misheard words say little about the language; two thirds of the rest must + // be English, since other languages share a few words with it ("den", "part"). + const rest = keys.filter((key, index) => key.length > 2 && !found[index]) + const english = rest.filter(isCommon).length + return rest.length > 0 && english * 3 >= rest.length * 2 ? found : null + } +} diff --git a/src/shared/dictation-term-spelling.test.ts b/src/shared/dictation-term-spelling.test.ts new file mode 100644 index 00000000000..181ad84a45f --- /dev/null +++ b/src/shared/dictation-term-spelling.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from 'vitest' +import { createDictationDictionary } from './dictation-term-spelling' + +const spell = (terms: Parameters[0], text: string): string => + createDictationDictionary(terms)!(text) + +describe('createDictationDictionary', () => { + // Parakeet v3's real output for the dev bench's code-term clips. + it('joins the words a model splits a code term into back into the term', () => { + const terms = [ + { term: 'useAudioCapture' }, + { term: 'usePcmWorklet' }, + { term: 'stt-worker.ts' }, + { term: 'numThreads' }, + { term: 'useMemo' }, + { term: 'onChange' } + ] + expect( + spell(terms, 'Rename use audio capture to use PCM worklet in the dictation controller.') + ).toBe('Rename useAudioCapture to usePcmWorklet in the dictation controller.') + expect(spell(terms, 'Open stt worker TS and set num threads to 4.')).toBe( + 'Open stt-worker.ts and set numThreads to 4.' + ) + expect(spell(terms, 'Wrap it in use memo and pass the on-change call back.')).toBe( + 'Wrap it in useMemo and pass the onChange call back.' + ) + }) + + // Parakeet v3 and Whisper large-v3 turbo's real output for `say` clips of the terms. + it('spells a misheard word as the term when it sounds the same and is spelled close', async () => { + const clean = createDictationDictionary([ + { term: 'Supabase' }, + { term: 'Vercel' }, + { term: 'oxlint' }, + { term: 'Silero' } + ])! + await expect + .poll(() => clean('We moved the auth tables from Superbase to Postgres last week.'), { + timeout: 5000 + }) + .toBe('We moved the auth tables from Supabase to Postgres last week.') + expect(clean('Deploy the preview to Versal before the review.')).toBe( + 'Deploy the preview to Vercel before the review.' + ) + expect(clean('Run auxlint on the changed files before you push.')).toBe( + 'Run oxlint on the changed files before you push.' + ) + expect(clean('Parakeet and Celero both run inside the speech child.')).toBe( + 'Parakeet and Silero both run inside the speech child.' + ) + expect(clean("It doesn't work on Versal.")).toBe("It doesn't work on Vercel.") + }) + + it('leaves ordinary words, names, runs of words and other languages alone', async () => { + const clean = createDictationDictionary([ + { term: 'Bazel' }, + { term: 'Jupyter' }, + { term: 'Istio' }, + { term: 'Saleor' }, + { term: 'Vercel' } + ])! + await expect + .poll(() => clean('Deploy the preview to Versal before the review.'), { timeout: 5000 }) + .toBe('Deploy the preview to Vercel before the review.') + for (const text of [ + 'The vessel reached the harbor just after noon.', + 'The phone has a thin bezel.', + 'The planet Jupiter is bright tonight.', + 'It is too late to call him now.', + 'The ship was a very fast sailer.', + 'Despliega la vista previa en Versal antes de la revisión.' + ]) { + expect(clean(text)).toBe(text) + } + // A bilingual model's Chinese sentence is not English, even though English is one of its languages. + const bilingual = createDictationDictionary([{ term: 'Vercel' }], ['zh', 'en'])! + expect(bilingual('请在 Versal 上部署预览。')).toBe('请在 Versal 上部署预览。') + expect(bilingual('Deploy the preview to Versal before the review.')).toBe( + 'Deploy the preview to Vercel before the review.' + ) + }) +}) diff --git a/src/shared/dictation-term-spelling.ts b/src/shared/dictation-term-spelling.ts new file mode 100644 index 00000000000..7983e831197 --- /dev/null +++ b/src/shared/dictation-term-spelling.ts @@ -0,0 +1,134 @@ +import type { DictationTerm } from './dictation-dictionary' +import { createNearMissMatcher, type NearMissMatcher } from './dictation-near-miss' + +// Symbols that belong to a name ("C#", "C++", "@orca") count as part of a word, so a term never doubles them. +const WORD_RE = /[\p{L}\p{M}\p{N}#+@$&]+/gu +// Spaces, or one joiner as in "on-change" or "stt-worker.ts": what may sit between the words of one term. +const JOINING_GAP_RE = /^(?:\s+|[-_./])$/u +// A term's own leading or trailing joiners, as in ".NET", taken along when the text already has them. +const EDGE_JOINERS_RE = /^([-_./]*)[\s\S]*?([-_./]*)$/u +// Scripts written without spaces, where a phrase can only be found inside a longer run of letters. +const UNSPACED_SCRIPT_RE = + /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u +const MAX_WORDS_PER_TERM = 8 + +// "Use Audio Capture", "use-audio-capture" and "useAudioCapture" all key as "useaudiocapture". +function wordKey(text: string): string { + return (text.normalize('NFKC').toLowerCase().match(WORD_RE) ?? []).join('') +} + +type Spelling = { term: string; lead: string; trail: string } + +function spelling(term: string): Spelling { + const [, lead = '', trail = ''] = EDGE_JOINERS_RE.exec(term) ?? [] + return { term, lead, trail } +} + +/** + * Rewrites words that key the same as a term (or its "heard as") to the term's spelling, then, in English + * text (`languages` includes "en", or the text reads as English when they are unknown), single words that are + * near misses of a long, uncommon term ("Superbase" for "Supabase"); null when there are no terms. + */ +export function createDictationDictionary( + terms: readonly DictationTerm[] | undefined, + languages?: readonly string[] +): ((text: string) => string) | null { + const byKey = new Map() + const unspacedAliases: [heardAs: string, term: string][] = [] + const add = (key: string, term: string): void => { + if (key && !byKey.has(key)) { + byKey.set(key, spelling(term)) + } + } + // A "heard as" is what the user asked for, so it beats another term spelled the same. + for (const { term, heardAs } of terms ?? []) { + if (heardAs && UNSPACED_SCRIPT_RE.test(heardAs)) { + unspacedAliases.push([heardAs, term]) + } else if (heardAs) { + add(wordKey(heardAs), term) + } + } + // The repo name is a guess, not something the user typed, so it never takes a near miss. + const typedTerms: [key: string, spelling: Spelling][] = [] + for (const { term, hint } of terms ?? []) { + // A one-word repo name like "orca" would recase every "Orca"; only a name of several words joins. + if (!hint || (term.match(WORD_RE)?.length ?? 0) > 1) { + add(wordKey(term), term) + } + if (!hint) { + typedTerms.push([wordKey(term), spelling(term)]) + } + } + if (byKey.size === 0 && unspacedAliases.length === 0) { + return null + } + const nearMiss = createNearMissMatcher(typedTerms, languages) + const longestKey = Math.max(0, ...[...byKey.keys()].map((key) => key.length)) + return (text) => { + for (const [alias, term] of unspacedAliases) { + text = text.split(alias).join(term) + } + return byKey.size > 0 ? replaceWordRuns(text, byKey, longestKey, nearMiss) : text + } +} + +// At each word, the longest run of joined words whose key is a term's becomes that term; failing +// that, the word alone when it is a near miss of one. +function replaceWordRuns( + text: string, + byKey: Map, + longestKey: number, + nearMiss: NearMissMatcher | null +): string { + const words = [...text.matchAll(WORD_RE)].map((word) => ({ + from: word.index, + to: word.index + word[0].length, + key: wordKey(word[0]) + })) + // joinsNext[i]: words i and i + 1 may belong to one term. + const joinsNext = words.map( + (word, i) => i + 1 < words.length && JOINING_GAP_RE.test(text.slice(word.to, words[i + 1].from)) + ) + const nearMisses = nearMiss?.(words.map((word) => word.key)) ?? null + let out = '' + let cursor = 0 + for (let start = 0; start < words.length;) { + let key = '' + let match: { end: number; spelling: Spelling } | null = null + for (let end = start; end < words.length && end - start < MAX_WORDS_PER_TERM; end++) { + if (end > start && !joinsNext[end - 1]) { + break + } + key += words[end].key + if (key.length > longestKey) { + break + } + const found = byKey.get(key) + if (found) { + match = { end, spelling: found } + } + } + // Only a single word: in ordinary speech, words run together sound like terms ("is to" and "Istio"). + const nearMissOf = match ? undefined : nearMisses?.[start] + if (nearMissOf) { + match = { end: start, spelling: nearMissOf } + } + if (!match) { + start++ + continue + } + const { term, lead, trail } = match.spelling + let from = words[start].from + let to = words[match.end].to + if (lead && from - lead.length >= cursor && text.slice(from - lead.length, from) === lead) { + from -= lead.length + } + if (trail && text.startsWith(trail, to)) { + to += trail.length + } + out += text.slice(cursor, from) + term + cursor = to + start = match.end + 1 + } + return out + text.slice(cursor) +} diff --git a/src/shared/dictation-text-pipeline.ts b/src/shared/dictation-text-pipeline.ts index 7adc116ea53..5974be53291 100644 --- a/src/shared/dictation-text-pipeline.ts +++ b/src/shared/dictation-text-pipeline.ts @@ -1,4 +1,5 @@ -import { createDictationDictionary, type DictationTerm } from './dictation-dictionary' +import type { DictationTerm } from './dictation-dictionary' +import { createDictationDictionary } from './dictation-term-spelling' import { engineDictationLanguage } from './dictation-language' import { removeFillerWords } from './dictation-filler-words' import type { SpeechModelManifest, VoiceSettings } from './speech-types' @@ -41,7 +42,7 @@ export function createDictationTextPipeline( settings?.removeFillerWords === false ? null : (text: string) => removeFillerWords(text, languages, settings?.correctionWord) - const spellTerms = createDictationDictionary(terms) + const spellTerms = createDictationDictionary(terms, languages) if (!dropFillers || !spellTerms) { return dropFillers ?? spellTerms } diff --git a/src/shared/dictation-word-filter.ts b/src/shared/dictation-word-filter.ts new file mode 100644 index 00000000000..b75ca5b9c1c --- /dev/null +++ b/src/shared/dictation-word-filter.ts @@ -0,0 +1,31 @@ +/** + * A Bloom filter over lowercase a-z words: about 1 byte a word instead of the word, so a ~90k-word list fits + * in a phone's page bundle. A false "yes" (~2%) only makes dictation leave a word alone. + */ +export type WordFilter = { bits: number; hashes: number; base64: string } + +// Double hashing over two FNV-1a variants; the generator and the reader must agree on this. +export function wordFilterSlots(word: string, bits: number, hashes: number): number[] { + let first = 0x811c9dc5 + let second = 0x01000193 + for (let index = 0; index < word.length; index++) { + const code = word.charCodeAt(index) + first = Math.imul(first ^ code, 0x01000193) + second = Math.imul(second ^ code, 0x5bd1e995) ^ (second >>> 15) + } + const step = (second | 1) >>> 0 + const slots: number[] = [] + for (let index = 0; index < hashes; index++) { + slots.push(((first >>> 0) + index * step) % bits) + } + return slots +} + +/** Whether `word` may be in the filter: false is certain, true is right ~98% of the time. */ +export function createWordFilterLookup(filter: WordFilter): (word: string) => boolean { + const bytes = Uint8Array.from(atob(filter.base64), (char) => char.charCodeAt(0)) + return (word) => + wordFilterSlots(word, filter.bits, filter.hashes).every( + (slot) => (bytes[slot >>> 3] & (1 << (slot & 7))) !== 0 + ) +} From 560643500ce6f866f5cd77b5f0bf5e7ca27ce21a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 13 Nov 2026 01:41:32 -0800 Subject: [PATCH 12/17] Show remote files created while a restarted host's watcher starts (#41874) * fix(explorer): resync a recovered remote watch only after the host watcher is installed The contact-regained resync fired when the files.watch subscription was accepted, before the restarted host reported its watcher ready, so a file created in that gap was neither in the re-read listing nor reported by the watcher. The managed-orcad explorer recovery spec now waits for that resync before writing its probe file. * fix(explorer): re-read a recovered remote explorer once when its host watcher fails to install * test(explorer): the recovered watch resyncs after its ready signal * fix(explorer): re-read a remote watch on acceptance and again once its host watcher is installed A recovered watch re-reads when the restarted host accepts it, so outage changes still appear if the watcher install stays pending, and again on ready so writes made before the install appear. A first subscription also re-reads on ready, which replaces the trimmed-watch first-ready catch-up for remote targets. * test(explorer): the recovered explorer shows a file written while the host watcher installs Counting resyncs is not an install barrier: two recovery attempts can both re-read on acceptance before any watcher exists, and a ready that lands before acceptance re-reads once. Assert the user-visible result instead, which holds for any order of acceptance, install and the write. --- .../hooks/editor-runtime-file-watch.test.ts | 69 ++++++++++++++++--- .../src/hooks/editor-runtime-file-watch.ts | 52 +++++++------- ...itorExternalWatch-background-trim.test.tsx | 4 +- ...seEditorExternalWatch-shared-root.test.tsx | 4 +- ...EditorExternalWatch-subscriptions.test.tsx | 4 +- .../src/hooks/useEditorExternalWatch.ts | 36 +++++----- .../ssh-orcad-explorer-watch-recovery.spec.ts | 16 ++--- 7 files changed, 120 insertions(+), 65 deletions(-) diff --git a/src/renderer/src/hooks/editor-runtime-file-watch.test.ts b/src/renderer/src/hooks/editor-runtime-file-watch.test.ts index 5ead255db73..222467f143e 100644 --- a/src/renderer/src/hooks/editor-runtime-file-watch.test.ts +++ b/src/renderer/src/hooks/editor-runtime-file-watch.test.ts @@ -57,15 +57,40 @@ beforeEach(() => { runtime.subscribe.mockReset() }) +// The explorer's view of the host directory: whatever the last catch-up re-read saw. +function hostDirectory(): { + host: Set + shown: Set + onCatchUp: () => void +} { + const host = new Set() + const shown = new Set() + return { + host, + shown, + onCatchUp: () => { + shown.clear() + host.forEach((name) => shown.add(name)) + } + } +} +function streamCallback(call: number, index: 2 | 3): (error?: Error) => void { + const callback: unknown = runtime.subscribe.mock.calls[call]?.[index] + if (typeof callback !== 'function') { + throw new Error(`stream ${call} registered no ${index === 2 ? 'error' : 'ready'} callback`) + } + return (error) => callback(error) +} + describe('editor runtime file watch recovery', () => { it('disposes late old stream handles without replacing the current handle', async () => { const old = pendingSubscription() const fresh = pendingSubscription() const stopOld = vi.fn() const stopFresh = vi.fn() - const onPayload = vi.fn() + const onCatchUp = vi.fn() runtime.subscribe.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise) - const stop = subscribeEditorRuntimeFileWatch(target, onPayload, vi.fn()) + const stop = subscribeEditorRuntimeFileWatch(target, vi.fn(), vi.fn(), onCatchUp) runtime.contact.get('host-a')?.() fresh.resolve(stopFresh) await settle() @@ -73,13 +98,41 @@ describe('editor runtime file watch recovery', () => { await settle() expect(stopOld).toHaveBeenCalledOnce() expect(stopFresh).not.toHaveBeenCalled() - expect(onPayload).toHaveBeenCalledOnce() - expect(onPayload).toHaveBeenCalledWith({ - worktreePath: '/repo', - events: [{ kind: 'overflow', absolutePath: '/repo' }], - resync: true - }) + expect(onCatchUp).toHaveBeenCalledOnce() stop() expect(stopFresh).toHaveBeenCalledOnce() }) + + it('shows files written before the host watcher was installed', async () => { + const dir = hostDirectory() + runtime.subscribe.mockResolvedValue(vi.fn()) + subscribeEditorRuntimeFileWatch(target, vi.fn(), vi.fn(), dir.onCatchUp) + await settle() + dir.host.add('BEFORE_FIRST_READY.txt') + streamCallback(0, 3)() + expect([...dir.shown]).toEqual(['BEFORE_FIRST_READY.txt']) + + runtime.contact.get('host-a')?.() + dir.host.add('DURING_OUTAGE.txt') + await settle() + // Install can stay pending on the restarted host, so outage changes must not wait for it. + expect(dir.shown.has('DURING_OUTAGE.txt')).toBe(true) + dir.host.add('BEFORE_RECOVERED_READY.txt') + streamCallback(1, 3)() + expect(dir.shown.has('BEFORE_RECOVERED_READY.txt')).toBe(true) + }) + + it('re-reads once more when the recovered host watcher fails to install', async () => { + const dir = hostDirectory() + const onError = vi.fn() + runtime.subscribe.mockResolvedValue(vi.fn()) + subscribeEditorRuntimeFileWatch(target, vi.fn(), onError, dir.onCatchUp) + runtime.contact.get('host-a')?.() + await settle() + dir.host.add('BEFORE_INSTALL_FAILED.txt') + const failure = new Error('watcher capacity') + streamCallback(1, 2)(failure) + expect([...dir.shown]).toEqual(['BEFORE_INSTALL_FAILED.txt']) + expect(onError).toHaveBeenCalledWith(failure) + }) }) diff --git a/src/renderer/src/hooks/editor-runtime-file-watch.ts b/src/renderer/src/hooks/editor-runtime-file-watch.ts index 8ea1cf995dc..34c18b16274 100644 --- a/src/renderer/src/hooks/editor-runtime-file-watch.ts +++ b/src/renderer/src/hooks/editor-runtime-file-watch.ts @@ -9,14 +9,13 @@ export function subscribeEditorRuntimeFileWatch( target: EditorExternalWatchTarget & { runtimeEnvironmentId: string }, onPayload: (payload: FsChangedPayload) => void, onError: (error: unknown) => void, - onFirstReady?: () => void + onCatchUp: () => void ): () => void { - let readySeen = false let disposed = false let attempt = 0 let unsubscribe: (() => void) | null = null - const start = (resync: boolean): void => { + const start = (recovering: boolean): void => { if (disposed) { return } @@ -24,6 +23,26 @@ export function subscribeEditorRuntimeFileWatch( unsubscribe?.() unsubscribe = null const isCurrent = (): boolean => !disposed && attempt === currentAttempt + // Writes between a directory read and the host watcher's install reach neither, so every + // install re-reads. A recovery also re-reads on acceptance, since install can stay pending. + let acceptancePending = recovering + let installPending = true + const settleInstall = (catchUp: boolean): void => { + acceptancePending = false + if (!installPending) { + return + } + installPending = false + if (catchUp) { + onCatchUp() + } + } + const fail = (error: unknown): void => { + if (isCurrent()) { + settleInstall(recovering) + onError(error) + } + } void subscribeRuntimeFileChanges( { target: runtimeTargetForOwnerEnvironment(target.runtimeEnvironmentId), @@ -36,15 +55,10 @@ export function subscribeEditorRuntimeFileWatch( onPayload(payload) } }, - (error) => { - if (isCurrent()) { - onError(error) - } - }, + fail, () => { - if (isCurrent() && !readySeen) { - readySeen = true - onFirstReady?.() + if (isCurrent()) { + settleInstall(true) } } ) @@ -54,20 +68,12 @@ export function subscribeEditorRuntimeFileWatch( return } unsubscribe = stop - // A restored stream cannot replay file changes missed while contact was lost. - if (resync) { - onPayload({ - worktreePath: target.worktreePath, - events: [{ kind: 'overflow', absolutePath: target.worktreePath }], - resync: true - }) - } - }) - .catch((error: unknown) => { - if (isCurrent()) { - onError(error) + if (acceptancePending) { + acceptancePending = false + onCatchUp() } }) + .catch(fail) } const stopContact = subscribeRuntimeHostContactRegained(target.runtimeEnvironmentId, () => start(true) diff --git a/src/renderer/src/hooks/useEditorExternalWatch-background-trim.test.tsx b/src/renderer/src/hooks/useEditorExternalWatch-background-trim.test.tsx index 4b088dd29e7..25e516c45ff 100644 --- a/src/renderer/src/hooks/useEditorExternalWatch-background-trim.test.tsx +++ b/src/renderer/src/hooks/useEditorExternalWatch-background-trim.test.tsx @@ -50,9 +50,9 @@ vi.mock('./editor-runtime-file-watch', () => ({ _target: unknown, _onPayload: unknown, _onError: unknown, - onFirstReady?: () => void + onCatchUp?: () => void ) => { - harness.runtimeReady.current = onFirstReady + harness.runtimeReady.current = onCatchUp return harness.runtimeUnsubscribe } })) diff --git a/src/renderer/src/hooks/useEditorExternalWatch-shared-root.test.tsx b/src/renderer/src/hooks/useEditorExternalWatch-shared-root.test.tsx index 4e65ff951da..34567b4ef56 100644 --- a/src/renderer/src/hooks/useEditorExternalWatch-shared-root.test.tsx +++ b/src/renderer/src/hooks/useEditorExternalWatch-shared-root.test.tsx @@ -53,9 +53,9 @@ vi.mock('./editor-runtime-file-watch', () => ({ _target: unknown, _onPayload: unknown, _onError: unknown, - onFirstReady?: () => void + onCatchUp?: () => void ) => { - onFirstReady?.() + onCatchUp?.() return vi.fn() } })) diff --git a/src/renderer/src/hooks/useEditorExternalWatch-subscriptions.test.tsx b/src/renderer/src/hooks/useEditorExternalWatch-subscriptions.test.tsx index 0c6c1787cb8..8fd792b1898 100644 --- a/src/renderer/src/hooks/useEditorExternalWatch-subscriptions.test.tsx +++ b/src/renderer/src/hooks/useEditorExternalWatch-subscriptions.test.tsx @@ -172,9 +172,11 @@ describe('useEditorExternalWatch subscriptions', () => { { worktreePath: '/runtime/repo', events: [{ kind: 'overflow', absolutePath: '/runtime/repo' }], + connectionId: 'nested-ssh', resync: true }, - 'runtime-1' + 'runtime-1', + runtimeTarget() ) } finally { warning.mockRestore() diff --git a/src/renderer/src/hooks/useEditorExternalWatch.ts b/src/renderer/src/hooks/useEditorExternalWatch.ts index af7251b9c8c..0857454aced 100644 --- a/src/renderer/src/hooks/useEditorExternalWatch.ts +++ b/src/renderer/src/hooks/useEditorExternalWatch.ts @@ -78,22 +78,21 @@ export function useEditorExternalWatch(): void { targetsRef.current = nextTargets // Why: acquire before release so a root shared by an added and a removed target is never dropped in between. for (const target of added) { - // After reacquiring trimmed background watches, overflow-resync missed changes through the normal pipeline. - const resync = previousUnwatchedKeys.has(getEditorExternalWatchTargetKey(target)) - ? () => - fsChangedHandlerRef.current?.( - markWorktreeCatchUpPayload({ - worktreePath: target.worktreePath, - events: [{ kind: 'overflow', absolutePath: target.worktreePath }], - connectionId: target.connectionId, - resync: true - }), - target.runtimeEnvironmentId, - target - ) - : undefined + // Overflow-resync missed changes through the normal pipeline, scoped to this target. + const resync = (): void => { + fsChangedHandlerRef.current?.( + markWorktreeCatchUpPayload({ + worktreePath: target.worktreePath, + events: [{ kind: 'overflow', absolutePath: target.worktreePath }], + connectionId: target.connectionId, + resync: true + }), + target.runtimeEnvironmentId, + target + ) + } if (target.runtimeEnvironmentId) { - // Why: the host's ready event means its watcher is installed, so nothing after the resync is lost. + // Why: the remote watch decides when to resync (each host watcher install and each recovery). subscribeRuntimeTarget(target, remoteWatchUnsubsRef.current, fsChangedHandlerRef, resync) continue } @@ -101,7 +100,8 @@ export function useEditorExternalWatch(): void { // Provider disappearance must report watch failure without uncaught renderer rejection. warnExternalWatchFailure(target, err) }) - if (resync) { + // After reacquiring trimmed background watches, catch up on changes made while unwatched. + if (previousUnwatchedKeys.has(getEditorExternalWatchTargetKey(target))) { void installed.then(resync) } } @@ -168,7 +168,7 @@ function subscribeRuntimeTarget( target: EditorExternalWatchTarget, remoteWatchUnsubs: Map void>, fsChangedHandlerRef: { current: FsChangedHandler | null }, - onFirstReady: (() => void) | undefined + onCatchUp: () => void ): void { const runtimeEnvironmentId = target.runtimeEnvironmentId if (!runtimeEnvironmentId) { @@ -181,7 +181,7 @@ function subscribeRuntimeTarget( { ...target, runtimeEnvironmentId }, (payload) => fsChangedHandlerRef.current?.(payload, runtimeEnvironmentId), (error) => warnExternalWatchFailure(target, error), - onFirstReady + onCatchUp ) ) } diff --git a/tests/e2e/ssh-orcad-explorer-watch-recovery.spec.ts b/tests/e2e/ssh-orcad-explorer-watch-recovery.spec.ts index 75620958670..4a8ba2fc960 100644 --- a/tests/e2e/ssh-orcad-explorer-watch-recovery.spec.ts +++ b/tests/e2e/ssh-orcad-explorer-watch-recovery.spec.ts @@ -101,12 +101,8 @@ for (const workspace of ['worktree', 'folder'] as const) { '[managed-server-restart]', JSON.stringify({ before, after: serverPids(), workspace, worktreeId }) ) - const resumed = page.waitForEvent('console', { - predicate: (message) => - message.text().startsWith('[file-change-event]') && - message.text().includes('WATCH_RECOVERED.txt'), - timeout: 30_000 - }) + // Written while the restarted host may still be installing its watcher; the explorer must + // show it whichever of the watcher event or the post-install re-read reports it. execute(`printf 'watcher recovered\n' > '${rootPath}/WATCH_RECOVERED.txt'`) const created = await serverCall(page, environmentId, 'files.read', { worktree: `id:${worktreeId}`, @@ -114,15 +110,13 @@ for (const workspace of ['worktree', 'folder'] as const) { }) console.log('[host-post-restart-file]', created) expect(created).toContain('watcher recovered') - await resumed - console.log('[recovered-broker-event]', 'WATCH_RECOVERED.txt') + await expect(page.getByText('WATCH_RECOVERED.txt', { exact: true })).toBeVisible({ + timeout: 180_000 + }) await page.screenshot({ path: testInfo.outputPath('remote-explorer-observed.png') }) await expect(page.getByText('DURING_OUTAGE.txt', { exact: true })).toBeVisible({ timeout: 10_000 }) - await expect(page.getByText('WATCH_RECOVERED.txt', { exact: true })).toBeVisible({ - timeout: 10_000 - }) await page.screenshot({ path: testInfo.outputPath('remote-explorer-refreshed.png') }) }) }) From 37f8222979b95dade02d152b23e3e2e063aa0468 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 13 Nov 2026 01:43:44 -0800 Subject: [PATCH 13/17] test: remove low-value cleanup suites and generation replays (#41941) * test: remove cleanup wrappers and redundant settlement coverage * test: remove ineffective preview and generation failure replays --------- Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../scripts/ci/sharding/ci-shard-timings.json | 3 - .../failures/agent-failure-output.test.ts | 33 ------- ...essage-text-generation-branch-name.test.ts | 36 -------- ...nversation-name-generation-request.test.ts | 36 +------- ...-chat-github-routed-preview-store.test.tsx | 23 ----- .../workspace-cleanup-flat-list.test.tsx | 90 ------------------- ...anupDialog.stale-while-revalidate.test.tsx | 55 ------------ .../workspace-cleanup-facet-sort.test.ts | 26 ------ ...rkspace-cleanup-removal-settlement.test.ts | 57 ------------ 9 files changed, 1 insertion(+), 358 deletions(-) delete mode 100644 src/renderer/src/components/workspace-cleanup/candidate-list/workspace-cleanup-flat-list.test.tsx delete mode 100644 src/renderer/src/components/workspace-cleanup/query/workspace-cleanup-facet-sort.test.ts delete mode 100644 src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-removal-settlement.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index a2b1f69743b..a3d35790db0 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -5391,10 +5391,7 @@ "src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-background-removal-late-settlement.test.ts": 1880, "src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-background-removal.test.ts": 283, "src/renderer/src/components/workspace-cleanup/candidate-evidence/workspace-cleanup-host-index.test.ts": 341, - "src/renderer/src/components/workspace-cleanup/query/workspace-cleanup-facet-sort.test.ts": 264, - "src/renderer/src/components/workspace-cleanup/candidate-list/workspace-cleanup-flat-list.test.tsx": 2594, "src/renderer/src/components/workspace-cleanup/removal/workspace-cleanup-removal-candidates.test.ts": 206, - "src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-removal-settlement.test.ts": 203, "src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-removal-timeout-recovery.test.ts": 1817, "src/renderer/src/components/workspace-emoji/WorkspaceEmojiPickerButton.test.tsx": 1086, "src/renderer/src/components/workspace-emoji/WorkspaceEmojiPickerPanel.test.tsx": 763, diff --git a/src/main/text-generation/failures/agent-failure-output.test.ts b/src/main/text-generation/failures/agent-failure-output.test.ts index b4c24617d9e..4a17870e634 100644 --- a/src/main/text-generation/failures/agent-failure-output.test.ts +++ b/src/main/text-generation/failures/agent-failure-output.test.ts @@ -8,15 +8,6 @@ const ESC = String.fromCharCode(27) const BEL = String.fromCharCode(7) describe('captureAgentGenerationFailureOutput', () => { - it('returns null when both streams are blank', () => { - expect(captureAgentGenerationFailureOutput('Pi', 1, ' \n', '\t')).toBeNull() - }) - - it('keeps short streams verbatim', () => { - const capture = captureAgentGenerationFailureOutput('Pi', 1, 'out', 'err') - expect(capture).toEqual({ label: 'Pi', exitCode: 1, stdout: 'out', stderr: 'err' }) - }) - it('bounds an oversized stream to its head and tail with an omission marker', () => { const oversized = `${'h'.repeat(20_000)}${'m'.repeat(40_000)}${'t'.repeat(50_000)}` const capture = captureAgentGenerationFailureOutput('Pi', 1, '', oversized) @@ -29,30 +20,6 @@ describe('captureAgentGenerationFailureOutput', () => { }) describe('formatAgentGenerationFailureOutputForDisplay', () => { - it('renders a header plus the streams that had content, stderr first', () => { - const text = formatAgentGenerationFailureOutputForDisplay({ - label: 'Pi', - exitCode: 1, - stdout: 'partial result', - stderr: 'No API key found for github-copilot.' - }) - expect(text).toBe( - 'Pi exited with code 1.\n\n[stderr]\nNo API key found for github-copilot.\n\n[stdout]\npartial result' - ) - }) - - it('omits a blank stream section and reports an unknown exit code', () => { - const text = formatAgentGenerationFailureOutputForDisplay({ - label: 'Claude', - exitCode: null, - stdout: 'Not logged in · Please run /login', - stderr: ' ' - }) - expect(text).toBe( - 'Claude exited with code unknown.\n\n[stdout]\nNot logged in · Please run /login' - ) - }) - it('strips ANSI, OSC, and bidi-override characters while keeping line structure', () => { const text = formatAgentGenerationFailureOutputForDisplay({ label: 'Pi', diff --git a/src/main/text-generation/requests/commit-message-text-generation-branch-name.test.ts b/src/main/text-generation/requests/commit-message-text-generation-branch-name.test.ts index 52e3c8d6945..d50ffbe63ad 100644 --- a/src/main/text-generation/requests/commit-message-text-generation-branch-name.test.ts +++ b/src/main/text-generation/requests/commit-message-text-generation-branch-name.test.ts @@ -1,43 +1,7 @@ -import { realKimiOccupiedOutput } from '../../../shared/__fixtures__/kimi-generation-source-shaped' import { describe, expect, it } from 'vitest' import { generateBranchNameFromContext } from '../commit-message-text-generation' describe('generateBranchNameFromContext', () => { - it.each(['pi', 'kimi'] as const)('%s failure diagnostics', async (agentId) => { - const result = await generateBranchNameFromContext( - { firstPrompt: 'Fix login flow' }, - { - agentId, - model: agentId === 'kimi' ? 'default' : 'github-copilot/gpt-5.5' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async () => ({ - stdout: agentId === 'kimi' ? realKimiOccupiedOutput : 'partial', - stderr: 'No API key found for github-copilot.', - exitCode: agentId === 'kimi' ? 4 : 1, - timedOut: false - }) - } - ) - - expect(result.success).toBe(false) - if (result.success) { - throw new Error('expected a failure result') - } - if (agentId === 'kimi') { - expect(result.error).toMatch(/Kimi.*active.*Stop.*exit.*try again/) - } - expect(result.failureOutput).toEqual({ - label: agentId === 'kimi' ? 'Kimi' : 'Pi', - exitCode: agentId === 'kimi' ? 4 : 1, - stdout: agentId === 'kimi' ? realKimiOccupiedOutput : 'partial', - stderr: 'No API key found for github-copilot.' - }) - }) - it('reruns Copilot once on its default model when the plan hides the saved model', async () => { const calls: string[][] = [] const result = await generateBranchNameFromContext( diff --git a/src/main/text-generation/requests/conversation-name-generation-request.test.ts b/src/main/text-generation/requests/conversation-name-generation-request.test.ts index 8fbdf1bf3f9..ee6ce11608a 100644 --- a/src/main/text-generation/requests/conversation-name-generation-request.test.ts +++ b/src/main/text-generation/requests/conversation-name-generation-request.test.ts @@ -1,10 +1,5 @@ -import { realKimiOccupiedOutput } from '../../../shared/__fixtures__/kimi-generation-source-shaped' -import { describe, expect, it, vi } from 'vitest' -import { createMockDiscoveryChild } from '../execution/commit-message-text-generation-test-harness' +import { describe, expect, it } from 'vitest' import { generateConversationNameFromContext } from '../commit-message-text-generation' -import { cancelLocalGeneration } from '../execution/source-control-generation-lanes' -import { generateConversationName } from './conversation-name-generation-request' -import type { SpawnedSourceControlAgentProcess } from '../source-control-text-generation-types' describe('generateConversationName', () => { it.each([ @@ -76,33 +71,4 @@ describe('generateConversationName', () => { error: 'Generated chat name was empty after sanitization.' }) }) - - it.each(['cancel', 'occupied'])('handles a local %s outcome', async (outcome) => { - const child = createMockDiscoveryChild() - const spawnAgent = vi.fn(() => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The test child implements every process member the generation lane reads. - return child as unknown as SpawnedSourceControlAgentProcess - }) - const pending = generateConversationName({ - context: { firstPrompt: 'Fix login' }, - params: - outcome === 'cancel' - ? { agentId: 'custom', model: '', customAgentCommand: 'agent' } - : { agentId: 'kimi', model: 'default' }, - target: { kind: 'local', cwd: '/repo' }, - spawnAgent - }) - await vi.waitFor(() => expect(spawnAgent).toHaveBeenCalledOnce()) - if (outcome === 'occupied') { - child.stdout.emit('data', Buffer.from(realKimiOccupiedOutput)) - child.emit('close', 4) - expect(await pending).toMatchObject({ - success: false, - error: expect.stringMatching(/Kimi.*active.*Stop.*exit.*try again/) - }) - return - } - cancelLocalGeneration('conversation-name', '/repo') - expect(await pending).toMatchObject({ success: false, canceled: true }) - }) }) diff --git a/src/renderer/src/components/native-chat/links/previews/native-chat-github-routed-preview-store.test.tsx b/src/renderer/src/components/native-chat/links/previews/native-chat-github-routed-preview-store.test.tsx index 3c5b69f1614..c3c746bef90 100644 --- a/src/renderer/src/components/native-chat/links/previews/native-chat-github-routed-preview-store.test.tsx +++ b/src/renderer/src/components/native-chat/links/previews/native-chat-github-routed-preview-store.test.tsx @@ -83,29 +83,6 @@ afterEach(() => { vi.unstubAllGlobals() }) -it('shows the pending response after an unrelated store update', async () => { - const response = Promise.withResolvers() - const started = Promise.withResolvers() - mocks.endpoint.mockImplementationOnce(() => { - started.resolve() - return response.promise - }) - const link = parseGitHubIssueOrPRLink('https://github.com/acme/repo-2/pull/42')! - await act(async () => { - root.render( - - ) - }) - await started.promise - await act(async () => { - mocks.store.setState({ tick: 1 }) - }) - await act(async () => { - response.resolve(preview(42, 'Pending preview completed')) - }) - expect(container.textContent).toContain('Pending preview completed') -}) - it('shows the new route response and ignores a late response from the removed route', async () => { const oldResponse = Promise.withResolvers() const newResponse = Promise.withResolvers() diff --git a/src/renderer/src/components/workspace-cleanup/candidate-list/workspace-cleanup-flat-list.test.tsx b/src/renderer/src/components/workspace-cleanup/candidate-list/workspace-cleanup-flat-list.test.tsx deleted file mode 100644 index b5f2c6b64af..00000000000 --- a/src/renderer/src/components/workspace-cleanup/candidate-list/workspace-cleanup-flat-list.test.tsx +++ /dev/null @@ -1,90 +0,0 @@ -// @vitest-environment happy-dom -import type { ReactNode } from 'react' -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { CandidateRow } from './workspace-cleanup-candidate-row' -import { WorkspaceCleanupCandidateList } from './workspace-cleanup-candidate-list' -import { makeNamedFacets } from '../query/workspace-cleanup-facet.test.fixture' - -import type { WorkspaceCleanupFacets } from '../query/workspace-cleanup-facets' - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: ReactNode }) => <>{children}, - TooltipContent: () => null, - TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children} -})) - -let root: Root | null = null -let container: HTMLDivElement | null = null - -function renderRows( - rows: readonly WorkspaceCleanupFacets[], - onForgetLocally?: (candidate: WorkspaceCleanupFacets['candidate']) => void -): void { - act(() => - root?.render( - row.worktreeId} - scrollElement={null} - renderRow={(row, index) => ( - - )} - /> - ) - ) -} - -describe('workspace cleanup flat list', () => { - beforeEach(() => { - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - }) - - afterEach(() => { - if (root) { - act(() => root?.unmount()) - } - container?.remove() - root = null - container = null - }) - - it('offers local removal for a disconnected SSH row without making it selectable', () => { - const onForgetLocally = vi.fn() - const disconnected = makeNamedFacets('disconnected', { - candidate: { blockers: ['ssh-disconnected'] } - }) - - renderRows([disconnected], onForgetLocally) - - expect(container?.querySelector('[aria-label^="Select disconnected"]')).toBeNull() - const forgetButton = container?.querySelector('[aria-label="Remove from Orca"]') - expect(forgetButton).not.toBeNull() - act(() => forgetButton?.click()) - expect(onForgetLocally).toHaveBeenCalledWith(disconnected.candidate) - }) -}) diff --git a/src/renderer/src/components/workspace-cleanup/dialog/WorkspaceCleanupDialog.stale-while-revalidate.test.tsx b/src/renderer/src/components/workspace-cleanup/dialog/WorkspaceCleanupDialog.stale-while-revalidate.test.tsx index b8bd91fbbf0..4453a68a0b9 100644 --- a/src/renderer/src/components/workspace-cleanup/dialog/WorkspaceCleanupDialog.stale-while-revalidate.test.tsx +++ b/src/renderer/src/components/workspace-cleanup/dialog/WorkspaceCleanupDialog.stale-while-revalidate.test.tsx @@ -182,21 +182,6 @@ function cachedFleet(): WorkspaceCleanupScanResult { } } -function progressTick( - rig: ScanRig, - progress: Partial & Pick -): void { - rig.progressCallbacks.at(-1)?.({ - scanId: 'scan-1', - scannedAt: NOW, - scannedWorktreeCount: progress.candidates.length, - totalWorktreeCount: 3, - errors: [], - candidateMode: 'append', - ...progress - }) -} - describe('WorkspaceCleanupDialog stale-while-revalidate', () => { beforeEach(() => { globalThis.IS_REACT_ACT_ENVIRONMENT = true @@ -299,46 +284,6 @@ describe('WorkspaceCleanupDialog stale-while-revalidate', () => { expect(rowCheckbox('alpha')?.getAttribute('aria-checked')).toBe('false') }) - it('adopts the in-flight scan on reopen instead of starting a duplicate', async () => { - const rig = installApi(cachedFleet()) - await renderDialog() - await openDialog() - expect(rig.scan).toHaveBeenCalledTimes(1) - - progressTick(rig, { - candidates: [makeCandidate({ worktreeId: 'repo1::/tmp/gamma', displayName: 'gamma' })], - scannedWorktreeCount: 1 - }) - await flush() - - await act(async () => { - holders.store.setState({ activeModal: null }) - }) - await openDialog() - expect(rig.scan).toHaveBeenCalledTimes(1) - - progressTick(rig, { - candidates: [makeCandidate({ worktreeId: 'repo1::/tmp/delta', displayName: 'delta' })], - scannedWorktreeCount: 2 - }) - await flush() - await act(async () => { - rig.resolvers.at(-1)?.({ - scannedAt: NOW, - candidates: [ - ...cachedFleet().candidates, - makeCandidate({ worktreeId: 'repo1::/tmp/gamma', displayName: 'gamma' }), - makeCandidate({ worktreeId: 'repo1::/tmp/delta', displayName: 'delta' }) - ], - errors: [] - }) - }) - await flush() - - expect(rig.scan).toHaveBeenCalledTimes(1) - expect(rowNames()).toEqual(expect.arrayContaining(['alpha', 'beta', 'gamma', 'delta'])) - }) - it('keeps selections across a refresh and surfaces vanished selections', async () => { const rig = installApi(cachedFleet()) await renderDialog() diff --git a/src/renderer/src/components/workspace-cleanup/query/workspace-cleanup-facet-sort.test.ts b/src/renderer/src/components/workspace-cleanup/query/workspace-cleanup-facet-sort.test.ts deleted file mode 100644 index 30d335b3083..00000000000 --- a/src/renderer/src/components/workspace-cleanup/query/workspace-cleanup-facet-sort.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { makeNamedFacets } from './workspace-cleanup-facet.test.fixture' -import { sortWorkspaceCleanupFacets } from './workspace-cleanup-facet-sort' -import type { WorkspaceCleanupSortField } from '../../../../../shared/workspace-cleanup/workspace-cleanup-filter-model' - -function names( - rows: ReturnType[], - field: WorkspaceCleanupSortField, - direction: 'asc' | 'desc' -): string[] { - return sortWorkspaceCleanupFacets(rows, { field, direction }).map((row) => row.displayName) -} - -describe('ranked fields', () => { - it('breaks equal blocker counts by the worst blocker', () => { - const rows = [ - makeNamedFacets('softest', { - candidate: { blockers: ['git-status-error'] } - }), - makeNamedFacets('hardest', { - candidate: { blockers: ['main-worktree'] } - }) - ] - expect(names(rows, 'blocker-count', 'desc')).toEqual(['hardest', 'softest']) - }) -}) diff --git a/src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-removal-settlement.test.ts b/src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-removal-settlement.test.ts deleted file mode 100644 index 57d428bd218..00000000000 --- a/src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-removal-settlement.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - trackWorkspaceCleanupLateSettlement, - type WorkspaceCleanupRemovalSettlement -} from './workspace-cleanup-removal-settlement' -import { makeCandidate } from '../../query/workspace-cleanup-candidate-state.test-fixture' - -describe('workspace cleanup late settlement tracking', () => { - it('detaches the batch callback and reports with a compact candidate identity', async () => { - const candidate = makeCandidate() - let resolveSettlement: (settlement: WorkspaceCleanupRemovalSettlement) => void = () => {} - const settlement = new Promise((resolve) => { - resolveSettlement = resolve - }) - const reconcileBeforeBatchResult = vi.fn() - const reportAfterBatchResult = vi.fn() - const tracker = trackWorkspaceCleanupLateSettlement( - settlement, - candidate, - reconcileBeforeBatchResult - ) - - // The compact copy keeps the host facts a late failure needs to name its row. - expect(tracker.candidate).toEqual({ - worktreeId: candidate.worktreeId, - connectionId: candidate.connectionId, - displayName: candidate.displayName - }) - expect(tracker.candidate).not.toBe(candidate) - tracker.detach(reportAfterBatchResult) - resolveSettlement({ status: 'rejected', error: new Error('remote removal failed') }) - await settlement - await Promise.resolve() - - expect(reconcileBeforeBatchResult).not.toHaveBeenCalled() - expect(reportAfterBatchResult).toHaveBeenCalledWith( - { - worktreeId: candidate.worktreeId, - connectionId: candidate.connectionId, - displayName: candidate.displayName - }, - { - removedIds: [], - removedIdentities: [], - failures: [ - { - worktreeId: candidate.worktreeId, - executionHostId: 'local', - displayName: candidate.displayName, - message: 'remote removal failed' - } - ] - } - ) - expect(reportAfterBatchResult.mock.calls[0][0]).not.toBe(candidate) - }) -}) From d1d338cd02596a84061ede488295fea0cf0ccb70 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 13 Nov 2026 01:52:46 -0800 Subject: [PATCH 14/17] test: remove generation replays and cache counter cases (#41944) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../scripts/ci/sharding/ci-shard-timings.json | 1 - .../integration-state-file-cache.test.ts | 60 ------------ .../integration-token-file-cache.test.ts | 19 ---- .../commit-message-agent-environment.test.ts | 16 ---- ...e-text-generation-local-subprocess.test.ts | 33 +------ ...e-text-generation-remote-execution.test.ts | 40 -------- .../source-control-agent-cli-path.test.ts | 3 +- .../source-control-agent-launch.test.ts | 93 ------------------- 8 files changed, 2 insertions(+), 263 deletions(-) delete mode 100644 src/main/text-generation/execution/source-control-agent-launch.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index a3d35790db0..38ac05a3f8c 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -3903,7 +3903,6 @@ "src/main/text-generation/requests/jira-issue-summary-requests.test.ts": 276, "src/main/text-generation/failures/kimi-generation-failure.test.ts": 151, "src/main/text-generation/execution/source-control-agent-cli-path.test.ts": 615, - "src/main/text-generation/execution/source-control-agent-launch.test.ts": 1879, "src/main/text-generation/execution/source-control-local-process.test.ts": 1834, "src/main/text-generation/prompts/source-control-omp-prompt-file.test.ts": 6676, "src/main/text-generation/execution/source-control-wsl-launch.test.ts": 482, diff --git a/src/main/credentials/integration-state-file-cache.test.ts b/src/main/credentials/integration-state-file-cache.test.ts index 92673a31041..a2bb7cee926 100644 --- a/src/main/credentials/integration-state-file-cache.test.ts +++ b/src/main/credentials/integration-state-file-cache.test.ts @@ -28,23 +28,6 @@ afterEach(() => { }) describe('createIntegrationStateFileCache', () => { - it('memoizes while the file is unchanged', () => { - const path = tempFile() - writeFileSync(path, '1') - let reads = 0 - const cache = createIntegrationStateFileCache({ - filePath: () => path, - readFromDisk: () => { - reads += 1 - return { reads } - } - }) - - expect(cache.get()).toEqual({ reads: 1 }) - expect(cache.get()).toEqual({ reads: 1 }) - expect(reads).toBe(1) - }) - it('notices a same-size atomic replacement with the original modification time', () => { const path = tempFile() writeFileSync(path, 'old') @@ -63,18 +46,6 @@ describe('createIntegrationStateFileCache', () => { expect(cache.get()).toBe('new') }) - it('distinguishes backing paths when both files are initially absent', () => { - let path = tempFile() - let reads = 0 - const cache = createIntegrationStateFileCache({ - filePath: () => path, - readFromDisk: () => ++reads - }) - expect(cache.get()).toBe(1) - path = join(dir, 'another.json') - expect(cache.get()).toBe(2) - }) - it('reloads when a file appears after an absent first read', () => { const path = tempFile() const cache = createIntegrationStateFileCache({ @@ -101,37 +72,6 @@ describe('createIntegrationStateFileCache', () => { expect(cache.get()).toEqual({ present: false }) }) - - it('recovers when another process writes between the stamp and the read', () => { - const path = tempFile() - writeFileSync(path, 'v1') - let reads = 0 - let writeDuringRead = false - const cache = createIntegrationStateFileCache({ - filePath: () => path, - readFromDisk: () => { - reads += 1 - if (writeDuringRead) { - writeDuringRead = false - writeFileSync(path, 'theirs') - } - return { body: readBody(path) } - } - }) - expect(cache.get()).toEqual({ body: 'v1' }) - - writeFileSync(path, 'ours') - cache.invalidate() - writeDuringRead = true - - // Content read after a concurrent write still carries the earlier stamp, forcing one more read. - expect(cache.get()).toEqual({ body: 'theirs' }) - expect(cache.get()).toEqual({ body: 'theirs' }) - expect(reads).toBe(3) - - expect(cache.get()).toEqual({ body: 'theirs' }) - expect(reads).toBe(3) - }) }) function readBody(path: string): string { diff --git a/src/main/credentials/integration-token-file-cache.test.ts b/src/main/credentials/integration-token-file-cache.test.ts index f574052cc79..143b6b03b26 100644 --- a/src/main/credentials/integration-token-file-cache.test.ts +++ b/src/main/credentials/integration-token-file-cache.test.ts @@ -29,25 +29,6 @@ function createCache() { } describe('integration token file cache', () => { - it('bounds errors, keeps status lazy, and permits retry after keychain approval', () => { - const cache = createCache() - decrypt.mockImplementation(() => { - throw new Error('Keychain access denied') - }) - for (let index = 0; index < 132; index += 1) { - const id = `credential-${index}` - writeFileSync(filePath(id), Buffer.from([0x76, 0x31, 0x30, 0xff, 0xfe])) - expect(() => cache.read(id)).toThrow('Could not decrypt') - } - expect(cache.error('credential-131')).toContain('Could not decrypt') - expect(cache.error('credential-0')).toBeUndefined() - expect(cache.has('credential-131')).toBe(true) - expect(decrypt).toHaveBeenCalledTimes(132) - decrypt.mockReturnValue('approved-token') - expect(cache.read('credential-131')).toBe('approved-token') - expect(cache.error('credential-131')).toBeUndefined() - }) - it('clears an old decryption error after external replacement without prompting on status', () => { const cache = createCache() writeFileSync(filePath('site'), Buffer.from([0xff, 0xfe])) diff --git a/src/main/text-generation/execution/commit-message-agent-environment.test.ts b/src/main/text-generation/execution/commit-message-agent-environment.test.ts index f90cc8cb368..1d1c243eb64 100644 --- a/src/main/text-generation/execution/commit-message-agent-environment.test.ts +++ b/src/main/text-generation/execution/commit-message-agent-environment.test.ts @@ -71,7 +71,6 @@ describe('prepareLocalCommitMessageAgentEnv', () => { ANTHROPIC_AUTH_TOKEN: 'chosen-token' } }) - expect(await prepareLocalCommitMessageAgentEnv('custom', undefined)).toEqual({ ok: true }) }) it('hydrates OpenCode config dir from shell startup files for headless generation', async () => { @@ -89,21 +88,6 @@ describe('prepareLocalCommitMessageAgentEnv', () => { }) }) - it('hydrates Pi agent dir from shell startup files for headless generation', async () => { - const home = makeHome() - delete process.env.PI_CODING_AGENT_DIR - writeFileSync(join(home, '.zshrc'), 'export PI_CODING_AGENT_DIR="$HOME/.config/pi-agent"\n') - - const result = await prepareLocalCommitMessageAgentEnv('pi', undefined) - - expect(result).toEqual({ - ok: true, - env: expect.objectContaining({ - PI_CODING_AGENT_DIR: `${home}/.config/pi-agent` - }) - }) - }) - // STA-4422: failed managed-home preparation must not fall through to the user's real account while UI shows a managed account. it('strips a nested-Orca CODEX_HOME override when the launch resolves to the real home', async () => { diff --git a/src/main/text-generation/execution/commit-message-text-generation-local-subprocess.test.ts b/src/main/text-generation/execution/commit-message-text-generation-local-subprocess.test.ts index 28e3af02068..4206ed42778 100644 --- a/src/main/text-generation/execution/commit-message-text-generation-local-subprocess.test.ts +++ b/src/main/text-generation/execution/commit-message-text-generation-local-subprocess.test.ts @@ -2,10 +2,7 @@ import { spawn } from 'node:child_process' import type * as ChildProcess from 'node:child_process' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { generateCommitMessageFromContext } from '../commit-message-text-generation' -import { - createChildTerminationExpectation, - withPlatform -} from './commit-message-text-generation-test-harness' +import { createChildTerminationExpectation } from './commit-message-text-generation-test-harness' const { terminateWindowsProcessTreeMock } = vi.hoisted(() => ({ terminateWindowsProcessTreeMock: vi.fn(async () => {}) @@ -84,32 +81,4 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () }) await expectChildTerminated(child) }) - - it('rejects unsafe argv prompts for Windows batch-script agent commands', async () => { - await withPlatform('win32', async () => { - const result = await generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M\tREADME.md', - stagedPatch: '+hello & goodbye' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'C:/tools/agent.cmd {prompt}' - }, - { - kind: 'local', - cwd: 'C:\\repo' - } - ) - - expect(result).toMatchObject({ - success: false, - error: - "C:/tools/agent.cmd runs through a Windows batch script that cannot take the multi-line prompt as an argument. Point Settings at the agent's executable, or use a custom command without {prompt} so Orca sends the prompt on stdin." - }) - expect(spawnMock).not.toHaveBeenCalled() - }) - }) }) diff --git a/src/main/text-generation/execution/commit-message-text-generation-remote-execution.test.ts b/src/main/text-generation/execution/commit-message-text-generation-remote-execution.test.ts index bb0ec740533..1b7445c090c 100644 --- a/src/main/text-generation/execution/commit-message-text-generation-remote-execution.test.ts +++ b/src/main/text-generation/execution/commit-message-text-generation-remote-execution.test.ts @@ -3,46 +3,6 @@ import { describe, expect, it } from 'vitest' import { generateCommitMessageFromContext } from '../commit-message-text-generation' describe('generateCommitMessageFromContext', () => { - it('uses a prepared remote execution plan instead of running git on the remote side', async () => { - const result = await generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M\tREADME.md', - stagedPatch: '+hello' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'agent --message {prompt}' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async (plan, cwd, timeoutMs) => { - expect(cwd).toBe('/repo') - expect(timeoutMs).toBe(60_000) - expect(plan.binary).toBe('agent') - expect(plan.args).toHaveLength(2) - expect(plan.args[0]).toBe('--message') - expect(plan.args[1]).toContain('Staged files:\nM\tREADME.md') - return { - stdout: 'Add README note.\n', - stderr: '', - exitCode: 0, - timedOut: false - } - } - } - ) - - expect(result).toEqual({ - success: true, - message: 'Add README note', - agentLabel: 'agent' - }) - }) - it('sanitizes remote execution transport failures', async () => { const result = await generateCommitMessageFromContext( { diff --git a/src/main/text-generation/execution/source-control-agent-cli-path.test.ts b/src/main/text-generation/execution/source-control-agent-cli-path.test.ts index 027c206b3eb..7735fd6c874 100644 --- a/src/main/text-generation/execution/source-control-agent-cli-path.test.ts +++ b/src/main/text-generation/execution/source-control-agent-cli-path.test.ts @@ -47,8 +47,7 @@ describe.runIf(process.platform !== 'win32')('chat naming CLI discovery', () => it.each([ ['./node_modules/.bin:EMPTY', 'node_modules/.bin'], - [':EMPTY', '.'], - ['EMPTY:', '.'] + [':EMPTY', '.'] ])('resolves recipe PATH %s from the workspace before global installs', async (path, folder) => { const home = mkdtempSync(join(tmpdir(), 'orca-naming-recipe-path-')) homes.push(home) diff --git a/src/main/text-generation/execution/source-control-agent-launch.test.ts b/src/main/text-generation/execution/source-control-agent-launch.test.ts deleted file mode 100644 index cda7896d791..00000000000 --- a/src/main/text-generation/execution/source-control-agent-launch.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import 'node:events' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as RunProcess from '@orca/process-host' -import type { ProcessSpec } from '@orca/process-host/process-spec' -import '../../provider-process/provider-process-supervisor' -import { generateCommitMessageFromContext } from '../commit-message-text-generation' -import './commit-message-text-generation-test-harness' -import './source-control-agent-launch' - -const { spawnProcessMock } = vi.hoisted(() => ({ spawnProcessMock: vi.fn() })) - -vi.mock('@orca/process-host', async (importOriginal) => { - const actual = await importOriginal() - spawnProcessMock.mockImplementation(actual.spawnProcess) - return { ...actual, spawnProcess: spawnProcessMock } -}) - -function lastSpawnSpec(): ProcessSpec { - return spawnProcessMock.mock.calls.at(-1)![0] -} - -function decodedSupervisorSpec(spec: ProcessSpec): Record { - return JSON.parse(Buffer.from(spec.env!.ORCA_PROVIDER_SUPERVISOR_SPEC!, 'base64').toString()) -} - -const folder = mkdtempSync(join(tmpdir(), 'orca-agent-launch-')) -afterAll(() => rmSync(folder, { recursive: true, force: true })) - -beforeEach(() => { - spawnProcessMock.mockClear() -}) - -describe.runIf(process.platform !== 'win32')('supervised agent processes', () => { - it('passes the stdin end through so the agent can answer its request', async () => { - const agent = join(folder, 'echo-agent.cjs') - writeFileSync( - agent, - `let prompt = '' -process.stdin.on('data', (chunk) => (prompt += chunk)) -process.stdin.on('end', () => setTimeout(() => console.log(prompt.includes('README') ? 'Update README' : 'no prompt'), 1200)) -` - ) - - await expect( - generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M README.md', - stagedPatch: '+test' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: `"${process.execPath}" "${agent}"` - }, - { kind: 'local', cwd: folder } - ) - ).resolves.toMatchObject({ success: true, message: 'Update README' }) - expect(lastSpawnSpec().program).toBe(process.execPath) - expect(decodedSupervisorSpec(lastSpawnSpec())).toMatchObject({ - lifetime: 'one-shot' - }) - }) - - it('drops the agent session that launched Orca but keeps assignments in the command', async () => { - const agent = join(folder, 'session-agent.cjs') - writeFileSync( - agent, - `process.stdin.resume() -process.stdin.on('end', () => console.log('Thread ' + (process.env.CODEX_THREAD_ID ?? 'unset') + ', effort ' + process.env.CLAUDE_EFFORT)) -` - ) - vi.stubEnv('CODEX_THREAD_ID', 'parent-thread') - try { - await expect( - generateCommitMessageFromContext( - { branch: 'main', stagedSummary: 'M README.md', stagedPatch: '+test' }, - { - agentId: 'custom', - model: '', - customAgentCommand: `CLAUDE_EFFORT=low "${process.execPath}" "${agent}"` - }, - { kind: 'local', cwd: folder } - ) - ).resolves.toMatchObject({ success: true, message: 'Thread unset, effort low' }) - } finally { - vi.unstubAllEnvs() - } - }) -}) From fde1ae70dac41473c97044b0ea81fb222fc9447d Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Fri, 13 Nov 2026 04:53:48 -0500 Subject: [PATCH 15/17] fix(mac): give Orca's main executable its own UUID so Local Network access works (#41676) * fix(mac): give Orca's main executable its own Mach-O UUID macOS Local Network privacy identifies an app by its main executable's UUID. The packaged executable is stock Electron's, so it shares that UUID with every other app on the same Electron version and macOS can apply another app's Local Network decision to Orca. Rewrite LC_UUID in every slice to a value derived from the app id, executable name and CPU type, before signing. * fix(mac): re-sign rewritten executables ad hoc, cover the terminal host, assert UUIDs at release Rewriting LC_UUID breaks Electron's linker ad hoc signature, and arm64 kills unsigned code, so identity-less local builds (where app signing is skipped) produced an Orca.app that died at launch. Re-sign the rewritten executable ad hoc, outside the bundle so codesign does not treat it as the bundle; real signing replaces it later. The terminal host's executable is a stock Node binary whose UUID is shared by every copy of that Node release, so give it its own stable UUID the same way. Packaging and release verification now fail when a shipped executable does not carry its expected UUID. * fix(mac): scope the executable UUID rewrite to the main app The terminal host gets a separate design; leave it unchanged here. --- config/electron-builder.config.cjs | 14 +++ .../macos/build-mac-notarization-overlap.mjs | 7 +- .../macos/macos-executable-uuid.cjs | 115 ++++++++++++++++++ .../macos/macos-executable-uuid.test.mjs | 99 +++++++++++++++ 4 files changed, 234 insertions(+), 1 deletion(-) create mode 100644 config/scripts/desktop-distribution/macos/macos-executable-uuid.cjs create mode 100644 config/scripts/desktop-distribution/macos/macos-executable-uuid.test.mjs diff --git a/config/electron-builder.config.cjs b/config/electron-builder.config.cjs index affa225978c..c6531b87a38 100644 --- a/config/electron-builder.config.cjs +++ b/config/electron-builder.config.cjs @@ -5,6 +5,9 @@ const { MACOS_FOLDER_USAGE_DESCRIPTIONS, applyMacHelperFolderUsageDescriptions } = require('./scripts/desktop-distribution/macos/macos-folder-usage-descriptions.cjs') +const { + giveMacExecutableUniqueUuid +} = require('./scripts/desktop-distribution/macos/macos-executable-uuid.cjs') const electronBuilderNativeRebuild = require('./scripts/desktop-distribution/runtime-verification/electron-builder-native-rebuild.cjs') const { assertPackagedDaemonEntryExists, @@ -426,6 +429,17 @@ module.exports = { join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`), context.packager.appInfo.productFilename ) + // Before signing, so the signature seals the rewritten executable. + giveMacExecutableUniqueUuid( + join( + context.appOutDir, + `${context.packager.appInfo.productFilename}.app`, + 'Contents', + 'MacOS', + context.packager.appInfo.productFilename + ), + context.packager.appInfo.id + ) const architecture = macSliceArch(context.arch, 'local-build compatibility') const schedulingAddon = buildMacShipItScheduling(resourcesDir, architecture) await signMacStandaloneHelper(schedulingAddon, 'ShipIt scheduling', context.packager) diff --git a/config/scripts/desktop-distribution/macos/build-mac-notarization-overlap.mjs b/config/scripts/desktop-distribution/macos/build-mac-notarization-overlap.mjs index 81c092a1282..0f064c2db1f 100644 --- a/config/scripts/desktop-distribution/macos/build-mac-notarization-overlap.mjs +++ b/config/scripts/desktop-distribution/macos/build-mac-notarization-overlap.mjs @@ -1,6 +1,7 @@ import { execFileSync } from 'node:child_process' import { createRequire } from 'node:module' -import { join, resolve } from 'node:path' +import { basename, join, resolve } from 'node:path' +import { assertMacExecutableUuid } from './macos-executable-uuid.cjs' const ARCHITECTURES = [1, 3] // electron-builder: x64, arm64. @@ -138,6 +139,10 @@ export async function main(args = process.argv.slice(2)) { verify: (appPath) => { execFileSync('codesign', ['--verify', '--deep', '--strict', appPath], { stdio: 'inherit' }) execFileSync('xcrun', ['stapler', 'validate', appPath], { stdio: 'inherit' }) + assertMacExecutableUuid( + join(appPath, 'Contents', 'MacOS', basename(appPath, '.app')), + config.appId + ) }, targets: new Map([ [ diff --git a/config/scripts/desktop-distribution/macos/macos-executable-uuid.cjs b/config/scripts/desktop-distribution/macos/macos-executable-uuid.cjs new file mode 100644 index 00000000000..f07939c09b4 --- /dev/null +++ b/config/scripts/desktop-distribution/macos/macos-executable-uuid.cjs @@ -0,0 +1,115 @@ +// macOS Local Network privacy maps a process to its app by executable UUID; stock Electron's is shared by every app shipping that build (TN3179). +const { execFileSync } = require('node:child_process') +const { createHash } = require('node:crypto') +const { copyFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } = require('node:fs') +const { tmpdir } = require('node:os') +const { basename, join } = require('node:path') + +const MH_MAGIC = 0xfeedface +const MH_MAGIC_64 = 0xfeedfacf +const FAT_MAGIC = 0xcafebabe +const FAT_MAGIC_64 = 0xcafebabf +const LC_UUID = 0x1b + +function formatUuid(bytes) { + const hex = Buffer.from(bytes).toString('hex').toUpperCase() + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}` +} + +// Stable per app, executable and CPU so releases keep one identity, as the stock UUID did within an Electron version. +function deriveExecutableUuid(appId, executableName, cpuType) { + const uuid = createHash('sha256') + .update(`${appId}\0${executableName}\0${cpuType}`) + .digest() + .subarray(0, 16) + uuid[6] = (uuid[6] & 0x0f) | 0x80 + uuid[8] = (uuid[8] & 0x3f) | 0x80 + return uuid +} + +function sliceOffsets(buffer) { + const magic = buffer.readUInt32BE(0) + if (magic !== FAT_MAGIC && magic !== FAT_MAGIC_64) { + return [0] + } + const is64 = magic === FAT_MAGIC_64 + const count = buffer.readUInt32BE(4) + const offsets = [] + for (let i = 0; i < count; i++) { + const entry = 8 + i * (is64 ? 32 : 20) + offsets.push(is64 ? Number(buffer.readBigUInt64BE(entry + 8)) : buffer.readUInt32BE(entry + 8)) + } + return offsets +} + +/** Where each slice's LC_UUID payload sits. */ +function machOUuidSlots(buffer) { + return sliceOffsets(buffer).map((offset) => { + const magic = buffer.readUInt32LE(offset) + if (magic !== MH_MAGIC && magic !== MH_MAGIC_64) { + throw new Error( + `Unsupported Mach-O slice at offset ${offset} (magic 0x${magic.toString(16)})` + ) + } + const cpuType = buffer.readUInt32LE(offset + 4) + const commandCount = buffer.readUInt32LE(offset + 16) + let command = offset + (magic === MH_MAGIC_64 ? 32 : 28) + for (let i = 0; i < commandCount; i++) { + if (buffer.readUInt32LE(command) === LC_UUID) { + return { cpuType, uuidOffset: command + 8 } + } + command += buffer.readUInt32LE(command + 4) + } + throw new Error(`Mach-O slice for CPU type ${cpuType} has no LC_UUID`) + }) +} + +/** Rewrites LC_UUID in every slice of `buffer` in place. */ +function rewriteMachOUuids(buffer, appId, executableName) { + return machOUuidSlots(buffer).map(({ cpuType, uuidOffset }) => { + const before = formatUuid(buffer.subarray(uuidOffset, uuidOffset + 16)) + const next = deriveExecutableUuid(appId, executableName, cpuType) + next.copy(buffer, uuidOffset) + return { cpuType, before, after: formatUuid(next) } + }) +} + +/** Gives the executable its own UUID, then re-signs it ad hoc; real signing replaces that later. */ +function giveMacExecutableUniqueUuid(executable, appId) { + const name = basename(executable) + const buffer = readFileSync(executable) + const changes = rewriteMachOUuids(buffer, appId, name) + // The edit breaks Electron's linker ad hoc signature and arm64 kills unsigned code, but identity-less builds skip app signing. + // Signed outside the bundle: in place, codesign would treat it as the bundle and require its unsigned siblings be signed. + const staging = mkdtempSync(join(tmpdir(), 'orca-executable-uuid-')) + try { + const staged = join(staging, name) + writeFileSync(staged, buffer, { mode: 0o755 }) + execFileSync('codesign', ['--force', '--sign', '-', '--identifier', appId, staged], { + stdio: 'inherit' + }) + copyFileSync(staged, executable) + } finally { + rmSync(staging, { recursive: true, force: true }) + } + for (const { cpuType, before, after } of changes) { + console.log(`[macos-executable-uuid] ${name} cpu ${cpuType}: ${before} -> ${after}`) + } +} + +/** Fails when a shipped executable lost its own UUID, e.g. the hook was skipped or signing rewrote it. */ +function assertMacExecutableUuid(executable, appId) { + const name = basename(executable) + const buffer = readFileSync(executable) + for (const { cpuType, uuidOffset } of machOUuidSlots(buffer)) { + const actual = formatUuid(buffer.subarray(uuidOffset, uuidOffset + 16)) + const expected = formatUuid(deriveExecutableUuid(appId, name, cpuType)) + if (actual !== expected) { + throw new Error( + `[macos-executable-uuid] ${executable} cpu ${cpuType} has UUID ${actual}, expected ${expected}` + ) + } + } +} + +module.exports = { assertMacExecutableUuid, giveMacExecutableUniqueUuid, rewriteMachOUuids } diff --git a/config/scripts/desktop-distribution/macos/macos-executable-uuid.test.mjs b/config/scripts/desktop-distribution/macos/macos-executable-uuid.test.mjs new file mode 100644 index 00000000000..0f5b041221c --- /dev/null +++ b/config/scripts/desktop-distribution/macos/macos-executable-uuid.test.mjs @@ -0,0 +1,99 @@ +import { execFileSync } from 'node:child_process' +import { copyFileSync, mkdtempSync, rmSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' + +const require = createRequire(import.meta.url) +const { + assertMacExecutableUuid, + giveMacExecutableUniqueUuid, + rewriteMachOUuids +} = require('./macos-executable-uuid.cjs') + +const ARM64 = 0x0100000c +const X86_64 = 0x01000007 +const STOCK_UUID = Buffer.from('4C4C44C055553144A1E0C291B44FDBE3', 'hex') + +function thinSlice(cpuType) { + const header = Buffer.alloc(32) + header.writeUInt32LE(0xfeedfacf, 0) + header.writeUInt32LE(cpuType, 4) + header.writeUInt32LE(2, 12) + header.writeUInt32LE(2, 16) + header.writeUInt32LE(16 + 24, 20) + const other = Buffer.alloc(16, 0xaa) + other.writeUInt32LE(0x19, 0) + other.writeUInt32LE(16, 4) + const uuid = Buffer.alloc(24) + uuid.writeUInt32LE(0x1b, 0) + uuid.writeUInt32LE(24, 4) + STOCK_UUID.copy(uuid, 8) + return Buffer.concat([header, other, uuid, Buffer.alloc(8, 0xbb)]) +} + +function fatBinary(slices) { + const table = Buffer.alloc(8 + slices.length * 20) + table.writeUInt32BE(0xcafebabe, 0) + table.writeUInt32BE(slices.length, 4) + const parts = [table] + let offset = 4096 + slices.forEach((slice, i) => { + table.writeUInt32BE(slice.readUInt32LE(4), 8 + i * 20) + table.writeUInt32BE(offset, 8 + i * 20 + 8) + table.writeUInt32BE(slice.length, 8 + i * 20 + 12) + const end = parts.reduce((n, p) => n + p.length, 0) + parts.push(Buffer.alloc(offset - end), slice) + offset += 4096 + }) + return Buffer.concat(parts) +} + +const uuidAt = (buffer, offset) => buffer.subarray(offset, offset + 16).toString('hex') + +describe('rewriteMachOUuids', () => { + it('replaces the stock UUID of a thin executable and nothing else', () => { + const original = thinSlice(ARM64) + const rewritten = Buffer.from(original) + rewriteMachOUuids(rewritten, 'com.stablyai.orca', 'Orca') + expect(uuidAt(rewritten, 56)).toBe('e64304103b228bd69677b18884034a30') + expect(Buffer.concat([rewritten.subarray(0, 56), rewritten.subarray(72)])).toEqual( + Buffer.concat([original.subarray(0, 56), original.subarray(72)]) + ) + }) + + it('gives every slice of a universal executable its own stable UUID', () => { + const binary = fatBinary([thinSlice(X86_64), thinSlice(ARM64)]) + rewriteMachOUuids(binary, 'com.stablyai.orca', 'Orca') + rewriteMachOUuids(binary, 'com.stablyai.orca', 'Orca') + expect(uuidAt(binary, 4096 + 56)).toBe('016ee6813dc381c7a6da12dc23b89dd9') + expect(uuidAt(binary, 8192 + 56)).toBe('e64304103b228bd69677b18884034a30') + }) + + it('refuses an executable without LC_UUID', () => { + const slice = thinSlice(ARM64) + slice.writeUInt32LE(0x1a, 48) + expect(() => rewriteMachOUuids(slice, 'com.stablyai.orca', 'Orca')).toThrow('has no LC_UUID') + }) +}) + +describe.runIf(process.platform === 'darwin')('giveMacExecutableUniqueUuid', () => { + it('leaves a signed, runnable universal executable that passes the release check', () => { + const dir = mkdtempSync(join(tmpdir(), 'orca-exe-uuid-')) + try { + const executable = join(dir, 'Orca') + // A real platform-signed fat binary: rewriting it without re-signing gets it killed at exec. + copyFileSync('/usr/bin/true', executable) + expect(() => assertMacExecutableUuid(executable, 'com.stablyai.orca')).toThrow( + 'expected 016EE681-3DC3-81C7-A6DA-12DC23B89DD9' + ) + giveMacExecutableUniqueUuid(executable, 'com.stablyai.orca') + execFileSync(executable) + execFileSync('codesign', ['--verify', '--strict', executable]) + assertMacExecutableUuid(executable, 'com.stablyai.orca') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) From 7f43d8aab63681c2ae6dccf9e5707e79e5a62971 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 13 Nov 2026 02:01:50 -0800 Subject: [PATCH 16/17] test: remove prompt transport replays and secret bookkeeping cases (#41947) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- ...ted-secret-persistence-concurrency.test.ts | 12 - .../protected-secret-persistence.test.ts | 30 --- .../saved-credential-readability.test.ts | 3 +- ...xt-generation-failure-sanitization.test.ts | 31 --- .../failures/kimi-generation-failure.test.ts | 37 --- .../source-control-omp-prompt-file.test.ts | 230 +----------------- .../prompts/source-control-wsl-prompt.test.ts | 69 ------ .../issue-command-wsl-stopped-distro.test.ts | 28 --- 8 files changed, 2 insertions(+), 438 deletions(-) diff --git a/src/main/credentials/protected-secret-persistence-concurrency.test.ts b/src/main/credentials/protected-secret-persistence-concurrency.test.ts index 5696287957f..c905b84c8a5 100644 --- a/src/main/credentials/protected-secret-persistence-concurrency.test.ts +++ b/src/main/credentials/protected-secret-persistence-concurrency.test.ts @@ -153,18 +153,6 @@ describe('protected secret acknowledgements', () => { expect(secrets.encrypt('remove', 'replacement').blob).toBe('') }) - it('does not accept a prepared update from a replaced persistence instance', () => { - const previous = new ProtectedSecretPersistence() - const current = new ProtectedSecretPersistence() - const older = prepare(previous, 'slot', 'older') - const newer = prepare(current, 'slot', 'newer') - - current.commitRetentionUpdates([older, newer]) - - cipherState.available = false - expect(current.encrypt('slot', 'replacement').blob).toBe(ciphertext('newer')) - }) - it('keeps the previous ciphertext and pending retry when a prepared save has no confirmed ack', () => { const secrets = new ProtectedSecretPersistence() const original = ciphertext('original') diff --git a/src/main/credentials/protected-secret-persistence.test.ts b/src/main/credentials/protected-secret-persistence.test.ts index a0fa87fccc7..81fea025bb6 100644 --- a/src/main/credentials/protected-secret-persistence.test.ts +++ b/src/main/credentials/protected-secret-persistence.test.ts @@ -44,34 +44,4 @@ describe('ProtectedSecretPersistence', () => { secrets.removeRetainedBlob(slot) expect(secrets.encrypt(slot, '')).toEqual({ blob: '', degraded: false }) }) - - it('keeps deferred encryption pending until its retention update commits', async () => { - const { ProtectedSecretPersistence } = await import('./protected-secret-persistence') - const secrets = new ProtectedSecretPersistence() - cipherState.available = false - secrets.encrypt('slot', 'pending') - expect(secrets.hasPendingEncryption()).toBe(true) - cipherState.available = true - const encrypted = secrets.encrypt('slot', 'pending') - expect(secrets.hasPendingEncryption()).toBe(true) - if (!encrypted.retentionUpdate) { - throw new Error('Expected a retention update') - } - secrets.commitRetentionUpdates([encrypted.retentionUpdate]) - expect(secrets.hasPendingEncryption()).toBe(false) - }) - - it('retires a deferred empty secret without retaining a phantom retry', async () => { - const { ProtectedSecretPersistence } = await import('./protected-secret-persistence') - const secrets = new ProtectedSecretPersistence() - cipherState.available = false - secrets.encrypt('slot', 'pending') - const cleared = secrets.encrypt('slot', '') - expect(secrets.hasPendingEncryption()).toBe(true) - if (!cleared.retentionUpdate) { - throw new Error('Expected a retention update') - } - secrets.commitRetentionUpdates([cleared.retentionUpdate]) - expect(secrets.hasPendingEncryption()).toBe(false) - }) }) diff --git a/src/main/credentials/saved-credential-readability.test.ts b/src/main/credentials/saved-credential-readability.test.ts index 6f5d23b6426..c4607cf8279 100644 --- a/src/main/credentials/saved-credential-readability.test.ts +++ b/src/main/credentials/saved-credential-readability.test.ts @@ -49,8 +49,7 @@ describe('savedCredentialUnreadable', () => { it.each([ ['an empty', ''], - ['a non-base64', 'not*base64!'], - ['a truncated base64', 'c2VhbGVkLWhlcmU6a2V5x'] + ['a non-base64', 'not*base64!'] ])('reports %s payload as unreadable, not sealed elsewhere', (_label, payload) => { expect(judge(`${PREFIX}encrypted:${payload}`)).toBe('unreadable') }) diff --git a/src/main/text-generation/failures/commit-message-text-generation-failure-sanitization.test.ts b/src/main/text-generation/failures/commit-message-text-generation-failure-sanitization.test.ts index 2a1977e2825..df1c71b8d18 100644 --- a/src/main/text-generation/failures/commit-message-text-generation-failure-sanitization.test.ts +++ b/src/main/text-generation/failures/commit-message-text-generation-failure-sanitization.test.ts @@ -2,37 +2,6 @@ import { describe, expect, it } from 'vitest' import { generateCommitMessageFromContext } from '../commit-message-text-generation' describe('generateCommitMessageFromContext', () => { - it('exposes raw CLI failure output only after path sanitization', async () => { - const result = await generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M\tREADME.md', - stagedPatch: '+hello' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'agent' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async () => ({ - stdout: 'You are generating a single git commit message for /secret/repo', - stderr: 'raw failure output with /Users/thebr/My Repo/secret/file.ts', - exitCode: 1, - timedOut: false - }) - } - ) - - expect(result).toMatchObject({ - success: false, - error: 'agent CLI command failed with code 1: raw failure output with [path]' - }) - }) - it('formats nonzero exit failures with extracted sanitized CLI details', async () => { const result = await generateCommitMessageFromContext( { diff --git a/src/main/text-generation/failures/kimi-generation-failure.test.ts b/src/main/text-generation/failures/kimi-generation-failure.test.ts index ab37b8665da..46edc2093c9 100644 --- a/src/main/text-generation/failures/kimi-generation-failure.test.ts +++ b/src/main/text-generation/failures/kimi-generation-failure.test.ts @@ -27,7 +27,6 @@ const run = (message: string) => `error: failed to run prompt: ${message}\nSee l const network = run('provider.connection_error: getaddrinfo ENOTFOUND private-host') const agentOptions = /^Kimi received conflicting or repeated agent options\. Keep a single --agent or --agent-file option in the generation recipe or CLI arguments, then retry\.$/ -const credentials = /credentials.*execution host.*configure.*sign in/ const parser = /^Kimi rejected an option or argument\. Correct the generation recipe or CLI arguments, then retry\.$/ const delimiters = "private-x' argument '".repeat(12) @@ -36,36 +35,11 @@ const delimiters = "private-x' argument '".repeat(12) it.each([ ['', occupied, realKimiOccupiedOutput, 4], [run('unrelated private-prose'), occupied, `${earlier}\n${realKimiOccupiedOutput}`, 4], - [run('Session "private-session" not found.'), /find.*session.*existing session.*new one/], - [ - run('Session "private-session" was created under a different directory.'), - /another directory.*Resume it there.*workspace/ - ], - [ - run('no provider configured; complete onboarding via /login or the providers endpoint'), - credentials - ], - [ - run( - 'Provider "private-provider" declares api_key_env = "PRIVATE_ENV" in config.toml, but the environment variable is not set or is empty.' - ), - /credential environment variable.*Set it.*execution host/ - ], - [ - run('model private-model does not resolve to a configured provider'), - /usable model.*configure or select/ - ], - [run('Prompt hook blocked the request.'), /hook blocked.*Review.*hooks.*retry/], - [run('Prompt turn ended with reason: cancelled'), /cancelled.*Try again/], [ run('provider.auth_error: private-provider prose'), /authenticate.*Sign in.*credentials.*retry/, '{broken' ], - [run('provider.rate_limit: private-provider prose'), /limit.*Wait.*reduce/], - [run('Provider safety policy blocked the response.'), /blocked.*Revise.*prompt.*configuration/], - [run('context.overflow: private-provider prose'), /context.*Shorten.*new session/], - [run('config.invalid: private-provider prose'), /invalid configuration.*Check.*model.*provider/], [network, /connect.*network.*retry/], [network, /connect.*network.*MagicDNS/, '', 1, true], ...[ @@ -84,17 +58,6 @@ it.each([ [run("unknown option '--private-flag'"), unknown, '{"type":"error","code":"unknown.code"}'], [`error: option '${delimiters}tail`, unknown], [`error: option '${delimiters}value' is invalid. provider.auth_error: private-prose`, parser], - ['error: Login required\n\nmessage:\nprivate-prose\nSee log: private-path', credentials], - ['error: Prompt cannot be empty.', /empty prompt.*recipe.*CLI arguments/], - [ - 'error: Cannot combine --prompt with --auto.', - /conflicting.*--prompt.*--auto.*recipe.*arguments/ - ], - [ - 'error: Cannot combine --agent/--agent-file with --session/--continue: the agent is bound at session creation and the bound agent is restored automatically on resume.', - /cannot change the agent.*Remove.*override.*new session/ - ], - ['error: Cannot use --session without an id in prompt mode.', /session id.*recipe.*arguments/], ["hook narration error: unknown option '--private-flag'", unknown], ['', /Kimi.*interrupted.*Try again/, '', null], ['', invalid, realKimiOccupiedOutput, 0], diff --git a/src/main/text-generation/prompts/source-control-omp-prompt-file.test.ts b/src/main/text-generation/prompts/source-control-omp-prompt-file.test.ts index 0b5dfe6f972..ce2baf2088d 100644 --- a/src/main/text-generation/prompts/source-control-omp-prompt-file.test.ts +++ b/src/main/text-generation/prompts/source-control-omp-prompt-file.test.ts @@ -1,18 +1,9 @@ import { spawnProcess } from '@orca/process-host' -import * as agentSpecs from '../../../shared/source-control/ai/generation/commit-message-agent-spec' -import type { ResolvedSourceControlAiGenerationParams } from '../../../shared/source-control/ai/source-control-ai-operation-resolution' import type { SpawnSourceControlAgent } from '../source-control-text-generation-types' -import { - generateCommitMessage, - generatePullRequestFields, - generateBranchName -} from '../requests/source-control-text-generation-requests' -import { generateConversationName } from '../requests/conversation-name-generation-request' -import { generateJiraIssueSummaryFromContext } from '../requests/jira-issue-summary-text-generation' +import { generateCommitMessage } from '../requests/source-control-text-generation-requests' import { existsSync, mkdtempSync, readFileSync } from 'node:fs' import { rm } from 'node:fs/promises' -import type * as FsPromises from 'node:fs/promises' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' @@ -29,13 +20,6 @@ vi.mock('../../pty/process-retirement/windows-process-tree-kill', () => ({ terminateWindowsProcessTree: vi.fn(async () => true) })) -vi.mock('node:fs/promises', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, rm: vi.fn(actual.rm) } -}) - -const actualFs = await vi.importActual('node:fs/promises') - afterEach(() => vi.useRealTimers()) // OMP 17.0.5 recorded stdin-only execution: exit 0, empty stdout/stderr, no submitted prompt. @@ -137,96 +121,6 @@ const commitContext = { stagedPatch: '+ Trace lighthouse signal' } -type Consumer = { - label: string - run( - params: ResolvedSourceControlAiGenerationParams, - spawnAgent: SpawnSourceControlAgent - ): Promise - output: string - expected: object -} -const consumers: Consumer[] = [ - { - label: 'commit', - run: (params, spawnAgent) => - generateCommitMessage({ context: commitContext, params, target: contractTarget, spawnAgent }), - output: 'Trace lighthouse signal.\n\nPreserve request bytes\n', - expected: { message: 'Trace lighthouse signal\n\nPreserve request bytes' } - }, - { - label: 'PR fields', - run: (params, spawnAgent) => - generatePullRequestFields({ - context: { - branch: 'feature', - base: 'main', - branchChangedByPreparation: true, - currentTitle: '', - currentBody: '', - currentDraft: false, - commitSummary: 'Trace lighthouse signal', - changeSummary: 'signal.ts', - patch: '+ Trace lighthouse signal' - }, - params, - target: contractTarget, - spawnAgent - }), - output: JSON.stringify({ - base: 'main', - title: 'Trace lighthouse signal.', - body: 'Preserve request bytes\n', - draft: true - }), - expected: { - fields: { - base: 'main', - title: 'Trace lighthouse signal', - body: 'Preserve request bytes', - draft: true - }, - branchChangedByPreparation: true - } - }, - { - label: 'branch slug / folder title', - run: (params, spawnAgent) => - generateBranchName({ - context: { firstPrompt: 'Trace lighthouse signal' }, - params, - target: contractTarget, - spawnAgent - }), - output: 'Trace Lighthouse Signal!', - expected: { slug: 'trace-lighthouse-signal' } - }, - { - label: 'conversation name', - run: (params, spawnAgent) => - generateConversationName({ - context: { firstPrompt: 'Trace lighthouse signal' }, - params, - target: contractTarget, - spawnAgent - }), - output: '# Title: "Trace lighthouse signal"\nextra commentary', - expected: { name: 'Trace lighthouse signal' } - }, - { - label: 'Jira summary', - run: (params, spawnAgent) => - generateJiraIssueSummaryFromContext( - { description: 'Trace lighthouse signal' }, - params, - contractTarget, - spawnAgent - ), - output: '"Trace lighthouse signal"\nextra commentary', - expected: { summary: 'Trace lighthouse signal' } - } -] - type Receipt = { paths: string[]; sizes: number[]; content: string; stdin: string; message: string } async function withReader( output: string, @@ -271,55 +165,6 @@ async function withReader( } } -it.each(consumers)( - 'preserves $label output and failure classification across stdin/file transport', - async (consumer) => { - const spec = agentSpecs.getCommitMessageAgentSpec('omp') - if (!spec) { - throw new Error('Missing OMP spec') - } - for (const fail of [false, true]) { - const delivered = await withReader(consumer.output, fail, (spawn) => - consumer.run(contractParams, spawn) - ) - expect(delivered.receipt.paths).toHaveLength(1) - expect(delivered.receipt.stdin).toBe('') - expect(delivered.receipt.message.endsWith('recipe-message')).toBe(true) - expect(delivered.receipt.content).toContain('Trace lighthouse signal') - expect(delivered.receipt.content.includes('Saved recipe instruction')).toBe( - consumer.label !== 'Jira summary' - ) - if (fail) { - expect(delivered.result).toMatchObject({ - success: false, - error: expect.stringContaining('OMP CLI command failed with code 7') - }) - } else { - expect(delivered.result).toMatchObject({ - success: true, - agentLabel: 'OMP', - ...consumer.expected - }) - } - const legacy = vi.spyOn(agentSpecs, 'getCommitMessageAgentSpec').mockReturnValue({ - ...spec, - promptDelivery: 'stdin', - buildArgs: (params) => spec.buildArgs(params).slice(0, -1) - }) - try { - const previous = await withReader(consumer.output, fail, (spawn) => - consumer.run(contractParams, spawn) - ) - expect(previous.receipt.paths).toHaveLength(0) - expect(previous.receipt.content).toBe(delivered.receipt.content) - expect(previous.result).toEqual(delivered.result) - } finally { - legacy.mockRestore() - } - } - } -) - it.each(['below', 'at', 'above', 'multibyte', 'BOM run', 'GIF', 'RIFF', 'internal magic'] as const)( 'delivers complete text recipe content: %s', async (boundary) => { @@ -363,76 +208,3 @@ it.each(['below', 'at', 'above', 'multibyte', 'BOM run', 'GIF', 'RIFF', 'interna } } ) - -it.each(['success', 'spawn failure', 'permanent failure'] as const)( - 'settles independently of bounded async cleanup after %s', - async (outcome) => { - const originalPlatform = process.platform - const rmMock = vi.mocked(rm) - const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) - const locked = Object.assign(new Error('EPERM: prompt handle held'), { code: 'EPERM' }) - let directory = '' - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - rmMock.mockClear() - rmMock.mockImplementationOnce(async () => { - throw locked - }) - if (outcome === 'permanent failure') { - rmMock.mockRejectedValue(locked) - } - try { - const planned = planCommitMessageGeneration( - { agentId: 'omp', model: 'default' }, - recordedPrompt - ) - if (!planned.ok) { - throw new Error(planned.error) - } - const child = createMockDiscoveryChild() - const execution = runLocalSourceControlPlan({ - plan: planned.plan, - cwd: '/omp-cleanup', - env: undefined, - operation: 'conversation-name', - spawnAgent: ({ args }) => { - directory = dirname(args[planned.plan.promptFile?.argIndex ?? -1].slice(1)) - if (outcome === 'spawn failure') { - throw new Error('Fixture spawn failure') - } - return child - } - }) - if (outcome !== 'spawn failure') { - child.stdout.emit('data', Buffer.from('Lighthouse Signal Trace')) - child.emit('close', 0) - } - expect((await execution.result).success).toBe(outcome !== 'spawn failure') - await execution.processClosed - expect(rmMock).toHaveBeenCalledTimes(1) - expect(existsSync(directory)).toBe(true) - if (outcome === 'permanent failure') { - await vi.waitFor( - () => - expect(errors).toHaveBeenCalledWith( - '[commit-message] Failed to remove generation prompt:', - locked - ), - { timeout: 5000 } - ) - expect(rmMock).toHaveBeenCalledTimes(5) - expect(errors).toHaveBeenCalledTimes(1) - expect(existsSync(directory)).toBe(true) - } else { - await vi.waitFor(() => expect(existsSync(directory)).toBe(false), { timeout: 2000 }) - expect(rmMock).toHaveBeenCalledTimes(2) - } - } finally { - Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) - rmMock.mockImplementation(actualFs.rm) - if (directory) { - await actualFs.rm(directory, { recursive: true, force: true }) - } - errors.mockRestore() - } - } -) diff --git a/src/main/text-generation/prompts/source-control-wsl-prompt.test.ts b/src/main/text-generation/prompts/source-control-wsl-prompt.test.ts index 45134cdd5e5..67538be68c0 100644 --- a/src/main/text-generation/prompts/source-control-wsl-prompt.test.ts +++ b/src/main/text-generation/prompts/source-control-wsl-prompt.test.ts @@ -334,75 +334,6 @@ it.each([ } ) -it.each(['success', 'nonzero', 'empty', 'storage', 'pipe-close'] as const)( - 'runs the production attempt through real private shell preparation and %s', - async (outcome) => { - let directory = '' - let actualPipeError = false - const execution = withPlatform('win32', () => - runLocalSourceControlPlan({ - plan: plan(tricky.repeat(40)), - cwd, - env: undefined, - operation: 'conversation-name', - spawnAgent: (input) => { - const preparation = input.preparation - if (!preparation) { - throw new Error('Missing preparation') - } - directory = `/tmp/orca-generation-${preparation.args[0]}` - const argv = - outcome === 'pipe-close' - ? [ - '-c', - `exec 0<&-; printf 'ORCA_GENERATION_READY:%s\\n' "$1" >&2; sleep 0.1`, - 'fixture', - preparation.args[0] - ] - : [ - '-c', - preparation.script, - 'fixture', - ...preparation.args, - '/bin/sh', - '-c', - outcome === 'empty' - ? ':' - : `printf '%s' 'Useful name'; exit ${outcome === 'nonzero' ? 7 : 0}` - ] - const child = withPlatform('darwin', () => - spawnProcess({ program: '/bin/sh', args: argv, stdio: 'pipe' }) - ) - child.stdin.on('error', (error) => { - actualPipeError ||= 'code' in error && error.code === 'EPIPE' - }) - if (outcome === 'storage') { - child.stderr.once('data', () => mkdirSync(join(directory, 'prompt-1.txt'))) - } - return child - } - }) - ) - try { - const result = await execution.result - await execution.processClosed - expect(result.success).toBe(outcome === 'success') - expect(removeTreeMock).toHaveBeenCalledTimes(1) - if (outcome === 'pipe-close') { - expect(actualPipeError).toBe(true) - } - if (outcome === 'success') { - const file = readFileSync(join(directory, 'prompt-1.txt')) - expect(new TextDecoder().decode(file)).toBe(Buffer.from(tricky.repeat(40)).toString()) - } - } finally { - if (directory) { - await rm(directory, { recursive: true, force: true }) - } - } - } -) - it('delivers a plain UTF-8 policy module and preserves the stdin task after guest materialization', async () => { const guest = prepareWslPrompt( { diff --git a/src/main/workspace-hooks/issue-command-wsl-stopped-distro.test.ts b/src/main/workspace-hooks/issue-command-wsl-stopped-distro.test.ts index 25732ca452c..855ae0924ae 100644 --- a/src/main/workspace-hooks/issue-command-wsl-stopped-distro.test.ts +++ b/src/main/workspace-hooks/issue-command-wsl-stopped-distro.test.ts @@ -32,7 +32,6 @@ import { readIssueCommandUnlessWslStopped, writeIssueCommandUnlessWslStopped } from './issue-command-file' -import { RuntimeRepositoryIssueCommand } from '../runtime/repositories/runtime-repository-issue-command' const WSL_REPO = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo' const HOST_REPO = 'C:\\src\\repo' @@ -67,24 +66,6 @@ describe('issue command reads for a stopped WSL distro (E9)', () => { expect(mocks.loadHooks).not.toHaveBeenCalled() }) - it("gates the runtime read a paired client's Settings pane makes, and passes a launch's wake", async () => { - const reader = new RuntimeRepositoryIssueCommand({ - resolveRepo: async () => ({ - id: 'repo-1', - path: WSL_REPO, - displayName: 'repo', - badgeColor: '#000', - addedAt: 1, - kind: 'git' - }), - getLocalGitArgs: () => [] - }) - await expect(reader.read('id:repo-1')).resolves.toMatchObject({ status: 'error' }) - expect(mocks.loadHooks).not.toHaveBeenCalled() - await reader.read('id:repo-1', { wakeWslDistro: true }) - expect(mocks.loadHooks).toHaveBeenCalledWith(WSL_REPO) - }) - it("refuses a write the user didn't make, leaving the hidden file and the distro alone", async () => { await expect(writeIssueCommandUnlessWslStopped(WSL_REPO, 'x', {})).rejects.toThrow( "WSL distro 'Ubuntu' is not running" @@ -94,15 +75,6 @@ describe('issue command reads for a stopped WSL distro (E9)', () => { expect(mocks.rmSync).not.toHaveBeenCalled() }) - it("saves the user's own edit, a user act that may start the distro", async () => { - await writeIssueCommandUnlessWslStopped(WSL_REPO, 'mine', {}, { wakeWslDistro: true }) - expect(mocks.writeFileSync).toHaveBeenCalledWith( - expect.stringContaining('issue-command'), - 'mine\n', - 'utf-8' - ) - }) - it('refuses a host-path repo whose Git runs in the stopped distro', async () => { await expect( writeIssueCommandUnlessWslStopped(HOST_REPO, 'x', () => ({ wslDistro: 'Ubuntu' })) From 7e10540b93585b413e263a27cccfbaa6f069c823 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:06:33 -0800 Subject: [PATCH 17/17] refactor: group preload modules by domain (#41940) * refactor: group preload modules by domain * fix: include preload entry dependencies in web typecheck --- config/main-blocking-ipc-baseline.txt | 2 +- config/reliability-gates.jsonc | 22 +- .../scripts/ci/sharding/ci-shard-timings.json | 45 ++-- config/tsconfig.tc.web.json | 26 +- ...t-page-renderer-lifecycle.electron.test.ts | 7 +- .../browser-extension-api-host.test.ts | 78 +----- ...tension-content-script-persistence.test.ts | 194 -------------- .../browser-extension-api-namespaces.test.ts | 137 +--------- .../api/declarative-net-request.test.ts | 139 +--------- .../browser/extensions/api/storage-relay.ts | 2 +- .../browser/extensions/api/storage-sync.ts | 2 +- .../extensions/api/web-navigation.test.ts | 2 +- .../register-browser-extension-namespaces.ts | 2 +- .../browser-extension-discarded-tabs.test.ts | 27 +- src/preload/api-types.ts | 62 ----- src/preload/api/app-bridge.ts | 7 +- src/preload/api/automations-bridge.ts | 3 +- ...bridge-guest-registration-and-downloads.ts | 2 +- src/preload/api/claude-usage-bridge.ts | 4 +- src/preload/api/codex-usage-bridge.ts | 4 +- src/preload/api/crash-reports-bridge.ts | 4 +- src/preload/api/e2e-bridge.ts | 2 +- src/preload/{ => api}/gitlab.ts | 4 +- src/preload/api/gl-bridge.ts | 4 - src/preload/api/muse-usage-bridge.ts | 4 +- src/preload/api/native-chat-bridge.ts | 6 +- src/preload/api/open-code-usage-bridge.ts | 4 +- src/preload/api/orca-profiles-bridge.ts | 4 +- src/preload/api/platform-bridge.test.ts | 48 ---- src/preload/api/platform-bridge.ts | 2 +- src/preload/api/plugins-bridge.ts | 8 +- src/preload/api/preflight-bridge.ts | 3 +- src/preload/api/runtime-bridge.ts | 2 +- .../api/runtime-environments-bridge.ts | 2 +- .../ssh-authority-forwarding.test.ts | 38 +-- .../api/ui-bridge-tab-and-browser-commands.ts | 4 +- src/preload/api/updater-bridge.ts | 4 +- .../app-restart-checkpoint-routing.test.ts | 239 ------------------ .../browser-extension-content-script-api.ts | 6 +- ...browser-extension-native-messaging.test.ts | 159 ------------ src/preload/browser-extension-preload.ts | 22 +- .../browser-extension-storage-sync.test.ts | 209 --------------- ...rowser-extension-web-store-wording.test.ts | 48 ---- src/preload/browser-extension-worker-shim.ts | 18 +- src/preload/browser-guest.ts | 8 +- src/preload/browser-passkey-request.ts | 2 +- .../browser-window-close-installation.test.ts | 62 ----- .../api}/browser-extension-api-surface.ts | 0 .../api}/browser-extension-event-filters.ts | 0 .../api}/browser-extension-frame-lifetime.ts | 0 .../api}/browser-extension-inert-apis.test.ts | 6 - .../api}/browser-extension-inert-apis.ts | 0 .../api}/browser-extension-main-world.test.ts | 0 .../api}/browser-extension-main-world.ts | 0 ...browser-extension-document-targets.test.ts | 102 -------- .../browser-extension-document-targets.ts | 2 +- ...ser-extension-content-script-relay.test.ts | 2 +- .../browser-extension-content-script-relay.ts | 4 +- .../browser-extension-native-messaging.ts | 2 +- .../browser-extension-storage-relay.test.ts | 65 +---- .../browser-extension-storage-relay.ts | 2 +- .../browser-extension-storage-sync.test.ts | 100 ++++++++ .../browser-extension-storage-sync.ts | 2 +- .../browser-extension-web-store-bridge.ts | 0 ...ser-extension-web-store-main-world.test.ts | 6 - .../browser-extension-web-store-main-world.ts | 0 .../browser-extension-web-store-wording.ts | 0 .../browser-passkey-request-watch.test.ts | 0 .../browser-passkey-request-watch.ts | 0 .../browser-password-detector.test.ts | 62 +---- .../passwords}/browser-password-detector.ts | 2 +- .../browser-password-element-tokens.ts | 0 .../passwords}/browser-password-field-fill.ts | 2 +- .../browser-password-field-rules.ts | 0 .../browser-password-focus-tracker.ts | 2 +- .../browser-password-form-parser.test.ts | 53 ---- .../browser-password-form-parser.ts | 2 +- .../passwords}/browser-password-form-scan.ts | 2 +- .../browser-password-guest-channels.ts | 2 +- .../passwords}/browser-password-guest-port.ts | 0 .../browser-password-submit-tracker.ts | 2 +- .../browser-window-close-installation.test.ts | 22 ++ .../browser-window-close-installation.ts | 0 .../browser-window-prompt-installation.ts | 0 src/preload/doc-preview-link.ts | 4 +- .../doc-preview-link-interception.ts | 2 +- src/preload/gitlab-work-item-details.test.ts | 18 -- src/preload/index.ts | 8 +- .../native-chat-visual-guest-theme.ts | 2 +- src/preload/opencode-go-credentials.test.ts | 23 -- src/preload/plugin-frame-guest.ts | 4 +- .../plugin-frame-guest-render-lane.test.ts | 0 .../frames}/plugin-frame-guest-send-budget.ts | 0 .../frames}/plugin-frame-guest-transport.ts | 0 .../frames}/plugin-frame-guest.test.ts | 64 +---- src/preload/renderer-restart-wiring.test.ts | 163 ------------ ...wser-client-page-renderer-requests.test.ts | 49 +--- .../browser-client-page-renderer-requests.ts | 2 +- .../browser-find-subscriptions.test.ts | 30 --- .../browser-find-subscriptions.ts | 4 +- .../renderer-heap-statistics-reader.test.ts | 0 .../renderer-heap-statistics-reader.ts | 2 +- .../renderer-process-memory-reader.test.ts | 0 .../renderer-process-memory-reader.ts | 2 +- src/preload/{ => renderer}/e2e-config.ts | 2 +- .../hidden-window-frame-pump.ts | 2 +- .../renderer-runtime.ts} | 10 +- .../app-restart-checkpoint-routing.test.ts | 96 +++++++ .../restart/renderer-restart-wiring.test.ts | 69 +++++ .../restart}/renderer-restart-wiring.ts | 8 +- ...close-active-tab-payload-admission.test.ts | 0 .../close-active-tab-payload-admission.ts | 2 +- .../runtime-environment-subscriptions.ts | 4 +- src/preload/updater-package-recovery.test.ts | 83 ------ src/preload/usage-provider-api.test.ts | 33 --- .../{ => usage}/backend-port-client.ts | 4 +- src/preload/{ => usage}/usage-provider-api.ts | 4 +- .../plugins/catalog/PluginCatalogGroups.tsx | 2 +- .../PluginCatalogHighlights.fixture.tsx | 2 +- .../catalog/plugin-catalog-highlights.test.ts | 2 +- .../plugins/dialogs/PluginInstallDialog.tsx | 2 +- .../dialogs/PluginMarketplaceSourceDialog.tsx | 2 +- .../plugins/dialogs/PluginRemoveDialog.tsx | 2 +- .../plugins/dialogs/PluginRollbackDialog.tsx | 2 +- .../dialogs/PluginUpdateAllDialog.test.tsx | 194 +------------- .../plugins/dialogs/PluginUpdateAllDialog.tsx | 2 +- .../plugins/list/PluginFilterPopover.tsx | 2 +- .../plugins/list/PluginListToolbar.tsx | 2 +- .../plugins/list/PluginManager.test.tsx | 217 ---------------- .../components/plugins/list/PluginManager.tsx | 2 +- .../plugins/list/PluginManagerRows.tsx | 2 +- .../plugins/list/PluginSettingsOverview.tsx | 2 +- .../plugins/list/plugin-list-entries.test.ts | 4 +- .../plugins/list/plugin-list-entries.ts | 4 +- .../plugins/list/plugin-public-catalog.ts | 2 +- .../plugins/page/PluginAddsSection.test.tsx | 2 +- .../plugins/page/PluginAddsSection.tsx | 6 +- .../page/PluginContributionActionEvents.tsx | 2 +- .../page/PluginContributionActionPanel.tsx | 2 +- .../plugins/page/PluginDetailPage.fixture.tsx | 2 +- .../plugins/page/PluginDetailPage.test.tsx | 2 +- ...plugin-contribution-action-availability.ts | 2 +- .../presentation/plugin-access-profile.ts | 6 +- .../presentation/plugin-install-trust.ts | 2 +- .../plugin-status-presentation.ts | 2 +- .../plugins/review/PluginInstallConsent.tsx | 2 +- .../plugins/review/PluginUpdateCandidate.tsx | 2 +- .../plugins/review/PluginUpdateReview.tsx | 2 +- .../review/PluginVmRecipeConsentPreview.tsx | 2 +- .../plugins/state/plugin-preview-cache.ts | 2 +- .../plugins/state/use-plugin-art-palettes.ts | 2 +- .../plugins/state/use-plugin-catalog.ts | 2 +- .../state/use-plugin-contribution-source.ts | 2 +- .../state/use-plugin-hover-prefetch.ts | 2 +- .../state/use-plugin-install-action.test.tsx | 148 ----------- .../state/use-plugin-install-action.ts | 2 +- .../state/use-plugin-install-link.test.tsx | 2 +- .../plugins/state/use-plugin-install-link.ts | 2 +- .../plugins/state/use-plugin-logs.ts | 3 +- .../state/use-plugin-marketplace-lifecycle.ts | 2 +- .../plugins/state/use-plugin-page-model.ts | 2 +- .../state/use-plugin-page-navigation.test.tsx | 146 ----------- .../state/use-plugin-review-queue.test.tsx | 2 +- .../plugins/state/use-plugin-review-queue.ts | 2 +- .../shared/MacFolderAccessFixDialog.tsx | 2 +- .../shared/mac-folder-access-folder-name.ts | 4 +- .../sidebar/SeveredTerminalDaemonBanner.tsx | 2 +- .../task-source-provider-availability.ts | 2 +- .../linear-linked-issue-refresh.test.ts | 58 +---- ...untime-client-ipc-bridge-ownership.test.ts | 56 +--- .../useMacTccAttributionSeveredNotice.ts | 2 +- .../slices/usage/usage-backend-port.test.ts | 10 +- .../preload-api/web-host-capability-api.ts | 7 +- .../web/preload-api/web-native-chat-api.ts | 5 +- .../src/web/web-runtime-crew-follow.test.tsx | 185 -------------- .../src/web/web-runtime-crew.test-fixture.ts | 137 ---------- 176 files changed, 538 insertions(+), 3557 deletions(-) delete mode 100644 src/main/browser/extensions/api-runtime/browser-extension-content-script-persistence.test.ts rename src/preload/{ => api}/gitlab.ts (96%) delete mode 100644 src/preload/api/gl-bridge.ts delete mode 100644 src/preload/api/platform-bridge.test.ts rename src/preload/{ => api}/ssh-authority-forwarding.test.ts (79%) delete mode 100644 src/preload/app-restart-checkpoint-routing.test.ts delete mode 100644 src/preload/browser-extension-native-messaging.test.ts delete mode 100644 src/preload/browser-extension-storage-sync.test.ts delete mode 100644 src/preload/browser-extension-web-store-wording.test.ts delete mode 100644 src/preload/browser-window-close-installation.test.ts rename src/preload/{ => browser/extensions/api}/browser-extension-api-surface.ts (100%) rename src/preload/{ => browser/extensions/api}/browser-extension-event-filters.ts (100%) rename src/preload/{ => browser/extensions/api}/browser-extension-frame-lifetime.ts (100%) rename src/preload/{ => browser/extensions/api}/browser-extension-inert-apis.test.ts (90%) rename src/preload/{ => browser/extensions/api}/browser-extension-inert-apis.ts (100%) rename src/preload/{ => browser/extensions/api}/browser-extension-main-world.test.ts (100%) rename src/preload/{ => browser/extensions/api}/browser-extension-main-world.ts (100%) rename src/preload/{ => browser/extensions/documents}/browser-extension-document-targets.test.ts (67%) rename src/preload/{ => browser/extensions/documents}/browser-extension-document-targets.ts (99%) rename src/preload/{ => browser/extensions/messaging}/browser-extension-content-script-relay.test.ts (98%) rename src/preload/{ => browser/extensions/messaging}/browser-extension-content-script-relay.ts (98%) rename src/preload/{ => browser/extensions/messaging}/browser-extension-native-messaging.ts (98%) rename src/preload/{ => browser/extensions/storage}/browser-extension-storage-relay.test.ts (75%) rename src/preload/{ => browser/extensions/storage}/browser-extension-storage-relay.ts (98%) create mode 100644 src/preload/browser/extensions/storage/browser-extension-storage-sync.test.ts rename src/preload/{ => browser/extensions/storage}/browser-extension-storage-sync.ts (99%) rename src/preload/{ => browser/extensions/web-store}/browser-extension-web-store-bridge.ts (100%) rename src/preload/{ => browser/extensions/web-store}/browser-extension-web-store-main-world.test.ts (94%) rename src/preload/{ => browser/extensions/web-store}/browser-extension-web-store-main-world.ts (100%) rename src/preload/{ => browser/extensions/web-store}/browser-extension-web-store-wording.ts (100%) rename src/preload/{ => browser/passkeys}/browser-passkey-request-watch.test.ts (100%) rename src/preload/{ => browser/passkeys}/browser-passkey-request-watch.ts (100%) rename src/preload/{ => browser/passwords}/browser-password-detector.test.ts (90%) rename src/preload/{ => browser/passwords}/browser-password-detector.ts (99%) rename src/preload/{ => browser/passwords}/browser-password-element-tokens.ts (100%) rename src/preload/{ => browser/passwords}/browser-password-field-fill.ts (99%) rename src/preload/{ => browser/passwords}/browser-password-field-rules.ts (100%) rename src/preload/{ => browser/passwords}/browser-password-focus-tracker.ts (98%) rename src/preload/{ => browser/passwords}/browser-password-form-parser.test.ts (80%) rename src/preload/{ => browser/passwords}/browser-password-form-parser.ts (99%) rename src/preload/{ => browser/passwords}/browser-password-form-scan.ts (99%) rename src/preload/{ => browser/passwords}/browser-password-guest-channels.ts (95%) rename src/preload/{ => browser/passwords}/browser-password-guest-port.ts (100%) rename src/preload/{ => browser/passwords}/browser-password-submit-tracker.ts (99%) create mode 100644 src/preload/browser/window-controls/browser-window-close-installation.test.ts rename src/preload/{ => browser/window-controls}/browser-window-close-installation.ts (100%) rename src/preload/{ => browser/window-controls}/browser-window-prompt-installation.ts (100%) rename src/preload/{ => document-preview}/doc-preview-link-interception.ts (97%) delete mode 100644 src/preload/gitlab-work-item-details.test.ts rename src/preload/{ => native-chat}/native-chat-visual-guest-theme.ts (95%) delete mode 100644 src/preload/opencode-go-credentials.test.ts rename src/preload/{ => plugins/frames}/plugin-frame-guest-render-lane.test.ts (100%) rename src/preload/{ => plugins/frames}/plugin-frame-guest-send-budget.ts (100%) rename src/preload/{ => plugins/frames}/plugin-frame-guest-transport.ts (100%) rename src/preload/{ => plugins/frames}/plugin-frame-guest.test.ts (60%) delete mode 100644 src/preload/renderer-restart-wiring.test.ts rename src/preload/{ => renderer/browser-pages}/browser-client-page-renderer-requests.test.ts (81%) rename src/preload/{ => renderer/browser-pages}/browser-client-page-renderer-requests.ts (99%) rename src/preload/{ => renderer/browser-pages}/browser-find-subscriptions.test.ts (70%) rename src/preload/{ => renderer/browser-pages}/browser-find-subscriptions.ts (94%) rename src/preload/{ => renderer/diagnostics}/renderer-heap-statistics-reader.test.ts (100%) rename src/preload/{ => renderer/diagnostics}/renderer-heap-statistics-reader.ts (91%) rename src/preload/{ => renderer/diagnostics}/renderer-process-memory-reader.test.ts (100%) rename src/preload/{ => renderer/diagnostics}/renderer-process-memory-reader.ts (89%) rename src/preload/{ => renderer}/e2e-config.ts (93%) rename src/preload/{ => renderer}/hidden-window-frame-pump.ts (97%) rename src/preload/{preload-runtime-support.ts => renderer/renderer-runtime.ts} (82%) create mode 100644 src/preload/renderer/restart/app-restart-checkpoint-routing.test.ts create mode 100644 src/preload/renderer/restart/renderer-restart-wiring.test.ts rename src/preload/{ => renderer/restart}/renderer-restart-wiring.ts (92%) rename src/preload/{ => renderer/window-commands}/close-active-tab-payload-admission.test.ts (100%) rename src/preload/{ => renderer/window-commands}/close-active-tab-payload-admission.ts (90%) rename src/preload/{ => runtime}/runtime-environment-subscriptions.ts (98%) delete mode 100644 src/preload/updater-package-recovery.test.ts delete mode 100644 src/preload/usage-provider-api.test.ts rename src/preload/{ => usage}/backend-port-client.ts (97%) rename src/preload/{ => usage}/usage-provider-api.ts (95%) delete mode 100644 src/renderer/src/components/plugins/list/PluginManager.test.tsx delete mode 100644 src/renderer/src/components/plugins/state/use-plugin-install-action.test.tsx delete mode 100644 src/renderer/src/components/plugins/state/use-plugin-page-navigation.test.tsx delete mode 100644 src/renderer/src/web/web-runtime-crew-follow.test.tsx delete mode 100644 src/renderer/src/web/web-runtime-crew.test-fixture.ts diff --git a/config/main-blocking-ipc-baseline.txt b/config/main-blocking-ipc-baseline.txt index 5821c30c503..dac3b7e5930 100644 --- a/config/main-blocking-ipc-baseline.txt +++ b/config/main-blocking-ipc-baseline.txt @@ -6,4 +6,4 @@ 1 src/preload/api/app-bridge.ts 1 src/preload/api/native-chat-bridge.ts 1 src/preload/api/settings-bridge.ts -1 src/preload/native-chat-visual-guest-theme.ts +1 src/preload/native-chat/native-chat-visual-guest-theme.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index d7e19757b11..c361edcc424 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -9350,7 +9350,7 @@ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh/ssh.test.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/preload/ssh-authority-forwarding.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/ssh-retained-payload-admission.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh/ssh.test.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/preload/api/ssh-authority-forwarding.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/ssh-retained-payload-admission.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", "pnpm run build:web-from-renderer", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" @@ -9376,7 +9376,7 @@ "src/main/ipc/ssh/ssh.test.ts", "src/main/ssh/connection/ssh-connection-manager.test.ts", "src/main/ssh/connection/ssh-connection.test.ts", - "src/preload/ssh-authority-forwarding.test.ts", + "src/preload/api/ssh-authority-forwarding.test.ts", "src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts", "src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts", "src/shared/ssh-retained-payload-admission.test.ts" @@ -9428,7 +9428,7 @@ ] }, { - "file": "src/preload/ssh-authority-forwarding.test.ts", + "file": "src/preload/api/ssh-authority-forwarding.test.ts", "assertions": [ "full authority crosses Electron IPC without loss", "partial authority becomes unknown for bounded reconciliation and malformed full authority is dropped", @@ -9779,7 +9779,7 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": [], - "coverageNotes": "Audit3699 removes the complete restored app-owned-copy xterm bypass predicate suite (3 authored/3 finite). Intentionally lose Linux/Windows Ctrl+Shift+C keydown/keyup and logical-over-physical-key pass-through, selection/Kitty-disabled/defaultPrevented refusal, and macOS Cmd+C pass-through/selection/Kitty-disabled policy alarms. No actual browser dispatch, clipboard operation, negotiated application bytes, native key delivery or PTY result was established by this driver. No equivalent replacement or fresh execution claimed. Preserve all prior dated receipts and historical accounts. Previous account (preserved verbatim): Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked AgentTerminalPreview component suite is removed, including the snapshot-proven kitty mirror forwarding alarm. Remove its active file, command token and assertion reference; the other IME drivers are unchanged and do not replace the removed component checks. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: 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. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1619 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts: Loses direct timestamp-formula assertion; no useful independent alarm in removed registration. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1361 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1320 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser native-keyboard fallback inventory case. Its empty-chord, absent-layout and no-op-subscription alarms are lost; retained native input evidence is not an equivalent replacement. Historical commands and results remain historical. Local macOS and containerized Linux evidence, deterministic renderer-unit coverage for the Linux/Sogou candidate-key policy including the legacy orphaned-keyup fallback, xterm preedit visibility and row-occlusion behavior, Electron/CDP preedit geometry, Electron/CDP live-PTY Sogou-style repros, and macOS renderer/main slices for Preview kitty commits and layout-native Option input. The Option slice covers complete CSI-u flag fields including lock state, repeat/release event types, authoritative committed associated text, native dead-key release suppression, functional-versus-printable numpad codes, press-pinned release identity, live keyup modifiers, pending-layout text fallback, atomic layout refresh, rapid in-focus input-source changes, stable native layout characters, and both native/web preload fallbacks. The standalone remote SnapshotStart metadata suite is removed. Its proven-zero, nonzero, absent-field and malformed-value propagation alarms are intentionally lost; retained daemon and preview consumer contracts do not establish equivalent remote projection coverage. Historical commands and results remain historical. Real Linux/Sogou OS IME automation, native Windows candidate-window placement, Windows ConPTY post-agent reset, and the CJK/Vietnamese/Arabic matrix remain registered gaps. The audit removes isolated candidate-anchor width, last-column, timer-ordering and detached-textarea examples. The retained deterministic fixtures do not observe a native candidate window or establish equivalent geometry coverage; separate Electron geometry evidence remains historical. The test-value audit removes the empty end-of-row/no-tail composition baseline from terminal-korean-midline-preedit-occlusion.spec.ts. The placeholder masking and measured row-tail occlusion registrations remain; they are not equivalent replacement coverage for the removed empty-tail alarm. No new execution or native IME evidence is claimed. Audit1301: src/renderer/src/components/terminal-pane/terminal-shortcut-option-compose.test.ts reduced. Dead-key/IME variants, Unicode/language inventories, numpad/CapsLock cases and other protocol samples lose their individual alarms. No equivalent replacement coverage is claimed. Audit1320: src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts reduced. Last-complete snapshot while layout-map/native-snapshot partial refresh settles loses its individual implementation-cache alarm. No equivalent replacement coverage is claimed. Audit1342: src/renderer/src/components/terminal-pane/terminal-ime-macos-keybinding-dict-trace.test.ts reduced. Second Korean-layout replay, ordinary Korean/ASCII no-remap baselines and weak Option nonempty-byte alarm are dropped. No equivalent replacement coverage is claimed. Audit1361: src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts removed. Snapshot/live-proven kitty flags, replacement choice and replay idempotence in the assembled mirror. No equivalent replacement coverage is claimed. Audit1365: focused Linux unit selection passed on source head 8880357cb420c45f1b808ae545a5bc609324624d. This new result has its own exact command; historical results keep their prior scope. Intentional test losses remain recorded in knownGaps. No physical-provider, native input, rendered E2E, p95, soak or replacement-coverage claim. Audit1391: src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.test.ts reduced. Lose explicit one-read/unchanged-style work budget across 30 syllables and single-timer burst alarm. Synthetic screen bounds/terminal cursor bound retained proof to DOM anchor updates, not actual OS IME placement. src/renderer/src/components/terminal-pane/terminal-kitty-csi-u-encoding.test.ts reduced. Lose explicit PC-101 alternate omission, multi-codepoint/control associated text filtering, lock modifier integer, shifted punctuation, standalone separator and printable nonfunctional keypad fallbacks. Retained pure encoding is a wire-contract check without host input delivery. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1396: src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts reduced. Lose standalone handled Ctrl, Shift+Space, shifted non-ASCII keydown and active-composition backspace/arrow/text/Process suppression alarms. No actual IME/PTY encoding occurs. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/lib/keyboard-layout/option-as-alt-probe.test.ts removed. Intentionally loses invalidation, focus/manual refresh gating and stale/newest generation settlement outcomes, including direct stale category suppression. No equivalent replacement or default preload input-source delivery claim. src/renderer/src/components/terminal-pane/terminal-ime-substituted-text-commit.test.ts removed. Intentionally loses substituted sentence punctuation, shifted/backslash/multi-unit/full-width/letter input and Kitty flag/release/report encoding alarms across14 authored registrations. No equivalent replacement or real pane/browser input delivery claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Preload layout cleanup retires the complete mocked macOS keyboard bridge registration. Its API-read forwarding, two-phase payload forwarding and exact listener-disposer alarms are intentionally lost without equivalent replacement. The remaining restart/checkpoint registrations do not cover this IME contract. Unaffected dated receipts retain their original commands and scope; this metadata change claims no new execution. Previous account (preserved verbatim): Audit3699 removes the complete restored app-owned-copy xterm bypass predicate suite (3 authored/3 finite). Intentionally lose Linux/Windows Ctrl+Shift+C keydown/keyup and logical-over-physical-key pass-through, selection/Kitty-disabled/defaultPrevented refusal, and macOS Cmd+C pass-through/selection/Kitty-disabled policy alarms. No actual browser dispatch, clipboard operation, negotiated application bytes, native key delivery or PTY result was established by this driver. No equivalent replacement or fresh execution claimed. Preserve all prior dated receipts and historical accounts. Previous account (preserved verbatim): Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked AgentTerminalPreview component suite is removed, including the snapshot-proven kitty mirror forwarding alarm. Remove its active file, command token and assertion reference; the other IME drivers are unchanged and do not replace the removed component checks. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: 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. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1619 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts: Loses direct timestamp-formula assertion; no useful independent alarm in removed registration. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1361 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1320 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser native-keyboard fallback inventory case. Its empty-chord, absent-layout and no-op-subscription alarms are lost; retained native input evidence is not an equivalent replacement. Historical commands and results remain historical. Local macOS and containerized Linux evidence, deterministic renderer-unit coverage for the Linux/Sogou candidate-key policy including the legacy orphaned-keyup fallback, xterm preedit visibility and row-occlusion behavior, Electron/CDP preedit geometry, Electron/CDP live-PTY Sogou-style repros, and macOS renderer/main slices for Preview kitty commits and layout-native Option input. The Option slice covers complete CSI-u flag fields including lock state, repeat/release event types, authoritative committed associated text, native dead-key release suppression, functional-versus-printable numpad codes, press-pinned release identity, live keyup modifiers, pending-layout text fallback, atomic layout refresh, rapid in-focus input-source changes, stable native layout characters, and both native/web preload fallbacks. The standalone remote SnapshotStart metadata suite is removed. Its proven-zero, nonzero, absent-field and malformed-value propagation alarms are intentionally lost; retained daemon and preview consumer contracts do not establish equivalent remote projection coverage. Historical commands and results remain historical. Real Linux/Sogou OS IME automation, native Windows candidate-window placement, Windows ConPTY post-agent reset, and the CJK/Vietnamese/Arabic matrix remain registered gaps. The audit removes isolated candidate-anchor width, last-column, timer-ordering and detached-textarea examples. The retained deterministic fixtures do not observe a native candidate window or establish equivalent geometry coverage; separate Electron geometry evidence remains historical. The test-value audit removes the empty end-of-row/no-tail composition baseline from terminal-korean-midline-preedit-occlusion.spec.ts. The placeholder masking and measured row-tail occlusion registrations remain; they are not equivalent replacement coverage for the removed empty-tail alarm. No new execution or native IME evidence is claimed. Audit1301: src/renderer/src/components/terminal-pane/terminal-shortcut-option-compose.test.ts reduced. Dead-key/IME variants, Unicode/language inventories, numpad/CapsLock cases and other protocol samples lose their individual alarms. No equivalent replacement coverage is claimed. Audit1320: src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts reduced. Last-complete snapshot while layout-map/native-snapshot partial refresh settles loses its individual implementation-cache alarm. No equivalent replacement coverage is claimed. Audit1342: src/renderer/src/components/terminal-pane/terminal-ime-macos-keybinding-dict-trace.test.ts reduced. Second Korean-layout replay, ordinary Korean/ASCII no-remap baselines and weak Option nonempty-byte alarm are dropped. No equivalent replacement coverage is claimed. Audit1361: src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts removed. Snapshot/live-proven kitty flags, replacement choice and replay idempotence in the assembled mirror. No equivalent replacement coverage is claimed. Audit1365: focused Linux unit selection passed on source head 8880357cb420c45f1b808ae545a5bc609324624d. This new result has its own exact command; historical results keep their prior scope. Intentional test losses remain recorded in knownGaps. No physical-provider, native input, rendered E2E, p95, soak or replacement-coverage claim. Audit1391: src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.test.ts reduced. Lose explicit one-read/unchanged-style work budget across 30 syllables and single-timer burst alarm. Synthetic screen bounds/terminal cursor bound retained proof to DOM anchor updates, not actual OS IME placement. src/renderer/src/components/terminal-pane/terminal-kitty-csi-u-encoding.test.ts reduced. Lose explicit PC-101 alternate omission, multi-codepoint/control associated text filtering, lock modifier integer, shifted punctuation, standalone separator and printable nonfunctional keypad fallbacks. Retained pure encoding is a wire-contract check without host input delivery. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1396: src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts reduced. Lose standalone handled Ctrl, Shift+Space, shifted non-ASCII keydown and active-composition backspace/arrow/text/Process suppression alarms. No actual IME/PTY encoding occurs. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/lib/keyboard-layout/option-as-alt-probe.test.ts removed. Intentionally loses invalidation, focus/manual refresh gating and stale/newest generation settlement outcomes, including direct stale category suppression. No equivalent replacement or default preload input-source delivery claim. src/renderer/src/components/terminal-pane/terminal-ime-substituted-text-commit.test.ts removed. Intentionally loses substituted sentence punctuation, shifted/backslash/multi-unit/full-width/letter input and Kitty flag/release/report encoding alarms across14 authored registrations. No equivalent replacement or real pane/browser input delivery claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6699", "https://github.com/stablyai/orca/pull/6682", @@ -9796,7 +9796,7 @@ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/preload/app-restart-checkpoint-routing.test.ts src/renderer/src/web/web-preload-api-ui.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/renderer/src/web/web-preload-api-ui.test.ts", "pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts", "pnpm run test:e2e -- tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts", "pnpm run test:e2e -- tests/e2e/terminal-option-composed-ascii.spec.ts" @@ -9812,7 +9812,6 @@ "src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts", "src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts", "src/main/ipc/macos-keyboard-layout-change-notifications.test.ts", - "src/preload/app-restart-checkpoint-routing.test.ts", "src/renderer/src/web/web-preload-api-ui.test.ts", "src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts", "src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts", @@ -9856,14 +9855,6 @@ "rapid input-source changes coalesce to one latest-generation refresh signal" ] }, - { - "file": "src/preload/app-restart-checkpoint-routing.test.ts", - "assertions": [ - "macOS keyboard reads and the change subscription remain wired after main integration", - "the two-phase change payload reaches the renderer unchanged", - "the subscription disposer removes the exact IPC listener" - ] - }, { "file": "src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts", "assertions": [ @@ -9992,7 +9983,8 @@ "Audit1896 historical assertion inventory for three retired and three narrowed refs; not current validated assertions. Original raw assertion objects follow:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-trailing-preedit-occlusion.test.ts\",\n \"assertions\": [\n \"rolling Korean input keeps only the uncommitted trailing syllable in the themed overlay\",\n \"the overlay remains anchored to the live cursor cell and clears after commit\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/xterm-bypass-policy-non-mac.test.ts\",\n \"assertions\": [\n \"standalone Linux 229 keydowns reach xterm while Windows 229 keydowns stay suppressed\",\n \"candidate Space/digit selectors are suppressed only while candidate guards are active\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/paste/terminal-paste-runtime.test.ts\",\n \"assertions\": [\"paste/runtime forwarding avoids duplicate terminal payloads\"]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-midline-preedit-tail.test.ts\",\n \"assertions\": [\n \"a mid-line preedit reproduces committed cells hidden by its opaque overlay and refreshes that tail after terminal renders\",\n \"arbitrary fully dimmed output remains visible even at column zero\",\n \"the final-column caret stays visible and the textarea candidate anchor shifts left with an over-wide preedit\",\n \"cancel, empty resumed updates, and disposal remove transient overlay state\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"assertions\": [\n \"recorded Windows Korean compositionupdate-without-compositionstart traces reactivate a visible preedit transaction\",\n \"the resumed transaction commits exactly once and cleans up normally\",\n \"the ordinary Linux compositionstart sequence remains unchanged\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"assertions\": [\n \"owned releases use live Shift and Option state and current alternate-key flags\",\n \"owned releases retain the delivered press identity across layout, Shift, and NumLock changes\",\n \"a native dead-key keyup is consumed without inventing an unmatched protocol release\",\n \"event-type pop consumes without bytes and repeat keydowns cannot replace the original release owner\"\n ]\n }", "Renderer direct-owner cleanup retires the complete layout-base-character suite (one registration). Lost alarm: layout invalidation blocks focus refresh, fences an older snapshot, and accepts the new-generation character. The removed case consumed private snapshot/reset state and internal refresh-count accounting. No equivalent replacement or new execution is claimed. Remaining IME/keyboard/provider sources and the unchanged fcitx4 receipt retain their existing bounded qualifications; this removal does not validate their selectors. Historical removed active mappings (verbatim semantic values; no longer active): [{\"field\":\"testFiles\",\"previous\":[\"src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts\"]},{\"field\":\"commands\",\"previous\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/preload/app-restart-checkpoint-routing.test.ts src/renderer/src/web/web-preload-api-ui.test.ts\"]}]", "Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked AgentTerminalPreview component suite is removed, including the snapshot-proven kitty mirror forwarding alarm. Remove its active file, command token and assertion reference; the other IME drivers are unchanged and do not replace the removed component checks. Earlier notes, complete dated receipts and archived gaps retain their original scopes.", - "Audit3460 historical original active selectors (verbatim JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/preload/app-restart-checkpoint-routing.test.ts src/renderer/src/web/web-preload-api-ui.test.ts\",\n \"pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-option-composed-ascii.spec.ts\"\n ]\ntestFiles: [\n \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts\",\n \"src/shared/terminal/input/terminal-composer-draft.test.ts\",\n \"src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"src/main/ipc/macos-keyboard-layout-change-notifications.test.ts\",\n \"src/preload/app-restart-checkpoint-routing.test.ts\",\n \"src/renderer/src/web/web-preload-api-ui.test.ts\",\n \"src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts\",\n \"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx\",\n \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"src/main/ipc/terminal-preview-output-stream.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"assertions\": [\n \"real fcitx4 Sogou captures (GTK module and XIM) send only the committed candidate for Space and digit picks, under legacy keys and kitty flags 1 and 5\",\n \"a real fcitx4 Google Pinyin in-client preedit still commits through the composition path\",\n \"an XIM pick's code-less keydown pairs with its keyup so kitty event reporting sends one release per pick\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"assertions\": [\"A transaction inferred from update alone commits and cleans up.\"]\n },\n {\n \"file\": \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"assertions\": [\n \"a live kitty-negotiated pane receives the Option-composed ASCII character, not the physical alt chord\",\n \"an Option layer that also needs Shift still reaches the pty as text\",\n \"configured Option-as-Alt still reports the layout-resolved physical chord\",\n \"a non-ASCII Option glyph still reaches the application as its alt hotkey\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"assertions\": [\n \"Autorepeat cannot replace the first release sender; a fresh press can replace an orphaned sender for the same key.\"\n ]\n },\n {\n \"file\": \"src/main/ipc/macos-keyboard-layout-change-notifications.test.ts\",\n \"assertions\": [\n \"rapid input-source changes coalesce to one latest-generation refresh signal\"\n ]\n },\n {\n \"file\": \"src/preload/app-restart-checkpoint-routing.test.ts\",\n \"assertions\": [\n \"macOS keyboard reads and the change subscription remain wired after main integration\",\n \"the two-phase change payload reaches the renderer unchanged\",\n \"the subscription disposer removes the exact IPC listener\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts\",\n \"assertions\": [\n \"the real forwarder behind the Preview bridge encodes the commit from the snapshot-proven flags before any live output\",\n \"flags 0/1 commit raw text, flags 2 add one CSI-u release, flags 8 emit one CSI-u press, and flags 10 emit a CSI-u press followed by exactly one release\",\n \"both keydown->insertText->keyup and keydown->keyup->insertText orderings produce the same bytes\",\n \"the release is emitted by the forwarder while xterm's internal kitty flags stay 0\",\n \"the mutable flags getter is read exactly once, at commit time, never on keydown or keyup\",\n \"auto-repeat, two-key rollover, a swallowed commit, a retired claim, blur, and disposal each emit at most one release and never synthesize one\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx\",\n \"assertions\": [\n \"the Preview hands the forwarder the live kitty mirror seeded from the snapshot's proven flags\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"assertions\": [\n \"a fresh PTY's known 0 is distinguishable from a snapshot's unproven 0 fallback\",\n \"restoreSnapshotFlags proves only the active screen\",\n \"provenance survives absolute sets, screen switches, RIS and DECSTR, but a pop past omitted push history returns to unknown rather than a manufactured 0\"\n ]\n },\n {\n \"file\": \"src/main/ipc/terminal-preview-output-stream.test.ts\",\n \"assertions\": [\n \"a partially covered sequenced chunk retains exactly its unseen suffix in live mode\",\n \"a transformed overlap remains unsliced in replay mode\"\n ]\n },\n {\n \"file\": \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"assertions\": [\n \"Sogou-style Space candidate selection submits only the committed Chinese character\",\n \"Sogou-style digit candidate selection submits only the committed Chinese phrase\",\n \"Post-composition Sogou-style digit selection stays out of the PTY after compositionend\",\n \"Legacy orphaned-letter-keyup digit selection submits no selector byte to the PTY; real legacy candidate commit preservation remains a platform gap\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"assertions\": [\n \"the rendered final-column preedit caret remains inside the terminal screen\",\n \"a rendered full-width Korean preedit spans materially more than the one terminal cell reported in #12729\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"assertions\": [\n \"the rendered opaque overlay reproduces every committed row-tail cell its measured rectangle hides\",\n \"a real Codex placeholder with bold prompt, blank footer gap, model footer, and cursor at column 2 stays masked\"\n ]\n }\n ]" + "Audit3460 historical original active selectors (verbatim JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/preload/app-restart-checkpoint-routing.test.ts src/renderer/src/web/web-preload-api-ui.test.ts\",\n \"pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-option-composed-ascii.spec.ts\"\n ]\ntestFiles: [\n \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts\",\n \"src/shared/terminal/input/terminal-composer-draft.test.ts\",\n \"src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"src/main/ipc/macos-keyboard-layout-change-notifications.test.ts\",\n \"src/preload/app-restart-checkpoint-routing.test.ts\",\n \"src/renderer/src/web/web-preload-api-ui.test.ts\",\n \"src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts\",\n \"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx\",\n \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"src/main/ipc/terminal-preview-output-stream.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"assertions\": [\n \"real fcitx4 Sogou captures (GTK module and XIM) send only the committed candidate for Space and digit picks, under legacy keys and kitty flags 1 and 5\",\n \"a real fcitx4 Google Pinyin in-client preedit still commits through the composition path\",\n \"an XIM pick's code-less keydown pairs with its keyup so kitty event reporting sends one release per pick\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"assertions\": [\"A transaction inferred from update alone commits and cleans up.\"]\n },\n {\n \"file\": \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"assertions\": [\n \"a live kitty-negotiated pane receives the Option-composed ASCII character, not the physical alt chord\",\n \"an Option layer that also needs Shift still reaches the pty as text\",\n \"configured Option-as-Alt still reports the layout-resolved physical chord\",\n \"a non-ASCII Option glyph still reaches the application as its alt hotkey\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"assertions\": [\n \"Autorepeat cannot replace the first release sender; a fresh press can replace an orphaned sender for the same key.\"\n ]\n },\n {\n \"file\": \"src/main/ipc/macos-keyboard-layout-change-notifications.test.ts\",\n \"assertions\": [\n \"rapid input-source changes coalesce to one latest-generation refresh signal\"\n ]\n },\n {\n \"file\": \"src/preload/app-restart-checkpoint-routing.test.ts\",\n \"assertions\": [\n \"macOS keyboard reads and the change subscription remain wired after main integration\",\n \"the two-phase change payload reaches the renderer unchanged\",\n \"the subscription disposer removes the exact IPC listener\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts\",\n \"assertions\": [\n \"the real forwarder behind the Preview bridge encodes the commit from the snapshot-proven flags before any live output\",\n \"flags 0/1 commit raw text, flags 2 add one CSI-u release, flags 8 emit one CSI-u press, and flags 10 emit a CSI-u press followed by exactly one release\",\n \"both keydown->insertText->keyup and keydown->keyup->insertText orderings produce the same bytes\",\n \"the release is emitted by the forwarder while xterm's internal kitty flags stay 0\",\n \"the mutable flags getter is read exactly once, at commit time, never on keydown or keyup\",\n \"auto-repeat, two-key rollover, a swallowed commit, a retired claim, blur, and disposal each emit at most one release and never synthesize one\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx\",\n \"assertions\": [\n \"the Preview hands the forwarder the live kitty mirror seeded from the snapshot's proven flags\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"assertions\": [\n \"a fresh PTY's known 0 is distinguishable from a snapshot's unproven 0 fallback\",\n \"restoreSnapshotFlags proves only the active screen\",\n \"provenance survives absolute sets, screen switches, RIS and DECSTR, but a pop past omitted push history returns to unknown rather than a manufactured 0\"\n ]\n },\n {\n \"file\": \"src/main/ipc/terminal-preview-output-stream.test.ts\",\n \"assertions\": [\n \"a partially covered sequenced chunk retains exactly its unseen suffix in live mode\",\n \"a transformed overlap remains unsliced in replay mode\"\n ]\n },\n {\n \"file\": \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"assertions\": [\n \"Sogou-style Space candidate selection submits only the committed Chinese character\",\n \"Sogou-style digit candidate selection submits only the committed Chinese phrase\",\n \"Post-composition Sogou-style digit selection stays out of the PTY after compositionend\",\n \"Legacy orphaned-letter-keyup digit selection submits no selector byte to the PTY; real legacy candidate commit preservation remains a platform gap\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"assertions\": [\n \"the rendered final-column preedit caret remains inside the terminal screen\",\n \"a rendered full-width Korean preedit spans materially more than the one terminal cell reported in #12729\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"assertions\": [\n \"the rendered opaque overlay reproduces every committed row-tail cell its measured rectangle hides\",\n \"a real Codex placeholder with bold prompt, blank footer gap, model footer, and cursor at column 2 stays masked\"\n ]\n }\n ]", + "Preload layout cleanup retires the complete mocked macOS keyboard bridge registration. Its API-read forwarding, two-phase payload forwarding and exact listener-disposer alarms are intentionally lost without equivalent replacement. The remaining restart/checkpoint registrations do not cover this IME contract. Unaffected dated receipts retain their original commands and scope; this metadata change claims no new execution. Retired assertion reference: {\"file\":\"src/preload/app-restart-checkpoint-routing.test.ts\",\"assertions\":[\"macOS keyboard reads and the change subscription remain wired after main integration\",\"the two-phase change payload reaches the renderer unchanged\",\"the subscription disposer removes the exact IPC listener\"]}" ], "demotionRule": "Cannot promote if success is based only on DOM text without PTY byte/cell evidence." }, diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 38ac05a3f8c..b19b9bd1a84 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -770,7 +770,6 @@ "src/main/automations/automation-dispatch-host-fence.test.ts": 2592, "src/main/automations/automation-owner-fencing.test.ts": 2028, "src/main/automations/automation-run-terminal-surface.test.ts": 4180, - "src/main/automations/automation-skip-coalescing.test.ts": 2577, "src/main/automations/ownership/automation-ssh-readoption-migration.test.ts": 59, "src/main/automations/automation-update-host-retarget.test.ts": 1842, @@ -945,7 +944,6 @@ "src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts": 832, "src/main/browser/extensions/installation/browser-extension-archive.test.ts": 72, "src/main/browser/extensions/actions/browser-extension-commands.test.ts": 52, - "src/main/browser/extensions/api-runtime/browser-extension-content-script-persistence.test.ts": 313, "src/main/browser/extensions/context-menus/browser-extension-context-menu-host.test.ts": 68, "src/main/browser/extensions/context-menus/browser-extension-context-menu-model.test.ts": 57, "src/main/browser/extensions/installation/browser-extension-crx.test.ts": 214, @@ -4125,32 +4123,25 @@ "src/packages/process-host/src/windows-tree-kill.test.ts": 81, "src/packages/process-host/src/wsl-distro-allowlist.test.ts": 55, "src/preload/api/notification-sound-playback.test.ts": 64, - "src/preload/api/platform-bridge.test.ts": 48, - "src/preload/app-restart-checkpoint-routing.test.ts": 2028, - "src/preload/browser-client-page-renderer-requests.test.ts": 154, - "src/preload/browser-extension-content-script-relay.test.ts": 65, - "src/preload/browser-extension-document-targets.test.ts": 75, - "src/preload/browser-extension-inert-apis.test.ts": 50, - "src/preload/browser-extension-main-world.test.ts": 81, - "src/preload/browser-extension-native-messaging.test.ts": 70, - "src/preload/browser-extension-storage-relay.test.ts": 104, - "src/preload/browser-extension-storage-sync.test.ts": 108, - "src/preload/browser-extension-web-store-main-world.test.ts": 166, - "src/preload/browser-extension-web-store-wording.test.ts": 194, - "src/preload/browser-find-subscriptions.test.ts": 66, + "src/preload/renderer/restart/app-restart-checkpoint-routing.test.ts": 2028, + "src/preload/renderer/browser-pages/browser-client-page-renderer-requests.test.ts": 154, + "src/preload/browser/extensions/messaging/browser-extension-content-script-relay.test.ts": 65, + "src/preload/browser/extensions/documents/browser-extension-document-targets.test.ts": 75, + "src/preload/browser/extensions/api/browser-extension-inert-apis.test.ts": 50, + "src/preload/browser/extensions/api/browser-extension-main-world.test.ts": 81, + "src/preload/browser/extensions/storage/browser-extension-storage-relay.test.ts": 104, + "src/preload/browser/extensions/storage/browser-extension-storage-sync.test.ts": 108, + "src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.test.ts": 166, + "src/preload/renderer/browser-pages/browser-find-subscriptions.test.ts": 66, "src/preload/browser-window-close.test.ts": 98, - "src/preload/close-active-tab-payload-admission.test.ts": 48, + "src/preload/renderer/window-commands/close-active-tab-payload-admission.test.ts": 48, "src/preload/doc-preview-link-interception.test.ts": 234, - "src/preload/gitlab-work-item-details.test.ts": 49, - "src/preload/opencode-go-credentials.test.ts": 45, - "src/preload/plugin-frame-guest-render-lane.test.ts": 47, - "src/preload/plugin-frame-guest.test.ts": 287, - "src/preload/renderer-heap-statistics-reader.test.ts": 50, - "src/preload/renderer-process-memory-reader.test.ts": 66, - "src/preload/renderer-restart-wiring.test.ts": 96, - "src/preload/ssh-authority-forwarding.test.ts": 1111, - "src/preload/updater-package-recovery.test.ts": 1102, - "src/preload/usage-provider-api.test.ts": 46, + "src/preload/plugins/frames/plugin-frame-guest-render-lane.test.ts": 47, + "src/preload/plugins/frames/plugin-frame-guest.test.ts": 287, + "src/preload/renderer/diagnostics/renderer-heap-statistics-reader.test.ts": 50, + "src/preload/renderer/diagnostics/renderer-process-memory-reader.test.ts": 66, + "src/preload/renderer/restart/renderer-restart-wiring.test.ts": 96, + "src/preload/api/ssh-authority-forwarding.test.ts": 1111, "src/renderer/src/app-shell/shutdown-checkpoint-persist.test.ts": 65, "src/renderer/src/app-shell/use-profile-state-save-delay-notice.sonner.test.tsx": 355, "src/renderer/src/app-shell/use-profile-state-save-delay-notice.test.tsx": 293, @@ -4771,7 +4762,6 @@ "src/renderer/src/components/plain-ssh-terminal/PlainSshTerminalPanels.test.tsx": 2510, "src/renderer/src/components/plugins/declarative/PluginDeclarativeView.test.tsx": 2804, "src/renderer/src/components/plugins/dialogs/PluginUpdateAllDialog.test.tsx": 2313, - "src/renderer/src/components/plugins/list/PluginManager.test.tsx": 3449, "src/renderer/src/components/plugins/list/plugin-list-entries.test.ts": 231, "src/renderer/src/components/plugins/page/PluginAddsSection.test.tsx": 2043, "src/renderer/src/components/plugins/page/PluginCommandReplacementRow.test.tsx": 1926, @@ -4779,7 +4769,6 @@ "src/renderer/src/components/plugins/page/PluginSettingsSection.test.tsx": 572, "src/renderer/src/components/plugins/state/use-plugin-contribution-source.test.tsx": 1935, "src/renderer/src/components/plugins/state/use-plugin-install-link.test.tsx": 518, - "src/renderer/src/components/plugins/state/use-plugin-page-navigation.test.tsx": 480, "src/renderer/src/components/plugins/state/use-plugin-review-queue.test.tsx": 389, "src/renderer/src/components/plugins/view/plugin-view-acts.test.tsx": 3241, "src/renderer/src/components/plugins/view/plugin-view-data-acts.test.tsx": 3002, diff --git a/config/tsconfig.tc.web.json b/config/tsconfig.tc.web.json index b0f23d98c71..95529130196 100644 --- a/config/tsconfig.tc.web.json +++ b/config/tsconfig.tc.web.json @@ -14,18 +14,20 @@ "../src/renderer/src/**/*.tsx", "../src/preload/api-types.ts", "../src/preload/api/**/*", - "../src/preload/backend-port-client.ts", - "../src/preload/browser-client-page-renderer-requests.ts", - "../src/preload/browser-find-subscriptions.ts", - "../src/preload/close-active-tab-payload-admission.ts", - "../src/preload/e2e-config.ts", - "../src/preload/gitlab.ts", - "../src/preload/preload-runtime-support.ts", - "../src/preload/renderer-heap-statistics-reader.ts", - "../src/preload/renderer-process-memory-reader.ts", - "../src/preload/renderer-restart-wiring.ts", - "../src/preload/runtime-environment-subscriptions.ts", - "../src/preload/usage-provider-api.ts", + "../src/preload/index.ts", + "../src/preload/usage/backend-port-client.ts", + "../src/preload/renderer/browser-pages/browser-client-page-renderer-requests.ts", + "../src/preload/renderer/browser-pages/browser-find-subscriptions.ts", + "../src/preload/renderer/window-commands/close-active-tab-payload-admission.ts", + "../src/preload/renderer/e2e-config.ts", + "../src/preload/renderer/hidden-window-frame-pump.ts", + "../src/preload/api/gitlab.ts", + "../src/preload/renderer/renderer-runtime.ts", + "../src/preload/renderer/diagnostics/renderer-heap-statistics-reader.ts", + "../src/preload/renderer/diagnostics/renderer-process-memory-reader.ts", + "../src/preload/renderer/restart/renderer-restart-wiring.ts", + "../src/preload/runtime/runtime-environment-subscriptions.ts", + "../src/preload/usage/usage-provider-api.ts", "../src/main/pi/rpc/options/rpc-model-schema.ts", "../src/main/pi/rpc/options/rpc-model-options.ts", "../src/shared/**/*", diff --git a/src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts b/src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts index eaa68d7e2ce..137b4712532 100644 --- a/src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts +++ b/src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts @@ -228,7 +228,12 @@ async function runFixture(): Promise { const resultPath = join(root, 'result.json') writeFileSync( preloadSource, - preloadEntry(join(process.cwd(), 'src/preload/browser-client-page-renderer-requests.ts')) + preloadEntry( + join( + process.cwd(), + 'src/preload/renderer/browser-pages/browser-client-page-renderer-requests.ts' + ) + ) ) writeFileSync( rendererSource, diff --git a/src/main/browser/extensions/api-runtime/browser-extension-api-host.test.ts b/src/main/browser/extensions/api-runtime/browser-extension-api-host.test.ts index c1a882d765d..20cdd567c36 100644 --- a/src/main/browser/extensions/api-runtime/browser-extension-api-host.test.ts +++ b/src/main/browser/extensions/api-runtime/browser-extension-api-host.test.ts @@ -70,7 +70,7 @@ mocks.userData = mkdtempSync(join(tmpdir(), 'orca-extension-api-host-')) const { BROWSER_EXTENSION_INVOKE_CHANNEL } = await import('../../../../shared/browser/extensions/browser-extension-channels') -await import('../../../../preload/browser-extension-api-surface') +await import('../../../../preload/browser/extensions/api/browser-extension-api-surface') const registry = await import('./browser-extension-namespace-registry') const host = await import('./browser-extension-api-host') const contexts = await import('./browser-extension-contexts') @@ -180,22 +180,6 @@ describe('extension API host', () => { }) }) -it('retires the current host after extension support restarts in the same document', async () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the session boundary copies the extensions, serviceWorkers and protocol members consumed by the actual host. - const isolated = { ...extensionSession } as unknown as Electron.Session - host.attachBrowserExtensionApiHostToSession(isolated, 'restarted') - const current = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, isolated, 10, 1) - const listen = { type: 'listen', namespace: 'probe', event: 'onPing', active: true } - await invoke(current.event, listen) - host.forgetBrowserExtensionContexts(isolated) - host.attachBrowserExtensionApiHostToSession(isolated, 'restarted') - await invoke(current.event, listen) - current.event.sender.emit('did-navigate') - expect(contexts.getHostSessionState(isolated)?.frames.size).toBe(0) - expect(contexts.browserExtensionEventHasListener(isolated, 'probe', 'onPing')).toBe(false) - host.forgetBrowserExtensionContexts(isolated) -}) - describe('extension subframe listener retirement', () => { const listen = { type: 'listen', namespace: 'probe', event: 'onPing', active: true } @@ -218,66 +202,6 @@ describe('extension subframe listener retirement', () => { return current } - it('shares one port across listeners and replaces it after final removal', async () => { - const { sess, state } = isolatedSession() - const page = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 21, 1) - await invoke(page.event, listen) - const first = channel() - const lateClose = first.port1.listeners('close')[0] - await invoke(page.event, listen) - await invoke(page.event, { ...listen, namespace: 'tabs', event: 'onCreated' }) - expect(page.frame.postMessage).toHaveBeenCalledTimes(1) - await invoke(page.event, { ...listen, active: false }) - expect(state.frames.size).toBe(1) - expect(first.port1.close).not.toHaveBeenCalled() - await invoke(page.event, { ...listen, namespace: 'tabs', event: 'onCreated', active: false }) - expect(state.frames.size).toBe(0) - expect(first.port1.close).toHaveBeenCalledTimes(1) - expect(first.port1.listenerCount('close')).toBe(0) - await invoke(page.event, listen) - expect(channel()).not.toBe(first) - lateClose?.() - host.emitBrowserExtensionEvent({ session: sess }, 'probe', 'onPing', ['successor']) - expect(page.frame.send).toHaveBeenCalledTimes(1) - expect(state.frames.size).toBe(1) - host.forgetBrowserExtensionContexts(sess) - }) - - it('preserves sibling frames, windows, sessions and worker listeners', async () => { - const { sess, state } = isolatedSession() - const elsewhere = isolatedSession() - const removed = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 22, 1) - const sibling = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 22, 2) - sibling.event.sender = removed.event.sender - const window = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, sess, 22, 3) - window.event.sender.id = 78 - const other = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, elsewhere.sess, 23, 1) - await invoke(removed.event, listen) - const owner = channel() - await invoke(sibling.event, listen) - await invoke(window.event, listen) - await invoke(other.event, listen) - const worker = contexts.ensureWorkerContext( - state, - EXTENSION_ID, - `chrome-extension://${EXTENSION_ID}/` - ) - worker.events.add('probe.onPing') - worker.stream = { send: vi.fn(), close: vi.fn() } - owner.port1.emit('close') - host.emitBrowserExtensionEvent({}, 'probe', 'onPing', ['survivors']) - expect(removed.frame.send).not.toHaveBeenCalled() - for (const frame of [sibling.frame, window.frame, other.frame]) { - expect(frame.send).toHaveBeenCalledTimes(1) - } - expect(worker.stream.send).toHaveBeenCalledTimes(1) - expect(worker.stream.close).not.toHaveBeenCalled() - expect(state.frames.size).toBe(2) - expect(elsewhere.state.frames.size).toBe(1) - host.forgetBrowserExtensionContexts(sess) - host.forgetBrowserExtensionContexts(elsewhere.sess) - }) - it('keeps extension membership snapshotted while resolving current frames after callbacks', async () => { const { sess } = isolatedSession() const first = frameEvent(`chrome-extension://${EXTENSION_ID}/first.html`, sess, 41, 1) diff --git a/src/main/browser/extensions/api-runtime/browser-extension-content-script-persistence.test.ts b/src/main/browser/extensions/api-runtime/browser-extension-content-script-persistence.test.ts deleted file mode 100644 index af0d8e07d20..00000000000 --- a/src/main/browser/extensions/api-runtime/browser-extension-content-script-persistence.test.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { mkdtempSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { runInNewContext } from 'node:vm' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { ContentScriptMethod } from './browser-extension-content-scripts' - -type Script = Record & { id: string } -const mocks = vi.hoisted(() => ({ - directory: '', - scripts: new Map(), - beforeExecute: async (): Promise => {}, - beforeCallback: async (): Promise => {}, - nativeError: '', - windows: new Array<{ options: unknown; destroyed: boolean }>() -})) -vi.mock('electron', () => ({ - app: { on() {} }, - webFrameMain: { fromId() {} }, - BrowserWindow: class { - record: { options: unknown; destroyed: boolean } - constructor(options: unknown) { - this.record = { options, destroyed: false } - mocks.windows.push(this.record) - } - async loadURL() {} - webContents = { - executeJavaScript: async (code: string) => { - await mocks.beforeExecute() - const runtime: { lastError?: { message: string } } = {} - const complete = async (callback: (value?: unknown) => void, value?: unknown) => { - await mocks.beforeCallback() - if (mocks.nativeError) { - runtime.lastError = { message: mocks.nativeError } - } - callback(value) - delete runtime.lastError - } - return runInNewContext(code, { - chrome: { - runtime, - scripting: { - registerContentScripts(scripts: Script[], callback: () => void) { - if (!mocks.nativeError) { - for (const script of scripts) { - if (mocks.scripts.has(script.id)) { - runtime.lastError = { message: 'Duplicate script ID' } - callback() - delete runtime.lastError - return - } - mocks.scripts.set(script.id, { ...script }) - } - } - complete(callback) - }, - updateContentScripts(updates: Script[], callback: () => void) { - if (!mocks.nativeError) { - for (const update of updates) { - mocks.scripts.set(update.id, { ...mocks.scripts.get(update.id), ...update }) - } - } - complete(callback) - }, - unregisterContentScripts(filter: { ids?: string[] }, callback: () => void) { - for (const id of filter.ids ?? [...mocks.scripts.keys()]) { - mocks.scripts.delete(id) - } - complete(callback) - }, - getRegisteredContentScripts( - filterOrCallback: { ids?: string[] } | ((value: Script[]) => void), - callback?: (value: Script[]) => void - ) { - const filter = typeof filterOrCallback === 'function' ? {} : filterOrCallback - const done = typeof filterOrCallback === 'function' ? filterOrCallback : callback - done?.( - [...mocks.scripts.values()] - .filter((script) => !filter.ids || filter.ids.includes(script.id)) - .map((script) => ({ ...script })) - ) - } - } - } - }) - } - } - destroy() { - this.record.destroyed = true - } - } -})) -vi.mock('../profile-storage/browser-extension-profile-data-directory', () => ({ - getBrowserExtensionProfileDataDirectory: () => mocks.directory -})) -mocks.directory = mkdtempSync(join(tmpdir(), 'orca-content-script-persistence-')) - -const registry = await import('./browser-extension-namespace-registry') -const { registerScriptingNamespaces } = await import('../api/scripting') -const { forgetBrowserExtensionContentScriptRestore, restoreBrowserExtensionContentScripts } = - await import('./browser-extension-content-scripts') -const { getBrowserExtensionProfileStateStore } = - await import('../profile-storage/browser-extension-profile-state-store') -const { installBrowserExtensionApis } = - await import('../../../../preload/browser-extension-main-world') -const { BROWSER_EXTENSION_API_SURFACE } = - await import('../../../../preload/browser-extension-api-surface') -const extension: Electron.Extension = { - id: 'a'.repeat(32), - name: 'Popup only', - version: '1', - path: '/example', - url: '', - manifest: { - manifest_version: 3, - permissions: ['scripting'], - action: { default_popup: 'popup.html' } - } -} -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: native page creation is mocked; the owner only uses session identity. -const session = {} as Electron.Session -const store = getBrowserExtensionProfileStateStore() -const stored = () => store.read('default', extension.id).contentScripts -function context(fromWorker: boolean) { - const scripting: Partial> = {} - const chrome = { runtime: { getManifest: () => extension.manifest }, scripting } - const bridge = { - call: async (namespace: string, method: string, args: unknown[]) => ({ - ok: true, - value: await registry - .getBrowserExtensionNamespace(namespace) - ?.methods[method].invoke( - { extension, session, browserProfileId: 'default', fromWorker }, - args - ) - }), - listen() {}, - onEvent() {}, - passesFilter: () => true - } - runInNewContext(`(${installBrowserExtensionApis.toString()})(bridge, surface)`, { - chrome, - bridge, - console, - surface: { scripting: BROWSER_EXTENSION_API_SURFACE.scripting } - }) - const call = async (method: ContentScriptMethod, ...args: unknown[]) => { - const fn = chrome.scripting[method] - if (typeof fn !== 'function') { - throw new Error('Missing scripting method') - } - return fn(...args) - } - return call -} -registerScriptingNamespaces() -beforeEach(() => { - forgetBrowserExtensionContentScriptRestore(session, extension.id) - mocks.scripts.clear() - mocks.windows.length = 0 - mocks.beforeExecute = async () => {} - mocks.beforeCallback = async () => {} - mocks.nativeError = '' - store.update('default', extension.id, (state) => ({ ...state, contentScripts: [] })) -}) - -describe('native content script ownership', () => { - it('retires timed-out native work instead of allowing a successor to overlap it', async () => { - const script = { id: 'saved', js: ['saved.js'] } - store.update('default', extension.id, (state) => ({ ...state, contentScripts: [script] })) - let release = () => {} - let completed = () => {} - const nativeCompleted = new Promise((resolve) => { - completed = resolve - }) - mocks.beforeCallback = () => - new Promise((resolve) => { - release = () => { - resolve() - completed() - } - }) - await expect( - restoreBrowserExtensionContentScripts(session, 'default', extension, 1) - ).rejects.toThrow('timed out') - await expect(context(false)('unregisterContentScripts', {})).rejects.toThrow('timed out') - expect(mocks.windows).toHaveLength(1) - expect(mocks.windows[0].destroyed).toBe(true) - expect([...mocks.scripts.values()]).toEqual([script]) - release() - await nativeCompleted - expect(stored()).toEqual([script]) - }) -}) diff --git a/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts b/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts index 0b5419b68ba..4cad31a7369 100644 --- a/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts +++ b/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts @@ -72,15 +72,10 @@ const { getBrowserExtensionProfileStateStore } = const menuHost = await import('../context-menus/browser-extension-context-menu-host') const webRequest = await import('../requests/browser-extension-web-request-observer') const { setBrowserExtensionSupportEnabled } = await import('../browser-extension-support') -const contexts = await import('../api-runtime/browser-extension-contexts') -const eventDispatch = await import('../api-runtime/browser-extension-event-dispatch') -const { attachWorkerEventStream } = - await import('../api-runtime/browser-extension-worker-event-stream') -const { handleBrowserExtensionApiRequest } = - await import('../api-runtime/browser-extension-api-request') -await import('../../../../preload/browser-extension-storage-relay') + +await import('../../../../preload/browser/extensions/storage/browser-extension-storage-relay') const { PRELOAD_STORAGE_SYNC_NAMESPACE } = - await import('../../../../preload/browser-extension-storage-sync') + await import('../../../../preload/browser/extensions/storage/browser-extension-storage-sync') const VAULT = 'a'.repeat(32) const OTHER = 'b'.repeat(32) @@ -205,79 +200,6 @@ beforeEach(() => { mocks.prompt.mockReset() }) -describe('permissions.request', () => { - it.each(['extension unload', 'profile deletion'] as const)( - 'does not recreate grants when accepted after %s', - async (reason) => { - const extensionId = (reason === 'extension unload' ? 'd' : 'e').repeat(32) - extensions.set(extensionId, makeExtension(extensionId, { optional_permissions: ['privacy'] })) - let answer: (accepted: boolean) => void = () => {} - mocks.prompt.mockReturnValueOnce( - new Promise((resolve) => { - answer = resolve - }) - ) - const pending = call( - extensionId, - 'permissions', - 'request', - [{ permissions: ['privacy'] }], - 'page' - ) - const store = getBrowserExtensionProfileStateStore() - if (reason === 'extension unload') { - extensionSession.extensions.emit('extension-unloaded', {}, extensions.get(extensionId)) - store.forgetExtension(extensionId) - } else { - host.forgetBrowserExtensionContexts(session) - store.forgetProfile('default') - } - answer(true) - await expect(pending).resolves.toBe(false) - expect(store.readProfile('default')).not.toHaveProperty(extensionId) - host.attachBrowserExtensionApiHostToSession(session, 'default') - } - ) - - it('delivers a previously registered optional event only while permission is granted', async () => { - const extensionId = 'f'.repeat(32) - extensions.set(extensionId, makeExtension(extensionId, { optional_permissions: ['privacy'] })) - const event = 'services.passwordSavingEnabled.onChange' - const frame = await listenFrame(extensionId, 'privacy', event) - const state = contexts.getHostSessionState(session) - if (!state) { - throw new Error('Session not attached') - } - const worker = contexts.ensureWorkerContext( - state, - extensionId, - `chrome-extension://${extensionId}/` - ) - const listen = () => - handleBrowserExtensionApiRequest( - caller(extensionId), - state, - { type: 'listen', namespace: 'privacy', event, active: true }, - { kind: 'worker', context: worker } - ) - await expect(listen()).resolves.toEqual({ ok: true, value: undefined }) - host.emitBrowserExtensionEvent({ session, extensionId }, 'privacy', event, [{ value: false }]) - expect(frame.payloads()).toEqual([]) - mocks.prompt.mockResolvedValueOnce(true) - await call(extensionId, 'permissions', 'request', [{ permissions: ['privacy'] }], 'page') - host.emitBrowserExtensionEvent({ session, extensionId }, 'privacy', event, [{ value: false }]) - expect(frame.payloads()).toEqual([[{ value: false }]]) - expect(worker.queue).toHaveLength(1) - await call(extensionId, 'permissions', 'remove', [{ permissions: ['privacy'] }]) - const send = vi.fn() - attachWorkerEventStream(worker, { send, close() {} }) - await expect(listen()).resolves.toEqual({ ok: true, value: undefined }) - expect(send).not.toHaveBeenCalled() - host.emitBrowserExtensionEvent({ session, extensionId }, 'privacy', event, [{ value: true }]) - expect(frame.payloads()).toEqual([[{ value: false }]]) - }) -}) - describe('context menus in the page menu', () => { const guest = { id: 900, @@ -379,63 +301,10 @@ describe('storage.sync', () => { ) } - function listeningWorker(sess: Electron.Session, extensionId: string) { - const state = contexts.getHostSessionState(sess) - if (!state) { - throw new Error('Session is not attached') - } - const context = contexts.ensureWorkerContext( - state, - extensionId, - `chrome-extension://${extensionId}/` - ) - context.events.add(eventDispatch.eventKey(SYNC, 'onChanged')) - const send = vi.fn() - attachWorkerEventStream(context, { send, close: vi.fn() }) - return { changes: () => send.mock.calls.map(([payload]) => payload.args) } - } - beforeEach(async () => { await sync('clear', []) }) - it('sends exact old and new values to the extension pages and worker in that session only', async () => { - host.attachBrowserExtensionApiHostToSession(workSession, 'work') - const worker = listeningWorker(session, VAULT) - const page = await listenFrame(VAULT, SYNC, 'onChanged') - const otherExtension = listeningWorker(session, OTHER) - const otherProfile = listeningWorker(workSession, VAULT) - const fromPage = { kind: 'page' } as const - - const written = { a: { newValue: 1 }, b: { newValue: { deep: [1] } } } - // The writer gets its changes back and fires its own listeners. - await expect(sync('set', [{ a: 1, b: { deep: [1] } }], fromPage)).resolves.toEqual(written) - await sync('set', [{ a: 1, b: { deep: [2] } }], fromPage) - await expect(sync('set', [{ a: 1 }], fromPage)).resolves.toEqual({}) - await sync('remove', [['a', 'missing']], fromPage) - await sync('clear', [], fromPage) - await sync('clear', [], fromPage) - const expected = [ - [written], - [{ b: { oldValue: { deep: [1] }, newValue: { deep: [2] } } }], - [{ a: { oldValue: 1 } }], - [{ b: { oldValue: { deep: [2] } } }] - ] - expect(worker.changes()).toEqual(expected) - expect(page.payloads()).toEqual(expected) - expect(otherExtension.changes()).toEqual([]) - expect(otherProfile.changes()).toEqual([]) - - await sync('set', [{ fromWorker: 1 }]) - expect(worker.changes()).toHaveLength(4) - expect(page.payloads().at(-1)).toEqual([{ fromWorker: { newValue: 1 } }]) - - await sync('set', [{ mine: true }]) - await expect(sync('get', [null], { extensionId: OTHER })).resolves.toEqual({}) - await expect(sync('get', [null], { profile: 'work' })).resolves.toEqual({}) - await sync('clear', []) - }) - it('validates an atomic batch against its final size regardless of key order', async () => { const initial = Object.fromEntries( Array.from({ length: 12 }, (_, index) => [`key${index}`, 'x'.repeat(8000)]) diff --git a/src/main/browser/extensions/api/declarative-net-request.test.ts b/src/main/browser/extensions/api/declarative-net-request.test.ts index 1c933fdb927..44a63993765 100644 --- a/src/main/browser/extensions/api/declarative-net-request.test.ts +++ b/src/main/browser/extensions/api/declarative-net-request.test.ts @@ -29,14 +29,12 @@ const { attachBrowserExtensionDnr, getDnrSessionRuntime } = const { browserExtensionDnrRequestDecider: decider } = await import('../declarative-net-request/session/browser-extension-dnr-requests') await import('../declarative-net-request/session/browser-extension-dnr-limits') -await import('../../../../preload/browser-extension-api-surface') +await import('../../../../preload/browser/extensions/api/browser-extension-api-surface') const { getBrowserExtensionDnrStore } = await import('../declarative-net-request/session/browser-extension-dnr-store') const { registerPermissionsNamespace } = await import('./permissions') -const { ensureHostSessionState } = await import('../api-runtime/browser-extension-contexts') -const { getBrowserExtensionInstallStore } = - await import('../installation/browser-extension-install-store') + registerPermissionsNamespace() registerDeclarativeNetRequestNamespace() @@ -132,137 +130,4 @@ describe('chrome.declarativeNetRequest', () => { expect(next.blocks('https://z.example/1.js')).toBe(true) await next.call('updateDynamicRules', { removeRuleIds: [1, 3] }) }) - - it('switches static rulesets, and an update brings back the manifest choice', async () => { - const { call, blocks } = await launch() - await expect(call('getEnabledRulesets')).resolves.toEqual(['a']) - await call('updateEnabledRulesets', { enableRulesetIds: ['b'], disableRulesetIds: ['a'] }) - expect(blocks('https://b.example/x.js')).toBe(true) - expect(blocks('https://a.example/x.js')).toBe(false) - await expect(call('updateEnabledRulesets', { enableRulesetIds: ['zzz'] })).rejects.toThrow( - 'Invalid ruleset id: zzz.' - ) - await expect(call('getAvailableStaticRuleCount')).resolves.toBe(330_000 - 2) - await expect((await launch()).call('getEnabledRulesets')).resolves.toEqual(['b']) - await expect((await launch(extension('2'))).call('getEnabledRulesets')).resolves.toEqual(['a']) - }) - - it('drops updates still queued when the extension unloads', async () => { - const { session } = await launch(extension('6')) - const runtime = getDnrSessionRuntime(session) - const rules = runtime?.extensions.get(ID)?.rules - const enabling = rules?.updateEnabledRulesets(['b'], []) - const disabling = rules?.updateStaticRules('a', [1], []) - runtime?.removeExtension(ID) - await enabling?.catch(() => undefined) - await expect(disabling).rejects.toThrow('Internal error.') - const next = await launch(extension('6')) - expect(next.blocks('https://a.example/x.js')).toBe(true) - }) -}) - -describe('live DNR permission changes and precedence', () => { - it('activates optional authority immediately and preserves session rules across feedback changes', async () => { - const ext = extension() - ext.manifest.permissions = [] - ext.manifest.optional_permissions = [ - 'declarativeNetRequestWithHostAccess', - 'declarativeNetRequestFeedback' - ] - const { session, call, blocks } = await launch(ext) - ensureHostSessionState(session, PROFILE) - const caller = { extension: ext, session, browserProfileId: PROFILE, userGesture: true } - const permission = (method: string, permissions: string[]) => - registry - .getBrowserExtensionNamespace('permissions') - ?.methods[method].invoke(caller, [{ permissions }]) - expect(blocks('https://a.example/file')).toBe(false) - await expect(permission('request', ['declarativeNetRequestWithHostAccess'])).resolves.toBe(true) - expect(blocks('https://a.example/file')).toBe(true) - await call('updateSessionRules', { addRules: [block(21, '||session.example^')] }) - await permission('request', ['declarativeNetRequestFeedback']) - expect(blocks('https://session.example/file')).toBe(true) - expect(await call('getSessionRules')).toEqual([block(21, '||session.example^')]) - const runtime = getDnrSessionRuntime(session) - expect(runtime?.matched.matchedRules(ID, {})).not.toEqual([]) - await permission('remove', ['declarativeNetRequestFeedback']) - expect(runtime?.matched.matchedRules(ID, {})).toEqual([]) - expect(blocks('https://session.example/file')).toBe(true) - await permission('remove', ['declarativeNetRequestWithHostAccess']) - expect(blocks('https://a.example/file')).toBe(false) - expect(blocks('https://session.example/file')).toBe(false) - }) - - it('keeps install precedence when an older extension reloads or another profile loads in reverse order', async () => { - const store = getBrowserExtensionInstallStore() - const make = (id: string, target: string): Electron.Extension => { - const path = mkdtempSync(join(tmpdir(), 'orca-dnr-precedence-')) - writeFileSync( - join(path, 'rules.json'), - JSON.stringify([ - { - id: 1, - condition: { urlFilter: '|https://tie.example/' }, - action: { type: 'redirect', redirect: { url: target } } - } - ]) - ) - store.save({ - id, - name: id, - version: '1', - path, - source: 'unpacked', - iconPath: null, - permissions: ['declarativeNetRequest'], - hostPermissions: [''], - optionsPage: null - }) - return { - id, - name: id, - version: '1', - path, - url: '', - manifest: { - permissions: ['declarativeNetRequest'], - host_permissions: [''], - declarative_net_request: { - rule_resources: [{ id: 'rules', enabled: true, path: 'rules.json' }] - } - } - } - } - const older = make('a'.repeat(32), 'https://older.example/') - const newer = make('b'.repeat(32), 'https://newer.example/') - const first = await launch(older) - const runtime = getDnrSessionRuntime(first.session) - if (!runtime) { - throw new Error('Missing DNR runtime') - } - await runtime.addExtension(newer) - const winner = (owner: typeof runtime) => - owner.engine.evaluateBeforeRequest( - { - url: 'https://tie.example/file', - method: 'GET', - type: 'script', - initiator: null, - tabId: TAB - }, - { allowByExtension: new Map(), actions: [] }, - { hostAccess: () => 'allowed' } - ).actions[0]?.redirectUrl - expect(winner(runtime)).toBe('https://newer.example/') - runtime.removeExtension(older.id) - await runtime.addExtension(older) - expect(winner(runtime)).toBe('https://newer.example/') - const second = await launch(newer) - const reversed = getDnrSessionRuntime(second.session) - if (!reversed) { - throw new Error('Missing DNR runtime') - } - await reversed.addExtension(older) - expect(winner(reversed)).toBe('https://newer.example/') - }) }) diff --git a/src/main/browser/extensions/api/storage-relay.ts b/src/main/browser/extensions/api/storage-relay.ts index 7a24c8fc2a2..9b7f2df9832 100644 --- a/src/main/browser/extensions/api/storage-relay.ts +++ b/src/main/browser/extensions/api/storage-relay.ts @@ -9,7 +9,7 @@ import { /** * Electron never fires chrome.storage.onChanged in extension service workers, so extension pages * report their own storage writes here and main forwards them to the same extension's worker in the - * same session (see src/preload/browser-extension-storage-relay.ts). Workers deliver their own. + * same session (see src/preload/browser/extensions/storage/browser-extension-storage-relay.ts). Workers deliver their own. * Sync is not relayed: main owns that area and fires its events (api/storage-sync.ts). */ const STORAGE_RELAY_NAMESPACE = 'orcaStorageRelay' diff --git a/src/main/browser/extensions/api/storage-sync.ts b/src/main/browser/extensions/api/storage-sync.ts index 17862c39604..073e44bdac5 100644 --- a/src/main/browser/extensions/api/storage-sync.ts +++ b/src/main/browser/extensions/api/storage-sync.ts @@ -15,7 +15,7 @@ import type { BrowserExtensionProfileDocumentItems } from '../profile-storage/br * writer, so every change carries exact old values. A write returns its changes to the caller, * which fires its own listeners (a starting worker's write can reach main before its listen * does); onChanged goes to the extension's other pages and its worker in the session. - * The preload installs it as chrome.storage.sync (src/preload/browser-extension-storage-sync.ts). + * The preload installs it as chrome.storage.sync (src/preload/browser/extensions/storage/browser-extension-storage-sync.ts). */ const STORAGE_SYNC_NAMESPACE = 'orcaStorageSync' diff --git a/src/main/browser/extensions/api/web-navigation.test.ts b/src/main/browser/extensions/api/web-navigation.test.ts index ade2520dc15..918aa1bc48c 100644 --- a/src/main/browser/extensions/api/web-navigation.test.ts +++ b/src/main/browser/extensions/api/web-navigation.test.ts @@ -36,7 +36,7 @@ const registry = await import('../api-runtime/browser-extension-namespace-regist const { observeBrowserExtensionWebNavigation, registerWebNavigationNamespace } = await import('./web-navigation') const { PRELOAD_DOCUMENT_TARGETS_NAMESPACE } = - await import('../../../../preload/browser-extension-document-targets') + await import('../../../../preload/browser/extensions/documents/browser-extension-document-targets') function frame(frameTreeNodeId: number, url: string, parent: FakeFrame | null = null): FakeFrame { const created: FakeFrame = { diff --git a/src/main/browser/extensions/register-browser-extension-namespaces.ts b/src/main/browser/extensions/register-browser-extension-namespaces.ts index 38223e59a31..4f6808de1f2 100644 --- a/src/main/browser/extensions/register-browser-extension-namespaces.ts +++ b/src/main/browser/extensions/register-browser-extension-namespaces.ts @@ -19,7 +19,7 @@ import { registerTabsNamespace } from './api/tabs' import { registerWebNavigationNamespace } from './api/web-navigation' import { registerWindowsNamespace } from './api/windows' -/** Every main-side namespace; each must also appear in src/preload/browser-extension-api-surface.ts. */ +/** Every main-side namespace; each must also appear in src/preload/browser/extensions/api/browser-extension-api-surface.ts. */ export function registerBrowserExtensionNamespaces(): void { registerWindowsNamespace() registerTabsNamespace() diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts index d8dde11508b..fe53dc4afc5 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts @@ -110,7 +110,7 @@ const { recordActiveBrowserPage } = await import('./browser-extension-tab-model' const { registerTabsNamespace } = await import('../api/tabs') const { announceRegisteredBrowserExtensionTab, observeBrowserExtensionTabLifecycle } = await import('./browser-extension-tab-lifecycle') -await import('../../../../preload/browser-extension-document-targets') +await import('../../../../preload/browser/extensions/documents/browser-extension-document-targets') function page(id: string, workspaceId: string, overrides: Partial = {}): BrowserPage { return { @@ -276,31 +276,6 @@ beforeEach(() => { }) describe('restored browser pages without a guest are discarded tabs', () => { - it('lists every unloaded page of the caller’s profile after the loaded tabs, with a stable id', async () => { - const tabs = await query({}, [{ id: 11, url: 'https://live.test/' }]) - expect(tabs.map((entry) => [entry.url, entry.discarded, entry.status, entry.index])).toEqual([ - ['https://live.test/', false, 'loading', 0], - ['https://cold.test/', true, 'unloaded', 1], - ['https://notes.test/', true, 'unloaded', 3], - ['https://remote.test/', true, 'unloaded', 4] - ]) - const cold = tabs[1] - expect(cold).toMatchObject({ title: 'cold title', windowId: 1, active: false }) - expect(cold.id).toBeGreaterThanOrEqual(discardedTabs.FIRST_DISCARDED_BROWSER_TAB_ID) - expect((await query({ discarded: true })).map((entry) => entry.id)).toEqual( - tabs.slice(1).map((entry) => entry.id) - ) - expect(await call('get', [cold.id, null])).toMatchObject({ id: cold.id, discarded: true }) - // Electron's native query already filtered the loaded tabs by url. - expect((await query({ url: 'https://cold.test/*' })).map((entry) => entry.id)).toEqual([ - cold.id - ]) - // The other profile's extensions see only its own page. - expect((await query({}, [], mocks.sessions.work)).map((entry) => entry.url)).toEqual([ - 'https://job.test/' - ]) - }) - it('activates through the renderer, then is replaced by the loaded guest', async () => { const [cold] = await query({ discarded: true }) const coldId = cold.id! diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 06f6052d657..c127099dcc9 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -179,68 +179,6 @@ export type PreloadApi = { speech: SpeechApi } -export type { - ClaudeUsageApi, - CodexUsageApi, - MuseUsageApi, - OpenCodeUsageApi -} from './api/agent-usage-api' -export type { AiVaultApi } from './api/ai-vault-api' -export type { AutomationsApi, ExternalAutomationManagerResult } from './api/automation-api' -export type { AppApi } from './api/app-api' -export type { - BrowserApi, - DetectedBrowserInfo, - DetectedBrowserProfileInfo -} from './api/browser/browser-api' -export type { EmulatorApi } from './api/emulator-api' -export type { ExportApi } from './api/filesystem-api' -export type { - NativeChatApi, - NativeChatAppendedMessages, - NativeChatAppendedPayload, - NativeChatReadSessionResult, - NativeChatSubscribeArgs, - NativeChatSubscriptionFrame -} from './api/native-chat-api' -export type { - PluginAutoUpdateEvent, - PluginHostCustomEditor, - PluginHostNewFile, - PluginHostInstallResult, - PluginHostInstallSource, - PluginHostListEntry, - PluginHostLogLine, - PluginHostPanel, - PluginHostStatus, - PluginMarketplaceHostInstallPreview, - PluginMarketplaceHostListing, - PluginMarketplaceHostSourceState -} from './api/plugin-host-api' -export type { - PreflightApi, - PreflightRuntimeContext, - PreflightStatus, - RefreshAgentsResult -} from './api/preflight-api' -export type { - PtyManagementApi, - PtyManagementDaemonCwdClass, - PtyManagementFolderAccessMismatch, - PtyManagementMacTccAttributionHealth, - PtyManagementSession, - PtyManagementSeveredDaemon, - PtyManagementSeveredDaemonRestartResult -} from './api/pty-management-api' - -export type { - DiagnosticsBundlePayload, - DiagnosticsStatusPayload, - DiagnosticsUploadPayload, - MemoryApi, - StatsApi -} from './api/telemetry-api' - declare global { // oxlint-disable-next-line typescript-eslint/consistent-type-definitions -- declaration merging requires interface interface Window { diff --git a/src/preload/api/app-bridge.ts b/src/preload/api/app-bridge.ts index d9b9bd19edf..b684fb55485 100644 --- a/src/preload/api/app-bridge.ts +++ b/src/preload/api/app-bridge.ts @@ -9,8 +9,11 @@ import { KEYBOARD_LAYOUT_CHANGED_CHANNEL, type KeyboardLayoutChangeEvent } from '../../shared/keyboard-layout-events' -import { prepareAndInvokeAppRestart } from '../renderer-restart-wiring' -import { awaitBeforeUnloadCheckpoint, startupDiagnosticsEnabled } from '../preload-runtime-support' +import { prepareAndInvokeAppRestart } from '../renderer/restart/renderer-restart-wiring' +import { + awaitBeforeUnloadCheckpoint, + startupDiagnosticsEnabled +} from '../renderer/renderer-runtime' import type { PreloadApi } from '../api-types' export const appApi = { diff --git a/src/preload/api/automations-bridge.ts b/src/preload/api/automations-bridge.ts index 1e6135996ce..78779f12381 100644 --- a/src/preload/api/automations-bridge.ts +++ b/src/preload/api/automations-bridge.ts @@ -1,6 +1,7 @@ import type { ExecutionHostId } from '../../shared/execution-host' import { ipcRenderer } from 'electron' -import type { ExternalAutomationManagerResult, PreloadApi } from '../api-types' +import type { ExternalAutomationManagerResult } from './automation-api' +import type { PreloadApi } from '../api-types' import type { AutomationOwnerRef } from '../../shared/automations/ownership/automation-owner-ref' import type { ScopedExternalManagerActionRequest, diff --git a/src/preload/api/browser/browser-bridge-guest-registration-and-downloads.ts b/src/preload/api/browser/browser-bridge-guest-registration-and-downloads.ts index 48d27c8f339..3f5d1245fc8 100644 --- a/src/preload/api/browser/browser-bridge-guest-registration-and-downloads.ts +++ b/src/preload/api/browser/browser-bridge-guest-registration-and-downloads.ts @@ -17,7 +17,7 @@ import type { BrowserPagePromptResult } from '../../../shared/browser/prompts/browser-page-prompt' import { readBrowserClientHostIdArgument } from '../../../shared/browser/client-hosting/browser-client-host-id-argument' -import { browserClientPageRendererRequests } from '../../preload-runtime-support' +import { browserClientPageRendererRequests } from '../../renderer/renderer-runtime' import type { PreloadApi } from '../../api-types' export const browserGuestRegistrationAndDownloadsApi = { diff --git a/src/preload/api/claude-usage-bridge.ts b/src/preload/api/claude-usage-bridge.ts index aee5e62425e..af96d18ef5b 100644 --- a/src/preload/api/claude-usage-bridge.ts +++ b/src/preload/api/claude-usage-bridge.ts @@ -1,5 +1,5 @@ -import { backendUsageTransport } from '../backend-port-client' -import { createUsageProviderApi } from '../usage-provider-api' +import { backendUsageTransport } from '../usage/backend-port-client' +import { createUsageProviderApi } from '../usage/usage-provider-api' import type { PreloadApi } from '../api-types' export const claudeUsageApi = createUsageProviderApi( diff --git a/src/preload/api/codex-usage-bridge.ts b/src/preload/api/codex-usage-bridge.ts index 0705d66ccb5..5caeda7115c 100644 --- a/src/preload/api/codex-usage-bridge.ts +++ b/src/preload/api/codex-usage-bridge.ts @@ -1,5 +1,5 @@ -import { backendUsageTransport } from '../backend-port-client' -import { createUsageProviderApi } from '../usage-provider-api' +import { backendUsageTransport } from '../usage/backend-port-client' +import { createUsageProviderApi } from '../usage/usage-provider-api' import type { PreloadApi } from '../api-types' export const codexUsageApi = createUsageProviderApi( diff --git a/src/preload/api/crash-reports-bridge.ts b/src/preload/api/crash-reports-bridge.ts index a77ad412eb7..9b57675f036 100644 --- a/src/preload/api/crash-reports-bridge.ts +++ b/src/preload/api/crash-reports-bridge.ts @@ -9,8 +9,8 @@ import type { } from '../../shared/crash-reporting' import type { RendererHeapStatistics } from '../../shared/renderer-heap-statistics' import type { RendererProcessMemory } from '../../shared/renderer-process-memory' -import { readRendererHeapStatistics } from '../renderer-heap-statistics-reader' -import { readRendererProcessMemory } from '../renderer-process-memory-reader' +import { readRendererHeapStatistics } from '../renderer/diagnostics/renderer-heap-statistics-reader' +import { readRendererProcessMemory } from '../renderer/diagnostics/renderer-process-memory-reader' import type { PreloadApi } from '../api-types' export const crashReportsApi = { diff --git a/src/preload/api/e2e-bridge.ts b/src/preload/api/e2e-bridge.ts index 900b17a9fcf..95ae25baabb 100644 --- a/src/preload/api/e2e-bridge.ts +++ b/src/preload/api/e2e-bridge.ts @@ -1,4 +1,4 @@ -import { preloadE2EConfig } from '../e2e-config' +import { preloadE2EConfig } from '../renderer/e2e-config' import type { PreloadApi } from '../api-types' export const e2eApi = { diff --git a/src/preload/gitlab.ts b/src/preload/api/gitlab.ts similarity index 96% rename from src/preload/gitlab.ts rename to src/preload/api/gitlab.ts index ed2904de2a0..0b393f98904 100644 --- a/src/preload/gitlab.ts +++ b/src/preload/api/gitlab.ts @@ -1,6 +1,6 @@ import { ipcRenderer } from 'electron' -import type { GitLabMRInvolvement } from '../shared/gitlab-types' -import type { TaskSourceContext } from '../shared/work-items/task-source-context' +import type { GitLabMRInvolvement } from '../../shared/gitlab-types' +import type { TaskSourceContext } from '../../shared/work-items/task-source-context' type GitLabRepoSelectorArgs = { repoPath: string diff --git a/src/preload/api/gl-bridge.ts b/src/preload/api/gl-bridge.ts deleted file mode 100644 index 3977536a838..00000000000 --- a/src/preload/api/gl-bridge.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { glApi } from '../gitlab' -import type { PreloadApi } from '../api-types' - -export const glApiBridge = glApi satisfies PreloadApi['gl'] diff --git a/src/preload/api/muse-usage-bridge.ts b/src/preload/api/muse-usage-bridge.ts index a741ddac1cb..833b0541434 100644 --- a/src/preload/api/muse-usage-bridge.ts +++ b/src/preload/api/muse-usage-bridge.ts @@ -1,5 +1,5 @@ -import { backendUsageTransport } from '../backend-port-client' -import { createUsageProviderApi } from '../usage-provider-api' +import { backendUsageTransport } from '../usage/backend-port-client' +import { createUsageProviderApi } from '../usage/usage-provider-api' import type { PreloadApi } from '../api-types' export const museUsageApi = createUsageProviderApi( diff --git a/src/preload/api/native-chat-bridge.ts b/src/preload/api/native-chat-bridge.ts index b4067ed7d09..fdea9c0b8c9 100644 --- a/src/preload/api/native-chat-bridge.ts +++ b/src/preload/api/native-chat-bridge.ts @@ -2,9 +2,9 @@ import { ipcRenderer } from 'electron' import type { NativeChatAppendedPayload, NativeChatReadSessionResult, - NativeChatSubscriptionFrame, - PreloadApi -} from '../api-types' + NativeChatSubscriptionFrame +} from './native-chat-api' +import type { PreloadApi } from '../api-types' import type { AgentType } from '../../shared/agent-status/contracts/agent-status-types' import { NATIVE_CHAT_VISUAL_GUEST_THEME_PUBLISH, diff --git a/src/preload/api/open-code-usage-bridge.ts b/src/preload/api/open-code-usage-bridge.ts index 8b583be211d..beb6ee468a9 100644 --- a/src/preload/api/open-code-usage-bridge.ts +++ b/src/preload/api/open-code-usage-bridge.ts @@ -1,5 +1,5 @@ -import { backendUsageTransport } from '../backend-port-client' -import { createUsageProviderApi } from '../usage-provider-api' +import { backendUsageTransport } from '../usage/backend-port-client' +import { createUsageProviderApi } from '../usage/usage-provider-api' import type { PreloadApi } from '../api-types' export const openCodeUsageApi = createUsageProviderApi( diff --git a/src/preload/api/orca-profiles-bridge.ts b/src/preload/api/orca-profiles-bridge.ts index f144c9d7697..063de33913f 100644 --- a/src/preload/api/orca-profiles-bridge.ts +++ b/src/preload/api/orca-profiles-bridge.ts @@ -8,8 +8,8 @@ import { type SwitchOrcaProfileResult, type TransferOrcaProfileProjectResult } from '../../shared/orca-profiles' -import { prepareAndInvokeAppRestart } from '../renderer-restart-wiring' -import { awaitBeforeUnloadCheckpoint } from '../preload-runtime-support' +import { prepareAndInvokeAppRestart } from '../renderer/restart/renderer-restart-wiring' +import { awaitBeforeUnloadCheckpoint } from '../renderer/renderer-runtime' export const orcaProfilesApi = { list: () => ipcRenderer.invoke('orcaProfiles:list'), diff --git a/src/preload/api/platform-bridge.test.ts b/src/preload/api/platform-bridge.test.ts deleted file mode 100644 index 1e67947d77c..00000000000 --- a/src/preload/api/platform-bridge.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { platformApi } from './platform-bridge' - -const mocks = vi.hoisted(() => ({ getLinuxDisplayServer: vi.fn(() => null) })) - -vi.mock('../preload-runtime-support', () => ({ - getLinuxDisplayServer: mocks.getLinuxDisplayServer -})) - -// Electron declares getSystemVersion as required on NodeJS.Process; Node does not have it. -const mutableProcess = process as unknown as { getSystemVersion?: () => string } - -async function loadPlatformApi(): Promise { - vi.resetModules() - return (await import('./platform-bridge')).platformApi -} - -describe('platformApi.get', () => { - beforeEach(() => { - mocks.getLinuxDisplayServer.mockClear() - }) - - afterEach(() => { - delete mutableProcess.getSystemVersion - }) - - it('resolves the immutable payload once and returns the identical object', async () => { - const platformApi = await loadPlatformApi() - const getSystemVersion = vi.fn(() => '25.3.0') - mutableProcess.getSystemVersion = getSystemVersion - - const first = platformApi.get() - expect(platformApi.get()).toBe(first) - expect(Object.isFrozen(first)).toBe(true) - - expect(getSystemVersion).toHaveBeenCalledTimes(1) - expect(mocks.getLinuxDisplayServer).toHaveBeenCalledTimes(1) - expect(first.platform).toBe(process.platform) - expect(first.arch).toBe(process.arch) - expect(first.osRelease).toBe('25.3.0') - }) - - it('resolves nothing before the first get, keeping preload startup free', async () => { - await loadPlatformApi() - - expect(mocks.getLinuxDisplayServer).not.toHaveBeenCalled() - }) -}) diff --git a/src/preload/api/platform-bridge.ts b/src/preload/api/platform-bridge.ts index 6ea1102f598..534cd0d80cc 100644 --- a/src/preload/api/platform-bridge.ts +++ b/src/preload/api/platform-bridge.ts @@ -1,4 +1,4 @@ -import { getLinuxDisplayServer } from '../preload-runtime-support' +import { getLinuxDisplayServer } from '../renderer/renderer-runtime' import { parseWindowMaterialArgument } from '../../shared/window-material' import type { PreloadApi } from '../api-types' diff --git a/src/preload/api/plugins-bridge.ts b/src/preload/api/plugins-bridge.ts index 348cbab6e6d..54fc1c5eb61 100644 --- a/src/preload/api/plugins-bridge.ts +++ b/src/preload/api/plugins-bridge.ts @@ -20,10 +20,10 @@ import type { PluginAutoUpdateEvent, PluginHostInstallResult, PluginHostInstallSource, - PluginHostListEntry, - PluginHostLogLine, - PreloadApi -} from '../api-types' + PluginHostLogLine +} from './plugin-host-api' +import type { PluginHostListEntry } from '../../shared/plugins/plugin-list-entry' +import type { PreloadApi } from '../api-types' export const pluginsApi = { list: (): Promise => ipcRenderer.invoke('plugins:list'), diff --git a/src/preload/api/preflight-bridge.ts b/src/preload/api/preflight-bridge.ts index ca0f030c155..152d757247d 100644 --- a/src/preload/api/preflight-bridge.ts +++ b/src/preload/api/preflight-bridge.ts @@ -1,5 +1,6 @@ import { ipcRenderer } from 'electron' -import type { PreflightRuntimeContext, PreloadApi, RefreshAgentsResult } from '../api-types' +import type { PreflightRuntimeContext, RefreshAgentsResult } from './preflight-api' +import type { PreloadApi } from '../api-types' import type { ZCodeInteractiveCapability } from '../../shared/zcode-missing-tui' export const preflightApi = { diff --git a/src/preload/api/runtime-bridge.ts b/src/preload/api/runtime-bridge.ts index eaf6c4e7eff..96515e0fe59 100644 --- a/src/preload/api/runtime-bridge.ts +++ b/src/preload/api/runtime-bridge.ts @@ -8,7 +8,7 @@ import type { } from '../../shared/runtime-types' import type { RuntimeTerminalDriverState } from '../../shared/runtime-session-contracts' import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' -import type { RuntimeEnvironmentSubscriptionHandle } from '../runtime-environment-subscriptions' +import type { RuntimeEnvironmentSubscriptionHandle } from '../runtime/runtime-environment-subscriptions' import type { PreloadApi } from '../api-types' export const runtimeApi = { diff --git a/src/preload/api/runtime-environments-bridge.ts b/src/preload/api/runtime-environments-bridge.ts index 715605b216f..517b443e774 100644 --- a/src/preload/api/runtime-environments-bridge.ts +++ b/src/preload/api/runtime-environments-bridge.ts @@ -22,7 +22,7 @@ import { subscribeCrewAttemptFromPreload, cancelRuntimeEnvironmentSubscriptionFromPreload, type RuntimeEnvironmentSubscriptionHandle -} from '../runtime-environment-subscriptions' +} from '../runtime/runtime-environment-subscriptions' import type { PreloadApi } from '../api-types' import { managedOrcadApi } from './managed-orcad-api' import { getWslHostsApi } from './wsl-hosts-api' diff --git a/src/preload/ssh-authority-forwarding.test.ts b/src/preload/api/ssh-authority-forwarding.test.ts similarity index 79% rename from src/preload/ssh-authority-forwarding.test.ts rename to src/preload/api/ssh-authority-forwarding.test.ts index 70a90a4a4b2..4594039a0ca 100644 --- a/src/preload/ssh-authority-forwarding.test.ts +++ b/src/preload/api/ssh-authority-forwarding.test.ts @@ -1,11 +1,11 @@ import { afterEach, beforeEach, describe, expect, expectTypeOf, it, vi } from 'vitest' -import type { PreloadApi } from './api-types' -import type { SshConnectionState, SshProviderEpoch } from '../shared/ssh-types' +import type { PreloadApi } from '../api-types' +import type { SshConnectionState, SshProviderEpoch } from '../../shared/ssh-types' import type { HostQualifiedDetectedWorktreeResult, ListDetectedWorktreesArgs -} from '../shared/detected-worktree-provider-contract' -import type { DetectedWorktreeListResult } from '../shared/worktree/types' +} from '../../shared/detected-worktree-provider-contract' +import type { DetectedWorktreeListResult } from '../../shared/worktree/types' function listDetectedVariableTypeProbe(api: PreloadApi, args: ListDetectedWorktreesArgs) { return api.worktrees.listDetected(args) @@ -66,30 +66,6 @@ describe('native preload SSH authority forwarding', () => { >() }) - it('forwards host-qualified metadata-only worktree reads', async () => { - await import('./index') - const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi - const args = { repoId: 'repo-1', executionHostId: 'ssh:ssh-1' as const } - - await api.worktrees.listKnownForExecutionHost?.(args) - - expect(invoke).toHaveBeenCalledWith('worktrees:listKnownForExecutionHost', args) - }) - - it('forwards metadata retirement for authoritatively removed worktrees', async () => { - await import('./index') - const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi - const args = { - repoId: 'repo-1', - executionHostId: 'ssh:ssh-1' as const, - worktreeIds: ['repo-1::/remote/deleted'] - } - - await api.worktrees.forgetRemovedForExecutionHost?.(args) - - expect(invoke).toHaveBeenCalledWith('worktrees:forgetRemovedForExecutionHost', args) - }) - it('forwards full-pair get and push states without cloning away authority', async () => { const state: SshConnectionState = { targetId: 'ssh-1', @@ -100,7 +76,7 @@ describe('native preload SSH authority forwarding', () => { connectionGeneration: 29 } invoke.mockResolvedValueOnce(state) - await import('./index') + await import('../index') const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi await expect(api.ssh.getState({ targetId: 'ssh-1' })).resolves.toEqual(state) @@ -126,7 +102,7 @@ describe('native preload SSH authority forwarding', () => { providerEpoch: 'partial-provider-epoch' } as SshConnectionState invoke.mockResolvedValueOnce(partialState) - await import('./index') + await import('../index') const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi const returned = await api.ssh.getState({ targetId: 'ssh-1' }) @@ -156,7 +132,7 @@ describe('native preload SSH authority forwarding', () => { }) it('drops malformed full authority before it reaches the renderer', async () => { - await import('./index') + await import('../index') const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi const onStateChanged = vi.fn() api.ssh.onStateChanged(onStateChanged) diff --git a/src/preload/api/ui-bridge-tab-and-browser-commands.ts b/src/preload/api/ui-bridge-tab-and-browser-commands.ts index 3b7a092224a..ea87e6e2b61 100644 --- a/src/preload/api/ui-bridge-tab-and-browser-commands.ts +++ b/src/preload/api/ui-bridge-tab-and-browser-commands.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import { admitCloseActiveTabPayload } from '../close-active-tab-payload-admission' +import { admitCloseActiveTabPayload } from '../renderer/window-commands/close-active-tab-payload-admission' import type { CloseActiveTabPayload } from '../api/ui-command-event-api' import type { BrowserHistoryNavigateCommand, @@ -11,7 +11,7 @@ import type { WorktreeDefaultTabsLaunch, WorktreeSetupLaunch } from '../../shared/worktree/launch-types' -import { browserFindSubscriptions } from '../preload-runtime-support' +import { browserFindSubscriptions } from '../renderer/renderer-runtime' import type { PreloadApi } from '../api-types' export const uiTabAndBrowserCommandsApi = { diff --git a/src/preload/api/updater-bridge.ts b/src/preload/api/updater-bridge.ts index 325d5ace205..af55a0967d0 100644 --- a/src/preload/api/updater-bridge.ts +++ b/src/preload/api/updater-bridge.ts @@ -1,7 +1,7 @@ import { ipcRenderer } from 'electron' import type { UpdateStatus } from '../../shared/update-status-types' -import { prepareAndInvokeUpdaterInstall } from '../renderer-restart-wiring' -import { awaitBeforeUnloadCheckpoint, updaterQuitAbortRelay } from '../preload-runtime-support' +import { prepareAndInvokeUpdaterInstall } from '../renderer/restart/renderer-restart-wiring' +import { awaitBeforeUnloadCheckpoint, updaterQuitAbortRelay } from '../renderer/renderer-runtime' import type { PreloadApi } from '../api-types' export const updaterApi = { diff --git a/src/preload/app-restart-checkpoint-routing.test.ts b/src/preload/app-restart-checkpoint-routing.test.ts deleted file mode 100644 index a62da40ea76..00000000000 --- a/src/preload/app-restart-checkpoint-routing.test.ts +++ /dev/null @@ -1,239 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PreloadApi } from './api-types' -import { - ORCA_APP_RESTART_ABORTED_EVENT, - ORCA_APP_RESTART_STARTED_EVENT -} from '../shared/updater-renderer-events' -import { KEYBOARD_LAYOUT_CHANGED_CHANNEL } from '../shared/keyboard-layout-events' - -const { exposeInMainWorld, invoke, on, removeListener, send, sendSync, getPathForFile } = - vi.hoisted(() => ({ - exposeInMainWorld: vi.fn(), - invoke: vi.fn(), - on: vi.fn(), - removeListener: vi.fn(), - send: vi.fn(), - sendSync: vi.fn(), - getPathForFile: vi.fn(() => '/files/notes.txt') - })) - -vi.mock('electron', () => ({ - contextBridge: { exposeInMainWorld }, - ipcRenderer: { invoke, on, removeListener, send, sendSync }, - webFrame: { - getZoomFactor: vi.fn(() => 1), - setZoomFactor: vi.fn(), - setVisualZoomLevelLimits: vi.fn() - }, - webUtils: { getPathForFile } -})) - -describe('native preload destructive app actions', () => { - const originalContextIsolated = Object.getOwnPropertyDescriptor(process, 'contextIsolated') - let eventTarget: EventTarget - - beforeEach(() => { - vi.resetModules() - exposeInMainWorld.mockReset() - invoke.mockReset() - on.mockReset() - removeListener.mockReset() - send.mockReset() - sendSync.mockReset() - Object.defineProperty(process, 'contextIsolated', { configurable: true, value: true }) - eventTarget = new EventTarget() - vi.stubGlobal('window', eventTarget) - vi.stubGlobal('document', { addEventListener: vi.fn() }) - }) - - afterEach(() => { - vi.unstubAllGlobals() - if (originalContextIsolated) { - Object.defineProperty(process, 'contextIsolated', originalContextIsolated) - } else { - Reflect.deleteProperty(process, 'contextIsolated') - } - }) - - const loadApi = async (): Promise => { - await import('./index') - return exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi - } - - it('exposes synchronous file path resolution and a window-local preparation invoke', async () => { - const api = await loadApi() - const file = new File(['x'], 'notes.txt') - expect(api).not.toHaveProperty('getPathForFile') - expect(api.fs.getPathForFile?.(file)).toBe('/files/notes.txt') - expect(getPathForFile).toHaveBeenCalledWith(file) - const request = { paths: ['/files/notes.txt'], consumer: 'agent' as const } - invoke.mockResolvedValue({ paths: request.paths, failures: [] }) - await expect(api.fs.prepareDroppedPaths(request)).resolves.toEqual({ - paths: request.paths, - failures: [] - }) - expect(invoke).toHaveBeenCalledExactlyOnceWith('fs:prepareDroppedPaths', request) - }) - - for (const action of ['reload', 'relaunch'] as const) { - it(`prepares and awaits durability before ${action}`, async () => { - const api = await loadApi() - const calls: string[] = [] - eventTarget.addEventListener(ORCA_APP_RESTART_STARTED_EVENT, () => calls.push('prepared')) - invoke.mockImplementation(async (channel: string) => { - calls.push(channel) - return channel === 'app:await-before-unload-checkpoint' ? { ok: true } : undefined - }) - - await api.app[action]() - - expect(calls).toEqual(['prepared', 'app:await-before-unload-checkpoint', `app:${action}`]) - }) - - it(`refuses ${action} when the durable checkpoint fails`, async () => { - const api = await loadApi() - const aborted = vi.fn() - eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted) - invoke.mockImplementation(async (channel: string) => - channel === 'app:await-before-unload-checkpoint' ? { ok: false } : undefined - ) - - await expect(api.app[action]()).rejects.toThrow( - 'Failed to persist renderer state before unload.' - ) - - expect(invoke).not.toHaveBeenCalledWith(`app:${action}`) - expect(aborted).toHaveBeenCalledTimes(1) - }) - } - - it('exposes the durable checkpoint join the lazy-chunk recovery reload depends on', async () => { - const api = await loadApi() - invoke.mockResolvedValue({ ok: true }) - - await expect(api.app.awaitBeforeUnloadCheckpoint()).resolves.toBeUndefined() - expect(invoke).toHaveBeenCalledWith('app:await-before-unload-checkpoint') - - invoke.mockResolvedValue({ ok: false }) - - await expect(api.app.awaitBeforeUnloadCheckpoint()).rejects.toThrow( - 'Failed to persist renderer state before unload.' - ) - }) - - it('preserves both macOS keyboard preload adapters', async () => { - const api = await loadApi() - invoke.mockResolvedValue(undefined) - - await api.app.getMacCapturedDigitRowChords() - await api.app.getKeyboardLayoutSnapshot() - const onKeyboardLayoutChanged = vi.fn() - const unsubscribe = api.app.onKeyboardLayoutChanged(onKeyboardLayoutChanged) - const listener = on.mock.calls.find( - ([channel]) => channel === KEYBOARD_LAYOUT_CHANGED_CHANNEL - )?.[1] as ((event: unknown, payload: unknown) => void) | undefined - const payload = { phase: 'invalidated', generation: 1 } - listener?.({}, payload) - unsubscribe() - - expect(invoke).toHaveBeenCalledWith('app:getMacCapturedDigitRowChords') - expect(invoke).toHaveBeenCalledWith('app:getKeyboardLayoutSnapshot') - expect(onKeyboardLayoutChanged).toHaveBeenCalledExactlyOnceWith(payload) - expect(removeListener).toHaveBeenCalledWith(KEYBOARD_LAYOUT_CHANGED_CHANNEL, listener) - }) - - it('awaits renderer durability before profile maintenance and preserves its result', async () => { - const api = await loadApi() - const started = vi.fn() - eventTarget.addEventListener(ORCA_APP_RESTART_STARTED_EVENT, started) - let finishCheckpoint = (_result: { ok: boolean }): void => {} - const checkpoint = new Promise((resolve) => { - finishCheckpoint = resolve - }) - const result = { status: 'relaunching' } - invoke.mockImplementation((channel: string) => - channel === 'app:await-before-unload-checkpoint' ? checkpoint : Promise.resolve(result) - ) - - const switching = api.orcaProfiles.switchProfile({ profileId: 'target' }) - await vi.waitFor(() => - expect(invoke).toHaveBeenCalledWith('app:await-before-unload-checkpoint') - ) - expect(started).toHaveBeenCalledOnce() - expect(invoke).not.toHaveBeenCalledWith('orcaProfiles:switch', expect.anything()) - finishCheckpoint({ ok: true }) - await expect(switching).resolves.toBe(result) - expect(invoke).toHaveBeenLastCalledWith('orcaProfiles:switch', { profileId: 'target' }) - }) - - it.each(['checkpoint-failed', 'switch-failed', 'already-active'])( - 'resets restart preparation when profile switching returns %s', - async (outcome) => { - const api = await loadApi() - const aborted = vi.fn() - eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted) - invoke.mockImplementation(async (channel: string) => { - if (channel === 'app:await-before-unload-checkpoint') { - return { ok: outcome !== 'checkpoint-failed' } - } - if (outcome === 'switch-failed') { - throw new Error('switch failed') - } - return { status: 'already-active' } - }) - const switching = api.orcaProfiles.switchProfile({ profileId: 'target' }) - await (outcome === 'already-active' - ? expect(switching).resolves.toEqual({ status: 'already-active' }) - : expect(switching).rejects.toThrow()) - expect(aborted).toHaveBeenCalledOnce() - if (outcome === 'checkpoint-failed') { - expect(invoke).not.toHaveBeenCalledWith('orcaProfiles:switch', expect.anything()) - } - } - ) - - it.each(['move', 'copy', 'inactive', 'duplicate', 'recovery'] as const)( - 'prepares only a potentially relaunching project transfer: %s', - async (outcome) => { - const api = await loadApi() - const started = vi.fn() - const aborted = vi.fn() - eventTarget.addEventListener(ORCA_APP_RESTART_STARTED_EVENT, started) - eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted) - const args = { - sourceProfileId: outcome === 'inactive' ? 'inactive' : 'active', - targetProfileId: 'target', - repoId: 'repo', - mode: outcome === 'copy' ? ('copy' as const) : ('move' as const) - } - const result = - outcome === 'duplicate' - ? { status: 'duplicate-target' } - : { status: 'transferred', willRelaunch: outcome === 'move' } - invoke.mockImplementation(async (channel: string) => { - if (channel === 'orcaProfiles:list') { - return { activeProfileId: 'active' } - } - if (channel === 'app:await-before-unload-checkpoint') { - return { ok: true } - } - if (outcome === 'recovery') { - const listener = on.mock.calls.find(([name]) => name === 'app:restart-committed')?.[1] - expect(listener).toBeTypeOf('function') - listener() - throw new Error('move requires recovery') - } - return result - }) - - const transfer = api.orcaProfiles.transferProject(args) - await (outcome === 'recovery' - ? expect(transfer).rejects.toThrow('move requires recovery') - : expect(transfer).resolves.toBe(result)) - const needsPreparation = outcome !== 'copy' && outcome !== 'inactive' - expect(started).toHaveBeenCalledTimes(needsPreparation ? 1 : 0) - expect(aborted).toHaveBeenCalledTimes(outcome === 'duplicate' ? 1 : 0) - expect(invoke).toHaveBeenLastCalledWith('orcaProfiles:transferProject', args) - } - ) -}) diff --git a/src/preload/browser-extension-content-script-api.ts b/src/preload/browser-extension-content-script-api.ts index 70617263a18..3e5c0779803 100644 --- a/src/preload/browser-extension-content-script-api.ts +++ b/src/preload/browser-extension-content-script-api.ts @@ -1,12 +1,12 @@ import { createContentScriptRelayBridge, installContentScriptRelayFilter -} from './browser-extension-content-script-relay' -import { installBrowserExtensionInertApis } from './browser-extension-inert-apis' +} from './browser/extensions/messaging/browser-extension-content-script-relay' +import { installBrowserExtensionInertApis } from './browser/extensions/api/browser-extension-inert-apis' import { installBrowserExtensionStorageSync, PRELOAD_STORAGE_SYNC_CONSTANTS -} from './browser-extension-storage-sync' +} from './browser/extensions/storage/browser-extension-storage-sync' /** * Orca's content script, bundled into one standalone file that Orca's manifest rewrite puts first diff --git a/src/preload/browser-extension-native-messaging.test.ts b/src/preload/browser-extension-native-messaging.test.ts deleted file mode 100644 index fdfc7c30987..00000000000 --- a/src/preload/browser-extension-native-messaging.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { runInNewContext } from 'node:vm' -import { describe, expect, it, vi } from 'vitest' -import type { BrowserExtensionInvokeReply } from './browser-extension-main-world' -import { - installBrowserExtensionNativeMessaging, - PRELOAD_NATIVE_MESSAGING_NAMESPACE, - type BrowserExtensionNativeMessagingContext -} from './browser-extension-native-messaging' - -type Reply = BrowserExtensionInvokeReply -type Call = { method: string; args: unknown[] } - -function isRecord(value: unknown): value is Record { - return value !== null && typeof value === 'object' -} - -/** Calls `path` (e.g. 'onMessage.addListener') on `owner` with its parent as `this`. */ -function call(owner: unknown, path: string, ...args: unknown[]): unknown { - const keys = path.split('.') - const leaf = keys.pop() ?? '' - const parent = keys.reduce( - (value, key) => (isRecord(value) ? value[key] : undefined), - owner - ) - const fn = isRecord(parent) ? parent[leaf] : undefined - if (typeof fn !== 'function') { - throw new Error(`${path} is not a function`) - } - return fn.apply(parent, args) -} - -/** Runs the installer from its source text, as contextBridge.executeInMainWorld does. */ -function install( - permissions: Record, - context: BrowserExtensionNativeMessagingContext = 'page' -) { - const runtime: Record = { getManifest: () => permissions } - const browserRuntime: Record = {} - const calls: Call[] = [] - const listens: unknown[][] = [] - const pending = new Map void>() - let dispatch: ((namespace: string, event: string, args: unknown[]) => void) | null = null - const bridge = { - call: (namespace: string, method: string, args: unknown[]) => { - expect(namespace).toBe(PRELOAD_NATIVE_MESSAGING_NAMESPACE) - calls.push({ method, args }) - return new Promise((resolve) => pending.set(`${method}:${String(args[0])}`, resolve)) - }, - listen: (namespace: string, event: string, active: boolean) => - listens.push([namespace, event, active]), - onEvent: (handler: typeof dispatch) => { - dispatch = handler - }, - passesFilter: () => true - } - const error = vi.fn() - const realm = { - chrome: { runtime }, - browser: { runtime: browserRuntime }, - console: { error }, - JSON, - Math, - Date, - Promise - } - runInNewContext(`(${installBrowserExtensionNativeMessaging.toString()})(bridge, context)`, { - ...realm, - globalThis: realm, - bridge, - context - }) - return { - runtime, - browserRuntime, - calls, - listens, - error, - /** The id the installer chose for the n-th call's port. */ - portId: (index = 0) => String(calls[index]?.args[0]), - lastError: () => (isRecord(runtime.lastError) ? runtime.lastError.message : undefined), - reply: (key: string, value: Reply) => pending.get(key)?.(value), - emit: (args: unknown[]) => dispatch?.(PRELOAD_NATIVE_MESSAGING_NAMESPACE, 'onPortEvent', args) - } -} - -const tick = () => new Promise((resolve) => setTimeout(resolve, 0)) - -describe('chrome.runtime native messaging in extension contexts', () => { - it('queues posts until the host runs and routes replies by port', async () => { - const page = install({ permissions: ['nativeMessaging'] }) - const port = call(page.runtime, 'connectNative', 'com.example.vault') - const received: unknown[][] = [] - call(port, 'onMessage.addListener', (message: unknown, from: unknown) => - received.push([message, from === port]) - ) - call(port, 'postMessage', { hello: 'é' }) - expect(isRecord(port) && port.name).toBe('') - const id = page.portId() - expect(page.calls).toEqual([{ method: 'connect', args: [id, 'com.example.vault'] }]) - // A reply can beat the connect answer; it still reaches the port. - page.emit([id, 'message', '{"early":true}']) - page.reply(`connect:${id}`, { ok: true, value: undefined }) - await tick() - expect(page.calls[1]).toEqual({ method: 'postMessage', args: [id, '{"hello":"é"}'] }) - page.emit(['another-port', 'message', '{"stray":1}']) - expect(received).toEqual([[{ early: true }, true]]) - expect(page.listens).toEqual([]) - }) - - it('fires onDisconnect with runtime.lastError set only during the call', async () => { - const page = install({ permissions: ['nativeMessaging'] }) - const port = call(page.runtime, 'connectNative', 'com.example.missing') - const seen: unknown[] = [] - call(port, 'onDisconnect.addListener', () => seen.push(page.lastError())) - page.reply(`connect:${page.portId()}`, { - ok: false, - error: 'Specified native messaging host not found.' - }) - await tick() - expect(seen).toEqual(['Specified native messaging host not found.']) - expect(page.runtime.lastError).toBeUndefined() - expect(() => call(port, 'postMessage', 1)).toThrow( - 'Attempting to use a disconnected port object' - ) - }) - - it('lets main release a port the extension dropped while it was starting', async () => { - const worker = install({ permissions: ['nativeMessaging'] }, 'worker') - const port = call(worker.runtime, 'connectNative', 'com.example.vault') - expect(worker.listens).toEqual([[PRELOAD_NATIVE_MESSAGING_NAMESPACE, 'onPortEvent', true]]) - call(port, 'disconnect') - worker.reply(`connect:${worker.portId()}`, { ok: true, value: undefined }) - await tick() - expect(worker.calls.at(-1)).toEqual({ method: 'disconnect', args: [worker.portId()] }) - }) - - it('answers sendNativeMessage with a promise, or a callback that sees lastError', async () => { - const page = install({ permissions: ['nativeMessaging'] }) - const promised = call(page.runtime, 'sendNativeMessage', 'com.example.vault', { q: 1 }) - expect(page.calls[0]).toEqual({ - method: 'sendNativeMessage', - args: ['com.example.vault', '{"q":1}'] - }) - page.reply('sendNativeMessage:com.example.vault', { ok: true, value: '{"a":2}' }) - await expect(promised).resolves.toEqual({ a: 2 }) - - const results: unknown[] = [] - call(page.runtime, 'sendNativeMessage', 'com.example.gone', 1, (response: unknown) => - results.push([response, page.lastError()]) - ) - await tick() - page.reply('sendNativeMessage:com.example.gone', { - ok: false, - error: 'Native host has exited.' - }) - await tick() - expect(results).toEqual([[undefined, 'Native host has exited.']]) - }) -}) diff --git a/src/preload/browser-extension-preload.ts b/src/preload/browser-extension-preload.ts index 43aa35d0415..82df2ff05b1 100644 --- a/src/preload/browser-extension-preload.ts +++ b/src/preload/browser-extension-preload.ts @@ -3,30 +3,30 @@ import { BROWSER_EXTENSION_API_SURFACE, PRELOAD_BROWSER_EXTENSION_EVENT_CHANNEL, PRELOAD_BROWSER_EXTENSION_INVOKE_CHANNEL -} from './browser-extension-api-surface' +} from './browser/extensions/api/browser-extension-api-surface' import { installBrowserExtensionApis, type BrowserExtensionInvokeReply, type BrowserExtensionMainWorldBridge -} from './browser-extension-main-world' +} from './browser/extensions/api/browser-extension-main-world' import { installBrowserExtensionDocumentTargets, PRELOAD_FIRST_DISCARDED_TAB_ID -} from './browser-extension-document-targets' -import { passesBrowserExtensionEventFilter } from './browser-extension-event-filters' -import { installBrowserExtensionInertApis } from './browser-extension-inert-apis' -import { installContentScriptRelayFilter } from './browser-extension-content-script-relay' -import { installBrowserExtensionNativeMessaging } from './browser-extension-native-messaging' -import { installBrowserExtensionFrameLifetime } from './browser-extension-frame-lifetime' -import { installBrowserExtensionStorageRelay } from './browser-extension-storage-relay' +} from './browser/extensions/documents/browser-extension-document-targets' +import { passesBrowserExtensionEventFilter } from './browser/extensions/api/browser-extension-event-filters' +import { installBrowserExtensionInertApis } from './browser/extensions/api/browser-extension-inert-apis' +import { installContentScriptRelayFilter } from './browser/extensions/messaging/browser-extension-content-script-relay' +import { installBrowserExtensionNativeMessaging } from './browser/extensions/messaging/browser-extension-native-messaging' +import { installBrowserExtensionFrameLifetime } from './browser/extensions/api/browser-extension-frame-lifetime' +import { installBrowserExtensionStorageRelay } from './browser/extensions/storage/browser-extension-storage-relay' import { installBrowserExtensionStorageSync, PRELOAD_STORAGE_SYNC_CONSTANTS -} from './browser-extension-storage-sync' +} from './browser/extensions/storage/browser-extension-storage-sync' import { CHROME_WEB_STORE_ORIGIN, installChromeWebStoreBridge -} from './browser-extension-web-store-bridge' +} from './browser/extensions/web-store/browser-extension-web-store-bridge' const electron: { contextBridge: ContextBridge; ipcRenderer: IpcRenderer } = require('electron') const { contextBridge, ipcRenderer } = electron diff --git a/src/preload/browser-extension-storage-sync.test.ts b/src/preload/browser-extension-storage-sync.test.ts deleted file mode 100644 index 72a2bf1a8a7..00000000000 --- a/src/preload/browser-extension-storage-sync.test.ts +++ /dev/null @@ -1,209 +0,0 @@ -import { runInNewContext } from 'node:vm' -import { describe, expect, it, vi } from 'vitest' -import type { BrowserExtensionInvokeReply } from './browser-extension-main-world' -import { - installBrowserExtensionStorageSync, - PRELOAD_STORAGE_SYNC_CONSTANTS, - PRELOAD_STORAGE_SYNC_NAMESPACE -} from './browser-extension-storage-sync' - -type Runtime = { lastError?: { message: string } } - -function nativeEvent() { - const listeners = new Set() - return { - listeners, - addListener: vi.fn((callback: unknown) => listeners.add(callback)), - removeListener: vi.fn((callback: unknown) => listeners.delete(callback)) - } -} - -/** Runs the installer from its source text, as contextBridge.executeInMainWorld does. */ -function install( - reply: (method: string, args: unknown[]) => BrowserExtensionInvokeReply, - forward?: (changes: unknown, from?: string) => void -) { - const runtime: Runtime = {} - const native = nativeEvent() - const nativeSync = { get: vi.fn(), set: vi.fn() } - const chrome = { runtime, storage: { local: {}, sync: nativeSync, onChanged: native } } - let dispatch: ((namespace: string, event: string, args: unknown[]) => void) | null = null - const calls: unknown[][] = [] - const listens: unknown[][] = [] - const bridge = { - call: async (namespace: string, method: string, args: unknown[]) => { - calls.push([namespace, method, args]) - return reply(method, args) - }, - listen: (namespace: string, event: string, active: boolean) => - listens.push([namespace, event, active]), - onEvent: (handler: typeof dispatch) => { - dispatch = handler - }, - passesFilter: () => true - } - const realm = { chrome, console, JSON, Promise } - const relay: unknown = runInNewContext( - `(${installBrowserExtensionStorageSync.toString()})(bridge, constants, forward)`, - { - ...realm, - globalThis: realm, - bridge, - constants: PRELOAD_STORAGE_SYNC_CONSTANTS, - forward - } - ) - return { - relay: (method: string, args: unknown[], from?: string): unknown => - typeof relay === 'function' ? relay(method, args, from) : undefined, - chrome, - native, - nativeSync, - calls, - listens, - emit: (changes: unknown) => dispatch?.(PRELOAD_STORAGE_SYNC_NAMESPACE, 'onChanged', [changes]) - } -} - -function isRecord(value: unknown): value is Record { - return value !== null && typeof value === 'object' -} - -function call(root: unknown, path: string, ...args: unknown[]): unknown { - const keys = path.split('.') - const name = keys.pop() ?? '' - const owner = keys.reduce( - (value, key) => (isRecord(value) ? value[key] : undefined), - root - ) - const fn = isRecord(owner) ? owner[name] : null - if (typeof fn !== 'function') { - throw new Error(`${path} is not a function`) - } - return fn.call(owner, ...args) -} - -describe('installBrowserExtensionStorageSync', () => { - it('replaces the disabled native area with calls to main, as promises or callbacks', async () => { - const page = install((method) => - method === 'get' ? { ok: true, value: { theme: 'dark' } } : { ok: true, value: undefined } - ) - expect(page.chrome.storage.sync).not.toBe(page.nativeSync) - expect(page.chrome.storage.sync).toMatchObject({ QUOTA_BYTES: 102_400, MAX_ITEMS: 512 }) - - await expect(call(page.chrome, 'storage.sync.get', 'theme')).resolves.toEqual({ - theme: 'dark' - }) - const got = await new Promise((resolve) => call(page.chrome, 'storage.sync.get', resolve)) - expect(got).toEqual({ theme: 'dark' }) - const setDone = vi.fn() - expect( - call(page.chrome, 'storage.sync.set', { at: new Date(0), skip: undefined }, setDone) - ).toBeUndefined() - await vi.waitFor(() => expect(setDone).toHaveBeenCalledWith()) - await expect( - call(page.chrome, 'storage.sync.setAccessLevel', { - accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS' - }) - ).resolves.toBeUndefined() - await expect( - call(page.chrome, 'storage.sync.setAccessLevel', { accessLevel: 'TRUSTED_CONTEXTS' }) - ).rejects.toThrow('This StorageArea is not available for setting access level') - - expect(page.calls).toEqual([ - [PRELOAD_STORAGE_SYNC_NAMESPACE, 'get', ['theme']], - [PRELOAD_STORAGE_SYNC_NAMESPACE, 'get', []], - [PRELOAD_STORAGE_SYNC_NAMESPACE, 'set', [{ at: '1970-01-01T00:00:00.000Z' }]] - ]) - expect(page.nativeSync.get).not.toHaveBeenCalled() - expect(page.nativeSync.set).not.toHaveBeenCalled() - }) - - it('sets lastError only inside a failed callback and rejects a failed promise', async () => { - const page = install(() => ({ ok: false, error: 'QUOTA_BYTES quota exceeded' })) - const lastError = await new Promise((resolve) => - call(page.chrome, 'storage.sync.set', { big: 1 }, () => - resolve(page.chrome.runtime.lastError?.message) - ) - ) - expect(lastError).toBe('QUOTA_BYTES quota exceeded') - expect(page.chrome.runtime.lastError).toBeUndefined() - await expect(call(page.chrome, 'storage.sync.set', { big: 1 })).rejects.toThrow( - 'QUOTA_BYTES quota exceeded' - ) - }) - - it("delivers main's sync changes to sync.onChanged and storage.onChanged with 'sync'", async () => { - const own = { mine: { newValue: 1 } } - const page = install((method) => ({ ok: true, value: method === 'set' ? own : undefined })) - const all: unknown[][] = [] - const area: unknown[][] = [] - const onAll = (changes: unknown, areaName: unknown) => all.push([areaName, changes]) - call(page.chrome, 'storage.onChanged.addListener', onAll) - call(page.chrome, 'storage.sync.onChanged.addListener', (changes: unknown) => - area.push([changes]) - ) - // The underlying onChanged keeps its own listeners for local and session. - expect(page.native.listeners.has(onAll)).toBe(true) - expect(call(page.chrome, 'storage.onChanged.hasListener', onAll)).toBe(true) - expect(page.listens).toEqual([[PRELOAD_STORAGE_SYNC_NAMESPACE, 'onChanged', true]]) - - const changes = { theme: { oldValue: 'light', newValue: 'dark' } } - page.emit(changes) - expect(all).toEqual([['sync', changes]]) - expect(area).toEqual([[changes]]) - - // Main skips the writer, which fires its own listeners from the changes main returns. - await expect(call(page.chrome, 'storage.sync.set', { mine: 1 })).resolves.toBeUndefined() - expect(all).toEqual([ - ['sync', changes], - ['sync', own] - ]) - expect(area).toEqual([[changes], [own]]) - - call(page.chrome, 'storage.onChanged.removeListener', onAll) - expect(page.native.listeners.has(onAll)).toBe(false) - page.emit(changes) - expect(all).toHaveLength(2) - expect(area).toHaveLength(3) - }) - - it("makes a content script's relayed call and fires this context's listeners for its writes", async () => { - const changes = { theme: { newValue: 'dark' } } - const worker = install((method) => ({ ok: true, value: method === 'set' ? changes : 'value' })) - const heard: unknown[] = [] - call(worker.chrome, 'storage.sync.onChanged.addListener', (change: unknown) => - heard.push(change) - ) - - await expect(worker.relay('get', ['theme'])).resolves.toEqual({ ok: true, value: 'value' }) - await expect(worker.relay('set', [{ theme: 'dark' }])).resolves.toEqual({ - ok: true, - value: changes - }) - expect(heard).toEqual([changes]) - await expect(worker.relay('setAccessLevel', [{}])).resolves.toMatchObject({ ok: false }) - expect(worker.calls).toEqual([ - [PRELOAD_STORAGE_SYNC_NAMESPACE, 'get', ['theme']], - [PRELOAD_STORAGE_SYNC_NAMESPACE, 'set', [{ theme: 'dark' }]] - ]) - }) - - it('passes every sync change on to content scripts, naming the one that wrote it', async () => { - const own = { mine: { newValue: 1 } } - const forward = vi.fn() - const worker = install(() => ({ ok: true, value: own }), forward) - // Listens with no listener of its own: content scripts hear other contexts only this way. - expect(worker.listens).toEqual([[PRELOAD_STORAGE_SYNC_NAMESPACE, 'onChanged', true]]) - - const elsewhere = { theme: { newValue: 'dark' } } - worker.emit(elsewhere) - await call(worker.chrome, 'storage.sync.set', { mine: 1 }) - await worker.relay('set', [{ mine: 1 }], 'cs-1') - expect(forward.mock.calls).toEqual([ - [elsewhere, undefined], - [own, undefined], - [own, 'cs-1'] - ]) - }) -}) diff --git a/src/preload/browser-extension-web-store-wording.test.ts b/src/preload/browser-extension-web-store-wording.test.ts deleted file mode 100644 index 382da7dd12a..00000000000 --- a/src/preload/browser-extension-web-store-wording.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, describe, expect, it } from 'vitest' -import { adaptChromeWebStoreWordingForOrca } from './browser-extension-web-store-wording' - -const flushMutations = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)) - -afterEach(() => { - document.body.innerHTML = '' -}) - -describe('adaptChromeWebStoreWordingForOrca', () => { - it('renames the install wording but keeps the store name', () => { - document.body.innerHTML = - 'Chrome Web Store' - adaptChromeWebStoreWordingForOrca() - expect(document.querySelector('a')?.textContent).toBe('Chrome Web Store') - expect(document.querySelector('button')?.getAttribute('aria-label')).toBe('Add to Orca') - expect(document.querySelector('span')?.textContent).toBe('Add to Orca') - }) - - it('renames wording the store draws later, including the removal toast', async () => { - adaptChromeWebStoreWordingForOrca() - const button = document.createElement('span') - button.textContent = 'Remove from Chrome' - document.body.appendChild(button) - const toast = document.createElement('div') - toast.textContent = 'Bitwarden has been removed from Chrome.' - document.body.appendChild(toast) - await flushMutations() - expect(button.textContent).toBe('Remove from Orca') - expect(toast.textContent).toBe('Bitwarden has been removed from Orca.') - button.firstChild!.nodeValue = 'Add to Chrome' - await flushMutations() - expect(button.textContent).toBe('Add to Orca') - }) - - it('hides the switch-to-Chrome banner and shows the box again when the store reuses it', async () => { - document.body.innerHTML = - '

Vault

' - adaptChromeWebStoreWordingForOrca() - const banner = document.getElementById('banner')! - expect(banner.style.display).toBe('none') - expect(document.querySelector('h1')?.textContent).toBe('Vault') - banner.innerHTML = '
This item is disabled
Enable now' - await flushMutations() - expect(banner.style.display).toBe('') - }) -}) diff --git a/src/preload/browser-extension-worker-shim.ts b/src/preload/browser-extension-worker-shim.ts index a3aa1b19058..bb595fba55c 100644 --- a/src/preload/browser-extension-worker-shim.ts +++ b/src/preload/browser-extension-worker-shim.ts @@ -5,28 +5,28 @@ import { decodeBrowserExtensionWireJson, encodeBrowserExtensionWireJson } from '../shared/browser/extensions/browser-extension-worker-api' -import { BROWSER_EXTENSION_API_SURFACE } from './browser-extension-api-surface' +import { BROWSER_EXTENSION_API_SURFACE } from './browser/extensions/api/browser-extension-api-surface' import { createContentScriptSyncForward, installContentScriptRelayFilter -} from './browser-extension-content-script-relay' +} from './browser/extensions/messaging/browser-extension-content-script-relay' import { installBrowserExtensionDocumentTargets, PRELOAD_FIRST_DISCARDED_TAB_ID -} from './browser-extension-document-targets' -import { passesBrowserExtensionEventFilter } from './browser-extension-event-filters' -import { installBrowserExtensionInertApis } from './browser-extension-inert-apis' +} from './browser/extensions/documents/browser-extension-document-targets' +import { passesBrowserExtensionEventFilter } from './browser/extensions/api/browser-extension-event-filters' +import { installBrowserExtensionInertApis } from './browser/extensions/api/browser-extension-inert-apis' import { installBrowserExtensionApis, type BrowserExtensionInvokeReply, type BrowserExtensionMainWorldBridge -} from './browser-extension-main-world' -import { installBrowserExtensionNativeMessaging } from './browser-extension-native-messaging' -import { installBrowserExtensionStorageRelay } from './browser-extension-storage-relay' +} from './browser/extensions/api/browser-extension-main-world' +import { installBrowserExtensionNativeMessaging } from './browser/extensions/messaging/browser-extension-native-messaging' +import { installBrowserExtensionStorageRelay } from './browser/extensions/storage/browser-extension-storage-relay' import { installBrowserExtensionStorageSync, PRELOAD_STORAGE_SYNC_CONSTANTS -} from './browser-extension-storage-sync' +} from './browser/extensions/storage/browser-extension-storage-sync' /** * Orca's API shim for extension service workers, bundled into one standalone script that Orca's diff --git a/src/preload/browser-guest.ts b/src/preload/browser-guest.ts index 3f42876ed39..1903fc84cdc 100644 --- a/src/preload/browser-guest.ts +++ b/src/preload/browser-guest.ts @@ -1,11 +1,11 @@ import type { ContextBridge, IpcRenderer, WebFrame } from 'electron' -import { installBrowserPasswordDetector } from './browser-password-detector' +import { installBrowserPasswordDetector } from './browser/passwords/browser-password-detector' import { installBrowserWindowCloseGuard, PRELOAD_BROWSER_GUEST_WINDOW_CLOSE_CHANNEL -} from './browser-window-close-installation' -import { installBrowserWindowPrompt } from './browser-window-prompt-installation' -import { installNativeChatVisualGuestTheme } from './native-chat-visual-guest-theme' +} from './browser/window-controls/browser-window-close-installation' +import { installBrowserWindowPrompt } from './browser/window-controls/browser-window-prompt-installation' +import { installNativeChatVisualGuestTheme } from './native-chat/native-chat-visual-guest-theme' // Raw require keeps the sandboxed preload standalone in the CJS build. const electron: { diff --git a/src/preload/browser-passkey-request.ts b/src/preload/browser-passkey-request.ts index 5f666278ea3..4066364b673 100644 --- a/src/preload/browser-passkey-request.ts +++ b/src/preload/browser-passkey-request.ts @@ -3,7 +3,7 @@ import { BROWSER_PASSKEY_REQUEST_CANCEL_CHANNEL, BROWSER_PASSKEY_REQUEST_PENDING_CHANNEL } from '../shared/browser-passkey-request' -import { installBrowserPasskeyRequestWatch } from './browser-passkey-request-watch' +import { installBrowserPasskeyRequestWatch } from './browser/passkeys/browser-passkey-request-watch' // A session preload: it runs in every frame of every browser page, popup and serve window. const electron: { diff --git a/src/preload/browser-window-close-installation.test.ts b/src/preload/browser-window-close-installation.test.ts deleted file mode 100644 index afca315c1a2..00000000000 --- a/src/preload/browser-window-close-installation.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { buildSync } from 'esbuild' -import { fileURLToPath } from 'node:url' -import { runInNewContext } from 'node:vm' - -import { installBrowserWindowCloseGuard } from './browser-window-close-installation' -import { BROWSER_GUEST_WINDOW_CLOSE_CHANNEL } from '../shared/browser-guest-window-close' - -describe('browser window close guard', () => { - afterEach(() => { - vi.unstubAllGlobals() - }) - - it('replaces the native close with a non-replaceable request to Orca', () => { - const nativeClose = vi.fn() - const requestClose = vi.fn() - vi.stubGlobal('window', { close: nativeClose }) - - installBrowserWindowCloseGuard(requestClose) - - expect(window.close()).toBeUndefined() - expect(nativeClose).not.toHaveBeenCalled() - expect(requestClose).toHaveBeenCalledTimes(1) - expect(Reflect.set(window, 'close', nativeClose)).toBe(false) - }) - - it.each([true, false])('routes a close only from the top frame: %s', (isMainFrame) => { - const sendToHost = vi.fn() - const nativeClose = vi.fn() - const pageWindow = { close: nativeClose } - const preload = buildSync({ - entryPoints: [fileURLToPath(new URL('./browser-guest.ts', import.meta.url))], - bundle: true, - platform: 'node', - format: 'cjs', - external: ['electron'], - write: false - }).outputFiles[0].text - - runInNewContext(preload, { - window: pageWindow, - process: { isMainFrame }, - require: (name: string) => { - expect(name).toBe('electron') - return { - ipcRenderer: { sendToHost }, - contextBridge: { - executeInMainWorld: (script: { - func: (requestClose: () => void) => void - args: [() => void] - }) => script.func(...script.args) - } - } - } - }) - - pageWindow.close() - - expect(nativeClose).toHaveBeenCalledTimes(isMainFrame ? 0 : 1) - expect(sendToHost.mock.calls).toEqual(isMainFrame ? [[BROWSER_GUEST_WINDOW_CLOSE_CHANNEL]] : []) - }) -}) diff --git a/src/preload/browser-extension-api-surface.ts b/src/preload/browser/extensions/api/browser-extension-api-surface.ts similarity index 100% rename from src/preload/browser-extension-api-surface.ts rename to src/preload/browser/extensions/api/browser-extension-api-surface.ts diff --git a/src/preload/browser-extension-event-filters.ts b/src/preload/browser/extensions/api/browser-extension-event-filters.ts similarity index 100% rename from src/preload/browser-extension-event-filters.ts rename to src/preload/browser/extensions/api/browser-extension-event-filters.ts diff --git a/src/preload/browser-extension-frame-lifetime.ts b/src/preload/browser/extensions/api/browser-extension-frame-lifetime.ts similarity index 100% rename from src/preload/browser-extension-frame-lifetime.ts rename to src/preload/browser/extensions/api/browser-extension-frame-lifetime.ts diff --git a/src/preload/browser-extension-inert-apis.test.ts b/src/preload/browser/extensions/api/browser-extension-inert-apis.test.ts similarity index 90% rename from src/preload/browser-extension-inert-apis.test.ts rename to src/preload/browser/extensions/api/browser-extension-inert-apis.test.ts index f54dba1de67..f98d3ca313b 100644 --- a/src/preload/browser-extension-inert-apis.test.ts +++ b/src/preload/browser/extensions/api/browser-extension-inert-apis.test.ts @@ -63,10 +63,4 @@ describe('installBrowserExtensionInertApis', () => { expect(member(chrome, 'storage.managed.onChanged')).toEqual({ native: true }) } }) - - it('keeps members Electron already provides', () => { - const native = vi.fn() - const { chrome } = install('page', {}, { extension: { getViews: native } }) - expect(member(chrome, 'extension.getViews')).toBe(native) - }) }) diff --git a/src/preload/browser-extension-inert-apis.ts b/src/preload/browser/extensions/api/browser-extension-inert-apis.ts similarity index 100% rename from src/preload/browser-extension-inert-apis.ts rename to src/preload/browser/extensions/api/browser-extension-inert-apis.ts diff --git a/src/preload/browser-extension-main-world.test.ts b/src/preload/browser/extensions/api/browser-extension-main-world.test.ts similarity index 100% rename from src/preload/browser-extension-main-world.test.ts rename to src/preload/browser/extensions/api/browser-extension-main-world.test.ts diff --git a/src/preload/browser-extension-main-world.ts b/src/preload/browser/extensions/api/browser-extension-main-world.ts similarity index 100% rename from src/preload/browser-extension-main-world.ts rename to src/preload/browser/extensions/api/browser-extension-main-world.ts diff --git a/src/preload/browser-extension-document-targets.test.ts b/src/preload/browser/extensions/documents/browser-extension-document-targets.test.ts similarity index 67% rename from src/preload/browser-extension-document-targets.test.ts rename to src/preload/browser/extensions/documents/browser-extension-document-targets.test.ts index c58e19fee45..cd46a140026 100644 --- a/src/preload/browser-extension-document-targets.test.ts +++ b/src/preload/browser/extensions/documents/browser-extension-document-targets.test.ts @@ -251,108 +251,6 @@ describe('Orca documentIds in native scripting targets', () => { expect(listeners.size).toBe(0) } ) - - it("preserves a native document constraint for Orca's document ids", async () => { - const { chrome, executeScript, calls } = install(['webNavigation', 'scripting']) - const results = await chrome.scripting.executeScript({ - target: { tabId: 3, documentIds: [ORCA_AD] }, - func: () => 1 - }) - expect(executeScript).toHaveBeenCalledTimes(2) - expect(executeScript.mock.calls[1][0].target).toEqual({ tabId: 3, documentIds: [CHROMIUM_AD] }) - expect(results).toEqual([{ frameId: 42, documentId: ORCA_AD, result: 42 }]) - expect(calls).toEqual([[3], [3]]) - }) - - it("passes Chromium's own ids through and keeps the callback form", async () => { - const { chrome, executeScript, insertCSS, sendMessage } = install(['webRequest']) - await chrome.scripting.executeScript({ target: { tabId: 3, documentIds: [CHROMIUM_TOP] } }) - expect(executeScript.mock.calls[0][0].target).toEqual({ tabId: 3, documentIds: [CHROMIUM_TOP] }) - - const done = await new Promise((resolve) => - chrome.scripting.insertCSS( - { target: { tabId: 3, documentIds: [ORCA_TOP] }, css: 'a{}' }, - () => resolve('called back') - ) - ) - expect(done).toBe('called back') - expect(insertCSS.mock.calls[0][0]).toEqual({ - target: { tabId: 3, documentIds: [CHROMIUM_TOP] }, - css: 'a{}' - }) - - await chrome.tabs.sendMessage(3, 'ping', { documentId: ORCA_AD }) - expect(sendMessage).toHaveBeenCalledWith(3, 'ping', { documentId: CHROMIUM_AD }) - }) - - it.each([false, true])( - 'resolves message recipients without requiring scripting even when the namespace exists: %s', - async (nativeScripting) => { - const { chrome, executeScript, sendMessage, nativeListeners } = install( - ['webNavigation'], - nativeScripting - ) - executeScript.mockRejectedValueOnce(new Error('Requires scripting permission')) - - await expect(chrome.tabs.sendMessage(3, 'ping', { documentId: ORCA_AD })).resolves.toBe( - 'pong' - ) - - expect(sendMessage).toHaveBeenLastCalledWith(3, 'ping', { documentId: CHROMIUM_AD }) - expect(executeScript).toHaveBeenCalledTimes(nativeScripting ? 1 : 0) - expect(nativeListeners.size).toBe(0) - } - ) - - it('reaches dynamically injected message listeners that do not handle private probes', async () => { - const { chrome, sendMessage, nativeListeners } = install(['webNavigation', 'scripting']) - sendMessage.mockImplementationOnce(async (_tabId, message) => { - if (typeof message !== 'string') { - throw new Error('Unexpected private packet') - } - return 'dynamic receiver response' - }) - - await expect( - chrome.tabs.sendMessage(3, 'real payload', { documentId: ORCA_TOP }) - ).resolves.toBe('dynamic receiver response') - - expect(sendMessage).toHaveBeenCalledTimes(1) - expect(sendMessage).toHaveBeenCalledWith(3, 'real payload', { documentId: CHROMIUM_TOP }) - expect(nativeListeners.size).toBe(0) - }) - - it('never labels an unexpected native document as the requested Orca document', async () => { - const { chrome, executeScript } = install(['webNavigation', 'scripting']) - executeScript.mockResolvedValueOnce([{ frameId: 0, documentId: CHROMIUM_TOP, result: 0 }]) - executeScript.mockResolvedValueOnce([ - { frameId: 0, documentId: 'replacement-document', result: 1 } - ]) - - await expect( - chrome.scripting.executeScript({ - target: { tabId: 3, documentIds: [ORCA_TOP] } - }) - ).resolves.toEqual([{ frameId: 0, documentId: 'replacement-document', result: 1 }]) - }) - - it('cleans up failed identity probes and reports callback errors without delivering the payload', async () => { - const { chrome, sendMessage, nativeListeners } = install(['webNavigation'], false) - sendMessage.mockRejectedValueOnce(new Error('Receiving end does not exist')) - const callback = vi.fn() - const error = await new Promise((resolve) => { - chrome.tabs.sendMessage(3, 'private payload', { documentId: ORCA_TOP }, () => { - callback() - resolve(chrome.runtime.lastError) - }) - }) - - expect(error).toEqual({ message: 'Receiving end does not exist' }) - expect(callback).toHaveBeenCalledTimes(1) - expect(sendMessage).toHaveBeenCalledTimes(1) - expect(chrome.runtime.lastError).toBeUndefined() - expect(nativeListeners.size).toBe(0) - }) }) describe('calls to a discarded tab', () => { diff --git a/src/preload/browser-extension-document-targets.ts b/src/preload/browser/extensions/documents/browser-extension-document-targets.ts similarity index 99% rename from src/preload/browser-extension-document-targets.ts rename to src/preload/browser/extensions/documents/browser-extension-document-targets.ts index df091692047..eaac39d963a 100644 --- a/src/preload/browser-extension-document-targets.ts +++ b/src/preload/browser/extensions/documents/browser-extension-document-targets.ts @@ -1,4 +1,4 @@ -import type { BrowserExtensionMainWorldBridge } from './browser-extension-main-world' +import type { BrowserExtensionMainWorldBridge } from '../api/browser-extension-main-world' /** Main-only namespace listing a tab's frames with Orca's documentIds; never on `chrome`. */ export const PRELOAD_DOCUMENT_TARGETS_NAMESPACE = 'orcaDocumentTargets' diff --git a/src/preload/browser-extension-content-script-relay.test.ts b/src/preload/browser/extensions/messaging/browser-extension-content-script-relay.test.ts similarity index 98% rename from src/preload/browser-extension-content-script-relay.test.ts rename to src/preload/browser/extensions/messaging/browser-extension-content-script-relay.test.ts index 98d21664c1a..4d98f9d5a60 100644 --- a/src/preload/browser-extension-content-script-relay.test.ts +++ b/src/preload/browser/extensions/messaging/browser-extension-content-script-relay.test.ts @@ -5,7 +5,7 @@ import { createContentScriptRelayBridge, installContentScriptRelayFilter } from './browser-extension-content-script-relay' -import type { BrowserExtensionStorageSyncRelay } from './browser-extension-storage-sync' +import type { BrowserExtensionStorageSyncRelay } from '../storage/browser-extension-storage-sync' type Listener = ( message: unknown, diff --git a/src/preload/browser-extension-content-script-relay.ts b/src/preload/browser/extensions/messaging/browser-extension-content-script-relay.ts similarity index 98% rename from src/preload/browser-extension-content-script-relay.ts rename to src/preload/browser/extensions/messaging/browser-extension-content-script-relay.ts index 0188f6bcb9f..50f2ddd8426 100644 --- a/src/preload/browser-extension-content-script-relay.ts +++ b/src/preload/browser/extensions/messaging/browser-extension-content-script-relay.ts @@ -1,11 +1,11 @@ import type { BrowserExtensionInvokeReply, BrowserExtensionMainWorldBridge -} from './browser-extension-main-world' +} from '../api/browser-extension-main-world' import type { BrowserExtensionStorageSyncForward, BrowserExtensionStorageSyncRelay -} from './browser-extension-storage-sync' +} from '../storage/browser-extension-storage-sync' /** * Content scripts run in Chromium's per-extension isolated world, which no Orca preload reaches, diff --git a/src/preload/browser-extension-native-messaging.ts b/src/preload/browser/extensions/messaging/browser-extension-native-messaging.ts similarity index 98% rename from src/preload/browser-extension-native-messaging.ts rename to src/preload/browser/extensions/messaging/browser-extension-native-messaging.ts index 88d4a32f85e..3c793e8ec18 100644 --- a/src/preload/browser-extension-native-messaging.ts +++ b/src/preload/browser/extensions/messaging/browser-extension-native-messaging.ts @@ -1,4 +1,4 @@ -import type { BrowserExtensionMainWorldBridge } from './browser-extension-main-world' +import type { BrowserExtensionMainWorldBridge } from '../api/browser-extension-main-world' /** Main-only namespace behind connectNative/sendNativeMessage; never installed on `chrome`. */ export const PRELOAD_NATIVE_MESSAGING_NAMESPACE = 'orcaNativeMessaging' diff --git a/src/preload/browser-extension-storage-relay.test.ts b/src/preload/browser/extensions/storage/browser-extension-storage-relay.test.ts similarity index 75% rename from src/preload/browser-extension-storage-relay.test.ts rename to src/preload/browser/extensions/storage/browser-extension-storage-relay.test.ts index 4c611b29325..5ba7e59bc13 100644 --- a/src/preload/browser-extension-storage-relay.test.ts +++ b/src/preload/browser/extensions/storage/browser-extension-storage-relay.test.ts @@ -1,6 +1,6 @@ import { runInNewContext } from 'node:vm' import { describe, expect, it, vi } from 'vitest' -import type { BrowserExtensionInvokeReply } from './browser-extension-main-world' +import type { BrowserExtensionInvokeReply } from '../api/browser-extension-main-world' import { installBrowserExtensionStorageRelay, PRELOAD_STORAGE_RELAY_NAMESPACE, @@ -149,36 +149,7 @@ function call(root: unknown, path: string, ...args: unknown[]): unknown { return fn.call(owner, ...args) } -const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) - describe('installBrowserExtensionStorageRelay in a worker', () => { - it('fires onChanged and the area event once per write with only the keys that changed', async () => { - const worker = install('worker') - worker.listen() - expect(worker.listens).toEqual([[PRELOAD_STORAGE_RELAY_NAMESPACE, 'onChanged', true]]) - - await call(worker.chrome, 'storage.local.set', { kept: 'same', changed: 'new', added: [1] }) - await call(worker.chrome, 'storage.local.set', { kept: 'same' }) - await call(worker.chrome, 'storage.local.remove', ['gone', 'missing']) - await call(worker.chrome, 'storage.session.set', { token: 'abc' }) - await call(worker.chrome, 'storage.session.clear') - - const written = { changed: { oldValue: 'old', newValue: 'new' }, added: { newValue: [1] } } - expect(worker.all).toEqual([ - ['local', written], - ['local', { gone: { oldValue: 1 } }], - ['session', { token: { newValue: 'abc' } }], - ['session', { token: { oldValue: 'abc' } }] - ]) - expect(worker.perArea).toEqual([ - ['local', written], - ['local', { gone: { oldValue: 1 } }], - ['session', { token: { newValue: 'abc' } }], - ['session', { token: { oldValue: 'abc' } }] - ]) - expect(worker.calls).toEqual([]) - }) - it('reports old values in write order when writes are not awaited', async () => { const worker = install('worker') worker.listen() @@ -239,37 +210,3 @@ describe('installBrowserExtensionStorageRelay in a worker', () => { expect(worker.perArea).toEqual([['session', { token: { newValue: 'abc' } }]]) }) }) - -describe('installBrowserExtensionStorageRelay in an extension page', () => { - it('reports its own changed keys to main and leaves the native onChanged alone', async () => { - const page = install('page') - expect(page.chrome.storage.onChanged).toEqual({ native: true }) - expect(page.local.area.onChanged).toEqual({ native: true }) - expect(page.hasEventHandler()).toBe(false) - - await call(page.chrome, 'storage.local.set', { kept: 'same', changed: 'new' }) - await call(page.chrome, 'storage.local.set', { kept: 'same' }) - await call(page.chrome, 'storage.local.clear') - await settle() - expect(page.calls).toEqual([ - [ - PRELOAD_STORAGE_RELAY_NAMESPACE, - 'report', - ['local', { changed: { oldValue: 'old', newValue: 'new' } }] - ], - [ - PRELOAD_STORAGE_RELAY_NAMESPACE, - 'report', - [ - 'local', - { - kept: { oldValue: 'same' }, - changed: { oldValue: 'new' }, - gone: { oldValue: 1 } - } - ] - ] - ]) - expect(page.local.data.size).toBe(0) - }) -}) diff --git a/src/preload/browser-extension-storage-relay.ts b/src/preload/browser/extensions/storage/browser-extension-storage-relay.ts similarity index 98% rename from src/preload/browser-extension-storage-relay.ts rename to src/preload/browser/extensions/storage/browser-extension-storage-relay.ts index 9c43ba3bf11..5f090e6fc99 100644 --- a/src/preload/browser-extension-storage-relay.ts +++ b/src/preload/browser/extensions/storage/browser-extension-storage-relay.ts @@ -1,4 +1,4 @@ -import type { BrowserExtensionMainWorldBridge } from './browser-extension-main-world' +import type { BrowserExtensionMainWorldBridge } from '../api/browser-extension-main-world' /** Main-only namespace carrying page storage writes to the worker; never installed on `chrome`. */ export const PRELOAD_STORAGE_RELAY_NAMESPACE = 'orcaStorageRelay' diff --git a/src/preload/browser/extensions/storage/browser-extension-storage-sync.test.ts b/src/preload/browser/extensions/storage/browser-extension-storage-sync.test.ts new file mode 100644 index 00000000000..40ba69c72d6 --- /dev/null +++ b/src/preload/browser/extensions/storage/browser-extension-storage-sync.test.ts @@ -0,0 +1,100 @@ +import { runInNewContext } from 'node:vm' +import { describe, expect, it, vi } from 'vitest' +import type { BrowserExtensionInvokeReply } from '../api/browser-extension-main-world' +import { + installBrowserExtensionStorageSync, + PRELOAD_STORAGE_SYNC_CONSTANTS, + PRELOAD_STORAGE_SYNC_NAMESPACE +} from './browser-extension-storage-sync' + +type Runtime = { lastError?: { message: string } } + +function nativeEvent() { + const listeners = new Set() + return { + listeners, + addListener: vi.fn((callback: unknown) => listeners.add(callback)), + removeListener: vi.fn((callback: unknown) => listeners.delete(callback)) + } +} + +/** Runs the installer from its source text, as contextBridge.executeInMainWorld does. */ +function install( + reply: (method: string, args: unknown[]) => BrowserExtensionInvokeReply, + forward?: (changes: unknown, from?: string) => void +) { + const runtime: Runtime = {} + const native = nativeEvent() + const nativeSync = { get: vi.fn(), set: vi.fn() } + const chrome = { runtime, storage: { local: {}, sync: nativeSync, onChanged: native } } + let dispatch: ((namespace: string, event: string, args: unknown[]) => void) | null = null + const calls: unknown[][] = [] + const listens: unknown[][] = [] + const bridge = { + call: async (namespace: string, method: string, args: unknown[]) => { + calls.push([namespace, method, args]) + return reply(method, args) + }, + listen: (namespace: string, event: string, active: boolean) => + listens.push([namespace, event, active]), + onEvent: (handler: typeof dispatch) => { + dispatch = handler + }, + passesFilter: () => true + } + const realm = { chrome, console, JSON, Promise } + const relay: unknown = runInNewContext( + `(${installBrowserExtensionStorageSync.toString()})(bridge, constants, forward)`, + { + ...realm, + globalThis: realm, + bridge, + constants: PRELOAD_STORAGE_SYNC_CONSTANTS, + forward + } + ) + return { + relay: (method: string, args: unknown[], from?: string): unknown => + typeof relay === 'function' ? relay(method, args, from) : undefined, + chrome, + native, + nativeSync, + calls, + listens, + emit: (changes: unknown) => dispatch?.(PRELOAD_STORAGE_SYNC_NAMESPACE, 'onChanged', [changes]) + } +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' +} + +function call(root: unknown, path: string, ...args: unknown[]): unknown { + const keys = path.split('.') + const name = keys.pop() ?? '' + const owner = keys.reduce( + (value, key) => (isRecord(value) ? value[key] : undefined), + root + ) + const fn = isRecord(owner) ? owner[name] : null + if (typeof fn !== 'function') { + throw new Error(`${path} is not a function`) + } + return fn.call(owner, ...args) +} + +describe('installBrowserExtensionStorageSync', () => { + it('sets lastError only inside a failed callback and rejects a failed promise', async () => { + const page = install(() => ({ ok: false, error: 'QUOTA_BYTES quota exceeded' })) + const lastError = await new Promise((resolve) => + call(page.chrome, 'storage.sync.set', { big: 1 }, () => + resolve(page.chrome.runtime.lastError?.message) + ) + ) + expect(lastError).toBe('QUOTA_BYTES quota exceeded') + expect(page.chrome.runtime.lastError).toBeUndefined() + await expect(call(page.chrome, 'storage.sync.set', { big: 1 })).rejects.toThrow( + 'QUOTA_BYTES quota exceeded' + ) + }) +}) diff --git a/src/preload/browser-extension-storage-sync.ts b/src/preload/browser/extensions/storage/browser-extension-storage-sync.ts similarity index 99% rename from src/preload/browser-extension-storage-sync.ts rename to src/preload/browser/extensions/storage/browser-extension-storage-sync.ts index 89c4824a3bb..bd0c5d788df 100644 --- a/src/preload/browser-extension-storage-sync.ts +++ b/src/preload/browser/extensions/storage/browser-extension-storage-sync.ts @@ -1,7 +1,7 @@ import type { BrowserExtensionInvokeReply, BrowserExtensionMainWorldBridge -} from './browser-extension-main-world' +} from '../api/browser-extension-main-world' /** Main-only namespace backing chrome.storage.sync; never installed on `chrome` by that name. */ export const PRELOAD_STORAGE_SYNC_NAMESPACE = 'orcaStorageSync' diff --git a/src/preload/browser-extension-web-store-bridge.ts b/src/preload/browser/extensions/web-store/browser-extension-web-store-bridge.ts similarity index 100% rename from src/preload/browser-extension-web-store-bridge.ts rename to src/preload/browser/extensions/web-store/browser-extension-web-store-bridge.ts diff --git a/src/preload/browser-extension-web-store-main-world.test.ts b/src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.test.ts similarity index 94% rename from src/preload/browser-extension-web-store-main-world.test.ts rename to src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.test.ts index 6923b31d5a4..feb494d4ef7 100644 --- a/src/preload/browser-extension-web-store-main-world.test.ts +++ b/src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.test.ts @@ -63,12 +63,6 @@ function lastErrors(realm: unknown): [unknown, unknown] { } describe('installChromeWebStoreApis', () => { - it('keeps existing runtime members', () => { - const sendMessage = () => {} - const { realm } = installInFreshRealm(() => ({}), { runtime: { sendMessage } }) - expect(member(realm, 'chrome.runtime.sendMessage')).toBe(sendMessage) - }) - it('sets lastError on runtime and extension only while the callback runs', async () => { const { realm, calls } = installInFreshRealm(() => ({ value: 'user_cancelled', diff --git a/src/preload/browser-extension-web-store-main-world.ts b/src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.ts similarity index 100% rename from src/preload/browser-extension-web-store-main-world.ts rename to src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.ts diff --git a/src/preload/browser-extension-web-store-wording.ts b/src/preload/browser/extensions/web-store/browser-extension-web-store-wording.ts similarity index 100% rename from src/preload/browser-extension-web-store-wording.ts rename to src/preload/browser/extensions/web-store/browser-extension-web-store-wording.ts diff --git a/src/preload/browser-passkey-request-watch.test.ts b/src/preload/browser/passkeys/browser-passkey-request-watch.test.ts similarity index 100% rename from src/preload/browser-passkey-request-watch.test.ts rename to src/preload/browser/passkeys/browser-passkey-request-watch.test.ts diff --git a/src/preload/browser-passkey-request-watch.ts b/src/preload/browser/passkeys/browser-passkey-request-watch.ts similarity index 100% rename from src/preload/browser-passkey-request-watch.ts rename to src/preload/browser/passkeys/browser-passkey-request-watch.ts diff --git a/src/preload/browser-password-detector.test.ts b/src/preload/browser/passwords/browser-password-detector.test.ts similarity index 90% rename from src/preload/browser-password-detector.test.ts rename to src/preload/browser/passwords/browser-password-detector.test.ts index a06fdf168c5..2044a7f7565 100644 --- a/src/preload/browser-password-detector.test.ts +++ b/src/preload/browser/passwords/browser-password-detector.test.ts @@ -3,11 +3,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { BROWSER_PASSWORDS_GUEST_CHANNELS, BROWSER_PASSWORDS_TO_GUEST_CHANNELS -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import type { BrowserPasswordFillRequest, BrowserPasswordGuestEnable -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { installBrowserPasswordDetector } from './browser-password-detector' const CHANNEL = BROWSER_PASSWORDS_GUEST_CHANNELS @@ -162,26 +162,6 @@ afterEach(() => { }) describe('browser password detector', () => { - it('installs only its main listeners until main enables the document', async () => { - load(LOGIN_FORM) - const addEventListener = vi.mocked(document.addEventListener) - const observe = vi.mocked(MutationObserver.prototype.observe) - - install() - typeInto(el('#pw'), 'secret') - await vi.advanceTimersByTimeAsync(1000) - - expect([...listeners.keys()].sort()).toEqual( - Object.values(BROWSER_PASSWORDS_TO_GUEST_CHANNELS).sort() - ) - expect(addEventListener).not.toHaveBeenCalled() - expect(observe).not.toHaveBeenCalled() - expect(sent).toEqual([]) - - enable() - expect(observe).toHaveBeenCalled() - }) - it('reports no page forms unless main waits on a login that navigated here', async () => { load(LOGIN_FORM) install() @@ -193,44 +173,6 @@ describe('browser password detector', () => { expect(sentOn(CHANNEL.pageForms)).toEqual([]) }) - it('reports the page forms once after enable and again only when they change', async () => { - load(LOGIN_FORM) - install() - enable({ reportPageForms: true }) - await vi.advanceTimersByTimeAsync(600) - - expect(sentOn(CHANNEL.pageForms)).toEqual([ - { - forms: [ - { - formSignature: expect.any(String), - kind: 'login', - usernameFieldName: 'email', - passwordFieldName: 'password', - action: new URL('/session', window.location.href).toString() - } - ] - } - ]) - - document.body.insertAdjacentHTML('beforeend', '

unrelated

') - await vi.advanceTimersByTimeAsync(600) - expect(sentOn(CHANNEL.pageForms)).toHaveLength(1) - - document.body.insertAdjacentHTML( - 'beforeend', - '
' - ) - layout() - await vi.advanceTimersByTimeAsync(600) - expect(sentOn(CHANNEL.pageForms).at(-1)).toEqual({ - forms: [ - expect.objectContaining({ kind: 'login' }), - expect.objectContaining({ kind: 'signup' }) - ] - }) - }) - it('reports trusted typing after the debounce, with only typed values', async () => { load(LOGIN_FORM) el('#email').value = 'prefilled@example.com' diff --git a/src/preload/browser-password-detector.ts b/src/preload/browser/passwords/browser-password-detector.ts similarity index 99% rename from src/preload/browser-password-detector.ts rename to src/preload/browser/passwords/browser-password-detector.ts index ad35208bc1f..6dba6cd7c0b 100644 --- a/src/preload/browser-password-detector.ts +++ b/src/preload/browser/passwords/browser-password-detector.ts @@ -6,7 +6,7 @@ import type { BrowserPasswordGuestCapture, BrowserPasswordGuestPageForms -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { createBrowserPasswordElementTokens } from './browser-password-element-tokens' import { applyBrowserPasswordFill, diff --git a/src/preload/browser-password-element-tokens.ts b/src/preload/browser/passwords/browser-password-element-tokens.ts similarity index 100% rename from src/preload/browser-password-element-tokens.ts rename to src/preload/browser/passwords/browser-password-element-tokens.ts diff --git a/src/preload/browser-password-field-fill.ts b/src/preload/browser/passwords/browser-password-field-fill.ts similarity index 99% rename from src/preload/browser-password-field-fill.ts rename to src/preload/browser/passwords/browser-password-field-fill.ts index ec617be730e..0adcbe2cb78 100644 --- a/src/preload/browser-password-field-fill.ts +++ b/src/preload/browser/passwords/browser-password-field-fill.ts @@ -5,7 +5,7 @@ import type { BrowserPasswordFillRequest, BrowserPasswordFillResult -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { isPlaceholderUsernameValue } from './browser-password-field-rules' import type { BrowserPasswordFormScanner } from './browser-password-form-scan' diff --git a/src/preload/browser-password-field-rules.ts b/src/preload/browser/passwords/browser-password-field-rules.ts similarity index 100% rename from src/preload/browser-password-field-rules.ts rename to src/preload/browser/passwords/browser-password-field-rules.ts diff --git a/src/preload/browser-password-focus-tracker.ts b/src/preload/browser/passwords/browser-password-focus-tracker.ts similarity index 98% rename from src/preload/browser-password-focus-tracker.ts rename to src/preload/browser/passwords/browser-password-focus-tracker.ts index 950bb57df21..000aa06c3c9 100644 --- a/src/preload/browser-password-focus-tracker.ts +++ b/src/preload/browser/passwords/browser-password-focus-tracker.ts @@ -6,7 +6,7 @@ import type { BrowserPasswordFieldRole, BrowserPasswordGuestFieldBlurred, BrowserPasswordGuestFieldFocused -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { PRELOAD_BROWSER_PASSWORDS_GUEST_CHANNELS } from './browser-password-guest-channels' import type { BrowserPasswordGuestPort } from './browser-password-guest-port' import { diff --git a/src/preload/browser-password-form-parser.test.ts b/src/preload/browser/passwords/browser-password-form-parser.test.ts similarity index 80% rename from src/preload/browser-password-form-parser.test.ts rename to src/preload/browser/passwords/browser-password-form-parser.test.ts index 3139ad42165..61fbbcbfe81 100644 --- a/src/preload/browser-password-form-parser.test.ts +++ b/src/preload/browser/passwords/browser-password-form-parser.test.ts @@ -253,57 +253,4 @@ describe('parsePasswordForm', () => { ])('%s', (_name, fields, text, expected) => { expect(parse(fields, text)).toEqual(expected) }) - - describe('username-first steps', () => { - it.each<[string, TestField[], string, string | null]>([ - [ - 'Google: autocomplete=username identifier box', - [input('identifier', { type: 'email', id: 'identifierId', autocomplete: 'username' })], - 'next', - 'identifier' - ], - [ - 'Microsoft: lone email box in a form that says Next', - [input('loginfmt', { type: 'email' })], - 'sign in next', - 'loginfmt' - ], - [ - 'Okta: autocomplete=username with a remember-me checkbox', - [ - input('identifier', { autocomplete: 'username' }), - input('rememberMe', { type: 'checkbox' }) - ], - 'sign in', - 'identifier' - ], - ['lone autocomplete=email box', [input('mail', { autocomplete: 'email' })], 'go', 'mail'], - ['lone field without any sign-in wording', [input('city')], 'submit', null], - [ - 'contact form: autocomplete=email beside other fields', - [input('name'), input('mail', { autocomplete: 'email' }), input('subject')], - 'send', - null - ], - [ - 'newsletter email form', - [input('email', { type: 'email', autocomplete: 'email' })], - 'subscribe to our newsletter', - null - ], - [ - 'newsletter by field name', - [input('newsletter_email', { type: 'email' })], - 'continue', - null - ], - ['lone search box that says next', [input('q', { type: 'search' })], 'next', null] - ])('%s', (_name, fields, text, username) => { - const parsed = parse(fields, text) - expect(parsed ? parsed.username : null).toBe(username) - if (username) { - expect(parsed?.kind).toBe('username-only') - } - }) - }) }) diff --git a/src/preload/browser-password-form-parser.ts b/src/preload/browser/passwords/browser-password-form-parser.ts similarity index 99% rename from src/preload/browser-password-form-parser.ts rename to src/preload/browser/passwords/browser-password-form-parser.ts index f89ca3a3989..aee557fca18 100644 --- a/src/preload/browser-password-form-parser.ts +++ b/src/preload/browser/passwords/browser-password-form-parser.ts @@ -5,7 +5,7 @@ import type { BrowserPasswordFieldRole, BrowserPasswordFormKind -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { autocompleteRoleToken, isCandidatePasswordFormField, diff --git a/src/preload/browser-password-form-scan.ts b/src/preload/browser/passwords/browser-password-form-scan.ts similarity index 99% rename from src/preload/browser-password-form-scan.ts rename to src/preload/browser/passwords/browser-password-form-scan.ts index 57d8c3c7317..74cbbcdba09 100644 --- a/src/preload/browser-password-form-scan.ts +++ b/src/preload/browser/passwords/browser-password-form-scan.ts @@ -6,7 +6,7 @@ import type { BrowserPasswordFieldRole, BrowserPasswordFormSummary -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { isCredentialInputType, type PasswordFieldDescriptor } from './browser-password-field-rules' import { parsePasswordForm, diff --git a/src/preload/browser-password-guest-channels.ts b/src/preload/browser/passwords/browser-password-guest-channels.ts similarity index 95% rename from src/preload/browser-password-guest-channels.ts rename to src/preload/browser/passwords/browser-password-guest-channels.ts index 484fe08099e..cd82664a1cd 100644 --- a/src/preload/browser-password-guest-channels.ts +++ b/src/preload/browser/passwords/browser-password-guest-channels.ts @@ -1,7 +1,7 @@ import type { BROWSER_PASSWORDS_GUEST_CHANNELS, BROWSER_PASSWORDS_TO_GUEST_CHANNELS -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' // Why literals: the sandboxed guest preload's `require` resolves only 'electron', so importing the // shared constants would emit a chunk it cannot load. `satisfies` and the test pin them. diff --git a/src/preload/browser-password-guest-port.ts b/src/preload/browser/passwords/browser-password-guest-port.ts similarity index 100% rename from src/preload/browser-password-guest-port.ts rename to src/preload/browser/passwords/browser-password-guest-port.ts diff --git a/src/preload/browser-password-submit-tracker.ts b/src/preload/browser/passwords/browser-password-submit-tracker.ts similarity index 99% rename from src/preload/browser-password-submit-tracker.ts rename to src/preload/browser/passwords/browser-password-submit-tracker.ts index 1c1894abe57..331f236930f 100644 --- a/src/preload/browser-password-submit-tracker.ts +++ b/src/preload/browser/passwords/browser-password-submit-tracker.ts @@ -7,7 +7,7 @@ import type { BrowserPasswordGuestFormGone, BrowserPasswordGuestSubmitted, BrowserPasswordSubmitSource -} from '../shared/browser-passwords-types' +} from '../../../shared/browser-passwords-types' import { PRELOAD_BROWSER_PASSWORDS_GUEST_CHANNELS } from './browser-password-guest-channels' import type { BrowserPasswordGuestPort } from './browser-password-guest-port' import { diff --git a/src/preload/browser/window-controls/browser-window-close-installation.test.ts b/src/preload/browser/window-controls/browser-window-close-installation.test.ts new file mode 100644 index 00000000000..9c0a3f9b884 --- /dev/null +++ b/src/preload/browser/window-controls/browser-window-close-installation.test.ts @@ -0,0 +1,22 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { installBrowserWindowCloseGuard } from './browser-window-close-installation' + +describe('browser window close guard', () => { + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('replaces the native close with a non-replaceable request to Orca', () => { + const nativeClose = vi.fn() + const requestClose = vi.fn() + vi.stubGlobal('window', { close: nativeClose }) + + installBrowserWindowCloseGuard(requestClose) + + expect(window.close()).toBeUndefined() + expect(nativeClose).not.toHaveBeenCalled() + expect(requestClose).toHaveBeenCalledTimes(1) + expect(Reflect.set(window, 'close', nativeClose)).toBe(false) + }) +}) diff --git a/src/preload/browser-window-close-installation.ts b/src/preload/browser/window-controls/browser-window-close-installation.ts similarity index 100% rename from src/preload/browser-window-close-installation.ts rename to src/preload/browser/window-controls/browser-window-close-installation.ts diff --git a/src/preload/browser-window-prompt-installation.ts b/src/preload/browser/window-controls/browser-window-prompt-installation.ts similarity index 100% rename from src/preload/browser-window-prompt-installation.ts rename to src/preload/browser/window-controls/browser-window-prompt-installation.ts diff --git a/src/preload/doc-preview-link.ts b/src/preload/doc-preview-link.ts index 5cba0144e53..24c402907a4 100644 --- a/src/preload/doc-preview-link.ts +++ b/src/preload/doc-preview-link.ts @@ -1,9 +1,9 @@ import { installDocPreviewLinkInterception, PRELOAD_DOC_PREVIEW_LINK_CLICK_CHANNEL -} from './doc-preview-link-interception' +} from './document-preview/doc-preview-link-interception' import type { IpcRenderer, WebFrame } from 'electron' -import { installNativeChatVisualGuestTheme } from './native-chat-visual-guest-theme' +import { installNativeChatVisualGuestTheme } from './native-chat/native-chat-visual-guest-theme' // Raw require keeps the sandboxed preload standalone in the CJS build. const electron: { diff --git a/src/preload/doc-preview-link-interception.ts b/src/preload/document-preview/doc-preview-link-interception.ts similarity index 97% rename from src/preload/doc-preview-link-interception.ts rename to src/preload/document-preview/doc-preview-link-interception.ts index 99ea276ccf6..d9bee1dd5f3 100644 --- a/src/preload/doc-preview-link-interception.ts +++ b/src/preload/document-preview/doc-preview-link-interception.ts @@ -1,5 +1,5 @@ // Runs in the isolated world so page scripts cannot access the link reporter or its listeners. -import type { DocPreviewLinkModifiers } from '../shared/document-preview/doc-preview-scheme' +import type { DocPreviewLinkModifiers } from '../../shared/document-preview/doc-preview-scheme' export type DocPreviewExternalLinkReporter = ( url: string, diff --git a/src/preload/gitlab-work-item-details.test.ts b/src/preload/gitlab-work-item-details.test.ts deleted file mode 100644 index b7a7c955168..00000000000 --- a/src/preload/gitlab-work-item-details.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' - -const invoke = vi.hoisted(() => vi.fn()) -vi.mock('electron', () => ({ ipcRenderer: { invoke } })) -import { glApi } from './gitlab' - -beforeEach(() => invoke.mockReset()) - -it('preserves the optional review scope through the existing desktop details channel', async () => { - const args = { repoPath: '/repo', iid: 12, type: 'mr' as const, includeReviewDetails: false } - const details = { body: 'MR body', comments: [], pipelineJobs: [] } - invoke.mockResolvedValue(details) - expect(await glApi.workItemDetails(args)).toBe(details) - expect(invoke).toHaveBeenCalledWith('gitlab:workItemDetails', args) - const defaultArgs = { repoPath: '/repo', iid: 12, type: 'mr' as const } - await glApi.workItemDetails(defaultArgs) - expect(invoke).toHaveBeenLastCalledWith('gitlab:workItemDetails', defaultArgs) -}) diff --git a/src/preload/index.ts b/src/preload/index.ts index 6ccddcf2d8c..1830e09c681 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1,8 +1,8 @@ import { contextBridge, ipcRenderer } from 'electron' import { HIDDEN_WINDOW_FRAME_PUMP_STOP_CHANNEL } from '../shared/hidden-window-frame-pump' -import { installHiddenWindowFramePump } from './hidden-window-frame-pump' +import { installHiddenWindowFramePump } from './renderer/hidden-window-frame-pump' import type { PreloadApi } from './api-types' -import { installBrowserFindListener } from './preload-runtime-support' +import { installBrowserFindListener } from './renderer/renderer-runtime' import { appApi } from './api/app-bridge' import { orcaProfilesApi } from './api/orca-profiles-bridge' import { platformApi } from './api/platform-bridge' @@ -29,7 +29,7 @@ import { crashReportsApi } from './api/crash-reports-bridge' import { exportApi } from './api/export-bridge' import { ghApi } from './api/gh-bridge' import { hostedReviewApi } from './api/hosted-review-bridge' -import { glApiBridge } from './api/gl-bridge' +import { glApi } from './api/gitlab' import { bitbucketApi } from './api/bitbucket-bridge' import { linearApi } from './api/linear-bridge' import { jiraApi } from './api/jira-bridge' @@ -131,7 +131,7 @@ const api = { export: exportApi, gh: ghApi, hostedReview: hostedReviewApi, - gl: glApiBridge, + gl: glApi, bitbucket: bitbucketApi, linear: linearApi, jira: jiraApi, diff --git a/src/preload/native-chat-visual-guest-theme.ts b/src/preload/native-chat/native-chat-visual-guest-theme.ts similarity index 95% rename from src/preload/native-chat-visual-guest-theme.ts rename to src/preload/native-chat/native-chat-visual-guest-theme.ts index ef3efe9024c..5237d255702 100644 --- a/src/preload/native-chat-visual-guest-theme.ts +++ b/src/preload/native-chat/native-chat-visual-guest-theme.ts @@ -3,7 +3,7 @@ import { NATIVE_CHAT_VISUAL_GUEST_THEME_READ, NATIVE_CHAT_VISUAL_GUEST_THEME_UPDATE, type NativeChatVisualGuestTheme -} from '../shared/native-chat/native-chat-visual-shell' +} from '../../shared/native-chat/native-chat-visual-shell' export function installNativeChatVisualGuestTheme( ipc: Pick, diff --git a/src/preload/opencode-go-credentials.test.ts b/src/preload/opencode-go-credentials.test.ts deleted file mode 100644 index e7c5f6d4bea..00000000000 --- a/src/preload/opencode-go-credentials.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { opencodeGoCredentialsApi } from './api/opencode-go-credentials-bridge' - -const invoke = vi.hoisted(() => vi.fn(async () => ({ apiKeyConfigured: true }))) -vi.mock('electron', () => ({ ipcRenderer: { invoke } })) - -describe('OpenCode Go credential bridge', () => { - it('exposes only status and write operations', async () => { - expect(await opencodeGoCredentialsApi.getStatus()).toEqual({ apiKeyConfigured: true }) - await opencodeGoCredentialsApi.saveApiKey('fake-key') - await opencodeGoCredentialsApi.clearApiKey() - expect(invoke.mock.calls).toEqual([ - ['opencodeGoCredentials:getStatus'], - ['opencodeGoCredentials:saveApiKey', 'fake-key'], - ['opencodeGoCredentials:clearApiKey'] - ]) - expect(Object.keys(opencodeGoCredentialsApi)).toEqual([ - 'getStatus', - 'saveApiKey', - 'clearApiKey' - ]) - }) -}) diff --git a/src/preload/plugin-frame-guest.ts b/src/preload/plugin-frame-guest.ts index f68e4787b4e..42fdb3ea6cd 100644 --- a/src/preload/plugin-frame-guest.ts +++ b/src/preload/plugin-frame-guest.ts @@ -4,12 +4,12 @@ import { PRELOAD_PLUGIN_FRAME_IPC_CHANNEL, PRELOAD_PLUGIN_FRAME_KEY_CHANNEL, PRELOAD_PLUGIN_FRAME_TRANSPORT_GLOBAL -} from './plugin-frame-guest-transport' +} from './plugins/frames/plugin-frame-guest-transport' import { createPluginFrameGestureTracker, createPluginFrameSendBudget, type PluginFrameSendRefusal -} from './plugin-frame-guest-send-budget' +} from './plugins/frames/plugin-frame-guest-send-budget' // Raw require keeps the sandboxed preload standalone in the CJS build. const electron: { diff --git a/src/preload/plugin-frame-guest-render-lane.test.ts b/src/preload/plugins/frames/plugin-frame-guest-render-lane.test.ts similarity index 100% rename from src/preload/plugin-frame-guest-render-lane.test.ts rename to src/preload/plugins/frames/plugin-frame-guest-render-lane.test.ts diff --git a/src/preload/plugin-frame-guest-send-budget.ts b/src/preload/plugins/frames/plugin-frame-guest-send-budget.ts similarity index 100% rename from src/preload/plugin-frame-guest-send-budget.ts rename to src/preload/plugins/frames/plugin-frame-guest-send-budget.ts diff --git a/src/preload/plugin-frame-guest-transport.ts b/src/preload/plugins/frames/plugin-frame-guest-transport.ts similarity index 100% rename from src/preload/plugin-frame-guest-transport.ts rename to src/preload/plugins/frames/plugin-frame-guest-transport.ts diff --git a/src/preload/plugin-frame-guest.test.ts b/src/preload/plugins/frames/plugin-frame-guest.test.ts similarity index 60% rename from src/preload/plugin-frame-guest.test.ts rename to src/preload/plugins/frames/plugin-frame-guest.test.ts index 545a4920794..eef66dc5d5a 100644 --- a/src/preload/plugin-frame-guest.test.ts +++ b/src/preload/plugins/frames/plugin-frame-guest.test.ts @@ -4,9 +4,8 @@ import { fileURLToPath } from 'node:url' import { runInNewContext } from 'node:vm' import { PLUGIN_FRAME_IPC_CHANNEL, - PLUGIN_FRAME_KEY_CHANNEL, PLUGIN_FRAME_TRANSPORT_GLOBAL -} from '../shared/plugins/frames/plugin-frame-guest' +} from '../../../shared/plugins/frames/plugin-frame-guest' import { createPluginFrameGestureTracker, createPluginFrameSendBudget, @@ -17,7 +16,7 @@ type Transport = { send: (message: unknown) => void; subscribe: (fn: (m: unknown type Listener = (event: { isTrusted: boolean } & Record) => void const preloadSource = buildSync({ - entryPoints: [fileURLToPath(new URL('./plugin-frame-guest.ts', import.meta.url))], + entryPoints: [fileURLToPath(new URL('../../plugin-frame-guest.ts', import.meta.url))], bundle: true, platform: 'node', format: 'cjs', @@ -73,65 +72,6 @@ function runPreload(isMainFrame: boolean, contentType = 'text/html') { } describe('plugin frame guest preload', () => { - it('hands the shell a deletable transport and stamps each send with a gesture serial', () => { - const { sendToHost, ipcListeners, pageWindow, input, transport } = runPreload(true) - expect( - Object.getOwnPropertyDescriptor(pageWindow, PLUGIN_FRAME_TRANSPORT_GLOBAL) - ).toMatchObject({ configurable: true, enumerable: false, writable: false }) - transport().send({ orca: 1, kind: 'evt', event: 'ready' }) - expect(sendToHost).toHaveBeenLastCalledWith( - PLUGIN_FRAME_IPC_CHANNEL, - { orca: 1, kind: 'evt', event: 'ready' }, - { gesture: 0 } - ) - // Untrusted (page-dispatched) input is not a gesture. - input('pointerdown', { isTrusted: false }) - transport().send({}) - expect(sendToHost).toHaveBeenLastCalledWith(PLUGIN_FRAME_IPC_CHANNEL, {}, { gesture: 0 }) - input('pointerdown', { isTrusted: true }) - transport().send({}) - expect(sendToHost).toHaveBeenLastCalledWith(PLUGIN_FRAME_IPC_CHANNEL, {}, { gesture: 1 }) - input('keydown', { isTrusted: true, key: 'a', code: 'KeyA' }) - transport().send({}) - expect(sendToHost).toHaveBeenLastCalledWith(PLUGIN_FRAME_IPC_CHANNEL, {}, { gesture: 2 }) - const first = vi.fn() - transport().subscribe(first) - transport().subscribe(vi.fn()) - expect(ipcListeners).toHaveLength(1) - ipcListeners[0]?.({}, { orca: 1, kind: 'res', id: 0 }) - expect(first).toHaveBeenCalledWith({ orca: 1, kind: 'res', id: 0 }) - }) - - it('reports trusted modifier chords on their own channel, never page-dispatched ones', () => { - const { sendToHost, input } = runPreload(true) - const chord = { key: 's', code: 'KeyS', metaKey: true, ctrlKey: false, altKey: false } - input('keydown', { isTrusted: false, ...chord, shiftKey: false }) - expect(sendToHost).not.toHaveBeenCalledWith(PLUGIN_FRAME_KEY_CHANNEL, expect.anything()) - input('keydown', { isTrusted: true, ...chord, shiftKey: false, repeat: false }) - expect(sendToHost).toHaveBeenCalledWith(PLUGIN_FRAME_KEY_CHANNEL, { ...chord, shiftKey: false }) - }) - - it('answers a refused request at once instead of leaving it pending', async () => { - const { sendToHost, transport } = runPreload(true) - const receive = vi.fn() - transport().subscribe(receive) - transport().send({ - orca: 1, - kind: 'req', - id: 7, - method: 'notifications.show', - params: { title: 'x'.repeat(200 * 1024) } - }) - await Promise.resolve() - expect(sendToHost).not.toHaveBeenCalled() - expect(receive).toHaveBeenCalledWith({ - orca: 1, - kind: 'res', - id: 7, - error: expect.objectContaining({ code: 'too_large', retryable: false }) - }) - }) - it('leaves subframes and non-HTML documents without a transport', () => { expect(PLUGIN_FRAME_TRANSPORT_GLOBAL in runPreload(false).pageWindow).toBe(false) expect(PLUGIN_FRAME_TRANSPORT_GLOBAL in runPreload(true, 'image/svg+xml').pageWindow).toBe( diff --git a/src/preload/renderer-restart-wiring.test.ts b/src/preload/renderer-restart-wiring.test.ts deleted file mode 100644 index 595ef92a1cf..00000000000 --- a/src/preload/renderer-restart-wiring.test.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { EventEmitter } from 'node:events' -import { ORCA_RENDERER_UNLOAD_PREVENTED_EVENT } from '../shared/renderer-shutdown-events' -import { - ORCA_APP_RESTART_ABORTED_EVENT, - ORCA_APP_RESTART_STARTED_EVENT, - ORCA_UPDATER_QUIT_AND_INSTALL_STARTED_EVENT -} from '../shared/updater-renderer-events' -import { - prepareAndInvokeAppRestart, - prepareAndInvokeUpdaterInstall, - registerRendererRestartIpcRelays -} from './renderer-restart-wiring' - -function restartIpc(eventTarget: EventTarget) { - const ipcRenderer = Object.assign(new EventEmitter(), { - invoke: vi.fn(async () => {}), - postMessage: vi.fn(), - send: vi.fn(), - sendSync: vi.fn(), - sendToHost: vi.fn() - }) - const relay = { handleStatus: vi.fn(), abort: vi.fn() } - registerRendererRestartIpcRelays(ipcRenderer, eventTarget, relay) - return { ipcRenderer, ...relay } -} - -describe('renderer restart wiring', () => { - it.each(['no-op', 'failure'] as const)( - 'keeps a committed restart prepared after a later %s', - async (outcome) => { - const eventTarget = new EventTarget() - const { ipcRenderer } = restartIpc(eventTarget) - const aborted = vi.fn() - const started = vi.fn() - const checkpoint = vi.fn(async () => {}) - eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted) - eventTarget.addEventListener(ORCA_APP_RESTART_STARTED_EVENT, started) - await prepareAndInvokeAppRestart( - eventTarget, - async () => { - ipcRenderer.emit('app:restart-committed') - return true - }, - checkpoint, - Boolean - ) - const subsequent = prepareAndInvokeAppRestart( - eventTarget, - async () => { - if (outcome === 'failure') { - throw new Error('already finalized') - } - return false - }, - checkpoint, - Boolean - ) - await (outcome === 'failure' - ? expect(subsequent).rejects.toThrow('already finalized') - : expect(subsequent).resolves.toBe(false)) - expect(checkpoint).toHaveBeenCalledOnce() - expect(started).toHaveBeenCalledOnce() - expect(aborted).not.toHaveBeenCalled() - } - ) - - it('refuses overlapping preparation without abandoning the accepted restart', async () => { - const eventTarget = new EventTarget() - const aborted = vi.fn() - eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted) - const checkpoint = Promise.withResolvers() - const invoke = vi.fn(async () => true) - const first = prepareAndInvokeAppRestart(eventTarget, invoke, () => checkpoint.promise) - const refused = vi.fn(async () => false) - await expect( - prepareAndInvokeAppRestart(eventTarget, refused, async () => {}, Boolean) - ).rejects.toThrow('already in progress') - expect(refused).not.toHaveBeenCalled() - expect(aborted).not.toHaveBeenCalled() - checkpoint.resolve() - await expect(first).resolves.toBe(true) - expect(invoke).toHaveBeenCalledOnce() - }) - - it('retains late commitment across an unrelated unload veto', async () => { - const eventTarget = new EventTarget() - const abandoned = vi.fn() - eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, abandoned) - eventTarget.addEventListener(ORCA_RENDERER_UNLOAD_PREVENTED_EVENT, abandoned) - const { ipcRenderer } = restartIpc(eventTarget) - const checkpoint = vi.fn(async () => {}) - await prepareAndInvokeAppRestart(eventTarget, async () => true, checkpoint, Boolean) - ipcRenderer.emit('app:restart-committed') - await prepareAndInvokeAppRestart(eventTarget, async () => false, checkpoint, Boolean) - expect(checkpoint).toHaveBeenCalledOnce() - ipcRenderer.emit('window:unload-prevented') - await prepareAndInvokeAppRestart(eventTarget, async () => true, checkpoint, Boolean) - expect(checkpoint).toHaveBeenCalledOnce() - expect(abandoned).not.toHaveBeenCalled() - }) - - it('releases preparation ownership and its listener after checkpoint failure', async () => { - const eventTarget = new EventTarget() - const add = vi.spyOn(eventTarget, 'addEventListener') - const remove = vi.spyOn(eventTarget, 'removeEventListener') - await expect( - prepareAndInvokeAppRestart( - eventTarget, - async () => {}, - async () => { - throw new Error('checkpoint failed') - } - ) - ).rejects.toThrow('checkpoint failed') - await prepareAndInvokeAppRestart( - eventTarget, - async () => {}, - async () => {} - ) - expect(add.mock.calls).toHaveLength(2) - expect(remove.mock.calls).toEqual(add.mock.calls) - }) - - it('marks preparation before invoking main and aborts on IPC failure', async () => { - const eventTarget = new EventTarget() - const calls: string[] = [] - eventTarget.addEventListener(ORCA_UPDATER_QUIT_AND_INSTALL_STARTED_EVENT, () => { - calls.push('prepared') - }) - const relay = { - markPrepared: () => calls.push('marked'), - abort: () => calls.push('aborted') - } - const invoke = vi.fn(async () => { - calls.push('invoked') - throw new Error('IPC failed') - }) - - await expect( - prepareAndInvokeUpdaterInstall(eventTarget, relay, invoke, async () => { - calls.push('checkpoint-flushed') - }) - ).rejects.toThrow('IPC failed') - - expect(calls).toEqual(['prepared', 'checkpoint-flushed', 'marked', 'invoked', 'aborted']) - }) - - it('never installs the update when the shutdown checkpoint fails to persist', async () => { - const eventTarget = new EventTarget() - const invoke = vi.fn(() => Promise.resolve()) - const relay = { markPrepared: vi.fn(), abort: vi.fn() } - - await expect( - prepareAndInvokeUpdaterInstall(eventTarget, relay, invoke, () => - Promise.reject(new Error('Failed to persist renderer state before unload.')) - ) - ).rejects.toThrow('Failed to persist renderer state before unload.') - - expect(invoke).not.toHaveBeenCalled() - expect(relay.markPrepared).not.toHaveBeenCalled() - }) -}) diff --git a/src/preload/browser-client-page-renderer-requests.test.ts b/src/preload/renderer/browser-pages/browser-client-page-renderer-requests.test.ts similarity index 81% rename from src/preload/browser-client-page-renderer-requests.test.ts rename to src/preload/renderer/browser-pages/browser-client-page-renderer-requests.test.ts index 6baaf0215ba..5f0f88322b2 100644 --- a/src/preload/browser-client-page-renderer-requests.test.ts +++ b/src/preload/renderer/browser-pages/browser-client-page-renderer-requests.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { BrowserClientPageRendererReply, BrowserClientPageRendererRequest -} from '../shared/browser/client-hosting/browser-client-page-renderer-protocol' +} from '../../../shared/browser/client-hosting/browser-client-page-renderer-protocol' import { createBrowserClientPageRendererRequests } from './browser-client-page-renderer-requests' type Listener = (event: unknown, request: unknown) => void @@ -230,51 +230,4 @@ describe('browser client page renderer preload requests', () => { expect(callback).toHaveBeenCalledTimes(2) expect(ipc.sent).toHaveLength(1) }) - - it.each(['dispose', 'unsubscribe', 'replace', 'timeout'] as const)( - 'does not start already-settled callbacks after %s', - async (action) => { - vi.useFakeTimers() - const ipc = new FakeIpc() - const requests = createBrowserClientPageRendererRequests({ - ipc, - isTopFrame: () => true, - timeoutMs: 50 - }) - const callback = vi.fn(() => ({ type: 'mounted' as const, webContentsId: 91 })) - const unsubscribe = requests.subscribe(callback) - for (let index = 0; index < 64; index += 1) { - ipc.emit(request(`request-${index}`)) - } - let errorCode = 'browser_client_page_renderer_preload_disposed' - if (action === 'dispose') { - requests.dispose() - } else if (action === 'unsubscribe') { - unsubscribe() - errorCode = 'browser_client_page_renderer_subscriber_unavailable' - } else if (action === 'replace') { - requests.subscribe(() => ({ type: 'mounted', webContentsId: 92 })) - errorCode = 'browser_client_page_renderer_subscriber_replaced' - } else { - vi.advanceTimersByTime(50) - errorCode = 'browser_client_page_renderer_subscriber_timeout' - } - try { - await flush() - expect(ipc.sent.map(({ reply }) => reply)).toEqual( - Array.from({ length: 64 }, (_, index) => ({ - type: 'failed', - errorCode, - requestId: `request-${index}`, - page: PAGE, - operation: 'mountPage' - })) - ) - expect(vi.getTimerCount()).toBe(0) - expect(callback).not.toHaveBeenCalled() - } finally { - requests.dispose() - } - } - ) }) diff --git a/src/preload/browser-client-page-renderer-requests.ts b/src/preload/renderer/browser-pages/browser-client-page-renderer-requests.ts similarity index 99% rename from src/preload/browser-client-page-renderer-requests.ts rename to src/preload/renderer/browser-pages/browser-client-page-renderer-requests.ts index 46aec46359e..d52ef50759e 100644 --- a/src/preload/browser-client-page-renderer-requests.ts +++ b/src/preload/renderer/browser-pages/browser-client-page-renderer-requests.ts @@ -6,7 +6,7 @@ import { BrowserClientPageRendererRequest, type BrowserClientPageRendererOutcome as RendererOutcome, type BrowserClientPageRendererRequest as RendererRequest -} from '../shared/browser/client-hosting/browser-client-page-renderer-protocol' +} from '../../../shared/browser/client-hosting/browser-client-page-renderer-protocol' const DEFAULT_MAX_PENDING = 512 const DEFAULT_TIMEOUT_MS = 10_000 diff --git a/src/preload/browser-find-subscriptions.test.ts b/src/preload/renderer/browser-pages/browser-find-subscriptions.test.ts similarity index 70% rename from src/preload/browser-find-subscriptions.test.ts rename to src/preload/renderer/browser-pages/browser-find-subscriptions.test.ts index c25b00baa1d..f85bfb4835b 100644 --- a/src/preload/browser-find-subscriptions.test.ts +++ b/src/preload/renderer/browser-pages/browser-find-subscriptions.test.ts @@ -77,34 +77,4 @@ describe('browser Find subscriptions', () => { expect(callback).not.toHaveBeenCalled() }) - - it('drops empty ownership entries when subscribers clean up', () => { - const subscriptions = createBrowserFindSubscriptions() - const callback = vi.fn() - const unsubscribe = subscriptions.subscribe(FIRST_SOURCE, callback) - expect(subscriptions.subscribedPageCount()).toBe(1) - - unsubscribe() - - subscriptions.dispatch(FIRST_SOURCE) - subscriptions.dispatch({ browserPageId: FIRST_SOURCE.browserPageId }) - expect(callback).not.toHaveBeenCalled() - expect(subscriptions.subscribedPageCount()).toBe(0) - }) - - it('keeps the other workspaces on a page when one of them unsubscribes', () => { - const subscriptions = createBrowserFindSubscriptions() - const firstCallback = vi.fn() - const samePageCallback = vi.fn() - const unsubscribe = subscriptions.subscribe(FIRST_SOURCE, firstCallback) - subscriptions.subscribe(SAME_PAGE_SOURCE, samePageCallback) - - unsubscribe() - subscriptions.dispatch(SAME_PAGE_SOURCE) - subscriptions.dispatch({ browserPageId: FIRST_SOURCE.browserPageId }) - - expect(firstCallback).not.toHaveBeenCalled() - expect(samePageCallback).toHaveBeenCalledTimes(2) - expect(subscriptions.subscribedPageCount()).toBe(1) - }) }) diff --git a/src/preload/browser-find-subscriptions.ts b/src/preload/renderer/browser-pages/browser-find-subscriptions.ts similarity index 94% rename from src/preload/browser-find-subscriptions.ts rename to src/preload/renderer/browser-pages/browser-find-subscriptions.ts index 8bd9e2a76d0..5e4928acd08 100644 --- a/src/preload/browser-find-subscriptions.ts +++ b/src/preload/renderer/browser-pages/browser-find-subscriptions.ts @@ -1,17 +1,15 @@ -import { asBrowserFindTarget, type BrowserFindSource } from '../shared/browser-find-source' +import { asBrowserFindTarget, type BrowserFindSource } from '../../../shared/browser-find-source' type BrowserFindCallback = () => void export function createBrowserFindSubscriptions(): { dispatch: (target: unknown) => void subscribe: (source: BrowserFindSource, callback: BrowserFindCallback) => () => void - subscribedPageCount: () => number } { // Page-only targets must reach every workspace holding that page. const callbacksByPage = new Map>>() return { - subscribedPageCount: () => callbacksByPage.size, dispatch: (target) => { const findTarget = asBrowserFindTarget(target) if (!findTarget) { diff --git a/src/preload/renderer-heap-statistics-reader.test.ts b/src/preload/renderer/diagnostics/renderer-heap-statistics-reader.test.ts similarity index 100% rename from src/preload/renderer-heap-statistics-reader.test.ts rename to src/preload/renderer/diagnostics/renderer-heap-statistics-reader.test.ts diff --git a/src/preload/renderer-heap-statistics-reader.ts b/src/preload/renderer/diagnostics/renderer-heap-statistics-reader.ts similarity index 91% rename from src/preload/renderer-heap-statistics-reader.ts rename to src/preload/renderer/diagnostics/renderer-heap-statistics-reader.ts index aa578e8ff46..9126e041574 100644 --- a/src/preload/renderer-heap-statistics-reader.ts +++ b/src/preload/renderer/diagnostics/renderer-heap-statistics-reader.ts @@ -1,4 +1,4 @@ -import type { RendererHeapStatistics } from '../shared/renderer-heap-statistics' +import type { RendererHeapStatistics } from '../../../shared/renderer-heap-statistics' type HeapStatisticsSource = Pick diff --git a/src/preload/renderer-process-memory-reader.test.ts b/src/preload/renderer/diagnostics/renderer-process-memory-reader.test.ts similarity index 100% rename from src/preload/renderer-process-memory-reader.test.ts rename to src/preload/renderer/diagnostics/renderer-process-memory-reader.test.ts diff --git a/src/preload/renderer-process-memory-reader.ts b/src/preload/renderer/diagnostics/renderer-process-memory-reader.ts similarity index 89% rename from src/preload/renderer-process-memory-reader.ts rename to src/preload/renderer/diagnostics/renderer-process-memory-reader.ts index 2e501b3e740..01dbb1e2414 100644 --- a/src/preload/renderer-process-memory-reader.ts +++ b/src/preload/renderer/diagnostics/renderer-process-memory-reader.ts @@ -1,4 +1,4 @@ -import type { RendererProcessMemory } from '../shared/renderer-process-memory' +import type { RendererProcessMemory } from '../../../shared/renderer-process-memory' type ProcessMemorySource = Pick diff --git a/src/preload/e2e-config.ts b/src/preload/renderer/e2e-config.ts similarity index 93% rename from src/preload/e2e-config.ts rename to src/preload/renderer/e2e-config.ts index c62c844a7c8..d524eb2c5da 100644 --- a/src/preload/e2e-config.ts +++ b/src/preload/renderer/e2e-config.ts @@ -1,4 +1,4 @@ -import { createE2EConfig } from '../shared/e2e-config' +import { createE2EConfig } from '../../shared/e2e-config' const preloadEnv = ( import.meta as ImportMeta & { diff --git a/src/preload/hidden-window-frame-pump.ts b/src/preload/renderer/hidden-window-frame-pump.ts similarity index 97% rename from src/preload/hidden-window-frame-pump.ts rename to src/preload/renderer/hidden-window-frame-pump.ts index 94e415f8bbe..015ae7ff6b2 100644 --- a/src/preload/hidden-window-frame-pump.ts +++ b/src/preload/renderer/hidden-window-frame-pump.ts @@ -1,7 +1,7 @@ import { HIDDEN_WINDOW_FRAME_PUMP_INTERVAL_MS, hasHiddenWindowFramePumpArgument -} from '../shared/hidden-window-frame-pump' +} from '../../shared/hidden-window-frame-pump' // Near-black so the single damaged frame is indistinguishable even if the window were visible. const FLIP_COLOR = 'rgb(1, 1, 1)' diff --git a/src/preload/preload-runtime-support.ts b/src/preload/renderer/renderer-runtime.ts similarity index 82% rename from src/preload/preload-runtime-support.ts rename to src/preload/renderer/renderer-runtime.ts index f8753d7794e..d3f4e6d89fc 100644 --- a/src/preload/preload-runtime-support.ts +++ b/src/preload/renderer/renderer-runtime.ts @@ -1,9 +1,9 @@ import { ipcRenderer } from 'electron' -import { createBrowserClientPageRendererRequests } from './browser-client-page-renderer-requests' -import { createBrowserFindSubscriptions } from './browser-find-subscriptions' -import { registerRendererRestartIpcRelays } from './renderer-restart-wiring' -import { createUpdaterQuitAbortRelay } from '../shared/renderer-restart-preparation' -import { ORCA_UPDATER_QUIT_AND_INSTALL_ABORTED_EVENT } from '../shared/updater-renderer-events' +import { createBrowserClientPageRendererRequests } from './browser-pages/browser-client-page-renderer-requests' +import { createBrowserFindSubscriptions } from './browser-pages/browser-find-subscriptions' +import { registerRendererRestartIpcRelays } from './restart/renderer-restart-wiring' +import { createUpdaterQuitAbortRelay } from '../../shared/renderer-restart-preparation' +import { ORCA_UPDATER_QUIT_AND_INSTALL_ABORTED_EVENT } from '../../shared/updater-renderer-events' export async function awaitBeforeUnloadCheckpoint(): Promise { const result = (await ipcRenderer.invoke('app:await-before-unload-checkpoint')) as { ok?: unknown diff --git a/src/preload/renderer/restart/app-restart-checkpoint-routing.test.ts b/src/preload/renderer/restart/app-restart-checkpoint-routing.test.ts new file mode 100644 index 00000000000..94000e9bbff --- /dev/null +++ b/src/preload/renderer/restart/app-restart-checkpoint-routing.test.ts @@ -0,0 +1,96 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { PreloadApi } from '../../api-types' +import { ORCA_APP_RESTART_STARTED_EVENT } from '../../../shared/updater-renderer-events' + +const { exposeInMainWorld, invoke, on, removeListener, send, sendSync, getPathForFile } = + vi.hoisted(() => ({ + exposeInMainWorld: vi.fn(), + invoke: vi.fn(), + on: vi.fn(), + removeListener: vi.fn(), + send: vi.fn(), + sendSync: vi.fn(), + getPathForFile: vi.fn(() => '/files/notes.txt') + })) + +vi.mock('electron', () => ({ + contextBridge: { exposeInMainWorld }, + ipcRenderer: { invoke, on, removeListener, send, sendSync }, + webFrame: { + getZoomFactor: vi.fn(() => 1), + setZoomFactor: vi.fn(), + setVisualZoomLevelLimits: vi.fn() + }, + webUtils: { getPathForFile } +})) + +describe('native preload destructive app actions', () => { + const originalContextIsolated = Object.getOwnPropertyDescriptor(process, 'contextIsolated') + let eventTarget: EventTarget + + beforeEach(() => { + vi.resetModules() + exposeInMainWorld.mockReset() + invoke.mockReset() + on.mockReset() + removeListener.mockReset() + send.mockReset() + sendSync.mockReset() + Object.defineProperty(process, 'contextIsolated', { configurable: true, value: true }) + eventTarget = new EventTarget() + vi.stubGlobal('window', eventTarget) + vi.stubGlobal('document', { addEventListener: vi.fn() }) + }) + + afterEach(() => { + vi.unstubAllGlobals() + if (originalContextIsolated) { + Object.defineProperty(process, 'contextIsolated', originalContextIsolated) + } else { + Reflect.deleteProperty(process, 'contextIsolated') + } + }) + + const loadApi = async (): Promise => { + await import('../../index') + return exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi + } + + it('exposes the durable checkpoint join the lazy-chunk recovery reload depends on', async () => { + const api = await loadApi() + invoke.mockResolvedValue({ ok: true }) + + await expect(api.app.awaitBeforeUnloadCheckpoint()).resolves.toBeUndefined() + expect(invoke).toHaveBeenCalledWith('app:await-before-unload-checkpoint') + + invoke.mockResolvedValue({ ok: false }) + + await expect(api.app.awaitBeforeUnloadCheckpoint()).rejects.toThrow( + 'Failed to persist renderer state before unload.' + ) + }) + + it('awaits renderer durability before profile maintenance and preserves its result', async () => { + const api = await loadApi() + const started = vi.fn() + eventTarget.addEventListener(ORCA_APP_RESTART_STARTED_EVENT, started) + let finishCheckpoint = (_result: { ok: boolean }): void => {} + const checkpoint = new Promise((resolve) => { + finishCheckpoint = resolve + }) + const result = { status: 'relaunching' } + invoke.mockImplementation((channel: string) => + channel === 'app:await-before-unload-checkpoint' ? checkpoint : Promise.resolve(result) + ) + + const switching = api.orcaProfiles.switchProfile({ profileId: 'target' }) + await vi.waitFor(() => + expect(invoke).toHaveBeenCalledWith('app:await-before-unload-checkpoint') + ) + expect(started).toHaveBeenCalledOnce() + expect(invoke).not.toHaveBeenCalledWith('orcaProfiles:switch', expect.anything()) + finishCheckpoint({ ok: true }) + await expect(switching).resolves.toBe(result) + expect(invoke).toHaveBeenLastCalledWith('orcaProfiles:switch', { profileId: 'target' }) + }) +}) diff --git a/src/preload/renderer/restart/renderer-restart-wiring.test.ts b/src/preload/renderer/restart/renderer-restart-wiring.test.ts new file mode 100644 index 00000000000..dd382790100 --- /dev/null +++ b/src/preload/renderer/restart/renderer-restart-wiring.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it, vi } from 'vitest' + +import { + ORCA_APP_RESTART_ABORTED_EVENT, + ORCA_UPDATER_QUIT_AND_INSTALL_STARTED_EVENT +} from '../../../shared/updater-renderer-events' +import { + prepareAndInvokeAppRestart, + prepareAndInvokeUpdaterInstall +} from './renderer-restart-wiring' + +describe('renderer restart wiring', () => { + it('refuses overlapping preparation without abandoning the accepted restart', async () => { + const eventTarget = new EventTarget() + const aborted = vi.fn() + eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted) + const checkpoint = Promise.withResolvers() + const invoke = vi.fn(async () => true) + const first = prepareAndInvokeAppRestart(eventTarget, invoke, () => checkpoint.promise) + const refused = vi.fn(async () => false) + await expect( + prepareAndInvokeAppRestart(eventTarget, refused, async () => {}, Boolean) + ).rejects.toThrow('already in progress') + expect(refused).not.toHaveBeenCalled() + expect(aborted).not.toHaveBeenCalled() + checkpoint.resolve() + await expect(first).resolves.toBe(true) + expect(invoke).toHaveBeenCalledOnce() + }) + + it('marks preparation before invoking main and aborts on IPC failure', async () => { + const eventTarget = new EventTarget() + const calls: string[] = [] + eventTarget.addEventListener(ORCA_UPDATER_QUIT_AND_INSTALL_STARTED_EVENT, () => { + calls.push('prepared') + }) + const relay = { + markPrepared: () => calls.push('marked'), + abort: () => calls.push('aborted') + } + const invoke = vi.fn(async () => { + calls.push('invoked') + throw new Error('IPC failed') + }) + + await expect( + prepareAndInvokeUpdaterInstall(eventTarget, relay, invoke, async () => { + calls.push('checkpoint-flushed') + }) + ).rejects.toThrow('IPC failed') + + expect(calls).toEqual(['prepared', 'checkpoint-flushed', 'marked', 'invoked', 'aborted']) + }) + + it('never installs the update when the shutdown checkpoint fails to persist', async () => { + const eventTarget = new EventTarget() + const invoke = vi.fn(() => Promise.resolve()) + const relay = { markPrepared: vi.fn(), abort: vi.fn() } + + await expect( + prepareAndInvokeUpdaterInstall(eventTarget, relay, invoke, () => + Promise.reject(new Error('Failed to persist renderer state before unload.')) + ) + ).rejects.toThrow('Failed to persist renderer state before unload.') + + expect(invoke).not.toHaveBeenCalled() + expect(relay.markPrepared).not.toHaveBeenCalled() + }) +}) diff --git a/src/preload/renderer-restart-wiring.ts b/src/preload/renderer/restart/renderer-restart-wiring.ts similarity index 92% rename from src/preload/renderer-restart-wiring.ts rename to src/preload/renderer/restart/renderer-restart-wiring.ts index 67b14d33c71..eeed8069f01 100644 --- a/src/preload/renderer-restart-wiring.ts +++ b/src/preload/renderer/restart/renderer-restart-wiring.ts @@ -1,16 +1,16 @@ import type { IpcRenderer } from 'electron' -import { ORCA_RENDERER_UNLOAD_PREVENTED_EVENT } from '../shared/renderer-shutdown-events' +import { ORCA_RENDERER_UNLOAD_PREVENTED_EVENT } from '../../../shared/renderer-shutdown-events' import { prepareRendererForAppRestart, type UpdaterQuitAbortRelay -} from '../shared/renderer-restart-preparation' -import type { UpdateStatus } from '../shared/update-status-types' +} from '../../../shared/renderer-restart-preparation' +import type { UpdateStatus } from '../../../shared/update-status-types' import { ORCA_APP_RESTART_ABORTED_EVENT, ORCA_APP_RESTART_STARTED_EVENT, ORCA_UPDATER_QUIT_AND_INSTALL_ABORTED_EVENT, ORCA_UPDATER_QUIT_AND_INSTALL_STARTED_EVENT -} from '../shared/updater-renderer-events' +} from '../../../shared/updater-renderer-events' type AppRestartState = { committed: boolean; pending: boolean } const appRestartStates = new WeakMap() diff --git a/src/preload/close-active-tab-payload-admission.test.ts b/src/preload/renderer/window-commands/close-active-tab-payload-admission.test.ts similarity index 100% rename from src/preload/close-active-tab-payload-admission.test.ts rename to src/preload/renderer/window-commands/close-active-tab-payload-admission.test.ts diff --git a/src/preload/close-active-tab-payload-admission.ts b/src/preload/renderer/window-commands/close-active-tab-payload-admission.ts similarity index 90% rename from src/preload/close-active-tab-payload-admission.ts rename to src/preload/renderer/window-commands/close-active-tab-payload-admission.ts index 17428cb6a7a..c407c94376e 100644 --- a/src/preload/close-active-tab-payload-admission.ts +++ b/src/preload/renderer/window-commands/close-active-tab-payload-admission.ts @@ -1,4 +1,4 @@ -import type { CloseActiveTabPayload } from './api/ui-command-event-api' +import type { CloseActiveTabPayload } from '../../api/ui-command-event-api' export type AdmittedCloseActiveTabPayload = | { kind: 'legacy' } diff --git a/src/preload/runtime-environment-subscriptions.ts b/src/preload/runtime/runtime-environment-subscriptions.ts similarity index 98% rename from src/preload/runtime-environment-subscriptions.ts rename to src/preload/runtime/runtime-environment-subscriptions.ts index 38baf347fd8..0629a2ca6e5 100644 --- a/src/preload/runtime-environment-subscriptions.ts +++ b/src/preload/runtime/runtime-environment-subscriptions.ts @@ -3,9 +3,9 @@ import { type CrewSubscriptionAttemptArgs, type CrewSubscriptionAttemptCallbacks, type CrewSubscriptionSetupResult -} from '../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' +} from '../../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' -import type { RuntimeRpcResponse } from '../shared/runtime-rpc-envelope' +import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' type RuntimeEnvironmentSubscribeArgs = { subscriptionId?: string diff --git a/src/preload/updater-package-recovery.test.ts b/src/preload/updater-package-recovery.test.ts deleted file mode 100644 index fb58791e9cc..00000000000 --- a/src/preload/updater-package-recovery.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PreloadApi } from './api-types' - -const { exposeInMainWorld, invoke, on, removeListener, send, sendSync } = vi.hoisted(() => ({ - exposeInMainWorld: vi.fn(), - invoke: vi.fn(), - on: vi.fn(), - removeListener: vi.fn(), - send: vi.fn(), - sendSync: vi.fn() -})) - -vi.mock('electron', () => ({ - contextBridge: { exposeInMainWorld }, - ipcRenderer: { invoke, on, removeListener, send, sendSync }, - webFrame: { - getZoomFactor: vi.fn(() => 1), - setZoomFactor: vi.fn(), - setVisualZoomLevelLimits: vi.fn() - }, - webUtils: { getPathForFile: vi.fn(() => '') } -})) - -describe('native preload linux package recovery methods', () => { - const originalContextIsolated = Object.getOwnPropertyDescriptor(process, 'contextIsolated') - - beforeEach(() => { - vi.resetModules() - exposeInMainWorld.mockReset() - invoke.mockReset() - on.mockReset() - removeListener.mockReset() - send.mockReset() - sendSync.mockReset() - Object.defineProperty(process, 'contextIsolated', { configurable: true, value: true }) - vi.stubGlobal('window', { - addEventListener: vi.fn(), - dispatchEvent: vi.fn(), - removeEventListener: vi.fn() - }) - vi.stubGlobal('document', { addEventListener: vi.fn() }) - }) - - afterEach(() => { - vi.unstubAllGlobals() - if (originalContextIsolated) { - Object.defineProperty(process, 'contextIsolated', originalContextIsolated) - } else { - Reflect.deleteProperty(process, 'contextIsolated') - } - }) - - const loadApi = async (): Promise => { - await import('./index') - return exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi - } - - it('invokes only the instructions channel and returns the main-built command', async () => { - const api = await loadApi() - invoke.mockResolvedValueOnce({ - command: "sudo apt install -- '/cache/orca.deb'", - packageFileName: 'orca.deb' - }) - invoke.mockClear() - - await expect(api.updater.getLinuxPackageInstallInstructions()).resolves.toEqual({ - command: "sudo apt install -- '/cache/orca.deb'", - packageFileName: 'orca.deb' - }) - - expect(invoke.mock.calls).toEqual([['updater:getLinuxPackageInstallInstructions']]) - }) - - it('invokes only the show-package channel', async () => { - const api = await loadApi() - invoke.mockResolvedValueOnce(undefined) - invoke.mockClear() - - await expect(api.updater.showLinuxPackage()).resolves.toBeUndefined() - - expect(invoke.mock.calls).toEqual([['updater:showLinuxPackage']]) - }) -}) diff --git a/src/preload/usage-provider-api.test.ts b/src/preload/usage-provider-api.test.ts deleted file mode 100644 index 2faae9158e1..00000000000 --- a/src/preload/usage-provider-api.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { createUsageProviderApi } from './usage-provider-api' - -describe('usage provider preload API', () => { - it('keeps every provider on its existing IPC channels', async () => { - const invoke = vi.fn().mockResolvedValue(undefined) - const query = { scope: 'orca' as const, range: '30d' as const } - - for (const prefix of ['claudeUsage', 'codexUsage', 'openCodeUsage', 'museUsage'] as const) { - const api = createUsageProviderApi({ invoke } as never, prefix) - await api.getScanState() - await api.setEnabled({ enabled: true }) - await api.refresh() - await api.getSnapshot({ ...query, limit: 7 }) - await api.getSummary(query) - await api.getDaily(query) - await api.getBreakdown({ ...query, kind: 'project' }) - await api.getRecentSessions({ ...query, limit: 4 }) - - expect(invoke.mock.calls).toEqual([ - [`${prefix}:getScanState`], - [`${prefix}:setEnabled`, { enabled: true }], - [`${prefix}:refresh`, undefined], - [`${prefix}:getSnapshot`, { ...query, limit: 7 }], - [`${prefix}:getSummary`, query], - [`${prefix}:getDaily`, query], - [`${prefix}:getBreakdown`, { ...query, kind: 'project' }], - [`${prefix}:getRecentSessions`, { ...query, limit: 4 }] - ]) - invoke.mockClear() - } - }) -}) diff --git a/src/preload/backend-port-client.ts b/src/preload/usage/backend-port-client.ts similarity index 97% rename from src/preload/backend-port-client.ts rename to src/preload/usage/backend-port-client.ts index dae6df4e82b..13c3bec8d70 100644 --- a/src/preload/backend-port-client.ts +++ b/src/preload/usage/backend-port-client.ts @@ -1,5 +1,5 @@ import { ipcRenderer } from 'electron' -import { BackendPortRpc, type BackendPort } from '../shared/backend-port-rpc' +import { BackendPortRpc, type BackendPort } from '../../shared/backend-port-rpc' import { BACKEND_CONNECTION_CHANGED, BACKEND_PORT_DELIVERY, @@ -7,7 +7,7 @@ import { type BackendConnectionPurpose, type BackendConnectionStatus, type BackendConnectionListener -} from '../shared/backend-service-contract' +} from '../../shared/backend-service-contract' let connection: BackendPortRpc | undefined let connecting: Promise | undefined diff --git a/src/preload/usage-provider-api.ts b/src/preload/usage/usage-provider-api.ts similarity index 95% rename from src/preload/usage-provider-api.ts rename to src/preload/usage/usage-provider-api.ts index 3b9723a6aa0..ba73e86e1f9 100644 --- a/src/preload/usage-provider-api.ts +++ b/src/preload/usage/usage-provider-api.ts @@ -1,8 +1,8 @@ import type { BackendConnectionListener, BackendConnectionPurpose -} from '../shared/backend-service-contract' -import type { PreloadApi } from './api-types' +} from '../../shared/backend-service-contract' +import type { PreloadApi } from '../api-types' type UsageProviderApiKey = 'claudeUsage' | 'codexUsage' | 'openCodeUsage' | 'museUsage' type UsageProviderApi = PreloadApi[UsageProviderApiKey] diff --git a/src/renderer/src/components/plugins/catalog/PluginCatalogGroups.tsx b/src/renderer/src/components/plugins/catalog/PluginCatalogGroups.tsx index 05860ee7947..11e7d89a4a4 100644 --- a/src/renderer/src/components/plugins/catalog/PluginCatalogGroups.tsx +++ b/src/renderer/src/components/plugins/catalog/PluginCatalogGroups.tsx @@ -1,5 +1,5 @@ import { AlertTriangle, CircleAlert } from 'lucide-react' -import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api/plugin-host-api' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { formatShortTimeAgo } from '@/lib/time-format/short-time-ago' diff --git a/src/renderer/src/components/plugins/catalog/PluginCatalogHighlights.fixture.tsx b/src/renderer/src/components/plugins/catalog/PluginCatalogHighlights.fixture.tsx index 80f9bca736d..e63598b1df8 100644 --- a/src/renderer/src/components/plugins/catalog/PluginCatalogHighlights.fixture.tsx +++ b/src/renderer/src/components/plugins/catalog/PluginCatalogHighlights.fixture.tsx @@ -1,4 +1,4 @@ -import type { PluginMarketplaceHostListing } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostListing } from '../../../../../preload/api/plugin-host-api' import { defineFixture } from '../../../component-fixtures/component-fixture' import { usePluginInstallCountsStore } from '@/store/plugins/installation/plugin-install-counts' import { PluginListGroup } from '../list/PluginListGroup' diff --git a/src/renderer/src/components/plugins/catalog/plugin-catalog-highlights.test.ts b/src/renderer/src/components/plugins/catalog/plugin-catalog-highlights.test.ts index d76073fd690..afdf2bfdd33 100644 --- a/src/renderer/src/components/plugins/catalog/plugin-catalog-highlights.test.ts +++ b/src/renderer/src/components/plugins/catalog/plugin-catalog-highlights.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import type { PluginMarketplaceHostListing } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostListing } from '../../../../../preload/api/plugin-host-api' import { pluginListEntryFromListing, type PluginListEntry } from '../list/plugin-list-entries' import { pickFeaturedPlugins, pickNewlyAddedPlugins } from './plugin-catalog-highlights' diff --git a/src/renderer/src/components/plugins/dialogs/PluginInstallDialog.tsx b/src/renderer/src/components/plugins/dialogs/PluginInstallDialog.tsx index a84095a4aad..5f1351a7df2 100644 --- a/src/renderer/src/components/plugins/dialogs/PluginInstallDialog.tsx +++ b/src/renderer/src/components/plugins/dialogs/PluginInstallDialog.tsx @@ -1,6 +1,6 @@ import { useRef, useState } from 'react' import { Loader2 } from 'lucide-react' -import type { PluginHostInstallSource } from '../../../../../preload/api-types' +import type { PluginHostInstallSource } from '../../../../../preload/api/plugin-host-api' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { Button } from '../../ui/button' diff --git a/src/renderer/src/components/plugins/dialogs/PluginMarketplaceSourceDialog.tsx b/src/renderer/src/components/plugins/dialogs/PluginMarketplaceSourceDialog.tsx index 663400c6923..8362ba2779d 100644 --- a/src/renderer/src/components/plugins/dialogs/PluginMarketplaceSourceDialog.tsx +++ b/src/renderer/src/components/plugins/dialogs/PluginMarketplaceSourceDialog.tsx @@ -1,6 +1,6 @@ import { useRef, useState } from 'react' import { Loader2, RefreshCw, Trash2 } from 'lucide-react' -import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api/plugin-host-api' import { useTranslate } from '@/i18n/use-translate' import { Button } from '../../ui/button' import { Badge } from '../../ui/badge' diff --git a/src/renderer/src/components/plugins/dialogs/PluginRemoveDialog.tsx b/src/renderer/src/components/plugins/dialogs/PluginRemoveDialog.tsx index ee788a3cddc..c3cc9e79488 100644 --- a/src/renderer/src/components/plugins/dialogs/PluginRemoveDialog.tsx +++ b/src/renderer/src/components/plugins/dialogs/PluginRemoveDialog.tsx @@ -1,6 +1,6 @@ import { useRef } from 'react' import { Loader2 } from 'lucide-react' -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import { useTranslate } from '@/i18n/use-translate' import { Button } from '../../ui/button' import { diff --git a/src/renderer/src/components/plugins/dialogs/PluginRollbackDialog.tsx b/src/renderer/src/components/plugins/dialogs/PluginRollbackDialog.tsx index 130c30ff908..89e4b6075c8 100644 --- a/src/renderer/src/components/plugins/dialogs/PluginRollbackDialog.tsx +++ b/src/renderer/src/components/plugins/dialogs/PluginRollbackDialog.tsx @@ -1,6 +1,6 @@ import { useRef } from 'react' import { Loader2 } from 'lucide-react' -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import { useTranslate } from '@/i18n/use-translate' import { Button } from '../../ui/button' import { usePluginRollbackVersion } from '../state/use-plugin-rollback-version' diff --git a/src/renderer/src/components/plugins/dialogs/PluginUpdateAllDialog.test.tsx b/src/renderer/src/components/plugins/dialogs/PluginUpdateAllDialog.test.tsx index b246ee93c30..70a637a0e83 100644 --- a/src/renderer/src/components/plugins/dialogs/PluginUpdateAllDialog.test.tsx +++ b/src/renderer/src/components/plugins/dialogs/PluginUpdateAllDialog.test.tsx @@ -3,10 +3,8 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { - PluginHostListEntry, - PluginMarketplaceHostInstallPreview -} from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' +import type { PluginMarketplaceHostInstallPreview } from '../../../../../preload/api/plugin-host-api' import { pluginManifestSchema } from '../../../../../shared/plugins/manifest/plugin-manifest' import type { PluginCapabilityKind } from '../../../../../shared/plugins/capabilities/plugin-capabilities' import type { PluginListEntry } from '../list/plugin-list-entries' @@ -152,12 +150,6 @@ async function renderDialog( return container } -function reviewButton(container: HTMLElement, pluginKey: string): HTMLButtonElement | undefined { - return Array.from( - container.querySelectorAll(`[data-plugin-update="${pluginKey}"] button`) - ).find((candidate) => candidate.textContent === 'Review') -} - function button(container: HTMLElement, text: string): HTMLButtonElement | undefined { return Array.from(container.querySelectorAll('button')).find( (candidate) => candidate.textContent === text @@ -165,188 +157,6 @@ function button(container: HTMLElement, text: string): HTMLButtonElement | undef } describe('PluginUpdateAllDialog', () => { - it('lists every update in one dialog and bulk-installs only those asking for nothing new', async () => { - const installMarketplacePlugin = vi.fn().mockResolvedValue({ ok: true, pluginKey: 'b' }) - Object.defineProperty(window, 'api', { - configurable: true, - value: { - plugins: { - previewMarketplaceUpdate: vi.fn(({ pluginKey }: { pluginKey: string }) => - Promise.resolve(preview(pluginKey, pluginKey === 'a' ? ['secrets:own'] : [])) - ), - installMarketplacePlugin, - getInstalledManifest: vi.fn().mockResolvedValue(null) - } - } - }) - const onUpdated = vi.fn().mockResolvedValue(undefined) - const container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - await act(async () => { - root?.render( - - ) - }) - expect(container.querySelector('h2')?.textContent).toBe('Update 2 plugins') - expect(container.textContent).toContain('New: Store its own encrypted secrets') - expect(container.querySelector('[data-plugin-update="b"]')?.textContent).toBe('b1.0.0 → 1.1.0') - - // Why no checkbox: an update that grows access is never part of the bulk Update. - expect(container.querySelector('#plugin-update-a')).toBeNull() - const confirm = Array.from(container.querySelectorAll('button')).find( - (button) => button.textContent === 'Update' - ) - await act(async () => confirm?.click()) - - expect(installMarketplacePlugin).toHaveBeenCalledTimes(1) - expect(installMarketplacePlugin).toHaveBeenCalledWith( - expect.objectContaining({ pluginKey: 'b' }) - ) - expect(onUpdated).toHaveBeenCalledWith(['b']) - }) - - it('names what failed, keeps what updated, and retries only the failures', async () => { - const installMarketplacePlugin = vi.fn(({ pluginKey }: { pluginKey: string }) => - Promise.resolve(pluginKey === 'a' ? { ok: false, error: 'boom' } : { ok: true, pluginKey }) - ) - installApi({ - previewMarketplaceUpdate: vi.fn(({ pluginKey }: { pluginKey: string }) => - Promise.resolve(preview(pluginKey, [])) - ), - installMarketplacePlugin - }) - const onUpdated = vi.fn().mockResolvedValue(undefined) - const container = await renderDialog([entry('a', []), entry('b', [])], { onUpdated }) - - await act(async () => button(container, 'Update')?.click()) - expect(container.textContent).toContain('Couldn’t update a. The others were updated.') - expect(onUpdated).toHaveBeenCalledWith(['b']) - expect(container.querySelector('[data-plugin-update="b"]')?.textContent).toContain('Updated') - - installMarketplacePlugin.mockClear() - await act(async () => button(container, 'Try again')?.click()) - expect(installMarketplacePlugin).toHaveBeenCalledTimes(1) - expect(installMarketplacePlugin).toHaveBeenCalledWith( - expect.objectContaining({ pluginKey: 'a' }) - ) - // Why: "b" updated on the first pass, so a second failure isn't "nothing was updated". - expect(container.textContent).toContain('Couldn’t update a. The others were updated.') - }) - - it('keeps the set it opened with while the list reloads mid-run', async () => { - const previewMarketplaceUpdate = vi.fn(({ pluginKey }: { pluginKey: string }) => - Promise.resolve(preview(pluginKey, [])) - ) - installApi({ - previewMarketplaceUpdate, - installMarketplacePlugin: vi.fn(({ pluginKey }: { pluginKey: string }) => - Promise.resolve(pluginKey === 'a' ? { ok: false, error: 'boom' } : { ok: true, pluginKey }) - ) - }) - const onUpdated = vi.fn().mockResolvedValue(undefined) - const container = await renderDialog([entry('a', []), entry('b', [])], { onUpdated }) - await act(async () => button(container, 'Update')?.click()) - // Why: after "b" updates, the reloaded list no longer has it among pending updates. - await act(async () => { - root?.render( - - ) - }) - expect(previewMarketplaceUpdate).toHaveBeenCalledTimes(2) - expect(container.querySelector('[data-plugin-update="b"]')?.textContent).toContain('Updated') - }) - - it('approves an update that grows access only from its own before/after review', async () => { - const installMarketplacePlugin = vi.fn(({ pluginKey }: { pluginKey: string }) => - Promise.resolve({ ok: true, pluginKey, consentFingerprint: 'f' }) - ) - const consent = vi.fn().mockResolvedValue([]) - installApi({ - previewMarketplaceUpdate: vi.fn(({ pluginKey }: { pluginKey: string }) => - Promise.resolve(pluginKey === 'a' ? workerUpdate('a', false) : preview(pluginKey, [])) - ), - installMarketplacePlugin, - consent - }) - const onUpdated = vi.fn().mockResolvedValue(undefined) - const container = await renderDialog([entry('a', ['storage:own']), entry('b', [])], { - onUpdated - }) - - await act(async () => reviewButton(container, 'a')?.click()) - expect(container.querySelector('h2')?.textContent).toBe('Review update to a') - const review = container.querySelector('[data-plugin-update-review="a"]') - expect(review?.textContent).toContain('BeforeContent onlyStore its own data') - expect(review?.textContent).toContain('New: Full access') - expect(review?.textContent).toContain('New: Store its own encrypted secrets') - expect(review?.textContent).toContain('Not an official plugin:') - expect(installMarketplacePlugin).not.toHaveBeenCalled() - - await act(async () => button(container, 'Approve & update')?.click()) - expect(installMarketplacePlugin).toHaveBeenCalledTimes(1) - expect(installMarketplacePlugin).toHaveBeenCalledWith( - expect.objectContaining({ pluginKey: 'a' }) - ) - expect(consent).toHaveBeenCalledWith({ - pluginKey: 'a', - reviewedFingerprint: 'f', - decision: 'approve' - }) - expect(onUpdated).toHaveBeenCalledWith(['a']) - // Why back to the list: "b" still waits for the bulk Update. - expect(container.querySelector('[data-plugin-update="a"]')?.textContent).toContain('Updated') - }) - - it('opens a lone content-only update from a moved repository to its own review', async () => { - const installMarketplacePlugin = vi.fn(({ pluginKey }: { pluginKey: string }) => - Promise.resolve({ ok: true, pluginKey, consentFingerprint: 'f', needsReview: true }) - ) - const consent = vi.fn().mockResolvedValue([]) - installApi({ - previewMarketplaceUpdate: vi.fn(() => - Promise.resolve({ - ...preview('a', []), - source: { kind: 'git', url: 'https://example.com/someone-else/theme.git', ref: 'main' }, - repositoryMoved: true as const - }) - ), - installMarketplacePlugin, - consent - }) - const theme = entry('a', []) - theme.installed!.source = { - kind: 'marketplace', - reference: 'https://example.com/acme/theme.git', - resolvedCommit: 'r0', - contentHash: 'h0' - } - const container = await renderDialog([theme]) - - // Same access, so only the source line explains why this one asks again. - expect(container.querySelector('h2')?.textContent).toBe('Review update to a') - expect(container.textContent).toContain( - 'New source: https://example.com/someone-else/theme.git (was https://example.com/acme/theme.git)' - ) - expect(installMarketplacePlugin).not.toHaveBeenCalled() - await act(async () => button(container, 'Approve & update')?.click()) - expect(consent).toHaveBeenCalledWith({ - pluginKey: 'a', - reviewedFingerprint: 'f', - decision: 'approve' - }) - }) - it('never approves bytes other than the ones it reviewed', async () => { const consent = vi.fn().mockResolvedValue([]) installApi({ diff --git a/src/renderer/src/components/plugins/dialogs/PluginUpdateAllDialog.tsx b/src/renderer/src/components/plugins/dialogs/PluginUpdateAllDialog.tsx index 67d734cdb92..699f1c7a3d9 100644 --- a/src/renderer/src/components/plugins/dialogs/PluginUpdateAllDialog.tsx +++ b/src/renderer/src/components/plugins/dialogs/PluginUpdateAllDialog.tsx @@ -1,6 +1,6 @@ import { useEffect, useLayoutEffect, useRef, useState } from 'react' import { Loader2 } from 'lucide-react' -import type { PluginMarketplaceHostInstallPreview } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostInstallPreview } from '../../../../../preload/api/plugin-host-api' import { satisfiesOrcaEngineRange } from '../../../../../shared/plugins/manifest/plugin-manifest' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/plugins/list/PluginFilterPopover.tsx b/src/renderer/src/components/plugins/list/PluginFilterPopover.tsx index 41348461f4a..81ace9ed222 100644 --- a/src/renderer/src/components/plugins/list/PluginFilterPopover.tsx +++ b/src/renderer/src/components/plugins/list/PluginFilterPopover.tsx @@ -1,5 +1,5 @@ import { ListFilter } from 'lucide-react' -import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api/plugin-host-api' import { useTranslate } from '@/i18n/use-translate' import { Button } from '../../ui/button' import { Checkbox } from '../../ui/checkbox' diff --git a/src/renderer/src/components/plugins/list/PluginListToolbar.tsx b/src/renderer/src/components/plugins/list/PluginListToolbar.tsx index 8ca9164ef4d..30e7b9ddda9 100644 --- a/src/renderer/src/components/plugins/list/PluginListToolbar.tsx +++ b/src/renderer/src/components/plugins/list/PluginListToolbar.tsx @@ -1,5 +1,5 @@ import { RefreshCw } from 'lucide-react' -import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api/plugin-host-api' import { useTranslate } from '@/i18n/use-translate' import { Button } from '../../ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '../../ui/tooltip' diff --git a/src/renderer/src/components/plugins/list/PluginManager.test.tsx b/src/renderer/src/components/plugins/list/PluginManager.test.tsx deleted file mode 100644 index 9074843f380..00000000000 --- a/src/renderer/src/components/plugins/list/PluginManager.test.tsx +++ /dev/null @@ -1,217 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - PluginHostListEntry, - PluginMarketplaceHostListing, - PluginMarketplaceHostSourceState -} from '../../../../../preload/api-types' -import { OFFICIAL_MARKETPLACE_GIT_SOURCE } from '../../../../../shared/plugins/catalog/plugin-marketplace' -import { PLUGIN_GROUP_ROW_CAP, PluginManager } from './PluginManager' -import { usePluginPageNavigation } from '../state/use-plugin-page-navigation' - -vi.mock('../../ui/tooltip', () => ({ - Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipContent: () => null -})) -vi.mock('../dialogs/PluginMarketplaceSourceDialog', () => ({ - PluginMarketplaceSourceDialog: () => null -})) - -const installedPlugin: PluginHostListEntry = { - pluginKey: 'stablyai.orca-nord-theme', - consentFingerprint: 'sha256-nord', - name: 'Orca Nord', - version: '1.0.0', - publisher: 'stablyai', - status: 'idle', - needsReconsent: false, - isDev: false, - official: true, - bundled: false, - capabilities: [], - panels: [], - commands: [], - hasWorker: false, - restarts: 0, - source: { - kind: 'marketplace', - reference: 'https://example.invalid/nord.git', - resolvedCommit: 'a'.repeat(40), - contentHash: 'b'.repeat(64) - } -} - -const source: PluginMarketplaceHostSourceState = { - id: 'official', - source: { kind: 'git', url: 'https://example.invalid/catalog.git', ref: 'main' }, - addedAt: 0, - marketplace: { - name: 'Orca Official Plugins', - owner: 'stablyai', - resolvedCommit: 'c', - fetchedAt: 0 - }, - stale: false, - official: true -} - -function listing(pluginKey: string, extra: Partial = {}) { - const value: PluginMarketplaceHostListing = { - marketplaceSourceId: 'official', - marketplaceName: 'Orca Official Plugins', - marketplaceOwner: 'stablyai', - marketplaceCommit: 'c', - pluginKey, - source: { kind: 'git', url: 'https://example.invalid/plugin.git', ref: 'main' }, - description: `Description of ${pluginKey}`, - categories: ['themes'], - official: true, - bundled: false, - ...extra - } - return value -} - -const catalogListings = [ - listing('stablyai.orca-nord-theme', { - release: { - version: '1.2.0', - commit: 'd'.repeat(40), - contentHash: 'e'.repeat(64), - execution: 'data', - minimumOrca: '1.4.0', - types: ['app-theme'], - name: 'Orca Nord' - }, - license: 'MIT', - changelog: 'Warmer comments.\nnot markup' - }), - ...Array.from({ length: PLUGIN_GROUP_ROW_CAP + 2 }, (_, index) => - listing(`stablyai.extra-${index}`) - ) -] - -let root: Root | null = null - -function installApi(overrides: Record = {}): void { - Object.defineProperty(window, 'api', { - configurable: true, - value: { - plugins: { - listMarketplaces: vi.fn().mockResolvedValue([source]), - listMarketplacePlugins: vi.fn().mockResolvedValue(catalogListings), - refreshMarketplaces: vi.fn().mockResolvedValue(undefined), - previewMarketplacePlugin: vi.fn().mockResolvedValue(null), - getRollbackVersion: vi.fn().mockResolvedValue('1.0.0-rc.1'), - getInstalledManifest: vi.fn().mockResolvedValue(null), - ...overrides - }, - updater: { getVersion: vi.fn().mockResolvedValue('1.4.214') }, - ui: { writeClipboardText: vi.fn() } - } - }) -} - -function Harness({ plugins }: { plugins: PluginHostListEntry[] }): React.JSX.Element { - const page = usePluginPageNavigation() - return ( - - ) -} - -async function render(plugins: PluginHostListEntry[] = [installedPlugin]): Promise { - const container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - await act(async () => { - root?.render() - }) - return container -} - -beforeEach(() => installApi()) - -afterEach(() => { - act(() => root?.unmount()) - root = null - document.body.innerHTML = '' -}) - -describe('PluginManager', () => { - it('keeps installed plugins when the catalog never loads', async () => { - installApi({ listMarketplaces: vi.fn().mockRejectedValue(new Error('offline')) }) - const container = await render() - expect(container.querySelector('[data-plugin-key="stablyai.orca-nord-theme"]')).not.toBeNull() - expect(container.textContent).toContain('Couldn’t load the plugin catalog.') - }) - - it('renders each plugin card once and no Featured row when nothing is newly added', async () => { - const popular = ['themes', 'editors', 'icons', 'panels'].map((category, index) => - listing(`stablyai.popular-${index}`, { categories: [category] }) - ) - installApi({ - // Why the real official URL: only Orca's public catalogs have install counts to feature. - listMarketplaces: vi - .fn() - .mockResolvedValue([{ ...source, source: OFFICIAL_MARKETPLACE_GIT_SOURCE }]), - listMarketplacePlugins: vi.fn().mockResolvedValue([...popular, ...catalogListings.slice(1)]), - getInstallCounts: vi - .fn() - .mockResolvedValue( - Object.fromEntries(popular.map((item, index) => [item.pluginKey, 1000 - index])) - ) - }) - const container = await render([]) - const keys = [...container.querySelectorAll('[data-plugin-key]')].map((card) => - card.getAttribute('data-plugin-key') - ) - - expect(keys).toContain('stablyai.popular-0') - expect(new Set(keys).size).toBe(keys.length) - expect(container.textContent).not.toContain('Featured') - }) - - it('shows release notes as text, license and the rollback version on the plugin page', async () => { - const container = await render() - await act(async () => - container - .querySelector( - '[data-plugin-key="stablyai.orca-nord-theme"] [data-plugin-row-name]' - ) - ?.click() - ) - expect(window.api.plugins.getRollbackVersion).toHaveBeenCalledWith({ - pluginKey: 'stablyai.orca-nord-theme' - }) - expect(container.textContent).toContain('What’s new') - expect(container.textContent).toContain('not markup') - expect(container.querySelector('b')).toBeNull() - expect(container.textContent).toContain('MIT') - expect(container.textContent).toContain('1.0.0-rc.1') - }) -}) diff --git a/src/renderer/src/components/plugins/list/PluginManager.tsx b/src/renderer/src/components/plugins/list/PluginManager.tsx index 4682667e00d..2c0a7106399 100644 --- a/src/renderer/src/components/plugins/list/PluginManager.tsx +++ b/src/renderer/src/components/plugins/list/PluginManager.tsx @@ -1,5 +1,5 @@ import { useCallback, useState } from 'react' -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { Button } from '../../ui/button' diff --git a/src/renderer/src/components/plugins/list/PluginManagerRows.tsx b/src/renderer/src/components/plugins/list/PluginManagerRows.tsx index a24562edc75..37a72874ef3 100644 --- a/src/renderer/src/components/plugins/list/PluginManagerRows.tsx +++ b/src/renderer/src/components/plugins/list/PluginManagerRows.tsx @@ -1,5 +1,5 @@ import { ArrowUpCircle, Copy, FileText, Hash, Loader2, RotateCcw, Trash2 } from 'lucide-react' -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { Button } from '../../ui/button' diff --git a/src/renderer/src/components/plugins/list/PluginSettingsOverview.tsx b/src/renderer/src/components/plugins/list/PluginSettingsOverview.tsx index ed39d102d8e..1f42f5db18d 100644 --- a/src/renderer/src/components/plugins/list/PluginSettingsOverview.tsx +++ b/src/renderer/src/components/plugins/list/PluginSettingsOverview.tsx @@ -1,4 +1,4 @@ -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import { PluginManager } from './PluginManager' import { PluginsOffState } from './PluginsOffState' import type { InstalledRowHandlers } from './PluginManagerRows' diff --git a/src/renderer/src/components/plugins/list/plugin-list-entries.test.ts b/src/renderer/src/components/plugins/list/plugin-list-entries.test.ts index dc1056f5844..ae129d7ac73 100644 --- a/src/renderer/src/components/plugins/list/plugin-list-entries.test.ts +++ b/src/renderer/src/components/plugins/list/plugin-list-entries.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from 'vitest' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import type { - PluginHostListEntry, PluginMarketplaceHostListing, PluginMarketplaceHostSourceState -} from '../../../../../preload/api-types' +} from '../../../../../preload/api/plugin-host-api' import { buildPluginListEntries } from './plugin-list-entries' function listing(pluginKey: string, extra: Partial = {}) { diff --git a/src/renderer/src/components/plugins/list/plugin-list-entries.ts b/src/renderer/src/components/plugins/list/plugin-list-entries.ts index 3cd87cf6fa0..355d7fdacb1 100644 --- a/src/renderer/src/components/plugins/list/plugin-list-entries.ts +++ b/src/renderer/src/components/plugins/list/plugin-list-entries.ts @@ -1,8 +1,8 @@ +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import type { - PluginHostListEntry, PluginMarketplaceHostListing, PluginMarketplaceHostSourceState -} from '../../../../../preload/api-types' +} from '../../../../../preload/api/plugin-host-api' import { satisfiesOrcaEngineRange } from '../../../../../shared/plugins/manifest/plugin-manifest' import { pluginCatalogReleaseTypes, diff --git a/src/renderer/src/components/plugins/list/plugin-public-catalog.ts b/src/renderer/src/components/plugins/list/plugin-public-catalog.ts index 11d2c98b745..295cd45bf11 100644 --- a/src/renderer/src/components/plugins/list/plugin-public-catalog.ts +++ b/src/renderer/src/components/plugins/list/plugin-public-catalog.ts @@ -1,7 +1,7 @@ import type { PluginMarketplaceHostListing, PluginMarketplaceHostSourceState -} from '../../../../../preload/api-types' +} from '../../../../../preload/api/plugin-host-api' import { isOfficialMarketplaceGitSource, isSameGitRepository diff --git a/src/renderer/src/components/plugins/page/PluginAddsSection.test.tsx b/src/renderer/src/components/plugins/page/PluginAddsSection.test.tsx index 5e603c168a4..abb75a56361 100644 --- a/src/renderer/src/components/plugins/page/PluginAddsSection.test.tsx +++ b/src/renderer/src/components/plugins/page/PluginAddsSection.test.tsx @@ -2,7 +2,7 @@ import '@testing-library/jest-dom/vitest' import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import { useAppStore } from '@/store' import { usePluginLanguagePackStore } from '@/store/plugins/localization/plugin-language-packs' import { usePluginSyntaxStore } from '@/store/plugins/syntax/plugin-syntax-packs' diff --git a/src/renderer/src/components/plugins/page/PluginAddsSection.tsx b/src/renderer/src/components/plugins/page/PluginAddsSection.tsx index 4f2ee9cb711..df3ee47e8ec 100644 --- a/src/renderer/src/components/plugins/page/PluginAddsSection.tsx +++ b/src/renderer/src/components/plugins/page/PluginAddsSection.tsx @@ -15,10 +15,8 @@ import { SquareTerminal, Type } from 'lucide-react' -import type { - PluginHostListEntry, - PluginMarketplaceHostInstallPreview -} from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' +import type { PluginMarketplaceHostInstallPreview } from '../../../../../preload/api/plugin-host-api' import { formatKeybinding } from '../../../../../shared/keybindings/formatting' import type { PluginCatalogType } from '../../../../../shared/plugins/catalog/plugin-catalog-release' import { translate } from '@/i18n/i18n' diff --git a/src/renderer/src/components/plugins/page/PluginContributionActionEvents.tsx b/src/renderer/src/components/plugins/page/PluginContributionActionEvents.tsx index e42a3848050..10617501da1 100644 --- a/src/renderer/src/components/plugins/page/PluginContributionActionEvents.tsx +++ b/src/renderer/src/components/plugins/page/PluginContributionActionEvents.tsx @@ -1,5 +1,5 @@ import { Zap } from 'lucide-react' -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import type { PluginEventName } from '../../../../../shared/plugins/contributions/plugin-event-contribution' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/plugins/page/PluginContributionActionPanel.tsx b/src/renderer/src/components/plugins/page/PluginContributionActionPanel.tsx index ca2efc2b2d1..f191fb320e8 100644 --- a/src/renderer/src/components/plugins/page/PluginContributionActionPanel.tsx +++ b/src/renderer/src/components/plugins/page/PluginContributionActionPanel.tsx @@ -1,4 +1,4 @@ -import type { PluginHostPanel } from '../../../../../preload/api-types' +import type { PluginHostPanel } from '../../../../../shared/plugins/plugin-list-entry' import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store' import { Button } from '../../ui/button' diff --git a/src/renderer/src/components/plugins/page/PluginDetailPage.fixture.tsx b/src/renderer/src/components/plugins/page/PluginDetailPage.fixture.tsx index 0704a2a80ae..af29f4412fa 100644 --- a/src/renderer/src/components/plugins/page/PluginDetailPage.fixture.tsx +++ b/src/renderer/src/components/plugins/page/PluginDetailPage.fixture.tsx @@ -1,4 +1,4 @@ -import type { PluginMarketplaceHostListing } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostListing } from '../../../../../preload/api/plugin-host-api' import { defineFixture } from '../../../component-fixtures/component-fixture' import { usePluginInstallCountsStore } from '@/store/plugins/installation/plugin-install-counts' import { diff --git a/src/renderer/src/components/plugins/page/PluginDetailPage.test.tsx b/src/renderer/src/components/plugins/page/PluginDetailPage.test.tsx index dd49d08965f..3ecc8c94bcd 100644 --- a/src/renderer/src/components/plugins/page/PluginDetailPage.test.tsx +++ b/src/renderer/src/components/plugins/page/PluginDetailPage.test.tsx @@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { PluginMarketplaceHostInstallPreview, PluginMarketplaceHostListing -} from '../../../../../preload/api-types' +} from '../../../../../preload/api/plugin-host-api' import { usePluginSyntaxFailureStore } from '@/store/plugins/syntax/plugin-syntax-failures' import { usePluginSyntaxStore } from '@/store/plugins/syntax/plugin-syntax-packs' import { usePluginThemeStore } from '@/store/plugins/appearance/plugin-themes' diff --git a/src/renderer/src/components/plugins/page/plugin-contribution-action-availability.ts b/src/renderer/src/components/plugins/page/plugin-contribution-action-availability.ts index fca72c65538..4ad7b884417 100644 --- a/src/renderer/src/components/plugins/page/plugin-contribution-action-availability.ts +++ b/src/renderer/src/components/plugins/page/plugin-contribution-action-availability.ts @@ -1,4 +1,4 @@ -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import { isWorkspaceScopedPluginContext } from '../../../../../shared/plugins/contributions/plugin-command-contribution' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/plugins/presentation/plugin-access-profile.ts b/src/renderer/src/components/plugins/presentation/plugin-access-profile.ts index c6004f47199..a6a2b2f6ba1 100644 --- a/src/renderer/src/components/plugins/presentation/plugin-access-profile.ts +++ b/src/renderer/src/components/plugins/presentation/plugin-access-profile.ts @@ -1,7 +1,5 @@ -import type { - PluginHostListEntry, - PluginMarketplaceHostListing -} from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' +import type { PluginMarketplaceHostListing } from '../../../../../preload/api/plugin-host-api' import { pluginExecutionProfile, type PluginExecutionProfile diff --git a/src/renderer/src/components/plugins/presentation/plugin-install-trust.ts b/src/renderer/src/components/plugins/presentation/plugin-install-trust.ts index 0a35ca38449..b17c458acd1 100644 --- a/src/renderer/src/components/plugins/presentation/plugin-install-trust.ts +++ b/src/renderer/src/components/plugins/presentation/plugin-install-trust.ts @@ -2,7 +2,7 @@ import type { PluginHostInstallSource, PluginMarketplaceHostInstallPreview, PluginMarketplaceHostListing -} from '../../../../../preload/api-types' +} from '../../../../../preload/api/plugin-host-api' import { pluginExecutionProfile } from '../../../../../shared/plugins/contributions/plugin-execution-profile' import { splitQualifiedPluginKey } from '../../../../../shared/plugins/catalog/plugin-marketplace' import { pluginRepositoryOrigin } from '../../../../../shared/plugins/catalog/plugin-repository-link' diff --git a/src/renderer/src/components/plugins/presentation/plugin-status-presentation.ts b/src/renderer/src/components/plugins/presentation/plugin-status-presentation.ts index d739be7111e..b650d519a27 100644 --- a/src/renderer/src/components/plugins/presentation/plugin-status-presentation.ts +++ b/src/renderer/src/components/plugins/presentation/plugin-status-presentation.ts @@ -1,4 +1,4 @@ -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/plugins/review/PluginInstallConsent.tsx b/src/renderer/src/components/plugins/review/PluginInstallConsent.tsx index 09bfbd8bf4b..31636fb8388 100644 --- a/src/renderer/src/components/plugins/review/PluginInstallConsent.tsx +++ b/src/renderer/src/components/plugins/review/PluginInstallConsent.tsx @@ -1,6 +1,6 @@ import { useId } from 'react' import { AlertTriangle, Check, Loader2, ShieldAlert } from 'lucide-react' -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import { getIntlLocale } from '@/i18n/i18n' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform' diff --git a/src/renderer/src/components/plugins/review/PluginUpdateCandidate.tsx b/src/renderer/src/components/plugins/review/PluginUpdateCandidate.tsx index db9cb757573..371aac0478e 100644 --- a/src/renderer/src/components/plugins/review/PluginUpdateCandidate.tsx +++ b/src/renderer/src/components/plugins/review/PluginUpdateCandidate.tsx @@ -1,5 +1,5 @@ import { Check, ChevronDown } from 'lucide-react' -import type { PluginMarketplaceHostInstallPreview } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostInstallPreview } from '../../../../../preload/api/plugin-host-api' import { pluginExecutionProfile } from '../../../../../shared/plugins/contributions/plugin-execution-profile' import { pluginCapabilityReachable, diff --git a/src/renderer/src/components/plugins/review/PluginUpdateReview.tsx b/src/renderer/src/components/plugins/review/PluginUpdateReview.tsx index 8dccb41a6fc..4dd43a8f758 100644 --- a/src/renderer/src/components/plugins/review/PluginUpdateReview.tsx +++ b/src/renderer/src/components/plugins/review/PluginUpdateReview.tsx @@ -1,5 +1,5 @@ import { ArrowRight } from 'lucide-react' -import type { PluginMarketplaceHostInstallPreview } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostInstallPreview } from '../../../../../preload/api/plugin-host-api' import { pluginExecutionProfile } from '../../../../../shared/plugins/contributions/plugin-execution-profile' import { reachablePluginCapabilities } from '../../../../../shared/plugins/capabilities/plugin-capability-reach' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/plugins/review/PluginVmRecipeConsentPreview.tsx b/src/renderer/src/components/plugins/review/PluginVmRecipeConsentPreview.tsx index 3ec8748498c..ea833f15fab 100644 --- a/src/renderer/src/components/plugins/review/PluginVmRecipeConsentPreview.tsx +++ b/src/renderer/src/components/plugins/review/PluginVmRecipeConsentPreview.tsx @@ -1,4 +1,4 @@ -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import { PluginReviewSection } from './plugin-review-dialog-layout' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/plugins/state/plugin-preview-cache.ts b/src/renderer/src/components/plugins/state/plugin-preview-cache.ts index 7ee5c867bb7..43f5401e0cd 100644 --- a/src/renderer/src/components/plugins/state/plugin-preview-cache.ts +++ b/src/renderer/src/components/plugins/state/plugin-preview-cache.ts @@ -1,4 +1,4 @@ -import type { PluginMarketplaceHostListing } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostListing } from '../../../../../preload/api/plugin-host-api' import type { PluginPagePreview } from './use-plugin-catalog' /** Plugins whose preview one Settings visit keeps; each holds a parsed manifest. */ diff --git a/src/renderer/src/components/plugins/state/use-plugin-art-palettes.ts b/src/renderer/src/components/plugins/state/use-plugin-art-palettes.ts index 7cad8688a13..1653258bd2e 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-art-palettes.ts +++ b/src/renderer/src/components/plugins/state/use-plugin-art-palettes.ts @@ -1,5 +1,5 @@ import { useMemo } from 'react' -import type { PluginMarketplaceHostListing } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostListing } from '../../../../../preload/api/plugin-host-api' import { usePluginTerminalThemes, usePluginThemes } from '@/store/plugins/appearance/plugin-themes' import type { PluginArtPalette } from '../list/PluginCardArt' diff --git a/src/renderer/src/components/plugins/state/use-plugin-catalog.ts b/src/renderer/src/components/plugins/state/use-plugin-catalog.ts index 7bd93a7ea59..139c996ba5f 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-catalog.ts +++ b/src/renderer/src/components/plugins/state/use-plugin-catalog.ts @@ -3,7 +3,7 @@ import type { PluginMarketplaceHostInstallPreview, PluginMarketplaceHostListing, PluginMarketplaceHostSourceState -} from '../../../../../preload/api-types' +} from '../../../../../preload/api/plugin-host-api' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import { usePluginPreviewRequestStore } from '@/store/plugins/navigation/plugin-preview-request' diff --git a/src/renderer/src/components/plugins/state/use-plugin-contribution-source.ts b/src/renderer/src/components/plugins/state/use-plugin-contribution-source.ts index 7507945b66c..c53b5768d04 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-contribution-source.ts +++ b/src/renderer/src/components/plugins/state/use-plugin-contribution-source.ts @@ -1,5 +1,5 @@ import { useEffect, useMemo, useState } from 'react' -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import type { PluginManifest } from '../../../../../shared/plugins/manifest/plugin-manifest' import { usePluginIconThemes } from '@/store/plugins/appearance/plugin-icon-themes' import { diff --git a/src/renderer/src/components/plugins/state/use-plugin-hover-prefetch.ts b/src/renderer/src/components/plugins/state/use-plugin-hover-prefetch.ts index 241b7ae2cb8..035ccb780de 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-hover-prefetch.ts +++ b/src/renderer/src/components/plugins/state/use-plugin-hover-prefetch.ts @@ -1,5 +1,5 @@ import { useCallback, useEffect, useRef } from 'react' -import type { PluginMarketplaceHostListing } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostListing } from '../../../../../preload/api/plugin-host-api' import type { PluginPagePreview } from './use-plugin-catalog' /** Pointer rest before a hover counts as intent. */ diff --git a/src/renderer/src/components/plugins/state/use-plugin-install-action.test.tsx b/src/renderer/src/components/plugins/state/use-plugin-install-action.test.tsx deleted file mode 100644 index 93e0589f6c9..00000000000 --- a/src/renderer/src/components/plugins/state/use-plugin-install-action.test.tsx +++ /dev/null @@ -1,148 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot } from 'react-dom/client' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { - PluginMarketplaceHostInstallPreview, - PluginMarketplaceHostListing -} from '../../../../../preload/api-types' -import { pluginManifestSchema } from '../../../../../shared/plugins/manifest/plugin-manifest' -import { - settlePluginInstallTrust, - usePluginInstallTrustStore -} from '@/store/plugins/installation/plugin-install-trust-request' -import type { PluginInstallTrustPrompt } from '../presentation/plugin-install-trust' -import { usePluginInstallAction } from './use-plugin-install-action' - -vi.mock('sonner', () => ({ toast: { success: vi.fn(), warning: vi.fn() } })) -vi.mock('./plugin-theme-apply', () => ({ applyPluginThemesNow: vi.fn() })) -import { toast } from 'sonner' -import { applyPluginThemesNow } from './plugin-theme-apply' - -const listing: PluginMarketplaceHostListing = { - marketplaceSourceId: 'source', - marketplaceName: 'Catalog', - marketplaceOwner: 'acme', - marketplaceCommit: 'b'.repeat(40), - pluginKey: 'acme.dusk', - source: { kind: 'git', url: 'https://example.invalid/dusk.git', ref: 'main' }, - categories: [], - official: false, - bundled: false, - release: { - version: '1.0.0', - commit: 'c'.repeat(40), - contentHash: 'd'.repeat(64), - execution: 'data', - minimumOrca: '1.0.0', - types: ['app-theme'] - } -} - -const preview: PluginMarketplaceHostInstallPreview = { - ...listing, - resolvedCommit: 'c'.repeat(40), - contentHash: 'd'.repeat(64), - consentFingerprint: 'sha256-shown', - manifest: pluginManifestSchema.parse({ - manifestVersion: 1, - id: 'dusk', - publisher: 'acme', - name: 'Dusk', - version: '1.0.0', - engines: { orca: '>=1.0.0' }, - pluginApi: 1, - contributes: { themes: [{ id: 'dusk', title: 'Dusk', path: 'themes/dusk.json' }] } - }) -} - -const codePreview: PluginMarketplaceHostInstallPreview = { - ...preview, - manifest: pluginManifestSchema.parse({ - ...preview.manifest, - contributes: { commands: [{ id: 'go', title: 'Go', action: 'sidebar.left.toggle' }] } - }) -} - -function setup(isFromInstallLink?: (pluginKey: string) => boolean) { - const onInstalled = vi.fn().mockResolvedValue(undefined) - const fetchPreview = vi.fn().mockResolvedValue({ ok: true, preview }) - const hook: { current: ReturnType | null } = { current: null } - function Probe(): null { - hook.current = usePluginInstallAction({ fetchPreview, onInstalled, isFromInstallLink }) - return null - } - act(() => createRoot(document.createElement('div')).render()) - return { hook, onInstalled, fetchPreview } -} - -function installResult(on: boolean) { - return { - ok: true as const, - pluginKey: listing.pluginKey, - version: '1.0.0', - contentHash: 'd'.repeat(64), - consentFingerprint: 'sha256-shown', - resolvedCommit: 'c'.repeat(40), - needsReview: !on - } -} - -// Answers every trust ask the way the current test chose, recording what was shown. -const asked: PluginInstallTrustPrompt[] = [] -let answer = true -usePluginInstallTrustStore.subscribe(({ pending }) => { - if (pending) { - asked.push(pending.prompt) - queueMicrotask(() => settlePluginInstallTrust(answer)) - } -}) - -beforeEach(() => { - asked.length = 0 - answer = true - vi.mocked(toast.success).mockClear() - vi.mocked(toast.warning).mockClear() - vi.mocked(applyPluginThemesNow).mockReset().mockResolvedValue(false) - Object.defineProperty(window, 'api', { - configurable: true, - value: { - plugins: { - installMarketplacePlugin: vi.fn().mockResolvedValue(installResult(true)), - consent: vi.fn().mockResolvedValue([]) - } - } - }) -}) - -describe('usePluginInstallAction', () => { - it('leaves an install link’s replacement from a moved repository off and unapproved', async () => { - const codeListing = { - ...listing, - release: { ...listing.release!, execution: 'declarative' as const } - } - const movedCode = { ...codePreview, repositoryMoved: true as const } - for (const [target, moved, approve] of [ - [listing, { ...preview, repositoryMoved: true as const }, undefined], - [codeListing, movedCode, { preview: movedCode }] - ] as const) { - const { hook, fetchPreview, onInstalled } = setup(() => true) - fetchPreview.mockResolvedValue({ ok: true, preview: moved }) - vi.mocked(window.api.plugins.installMarketplacePlugin).mockResolvedValue(installResult(false)) - await act(async () => hook.current?.install(target, approve)) - expect(window.api.plugins.installMarketplacePlugin).toHaveBeenLastCalledWith( - expect.not.objectContaining({ enableIfData: true }) - ) - expect(window.api.plugins.consent).not.toHaveBeenCalled() - expect(applyPluginThemesNow).not.toHaveBeenCalled() - expect(hook.current?.phaseOf(listing.pluginKey)).toBeNull() - expect(onInstalled).toHaveBeenCalledWith(listing.pluginKey) - expect(toast.warning).toHaveBeenLastCalledWith( - 'Dusk 1.0.0 comes from a different repository', - expect.objectContaining({ description: 'It stays off until you review it.' }) - ) - expect(toast.success).not.toHaveBeenCalled() - } - }) -}) diff --git a/src/renderer/src/components/plugins/state/use-plugin-install-action.ts b/src/renderer/src/components/plugins/state/use-plugin-install-action.ts index 763cf3231f5..7aa390a7ad0 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-install-action.ts +++ b/src/renderer/src/components/plugins/state/use-plugin-install-action.ts @@ -3,7 +3,7 @@ import { toast } from 'sonner' import type { PluginMarketplaceHostInstallPreview, PluginMarketplaceHostListing -} from '../../../../../preload/api-types' +} from '../../../../../preload/api/plugin-host-api' import { pluginExecutionProfile } from '../../../../../shared/plugins/contributions/plugin-execution-profile' import { translate } from '@/i18n/i18n' import { pluginInstallErrorMessage } from '../presentation/plugin-error-presentation' diff --git a/src/renderer/src/components/plugins/state/use-plugin-install-link.test.tsx b/src/renderer/src/components/plugins/state/use-plugin-install-link.test.tsx index 67b758c34f3..10f6017c80a 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-install-link.test.tsx +++ b/src/renderer/src/components/plugins/state/use-plugin-install-link.test.tsx @@ -3,7 +3,7 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api/plugin-host-api' import { parsePluginInstallLink } from '../../../../../shared/plugins/catalog/plugin-install-link' import { usePluginPreviewRequestStore } from '@/store/plugins/navigation/plugin-preview-request' import { usePluginInstallLink } from './use-plugin-install-link' diff --git a/src/renderer/src/components/plugins/state/use-plugin-install-link.ts b/src/renderer/src/components/plugins/state/use-plugin-install-link.ts index 3641aed31a4..6e30f077d07 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-install-link.ts +++ b/src/renderer/src/components/plugins/state/use-plugin-install-link.ts @@ -1,5 +1,5 @@ import { useEffect, useLayoutEffect, useRef } from 'react' -import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api-types' +import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api/plugin-host-api' import { isSameGitRepository } from '../../../../../shared/plugins/catalog/plugin-marketplace' import type { PluginInstallLinkCatalog } from '../../../../../shared/plugins/catalog/plugin-install-link' import { usePluginPreviewRequestStore } from '@/store/plugins/navigation/plugin-preview-request' diff --git a/src/renderer/src/components/plugins/state/use-plugin-logs.ts b/src/renderer/src/components/plugins/state/use-plugin-logs.ts index 9b1b173b676..79856bf4b20 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-logs.ts +++ b/src/renderer/src/components/plugins/state/use-plugin-logs.ts @@ -1,5 +1,6 @@ import { useEffect, useRef, useState, type MutableRefObject } from 'react' -import type { PluginHostListEntry, PluginHostLogLine } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' +import type { PluginHostLogLine } from '../../../../../preload/api/plugin-host-api' import { useTranslate } from '@/i18n/use-translate' export type PluginLogsState = { diff --git a/src/renderer/src/components/plugins/state/use-plugin-marketplace-lifecycle.ts b/src/renderer/src/components/plugins/state/use-plugin-marketplace-lifecycle.ts index 93f5d3c9ba4..b2ec116b68e 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-marketplace-lifecycle.ts +++ b/src/renderer/src/components/plugins/state/use-plugin-marketplace-lifecycle.ts @@ -1,5 +1,5 @@ import { useState, type Dispatch, type MutableRefObject, type SetStateAction } from 'react' -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import { useTranslate } from '@/i18n/use-translate' import { pluginNeedsReview } from '../presentation/plugin-status-presentation' diff --git a/src/renderer/src/components/plugins/state/use-plugin-page-model.ts b/src/renderer/src/components/plugins/state/use-plugin-page-model.ts index 561819da1aa..d16846e4ce4 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-page-model.ts +++ b/src/renderer/src/components/plugins/state/use-plugin-page-model.ts @@ -2,7 +2,7 @@ import { useEffect, useState } from 'react' import type { PluginMarketplaceHostInstallPreview, PluginMarketplaceHostListing -} from '../../../../../preload/api-types' +} from '../../../../../preload/api/plugin-host-api' import { pluginExecutionProfile } from '../../../../../shared/plugins/contributions/plugin-execution-profile' import { PLUGIN_CONTRIBUTION_SUMMARY_LIMIT } from '../../../../../shared/plugins/contributions/plugin-contribution-summary' import { diff --git a/src/renderer/src/components/plugins/state/use-plugin-page-navigation.test.tsx b/src/renderer/src/components/plugins/state/use-plugin-page-navigation.test.tsx deleted file mode 100644 index 76329f55c0c..00000000000 --- a/src/renderer/src/components/plugins/state/use-plugin-page-navigation.test.tsx +++ /dev/null @@ -1,146 +0,0 @@ -// @vitest-environment happy-dom - -import { act, useEffect } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, describe, expect, it } from 'vitest' -import type { PluginHostListEntry } from '../../../../../preload/api-types' -import { usePluginReviewQueue } from './use-plugin-review-queue' -import { usePluginPageNavigation, type PluginPageNavigation } from './use-plugin-page-navigation' - -let root: Root | null = null -let nav: PluginPageNavigation | null = null -let reviews: ReturnType | null = null - -function pending(pluginKey: string): PluginHostListEntry { - return { - pluginKey, - consentFingerprint: null, - name: pluginKey, - version: '1.0.0', - publisher: 'acme', - status: 'pending', - needsReconsent: true, - isDev: false, - official: false, - bundled: false, - capabilities: [], - panels: [], - commands: [], - hasWorker: false, - restarts: 0 - } -} - -function Harness(): React.JSX.Element { - const queue = usePluginReviewQueue() - reviews = queue - nav = usePluginPageNavigation(queue.navigate) - const open = nav.open - useEffect(() => { - if (queue.reviewKey) { - open(queue.reviewKey, { replace: queue.replacePage }) - } - }, [queue.reviewKey, queue.replacePage, open]) - return ( - <> - -
- -
- - -
- -
- - ) -} - -async function mountOpen(): Promise { - const container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - await act(async () => root?.render()) - await act(async () => nav?.open('acme.notes')) - return container -} - -function pressBack(target: Element | null): void { - target?.dispatchEvent( - new KeyboardEvent('keydown', { key: 'ArrowLeft', altKey: true, bubbles: true }) - ) -} - -afterEach(() => { - act(() => root?.unmount()) - root = null - document.body.innerHTML = '' -}) - -describe('usePluginPageNavigation', () => { - it('returns through detail pages with Back and Alt+Left, then focuses the original list entry', async () => { - const container = await mountOpen() - await act(async () => nav?.open('acme.icons')) - await act(async () => nav?.open('acme.third')) - await act(async () => container.querySelector('[data-back]')?.click()) - expect(nav?.openKey).toBe('acme.icons') - await act(async () => pressBack(container.querySelector('[data-plain]'))) - expect(nav?.openKey).toBe('acme.notes') - await act(async () => pressBack(container.querySelector('[data-plain]'))) - expect(nav?.openKey).toBeNull() - expect(document.activeElement).toBe(container.querySelector('[data-plugin-row-name]')) - }) - - it('pauses A when visiting B, keeps B decisions outside the queue, and resumes A before the next review', async () => { - await mountOpen() - await act(async () => reviews?.enqueue(['acme.notes', 'acme.third'])) - await act(async () => - reviews?.advance('acme.icons', [pending('acme.notes'), pending('acme.third')]) - ) - expect(reviews?.reviewKey).toBe('acme.notes') - await act(async () => nav?.open('acme.icons')) - await act(async () => - reviews?.advance('acme.icons', [pending('acme.notes'), pending('acme.third')]) - ) - expect(nav?.openKey).toBe('acme.icons') - expect(reviews?.reviewKey).toBeNull() - - await act(async () => nav?.back()) - expect(nav?.openKey).toBe('acme.notes') - expect(reviews?.reviewKey).toBe('acme.notes') - await act(async () => reviews?.advance('acme.notes', [pending('acme.third')])) - expect(nav?.openKey).toBe('acme.third') - await act(async () => nav?.back()) - expect(nav?.openKey).toBeNull() - }) - - it.each(['button', 'keyboard'])( - 'pauses review on Back via %s, reopens the same plugin and accepts later update-all reviews', - async (method) => { - const container = await mountOpen() - await act(async () => reviews?.show('acme.notes')) - const back = (): void => { - if (method === 'button') { - container.querySelector('[data-back]')?.click() - } else { - pressBack(container.querySelector('[data-plain]')) - } - } - await act(async () => back()) - expect(nav?.openKey).toBeNull() - expect(reviews?.reviewKey).toBeNull() - await act(async () => reviews?.show('acme.notes')) - expect(nav?.openKey).toBe('acme.notes') - await act(async () => reviews?.advance('acme.notes', [])) - await act(async () => back()) - await act(async () => reviews?.enqueue(['acme.tasks', 'acme.third'])) - expect(nav?.openKey).toBe('acme.tasks') - await act(async () => reviews?.advance('acme.tasks', [pending('acme.third')])) - expect(nav?.openKey).toBe('acme.third') - await act(async () => back()) - expect(nav?.openKey).toBeNull() - } - ) -}) diff --git a/src/renderer/src/components/plugins/state/use-plugin-review-queue.test.tsx b/src/renderer/src/components/plugins/state/use-plugin-review-queue.test.tsx index 364be859c3c..3f876597a16 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-review-queue.test.tsx +++ b/src/renderer/src/components/plugins/state/use-plugin-review-queue.test.tsx @@ -3,7 +3,7 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, describe, expect, it } from 'vitest' -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import { usePluginReviewQueue } from './use-plugin-review-queue' let root: Root | null = null diff --git a/src/renderer/src/components/plugins/state/use-plugin-review-queue.ts b/src/renderer/src/components/plugins/state/use-plugin-review-queue.ts index c72cbc1f2ab..28a19408402 100644 --- a/src/renderer/src/components/plugins/state/use-plugin-review-queue.ts +++ b/src/renderer/src/components/plugins/state/use-plugin-review-queue.ts @@ -1,5 +1,5 @@ import { useCallback, useRef, useState } from 'react' -import type { PluginHostListEntry } from '../../../../../preload/api-types' +import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' import { pluginNeedsReview } from '../presentation/plugin-status-presentation' /** diff --git a/src/renderer/src/components/shared/MacFolderAccessFixDialog.tsx b/src/renderer/src/components/shared/MacFolderAccessFixDialog.tsx index be7b6ec50bb..02a53a509f1 100644 --- a/src/renderer/src/components/shared/MacFolderAccessFixDialog.tsx +++ b/src/renderer/src/components/shared/MacFolderAccessFixDialog.tsx @@ -1,6 +1,6 @@ import React, { useCallback, useState } from 'react' import { CircleCheck, CircleDashed, LoaderCircle } from 'lucide-react' -import type { PtyManagementFolderAccessMismatch } from '../../../../preload/api-types' +import type { PtyManagementFolderAccessMismatch } from '../../../../preload/api/pty-management-api' import { isMacTccFolderClass } from '../../../../shared/daemon-adoption-telemetry' import { useMountedRef } from '@/hooks/useMountedRef' import { translate } from '@/i18n/i18n' diff --git a/src/renderer/src/components/shared/mac-folder-access-folder-name.ts b/src/renderer/src/components/shared/mac-folder-access-folder-name.ts index b2238c8db28..f469a0b1ce8 100644 --- a/src/renderer/src/components/shared/mac-folder-access-folder-name.ts +++ b/src/renderer/src/components/shared/mac-folder-access-folder-name.ts @@ -1,10 +1,10 @@ -import type { PtyManagementDaemonCwdClass } from '../../../../preload/api-types' +import type { DaemonPtyCwdClass } from '../../../../shared/daemon-adoption-telemetry' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' /** Use the same macOS folder phrase in toast and remedy so they read as one notice. */ export function macFolderAccessFolderName( - cwdClass: PtyManagementDaemonCwdClass, + cwdClass: DaemonPtyCwdClass, t: Translate = translate ): string { switch (cwdClass) { diff --git a/src/renderer/src/components/sidebar/SeveredTerminalDaemonBanner.tsx b/src/renderer/src/components/sidebar/SeveredTerminalDaemonBanner.tsx index 530ee21e6a4..f0eaf47dcea 100644 --- a/src/renderer/src/components/sidebar/SeveredTerminalDaemonBanner.tsx +++ b/src/renderer/src/components/sidebar/SeveredTerminalDaemonBanner.tsx @@ -15,7 +15,7 @@ import { useTranslate, type Translate } from '@/i18n/use-translate' import type { PtyManagementSeveredDaemon, PtyManagementSeveredDaemonRestartResult -} from '../../../../preload/api-types' +} from '../../../../preload/api/pty-management-api' const POLL_INTERVAL_MS = 60_000 const DISMISSED_KEY = 'orca.severedTerminalDaemonBanner.dismissed' diff --git a/src/renderer/src/components/task-source-provider-availability.ts b/src/renderer/src/components/task-source-provider-availability.ts index 8efa20117d3..296dd5d1e57 100644 --- a/src/renderer/src/components/task-source-provider-availability.ts +++ b/src/renderer/src/components/task-source-provider-availability.ts @@ -1,6 +1,6 @@ import { parseExecutionHostId } from '../../../shared/execution-host' import type { TaskProvider } from '../../../shared/work-items/task-providers' -import type { PreflightStatus } from '../../../preload/api-types' +import type { PreflightStatus } from '../../../preload/api/preflight-api' import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' import type { TaskSourceHostAvailability } from './task-source-context-summary' diff --git a/src/renderer/src/hooks/ipc-events/linear-linked-issue-refresh.test.ts b/src/renderer/src/hooks/ipc-events/linear-linked-issue-refresh.test.ts index d62f5bc6a47..e52609d01e7 100644 --- a/src/renderer/src/hooks/ipc-events/linear-linked-issue-refresh.test.ts +++ b/src/renderer/src/hooks/ipc-events/linear-linked-issue-refresh.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { useAppStore } from '@/store' import { registerRuntimeClientIpcBridge } from './runtime-client-ipc-bridge' -import { subscribeRuntimeEnvironmentFromPreload } from '../../../../preload/runtime-environment-subscriptions' +import { subscribeRuntimeEnvironmentFromPreload } from '../../../../preload/runtime/runtime-environment-subscriptions' import { linearApi } from '../../../../preload/api/linear-bridge' import { createCompatibleRuntimeStatusResponse } from '@/runtime/rpc/testing/runtime-compatibility-test-fixture' import { runtimeCompatibilityChecks } from '@/runtime/rpc/compatibility/runtime-compatibility-cache' @@ -265,62 +265,6 @@ function harness(rows: Worktree[]) { } type AppStateSettings = NonNullable['settings']> -it.each([100, 1000])( - 'coalesces two actual same-source badge keys across %i remote notices without multiplying legacy refreshes', - async (population) => { - const a = row('same', source('runtime:host-a')) - const a2 = row('second', source('runtime:host-a'), 'w1') - const local = row('same', source('local')) - const wrongAccount = row('wrong-account', { - ...source('runtime:host-a'), - providerIdentity: { provider: 'linear', workspaceId: 'w2' } - }) - const h = harness([a, a2, local, wrongAccount]) - const keys = [await h.hydrate(a), await h.hydrate(a2)] - const localKey = await h.hydrate(local) - const wrongKey = await h.hydrate(wrongAccount) - h.request.mockClear() - h.responses.length = 0 - h.start() - for (let i = 0; i < population; i += 1) { - h.emit('same', true) - h.emit('second', true) - h.emit('wrong-account', true) - } - await settle() - const badgeCalls = () => h.request.mock.calls.filter((call) => call[1] === 'eng-1') - const legacyCalls = () => h.request.mock.calls.filter((call) => call[1] === 'ENG-1') - expect(badgeCalls()).toEqual([ - ['host-a', 'eng-1', 'all'], - ['host-a', 'eng-1', 'w1'] - ]) - expect(legacyCalls()).toHaveLength(population === 100 ? 300 : 3000) - expect(legacyCalls().every((call) => call[0] === 'host-b')).toBe(true) - h.responses - .filter((call) => call.id === 'eng-1') - .forEach((call) => call.response.resolve(issue('eng-1'))) - await settle() - expect(badgeCalls()).toHaveLength(4) - h.responses.forEach((call) => - call.response.resolve({ - ...issue(call.id), - workspaceId: 'w1', - state: { name: 'Done', type: 'completed', color: '#888888' } - }) - ) - await settle() - expect( - keys.map((key) => useAppStore.getState().linearIssueCache[key].data?.state.name) - ).toEqual(['Done', 'Done']) - expect(useAppStore.getState().linearIssueCache[localKey].data?.state.name).toBe('Todo') - expect(useAppStore.getState().linearIssueCache[wrongKey].data?.state.name).toBe('Todo') - expect(badgeCalls()).toHaveLength(4) - expect(legacyCalls()).toHaveLength(population === 100 ? 300 : 3000) - h.stop() - h.finishSetup() - } -) - it('tears down pending/trailing local and remote demand, rejects late setup and avoids late publication', async () => { const workspace = row('wt', source('local')) const h = harness([workspace]) diff --git a/src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge-ownership.test.ts b/src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge-ownership.test.ts index 3e28b442a3a..ac6047bce37 100644 --- a/src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge-ownership.test.ts +++ b/src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge-ownership.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { useAppStore } from '@/store' -import { subscribeRuntimeEnvironmentFromPreload } from '../../../../preload/runtime-environment-subscriptions' +import { subscribeRuntimeEnvironmentFromPreload } from '../../../../preload/runtime/runtime-environment-subscriptions' import { tagRuntimeSubscriptionReplayResponse } from '../../../../shared/runtime-subscription-replay' import { createCompatibleRuntimeStatusResponse } from '@/runtime/rpc/testing/runtime-compatibility-test-fixture' import { registerRuntimeClientIpcBridge } from './runtime-client-ipc-bridge' @@ -153,28 +153,6 @@ function createHarness() { } } -it('does no Linear read dispatch or cache publication after cleanup while setup is pending', async () => { - const h = createHarness() - let publications = 0 - const stopCounting = useAppStore.subscribe((state, previous) => { - if (state.linearIssueCache !== previous.linearIssueCache) { - publications += 1 - } - }) - try { - h.start()() - for (let index = 0; index < 100; index += 1) { - h.emit(0) - } - expect(h.getIssue).not.toHaveBeenCalled() - expect(publications).toBe(0) - } finally { - stopCounting() - await h.finish() - } - expect(h.ipc.removeListener).toHaveBeenCalledOnce() -}) - it('does not navigate for an unaddressed activation from an older remote host', async () => { const h = createHarness() try { @@ -252,38 +230,6 @@ it('does not mistake a local repo with the same id for the publishing remote rep } }) -it.each(['cleanup', 're-pair'] as const)( - 'cancels an accepted activation after %s during repository discovery', - async (change) => { - const h = createHarness() - const repos = Promise.withResolvers() - h.fetchRuntimeEnvironmentRepos.mockImplementation(() => repos.promise) - try { - const stop = h.start() - h.emit(0, false, { - type: 'activateWorktree', - repoId: 'remote-repo', - worktreeId: 'remote-wt', - navigation: 'clients' - }) - expect(h.fetchRuntimeEnvironmentRepos).toHaveBeenCalledWith('host-a') - if (change === 'cleanup') { - stop() - } else { - replaceRuntimeEnvironmentRevisions([{ id: 'host-a', createdAt: 1, pairingRevision: 2 }]) - } - repos.resolve([]) - for (let index = 0; index < 10; index += 1) { - await Promise.resolve() - } - expect(h.activateNotifiedWorktree).not.toHaveBeenCalled() - } finally { - repos.resolve([]) - await h.finish() - } - } -) - it('accepts a fresh bridge early frame while rejecting the previous bridge frame', async () => { const h = createHarness() try { diff --git a/src/renderer/src/hooks/useMacTccAttributionSeveredNotice.ts b/src/renderer/src/hooks/useMacTccAttributionSeveredNotice.ts index bb783027e16..e0060ab9654 100644 --- a/src/renderer/src/hooks/useMacTccAttributionSeveredNotice.ts +++ b/src/renderer/src/hooks/useMacTccAttributionSeveredNotice.ts @@ -4,7 +4,7 @@ import { toast } from 'sonner' import type { PtyManagementFolderAccessMismatch, PtyManagementMacTccAttributionHealth -} from '../../../preload/api-types' +} from '../../../preload/api/pty-management-api' import { isPluginUiLanguage } from '../../../shared/ui-language' import { useAppStore } from '@/store/index' import { diff --git a/src/renderer/src/store/slices/usage/usage-backend-port.test.ts b/src/renderer/src/store/slices/usage/usage-backend-port.test.ts index 437872eac3d..29a37373c3f 100644 --- a/src/renderer/src/store/slices/usage/usage-backend-port.test.ts +++ b/src/renderer/src/store/slices/usage/usage-backend-port.test.ts @@ -68,7 +68,7 @@ afterEach(() => { it('publishes port loss before rejection and preserves fresh work through duplicate loss', async () => { const { backendUsageTransport: transport } = - await import('../../../../../preload/backend-port-client') + await import('../../../../../preload/usage/backend-port-client') const events: string[] = [] let fresh: Promise | undefined detach.push( @@ -108,7 +108,7 @@ it('publishes port loss before rejection and preserves fresh work through duplic it('keeps a replacement handshake when the old handshake rejects after loss', async () => { const { backendUsageTransport: transport } = - await import('../../../../../preload/backend-port-client') + await import('../../../../../preload/usage/backend-port-client') let fresh: Promise | undefined detach.push( transport.onConnectionChanged((connected, detail) => { @@ -132,7 +132,7 @@ it('keeps a replacement handshake when the old handshake rejects after loss', as it('initializes terminal presentation without RPCs and preserves a fresh handshake through terminal escalation', async () => { const { backendUsageTransport: transport } = - await import('../../../../../preload/backend-port-client') + await import('../../../../../preload/usage/backend-port-client') emit(BACKEND_CONNECTION_CHANGED, { connected: false }) const fresh = transport.invoke('snapshot') emit(BACKEND_CONNECTION_CHANGED, { connected: false, unavailable: true }) @@ -149,7 +149,7 @@ it('initializes terminal presentation without RPCs and preserves a fresh handsha it('promotes pending recovery once and ignores its stale delivery and rejection', async () => { const { backendUsageTransport: transport } = - await import('../../../../../preload/backend-port-client') + await import('../../../../../preload/usage/backend-port-client') const old = Promise.withResolvers() electron.invoke.mockImplementationOnce(() => old.promise) const recovery = transport.invoke('snapshot', undefined, 'recovery') @@ -176,7 +176,7 @@ it('promotes pending recovery once and ignores its stale delivery and rejection' it('cancels pending recovery on loss without rearming, and admits fresh post-loss demand', async () => { const { backendUsageTransport: transport } = - await import('../../../../../preload/backend-port-client') + await import('../../../../../preload/usage/backend-port-client') const old = Promise.withResolvers() electron.invoke.mockImplementationOnce(() => old.promise) const recovery = transport.invoke('snapshot', undefined, 'recovery') diff --git a/src/renderer/src/web/preload-api/web-host-capability-api.ts b/src/renderer/src/web/preload-api/web-host-capability-api.ts index 19376cdd63e..86887d493de 100644 --- a/src/renderer/src/web/preload-api/web-host-capability-api.ts +++ b/src/renderer/src/web/preload-api/web-host-capability-api.ts @@ -1,8 +1,5 @@ -import type { - PreflightStatus, - PreloadApi, - RefreshAgentsResult -} from '../../../../preload/api-types' +import type { PreflightStatus, RefreshAgentsResult } from '../../../../preload/api/preflight-api' +import type { PreloadApi } from '../../../../preload/api-types' import type { ComputerUsePermissionSetupResult, ComputerUsePermissionStatusResult diff --git a/src/renderer/src/web/preload-api/web-native-chat-api.ts b/src/renderer/src/web/preload-api/web-native-chat-api.ts index 6130fb181e4..a81cb128e88 100644 --- a/src/renderer/src/web/preload-api/web-native-chat-api.ts +++ b/src/renderer/src/web/preload-api/web-native-chat-api.ts @@ -1,4 +1,7 @@ -import type { NativeChatApi, NativeChatAppendedMessages } from '../../../../preload/api-types' +import type { + NativeChatApi, + NativeChatAppendedMessages +} from '../../../../preload/api/native-chat-api' import { buildNativeChatUnsubscribe } from '../../../../shared/native-chat/native-chat-stream-unsubscribe' import { parseRuntimeNativeChatReadSessionResult, diff --git a/src/renderer/src/web/web-runtime-crew-follow.test.tsx b/src/renderer/src/web/web-runtime-crew-follow.test.tsx deleted file mode 100644 index 66eb161c09d..00000000000 --- a/src/renderer/src/web/web-runtime-crew-follow.test.tsx +++ /dev/null @@ -1,185 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, render } from '@testing-library/react' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' - -import { - type RuntimeEnvironmentStatus, - runtimeEnvironmentStatusFromSnapshot -} from '../../../shared/remote-runtime/host-status/runtime-host-status' -import type { StoredWebRuntimeEnvironment } from './web-runtime-environment' -import type * as RuntimeSession from './preload-api/web-runtime-session' -import type { PreloadApi } from '../../../preload/api-types' -import { replaceRuntimeEnvironmentRevisions } from '../runtime/rpc/environment-revisions/runtime-environment-revision' -import { useOrchestrationCrew } from '../components/orchestration-crew/use-orchestration-crew' -import { - type CrewSocket, - flushCrewWork, - installCrewSocketGlobals, - latestCrewSocket, - publicKeyB64, - verifyCrewPrimary -} from './web-runtime-crew.test-fixture' - -const store = vi.hoisted(() => ({ - state: { runtimeStatusByEnvironmentId: new Map() }, - listeners: new Set<() => void>() -})) -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => store.state, - subscribe: (wake: () => void) => { - store.listeners.add(wake) - return () => store.listeners.delete(wake) - } - } -})) -const environment: StoredWebRuntimeEnvironment = { - id: 'host', - name: 'Host', - createdAt: 1, - updatedAt: 1, - pairingRevision: 1, - runtimeId: 'rt', - lastUsedAt: null, - preferredEndpointId: 'endpoint', - endpoints: [ - { - id: 'endpoint', - kind: 'websocket', - label: 'WebSocket', - endpoint: 'ws://127.0.0.1:6768', - deviceToken: 'token', - publicKeyB64 - } - ] -} -const target = { kind: 'environment', environmentId: 'host' } as const -let session: typeof RuntimeSession -let api: PreloadApi['runtimeEnvironments'] -let disposeStatus: () => void -const domWindow = window -function Pane({ party = 'term_one' }: { party?: string }) { - const crew = useOrchestrationCrew(target, party) - return ( - - {crew.status === 'ok' ? crew.sections.managing.length : 'unknown'} - - ) -} -function requestId(socket: CrewSocket): string { - const request = socket.read(2) - if ( - !request || - typeof request !== 'object' || - !('id' in request) || - typeof request.id !== 'string' || - !('method' in request) || - request.method !== 'orchestration.crewSubscribe' - ) { - throw new Error('Expected actual Crew subscribe request') - } - return request.id -} -async function ready(socket = latestCrewSocket()): Promise { - socket.open() - socket.ready() - await flushCrewWork() - socket.authenticated() - await flushCrewWork() - return requestId(socket) -} -function frame(socket: CrewSocket, id: string, result: unknown, runtimeId = 'rt'): void { - socket.frame({ id, ok: true, result, _meta: { runtimeId } }) -} -async function complete(socket: CrewSocket, id: string, runtimeId = 'rt'): Promise { - frame(socket, id, { type: 'begin', status: 'ok' }, runtimeId) - frame( - socket, - id, - { - type: 'rows', - section: 'managing', - rows: [ - { - partyKey: 'worker', - role: 'worker', - label: 'Worker', - agentKind: 'codex', - status: 'working' - } - ] - }, - runtimeId - ) - frame(socket, id, { type: 'complete' }, runtimeId) - await flushCrewWork() -} -beforeEach(async () => { - vi.useFakeTimers() - vi.spyOn(Math, 'random').mockReturnValue(0) - installCrewSocketGlobals() - vi.stubGlobal('window', domWindow) - localStorage.clear() - localStorage.setItem('orca.web.runtimeEnvironment.v1', JSON.stringify(environment)) - session = await import('./preload-api/web-runtime-session') - session.manuallyDisconnectedEnvironmentIds.clear() - session.webRuntimeState.activeEnvironment = environment - api = (await import('./preload-api/web-runtime-environments-api')).createRuntimeEnvironmentsApi() - Object.assign(window, { api: { runtimeEnvironments: api } }) - store.state = { runtimeStatusByEnvironmentId: new Map() } - disposeStatus = session.subscribeWebRuntimeStatus((snapshot) => { - store.state = { - runtimeStatusByEnvironmentId: new Map(store.state.runtimeStatusByEnvironmentId).set( - 'host', - runtimeEnvironmentStatusFromSnapshot(snapshot) - ) - } - store.listeners.forEach((wake) => wake()) - }) - replaceRuntimeEnvironmentRevisions([{ id: 'host', createdAt: 1 }]) - await verifyCrewPrimary(session.getClientForEnvironment(environment)) -}) -afterEach(() => { - cleanup() - - disposeStatus() - session.closeActiveRuntimeClients() - vi.restoreAllMocks() - vi.useRealTimers() - vi.unstubAllGlobals() -}) - -it('retires the old source and follows the real verified runtime publication after its writer completes', async () => { - const ordinary = vi.spyOn(api, 'subscribe') - const retry = vi.spyOn(api, 'subscribeCrewAttempt') - const view = render() - const first = latestCrewSocket() - let oldId = '' - await act(async () => { - oldId = await ready(first) - await complete(first, oldId) - const owner = session.webRuntimeState.activeClient!.statusOwner! - owner.acceptVerified({ - id: 'status', - ok: true, - result: { ...owner.read().status!, runtimeId: 'next' }, - _meta: { runtimeId: 'next' } - }) - await complete(first, oldId) - }) - expect(view.getByTestId('term_one').textContent).toBe('unknown') - expect(retry).not.toHaveBeenCalled() - await act(async () => { - await vi.advanceTimersByTimeAsync(250) - }) - expect(retry).toHaveBeenCalledOnce() - expect(retry.mock.calls[0][0].expectedEnvironmentRuntimeId).toBe('next') - const current = latestCrewSocket() - await act(async () => { - const id = await ready(current) - await complete(current, id, 'next') - }) - expect(view.getByTestId('term_one').textContent).toBe('1') - expect(ordinary).toHaveBeenCalledOnce() - view.unmount() -}) diff --git a/src/renderer/src/web/web-runtime-crew.test-fixture.ts b/src/renderer/src/web/web-runtime-crew.test-fixture.ts deleted file mode 100644 index 5bdb32fcd58..00000000000 --- a/src/renderer/src/web/web-runtime-crew.test-fixture.ts +++ /dev/null @@ -1,137 +0,0 @@ -import type { WebRuntimeClient } from './web-runtime-client' -import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../shared/protocol-version' -import { vi } from 'vitest' -import { NODE_PAIRED_E2EE_PRIMITIVES as crypto } from '../../../shared/remote-runtime/e2ee/node/paired-e2ee-node-primitives' - -const host = crypto.generateKeyPair() -export const publicKeyB64 = crypto.publicKeyToBase64(host.publicKey) - -export class CrewSocket { - static readonly CONNECTING = 0 - static readonly OPEN = 1 - static sockets: CrewSocket[] = [] - readyState = CrewSocket.CONNECTING - binaryType = 'arraybuffer' - onopen: (() => void) | null = null - onclose: (() => void) | null = null - onerror: (() => void) | null = null - onmessage: ((event: { data: unknown }) => void) | null = null - close = vi.fn(() => { - this.readyState = 3 - }) - send = vi.fn((_data: unknown) => {}) - private key: Uint8Array | undefined - - constructor() { - CrewSocket.sockets.push(this) - } - - open(): void { - this.readyState = CrewSocket.OPEN - this.onopen?.() - } - - ready(): void { - const hello: unknown = JSON.parse(String(this.send.mock.calls[0]?.[0])) - if ( - !hello || - typeof hello !== 'object' || - !('publicKeyB64' in hello) || - typeof hello.publicKeyB64 !== 'string' - ) { - throw new Error('Invalid legacy hello') - } - this.key = crypto.deriveSharedKey( - host.secretKey, - crypto.publicKeyFromBase64(hello.publicKeyB64) - ) - this.onmessage?.({ data: JSON.stringify({ type: 'e2ee_ready' }) }) - } - - frame(value: unknown): void { - if (!this.key) { - throw new Error('No fixture session') - } - this.onmessage?.({ data: crypto.sealLegacyText(JSON.stringify(value), this.key) }) - } - - authenticated(): void { - this.frame({ type: 'e2ee_authenticated' }) - } - - read(index: number): unknown { - const frame = String(this.send.mock.calls[index]?.[0]) - const plaintext = this.key ? crypto.openLegacyText(frame, this.key) : null - if (!plaintext) { - throw new Error('Invalid fixture frame') - } - return JSON.parse(plaintext) - } -} - -export function installCrewSocketGlobals(): void { - CrewSocket.sockets = [] - vi.stubGlobal('WebSocket', CrewSocket) - vi.stubGlobal('window', { - setTimeout, - clearTimeout, - setInterval, - clearInterval, - atob: (value: string) => Buffer.from(value, 'base64').toString('binary'), - btoa: (value: string) => Buffer.from(value, 'binary').toString('base64') - }) -} - -export async function flushCrewWork(): Promise { - for (let index = 0; index < 20; index++) { - await Promise.resolve() - } -} - -export function latestCrewSocket(): CrewSocket { - const socket = CrewSocket.sockets.at(-1) - if (!socket) { - throw new Error('No fixture socket') - } - return socket -} - -/** Complete the existing primary's real status request over the controlled encrypted socket. */ -export async function verifyCrewPrimary(client: WebRuntimeClient): Promise { - const socket = latestCrewSocket() - socket.open() - socket.ready() - await flushCrewWork() - socket.authenticated() - await flushCrewWork() - const request = socket.read(2) - if ( - !request || - typeof request !== 'object' || - !('id' in request) || - typeof request.id !== 'string' || - !('method' in request) || - request.method !== 'status.get' - ) { - throw new Error('Expected actual primary status request') - } - socket.frame({ - id: request.id, - ok: true, - result: { - runtimeId: 'rt', - rendererGraphEpoch: 1, - graphStatus: 'ready', - authoritativeWindowId: null, - liveTabCount: 0, - liveLeafCount: 0, - capabilities: [REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY] - }, - _meta: { runtimeId: 'rt' } - }) - await flushCrewWork() - if (client.statusOwner?.read().verification !== 'verified') { - throw new Error('Primary did not verify') - } - return socket -}