From 0a613d5fed773f650b2e1c74f8581515ab43fc54 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Sun, 23 Aug 2026 16:47:12 -0700 Subject: [PATCH 01/13] test(e2e): stabilize paired Quick Open large-tree coverage (#16058) --- .github/workflows/e2e.yml | 3 +- .../e2e/paired-quick-open-large-tree.spec.ts | 95 +++++++++++-------- 2 files changed, 55 insertions(+), 43 deletions(-) diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index eba322cd13f..24c0ffa0e5b 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -134,7 +134,8 @@ jobs: # scripts still need the Linux toolchain even though this shard reuses # the prebuilt Electron output. - name: Install native build tools - run: sudo apt-get update && sudo apt-get install -y build-essential fonts-noto-cjk python3 zsh + # Why: paired Quick Open coverage exercises the resource-bounded host search. + run: sudo apt-get update && sudo apt-get install -y build-essential fonts-noto-cjk python3 ripgrep zsh # Why: Electron on Linux needs an X display even when the app # suppresses mainWindow.show() via ORCA_E2E_HEADLESS. xvfb provides a diff --git a/tests/e2e/paired-quick-open-large-tree.spec.ts b/tests/e2e/paired-quick-open-large-tree.spec.ts index 36184e990b3..683b7b435c3 100644 --- a/tests/e2e/paired-quick-open-large-tree.spec.ts +++ b/tests/e2e/paired-quick-open-large-tree.spec.ts @@ -10,6 +10,8 @@ import { createPairedQuickOpenLargeTreeFixture } from './helpers/paired-quick-op import type { PairedQuickOpenLargeTreeFixture } from './helpers/paired-quick-open-large-tree-fixture' import { waitForSessionReady } from './helpers/store' +const QUICK_OPEN_SEARCH_DEBOUNCE_MS = 120 + async function activateWorktree(page: Page, repoPath: string, timeout = 60_000): Promise { await expect .poll( @@ -57,47 +59,8 @@ async function expectQuickOpenAndRuntimeHealthy( ): Promise { const dialog = client.page.getByRole('dialog', { name: 'Go to file' }) const input = dialog.getByPlaceholder('Go to file...') - for (const targetPath of [fixture.gitIgnoredTargetPath, fixture.orcaIgnoredTargetPath]) { - const filename = targetPath.split('/').at(-1)! - const stat = await client.page.evaluate( - async ({ environmentId, worktreeId, targetPath }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'files.stat', - params: { worktree: `id:${worktreeId}`, relativePath: targetPath } - }) - if (!response.ok) { - throw new Error(`files.stat oracle failed: ${JSON.stringify(response)}`) - } - return response.result - }, - { environmentId: client.environmentId, worktreeId, targetPath } - ) - expect(stat.isDirectory).toBe(false) - expect(stat.size).toBeGreaterThanOrEqual(0) - await input.fill(filename.slice(0, 8)) - await input.fill(filename.slice(0, 18)) - await input.fill(filename) - await expect(dialog.getByText('Loading files...')).toHaveCount(0, { timeout: 60_000 }) - await expect(dialog.getByRole('option').filter({ hasText: filename })).toHaveCount(1) - await expect(dialog).not.toContainText('Outbound reply buffer overflow') - await expect(dialog).not.toContainText('Remote Orca runtime closed the connection') - } - - const response = await client.page.evaluate( - async ({ environmentId }) => - window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'worktree.list', - params: { limit: 10_000 } - }), - { environmentId: client.environmentId } - ) - expect(response.ok).toBe(true) - if (response.ok) { - expect(response.result.worktrees.some((worktree) => worktree.id === worktreeId)).toBe(true) - } - + const loading = dialog.getByText('Loading files...') + await client.page.clock.install() const queryOracle = async (targetPath: string) => client.page.evaluate( async ({ environmentId, worktreeId, targetPath }) => { @@ -129,10 +92,28 @@ async function expectQuickOpenAndRuntimeHealthy( { environmentId: client.environmentId, worktreeId, targetPath } ) for (const targetPath of [fixture.gitIgnoredTargetPath, fixture.orcaIgnoredTargetPath]) { + const filename = targetPath.split('/').at(-1)! + const stat = await client.page.evaluate( + async ({ environmentId, worktreeId, targetPath }) => { + const response = await window.api.runtimeEnvironments.call({ + selector: environmentId, + method: 'files.stat', + params: { worktree: `id:${worktreeId}`, relativePath: targetPath } + }) + if (!response.ok) { + throw new Error(`files.stat oracle failed: ${JSON.stringify(response)}`) + } + return response.result + }, + { environmentId: client.environmentId, worktreeId, targetPath } + ) + expect(stat.isDirectory).toBe(false) + expect(stat.size).toBeGreaterThanOrEqual(0) + const queryResult = await queryOracle(targetPath) const repeatedResult = await queryOracle(targetPath) console.log( - `[STA-4354] query=${targetPath} oracle=${JSON.stringify(queryResult)} repeated=${JSON.stringify(repeatedResult)}` + `[STA-5209] query=${targetPath} oracle=${JSON.stringify(queryResult)} repeated=${JSON.stringify(repeatedResult)}` ) expect(queryResult).toEqual(repeatedResult) expect(queryResult.files).toEqual([targetPath]) @@ -150,6 +131,36 @@ async function expectQuickOpenAndRuntimeHealthy( sha256: '9e7399e32001d443105e0f612f0eb2eee88fba50902dc75c926c547538e93eb5' } ) + + // Why: control only the debounce; RPC deadlines and socket liveness stay on real time. + const pauseAt = await client.page.evaluate(() => Date.now() + 1_000) + await client.page.clock.pauseAt(pauseAt) + await input.fill(filename.slice(0, 8)) + await input.fill(filename.slice(0, 18)) + await input.fill(filename) + await expect(loading).toBeVisible() + await client.page.clock.runFor(QUICK_OPEN_SEARCH_DEBOUNCE_MS) + await client.page.clock.resume() + await expect(dialog.getByRole('option').filter({ hasText: filename })).toHaveCount(1, { + timeout: 60_000 + }) + await expect(loading).toHaveCount(0) + await expect(dialog).not.toContainText('Outbound reply buffer overflow') + await expect(dialog).not.toContainText('Remote Orca runtime closed the connection') + } + + const response = await client.page.evaluate( + async ({ environmentId }) => + window.api.runtimeEnvironments.call({ + selector: environmentId, + method: 'worktree.list', + params: { limit: 10_000 } + }), + { environmentId: client.environmentId } + ) + expect(response.ok).toBe(true) + if (response.ok) { + expect(response.result.worktrees.some((worktree) => worktree.id === worktreeId)).toBe(true) } } From 5bcbafff537edaeee201e0caa753ac2a216ab288 Mon Sep 17 00:00:00 2001 From: erish Date: Mon, 24 Aug 2026 09:32:36 +0900 Subject: [PATCH 02/13] docs(cli): document worktree rm branch cleanup (#16167) Document that Git worktree removal may also delete the checked-out local branch, while clarifying that --force does not force branch deletion and that Orca retains branches whose changes cannot be proven merged. --- src/cli/help.ts | 3 ++- src/cli/specs/core.ts | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/cli/help.ts b/src/cli/help.ts index a8a195e63e2..d43c8294963 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -547,7 +547,8 @@ export function formatFlagHelp(flag: string): string { 'element-index': '--element-index Element index from get-app-state', title: '--title Custom title for the terminal tab (omit to reset)', enter: '--enter Append Enter after sending text', - force: '--force Force worktree removal when supported', + force: + '--force Force worktree removal when supported; does not force branch deletion', focus: '--focus Reveal the created terminal session in Orca', for: '--for exit|tui-idle Wait condition to satisfy', 'from-element-index': '--from-element-index Source element index from get-app-state', diff --git a/src/cli/specs/core.ts b/src/cli/specs/core.ts index a3cab5dfe70..d4422943f67 100644 --- a/src/cli/specs/core.ts +++ b/src/cli/specs/core.ts @@ -170,7 +170,10 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [ summary: 'Remove a worktree from Orca and git', usage: 'orca worktree rm --worktree [--force] [--run-hooks] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'worktree', 'force', 'run-hooks'], - notes: ['Repo-defined orca.yaml archive hooks are skipped unless --run-hooks is passed.'] + notes: [ + 'Repo-defined orca.yaml archive hooks are skipped unless --run-hooks is passed.', + 'For Git worktrees, removal also attempts to delete the checked-out local branch, with or without --force. Orca retains branches it knows predated the worktree and any branch whose changes it cannot prove are already merged.' + ] }, { path: ['worktree', 'ps'], From 4c4411619705783d2de33fce53fa04b52806ec47 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 23 Aug 2026 18:35:05 -0700 Subject: [PATCH 03/13] fix(workspace-cleanup): name the local context instead of totalling it (#15070) * fix(workspace-cleanup): name the local context instead of totalling it The delete confirmation showed 'Context: 2', a sum of five unrelated things (terminal tabs, clean editor tabs, browser tabs, diff notes, finished agents) rendered as plain text with no icon or tooltip. A reader cannot tell what the number counts, which is the one thing that screen exists to tell them. Reuse the breakdown the expanded row already renders ('Terminal tabs: 1, Browser tabs: 1') so the confirmation names what deleting would discard. No new strings: the per-kind labels already exist and were already translated. * fix(workspace-cleanup): keep context labels legible --- .../workspace-cleanup-candidate-labels.ts | 8 ---- .../workspace-cleanup-candidate-row-data.ts | 16 +++---- .../workspace-cleanup-confirm-remove.test.tsx | 43 +++++++++++++++++++ .../workspace-cleanup-confirm-remove.tsx | 8 ++-- 4 files changed, 54 insertions(+), 21 deletions(-) diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-labels.ts b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-labels.ts index 78b98f9b4d0..f1ce3ffb6b9 100644 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-labels.ts +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-labels.ts @@ -166,11 +166,3 @@ export function formatWorkspaceCleanupContextDetail( ) } } - -export function formatWorkspaceCleanupContextCount(count: number): string { - return translate( - 'auto.components.workspace.cleanup.candidateRow.contextCount', - 'Context: {{value0}}', - { value0: count } - ) -} diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-row-data.ts b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-row-data.ts index 42a7d0c58a5..6b173868f59 100644 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-row-data.ts +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-row-data.ts @@ -2,12 +2,10 @@ import { translate } from '@/i18n/i18n' import type { WorkspaceCleanupCandidate } from '../../../../shared/workspace-cleanup' import { getWorkspaceCleanupGitLabel, - hasWorkspaceCleanupLocalContext, type WorkspaceCleanupReviewInfo } from './workspace-cleanup-presentation' import { formatUnpushedCommitCount, - formatWorkspaceCleanupContextCount, formatWorkspaceCleanupContextDetail, formatWorkspaceCleanupGitStatusLabel, getGitStatusUnknownLabel, @@ -85,7 +83,7 @@ export function formatBranchSafetyDetails(candidate: WorkspaceCleanupCandidate): return details } -export function formatContextDetails(candidate: WorkspaceCleanupCandidate): string | null { +export function formatContextDetailLabels(candidate: WorkspaceCleanupCandidate): string[] { const parts: string[] = [] if (candidate.localContext.terminalTabCount > 0) { parts.push( @@ -110,6 +108,11 @@ export function formatContextDetails(candidate: WorkspaceCleanupCandidate): stri formatWorkspaceCleanupContextDetail('agent', candidate.localContext.retainedDoneAgentCount) ) } + return parts +} + +export function formatContextDetails(candidate: WorkspaceCleanupCandidate): string | null { + const parts = formatContextDetailLabels(candidate) return parts.length > 0 ? parts.join(', ') : null } @@ -166,13 +169,6 @@ export function getReviewPillTone(reviewInfo: WorkspaceCleanupReviewInfo): Statu return 'neutral' } -export function getContextPillLabel(candidate: WorkspaceCleanupCandidate): string | null { - if (!hasWorkspaceCleanupLocalContext(candidate)) { - return null - } - return formatWorkspaceCleanupContextCount(getContextCount(candidate)) -} - export function getContextCount(candidate: WorkspaceCleanupCandidate): number { return ( candidate.localContext.terminalTabCount + diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx index 0a7014cf1b2..03a146f17ea 100644 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx @@ -84,6 +84,49 @@ describe('WorkspaceCleanupConfirmRemove', () => { expect(container.querySelectorAll('span.truncate.text-sm.font-medium')).toHaveLength(5) }) + it('names each local context type separately instead of totalling them', () => { + const candidate = makeFacetCandidate({ + worktreeId: 'repo-1::/repo/with-context', + displayName: 'Has context', + localContext: { + terminalTabCount: 1, + cleanEditorTabCount: 2, + browserTabCount: 3, + diffCommentCount: 4, + newestDiffCommentAt: null, + retainedDoneAgentCount: 5 + } + }) + + act(() => { + root.render( + + ) + }) + + const labels = [ + 'Terminal tabs: 1', + 'Editor tabs: 2', + 'Browser tabs: 3', + 'Diff notes: 4', + 'Completed agents: 5' + ] + const renderedLabels = Array.from(container.querySelectorAll('span')) + .map((element) => element.textContent) + .filter((label): label is string => labels.includes(label ?? '')) + + expect(renderedLabels).toEqual(labels) + expect(container.textContent).not.toContain('Context: ') + }) + it('visibly and accessibly identifies each host for colliding confirmations', () => { const local = makeFacetCandidate({ executionHostId: 'local' }) const remote = makeFacetCandidate({ diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.tsx b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.tsx index ee068fe3f21..51135d63265 100644 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.tsx +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.tsx @@ -10,7 +10,7 @@ import type { WorkspaceCleanupCandidate } from '../../../../shared/workspace-cle import type { WorkspaceCleanupRemovalProgress } from './workspace-cleanup-background-removal' import { getCandidateFactStatus, - getContextPillLabel, + formatContextDetailLabels, getDirtyGitLabel, getReviewPillTone, shouldShowGitMetadataChip @@ -204,7 +204,7 @@ function ConfirmRemoveRow({ }): React.JSX.Element { const dirtyLabel = getDirtyGitLabel(candidate) const branchDiffersFromName = candidate.branch !== candidate.displayName - const contextPillLabel = getContextPillLabel(candidate) + const contextPillLabels = formatContextDetailLabels(candidate) const showGitMetadataChip = shouldShowGitMetadataChip(candidate) const factStatus = getCandidateFactStatus(candidate) const hostLabel = getWorkspaceCleanupCandidateHostLabel(candidate) @@ -234,7 +234,9 @@ function ConfirmRemoveRow({ {reviewInfo.label ? ( {reviewInfo.label} ) : null} - {contextPillLabel ? {contextPillLabel} : null} + {contextPillLabels.map((label) => ( + {label} + ))} {dirtyLabel && showGitMetadataChip ? ( {dirtyLabel} ) : null} From 41ddcbde066703c55f225034bee5a40a3955a34f Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 23 Aug 2026 18:35:27 -0700 Subject: [PATCH 04/13] fix(workspace-cleanup): stop pre-selecting workspaces for deletion (#15152) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(workspace-cleanup): stop pre-selecting workspaces for deletion 'Ready' is Orca's verdict about the user's own work. The dialog already refuses to display the tier as a workspace fact, then pre-checked rows based on it anyway — acting on the verdict more loudly than showing it would. Open with an empty selection and let the user decide. Removing auto-select unmasks two selection defects it was hiding, both fixed here because they become reachable the moment select-all is the primary path: - The header checkbox compared a canQueue-scoped selected count against a canSelect-scoped selectable count, so hand-picking review-tier rows flipped it to fully-checked and the next click cleared the entire selection. - A filter change silently dropped selected rows; auto-select used to refill them instantly, so the loss was invisible. It is now reported. Also drops the scan toast's 'N cleanup suggestions' clause, which published the same verdict outside the dialog, and labels select-all with the count it actually takes (the deletable subset, not every matched row). * chore(i18n): sync the catalog for the cleanup selection strings * fix(workspace-cleanup): preserve explicit selections --- ...anupDialog.stale-while-revalidate.test.tsx | 74 ++++++++++++++++++- .../WorkspaceCleanupDialog.tsx | 72 +++++++++--------- .../use-workspace-cleanup-scan-lifecycle.ts | 8 +- .../workspace-cleanup-scan-notice.ts | 31 ++------ .../workspace-cleanup-selection-model.ts | 26 +++---- .../workspace-cleanup-sort-header.test.tsx | 25 +++++++ .../workspace-cleanup-sort-header.tsx | 23 +++--- src/renderer/src/i18n/locales/en.json | 10 ++- src/renderer/src/i18n/locales/ko.json | 10 +++ src/renderer/src/i18n/locales/zh.json | 10 +++ 10 files changed, 192 insertions(+), 97 deletions(-) diff --git a/src/renderer/src/components/workspace-cleanup/WorkspaceCleanupDialog.stale-while-revalidate.test.tsx b/src/renderer/src/components/workspace-cleanup/WorkspaceCleanupDialog.stale-while-revalidate.test.tsx index bc4a90dd892..5e1ef3b9212 100644 --- a/src/renderer/src/components/workspace-cleanup/WorkspaceCleanupDialog.stale-while-revalidate.test.tsx +++ b/src/renderer/src/components/workspace-cleanup/WorkspaceCleanupDialog.stale-while-revalidate.test.tsx @@ -7,6 +7,7 @@ import type { WorkspaceCleanupScanProgress, WorkspaceCleanupScanResult } from '../../../../shared/workspace-cleanup' +import type { WorkspaceCleanupBrowseState } from '../../../../shared/workspace-cleanup-browse-state' import { createTestStore, seedStore } from '../../store/slices/store-test-helpers' import { resetWorkspaceCleanupBrowsePersistTimer } from '../../store/slices/workspace-cleanup-browse' import { NOW, makeCandidate } from '../../store/slices/workspace-cleanup-slice-test-harness' @@ -349,6 +350,35 @@ describe('WorkspaceCleanupDialog stale-while-revalidate', () => { expect(rowCheckbox('alpha')?.getAttribute('aria-checked')).toBe('true') }) + it('reports selections removed by facet filters', async () => { + installApi(cachedFleet()) + await renderDialog() + await openDialog() + + await act(async () => rowCheckbox('alpha')?.click()) + const browse = holders.store.getState().workspaceCleanupBrowse as WorkspaceCleanupBrowseState + await act(async () => { + holders.store.setState({ + workspaceCleanupBrowse: { + ...browse, + filters: { + ...browse.filters, + safety: { ...browse.filters.safety, tiers: ['review'] } + } + } + }) + }) + await flush() + + expect(holders.infoToasts).toContain( + '1 selected workspace is hidden by the current filters and was deselected.' + ) + + await act(async () => holders.store.setState({ workspaceCleanupBrowse: browse })) + await flush() + 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() @@ -399,7 +429,16 @@ describe('WorkspaceCleanupDialog stale-while-revalidate', () => { }) await flush() - // Both rows are default-selected suggestions after the first settle. + // Nothing is pre-selected: the dialog no longer acts on its own verdict. + expect(rowCheckbox('alpha')?.getAttribute('aria-checked')).toBe('false') + expect(rowCheckbox('beta')?.getAttribute('aria-checked')).toBe('false') + + // The user selects both, which is what must survive the refresh. + await act(async () => { + rowCheckbox('alpha')?.click() + rowCheckbox('beta')?.click() + }) + await flush() expect(rowCheckbox('alpha')?.getAttribute('aria-checked')).toBe('true') expect(rowCheckbox('beta')?.getAttribute('aria-checked')).toBe('true') @@ -424,4 +463,37 @@ describe('WorkspaceCleanupDialog stale-while-revalidate', () => { expect(rowNames()).not.toContain('beta') expect(holders.infoToasts).toContain('1 selected workspace no longer exists.') }) + + it('keeps selected review rows outside the select-all scope', async () => { + installApi({ + scannedAt: CACHED_AT, + candidates: [ + makeCandidate({ worktreeId: 'repo1::/tmp/ready', displayName: 'ready' }), + makeCandidate({ + worktreeId: 'repo1::/tmp/review', + displayName: 'review', + tier: 'review', + selectedByDefault: false, + git: { clean: null, upstreamAhead: 0, upstreamBehind: 0, checkedAt: null } + }) + ], + errors: [] + }) + await renderDialog() + await openDialog() + + await act(async () => rowCheckbox('review')?.click()) + const selectAll = container?.querySelector( + '[aria-label="Select 1 safety-checked workspace"]' + ) + expect(selectAll?.getAttribute('aria-checked')).toBe('false') + + await act(async () => selectAll?.click()) + expect(rowCheckbox('ready')?.getAttribute('aria-checked')).toBe('true') + expect(rowCheckbox('review')?.getAttribute('aria-checked')).toBe('true') + + await act(async () => selectAll?.click()) + expect(rowCheckbox('ready')?.getAttribute('aria-checked')).toBe('false') + expect(rowCheckbox('review')?.getAttribute('aria-checked')).toBe('true') + }) }) diff --git a/src/renderer/src/components/workspace-cleanup/WorkspaceCleanupDialog.tsx b/src/renderer/src/components/workspace-cleanup/WorkspaceCleanupDialog.tsx index 606d42aca3c..ecc72781cab 100644 --- a/src/renderer/src/components/workspace-cleanup/WorkspaceCleanupDialog.tsx +++ b/src/renderer/src/components/workspace-cleanup/WorkspaceCleanupDialog.tsx @@ -43,7 +43,7 @@ import { useWorkspaceCleanupGitEvidence } from './use-workspace-cleanup-git-evid import { useWorkspaceCleanupRowOrder } from './use-workspace-cleanup-row-order' import { formatVanishedSelectionNotice, - getDefaultSelectedWorkspaceCleanupIdentities, + formatWithheldSelectionNotice, toggleSetMember } from './workspace-cleanup-selection-model' @@ -84,12 +84,7 @@ function WorkspaceCleanupDialogContent({ const [facetPanelOpen, setFacetPanelOpen] = useState(false) const [expandedRowIds, setExpandedRowIds] = useState>(() => new Set()) const [rowsScrollElement, setRowsScrollElement] = useState(null) - const selectedDefaultsScanAtRef = useRef(null) const wasOpenRef = useRef(open) - // Why: a refresh completing mid-open must not clobber a selection the user - // already made (or was given) for this open — defaults apply at most once. - const defaultsAppliedForOpenRef = useRef(false) - const selectionTouchedRef = useRef(false) const mountedRef = useMountedRef() // Why: the facet clock must be stable across renders but never older than @@ -99,8 +94,6 @@ function WorkspaceCleanupDialogContent({ useEffect(() => { if (open && !wasOpenRef.current) { - defaultsAppliedForOpenRef.current = false - selectionTouchedRef.current = false setOpenedAt(Date.now()) } wasOpenRef.current = open @@ -193,33 +186,20 @@ function WorkspaceCleanupDialogContent({ }, [deletingIdentities, rows, selectedIds]) const selectedCount = selectedCandidates.length - useEffect(() => { - if (loading || !scan || selectedDefaultsScanAtRef.current === scan.scannedAt) { - return - } - selectedDefaultsScanAtRef.current = scan.scannedAt - if (removalInFlightRef.current) { - return - } - if (defaultsAppliedForOpenRef.current || selectionTouchedRef.current) { - return - } - defaultsAppliedForOpenRef.current = true - setSelectedIds( - getDefaultSelectedWorkspaceCleanupIdentities(scan.candidates, deletingIdentities) - ) - }, [deletingIdentities, loading, removalInFlightRef, scan, setSelectedIds]) + // A destructive dialog leaves selection to the user. const pruneSelectionToVisibleRows = useEffectEvent(() => { - setSelectedIds((current) => { - const next = new Set( - [...current].filter( - (identity) => - facetRows.facetMatchedIdentities.has(identity) && !deletingIdentities.has(identity) - ) + const next = new Set( + [...selectedIds].filter( + (identity) => + facetRows.facetMatchedIdentities.has(identity) && !deletingIdentities.has(identity) ) - return next.size === current.size ? current : next - }) + ) + if (next.size === selectedIds.size) { + return + } + setSelectedIds(next) + toast.info(formatWithheldSelectionNotice(selectedIds.size - next.size)) }) useEffect(() => { @@ -292,7 +272,6 @@ function WorkspaceCleanupDialogContent({ const toggleSelectedRow = useCallback( (identity: string) => { - selectionTouchedRef.current = true setSelectedIds((current) => toggleSetMember(current, identity)) }, [setSelectedIds] @@ -305,10 +284,30 @@ function WorkspaceCleanupDialogContent({ : facetRows.selectableIdentities.filter((identity) => !deletingIdentities.has(identity)), [deletingIdentities, facetRows.selectableIdentities, removal.removalInFlight] ) + // Header state is scoped to the same rows the header action controls. + const selectedSelectableCount = useMemo(() => { + let count = 0 + for (const identity of selectableIdentities) { + if (selectedIds.has(identity)) { + count += 1 + } + } + return count + }, [selectableIdentities, selectedIds]) + const toggleSelectAll = useCallback( (selectAll: boolean) => { - selectionTouchedRef.current = true - setSelectedIds(selectAll ? new Set(selectableIdentities) : new Set()) + setSelectedIds((current) => { + const next = new Set(current) + for (const identity of selectableIdentities) { + if (selectAll) { + next.add(identity) + } else { + next.delete(identity) + } + } + return next + }) }, [selectableIdentities, setSelectedIds] ) @@ -323,7 +322,6 @@ function WorkspaceCleanupDialogContent({ if (removalInFlightRef.current) { return } - selectionTouchedRef.current = true setSelectedIds(new Set([getWorkspaceCleanupCandidateIdentity(candidate)])) openConfirmRemove([candidate]) }, @@ -390,7 +388,7 @@ function WorkspaceCleanupDialogContent({ facetPanelOpen={facetPanelOpen} onFacetPanelOpenChange={setFacetPanelOpen} selectableCount={selectableIdentities.length} - selectedCount={selectedCount} + selectedCount={selectedSelectableCount} spaceScanning={workspaceSpaceScanning} spaceProgress={workspaceSpaceProgress} gitPendingCount={gitEvidence.pendingWorktreeIds.size} diff --git a/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-scan-lifecycle.ts b/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-scan-lifecycle.ts index 8537f2136ff..0027183a077 100644 --- a/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-scan-lifecycle.ts +++ b/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-scan-lifecycle.ts @@ -56,19 +56,13 @@ export function useWorkspaceCleanupScanLifecycle({ return } latestReadyToastScanAtRef.current = result.scannedAt - const suggestedCount = result.candidates.filter( - (candidate) => candidate.selectedByDefault - ).length toast.success( translate( 'auto.components.workspace.cleanup.WorkspaceCleanupDialog.0e2d235c63', 'Workspace scan ready' ), { - description: formatWorkspaceCleanupReadyToast( - result.candidates.length, - suggestedCount - ), + description: formatWorkspaceCleanupReadyToast(result.candidates.length), action: { label: translate( 'auto.components.workspace.cleanup.WorkspaceCleanupDialog.4a35c08764', diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-scan-notice.ts b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-scan-notice.ts index e05d4b2caa7..5b9de759572 100644 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-scan-notice.ts +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-scan-notice.ts @@ -64,36 +64,17 @@ export function formatWorkspaceCleanupScanProgress( ) } -export function formatWorkspaceCleanupReadyToast( - workspaceCount: number, - suggestedCount: number -): string { +/** Reports scan size without classifying the user's work. */ +export function formatWorkspaceCleanupReadyToast(workspaceCount: number): string { if (workspaceCount === 0) { return translate('components.workspace.cleanup.scan.noWorkspaces', 'No workspaces found.') } if (workspaceCount === 1) { - return suggestedCount === 1 - ? translate( - 'components.workspace.cleanup.scan.readyOneOne', - '1 workspace found, with 1 cleanup suggestion.' - ) - : translate( - 'components.workspace.cleanup.scan.readyOneMany', - '1 workspace found, with {{value0}} cleanup suggestions.', - { value0: suggestedCount } - ) + return translate('components.workspace.cleanup.scan.readyOne', '1 workspace found.') } - return suggestedCount === 1 - ? translate( - 'components.workspace.cleanup.scan.readyManyOne', - '{{value0}} workspaces found, with 1 cleanup suggestion.', - { value0: workspaceCount } - ) - : translate( - 'components.workspace.cleanup.scan.readyManyMany', - '{{value0}} workspaces found, with {{value1}} cleanup suggestions.', - { value0: workspaceCount, value1: suggestedCount } - ) + return translate('components.workspace.cleanup.scan.readyMany', '{{value0}} workspaces found.', { + value0: workspaceCount + }) } function formatScanErrorRepoName( diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-selection-model.ts b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-selection-model.ts index d9dc94bb8df..5824ebe1846 100644 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-selection-model.ts +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-selection-model.ts @@ -1,6 +1,4 @@ import { translate } from '@/i18n/i18n' -import type { WorkspaceCleanupCandidate } from '../../../../shared/workspace-cleanup' -import { getWorkspaceCleanupCandidateIdentity } from '../../../../shared/workspace-cleanup-host-identity' export function formatVanishedSelectionNotice(count: number): string { return count === 1 @@ -15,20 +13,18 @@ export function formatVanishedSelectionNotice(count: number): string { ) } -/** Host-qualified identities, so a default selection cannot span two hosts' rows. */ -export function getDefaultSelectedWorkspaceCleanupIdentities( - candidates: readonly WorkspaceCleanupCandidate[], - deletingIdentities: ReadonlySet = new Set() -): Set { - return new Set( - candidates - .filter( - (candidate) => - candidate.selectedByDefault && - !deletingIdentities.has(getWorkspaceCleanupCandidateIdentity(candidate)) +/** Explains selection removed when a facet filter hides rows. */ +export function formatWithheldSelectionNotice(count: number): string { + return count === 1 + ? translate( + 'components.workspace.cleanup.browse.selectionWithheldOne', + '1 selected workspace is hidden by the current filters and was deselected.' + ) + : translate( + 'components.workspace.cleanup.browse.selectionWithheld', + '{{value0}} selected workspaces are hidden by the current filters and were deselected.', + { value0: count } ) - .map((candidate) => getWorkspaceCleanupCandidateIdentity(candidate)) - ) } export function toggleSetMember(current: Set, value: string): Set { diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-sort-header.test.tsx b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-sort-header.test.tsx index 0300865b531..151df522781 100644 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-sort-header.test.tsx +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-sort-header.test.tsx @@ -92,4 +92,29 @@ describe('WorkspaceCleanupSortHeader', () => { container?.querySelector('[role="checkbox"]')?.getAttribute('aria-checked') ).toBe('mixed') }) + it('states how many workspaces select-all would take', () => { + render({ field: 'name', direction: 'asc' }, { selectableCount: 12 }) + + expect(container?.textContent).toContain('Select all 12 safety-checked workspaces') + }) + + it('uses singular copy for one safety-checked workspace', () => { + render({ field: 'name', direction: 'asc' }, { selectableCount: 1 }) + + expect(container?.textContent).toContain('Select 1 safety-checked workspace') + }) + + it('does not report all-selected when the selected rows are not the selectable ones', () => { + const onToggleSelectAll = vi.fn() + render( + { field: 'name', direction: 'asc' }, + { selectableCount: 3, selectedCount: 0, onToggleSelectAll } + ) + + const checkbox = container?.querySelector('[role="checkbox"]') + expect(checkbox?.getAttribute('aria-checked')).toBe('false') + + act(() => (checkbox as HTMLElement | null)?.click()) + expect(onToggleSelectAll).toHaveBeenCalledWith(true) + }) }) diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-sort-header.tsx b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-sort-header.tsx index 2e8de45c1a8..3a3e78429c3 100644 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-sort-header.tsx +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-sort-header.tsx @@ -31,6 +31,17 @@ export function WorkspaceCleanupSortHeader({ }): React.JSX.Element { const allSelected = selectableCount > 0 && selectedCount >= selectableCount const someSelected = selectableCount > 0 && selectedCount > 0 && !allSelected + const selectAllLabel = + selectableCount === 1 + ? translate( + 'components.workspace.cleanup.browse.selectAllCountOne', + 'Select 1 safety-checked workspace' + ) + : translate( + 'components.workspace.cleanup.browse.selectAllCount', + 'Select all {{value0}} safety-checked workspaces', + { value0: selectableCount } + ) return (
- - {translate( - 'components.workspace.cleanup.browse.selectAll', - 'Select all matching workspaces' - )} - + {selectAllLabel}
) } diff --git a/src/renderer/src/components/automations/AutomationPromptDisclosure.test.tsx b/src/renderer/src/components/automations/AutomationPromptDisclosure.test.tsx new file mode 100644 index 00000000000..6ac693aea82 --- /dev/null +++ b/src/renderer/src/components/automations/AutomationPromptDisclosure.test.tsx @@ -0,0 +1,234 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' +import type React from 'react' +import { act, cleanup, render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { Automation } from '../../../../shared/automations-types' +import { i18n } from '@/i18n/i18n' +import { AutomationDetail } from './AutomationDetail' +import { AutomationPromptDisclosure } from './AutomationPromptDisclosure' + +vi.mock('@/components/ui/tooltip', () => ({ + Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}, + TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children}, + TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children} +})) + +let promptNaturalHeight = 0 +let resizeCallback: ResizeObserverCallback | null = null + +class PromptResizeObserver implements ResizeObserver { + constructor(callback: ResizeObserverCallback) { + resizeCallback = callback + } + + disconnect(): void {} + observe(): void {} + unobserve(): void {} +} + +function makeAutomation( + updatedAt: number, + prompt = `Synthetic opening.\n${'Synthetic detail. '.repeat(80)}` +): Automation { + return { + id: 'synthetic-automation', + name: 'Synthetic automation', + prompt, + precheck: null, + agentId: 'codex', + projectId: 'synthetic-project', + executionTargetType: 'local', + executionTargetId: 'local', + schedulerOwner: 'local_host_service', + workspaceMode: 'existing', + workspaceId: 'synthetic-workspace', + baseBranch: null, + reuseSession: false, + timezone: 'UTC', + rrule: 'FREQ=DAILY', + dtstart: 1, + enabled: false, + nextRunAt: 2, + missedRunPolicy: 'run_once_within_grace', + missedRunGraceMinutes: 720, + createdAt: 1, + updatedAt + } +} + +const detailCallbacks = { + onRunNow: vi.fn(), + onEdit: vi.fn(), + onToggle: vi.fn(), + onDelete: vi.fn() +} + +describe('AutomationPromptDisclosure', () => { + beforeEach(async () => { + await i18n.changeLanguage('en') + vi.stubGlobal('ResizeObserver', PromptResizeObserver) + vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation( + function (this: HTMLElement) { + if (this.tagName !== 'P') { + return 0 + } + return this.classList.contains('line-clamp-4') + ? Math.min(promptNaturalHeight, 80) + : promptNaturalHeight + } + ) + vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation( + function (this: HTMLElement) { + return this.tagName === 'P' ? promptNaturalHeight : 0 + } + ) + }) + + afterEach(async () => { + cleanup() + resizeCallback = null + vi.restoreAllMocks() + vi.unstubAllGlobals() + await i18n.changeLanguage('en') + }) + + it('leaves a short prompt fully readable without a disclosure control', () => { + promptNaturalHeight = 40 + render() + + expect(screen.getByText('Synthetic short prompt.')).toBeVisible() + expect(screen.queryByRole('button', { name: 'Show more' })).not.toBeInTheDocument() + }) + + it('labels the prompt correctly in Spanish', async () => { + promptNaturalHeight = 40 + await i18n.changeLanguage('es') + render() + + expect(screen.getByText('Prompt')).toBeVisible() + expect(screen.queryByText('Inmediato')).not.toBeInTheDocument() + }) + + it('reveals the complete long prompt from the keyboard and keeps it selectable', async () => { + promptNaturalHeight = 240 + const prompt = `Synthetic opening.\n${'Synthetic detail. '.repeat(80)}\nSYNTHETIC-END-MARKER` + const user = userEvent.setup() + render() + + const content = screen.getByText(/SYNTHETIC-END-MARKER/) + const toggle = screen.getByRole('button', { name: 'Show more' }) + expect(screen.getAllByText('Prompt')).toHaveLength(1) + expect(content).toHaveClass('line-clamp-4', 'select-text', '[overflow-wrap:anywhere]') + expect(toggle).toHaveAttribute('aria-expanded', 'false') + expect(toggle).toHaveAttribute('aria-controls', content.id) + expect(toggle).toHaveAttribute('data-variant', 'ghost') + expect(toggle).toHaveAttribute('data-size', 'xs') + expect(toggle).not.toHaveClass('h-auto', 'p-0') + + await user.tab() + expect(toggle).toHaveFocus() + await user.keyboard('{Enter}') + + expect(screen.getByRole('button', { name: 'Show less' })).toHaveAttribute( + 'aria-expanded', + 'true' + ) + expect(content).not.toHaveClass('line-clamp-4') + expect(content).toHaveTextContent('SYNTHETIC-END-MARKER') + + await user.click(screen.getByRole('button', { name: 'Show less' })) + expect(screen.getByRole('button', { name: 'Show more' })).toHaveAttribute( + 'aria-expanded', + 'false' + ) + expect(content).toHaveClass('line-clamp-4') + + await user.click(screen.getByRole('button', { name: 'Show more' })) + act(() => resizeCallback?.([], {} as ResizeObserver)) + expect(screen.getByRole('button', { name: 'Show less' })).toHaveFocus() + + await user.click(screen.getByRole('button', { name: 'Show less' })) + expect(screen.getByRole('button', { name: 'Show more' })).toHaveFocus() + expect(content).toHaveClass('line-clamp-4') + }) + + it('offers disclosure after a narrow resize makes the prompt overflow', () => { + promptNaturalHeight = 60 + render() + expect(screen.queryByRole('button', { name: 'Show more' })).not.toBeInTheDocument() + + promptNaturalHeight = 180 + act(() => resizeCallback?.([], {} as ResizeObserver)) + + expect(screen.getByRole('button', { name: 'Show more' })).toBeVisible() + }) + + it('moves focus to the fully visible prompt when resizing removes the disclosure', () => { + promptNaturalHeight = 180 + render() + const content = screen.getByText('Synthetic prompt that fits after widening.') + screen.getByRole('button', { name: 'Show more' }).focus() + + promptNaturalHeight = 60 + act(() => resizeCallback?.([], {} as ResizeObserver)) + + expect(screen.queryByRole('button', { name: 'Show more' })).not.toBeInTheDocument() + expect(content).toHaveFocus() + }) + + it('preserves expansion and focus across unrelated automation updates', async () => { + promptNaturalHeight = 240 + const user = userEvent.setup() + const { rerender } = render( + + ) + + await user.click(screen.getByRole('button', { name: 'Show more' })) + const showLess = screen.getByRole('button', { name: 'Show less' }) + showLess.focus() + + rerender( + + ) + + expect(screen.getByRole('button', { name: 'Show less' })).toHaveFocus() + + promptNaturalHeight = 40 + rerender( + + ) + + expect(screen.getByText('Synthetic replacement prompt.')).toBeVisible() + expect(screen.queryByRole('button', { name: 'Show less' })).not.toBeInTheDocument() + }) +}) diff --git a/src/renderer/src/components/automations/AutomationPromptDisclosure.tsx b/src/renderer/src/components/automations/AutomationPromptDisclosure.tsx new file mode 100644 index 00000000000..b5eefc7dd74 --- /dev/null +++ b/src/renderer/src/components/automations/AutomationPromptDisclosure.tsx @@ -0,0 +1,93 @@ +import React, { useCallback, useEffect, useId, useRef, useState } from 'react' +import { Button } from '@/components/ui/button' +import { cn } from '@/lib/utils' +import { translate } from '@/i18n/i18n' + +export function AutomationPromptDisclosure({ prompt }: { prompt: string }): React.JSX.Element { + const contentId = useId() + const expandedRef = useRef(false) + const toggleRef = useRef(null) + const [promptElement, setPromptElement] = useState(null) + const [expanded, setExpanded] = useState(false) + const [overflows, setOverflows] = useState(false) + + const measureOverflow = useCallback((element: HTMLParagraphElement) => { + const nextOverflows = element.scrollHeight > element.clientHeight + 1 + if (!nextOverflows && document.activeElement === toggleRef.current) { + element.focus({ preventScroll: true }) + } + setOverflows((current) => (current === nextOverflows ? current : nextOverflows)) + }, []) + + useEffect(() => { + if (!promptElement || expanded) { + return + } + + const updateOverflow = () => { + if (!expandedRef.current) { + measureOverflow(promptElement) + } + } + updateOverflow() + if (typeof ResizeObserver === 'undefined') { + window.addEventListener('resize', updateOverflow) + return () => window.removeEventListener('resize', updateOverflow) + } + + const observer = new ResizeObserver(updateOverflow) + observer.observe(promptElement) + return () => observer.disconnect() + }, [expanded, measureOverflow, promptElement]) + + const toggleExpanded = (): void => { + const nextExpanded = !expanded + expandedRef.current = nextExpanded + setExpanded(nextExpanded) + } + + return ( +
+
+
+ {translate('auto.components.automations.AutomationEditorDialog.058c23cb3f', 'Prompt')} +
+ {overflows || expanded ? ( + + ) : null} +
+
+

+ {prompt} +

+
+
+ ) +} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 291cc9395de..c117b08e172 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -15008,6 +15008,10 @@ "0e1de0358b": "Month", "77e96bded6": "Weekday" }, + "AutomationPromptDisclosure": { + "showLess": "Show less", + "showMore": "Show more" + }, "AutomationDetail": { "007c8ad874": "Prompt", "a1d52c2189": "Usage coverage", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 27136599f39..9f1ef9ca5cc 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -13612,6 +13612,10 @@ "0e1de0358b": "Mes", "77e96bded6": "Día de la semana" }, + "AutomationPromptDisclosure": { + "showLess": "Mostrar menos", + "showMore": "Mostrar más" + }, "AutomationDetail": { "007c8ad874": "Inmediato", "a1d52c2189": "Cobertura de uso", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 1a2f3e9f95a..508c9d9bec3 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -13612,6 +13612,10 @@ "0e1de0358b": "月", "77e96bded6": "曜日" }, + "AutomationPromptDisclosure": { + "showLess": "折りたたむ", + "showMore": "さらに表示" + }, "AutomationDetail": { "007c8ad874": "プロンプト", "a1d52c2189": "使用範囲", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 40e5469d0ae..2384a7996fc 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -13641,6 +13641,10 @@ "0e1de0358b": "월", "77e96bded6": "요일" }, + "AutomationPromptDisclosure": { + "showLess": "접기", + "showMore": "더 보기" + }, "AutomationDetail": { "007c8ad874": "프롬프트", "a1d52c2189": "사용 범위", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 6ad65d655e8..fdd53f16ed9 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -13632,6 +13632,10 @@ "0e1de0358b": "月", "77e96bded6": "星期" }, + "AutomationPromptDisclosure": { + "showLess": "收起", + "showMore": "显示更多" + }, "AutomationDetail": { "007c8ad874": "提示词", "a1d52c2189": "使用范围", diff --git a/tests/e2e/automation-prompt-disclosure.spec.ts b/tests/e2e/automation-prompt-disclosure.spec.ts new file mode 100644 index 00000000000..4137f8495c4 --- /dev/null +++ b/tests/e2e/automation-prompt-disclosure.spec.ts @@ -0,0 +1,158 @@ +import { test, expect } from './helpers/orca-app' +import { waitForSessionReady } from './helpers/store' + +const SHORT_NAME = 'synthetic-short-prompt-demo' +const RESIZE_NAME = 'synthetic-resize-prompt-demo' +const LONG_NAME = 'visual-proof-long-prompt-demo' +const END_MARKER = 'SYNTHETIC-END-MARKER' +const RESIZE_PROMPT = `Synthetic resize focus validation. ${'placeholder '.repeat(24)}` + +test('automation detail keeps short prompts readable and reveals a very long prompt at narrow width', async ({ + orcaPage +}) => { + await waitForSessionReady(orcaPage) + await orcaPage.setViewportSize({ width: 820, height: 700 }) + + await orcaPage.evaluate( + async ({ shortName, resizeName, resizePrompt, longName, endMarker }) => { + const store = window.__store + if (!store) { + throw new Error('window.__store is not available') + } + const repo = store.getState().repos[0] + if (!repo) { + throw new Error('Seeded test repo is not available') + } + const base = { + agentId: 'codex' as const, + projectId: repo.id, + workspaceMode: 'new_per_run' as const, + reuseSession: false, + timezone: 'UTC', + rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', + dtstart: Date.now(), + enabled: false, + missedRunGraceMinutes: 720 + } + await window.api.automations.create({ + ...base, + name: shortName, + prompt: 'Synthetic short prompt.' + }) + await window.api.automations.create({ + ...base, + name: longName, + prompt: [ + 'Synthetic prompt preview validation only.', + '', + ...Array.from( + { length: 20 }, + (_, index) => + `Synthetic step ${index + 1}: inspect placeholder input and summarize placeholder output.` + ), + '', + `UNBROKEN_SYNTHETIC_${'X'.repeat(240)}`, + '', + endMarker + ].join('\n') + }) + await window.api.automations.create({ + ...base, + name: resizeName, + prompt: resizePrompt + }) + store.getState().openAutomationsPage() + }, + { + shortName: SHORT_NAME, + resizeName: RESIZE_NAME, + resizePrompt: RESIZE_PROMPT, + longName: LONG_NAME, + endMarker: END_MARKER + } + ) + + await orcaPage.getByRole('button', { name: new RegExp(`^${SHORT_NAME}`) }).click() + await expect(orcaPage.getByText('Synthetic short prompt.')).toBeVisible() + await expect(orcaPage.getByRole('button', { name: 'Show more' })).toHaveCount(0) + + await orcaPage.getByRole('button', { name: 'All automations' }).click() + await orcaPage.getByRole('button', { name: new RegExp(`^${RESIZE_NAME}`) }).click() + const resizePrompt = orcaPage.getByText(RESIZE_PROMPT) + const resizeToggle = orcaPage.getByRole('button', { name: 'Show more' }) + await expect(resizeToggle).toBeVisible() + await resizeToggle.focus() + await orcaPage.setViewportSize({ width: 1400, height: 700 }) + await expect(resizeToggle).toHaveCount(0) + await expect(resizePrompt).toBeFocused() + + await orcaPage.setViewportSize({ width: 820, height: 700 }) + await orcaPage.getByRole('button', { name: 'All automations' }).click() + await orcaPage.getByRole('button', { name: new RegExp(`^${LONG_NAME}`) }).click() + + const prompt = orcaPage.getByText(new RegExp(END_MARKER)) + const showMore = orcaPage.getByRole('button', { name: 'Show more' }) + await expect(showMore).toBeVisible() + expect(await showMore.getAttribute('aria-controls')).toBe(await prompt.getAttribute('id')) + const collapsedMetrics = await prompt.evaluate((element) => ({ + clientHeight: element.clientHeight, + scrollHeight: element.scrollHeight, + lineClamp: getComputedStyle(element).webkitLineClamp + })) + expect(collapsedMetrics.scrollHeight).toBeGreaterThan(collapsedMetrics.clientHeight) + expect(collapsedMetrics.lineClamp).toBe('4') + + await showMore.focus() + await orcaPage.keyboard.press('Enter') + await expect(orcaPage.getByRole('button', { name: 'Show less' })).toBeFocused() + + const expandedMetrics = await prompt.evaluate((element) => ({ + clientHeight: element.clientHeight, + scrollHeight: element.scrollHeight, + scrollWidth: element.scrollWidth, + clientWidth: element.clientWidth, + lineClamp: getComputedStyle(element).webkitLineClamp, + overflowWrap: getComputedStyle(element).overflowWrap + })) + expect(expandedMetrics.clientHeight).toBeGreaterThan(80) + expect(expandedMetrics.scrollHeight).toBeLessThanOrEqual(expandedMetrics.clientHeight + 1) + expect(expandedMetrics.scrollWidth).toBeLessThanOrEqual(expandedMetrics.clientWidth + 1) + expect(expandedMetrics.lineClamp).toBe('none') + expect(expandedMetrics.overflowWrap).toBe('anywhere') + + const markerProof = await prompt.evaluate(async (element, marker) => { + const text = element.firstChild + if (!(text instanceof Text)) { + throw new Error('Prompt text node is unavailable') + } + const start = text.data.indexOf(marker) + if (start === -1) { + throw new Error('Prompt end marker is unavailable') + } + const range = document.createRange() + range.setStart(text, start) + range.setEnd(text, start + marker.length) + const selection = window.getSelection() + selection?.removeAllRanges() + selection?.addRange(range) + const scrollContainer = element.closest('[role="tabpanel"]') + if (!(scrollContainer instanceof HTMLElement)) { + throw new Error('Automation overview scroll container is unavailable') + } + scrollContainer.scrollTop += + range.getBoundingClientRect().bottom - scrollContainer.getBoundingClientRect().bottom + 16 + await new Promise(requestAnimationFrame) + const markerRect = range.getBoundingClientRect() + const containerRect = scrollContainer.getBoundingClientRect() + return { + selectedText: selection?.toString(), + markerTop: markerRect.top, + markerBottom: markerRect.bottom, + visibleTop: containerRect.top, + visibleBottom: containerRect.bottom + } + }, END_MARKER) + expect(markerProof.selectedText).toBe(END_MARKER) + expect(markerProof.markerTop).toBeGreaterThanOrEqual(markerProof.visibleTop) + expect(markerProof.markerBottom).toBeLessThanOrEqual(markerProof.visibleBottom) +}) From 95633a78834ce6182a503a079aeafe7e15feba8b Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sun, 23 Aug 2026 22:18:39 -0700 Subject: [PATCH 09/13] Fix stale task-source flashes in new workspace input (#16145) * fix(new-workspace): prevent stale GitHub URL selection * fix(new-workspace): guard all task URL transitions * test(e2e): make task URL frame proof runner-safe * fix(new-workspace): guard Enter during task URL lookup --- .../new-workspace/SmartWorkspaceNameField.tsx | 27 +- .../smart-workspace-source-results.test.ts | 33 ++ .../smart-workspace-source-results.ts | 80 ++-- ...smart-workspace-url-source-results.test.ts | 210 +++++++++++ .../smart-workspace-url-source-results.ts | 126 +++++++ .../github-url-smart-input-transition.spec.ts | 351 ++++++++++++++++++ 6 files changed, 794 insertions(+), 33 deletions(-) create mode 100644 src/shared/new-workspace/smart-workspace-url-source-results.test.ts create mode 100644 src/shared/new-workspace/smart-workspace-url-source-results.ts create mode 100644 tests/e2e/github-url-smart-input-transition.spec.ts diff --git a/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx b/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx index 58e771477dd..47040268575 100644 --- a/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx +++ b/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx @@ -61,6 +61,7 @@ import { getVisibleBranchResults, getVisibleHeldProviderResults, isBlockingJiraUrlIntent, + isBlockingTaskUrlResolution, type SmartNameMode, type SmartWorkspaceSourceRow } from './smart-workspace-source-results' @@ -639,6 +640,20 @@ export default function SmartWorkspaceNameField({ () => (sourceQueryWithinLimit ? parseGitHubIssueOrPRLink(debouncedQuery) : null), [debouncedQuery, sourceQueryWithinLimit] ) + const githubUrlIntent = useMemo( + () => + isSmartWorkspaceSourceQueryWithinLimit(value) && (mode === 'smart' || mode === 'github') + ? parseGitHubIssueOrPRLink(value) + : null, + [mode, value] + ) + const gitlabUrlIntent = useMemo( + () => + isSmartWorkspaceSourceQueryWithinLimit(value) && (mode === 'smart' || mode === 'gitlab') + ? parseGitLabIssueOrMRLink(value) + : null, + [mode, value] + ) const linearUrlIntent = useMemo( () => parseBoundedSmartWorkspaceLinearIssueUrlIntent(value), [value] @@ -1270,12 +1285,14 @@ export default function SmartWorkspaceNameField({ value, debouncedQuery }), + githubUrlIntent, gitlabAvailable: gitlabSourceAvailable, gitlabItems: getVisibleHeldProviderResults({ items: gitlabItems, value, debouncedQuery }), + gitlabUrlIntent, jiraIntent: jiraSource.intent, jiraIssue: jiraSource.issue, jiraIssues: getVisibleHeldProviderResults({ @@ -1302,8 +1319,10 @@ export default function SmartWorkspaceNameField({ branchResultsSource, debouncedQuery, githubItems, + githubUrlIntent, gitlabSourceAvailable, gitlabItems, + gitlabUrlIntent, jiraSource.accountChoices, jiraSource.intent, jiraSource.issue, @@ -1369,6 +1388,12 @@ export default function SmartWorkspaceNameField({ linearAvailable && sourceIntent !== 'linear' && (linearLoading || settledLinearUrlQuery !== linearQuery.trim()) + const blockingTaskUrlResolution = isBlockingTaskUrlResolution({ + sourceIntent: sourceIntent === 'github' || sourceIntent === 'gitlab' ? sourceIntent : null, + isQueryStale, + githubLoading, + gitlabLoading + }) const resolvedCommandValue = resolveSmartWorkspaceCommandValue({ currentValue: commandValue, @@ -1975,7 +2000,7 @@ export default function SmartWorkspaceNameField({ handleEmojiSelect(selectedEmojiSuggestion) return } - if (unresolvedLinearUrlIntent) { + if (unresolvedLinearUrlIntent || blockingTaskUrlResolution) { event.preventDefault() return } diff --git a/src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts b/src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts index 780800bb9a4..e78b6d5d76c 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts +++ b/src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts @@ -7,6 +7,7 @@ import { getVisibleBranchResults, getVisibleHeldProviderResults, isBlockingJiraUrlIntent, + isBlockingTaskUrlResolution, shouldHoldSourceResultsForQuery } from './smart-workspace-source-results' import { @@ -684,6 +685,38 @@ describe('Linear issue source input', () => { }) }) +describe('Task URL Enter protection', () => { + it('blocks Enter while a pasted GitHub or GitLab URL is resolving', () => { + expect( + isBlockingTaskUrlResolution({ + sourceIntent: 'github', + isQueryStale: true, + githubLoading: false, + gitlabLoading: false + }) + ).toBe(true) + expect( + isBlockingTaskUrlResolution({ + sourceIntent: 'gitlab', + isQueryStale: false, + githubLoading: false, + gitlabLoading: true + }) + ).toBe(true) + }) + + it('keeps the workspace-name fallback after lookup settles without a match', () => { + expect( + isBlockingTaskUrlResolution({ + sourceIntent: 'github', + isQueryStale: false, + githubLoading: false, + gitlabLoading: false + }) + ).toBe(false) + }) +}) + describe('Jira issue search', () => { it('keeps valid Jira URL intent blocking in both Smart and Jira modes', () => { const firstUrl = 'https://company.atlassian.net/browse/ORCA-1' diff --git a/src/shared/new-workspace/smart-workspace-source-results.ts b/src/shared/new-workspace/smart-workspace-source-results.ts index 40de888f150..39bd8ae3b54 100644 --- a/src/shared/new-workspace/smart-workspace-source-results.ts +++ b/src/shared/new-workspace/smart-workspace-source-results.ts @@ -5,10 +5,11 @@ import type { LinearIssue } from '../linear/issue-types' import type { LinearCollectionResult } from '../linear/workspace-types' import type { BaseRefSearchResult } from '../repo-types' import { JIRA_ISSUE_KEY_PATTERN, parseJiraIssueUrl } from '../jira-issue-url' +import type { GitHubIssueOrPRLink } from '../github/links' import { - isSmartWorkspaceLinearIssueIntentMatch, - parseBoundedSmartWorkspaceLinearIssueUrlIntent -} from './smart-workspace-linear-intent' + buildSmartWorkspaceUrlSourceRows, + type SmartWorkspaceGitLabUrlIntent +} from './smart-workspace-url-source-results' import { isSmartWorkspaceSourceQueryWithinLimit } from './smart-workspace-source-query' export { @@ -59,10 +60,31 @@ export function isBlockingJiraUrlIntent(mode: SmartNameMode, value: string): boo return (mode === 'smart' || mode === 'jira') && parseJiraIssueUrl(value) !== null } +export function isBlockingTaskUrlResolution({ + sourceIntent, + isQueryStale, + githubLoading, + gitlabLoading +}: { + sourceIntent: 'github' | 'gitlab' | null + isQueryStale: boolean + githubLoading: boolean + gitlabLoading: boolean +}): boolean { + if (sourceIntent === null) { + return false + } + return isQueryStale || (sourceIntent === 'github' ? githubLoading : gitlabLoading) +} + function toJiraSourceRow(issue: JiraIssue): SmartWorkspaceSourceRow { return { kind: 'jira', value: `jira-${issue.siteId ?? ''}-${issue.key}`, issue } } +function toGitHubSourceRow(item: GitHubWorkItem): SmartWorkspaceSourceRow { + return { kind: 'github', value: `github-${item.repoId}-${item.type}-${item.number}`, item } +} + export function getBranchSearchRequest({ branchesEnabled, disabled, @@ -186,8 +208,10 @@ export function shouldHoldSourceResultsForQuery({ export function buildSmartWorkspaceSourceRows({ branches, githubItems, + githubUrlIntent, gitlabAvailable, gitlabItems, + gitlabUrlIntent, jiraIntent = false, jiraIssue, jiraIssues = [], @@ -200,8 +224,10 @@ export function buildSmartWorkspaceSourceRows({ }: { branches: BaseRefSearchResult[] githubItems: GitHubWorkItem[] + githubUrlIntent?: GitHubIssueOrPRLink | null gitlabAvailable: boolean gitlabItems: GitLabWorkItem[] + gitlabUrlIntent?: SmartWorkspaceGitLabUrlIntent | null jiraIntent?: boolean jiraIssue?: JiraIssue | null jiraIssues?: JiraIssue[] @@ -219,34 +245,30 @@ export function buildSmartWorkspaceSourceRows({ if (!isSmartWorkspaceSourceQueryWithinLimit(value)) { return [] } - const trimmed = value.trim() - const nextRows: SmartWorkspaceSourceRow[] = [] const resolvedLinearIssues = Array.isArray(linearIssues) ? linearIssues : Array.isArray(linearIssues?.items) ? linearIssues.items : [] - const linearUrlIntent = parseBoundedSmartWorkspaceLinearIssueUrlIntent(trimmed) - if ( - linearUrlIntentOwnsResults && - linearAvailable && - linearUrlIntent && - (mode === 'smart' || mode === 'linear') - ) { - const linearRows = resolvedLinearIssues - .filter((issue) => isSmartWorkspaceLinearIssueIntentMatch(linearUrlIntent, issue)) - .map((issue) => ({ - kind: 'linear' as const, - value: `linear-${issue.id}`, - issue - })) - .slice(0, resultLimit) - // Why: keep "use as workspace name" available; sourceIntent focuses the issue. - if (trimmed && mode === 'smart') { - return [{ kind: 'use-name' as const, value: 'use-name', name: trimmed }, ...linearRows] - } - return linearRows + // Why: a full task URL is unambiguous, so unrelated held rows must never remain selectable. + const urlSourceRows = buildSmartWorkspaceUrlSourceRows({ + githubItems, + githubUrlIntent, + gitlabAvailable, + gitlabItems, + gitlabUrlIntent, + linearAvailable, + linearIssues: resolvedLinearIssues, + linearUrlIntentOwnsResults, + mode, + resultLimit, + value + }) + if (urlSourceRows !== null) { + return urlSourceRows } + const trimmed = value.trim() + const nextRows: SmartWorkspaceSourceRow[] = [] if (trimmed && mode === 'smart') { // Why: stable cmdk value — embedding the query remounted the row every keystroke. nextRows.push({ kind: 'use-name', value: 'use-name', name: trimmed }) @@ -255,13 +277,7 @@ export function buildSmartWorkspaceSourceRows({ return nextRows } if (mode === 'smart' || mode === 'github') { - nextRows.push( - ...githubItems.map((item) => ({ - kind: 'github' as const, - value: `github-${item.repoId}-${item.type}-${item.number}`, - item - })) - ) + nextRows.push(...githubItems.map(toGitHubSourceRow)) } if (gitlabAvailable && (mode === 'smart' || mode === 'gitlab')) { nextRows.push( diff --git a/src/shared/new-workspace/smart-workspace-url-source-results.test.ts b/src/shared/new-workspace/smart-workspace-url-source-results.test.ts new file mode 100644 index 00000000000..83a47854545 --- /dev/null +++ b/src/shared/new-workspace/smart-workspace-url-source-results.test.ts @@ -0,0 +1,210 @@ +import { describe, expect, it } from 'vitest' +import { buildSmartWorkspaceUrlSourceRows } from './smart-workspace-url-source-results' + +describe('smart workspace URL-owned source rows', () => { + it('hides unrelated held results while a full GitHub URL resolves', () => { + const targetUrl = 'https://github.com/acme/widgets/issues/42' + const staleItem = { + id: 'issue-17', + type: 'issue' as const, + number: 17, + title: 'Wrong cached issue', + state: 'open' as const, + url: 'https://github.com/acme/widgets/issues/17', + labels: [], + updatedAt: '2026-08-01T00:00:00.000Z', + author: 'octocat', + repoId: 'repo-1' + } + + expect( + buildSmartWorkspaceUrlSourceRows({ + mode: 'smart', + value: targetUrl, + githubUrlIntent: { + slug: { owner: 'acme', repo: 'widgets', host: 'github.com' }, + type: 'issue', + number: 42 + }, + githubItems: [ + staleItem, + { + ...staleItem, + id: 'same-number-other-repo', + number: 42, + url: 'https://github.com/acme/other-repo/issues/42' + }, + { + ...staleItem, + id: 'same-number-pull-request', + type: 'pr', + number: 42, + url: 'https://github.com/acme/widgets/pull/42' + } + ], + gitlabItems: [], + linearIssues: [], + gitlabAvailable: false, + linearAvailable: false, + linearUrlIntentOwnsResults: true, + resultLimit: 12 + }) + ).toEqual([{ kind: 'use-name', value: 'use-name', name: targetUrl }]) + }) + + it('shows only the exact GitHub URL result after lookup settles', () => { + const targetUrl = 'https://github.com/acme/widgets/issues/42' + const exactItem = { + id: 'issue-42', + type: 'issue' as const, + number: 42, + title: 'Exact pasted issue', + state: 'open' as const, + url: targetUrl, + labels: [], + updatedAt: '2026-08-02T00:00:00.000Z', + author: 'octocat', + repoId: 'repo-1' + } + + expect( + buildSmartWorkspaceUrlSourceRows({ + mode: 'smart', + value: targetUrl, + githubUrlIntent: { + slug: { owner: 'ACME', repo: 'Widgets', host: 'GitHub.com' }, + type: 'issue', + number: 42 + }, + githubItems: [ + { ...exactItem, id: 'issue-17', number: 17, url: `${targetUrl.slice(0, -2)}17` }, + exactItem + ], + gitlabItems: [], + linearIssues: [], + gitlabAvailable: false, + linearAvailable: false, + linearUrlIntentOwnsResults: true, + resultLimit: 12 + }) + ).toEqual([ + { kind: 'use-name', value: 'use-name', name: targetUrl }, + { kind: 'github', value: 'github-repo-1-issue-42', item: exactItem } + ]) + }) + + it('hides unrelated held results while a full GitLab URL resolves', () => { + const targetUrl = 'https://gitlab.example.test/acme/widgets/-/issues/42' + const staleItem = { + id: 'mr-17', + type: 'mr' as const, + number: 17, + title: 'Wrong cached merge request', + state: 'opened' as const, + url: 'https://gitlab.example.test/acme/widgets/-/merge_requests/17', + labels: [], + updatedAt: '2026-08-01T00:00:00.000Z', + author: 'gitlab-user', + repoId: 'repo-1' + } + + expect( + buildSmartWorkspaceUrlSourceRows({ + mode: 'smart', + value: targetUrl, + gitlabUrlIntent: { + slug: { host: 'gitlab.example.test', path: 'acme/widgets' }, + type: 'issue', + number: 42 + }, + githubItems: [], + gitlabItems: [ + staleItem, + { + ...staleItem, + id: 'same-number-other-project', + type: 'issue', + number: 42, + url: 'https://gitlab.example.test/acme/other/-/issues/42' + }, + { + ...staleItem, + id: 'same-project-other-host', + type: 'issue', + number: 42, + url: 'https://gitlab.other.test/acme/widgets/-/issues/42' + } + ], + linearIssues: [], + gitlabAvailable: true, + linearAvailable: false, + linearUrlIntentOwnsResults: true, + resultLimit: 12 + }) + ).toEqual([{ kind: 'use-name', value: 'use-name', name: targetUrl }]) + }) + + it('shows only the exact GitLab URL result after lookup settles', () => { + const targetUrl = 'https://gitlab.example.test/acme/widgets/-/issues/42' + const exactItem = { + id: 'issue-42', + type: 'issue' as const, + number: 42, + title: 'Exact pasted issue', + state: 'opened' as const, + url: targetUrl, + labels: [], + updatedAt: '2026-08-02T00:00:00.000Z', + author: 'gitlab-user', + repoId: 'repo-1' + } + + expect( + buildSmartWorkspaceUrlSourceRows({ + mode: 'smart', + value: targetUrl, + gitlabUrlIntent: { + slug: { host: 'GITLAB.EXAMPLE.TEST', path: 'Acme/Widgets' }, + type: 'issue', + number: 42 + }, + githubItems: [], + gitlabItems: [ + { + ...exactItem, + id: 'issue-17', + number: 17, + url: 'https://gitlab.example.test/acme/widgets/-/issues/17' + }, + exactItem + ], + linearIssues: [], + gitlabAvailable: true, + linearAvailable: false, + linearUrlIntentOwnsResults: true, + resultLimit: 12 + }) + ).toEqual([ + { kind: 'use-name', value: 'use-name', name: targetUrl }, + { kind: 'gitlab', value: 'gitlab-repo-1-issue-42', item: exactItem } + ]) + }) + + it('hides held provider rows when a Linear URL is recognized but disconnected', () => { + const issueUrl = 'https://linear.app/stably/issue/STA-4084/restore-shell-integration' + + expect( + buildSmartWorkspaceUrlSourceRows({ + mode: 'smart', + value: issueUrl, + githubItems: [{ repoId: 'repo-1', type: 'issue', number: 17 } as never], + gitlabItems: [{ repoId: 'repo-1', type: 'mr', number: 17 } as never], + linearIssues: [], + gitlabAvailable: true, + linearAvailable: false, + linearUrlIntentOwnsResults: true, + resultLimit: 12 + }) + ).toEqual([{ kind: 'use-name', value: 'use-name', name: issueUrl }]) + }) +}) diff --git a/src/shared/new-workspace/smart-workspace-url-source-results.ts b/src/shared/new-workspace/smart-workspace-url-source-results.ts new file mode 100644 index 00000000000..a1aa75b82f0 --- /dev/null +++ b/src/shared/new-workspace/smart-workspace-url-source-results.ts @@ -0,0 +1,126 @@ +import { parseGitHubIssueOrPRLink, type GitHubIssueOrPRLink } from '../github/links' +import { githubRepoIdentityKey } from '../github/repository-identity-key' +import type { GitHubWorkItem } from '../github/work-item-types' +import type { GitLabWorkItem } from '../gitlab-types' +import type { LinearIssue } from '../linear/issue-types' +import { parseGitLabIssueOrMRLink } from './gitlab-links' +import { + isSmartWorkspaceLinearIssueIntentMatch, + parseBoundedSmartWorkspaceLinearIssueUrlIntent +} from './smart-workspace-linear-intent' + +export type SmartWorkspaceGitLabUrlIntent = NonNullable> + +type SmartWorkspaceUrlSourceMode = + | 'smart' + | 'github' + | 'gitlab' + | 'branches' + | 'linear' + | 'jira' + | 'text' + +export type SmartWorkspaceUrlSourceRow = + | { kind: 'use-name'; value: 'use-name'; name: string } + | { kind: 'github'; value: string; item: GitHubWorkItem } + | { kind: 'gitlab'; value: string; item: GitLabWorkItem } + | { kind: 'linear'; value: string; issue: LinearIssue } + +function toGitHubSourceRow(item: GitHubWorkItem): SmartWorkspaceUrlSourceRow { + return { kind: 'github', value: `github-${item.repoId}-${item.type}-${item.number}`, item } +} + +function withSmartNameFallback( + mode: SmartWorkspaceUrlSourceMode, + name: string, + rows: SmartWorkspaceUrlSourceRow[] +): SmartWorkspaceUrlSourceRow[] { + return name && mode === 'smart' ? [{ kind: 'use-name', value: 'use-name', name }, ...rows] : rows +} + +function isGitHubLinkIntentMatch(intent: GitHubIssueOrPRLink, item: GitHubWorkItem): boolean { + const itemLink = parseGitHubIssueOrPRLink(item.url) + return ( + itemLink !== null && + itemLink.type === intent.type && + itemLink.number === intent.number && + githubRepoIdentityKey(itemLink.slug) === githubRepoIdentityKey(intent.slug) + ) +} + +function isGitLabLinkIntentMatch( + intent: SmartWorkspaceGitLabUrlIntent, + item: GitLabWorkItem +): boolean { + const itemLink = parseGitLabIssueOrMRLink(item.url) + return ( + itemLink !== null && + itemLink.type === intent.type && + itemLink.number === intent.number && + itemLink.slug.host.toLowerCase() === intent.slug.host.toLowerCase() && + itemLink.slug.path.toLowerCase() === intent.slug.path.toLowerCase() + ) +} + +export function buildSmartWorkspaceUrlSourceRows({ + githubItems, + githubUrlIntent, + gitlabAvailable, + gitlabItems, + gitlabUrlIntent, + linearAvailable, + linearIssues, + linearUrlIntentOwnsResults, + mode, + resultLimit, + value +}: { + githubItems: GitHubWorkItem[] + githubUrlIntent?: GitHubIssueOrPRLink | null + gitlabAvailable: boolean + gitlabItems: GitLabWorkItem[] + gitlabUrlIntent?: SmartWorkspaceGitLabUrlIntent | null + linearAvailable: boolean + linearIssues: LinearIssue[] + linearUrlIntentOwnsResults: boolean + mode: SmartWorkspaceUrlSourceMode + resultLimit: number + value: string +}): SmartWorkspaceUrlSourceRow[] | null { + const trimmed = value.trim() + if (githubUrlIntent && (mode === 'smart' || mode === 'github')) { + const rows = githubItems + .filter((item) => isGitHubLinkIntentMatch(githubUrlIntent, item)) + .map(toGitHubSourceRow) + .slice(0, resultLimit) + return withSmartNameFallback(mode, trimmed, rows) + } + if (gitlabUrlIntent && (mode === 'smart' || mode === 'gitlab')) { + const rows = gitlabAvailable + ? gitlabItems + .filter((item) => isGitLabLinkIntentMatch(gitlabUrlIntent, item)) + .map((item) => ({ + kind: 'gitlab' as const, + value: `gitlab-${item.repoId}-${item.type}-${item.number}`, + item + })) + .slice(0, resultLimit) + : [] + return withSmartNameFallback(mode, trimmed, rows) + } + const linearUrlIntent = parseBoundedSmartWorkspaceLinearIssueUrlIntent(trimmed) + if (linearUrlIntentOwnsResults && linearUrlIntent && (mode === 'smart' || mode === 'linear')) { + const rows = linearAvailable + ? linearIssues + .filter((issue) => isSmartWorkspaceLinearIssueIntentMatch(linearUrlIntent, issue)) + .map((issue) => ({ + kind: 'linear' as const, + value: `linear-${issue.id}`, + issue + })) + .slice(0, resultLimit) + : [] + return withSmartNameFallback(mode, trimmed, rows) + } + return null +} diff --git a/tests/e2e/github-url-smart-input-transition.spec.ts b/tests/e2e/github-url-smart-input-transition.spec.ts new file mode 100644 index 00000000000..637620eaa89 --- /dev/null +++ b/tests/e2e/github-url-smart-input-transition.spec.ts @@ -0,0 +1,351 @@ +import type { ElectronApplication, Locator, Page } from '@stablyai/playwright-test' +import type { GitHubWorkItem } from '../../src/shared/github/work-item-types' +import type { GitLabWorkItem } from '../../src/shared/gitlab-types' +import { test, expect } from './helpers/orca-app' +import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' + +const TARGET_URL = 'https://github.com/stablyai/orca/issues/4242' +const WRONG_TITLE = 'Wrong cached issue' +const TARGET_TITLE = 'Exact pasted issue' +const GITLAB_TARGET_URL = 'https://gitlab.example.test/stablyai/orca/-/merge_requests/4242' +const GITLAB_WRONG_TITLE = 'Wrong cached merge request' +const GITLAB_TARGET_TITLE = 'Exact pasted merge request' +const MIN_PASTED_FRAMES = 2 +const TRANSITION_FRAME_LIMIT = 600 + +const WRONG_ITEM: GitHubWorkItem = { + id: 'issue-17', + type: 'issue', + number: 17, + title: WRONG_TITLE, + state: 'open', + url: 'https://github.com/stablyai/orca/issues/17', + labels: [], + updatedAt: '2026-08-01T00:00:00.000Z', + author: 'e2e', + repoId: 'e2e-repo' +} + +const TARGET_ITEM: GitHubWorkItem = { + ...WRONG_ITEM, + id: 'issue-4242', + number: 4242, + title: TARGET_TITLE, + url: TARGET_URL, + updatedAt: '2026-08-02T00:00:00.000Z' +} + +const GITLAB_WRONG_ITEM: GitLabWorkItem = { + id: 'mr-17', + type: 'mr', + number: 17, + title: GITLAB_WRONG_TITLE, + state: 'opened', + url: 'https://gitlab.example.test/stablyai/orca/-/merge_requests/17', + labels: [], + updatedAt: '2026-08-01T00:00:00.000Z', + author: 'e2e', + repoId: 'e2e-repo' +} + +const GITLAB_TARGET_ITEM: GitLabWorkItem = { + ...GITLAB_WRONG_ITEM, + id: 'mr-4242', + number: 4242, + title: GITLAB_TARGET_TITLE, + url: GITLAB_TARGET_URL, + updatedAt: '2026-08-02T00:00:00.000Z' +} + +type TransitionFrame = { + value: string + wrongVisible: boolean + wrongSelected: boolean + targetVisible: boolean + targetSelected: boolean +} + +function pasteChord(): string { + return process.platform === 'darwin' ? 'Meta+V' : 'Control+V' +} + +async function startTransitionCapture( + page: Page, + frameKey: string, + wrongTitle: string, + targetTitle: string +): Promise { + await page.evaluate( + ({ frameKey, frameLimit, wrongTitle, targetTitle }) => { + const frames: TransitionFrame[] = [] + const capture = (): void => { + const input = document.querySelector('[data-workspace-name-input="true"]') + const options = [...document.querySelectorAll('[role="option"]')] + const wrong = options.find((option) => option.textContent?.includes(wrongTitle)) + const target = options.find((option) => option.textContent?.includes(targetTitle)) + frames.push({ + value: input?.value ?? '', + wrongVisible: Boolean(wrong && wrong.getClientRects().length > 0), + wrongSelected: wrong?.dataset.selected === 'true', + targetVisible: Boolean(target && target.getClientRects().length > 0), + targetSelected: target?.dataset.selected === 'true' + }) + if (frames.length < frameLimit) { + requestAnimationFrame(capture) + } + } + Reflect.set(window, frameKey, frames) + capture() + }, + { frameKey, frameLimit: TRANSITION_FRAME_LIMIT, wrongTitle, targetTitle } + ) +} + +async function readTransitionFrames(page: Page, frameKey: string): Promise { + return page.evaluate((key) => Reflect.get(window, key) as TransitionFrame[], frameKey) +} + +async function expectLookupHeldWithoutStaleRow( + page: Page, + frameKey: string, + targetUrl: string, + wrongOption: Locator, + targetOption: Locator +): Promise { + await expect + .poll(async () => { + const frames = await readTransitionFrames(page, frameKey) + return frames.filter((frame) => frame.value === targetUrl).length + }) + .toBeGreaterThanOrEqual(MIN_PASTED_FRAMES) + await expect(wrongOption).toHaveCount(0) + await expect(targetOption).toHaveCount(0) +} + +async function expectExactTargetAfterLookup( + page: Page, + frameKey: string, + targetUrl: string, + targetOption: Locator +): Promise { + await expect(targetOption).toBeVisible() + await expect(targetOption).toHaveAttribute('data-selected', 'true') + await expect + .poll(async () => { + const frames = await readTransitionFrames(page, frameKey) + return frames.some((frame) => frame.targetVisible && frame.targetSelected) + }) + .toBe(true) + + const frames = await readTransitionFrames(page, frameKey) + const pastedFrames = frames.filter((frame) => frame.value === targetUrl) + expect(frames.some((frame) => frame.wrongVisible)).toBe(true) + expect(pastedFrames.length).toBeGreaterThanOrEqual(MIN_PASTED_FRAMES) + expect(pastedFrames.every((frame) => !frame.wrongVisible && !frame.wrongSelected)).toBe(true) + expect(pastedFrames.some((frame) => frame.targetVisible && frame.targetSelected)).toBe(true) +} + +async function installHeldGitHubLookup( + electronApp: ElectronApplication, + page: Page +): Promise { + await electronApp.evaluate(({ ipcMain }, targetItem) => { + const fixture = globalThis as unknown as { + __githubUrlLookupStarted?: boolean + __releaseGitHubUrlLookup?: () => void + } + fixture.__githubUrlLookupStarted = false + ipcMain.removeHandler('gh:workItemByOwnerRepo') + ipcMain.handle('gh:workItemByOwnerRepo', () => { + fixture.__githubUrlLookupStarted = true + return new Promise((resolve) => { + fixture.__releaseGitHubUrlLookup = () => resolve(targetItem) + }) + }) + }, TARGET_ITEM) + await page.evaluate((wrongItem) => { + const store = window.__store + if (!store) { + throw new Error('window.__store is not available') + } + store.setState({ + getCachedWorkItems: () => [wrongItem], + fetchWorkItems: async () => [wrongItem], + fetchWorkItemsAcrossRepos: async () => ({ + items: [wrongItem], + failedCount: 0, + githubUnavailable: false + }) + }) + }, WRONG_ITEM) +} + +async function releaseGitHubLookup(electronApp: ElectronApplication): Promise { + await electronApp.evaluate(() => { + const fixture = globalThis as unknown as { __releaseGitHubUrlLookup?: () => void } + if (!fixture.__releaseGitHubUrlLookup) { + throw new Error('GitHub lookup is not held') + } + fixture.__releaseGitHubUrlLookup() + }) +} + +async function installHeldGitLabLookup( + electronApp: ElectronApplication, + page: Page +): Promise { + await electronApp.evaluate( + ({ ipcMain }, { wrongItem, targetItem }) => { + const fixture = globalThis as unknown as { + __gitlabUrlLookupStarted?: boolean + __releaseGitLabUrlLookup?: () => void + } + fixture.__gitlabUrlLookupStarted = false + ipcMain.removeHandler('gitlab:listMRs') + ipcMain.handle('gitlab:listMRs', () => ({ + items: [wrongItem], + page: 1, + perPage: 12, + totalCount: 1, + totalPages: 1 + })) + ipcMain.removeHandler('gitlab:workItemByPath') + ipcMain.handle('gitlab:workItemByPath', () => { + fixture.__gitlabUrlLookupStarted = true + return new Promise((resolve) => { + fixture.__releaseGitLabUrlLookup = () => resolve(targetItem) + }) + }) + }, + { wrongItem: GITLAB_WRONG_ITEM, targetItem: GITLAB_TARGET_ITEM } + ) + await page.evaluate(() => { + const store = window.__store + if (!store) { + throw new Error('window.__store is not available') + } + const state = store.getState() + if (!state.preflightStatusContextKey) { + throw new Error('preflight context is not ready') + } + store.setState({ + preflightStatus: { + git: state.preflightStatus?.git ?? { installed: true }, + gh: state.preflightStatus?.gh ?? { installed: true, authenticated: true }, + glab: { installed: true, authenticated: true } + }, + preflightStatusChecked: true + }) + }) +} + +async function releaseGitLabLookup(electronApp: ElectronApplication): Promise { + await electronApp.evaluate(() => { + const fixture = globalThis as unknown as { __releaseGitLabUrlLookup?: () => void } + if (!fixture.__releaseGitLabUrlLookup) { + throw new Error('GitLab lookup is not held') + } + fixture.__releaseGitLabUrlLookup() + }) +} + +test('a pasted GitHub URL never selects a stale cached issue', async ({ + electronApp, + orcaPage +}, testInfo) => { + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + await installHeldGitHubLookup(electronApp, orcaPage) + + await orcaPage.getByRole('button', { name: 'New workspace', exact: true }).click() + const dialog = orcaPage.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) + const input = dialog.locator('[data-workspace-name-input="true"]') + await expect(input).toBeVisible() + await input.click() + + const wrongOption = orcaPage.getByRole('option', { name: `#17 ${WRONG_TITLE}`, exact: true }) + const targetOption = orcaPage.getByRole('option', { + name: `#4242 ${TARGET_TITLE}`, + exact: true + }) + await expect(wrongOption).toBeVisible() + + const frameKey = '__githubUrlTransitionFrames' + await startTransitionCapture(orcaPage, frameKey, WRONG_TITLE, TARGET_TITLE) + + await orcaPage.evaluate((text) => window.api.ui.writeClipboardText(text), TARGET_URL) + await input.focus() + await orcaPage.keyboard.press(pasteChord()) + await expect + .poll(() => + electronApp.evaluate(() => { + const fixture = globalThis as unknown as { __githubUrlLookupStarted?: boolean } + return fixture.__githubUrlLookupStarted === true + }) + ) + .toBe(true) + await expectLookupHeldWithoutStaleRow(orcaPage, frameKey, TARGET_URL, wrongOption, targetOption) + + await releaseGitHubLookup(electronApp) + await expectExactTargetAfterLookup(orcaPage, frameKey, TARGET_URL, targetOption) + + await testInfo.attach('github-url-smart-input-fixed.png', { + body: await orcaPage.screenshot(), + contentType: 'image/png' + }) +}) + +test('a pasted GitLab URL never selects a stale cached merge request', async ({ + electronApp, + orcaPage +}, testInfo) => { + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + await installHeldGitLabLookup(electronApp, orcaPage) + + await orcaPage.getByRole('button', { name: 'New workspace', exact: true }).click() + const dialog = orcaPage.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) + const input = dialog.locator('[data-workspace-name-input="true"]') + await expect(input).toBeVisible() + await input.click() + + const wrongOption = orcaPage.getByRole('option', { + name: `!17 ${GITLAB_WRONG_TITLE}`, + exact: true + }) + const targetOption = orcaPage.getByRole('option', { + name: `!4242 ${GITLAB_TARGET_TITLE}`, + exact: true + }) + await expect(wrongOption).toBeVisible() + + const frameKey = '__gitlabUrlTransitionFrames' + await startTransitionCapture(orcaPage, frameKey, GITLAB_WRONG_TITLE, GITLAB_TARGET_TITLE) + + await orcaPage.evaluate((text) => window.api.ui.writeClipboardText(text), GITLAB_TARGET_URL) + await input.focus() + await orcaPage.keyboard.press(pasteChord()) + await expect + .poll(() => + electronApp.evaluate(() => { + const fixture = globalThis as unknown as { __gitlabUrlLookupStarted?: boolean } + return fixture.__gitlabUrlLookupStarted === true + }) + ) + .toBe(true) + await expectLookupHeldWithoutStaleRow( + orcaPage, + frameKey, + GITLAB_TARGET_URL, + wrongOption, + targetOption + ) + + await releaseGitLabLookup(electronApp) + await expectExactTargetAfterLookup(orcaPage, frameKey, GITLAB_TARGET_URL, targetOption) + + await testInfo.attach('gitlab-url-smart-input-fixed.png', { + body: await orcaPage.screenshot(), + contentType: 'image/png' + }) +}) From afd76a4df939e336180bd53611c5be8fa53d930b Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Mon, 24 Aug 2026 00:01:53 -0700 Subject: [PATCH 10/13] fix(terminal): preserve synchronized frames on reveal (#16026) --- config/reliability-gates.jsonc | 204 ++++++++- ...connection-hidden-backlog-snapshot.test.ts | 12 +- .../hidden-output-restore-snapshot.ts | 8 + .../terminal-visibility-resume.test.ts | 59 ++- .../terminal-visibility-resume.ts | 30 +- .../terminal-webgl-atlas-recovery.test.ts | 25 +- .../terminal-webgl-atlas-recovery.ts | 6 - ...e-global-effects-visibility-resume.test.ts | 16 +- .../use-terminal-window-wake-recovery.test.ts | 136 +++++- .../use-terminal-window-wake-recovery.ts | 68 +++ .../pane-manager-registry.test.ts | 46 +- .../lib/pane-manager/pane-manager-registry.ts | 18 +- .../src/lib/pane-manager/pane-manager.ts | 13 +- .../pane-manager/pane-rendering-control.ts | 14 + .../lib/pane-manager/pane-reveal-repaint.ts | 16 +- .../pane-manager/pane-webgl-renderer.test.ts | 112 ++++- .../lib/pane-manager/pane-webgl-renderer.ts | 101 ++++- .../terminal-canvas-dpr-repair.test.ts | 38 +- .../terminal-canvas-dpr-repair.ts | 29 +- .../terminal-render-pause-release.test.ts | 145 ++++++- .../terminal-render-pause-release.ts | 112 +++++ ...erminal-reveal-paused-render-repro.spec.ts | 392 +++++++++++++++++- 22 files changed, 1481 insertions(+), 119 deletions(-) diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 12b937b187f..97711a43088 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -2674,7 +2674,7 @@ "platform": "macos", "command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-browser-link.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "result": "failed", - "durationSeconds": 60, + "durationSeconds": 53, "summary": "The byte-identical final Electron oracle failed at its exact host/client identity barrier when the sole source delta replaced src/renderer/src/store/index.ts registration lines 110-113 with registerRuntimeHttpLinkBrowserOpener(null); no host-owned browser appeared within the deterministic 60-second bound." } ], @@ -12284,7 +12284,7 @@ "id": "terminal-render.pixel-refresh-repair", "title": "Forced repaint does not change revealed pane pixels", "maturity": "experimental", - "protection": "none", + "protection": "partial", "owner": "terminal-rendering", "layer": "electron-visual-golden", "surfaces": [ @@ -12296,47 +12296,207 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon"], - "coveredPlatforms": [], - "coveredProviders": [], - "coverageNotes": "Registered gap only; the live repro harness with a refresh-repair oracle exists but is not productized into the release-blocking terminal-rendering-golden suite.", + "coveredPlatforms": ["macos"], + "coveredProviders": ["local"], + "coverageNotes": "A headed macOS Electron test drives explicit destructive atlas recovery while DEC 2026 output is held, then compares compositor screenshots before and after a direct full-buffer present. The same renderer choreography is provider-local, but daemon, SSH, remote-runtime, Linux, and Windows GPU runs remain gaps.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/7133", "https://github.com/stablyai/orca/pull/7054" ], - "invariant": "After any reveal, restore, or wake, the pixels a pane displays must equal what a forced full model-invalidating repaint would draw from the buffer; a material refresh-repair diff means stale rendering escaped, whatever the mechanism.", - "oracle": "Screenshot the revealed pane, force a model-invalidating full repaint, screenshot again, and assert the bounded pixel diff is immaterial; pair with a JS-level render-model-vs-buffer comparison. Compositor screenshots only, because WebGL canvas readback is blank with preserveDrawingBuffer disabled.", - "commands": [], - "testFiles": [], - "assertionRefs": [], - "evidenceRuns": [], + "invariant": "After proven renderer damage triggers destructive recovery, visible pixels equal a full model-invalidating present of the current buffer.", + "oracle": "Hold DEC 2026, invoke explicit atlas recovery, require an atlas clear, screenshot the pane, force a direct renderer present, and assert the bounded pixel diff is immaterial. Compositor screenshots only, because WebGL canvas readback is blank with preserveDrawingBuffer disabled.", + "commands": [ + "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts src/renderer/src/lib/pane-manager/pane-manager-registry.test.ts src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts", + "ORCA_E2E_RECORD_VIDEO=1 pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --repeat-each=3" + ], + "testFiles": [ + "src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts", + "src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts", + "src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts", + "src/renderer/src/lib/pane-manager/pane-manager-registry.test.ts", + "src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts", + "src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts", + "src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts", + "tests/e2e/terminal-reveal-paused-render-repro.spec.ts" + ], + "assertionRefs": [ + { + "file": "src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts", + "assertions": [ + "deduplicates a deferred dpr retry and consumes it after repair succeeds", + "caps a deferred dpr transition at sixteen animation-frame retries" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts", + "assertions": ["defers a heavy-reveal dpr present until the shared atlas recovery"] + }, + { + "file": "src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts", + "assertions": [ + "repairs when the canvas and renderer dimensions share a stale dpr cache", + "defers an unmeasurable WebGL canvas but accepts a renderer-less pane" + ] + }, + { + "file": "tests/e2e/terminal-reveal-paused-render-repro.spec.ts", + "assertions": ["@headful atlas recovery presents a synchronized-output WebGL frame"] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-23", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts src/renderer/src/lib/pane-manager/pane-manager-registry.test.ts src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts", + "result": "passed", + "durationSeconds": 2, + "summary": "All 98 renderer contracts passed, including same-DPR zero-scan behavior, visible-only fanout, tri-state DPR repair, deduplicated bounded retry, heavy-reveal repair, and listener cleanup." + }, + { + "date": "2026-08-23", + "runner": "local", + "platform": "macos", + "command": "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", + "result": "passed", + "durationSeconds": 60, + "summary": "Both headed oracles passed together. Explicit destructive atlas recovery presented the held synchronized-output buffer with zero pixels different from a direct renderer present; the test attached before/after screenshots plus pixel-diff metadata." + }, + { + "date": "2026-08-22", + "runner": "local", + "platform": "macos", + "command": "ORCA_E2E_RECORD_VIDEO=1 pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --repeat-each=3", + "result": "passed", + "durationSeconds": 48, + "summary": "Three consecutive headed real-WebGL runs passed in 15.0-15.7 seconds each and emitted a 1920x1080 video per BrowserWindow." + } + ], "runtimeBudget": { - "p95Seconds": 300, - "scope": "release-blocking golden Electron visual test" + "p95Seconds": 120, + "scope": "focused prebuilt headed Electron visual test" }, "flakeHistory": { - "status": "not-started", - "evidence": "Runs nightly only while the per-platform diff threshold stabilizes; the destination is the release-blocking terminal-rendering-golden suite in release-cut.yml." + "status": "unknown", + "evidence": "Five local macOS headed runs passed, including one on the final branch state and three consecutive video-recorded repeats; CI soak history and cross-platform GPU runs are not yet available." }, "redGreenEvidence": { - "status": "missing", - "evidence": "Needs an intentionally fossilized render model (skip the model invalidation on reveal) proving the refresh-repair diff fires." + "status": "complete", + "evidence": "Without the forced synchronized-output present, the damaged compositor differed from a direct renderer present across 87.68% of pixels even though serialization already contained the new frame. With explicit destructive recovery, the same oracle passes the 1.5% material-diff threshold." }, "performanceBudget": { "required": true, - "evidence": "Soak-only; must not add product-path repaints beyond the existing reveal hardening." + "evidence": "Destructive recovery remains event-driven and limited to confirmed renderer-lifecycle boundaries. Gate-local contracts prove ordinary same-DPR resize performs zero pane scans; a true transition scans only the visible manager; unavailable canvas retry is deduplicated and capped at 16 frames; and heavy reveal adds one bounded visible-pane scan. The shared terminal-render.atlas-recovery-fanout contracts separately prove zero hidden-manager atlas clears or presents and a per-pane display:none retry capped at 16 frames." }, "promotionCriteria": [ - "Productize the existing stale-render repro harness with the refresh-repair oracle and failure artifacts.", "Establish a stable material-diff threshold across platforms via nightly runs.", "Promotion means membership in the release-blocking terminal-rendering-golden suite that release-cut.yml runs against every release tag; never PR-blocking.", - "Register the gate command as a direct spec-file invocation; the checker rejects --grep tag selectors, so do not reuse the existing --grep-based golden script as the command." + "Add Linux and Windows GPU evidence or retain those platform gaps explicitly." ], "knownGaps": [ - "No manifest command yet.", - "Buffer-clean, pixels-stale variants are otherwise invisible to every buffer oracle in the manifest." + "The deterministic recovery test disables xterm's one-second safety timeout so the held-frame damage remains stable until recovery.", + "The renderer-level frame injection isolates the paint failure; provider delivery and hidden-output snapshot restore have separate gates.", + "Linux, Windows, daemon, SSH, and remote-runtime live GPU evidence is not yet recorded." ], "demotionRule": "Drop from the golden suite back to nightly diagnostic if diff thresholds cannot be kept stable across CI runners." }, + { + "id": "terminal-render.synchronized-reveal-coherence", + "title": "Ordinary reveal preserves synchronized-output frame coherence", + "maturity": "experimental", + "protection": "partial", + "owner": "terminal-rendering", + "layer": "electron-visual-golden", + "surfaces": ["WebGL rendering", "tab reveal", "snapshot restore", "DEC 2026"], + "platforms": ["macos", "linux", "windows"], + "providers": ["local", "daemon", "ssh", "remote-runtime"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["local"], + "coverageNotes": "A headed macOS Electron test uses a real xterm WebGL renderer and production tab reveal. It proves the coherent pre-hide canvas remains visible while DEC 2026 holds a newer buffer, then proves normal release and xterm's one-second watchdog publish complete frames. Renderer behavior is provider-neutral; live Linux, Windows, daemon, SSH, and remote-runtime GPU runs remain gaps.", + "motivatingLinks": [ + "https://github.com/stablyai/orca/pull/7133", + "https://github.com/stablyai/orca/pull/7054" + ], + "invariant": "terminal-render.synchronized-reveal-coherence: an ordinary reveal never clears a healthy shared atlas or publishes a partially built DEC 2026 frame; it retains the last coherent canvas until release or xterm's bounded watchdog.", + "oracle": "Paint and capture a coherent frame, hide the real terminal tab, build a distinct full-screen frame while DEC 2026 is held, reveal through production, and require zero atlas clears plus pixel-equivalence with the coherent frame. Then release normally and through the one-second watchdog, requiring both compositor frames to match a direct renderer present.", + "commands": [ + "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts" + ], + "testFiles": [ + "src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts", + "src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts", + "src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts", + "src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts", + "src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts", + "tests/e2e/terminal-reveal-paused-render-repro.spec.ts" + ], + "assertionRefs": [ + { + "file": "src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts", + "assertions": [ + "schedules an atlas-preserving present on a light tab reveal", + "keeps heavy atlas recovery off a plain window refocus" + ] + }, + { + "file": "src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts", + "assertions": ["preserves a synchronized frame on an ordinary reveal present"] + }, + { + "file": "src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts", + "assertions": [ + "routes synchronized output through RenderService instead of the renderer", + "releases observer pause before requesting the synchronized frame" + ] + }, + { + "file": "tests/e2e/terminal-reveal-paused-render-repro.spec.ts", + "assertions": [ + "@headful reveal preserves the coherent frame until synchronized output releases" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-23", + "runner": "local", + "platform": "macos", + "command": "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", + "result": "passed", + "durationSeconds": 53, + "summary": "Both final-head headed oracles passed together. The coherent held frame differed by 73 of 1,404,288 pixels (0.0052%), ordinary reveal performed zero atlas clears, normal release differed from the direct present by 95 pixels (0.0068%), and watchdog release matched exactly. All three ratios passed the 1.5% compositor threshold." + } + ], + "runtimeBudget": { + "p95Seconds": 120, + "scope": "focused prebuilt headed Electron prevention and watchdog test" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "One final watchdog-inclusive macOS headed run passed; CI soak history and cross-platform GPU runs are not yet available." + }, + "redGreenEvidence": { + "status": "complete", + "evidence": "Before the prevention change, the ordinary reveal oracle failed deterministically because it observed three atlas clears. After the change, reveal performs zero clears and the first visible frame remains pixel-equivalent to the coherent pre-hide frame." + }, + "performanceBudget": { + "required": true, + "evidence": "Ordinary reveal removes three shared-atlas clears and their global visible-manager presents. It adds one settled, event-driven full-viewport refresh request per revealed pane; DEC 2026 coalesces it and uses xterm's existing one-second watchdog. No polling, subprocess, provider call, PTY inventory, background-output work, listener, or unbounded retry was added; the display-none retry remains deduplicated and capped at 16 frames." + }, + "promotionCriteria": [ + "Accumulate stable macOS runs for both normal release and watchdog release.", + "Add Linux and Windows GPU evidence or retain those platform gaps explicitly.", + "Keep the destructive atlas-recovery oracle separate and passing." + ], + "knownGaps": [ + "The deterministic test injects full-screen marker frames through xterm rather than invoking a live model; genuine OpenCode full-window evidence separately proves the original corruption.", + "Linux, Windows, daemon, SSH, and remote-runtime live GPU evidence is not yet recorded.", + "The 1.5% compositor threshold tolerates cursor and shell-prompt timing noise; exact buffer content and atlas-clear counts are asserted separately." + ], + "demotionRule": "Demote if ordinary reveal clears the shared atlas, the held frame stops matching its coherent baseline, release/watchdog output diverges from a direct present, or the headed oracle cannot remain deterministic." + }, { "id": "pty-delivery.renderer-lifecycle-accounting-reset", "title": "Renderer lifecycle reset clears leaked PTY delivery accounting so surviving PTYs cannot freeze", diff --git a/src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts index c1df93dca25..a54c78f87de 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts @@ -33,14 +33,16 @@ const { scheduleRuntimeGraphSync, shouldSeedCacheTimerOnInitialTitle, toastInfo, - notifyCodexPaneBoundForStaleSweep + notifyCodexPaneBoundForStaleSweep, + presentPaneViewportPreservingSynchronizedOutput } = vi.hoisted(() => ({ resetAndRefreshAllTerminalWebglAtlases: vi.fn(), scheduleTerminalWebglAtlasRecovery: vi.fn(), scheduleRuntimeGraphSync: vi.fn(), shouldSeedCacheTimerOnInitialTitle: vi.fn(() => false), toastInfo: vi.fn(), - notifyCodexPaneBoundForStaleSweep: vi.fn() + notifyCodexPaneBoundForStaleSweep: vi.fn(), + presentPaneViewportPreservingSynchronizedOutput: vi.fn() })) let mockStoreState: StoreState @@ -57,6 +59,11 @@ vi.mock('@/lib/pane-manager/pane-manager-registry', async (importOriginal) => ({ resetAndRefreshAllTerminalWebglAtlases })) +vi.mock('@/lib/pane-manager/pane-webgl-renderer', async (importOriginal) => ({ + ...(await importOriginal>()), + presentPaneViewportPreservingSynchronizedOutput +})) + vi.mock('./terminal-webgl-atlas-recovery', () => ({ scheduleTerminalWebglAtlasRecovery })) @@ -201,6 +208,7 @@ describe('connectPanePty', () => { expect.stringContaining('remote snapshot with hidden remote output'), expect.any(Function) ) + expect(presentPaneViewportPreservingSynchronizedOutput).toHaveBeenCalledWith(pane) disposable.dispose() }) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/hidden-output-restore-snapshot.ts b/src/renderer/src/components/terminal-pane/pty-connection/hidden-output-restore-snapshot.ts index 8714adbd84b..076c9194934 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/hidden-output-restore-snapshot.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/hidden-output-restore-snapshot.ts @@ -11,6 +11,7 @@ import { writeTerminalOutput } from '@/lib/pane-manager/pane-terminal-output-scheduler' import { recordTerminalOutput } from '@/lib/pane-manager/pane-scroll' +import { presentPaneViewportPreservingSynchronizedOutput } from '@/lib/pane-manager/pane-webgl-renderer' import { buildMainModelSnapshotReplayWrites, hasPositiveTerminalDimensions, @@ -22,6 +23,7 @@ import { HIDDEN_OUTPUT_RESTORE_UNAVAILABLE_WARNING } from './hidden-output-resto import { shouldWritePtyOutputForeground } from './foreground-output-scan' import { isRemoteRuntimePtyId } from './paired-parked-terminal-restore' import { restoredSnapshotPaintsPrintableContent } from '../restored-snapshot-coverage' +import { recordTerminalFreezeBreadcrumb } from '../terminal-freeze-breadcrumbs' import type { ConnectPanePtySession } from './connect-pane-pty-session' @@ -152,6 +154,12 @@ export function bindHiddenOutputRestoreSnapshot(session: ConnectPanePtySession): session.recordRendererOrderedSeq(snapshot) recordTerminalOutput(session.pane.terminal) await waitForTerminalReplayWritesParsed(session.pane.terminal) + if (session.deps.isVisibleRef.current) { + presentPaneViewportPreservingSynchronizedOutput(session.pane) + recordTerminalFreezeBreadcrumb('stale-pixel-restore-present', { + paneId: session.pane.id + }) + } }, { shouldRestore: () => diff --git a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts index 3b198054861..74af99a8e14 100644 --- a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts @@ -8,6 +8,10 @@ import { vi.mock('@/lib/pane-manager/pane-manager-registry', () => ({ resetAndRefreshAllTerminalWebglAtlases: vi.fn() })) +const presentPaneViewport = vi.fn() +vi.mock('@/lib/pane-manager/pane-webgl-renderer', () => ({ + presentPaneViewport: (pane: unknown) => presentPaneViewport(pane) +})) vi.mock('@/lib/pane-manager/pane-terminal-output-scheduler', () => ({ flushTerminalOutput: vi.fn(), requestTerminalBacklogRecovery: vi.fn() @@ -21,10 +25,6 @@ vi.mock('./pane-helpers', () => ({ fitPanes: vi.fn(), focusActivePane: vi.fn() })) -const scheduleTabRevealWebglAtlasRecovery = vi.fn() -vi.mock('./terminal-webgl-atlas-recovery', () => ({ - scheduleTabRevealWebglAtlasRecovery: () => scheduleTabRevealWebglAtlasRecovery() -})) const flushDeferredPaneMetricOptionsIfMeasurable = vi.fn((_pane: unknown) => false) vi.mock('@/lib/pane-manager/pane-fit', () => ({ flushDeferredPaneMetricOptionsIfMeasurable: (pane: unknown) => @@ -77,18 +77,19 @@ function resumeArgs(manager: FakeManager, shouldUseLightTabResume: boolean) { describe('resumeTerminalVisibility reveal repaint', () => { beforeEach(() => { vi.clearAllMocks() + repairPaneWebglCanvasDprMismatch.mockReturnValue(false) }) - it('schedules a pane-scoped repaint on a light tab reveal', () => { + it('schedules an atlas-preserving present on a light tab reveal', () => { // The light path is the "click the tab that was not open" gesture: it has // no rendering resume or fit, so without this repaint a hidden-while- // working pane keeps compositing pre-hide pixels. const manager = createManager() resumeTerminalVisibility(resumeArgs(manager, true)) - expect(manager.scheduleRevealRepaint).toHaveBeenCalledTimes(1) + expect(manager.scheduleRevealRepaint).not.toHaveBeenCalled() + expect(manager.scheduleRevealPresent).toHaveBeenCalledTimes(1) expect(manager.resumeRendering).not.toHaveBeenCalled() - expect(scheduleTabRevealWebglAtlasRecovery).toHaveBeenCalledTimes(1) }) it('captures native trim movement before enforcing viewport intent', async () => { @@ -147,6 +148,29 @@ describe('resumeTerminalVisibility reveal repaint', () => { expect(flushDeferredPaneMetricOptionsIfMeasurable).not.toHaveBeenCalled() }) + it('defers a heavy-reveal dpr present until the shared atlas recovery', async () => { + const pane = { terminal: {} } + const manager = createManager() + manager.getPanes.mockReturnValue([pane]) + repairPaneWebglCanvasDprMismatch.mockReturnValueOnce(true) + const { resetAndRefreshAllTerminalWebglAtlases } = vi.mocked( + await import('@/lib/pane-manager/pane-manager-registry') + ) + + resumeTerminalVisibility(resumeArgs(manager, false)) + + expect(repairPaneWebglCanvasDprMismatch).toHaveBeenCalledWith(pane) + expect(presentPaneViewport).not.toHaveBeenCalled() + expect(resetAndRefreshAllTerminalWebglAtlases).toHaveBeenCalledTimes(1) + const atlasResetCallOrder = resetAndRefreshAllTerminalWebglAtlases.mock.invocationCallOrder[0] + if (atlasResetCallOrder === undefined) { + throw new Error('Shared atlas recovery call order missing') + } + expect(repairPaneWebglCanvasDprMismatch.mock.invocationCallOrder[0]).toBeLessThan( + atlasResetCallOrder + ) + }) + it('does not fit on a light tab reveal', () => { const manager = createManager() resumeTerminalVisibility(resumeArgs(manager, true)) @@ -193,6 +217,27 @@ describe('resumeTerminalVisibility reveal repaint', () => { expect(manager.fitAllPanes).not.toHaveBeenCalled() }) + it('repairs WebGL canvas backing-store dpr on window wake', () => { + // Clamshell undock: dpr changes while the pane stayed "visible" with a + // stale backing store; tab-reveal is not in the path. + const first = { terminal: { name: 'pane-a' } } + const second = { terminal: { name: 'pane-b' } } + const manager = createManager() + manager.getPanes.mockReturnValue([first, second]) + repairPaneWebglCanvasDprMismatch.mockReturnValueOnce(true) + + recoverVisibleTerminalWindowWake({ + manager: manager as never as PaneManager, + isActive: true, + clearGlyphAtlases: false + }) + + expect(repairPaneWebglCanvasDprMismatch).toHaveBeenCalledTimes(2) + expect(repairPaneWebglCanvasDprMismatch).toHaveBeenNthCalledWith(1, first) + expect(repairPaneWebglCanvasDprMismatch).toHaveBeenNthCalledWith(2, second) + expect(presentPaneViewport).toHaveBeenCalledWith(first) + }) + it('latches viewport intent before refocus recovery flushes streaming output', async () => { const terminal = { name: 'streaming-terminal' } const manager = createManager() diff --git a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts index ee86edeba18..0ea98f1db8f 100644 --- a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts +++ b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts @@ -14,9 +14,9 @@ import { resetTerminalLinkifierHoverState } from '@/lib/pane-manager/terminal-linkifier-hover-reset' import { focusActivePane } from './pane-helpers' -import { scheduleTabRevealWebglAtlasRecovery } from './terminal-webgl-atlas-recovery' import { flushDeferredPaneMetricOptionsIfMeasurable } from '@/lib/pane-manager/pane-fit' import { repairPaneWebglCanvasDprMismatch } from '@/lib/pane-manager/terminal-canvas-dpr-repair' +import { presentPaneViewport } from '@/lib/pane-manager/pane-webgl-renderer' const VISIBLE_RESUME_FLUSH_CHARS = 256 * 1024 const WINDOW_WAKE_FLUSH_CHARS = 64 * 1024 @@ -88,8 +88,6 @@ export function resumeTerminalVisibility({ // overlay's delayed geometry fit. Still request hidden-output recovery: // agent TUIs can suppress hidden bytes until the pane is foregrounded. requestLightTabBacklogRecovery(manager) - // Why: reveal is the lifecycle boundary that owns hidden renderer repair. - scheduleTabRevealWebglAtlasRecovery() if (flushedDeferredMetrics) { // Why: the light path normally skips fitting, but flushed metrics changed // cell size — refit so cols/rows match before the overlay settles. @@ -109,10 +107,15 @@ export function resumeTerminalVisibility({ // terminals; refresh after reset so rebuilt atlases repaint from xterm. resetAndRefreshAllTerminalWebglAtlases('visibility-resume') } - // Why: the synchronous recovery above can fire before the revealed pane is - // attached and laid out. Follow up after layout with one shared-atlas-safe - // recovery covering every visible terminal manager. - manager.scheduleRevealRepaint() + if (shouldUseLightTabResume) { + // Why: preserve the last coherent frame while a TUI holds DEC 2026. The + // settled refresh arms xterm's watchdog without clearing shared GPU data. + manager.scheduleRevealPresent() + } else { + // Why: rendering was recreated, so the heavy path still needs the proven + // shared-atlas recovery after layout settles. + manager.scheduleRevealRepaint() + } }) } @@ -161,6 +164,13 @@ export function recoverVisibleTerminalWindowWake({ // Why: backlog writes can expose transient viewport geometry while parsing. syncTerminalViewportIntents(manager) for (const pane of manager.getPanes()) { + // Why: clamshell undock / monitor move changes devicePixelRatio while the + // pane can stay "visible" with a stale WebGL backing store. The addon's + // device-pixel observer misses that (no CSS-box change, or no box while + // the lid was closed). Repair here — not only on tab reveal. + if (repairPaneWebglCanvasDprMismatch(pane)) { + presentPaneViewport(pane) + } requestTerminalBacklogRecovery(pane.terminal) flushTerminalOutput(pane.terminal, { maxChars: WINDOW_WAKE_FLUSH_CHARS }) // Why: window blur fires mouseleave, clearing xterm's current link but not @@ -214,6 +224,12 @@ function resumeTerminalVisibilityHeavy(manager: PaneManager, isActive: boolean): // Windows (ANGLE -> D3D11) it can be 100-500 ms but a deferred resume // would paint a stretched DOM-fallback flash, which is worse UX. manager.resumeRendering() + // Why: unchanged grid geometry can skip the reveal fit, but a retained WebGL + // canvas may still carry the previous display's backing-store DPR. The + // caller's atlas recovery presents the final shared-atlas generation. + for (const pane of manager.getPanes()) { + repairPaneWebglCanvasDprMismatch(pane) + } // Why: resumeRendering just re-attached WebGL, whose cell metrics briefly differ // from the DOM renderer's; a raw fit here reflows on a transient one-column-off // grid and garbles diff-painting inline TUIs (grok minimize→restore). diff --git a/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts b/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts index 80013abb860..51be05fc091 100644 --- a/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts @@ -5,8 +5,7 @@ import { } from '@/lib/pane-manager/pane-manager-registry' import * as terminalWebglAtlasRecovery from './terminal-webgl-atlas-recovery' -const { scheduleImagePasteWebglAtlasRecovery, scheduleTabRevealWebglAtlasRecovery } = - terminalWebglAtlasRecovery +const { scheduleImagePasteWebglAtlasRecovery } = terminalWebglAtlasRecovery describe('terminal WebGL atlas recovery', () => { const registeredManagers: { resetWebglTextureAtlases(): void }[] = [] @@ -151,26 +150,4 @@ describe('terminal WebGL atlas recovery', () => { expect(healthyManager.refreshAllPanes).toHaveBeenCalledTimes(3) expect(manager.refreshAllPanes).not.toHaveBeenCalled() }) - - it('recovers immediately on a tab reveal', () => { - vi.useFakeTimers() - const rafCallbacks: FrameRequestCallback[] = [] - vi.stubGlobal( - 'requestAnimationFrame', - vi.fn((callback: FrameRequestCallback) => { - rafCallbacks.push(callback) - return rafCallbacks.length - }) - ) - const manager = registerManager() - - scheduleTabRevealWebglAtlasRecovery() - rafCallbacks[0]?.(0) - expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1) - expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1) - vi.advanceTimersByTime(120) - vi.advanceTimersByTime(380) - expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(3) - expect(manager.refreshAllPanes).toHaveBeenCalledTimes(3) - }) }) diff --git a/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.ts b/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.ts index 72dc08e46c1..9253bdd0ffb 100644 --- a/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.ts +++ b/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.ts @@ -33,9 +33,3 @@ export function scheduleImagePasteWebglAtlasRecovery(): void { // one-shot event, so recover immediately rather than debouncing. scheduleAtlasRecoveryBurst('image-paste') } - -export function scheduleTabRevealWebglAtlasRecovery(): void { - // Why: a tab reveal is an explicit renderer lifecycle boundary where hidden - // GPU state can be stale; ordinary PTY output must not clear the shared atlas. - scheduleAtlasRecoveryBurst('tab-reveal') -} diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects-visibility-resume.test.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects-visibility-resume.test.ts index c7972f542f5..4fdf805100d 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects-visibility-resume.test.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects-visibility-resume.test.ts @@ -260,6 +260,8 @@ describe('useTerminalPaneGlobalEffects', () => { manager.resumeRendering.mockClear() manager.resetWebglTextureAtlases.mockClear() + manager.scheduleRevealRepaint.mockClear() + manager.scheduleRevealPresent.mockClear() manager.refreshAllPanes.mockClear() manager.suspendRendering.mockClear() mocks.fitAndFocusPanes.mockClear() @@ -289,8 +291,10 @@ describe('useTerminalPaneGlobalEffects', () => { expect(manager.resumeRendering).not.toHaveBeenCalled() expect(mocks.fitAndFocusPanes).not.toHaveBeenCalled() expect(mocks.fitPanes).not.toHaveBeenCalled() - expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1) - expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1) + expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled() + expect(manager.refreshAllPanes).not.toHaveBeenCalled() + expect(manager.scheduleRevealRepaint).not.toHaveBeenCalled() + expect(manager.scheduleRevealPresent).toHaveBeenCalledTimes(1) expect(mocks.focusActivePane).toHaveBeenCalledWith(manager) vi.advanceTimersByTime(500) }) @@ -342,6 +346,8 @@ describe('useTerminalPaneGlobalEffects', () => { manager.resumeRendering.mockClear() manager.resetWebglTextureAtlases.mockClear() + manager.scheduleRevealRepaint.mockClear() + manager.scheduleRevealPresent.mockClear() manager.refreshAllPanes.mockClear() mocks.fitAndFocusPanes.mockClear() mocks.fitPanes.mockClear() @@ -361,8 +367,10 @@ describe('useTerminalPaneGlobalEffects', () => { expect(manager.resumeRendering).not.toHaveBeenCalled() expect(mocks.fitAndFocusPanes).not.toHaveBeenCalled() expect(mocks.fitPanes).not.toHaveBeenCalled() - expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1) - expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1) + expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled() + expect(manager.refreshAllPanes).not.toHaveBeenCalled() + expect(manager.scheduleRevealRepaint).not.toHaveBeenCalled() + expect(manager.scheduleRevealPresent).toHaveBeenCalledTimes(1) expect(mocks.focusActivePane).toHaveBeenCalledWith(manager) vi.advanceTimersByTime(500) }) diff --git a/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts b/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts index b866c90af42..c903ec1a2f9 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts @@ -2,15 +2,30 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { renderHook } from '@testing-library/react' import type { PaneManager } from '@/lib/pane-manager/pane-manager' +import type { PaneWebglCanvasDprRepairState } from '@/lib/pane-manager/terminal-canvas-dpr-repair' -const { recoverVisibleTerminalWindowWakeMock } = vi.hoisted(() => ({ - recoverVisibleTerminalWindowWakeMock: vi.fn() +const { + recoverVisibleTerminalWindowWakeMock, + repairPaneWebglCanvasDprMock, + presentPaneViewportMock +} = vi.hoisted(() => ({ + recoverVisibleTerminalWindowWakeMock: vi.fn(), + repairPaneWebglCanvasDprMock: vi.fn<() => PaneWebglCanvasDprRepairState>(() => 'current'), + presentPaneViewportMock: vi.fn() })) vi.mock('./terminal-visibility-resume', () => ({ recoverVisibleTerminalWindowWake: recoverVisibleTerminalWindowWakeMock })) +vi.mock('@/lib/pane-manager/terminal-canvas-dpr-repair', () => ({ + repairPaneWebglCanvasDpr: repairPaneWebglCanvasDprMock +})) + +vi.mock('@/lib/pane-manager/pane-webgl-renderer', () => ({ + presentPaneViewport: presentPaneViewportMock +})) + import { useTerminalWindowWakeRecovery } from './use-terminal-window-wake-recovery' import { getTerminalFreezeBreadcrumbs, @@ -29,6 +44,9 @@ describe('useTerminalWindowWakeRecovery', () => { beforeEach(() => { systemResumedCallback = null recoverVisibleTerminalWindowWakeMock.mockClear() + repairPaneWebglCanvasDprMock.mockClear() + presentPaneViewportMock.mockClear() + repairPaneWebglCanvasDprMock.mockReturnValue('current') unsubscribeSystemResumed.mockClear() onSystemResumed.mockClear() resetTerminalFreezeBreadcrumbsForTesting() @@ -180,4 +198,118 @@ describe('useTerminalWindowWakeRecovery', () => { expect(onSystemResumed).not.toHaveBeenCalled() }) + + it('repairs WebGL canvas dpr on window resize without wiping the glyph atlas', () => { + // Chromium emits resize when devicePixelRatio changes (undock / monitor + // move) even if the CSS box is unchanged. + const pane = { id: 1, terminal: {} } + const resizeManager = { getPanes: () => [pane] } as unknown as PaneManager + repairPaneWebglCanvasDprMock.mockReturnValue('repaired') + vi.stubGlobal('devicePixelRatio', 1) + const { unmount } = renderHook(() => + useTerminalWindowWakeRecovery({ + isVisible: true, + managerRef: { current: resizeManager }, + isActiveRef: { current: true }, + isVisibleRef: { current: true } + }) + ) + + window.dispatchEvent(new Event('resize')) + expect(repairPaneWebglCanvasDprMock).not.toHaveBeenCalled() + + vi.stubGlobal('devicePixelRatio', 2) + window.dispatchEvent(new Event('resize')) + + expect(repairPaneWebglCanvasDprMock).toHaveBeenCalledWith(pane) + expect(presentPaneViewportMock).toHaveBeenCalledWith(pane) + expect(recoverVisibleTerminalWindowWakeMock).not.toHaveBeenCalled() + + unmount() + vi.stubGlobal('devicePixelRatio', 3) + window.dispatchEvent(new Event('resize')) + expect(repairPaneWebglCanvasDprMock).toHaveBeenCalledTimes(1) + }) + + it('retains a dpr transition until the visible manager is available', () => { + const pane = { id: 1, terminal: {} } + const managerRef: { current: PaneManager | null } = { current: null } + vi.stubGlobal('devicePixelRatio', 1) + renderHook(() => + useTerminalWindowWakeRecovery({ + isVisible: true, + managerRef, + isActiveRef: { current: true }, + isVisibleRef: { current: true } + }) + ) + + vi.stubGlobal('devicePixelRatio', 2) + window.dispatchEvent(new Event('resize')) + expect(repairPaneWebglCanvasDprMock).not.toHaveBeenCalled() + + managerRef.current = { getPanes: () => [pane] } as unknown as PaneManager + window.dispatchEvent(new Event('resize')) + expect(repairPaneWebglCanvasDprMock).toHaveBeenCalledWith(pane) + }) + + it('deduplicates a deferred dpr retry and consumes it after repair succeeds', () => { + const pane = { id: 1, terminal: {} } + const callbacks: FrameRequestCallback[] = [] + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + callbacks.push(callback) + return callbacks.length + }) + vi.stubGlobal('devicePixelRatio', 1) + repairPaneWebglCanvasDprMock.mockReturnValueOnce('deferred').mockReturnValue('repaired') + renderHook(() => + useTerminalWindowWakeRecovery({ + isVisible: true, + managerRef: { current: { getPanes: () => [pane] } as unknown as PaneManager }, + isActiveRef: { current: true }, + isVisibleRef: { current: true } + }) + ) + + vi.stubGlobal('devicePixelRatio', 2) + window.dispatchEvent(new Event('resize')) + window.dispatchEvent(new Event('resize')) + expect(repairPaneWebglCanvasDprMock).toHaveBeenCalledTimes(1) + expect(callbacks).toHaveLength(1) + + callbacks.shift()?.(performance.now()) + expect(presentPaneViewportMock).toHaveBeenCalledWith(pane) + window.dispatchEvent(new Event('resize')) + expect(repairPaneWebglCanvasDprMock).toHaveBeenCalledTimes(2) + }) + + it('caps a deferred dpr transition at sixteen animation-frame retries', () => { + const pane = { id: 1, terminal: {} } + const callbacks: FrameRequestCallback[] = [] + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + callbacks.push(callback) + return callbacks.length + }) + vi.stubGlobal('devicePixelRatio', 1) + repairPaneWebglCanvasDprMock.mockReturnValue('deferred') + renderHook(() => + useTerminalWindowWakeRecovery({ + isVisible: true, + managerRef: { current: { getPanes: () => [pane] } as unknown as PaneManager }, + isActiveRef: { current: true }, + isVisibleRef: { current: true } + }) + ) + + vi.stubGlobal('devicePixelRatio', 2) + window.dispatchEvent(new Event('resize')) + let callbackCount = 0 + while (callbacks.length > 0) { + callbacks.shift()?.(performance.now()) + callbackCount += 1 + } + + expect(callbackCount).toBe(16) + expect(repairPaneWebglCanvasDprMock).toHaveBeenCalledTimes(17) + }) }) diff --git a/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.ts b/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.ts index ba8102a5fb1..444d0f1f9dd 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.ts @@ -1,6 +1,8 @@ import { useEffect } from 'react' import type { PaneManager } from '@/lib/pane-manager/pane-manager' import { recoverVisibleTerminalWindowWake } from './terminal-visibility-resume' +import { repairPaneWebglCanvasDpr } from '@/lib/pane-manager/terminal-canvas-dpr-repair' +import { presentPaneViewport } from '@/lib/pane-manager/pane-webgl-renderer' import { recordTerminalFreezeBreadcrumb } from './terminal-freeze-breadcrumbs' import type { IDisposable } from '@xterm/xterm' @@ -16,6 +18,8 @@ type WindowWakePtyBinding = IDisposable & { reassertPtySizeAfterWindowWake?: () => void } +const DPR_RECOVERY_RETRY_FRAMES = 16 + export function useTerminalWindowWakeRecovery({ isVisible, managerRef, @@ -28,7 +32,10 @@ export function useTerminalWindowWakeRecovery({ return } let wakeRecoveryFrameId: number | null = null + let dprRecoveryFrameId: number | null = null + let dprRecoveryFramesRemaining = 0 let settledClearGlyphAtlases = false + let observedDevicePixelRatio = window.devicePixelRatio const cancelScheduledWakeRecovery = (): void => { if (wakeRecoveryFrameId === null || typeof cancelAnimationFrame !== 'function') { wakeRecoveryFrameId = null @@ -37,6 +44,13 @@ export function useTerminalWindowWakeRecovery({ cancelAnimationFrame(wakeRecoveryFrameId) wakeRecoveryFrameId = null } + const cancelScheduledDprRecovery = (): void => { + if (dprRecoveryFrameId !== null && typeof cancelAnimationFrame === 'function') { + cancelAnimationFrame(dprRecoveryFrameId) + } + dprRecoveryFrameId = null + dprRecoveryFramesRemaining = 0 + } const reassertPanePtySizes = (): void => { for (const binding of panePtyBindingsRef?.current.values() ?? []) { // Why: one settled read avoids duplicate SSH RPCs while still detecting a dropped resize. @@ -111,7 +125,59 @@ export function useTerminalWindowWakeRecovery({ recoverVisibleWake(true, 'system-resumed') } } + const repairVisiblePanesForDpr = (devicePixelRatio: number): boolean => { + const manager = managerRef.current + if (!manager || !isVisibleRef.current) { + return false + } + let deferred = false + for (const pane of manager.getPanes?.() ?? []) { + const state = repairPaneWebglCanvasDpr(pane) + deferred ||= state === 'deferred' + if (state === 'repaired') { + presentPaneViewport(pane) + } + } + if (!deferred) { + observedDevicePixelRatio = devicePixelRatio + } + return !deferred + } + const scheduleDprRecovery = (): void => { + if (dprRecoveryFrameId !== null || typeof requestAnimationFrame !== 'function') { + return + } + dprRecoveryFramesRemaining = DPR_RECOVERY_RETRY_FRAMES + const retry = (): void => { + dprRecoveryFrameId = null + if (repairVisiblePanesForDpr(window.devicePixelRatio)) { + dprRecoveryFramesRemaining = 0 + return + } + dprRecoveryFramesRemaining -= 1 + if (dprRecoveryFramesRemaining > 0) { + dprRecoveryFrameId = requestAnimationFrame(retry) + } + } + dprRecoveryFrameId = requestAnimationFrame(retry) + } + const onWindowResize = (): void => { + // Why: Chromium emits window resize on devicePixelRatio changes even when + // the CSS box is unchanged (monitor move / undock). xterm's own observer + // misses that while the canvas had no box (laptop lid closed). + const devicePixelRatio = window.devicePixelRatio + if (devicePixelRatio === observedDevicePixelRatio) { + return + } + if (dprRecoveryFrameId !== null) { + return + } + if (!repairVisiblePanesForDpr(devicePixelRatio)) { + scheduleDprRecovery() + } + } window.addEventListener('focus', onFocus) + window.addEventListener('resize', onWindowResize) if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') { document.addEventListener('visibilitychange', onVisibilityChange) } @@ -125,7 +191,9 @@ export function useTerminalWindowWakeRecovery({ : null return () => { cancelScheduledWakeRecovery() + cancelScheduledDprRecovery() window.removeEventListener('focus', onFocus) + window.removeEventListener('resize', onWindowResize) if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') { document.removeEventListener('visibilitychange', onVisibilityChange) } diff --git a/src/renderer/src/lib/pane-manager/pane-manager-registry.test.ts b/src/renderer/src/lib/pane-manager/pane-manager-registry.test.ts index 10beddbf8b9..9320e0410b4 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager-registry.test.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager-registry.test.ts @@ -85,9 +85,43 @@ describe('pane manager registry', () => { expect(order).toEqual(['first-reset', 'second-reset', 'first-refresh', 'second-refresh']) }) + it('clears every recovered atlas before presenting any pane', () => { + // Why: per-pane clear+present interleaves a present against atlas generation + // N with the next pane's wipe to N+1. The first synchronized-output column + // then keeps pre-hide footer pixels. Wipe first, present once the generation + // is final. + const order: string[] = [] + const first = { + resetWebglTextureAtlases: vi.fn<() => void>(() => order.push('first-reset')), + clearWebglTextureAtlases: vi.fn<() => void>(() => order.push('first-clear')), + presentForcedViewports: vi.fn<() => void>(() => order.push('first-present')), + refreshAllPanes: vi.fn<() => void>(() => order.push('first-refresh')), + isVisibleForAtlasRecovery: () => true + } + const second = { + resetWebglTextureAtlases: vi.fn<() => void>(() => order.push('second-reset')), + clearWebglTextureAtlases: vi.fn<() => void>(() => order.push('second-clear')), + presentForcedViewports: vi.fn<() => void>(() => order.push('second-present')), + refreshAllPanes: vi.fn<() => void>(() => order.push('second-refresh')), + isVisibleForAtlasRecovery: () => true + } + registerLivePaneManager(first) + registeredManagers.push(first) + registerLivePaneManager(second) + registeredManagers.push(second) + + resetAndRefreshAllTerminalWebglAtlases() + + expect(order).toEqual(['first-clear', 'second-clear', 'first-present', 'second-present']) + expect(first.resetWebglTextureAtlases).not.toHaveBeenCalled() + expect(second.refreshAllPanes).not.toHaveBeenCalled() + }) + it('bounds atlas recovery to visible managers', () => { const visible = { resetWebglTextureAtlases: vi.fn<() => void>(), + clearWebglTextureAtlases: vi.fn<() => void>(), + presentForcedViewports: vi.fn<() => void>(), refreshAllPanes: vi.fn<() => void>(), isVisibleForAtlasRecovery: () => true } @@ -95,6 +129,8 @@ describe('pane manager registry', () => { registeredManagers.push(visible) const hidden = Array.from({ length: 64 }, () => ({ resetWebglTextureAtlases: vi.fn<() => void>(), + clearWebglTextureAtlases: vi.fn<() => void>(), + presentForcedViewports: vi.fn<() => void>(), refreshAllPanes: vi.fn<() => void>(), isVisibleForAtlasRecovery: () => false })) @@ -105,12 +141,14 @@ describe('pane manager registry', () => { resetAndRefreshAllTerminalWebglAtlases() - expect(visible.resetWebglTextureAtlases).toHaveBeenCalledOnce() - expect(visible.refreshAllPanes).toHaveBeenCalledOnce() + expect(visible.clearWebglTextureAtlases).toHaveBeenCalledOnce() + expect(visible.presentForcedViewports).toHaveBeenCalledOnce() expect( - hidden.every((manager) => manager.resetWebglTextureAtlases.mock.calls.length === 0) + hidden.every((manager) => manager.clearWebglTextureAtlases.mock.calls.length === 0) ).toBe(true) - expect(hidden.every((manager) => manager.refreshAllPanes.mock.calls.length === 0)).toBe(true) + expect(hidden.every((manager) => manager.presentForcedViewports.mock.calls.length === 0)).toBe( + true + ) }) it('continues reset-and-refresh recovery when one manager throws', () => { diff --git a/src/renderer/src/lib/pane-manager/pane-manager-registry.ts b/src/renderer/src/lib/pane-manager/pane-manager-registry.ts index 588970436de..34492cd508e 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager-registry.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager-registry.ts @@ -4,6 +4,8 @@ import type { PaneRenderingDiagnostics } from './pane-manager-types' type RegisteredPaneManager = { resetWebglTextureAtlases(): void + clearWebglTextureAtlases?: () => void + presentForcedViewports?: () => void fitAllPanes?: () => void refreshAllPanes?: () => void getRenderingDiagnostics?: () => PaneRenderingDiagnostics[] @@ -60,9 +62,17 @@ export function resetAndRefreshAllTerminalWebglAtlases(reason?: string): void { ...(reason ? { reason } : {}) }) const resetManagers: RegisteredPaneManager[] = [] + // Why: clearTextureAtlas() is module-global. Clearing then presenting per + // pane interleaves a present against generation N with the next pane's wipe + // to N+1, so the first synchronized-output column keeps pre-hide footer pixels. + // Wipe every recovered atlas first; present only once the generation is final. for (const manager of recoveryManagers) { try { - manager.resetWebglTextureAtlases() + if (manager.clearWebglTextureAtlases) { + manager.clearWebglTextureAtlases() + } else { + manager.resetWebglTextureAtlases() + } resetManagers.push(manager) } catch { // Why: recovery is best-effort during pane teardown; a disposed manager @@ -71,7 +81,11 @@ export function resetAndRefreshAllTerminalWebglAtlases(reason?: string): void { } for (const manager of resetManagers) { try { - manager.refreshAllPanes?.() + if (manager.presentForcedViewports) { + manager.presentForcedViewports() + } else { + manager.refreshAllPanes?.() + } } catch { // Why: a pane can unmount between atlas reset and repaint; later // managers still need to repaint from their xterm buffers. diff --git a/src/renderer/src/lib/pane-manager/pane-manager.ts b/src/renderer/src/lib/pane-manager/pane-manager.ts index 8a99a00563e..bc05069bdfe 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager.ts @@ -26,6 +26,8 @@ import { applyTerminalGpuAcceleration } from './pane-terminal-gpu-acceleration' import { rebuildAttachedWebgl } from './pane-webgl-reattach' import { markPaneComplexScriptOutput, + clearPaneWebglTextureAtlases, + presentPaneViewports, resetPaneWebglTextureAtlases, resumePaneRendering, setPaneGpuRenderingState, @@ -280,6 +282,14 @@ export class PaneManager { resetPaneWebglTextureAtlases(this.panes.values()) } + clearWebglTextureAtlases(): void { + clearPaneWebglTextureAtlases(this.panes.values()) + } + + presentForcedViewports(): void { + presentPaneViewports(this.panes.values()) + } + setAtlasRecoveryVisible(visible: boolean): void { this.atlasRecoveryVisible = visible } @@ -296,8 +306,7 @@ export class PaneManager { } scheduleRevealPresent(): void { - // Why: same destroy guard as scheduleRevealRepaint, but presents without - // clearing the shared glyph atlas — used by the plain-refocus recovery. + // Why: ordinary reveal keeps the coherent canvas until DEC 2026 releases. schedulePaneRevealPresent(() => (this.destroyed ? [] : this.panes.values())) } diff --git a/src/renderer/src/lib/pane-manager/pane-rendering-control.ts b/src/renderer/src/lib/pane-manager/pane-rendering-control.ts index 2c005f0ff05..1de4621a60f 100644 --- a/src/renderer/src/lib/pane-manager/pane-rendering-control.ts +++ b/src/renderer/src/lib/pane-manager/pane-rendering-control.ts @@ -6,6 +6,8 @@ import { disposeWebgl, isPaneWebglContextLost, markComplexScriptOutput, + clearWebglTextureAtlas, + presentPaneViewport, resetWebglTextureAtlas } from './pane-webgl-renderer' import { rebuildAttachedWebgl, reattachWebglIfNeeded } from './pane-webgl-reattach' @@ -101,3 +103,15 @@ export function resetPaneWebglTextureAtlases(panes: Iterable): void { + for (const pane of panes) { + clearWebglTextureAtlas(pane) + } +} + +export function presentPaneViewports(panes: Iterable): void { + for (const pane of panes) { + presentPaneViewport(pane) + } +} diff --git a/src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts b/src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts index bfc4797aa52..ab2f973bcfa 100644 --- a/src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts +++ b/src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts @@ -1,5 +1,6 @@ import type { ManagedPaneInternal } from './pane-manager-types' import { reattachWebglIfNeeded } from './pane-webgl-reattach' +import { presentPaneViewportPreservingSynchronizedOutput } from './pane-webgl-renderer' import { resetAndRefreshAllTerminalWebglAtlases } from './pane-manager-registry' type PaneGetter = () => Iterable @@ -83,21 +84,10 @@ export function schedulePaneRevealRepaint(getPanes: () => Iterable Iterable): void { forEachPaneOnSettledFrame(getPanes, (pane) => { reattachWebglIfNeeded(pane) - if (pane.terminal.rows > 0) { - pane.terminal.refresh(0, pane.terminal.rows - 1) - } + presentPaneViewportPreservingSynchronizedOutput(pane) }) } diff --git a/src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts b/src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts index 11076608027..00c8174967a 100644 --- a/src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts +++ b/src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts @@ -4,6 +4,8 @@ import type { ManagedPaneInternal } from './pane-manager-types' import { attachWebgl, clearTerminalWebglAttachBackoff, + presentPaneViewport, + presentPaneViewportPreservingSynchronizedOutput, resetTerminalWebglSuggestion, resetWebglTextureAtlas } from './pane-webgl-renderer' @@ -75,6 +77,7 @@ type FakeRenderService = { function createPausedPane(display: 'block' | 'none'): { pane: ManagedPaneInternal renderService: FakeRenderService + setDisplay: (next: 'block' | 'none') => void } { const pane = createPane() const renderService: FakeRenderService = { @@ -87,7 +90,8 @@ function createPausedPane(display: 'block' | 'none'): { } }) } - const view = { getComputedStyle: () => ({ display }) } + let currentDisplay = display + const view = { getComputedStyle: () => ({ display: currentDisplay }) } const element = { ownerDocument: { defaultView: view }, parentElement: null } pane.container = element as never pane.xtermContainer = element as never @@ -96,7 +100,13 @@ function createPausedPane(display: 'block' | 'none'): { refresh: vi.fn(() => renderService.refreshRows(0, pane.terminal.rows - 1)), _core: { _renderService: renderService } } as never - return { pane, renderService } + return { + pane, + renderService, + setDisplay: (next) => { + currentDisplay = next + } + } } describe('terminal WebGL addon lifecycle', () => { @@ -168,6 +178,58 @@ describe('terminal WebGL addon lifecycle', () => { expect(pane.terminal.refresh).toHaveBeenCalledWith(0, 23) }) + it('falls back to terminal.refresh on an unpaused, unsynchronized pane', () => { + // Restore-after-replay and other callers use presentPaneViewport even when + // forceFullViewportPresent is a no-op (not paused, no DEC 2026). + const refreshRows = vi.fn() + const renderRows = vi.fn() + const pane = createPane() + pane.terminal = { + ...pane.terminal, + refresh: vi.fn(), + _core: { + _renderService: { + _isPaused: false, + _needsFullRefresh: false, + refreshRows, + _renderer: { value: { renderRows } } + }, + coreService: { decPrivateModes: { synchronizedOutput: false } } + } + } as never + + presentPaneViewport(pane) + + expect(pane.terminal.refresh).toHaveBeenCalledWith(0, 23) + expect(refreshRows).not.toHaveBeenCalled() + expect(renderRows).not.toHaveBeenCalled() + }) + + it('preserves a synchronized frame on an ordinary reveal present', () => { + const refreshRows = vi.fn() + const renderRows = vi.fn() + const pane = createPane() + pane.terminal = { + ...pane.terminal, + refresh: vi.fn(), + _core: { + _renderService: { + _isPaused: false, + _needsFullRefresh: false, + refreshRows, + _renderer: { value: { renderRows } } + }, + coreService: { decPrivateModes: { synchronizedOutput: true } } + } + } as never + + presentPaneViewportPreservingSynchronizedOutput(pane) + + expect(refreshRows).toHaveBeenCalledWith(0, 23, true) + expect(renderRows).not.toHaveBeenCalled() + expect(pane.terminal.refresh).not.toHaveBeenCalled() + }) + it('keeps the render pause latched when resetting a pane that has no layout box', () => { // Regression: the atlas reset released xterm's pause for every pane of a // visible manager, including a collapsed sibling of an expanded pane. That @@ -185,6 +247,52 @@ describe('terminal WebGL addon lifecycle', () => { expect(pane.terminal.refresh).toHaveBeenCalledWith(0, 23) }) + it('retries a display:none present after the overlay actually shows a box', () => { + // Field traces show paused=true needFull=true because the + // first present ran while the overlay was still display:none. Selection + // later healed the inner rows; only a resize cleared the sides. Flush the + // retry after the box exists so the full present actually runs. + const queued: FrameRequestCallback[] = [] + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + queued.push(callback) + return queued.length + }) + const { pane, renderService, setDisplay } = createPausedPane('none') + + presentPaneViewport(pane) + + expect(renderService._isPaused).toBe(true) + expect(queued).toHaveLength(1) + + setDisplay('block') + queued.shift()?.(16) + + expect(renderService._isPaused).toBe(false) + expect(renderService.refreshRows).toHaveBeenCalledWith(0, 23, true) + }) + + it('caps display:none present retries', () => { + const queued: FrameRequestCallback[] = [] + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + queued.push(callback) + return queued.length + }) + const { pane, renderService } = createPausedPane('none') + + presentPaneViewport(pane) + presentPaneViewport(pane) + expect(queued).toHaveLength(1) + let callbacks = 0 + while (queued.length > 0) { + queued.shift()?.(callbacks * 16) + callbacks += 1 + } + + expect(callbacks).toBe(16) + expect(renderService._isPaused).toBe(true) + expect(renderService.refreshRows).toHaveBeenCalledTimes(2) + }) + it('still forces the paused render through for a pane that has a layout box', () => { // The reveal case the release exists for: DOM-visible, but xterm's observer // has not caught up, so a plain refresh() would be swallowed. diff --git a/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts b/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts index 9d05e6b876b..463bc76e53a 100644 --- a/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts +++ b/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts @@ -1,9 +1,12 @@ import { WebglAddon } from '@xterm/addon-webgl' -import type { ManagedPaneInternal } from './pane-manager-types' +import type { ManagedPane, ManagedPaneInternal } from './pane-manager-types' import { recordTerminalWebglDiagnostic } from '../../../../shared/terminal-webgl-diagnostics' import { getLivePaneCensus } from './pane-manager-registry' import { isManagedPaneDisplayNone } from './pane-display-visibility' -import { forceRepaintThroughRenderPause } from './terminal-render-pause-release' +import { + forceFullViewportPresent, + requestFullViewportPresent +} from './terminal-render-pause-release' import { getTerminalWebglAutoDecision, resetTerminalWebglAutoDecision @@ -138,7 +141,7 @@ export function markComplexScriptOutput(pane: ManagedPaneInternal): void { pane.hasComplexScriptOutput = true } -export function resetWebglTextureAtlas(pane: ManagedPaneInternal): void { +export function clearWebglTextureAtlas(pane: ManagedPaneInternal): void { if (pane.webglDisabledAfterContextLoss) { return } @@ -147,22 +150,89 @@ export function resetWebglTextureAtlas(pane: ManagedPaneInternal): void { // context-loss event. Clearing the atlas preserves GPU rendering and forces // a fresh paint when the pane becomes visible/focused again. pane.webglAddon?.clearTextureAtlas() + } catch { + /* ignore — pane may have been disposed in the meantime */ + } +} + +const DISPLAYED_PRESENT_RETRY_FRAMES = 16 +type ViewportPresentMode = 'preserve-synchronized-output' | 'force-current-buffer' +type DisplayedPresentRetry = { frames: number; mode: ViewportPresentMode } +const pendingDisplayedPresentRetries = new WeakMap() + +function schedulePresentWhenDisplayed(pane: ManagedPaneInternal, mode: ViewportPresentMode): void { + if (typeof globalThis.requestAnimationFrame !== 'function') { + return + } + const pending = pendingDisplayedPresentRetries.get(pane) + if (pending) { + if (mode === 'force-current-buffer') { + pending.mode = mode + } + return + } + pendingDisplayedPresentRetries.set(pane, { + frames: DISPLAYED_PRESENT_RETRY_FRAMES, + mode + }) + const tick = (): void => { + const retry = pendingDisplayedPresentRetries.get(pane) + if (!retry || retry.frames <= 0 || !pane.terminal) { + pendingDisplayedPresentRetries.delete(pane) + return + } + if (isManagedPaneDisplayNone(pane)) { + if (retry.frames === 1) { + pendingDisplayedPresentRetries.delete(pane) + return + } + retry.frames -= 1 + globalThis.requestAnimationFrame(tick) + return + } + pendingDisplayedPresentRetries.delete(pane) + presentPaneViewportWithMode(pane, retry.mode) + } + globalThis.requestAnimationFrame(tick) +} + +function presentPaneViewportWithMode(pane: ManagedPane, mode: ViewportPresentMode): void { + const internal = pane as ManagedPaneInternal + if (internal.webglDisabledAfterContextLoss) { + return + } + try { // Why: on reveal xterm's IntersectionObserver can still report the pane as // not intersecting, so a plain refresh() is swallowed by RenderService's - // paused-render gate and the cleared model never repaints (stale bottom rows - // until a drag-select forces a redraw). Force the paused render through - // first; only fall back to refresh() when the terminal was not gated. + // paused-render gate and the pending model never repaints (stale bottom rows + // until a drag-select forces a redraw). Request one synchronous full present + // even if the observer already unpaused; only fall back to refresh() when + // internals are unavailable. // // Why the display check: that release is only right for a pane that is // DOM-visible. A pane with no box at all (collapsed sibling of an expanded // pane, a restore that stays display:none for its whole reattach) is - // legitimately paused, and releasing it paints the just-cleared model into - // nothing and then leaves the service unpaused for good — the observer only + // legitimately paused, and releasing it paints into nothing and then leaves + // the service unpaused for good — the observer only // fires on a change, so it never re-pauses. Clearing _needsFullRefresh with // it also drops the full repaint the observer owes the pane on reveal, and // the deferred _pausedResizeTask that flushes alongside it. Latching is what // xterm's own gate does, and the reveal repaints from the latch. - if (isManagedPaneDisplayNone(pane) || !forceRepaintThroughRenderPause(pane.terminal)) { + if (isManagedPaneDisplayNone(pane)) { + pane.terminal.refresh(0, pane.terminal.rows - 1) + // Why: light tab reveal runs while the overlay is still display:none + // (field trace: paused=true needFull=true at click). A plain refresh only + // latches _needsFullRefresh; if IntersectionObserver never fires, the + // canvas keeps pre-hide pixels until a user resize. Retry once the box + // exists so the full present actually runs. + schedulePresentWhenDisplayed(internal, mode) + return + } + const presented = + mode === 'force-current-buffer' + ? forceFullViewportPresent(pane.terminal) + : requestFullViewportPresent(pane.terminal) + if (!presented) { // Why: refresh even without a WebGL addon so recovery never silently // no-ops — a DOM-rendered pane can hold stale pixels after reveal too. pane.terminal.refresh(0, pane.terminal.rows - 1) @@ -172,6 +242,19 @@ export function resetWebglTextureAtlas(pane: ManagedPaneInternal): void { } } +export function presentPaneViewport(pane: ManagedPane): void { + presentPaneViewportWithMode(pane, 'force-current-buffer') +} + +export function presentPaneViewportPreservingSynchronizedOutput(pane: ManagedPane): void { + presentPaneViewportWithMode(pane, 'preserve-synchronized-output') +} + +export function resetWebglTextureAtlas(pane: ManagedPaneInternal): void { + clearWebglTextureAtlas(pane) + presentPaneViewport(pane) +} + function refitAfterFitAnchoredWebglAttach(pane: ManagedPaneInternal): void { // Why: the fit that triggered this attach measured DOM cell metrics, but WebGL // floors the device cell width — keeping that grid leaves an unpainted right diff --git a/src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts b/src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts index 188b8441104..0d7f241ffbf 100644 --- a/src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts +++ b/src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts @@ -1,11 +1,15 @@ import { describe, expect, it, vi } from 'vitest' import type { ManagedPane } from './pane-manager-types' -import { repairPaneWebglCanvasDprMismatch } from './terminal-canvas-dpr-repair' +import { + repairPaneWebglCanvasDpr, + repairPaneWebglCanvasDprMismatch +} from './terminal-canvas-dpr-repair' function makePane(args: { backingWidth: number expectedWidth: number dpr: number + cachedDpr?: number backingHeight?: number expectedHeight?: number connected?: boolean @@ -32,6 +36,7 @@ function makePane(args: { (args.hasRenderer ?? true) ? { _canvas: canvas, + _devicePixelRatio: args.cachedDpr ?? args.dpr, dimensions: { device: { canvas: { width: args.expectedWidth, height: args.expectedHeight ?? 1200 } @@ -79,6 +84,19 @@ describe('repairPaneWebglCanvasDprMismatch', () => { expect(handleResize).toHaveBeenCalledTimes(1) }) + it('repairs when the canvas and renderer dimensions share a stale dpr cache', () => { + const { pane, handleDevicePixelRatioChange, handleResize } = makePane({ + backingWidth: 1080, + expectedWidth: 1080, + dpr: 2, + cachedDpr: 1 + }) + + expect(repairPaneWebglCanvasDprMismatch(pane)).toBe(true) + expect(handleDevicePixelRatioChange).toHaveBeenCalledTimes(1) + expect(handleResize).toHaveBeenCalledWith(120, 40) + }) + it('is a no-op when backing matches the renderer device dimensions', () => { const { pane, handleResize, refresh } = makePane({ backingWidth: 2160, @@ -136,6 +154,24 @@ describe('repairPaneWebglCanvasDprMismatch', () => { expect(repairPaneWebglCanvasDprMismatch(noRenderer.pane)).toBe(false) }) + it('defers an unmeasurable WebGL canvas but accepts a renderer-less pane', () => { + const detached = makePane({ + backingWidth: 2160, + expectedWidth: 1080, + dpr: 1, + connected: false + }) + const noRenderer = makePane({ + backingWidth: 2160, + expectedWidth: 1080, + dpr: 1, + hasRenderer: false + }) + + expect(repairPaneWebglCanvasDpr(detached.pane)).toBe('deferred') + expect(repairPaneWebglCanvasDpr(noRenderer.pane)).toBe('current') + }) + it('reports failure without throwing when the repair path throws mid-teardown', () => { const { pane, handleResize } = makePane({ backingWidth: 2160, diff --git a/src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.ts b/src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.ts index 72bde40b30b..587e01288e4 100644 --- a/src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.ts +++ b/src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.ts @@ -14,6 +14,7 @@ import { recordTerminalWebglDiagnostic } from '../../../../shared/terminal-webgl */ type XtermRendererInternals = { _canvas?: HTMLCanvasElement + _devicePixelRatio?: number _gl?: { canvas?: HTMLCanvasElement } dimensions?: { device?: { canvas?: { width?: number; height?: number } } @@ -22,33 +23,42 @@ type XtermRendererInternals = { handleResize?: (cols: number, rows: number) => void } -export function repairPaneWebglCanvasDprMismatch(pane: ManagedPane): boolean { +export type PaneWebglCanvasDprRepairState = 'current' | 'deferred' | 'repaired' + +export function repairPaneWebglCanvasDpr(pane: ManagedPane): PaneWebglCanvasDprRepairState { const renderer = ( pane.terminal as unknown as { _core?: { _renderService?: { _renderer?: { value?: XtermRendererInternals } } } } )._core?._renderService?._renderer?.value const canvas = renderer?._canvas ?? renderer?._gl?.canvas - if (!renderer || !canvas?.isConnected) { - return false + if (!renderer || !canvas) { + return 'current' + } + if (!canvas.isConnected) { + return 'deferred' } const view = canvas.ownerDocument?.defaultView const expected = renderer.dimensions?.device?.canvas const expectedWidth = expected?.width ?? 0 const expectedHeight = expected?.height ?? 0 if (!view || expectedWidth <= 0 || expectedHeight <= 0) { - return false + return 'deferred' } const staleBackingWidth = canvas.width const staleBackingHeight = canvas.height + const cachedDevicePixelRatio = renderer._devicePixelRatio + const devicePixelRatioChanged = + typeof cachedDevicePixelRatio === 'number' && cachedDevicePixelRatio !== view.devicePixelRatio // xterm rounds its CSS canvas size before ResizeObserver converts it back to // device pixels; allow that round trip without forcing layout on every fit. const roundingTolerance = Math.max(1, Math.ceil(view.devicePixelRatio / 2)) if ( + !devicePixelRatioChanged && Math.abs(staleBackingWidth - expectedWidth) <= roundingTolerance && Math.abs(staleBackingHeight - expectedHeight) <= roundingTolerance ) { - return false + return 'current' } try { // Order matters: refresh the renderer's cached dpr/dimensions first, then @@ -58,13 +68,18 @@ export function repairPaneWebglCanvasDprMismatch(pane: ManagedPane): boolean { pane.terminal.refresh(0, pane.terminal.rows - 1) } catch { // Pane may be mid-teardown; the next reveal/fit retries the check. - return false + return 'deferred' } recordTerminalWebglDiagnostic('webgl-canvas-dpr-repair', { paneId: pane.id, staleBackingWidth, expectedBackingWidth: expectedWidth, + ...(cachedDevicePixelRatio === undefined ? {} : { cachedDevicePixelRatio }), devicePixelRatio: view.devicePixelRatio }) - return true + return 'repaired' +} + +export function repairPaneWebglCanvasDprMismatch(pane: ManagedPane): boolean { + return repairPaneWebglCanvasDpr(pane) === 'repaired' } diff --git a/src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts b/src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts index e3d84677424..a0a81ec16d1 100644 --- a/src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts +++ b/src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts @@ -1,24 +1,35 @@ import { describe, expect, it, vi } from 'vitest' -import { forceRepaintThroughRenderPause } from './terminal-render-pause-release' +import { + forceFullViewportPresent, + forceRepaintThroughRenderPause, + requestFullViewportPresent +} from './terminal-render-pause-release' type FakeRenderService = { _isPaused?: boolean _needsFullRefresh?: boolean refreshRows?: ReturnType + _renderer?: { + value?: { clear?: ReturnType; renderRows?: ReturnType } + } } function createTerminal(options: { rows?: number renderService?: FakeRenderService | null withoutCore?: boolean + synchronizedOutput?: boolean }): unknown { - const { rows = 24, renderService, withoutCore } = options + const { rows = 24, renderService, withoutCore, synchronizedOutput } = options if (withoutCore) { return { rows } } return { rows, - _core: { _renderService: renderService ?? null } + _core: { + _renderService: renderService ?? null, + coreService: { decPrivateModes: { synchronizedOutput: synchronizedOutput === true } } + } } } @@ -85,3 +96,131 @@ describe('forceRepaintThroughRenderPause', () => { expect(renderService._isPaused).toBe(false) }) }) + +describe('forceFullViewportPresent', () => { + it('fails closed when xterm internals are unavailable', () => { + expect(forceFullViewportPresent(null)).toBe(false) + }) + + it('leaves an unpaused, unsynchronized terminal to the normal refresh path', () => { + // A forced sync renderRows on first splash paints before cell metrics + // settle and shows a 1px black gutter under the TUI composer. + const refreshRows = vi.fn() + const renderRows = vi.fn() + const terminal = createTerminal({ + rows: 24, + renderService: { + _isPaused: false, + _needsFullRefresh: false, + refreshRows, + _renderer: { value: { renderRows } } + } + }) + + expect(forceFullViewportPresent(terminal)).toBe(false) + expect(renderRows).not.toHaveBeenCalled() + expect(refreshRows).not.toHaveBeenCalled() + }) + + it('paints through the renderer so DEC 2026 cannot swallow the reveal present', () => { + const refreshRows = vi.fn() + const renderRows = vi.fn() + const renderService = { + _isPaused: false, + _needsFullRefresh: false, + refreshRows, + _renderer: { value: { renderRows } } + } + const terminal = createTerminal({ + rows: 24, + renderService, + synchronizedOutput: true + }) + + expect(forceFullViewportPresent(terminal)).toBe(true) + expect(renderRows).toHaveBeenCalledWith(0, 23) + expect(refreshRows).not.toHaveBeenCalled() + }) + + it('uses RenderService refreshRows when paused without DEC 2026, matching production splash', () => { + const refreshRows = vi.fn() + const renderRows = vi.fn() + const renderService = { + _isPaused: true, + _needsFullRefresh: true, + refreshRows, + _renderer: { value: { renderRows } } + } + const terminal = createTerminal({ rows: 24, renderService }) + + expect(forceFullViewportPresent(terminal)).toBe(true) + expect(refreshRows).toHaveBeenCalledWith(0, 23, true) + expect(renderRows).not.toHaveBeenCalled() + expect(renderService._isPaused).toBe(false) + }) + + it('leaves pause cleared when the forced render throws so callers can refresh()', () => { + const renderService = { + _isPaused: true, + _needsFullRefresh: true, + refreshRows: vi.fn(() => { + throw new Error('terminal disposed') + }), + _renderer: { value: { renderRows: vi.fn() } } + } + const terminal = createTerminal({ rows: 24, renderService }) + + expect(forceFullViewportPresent(terminal)).toBe(false) + expect(renderService._isPaused).toBe(false) + expect(renderService._needsFullRefresh).toBe(false) + }) +}) + +describe('requestFullViewportPresent', () => { + it('fails closed when xterm internals are unavailable', () => { + expect(requestFullViewportPresent(null)).toBe(false) + }) + + it('leaves a normal visible terminal on the debounced refresh path', () => { + const refreshRows = vi.fn() + const terminal = createTerminal({ + renderService: { _isPaused: false, refreshRows } + }) + + expect(requestFullViewportPresent(terminal)).toBe(false) + expect(refreshRows).not.toHaveBeenCalled() + }) + + it('routes synchronized output through RenderService instead of the renderer', () => { + const refreshRows = vi.fn() + const renderRows = vi.fn() + const terminal = createTerminal({ + rows: 24, + synchronizedOutput: true, + renderService: { + _isPaused: false, + refreshRows, + _renderer: { value: { renderRows } } + } + }) + + expect(requestFullViewportPresent(terminal)).toBe(true) + expect(refreshRows).toHaveBeenCalledWith(0, 23, true) + expect(renderRows).not.toHaveBeenCalled() + }) + + it('releases observer pause before requesting the synchronized frame', () => { + const refreshRows = vi.fn() + const renderService = { + _isPaused: true, + _needsFullRefresh: true, + refreshRows + } + const terminal = createTerminal({ rows: 30, renderService, synchronizedOutput: true }) + + expect(requestFullViewportPresent(terminal)).toBe(true) + expect(renderService._isPaused).toBe(false) + expect(renderService._needsFullRefresh).toBe(false) + expect(refreshRows).toHaveBeenCalledWith(0, 29, true) + }) +}) diff --git a/src/renderer/src/lib/pane-manager/terminal-render-pause-release.ts b/src/renderer/src/lib/pane-manager/terminal-render-pause-release.ts index 88b53129d87..552939e6cd8 100644 --- a/src/renderer/src/lib/pane-manager/terminal-render-pause-release.ts +++ b/src/renderer/src/lib/pane-manager/terminal-render-pause-release.ts @@ -17,10 +17,15 @@ * never throws into a render frame. */ +type MaybeWebglRenderer = { + renderRows?: (start: number, end: number) => void +} + type MaybePausableRenderService = { _isPaused?: boolean _needsFullRefresh?: boolean refreshRows?: (start: number, end: number, sync?: boolean) => void + _renderer?: { value?: MaybeWebglRenderer | null } | MaybeWebglRenderer | null } type PausableRenderService = MaybePausableRenderService & { @@ -31,6 +36,8 @@ type TerminalWithRenderService = { rows?: number _core?: { _renderService?: MaybePausableRenderService + coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } + _coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } } } @@ -71,3 +78,108 @@ export function forceRepaintThroughRenderPause(terminal: unknown): boolean { return false } } + +/** + * Requests a full viewport while preserving a TUI's synchronized-output frame. + * + * Why: ordinary reveal must not publish a half-built DEC 2026 frame. Routing + * through RenderService keeps the previous canvas coherent and arms xterm's + * bounded safety timeout if the TUI never closes the frame. + */ +export function requestFullViewportPresent(terminal: unknown): boolean { + const service = getRenderService(terminal) + if (!service) { + return false + } + const rows = (terminal as TerminalWithRenderService).rows + if (typeof rows !== 'number' || rows < 1) { + return false + } + + const paused = service._isPaused === true + if (!paused && !isSynchronizedOutputHeld(terminal)) { + return false + } + + if (paused) { + service._isPaused = false + service._needsFullRefresh = false + } + + try { + service.refreshRows(0, rows - 1, true) + return true + } catch { + return false + } +} + +function getRenderer(service: MaybePausableRenderService): MaybeWebglRenderer | null { + const holder = service._renderer + if (!holder) { + return null + } + if (typeof (holder as MaybeWebglRenderer).renderRows === 'function') { + return holder as MaybeWebglRenderer + } + const wrapped = (holder as { value?: MaybeWebglRenderer | null }).value + return wrapped ?? null +} + +function isSynchronizedOutputHeld(terminal: unknown): boolean { + const core = (terminal as TerminalWithRenderService)._core + return ( + (core?.coreService?.decPrivateModes ?? core?._coreService?.decPrivateModes) + ?.synchronizedOutput === true + ) +} + +/** + * One synchronous full-viewport present when xterm would otherwise swallow it: + * IntersectionObserver pause, or DEC 2026 synchronized output. + * + * Why not on every paint: a forced renderer.renderRows on a fresh, unpaused + * splash paints before cell metrics settle and leaves a 1px black gutter under + * a TUI composer — production never does that. Callers fall back to + * terminal.refresh() for the normal path. + */ +export function forceFullViewportPresent(terminal: unknown): boolean { + const service = getRenderService(terminal) + if (!service) { + return false + } + const rows = (terminal as TerminalWithRenderService).rows + if (typeof rows !== 'number' || rows < 1) { + return false + } + + const paused = service._isPaused === true + const syncHeld = isSynchronizedOutputHeld(terminal) + if (!paused && !syncHeld) { + return false + } + + if (paused) { + service._isPaused = false + service._needsFullRefresh = false + } + + const renderer = getRenderer(service) + try { + // Why: a new TUI tab is often still paused (observer lag). Painting + // via renderer.renderRows skips RenderService's dimension clamp and draws + // 1px short of the composer box. Production uses refreshRows here. + // renderer.renderRows is only for DEC 2026, which swallows refreshRows. + if (syncHeld && typeof renderer?.renderRows === 'function') { + renderer.renderRows(0, rows - 1) + return true + } + service.refreshRows(0, rows - 1, true) + return true + } catch { + // Why: same as forceRepaintThroughRenderPause — leave the latch cleared so + // the caller's terminal.refresh() fallback can still paint. Restoring + // _isPaused would swallow that refresh until IntersectionObserver fires. + return false + } +} diff --git a/tests/e2e/terminal-reveal-paused-render-repro.spec.ts b/tests/e2e/terminal-reveal-paused-render-repro.spec.ts index 5b280037da4..9efabdea164 100644 --- a/tests/e2e/terminal-reveal-paused-render-repro.spec.ts +++ b/tests/e2e/terminal-reveal-paused-render-repro.spec.ts @@ -1,6 +1,7 @@ +import { writeFile } from 'node:fs/promises' import type { Page } from '@stablyai/playwright-test' import { test, expect } from './helpers/orca-app' -import { getActiveTabId, waitForSessionReady } from './helpers/store' +import { getActiveTabId, getActiveWorktreeId, waitForSessionReady } from './helpers/store' import { execInTerminal, waitForActivePanePtyId, @@ -19,7 +20,7 @@ import { compareTerminalScreenshots } from './terminal-screenshot-diff' * is then swallowed and the freshly-cleared render model never repaints. * * This spec drives the REAL production reveal path (manager.resetWebglTextureAtlases - * -> resetWebglTextureAtlas -> forceRepaintThroughRenderPause) against a real + * -> resetWebglTextureAtlas -> forceFullViewportPresent) against a real * xterm Terminal + RenderService. It: * 1. proves the bug: while paused, a plain refresh() renders nothing; * 2. proves the fix: the real reveal repaint forces a full-viewport render @@ -50,6 +51,16 @@ type RevealRenderDebug = { type RevealProbeWindow = Window & { __revealRenderProbe?: RevealRenderDebug + __syncRevealProbe?: { + paintFrame: (marker: string, background: number, release: boolean) => Promise + forceRendererPresent: () => void + read: () => { + atlasClears: number + fullViewportRenderRows: number + screen: string + synchronizedOutput: boolean + } + } } /** @@ -182,6 +193,154 @@ async function forceWebglOn(page: Page, tabId: string): Promise { }, tabId) } +async function installSynchronizedRevealProbe(page: Page, tabId: string): Promise { + return page.evaluate((tabId) => { + const manager = window.__paneManagers?.get(tabId) + const pane = [ + ...((manager as unknown as { panes?: Map } | undefined)?.panes?.values() ?? + []) + ][0] as + | { + serializeAddon?: { serialize?: () => string } + terminal: unknown + webglAddon?: unknown + } + | undefined + const addon = pane?.webglAddon as { clearTextureAtlas: () => void } | null | undefined + type SyncRenderService = { + _renderer?: + | { renderRows?: (start: number, end: number) => void } + | { value?: { renderRows?: (start: number, end: number) => void } | null } + _syncOutputHandler?: { _timeout?: number } + } + const terminal = pane?.terminal as + | { + cols: number + rows: number + write: (data: string, callback: () => void) => void + _core?: { + coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } + _coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } + _renderService?: SyncRenderService + } + } + | undefined + const service = terminal?._core?._renderService + const modes = + terminal?._core?.coreService?.decPrivateModes ?? + terminal?._core?._coreService?.decPrivateModes + const rendererHolder = service?._renderer + const renderer = + rendererHolder && 'renderRows' in rendererHolder + ? rendererHolder + : rendererHolder && 'value' in rendererHolder + ? rendererHolder.value + : null + if (!pane || !addon || !terminal || !service || !modes || !renderer?.renderRows) { + throw new Error( + JSON.stringify({ + addon: Boolean(addon), + modes: Boolean(modes), + pane: Boolean(pane), + renderer: Boolean(renderer?.renderRows), + rendererKeys: rendererHolder ? Object.keys(rendererHolder) : [], + service: Boolean(service), + terminal: Boolean(terminal) + }) + ) + } + + let atlasClears = 0 + let fullViewportRenderRows = 0 + const originalClear = addon.clearTextureAtlas.bind(addon) + addon.clearTextureAtlas = () => { + atlasClears += 1 + originalClear() + } + const originalRenderRows = renderer.renderRows.bind(renderer) + renderer.renderRows = (start: number, end: number) => { + if (start === 0 && end >= terminal.rows - 1) { + fullViewportRenderRows += 1 + } + originalRenderRows(start, end) + } + + const paintFrame = (marker: string, background: number, release: boolean): Promise => { + const width = Math.max(1, terminal.cols) + const rows = Math.max(1, terminal.rows) + const line = ` ${marker} `.padEnd(width, marker[0] ?? '#').slice(0, width) + const frame = Array.from( + { length: rows }, + (_, row) => `\x1b[${row + 1};1H\x1b[48;5;${background}m\x1b[38;5;231m${line}` + ).join('') + return new Promise((resolve) => { + terminal.write( + `\x1b[?2026h\x1b[?1049h\x1b[2J${frame}\x1b[0m${release ? '\x1b[?2026l' : ''}`, + () => { + if (!release && service._syncOutputHandler?._timeout !== undefined) { + window.clearTimeout(service._syncOutputHandler._timeout) + service._syncOutputHandler._timeout = undefined + } + resolve() + } + ) + }) + } + + ;(window as RevealProbeWindow).__syncRevealProbe = { + paintFrame, + forceRendererPresent: () => renderer.renderRows?.(0, terminal.rows - 1), + read: () => ({ + atlasClears, + fullViewportRenderRows, + screen: pane.serializeAddon?.serialize?.() ?? '', + synchronizedOutput: modes.synchronizedOutput === true + }) + } + return true + }, tabId) +} + +async function callSynchronizedRevealProbe( + page: Page, + action: 'forceRendererPresent' | 'paintFrame', + frame?: { marker: string; background: number; release: boolean } +): Promise { + await page.evaluate( + async ({ action, frame }) => { + const probe = (window as RevealProbeWindow).__syncRevealProbe + if (!probe) { + throw new Error('Synchronized reveal probe not installed') + } + if (action === 'paintFrame') { + if (!frame) { + throw new Error('Synchronized frame missing') + } + await probe.paintFrame(frame.marker, frame.background, frame.release) + return + } + probe.forceRendererPresent() + }, + { action, frame } + ) +} + +async function readSynchronizedRevealProbe(page: Page) { + return page.evaluate(() => { + const probe = (window as RevealProbeWindow).__syncRevealProbe + if (!probe) { + throw new Error('Synchronized reveal probe not installed') + } + return probe.read() + }) +} + +async function captureFirstRevealedFrame(page: Page, tabId: string): Promise { + const screen = page.locator(`[data-terminal-tab-id="${tabId}"] .xterm-screen`).first() + await expect(screen).toBeVisible() + return screen.screenshot({ animations: 'disabled' }) +} + test.describe('terminal reveal paused-render recovery', () => { test("reveal repaint forces a render through xterm's paused gate", async ({ orcaPage }) => { // Why: __store / __paneManagers live on the main Orca renderer window @@ -265,4 +424,233 @@ test.describe('terminal reveal paused-render recovery', () => { `recovered surface matches the revealed content (diffRatio=${diff.diffRatio})` ).toBe(true) }) + + test('@headful atlas recovery presents a synchronized-output WebGL frame', async ({ + orcaPage + }, testInfo) => { + await waitForSessionReady(orcaPage) + await waitForActiveTerminalManager(orcaPage) + const tabId = (await getActiveTabId(orcaPage))! + await forceWebglOn(orcaPage, tabId) + const webglAttached = await orcaPage + .waitForFunction( + (tabId) => + (window.__paneManagers?.get(tabId)?.getRenderingDiagnostics?.() ?? []).some( + (diagnostic) => diagnostic.hasWebgl + ), + tabId, + { timeout: 15_000 } + ) + .then(() => true) + .catch(() => false) + test.skip(!webglAttached, 'WebGL renderer is unavailable') + if (!webglAttached) { + return + } + const installed = await installSynchronizedRevealProbe(orcaPage, tabId) + expect(installed, 'WebGL renderer internals are available').toBe(true) + + await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { + marker: 'BASELINE_FRAME', + background: 17, + release: true + }) + await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { + marker: 'REVEALED_FRAME', + background: 52, + release: false + }) + const held = await readSynchronizedRevealProbe(orcaPage) + expect(held.synchronizedOutput).toBe(true) + expect(held.screen).toContain('REVEALED_FRAME') + + await orcaPage.evaluate((tabId) => { + window.__paneManagers?.get(tabId)?.scheduleRevealRepaint?.() + }, tabId) + await expect + .poll(async () => (await readSynchronizedRevealProbe(orcaPage)).atlasClears) + .toBeGreaterThan(0) + const afterReveal = await captureStableTabScreenshot(orcaPage, tabId) + + await callSynchronizedRevealProbe(orcaPage, 'forceRendererPresent') + const afterForcedPresent = await captureStableTabScreenshot(orcaPage, tabId) + const diff = compareTerminalScreenshots(afterReveal, afterForcedPresent) + const afterRevealPath = testInfo.outputPath('synchronized-frame-after-reveal.png') + const afterForcedPresentPath = testInfo.outputPath( + 'synchronized-frame-after-forced-present.png' + ) + const pixelDiffPath = testInfo.outputPath('synchronized-frame-pixel-diff.json') + await Promise.all([ + writeFile(afterRevealPath, afterReveal), + writeFile(afterForcedPresentPath, afterForcedPresent), + writeFile(pixelDiffPath, JSON.stringify(diff, null, 2)) + ]) + await testInfo.attach('synchronized-frame-after-reveal.png', { + path: afterRevealPath, + contentType: 'image/png' + }) + await testInfo.attach('synchronized-frame-after-forced-present.png', { + path: afterForcedPresentPath, + contentType: 'image/png' + }) + await testInfo.attach('synchronized-frame-pixel-diff.json', { + path: pixelDiffPath, + contentType: 'application/json' + }) + expect( + diff.matches, + `revealed pixels already match a forced buffer present (diffRatio=${diff.diffRatio})` + ).toBe(true) + }) + + test('@headful reveal preserves the coherent frame until synchronized output releases', async ({ + orcaPage + }, testInfo) => { + await waitForSessionReady(orcaPage) + await waitForActiveTerminalManager(orcaPage) + const tabId = (await getActiveTabId(orcaPage))! + const worktreeId = (await getActiveWorktreeId(orcaPage))! + await forceWebglOn(orcaPage, tabId) + const webglAttached = await orcaPage + .waitForFunction( + (tabId) => + (window.__paneManagers?.get(tabId)?.getRenderingDiagnostics?.() ?? []).some( + (diagnostic) => diagnostic.hasWebgl + ), + tabId, + { timeout: 15_000 } + ) + .then(() => true) + .catch(() => false) + test.skip(!webglAttached, 'WebGL renderer is unavailable') + if (!webglAttached) { + return + } + expect(await installSynchronizedRevealProbe(orcaPage, tabId)).toBe(true) + + await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { + marker: 'COHERENT_FRAME', + background: 17, + release: true + }) + const coherent = await captureStableTabScreenshot(orcaPage, tabId) + const beforeHide = await readSynchronizedRevealProbe(orcaPage) + const siblingTabId = await orcaPage.evaluate((worktreeId) => { + const state = window.__store?.getState() + if (!state) { + throw new Error('Renderer store unavailable') + } + return state.createTab(worktreeId, undefined, undefined, { activate: false }).id + }, worktreeId) + await orcaPage.evaluate( + (siblingTabId) => window.__store?.getState().setActiveTab(siblingTabId), + siblingTabId + ) + await expect(orcaPage.locator(`[data-terminal-tab-id="${tabId}"]`)).toBeHidden() + + await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { + marker: 'PENDING_FRAME', + background: 52, + release: false + }) + await orcaPage.evaluate((tabId) => window.__store?.getState().setActiveTab(tabId), tabId) + await expect.poll(() => getActiveTabId(orcaPage)).toBe(tabId) + const held = await captureFirstRevealedFrame(orcaPage, tabId) + const heldState = await readSynchronizedRevealProbe(orcaPage) + const heldDiff = compareTerminalScreenshots(coherent, held) + + expect(heldState.synchronizedOutput).toBe(true) + expect(heldState.screen).toContain('PENDING_FRAME') + expect(heldState.atlasClears - beforeHide.atlasClears, 'ordinary reveal atlas clears').toBe(0) + expect( + heldDiff.matches, + `held reveal preserves the coherent frame (diffRatio=${heldDiff.diffRatio})` + ).toBe(true) + + await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { + marker: 'PENDING_FRAME', + background: 52, + release: true + }) + const released = await captureStableTabScreenshot(orcaPage, tabId) + const releaseState = await readSynchronizedRevealProbe(orcaPage) + await callSynchronizedRevealProbe(orcaPage, 'forceRendererPresent') + const direct = await captureStableTabScreenshot(orcaPage, tabId) + const releasedDiff = compareTerminalScreenshots(released, direct) + + await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { + marker: 'WATCHDOG_FRAME', + background: 88, + release: false + }) + const beforeWatchdog = await readSynchronizedRevealProbe(orcaPage) + await orcaPage.evaluate((tabId) => { + window.__paneManagers?.get(tabId)?.scheduleRevealPresent?.() + }, tabId) + await expect + .poll(async () => (await readSynchronizedRevealProbe(orcaPage)).synchronizedOutput, { + timeout: 2_500 + }) + .toBe(false) + const watchdog = await captureStableTabScreenshot(orcaPage, tabId) + const watchdogState = await readSynchronizedRevealProbe(orcaPage) + await callSynchronizedRevealProbe(orcaPage, 'forceRendererPresent') + const watchdogDirect = await captureStableTabScreenshot(orcaPage, tabId) + const watchdogDiff = compareTerminalScreenshots(watchdog, watchdogDirect) + const coherentPath = testInfo.outputPath('synchronized-coherent-before-hide.png') + const heldPath = testInfo.outputPath('synchronized-coherent-while-held.png') + const releasedPath = testInfo.outputPath('synchronized-new-frame-after-release.png') + const watchdogPath = testInfo.outputPath('synchronized-new-frame-after-watchdog.png') + const metricsPath = testInfo.outputPath('synchronized-prevention-metrics.json') + const counts = (state: Awaited>) => ({ + atlasClears: state.atlasClears, + fullViewportRenderRows: state.fullViewportRenderRows, + synchronizedOutput: state.synchronizedOutput + }) + await Promise.all([ + writeFile(coherentPath, coherent), + writeFile(heldPath, held), + writeFile(releasedPath, released), + writeFile(watchdogPath, watchdog), + writeFile( + metricsPath, + JSON.stringify( + { + beforeHide: counts(beforeHide), + heldState: counts(heldState), + releaseState: counts(releaseState), + beforeWatchdog: counts(beforeWatchdog), + watchdogState: counts(watchdogState), + heldDiff, + releasedDiff, + watchdogDiff + }, + null, + 2 + ) + ) + ]) + for (const [name, path] of [ + ['synchronized-coherent-before-hide.png', coherentPath], + ['synchronized-coherent-while-held.png', heldPath], + ['synchronized-new-frame-after-release.png', releasedPath], + ['synchronized-new-frame-after-watchdog.png', watchdogPath], + ['synchronized-prevention-metrics.json', metricsPath] + ] as const) { + await testInfo.attach(name, { + path, + contentType: name.endsWith('.json') ? 'application/json' : 'image/png' + }) + } + expect(releaseState.synchronizedOutput).toBe(false) + expect( + releasedDiff.matches, + `released frame matches a direct renderer present (diffRatio=${releasedDiff.diffRatio})` + ).toBe(true) + expect(watchdogState.atlasClears - beforeWatchdog.atlasClears).toBe(0) + expect( + watchdogDiff.matches, + `watchdog frame matches a direct renderer present (diffRatio=${watchdogDiff.diffRatio})` + ).toBe(true) + }) }) From f5fd7303ab00bcfeff72c92f2bc33ba9364cd622 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Mon, 24 Aug 2026 08:58:19 -0700 Subject: [PATCH 11/13] test(e2e): cover tab-bar agent launches on Windows and WSL (#16110) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * test(e2e): gate the tab-bar agent launcher on Windows shells and WSL The `+` menu agent launcher had no golden coverage in the Windows lane, so a Windows-only break anywhere in its chain (detection row, startup-plan build, tab create, PTY spawn, startup-command injection) could ship unnoticed. Adds a golden spec that launches a stub agent from the menu and asserts the agent's own banner reached the pane — a tab that spawned a bare shell instead is indistinguishable at the store/tab layer. Runs two agents everywhere, and on Windows also PowerShell, cmd, Git Bash and a WSL project runtime. * test(e2e): track WSL stub agent staging state for precise cleanup Refactor `stageWslGoldenStubAgent` to track which artifacts it creates during setup, then only remove those artifacts during cleanup. This prevents the test from destructively removing pre-existing symlinks or state from previous runs, improving test isolation and idempotency. * test(e2e): track WSL stub agent staging state for precise cleanup - Back up and restore pre-existing stub agents to avoid destroying them - Simplify verbose test comments to match project style guidelines * test(e2e): serialize WSL stub agent setup with distributed lock - Add mkdir-based lock to prevent concurrent staging invocations - Reclaim stale locks after 10 minutes to recover from crashes - Track lock ownership in stage state for safe cleanup * test(e2e): track WSL stub agent staging state for precise cleanup Track which stubs this test helper stages by writing a marker file, then only remove stubs during stale-lock recovery if we created them. Prevents cleanup from removing stubs left by other processes. --- .github/workflows/golden-e2e-experiment.yml | 3 + package.json | 1 + tests/e2e/fixtures/golden-stub-agent/claude | 2 + .../e2e/fixtures/golden-stub-agent/claude.cmd | 2 + tests/e2e/golden-tab-bar-agent-launch.spec.ts | 90 ++++++++++ tests/e2e/helpers/golden-stub-agent.ts | 50 ++++-- tests/e2e/helpers/wsl-golden-stub-agent.ts | 159 ++++++++++++++++++ 7 files changed, 293 insertions(+), 14 deletions(-) create mode 100755 tests/e2e/fixtures/golden-stub-agent/claude create mode 100644 tests/e2e/fixtures/golden-stub-agent/claude.cmd create mode 100644 tests/e2e/golden-tab-bar-agent-launch.spec.ts create mode 100644 tests/e2e/helpers/wsl-golden-stub-agent.ts diff --git a/.github/workflows/golden-e2e-experiment.yml b/.github/workflows/golden-e2e-experiment.yml index 1f0a2b42755..040996489d1 100644 --- a/.github/workflows/golden-e2e-experiment.yml +++ b/.github/workflows/golden-e2e-experiment.yml @@ -74,6 +74,7 @@ jobs: xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:posix-profile-index-golden xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:agent-tui-golden + xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:tab-bar-agent-launch-golden xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:source-control-golden - name: Run golden E2E tests on macOS @@ -87,6 +88,7 @@ jobs: env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:posix-profile-index-golden env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:agent-tui-golden + env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:tab-bar-agent-launch-golden env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:source-control-golden - name: Run golden E2E tests on Windows @@ -97,6 +99,7 @@ jobs: $env:ORCA_E2E_FORWARD_APP_LOGS = '1' pnpm run --if-present test:e2e:workspace-session-golden pnpm run --if-present test:e2e:windows-fresh-startup-golden + pnpm run --if-present test:e2e:tab-bar-agent-launch-golden if (Test-Path tests/e2e/golden-fresh-profile-terminal.spec.ts) { pnpm run test:e2e -- tests/e2e/golden-fresh-profile-terminal.spec.ts tests/e2e/golden-shell-command.spec.ts } diff --git a/package.json b/package.json index a026bdb7824..66d0d0bf53e 100644 --- a/package.json +++ b/package.json @@ -100,6 +100,7 @@ "test:e2e:posix-profile-index-golden": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/golden-posix-fresh-startup.spec.ts tests/e2e/golden-posix-profile-index-fsync.spec.ts --grep @posix-profile-index-golden --config tests/playwright.config.ts --project electron-headless --workers=1", "test:e2e:windows-fresh-startup-golden": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/golden-windows-fresh-startup.spec.ts --grep @windows-fresh-startup-golden --config tests/playwright.config.ts --project electron-headless --workers=1", "test:e2e:agent-tui-golden": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/golden-agent-tui-launch.spec.ts tests/e2e/golden-shell-after-agent-exit.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "test:e2e:tab-bar-agent-launch-golden": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/golden-tab-bar-agent-launch.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "test:e2e:terminal-rendering-release-evidence": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/terminal-opencode-emoji-table-rendering.spec.ts tests/e2e/terminal-long-table-scroll-restore.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=2", "test:e2e:terminal-perf": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/terminal-typing-latency.spec.ts tests/e2e/terminal-foreground-redraw-freeze.spec.ts tests/e2e/terminal-output-scheduler.spec.ts tests/e2e/terminal-hidden-tui-visual-restore.spec.ts tests/e2e/artificial-opencode-terminal-load.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=2", "test:e2e:terminal-perf:scale": "pnpm run ensure:electron-runtime && node config/scripts/run-terminal-scale-perf-e2e.mjs", diff --git a/tests/e2e/fixtures/golden-stub-agent/claude b/tests/e2e/fixtures/golden-stub-agent/claude new file mode 100755 index 00000000000..d16a99de266 --- /dev/null +++ b/tests/e2e/fixtures/golden-stub-agent/claude @@ -0,0 +1,2 @@ +#!/bin/sh +exec "$(dirname "$0")/golden-stub-agent" "$@" diff --git a/tests/e2e/fixtures/golden-stub-agent/claude.cmd b/tests/e2e/fixtures/golden-stub-agent/claude.cmd new file mode 100644 index 00000000000..894a9216aa2 --- /dev/null +++ b/tests/e2e/fixtures/golden-stub-agent/claude.cmd @@ -0,0 +1,2 @@ +@echo off +call "%~dp0golden-stub-agent.cmd" %* diff --git a/tests/e2e/golden-tab-bar-agent-launch.spec.ts b/tests/e2e/golden-tab-bar-agent-launch.spec.ts new file mode 100644 index 00000000000..d8501c0a668 --- /dev/null +++ b/tests/e2e/golden-tab-bar-agent-launch.spec.ts @@ -0,0 +1,90 @@ +import type { Page } from '@stablyai/playwright-test' +import { expect, test } from './helpers/orca-app' +import { + configureGoldenStubAgent, + getGoldenStubAgentLaunchEnv, + GOLDEN_STUB_AGENTS, + GOLDEN_STUB_READY_MARKER, + launchGoldenStubAgentFromNewTab +} from './helpers/golden-stub-agent' +import { + getFirstWslDistro, + removeWslGoldenStubAgent, + stageWslGoldenStubAgent, + useWslRuntimeForActiveProject +} from './helpers/wsl-golden-stub-agent' +import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { getTerminalContent } from './helpers/terminal' +import type { BuiltInWindowsTerminalShell } from '../../src/shared/windows-terminal-shell' + +// Covers the Windows-only tab-bar launch path that the default-shell test misses. + +test.use({ launchEnv: getGoldenStubAgentLaunchEnv() }) + +const WINDOWS_SHELLS: readonly BuiltInWindowsTerminalShell[] = [ + 'powershell.exe', + 'cmd.exe', + 'git-bash' +] + +async function openWorkspaceTerminal(page: Page): Promise { + await waitForSessionReady(page) + await waitForActiveWorktree(page) + await ensureTerminalVisible(page) +} + +for (const { id, menuItemName } of GOLDEN_STUB_AGENTS) { + test(`tab-bar + menu launches ${id} into a live TUI @tab-bar-agent-launch-golden`, async ({ + orcaPage + }) => { + await openWorkspaceTerminal(orcaPage) + await configureGoldenStubAgent(orcaPage, { agent: id }) + await launchGoldenStubAgentFromNewTab(orcaPage, menuItemName) + + const activeTab = orcaPage.locator('[data-testid="sortable-tab"][data-active="true"]') + await expect(activeTab).toHaveAttribute('data-tab-title', /Golden Stub Agent|Codex|Claude/i) + // The marker distinguishes an agent launch from an identical bare-shell tab. + expect(await getTerminalContent(orcaPage)).toContain(GOLDEN_STUB_READY_MARKER) + }) +} + +// Suite-level skipping avoids launching Electron for each unsupported case. +test.describe('Windows runtimes', () => { + test.skip(process.platform !== 'win32', 'Windows agent launch matrix is Windows-only') + + for (const shell of WINDOWS_SHELLS) { + test(`tab-bar + menu launches an agent under ${shell} @tab-bar-agent-launch-golden`, async ({ + orcaPage + }) => { + await openWorkspaceTerminal(orcaPage) + // Each shell family requires different launch-command quoting. + await configureGoldenStubAgent(orcaPage, { agent: 'codex', windowsShell: shell }) + await launchGoldenStubAgentFromNewTab(orcaPage) + + expect(await getTerminalContent(orcaPage)).toContain(GOLDEN_STUB_READY_MARKER) + }) + } + + test('tab-bar + menu launches an agent inside WSL @tab-bar-agent-launch-golden', async ({ + orcaPage + }) => { + await openWorkspaceTerminal(orcaPage) + + const distro = await getFirstWslDistro(orcaPage) + test.skip(!distro, 'No WSL distro is available on this Windows host') + const stage = stageWslGoldenStubAgent(distro!) + test.skip(!stage, 'WSL distro would not accept the staged stub agent') + + try { + // WSL must retarget both agent detection and the PTY. + await useWslRuntimeForActiveProject(orcaPage, distro!) + await configureGoldenStubAgent(orcaPage, { agent: 'codex' }) + await launchGoldenStubAgentFromNewTab(orcaPage) + + // The distro-only marker proves the agent ran in WSL. + expect(await getTerminalContent(orcaPage)).toContain(GOLDEN_STUB_READY_MARKER) + } finally { + removeWslGoldenStubAgent(distro!, stage!) + } + }) +}) diff --git a/tests/e2e/helpers/golden-stub-agent.ts b/tests/e2e/helpers/golden-stub-agent.ts index 62e44c9b091..5f01e691c53 100644 --- a/tests/e2e/helpers/golden-stub-agent.ts +++ b/tests/e2e/helpers/golden-stub-agent.ts @@ -2,10 +2,17 @@ import path from 'node:path' import type { Page } from '@stablyai/playwright-test' import { expect } from '@stablyai/playwright-test' import { focusActiveTerminalInput, waitForTerminalOutput } from './terminal' +import type { BuiltInWindowsTerminalShell } from '../../../src/shared/windows-terminal-shell' export const GOLDEN_STUB_READY_MARKER = 'GOLDEN_STUB_AGENT_READY' export const GOLDEN_STUB_EXIT_MARKER = 'GOLDEN_STUB_AGENT_EXITED' +/** Agents exposed by the fixture directory for tab-bar detection. */ +export const GOLDEN_STUB_AGENTS = [ + { id: 'codex', menuItemName: /^Codex(?:\s|$)/i }, + { id: 'claude', menuItemName: /^Claude(?:\s|$)/i } +] as const + const fixtureDir = path.join(process.cwd(), 'tests', 'e2e', 'fixtures', 'golden-stub-agent') export function getGoldenStubAgentLaunchEnv(): NodeJS.ProcessEnv { @@ -15,23 +22,38 @@ export function getGoldenStubAgentLaunchEnv(): NodeJS.ProcessEnv { } } -export async function configureGoldenStubAgent(page: Page): Promise { - await page.evaluate(async () => { - const store = window.__store - if (!store) { - throw new Error('Orca store is unavailable') - } - await store.getState().updateSettings({ - defaultTuiAgent: 'codex', - agentCmdOverrides: { codex: 'golden-stub-agent' }, - agentDefaultArgs: { codex: '' } - }) - }) +export async function configureGoldenStubAgent( + page: Page, + options: { + agent?: (typeof GOLDEN_STUB_AGENTS)[number]['id'] + /** Windows default shell the launch command must survive; ignored elsewhere. */ + windowsShell?: BuiltInWindowsTerminalShell + } = {} +): Promise { + const agent = options.agent ?? 'codex' + await page.evaluate( + async ({ agent, windowsShell }) => { + const store = window.__store + if (!store) { + throw new Error('Orca store is unavailable') + } + await store.getState().updateSettings({ + defaultTuiAgent: agent, + agentCmdOverrides: { [agent]: 'golden-stub-agent' }, + agentDefaultArgs: { [agent]: '' }, + ...(windowsShell ? { terminalWindowsShell: windowsShell } : {}) + }) + }, + { agent, windowsShell: options.windowsShell ?? null } + ) } -export async function launchGoldenStubAgentFromNewTab(page: Page): Promise { +export async function launchGoldenStubAgentFromNewTab( + page: Page, + menuItemName: RegExp = /^Codex(?:\s|$)/i +): Promise { await page.getByRole('button', { name: 'New tab' }).click({ force: true }) - const launchOption = page.getByRole('menuitem', { name: /^Codex(?:\s|$)/i }).first() + const launchOption = page.getByRole('menuitem', { name: menuItemName }).first() await expect(launchOption).toBeVisible({ timeout: 15_000 }) await launchOption.click({ force: true }) await focusActiveTerminalInput(page) diff --git a/tests/e2e/helpers/wsl-golden-stub-agent.ts b/tests/e2e/helpers/wsl-golden-stub-agent.ts new file mode 100644 index 00000000000..0b09644c14b --- /dev/null +++ b/tests/e2e/helpers/wsl-golden-stub-agent.ts @@ -0,0 +1,159 @@ +import { execFileSync } from 'node:child_process' +import type { Page } from '@stablyai/playwright-test' +import { buildWslExecArgs } from '../../../src/shared/wsl-login-shell-command' + +/** A WSL-only path makes the stub marker proof that the pane ran in the distro. */ +const WSL_STUB_PATH = '/usr/local/bin/golden-stub-agent' +const WSL_STUB_AGENT_LINK = '/usr/local/bin/codex' +const WSL_STUB_BACKUP_PATH = '/usr/local/bin/golden-stub-agent.orca-e2e-backup' +/** mkdir is atomic in the distro, so the lock dir serializes overlapping invocations. */ +const WSL_STUB_LOCK_PATH = '/usr/local/bin/golden-stub-agent.orca-e2e-lock' +const WSL_STUB_LINK_MARKER = `${WSL_STUB_LOCK_PATH}/created-codex-link` +const WSL_STUB_STAGED_MARKER = `${WSL_STUB_LOCK_PATH}/staged-stub` +const WSL_STUB_LOCK_STALE_MINUTES = 10 +const WSL_STUB_LOCK_WAIT_SECONDS = 60 + +// Undoes a lock holder that died mid-run, so its leftovers cannot poison later invocations. +const RECLAIM_STALE_LOCK_SCRIPT = + `if [ -e ${WSL_STUB_LINK_MARKER} ]; then rm -f ${WSL_STUB_AGENT_LINK}; fi; ` + + `if [ -e ${WSL_STUB_STAGED_MARKER} ]; then rm -f ${WSL_STUB_PATH}; fi; ` + + `if [ -e ${WSL_STUB_BACKUP_PATH} ] || [ -L ${WSL_STUB_BACKUP_PATH} ]; then ` + + `mv ${WSL_STUB_BACKUP_PATH} ${WSL_STUB_PATH}; fi; ` + + `rm -rf ${WSL_STUB_LOCK_PATH}` + +const ACQUIRE_LOCK_SCRIPT = + `mkdir -p /usr/local/bin || exit 1; i=0; ` + + `while [ $i -lt ${WSL_STUB_LOCK_WAIT_SECONDS} ]; do ` + + `if mkdir ${WSL_STUB_LOCK_PATH} 2>/dev/null; then printf acquired; exit 0; fi; ` + + `if [ -n "$(find ${WSL_STUB_LOCK_PATH} -maxdepth 0 -mmin +${WSL_STUB_LOCK_STALE_MINUTES} ` + + `2>/dev/null)" ]; then ${RECLAIM_STALE_LOCK_SCRIPT}; else sleep 1; fi; i=$((i+1)); ` + + `done; printf timeout` + +// Keep the cross-boundary script newline-free to avoid Windows argv-encoding surprises. +// Moving the entry avoids following and overwriting a pre-existing symlink. +const BACKUP_EXISTING_STUB_SCRIPT = + `mkdir -p /usr/local/bin && ` + + `if [ -e ${WSL_STUB_BACKUP_PATH} ] || [ -L ${WSL_STUB_BACKUP_PATH} ]; then exit 1; fi && ` + + `if [ -e ${WSL_STUB_PATH} ] || [ -L ${WSL_STUB_PATH} ]; then ` + + `mv ${WSL_STUB_PATH} ${WSL_STUB_BACKUP_PATH} && ` + + `printf backed-up; else printf none; fi` + +// The marker is written first so stale-lock recovery only removes a stub this helper wrote. +const STAGE_SCRIPT = + `mkdir -p /usr/local/bin && : > ${WSL_STUB_STAGED_MARKER} && ` + + `printf '#!/bin/sh\\necho GOLDEN_STUB_AGENT_READY\\nexec sleep 3600\\n' > ${WSL_STUB_PATH} && ` + + `chmod 0755 ${WSL_STUB_PATH}` + +// The marker is written before the link so a crashed run over-reports rather than leaks a link. +const STAGE_CODEX_LINK_IF_MISSING_SCRIPT = + `if [ -e ${WSL_STUB_AGENT_LINK} ] || [ -L ${WSL_STUB_AGENT_LINK} ]; then ` + + `printf existing; else : > ${WSL_STUB_LINK_MARKER} && ` + + `ln -s ${WSL_STUB_PATH} ${WSL_STUB_AGENT_LINK} && printf created; fi` + +// `;` between steps so the lock is released even when a restore step fails. +function buildRestoreScript(stage: WslGoldenStubAgentStage): string { + const steps: string[] = [] + if (stage.ownsStubPath) { + const removed = stage.createdCodexLink + ? `${WSL_STUB_AGENT_LINK} ${WSL_STUB_PATH}` + : WSL_STUB_PATH + steps.push(`rm -f ${removed}`) + if (stage.backedUpStub) { + steps.push(`mv ${WSL_STUB_BACKUP_PATH} ${WSL_STUB_PATH}`) + } + } + if (stage.heldLock) { + steps.push(`rm -rf ${WSL_STUB_LOCK_PATH}`) + } + return steps.join(' ; ') +} + +// --exec prevents wsl.exe from expanding shell variables in argv. +function runInWslAsRoot(distro: string, script: string): string { + return execFileSync( + 'wsl.exe', + ['-u', 'root', ...buildWslExecArgs(distro, ['sh', '-c', script])], + { encoding: 'utf8', stdio: 'pipe', windowsHide: true } + ) +} + +export async function getFirstWslDistro(page: Page): Promise { + const wsl = await page.evaluate(async () => ({ + available: await window.api.wsl.isAvailable(), + distros: await window.api.wsl.listDistros() + })) + return wsl.available ? (wsl.distros[0] ?? null) : null +} + +export type WslGoldenStubAgentStage = { + createdCodexLink: boolean + backedUpStub: boolean + ownsStubPath: boolean + heldLock: boolean +} + +/** Returns null when the distro cannot stage the stub. Holds a distro lock until cleanup. */ +export function stageWslGoldenStubAgent(distro: string): WslGoldenStubAgentStage | null { + const stage: WslGoldenStubAgentStage = { + createdCodexLink: false, + backedUpStub: false, + ownsStubPath: false, + heldLock: false + } + try { + if (runInWslAsRoot(distro, ACQUIRE_LOCK_SCRIPT).trim() !== 'acquired') { + return null + } + stage.heldLock = true + stage.backedUpStub = runInWslAsRoot(distro, BACKUP_EXISTING_STUB_SCRIPT).trim() === 'backed-up' + stage.ownsStubPath = true + runInWslAsRoot(distro, STAGE_SCRIPT) + stage.createdCodexLink = + runInWslAsRoot(distro, STAGE_CODEX_LINK_IF_MISSING_SCRIPT).trim() === 'created' + return stage + } catch { + removeWslGoldenStubAgent(distro, stage) + return null + } +} + +export function removeWslGoldenStubAgent(distro: string, stage: WslGoldenStubAgentStage): void { + const script = buildRestoreScript(stage) + if (!script) { + return + } + try { + runInWslAsRoot(distro, script) + stage.heldLock = false + stage.ownsStubPath = false + } catch { + // Best-effort cleanup; a leftover stub only affects this fixture's own name. + } +} + +/** Retargets project agent detection and terminal spawning to WSL. */ +export async function useWslRuntimeForActiveProject(page: Page, distro: string): Promise { + await page.evaluate(async (wslDistro) => { + const store = window.__store + if (!store) { + throw new Error('Orca store is unavailable') + } + const state = store.getState() + const worktreeId = state.activeWorktreeId + if (!worktreeId) { + throw new Error('No active worktree') + } + const activeWorktree = Object.values(state.worktreesByRepo) + .flat() + .find((worktree) => worktree.id === worktreeId) + const activeProject = state.projects.find((project) => + activeWorktree ? project.sourceRepoIds.includes(activeWorktree.repoId) : false + ) + if (!activeProject) { + throw new Error('No active project') + } + await state.updateProject(activeProject.id, { + localWindowsRuntimePreference: { kind: 'wsl', distro: wslDistro } + }) + }, distro) +} From c618ec739376783bd167ed2691926e92af6ed097 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 24 Aug 2026 09:38:46 -0700 Subject: [PATCH 12/13] test(reliability): protect recent P0 regression invariants (#16163) --- .github/workflows/pr.yml | 38 +- config/reliability-gates.jsonc | 416 +++++++++++++++- config/scripts/pr-e2e-gate-contract.test.mjs | 132 +++++- config/scripts/pr-e2e-source-routing.mjs | 117 +++++ ...ws-pty-native-capability-workflow.test.mjs | 70 +++ package.json | 1 + ...-prompt-submission-runtime-test-fixture.ts | 28 ++ .../agent-prompt-submission-runtime.test.ts | 44 +- ...-runtime-terminal-close-continuity.test.ts | 250 +++++++++- ...ation-worker-start-prompt-contract.test.ts | 277 +++++++++++ ...-connection-direct-ssh-spawn-retry.test.ts | 42 ++ .../agent-idle-working-handlers.ts | 11 +- .../pty-connection/connect-pane-pty.ts | 39 ++ .../deferred-session-reattach-choice.ts | 13 +- .../pty-connection/fresh-spawn-start.ts | 81 +++- .../pty-connection/pty-connect-limits.ts | 1 + .../pty-connection/terminal-tab-id.test.ts | 33 ++ .../pty-connection/terminal-tab-id.ts | 15 + .../pty-transport-connect-spawn.test.ts | 12 + .../terminal-pane/pty-transport-types.ts | 2 + .../components/terminal-pane/pty-transport.ts | 11 + .../terminal-pty-pre-spawn-e2e-barrier.ts | 72 +++ src/renderer/src/env.d.ts | 2 + .../terminal-tab-recovery-remount.test.ts | 14 + src/renderer/src/store/slices/terminals.ts | 5 + .../session/worktree-slice-lookups.ts | 13 +- tests/e2e/global-teardown.ts | 59 ++- tests/e2e/global-teardown.unit.test.ts | 52 ++ ...al-quick-command-pre-bind-recovery.spec.ts | 349 ++++++++++++++ .../README.md | 16 + .../packaged-node-pty-capability-oracle.mjs | 139 ++++++ ...ckaged-node-pty-capability-oracle.test.mjs | 98 ++++ .../packaged-node-pty-capability-probe.cjs | 448 ++++++++++++++++++ ...ackaged-node-pty-capability-probe.test.mjs | 89 ++++ .../real-orca-detached-launcher.vbs | 24 + .../run.mjs | 72 +++ .../run.test.mjs | 47 ++ 37 files changed, 2986 insertions(+), 146 deletions(-) create mode 100644 config/scripts/pr-e2e-source-routing.mjs create mode 100644 config/scripts/windows-pty-native-capability-workflow.test.mjs create mode 100644 src/main/runtime/agent-prompt-submission-runtime-test-fixture.ts create mode 100644 src/main/runtime/rpc/methods/orchestration-worker-start-prompt-contract.test.ts create mode 100644 src/renderer/src/components/terminal-pane/pty-connection/terminal-tab-id.test.ts create mode 100644 src/renderer/src/components/terminal-pane/pty-connection/terminal-tab-id.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-pty-pre-spawn-e2e-barrier.ts create mode 100644 tests/e2e/global-teardown.unit.test.ts create mode 100644 tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts create mode 100644 tests/tools/windows-pty-native-capability-smoke/README.md create mode 100644 tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-oracle.mjs create mode 100644 tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-oracle.test.mjs create mode 100644 tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-probe.cjs create mode 100644 tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-probe.test.mjs create mode 100644 tests/tools/windows-pty-native-capability-smoke/real-orca-detached-launcher.vbs create mode 100644 tests/tools/windows-pty-native-capability-smoke/run.mjs create mode 100644 tests/tools/windows-pty-native-capability-smoke/run.test.mjs diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 01724348ba6..22fb956a1a5 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -673,6 +673,9 @@ jobs: ORCA_REUSE_PREPARED_NATIVE_RUNTIME: '1' run: pnpm exec electron-builder --config config/electron-builder.config.cjs --dir + - name: Smoke packaged Windows PTY native capability + run: pnpm run smoke:windows-pty-native-capability -- --exe=dist/win-unpacked/Orca.exe + - name: Smoke packaged CLI run: node config/scripts/smoke-packaged-cli.mjs --app-dir=dist/win-unpacked @@ -707,38 +710,9 @@ jobs: BASE="${{ github.event.pull_request.base.sha }}" HEAD="${{ github.event.pull_request.head.sha }}" CHANGED="$(git diff --name-only --diff-filter=AMCR --merge-base "$BASE" "$HEAD")" - TEST_FILES="$(printf '%s\n' "$CHANGED" | grep -E '^tests/e2e/.*\.spec\.ts$' || true)" - if printf '%s\n' "$CHANGED" | grep -Eq '^src/(main/ephemeral-vm-(runtime-(service|provisioning-persistence)|failed-start-cleanup)|shared/(ephemeral-vm-runtime-(store|feature-store|rollback-projection|runtimes)|ephemeral-vm-recipes|orca-yaml-hook-types))\.ts$'; then - TEST_FILES="$(printf '%s\n%s\n' "$TEST_FILES" 'tests/e2e/ephemeral-vm-provisioned-root.spec.ts' | sort -u)" - fi - # Why: the Docker-SSH specs only ever ran when someone edited a spec, so four - # pane-restore regressions shipped from SSH source edits that touched no test. - # Unit tests are excluded because they prove the same source without Docker. - # ssh-startup-exec-readiness.spec.ts is listed to route e2e.yml's dedicated - # ssh-docker-watcher-isolation lane, which filters it out of changed-e2e. - if printf '%s\n' "$CHANGED" | grep -Ev '\.test\.tsx?$' | grep -Eq '^(src/main/ssh/|src/main/providers/ssh-|src/main/ipc/(ssh-|pty)|src/relay/|src/renderer/src/components/terminal-pane/(pty-|ssh-|remote-runtime-|terminal-parked-pty))'; then - TEST_FILES="$(printf '%s\n' "$TEST_FILES" \ - 'tests/e2e/pty-input-write-queue-ssh.spec.ts' \ - 'tests/e2e/ssh-cold-activation-restore.spec.ts' \ - 'tests/e2e/ssh-docker-reconnect-pane-restore.spec.ts' \ - 'tests/e2e/ssh-startup-exec-readiness.spec.ts' \ - 'tests/e2e/ssh-terminal-window-wake-stale-grid-repro.spec.ts' | sort -u)" - fi - # Why: same lesson as the SSH specs above. The IME e2e suite asserts real pty bytes and - # real overlay geometry, but only ran when someone edited a spec, so every IME fix in the - # 1.4.18x window shipped without it - including one whose diagnosis hardware later refuted. - # config/patches is listed because the terminal's input handling lives in the xterm patch. - if printf '%s\n' "$CHANGED" | grep -Ev '\.test\.tsx?$' | grep -Eq '^(config/patches/|src/renderer/src/components/terminal-pane/(terminal-ime-|use-terminal-pane-lifecycle|xterm-bypass-policy|terminal-option-shortcut-policy))'; then - TEST_FILES="$(printf '%s\n' "$TEST_FILES" \ - 'tests/e2e/terminal-cjk-ime-committed-text.spec.ts' \ - 'tests/e2e/terminal-hangul-wrap-boundary-bytes.spec.ts' \ - 'tests/e2e/terminal-ime-exact-byte.spec.ts' \ - 'tests/e2e/terminal-korean-composing-chord-order.spec.ts' \ - 'tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts' \ - 'tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts' \ - 'tests/e2e/terminal-korean-preedit-visibility.spec.ts' | sort -u)" - fi - TEST_FILES_JSON="$(printf '%s\n' "$TEST_FILES" | jq --raw-input --slurp --compact-output 'split("\n") | map(select(length > 0))')" + # Source routes are executable contracts so a test can prove exact + # authorities, exclusions, and sentinels without evaluating workflow shell. + TEST_FILES_JSON="$(printf '%s\n' "$CHANGED" | node config/scripts/pr-e2e-source-routing.mjs)" echo "test_files=$TEST_FILES_JSON" >> "$GITHUB_OUTPUT" if [ "$TEST_FILES_JSON" != '[]' ]; then echo "should_run=true" >> "$GITHUB_OUTPUT" diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 97711a43088..c0fcd77c2fb 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "updatedAt": "2026-08-20", + "updatedAt": "2026-08-23", "policy": { "maturityLevels": ["experimental", "soak", "blocking", "accepted-gap", "deprecated"], "blockingPromotion": { @@ -3680,14 +3680,16 @@ "providers": ["local", "daemon", "ssh", "runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "ssh", "runtime"], - "coverageNotes": "Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. Deterministic tests cover final-pane CLI close durability, persisted-empty restart suppression, same-incarnation handle continuity, replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. That claim now covers BOTH shapes, including the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId - each asserted by its own test. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here.", + "coverageNotes": "Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. A deterministic final-pane interleaving now proves durable tab retirement commits before externally owned PTY teardown can publish graph loss, and preserves an unrelated live canary through duplicate exit retirement. Deterministic tests also cover final-pane CLI close durability, persisted-empty restart suppression, same-incarnation handle continuity, replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. That claim now covers BOTH shapes, including the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId - each asserted by its own test. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here.", "motivatingLinks": [ + "https://linear.app/stably/issue/STA-4327", + "https://github.com/stablyai/orca/pull/14590", "https://github.com/stablyai/orca/pull/8628", "https://github.com/stablyai/orca/pull/8706", "https://github.com/stablyai/orca/issues/14524" ], - "invariant": "Close permanently removes the owned provider session, agent descendants, persisted tab/layout authority, and resume authority even when no TerminalPane is mounted; final-pane CLI close does not acknowledge before durable tab retirement, and a persisted explicit-empty state prevents initial-tab fallback from repopulating the workspace after reload or restart. A handle remains valid while the same provider-attested PTY incarnation survives renderer reload or re-key, and becomes stale without adopting a replacement incarnation. A terminating id remains reserved through natural exit, duplicate callers await the same completion, and immediate teardown upgrades any graceful request without signalling a recycled PID or a descendant tree after root ownership is lost; process-table work is locale-stable, bounded, fresh for each post-start request, same-turn coalesced, and begins within the requesting caller's deadline, including bulk worktree cleanup; detach and park preserve ownership; aliases prevent a detached agent's immutable physical pane key from being retired with its former tab.", - "oracle": "Capture exact tab, pane, PTY, handle, incarnation, and persisted layout identities. Final-pane terminal.close must kill the exact PTY once, invoke one durability-acknowledged tab retirement, stay pending until the persisted row is removed, and never fall back to the fire-and-forget pane event; reload/restart must keep the explicitly emptied worktree at zero terminal tabs and provider sessions. Reloading the renderer with the same tab/pane/PTY/incarnation must keep the handle readable; changing only the incarnation behind the same PTY id, losing the authoritative graph, or superseding the renderer handle with a preallocated handle must reject the old handle with terminal_handle_stale. Parked-close tests prove the exact PTY disappears; descendant/process tests keep natural exits reserved, upgrade teardown safely, bound/coalesce process-table work, and protect recycled identities.", + "invariant": "Close permanently removes the owned provider session, agent descendants, persisted tab/layout authority, and resume authority even when no TerminalPane is mounted; final-pane CLI close commits durable tab retirement before PTY stop can publish graph loss, does not acknowledge before that retirement, and treats the later exit retirement as idempotent. A persisted explicit-empty state prevents initial-tab fallback from repopulating the workspace after reload or restart. A handle remains valid while the same provider-attested PTY incarnation survives renderer reload or re-key, and becomes stale without adopting a replacement incarnation. A terminating id remains reserved through natural exit, duplicate callers await the same completion, and immediate teardown upgrades any graceful request without signalling a recycled PID or a descendant tree after root ownership is lost; process-table work is locale-stable, bounded, fresh for each post-start request, same-turn coalesced, and begins within the requesting caller's deadline, including bulk worktree cleanup; detach and park preserve ownership; aliases prevent a detached agent's immutable physical pane key from being retired with its former tab.", + "oracle": "Capture exact tab, pane, PTY, handle, incarnation, and persisted layout identities. Final-pane terminal.close must invoke one durability-acknowledged tab retirement before exact PTY teardown; controlled PTY exit and graph removal afterward must remain idempotent, omit the target from persistence and provider inventory, and leave an unrelated canary handle live. The ordinary path stays pending until the persisted row is removed and never falls back to the fire-and-forget pane event; reload/restart must keep the explicitly emptied worktree at zero terminal tabs and provider sessions. Reloading the renderer with the same tab/pane/PTY/incarnation must keep the handle readable; changing only the incarnation behind the same PTY id, losing the authoritative graph, or superseding the renderer handle with a preallocated handle must reject the old handle with terminal_handle_stale. Parked-close tests prove the exact PTY disappears; descendant/process tests keep natural exits reserved, upgrade teardown safely, bound/coalesce process-table work, and protect recycled identities.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime-terminal-close-continuity.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/initial-terminal.test.ts src/renderer/src/lib/worktree-activation-default-tabs.test.ts src/renderer/src/store/slices/terminals-explicit-empty-hydration.test.ts", @@ -3733,6 +3735,7 @@ "file": "src/main/runtime/orca-runtime-terminal-close-continuity.test.ts", "assertions": [ "final-pane terminal.close remains pending until one renderer durability acknowledgement retires the persisted tab and layout", + "final-pane externally owned teardown commits session retirement before PTY stop, tolerates duplicate exit retirement, and preserves an unrelated live canary", "post-ack workspace-session loss falls back to renderer cleanup and verified PTY teardown while every pre-ack retirement error remains non-destructive", "renderer reload with the same provider-attested PTY incarnation preserves the exact handle", "same-id replacement incarnation publishes a new handle and makes the old handle deterministically stale", @@ -3913,7 +3916,7 @@ }, "redGreenEvidence": { "status": "complete", - "evidence": "STA-4327 used two byte-identical oracles. Runtime oracle cd248b67cc10ef64f2def315b86c3b0236b102639d03c65a0c5d9519e538d3af failed the same three durability/continuity checks on reported v1.4.180 (0b62333cf1), latest main (9bb8836bb6), and disabled fix; runtime candidate 3cf8a37447 passed 5/5, and final code candidate 121e112d77 separately passed its expanded 6/6 oracle. Renderer oracle 3b0949eef8b792cf5b09cfa55341f4216c08714f158e4b132e988e8114636cea failed both explicit-empty hydration/fallback checks on v1.4.180, latest main, and disabled fix, while renderer candidate 121e112d77 passed 2/2." + "evidence": "STA-4327 used two byte-identical oracles. Runtime oracle cd248b67cc10ef64f2def315b86c3b0236b102639d03c65a0c5d9519e538d3af failed the same three durability/continuity checks on reported v1.4.180 (0b62333cf1), latest main (9bb8836bb6), and disabled fix; runtime candidate 3cf8a37447 passed 5/5, and final code candidate 121e112d77 separately passed its expanded 6/6 oracle. Renderer oracle 3b0949eef8b792cf5b09cfa55341f4216c08714f158e4b132e988e8114636cea failed both explicit-empty hydration/fallback checks on v1.4.180, latest main, and disabled fix, while renderer candidate 121e112d77 passed 2/2. The 1.4.187 recurrence oracle deterministically failed with historical tab_not_found when PTY stop was moved ahead of durable retirement, then passed with retirement committed before externally owned teardown while the canary remained live." }, "performanceBudget": { "required": true, @@ -8047,6 +8050,7 @@ "remote-runtime host surface materialization", "remote-runtime mirror polling", "remote-runtime network recovery", + "paired client sleep/wake reconnect", "terminal create idempotency", "provider listing", "reattach", @@ -8059,6 +8063,8 @@ "coveredProviders": ["ssh", "remote-runtime"], "coverageNotes": "Deterministic renderer coverage proves startup publishes the state returned by ssh.connect, retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes clear and retry by exact authority, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. Target snapshot hydration/reconnect preserves sibling SSH/local/WSL/runtime state, and a mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps.", "motivatingLinks": [ + "https://linear.app/stably/issue/STA-3107", + "https://github.com/stablyai/orca/pull/12664", "https://github.com/stablyai/orca/pull/6951", "https://github.com/stablyai/orca/pull/6955", "https://github.com/stablyai/orca/pull/6979", @@ -8070,6 +8076,7 @@ "oracle": "Deterministic tests cover bounded stale-handle replacement, suspended heartbeat clocks, cold and established subscription failure, ten partition/recovery cycles, automatic-recovery cutoff, manual reconnect, and exact direct SSH binding recovery. They assert one atomic store publication clears only exact-target PTY indexes, null-PTY activation remains unchanged, relay identity survives, Git and folder panes retry symmetrically, another target/local/WSL/runtime panes remain byte-identical through target snapshot hydration and reconnect, only an accepted exact failure or timeout starts the second attempt, two 31-second timeouts cannot start a third settlement-triggered attempt, rejected stale/mismatched acknowledgements preserve every store map, and concurrent split-pane spawn and reattach callbacks both commit under the same attempt ID after the first success replaces pending state with live shared authority. A sibling failure revokes that shared authority and starts exactly one second attempt; duplicate failures and late first-attempt PTY callbacks preserve the second attempt and every state map. Attempt-two failure retains continuation authority for later siblings, primary exit promotes a bound survivor or preserves the lease until a late sibling binds, and primary plus non-primary detach retain exact authority and history on both resulting tabs. Both remount callbacks consume split-count activity suppression, intentional dispose emits no failure/timeout, and a same-attempt StrictMode remount still owns one timeout. Hydration clears an untrusted PTY hint without clearing its current pending owner, healthy current-authority bindings suppress correction, hydration finalizes once, and reconnect emits no paired close lifecycle. A provider-level session-ID reattach returns an incarnation, then a legacy exit without an incarnation must resolve to that returned identity rather than minting a fallback identity. The shared-control oracle withholds the first encrypted ready frame, starts one RPC, triggers the successful-probe refresh, then requires exactly two client connections, one host request, a successful response, zero pending calls, and zero retained request bytes. Tests also assert one unsubscribe per remote-runtime epoch, observable recovery phases, stable PTY identity, resumed snapshot/output/input, no healthy state before replay, no retry or input after cutoff, a new manual epoch against the same PTY, quiet recovery UI with an explicit Reconnect action, pane-close state cleanup, one stable create mutation id, old-runtime no-retry behavior, cross-process PTY adoption, and bounded in-flight coordination.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/providers/ssh-pty-provider-reattach-incarnation.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/paired-reconnect-multi-pane-materialization.test.ts src/renderer/src/runtime/paired-reconnect-sidebar-agent-count.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/startup/ssh-startup-reconnect.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-spawn-retry.test.ts src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-reattach-retry.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/runtime/web-session-terminal-handle-events.test.ts src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport-reattach-admission.test.ts src/renderer/src/components/terminal-pane/pty-transport-detach-attach-handoff.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-attach-subscription.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-create-outcome-recovery.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-create-handoff.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.test.ts src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.test.tsx src/renderer/src/components/terminal-pane/terminal-remote-runtime-recovery-ui-state.test.ts src/shared/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/rpc/methods/terminal-create-idempotency.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts", @@ -8084,6 +8091,8 @@ ], "testFiles": [ "src/main/providers/ssh-pty-provider-reattach-incarnation.test.ts", + "src/renderer/src/components/terminal-pane/paired-reconnect-multi-pane-materialization.test.ts", + "src/renderer/src/runtime/paired-reconnect-sidebar-agent-count.test.ts", "src/renderer/src/startup/ssh-startup-reconnect.test.ts", "src/renderer/src/lib/resolved-worktree-execution-host.test.ts", "src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts", @@ -8142,6 +8151,20 @@ "tests/e2e/ssh-docker-relay-perf.spec.ts" ], "assertionRefs": [ + { + "file": "src/renderer/src/components/terminal-pane/paired-reconnect-multi-pane-materialization.test.ts", + "assertions": [ + "six panes sharing one dropped multiplex connection each resubscribe to a distinct live host handle", + "a pane parked while the client slept is authoritatively activated and rematerialized without leaving any pane handle null" + ] + }, + { + "file": "src/renderer/src/runtime/paired-reconnect-sidebar-agent-count.test.ts", + "assertions": [ + "after a long sleep every live host PTY and tab retains its client-owned sidebar agent row", + "unwritten or explicitly released pane authority still cedes deletion to the host" + ] + }, { "file": "src/renderer/src/startup/ssh-startup-reconnect.test.ts", "assertions": [ @@ -8471,6 +8494,15 @@ } ], "evidenceRuns": [ + { + "date": "2026-08-23", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/paired-reconnect-multi-pane-materialization.test.ts src/renderer/src/runtime/paired-reconnect-sidebar-agent-count.test.ts --reporter=dot", + "result": "passed", + "durationSeconds": 2.54, + "summary": "Seven deterministic STA-3107 contracts passed across six-pane multiplex rematerialization and client-owned sidebar-row retention after sleep/wake." + }, { "date": "2026-07-14", "runner": "local", @@ -8554,7 +8586,7 @@ }, "redGreenEvidence": { "status": "partial", - "evidence": "The remote-runtime fault tests failed before the recovery changes by leaving a cold restored subscription detached, reporting connected before authoritative replay, delivering a fatal setup error twice, and allowing an unknown create outcome to spawn again after process-local state was lost. On exact pre-fix HEAD 939719443, the split-pane store, fresh-spawn, and reattach oracles failed because the first success removed pending authority and the sibling could not bind; the same three oracles pass after live bindings retain the exact attempt ID. On exact committed HEAD d501f2e96, primary-exit-before-sibling and primary/non-primary split-detach oracles failed because live authority was deleted during the empty gap or transferred to only one resulting tab; all three pass after continuation-gap preservation and two-sided detach projection. On exact committed HEAD d44ea382b with test-only oracles, a pending-only all-null detach deleted the attempt ledger, a sibling mounted after first success committed without its lease, and that sibling could bind after authority rotation; all three pass after pending-only projection and retained-live-lease capture with provider retirement. On exact committed HEAD 9fa84dacf, the production-manager in-progress oracle rejected the fresh authority and the forward-removal barrier delayed stale transport cancellation; both pass after replacement starts cancellation immediately, shares concurrent fresh callers, and waits for teardown before connecting. On exact committed HEAD e5ba9a9e5, overlapping disconnect allowed a replacement connect before forward teardown completed and delayed transport cancellation behind that barrier; disconnect, removal, and terminate now share a target lifecycle barrier, start transport cancellation immediately, retain captured-session identity, and admit the replacement only after cleanup. On exact committed HEAD 9a29e7a81, a rejected forward teardown short-circuited the lifecycle while transport disconnect was pending, removal left its captured relay session alive, same-turn connect escaped admission, and reset remained outside the target barrier; the exact failure oracles pass after both cleanup branches settle, captured sessions always retire, admission is authority-fenced, and reset shares the barrier. On exact committed HEAD 47c7198f2, reset's remaining bespoke forward teardown could still reject after authority rotation but before captured-session retirement; reset now uses the same hardened session teardown and a failed reset remains cleanly retryable. Other direct SSH tests encode red conditions for non-atomic binding clear, cross-target retry, folder omission, duplicate same-authority attempts, hydration overwrite, terminal finalization delayed behind provider work, obsolete-authority pending-spawn adoption, Git lineage namespace mismatch, and snapshot PTY hint promotion without exact-attempt acknowledgement. Existing SSH and stale-handle reattach coverage remains green. Needs WSL, paired-close, and a patched live remote-runtime partition journey before promotion." + "evidence": "The remote-runtime fault tests failed before the recovery changes by leaving a cold restored subscription detached, reporting connected before authoritative replay, delivering a fatal setup error twice, and allowing an unknown create outcome to spawn again after process-local state was lost. For STA-3107, reverting #11542 in the six-pane multiplex harness leaves exactly one parked pane without a resubscribed handle while its siblings recover; before #12664, the first post-sleep host snapshot erases every stale client-owned sidebar row despite live tabs and host PTYs. The deterministic contracts pass after host activation rematerializes the missing pane and client-written ownership, rather than freshness, controls row retention. On exact pre-fix HEAD 939719443, the split-pane store, fresh-spawn, and reattach oracles failed because the first success removed pending authority and the sibling could not bind; the same three oracles pass after live bindings retain the exact attempt ID. On exact committed HEAD d501f2e96, primary-exit-before-sibling and primary/non-primary split-detach oracles failed because live authority was deleted during the empty gap or transferred to only one resulting tab; all three pass after continuation-gap preservation and two-sided detach projection. On exact committed HEAD d44ea382b with test-only oracles, a pending-only all-null detach deleted the attempt ledger, a sibling mounted after first success committed without its lease, and that sibling could bind after authority rotation; all three pass after pending-only projection and retained-live-lease capture with provider retirement. On exact committed HEAD 9fa84dacf, the production-manager in-progress oracle rejected the fresh authority and the forward-removal barrier delayed stale transport cancellation; both pass after replacement starts cancellation immediately, shares concurrent fresh callers, and waits for teardown before connecting. On exact committed HEAD e5ba9a9e5, overlapping disconnect allowed a replacement connect before forward teardown completed and delayed transport cancellation behind that barrier; disconnect, removal, and terminate now share a target lifecycle barrier, start transport cancellation immediately, retain captured-session identity, and admit the replacement only after cleanup. On exact committed HEAD 9a29e7a81, a rejected forward teardown short-circuited the lifecycle while transport disconnect was pending, removal left its captured relay session alive, same-turn connect escaped admission, and reset remained outside the target barrier; the exact failure oracles pass after both cleanup branches settle, captured sessions always retire, admission is authority-fenced, and reset shares the barrier. On exact committed HEAD 47c7198f2, reset's remaining bespoke forward teardown could still reject after authority rotation but before captured-session retirement; reset now uses the same hardened session teardown and a failed reset remains cleanly retryable. Other direct SSH tests encode red conditions for non-atomic binding clear, cross-target retry, folder omission, duplicate same-authority attempts, hydration overwrite, terminal finalization delayed behind provider work, obsolete-authority pending-spawn adoption, Git lineage namespace mismatch, and snapshot PTY hint promotion without exact-attempt acknowledgement. Existing SSH and stale-handle reattach coverage remains green. Needs WSL, paired-close, and a patched live remote-runtime partition journey before promotion." }, "performanceBudget": { "required": true, @@ -9878,22 +9910,27 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local"], - "coverageNotes": "Local macOS evidence covers the runtime PTY write contract, live Codex orchestration, a dev-runtime CLI repro, and Claude and Codex composer traces. The render gate stays on the PTY-owning runtime, so paired and SSH callers use the same provider write/output path without a wire change. SSH, daemon, remote-runtime, Linux, and Windows live journeys remain gaps.", + "coverageNotes": "Local macOS evidence covers the runtime PTY write contract, live Codex orchestration, a dev-runtime CLI repro, and Claude and Codex composer traces. A deterministic worker-start RPC/SQLite contract proves delayed Codex composer acceptance, exactly one submitted turn, durable Dispatch success, and explicit stalled failure when Enter is swallowed without a rescue send. The render gate stays on the PTY-owning runtime, so paired and SSH callers use the same provider write/output path without a wire change. SSH, daemon, remote-runtime, Linux, and Windows live journeys remain gaps.", "motivatingLinks": [ + "https://linear.app/stably/issue/STA-3800", + "https://linear.app/stably/issue/STA-3904", + "https://linear.app/stably/issue/STA-4328", "https://github.com/stablyai/orca/issues/7226", "https://github.com/stablyai/orca/issues/13821", "https://github.com/stablyai/orca/issues/14347" ], - "invariant": "Injected orchestration task prompts for recognized agent CLIs must send the prompt body inside one bracketed-paste frame, sanitize embedded ESC bytes, preserve chunk boundaries without losing the frame, and submit exactly once only after the agent can accept Enter. Claude and Codex must emit a post-paste composer marker and then settle, or reach the bounded fallback first; every other agent retains the platform delay.", - "oracle": "Runtime tests assert the exact PTY write sequence, failure cleanup, Claude/Codex marker-gated multi-frame renders, and the legacy platform delay for every other configured agent. The candidate resets settlement on later frames, gives a late marker a fresh bounded window, and still submits once at the hard deadline if output never settles. Orchestration tests assert dispatch/coordinator use the agent prompt path; the live CLI harness covers long Codex-like framing.", + "invariant": "Injected orchestration task prompts for recognized agent CLIs must send the prompt body inside one bracketed-paste frame, sanitize embedded ESC bytes, preserve chunk boundaries without losing the frame, and submit exactly once only after the agent can accept Enter. A successful orchestration.workerStart must durably record exactly one accepted and started turn; a swallowed Enter must fail with agent_prompt_stalled and never trigger a blind rescue Enter. Claude and Codex must emit a post-paste composer marker and then settle, or reach the bounded fallback first; every other agent retains the platform delay.", + "oracle": "Runtime tests assert the exact PTY write sequence, failure cleanup, Claude/Codex marker-gated multi-frame renders, and the legacy platform delay for every other configured agent. The candidate resets settlement on later frames, gives a late marker a fresh bounded window, and still submits once at the hard deadline if output never settles. The worker-start contract drives the production RPC through a delayed fake Codex composer and independently checks exact turn/Enter counts plus reopened SQLite Task, Dispatch, worker receipt, and mutation receipt state for accepted and swallowed outcomes. Other orchestration tests assert dispatch/coordinator use the agent prompt path; the live CLI harness covers long Codex-like framing.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/shared/agent-prompt-injection.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/orchestration-tasks-dispatch.test.ts src/main/runtime/orchestration/coordinator.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration-worker-start-prompt-contract.test.ts --reporter=dot", "node tests/tools/repro-orchestration-long-prompt.mjs --cli out/bin/orca-dev --mode codex-like --size-kb 32 --timeout-ms 20000" ], "testFiles": [ "src/shared/agent-prompt-injection.test.ts", "src/main/runtime/orca-runtime.test.ts", "src/main/runtime/rpc/methods/orchestration-tasks-dispatch.test.ts", + "src/main/runtime/rpc/methods/orchestration-worker-start-prompt-contract.test.ts", "src/main/runtime/orchestration/coordinator.test.ts", "tests/tools/repro-orchestration-long-prompt.mjs" ], @@ -9928,6 +9965,13 @@ "failed prompt injection rolls back the active dispatch" ] }, + { + "file": "src/main/runtime/rpc/methods/orchestration-worker-start-prompt-contract.test.ts", + "assertions": [ + "delayed composer readiness produces exactly one submitted and started turn with no premature Enter and durable ready receipts", + "a swallowed Enter records agent_prompt_stalled across Task, Dispatch, worker, and mutation receipts without a rescue Enter" + ] + }, { "file": "src/main/runtime/orchestration/coordinator.test.ts", "assertions": [ @@ -9945,6 +9989,15 @@ } ], "evidenceRuns": [ + { + "date": "2026-08-23", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration-worker-start-prompt-contract.test.ts --reporter=dot", + "result": "passed", + "durationSeconds": 21.84, + "summary": "Two deterministic worker-start RPC contracts passed with fake clocks and reopened SQLite receipts for one accepted turn and one swallowed-Enter stalled outcome." + }, { "date": "2026-08-14", "runner": "local", @@ -10001,7 +10054,7 @@ }, "redGreenEvidence": { "status": "partial", - "evidence": "The original Claude-shaped oracle fails on unmodified main and passes with the render gate. The hardened multi-frame oracle then fails on the first-marker candidate, which submits at 751 ms during an intermediate frame, and passes when the gate requires post-marker quiescence. Codex used the legacy platform delay before this candidate; the late-marker oracle proves the original deadline would pre-empt slow-host settlement without re-arming. The earlier live harness also reproduced the unsafe raw multiline contract before its framing fix. Intentional-break evidence remains local rather than a separate CI job." + "evidence": "The original Claude-shaped oracle fails on unmodified main and passes with the render gate. The hardened multi-frame oracle then fails on the first-marker candidate, which submits at 751 ms during an intermediate frame, and passes when the gate requires post-marker quiescence. Codex used the legacy platform delay before this candidate; the late-marker oracle proves the original deadline would pre-empt slow-host settlement without re-arming. The worker-start negative controls caught both premature submission before composer readiness and a false-ready swallowed Enter; the accepted candidate records one started turn, while the swallowed arm records agent_prompt_stalled without a rescue Enter. The earlier live harness also reproduced the unsafe raw multiline contract before its framing fix. Intentional-break evidence remains local rather than a separate CI job." }, "performanceBudget": { "required": true, @@ -14249,6 +14302,349 @@ "The legacy remote-uploads root is intentionally not reclaimed while a mixed-version relay may still own bytes there; eventual legacy-root retirement requires a separate compatibility decision." ], "demotionRule": "Demote if one live owner can remove another owner's bytes, cleanup exceeds 64 inspected entries per attempt, a lifecycle path retains its exact owned archive after settlement, or the process oracle flakes without an identified harness or product defect." + }, + { + "id": "terminal-startup.quick-command-pre-bind-recovery", + "title": "Quick Command survives a pre-bind terminal recovery", + "maturity": "experimental", + "protection": "partial", + "owner": "terminal-renderer-lifecycle", + "layer": "electron-ui-and-real-local-pty", + "surfaces": ["Quick Commands", "terminal pane recovery", "fresh PTY startup"], + "platforms": ["macos", "linux", "windows"], + "providers": ["local"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["local"], + "coverageNotes": "A forced pre-spawn barrier makes one visible Quick Command cross a recovery remount before its successor PTY binds. Store and lifecycle contracts retain lower-layer ownership; the Electron sentinel adds the rendered affordance, real PTY, exact-once terminal marker, staged identity file, and unrelated sibling canary.", + "motivatingLinks": [ + "https://linear.app/stably/issue/STA-4876", + "https://github.com/stablyai/orca/pull/15630" + ], + "invariant": "A Quick Command selected for a new terminal remains owned by that tab through a recovery remount, executes exactly once only after the successor PTY binds, and never reaches an unrelated terminal.", + "oracle": "Arm the E2E-only pre-spawn barrier, click the visible Quick Command, force one recovery generation while the original spawn is blocked, and release it. Require one exact semantic xterm marker, an independently written pane/tab identity file matching the bound live PTY, queue consumption only after bind, and a live interactive sibling canary.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection-queued-startup-consume.test.ts src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts src/renderer/src/store/slices/terminal-startup-command-retention.test.ts --reporter=dot", + "pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" + ], + "testFiles": [ + "src/renderer/src/components/terminal-pane/pty-connection-queued-startup-consume.test.ts", + "src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts", + "src/renderer/src/store/slices/terminal-startup-command-retention.test.ts", + "tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts" + ], + "assertionRefs": [ + { + "file": "src/renderer/src/store/slices/terminal-startup-command-retention.test.ts", + "assertions": ["recovery remount retains the exact queued startup command"] + }, + { + "file": "tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts", + "assertions": [ + "the visible Quick Command executes exactly once in the intended fresh PTY", + "queue consumption follows PTY binding and the sibling terminal remains live" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-23", + "runner": "local", + "platform": "macos", + "result": "passed", + "command": "pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "durationSeconds": 23, + "summary": "The exact rebased PR head passed the headless Electron flow in 23.0 seconds after an E2E-mode build." + }, + { + "date": "2026-08-23", + "runner": "local", + "platform": "macos", + "result": "passed", + "command": "ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "durationSeconds": 24, + "summary": "The exact rebased PR head passed the visible-window Electron flow in 23.9 seconds using the same E2E build." + } + ], + "runtimeBudget": { + "p95Seconds": 90, + "scope": "one isolated Electron app, one forced recovery remount, and two local PTYs" + }, + "flakeHistory": { + "status": "not-started", + "evidence": "The new sentinel has local headless and forced-headful evidence but no routed CI soak history." + }, + "redGreenEvidence": { + "status": "complete", + "evidence": "The byte-identical spec failed with pending:null before PTY bind when the pre-6e25a900 eager-consume behavior was restored, then passed after restoration." + }, + "performanceBudget": { + "required": true, + "evidence": "The barrier exists only in E2E builds, adds no production timer or polling, and the live sentinel completed in under 20 seconds locally." + }, + "promotionCriteria": [ + "Collect 100 consecutive routed CI passes over at least 14 days without an unexplained flake.", + "Keep retries at zero and retain both semantic and identity oracles.", + "Collect Linux Electron evidence before promoting the focused lane to blocking." + ], + "knownGaps": [ + "Windows, Linux, SSH, WSL, and paired-runtime topologies are not covered because they were not causal to STA-4876.", + "The sentinel remains advisory while the repository-wide E2E signal is red." + ], + "demotionRule": "Demote if the barrier can be bypassed nondeterministically, either independent oracle is removed, the sibling canary is no longer isolated, or one unexplained flake occurs." + }, + { + "id": "quick-open.paired-host-path-search", + "title": "Paired Quick Open searches bounded host paths", + "maturity": "experimental", + "protection": "partial", + "owner": "runtime-filesystem", + "layer": "host-file-search-and-paired-runtime", + "surfaces": ["Quick Open", "paired desktop runtime", "headless runtime host"], + "platforms": ["macos", "linux", "windows"], + "providers": ["local", "ssh", "paired-runtime"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["local", "paired-runtime"], + "coverageNotes": "Focused contracts cover bounded host search, ignore traversal, RPC response bounds, renderer cancellation, deterministic ordering, and transport payload size. Headed and headless paired-runtime journeys use an 88,763-file fixture and are source-routed into advisory PR E2E; physical SSH and Windows remain gaps.", + "motivatingLinks": [ + "https://linear.app/stably/issue/STA-4354", + "https://github.com/stablyai/orca/pull/15158" + ], + "invariant": "Quick Open queries execute on the worktree host, find exact ignored-path matches beyond the legacy inventory prefix, return deterministic bounded results, and keep the paired runtime usable without overflowing its outbound reply buffer.", + "oracle": "Create 88,763 paths with 77,792 ignored entries and a nominal 22 GiB sparse file, query exact late gitignored and .orcaignored targets through headed and headless paired runtimes, and require one deterministic match, a payload below 4 KiB, and a healthy follow-up worktree call.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem-search-file-paths.test.ts src/main/runtime/orca-runtime-files-search.test.ts src/main/runtime/rpc/methods/files-path-search.test.ts src/renderer/src/components/quick-open-file-list.react.test.tsx src/renderer/src/runtime/runtime-file-client-search-listing.test.ts src/shared/quick-open-transport-budget.test.ts --reporter=dot", + "pnpm exec playwright test tests/e2e/paired-quick-open-large-tree.spec.ts --config tests/playwright.config.ts --workers=1" + ], + "testFiles": [ + "src/main/ipc/filesystem-search-file-paths.test.ts", + "src/main/runtime/orca-runtime-files-search.test.ts", + "src/main/runtime/rpc/methods/files-path-search.test.ts", + "src/renderer/src/components/quick-open-file-list.react.test.tsx", + "src/renderer/src/runtime/runtime-file-client-search-listing.test.ts", + "src/shared/quick-open-transport-budget.test.ts", + "tests/e2e/paired-quick-open-large-tree.spec.ts" + ], + "assertionRefs": [ + { + "file": "src/main/ipc/filesystem-search-file-paths.test.ts", + "assertions": [ + "host search stays bounded and respects gitignore plus .orcaignore traversal" + ] + }, + { + "file": "src/renderer/src/runtime/runtime-file-client-search-listing.test.ts", + "assertions": ["paired path queries stay deterministic and bounded across transport"] + }, + { + "file": "tests/e2e/paired-quick-open-large-tree.spec.ts", + "assertions": ["headed and headless hosts find late ignored targets and remain callable"] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-23", + "runner": "local", + "platform": "macos", + "result": "passed", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem-search-file-paths.test.ts src/main/runtime/orca-runtime-files-search.test.ts src/main/runtime/rpc/methods/files-path-search.test.ts src/renderer/src/components/quick-open-file-list.react.test.tsx src/renderer/src/runtime/runtime-file-client-search-listing.test.ts src/shared/quick-open-transport-budget.test.ts --reporter=dot", + "durationSeconds": 5, + "summary": "Six focused files passed 52 tests across host search, runtime RPC, renderer query ownership, and transport bounds; existing React act warnings remained non-fatal." + } + ], + "runtimeBudget": { + "p95Seconds": 300, + "scope": "focused deterministic contracts plus two serial paired Electron large-tree journeys" + }, + "flakeHistory": { + "status": "not-started", + "evidence": "The sentinel is newly source-routed for PR collection; no route-specific soak history exists yet." + }, + "redGreenEvidence": { + "status": "complete", + "evidence": "The merged STA-4354 oracle places both targets beyond the removed inventory prefix; the old client-side prefix inventory misses them, while host search returns the exact deterministic paths." + }, + "performanceBudget": { + "required": true, + "evidence": "Search is query-driven, result-limited, cancellation-aware, and payload-bounded; PR routing selects this fixture only for its exact production authorities or direct spec edits." + }, + "promotionCriteria": [ + "Collect 100 consecutive routed CI passes or 14 days without an unexplained flake.", + "Collect physical SSH and Windows paired-runtime evidence.", + "Keep deterministic result hashes, payload bounds, and post-query runtime health green." + ], + "knownGaps": [ + "The live large-tree evidence uses local headed and headless hosts rather than physical SSH.", + "Windows path-search tooling and filesystem behavior are not represented by the local evidence." + ], + "demotionRule": "Demote if the routed fixture flakes without a diagnosed product or harness cause, returns unbounded payloads, misses either late ignored target, or leaves the paired runtime unhealthy." + }, + { + "id": "terminal-session.host-cold-park-stream-continuity", + "title": "Host cold parking preserves paired terminal streams", + "maturity": "experimental", + "protection": "partial", + "owner": "terminal-runtime-graph", + "layer": "renderer-runtime-graph-and-terminal-stream", + "surfaces": ["host terminal cold park", "paired remote viewer", "multi-pane runtime graph"], + "platforms": ["macos", "linux", "windows"], + "providers": ["local-daemon", "ssh-daemon", "paired-runtime"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["local-daemon", "paired-runtime"], + "coverageNotes": "Deterministic policy and multiplex tests separate renderer parking from authoritative stream liveness, while runtime-graph tests cover exact parked leaf, pane runtime ID, title, multi-pane active-leaf, and disposal behavior. One headed paired journey proves input and echoed output while the host pane remains cold-parked.", + "motivatingLinks": [ + "https://linear.app/stably/issue/STA-2854", + "https://github.com/stablyai/orca/pull/15514" + ], + "invariant": "Cold parking a host renderer pane never retires its live PTY's runtime-graph leaf or interrupts a paired subscriber's stream, input, reconnect, pane identity, or multi-pane routing; the leaf retires only when exact PTY ownership ends.", + "oracle": "Cold-park a host-owned pane while a paired client actively views it, require the host manager to unmount, then type through the client and require the same PTY to receive and echo the token without any disconnected sample. Separately publish multi-pane parked leaves with exact pane runtime IDs and require per-PTY disposal to remove only the retired leaf.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot", + "pnpm exec playwright test tests/e2e/host-parked-pane-remote-viewer.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" + ], + "testFiles": [ + "src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts", + "src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts", + "tests/e2e/host-cold-park-remote-subscriber.unit.test.ts", + "tests/e2e/host-parked-pane-remote-viewer.spec.ts" + ], + "assertionRefs": [ + { + "file": "src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts", + "assertions": [ + "a live parked watcher publishes the exact leaf, pane runtime ID, and title", + "multi-pane publication never names an unsent active leaf and exact disposal retires ownership" + ] + }, + { + "file": "tests/e2e/host-cold-park-remote-subscriber.unit.test.ts", + "assertions": [ + "a fully unmounted host renderer still streams, accepts input, and resubscribes" + ] + }, + { + "file": "tests/e2e/host-parked-pane-remote-viewer.spec.ts", + "assertions": [ + "a cold-parked host pane carries a complete paired-client input and echo round trip" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-23", + "runner": "local", + "platform": "macos", + "result": "passed", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot", + "durationSeconds": 8, + "summary": "Three focused files passed 64 watcher, multi-pane runtime-graph, cold-park policy, and authoritative-stream tests." + } + ], + "runtimeBudget": { + "p95Seconds": 180, + "scope": "focused deterministic contracts plus one serial headed paired cold-park journey" + }, + "flakeHistory": { + "status": "not-started", + "evidence": "The existing sentinel is newly source-routed for PR collection; route-specific CI history has not started." + }, + "redGreenEvidence": { + "status": "complete", + "evidence": "On the affected STA-2854 path, cold parking removed the runtime-graph leaf and the paired stream disconnected; retaining the exact live parked watcher leaf keeps every sampled client phase connected and completes input plus echo." + }, + "performanceBudget": { + "required": true, + "evidence": "Publication reads the existing bounded parked-watcher registry and adds no timer, polling, provider scan, subprocess, or wire field; the 90-second live timeline is selected only by exact parking and graph authorities." + }, + "promotionCriteria": [ + "Collect 100 consecutive routed CI passes or 14 days without an unexplained flake.", + "Collect Linux, Windows, WSL, and physical SSH cold-park evidence.", + "Keep exact per-leaf disposal, multi-pane identity, and full client round-trip assertions green." + ], + "knownGaps": [ + "The live paired cold-park journey is macOS-only and uses a local daemon PTY.", + "Physical SSH, WSL, Linux, Windows, and host-restart cold-park journeys are not recorded." + ], + "demotionRule": "Demote if a live parked PTY loses its exact graph leaf, a retired PTY remains published, multi-pane identity drifts, or the routed client round trip flakes without a diagnosed cause." + }, + { + "id": "terminal-session.remote-pane-layout-retry", + "title": "Remote pane layouts retry identical state after reconnect", + "maturity": "experimental", + "protection": "partial", + "owner": "terminal-layout-sync", + "layer": "renderer-paired-runtime-layout", + "surfaces": ["paired terminal split layout", "pane title", "runtime reconnect"], + "platforms": ["macos", "linux", "windows"], + "providers": ["paired-runtime"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["paired-runtime"], + "coverageNotes": "Pure contracts cover identity-equal local write bailouts and remote push deduplication, while a headless-host paired Electron journey proves that an identical local layout is retried after a failed disconnected push and becomes visible to an independent observer.", + "motivatingLinks": ["https://github.com/stablyai/orca/pull/12420"], + "invariant": "Identity-equal pane layout writes avoid local churn but never suppress a remote retry whose prior push failed; reconnecting and repeating the same layout persists it on the host and publishes it to other paired clients.", + "oracle": "Disconnect a paired client, change a pane title, and observe the failed host push while local state retains the layout. Reconnect without remounting, submit the identical title again, and require the headless host plus a second paired observer to receive it.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/remote-pane-layout-push.test.ts src/renderer/src/store/slices/terminal-write-identity-bailouts.test.ts --reporter=dot", + "pnpm exec playwright test tests/e2e/paired-remote-pane-layout-retry.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" + ], + "testFiles": [ + "src/renderer/src/components/terminal-pane/remote-pane-layout-push.test.ts", + "src/renderer/src/store/slices/terminal-write-identity-bailouts.test.ts", + "tests/e2e/paired-remote-pane-layout-retry.spec.ts" + ], + "assertionRefs": [ + { + "file": "src/renderer/src/components/terminal-pane/remote-pane-layout-push.test.ts", + "assertions": ["only successfully pushed layouts deduplicate later remote writes"] + }, + { + "file": "src/renderer/src/store/slices/terminal-write-identity-bailouts.test.ts", + "assertions": ["identity-equal layout and timer writes avoid redundant local updates"] + }, + { + "file": "tests/e2e/paired-remote-pane-layout-retry.spec.ts", + "assertions": [ + "an identical layout retries after reconnect and reaches a second paired observer" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-08-23", + "runner": "local", + "platform": "macos", + "result": "passed", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/remote-pane-layout-push.test.ts src/renderer/src/store/slices/terminal-write-identity-bailouts.test.ts --reporter=dot", + "durationSeconds": 5, + "summary": "Two focused files passed 20 remote-push and identity-bailout contracts." + } + ], + "runtimeBudget": { + "p95Seconds": 90, + "scope": "two focused renderer contracts plus one serial headless-host paired journey" + }, + "flakeHistory": { + "status": "not-started", + "evidence": "The existing paired sentinel is newly source-routed and has no route-specific CI soak history." + }, + "redGreenEvidence": { + "status": "complete", + "evidence": "The affected implementation cached the disconnected layout before host acknowledgment and suppressed the identical retry; the merged oracle keeps only successful remote pushes deduplicated and the observer receives the retried title." + }, + "performanceBudget": { + "required": true, + "evidence": "Successful identity-equal writes remain O(1) bailouts; one failed remote push permits one later identical retry, with no polling, timer, provider scan, subprocess, or new wire field." + }, + "promotionCriteria": [ + "Collect 100 consecutive routed CI passes or 14 days without an unexplained flake.", + "Collect Linux and Windows paired-runtime reconnect evidence.", + "Keep local identity bailouts and failed-push retry ownership green." + ], + "knownGaps": [ + "The paired reconnect journey has only local macOS evidence.", + "The sentinel changes a pane title within an existing layout; concurrent split and close conflicts remain separate coverage." + ], + "demotionRule": "Demote if a failed push suppresses an identical retry, a successful equal write resumes redundant churn, or the routed observer journey flakes without a diagnosed cause." } ] } diff --git a/config/scripts/pr-e2e-gate-contract.test.mjs b/config/scripts/pr-e2e-gate-contract.test.mjs index 92faae907a1..877b9b07c08 100644 --- a/config/scripts/pr-e2e-gate-contract.test.mjs +++ b/config/scripts/pr-e2e-gate-contract.test.mjs @@ -1,11 +1,17 @@ import { existsSync, readFileSync } from 'node:fs' import { join, resolve } from 'node:path' +import { parse as parseJsonc } from 'jsonc-parser' import { describe, expect, it } from 'vitest' -import { parse } from 'yaml' +import { parse as parseYaml } from 'yaml' +import { PR_E2E_SOURCE_ROUTES, selectPrE2eSpecs } from './pr-e2e-source-routing.mjs' const projectDir = resolve(import.meta.dirname, '../..') -const prWorkflow = parse(readFileSync(join(projectDir, '.github/workflows/pr.yml'), 'utf8')) -const e2eWorkflow = parse(readFileSync(join(projectDir, '.github/workflows/e2e.yml'), 'utf8')) +const prWorkflow = parseYaml(readFileSync(join(projectDir, '.github/workflows/pr.yml'), 'utf8')) +const e2eWorkflow = parseYaml(readFileSync(join(projectDir, '.github/workflows/e2e.yml'), 'utf8')) +const reliabilityManifest = parseJsonc( + readFileSync(join(projectDir, 'config/reliability-gates.jsonc'), 'utf8') +) +const playwrightConfig = readFileSync(join(projectDir, 'tests/playwright.config.ts'), 'utf8') const sshDockerRunner = readFileSync( join(projectDir, 'config/scripts/run-ssh-docker-terminal-parking-e2e.mjs'), 'utf8' @@ -69,8 +75,15 @@ describe('PR E2E gate contract', () => { it('selects modified Playwright specs without running deleted tests', () => { expect(filterStep.run).toContain('--diff-filter=AMCR') - expect(filterStep.run).toContain("'^tests/e2e/.*\\.spec\\.ts$'") + expect(filterStep.run).toContain('config/scripts/pr-e2e-source-routing.mjs') expect(filterStep.run).not.toContain('tests/playwright\\.') + expect( + selectPrE2eSpecs([ + 'tests/e2e/active-view-restart-restore.spec.ts', + 'tests/e2e/deleted.spec.ts.bak', + 'tests/e2e/global-teardown.unit.test.ts' + ]) + ).toEqual(['tests/e2e/active-view-restart-restore.spec.ts']) }) it('uses one runner for changed specs and keeps full runs sharded', () => { @@ -89,6 +102,7 @@ describe('PR E2E gate contract', () => { expect(changedRun.run).toContain( 'pnpm run test:e2e "${TEST_FILES[@]}" --workers=1 "${E2E_PROJECT_ARGS[@]}"' ) + expect(playwrightConfig).toContain('retries: 0') }) it('keeps startup-exec live parity in the isolated SSH lane', () => { @@ -121,7 +135,7 @@ describe('PR E2E gate contract', () => { ] for (const file of dedicatedWorkflows) { - const workflow = parse(readFileSync(join(projectDir, '.github/workflows', file), 'utf8')) + const workflow = parseYaml(readFileSync(join(projectDir, '.github/workflows', file), 'utf8')) expect(workflow.on.pull_request, file).toBeUndefined() } }) @@ -138,12 +152,14 @@ describe('PR E2E gate contract', () => { const sshSourceAuthorities = [ 'src/main/ssh/', 'src/main/providers/ssh-', - 'src/main/ipc/(ssh-|pty)', + 'src/main/ipc/pty', 'src/relay/', - 'src/renderer/src/components/terminal-pane/(pty-|ssh-|remote-runtime-|terminal-parked-pty)' + 'src/renderer/src/components/terminal-pane/remote-runtime-' ] for (const authority of sshSourceAuthorities) { - expect(filterStep.run).toContain(authority) + expect(selectPrE2eSpecs([`${authority}routing.ts`])).toContain( + 'tests/e2e/ssh-docker-reconnect-pane-restore.spec.ts' + ) } const mappedSpecs = [ @@ -154,7 +170,7 @@ describe('PR E2E gate contract', () => { 'tests/e2e/ssh-terminal-window-wake-stale-grid-repro.spec.ts' ] for (const spec of mappedSpecs) { - expect(filterStep.run).toContain(`'${spec}'`) + expect(selectPrE2eSpecs(['src/main/ssh/connection.ts'])).toContain(spec) expect(existsSync(join(projectDir, spec)), spec).toBe(true) // Why: a spec that stops reading the flag would silently run without Docker. if (spec !== 'tests/e2e/ssh-startup-exec-readiness.spec.ts') { @@ -162,8 +178,7 @@ describe('PR E2E gate contract', () => { } } - // Why: unit tests next to the mapped sources prove the same code without Docker. - expect(filterStep.run).toContain("grep -Ev '\\.test\\.tsx?$'") + expect(selectPrE2eSpecs(['src/main/ssh/connection.test.ts'])).toEqual([]) // Why: startup readiness is filtered out of changed-e2e, so listing it is only // meaningful while it still routes the dedicated Docker lane. @@ -183,6 +198,99 @@ describe('PR E2E gate contract', () => { expect(rollbackStep.run).toContain('--merge-base "$BASE_SHA" "$HEAD_SHA"') expect(rollbackStep.run).toContain('src/shared/ephemeral-vm-recipes.ts') expect(rollbackStep.run).toContain('src/shared/orca-yaml-hook-types.ts') - expect(filterStep.run).toContain('ephemeral-vm-recipes|orca-yaml-hook-types') + expect(selectPrE2eSpecs(['src/shared/ephemeral-vm-recipes.ts'])).toEqual([ + 'tests/e2e/ephemeral-vm-provisioned-root.spec.ts' + ]) + }) + + it('routes P0 sentinels from their causal sources', () => { + const cases = [ + [ + 'src/renderer/src/components/tab-bar/TabBarQuickCommandsMenu.tsx', + 'tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts' + ], + ['src/main/runtime/orca-runtime-files.ts', 'tests/e2e/paired-quick-open-large-tree.spec.ts'], + [ + 'src/renderer/src/runtime/sync-runtime-graph.ts', + 'tests/e2e/host-parked-pane-remote-viewer.spec.ts' + ], + [ + 'src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts', + 'tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts' + ], + [ + 'src/renderer/src/components/terminal-pane/remote-pane-layout-push.ts', + 'tests/e2e/paired-remote-pane-layout-retry.spec.ts' + ] + ] + for (const [source, spec] of cases) { + expect(selectPrE2eSpecs([source]), source).toEqual([spec]) + expect(selectPrE2eSpecs([source.replace(/\.tsx?$/, '.test.ts')]), source).toEqual([]) + expect(existsSync(join(projectDir, spec)), spec).toBe(true) + } + const quickCommandSpec = 'tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts' + for (const source of [ + 'src/renderer/src/components/terminal-pane/pty-connection.ts', + 'src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts', + 'src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts', + 'src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts', + 'src/renderer/src/components/terminal-pane/pty-connection/pty-input-recovery.ts' + ]) { + expect(selectPrE2eSpecs([source]), source).toContain(quickCommandSpec) + expect(selectPrE2eSpecs([source.replace(/\.ts$/, '.test.ts')]), source).not.toContain( + quickCommandSpec + ) + } + for (const source of [ + 'src/main/ipc/rg-availability.ts', + 'src/shared/ripgrep-process-availability.ts' + ]) { + expect(selectPrE2eSpecs([source]), source).toEqual([ + 'tests/e2e/paired-quick-open-large-tree.spec.ts' + ]) + } + expect( + selectPrE2eSpecs([ + 'src/main/runtime/orca-runtime-files.ts', + 'tests/e2e/paired-quick-open-large-tree.spec.ts' + ]) + ).toEqual(['tests/e2e/paired-quick-open-large-tree.spec.ts']) + expect(selectPrE2eSpecs(['src/renderer/src/components/FileExplorer.tsx'])).toEqual([]) + expect( + selectPrE2eSpecs([ + 'src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts' + ]) + ).toContain('tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts') + expect( + selectPrE2eSpecs([ + 'src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-test-harness.ts' + ]) + ).not.toContain('tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts') + expect(selectPrE2eSpecs(['src/main/ipc/pty.ts'])).not.toContain( + 'tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts' + ) + }) + + it('keeps source-routed sentinels registered to their reliability gates', () => { + const routedGateIds = [ + 'terminal-startup.quick-command-pre-bind-recovery', + 'quick-open.paired-host-path-search', + 'terminal-session.host-cold-park-stream-continuity', + 'terminal-provider.ssh-remote-reattach-contract', + 'terminal-session.remote-pane-layout-retry' + ] + for (const gateId of routedGateIds) { + const route = PR_E2E_SOURCE_ROUTES.find((candidate) => candidate.id === gateId) + const gate = reliabilityManifest.gates.find((candidate) => candidate.id === gateId) + expect(route, gateId).toBeDefined() + expect(gate, gateId).toMatchObject({ maturity: 'experimental', protection: 'partial' }) + for (const spec of route.specs) { + expect(gate.testFiles, gateId).toContain(spec) + expect( + gate.commands.some((command) => command.includes(spec)), + gateId + ).toBe(true) + } + } }) }) diff --git a/config/scripts/pr-e2e-source-routing.mjs b/config/scripts/pr-e2e-source-routing.mjs new file mode 100644 index 00000000000..4e429913c28 --- /dev/null +++ b/config/scripts/pr-e2e-source-routing.mjs @@ -0,0 +1,117 @@ +import process from 'node:process' +import { pathToFileURL } from 'node:url' + +const isProductSource = (file) => !/\.test\.tsx?$/.test(file) + +export const PR_E2E_SOURCE_ROUTES = [ + { + id: 'ephemeral-vm-runtime.rollback-readable-sidecar', + specs: ['tests/e2e/ephemeral-vm-provisioned-root.spec.ts'], + matches: (file) => + /^(?:src\/main\/ephemeral-vm-(?:runtime-(?:service|provisioning-persistence)|failed-start-cleanup)|src\/shared\/(?:ephemeral-vm-runtime-(?:store|feature-store|rollback-projection|runtimes)|ephemeral-vm-recipes|orca-yaml-hook-types))\.ts$/.test( + file + ) + }, + { + id: 'ssh-terminal-source', + specs: [ + 'tests/e2e/pty-input-write-queue-ssh.spec.ts', + 'tests/e2e/ssh-cold-activation-restore.spec.ts', + 'tests/e2e/ssh-docker-reconnect-pane-restore.spec.ts', + 'tests/e2e/ssh-startup-exec-readiness.spec.ts', + 'tests/e2e/ssh-terminal-window-wake-stale-grid-repro.spec.ts' + ], + matches: (file) => + isProductSource(file) && + /^(?:src\/main\/ssh\/|src\/main\/providers\/ssh-|src\/main\/ipc\/(?:ssh-|pty)|src\/relay\/|src\/renderer\/src\/components\/terminal-pane\/(?:pty-|ssh-|remote-runtime-|terminal-parked-pty))/.test( + file + ) + }, + { + id: 'terminal-input.ime-and-synthetic-forwarding', + specs: [ + 'tests/e2e/terminal-cjk-ime-committed-text.spec.ts', + 'tests/e2e/terminal-hangul-wrap-boundary-bytes.spec.ts', + 'tests/e2e/terminal-ime-exact-byte.spec.ts', + 'tests/e2e/terminal-korean-composing-chord-order.spec.ts', + 'tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts', + 'tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts', + 'tests/e2e/terminal-korean-preedit-visibility.spec.ts' + ], + matches: (file) => + isProductSource(file) && + /^(?:config\/patches\/|src\/renderer\/src\/components\/terminal-pane\/(?:terminal-ime-|use-terminal-pane-lifecycle|xterm-bypass-policy|terminal-option-shortcut-policy))/.test( + file + ) + }, + { + id: 'terminal-startup.quick-command-pre-bind-recovery', + specs: ['tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts'], + matches: (file) => + isProductSource(file) && + /^(?:src\/renderer\/src\/components\/tab-bar\/TabBarQuickCommandsMenu\.tsx|src\/renderer\/src\/hooks\/use-terminal-quick-command-hosts\.ts|src\/renderer\/src\/components\/terminal-pane\/(?:pty-connection|pty-transport|terminal-pty-pre-spawn-e2e-barrier)\.ts|src\/renderer\/src\/components\/terminal-pane\/pty-connection\/(?:connect-pane-pty|fresh-spawn-start|pane-pty-visibility-bind|pty-input-recovery)\.ts|src\/renderer\/src\/components\/terminal-pane\/(?:TerminalPane|use-terminal-pane-lifecycle)\.tsx?|src\/renderer\/src\/store\/slices\/terminals\.ts)$/.test( + file + ) + }, + { + id: 'quick-open.paired-host-path-search', + specs: ['tests/e2e/paired-quick-open-large-tree.spec.ts'], + matches: (file) => + isProductSource(file) && + /^(?:src\/main\/ipc\/(?:filesystem-(?:list-files|search-file-paths)|rg-availability)\.ts|src\/main\/providers\/(?:filesystem-provider-contract|ssh-filesystem-provider(?:-capabilities)?)\.ts|src\/main\/runtime\/(?:orca-runtime-files|rpc\/methods\/files)\.ts|src\/relay\/(?:fs-handler(?:-install-rg|-list-files|-ripgrep-fallback)?|fs-list-files-fallback-chain)\.ts|src\/renderer\/src\/(?:components\/(?:QuickOpen|quick-open-file-list|quick-open-search)\.tsx?|runtime\/(?:runtime-file-client|runtime-legacy-quick-open-inventory)\.ts)|src\/shared\/(?:quick-open-(?:install-rg|path-search|transport-budget)|ripgrep-process-availability)\.ts)$/.test( + file + ) + }, + { + id: 'terminal-session.host-cold-park-stream-continuity', + specs: ['tests/e2e/host-parked-pane-remote-viewer.spec.ts'], + matches: (file) => + isProductSource(file) && + /^(?:src\/renderer\/src\/components\/terminal-pane\/(?:terminal-hidden-view-parking|terminal-tab-park-candidates|terminal-tab-activation-order|terminal-parked-pty-watcher|terminal-parked-tab-watchers|terminal-parked-watcher-registry)\.ts|src\/renderer\/src\/runtime\/sync-runtime-graph\.ts)$/.test( + file + ) + }, + { + id: 'terminal-provider.ssh-remote-reattach-contract', + specs: ['tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts'], + matches: (file) => + isProductSource(file) && + !file.endsWith('-test-harness.ts') && + /^(?:src\/renderer\/src\/components\/terminal-pane\/remote-runtime-pty-transport(?:-[a-z0-9-]+)?\.ts|src\/renderer\/src\/runtime\/remote-runtime-terminal-multiplexer\.ts)$/.test( + file + ) + }, + { + id: 'terminal-session.remote-pane-layout-retry', + specs: ['tests/e2e/paired-remote-pane-layout-retry.spec.ts'], + matches: (file) => + isProductSource(file) && + /^(?:src\/renderer\/src\/components\/terminal-pane\/(?:remote-pane-layout-push|TerminalPane)\.tsx?|src\/renderer\/src\/lib\/terminal-layout-equality\.ts|src\/renderer\/src\/runtime\/web-session-tabs-sync\.ts|src\/renderer\/src\/store\/slices\/terminals\.ts)$/.test( + file + ) + } +] + +export function selectPrE2eSpecs(changedPaths, reportRoute = () => undefined) { + const specs = new Set(changedPaths.filter((file) => /^tests\/e2e\/.*\.spec\.ts$/.test(file))) + for (const route of PR_E2E_SOURCE_ROUTES) { + const matchedFiles = changedPaths.filter(route.matches) + if (matchedFiles.length === 0) { + continue + } + route.specs.forEach((spec) => specs.add(spec)) + reportRoute(`[pr-e2e] ${route.id}: ${route.specs.join(', ')}`) + } + return [...specs].sort((left, right) => left.localeCompare(right)) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + let input = '' + process.stdin.setEncoding('utf8') + for await (const chunk of process.stdin) { + input += chunk + } + const changedPaths = input.split(/\r?\n/).filter(Boolean) + const specs = selectPrE2eSpecs(changedPaths, (message) => console.error(message)) + process.stdout.write(`${JSON.stringify(specs)}\n`) +} diff --git a/config/scripts/windows-pty-native-capability-workflow.test.mjs b/config/scripts/windows-pty-native-capability-workflow.test.mjs new file mode 100644 index 00000000000..9a6b8b285cf --- /dev/null +++ b/config/scripts/windows-pty-native-capability-workflow.test.mjs @@ -0,0 +1,70 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' +import { parse } from 'yaml' + +const workflow = parse(readFileSync('.github/workflows/pr.yml', 'utf8')) +const packageJson = JSON.parse(readFileSync('package.json', 'utf8')) + +describe('packaged Windows PTY native capability routing', () => { + it('runs the packaged executable immediately after the unpacked app is built', () => { + const job = workflow.jobs.package_windows + const packageIndex = job.steps.findIndex((step) => step.name === 'Package unpacked app') + const smokeIndex = job.steps.findIndex( + (step) => step.name === 'Smoke packaged Windows PTY native capability' + ) + const smoke = job.steps[smokeIndex] + + expect(job['runs-on']).toBe('windows-2022') + expect(smokeIndex).toBe(packageIndex + 1) + expect(smoke.run).toBe( + 'pnpm run smoke:windows-pty-native-capability -- --exe=dist/win-unpacked/Orca.exe' + ) + expect(smoke.if).toBeUndefined() + expect(smoke['continue-on-error']).toBeUndefined() + expect(packageJson.scripts['smoke:windows-pty-native-capability']).toBe( + 'node tests/tools/windows-pty-native-capability-smoke/run.mjs' + ) + }) + + it('keeps patched source rebuild, release build, runtime reuse, and aggregate routing intact', () => { + const job = workflow.jobs.package_windows + const sourceRebuild = job.steps.find( + (step) => step.name === 'Rebuild node-pty from patched source' + ) + const build = job.steps.find((step) => step.name === 'Build package inputs') + const prepare = job.steps.find((step) => step.name === 'Prepare Electron native runtime') + const packageStep = job.steps.find((step) => step.name === 'Package unpacked app') + const verify = workflow.jobs.verify.steps.find( + (step) => step.name === 'Require successful checks' + ) + + expect(sourceRebuild.env.npm_config_build_from_source).toBe('true') + expect(sourceRebuild.run).toBe('pnpm rebuild node-pty') + expect(build.run).toBe('pnpm run build:release:parallel') + expect(prepare.run).toBe('node config/scripts/ensure-native-runtime.mjs --runtime=electron') + expect(packageStep.env.ORCA_REUSE_PREPARED_NATIVE_RUNTIME).toBe('1') + expect(workflow.jobs.verify.needs).toContain('package_windows') + expect(verify.env.PACKAGE_WINDOWS).toBe('${{ needs.package_windows.result }}') + expect(verify.run).toContain('"$PACKAGE_WINDOWS"') + }) + + it('keeps the native probe event-based, scoped, and runnable in packaged Node mode', () => { + const driver = readFileSync('tests/tools/windows-pty-native-capability-smoke/run.mjs', 'utf8') + const probe = readFileSync( + 'tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-probe.cjs', + 'utf8' + ) + const source = `${driver}\n${probe}` + + expect(driver).toContain("ELECTRON_RUN_AS_NODE: '1'") + expect(source).not.toMatch(/\b(?:sleep|tasklist|taskkill)\b/i) + expect(source).not.toContain('maxRetries') + expect(source).not.toContain('retryDelay') + expect(source).not.toContain("from 'node:child_process'") + expect(source).not.toContain("require('node:child_process')") + expect(probe).toContain("'System32', 'wscript.exe'") + expect(probe).toContain('real-orca-detached-launcher.vbs') + expect(probe).not.toMatch(/cmd\.exe|start "" \/b/i) + expect(probe).toContain('native.terminateJob(target._pty, target.pid)') + }) +}) diff --git a/package.json b/package.json index 66d0d0bf53e..933741f8cc4 100644 --- a/package.json +++ b/package.json @@ -115,6 +115,7 @@ "test:e2e:source-control-scale": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/source-control-large-file-count.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "win-update-e2e": "node tests/tools/win-update-e2e/run.mjs", "win-crash-survival-e2e": "node tests/tools/win-crash-survival-e2e/run.mjs", + "smoke:windows-pty-native-capability": "node tests/tools/windows-pty-native-capability-smoke/run.mjs", "test:e2e:ssh-codex-artifacts-repro": "node config/scripts/run-ssh-codex-artifacts-repro-e2e.mjs", "test:e2e:headful": "pnpm run ensure:electron-runtime && npx playwright test --config tests/playwright.config.ts --project electron-headful", "test:e2e:terminal-ime-native": "node config/scripts/run-terminal-ibus-hangul-e2e.mjs", diff --git a/src/main/runtime/agent-prompt-submission-runtime-test-fixture.ts b/src/main/runtime/agent-prompt-submission-runtime-test-fixture.ts new file mode 100644 index 00000000000..69470ac6148 --- /dev/null +++ b/src/main/runtime/agent-prompt-submission-runtime-test-fixture.ts @@ -0,0 +1,28 @@ +import type { TuiAgent } from '../../shared/tui-agent' +import { OrcaRuntimeService } from './orca-runtime' +import { makeStore } from './runtime-rpc-worktree-store-fixtures' + +export const AGENT_PROMPT_TEST_WORKTREE_PATH = '/tmp/worktree-a' +export const AGENT_PROMPT_TEST_WORKTREE_ID = 'repo-1::/tmp/worktree-a' + +export async function createAgentPromptSubmissionRuntime( + onWrite: (runtime: OrcaRuntimeService, data: string, writeIndex: number) => void, + launchAgent: TuiAgent = 'aider' +): Promise<{ runtime: OrcaRuntimeService; handle: string; writes: string[] }> { + const runtime = new OrcaRuntimeService(makeStore() as never) + const writes: string[] = [] + runtime.setPtyController({ + spawn: async () => ({ id: 'pty-prompt' }), + write: (_ptyId, data) => { + writes.push(data) + onWrite(runtime, data, writes.length) + return true + }, + kill: () => true, + getForegroundProcess: async () => null + }) + const terminal = await runtime.createTerminal(`path:${AGENT_PROMPT_TEST_WORKTREE_PATH}`, { + launchAgent + }) + return { runtime, handle: terminal.handle, writes } +} diff --git a/src/main/runtime/agent-prompt-submission-runtime.test.ts b/src/main/runtime/agent-prompt-submission-runtime.test.ts index 711e887b5c5..f26ff8030b8 100644 --- a/src/main/runtime/agent-prompt-submission-runtime.test.ts +++ b/src/main/runtime/agent-prompt-submission-runtime.test.ts @@ -3,10 +3,14 @@ import { AGENT_PROMPT_BRACKETED_PASTE_END, AGENT_PROMPT_SUBMIT_DELAY_MS } from '../../shared/agent-prompt-injection' +import { + AGENT_PROMPT_TEST_WORKTREE_PATH, + createAgentPromptSubmissionRuntime +} from './agent-prompt-submission-runtime-test-fixture' import { OrcaRuntimeService } from './orca-runtime' import { makeStore } from './runtime-rpc-worktree-store-fixtures' -const WORKTREE_PATH = '/tmp/worktree-a' +const createPromptRuntime = createAgentPromptSubmissionRuntime vi.mock('../git/worktree', () => ({ listWorktrees: vi.fn().mockResolvedValue([ @@ -29,37 +33,18 @@ vi.mock('../git/worktree', () => ({ ]) })) -async function createPromptRuntime( - onWrite: (runtime: OrcaRuntimeService, data: string, writeIndex: number) => void -): Promise<{ runtime: OrcaRuntimeService; handle: string; writes: string[] }> { - const runtime = new OrcaRuntimeService(makeStore() as never) - const writes: string[] = [] - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'pty-prompt' }), - write: (_ptyId, data) => { - writes.push(data) - onWrite(runtime, data, writes.length) - return true - }, - kill: () => true, - getForegroundProcess: async () => null - }) - const terminal = await runtime.createTerminal(`path:${WORKTREE_PATH}`, { - launchAgent: 'aider' - }) - return { runtime, handle: terminal.handle, writes } -} - describe('agent prompt submission runtime', () => { afterEach(() => vi.useRealTimers()) it('submits exactly once after an observed lifecycle transition', async () => { vi.useFakeTimers() - const { runtime, handle, writes } = await createPromptRuntime((runtime, data) => { - if (data === '\r') { - runtime.onPtyData('pty-prompt', '\x1b]0;Codex working\x07', Date.now()) + const { runtime, handle, writes } = await createAgentPromptSubmissionRuntime( + (runtime, data) => { + if (data === '\r') { + runtime.onPtyData('pty-prompt', '\x1b]0;Codex working\x07', Date.now()) + } } - }) + ) const submission = runtime.sendTerminalAgentPrompt(handle, 'review this') await vi.runAllTimersAsync() @@ -374,8 +359,11 @@ describe('agent prompt submission runtime', () => { kill: () => true, getForegroundProcess: async () => null }) - handle = (await runtime.createTerminal(`path:${WORKTREE_PATH}`, { launchAgent: 'aider' })) - .handle + handle = ( + await runtime.createTerminal(`path:${AGENT_PROMPT_TEST_WORKTREE_PATH}`, { + launchAgent: 'aider' + }) + ).handle runtime.onPtyData( 'pty-prompt', 'Permission required\nAllow once\nAllow always\nReject\n' + diff --git a/src/main/runtime/orca-runtime-terminal-close-continuity.test.ts b/src/main/runtime/orca-runtime-terminal-close-continuity.test.ts index c3a3e747b01..320f27d6c03 100644 --- a/src/main/runtime/orca-runtime-terminal-close-continuity.test.ts +++ b/src/main/runtime/orca-runtime-terminal-close-continuity.test.ts @@ -10,13 +10,62 @@ const WORKTREE_ID = `${REPO_ID}::${WORKTREE_PATH}` const TAB_ID = 'tab-close-continuity' const LEAF_ID = '11111111-1111-4111-8111-111111111111' const SIBLING_LEAF_ID = '33333333-3333-4333-8333-333333333333' +const CANARY_TAB_ID = 'tab-close-continuity-canary' +const CANARY_LEAF_ID = '55555555-5555-4555-8555-555555555555' const PTY_ID = 'pty-close-continuity' const RUNTIME_OWNED_PTY_ID = 'serve-close-continuity' const SIBLING_PTY_ID = 'pty-close-continuity-sibling' +const CANARY_PTY_ID = 'pty-close-continuity-canary' const INCARNATION_ID = '22222222-2222-4222-8222-222222222222' const SIBLING_INCARNATION_ID = '44444444-4444-4444-8444-444444444444' +const CANARY_INCARNATION_ID = '66666666-6666-4666-8666-666666666666' +const canarySessionTab = { + id: CANARY_TAB_ID, + ptyId: CANARY_PTY_ID, + worktreeId: WORKTREE_ID, + title: 'Canary shell', + customTitle: null, + color: null, + sortOrder: 1, + createdAt: 2 +} +const canarySessionLayout = { + root: { type: 'leaf' as const, leafId: CANARY_LEAF_ID }, + activeLeafId: CANARY_LEAF_ID, + expandedLeafId: null, + ptyIdsByLeafId: { [CANARY_LEAF_ID]: CANARY_PTY_ID } +} +const canarySyncedTab = { + tabId: CANARY_TAB_ID, + worktreeId: WORKTREE_ID, + title: 'Canary shell', + activeLeafId: CANARY_LEAF_ID, + layout: { type: 'leaf' as const, leafId: CANARY_LEAF_ID } +} +const canarySyncedLeaf = { + tabId: CANARY_TAB_ID, + worktreeId: WORKTREE_ID, + leafId: CANARY_LEAF_ID, + paneRuntimeId: 9, + ptyId: CANARY_PTY_ID +} +const canaryMobileTab = { + type: 'terminal' as const, + id: `${CANARY_TAB_ID}::${CANARY_LEAF_ID}`, + parentTabId: CANARY_TAB_ID, + leafId: CANARY_LEAF_ID, + ptyId: CANARY_PTY_ID, + title: 'Canary shell', + isActive: false +} +const canaryProcess = { + id: CANARY_PTY_ID, + incarnationId: CANARY_INCARNATION_ID, + cwd: WORKTREE_PATH, + title: 'Canary shell' +} -function makeSession(ptyId = PTY_ID): WorkspaceSessionState { +function makeSession(ptyId = PTY_ID, includeCanary = false): WorkspaceSessionState { return { ...getDefaultWorkspaceSession(), tabsByWorktree: { @@ -30,7 +79,8 @@ function makeSession(ptyId = PTY_ID): WorkspaceSessionState { color: null, sortOrder: 0, createdAt: 1 - } + }, + ...(includeCanary ? [canarySessionTab] : []) ] }, terminalLayoutsByTabId: { @@ -39,10 +89,14 @@ function makeSession(ptyId = PTY_ID): WorkspaceSessionState { activeLeafId: LEAF_ID, expandedLeafId: null, ptyIdsByLeafId: { [LEAF_ID]: ptyId } - } + }, + ...(includeCanary ? { [CANARY_TAB_ID]: canarySessionLayout } : {}) }, terminalPtyIncarnationsByPaneKey: { - [makePaneKey(TAB_ID, LEAF_ID)]: INCARNATION_ID + [makePaneKey(TAB_ID, LEAF_ID)]: INCARNATION_ID, + ...(includeCanary + ? { [makePaneKey(CANARY_TAB_ID, CANARY_LEAF_ID)]: CANARY_INCARNATION_ID } + : {}) } } } @@ -56,13 +110,19 @@ function makeDeferred() { } function createHarness( - options: { ptyId?: string; publishMobileSurface?: boolean; registerPtyBacked?: boolean } = {} + options: { + ptyId?: string + publishMobileSurface?: boolean + registerPtyBacked?: boolean + includeCanary?: boolean + } = {} ) { const ptyId = options.ptyId ?? PTY_ID - let session = makeSession(ptyId) + let session = makeSession(ptyId, options.includeCanary) let sessionAvailable = true let incarnationId = INCARNATION_ID let includeSiblingPty = false + let victimPtyListed = true const repo = { id: REPO_ID, path: WORKTREE_PATH, @@ -80,29 +140,40 @@ function createHarness( getWorkspaceSession: () => (sessionAvailable ? session : undefined), setWorkspaceSession: (next: WorkspaceSessionState) => { session = next - } + }, + flushOrThrow: () => {} } const acknowledged = makeDeferred() let closeTerminalTabError: Error | null = null + let closeTerminalTabAction: (() => void | Promise) | null = null const closeTerminal = vi.fn() - const closeTerminalTab = vi.fn(() => - closeTerminalTabError ? Promise.reject(closeTerminalTabError) : acknowledged.promise - ) + const closeTerminalTab = vi.fn(() => { + if (closeTerminalTabError) { + return Promise.reject(closeTerminalTabError) + } + return closeTerminalTabAction ? Promise.resolve(closeTerminalTabAction()) : acknowledged.promise + }) const kill = vi.fn(() => true) let verifiedStopResult: boolean | Error = false - const stopAndWait = vi.fn(async () => { + let stopAndWaitAction: ((stoppingPtyId: string) => void | Promise) | null = null + const stopAndWait = vi.fn(async (stoppingPtyId: string) => { + await stopAndWaitAction?.(stoppingPtyId) if (verifiedStopResult instanceof Error) { throw verifiedStopResult } return verifiedStopResult }) const listProcesses = vi.fn(async () => [ - { - id: ptyId, - incarnationId, - cwd: WORKTREE_PATH, - title: 'Fixture shell' - }, + ...(victimPtyListed + ? [ + { + id: ptyId, + incarnationId, + cwd: WORKTREE_PATH, + title: 'Fixture shell' + } + ] + : []), ...(includeSiblingPty ? [ { @@ -112,7 +183,8 @@ function createHarness( title: 'Fixture sibling shell' } ] - : []) + : []), + ...(options.includeCanary ? [canaryProcess] : []) ]) const runtime = new OrcaRuntimeService(store as never) runtime.setNotifier({ closeTerminal, closeTerminalTab } as never) @@ -134,7 +206,8 @@ function createHarness( title: 'Fixture shell', activeLeafId: LEAF_ID, layout: { type: 'leaf', leafId: LEAF_ID } - } + }, + ...(options.includeCanary ? [canarySyncedTab] : []) ], leaves: [ { @@ -143,7 +216,8 @@ function createHarness( leafId: LEAF_ID, paneRuntimeId: 7, ptyId - } + }, + ...(options.includeCanary ? [canarySyncedLeaf] : []) ], ...(options.publishMobileSurface ? { @@ -164,13 +238,34 @@ function createHarness( ptyId, title: 'Fixture shell', isActive: true - } + }, + ...(options.includeCanary ? [canaryMobileTab] : []) ] } ] } : {}) }) + const syncCanaryGraph = () => + runtime.syncWindowGraph(1, { + tabs: [canarySyncedTab], + leaves: [canarySyncedLeaf], + ...(options.publishMobileSurface + ? { + mobileSessionTabs: [ + { + worktree: WORKTREE_ID, + publicationEpoch: 'renderer:close-continuity', + snapshotVersion: 2, + activeGroupId: null, + activeTabId: `${CANARY_TAB_ID}::${CANARY_LEAF_ID}`, + activeTabType: 'terminal' as const, + tabs: [{ ...canaryMobileTab, isActive: true }] + } + ] + } + : {}) + }) const syncEmptyGraph = () => runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) const syncFixtureTabWithoutLeaf = () => runtime.syncWindowGraph(1, { @@ -181,9 +276,10 @@ function createHarness( title: 'Fixture shell', activeLeafId: LEAF_ID, layout: { type: 'leaf', leafId: LEAF_ID } - } + }, + ...(options.includeCanary ? [canarySyncedTab] : []) ], - leaves: [] + leaves: options.includeCanary ? [canarySyncedLeaf] : [] }) const syncSplitFixtureGraph = () => { includeSiblingPty = true @@ -245,6 +341,13 @@ function createHarness( leafId: LEAF_ID, incarnationId: INCARNATION_ID }) + if (options.includeCanary) { + runtime.registerPty(CANARY_PTY_ID, WORKTREE_ID, null, { + tabId: CANARY_TAB_ID, + leafId: CANARY_LEAF_ID, + incarnationId: CANARY_INCARNATION_ID + }) + } } syncFixtureGraph() return { @@ -254,6 +357,7 @@ function createHarness( closeTerminalTab, kill, stopAndWait, + syncCanaryGraph, syncEmptyGraph, syncFixtureGraph, syncFixtureTabWithoutLeaf, @@ -262,20 +366,41 @@ function createHarness( makeSessionUnavailable: () => { sessionAvailable = false }, + removeVictimFromInventory: () => { + victimPtyListed = false + }, retirePersistedTab: () => { + const victimPaneKey = makePaneKey(TAB_ID, LEAF_ID) session = { ...session, - tabsByWorktree: { ...session.tabsByWorktree, [WORKTREE_ID]: [] }, - terminalLayoutsByTabId: {}, - terminalPtyIncarnationsByPaneKey: {} + tabsByWorktree: { + ...session.tabsByWorktree, + [WORKTREE_ID]: (session.tabsByWorktree[WORKTREE_ID] ?? []).filter( + (tab) => tab.id !== TAB_ID + ) + }, + terminalLayoutsByTabId: Object.fromEntries( + Object.entries(session.terminalLayoutsByTabId).filter(([tabId]) => tabId !== TAB_ID) + ), + terminalPtyIncarnationsByPaneKey: Object.fromEntries( + Object.entries(session.terminalPtyIncarnationsByPaneKey ?? {}).filter( + ([paneKey]) => paneKey !== victimPaneKey + ) + ) } }, + setCloseTerminalTabAction: (action: () => void | Promise) => { + closeTerminalTabAction = action + }, rejectTerminalTabClose: (error: Error) => { closeTerminalTabError = error }, setVerifiedStopResult: (result: boolean | Error) => { verifiedStopResult = result }, + setStopAndWaitAction: (action: (stoppingPtyId: string) => void | Promise) => { + stopAndWaitAction = action + }, replaceIncarnation: (next: string) => { incarnationId = next } @@ -317,6 +442,79 @@ describe('terminal close and handle incarnation continuity', () => { expect(harness.getSession().tabsByWorktree[WORKTREE_ID]).toEqual([]) }) + it('fences final-pane exit ordering until exact retirement commits', async () => { + const harness = createHarness({ + includeCanary: true, + publishMobileSurface: true, + registerPtyBacked: true + }) + harness.syncFixtureTabWithoutLeaf() + const closeMobileSessionTab = vi.spyOn(harness.runtime, 'closeMobileSessionTab') + const order: string[] = [] + harness.setCloseTerminalTabAction(() => { + order.push('session-retirement') + harness.retirePersistedTab() + harness.syncCanaryGraph() + order.push('committed-graph-removal') + }) + harness.setVerifiedStopResult(true) + harness.setStopAndWaitAction((stoppingPtyId) => { + order.push('pty-stop') + harness.removeVictimFromInventory() + harness.syncCanaryGraph() + order.push('idempotent-graph-removal') + harness.runtime.onPtyExit(stoppingPtyId, 0, INCARNATION_ID) + order.push('idempotent-session-retirement') + }) + const terminals = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals + const victim = terminals.find((terminal) => terminal.ptyId === PTY_ID)! + const canary = terminals.find((terminal) => terminal.ptyId === CANARY_PTY_ID)! + + await expect(harness.runtime.closeTerminal(victim.handle)).resolves.toMatchObject({ + handle: victim.handle, + tabId: TAB_ID, + ptyKilled: true + }) + + expect(order).toEqual([ + 'session-retirement', + 'committed-graph-removal', + 'pty-stop', + 'idempotent-graph-removal', + 'idempotent-session-retirement' + ]) + expect(harness.stopAndWait).toHaveBeenCalledTimes(1) + expect(harness.stopAndWait).toHaveBeenCalledWith(PTY_ID, { + deadlineMs: expect.any(Number) + }) + expect(harness.kill).not.toHaveBeenCalled() + expect(closeMobileSessionTab).toHaveBeenCalledTimes(1) + expect(closeMobileSessionTab).toHaveBeenCalledWith(`id:${WORKTREE_ID}`, TAB_ID, { + localPtyTeardownOwnedExternally: true + }) + expect(harness.closeTerminalTab).toHaveBeenCalledTimes(1) + expect(harness.getSession().tabsByWorktree[WORKTREE_ID]).toEqual([ + expect.objectContaining({ id: CANARY_TAB_ID, ptyId: CANARY_PTY_ID }) + ]) + expect(harness.getSession().terminalLayoutsByTabId).toEqual({ + [CANARY_TAB_ID]: expect.objectContaining({ + ptyIdsByLeafId: { [CANARY_LEAF_ID]: CANARY_PTY_ID } + }) + }) + expect(harness.getSession().terminalPtyIncarnationsByPaneKey).toEqual({ + [makePaneKey(CANARY_TAB_ID, CANARY_LEAF_ID)]: CANARY_INCARNATION_ID + }) + const survivors = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals + expect(survivors).toHaveLength(1) + const [survivor] = survivors + expect(survivor).toMatchObject({ ptyId: CANARY_PTY_ID }) + await expect(harness.runtime.readTerminal(survivor.handle)).resolves.toMatchObject({ + handle: survivor.handle, + status: 'running' + }) + expect(canary.ptyId).toBe(survivor.ptyId) + }) + it('does not kill the final PTY when durable tab retirement is rejected', async () => { const harness = createHarness() const [{ handle }] = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals diff --git a/src/main/runtime/rpc/methods/orchestration-worker-start-prompt-contract.test.ts b/src/main/runtime/rpc/methods/orchestration-worker-start-prompt-contract.test.ts new file mode 100644 index 00000000000..89455f9cc0a --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration-worker-start-prompt-contract.test.ts @@ -0,0 +1,277 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { AGENT_PROMPT_BRACKETED_PASTE_END } from '../../../../shared/agent-prompt-injection' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../shared/protocol-version' +import { + AGENT_PROMPT_TEST_WORKTREE_ID, + createAgentPromptSubmissionRuntime +} from '../../agent-prompt-submission-runtime-test-fixture' +import { OrchestrationDb } from '../../orchestration/db' +import type { RpcRequest } from '../core' +import { RpcDispatcher } from '../dispatcher' +import { ORCHESTRATION_METHODS } from './orchestration' + +vi.mock('../../../git/worktree', () => ({ + listWorktrees: vi.fn().mockResolvedValue([ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/prompt-contract', + isBare: false, + isMainWorktree: false + } + ]), + listWorktreesStrict: vi.fn().mockResolvedValue([ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/prompt-contract', + isBare: false, + isMainWorktree: false + } + ]) +})) + +const COORDINATOR_PANE_KEY = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' +const WORKER_PANE_KEY = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' +const REQUEST_ID = 'worker_start_prompt_contract' +const openDatabases: OrchestrationDb[] = [] +const temporaryRoots: string[] = [] + +type PromptContractHarness = { + db: OrchestrationDb + dbPath: string + dispatcher: RpcDispatcher + request: RpcRequest + requestId: string + taskId: string + submittedTurns: () => number + startedTurns: () => number + prematureSubmits: () => number + writes: string[] +} + +async function createPromptContractHarness( + outcome: 'accepted' | 'swallowed' +): Promise { + let composerReady = false + let submittedTurns = 0 + let startedTurns = 0 + let prematureSubmits = 0 + const fixture = await createAgentPromptSubmissionRuntime((runtime, data) => { + if (data.includes(AGENT_PROMPT_BRACKETED_PASTE_END)) { + setTimeout(() => runtime.onPtyData('pty-prompt', 'partial composer frame', Date.now()), 650) + setTimeout(() => runtime.onPtyData('pty-prompt', '\x1b[?25h', Date.now()), 750) + setTimeout(() => { + composerReady = true + runtime.onPtyData('pty-prompt', 'final composer frame', Date.now()) + }, 1_000) + return + } + if (data !== '\r') { + return + } + submittedTurns += 1 + if (!composerReady) { + prematureSubmits += 1 + } + if (outcome === 'accepted') { + startedTurns += 1 + runtime.onPtyData('pty-prompt', '\x1b]0;Codex working\x07', Date.now()) + } + }, 'codex') + const { runtime, handle } = fixture + runtime.onPtyData('pty-prompt', '\x1b]0;Codex idle\x07', Date.now()) + + const temporaryRoot = mkdtempSync(join(tmpdir(), 'orca-worker-prompt-contract-')) + temporaryRoots.push(temporaryRoot) + const dbPath = join(temporaryRoot, 'orchestration.db') + const db = new OrchestrationDb(dbPath) + openDatabases.push(db) + runtime.setOrchestrationDb(db) + const run = db.createRun({ + objective: 'Worker prompt contract', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: COORDINATOR_PANE_KEY + }) + const task = db.createTask({ spec: 'start exactly one worker turn', runId: run.id }) + vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((candidate) => + candidate === 'term_coord' + ? COORDINATOR_PANE_KEY + : candidate === handle + ? WORKER_PANE_KEY + : null + ) + vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockImplementation((candidate) => + candidate === handle ? `runtime_test:${handle}:1` : null + ) + vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {}) + vi.spyOn(runtime, 'showTerminal').mockResolvedValue({ + handle: 'term_coord', + worktreeId: 'repo::parent', + status: 'running' + } as never) + vi.spyOn(runtime, 'showManagedWorktree').mockResolvedValue({ + id: 'repo::parent', + repoId: 'repo-1' + } as never) + vi.spyOn(runtime, 'showRepo').mockResolvedValue({ id: 'repo-1', kind: 'git' } as never) + vi.spyOn(runtime, 'createManagedWorktree').mockResolvedValue({ + worktree: { id: AGENT_PROMPT_TEST_WORKTREE_ID, repoId: 'repo-1' }, + startupTerminal: { spawned: true, handle }, + setupReceipt: { + requested: 'run', + hookFound: false, + startupPolicy: 'start-immediately', + state: 'not_configured' + } + } as never) + vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca') + + return { + db, + dbPath, + dispatcher: new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }), + request: { + id: `rpc_${outcome}`, + authToken: 'caller-token', + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationRequestId: `${REQUEST_ID}_${outcome}`, + method: 'orchestration.workerStart', + params: { + task: task.id, + from: 'term_coord', + worktree: 'new-child', + name: `prompt-contract-${outcome}`, + agent: 'codex' + } + }, + requestId: `${REQUEST_ID}_${outcome}`, + taskId: task.id, + submittedTurns: () => submittedTurns, + startedTurns: () => startedTurns, + prematureSubmits: () => prematureSubmits, + writes: fixture.writes + } +} + +function reopenPromptContractDb(harness: PromptContractHarness): OrchestrationDb { + const index = openDatabases.indexOf(harness.db) + if (index !== -1) { + openDatabases.splice(index, 1) + } + harness.db.close() + harness.db = new OrchestrationDb(harness.dbPath) + openDatabases.push(harness.db) + return harness.db +} + +describe('orchestration worker-start prompt contract', () => { + afterEach(() => { + for (const db of openDatabases.splice(0)) { + db.close() + } + for (const root of temporaryRoots.splice(0)) { + rmSync(root, { recursive: true, force: true }) + } + vi.useRealTimers() + }) + + it('durably accepts exactly one submitted and started turn', async () => { + vi.useFakeTimers() + const harness = await createPromptContractHarness('accepted') + const pending = harness.dispatcher.dispatch(harness.request) + + await vi.runAllTimersAsync() + const response = await pending + expect(response).toMatchObject({ + ok: true, + result: { + state: 'ready', + stage: 'input_accepted', + mutation: { requestId: harness.requestId, replayed: false }, + effects: expect.arrayContaining([ + expect.objectContaining({ kind: 'dispatch_input', state: 'accepted' }) + ]) + } + }) + if (!response.ok) { + throw new Error(response.error.message) + } + const dispatchId = (response.result as { dispatchId: string }).dispatchId + expect(harness.submittedTurns()).toBe(1) + expect(harness.startedTurns()).toBe(1) + expect(harness.prematureSubmits()).toBe(0) + expect(harness.writes.filter((data) => data === '\r')).toHaveLength(1) + const persisted = reopenPromptContractDb(harness) + expect(persisted.getTask(harness.taskId)?.status).toBe('dispatched') + expect(persisted.getDispatchContextById(dispatchId)).toMatchObject({ + status: 'dispatched', + capability_hash: expect.any(String), + capability_revoked_at: null + }) + expect(persisted.getWorkerDispatch(dispatchId)).toMatchObject({ + state: 'ready', + stage: 'input_accepted', + last_error: null + }) + const callerFingerprint = persisted.getOrCreateLocalMutationCallerFingerprint() + const receipt = persisted.getMutationReceipt(callerFingerprint, harness.requestId) + expect(receipt).toMatchObject({ state: 'completed' }) + expect(JSON.parse(receipt?.receipt ?? 'null')).toMatchObject({ + dispatchId, + state: 'ready', + stage: 'input_accepted' + }) + }) + + it('reports a swallowed Enter as stalled without sending a rescue Enter', async () => { + vi.useFakeTimers() + const harness = await createPromptContractHarness('swallowed') + const pending = harness.dispatcher.dispatch(harness.request) + + await vi.runAllTimersAsync() + const response = await pending + expect(response).toMatchObject({ + ok: true, + result: { + state: 'failed', + failedStage: 'dispatch_input', + lastError: 'agent_prompt_stalled', + mutation: { requestId: harness.requestId, replayed: false } + } + }) + if (!response.ok) { + throw new Error(response.error.message) + } + const dispatchId = (response.result as { dispatchId: string }).dispatchId + await vi.advanceTimersByTimeAsync(20_000) + expect(harness.submittedTurns()).toBe(1) + expect(harness.startedTurns()).toBe(0) + expect(harness.prematureSubmits()).toBe(0) + expect(harness.writes.filter((data) => data === '\r')).toHaveLength(1) + const persisted = reopenPromptContractDb(harness) + expect(persisted.getTask(harness.taskId)?.status).toBe('failed') + expect(persisted.getDispatchContextById(dispatchId)).toMatchObject({ + status: 'failed', + last_failure: 'agent_prompt_stalled', + capability_revoked_at: expect.any(String) + }) + expect(persisted.getWorkerDispatch(dispatchId)).toMatchObject({ + state: 'failed', + stage: 'dispatch_input', + last_error: 'agent_prompt_stalled' + }) + const callerFingerprint = persisted.getOrCreateLocalMutationCallerFingerprint() + const receipt = persisted.getMutationReceipt(callerFingerprint, harness.requestId) + expect(receipt).toMatchObject({ state: 'completed' }) + expect(JSON.parse(receipt?.receipt ?? 'null')).toMatchObject({ + dispatchId, + state: 'failed', + failedStage: 'dispatch_input', + lastError: 'agent_prompt_stalled' + }) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-spawn-retry.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-spawn-retry.test.ts index 9017b94dc98..410f8afac54 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-spawn-retry.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-spawn-retry.test.ts @@ -6,6 +6,10 @@ import { createMockTransport, createPane, createManager } from './pty-connection import { buildPaneConnectionDeps, buildDirectSshSplitRetryCommit } from './pty-connection-test-deps' import { createInitialStoreState } from './pty-connection-test-store-fixtures' import type { StoreState } from './pty-connection-test-store-state' +import { + pendingSpawnByPaneKey, + pendingSpawnGenerationByPaneKey +} from './pty-connection/pty-connect-limits' import type { MockTransport } from './pty-connection-test-pane-fixtures' import { installTerminalTestGlobals, @@ -139,6 +143,8 @@ describe('connectPanePty', () => { }) afterEach(async () => { + pendingSpawnByPaneKey.clear() + pendingSpawnGenerationByPaneKey.clear() await restoreTerminalTestGlobals() }) @@ -161,6 +167,42 @@ describe('connectPanePty', () => { logSpy.mockRestore() }, 30_000) + it('does not hold a successor behind a canceled spawn serializer declaration', async () => { + const { connectPanePty } = await import('./pty-connection') + const declaration = createDeferred() + const spawn = createDeferred() + const transport = createMockTransport() + transport.connect.mockReturnValueOnce(spawn.promise) + transportFactoryQueue.push(transport) + mockStoreState = { + ...mockStoreState, + tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] }, + ptyIdsByTabId: { 'tab-1': [] } + } + vi.mocked(window.api.pty.declarePendingPaneSerializer).mockReturnValueOnce(declaration.promise) + + const binding = connectPanePty( + createPane(1) as never, + createManager(1) as never, + createDeps() as never + ) + await flushAsyncTicks(12) + binding.dispose() + spawn.resolve(null) + await flushAsyncTicks(12) + + expect(pendingSpawnByPaneKey.size).toBe(0) + expect(window.api.pty.clearPendingPaneSerializer).not.toHaveBeenCalled() + + declaration.resolve(7) + await flushAsyncTicks(12) + + expect(window.api.pty.clearPendingPaneSerializer).toHaveBeenCalledExactlyOnceWith( + expect.any(String), + 7 + ) + }) + it.each(['rejects', 'resolves empty'] as const)( 'settles the exact direct SSH retry when its fresh spawn %s', async (outcome) => { diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-idle-working-handlers.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-idle-working-handlers.ts index 523b77a32f1..7623bfbafc2 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-idle-working-handlers.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-idle-working-handlers.ts @@ -151,9 +151,14 @@ export function installAgentIdleWorkingHandlers(session: ConnectPanePtySession): : undefined return attempt })() - session.pendingSpawnKey = session.directSshRetryAttempt - ? JSON.stringify([session.cacheKey, session.directSshRetryAttempt.attemptId]) - : session.cacheKey + // Generation is part of ownership: a recovery remount must not join a spawn + // started by the pane instance it replaced, while StrictMode remounts keep + // the same generation and may still share their in-flight spawn. + session.pendingSpawnKey = JSON.stringify([ + session.cacheKey, + session.tabGeneration, + session.directSshRetryAttempt?.attemptId ?? null + ]) session.capturedDirectSshRetryPtyAccepted = false session.directSshPaneRetrySettlementCancelled = false session.directSshPaneRetrySettlementTimers = new Set>() diff --git a/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts b/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts index c689b66f3ee..5b25adf6b51 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts @@ -1,4 +1,5 @@ import type { PaneManager, ManagedPane } from '@/lib/pane-manager/pane-manager' +import { useAppStore } from '@/store' import { TerminalKittyKeyboardModeTracker } from '../../../../../shared/terminal-kitty-keyboard-mode-tracker' import type { PtyConnectionDeps } from '../pty-connection-types' import { @@ -35,6 +36,7 @@ import { installPtyInputRecovery } from './pty-input-recovery' import { installPtyInputForward } from './pty-input-forward' import { installPtyResizeGeometry } from './pty-resize-geometry' import { installSessionReconcileDispose } from './session-reconcile-dispose' +import { resolveTerminalTabId } from './terminal-tab-id' /** * Establishes a binding between a terminal pane and its corresponding PTY stream, @@ -48,6 +50,43 @@ export function connectPanePty( const session = { pane, manager, deps } as ConnectPanePtySession session.shouldRefreshForegroundSynchronously = (): boolean => !session.manager.hasWebglRenderer(session.pane.id) + const state = useAppStore.getState() + const unifiedTab = state.getTab?.(deps.tabId) + const initialOwnerWorktreeId = + state.getTerminalTabOwnerWorktreeId?.(deps.tabId) ?? + (unifiedTab?.contentType === 'terminal' + ? state.getTerminalTabOwnerWorktreeId?.(unifiedTab.entityId) + : null) + const terminalTabId = resolveTerminalTabId( + { + getTab: state.getTab, + hasTerminalTab: (candidateId) => + Boolean( + state.tabsByWorktree[deps.worktreeId]?.some( + (candidate) => candidate.id === candidateId + ) || + (initialOwnerWorktreeId + ? state.tabsByWorktree[initialOwnerWorktreeId]?.some( + (candidate) => candidate.id === candidateId + ) + : false) + ) + }, + deps.tabId + ) + const ownerWorktreeId = + state.getTerminalTabOwnerWorktreeId?.(terminalTabId) ?? initialOwnerWorktreeId + const terminalTab = + state.tabsByWorktree[deps.worktreeId]?.find((candidate) => candidate.id === terminalTabId) ?? + (ownerWorktreeId + ? state.tabsByWorktree[ownerWorktreeId]?.find((candidate) => candidate.id === terminalTabId) + : undefined) ?? + // Why: folder/worktree migrations can leave the pane's render key stale for one commit. + Object.values(state.tabsByWorktree) + .find((tabs) => tabs.some((candidate) => candidate.id === terminalTabId)) + ?.find((candidate) => candidate.id === terminalTabId) + const tab = terminalTab ?? (unifiedTab && 'generation' in unifiedTab ? unifiedTab : null) + session.tabGeneration = tab?.generation ?? 0 // Why: recovery ownership belongs to this xterm instance. A request that // settles after remount must not remount its already-replaced successor. session.terminalRecoveryGeneration = captureTerminalPaneRecoveryGeneration(session.deps.tabId) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.ts b/src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.ts index 4d97ecf82c6..ca0da3e9731 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.ts @@ -3,7 +3,11 @@ import { useAppStore } from '@/store' import { isWebTerminalSurfaceTabId } from '@/runtime/web-terminal-surface-id' import { getEagerPtyBufferHandle } from '../pty-dispatcher' -import { pendingSpawnByPaneKey, recordPtyConnectDiagnostic } from './pty-connect-limits' +import { + pendingSpawnByPaneKey, + pendingSpawnGenerationByPaneKey, + recordPtyConnectDiagnostic +} from './pty-connect-limits' import { isRemoteRuntimePtyId, canRestorePairedParkedTerminal, @@ -158,6 +162,13 @@ export function runDeferredSessionReattachChoice(session: ConnectPanePtySession) session.allowInitialIdleCacheSeed = false const pendingSpawn = pendingSpawnByPaneKey.get(session.pendingSpawnKey) if (pendingSpawn) { + const pendingGeneration = pendingSpawnGenerationByPaneKey.get(session.pendingSpawnKey) + if (pendingGeneration !== undefined && pendingGeneration !== session.tabGeneration) { + recordPtyConnectDiagnostic(`pane=${session.pane.id} -> STALE PENDING SPAWN`) + session.startFreshSpawn() + scheduleRuntimeGraphSync() + return + } recordPtyConnectDiagnostic(`pane=${session.pane.id} -> PENDING SPAWN`) session.armDirectSshPaneRetryTimeout(pendingSpawn, session.directSshRetryAttempt) void pendingSpawn diff --git a/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts b/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts index 3bbbf76f2d9..d60e94a160f 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts @@ -3,7 +3,7 @@ import { hasPtySerializer } from '../pty-buffer-serializer' import { writeTerminalOutput } from '@/lib/pane-manager/pane-terminal-output-scheduler' import { STARTUP_CWD_FALLBACK_NOTICE } from './startup-cwd-fallback-notice' -import { pendingSpawnByPaneKey } from './pty-connect-limits' +import { pendingSpawnByPaneKey, pendingSpawnGenerationByPaneKey } from './pty-connect-limits' import { shouldWritePtyOutputForeground } from './foreground-output-scan' import { isRemoteRuntimePtyId } from './paired-parked-terminal-restore' import { toProcessExitStartup } from './process-exit-startup' @@ -14,6 +14,7 @@ import type { } from './fresh-spawn-types' import type { ConnectPanePtySession } from './connect-pane-pty-session' +import { resolveTerminalTabId } from './terminal-tab-id' export function bindStartFreshSpawn(session: ConnectPanePtySession): void { session.startFreshSpawn = ( @@ -56,6 +57,15 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { const preSignalPromise = session.runtimeEnvironmentId ? Promise.resolve(null) : window.api.pty.declarePendingPaneSerializer(session.cacheKey).catch(() => null) + const clearPreSignaledSerializer = (): void => { + // A disposed pre-bind connect must not keep a successor behind a slow + // serializer declaration. Cleanup can finish independently of spawn ownership. + void preSignalPromise.then((gen) => { + if (typeof gen === 'number') { + void window.api.pty.clearPendingPaneSerializer(session.cacheKey, gen).catch(() => {}) + } + }) + } session.transportConnectInFlightSince = Date.now() const effectiveStartup = startupOverride === undefined ? session.paneStartup : startupOverride @@ -86,6 +96,51 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { ...(coldRestoreOverride ? { launchToken: coldRestoreOverride.launchToken } : {}), ...(coldRestoreOverride ? { launchAgent: coldRestoreOverride.agent } : {}), ...(session.shouldDeclareHiddenAtSpawn() ? { initiallyHidden: true } : {}), + shouldContinue: () => { + const state = useAppStore.getState() + const unifiedTab = state.getTab?.(session.deps.tabId) + const initialOwnerWorktreeId = + state.getTerminalTabOwnerWorktreeId?.(session.deps.tabId) ?? + (unifiedTab?.contentType === 'terminal' + ? state.getTerminalTabOwnerWorktreeId?.(unifiedTab.entityId) + : null) + const terminalTabId = resolveTerminalTabId( + { + getTab: state.getTab, + hasTerminalTab: (candidateId) => + Boolean( + state.tabsByWorktree[session.deps.worktreeId]?.some( + (candidate) => candidate.id === candidateId + ) || + (initialOwnerWorktreeId + ? state.tabsByWorktree[initialOwnerWorktreeId]?.some( + (candidate) => candidate.id === candidateId + ) + : false) + ) + }, + session.deps.tabId + ) + const ownerWorktreeId = + state.getTerminalTabOwnerWorktreeId?.(terminalTabId) ?? initialOwnerWorktreeId + const terminalTab = + state.tabsByWorktree[session.deps.worktreeId]?.find( + (candidate) => candidate.id === terminalTabId + ) ?? + (ownerWorktreeId + ? state.tabsByWorktree[ownerWorktreeId]?.find( + (candidate) => candidate.id === terminalTabId + ) + : undefined) + const fallbackTab = Object.values(state.tabsByWorktree) + .find((tabs) => tabs.some((candidate) => candidate.id === terminalTabId)) + ?.find((candidate) => candidate.id === terminalTabId) + const currentTab = + terminalTab ?? + fallbackTab ?? + (unifiedTab && 'generation' in unifiedTab ? unifiedTab : null) + return !session.disposed && (currentTab?.generation ?? 0) === session.tabGeneration + }, callbacks: outputCallbacks.callbacks }) @@ -98,10 +153,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { .then(async (spawnedPtyId) => { if (outputCallbacks.generation !== session.transportStreamGeneration) { session.finishReattachLiveDataDeferral(false, outputCallbacks.generation) - const gen = await preSignalPromise - if (typeof gen === 'number') { - void window.api.pty.clearPendingPaneSerializer(session.cacheKey, gen).catch(() => {}) - } + clearPreSignaledSerializer() return null } const resolvedPtyId = @@ -114,10 +166,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { session.finishReattachLiveDataDeferral(false, outputCallbacks.generation) // Why: an outstanding declare keeps main's cooperation gate suppressing // this paneKey's daemon-snapshot seed until something releases it. - const gen = await preSignalPromise - if (typeof gen === 'number') { - void window.api.pty.clearPendingPaneSerializer(session.cacheKey, gen).catch(() => {}) - } + clearPreSignaledSerializer() return null } const connectResult = @@ -196,6 +245,11 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { if (resolvedPtyId) { session.reconcilePtySizeAfterSpawn(resolvedPtyId, session.cols, session.rows) } + if (!resolvedPtyId) { + clearPreSignaledSerializer() + session.finishReattachLiveDataDeferral(false, outputCallbacks.generation) + return null + } const gen = await preSignalPromise // Why: a bound PTY owns the renderer serializer even when the declare was // rejected; the gen token only settles or clears the pending declaration. @@ -206,8 +260,6 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { if (typeof gen === 'number') { void window.api.pty.settlePaneSerializer(session.cacheKey, gen).catch(() => {}) } - } else if (typeof gen === 'number') { - void window.api.pty.clearPendingPaneSerializer(session.cacheKey, gen).catch(() => {}) } if (resolvedPtyId && session.connectionId) { if ( @@ -229,15 +281,13 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { ) { session.clearRegisteredStartupLaunchConfig() } - const gen = await preSignalPromise - if (typeof gen === 'number') { - void window.api.pty.clearPendingPaneSerializer(session.cacheKey, gen).catch(() => {}) - } + clearPreSignaledSerializer() return null }) .finally(() => { if (pendingSpawnByPaneKey.get(session.pendingSpawnKey) === trackedPromise) { pendingSpawnByPaneKey.delete(session.pendingSpawnKey) + pendingSpawnGenerationByPaneKey.delete(session.pendingSpawnKey) } }) session.armDirectSshPaneRetryTimeout(trackedPromise, session.directSshRetryAttempt) @@ -259,6 +309,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { // Why: split panes in the same tab can spawn concurrently. Key by pane // as well as tab so a remount cannot attach to a sibling setup pane's PTY. pendingSpawnByPaneKey.set(session.pendingSpawnKey, trackedPromise) + pendingSpawnGenerationByPaneKey.set(session.pendingSpawnKey, session.tabGeneration) return trackedPromise } } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/pty-connect-limits.ts b/src/renderer/src/components/terminal-pane/pty-connection/pty-connect-limits.ts index 82e850eef19..e082c5703c9 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/pty-connect-limits.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/pty-connect-limits.ts @@ -1,6 +1,7 @@ import { e2eConfig } from '@/lib/e2e-config' export const pendingSpawnByPaneKey = new Map>() +export const pendingSpawnGenerationByPaneKey = new Map() export const SSH_SESSION_EXPIRED_ERROR = 'SSH_SESSION_EXPIRED' // Why: relay requests expire at 30s; leave one second for their fallback before re-arming locally. export const DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS = 31_000 diff --git a/src/renderer/src/components/terminal-pane/pty-connection/terminal-tab-id.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/terminal-tab-id.test.ts new file mode 100644 index 00000000000..24292e7d85d --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection/terminal-tab-id.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it, vi } from 'vitest' +import { resolveTerminalTabId } from './terminal-tab-id' + +describe('resolveTerminalTabId', () => { + it('maps a unified terminal tab id to its legacy owner id', () => { + const getTab = vi.fn(() => ({ contentType: 'terminal', entityId: 'legacy-tab' })) + + expect(resolveTerminalTabId({ getTab }, 'unified-tab')).toBe('legacy-tab') + expect(getTab).toHaveBeenCalledWith('unified-tab') + }) + + it('keeps non-terminal and unknown ids unchanged', () => { + expect( + resolveTerminalTabId( + { getTab: () => ({ contentType: 'editor', entityId: '/tmp/file.ts' }) }, + 'editor-tab' + ) + ).toBe('editor-tab') + expect(resolveTerminalTabId({}, 'legacy-tab')).toBe('legacy-tab') + }) + + it('keeps an exact terminal owner ahead of a stale unified alias', () => { + expect( + resolveTerminalTabId( + { + getTab: () => ({ contentType: 'terminal', entityId: 'old-owner' }), + hasTerminalTab: (tabId) => tabId === 'live-owner' + }, + 'live-owner' + ) + ).toBe('live-owner') + }) +}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/terminal-tab-id.ts b/src/renderer/src/components/terminal-pane/pty-connection/terminal-tab-id.ts new file mode 100644 index 00000000000..c4e02f82af0 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection/terminal-tab-id.ts @@ -0,0 +1,15 @@ +type TerminalTabLookup = { + getTab?: (tabId: string) => { contentType: string; entityId: string } | null + hasTerminalTab?: (tabId: string) => boolean +} + +/** Resolve a renderer tab id to the legacy terminal-tab id used by PTY state. */ +export function resolveTerminalTabId(state: TerminalTabLookup, tabId: string): string { + // The terminal-tab table is authoritative when both id forms are briefly present. + // A stale unified entry must not redirect a live PTY owner to an older entity id. + if (state.hasTerminalTab?.(tabId)) { + return tabId + } + const unifiedTab = state.getTab?.(tabId) + return unifiedTab?.contentType === 'terminal' ? unifiedTab.entityId : tabId +} diff --git a/src/renderer/src/components/terminal-pane/pty-transport-connect-spawn.test.ts b/src/renderer/src/components/terminal-pane/pty-transport-connect-spawn.test.ts index 4abc51cb28c..66dca98b360 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport-connect-spawn.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport-connect-spawn.test.ts @@ -38,6 +38,18 @@ describe('createIpcPtyTransport', () => { transport.disconnect() }) + it('does not create a PTY when the pane generation is stale', async () => { + const { createIpcPtyTransport } = await import('./pty-transport') + const spawn = window.api.pty.spawn as unknown as ReturnType + const transport = createIpcPtyTransport({}) + + await expect( + transport.connect({ url: '', shouldContinue: () => false, callbacks: {} }) + ).resolves.toBeUndefined() + + expect(spawn).not.toHaveBeenCalled() + }) + it('threads provider command ownership through the spawn IPC', async () => { const { createIpcPtyTransport } = await import('./pty-transport') const transport = createIpcPtyTransport({ diff --git a/src/renderer/src/components/terminal-pane/pty-transport-types.ts b/src/renderer/src/components/terminal-pane/pty-transport-types.ts index d8bdc63f62a..17f390f4ec4 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport-types.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport-types.ts @@ -154,6 +154,8 @@ export type PtyTransport = { startupCommandDelivery?: StartupCommandDelivery /** Reject a stale restored identity before this transport can publish global PTY handlers. */ admitPtyId?: (ptyId: string) => boolean + /** Reject a stale pane after any pre-spawn test gate but before creating a PTY. */ + shouldContinue?: () => boolean callbacks: PtyCallbacks }) => void | Promise attach: (options: { diff --git a/src/renderer/src/components/terminal-pane/pty-transport.ts b/src/renderer/src/components/terminal-pane/pty-transport.ts index f713ee6c2f9..5d24ede0b4d 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport.ts @@ -33,6 +33,7 @@ import { isPreHandlerPtyStateDiscarded } from './pty-pre-handler-buffer' import { createPtyInputWriteQueue } from './pty-input-write-queue' +import { waitAtTerminalPtyPreSpawnE2EBarrier } from './terminal-pty-pre-spawn-e2e-barrier' import type { PtyDataMeta } from './pty-dispatcher' import type { IpcPtyTransportOptions, PtyConnectResult, PtyTransport } from './pty-transport-types' import { createBellDetector } from '../../../../shared/terminal-bell-detector' @@ -807,6 +808,16 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra } try { + const preSpawnBarrier = waitAtTerminalPtyPreSpawnE2EBarrier() + if (preSpawnBarrier) { + await preSpawnBarrier + if (destroyed) { + return + } + } + if (options.shouldContinue && !options.shouldContinue()) { + return + } // Why: cwd fallback is only for fresh local spawns — reattach keeps the session's cwd and SSH transports resolve cwd on the remote host. const shouldSendLocalCwdFallback = cwdFallback === 'worktree' && !connectionId && !admittedSessionId diff --git a/src/renderer/src/components/terminal-pane/terminal-pty-pre-spawn-e2e-barrier.ts b/src/renderer/src/components/terminal-pane/terminal-pty-pre-spawn-e2e-barrier.ts new file mode 100644 index 00000000000..cc162e2ec91 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/terminal-pty-pre-spawn-e2e-barrier.ts @@ -0,0 +1,72 @@ +import { e2eConfig } from '@/lib/e2e-config' + +type BarrierState = { + blocked: boolean + release: () => void + released: Promise + reportBlocked: () => void + blockedReported: Promise +} + +export type TerminalPtyPreSpawnE2EBarrier = { + arm: () => void + waitUntilBlocked: () => Promise + release: () => void + status: () => 'idle' | 'armed' | 'blocked' +} + +let barrier: BarrierState | null = null + +function createBarrier(): BarrierState { + let release = (): void => {} + let reportBlocked = (): void => {} + const released = new Promise((resolve) => { + release = resolve + }) + const blockedReported = new Promise((resolve) => { + reportBlocked = resolve + }) + return { blocked: false, release, released, reportBlocked, blockedReported } +} + +function exposeBarrier(): void { + if (!e2eConfig.exposeStore || typeof window === 'undefined') { + return + } + window.__terminalPtyPreSpawnE2EBarrier ??= { + arm: () => { + if (barrier) { + throw new Error('Terminal PTY pre-spawn E2E barrier is already armed') + } + barrier = createBarrier() + }, + waitUntilBlocked: async () => { + if (!barrier) { + throw new Error('Terminal PTY pre-spawn E2E barrier is not armed') + } + await barrier.blockedReported + }, + release: () => { + barrier?.release() + }, + status: () => (barrier ? (barrier.blocked ? 'blocked' : 'armed') : 'idle') + } +} + +export function waitAtTerminalPtyPreSpawnE2EBarrier(): Promise | null { + if (!e2eConfig.exposeStore || typeof window === 'undefined') { + return null + } + exposeBarrier() + const current = barrier + if (!current || current.blocked) { + return null + } + current.blocked = true + current.reportBlocked() + return current.released.then(() => { + if (barrier === current) { + barrier = null + } + }) +} diff --git a/src/renderer/src/env.d.ts b/src/renderer/src/env.d.ts index e2ce09331d3..028ae6949f8 100644 --- a/src/renderer/src/env.d.ts +++ b/src/renderer/src/env.d.ts @@ -5,6 +5,7 @@ import type { OnboardingFeatureSetupDeps } from '@/components/onboarding/onboard import type { languages } from 'monaco-editor' import type { MonacoE2EProbe } from './components/editor/monaco-e2e-probe' import type { TerminalWorktreeParkingDebugVerdict } from './components/terminal-pane/terminal-parking-e2e-overrides' +import type { TerminalPtyPreSpawnE2EBarrier } from './components/terminal-pane/terminal-pty-pre-spawn-e2e-barrier' declare module 'monaco-editor/esm/vs/basic-languages/python/python.js' { export const conf: languages.LanguageConfiguration @@ -77,6 +78,7 @@ declare global { } __monacoEditorE2E?: MonacoE2EProbe __e2ePtyAppliedSizeReadDelayMs?: number + __terminalPtyPreSpawnE2EBarrier?: TerminalPtyPreSpawnE2EBarrier } } diff --git a/src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts b/src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts index 33a2fbce165..f4b28129251 100644 --- a/src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts +++ b/src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts @@ -28,6 +28,20 @@ describe('remountTerminalTabForRecovery', () => { expect(after?.pendingActivationSpawn).toBeTruthy() }) + it('gives a remounted pane a distinct queued startup owner', () => { + const store = createTestStore() + const tabId = seedWorktreeWithTab(store) + const startup = { command: 'echo recover' } + store.getState().queueTabStartupCommand(tabId, startup) + const before = store.getState().pendingStartupByTabId[tabId] + + expect(store.getState().remountTerminalTabForRecovery(tabId)).toBe(true) + + const after = store.getState().pendingStartupByTabId[tabId] + expect(after).toEqual(before) + expect(after).not.toBe(before) + }) + it('leaves sibling tabs untouched', () => { const store = createTestStore() const tabId = seedWorktreeWithTab(store) diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index 4e570420a11..49c2e7f00ed 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -649,6 +649,8 @@ export type TerminalSlice = { setTabBarOrder: (worktreeId: string, order: string[]) => void setActiveTab: (tabId: string) => void setActiveTabForWorktree: (worktreeId: string, tabId: string) => void + /** Resolve the canonical legacy terminal-tab owner key for renderer lifecycle guards. */ + getTerminalTabOwnerWorktreeId?: (tabId: string) => string | null updateTabTitle: (tabId: string, title: string) => void updateTabTitles: (updates: readonly TerminalTabTitleUpdate[]) => void setAiVaultTabTitle: (tabId: string, aiVaultTitle: AiVaultSessionTitle | null) => void @@ -1498,6 +1500,9 @@ export const createTerminalSlice: StateCreator return tab }, + getTerminalTabOwnerWorktreeId: (tabId) => + getTerminalTabOwnerWorktreeId(get().tabsByWorktree, tabId), + openNewTerminalTabInActiveWorkspace: async (groupId) => { const state = get() const worktreeId = state.activeWorktreeId diff --git a/src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts b/src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts index 112c4da1aff..f63712427c5 100644 --- a/src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts +++ b/src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts @@ -30,6 +30,7 @@ export function createRemountTerminalTabForRecovery( } const tab = tabs[index] const nextTabs = tabs.slice() + const pendingStartup = s.pendingStartupByTabId[tabId] nextTabs[index] = { ...tab, // Why: bump generation to remount a pane whose renderer died while its PTY stayed alive, so it reattaches, not spawns. @@ -44,7 +45,17 @@ export function createRemountTerminalTabForRecovery( tabsByWorktree: { ...s.tabsByWorktree, [worktreeId]: nextTabs - } + }, + ...(pendingStartup + ? { + // Why: a remounted pane must own a distinct one-shot startup record so a stale + // pane cannot consume the successor's command during teardown. + pendingStartupByTabId: { + ...s.pendingStartupByTabId, + [tabId]: { ...pendingStartup } + } + } + : {}) } } return {} diff --git a/tests/e2e/global-teardown.ts b/tests/e2e/global-teardown.ts index abb797878af..63248cd36c8 100644 --- a/tests/e2e/global-teardown.ts +++ b/tests/e2e/global-teardown.ts @@ -5,10 +5,48 @@ * test run so we don't litter the user's /tmp with test directories. */ -import { readFileSync, existsSync, rmSync, readdirSync } from 'node:fs' -import path from 'node:path' +import { execFileSync } from 'node:child_process' +import { readFileSync, existsSync, realpathSync, rmSync } from 'node:fs' import { TEST_REPO_PATH_FILE } from './global-setup' +export function linkedWorktreePaths(testRepoDir: string): string[] { + const root = realpathSync(testRepoDir) + const output = execFileSync('git', ['-C', testRepoDir, 'worktree', 'list', '--porcelain'], { + encoding: 'utf8' + }) + const linked = new Set() + for (const line of output.split(/\r?\n/)) { + if (!line.startsWith('worktree ')) { + continue + } + const recordedPath = line.slice('worktree '.length) + if (!existsSync(recordedPath)) { + continue + } + const canonicalPath = realpathSync(recordedPath) + if (canonicalPath !== root) { + linked.add(canonicalPath) + } + } + return [...linked] +} + +export function cleanupTestRepository(testRepoDir: string): void { + const root = realpathSync(testRepoDir) + let worktreePaths: string[] = [] + try { + worktreePaths = linkedWorktreePaths(root) + } catch { + // The isolated repo is still safe to remove when Git metadata is unreadable. + } + for (const worktreeDir of worktreePaths) { + if (existsSync(worktreeDir)) { + rmSync(worktreeDir, { recursive: true, force: true }) + } + } + rmSync(root, { recursive: true, force: true }) +} + export default function globalTeardown(): void { if (!existsSync(TEST_REPO_PATH_FILE)) { return @@ -16,22 +54,7 @@ export default function globalTeardown(): void { const testRepoDir = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() if (testRepoDir && existsSync(testRepoDir)) { - // Why: git worktree add creates directories as siblings. Clean up any - // seeded or test-created worktrees in the same parent so reruns remain - // idempotent and do not leak temp repos into /tmp. - const parentDir = path.dirname(testRepoDir) - try { - const siblings = readdirSync(parentDir) - for (const name of siblings) { - if (name.startsWith('orca-e2e-worktree-') || name.startsWith('e2e-test-')) { - rmSync(path.join(parentDir, name), { recursive: true, force: true }) - } - } - } catch { - // Best-effort cleanup of worktrees - } - - rmSync(testRepoDir, { recursive: true, force: true }) + cleanupTestRepository(testRepoDir) console.error(`[e2e] Cleaned up test repo at ${testRepoDir}`) } diff --git a/tests/e2e/global-teardown.unit.test.ts b/tests/e2e/global-teardown.unit.test.ts new file mode 100644 index 00000000000..b5fabfe3de8 --- /dev/null +++ b/tests/e2e/global-teardown.unit.test.ts @@ -0,0 +1,52 @@ +import { execFileSync } from 'node:child_process' +import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { cleanupTestRepository, linkedWorktreePaths } from './global-teardown' + +const roots: string[] = [] + +function git(cwd: string, args: string[]): void { + execFileSync('git', ['-C', cwd, ...args], { stdio: 'pipe' }) +} + +afterEach(() => { + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }) + } +}) + +describe('E2E global teardown ownership', () => { + it('removes every linked run worktree and preserves unrelated siblings', () => { + const root = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-teardown-contract-')) + roots.push(root) + const repoPath = path.join(root, 'orca-e2e-repo-run') + const firstWorktreePath = path.join(root, 'orca-e2e-worktree-owned') + const secondWorktreePath = path.join(root, 'e2e-test-owned') + const concurrentWorktreePath = path.join(root, 'orca-e2e-worktree-concurrent') + const unrelatedTestPath = path.join(root, 'e2e-test-unrelated') + mkdirSync(repoPath) + mkdirSync(concurrentWorktreePath) + mkdirSync(unrelatedTestPath) + writeFileSync(path.join(repoPath, 'README.md'), 'fixture\n') + git(repoPath, ['init']) + git(repoPath, ['config', 'user.email', 'e2e@test.local']) + git(repoPath, ['config', 'user.name', 'E2E Test']) + git(repoPath, ['add', 'README.md']) + git(repoPath, ['commit', '-m', 'seed']) + git(repoPath, ['worktree', 'add', '-b', 'first-owned', firstWorktreePath]) + git(repoPath, ['worktree', 'add', '-b', 'second-owned', secondWorktreePath]) + + expect(new Set(linkedWorktreePaths(repoPath))).toEqual( + new Set([realpathSync(firstWorktreePath), realpathSync(secondWorktreePath)]) + ) + cleanupTestRepository(repoPath) + + expect(existsSync(repoPath)).toBe(false) + expect(existsSync(firstWorktreePath)).toBe(false) + expect(existsSync(secondWorktreePath)).toBe(false) + expect(existsSync(concurrentWorktreePath)).toBe(true) + expect(existsSync(unrelatedTestPath)).toBe(true) + }) +}) diff --git a/tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts b/tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts new file mode 100644 index 00000000000..c734301d33f --- /dev/null +++ b/tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts @@ -0,0 +1,349 @@ +import { randomUUID } from 'node:crypto' +import { existsSync, readFileSync, rmSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { stripAnsiEscapeSequences } from '../../src/shared/ansi-escape-sequences' +import { test, expect } from './helpers/orca-app' +import { + runNodeScriptInTerminal, + stageNodeScriptForTerminal +} from './helpers/run-node-script-in-terminal' +import { registerTerminalPaneMountReadiness } from './helpers/terminal-pane-mount-readiness' +import { + focusActiveTerminalInput, + getTerminalContent, + waitForPaneIdentitySnapshot, + waitForTerminalOutput +} from './helpers/terminal' + +type QuickCommandIdentity = { + marker: string + paneKey: string + pid: number + tabId: string +} + +type QueueObservation = { + pending: boolean + ptyIds: string[] +} + +type QueueObservationWindow = Window & { + __quickCommandQueueObservations?: QueueObservation[] + __stopQuickCommandQueueObservations?: () => void +} + +function exactMarkerLineCount(content: string, marker: string): number { + return stripAnsiEscapeSequences(content) + .split(/\r?\n/) + .map((line) => line.trim()) + .filter((line) => line === marker).length +} + +test.describe('Quick Command startup recovery', () => { + registerTerminalPaneMountReadiness() + + test('visible Quick Command survives a forced pre-bind recovery on one fresh PTY', async ({ + orcaPage + }) => { + const siblingBefore = await waitForPaneIdentitySnapshot(orcaPage, 1) + const siblingPtyId = siblingBefore.panes[0]?.ptyId + if (!siblingPtyId) { + throw new Error('Sibling terminal has no live PTY') + } + + const siblingMarker = `ORCA_QUICK_COMMAND_SIBLING_${randomUUID()}` + const siblingProbe = await runNodeScriptInTerminal( + orcaPage, + siblingPtyId, + `process.stdout.write(${JSON.stringify(`${siblingMarker}\n`)})` + ) + await waitForTerminalOutput(orcaPage, siblingMarker) + siblingProbe.cleanup() + + const marker = `ORCA_QUICK_COMMAND_RECOVERY_${randomUUID()}` + const label = `Recovery sentinel ${randomUUID()}` + const identityPath = path.join(os.tmpdir(), `orca-quick-command-identity-${randomUUID()}.json`) + const staged = stageNodeScriptForTerminal( + ` +const { writeFileSync } = require('node:fs') +const identity = { + marker: ${JSON.stringify(marker)}, + paneKey: process.env.ORCA_PANE_KEY || '', + pid: process.pid, + tabId: process.env.ORCA_TAB_ID || '' +} +writeFileSync(${JSON.stringify(identityPath)}, JSON.stringify(identity), { flag: 'wx' }) +process.stdout.write(${JSON.stringify(`${marker}\n`)}) +`.trim() + ) + + try { + await orcaPage.evaluate( + async ({ command, label }) => { + const store = window.__store + if (!store) { + throw new Error('Renderer store unavailable') + } + await store.getState().updateSettings({ + terminalQuickCommands: [ + { + id: 'e2e-pre-bind-recovery', + label, + scope: { type: 'global' }, + action: 'terminal-command', + command, + appendEnter: true + } + ] + }) + const spawnBarrier = window.__terminalPtyPreSpawnE2EBarrier + if (!spawnBarrier) { + throw new Error('Terminal PTY pre-spawn E2E barrier unavailable') + } + spawnBarrier.arm() + }, + { command: staged.command, label } + ) + + const quickCommandButton = orcaPage.getByRole('button', { + name: `Run quick command: ${label}` + }) + await expect(quickCommandButton).toBeVisible() + await quickCommandButton.click() + await orcaPage.evaluate(async () => { + const spawnBarrier = window.__terminalPtyPreSpawnE2EBarrier + if (!spawnBarrier) { + throw new Error('Terminal PTY pre-spawn E2E barrier unavailable') + } + await spawnBarrier.waitUntilBlocked() + }) + + const blocked = await orcaPage.evaluate(() => { + const store = window.__store + if (!store) { + throw new Error('Renderer store unavailable') + } + const state = store.getState() + const tabId = state.activeTabId + if (!tabId) { + throw new Error('Quick Command did not create an active tab') + } + return { + generation: + state.tabsByWorktree[state.activeWorktreeId ?? '']?.find((tab) => tab.id === tabId) + ?.generation ?? 0, + pending: state.pendingStartupByTabId[tabId]?.command ?? null, + status: window.__terminalPtyPreSpawnE2EBarrier?.status(), + tabId + } + }) + expect(blocked.pending).toBe(staged.command) + expect(blocked.status).toBe('blocked') + + await orcaPage.evaluate((tabId) => { + const store = window.__store + if (!store) { + throw new Error('Renderer store unavailable') + } + const target = window as QueueObservationWindow + const observations: QueueObservation[] = [] + const observe = (): void => { + const state = store.getState() + observations.push({ + pending: state.pendingStartupByTabId[tabId] !== undefined, + ptyIds: [...(state.ptyIdsByTabId[tabId] ?? [])] + }) + } + target.__quickCommandQueueObservations = observations + target.__stopQuickCommandQueueObservations = store.subscribe(observe) + observe() + }, blocked.tabId) + + const remounted = await orcaPage.evaluate((tabId) => { + const state = window.__store?.getState() + if (!state) { + throw new Error('Renderer store unavailable') + } + return state.remountTerminalTabForRecovery(tabId) + }, blocked.tabId) + expect(remounted).toBe(true) + + // Keep the original pre-spawn attempt gated until React has committed the + // successor pane. Releasing earlier lets a loaded CI renderer finish the + // old mount's teardown before the replacement reaches its connect path. + await expect + .poll( + () => + orcaPage.evaluate( + ({ expectedGeneration, tabId }) => { + const state = window.__store?.getState() + const manager = window.__paneManagers?.get(tabId) + const pane = manager?.getPanes()[0] + const tab = state?.tabsByWorktree[state.activeWorktreeId ?? '']?.find( + (candidate) => candidate.id === tabId + ) + return { + generation: tab?.generation ?? 0, + leafReady: Boolean(pane?.leafId), + pending: state?.pendingStartupByTabId[tabId]?.command ?? null, + expectedGeneration + } + }, + { expectedGeneration: blocked.generation + 1, tabId: blocked.tabId } + ), + { message: 'Successor mount did not become ready before barrier release' } + ) + .toEqual({ + generation: blocked.generation + 1, + leafReady: true, + pending: staged.command, + expectedGeneration: blocked.generation + 1 + }) + await orcaPage.evaluate(() => window.__terminalPtyPreSpawnE2EBarrier?.release()) + + let targetPtyId = '' + let targetLeafId = '' + const successorReady = (): Promise<{ + generation: number + leafReady: boolean + pending: string | null + ptyReady: boolean + expectedGeneration: number + }> => + orcaPage.evaluate( + ({ expectedGeneration, tabId }) => { + const state = window.__store?.getState() + const manager = window.__paneManagers?.get(tabId) + const pane = manager?.getPanes()[0] + const tab = state?.tabsByWorktree[state.activeWorktreeId ?? '']?.find( + (candidate) => candidate.id === tabId + ) + return { + generation: tab?.generation ?? 0, + leafReady: Boolean(pane?.leafId), + pending: state?.pendingStartupByTabId[tabId]?.command ?? null, + ptyReady: Boolean(pane?.container.dataset.ptyId), + expectedGeneration + } + }, + { expectedGeneration: blocked.generation + 1, tabId: blocked.tabId } + ) + try { + await expect + .poll(successorReady, { + timeout: 60_000, + message: 'Successor mount did not bind its fresh Quick Command PTY' + }) + .toEqual({ + generation: blocked.generation + 1, + leafReady: true, + pending: null, + ptyReady: true, + expectedGeneration: blocked.generation + 1 + }) + } catch (error) { + const diagnostics = await orcaPage.evaluate(() => ({ + ptyConnect: (window as Window & { __ptyConnectDiag?: string[] }).__ptyConnectDiag ?? [], + barrier: window.__terminalPtyPreSpawnE2EBarrier?.status() ?? 'missing' + })) + throw new Error( + `${error instanceof Error ? error.message : String(error)}\nDiagnostics: ${JSON.stringify(diagnostics)}` + ) + } + + const successor = await orcaPage.evaluate((tabId) => { + const pane = window.__paneManagers?.get(tabId)?.getPanes()[0] + return { + leafId: pane?.leafId ?? '', + ptyId: pane?.container.dataset.ptyId ?? '' + } + }, blocked.tabId) + targetPtyId = successor.ptyId + targetLeafId = successor.leafId + expect(targetPtyId).not.toBe('') + expect(targetLeafId).not.toBe('') + expect(targetPtyId).not.toBe(siblingPtyId) + + const queueObservations = await orcaPage.evaluate(() => { + const target = window as QueueObservationWindow + target.__stopQuickCommandQueueObservations?.() + target.__stopQuickCommandQueueObservations = undefined + return target.__quickCommandQueueObservations ?? [] + }) + const firstConsumed = queueObservations.find((observation) => !observation.pending) + expect(firstConsumed?.ptyIds).toContain(targetPtyId) + + await expect + .poll( + () => + orcaPage.evaluate((tabId) => { + const pane = window.__paneManagers?.get(tabId)?.getPanes()[0] + return pane?.serializeAddon.serialize() ?? '' + }, blocked.tabId), + { message: 'Quick Command marker never reached the visible xterm' } + ) + .toContain(marker) + const targetContent = await orcaPage.evaluate((tabId) => { + const pane = window.__paneManagers?.get(tabId)?.getPanes()[0] + return pane?.serializeAddon.serialize() ?? '' + }, blocked.tabId) + expect(exactMarkerLineCount(targetContent, marker)).toBe(1) + + await expect.poll(() => existsSync(identityPath)).toBe(true) + const identity = JSON.parse(readFileSync(identityPath, 'utf8')) as QuickCommandIdentity + expect(identity).toMatchObject({ + marker, + paneKey: `${blocked.tabId}:${targetLeafId}`, + tabId: blocked.tabId + }) + expect(identity.pid).toBeGreaterThan(0) + + const ptyIdentity = await orcaPage.evaluate( + async ({ siblingPtyId, siblingTabId, tabId, targetPtyId }) => { + const state = window.__store?.getState() + const layout = state?.terminalLayoutsByTabId[tabId] + const sessions = await window.api.pty.listSessions() + return { + layoutPtyIds: Object.values(layout?.ptyIdsByLeafId ?? {}), + siblingLive: await window.api.pty.hasPty(siblingPtyId), + siblingStorePtyIds: state?.ptyIdsByTabId[siblingTabId] ?? [], + targetLive: await window.api.pty.hasPty(targetPtyId), + targetSessionIds: sessions + .filter((session) => session.id === targetPtyId) + .map((session) => session.id), + targetStorePtyIds: state?.ptyIdsByTabId[tabId] ?? [] + } + }, + { siblingPtyId, siblingTabId: siblingBefore.tabId, tabId: blocked.tabId, targetPtyId } + ) + expect(ptyIdentity.targetLive).toBe(true) + expect(ptyIdentity.targetSessionIds).toEqual([targetPtyId]) + expect(ptyIdentity.targetStorePtyIds).toContain(targetPtyId) + expect(ptyIdentity.layoutPtyIds).toContain(targetPtyId) + expect(ptyIdentity.siblingLive).toBe(true) + expect(ptyIdentity.siblingStorePtyIds).toContain(siblingPtyId) + + const siblingAfterMarker = `ORCA_QUICK_COMMAND_SIBLING_AFTER_${randomUUID()}` + await orcaPage.evaluate( + (tabId) => window.__store?.getState().setActiveTab(tabId), + siblingBefore.tabId + ) + await expect + .poll(() => orcaPage.evaluate(() => window.__store?.getState().activeTabId)) + .toBe(siblingBefore.tabId) + await focusActiveTerminalInput(orcaPage) + await orcaPage.keyboard.type(`echo ${siblingAfterMarker}`) + await orcaPage.keyboard.press('Enter') + await expect + .poll(async () => (await getTerminalContent(orcaPage)).split(siblingAfterMarker).length - 1) + .toBeGreaterThanOrEqual(1) + } finally { + await orcaPage + .evaluate(() => window.__terminalPtyPreSpawnE2EBarrier?.release()) + .catch(() => {}) + staged.cleanup() + rmSync(identityPath, { force: true }) + } + }) +}) diff --git a/tests/tools/windows-pty-native-capability-smoke/README.md b/tests/tools/windows-pty-native-capability-smoke/README.md new file mode 100644 index 00000000000..fa18f434687 --- /dev/null +++ b/tests/tools/windows-pty-native-capability-smoke/README.md @@ -0,0 +1,16 @@ +# Packaged Windows PTY native capability smoke + +This narrow harness runs the packaged `Orca.exe` with `ELECTRON_RUN_AS_NODE=1` and loads its bundled `node-pty`. Checkout Node processes provide the target/canary shell fixtures, so the smoke proves the packaged native addon without putting a GUI-subsystem Electron executable under ConPTY. A 256-bit fixture token binds the target shell, a grandchild that remains live after its intermediate launcher exits, and an unrelated canary to one unique named-pipe channel; the oracle checks the patched exports, job PIDs, exact job-handle termination, PTY/socket exit events, and canary survival. + +Run it against an unpacked Windows package: + +```text +pnpm run smoke:windows-pty-native-capability -- --exe=dist/win-unpacked/Orca.exe +``` + +The official `v1.4.158` package is the causal red artifact: it fails immediately because its +packaged `node-pty` lacks `assignCurrentProcessToJob`. Candidate green evidence comes from the +required Windows packaging job, which runs this smoke without retries. The one-shot probe flushes +its evidence and exits explicitly because direct native job termination intentionally bypasses +node-pty's ConPTY-worker disposal path; a 45-second outer ceiling reports bounded stdout, stderr, +and native-stage breadcrumbs if any boundary stops progressing. diff --git a/tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-oracle.mjs b/tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-oracle.mjs new file mode 100644 index 00000000000..d311bf24f28 --- /dev/null +++ b/tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-oracle.mjs @@ -0,0 +1,139 @@ +const REQUIRED_EXPORTS = ['assignCurrentProcessToJob', 'listJobProcessIds', 'terminateJob'] +const FIXTURE_TOKEN_PATTERN = /^[a-f0-9]{64}$/ + +function isFixtureObservation(value, expected) { + return ( + Number.isInteger(value?.pid) && + value.pid > 0 && + value.fixtureToken === expected.fixtureToken && + value.channel === expected.channel && + value.role === expected.role + ) +} + +function isFixtureClosure(value, expected) { + return ( + value?.fixtureToken === expected.fixtureToken && + value.channel === expected.channel && + value.role === expected.role + ) +} + +function isPtyExit(value, terminalHandle) { + return value?.terminalHandle === terminalHandle && Number.isInteger(value.exitCode) +} + +export function evaluatePackagedNodePtyCapability(evidence) { + const failures = [] + const exports = new Set(evidence?.patchedExports ?? []) + const fixtureToken = evidence?.fixtureToken + const channel = evidence?.channel + const target = evidence?.target + const canary = evidence?.canary + + if (REQUIRED_EXPORTS.some((name) => !exports.has(name))) { + failures.push('the packaged node-pty addon is missing a required patched export') + } + if (!FIXTURE_TOKEN_PATTERN.test(fixtureToken) || !channel?.includes(fixtureToken)) { + failures.push('the fixture channel is not bound to the per-run unguessable token') + } + if (!isFixtureObservation(target?.shell, { fixtureToken, channel, role: 'target-shell' })) { + failures.push('the target shell was not observed on its unique fixture channel') + } + if ( + !isFixtureObservation(target?.launcherExited, { + fixtureToken, + channel, + role: 'target-launcher-exited' + }) + ) { + failures.push('the transient launcher exit was not observed') + } + if ( + !isFixtureObservation(target?.grandchild, { + fixtureToken, + channel, + role: 'target-grandchild' + }) + ) { + failures.push('the grandchild was not observed after its launcher exited') + } + if (!isFixtureObservation(canary?.process, { fixtureToken, channel, role: 'canary-shell' })) { + failures.push('the unrelated canary was not observed on its unique fixture channel') + } + const observedPids = [ + target?.shell?.pid, + target?.launcherExited?.pid, + target?.grandchild?.pid, + canary?.process?.pid + ] + if (observedPids.every((pid) => Number.isInteger(pid)) && new Set(observedPids).size !== 4) { + failures.push('target shell, launcher, grandchild, and canary must be distinct processes') + } + + if (!Array.isArray(target?.jobProcessIds) || target.jobProcessIds.length === 0) { + failures.push('the target job membership must be available and nonempty') + } else if (!target.jobProcessIds.includes(target?.shell?.pid)) { + failures.push('the target job does not contain the observed shell PID') + } else if (!target.jobProcessIds.includes(target?.grandchild?.pid)) { + failures.push('the target job does not contain the observed grandchild PID') + } else if (target.jobProcessIds.includes(target?.launcherExited?.pid)) { + failures.push('the transient launcher is still live in the target job') + } + const close = evidence?.close + if ( + close?.method !== 'terminate-job' || + close?.requestedHandle !== target?.terminalHandle || + close?.completedHandle !== target?.terminalHandle + ) { + failures.push('close must complete for the one requested PTY job handle') + } + if ( + !isPtyExit(close?.targetExit, target?.terminalHandle) || + !isFixtureClosure(close?.targetShellClosed, { + fixtureToken, + channel, + role: 'target-shell' + }) || + !isFixtureClosure(close?.targetGrandchildClosed, { + fixtureToken, + channel, + role: 'target-grandchild' + }) + ) { + failures.push('target close did not complete from PTY and fixture socket exit events') + } + + if (canary?.connectedAfterTargetClose !== true) { + failures.push('the unrelated canary fixture connection was lost during target close') + } + if ( + !Array.isArray(canary?.jobProcessIdsAfterTargetClose) || + !canary.jobProcessIdsAfterTargetClose.includes(canary?.process?.pid) + ) { + failures.push('the unrelated canary PID is not live in its job after target close') + } + if (!isPtyExit(canary?.exit, canary?.terminalHandle)) { + failures.push('the unrelated canary PTY exit was not observed') + } + if ( + !isFixtureClosure(canary?.socketClosed, { + fixtureToken, + channel, + role: 'canary-shell' + }) + ) { + failures.push('the unrelated canary did not complete its later exact teardown') + } + + return { pass: failures.length === 0, failures } +} + +export function assertPackagedNodePtyCapability(evidence) { + const result = evaluatePackagedNodePtyCapability(evidence) + if (!result.pass) { + throw new Error( + `Packaged node-pty native capability failed:\n- ${result.failures.join('\n- ')}` + ) + } +} diff --git a/tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-oracle.test.mjs b/tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-oracle.test.mjs new file mode 100644 index 00000000000..a752c6f499d --- /dev/null +++ b/tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-oracle.test.mjs @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'vitest' +import { evaluatePackagedNodePtyCapability } from './packaged-node-pty-capability-oracle.mjs' + +const fixtureToken = 'a'.repeat(64) +const channel = `\\\\.\\pipe\\orca-pty-native-capability-${fixtureToken}` + +function observation(pid, role) { + return { pid, fixtureToken, role, channel } +} + +function closure(role) { + return { fixtureToken, role, channel } +} + +function passingEvidence() { + const shell = observation(4100, 'target-shell') + const launcherExited = observation(4101, 'target-launcher-exited') + const grandchild = observation(4102, 'target-grandchild') + const canary = observation(5100, 'canary-shell') + return { + patchedExports: ['assignCurrentProcessToJob', 'listJobProcessIds', 'terminateJob'], + fixtureToken, + channel, + target: { + terminalHandle: 'pty-job:7:4100', + shell, + launcherExited, + grandchild, + jobProcessIds: [shell.pid, grandchild.pid] + }, + canary: { + terminalHandle: 'pty-job:8:5100', + process: canary, + connectedAfterTargetClose: true, + jobProcessIdsAfterTargetClose: [canary.pid], + exit: { terminalHandle: 'pty-job:8:5100', exitCode: 1, signal: 0 }, + socketClosed: closure('canary-shell') + }, + close: { + method: 'terminate-job', + requestedHandle: 'pty-job:7:4100', + completedHandle: 'pty-job:7:4100', + targetExit: { terminalHandle: 'pty-job:7:4100', exitCode: 1, signal: 0 }, + targetShellClosed: closure('target-shell'), + targetGrandchildClosed: closure('target-grandchild') + } + } +} + +describe('packaged node-pty native capability oracle', () => { + it('accepts exact target teardown while the unrelated canary remains live', () => { + expect(evaluatePackagedNodePtyCapability(passingEvidence())).toEqual({ + pass: true, + failures: [] + }) + }) + + it.each([ + ['missing patched export', (evidence) => evidence.patchedExports.pop()], + ['launcher exit absent', (evidence) => delete evidence.target.launcherExited], + ['empty job membership', (evidence) => (evidence.target.jobProcessIds = [])], + [ + 'target shell outside membership', + (evidence) => (evidence.target.jobProcessIds = [evidence.target.grandchild.pid]) + ], + [ + 'launcher-surviving grandchild outside membership', + (evidence) => (evidence.target.jobProcessIds = [evidence.target.shell.pid]) + ], + ['target exit absent', (evidence) => delete evidence.close.targetExit], + ['canary connection loss', (evidence) => (evidence.canary.connectedAfterTargetClose = false)] + ])('rejects %s', (_name, mutate) => { + const evidence = passingEvidence() + mutate(evidence) + + expect(evaluatePackagedNodePtyCapability(evidence).pass).toBe(false) + }) + + it.each([ + ['guessable token', (evidence) => (evidence.fixtureToken = 'run-1')], + [ + 'grandchild from another channel', + (evidence) => (evidence.target.grandchild.channel = '\\\\.\\pipe\\other') + ], + ['wrong completed handle', (evidence) => (evidence.close.completedHandle = 'pty-job:9:9999')], + [ + 'launcher still in target job', + (evidence) => evidence.target.jobProcessIds.push(evidence.target.launcherExited.pid) + ], + ['canary outside its job', (evidence) => (evidence.canary.jobProcessIdsAfterTargetClose = [])], + ['canary teardown absent', (evidence) => delete evidence.canary.socketClosed] + ])('rejects scope violation: %s', (_name, mutate) => { + const evidence = passingEvidence() + mutate(evidence) + + expect(evaluatePackagedNodePtyCapability(evidence).pass).toBe(false) + }) +}) diff --git a/tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-probe.cjs b/tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-probe.cjs new file mode 100644 index 00000000000..580a2852a19 --- /dev/null +++ b/tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-probe.cjs @@ -0,0 +1,448 @@ +const { randomBytes } = require('node:crypto') +const { writeSync } = require('node:fs') +const net = require('node:net') +const path = require('node:path') + +const EVIDENCE_PREFIX = 'ORCA_NODE_PTY_CAPABILITY_EVIDENCE=' +const EXPECTED_ROLES = new Set([ + 'target-shell', + 'target-launcher-exited', + 'target-grandchild', + 'canary-shell' +]) +const ONE_SHOT_MODES = new Set(['--exercise', '--exit-contract-fixture']) + +function isOneShotMode(mode) { + return ONE_SHOT_MODES.has(mode) +} + +function stage(name) { + writeSync(2, `[windows-pty-native-capability-smoke] stage=${name}\n`) +} + +function writeStream(stream, value = '') { + return new Promise((resolve, reject) => { + stream.write(value, (error) => (error ? reject(error) : resolve())) + }) +} + +async function exitOneShot(code, exit = process.exit) { + await Promise.all([writeStream(process.stdout), writeStream(process.stderr)]) + exit(code) +} + +function fixtureObservation(fixtureToken, role, channel, extra = {}) { + return { pid: process.pid, fixtureToken, role, channel, ...extra } +} + +function connectFixture(channel, fixtureToken, role, extra = {}) { + const socket = net.createConnection(channel) + socket.once('connect', () => { + socket.write(`${JSON.stringify(fixtureObservation(fixtureToken, role, channel, extra))}\n`) + }) + socket.on('error', (error) => { + process.stderr.write(`${error.stack || error.message}\n`) + process.exitCode = 1 + }) + return socket +} + +function reportFixtureObservation(channel, fixtureToken, role, extra = {}) { + return new Promise((resolve, reject) => { + const socket = net.createConnection(channel) + socket.once('connect', () => { + socket.end(`${JSON.stringify(fixtureObservation(fixtureToken, role, channel, extra))}\n`) + }) + socket.once('error', reject) + socket.once('close', resolve) + }) +} + +function buildGrandchildLaunch(channel, fixtureToken) { + return { + program: path.join(process.env.SystemRoot, 'System32', 'wscript.exe'), + args: [ + path.join(__dirname, 'real-orca-detached-launcher.vbs'), + process.execPath, + __filename, + '--grandchild-member', + channel, + fixtureToken, + 'target-grandchild' + ] + } +} + +function startGrandchildAfterLauncherExit(channel, fixtureToken, resourcesDir) { + const { spawnProcess } = require( + path.join(resourcesDir, 'app.asar.unpacked', 'out', 'shared', 'child-process', 'run-process.js') + ) + const launch = buildGrandchildLaunch(channel, fixtureToken) + const child = spawnProcess({ + ...launch, + env: process.env + }) + for (const stream of [child.stdin, child.stdout, child.stderr]) { + stream?.on('error', () => {}) + } + child.stdin?.end() + return new Promise((resolve, reject) => { + child.once('error', reject) + child.once('exit', (code) => { + if (code !== 0) { + reject(new Error(`grandchild launcher exited ${code}`)) + return + } + reportFixtureObservation(channel, fixtureToken, 'target-launcher-exited', { + pid: child.pid + }).then(() => resolve(child.pid), reject) + }) + }) +} + +async function runPtyShell(channel, fixtureToken, role, resourcesDir) { + const socket = connectFixture(channel, fixtureToken, `${role}-shell`) + try { + if (role === 'target') { + await startGrandchildAfterLauncherExit(channel, fixtureToken, resourcesDir) + } + } catch (error) { + socket.destroy() + throw error + } +} + +function createFixtureServer(channel, fixtureToken) { + const pending = new Map() + const observations = new Map() + const sockets = new Map() + const closures = new Map() + const acceptedSockets = new Set() + let serverClosed = false + + function closureFor(role) { + const existing = closures.get(role) + if (existing) { + return existing + } + let resolve + const promise = new Promise((done) => { + resolve = done + }) + const closure = { promise, resolve } + closures.set(role, closure) + return closure + } + + function waitForRole(role) { + const existing = observations.get(role) + if (existing) { + return Promise.resolve(existing) + } + return new Promise((resolve) => pending.set(role, resolve)) + } + + const server = net.createServer((socket) => { + let input = '' + acceptedSockets.add(socket) + socket.once('close', () => acceptedSockets.delete(socket)) + socket.setEncoding('utf8') + socket.on('data', (chunk) => { + input += String(chunk) + const newline = input.indexOf('\n') + if (newline === -1) { + return + } + const observation = JSON.parse(input.slice(0, newline)) + if ( + observation.fixtureToken !== fixtureToken || + observation.channel !== channel || + !EXPECTED_ROLES.has(observation.role) + ) { + throw new Error('fixture observation did not match its unique token, channel, and role') + } + observations.set(observation.role, observation) + sockets.set(observation.role, socket) + pending.get(observation.role)?.(observation) + pending.delete(observation.role) + socket.once('close', () => { + closureFor(observation.role).resolve({ + fixtureToken, + channel, + role: observation.role + }) + }) + }) + }) + + const listening = new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(channel, resolve) + }) + const close = () => { + if (serverClosed) { + return Promise.resolve() + } + serverClosed = true + return new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())) + }) + } + + return { + listening, + waitForRole, + waitForClose: (role) => closureFor(role).promise, + sockets, + destroySockets: () => { + for (const socket of acceptedSockets) { + socket.destroy() + } + server.closeAllConnections?.() + server.unref() + }, + close + } +} + +function terminalHandle(pty) { + return `pty-job:${pty._pty}:${pty.pid}` +} + +function exitEvent(pty) { + const handle = terminalHandle(pty) + return new Promise((resolve) => + pty.onExit((event) => resolve({ terminalHandle: handle, ...event })) + ) +} + +function waitForBarrier(promise, label, timeoutMs = 30_000) { + let timer + const deadline = new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), + timeoutMs + ) + }) + return Promise.race([promise, deadline]).finally(() => clearTimeout(timer)) +} + +async function exercise(resourcesDir, fixtureExecutable) { + const nodePtyDir = path.join(resourcesDir, 'node_modules', 'node-pty') + stage('addon-load:start') + const nodePty = require(nodePtyDir) + const { module: native } = require(path.join(nodePtyDir, 'lib', 'utils.js')).loadNativeModule( + 'conpty' + ) + stage('addon-load:done') + const patchedExports = ['assignCurrentProcessToJob', 'listJobProcessIds', 'terminateJob'] + for (const name of patchedExports) { + if (typeof native[name] !== 'function') { + throw new Error(`packaged node-pty is missing ${name}`) + } + } + stage('host-job-assign:start') + const hostJobAssigned = native.assignCurrentProcessToJob() + stage('host-job-assign:done') + if (!hostJobAssigned) { + throw new Error('packaged probe could not establish host job ownership') + } + + const fixtureToken = randomBytes(32).toString('hex') + const channel = `\\\\.\\pipe\\orca-pty-native-capability-${fixtureToken}` + const fixtures = createFixtureServer(channel, fixtureToken) + stage('fixture-listen:start') + await waitForBarrier(fixtures.listening, 'fixture server listen') + stage('fixture-listen:done') + const options = { + name: 'xterm-256color', + cols: 80, + rows: 30, + cwd: process.cwd(), + env: process.env, + useConptyDll: true + } + const created = [] + const closed = new Set() + const exitPromises = [] + let completed = false + + try { + stage('target-spawn:start') + const target = nodePty.spawn( + fixtureExecutable, + [__filename, '--pty-shell', channel, fixtureToken, 'target', resourcesDir], + options + ) + stage('target-spawn:done') + created.push(target) + const targetExited = exitEvent(target) + exitPromises.push(targetExited) + stage('canary-spawn:start') + const canary = nodePty.spawn( + fixtureExecutable, + [__filename, '--pty-shell', channel, fixtureToken, 'canary', resourcesDir], + options + ) + stage('canary-spawn:done') + created.push(canary) + const canaryHandle = terminalHandle(canary) + const canaryExited = exitEvent(canary) + exitPromises.push(canaryExited) + + stage('fixture-readiness:start') + const [shell, launcherExited, grandchild, canaryProcess] = await Promise.all([ + waitForBarrier(fixtures.waitForRole('target-shell'), 'target shell readiness'), + waitForBarrier(fixtures.waitForRole('target-launcher-exited'), 'grandchild launcher exit'), + waitForBarrier(fixtures.waitForRole('target-grandchild'), 'target grandchild readiness'), + waitForBarrier(fixtures.waitForRole('canary-shell'), 'canary shell readiness') + ]) + stage('fixture-readiness:done') + stage('target-job-list:start') + const targetJobProcessIds = native.listJobProcessIds(target._pty, target.pid) + stage('target-job-list:done') + const targetHandle = terminalHandle(target) + stage('target-job-terminate:start') + const targetTerminated = native.terminateJob(target._pty, target.pid) + stage('target-job-terminate:done') + if (!targetTerminated) { + throw new Error('exact target job termination was refused') + } + closed.add(target) + stage('target-exit-barriers:start') + const [targetExit, targetShellClosed, targetGrandchildClosed] = await Promise.all([ + waitForBarrier(targetExited, 'target PTY exit'), + waitForBarrier(fixtures.waitForClose('target-shell'), 'target shell connection close'), + waitForBarrier( + fixtures.waitForClose('target-grandchild'), + 'target grandchild connection close' + ) + ]) + stage('target-exit-barriers:done') + + stage('canary-job-list:start') + const canaryJobProcessIdsAfterTargetClose = native.listJobProcessIds(canary._pty, canary.pid) + stage('canary-job-list:done') + const canarySocket = fixtures.sockets.get('canary-shell') + const connectedAfterTargetClose = Boolean(canarySocket && !canarySocket.destroyed) + stage('canary-job-terminate:start') + const canaryTerminated = native.terminateJob(canary._pty, canary.pid) + stage('canary-job-terminate:done') + if (!canaryTerminated) { + throw new Error('exact canary job termination was refused') + } + closed.add(canary) + stage('canary-exit-barriers:start') + const [canaryExit, canaryClosed] = await Promise.all([ + waitForBarrier(canaryExited, 'canary PTY exit'), + waitForBarrier(fixtures.waitForClose('canary-shell'), 'canary shell connection close') + ]) + stage('canary-exit-barriers:done') + + const evidence = { + patchedExports, + fixtureToken, + channel, + target: { + terminalHandle: targetHandle, + shell, + launcherExited, + grandchild, + jobProcessIds: targetJobProcessIds + }, + canary: { + terminalHandle: canaryHandle, + process: canaryProcess, + connectedAfterTargetClose, + jobProcessIdsAfterTargetClose: canaryJobProcessIdsAfterTargetClose, + exit: canaryExit, + socketClosed: canaryClosed + }, + close: { + method: 'terminate-job', + requestedHandle: targetHandle, + completedHandle: targetHandle, + targetExit, + targetShellClosed, + targetGrandchildClosed + } + } + stage('fixture-close:start') + await waitForBarrier(fixtures.close(), 'fixture server close') + stage('fixture-close:done') + await writeStream(process.stdout, `${EVIDENCE_PREFIX}${JSON.stringify(evidence)}\n`) + stage('evidence:flushed') + completed = true + } catch (error) { + process.stderr.write(`[windows-pty-native-capability-smoke] ${error.message}\n`) + throw error + } finally { + for (const pty of created) { + if (!closed.has(pty)) { + stage('cleanup-job-terminate:start') + native.terminateJob(pty._pty, pty.pid) + stage('cleanup-job-terminate:done') + } + } + if (!completed) { + await Promise.allSettled( + exitPromises.map((exit) => waitForBarrier(exit, 'cleanup PTY exit', 5_000)) + ) + fixtures.destroySockets() + try { + await waitForBarrier(fixtures.close(), 'fixture server cleanup', 5_000) + } catch (error) { + process.stderr.write(`[windows-pty-native-capability-smoke] ${error.message}\n`) + } + } else { + await fixtures.close() + } + } +} + +async function main() { + const [mode, ...args] = process.argv.slice(2) + if (mode === '--pty-shell') { + await runPtyShell(args[0], args[1], args[2], args[3]) + return + } + if (mode === '--grandchild-member') { + connectFixture(args[0], args[1], args[2]) + return + } + if (mode === '--exercise') { + if (!args[1]) { + throw new Error('exercise mode requires a fixture Node executable') + } + await exercise(args[0], args[1]) + return + } + if (mode === '--exit-contract-fixture') { + process.stdout.write('ORCA_ONE_SHOT_EVIDENCE=flushed\n') + setInterval(() => {}, 60_000) + return + } + throw new Error(`unknown packaged node-pty capability probe mode: ${mode}`) +} + +module.exports = { + buildGrandchildLaunch, + createFixtureServer, + isOneShotMode, + reportFixtureObservation +} + +if (require.main === module) { + const mode = process.argv[2] + main().then( + () => (isOneShotMode(mode) ? exitOneShot(0) : undefined), + async (error) => { + await writeStream(process.stderr, `${error.stack || error.message}\n`) + if (isOneShotMode(mode)) { + await exitOneShot(1) + } else { + process.exitCode = 1 + } + } + ) +} diff --git a/tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-probe.test.mjs b/tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-probe.test.mjs new file mode 100644 index 00000000000..f26b5ae481e --- /dev/null +++ b/tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-probe.test.mjs @@ -0,0 +1,89 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { runProcess } from '../../../src/shared/child-process/run-process' + +const require = createRequire(import.meta.url) +const probePath = require.resolve('./packaged-node-pty-capability-probe.cjs') +const { + buildGrandchildLaunch, + createFixtureServer, + isOneShotMode, + reportFixtureObservation +} = require(probePath) +const originalSystemRoot = process.env.SystemRoot + +afterEach(() => { + if (originalSystemRoot === undefined) { + delete process.env.SystemRoot + } else { + process.env.SystemRoot = originalSystemRoot + } +}) + +describe('packaged node-pty launcher-surviving grandchild', () => { + it('flushes one-shot evidence and exits despite a referenced handle', async () => { + expect(isOneShotMode('--exercise')).toBe(true) + expect(isOneShotMode('--exit-contract-fixture')).toBe(true) + expect(isOneShotMode('--pty-shell')).toBe(false) + + const result = await runProcess({ + program: process.execPath, + args: [probePath, '--exit-contract-fixture'], + timeoutMs: 5_000 + }) + + expect(result).toMatchObject({ code: 0, timedOut: false }) + expect(result.stdout).toBe('ORCA_ONE_SHOT_EVIDENCE=flushed\n') + expect(result.stderr).toBe('') + }) + + it('uses the hidden WScript launcher without cmd or start/b', () => { + process.env.SystemRoot = 'C:\\Windows' + const channel = '\\\\.\\pipe\\fixture & literal' + + const launch = buildGrandchildLaunch(channel, 'fixture-token^literal') + + expect(launch.program).toMatch(/wscript\.exe$/i) + expect(launch.args).toEqual([ + expect.stringMatching(/real-orca-detached-launcher\.vbs$/), + process.execPath, + probePath, + '--grandchild-member', + channel, + 'fixture-token^literal', + 'target-grandchild' + ]) + expect(JSON.stringify(launch)).not.toMatch(/cmd\.exe|start "" \/b/i) + }) + + it('closes one-shot fixture observations before server teardown', async () => { + const fixtureDir = await mkdtemp(join(tmpdir(), 'orca-pty-capability-')) + const channel = join(fixtureDir, 'fixture.sock') + const fixtureToken = 'fixture-token' + const fixtures = createFixtureServer(channel, fixtureToken) + + try { + await fixtures.listening + const observationPromise = fixtures.waitForRole('target-launcher-exited') + + await reportFixtureObservation(channel, fixtureToken, 'target-launcher-exited', { + pid: 1234 + }) + + await expect(observationPromise).resolves.toEqual({ + pid: 1234, + fixtureToken, + role: 'target-launcher-exited', + channel + }) + await expect(fixtures.close()).resolves.toBeUndefined() + } finally { + fixtures.destroySockets() + await fixtures.close() + await rm(fixtureDir, { recursive: true, force: true }) + } + }) +}) diff --git a/tests/tools/windows-pty-native-capability-smoke/real-orca-detached-launcher.vbs b/tests/tools/windows-pty-native-capability-smoke/real-orca-detached-launcher.vbs new file mode 100644 index 00000000000..cc24018bd52 --- /dev/null +++ b/tests/tools/windows-pty-native-capability-smoke/real-orca-detached-launcher.vbs @@ -0,0 +1,24 @@ +Option Explicit + +Function QuoteArgument(value) + If InStr(value, Chr(34)) > 0 Or InStr(value, vbCr) > 0 Or InStr(value, vbLf) > 0 Then + Err.Raise vbObjectError + 1, "real-orca-detached-launcher", "Invalid argument" + End If + QuoteArgument = Chr(34) & value & Chr(34) +End Function + +Dim args, command, index, shell, status +Set args = WScript.Arguments +If args.Count = 0 Then + Err.Raise vbObjectError + 2, "real-orca-detached-launcher", "Missing executable" +End If + +command = "" +For index = 0 To args.Count - 1 + If Len(command) > 0 Then command = command & " " + command = command & QuoteArgument(CStr(args(index))) +Next + +Set shell = CreateObject("WScript.Shell") +status = shell.Run(command, 0, False) +If status <> 0 Then WScript.Quit status diff --git a/tests/tools/windows-pty-native-capability-smoke/run.mjs b/tests/tools/windows-pty-native-capability-smoke/run.mjs new file mode 100644 index 00000000000..491fba2642d --- /dev/null +++ b/tests/tools/windows-pty-native-capability-smoke/run.mjs @@ -0,0 +1,72 @@ +import { createRequire } from 'node:module' +import path from 'node:path' +import { pathToFileURL } from 'node:url' +import { assertPackagedNodePtyCapability } from './packaged-node-pty-capability-oracle.mjs' + +const EVIDENCE_PREFIX = 'ORCA_NODE_PTY_CAPABILITY_EVIDENCE=' +const PROBE_TIMEOUT_MS = 45_000 +const MAX_DIAGNOSTIC_CHARS = 8_000 + +function executableArgument(argv) { + const value = argv.find((arg) => arg.startsWith('--exe='))?.slice('--exe='.length) + if (!value) { + throw new Error('usage: windows-pty-native-capability-smoke --exe=') + } + return path.resolve(value) +} + +export function checkoutRunProcessPath() { + return path.resolve(import.meta.dirname, '../../../out/shared/child-process/run-process.js') +} + +export function packagedProbeInvocation(executable, environment = process.env) { + const resolvedExecutable = path.resolve(executable) + const resourcesDir = path.join(path.dirname(resolvedExecutable), 'resources') + const probe = path.join(import.meta.dirname, 'packaged-node-pty-capability-probe.cjs') + return { + program: resolvedExecutable, + args: [probe, '--exercise', resourcesDir, process.execPath], + env: { ...environment, ELECTRON_RUN_AS_NODE: '1' }, + timeoutMs: PROBE_TIMEOUT_MS + } +} + +function diagnosticTail(value) { + return value.length <= MAX_DIAGNOSTIC_CHARS ? value : value.slice(-MAX_DIAGNOSTIC_CHARS) +} + +export function formatProbeFailure(result) { + return [ + `packaged native capability probe failed (code=${result.code}, timedOut=${result.timedOut})`, + `stdout:\n${diagnosticTail(result.stdout) || ''}`, + `stderr:\n${diagnosticTail(result.stderr) || ''}` + ].join('\n') +} + +function parseEvidence(stdout) { + const line = stdout.split(/\r?\n/).find((candidate) => candidate.startsWith(EVIDENCE_PREFIX)) + if (!line) { + throw new Error(`packaged probe did not emit ${EVIDENCE_PREFIX}`) + } + return JSON.parse(line.slice(EVIDENCE_PREFIX.length)) +} + +async function main() { + if (process.platform !== 'win32') { + throw new Error('windows-pty-native-capability-smoke requires a physical Windows host') + } + const executable = executableArgument(process.argv.slice(2)) + const require = createRequire(import.meta.url) + const { runProcess } = require(checkoutRunProcessPath()) + const result = await runProcess(packagedProbeInvocation(executable)) + if (result.code !== 0 || result.timedOut) { + throw new Error(formatProbeFailure(result)) + } + + assertPackagedNodePtyCapability(parseEvidence(result.stdout)) + process.stdout.write(`[windows-pty-native-capability-smoke] PASS ${executable}\n`) +} + +if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) { + await main() +} diff --git a/tests/tools/windows-pty-native-capability-smoke/run.test.mjs b/tests/tools/windows-pty-native-capability-smoke/run.test.mjs new file mode 100644 index 00000000000..bb8ab525da6 --- /dev/null +++ b/tests/tools/windows-pty-native-capability-smoke/run.test.mjs @@ -0,0 +1,47 @@ +import { readFileSync } from 'node:fs' +import path from 'node:path' +import { describe, expect, it } from 'vitest' +import { checkoutRunProcessPath, formatProbeFailure, packagedProbeInvocation } from './run.mjs' + +const runnerSource = readFileSync(new URL('./run.mjs', import.meta.url), 'utf8') + +describe('packaged Windows native smoke runner boundary', () => { + it('uses one checkout-owned runner for current and affected package paths', () => { + const current = packagedProbeInvocation('/ci/current/dist/win-unpacked/Orca.exe') + const affected = packagedProbeInvocation('/ci/1.4.158/dist/win-unpacked/Orca.exe') + + expect(checkoutRunProcessPath()).toBe(path.resolve('out/shared/child-process/run-process.js')) + expect(current.program).not.toBe(affected.program) + expect(current.args[0]).toBe(affected.args[0]) + expect(current.args[1]).toBe('--exercise') + expect(current.args[2]).not.toBe(affected.args[2]) + expect(current.args[3]).toBe(process.execPath) + expect(affected.args[3]).toBe(process.execPath) + expect(current.env.ELECTRON_RUN_AS_NODE).toBe('1') + expect(affected.env.ELECTRON_RUN_AS_NODE).toBe('1') + expect(current.timeoutMs).toBe(affected.timeoutMs) + expect(current.timeoutMs).toBe(45_000) + }) + + it('keeps timeout evidence bounded and preserves both output channels', () => { + const failure = formatProbeFailure({ + code: null, + timedOut: true, + stdout: `old-${'x'.repeat(9_000)}-stdout-tail`, + stderr: 'stage=target-spawn:start' + }) + + expect(failure).toContain('code=null, timedOut=true') + expect(failure).not.toContain('old-') + expect(failure).toContain('stdout-tail') + expect(failure).toContain('stage=target-spawn:start') + }) + + it('does not import child_process or resolve the runner from the artifact', () => { + expect(runnerSource).not.toContain('node:child_process') + expect(runnerSource).not.toMatch( + /path\.join\(resourcesDir[\s\S]*?app\.asar\.unpacked[\s\S]*?run-process\.js/ + ) + expect(runnerSource).toContain("'../../../out/shared/child-process/run-process.js'") + }) +}) From 7b9529da22502390c8784852e8495215006f924d Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Mon, 24 Aug 2026 10:12:38 -0700 Subject: [PATCH 13/13] Add keyboard shortcut for workspace deletion (#16271) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add keyboard shortcut for workspace deletion Default Mod+Shift+Backspace (⌘⇧⌫ on Mac) lets users delete the hovered worktree or folder workspace immediately. The shortcut targets the sidebar hover state rather than requiring focus, and avoids terminal pane D-based split shortcuts on all platforms. Co-authored-by: Brennan Benson * Omit delete shortcut from disabled Delete Worktree for primary checkout - Remove shortcut badge from the disabled "Delete Worktree" action when it cannot be executed - Only show shortcut in multi-context delete actions where the command is available - Extract host identity parsing into reusable helper function to prevent inline string manipulation - Fix folder workspace deletion to use correct host-qualified identity comparison * Document host extraction safety for destructive worktree ops Unqualified identities must stay undefined rather than defaulting to 'local'. Destructive operations depend on correct host identification. Added tests and JSDoc to clarify this safety-critical behavior. * fix test --------- Co-authored-by: Brennan Benson --- .../browser-guest-shortcut-dispatch.ts | 7 +- .../browser-guest-shortcut-forwarding.test.ts | 41 +++ ...ainWindow-terminal-focus-shortcuts.test.ts | 62 ++++- src/main/window/createMainWindow.ts | 5 +- ...-command-handlers-workspace-delete.test.ts | 88 +++++++ .../src/app-shell/app-command-handlers.ts | 20 ++ .../src/app-shell/use-global-keybindings.ts | 3 + ...rktreeContextMenu.delete-shortcut.test.tsx | 244 ++++++++++++++++++ .../sidebar/WorktreeContextMenu.tsx | 6 + .../WorktreeDeveloperMenuReveal.test.tsx | 3 +- .../sidebar/hovered-workspace-delete.test.ts | 223 ++++++++++++++++ .../sidebar/hovered-workspace-delete.ts | 133 ++++++++++ src/renderer/src/hooks/useIpcEvents.ts | 16 +- .../src/lib/worktree-runtime-owner-index.ts | 6 +- ...r-workspace-owner-routed-mutations.test.ts | 34 +++ src/renderer/src/store/slices/repos.ts | 30 ++- src/shared/keybindings-parsing.test.ts | 2 + .../keybindings-unassigned-actions.test.ts | 25 +- src/shared/keybindings.ts | 10 +- src/shared/window-shortcut-policy.test.ts | 13 +- .../worktree/host-qualified-identity.test.ts | 26 ++ .../worktree/host-qualified-identity.ts | 18 ++ tests/e2e/worktree-delete-shortcut.spec.ts | 76 ++++++ 23 files changed, 1048 insertions(+), 43 deletions(-) create mode 100644 src/renderer/src/app-shell/app-command-handlers-workspace-delete.test.ts create mode 100644 src/renderer/src/components/sidebar/WorktreeContextMenu.delete-shortcut.test.tsx create mode 100644 src/renderer/src/components/sidebar/hovered-workspace-delete.test.ts create mode 100644 src/renderer/src/components/sidebar/hovered-workspace-delete.ts create mode 100644 tests/e2e/worktree-delete-shortcut.spec.ts diff --git a/src/main/browser/browser-guest-shortcut-dispatch.ts b/src/main/browser/browser-guest-shortcut-dispatch.ts index 8785bed2c11..3992a5ade35 100644 --- a/src/main/browser/browser-guest-shortcut-dispatch.ts +++ b/src/main/browser/browser-guest-shortcut-dispatch.ts @@ -46,7 +46,10 @@ export function forwardGuestShortcutInput( return true } if (input.isAutoRepeat) { - if (action?.type === 'dictationKeyDown' && shouldForwardDictationShortcut?.()) { + if ( + (action?.type === 'dictationKeyDown' && shouldForwardDictationShortcut?.()) || + action?.type === 'deleteCurrentWorkspace' + ) { event.preventDefault() return true } @@ -176,6 +179,8 @@ export function forwardGuestShortcutInput( renderer.send('ui:toggleQuickCommandsMenu') } else if (action?.type === 'openNewWorkspace') { renderer.send('ui:openNewWorkspace') + } else if (action?.type === 'deleteCurrentWorkspace') { + renderer.send('ui:deleteCurrentWorkspace') } else if (action?.type === 'openWorkspaceBoard') { renderer.send('ui:openWorkspaceBoard') } else if (action?.type === 'openTasks') { diff --git a/src/main/browser/browser-guest-shortcut-forwarding.test.ts b/src/main/browser/browser-guest-shortcut-forwarding.test.ts index 39a24fa45fc..a3385a08582 100644 --- a/src/main/browser/browser-guest-shortcut-forwarding.test.ts +++ b/src/main/browser/browser-guest-shortcut-forwarding.test.ts @@ -623,6 +623,47 @@ describe('setupGuestShortcutForwarding', () => { expect(rendererSendMock).toHaveBeenCalledWith('ui:toggleQuickCommandsMenu') }) + it('forwards workspace delete shortcuts from focused guest pages', () => { + setupGuestShortcutForwarding({ + browserTabId, + guest: makeGuest(), + resolveRenderer: () => makeRenderer() + }) + + const isMac = process.platform === 'darwin' + const preventDefault = triggerBeforeInput({ + code: 'Backspace', + key: 'Backspace', + meta: isMac, + control: !isMac, + shift: true + }) + + expect(preventDefault).toHaveBeenCalledOnce() + expect(rendererSendMock).toHaveBeenCalledWith('ui:deleteCurrentWorkspace') + }) + + it('consumes repeated workspace delete shortcuts from focused guest pages', () => { + setupGuestShortcutForwarding({ + browserTabId, + guest: makeGuest(), + resolveRenderer: () => makeRenderer() + }) + + const isMac = process.platform === 'darwin' + const preventDefault = triggerBeforeInput({ + code: 'Backspace', + key: 'Backspace', + meta: isMac, + control: !isMac, + shift: true, + isAutoRepeat: true + }) + + expect(preventDefault).toHaveBeenCalledOnce() + expect(rendererSendMock).not.toHaveBeenCalled() + }) + it('consumes guest zoom shortcuts even when the renderer is unavailable', () => { setupGuestShortcutForwarding({ browserTabId, diff --git a/src/main/window/createMainWindow-terminal-focus-shortcuts.test.ts b/src/main/window/createMainWindow-terminal-focus-shortcuts.test.ts index ba87f891737..9b88c60800c 100644 --- a/src/main/window/createMainWindow-terminal-focus-shortcuts.test.ts +++ b/src/main/window/createMainWindow-terminal-focus-shortcuts.test.ts @@ -341,6 +341,64 @@ describe('createMainWindow', () => { expect(webContents.send).not.toHaveBeenCalled() }) + it('suppresses auto-repeat workspace deletes from before-input-event', () => { + const windowHandlers: Record void> = {} + const webContents = { + on: vi.fn((event, handler) => { + windowHandlers[event] = handler + }), + setZoomLevel: vi.fn(), + setBackgroundThrottling: vi.fn(), + invalidate: vi.fn(), + setWindowOpenHandler: vi.fn(), + send: vi.fn(), + isDevToolsOpened: vi.fn(), + openDevTools: vi.fn(), + closeDevTools: vi.fn() + } + const browserWindowInstance = { + webContents, + on: vi.fn(), + isDestroyed: vi.fn(() => false), + isMaximized: vi.fn(() => true), + isFullScreen: vi.fn(() => false), + getSize: vi.fn(() => [1200, 800]), + setSize: vi.fn(), + maximize: vi.fn(), + show: vi.fn(), + loadFile: vi.fn(), + loadURL: vi.fn() + } + browserWindowMock.mockImplementation(function () { + return browserWindowInstance + }) + + createMainWindow(null) + + const isDarwin = process.platform === 'darwin' + const input = { + type: 'keyDown', + code: 'Backspace', + key: 'Backspace', + meta: isDarwin, + control: !isDarwin, + alt: false, + shift: true + } + windowHandlers['before-input-event']({ preventDefault: vi.fn() } as never, input) + expect(webContents.send).toHaveBeenCalledWith('ui:deleteCurrentWorkspace') + + webContents.send.mockClear() + const repeatPreventDefault = vi.fn() + windowHandlers['before-input-event']({ preventDefault: repeatPreventDefault } as never, { + ...input, + isAutoRepeat: true + }) + + expect(repeatPreventDefault).toHaveBeenCalledOnce() + expect(webContents.send).not.toHaveBeenCalled() + }) + it('lets Terminal-first pass risky app shortcuts through when terminal input is focused', () => { const windowHandlers: Record void> = {} const webContents = { @@ -624,7 +682,7 @@ describe('createMainWindow', () => { expect(webContents.send).toHaveBeenNthCalledWith(2, 'ui:openQuickOpen') }) - it('forwards the configured workspace delete shortcut while terminal input is focused', () => { + it('forwards the default workspace delete shortcut while terminal input is focused', () => { const windowHandlers: Record void> = {} const webContents = { on: vi.fn((event, handler) => { @@ -662,7 +720,7 @@ describe('createMainWindow', () => { getSettings: () => ({ terminalShortcutPolicy: 'terminal-first' }) } as never, { - getKeybindings: () => ({ 'workspace.delete': ['Mod+Shift+Backspace'] }) + getKeybindings: () => ({}) } ) diff --git a/src/main/window/createMainWindow.ts b/src/main/window/createMainWindow.ts index 07e24b452b9..dac90bec357 100644 --- a/src/main/window/createMainWindow.ts +++ b/src/main/window/createMainWindow.ts @@ -811,7 +811,10 @@ export function createMainWindow( return true } - if (action.type === 'toggleQuickCommandsMenu' && isAutoRepeat) { + if ( + (action.type === 'toggleQuickCommandsMenu' || action.type === 'deleteCurrentWorkspace') && + isAutoRepeat + ) { event.preventDefault() return true } diff --git a/src/renderer/src/app-shell/app-command-handlers-workspace-delete.test.ts b/src/renderer/src/app-shell/app-command-handlers-workspace-delete.test.ts new file mode 100644 index 00000000000..7ffc3896a66 --- /dev/null +++ b/src/renderer/src/app-shell/app-command-handlers-workspace-delete.test.ts @@ -0,0 +1,88 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { AppState } from '@/store/types' +import type { HoveredWorkspaceDeleteTarget } from '../components/sidebar/hovered-workspace-delete' +import type { AppShortcutState, ShortcutDispatchInput } from './app-command-handlers' + +const mocks = vi.hoisted(() => ({ + deleteHoveredWorkspaceImmediately: vi.fn(), + hoveredTarget: { kind: 'worktree', worktree: {} } as HoveredWorkspaceDeleteTarget | null, + store: {} as AppState +})) + +vi.mock('../store', () => ({ + useAppStore: Object.assign(vi.fn(), { getState: () => mocks.store }) +})) + +vi.mock('../components/sidebar/hovered-workspace-delete', () => ({ + deleteHoveredWorkspaceImmediately: mocks.deleteHoveredWorkspaceImmediately, + resolveHoveredWorkspaceDeleteTarget: () => mocks.hoveredTarget +})) + +vi.mock('@/lib/floating-workspace-terminal-actions', () => ({ + isFloatingWorkspacePanelFocused: () => false +})) + +vi.mock('@/lib/terminal-shortcut-capture-notification', () => ({ + showTerminalShortcutCaptureNotification: vi.fn() +})) + +import { createAppCommandHandlers } from './app-command-handlers' + +function shortcutState(overrides: Partial = {}): AppShortcutState { + return { + activeView: 'terminal', + activeWorktreeId: 'repo::/feature', + actions: {} as AppShortcutState['actions'], + creationLayoutActive: false, + floatingTerminalEnabled: false, + floatingTerminalOpen: false, + floatingVisibleTabCount: 0, + keybindings: {}, + openFloatingWorkspaceMaximized: vi.fn(), + pluginCommands: [], + setFloatingTerminalOpen: vi.fn(), + terminalShortcutPolicy: 'orca-first', + workspaceChromeActive: true, + ...overrides + } +} + +function shortcutInput(): ShortcutDispatchInput { + return { + target: null, + defaultPrevented: false, + preventDefault: vi.fn() + } +} + +describe('workspace delete app command', () => { + beforeEach(() => { + vi.clearAllMocks() + mocks.store = { activeWorktreeId: 'repo::/feature' } as AppState + mocks.hoveredTarget = { kind: 'worktree', worktree: {} as never } + }) + + it('claims the chord and immediately deletes the active workspace', () => { + const input = shortcutInput() + const handler = createAppCommandHandlers(shortcutState(), input, 'terminal').get( + 'workspace.delete' + ) + + expect(handler?.()).toBe(true) + expect(input.preventDefault).toHaveBeenCalledOnce() + expect(mocks.deleteHoveredWorkspaceImmediately).toHaveBeenCalledWith( + mocks.store, + mocks.hoveredTarget + ) + }) + + it('does not claim the chord without a hovered workspace', () => { + const input = shortcutInput() + const handler = createAppCommandHandlers(shortcutState(), input).get('workspace.delete') + + mocks.hoveredTarget = null + expect(handler?.()).toBe(false) + expect(input.preventDefault).not.toHaveBeenCalled() + expect(mocks.deleteHoveredWorkspaceImmediately).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/app-shell/app-command-handlers.ts b/src/renderer/src/app-shell/app-command-handlers.ts index 11c69425552..99915597e67 100644 --- a/src/renderer/src/app-shell/app-command-handlers.ts +++ b/src/renderer/src/app-shell/app-command-handlers.ts @@ -5,6 +5,10 @@ import { requestScrollToCurrentWorkspaceRevealAndRename } from '@/lib/scroll-to- import { showTerminalShortcutCaptureNotification } from '@/lib/terminal-shortcut-capture-notification' import { shouldShowWorktreeHistoryControls } from '../lib/titlebar-worktree-history-controls' import { TOGGLE_WORKSPACE_BOARD_EVENT } from '../components/sidebar/useWorkspaceBoardPanel' +import { + deleteHoveredWorkspaceImmediately, + resolveHoveredWorkspaceDeleteTarget +} from '../components/sidebar/hovered-workspace-delete' import { useAppStore } from '../store' import type { usePluginCommands } from '@/store/plugin-panels' import { isGitRepoKind } from '../../../shared/repo-kind' @@ -191,6 +195,22 @@ export function createAppCommandHandlers( }) } ], + [ + 'workspace.delete', + () => { + if (floatingWorkspaceFocused) { + return false + } + const store = useAppStore.getState() + const target = resolveHoveredWorkspaceDeleteTarget(store) + if (!target) { + return false + } + return claim('workspace.delete', () => { + deleteHoveredWorkspaceImmediately(store, target) + }) + } + ], [ 'workspace.openBoard', () => { diff --git a/src/renderer/src/app-shell/use-global-keybindings.ts b/src/renderer/src/app-shell/use-global-keybindings.ts index d40d928a20c..78051a58ed5 100644 --- a/src/renderer/src/app-shell/use-global-keybindings.ts +++ b/src/renderer/src/app-shell/use-global-keybindings.ts @@ -236,6 +236,9 @@ export function useGlobalKeybindings(args: { } const handlers = createAppCommandHandlers(state, input, context) + if (matchShortcut('workspace.delete') && handlers.get('workspace.delete')?.()) { + return + } for (const actionId of PLUGIN_COMMAND_ALIAS_ACTION_IDS) { if (matchShortcut(actionId) && handlers.get(actionId)?.()) { return diff --git a/src/renderer/src/components/sidebar/WorktreeContextMenu.delete-shortcut.test.tsx b/src/renderer/src/components/sidebar/WorktreeContextMenu.delete-shortcut.test.tsx new file mode 100644 index 00000000000..c6664b14e2c --- /dev/null +++ b/src/renderer/src/components/sidebar/WorktreeContextMenu.delete-shortcut.test.tsx @@ -0,0 +1,244 @@ +/** + * @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 { Worktree } from '../../../../shared/worktree/types' +import WorktreeContextMenu from './WorktreeContextMenu' + +globalThis.IS_REACT_ACT_ENVIRONMENT = true + +const shortcutLabelMock = vi.hoisted(() => vi.fn()) + +vi.mock('@/hooks/useShortcutLabel', () => ({ + useOptionalShortcutLabel: shortcutLabelMock, + formatShortcutLabel: () => '', + formatOptionalShortcutLabel: () => null +})) + +vi.mock('@/components/ui/dropdown-menu', () => ({ + DropdownMenu: function DropdownMenu(props: { children?: React.ReactNode; open?: boolean }) { + return
{props.children}
+ }, + DropdownMenuContent: function DropdownMenuContent(props: { children?: React.ReactNode }) { + return
{props.children}
+ }, + DropdownMenuItem: function DropdownMenuItem(props: { + children?: React.ReactNode + disabled?: boolean + variant?: string + }) { + return ( +
+ {props.children} +
+ ) + }, + DropdownMenuSeparator: function DropdownMenuSeparator() { + return
+ }, + DropdownMenuShortcut: function DropdownMenuShortcut(props: { children?: React.ReactNode }) { + return {props.children} + }, + DropdownMenuLabel: function DropdownMenuLabel(props: { children?: React.ReactNode }) { + return
{props.children}
+ }, + DropdownMenuSub: function DropdownMenuSub(props: { children?: React.ReactNode }) { + return
{props.children}
+ }, + DropdownMenuSubContent: function DropdownMenuSubContent(props: { children?: React.ReactNode }) { + return
{props.children}
+ }, + DropdownMenuSubTrigger: function DropdownMenuSubTrigger(props: { children?: React.ReactNode }) { + return
{props.children}
+ }, + DropdownMenuTrigger: function DropdownMenuTrigger(props: { children?: React.ReactNode }) { + return
{props.children}
+ }, + DropdownMenuRadioGroup: function DropdownMenuRadioGroup(props: { children?: React.ReactNode }) { + return
{props.children}
+ }, + DropdownMenuRadioItem: function DropdownMenuRadioItem(props: { children?: React.ReactNode }) { + return
{props.children}
+ } +})) + +vi.mock('@/components/ui/tooltip', () => ({ + Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}, + TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children}, + TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children} +})) + +vi.mock('lucide-react', async () => + (await import('../tab-bar/lucide-icon-stub-fixture')).stubEveryIcon() +) + +vi.mock('@/i18n/i18n', () => ({ + translate: (_key: string, fallback: string) => fallback +})) + +const defaultStoreState = { + updateWorktreeMeta: vi.fn(), + setWorktreesPinnedAndReveal: vi.fn(), + workspaceStatuses: [], + openModal: vi.fn(), + projectGroups: [], + createProjectGroup: vi.fn(), + moveProjectToGroup: vi.fn(), + deleteStateByWorktreeId: {}, + worktreeLineageById: {}, + workspaceLineageByChildKey: {}, + updateWorktreeLineage: vi.fn(), + tabsByWorktree: {}, + ptyIdsByTabId: {}, + browserTabsByWorktree: {}, + worktreesByRepo: {}, + repos: [] +} + +vi.mock('@/store', () => ({ + useAppStore: Object.assign( + (selector: (state: typeof defaultStoreState) => unknown) => selector(defaultStoreState), + { + getState: () => defaultStoreState + } + ) +})) + +vi.mock('@/store/selectors', () => ({ + useAllWorktrees: () => [], + useRepoById: (repoId?: string) => + repoId ? { id: repoId, name: repoId, displayName: repoId } : undefined, + useRepoMap: () => new Map(), + useWorktreeMap: () => new Map() +})) + +vi.mock('./ProjectGroupNameDialog', () => ({ + ProjectGroupNameDialog: () => null +})) + +vi.mock('./WorktreeParentPickerPopover', () => ({ + WorktreeParentPickerPopover: () => null +})) + +vi.mock('./WorktreeDeveloperMenu', () => ({ + WorktreeDeveloperMenu: () => null +})) + +vi.mock('./WorktreeOpenInMenu', () => ({ + WorktreeOpenInSubMenu: () => null +})) + +vi.mock('./WorkspaceSleepMenuItems', () => ({ + WorkspaceSleepMenuItems: () => null +})) + +const mounted: { container: HTMLDivElement; root: Root }[] = [] + +function renderContextMenu(worktree: Worktree) { + const container = document.createElement('div') + document.body.appendChild(container) + const root = createRoot(container) + act(() => { + root.render( + +
Card Content
+
+ ) + }) + mounted.push({ container, root }) + return container +} + +describe('WorktreeContextMenu delete shortcut display', () => { + beforeEach(() => { + shortcutLabelMock.mockImplementation((action: string) => { + if (action === 'workspace.delete') { + return '⌘⇧⌫' + } + return null + }) + }) + + afterEach(() => { + for (const { root, container } of mounted) { + act(() => { + root.unmount() + }) + container.remove() + } + mounted.length = 0 + }) + + it('renders the delete shortcut badge for standard worktree delete', () => { + const worktree = { + id: 'repo::wt-1', + repoId: 'repo', + name: 'wt-1', + path: '/path/to/wt-1', + isMainWorktree: false + } as unknown as Worktree + + const container = renderContextMenu(worktree) + const target = container.querySelector('[data-worktree-context-menu-scope]') as HTMLElement + expect(target).toBeTruthy() + act(() => { + target.dispatchEvent( + new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 10, clientY: 10 }) + ) + }) + + const shortcuts = container.querySelectorAll('[data-testid="dropdown-menu-shortcut"]') + const deleteShortcuts = Array.from(shortcuts).filter((el) => el.textContent === '⌘⇧⌫') + expect(deleteShortcuts.length).toBe(1) + }) + + it('omits the delete shortcut on disabled Delete Worktree for primary checkout', () => { + const worktree = { + id: 'repo-1::main', + repoId: 'repo-1', + name: 'main', + path: '/path/to/main', + isMainWorktree: true + } as unknown as Worktree + + const container = renderContextMenu(worktree) + const target = container.querySelector('[data-worktree-context-menu-scope]') as HTMLElement + act(() => { + target.dispatchEvent( + new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 10, clientY: 10 }) + ) + }) + + const shortcuts = container.querySelectorAll('[data-testid="dropdown-menu-shortcut"]') + const deleteShortcuts = Array.from(shortcuts).filter((el) => el.textContent === '⌘⇧⌫') + expect(deleteShortcuts.length).toBe(0) + }) + + it('omits the shortcut badge when the action is unassigned', () => { + shortcutLabelMock.mockReturnValue(null) + const worktree = { + id: 'repo::wt-1', + repoId: 'repo', + name: 'wt-1', + path: '/path/to/wt-1', + isMainWorktree: false + } as unknown as Worktree + + const container = renderContextMenu(worktree) + const target = container.querySelector('[data-worktree-context-menu-scope]') as HTMLElement + act(() => { + target.dispatchEvent( + new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 10, clientY: 10 }) + ) + }) + + const shortcuts = container.querySelectorAll('[data-testid="dropdown-menu-shortcut"]') + expect(shortcuts.length).toBe(0) + }) +}) diff --git a/src/renderer/src/components/sidebar/WorktreeContextMenu.tsx b/src/renderer/src/components/sidebar/WorktreeContextMenu.tsx index 787090a5cd3..8e3d87fd658 100644 --- a/src/renderer/src/components/sidebar/WorktreeContextMenu.tsx +++ b/src/renderer/src/components/sidebar/WorktreeContextMenu.tsx @@ -8,6 +8,7 @@ import { DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, + DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, @@ -68,6 +69,7 @@ import { translate } from '@/i18n/i18n' import { unnestWorktrees } from './worktree-unnest' import { parseWorkspaceKey, worktreeWorkspaceKey } from '../../../../shared/workspace-scope' import { getDeleteStateForWorktreeHost } from './worktree-delete-state-host-match' +import { useOptionalShortcutLabel } from '@/hooks/useShortcutLabel' type Props = { worktree: Worktree @@ -337,6 +339,7 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({ const deleteState = useAppStore((s) => getDeleteStateForWorktreeHost(worktree, s.deleteStateByWorktreeId) ) + const deleteShortcut = useOptionalShortcutLabel('workspace.delete') const [menuOpen, setMenuOpen] = useState(false) // Why: the Developer submenu is a power-user affordance, so it is revealed by // holding Option/Alt at right-click — captured at open time (like the Help @@ -1086,6 +1089,9 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({ 'auto.components.sidebar.WorktreeContextMenu.f4475537d8', 'Delete' )} + {!isMultiContext && !removesProject && deleteShortcut ? ( + {deleteShortcut} + ) : null} diff --git a/src/renderer/src/components/sidebar/WorktreeDeveloperMenuReveal.test.tsx b/src/renderer/src/components/sidebar/WorktreeDeveloperMenuReveal.test.tsx index 6955e14ac60..4eed6feea33 100644 --- a/src/renderer/src/components/sidebar/WorktreeDeveloperMenuReveal.test.tsx +++ b/src/renderer/src/components/sidebar/WorktreeDeveloperMenuReveal.test.tsx @@ -66,7 +66,8 @@ vi.mock('@/components/ui/dropdown-menu', () => { DropdownMenuSub: passthrough, DropdownMenuSubContent: passthrough, DropdownMenuSubTrigger: passthrough, - DropdownMenuTrigger: passthrough + DropdownMenuTrigger: passthrough, + DropdownMenuShortcut: passthrough } }) diff --git a/src/renderer/src/components/sidebar/hovered-workspace-delete.test.ts b/src/renderer/src/components/sidebar/hovered-workspace-delete.test.ts new file mode 100644 index 00000000000..d0a749c0d14 --- /dev/null +++ b/src/renderer/src/components/sidebar/hovered-workspace-delete.test.ts @@ -0,0 +1,223 @@ +import { describe, expect, it, vi } from 'vitest' +import type { AppState } from '@/store/types' +import type { Worktree } from '../../../../shared/worktree/types' +import { + deleteHoveredWorkspaceImmediately, + getHoveredWorkspaceIdentity, + resolveHoveredWorkspaceDeleteTarget +} from './hovered-workspace-delete' + +function worktree(overrides: Partial = {}): Worktree { + return { + id: 'repo::/feature', + repoId: 'repo', + path: '/feature', + branch: 'feature', + isMainWorktree: false, + ...overrides + } as Worktree +} + +function hoveredDocument(...rows: { workspaceId: string; hostIdentity: string }[]) { + return { + activeElement: null, + querySelectorAll: () => ({ + length: rows.length, + item: (index: number) => { + const row = rows[index] + return row + ? ({ + dataset: { + worktreeId: row.workspaceId, + worktreeHostIdentity: row.hostIdentity + } + } as unknown as HTMLElement) + : null + } + }) + } as unknown as Pick +} + +function state(worktrees: Worktree[] = []): AppState { + return { + activeModal: 'none', + activeWorkspaceExecutionHostId: worktrees[0]?.hostId ?? null, + activeWorktreeId: worktrees[0]?.id ?? null, + deleteFolderWorkspace: vi.fn(), + deleteStateByWorktreeId: {}, + setActiveWorktree: vi.fn(), + worktreesByRepo: { repo: worktrees } + } as unknown as AppState +} + +describe('hovered workspace delete', () => { + it('uses the deepest hovered worktree row', () => { + expect( + getHoveredWorkspaceIdentity( + hoveredDocument( + { workspaceId: 'parent', hostIdentity: 'local|parent' }, + { workspaceId: 'child', hostIdentity: 'local|child' } + ) + ) + ).toEqual({ workspaceId: 'child', hostIdentity: 'local|child' }) + }) + + it('resolves the exact hovered host instead of the active workspace', () => { + const active = worktree({ id: 'repo::/active', path: '/active', hostId: 'local' }) + const hovered = worktree({ hostId: 'ssh:build', instanceId: 'instance-2' }) + + expect( + resolveHoveredWorkspaceDeleteTarget( + state([active, hovered]), + hoveredDocument({ workspaceId: hovered.id, hostIdentity: 'ssh:build|repo::/feature' }) + ) + ).toEqual({ kind: 'worktree', worktree: hovered }) + }) + + it('retains the hovered host when resolving a folder workspace', () => { + expect( + resolveHoveredWorkspaceDeleteTarget( + state(), + hoveredDocument({ + workspaceId: 'folder:folder-1', + hostIdentity: 'runtime:remote-1|folder:folder-1' + }) + ) + ).toEqual({ + kind: 'folder', + executionHostId: 'runtime:remote-1', + folderWorkspaceId: 'folder-1', + workspaceKey: 'folder:folder-1' + }) + }) + + it('rejects primary worktrees, stale rows, and missing hover', () => { + const primary = worktree({ hostId: 'local', isMainWorktree: true }) + const current = state([primary]) + + expect( + resolveHoveredWorkspaceDeleteTarget( + current, + hoveredDocument({ workspaceId: primary.id, hostIdentity: 'local|repo::/feature' }) + ) + ).toBeNull() + expect( + resolveHoveredWorkspaceDeleteTarget( + current, + hoveredDocument({ workspaceId: 'stale', hostIdentity: 'local|stale' }) + ) + ).toBeNull() + expect(resolveHoveredWorkspaceDeleteTarget(current, hoveredDocument())).toBeNull() + }) + + it('rejects worktrees that are already deleting', () => { + const target = worktree({ hostId: 'ssh:build' }) + const current = state([target]) + current.deleteStateByWorktreeId = { + 'ssh:build|repo::/feature': { + isDeleting: true, + error: null, + canForceDelete: false, + forceDeleteReason: null + } + } + + expect( + resolveHoveredWorkspaceDeleteTarget( + current, + hoveredDocument({ workspaceId: target.id, hostIdentity: 'ssh:build|repo::/feature' }) + ) + ).toBeNull() + }) + + it('rejects hovered rows while an editable control has focus', () => { + class EditableElement { + classList = { contains: () => false } + isContentEditable = false + closest = () => this + } + vi.stubGlobal('HTMLElement', EditableElement) + const target = worktree({ hostId: 'local' }) + const doc = hoveredDocument({ + workspaceId: target.id, + hostIdentity: 'local|repo::/feature' + }) as Pick + Object.defineProperty(doc, 'activeElement', { value: new EditableElement() }) + + try { + expect(resolveHoveredWorkspaceDeleteTarget(state([target]), doc)).toBeNull() + } finally { + vi.unstubAllGlobals() + } + }) + + it('routes the hovered worktree through the host-qualified safety flow', () => { + const target = worktree({ hostId: 'ssh:build', instanceId: 'instance-2' }) + const deleteWorktree = vi.fn() + const current = state([target]) + + expect( + deleteHoveredWorkspaceImmediately( + current, + { kind: 'worktree', worktree: target }, + { + deleteWorktree, + getCurrentState: () => current + } + ) + ).toBe(true) + expect(deleteWorktree).toHaveBeenCalledWith(target.id, { + expectedHostId: 'ssh:build', + expectedInstanceId: 'instance-2' + }) + }) + + it('removes a hovered folder workspace from Orca without deleting its directory', async () => { + const current = state() + current.activeWorktreeId = 'folder:folder-1' + current.activeWorkspaceExecutionHostId = 'runtime:remote-1' + current.deleteFolderWorkspace = vi.fn().mockResolvedValue(true) + + expect( + deleteHoveredWorkspaceImmediately( + current, + { + kind: 'folder', + executionHostId: 'runtime:remote-1', + folderWorkspaceId: 'folder-1', + workspaceKey: 'folder:folder-1' + }, + { deleteWorktree: vi.fn(), getCurrentState: () => current } + ) + ).toBe(true) + await vi.waitFor(() => expect(current.setActiveWorktree).toHaveBeenCalledWith(null)) + expect(current.deleteFolderWorkspace).toHaveBeenCalledWith('folder-1', { + executionHostId: 'runtime:remote-1' + }) + }) + + it('rejects a duplicate folder delete while the first request is pending', async () => { + let finishDelete!: (deleted: boolean) => void + const current = state() + current.deleteFolderWorkspace = vi.fn( + () => new Promise((resolve) => (finishDelete = resolve)) + ) + const target = { + kind: 'folder' as const, + executionHostId: 'runtime:remote-2' as const, + folderWorkspaceId: 'folder-2', + workspaceKey: 'folder:folder-2' + } + const dependencies = { deleteWorktree: vi.fn(), getCurrentState: () => current } + + expect(deleteHoveredWorkspaceImmediately(current, target, dependencies)).toBe(true) + expect(deleteHoveredWorkspaceImmediately(current, target, dependencies)).toBe(false) + expect(current.deleteFolderWorkspace).toHaveBeenCalledOnce() + + finishDelete(false) + await vi.waitFor(() => + expect(deleteHoveredWorkspaceImmediately(current, target, dependencies)).toBe(true) + ) + finishDelete(false) + }) +}) diff --git a/src/renderer/src/components/sidebar/hovered-workspace-delete.ts b/src/renderer/src/components/sidebar/hovered-workspace-delete.ts new file mode 100644 index 00000000000..f1ecdc30d8b --- /dev/null +++ b/src/renderer/src/components/sidebar/hovered-workspace-delete.ts @@ -0,0 +1,133 @@ +import { useAppStore } from '@/store' +import { getAllWorktreesFromState } from '@/store/selectors' +import type { AppState } from '@/store/types' +import { isEditableTarget } from '@/lib/editable-target' +import { + composeWorktreeHostIdentity, + getExecutionHostIdFromWorktreeHostIdentity, + getWorktreeHostIdentity +} from '../../../../shared/worktree/host-qualified-identity' +import type { Worktree } from '../../../../shared/worktree/types' +import { parseWorkspaceKey } from '../../../../shared/workspace-scope' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import { runWorktreeDelete } from './delete-worktree-flow' +import { getDeleteStateForWorktreeHost } from './worktree-delete-state-host-match' + +const pendingFolderDeletes = new Set() + +type DeleteWorktree = typeof runWorktreeDelete +type HoveredWorkspaceDeleteState = Pick< + AppState, + | 'activeModal' + | 'activeWorktreeId' + | 'deleteFolderWorkspace' + | 'deleteStateByWorktreeId' + | 'worktreesByRepo' +> +type CurrentWorkspaceState = Pick< + AppState, + 'activeWorkspaceExecutionHostId' | 'activeWorktreeId' | 'setActiveWorktree' +> +type HoveredWorkspaceDeleteDependencies = { + deleteWorktree: DeleteWorktree + getCurrentState: () => CurrentWorkspaceState +} +type HoveredWorkspaceDocument = Pick + +export type HoveredWorkspaceDeleteTarget = + | { + kind: 'folder' + executionHostId: ExecutionHostId + folderWorkspaceId: string + workspaceKey: string + } + | { kind: 'worktree'; worktree: Worktree } + +export function getHoveredWorkspaceIdentity( + doc: HoveredWorkspaceDocument = document +): { hostIdentity: string; workspaceId: string } | null { + const hoveredRows = doc.querySelectorAll( + '[data-worktree-sidebar] [role="option"][data-worktree-id]:hover' + ) + const row = hoveredRows.item(hoveredRows.length - 1) + const workspaceId = row?.dataset.worktreeId + const hostIdentity = row?.dataset.worktreeHostIdentity + return workspaceId && hostIdentity ? { workspaceId, hostIdentity } : null +} + +export function resolveHoveredWorkspaceDeleteTarget( + state: HoveredWorkspaceDeleteState, + doc: HoveredWorkspaceDocument = document +): HoveredWorkspaceDeleteTarget | null { + if (state.activeModal !== 'none' || (doc.activeElement && isEditableTarget(doc.activeElement))) { + return null + } + const hovered = getHoveredWorkspaceIdentity(doc) + if (!hovered) { + return null + } + const workspaceScope = parseWorkspaceKey(hovered.workspaceId) + if (workspaceScope?.type === 'folder') { + const executionHostId = getExecutionHostIdFromWorktreeHostIdentity(hovered.hostIdentity) + if (!executionHostId) { + return null + } + return { + kind: 'folder', + executionHostId, + folderWorkspaceId: workspaceScope.folderWorkspaceId, + workspaceKey: hovered.workspaceId + } + } + const worktree = getAllWorktreesFromState(state).find( + (candidate) => + candidate.id === hovered.workspaceId && + getWorktreeHostIdentity(candidate) === hovered.hostIdentity + ) + return worktree && + !worktree.isMainWorktree && + !getDeleteStateForWorktreeHost(worktree, state.deleteStateByWorktreeId)?.isDeleting + ? { kind: 'worktree', worktree } + : null +} + +export function deleteHoveredWorkspaceImmediately( + state: HoveredWorkspaceDeleteState, + target: HoveredWorkspaceDeleteTarget | null = resolveHoveredWorkspaceDeleteTarget(state), + dependencies: HoveredWorkspaceDeleteDependencies = { + deleteWorktree: runWorktreeDelete, + getCurrentState: useAppStore.getState + } +): boolean { + if (!target) { + return false + } + if (target.kind === 'folder') { + const pendingIdentity = composeWorktreeHostIdentity(target.executionHostId, target.workspaceKey) + if (pendingFolderDeletes.has(pendingIdentity)) { + return false + } + pendingFolderDeletes.add(pendingIdentity) + void state + .deleteFolderWorkspace(target.folderWorkspaceId, { + executionHostId: target.executionHostId + }) + .then((deleted) => { + const current = dependencies.getCurrentState() + if ( + deleted && + current.activeWorktreeId === target.workspaceKey && + current.activeWorkspaceExecutionHostId === target.executionHostId + ) { + current.setActiveWorktree(null) + } + }) + .finally(() => pendingFolderDeletes.delete(pendingIdentity)) + return true + } + dependencies.deleteWorktree(target.worktree.id, { + expectedInstanceId: target.worktree.instanceId, + ...(target.worktree.hostId ? { expectedHostId: target.worktree.hostId } : {}) + }) + return true +} diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index 333f5b51a69..f4700df44b3 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -8,7 +8,7 @@ import { getWorktreeMapFromState, getRepoMapFromState } from '@/store/selectors' import { applyUIZoom } from '@/lib/ui-zoom' import { activateAndRevealWorktree, activateAndRevealWorkspace } from '@/lib/worktree-activation' import { buildLinearIssueLinkedWorkItem } from '@/lib/linear-linked-work-item' -import { runWorktreeDelete } from '@/components/sidebar/delete-worktree-flow' +import { deleteHoveredWorkspaceImmediately } from '@/components/sidebar/hovered-workspace-delete' import { runSleepWorktree } from '@/components/sidebar/sleep-worktree-flow' import { createBackgroundSleepingAgentWakeDispatcher } from '@/lib/wake-sleeping-agents-in-background' import { TOGGLE_WORKSPACE_BOARD_EVENT } from '@/components/sidebar/useWorkspaceBoardPanel' @@ -1426,20 +1426,10 @@ export function useIpcEvents(): void { if (window.api.ui.onDeleteCurrentWorkspace) { unsubs.push( window.api.ui.onDeleteCurrentWorkspace(() => { - const store = useAppStore.getState() - if ( - store.activeModal !== 'none' || - store.activeView !== 'terminal' || - !store.activeWorktreeId - ) { + if (isFloatingWorkspacePanelFocused()) { return } - runWorktreeDelete( - store.activeWorktreeId, - store.activeWorkspaceExecutionHostId - ? { expectedHostId: store.activeWorkspaceExecutionHostId } - : {} - ) + deleteHoveredWorkspaceImmediately(useAppStore.getState()) }) ) } diff --git a/src/renderer/src/lib/worktree-runtime-owner-index.ts b/src/renderer/src/lib/worktree-runtime-owner-index.ts index 047976b4587..7bd0ebf2eba 100644 --- a/src/renderer/src/lib/worktree-runtime-owner-index.ts +++ b/src/renderer/src/lib/worktree-runtime-owner-index.ts @@ -54,7 +54,7 @@ type IndexedProjectGroupOwnerResolution = | { kind: 'missing' } | { kind: 'ambiguous' } -function catalogOwnerHostId(owner: { +export function getCatalogOwnerHostId(owner: { connectionId?: string | null executionHostId?: string | null }): ExecutionHostId { @@ -74,11 +74,11 @@ function buildCatalogOwnerIndex< const next = new Map() for (const record of records) { const id = record.id - const hostId = catalogOwnerHostId(record) + const hostId = getCatalogOwnerHostId(record) const current = next.get(id) if (!current) { next.set(id, { kind: 'resolved', owner: record }) - } else if (current.kind === 'resolved' && catalogOwnerHostId(current.owner) !== hostId) { + } else if (current.kind === 'resolved' && getCatalogOwnerHostId(current.owner) !== hostId) { next.set(id, { kind: 'ambiguous' }) } next.set(`${id}\0${hostId}`, { diff --git a/src/renderer/src/store/slices/folder-workspace-owner-routed-mutations.test.ts b/src/renderer/src/store/slices/folder-workspace-owner-routed-mutations.test.ts index 23e8a860706..b0298e76732 100644 --- a/src/renderer/src/store/slices/folder-workspace-owner-routed-mutations.test.ts +++ b/src/renderer/src/store/slices/folder-workspace-owner-routed-mutations.test.ts @@ -427,5 +427,39 @@ describe('folder workspace owner-routed mutations', () => { timeoutMs: 15_000 }) expect(folderWorkspacesDelete).not.toHaveBeenCalled() + expect(store.getState().folderWorkspaces).toEqual([]) + }) + + it('deletes only the host-qualified folder when ids collide', async () => { + const localFolder = makeFolderWorkspace({ executionHostId: 'local' }) + const runtimeFolder = makeFolderWorkspace({ executionHostId: 'runtime:env-owner' }) + runtimeEnvironmentCall.mockResolvedValue({ + id: 'rpc-delete-folder', + ok: true, + result: { deleted: true }, + _meta: { runtimeId: 'runtime-owner' } + }) + const store = createTestStore() + store.setState({ + activeWorktreeId: `folder:${runtimeFolder.id}`, + activeWorkspaceExecutionHostId: 'runtime:env-owner', + settings: { activeRuntimeEnvironmentId: 'env-owner' } as never, + projectGroups: [{ ...projectGroup, executionHostId: 'local' }], + folderWorkspaces: [localFolder, runtimeFolder] + }) + + await expect( + store + .getState() + .deleteFolderWorkspace(runtimeFolder.id, { executionHostId: 'runtime:env-owner' }) + ).resolves.toBe(true) + + expect(runtimeEnvironmentCall).toHaveBeenCalledWith({ + selector: 'env-owner', + method: 'folderWorkspace.delete', + params: { folderWorkspaceId: runtimeFolder.id }, + timeoutMs: 15_000 + }) + expect(store.getState().folderWorkspaces).toEqual([localFolder]) }) }) diff --git a/src/renderer/src/store/slices/repos.ts b/src/renderer/src/store/slices/repos.ts index f0fd6fcbae8..91cb7655790 100644 --- a/src/renderer/src/store/slices/repos.ts +++ b/src/renderer/src/store/slices/repos.ts @@ -112,6 +112,7 @@ import { getEnvironmentSshStateGeneration } from './runtime-environment-ssh' import { getRuntimeEnvironmentConnectionGeneration } from './runtime-status' import { findFolderWorkspaceOwner, + getExecutionHostIdForFolderWorkspace, getRuntimeEnvironmentIdForFolderWorkspace } from '@/lib/folder-workspace-runtime-owner' import { @@ -1908,7 +1909,10 @@ export type RepoSlice = { updates: FolderWorkspaceUpdates, options?: { executionHostId?: ExecutionHostId } ) => Promise - deleteFolderWorkspace: (folderWorkspaceId: string) => Promise + deleteFolderWorkspace: ( + folderWorkspaceId: string, + options?: { executionHostId?: ExecutionHostId } + ) => Promise // options.hostId targets a specific host's row + RPC target when the id exists on multiple hosts; else the group's own host owns the call. updateProjectGroup: ( groupId: string, @@ -2980,12 +2984,22 @@ export const createRepoSlice: StateCreator = (set, } }, - deleteFolderWorkspace: async (folderWorkspaceId) => { + deleteFolderWorkspace: async (folderWorkspaceId, options) => { const state = get() - if (!findFolderWorkspaceOwner(state, folderWorkspaceId)) { + const executionHostId = options?.executionHostId + if (!findFolderWorkspaceOwner(state, folderWorkspaceId, executionHostId)) { return false } - const runtimeEnvironmentId = getRuntimeEnvironmentIdForFolderWorkspace(state, folderWorkspaceId) + const ownerHostId = getExecutionHostIdForFolderWorkspace( + state, + folderWorkspaceId, + executionHostId + ) + const runtimeEnvironmentId = getRuntimeEnvironmentIdForFolderWorkspace( + state, + folderWorkspaceId, + executionHostId + ) try { // Why: deletion targets the folder's owner; focus may be on a different host. const target = getActiveRuntimeTarget({ activeRuntimeEnvironmentId: runtimeEnvironmentId }) @@ -3006,11 +3020,15 @@ export const createRepoSlice: StateCreator = (set, const workspaceKey = folderWorkspaceKey(folderWorkspaceId) set((s) => ({ folderWorkspaces: s.folderWorkspaces.filter( - (workspace) => workspace.id !== folderWorkspaceId + (workspace) => + workspace.id !== folderWorkspaceId || + getFolderWorkspaceHostId(workspace, s.projectGroups) !== ownerHostId ), folderWorkspacePathStatuses: {} })) - get().purgeWorktreeTerminalState([workspaceKey]) + if (!get().folderWorkspaces.some((workspace) => workspace.id === folderWorkspaceId)) { + get().purgeWorktreeTerminalState([workspaceKey]) + } return true } catch (err) { console.error('Failed to delete folder workspace:', err) diff --git a/src/shared/keybindings-parsing.test.ts b/src/shared/keybindings-parsing.test.ts index 32184076085..4b9dd99d658 100644 --- a/src/shared/keybindings-parsing.test.ts +++ b/src/shared/keybindings-parsing.test.ts @@ -144,6 +144,8 @@ describe('keybindings', () => { it('formats keybindings with platform labels', () => { expect(formatKeybindingList(['Mod+Shift+J'], 'darwin')).toBe('⌘⇧J') expect(formatKeybindingList(['Mod+Shift+J'], 'linux')).toBe('Ctrl+Shift+J') + expect(formatKeybindingList(['Mod+Shift+Backspace'], 'darwin')).toBe('⌘⇧⌫') + expect(formatKeybindingList(['Mod+Shift+Backspace'], 'linux')).toBe('Ctrl+Shift+Backspace') expect(formatKeybindingList([], 'win32')).toBe('Unassigned') }) diff --git a/src/shared/keybindings-unassigned-actions.test.ts b/src/shared/keybindings-unassigned-actions.test.ts index cb135f36bf3..007f1074bca 100644 --- a/src/shared/keybindings-unassigned-actions.test.ts +++ b/src/shared/keybindings-unassigned-actions.test.ts @@ -56,7 +56,7 @@ describe('keybindings', () => { ).toBe(true) }) - it('keeps workspace delete unassigned until users customize it', () => { + it('binds immediate workspace delete without claiming terminal split right', () => { const binding = { key: 'Backspace', code: 'Backspace', @@ -66,13 +66,28 @@ describe('keybindings', () => { shift: true } - expect(getEffectiveKeybindingsForAction('workspace.delete', 'linux')).toEqual([]) - expect(keybindingMatchesAction('workspace.delete', binding, 'linux')).toBe(false) + expect(getEffectiveKeybindingsForAction('workspace.delete', 'darwin')).toEqual([ + 'Mod+Shift+Backspace' + ]) + expect(getEffectiveKeybindingsForAction('workspace.delete', 'linux')).toEqual([ + 'Mod+Shift+Backspace' + ]) + expect(getEffectiveKeybindingsForAction('workspace.delete', 'win32')).toEqual([ + 'Mod+Shift+Backspace' + ]) + expect(keybindingMatchesAction('workspace.delete', binding, 'linux')).toBe(true) expect( keybindingMatchesAction('workspace.delete', binding, 'linux', { - 'workspace.delete': ['Mod+Shift+Backspace'] + 'workspace.delete': [] }) - ).toBe(true) + ).toBe(false) + expect( + keybindingMatchesAction( + 'workspace.delete', + { key: 'd', code: 'KeyD', control: false, meta: true, alt: true, shift: false }, + 'darwin' + ) + ).toBe(false) }) it('keeps workspace board unassigned until users customize it', () => { diff --git a/src/shared/keybindings.ts b/src/shared/keybindings.ts index 0beb3fa0faa..17f48be0159 100644 --- a/src/shared/keybindings.ts +++ b/src/shared/keybindings.ts @@ -293,8 +293,8 @@ export const KEYBINDING_DEFINITIONS: readonly KeybindingDefinition[] = [ 'remove', 'trash' ], - // Why: ship now without a default chord; user overrides still win when a future default is assigned. - defaultBindings: platformBindings([]), + // Why: Backspace avoids the terminal pane's D-based split shortcuts on every platform. + defaultBindings: platformBindings(['Mod+Shift+Backspace']), allowInTerminal: true }, { @@ -2281,7 +2281,7 @@ export function formatKeybinding(binding: string, platform: NodeJS.Platform): st if (parsed.shift) { parts.push(isMac ? '⇧' : 'Shift') } - parts.push(formatKeyToken(parsed.key)) + parts.push(formatKeyToken(parsed.key, isMac)) return parts } @@ -2317,7 +2317,7 @@ export function findKeybindingActionsForBinding( ).map((definition) => definition.id) } -function formatKeyToken(token: string): string { +function formatKeyToken(token: string, isMac: boolean): string { const labels: Record = { BracketLeft: '[', BracketRight: ']', @@ -2341,7 +2341,7 @@ function formatKeyToken(token: string): string { Quote: "'", Backquote: '`', Enter: 'Enter', - Backspace: 'Backspace', + Backspace: isMac ? '⌫' : 'Backspace', Delete: 'Delete', Insert: 'Insert', Tab: 'Tab', diff --git a/src/shared/window-shortcut-policy.test.ts b/src/shared/window-shortcut-policy.test.ts index 25e66e80366..77bc37a5cf9 100644 --- a/src/shared/window-shortcut-policy.test.ts +++ b/src/shared/window-shortcut-policy.test.ts @@ -377,7 +377,7 @@ describe('resolveWindowShortcutAction', () => { ).toEqual({ type: 'openTasks' }) }) - it('leaves workspace delete unbound by default but honors custom terminal-active bindings', () => { + it('resolves workspace delete by default and honors custom terminal-active bindings', () => { const input = { code: 'Backspace', key: 'Backspace', @@ -387,17 +387,18 @@ describe('resolveWindowShortcutAction', () => { shift: true } - expect(resolveWindowShortcutAction(input, 'linux')).toBeNull() + expect(resolveWindowShortcutAction(input, 'linux')).toEqual({ type: 'deleteCurrentWorkspace' }) + const customInput = { ...input, code: 'KeyX', key: 'x', alt: true, shift: false } expect( - resolveWindowShortcutAction(input, 'linux', { - 'workspace.delete': ['Mod+Shift+Backspace'] + resolveWindowShortcutAction(customInput, 'linux', { + 'workspace.delete': ['Mod+Alt+X'] }) ).toEqual({ type: 'deleteCurrentWorkspace' }) expect( resolveWindowShortcutAction( - input, + customInput, 'linux', - { 'workspace.delete': ['Mod+Shift+Backspace'] }, + { 'workspace.delete': ['Mod+Alt+X'] }, { context: 'terminal', terminalShortcutPolicy: 'terminal-first' } ) ).toEqual({ type: 'deleteCurrentWorkspace' }) diff --git a/src/shared/worktree/host-qualified-identity.test.ts b/src/shared/worktree/host-qualified-identity.test.ts index e0495aa19be..f6237005b28 100644 --- a/src/shared/worktree/host-qualified-identity.test.ts +++ b/src/shared/worktree/host-qualified-identity.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest' import { toRuntimeExecutionHostId, toSshExecutionHostId } from '../execution-host' import { composeWorktreeHostIdentity, + getExecutionHostIdFromWorktreeHostIdentity, getWorktreeHostIdentity, getWorktreeIdFromHostIdentity } from './host-qualified-identity' @@ -58,4 +59,29 @@ describe('worktree host identity', () => { expect(toSshExecutionHostId('we|rd')).not.toContain('|') expect(toRuntimeExecutionHostId('we|rd')).not.toContain('|') }) + + it('rejects identities without a host separator', () => { + expect(getExecutionHostIdFromWorktreeHostIdentity('ssh:build-box')).toBeUndefined() + }) + + // An unqualified row must not be assumed local: a destructive action keyed off + // this would then run against the wrong host. + it('leaves an unqualified identity without a host', () => { + expect( + getExecutionHostIdFromWorktreeHostIdentity( + composeWorktreeHostIdentity(undefined, WORKTREE_ID) + ) + ).toBeUndefined() + }) + + it('recovers the host from a qualified identity', () => { + expect( + getExecutionHostIdFromWorktreeHostIdentity(composeWorktreeHostIdentity('local', WORKTREE_ID)) + ).toBe('local') + expect( + getExecutionHostIdFromWorktreeHostIdentity( + composeWorktreeHostIdentity(toSshExecutionHostId('build-box'), WORKTREE_ID) + ) + ).toBe(toSshExecutionHostId('build-box')) + }) }) diff --git a/src/shared/worktree/host-qualified-identity.ts b/src/shared/worktree/host-qualified-identity.ts index 7e144c6336d..dcdc4411724 100644 --- a/src/shared/worktree/host-qualified-identity.ts +++ b/src/shared/worktree/host-qualified-identity.ts @@ -1,4 +1,5 @@ import type { ExecutionHostId } from '../execution-host' +import { parseExecutionHostId } from '../execution-host' import type { Worktree } from './types' /** @@ -38,6 +39,23 @@ export function composeWorktreeHostIdentity( return `${hostId ?? ''}${HOST_SEPARATOR}${worktreeId}` } +/** + * The host back out of an identity, when the identity names one. + * + * An empty prefix (`|`) stays undefined rather than defaulting to + * `local`: an unqualified row may be on any host, and callers use this to pick + * the host a destructive action runs against. + */ +export function getExecutionHostIdFromWorktreeHostIdentity( + identity: string +): ExecutionHostId | undefined { + const separatorIndex = identity.indexOf(HOST_SEPARATOR) + if (separatorIndex <= 0) { + return undefined + } + return parseExecutionHostId(identity.slice(0, separatorIndex))?.id +} + /** * The workspace id back out of an identity. * diff --git a/tests/e2e/worktree-delete-shortcut.spec.ts b/tests/e2e/worktree-delete-shortcut.spec.ts new file mode 100644 index 00000000000..29d4e1291c7 --- /dev/null +++ b/tests/e2e/worktree-delete-shortcut.spec.ts @@ -0,0 +1,76 @@ +import { test, expect } from './helpers/orca-app' +import { getAllWorktreeIds, waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { pressShortcut } from './helpers/shortcuts' +import { worktreeRow } from './worktree-row-locators' + +async function createIsolatedWorktree( + page: Parameters[0] +): Promise { + const name = `e2e-delete-shortcut-${Date.now()}` + return page.evaluate(async (worktreeName) => { + const state = window.__store?.getState() + if (!state?.activeWorktreeId) { + throw new Error('No active worktree to derive repo from') + } + const worktree = Object.values(state.worktreesByRepo) + .flat() + .find((candidate) => candidate.id === state.activeWorktreeId) + if (!worktree) { + throw new Error('Active worktree was not found') + } + + const result = await state.createWorktree(worktree.repoId, worktreeName) + await state.fetchWorktrees(worktree.repoId) + return result.worktree.id + }, name) +} + +test.describe('Worktree Delete Shortcut', () => { + let createdWorktreeId: string | null = null + + test.beforeEach(async ({ orcaPage }) => { + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + }) + + test.afterEach(async ({ orcaPage }) => { + if (!createdWorktreeId) { + return + } + const worktreeId = createdWorktreeId + createdWorktreeId = null + await orcaPage + .evaluate(async (id) => { + const state = window.__store?.getState() + await state?.removeWorktree( + { id, executionHostId: state.getKnownWorktreeById(id)?.hostId ?? null }, + true + ) + }, worktreeId) + .catch(() => undefined) + }) + + test('deletes the hovered worktree after Mod+Shift+Backspace confirmation', async ({ + orcaPage + }) => { + createdWorktreeId = await createIsolatedWorktree(orcaPage) + const worktreeId = createdWorktreeId + const row = worktreeRow(orcaPage, worktreeId) + await expect(row).toBeVisible() + + await row.hover() + await pressShortcut(orcaPage, 'Backspace', { shift: true }) + + const dialog = orcaPage.getByRole('dialog') + await expect(dialog).toBeVisible() + await dialog.getByRole('button', { name: 'Delete Workspace', exact: true }).click() + + await expect + .poll(async () => getAllWorktreeIds(orcaPage), { + timeout: 15_000, + message: 'hovered worktree was not removed by the delete shortcut' + }) + .not.toContain(worktreeId) + createdWorktreeId = null + }) +})