From 0680d9753ebd9c788ef15551f22f1ed039a74f04 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Mon, 9 Nov 2026 11:44:48 -0800 Subject: [PATCH 1/5] test: remove low-value browser, CLI and budget checks (#40459) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../scripts/ci/sharding/ci-shard-timings.json | 5 - src/cli/browser/browser.test.ts | 91 --------------- .../worker-list-run-scope.test.ts | 96 --------------- src/cli/index-worktree-wsl-selection.test.ts | 14 --- src/cli/worktree-selector-caller-host.test.ts | 30 ----- .../ReopenBrowserPageOnServerButton.test.tsx | 42 ------- .../annotate/markup-drawing-model.test.ts | 26 ----- .../annotate/useMarkupEditor.test.ts | 8 -- .../use-browser-chrome-tool-fold.test.tsx | 21 +--- ...er-client-hosted-download-notices.test.tsx | 103 ---------------- ...rowser-client-page-paint-retention.test.ts | 55 --------- .../browser-annotation-geometry.test.ts | 7 -- .../host-guest/browser-focus.test.ts | 20 ---- ...k-listener-command-code-transcript.test.ts | 110 +----------------- .../providers/jcode-turn-prompt.test.ts | 13 --- 15 files changed, 2 insertions(+), 639 deletions(-) delete mode 100644 src/cli/browser/browser.test.ts delete mode 100644 src/cli/handlers/orchestration/worker-list-run-scope.test.ts delete mode 100644 src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.test.tsx delete mode 100644 src/renderer/src/components/browser-pane/browser-client-hosted-download-notices.test.tsx delete mode 100644 src/renderer/src/components/browser-pane/browser-client-page-paint-retention.test.ts delete mode 100644 src/renderer/src/components/browser-pane/host-guest/browser-focus.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 396968458f5..ee0501b0119 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -311,7 +311,6 @@ "src/cli/automation-owner-conflict-recovery.test.ts": 448, "src/cli/automation-runs-paging.test.ts": 569, "src/cli/browser/browser-empty-values.test.ts": 313, - "src/cli/browser/browser.test.ts": 431, "src/cli/codex-command-classification.test.ts": 65, "src/cli/command-suggestion-budget.test.ts": 132, "src/cli/command-suggestion-destructive-families.test.ts": 226, @@ -353,7 +352,6 @@ "src/cli/handlers/orchestration/concise-list-row-size.test.ts": 492, "src/cli/handlers/orchestration/mutation-request.test.ts": 4146, "src/cli/handlers/orchestration/older-runtime-run-binding.test.ts": 547, - "src/cli/handlers/orchestration/worker-list-run-scope.test.ts": 495, "src/cli/handlers/orchestration/worker-output.test.ts": 79, "src/cli/handlers/orchestration/worker-start-implicit-coordinator.test.ts": 522, "src/cli/handlers/plugin-dev-watch.test.ts": 942, @@ -4735,7 +4733,6 @@ "src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.failure-remount.test.tsx": 3085, "src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.markup.test.tsx": 4575, "src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.test.tsx": 6541, - "src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.test.tsx": 497, "src/renderer/src/components/browser-pane/annotate/MarkupOverlay.test.tsx": 1124, "src/renderer/src/components/browser-pane/annotate/browser-annotation-output.test.ts": 74, "src/renderer/src/components/browser-pane/annotate/browser-grab-toast-owner-cleanup.test.tsx": 1007, @@ -4753,7 +4750,6 @@ "src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.retention-props.test.tsx": 3808, "src/renderer/src/components/browser-pane/assemble-chrome/use-browser-chrome-tool-fold.test.tsx": 307, "src/renderer/src/components/browser-pane/assemble-chrome/use-browser-page-find-shortcuts.test.tsx": 1874, - "src/renderer/src/components/browser-pane/browser-client-hosted-download-notices.test.tsx": 1020, "src/renderer/src/components/browser-pane/browser-client-page-attachment-scan-budget.test.ts": 464, "src/renderer/src/components/browser-pane/browser-client-page-metadata-publisher.test.ts": 315, "src/renderer/src/components/browser-pane/browser-client-page-profile-staging.test.ts": 434, @@ -4769,7 +4765,6 @@ "src/renderer/src/components/browser-pane/history/use-browser-history-shortcut.test.tsx": 1990, "src/renderer/src/components/browser-pane/host-guest/agent-input-focus-guard.test.ts": 228, "src/renderer/src/components/browser-pane/host-guest/browser-automation-visibility.test.ts": 45, - "src/renderer/src/components/browser-pane/host-guest/browser-focus.test.ts": 180, "src/renderer/src/components/browser-pane/host-guest/browser-guest-eviction-veto.test.ts": 1724, "src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-policy.test.ts": 2035, "src/renderer/src/components/browser-pane/host-guest/browser-page-evicted-guest-recovery.test.ts": 1839, diff --git a/src/cli/browser/browser.test.ts b/src/cli/browser/browser.test.ts deleted file mode 100644 index 6684f20fdeb..00000000000 --- a/src/cli/browser/browser.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as RuntimeTypes from '../runtime/types' - -const callMock = vi.fn() - -vi.mock('../runtime/types', () => { - class RuntimeClientError extends Error { - readonly code: string - - constructor(code: string, message: string) { - super(message) - this.code = code - } - } - - class RuntimeRpcFailureError extends RuntimeClientError { - readonly response: unknown - - constructor(response: unknown) { - super('runtime_error', 'runtime_error') - this.response = response - } - } - - return { RuntimeClientError, RuntimeRpcFailureError } -}) - -vi.mock('../runtime-client', async () => { - class RuntimeClient { - call = callMock - userDataPath = '/tmp/orca-dev-profile' - getCliStatus = vi.fn() - openOrca = vi.fn() - } - - const { RuntimeClientError, RuntimeRpcFailureError } = - await vi.importMock('../runtime/types') - - return { - RuntimeClient, - RuntimeClientError, - RuntimeRpcFailureError - } -}) - -import { main } from '../index' -import { okFixture, queueFixtures } from '../test-fixtures' - -describe('orca cli browser page targeting', () => { - beforeEach(() => { - callMock.mockReset() - }) - - afterEach(() => { - vi.restoreAllMocks() - vi.unstubAllEnvs() - }) - - it('saves screenshots where the CLI runs and prints the path instead of base64', async () => { - const screenshotDir = mkdtempSync(join(tmpdir(), 'orca-browser-shot-')) - vi.stubEnv('ORCA_BROWSER_SCREENSHOT_TMPDIR', screenshotDir) - queueFixtures( - callMock, - okFixture('req_shot', { data: Buffer.from('png-bytes').toString('base64'), format: 'png' }), - okFixture('req_unchanged', { data: '', format: 'png', changed: false }) - ) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - - try { - await main(['screenshot', '--page', 'page-1', '--json'], '/tmp/not-an-orca-worktree') - await main(['screenshot', '--page', 'page-1', '--if-changed'], '/tmp/not-an-orca-worktree') - - const saved = JSON.parse(String(log.mock.calls[0][0])).result - expect(saved.data).toBeUndefined() - expect(saved.path).toBe(join(screenshotDir, 'req_shot-screenshot.png')) - expect(readFileSync(saved.path, 'utf8')).toBe('png-bytes') - expect(callMock).toHaveBeenLastCalledWith('browser.screenshot', { - page: 'page-1', - ifChanged: true - }) - expect(log).toHaveBeenLastCalledWith( - 'Screenshot unchanged since the last --if-changed capture; nothing saved' - ) - } finally { - rmSync(screenshotDir, { recursive: true, force: true }) - } - }) -}) diff --git a/src/cli/handlers/orchestration/worker-list-run-scope.test.ts b/src/cli/handlers/orchestration/worker-list-run-scope.test.ts deleted file mode 100644 index 265fd666e04..00000000000 --- a/src/cli/handlers/orchestration/worker-list-run-scope.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ORCHESTRATION_HANDLERS } from '../orchestration' -import { okFixture } from '../../test-fixtures' - -type Call = { name: string; params: Record } - -describe('orchestration worker-list Run scope (CLI handler)', () => { - let calls: Call[] - let logged: string[] - let boundRun: string | null - - const client = { - call: async (name: string, params: Record) => { - calls.push({ name, params }) - if (name === 'orchestration.runCurrent') { - return okFixture('req_current', { run: boundRun ? { id: boundRun } : null }) - } - if (name === 'orchestration.workerList') { - return okFixture('req_list', { - workers: [], - counts: {}, - page: { hasMore: false, nextCursor: null, total: 0 } - }) - } - throw new Error(`unexpected call ${name}`) - } - } - - beforeEach(() => { - calls = [] - logged = [] - boundRun = null - vi.stubEnv('ORCA_TERMINAL_HANDLE', undefined) - vi.stubEnv('ORCA_AGENT_SESSION_ID', undefined) - vi.stubEnv('ORCA_STRUCTURED_SESSION', undefined) - vi.stubEnv('ORCA_PANE_KEY', undefined) - vi.spyOn(console, 'log').mockImplementation((line: string) => { - logged.push(line) - }) - }) - - afterEach(() => { - vi.restoreAllMocks() - vi.unstubAllEnvs() - }) - - async function list(flags = new Map(), json = true) { - await ORCHESTRATION_HANDLERS['orchestration worker-list']({ - flags, - client, - cwd: '/tmp/repo', - json - } as never) - expect(calls.map((call) => call.name)).toEqual( - flags.has('run') - ? ['orchestration.workerList'] - : ['orchestration.runCurrent', 'orchestration.workerList'] - ) - expect(logged).toHaveLength(1) - const listCall = calls.find((call) => call.name === 'orchestration.workerList') - const receipt: unknown = json ? JSON.parse(logged[0]) : null - return { listCall, receipt } - } - - it('defaults an unscoped list to the Run bound to the calling terminal', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_coord' - boundRun = 'run_bound' - - const { listCall, receipt } = await list() - - expect(calls[0]).toEqual({ name: 'orchestration.runCurrent', params: { from: 'term_coord' } }) - expect(listCall?.params.run).toBe('run_bound') - expect(receipt).toHaveProperty('result.scope', { run: 'run_bound', source: 'bound' }) - }) - - it('keeps --run as the override and never asks for the binding', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_coord' - boundRun = 'run_bound' - - const { listCall, receipt } = await list(new Map([['run', 'run_other']])) - - expect(calls.map((call) => call.name)).not.toContain('orchestration.runCurrent') - expect(listCall?.params.run).toBe('run_other') - expect(receipt).toHaveProperty('result.scope', { run: 'run_other', source: 'flag' }) - }) - - it('still lists every Run when the caller has no bound Run', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_unbound_shell' - boundRun = null - - const { listCall, receipt } = await list() - - expect(listCall?.params.run).toBeUndefined() - expect(receipt).toHaveProperty('result.scope', { source: 'all' }) - }) -}) diff --git a/src/cli/index-worktree-wsl-selection.test.ts b/src/cli/index-worktree-wsl-selection.test.ts index 119e8b12285..0da84286a57 100644 --- a/src/cli/index-worktree-wsl-selection.test.ts +++ b/src/cli/index-worktree-wsl-selection.test.ts @@ -21,20 +21,6 @@ const upper = buildWorktree(UPPER, 'main', 'abc', 'repo-a') const lower = buildWorktree(LOWER, 'main', 'abc', 'repo-b') describe('WSL enclosing selection with Windows path resolution on every platform', () => { - it.each([[UPPER, String.raw`\\wsl$\ubuntu\home\Alice\App\src`]])( - 'retains original identity for uppercase-tail aliases: %s', - (root, cwd) => { - const row = buildWorktree(root, 'main', 'abc', 'repo-a') - for (const caller of [undefined, row.id]) { - expect(selectEnclosingWorktreeSelectionOnHost([row], cwd, 'local', caller)).toEqual({ - selector: `id:${row.id}`, - worktreeId: row.id - }) - expect(selectEnclosingRepoOnHost([row], cwd, 'local', caller)).toBe('repo-a') - } - } - ) - it('excludes case-distinct directories before caller preference in either order', () => { for (const rows of [ [upper, lower], diff --git a/src/cli/worktree-selector-caller-host.test.ts b/src/cli/worktree-selector-caller-host.test.ts index d68e1d0b544..7dac5e4eca7 100644 --- a/src/cli/worktree-selector-caller-host.test.ts +++ b/src/cli/worktree-selector-caller-host.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' import { - getCallerExecutionHostId, selectEnclosingWorktreeOnHost, selectWorktreeIdOnHost } from './caller-host-worktree-selection' @@ -16,13 +15,6 @@ function row(hostId: 'local' | `ssh:${string}` | undefined, id: string, identity } } -const SSH_CALLER_D = { - ORCA_ORCHESTRATION_COMPATIBILITY_HOST_KIND: 'ssh', - ORCA_ORCHESTRATION_COMPATIBILITY_HOST_ID: 'host d', - ORCA_ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION: 'inc-1', - ORCA_ORCHESTRATION_COMPATIBILITY_ATTACHMENT: 'att-1' -} - const TWINS = [ row('ssh:host-a', `repo-a::${PATH}`), row('ssh:host%20d', `repo-d::${PATH}`), @@ -30,28 +22,6 @@ const TWINS = [ ] describe('implicit worktree selection is scoped to the caller host (#21210)', () => { - it('reads the caller host from the relay stamp, encoding the SSH target', () => { - expect(getCallerExecutionHostId(SSH_CALLER_D)).toBe('ssh:host%20d') - expect(getCallerExecutionHostId({})).toBe('local') - expect( - getCallerExecutionHostId({ - ORCA_ORCHESTRATION_COMPATIBILITY_HOST_KIND: 'wsl', - ORCA_ORCHESTRATION_COMPATIBILITY_HOST_ID: 'local', - ORCA_ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION: 'Ubuntu' - }) - ).toBe('local') - }) - - it("resolves an SSH caller's cwd to its own host's twin", () => { - const hostId = getCallerExecutionHostId(SSH_CALLER_D) - - expect(selectEnclosingWorktreeOnHost(TWINS, `${PATH}/src`, hostId)).toBe(`id:repo-d::${PATH}`) - }) - - it('resolves a caller with no host stamp to the local row only', () => { - expect(selectEnclosingWorktreeOnHost(TWINS, PATH, 'local')).toBe(`id:repo-l::${PATH}`) - }) - it('keeps a runtime-stamped local checkout for a local caller', () => { const rows = [ TWINS[0]!, diff --git a/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.test.tsx b/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.test.tsx deleted file mode 100644 index 7d802303a96..00000000000 --- a/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.test.tsx +++ /dev/null @@ -1,42 +0,0 @@ -// @vitest-environment happy-dom -import '@testing-library/jest-dom/vitest' -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' - -const reopenMocks = vi.hoisted(() => ({ reopenBrowserPageOnServer: vi.fn() })) - -vi.mock('./browser-reopen-on-server', () => ({ - reopenBrowserPageOnServer: reopenMocks.reopenBrowserPageOnServer -})) -vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) - -import { ReopenBrowserPageOnServerButton } from './ReopenBrowserPageOnServerButton' - -afterEach(() => { - cleanup() - vi.useRealTimers() - vi.clearAllMocks() -}) - -function renderButton(): HTMLElement { - render( - - ) - return screen.getByRole('button') -} - -describe('ReopenBrowserPageOnServerButton', () => { - it('rejects a second click while the first is still running', () => { - reopenMocks.reopenBrowserPageOnServer.mockImplementation(() => new Promise(() => {})) - const button = renderButton() - - fireEvent.click(button) - fireEvent.click(button) - - expect(reopenMocks.reopenBrowserPageOnServer).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/components/browser-pane/annotate/markup-drawing-model.test.ts b/src/renderer/src/components/browser-pane/annotate/markup-drawing-model.test.ts index 94844bd25a2..5ae19dbdab9 100644 --- a/src/renderer/src/components/browser-pane/annotate/markup-drawing-model.test.ts +++ b/src/renderer/src/components/browser-pane/annotate/markup-drawing-model.test.ts @@ -3,10 +3,7 @@ import { canRedo, commitShape, createMarkupDocument, - redoShape, - setShapes, undoShape, - type MarkupShape, type PenShape } from './markup-drawing-model' @@ -15,18 +12,6 @@ function pen(id: string): PenShape { } describe('markup document undo/redo', () => { - it('undoes and redoes in order', () => { - let doc = createMarkupDocument() - doc = commitShape(doc, pen('a')) - doc = commitShape(doc, pen('b')) - doc = undoShape(doc) - expect(doc.shapes.map((s) => s.id)).toEqual(['a']) - expect(canRedo(doc)).toBe(true) - doc = redoShape(doc) - expect(doc.shapes.map((s) => s.id)).toEqual(['a', 'b']) - expect(canRedo(doc)).toBe(false) - }) - it('forks history: committing after undo discards the redo stack', () => { let doc = createMarkupDocument() doc = commitShape(doc, pen('a')) @@ -36,15 +21,4 @@ describe('markup document undo/redo', () => { expect(doc.shapes.map((s) => s.id)).toEqual(['a', 'c']) expect(canRedo(doc)).toBe(false) }) - - it('undoes an edit (not just an add) via whole-list snapshots', () => { - let doc = commitShape(createMarkupDocument(), pen('a')) - doc = setShapes(doc, []) - expect(doc.shapes).toHaveLength(0) - doc = undoShape(doc) - expect(doc.shapes.map((s) => s.id)).toEqual(['a']) - }) }) - -const _exhaustive: MarkupShape['kind'][] = ['pen', 'highlight', 'arrow', 'rect', 'ellipse', 'text'] -void _exhaustive diff --git a/src/renderer/src/components/browser-pane/annotate/useMarkupEditor.test.ts b/src/renderer/src/components/browser-pane/annotate/useMarkupEditor.test.ts index a5c73a46513..579bbae50f0 100644 --- a/src/renderer/src/components/browser-pane/annotate/useMarkupEditor.test.ts +++ b/src/renderer/src/components/browser-pane/annotate/useMarkupEditor.test.ts @@ -63,14 +63,6 @@ describe('useMarkupEditor gestures', () => { return result } - it('commits a drawn stroke exactly once under StrictMode', () => { - const result = renderEditor({ wrapper: StrictMode }) - - drawLine(result, 0) - - expect(result.current.shapes).toHaveLength(1) - }) - it('erases the touched mark, hiding it from the export before release, and undo restores it', () => { const result = renderEditor({ wrapper: StrictMode }) drawLine(result, 0) diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/use-browser-chrome-tool-fold.test.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/use-browser-chrome-tool-fold.test.tsx index d72076ce9f7..2a8db973059 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/use-browser-chrome-tool-fold.test.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/use-browser-chrome-tool-fold.test.tsx @@ -3,11 +3,7 @@ import { act, cleanup, render } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { useRef } from 'react' import { BROWSER_CHROME_ADDRESS_SLOT_ATTRIBUTE } from './browser-chrome-address-slot' -import { - BROWSER_CHROME_ADDRESS_MIN_WIDTH_PX, - BROWSER_CHROME_FOLD_ORDER, - useBrowserChromeToolFold -} from './use-browser-chrome-tool-fold' +import { BROWSER_CHROME_FOLD_ORDER, useBrowserChromeToolFold } from './use-browser-chrome-tool-fold' const FIXED_WIDTH = 100 const TOOL_WIDTH = 30 @@ -70,22 +66,7 @@ function resizeTo(width: number): void { act(() => resizeCallbacks.forEach((callback) => callback())) } -function expectedFolded(width: number): number { - const room = width - FIXED_WIDTH - BROWSER_CHROME_ADDRESS_MIN_WIDTH_PX - const fits = Math.max(0, Math.floor(room / TOOL_WIDTH)) - return Math.max(0, BROWSER_CHROME_FOLD_ORDER.length - fits) -} - describe('useBrowserChromeToolFold', () => { - it('measures when a hidden row becomes visible', () => { - let folded = -1 - layout.rowWidth = 0 - render( (folded = count)} />) - - resizeTo(300) - expect(folded).toBe(expectedFolded(300)) - }) - it('discards measurements when the available tools change', () => { let folded = -1 layout.rowWidth = 300 diff --git a/src/renderer/src/components/browser-pane/browser-client-hosted-download-notices.test.tsx b/src/renderer/src/components/browser-pane/browser-client-hosted-download-notices.test.tsx deleted file mode 100644 index 0408984c7c7..00000000000 --- a/src/renderer/src/components/browser-pane/browser-client-hosted-download-notices.test.tsx +++ /dev/null @@ -1,103 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const toastMocks = vi.hoisted(() => ({ - loading: vi.fn(), - success: vi.fn(), - error: vi.fn() -})) - -vi.mock('sonner', () => ({ toast: toastMocks })) - -const store = vi.hoisted(() => { - const remoteBrowserPageHandlesByPageId: Record = {} - return { state: { remoteBrowserPageHandlesByPageId } } -}) -vi.mock('@/store', () => ({ useAppStore: { getState: () => store.state } })) - -import type { - BrowserDownloadFinishedEvent, - BrowserDownloadProgressEvent, - BrowserDownloadRequestedEvent -} from '../../../../shared/browser/guest-lifecycle/browser-guest-events' -import { paneChannel } from './client-hosted-browser-pane-test-rig' -import { useBrowserClientHostedDownloadNotices } from './browser-client-hosted-download-notices' - -let requested = paneChannel() -let progress = paneChannel() -let finished = paneChannel() - -beforeEach(() => { - requested = paneChannel() - progress = paneChannel() - finished = paneChannel() - store.state.remoteBrowserPageHandlesByPageId = { - 'page-a': { - environmentId: 'environment-a', - remotePageId: 'remote-page-a', - placement: { kind: 'client' } - } - } - Object.defineProperty(window, 'api', { - configurable: true, - value: { - browser: { - onDownloadRequested: requested.subscribe, - onDownloadProgress: progress.subscribe, - onDownloadFinished: finished.subscribe - } - } - }) -}) - -afterEach(() => { - cleanup() - vi.clearAllMocks() -}) - -function renderNotices(): void { - renderHook(useBrowserClientHostedDownloadNotices) -} - -function emitRequested(overrides: Partial = {}): void { - const event = { - browserPageId: 'page-a', - downloadId: 'download-1', - origin: 'https://example.internal', - filename: 'report.pdf', - totalBytes: 1024, - mimeType: 'application/pdf', - savePath: '/tmp/staging/download', - status: 'downloading', - ...overrides - } as BrowserDownloadRequestedEvent - act(() => requested.emit(event)) -} - -function emitFinished(overrides: Partial = {}): void { - const event = { - browserPageId: 'page-a', - downloadId: 'download-1', - status: 'completed', - savePath: null, - error: null, - ...overrides - } as BrowserDownloadFinishedEvent - act(() => finished.emit(event)) -} - -describe('client-hosted browser download notices', () => { - // Downloads outlive their panes; an unsettled loading toast has no close button. - it('settles the toast after the page that started the download is gone', () => { - renderNotices() - emitRequested() - store.state.remoteBrowserPageHandlesByPageId = {} - - emitFinished({ status: 'canceled' }) - - expect(toastMocks.error).toHaveBeenCalledWith('Download canceled.', { - id: 'browser-download:download-1' - }) - }) -}) diff --git a/src/renderer/src/components/browser-pane/browser-client-page-paint-retention.test.ts b/src/renderer/src/components/browser-pane/browser-client-page-paint-retention.test.ts deleted file mode 100644 index a216d32f047..00000000000 --- a/src/renderer/src/components/browser-pane/browser-client-page-paint-retention.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, expect, it, vi } from 'vitest' -import { setRemoteViewersForBrowserPage } from '../../lib/pane-manager/browser-remote-viewer-state' -import { - createRetainedHostFixture, - disposeRetainedHostFixtures -} from './browser-client-page-retained-host-fixture' - -afterEach(() => { - disposeRetainedHostFixtures() - setRemoteViewersForBrowserPage('page-a', false) - document.body.innerHTML = '' -}) - -it('keeps a streamed retained guest invisible and inert across desktop attach and detach', async () => { - const rig = createRetainedHostFixture() - await rig.mount() - setRemoteViewersForBrowserPage('page-a', true) - const host = rig.host() - expect(host.style.left).toBe('0px') - expect(Number.parseInt(host.style.width)).toBeGreaterThanOrEqual(320) - expect(host.style.opacity).toBe('0') - expect(host.inert).toBe(true) - expect(host.style.pointerEvents).toBe('none') - - const observer = new MutationObserver(() => {}) - observer.observe(host, { attributes: true }) - setRemoteViewersForBrowserPage('page-a', true) - expect(observer.takeRecords()).toHaveLength(0) - observer.disconnect() - - const attachment = rig.attach() - expect(host.style.opacity).toBe('') - expect(host.inert).toBe(false) - vi.spyOn(rig.container, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 0, 0)) - setRemoteViewersForBrowserPage('page-a', true) - expect(Number.parseInt(host.style.width)).toBeGreaterThanOrEqual(320) - expect(host.style.opacity).toBe('0') - attachment.detach() - host - .querySelector('webview')! - .dispatchEvent( - Object.assign(new Event('load-commit'), { url: 'about:blank', isMainFrame: true }) - ) - expect(host.style.visibility).toBe('') - expect(host.style.opacity).toBe('0') - expect(host.inert).toBe(true) - expect(host.style.pointerEvents).toBe('none') - - setRemoteViewersForBrowserPage('page-a', false) - expect(host.style.width).toBe('1px') - rig.registry.dispose() - setRemoteViewersForBrowserPage('page-a', true) - expect(host.style.width).toBe('1px') -}) diff --git a/src/renderer/src/components/browser-pane/describe-page/browser-annotation-geometry.test.ts b/src/renderer/src/components/browser-pane/describe-page/browser-annotation-geometry.test.ts index df05e189e5c..e8117da4faf 100644 --- a/src/renderer/src/components/browser-pane/describe-page/browser-annotation-geometry.test.ts +++ b/src/renderer/src/components/browser-pane/describe-page/browser-annotation-geometry.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from 'vitest' import type { BrowserGrabPayload } from '../../../../../shared/browser/element-grab/browser-grab-types' import { applyBrowserAnnotationViewportReport, - createBrowserAnnotationPayload, getBrowserOverlayAnchor, getLiveBrowserAnnotationRect } from './browser-annotation-geometry' @@ -80,12 +79,6 @@ describe('browser annotation geometry', () => { } ) }) - - it('strips screenshot bytes from persisted annotation payloads', () => { - const source = payload() - expect(createBrowserAnnotationPayload(source).screenshot).toBeNull() - expect(createBrowserAnnotationPayload(source).target.selector).toBe('button') - }) }) describe('browser annotation card follows the live element', () => { diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-focus.test.ts b/src/renderer/src/components/browser-pane/host-guest/browser-focus.test.ts deleted file mode 100644 index 71e1783f093..00000000000 --- a/src/renderer/src/components/browser-pane/host-guest/browser-focus.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { consumeBrowserFocusRequest, queueBrowserFocusRequest } from './browser-focus' - -describe('browser-focus', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it('expires unconsumed requests for pages that never mount', () => { - vi.useFakeTimers() - - queueBrowserFocusRequest({ pageId: 'page-stale', target: 'webview' }) - - vi.advanceTimersByTime(30_000) - - expect(consumeBrowserFocusRequest('page-stale')).toBeNull() - }) -}) diff --git a/src/shared/agent-hook-listener/normalization/agent-hook-listener-command-code-transcript.test.ts b/src/shared/agent-hook-listener/normalization/agent-hook-listener-command-code-transcript.test.ts index 5a2f0cbd836..33ee3c443a6 100644 --- a/src/shared/agent-hook-listener/normalization/agent-hook-listener-command-code-transcript.test.ts +++ b/src/shared/agent-hook-listener/normalization/agent-hook-listener-command-code-transcript.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { createHookListenerState, type HookListenerState } from '../listener-state' @@ -20,54 +20,6 @@ describe('shared agent-hook-listener', () => { vi.unstubAllEnvs() }) - it('reads the last assistant message behind an oversized line without quadratic copying', () => { - const tmpDir = mkdtempSync(join(tmpdir(), 'orca-assistant-huge-line-')) - const transcriptPath = join(tmpDir, 'transcript.jsonl') - const originalConcat = Buffer.concat - let concatenatedBytes = 0 - try { - // Multi-block lines must join once; per-block carry joins copy quadratic bytes. - const lineBytes = 2 * 1024 * 1024 - writeFileSync( - transcriptPath, - `${JSON.stringify({ - role: 'assistant', - content: [{ type: 'text', text: 'answer behind a huge line' }] - })}\n${JSON.stringify({ - role: 'user', - content: [{ type: 'text', text: 'x'.repeat(lineBytes) }] - })}\n` - ) - - Buffer.concat = ((list: readonly Uint8Array[], totalLength?: number) => { - const joined = originalConcat(list as Uint8Array[], totalLength) - concatenatedBytes += joined.length - return joined - }) as typeof Buffer.concat - - const done = normalizeHookPayload( - state, - 'claude', - { - paneKey: PANE_KEY, - tabId: 'tab-1', - worktreeId: 'wt', - env: 'production', - version: '1', - payload: { hook_event_name: 'Stop', transcript_path: transcriptPath } - }, - 'production' - ) - - expect(done?.payload.lastAssistantMessage).toBe('answer behind a huge line') - // Linear copies once (~lineBytes); the quadratic form copied many times that. - expect(concatenatedBytes).toBeLessThan(lineBytes * 4) - } finally { - Buffer.concat = originalConcat - rmSync(tmpDir, { recursive: true, force: true }) - } - }) - // Backward scanning must preserve boundary-spanning prompts, latest-user selection and absolute interaction offsets. it('reads a Command Code prompt that straddles the backward-scan chunk boundary', () => { const tmpDir = mkdtempSync(join(tmpdir(), 'orca-command-code-chunk-straddle-')) @@ -122,64 +74,4 @@ describe('shared agent-hook-listener', () => { rmSync(tmpDir, { recursive: true, force: true }) } }) - - it('ignores a Command Code prompt older than the transcript scan cap', () => { - const tmpDir = mkdtempSync(join(tmpdir(), 'orca-command-code-over-cap-')) - const transcriptPath = join(tmpDir, 'transcript.jsonl') - try { - // Put the only user line beyond 4MB so removing the read cap fails. - const filler = JSON.stringify({ - role: 'assistant', - content: [{ type: 'text', text: 'f'.repeat(64 * 1024) }] - }) - const lines = [ - JSON.stringify({ role: 'user', content: [{ type: 'text', text: 'ancient prompt' }] }) - ] - for (let index = 0; index < 80; index += 1) { - lines.push(filler) - } - writeFileSync(transcriptPath, `${lines.join('\n')}\n`) - expect(statSync(transcriptPath).size).toBeGreaterThan(4 * 1024 * 1024) - - const tool = normalizeHookPayload( - state, - 'command-code', - { - paneKey: PANE_KEY, - tabId: 'tab-1', - worktreeId: 'wt', - env: 'production', - version: '1', - payload: { - hook_event_name: 'PreToolUse', - transcript_path: transcriptPath, - tool_name: 'shell_command', - tool_input: { command: 'pwd' } - } - }, - 'production' - ) - - expect(tool?.payload).toMatchObject({ - state: 'working', - agentType: 'command-code', - prompt: '', - toolName: 'shell_command', - toolInput: 'pwd' - }) - writeFileSync(transcriptPath, `${lines[0]}\n`, { flag: 'a' }) - const recent = normalizeHookPayload( - createHookListenerState(), - 'command-code', - { - paneKey: PANE_KEY, - payload: { hook_event_name: 'PreToolUse', transcript_path: transcriptPath } - }, - 'production' - ) - expect(recent?.payload.prompt).toBe('ancient prompt') - } finally { - rmSync(tmpDir, { recursive: true, force: true }) - } - }) }) diff --git a/src/shared/agent-hook-listener/providers/jcode-turn-prompt.test.ts b/src/shared/agent-hook-listener/providers/jcode-turn-prompt.test.ts index 8244e0bf94b..a1ec6b923b6 100644 --- a/src/shared/agent-hook-listener/providers/jcode-turn-prompt.test.ts +++ b/src/shared/agent-hook-listener/providers/jcode-turn-prompt.test.ts @@ -23,19 +23,6 @@ describe('jcode turn prompt cache', () => { readMock.mockReturnValue({ text: 'ship it', interactionKey: 'k1' }) }) - it('reads the journal once per turn, not once per tool', () => { - readJcodeTurnPrompt(state, 'turn_start', 'pane-a', PAYLOAD) - for (let call = 0; call < 4; call += 1) { - readJcodeTurnPrompt(state, 'pre_tool', 'pane-a', PAYLOAD) - readJcodeTurnPrompt(state, 'post_tool', 'pane-a', PAYLOAD) - } - expect(readJcodeTurnPrompt(state, 'turn_end', 'pane-a', PAYLOAD)).toEqual({ - text: 'ship it', - interactionKey: 'k1' - }) - expect(readMock).toHaveBeenCalledTimes(1) - }) - it('re-reads on the next turn, so a new prompt is not served from the old turn', () => { const first = readJcodeTurnPrompt(state, 'turn_start', 'pane-a', PAYLOAD) expect(first).toEqual({ text: 'ship it', interactionKey: 'k1' }) From 6a69b2140e013e7389198a5012f8a3a93ff9aa45 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:52:19 -0800 Subject: [PATCH 2/5] fix(i18n): preserve web runtime error details (#40267) * fix(web): preserve runtime failure details * fix(i18n): update chat behavior settings hint --- src/renderer/src/i18n/locales/de.json | 2 +- src/renderer/src/i18n/locales/ru.json | 2 +- src/renderer/src/i18n/locales/tr.json | 2 +- src/renderer/src/i18n/locales/zh-Hant.json | 2 +- .../web-runtime-calls-connection-pin.test.ts | 27 +++++++++++++++++-- .../src/web/preload-api/web-runtime-calls.ts | 12 ++++----- 6 files changed, 34 insertions(+), 13 deletions(-) diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 65028d093a3..22a6ae4268b 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -2784,7 +2784,7 @@ "untitled": "Unbenannter Chat", "listLabel": "Chats, die fortgesetzt würden", "dontAskAgain": "Nicht erneut fragen (automatisch fortsetzen)", - "dontAskAgainHint": "Lässt sich unter Einstellungen → Experimentell → Chat-Oberfläche deaktivieren.", + "dontAskAgainHint": "Lässt sich unter Einstellungen → Chat → Verhalten deaktivieren.", "selectAgent": "{{value0}}-Chat „{{value1}}“ in {{value2}} fortsetzen", "dismissAll": "Alle verwerfen", "viewChats": "Chats anzeigen", diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index b46a9cc644d..ada9141abcb 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -2846,7 +2846,7 @@ "untitled": "Чат без названия", "listLabel": "Чаты, которые будут возобновлены", "dontAskAgain": "Больше не спрашивать (продолжать автоматически)", - "dontAskAgainHint": "Это можно отключить: Настройки → Экспериментальные → Интерфейс чата.", + "dontAskAgainHint": "Это можно отключить: Настройки → Чат → Поведение.", "selectAgent": "Возобновить чат {{value0}} «{{value1}}» в {{value2}}", "dismissAll": "Отклонить все", "viewChats": "Посмотреть чаты", diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index fc3aadad3ff..79b1047667c 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -2760,7 +2760,7 @@ "untitled": "Başlıksız sohbet", "listLabel": "Devam edilecek sohbetler", "dontAskAgain": "Bir daha sorma (otomatik devam et)", - "dontAskAgainHint": "Bu seçeneği Ayarlar → Deneysel → Sohbet Arayüzü bölümünden kapatabilirsiniz.", + "dontAskAgainHint": "Bu seçeneği Ayarlar → Sohbet → Davranış bölümünden kapatabilirsiniz.", "selectAgent": "{{value2}} içindeki \"{{value1}}\" adlı {{value0}} sohbetine devam et", "dismissAll": "Tümünü kapat", "viewChats": "Sohbetleri görüntüle", diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 1ab7c26c873..98f2098d45f 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -2726,7 +2726,7 @@ "untitled": "無標題聊天", "listLabel": "將恢復的聊天", "dontAskAgain": "不再詢問(自動恢復)", - "dontAskAgainHint": "您可以在「設定」→「實驗」→「聊天 UI」中關閉此功能。", + "dontAskAgainHint": "您可以在「設定」→「聊天」→「行為」中關閉此功能。", "selectAgent": "在 {{value2}} 中恢復 {{value0}} 聊天「{{value1}}」", "dismissAll": "全部關閉", "viewChats": "檢視聊天", diff --git a/src/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.ts b/src/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.ts index 4f25defa420..51ef1ad4cca 100644 --- a/src/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.ts +++ b/src/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.ts @@ -19,8 +19,11 @@ vi.mock('./web-runtime-session', () => ({ updateEnvironmentFromResponse: () => undefined })) -import { callEnvironmentEnvelope } from './web-runtime-calls' -import { RuntimeConnectionChangedBeforeSendError } from '../../runtime/rpc/calls/runtime-rpc-result' +import { callEnvironmentEnvelope, callRuntimeResult } from './web-runtime-calls' +import { + RuntimeConnectionChangedBeforeSendError, + RuntimeRpcCallError +} from '../../runtime/rpc/calls/runtime-rpc-result' describe('web runtime call pinned to the probed runtime', () => { beforeEach(() => { @@ -65,3 +68,23 @@ describe('web runtime call pinned to the probed runtime', () => { ) }) }) + +it('preserves runtime failure details for web callers', async () => { + session.client.call.mockResolvedValueOnce({ + id: 'rpc', + ok: false, + error: { + code: 'runtime_error', + message: 'Cannot add project', + data: { reason: 'windows_drive' } + } + }) + + const error = await callRuntimeResult('repo.add').catch((failure: unknown) => failure) + expect(error).toBeInstanceOf(RuntimeRpcCallError) + expect(error).toMatchObject({ + code: 'runtime_error', + message: 'Cannot add project', + response: { error: { data: { reason: 'windows_drive' } } } + }) +}) diff --git a/src/renderer/src/web/preload-api/web-runtime-calls.ts b/src/renderer/src/web/preload-api/web-runtime-calls.ts index d59c7abeb3b..e476a1d42af 100644 --- a/src/renderer/src/web/preload-api/web-runtime-calls.ts +++ b/src/renderer/src/web/preload-api/web-runtime-calls.ts @@ -1,4 +1,7 @@ -import { RuntimeConnectionChangedBeforeSendError } from '../../runtime/rpc/calls/runtime-rpc-result' +import { + RuntimeConnectionChangedBeforeSendError, + unwrapRuntimeRpcResult +} from '../../runtime/rpc/calls/runtime-rpc-result' import type { PreloadApi } from '../../../../preload/api-types' import type { WebRuntimeSubscribeOptions } from '../web-runtime-subscription-contract' import { parseExecutionHostId, toRuntimeExecutionHostId } from '../../../../shared/execution-host' @@ -159,12 +162,7 @@ export async function callRuntimeResult( params?: unknown, timeoutMs?: number ): Promise { - const response = await callRuntimeEnvelope(method, params, timeoutMs) - if (!response.ok) { - // Preserve error codes for recoverable-failure classification; human messages need not contain the token. - throw Object.assign(new Error(response.error.message), { code: response.error.code }) - } - return response.result as TResult + return unwrapRuntimeRpcResult(await callRuntimeEnvelope(method, params, timeoutMs)) } export async function callRuntimeResultWithOwner( From f5da9a9ff53ddd58860d2211c98c5761a7354682 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:55:11 +0000 Subject: [PATCH 3/5] feat(speech): commit dictation text at each pause with Silero VAD (#39378) Offline models write out the speech before each pause while recording goes on. Short noises and slow window-padded decodes are held off the pause cuts, a VAD error falls back to bounded chunks, and slow phrase decodes are judged per dictation against the time spoken. The VAD download carries legacy files and fetches after any GGUF model. --- config/main-sync-fs-baseline.txt | 1 + src/main/speech/model-download-catalog.ts | 28 ++- src/main/speech/model-manager.ts | 23 +-- src/main/speech/speech-vad-model.ts | 41 +++++ src/main/speech/stt-offline-audio-chunker.ts | 5 + src/main/speech/stt-recognizer.ts | 2 + src/main/speech/stt-service.test.ts | 38 +++-- src/main/speech/stt-session-start.ts | 6 +- .../speech/stt-transcribe-cpp-recognizer.ts | 160 +++++++++++++++--- .../speech/stt-vad-pause-segmenter.test.ts | 108 ++++++++++++ src/main/speech/stt-vad-pause-segmenter.ts | 159 +++++++++++++++++ 11 files changed, 517 insertions(+), 54 deletions(-) create mode 100644 src/main/speech/speech-vad-model.ts create mode 100644 src/main/speech/stt-vad-pause-segmenter.test.ts create mode 100644 src/main/speech/stt-vad-pause-segmenter.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 55df3070cc5..a4efe1beedc 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -498,6 +498,7 @@ 1 src/main/speech/speech-model-download-transport.ts 1 src/main/speech/speech-model-files.ts 2 src/main/speech/speech-model-http-download.ts +1 src/main/speech/speech-vad-model.ts 2 src/main/speech/stt-gpu-failure-marker.ts 2 src/main/sqlite/harden-database-files.ts 1 src/main/sqlite/row-cache/keyed-json-row-cache.ts diff --git a/src/main/speech/model-download-catalog.ts b/src/main/speech/model-download-catalog.ts index 0c5e4e73968..6d4b740976a 100644 --- a/src/main/speech/model-download-catalog.ts +++ b/src/main/speech/model-download-catalog.ts @@ -1,4 +1,4 @@ -import type { SpeechModelDownloadFile } from '../../shared/speech-types' +import type { SpeechModelDownloadFile, SpeechModelManifest } from '../../shared/speech-types' type DownloadFileSpec = readonly [name: string, sizeBytes: number, sha256: string] @@ -216,6 +216,32 @@ const MODEL_DOWNLOAD_FILES = { export type DownloadableSpeechModelId = keyof typeof MODEL_DOWNLOAD_FILES +/** What the model manager needs to download, verify and place one model's files. */ +export type SpeechModelDownload = Pick< + SpeechModelManifest, + 'id' | 'provider' | 'downloadFiles' | 'legacyDownloadFiles' | 'sizeBytes' +> + +const SILERO_VAD_FILES = huggingFaceFiles( + 'handy-computer/silero-vad-v6.2-gguf', + '97bbd75179f535e4708bccdf61e9278b8b60dfc7', + [ + [ + 'silero-vad-v6.2-F32.gguf', + 1_241_056, + '0d871a800c420fdd5d1b17a3aea4296d1c39608f0ff4a9295eb76457eb1c88e6' + ] + ] +) + +/** Silero VAD (MIT), which transcribe-cpp uses to find pauses; a helper download, never a dictation model. */ +export const SILERO_VAD_MODEL = { + id: 'silero-vad-v6.2', + provider: 'local', + downloadFiles: SILERO_VAD_FILES, + sizeBytes: SILERO_VAD_FILES.reduce((total, { sizeBytes }) => total + sizeBytes, 0) +} satisfies SpeechModelDownload + export function getSpeechModelDownloadMetadata(modelId: DownloadableSpeechModelId): { downloadFiles: SpeechModelDownloadFile[] files: string[] diff --git a/src/main/speech/model-manager.ts b/src/main/speech/model-manager.ts index 522e4525891..8e530065f6d 100644 --- a/src/main/speech/model-manager.ts +++ b/src/main/speech/model-manager.ts @@ -1,12 +1,10 @@ import { existsSync, mkdirSync, rmSync } from 'node:fs' import { rename, rm } from 'node:fs/promises' import { join, relative, resolve } from 'node:path' -import type { - SpeechModelManifest, - SpeechModelState, - SpeechModelStatus -} from '../../shared/speech-types' +import type { SpeechModelState, SpeechModelStatus } from '../../shared/speech-types' import { SPEECH_MODEL_CATALOG, getCatalogModel, isLocalSpeechModel } from './model-catalog' +import type { SpeechModelDownload } from './model-download-catalog' +import { downloadSileroVadInBackground, speechModelDownload } from './speech-vad-model' import { hasCloudSpeechCredentials } from './cloud-transcription-target' import { getSpeechModelCacheDirCandidates, @@ -99,12 +97,12 @@ export class ModelManager extends SpeechModelDownloadTransport { return cached } - const manifest = getCatalogModel(modelId) + const manifest = speechModelDownload(modelId) if (!manifest) { return { id: modelId, status: 'error', error: 'Unknown model' } } - if (!isLocalSpeechModel(manifest)) { + if (manifest.provider !== 'local') { const ready = this.hasCloudCredentials(manifest.provider) return { id: modelId, status: ready ? 'ready' : 'not-downloaded' } } @@ -127,7 +125,7 @@ export class ModelManager extends SpeechModelDownloadTransport { } private getSafeModelDir(modelId: string, root: string = this.modelsDir): string { - const manifest = getCatalogModel(modelId) + const manifest = speechModelDownload(modelId) if (!manifest) { throw new Error(`Unknown model: ${modelId}`) } @@ -146,11 +144,11 @@ export class ModelManager extends SpeechModelDownloadTransport { return } - const manifest = getCatalogModel(modelId) + const manifest = speechModelDownload(modelId) if (!manifest) { throw new Error(`Unknown model: ${modelId}`) } - if (!isLocalSpeechModel(manifest)) { + if (manifest.provider !== 'local') { throw new Error(`Model does not support downloads: ${modelId}`) } if (!manifest.downloadFiles?.length || !manifest.sizeBytes) { @@ -203,6 +201,9 @@ export class ModelManager extends SpeechModelDownloadTransport { await rm(modelDir, { recursive: true, force: true }) await rename(stagingDir, modelDir) this.updateState(modelId, 'ready') + if (getCatalogModel(modelId)?.files?.some((file) => file.endsWith('.gguf'))) { + downloadSileroVadInBackground(this) + } } catch (err) { if (!aborted) { console.error('[speech] Model download failed:', modelId, err) @@ -283,7 +284,7 @@ export class ModelManager extends SpeechModelDownloadTransport { } private async downloadModelFiles( - manifest: SpeechModelManifest, + manifest: SpeechModelDownload, stagingDir: string, modelId: string, isAborted: () => boolean, diff --git a/src/main/speech/speech-vad-model.ts b/src/main/speech/speech-vad-model.ts new file mode 100644 index 00000000000..5aa954a01b0 --- /dev/null +++ b/src/main/speech/speech-vad-model.ts @@ -0,0 +1,41 @@ +import { statSync } from 'node:fs' +import { join } from 'node:path' +import { getCatalogModel } from './model-catalog' +import { SILERO_VAD_MODEL, type SpeechModelDownload } from './model-download-catalog' +import type { ModelManager } from './model-manager' + +/** A catalog model, or the VAD helper the model manager downloads the same way but never lists. */ +export function speechModelDownload(modelId: string): SpeechModelDownload | undefined { + return modelId === SILERO_VAD_MODEL.id ? SILERO_VAD_MODEL : getCatalogModel(modelId) +} + +/** Fetch the VAD for later dictations; until it lands, offline text arrives at stop as before. */ +export function downloadSileroVadInBackground(models: Pick): void { + models.downloadModel(SILERO_VAD_MODEL.id).catch((error: unknown) => { + console.warn('[speech] Silero VAD download failed:', error) + }) +} + +// Settings never lists the VAD, so once its file is in place it stays; only a new models folder rechecks. +let verifiedVadPath: string | undefined + +/** The downloaded Silero VAD file; when it's missing, starts fetching it and returns undefined. */ +export function sileroVadModelPath( + models: Pick +): string | undefined { + const [file] = SILERO_VAD_MODEL.downloadFiles + const path = join(models.getModelDir(SILERO_VAD_MODEL.id), file.name) + if (path === verifiedVadPath) { + return path + } + try { + if (statSync(path).size === file.sizeBytes) { + verifiedVadPath = path + return path + } + } catch { + // Not downloaded yet, e.g. the model came before VAD support. + } + downloadSileroVadInBackground(models) + return undefined +} diff --git a/src/main/speech/stt-offline-audio-chunker.ts b/src/main/speech/stt-offline-audio-chunker.ts index 09b45586aac..d34be24ec33 100644 --- a/src/main/speech/stt-offline-audio-chunker.ts +++ b/src/main/speech/stt-offline-audio-chunker.ts @@ -18,6 +18,11 @@ export class OfflineAudioChunker { this.energyWindowSamples = Math.max(1, Math.round(SPLIT_ENERGY_WINDOW_SECONDS * sampleRate)) } + /** Samples pushed but not yet returned. */ + get heldSamples(): number { + return this.bufferedSamples + } + /** Return complete bounded chunks as samples arrive. */ push(samples: Float32Array): Float32Array[] { if (samples.length === 0) { diff --git a/src/main/speech/stt-recognizer.ts b/src/main/speech/stt-recognizer.ts index 66379b1ff3d..95a16492673 100644 --- a/src/main/speech/stt-recognizer.ts +++ b/src/main/speech/stt-recognizer.ts @@ -6,6 +6,8 @@ export type SttRecognizerInit = { sampleRate: number /** Absent = auto-detect. */ language?: string + /** Silero VAD GGUF; when present, offline models commit text at each pause. */ + vadModelPath?: string } export type SttRecognizerEvent = diff --git a/src/main/speech/stt-service.test.ts b/src/main/speech/stt-service.test.ts index aa2e80fd3a9..0990e7806de 100644 --- a/src/main/speech/stt-service.test.ts +++ b/src/main/speech/stt-service.test.ts @@ -1,4 +1,5 @@ import type { ModelManager } from './model-manager' +import type { SpeechModelState } from '../../shared/speech-types' import { beforeEach, describe, expect, it, vi } from 'vitest' const { @@ -136,12 +137,15 @@ const stoppedReply = (worker: InstanceType) => ({ streamId: worker.messages.findLast((message) => message.type === 'stop')?.streamId }) +const testModels = (models: Pick): ModelManager => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SttService reads getModelState and getModelDir, and fetches the VAD with downloadModel. + ({ ...models, downloadModel: vi.fn().mockResolvedValue(undefined) }) as never + const readyModels = (): ModelManager => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SttService reads only getModelState and getModelDir. - ({ + testModels({ getModelState: vi.fn().mockResolvedValue({ id: 'model-a', status: 'ready' }), getModelDir: vi.fn().mockReturnValue('/tmp/model-a') - }) as never + }) // Starting a session awaits the model check before it spawns the process. async function flushMicrotasks(): Promise { @@ -350,12 +354,11 @@ describe('SttService', () => { }) it('rebuilds the warm worker when the dictation language changes', async () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a local start reads only getModelState and getModelDir. const service = new SttService( - { + testModels({ getModelState: vi.fn().mockResolvedValue({ id: 'whisper-model', status: 'ready' }), getModelDir: vi.fn().mockReturnValue('/tmp/whisper-model') - } as never, + }), spawnMockWorker ) @@ -490,15 +493,15 @@ describe('SttService', () => { }) it('rejects deletion prep while the target model is starting', async () => { - let resolveModelState: (state: { id: string; status: string }) => void = () => {} - const modelStatePromise = new Promise<{ id: string; status: string }>((resolve) => { + let resolveModelState: (state: SpeechModelState) => void = () => {} + const modelStatePromise = new Promise((resolve) => { resolveModelState = resolve }) const service = new SttService( - { + testModels({ getModelState: vi.fn(() => modelStatePromise), getModelDir: vi.fn().mockReturnValue('/tmp/model-a') - } as never, + }), spawnMockWorker ) @@ -528,10 +531,10 @@ describe('SttService', () => { it('uses the OpenAI transcription session without creating a worker', async () => { const sink = vi.fn() const service = new SttService( - { + testModels({ getModelState: vi.fn().mockResolvedValue({ id: 'openai-model', status: 'ready' }), getModelDir: vi.fn().mockReturnValue('/tmp/model-a') - } as never, + }), spawnMockWorker ) @@ -815,10 +818,10 @@ describe('SttService', () => { status: modelStatus })) const service = new SttService( - { + testModels({ getModelState, getModelDir: vi.fn().mockReturnValue('/tmp/model-a') - } as never, + }), spawnMockWorker ) @@ -845,14 +848,15 @@ describe('SttService', () => { async (event) => { vi.useFakeTimers() try { - const models: Pick = { + const models: Pick = { getModelState: vi.fn().mockResolvedValue({ id: 'model-a', status: 'ready' }), - getModelDir: vi.fn().mockReturnValue('/tmp/model-a') + getModelDir: vi.fn().mockReturnValue('/tmp/model-a'), + downloadModel: vi.fn().mockResolvedValue(undefined) } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This lifecycle reads only getModelState/getModelDir on the model manager. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This lifecycle reads getModelState/getModelDir and downloadModel (VAD) on the model manager. const service = new SttService(models as ModelManager, spawnMockWorker) const sink = vi.fn() await service.startDictation('model-a', sink, undefined, 'desktop') diff --git a/src/main/speech/stt-session-start.ts b/src/main/speech/stt-session-start.ts index 619869ab03a..cd815fbc920 100644 --- a/src/main/speech/stt-session-start.ts +++ b/src/main/speech/stt-session-start.ts @@ -28,6 +28,7 @@ import { } from './stt-worker-startup' import { START_DICTATION_TIMEOUT_MS } from '../../shared/dictation-finish-deadlines' import { STT_WORKER_EXITED_ERROR } from './stt-worker-process' +import { sileroVadModelPath } from './speech-vad-model' export async function startSttDictation( state: SttSessionState, @@ -186,6 +187,8 @@ export function spawnSttEngine( if (!speechModulesDir) { throw new Error(LOCAL_SPEECH_UNAVAILABLE_ERROR) } + // A VAD fetched now serves the next engine start. + const vadModelPath = sileroVadModelPath(state.modelManager) clearSttIdleTeardownTimer(state) const worker = state.spawnWorker() const readyPromise = waitForSttWorkerReady(worker, START_DICTATION_TIMEOUT_MS) @@ -221,7 +224,8 @@ export function spawnSttEngine( modelDir: state.modelManager.getModelDir(config.modelId), sampleRate: manifest.sampleRate, files: manifest.files ?? [], - language: config.language + language: config.language, + vadModelPath }) return engine } diff --git a/src/main/speech/stt-transcribe-cpp-recognizer.ts b/src/main/speech/stt-transcribe-cpp-recognizer.ts index 24bed924fc2..578be1cc57e 100644 --- a/src/main/speech/stt-transcribe-cpp-recognizer.ts +++ b/src/main/speech/stt-transcribe-cpp-recognizer.ts @@ -4,6 +4,7 @@ import { pathToFileURL } from 'node:url' import type * as TranscribeCpp from 'transcribe-cpp' import { resampleToRate } from './stt-audio-resample' import { OfflineAudioChunker } from './stt-offline-audio-chunker' +import { VadPauseSegmenter } from './stt-vad-pause-segmenter' import type { SttRecognizer, SttRecognizerInit, SttRecognizerPost } from './stt-recognizer' // Past ~8 threads decode slowed 2-4x under load in the 2026-11 benchmark; E-cores and SMT siblings @@ -13,13 +14,69 @@ function performanceCoreThreads(): number { return Math.min(logical, 8, Math.max(4, Math.floor(logical / 2))) } +// Without the detector, audio is still cut at the decode bound, just not at pauses. +type AudioSegmenter = { + readonly heldSamples: number + push(samples: Float32Array): Float32Array[] | Promise + flush(): Float32Array[] | Promise +} + +function boundedChunks(sampleRate: number): AudioSegmenter { + const chunker = new OfflineAudioChunker(sampleRate) + return { + get heldSamples() { + return chunker.heldSamples + }, + push: (samples) => chunker.push(samples), + flush: () => { + const rest = chunker.flush() + return rest ? [rest] : [] + } + } +} + // Totals, not the nominal rate ratio: per-feed resampling rounds, and the drift would replay decoded audio. type StreamCoverage = { options: TranscribeCpp.TranscribeOptions - chunker: OfflineAudioChunker + segmenter: AudioSegmenter + vad: TranscribeCpp.VadSession | null inputSamples: number resampledSamples: number - decodedSamples: number + reportedSamples: number + slowPhraseDecodes: number +} + +// Whisper pads every decode to a 30 s window, so each phrase costs a full decode. Where that takes longer than the +// speech (and silence) it covers, per-pause decodes queue up behind the speaker, so that dictation stops cutting. +// Two in a row, so one slow first run or load spike doesn't. +const SLOW_PHRASE_DECODES_BEFORE_NO_CUTS = 2 + +// Dropped silence still counts as covered; report it so the host's replay buffer and stall watch don't grow through long pauses. +const SILENCE_COVERAGE_REPORT_SECONDS = 5 + +// Optional: without it dictation still works, with text only at the decode bound and at stop. +async function loadSileroVad( + transcribe: typeof TranscribeCpp, + path: string | undefined, + sampleRate: number +): Promise { + if (!path) { + return null + } + try { + // Tiny and per-frame; the CPU keeps it off a GPU that may fail over. + const model = await transcribe.TranscribeModel.load(path, { backend: 'cpu' }) + if (model.vadInfo.sampleRate === sampleRate) { + return model + } + console.warn( + `[speech] Silero VAD needs ${model.vadInfo.sampleRate} Hz; this model takes ${sampleRate} Hz` + ) + model.dispose() + } catch (error) { + console.warn('[speech] Silero VAD unavailable; text arrives at stop:', error) + } + return null } export async function createTranscribeCppRecognizer( @@ -52,7 +109,32 @@ export async function createTranscribeCppRecognizer( ? { ...baseOptions, prompt: `${vocabulary.toReversed().join(', ')}.` } : baseOptions const modelRate = model.capabilities.nativeSampleRate || init.sampleRate + const vadModel = await loadSileroVad(transcribe, init.vadModelPath, modelRate) const streams = new Map() + const openStream = (streamId: string, vocabulary: readonly string[]): StreamCoverage => { + // A VAD stream is per-dictation state, so each dictation gets its own session. + const vad = vadModel?.createVadSession({ nThreads: 1 }) ?? null + const stream: StreamCoverage = { + options: streamOptions(vocabulary), + segmenter: boundedChunks(modelRate), + vad, + inputSamples: 0, + resampledSamples: 0, + reportedSamples: 0, + slowPhraseDecodes: 0 + } + if (vad && vadModel) { + stream.segmenter = new VadPauseSegmenter( + vad, + modelRate, + vadModel.vadInfo.frameSamples, + () => stream.slowPhraseDecodes < SLOW_PHRASE_DECODES_BEFORE_NO_CUTS + ) + } + streams.get(streamId)?.vad?.dispose() + streams.set(streamId, stream) + return stream + } const transcribeChunk = async ( chunk: Float32Array, @@ -73,26 +155,55 @@ export async function createTranscribeCppRecognizer( await transcribeChunk(new Float32Array(Math.round(modelRate / 2)), baseOptions) // Coverage is in input-rate samples so the host can trim the audio it keeps for a CPU replay. - const decode = async (streamId: string, stream: StreamCoverage, chunk: Float32Array) => { - const text = await transcribeChunk(chunk, stream.options) - stream.decodedSamples += chunk.length + const report = (streamId: string, stream: StreamCoverage, text: string, undecoded: number) => { + const covered = stream.resampledSamples - stream.segmenter.heldSamples - undecoded + stream.reportedSamples = covered post({ type: 'chunk', streamId, - text: text.trim(), - samples: Math.round((stream.decodedSamples * stream.inputSamples) / stream.resampledSamples) + text, + samples: Math.round((covered * stream.inputSamples) / stream.resampledSamples) }) } - const openStream = (streamId: string, vocabulary: readonly string[]): StreamCoverage => { - const stream: StreamCoverage = { - options: streamOptions(vocabulary), - chunker: new OfflineAudioChunker(modelRate), - inputSamples: 0, - resampledSamples: 0, - decodedSamples: 0 + const decode = async (streamId: string, stream: StreamCoverage, chunks: Float32Array[]) => { + let undecoded = chunks.reduce((total, chunk) => total + chunk.length, 0) + for (const chunk of chunks) { + const startedAt = performance.now() + const text = await transcribeChunk(chunk, stream.options) + const decodeMs = performance.now() - startedAt + const spokenSince = stream.reportedSamples + undecoded -= chunk.length + report(streamId, stream, text.trim(), undecoded) + if (stream.vad) { + noteDecodeSpeed( + stream, + decodeMs, + ((stream.reportedSamples - spokenSince) / modelRate) * 1000 + ) + } } - streams.set(streamId, stream) + const dropped = stream.resampledSamples - stream.segmenter.heldSamples - stream.reportedSamples + if (dropped >= SILENCE_COVERAGE_REPORT_SECONDS * modelRate) { + report(streamId, stream, '', 0) + } + } + + const noteDecodeSpeed = (stream: StreamCoverage, decodeMs: number, spokenMs: number) => { + if (stream.slowPhraseDecodes >= SLOW_PHRASE_DECODES_BEFORE_NO_CUTS) { + return + } + stream.slowPhraseDecodes = decodeMs > spokenMs ? stream.slowPhraseDecodes + 1 : 0 + if (stream.slowPhraseDecodes === SLOW_PHRASE_DECODES_BEFORE_NO_CUTS) { + console.warn( + '[speech] Phrases decode slower than they are spoken; this dictation cuts only at 30 s' + ) + } + } + + const closeStream = (streamId: string): StreamCoverage | undefined => { + const stream = streams.get(streamId) + streams.delete(streamId) return stream } @@ -108,20 +219,21 @@ export async function createTranscribeCppRecognizer( ) stream.inputSamples += samples.length stream.resampledSamples += resampled.length - for (const chunk of stream.chunker.push(resampled)) { - await decode(streamId, stream, chunk) - } + await decode(streamId, stream, await stream.segmenter.push(resampled)) }, async finish(streamId) { - const stream = streams.get(streamId) - streams.delete(streamId) - const remaining = stream?.chunker.flush() - if (stream && remaining) { - await decode(streamId, stream, remaining) + const stream = closeStream(streamId) + if (!stream) { + return + } + try { + await decode(streamId, stream, await stream.segmenter.flush()) + } finally { + stream.vad?.dispose() } }, discard(streamId) { - streams.delete(streamId) + closeStream(streamId)?.vad?.dispose() } } } diff --git a/src/main/speech/stt-vad-pause-segmenter.test.ts b/src/main/speech/stt-vad-pause-segmenter.test.ts new file mode 100644 index 00000000000..0c9015361b2 --- /dev/null +++ b/src/main/speech/stt-vad-pause-segmenter.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest' +import { VadPauseSegmenter, type VadStream } from './stt-vad-pause-segmenter' + +// 100 Hz audio in 10-sample (0.1 s) frames; each sample holds its frame's speech probability, so outputs show which frames survived. +const RATE = 100 +const FRAME = 10 + +function fakeVad(): VadStream { + let pending: number[] = [] + let frames = 0 + const score = (flush: boolean) => { + const probs: number[] = [] + while (pending.length >= FRAME || (flush && pending.length > 0)) { + probs.push(pending[0]) + pending = pending.slice(FRAME) + } + const firstFrame = frames + frames = flush ? 0 : frames + probs.length + return { probs, firstFrame, segments: [] } + } + return { + streamFeed: async (pcm) => { + if (!(pcm instanceof Float32Array)) { + throw new Error('the segmenter feeds Float32Array') + } + pending.push(...pcm) + return score(false) + }, + streamFlush: async () => score(true) + } +} + +function audio(frames: number[]): Float32Array { + return Float32Array.from(frames.flatMap((probability) => Array(FRAME).fill(probability))) +} + +function framesOf(chunks: Float32Array[]): number[][] { + return chunks.map((chunk) => + Array.from( + chunk.filter((_, index) => index % FRAME === 0), + (value) => Math.round(value * 100) / 100 + ) + ) +} + +describe('VadPauseSegmenter', () => { + it('commits a phrase at a 0.6 s pause, keeps 0.4 s ahead of the next, and drops the silence between', async () => { + const segmenter = new VadPauseSegmenter(fakeVad(), RATE, FRAME) + const first = await segmenter.push(audio([0.1, 0.9, 0.8, 0.7, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2])) + expect(framesOf(first)).toEqual([[0.1, 0.9, 0.8, 0.7, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2]]) + expect(segmenter.heldSamples).toBe(0) + + const second = await segmenter.push(audio([0.1, 0.1, 0.1, 0.1, 0.1, 0.11, 0.12, 0.13, 0.14])) + expect(second).toEqual([]) + // Only the last 0.4 s of that silence is held as the next phrase's lead-in. + expect(segmenter.heldSamples).toBe(4 * FRAME) + + expect(await segmenter.push(audio([0.7, 0.6]))).toEqual([]) + expect(framesOf(await segmenter.flush())).toEqual([[0.11, 0.12, 0.13, 0.14, 0.7, 0.6]]) + }) + + it('keeps a phrase whole across a pause shorter than 0.6 s', async () => { + const segmenter = new VadPauseSegmenter(fakeVad(), RATE, FRAME) + const ready = await segmenter.push( + audio([0.9, 0.9, 0.2, 0.2, 0.2, 0.2, 0.2, 0.9, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2]) + ) + expect(framesOf(ready)).toEqual([ + [0.9, 0.9, 0.2, 0.2, 0.2, 0.2, 0.2, 0.9, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2] + ]) + }) + + it('holds a click shorter than 0.25 s of speech until real speech joins it', async () => { + const segmenter = new VadPauseSegmenter(fakeVad(), RATE, FRAME) + expect(await segmenter.push(audio([0.9, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2]))).toEqual([]) + const ready = await segmenter.push(audio([0.8, 0.8, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2])) + expect(framesOf(ready)).toEqual([ + [0.9, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.8, 0.8, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2] + ]) + }) + + it('returns nothing for a dictation that never had speech', async () => { + const segmenter = new VadPauseSegmenter(fakeVad(), RATE, FRAME) + expect(await segmenter.push(audio([0.1, 0.2, 0.3, 0.1]))).toEqual([]) + expect(await segmenter.flush()).toEqual([]) + expect(segmenter.heldSamples).toBe(0) + }) + + it('keeps every held sample when the detector fails mid-dictation', async () => { + const vad = fakeVad() + const segmenter = new VadPauseSegmenter( + { + streamFeed: async (pcm) => { + if (pcm instanceof Float32Array && pcm[0] === 0.5) { + throw new Error('vad failed') + } + return vad.streamFeed(pcm) + }, + streamFlush: vad.streamFlush + }, + RATE, + FRAME + ) + expect(await segmenter.push(audio([0.1, 0.2, 0.1, 0.1, 0.1, 0.9]))).toEqual([]) + expect(await segmenter.push(audio([0.5, 0.1]))).toEqual([]) + expect(await segmenter.push(audio([0.2]))).toEqual([]) + expect(framesOf(await segmenter.flush())).toEqual([[0.2, 0.1, 0.1, 0.1, 0.9, 0.5, 0.1, 0.2]]) + }) +}) diff --git a/src/main/speech/stt-vad-pause-segmenter.ts b/src/main/speech/stt-vad-pause-segmenter.ts new file mode 100644 index 00000000000..0212724b223 --- /dev/null +++ b/src/main/speech/stt-vad-pause-segmenter.ts @@ -0,0 +1,159 @@ +import type * as TranscribeCpp from 'transcribe-cpp' +import { OfflineAudioChunker } from './stt-offline-audio-chunker' + +// Silero's own defaults: a frame at or above this is speech; inside speech, one below the second is silence. +const SPEECH_PROBABILITY = 0.5 +const SILENCE_PROBABILITY = 0.35 +// A pause this long commits the phrase before it. Shorter cuts split phrases, and each piece gets its own capital and full stop. +export const VAD_PAUSE_SECONDS = 0.6 +// Silence kept ahead of detected speech so a soft first syllable isn't clipped. +const SPEECH_PREROLL_SECONDS = 0.4 +// Silero's minimum speech: a click or cough alone doesn't end a phrase; it waits for the speech after it, as without a detector. +const MIN_PHRASE_SPEECH_SECONDS = 0.25 + +export type VadStream = Pick + +/** + * Cuts one dictation's audio at pauses so an offline model can decode each phrase as it ends, and drops the + * silence between phrases. Phrases longer than the decode bound still split at their quietest point. + */ +export class VadPauseSegmenter { + private readonly phrase: OfflineAudioChunker + private readonly pauseFrames: number + private readonly minSpeechFrames: number + private readonly prerollSamples: number + private unscored: Float32Array = new Float32Array(0) + private preroll: Float32Array[] = [] + private prerollLength = 0 + private inSpeech = false + private speechFrames = 0 + private silentFrames = 0 + private vadFailed = false + + /** `cutsAtPauses` false: phrases end only at the decode bound and at stop, as without a detector. */ + constructor( + private readonly vad: VadStream, + sampleRate: number, + private readonly frameSamples: number, + private readonly cutsAtPauses: () => boolean = () => true + ) { + this.phrase = new OfflineAudioChunker(sampleRate) + this.pauseFrames = Math.ceil((VAD_PAUSE_SECONDS * sampleRate) / frameSamples) + this.minSpeechFrames = Math.ceil((MIN_PHRASE_SPEECH_SECONDS * sampleRate) / frameSamples) + this.prerollSamples = Math.round(SPEECH_PREROLL_SECONDS * sampleRate) + } + + /** Samples pushed but neither returned nor dropped as silence. */ + get heldSamples(): number { + return this.unscored.length + this.prerollLength + this.phrase.heldSamples + } + + /** Return the phrases that ended (or reached the decode bound) within these samples. */ + async push(samples: Float32Array): Promise { + if (this.vadFailed) { + return this.phrase.push(samples) + } + this.unscored = concat(this.unscored, samples) + try { + // The binding borrows the PCM until the call settles, so it gets its own copy. + return this.route((await this.vad.streamFeed(new Float32Array(samples))).probs) + } catch (error) { + return this.stopSegmenting(error) + } + } + + /** Return the rest of an open phrase; trailing silence is dropped. */ + async flush(): Promise { + let ready: Float32Array[] = [] + if (!this.vadFailed) { + try { + ready = this.route((await this.vad.streamFlush()).probs, true) + } catch (error) { + ready = this.stopSegmenting(error) + } + } + const rest = this.inSpeech ? this.phrase.flush() : null + this.inSpeech = false + this.preroll = [] + this.prerollLength = 0 + return rest ? [...ready, rest] : ready + } + + // A detector error must not cost the dictation: keep every held sample and finish as bounded chunks. + private stopSegmenting(error: unknown): Float32Array[] { + console.warn('[speech] Silero VAD failed mid-dictation; text arrives at stop:', error) + this.vadFailed = true + this.inSpeech = true + const ready: Float32Array[] = [] + for (const held of [...this.preroll, this.unscored]) { + ready.push(...this.phrase.push(held)) + } + this.preroll = [] + this.prerollLength = 0 + this.unscored = new Float32Array(0) + return ready + } + + private route(probs: readonly number[], last = false): Float32Array[] { + const ready: Float32Array[] = [] + let offset = 0 + for (const probability of probs) { + // The flushed last frame is zero padded past the real audio. + const end = Math.min(this.unscored.length, offset + this.frameSamples) + const frame = this.unscored.subarray(offset, end) + offset = end + if (!this.inSpeech && probability >= SPEECH_PROBABILITY) { + this.inSpeech = true + this.speechFrames = 0 + this.silentFrames = 0 + for (const held of this.preroll) { + ready.push(...this.phrase.push(held)) + } + this.preroll = [] + this.prerollLength = 0 + } + if (!this.inSpeech) { + this.holdPreroll(frame) + continue + } + ready.push(...this.phrase.push(frame)) + this.speechFrames += probability >= SPEECH_PROBABILITY ? 1 : 0 + this.silentFrames = probability < SILENCE_PROBABILITY ? this.silentFrames + 1 : 0 + if ( + this.silentFrames >= this.pauseFrames && + this.speechFrames >= this.minSpeechFrames && + this.cutsAtPauses() + ) { + this.inSpeech = false + const rest = this.phrase.flush() + if (rest) { + ready.push(rest) + } + } + } + this.unscored = last ? new Float32Array(0) : this.unscored.slice(offset) + return ready + } + + private holdPreroll(frame: Float32Array): void { + this.preroll.push(frame.slice()) + this.prerollLength += frame.length + while ( + this.preroll.length > 1 && + this.prerollLength - this.preroll[0].length >= this.prerollSamples + ) { + this.prerollLength -= this.preroll[0].length + this.preroll.shift() + } + } +} + +function concat(a: Float32Array, b: Float32Array): Float32Array { + if (a.length === 0) { + return b.slice() + } + const out = new Float32Array(a.length + b.length) + out.set(a) + out.set(b, a.length) + return out +} From cff5a151fcdb80b118d06c32d8d44c671f50d087 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Mon, 9 Nov 2026 11:58:10 -0800 Subject: [PATCH 4/5] test: remove low-value CLI, browser and E2E checks (#40466) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../scripts/ci/sharding/ci-shard-timings.json | 6 - .../handlers/data-account-commands.test.ts | 36 +-- .../orchestration-windows-ask-cli.test.ts | 109 --------- src/cli/index-file-open-headless.test.ts | 45 ---- src/cli/index-vm-recipe-doctor.test.ts | 107 --------- ...ion-structured-session-no-identity.test.ts | 11 - .../plugin-editor-check-loader-rules.test.ts | 8 - .../plugin-editor-check.test.ts | 10 +- .../plugin-release-entry.test.ts | 16 +- .../environment-pairing-exchange.test.ts | 7 - src/cli/runtime/environments.test.ts | 29 +-- .../orchestration-recovery-command.test.ts | 94 +------- src/cli/runtime/serve-install-hold.test.ts | 8 - .../runtime/serve-pairing-redaction.test.ts | 9 +- .../runtime/serve-supervisor-policy.test.ts | 17 -- ...pt-mutation-recovery-plugin-denied.test.ts | 22 -- .../browser-guest-paint-policy.test.ts | 40 ---- .../browser-page-guest-recovery.test.ts | 67 ------ .../windows-cmd-shim-resolution.test.ts | 28 --- src/shared/abort-signal-reason.test.ts | 27 +-- .../agent-cli-install-dir-fallback.test.ts | 22 -- .../reverse-file-region-scan.test.ts | 15 -- .../transcript-reader.test.ts | 29 --- .../agent-hook-endpoint-file.test.ts | 27 --- ...github-created-issue-start-prefill.spec.ts | 206 ------------------ 25 files changed, 7 insertions(+), 988 deletions(-) delete mode 100644 src/cli/handlers/orchestration-windows-ask-cli.test.ts delete mode 100644 src/cli/index-vm-recipe-doctor.test.ts delete mode 100644 src/cli/runtime/terminal-prompt-mutation-recovery-plugin-denied.test.ts delete mode 100644 src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-policy.test.ts delete mode 100644 src/shared/agent-hook-listener/transport/agent-hook-endpoint-file.test.ts delete mode 100644 tests/e2e/github-created-issue-start-prefill.spec.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index ee0501b0119..afd1ef5bf40 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -345,7 +345,6 @@ "src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts": 555, "src/cli/handlers/orchestration-lifecycle-rejection.test.ts": 781, "src/cli/handlers/orchestration-task-list-brief.test.ts": 494, - "src/cli/handlers/orchestration-windows-ask-cli.test.ts": 801, "src/cli/handlers/orchestration-worker-cli.test.ts": 706, "src/cli/handlers/orchestration.test.ts": 543, "src/cli/handlers/orchestration/agent-view.test.ts": 511, @@ -380,7 +379,6 @@ "src/cli/index-omitted-host-scope-selectors.test.ts": 6719, "src/cli/index-orchestration.test.ts": 659, "src/cli/index-terminal-commands.test.ts": 466, - "src/cli/index-vm-recipe-doctor.test.ts": 459, "src/cli/index-workspace-owner-choice-scaling.test.ts": 10154, "src/cli/index-workspace-owner-choice.test.ts": 1072, "src/cli/index-worktree-create-agent.test.ts": 582, @@ -441,7 +439,6 @@ "src/cli/runtime/serve-update-supervisor-gate.test.ts": 73, "src/cli/runtime/status-caller.test.ts": 488, "src/cli/runtime/status.test.ts": 1406, - "src/cli/runtime/terminal-prompt-mutation-recovery-plugin-denied.test.ts": 125, "src/cli/runtime/transport-framing.test.ts": 194, "src/cli/runtime/transport.test.ts": 462, "src/cli/runtime/types.test.ts": 62, @@ -4766,7 +4763,6 @@ "src/renderer/src/components/browser-pane/host-guest/agent-input-focus-guard.test.ts": 228, "src/renderer/src/components/browser-pane/host-guest/browser-automation-visibility.test.ts": 45, "src/renderer/src/components/browser-pane/host-guest/browser-guest-eviction-veto.test.ts": 1724, - "src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-policy.test.ts": 2035, "src/renderer/src/components/browser-pane/host-guest/browser-page-evicted-guest-recovery.test.ts": 1839, "src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts": 515, "src/renderer/src/components/browser-pane/host-guest/browser-page-registration-ownership.test.ts": 2197, @@ -7102,7 +7098,6 @@ "src/shared/agent-cli-install-dir-fallback.test.ts": 130, "src/shared/agent-launch/startup/agent-command-line-intent.test.ts": 95, "src/shared/agent-status/title/agent-detection.test.ts": 188, - "src/shared/agent-hook-listener/transport/agent-hook-endpoint-file.test.ts": 58, "src/shared/agent-hook-listener/transport/agent-hook-endpoint-temp-cleanup.test.ts": 55, "src/shared/agent-hook-listener/normalization/agent-hook-listener-claude-elicitation.test.ts": 229, "src/shared/agent-hook-listener/normalization/agent-hook-listener-codex-approval-ownership.test.ts": 258, @@ -8262,7 +8257,6 @@ "tests/e2e/git-history-tooltip-wrap.spec.ts": 22900, "tests/e2e/git-no-upstream-polling-churn.spec.ts": 22600, "tests/e2e/github-cli-stall-repro.spec.ts": 18200, - "tests/e2e/github-created-issue-start-prefill.spec.ts": 43100, "tests/e2e/github-url-smart-input-transition.spec.ts": 58200, "tests/e2e/golden-agent-tui-launch.spec.ts": 27300, "tests/e2e/golden-core-flows.spec.ts": 91100, diff --git a/src/cli/handlers/data-account-commands.test.ts b/src/cli/handlers/data-account-commands.test.ts index 7a4ae5d7bad..b0d881fe4e6 100644 --- a/src/cli/handlers/data-account-commands.test.ts +++ b/src/cli/handlers/data-account-commands.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { existsSync } from 'node:fs' import { dirname, join } from 'node:path' import { tmpdir } from 'node:os' -import { parseArgs, REPEATED_FLAG_SEPARATOR, specPaths } from '../args' +import { parseArgs, specPaths } from '../args' import { ACCOUNT_COMMAND_SPECS } from '../specs/account' import { RuntimeClient } from '../runtime-client' import { DATA_ACCOUNT_RUNTIME_CAPABILITY } from '../../shared/account-runtime-capabilities' @@ -61,40 +61,6 @@ describe('managed data account enrollment', () => { expect(existsSync(directory)).toBe(false) }) - it('passes OpenCode login method and answers before the standalone flag', async () => { - vi.spyOn(client, 'call') - .mockResolvedValueOnce({ - id: 'test', - ok: true, - result: { capabilities: [DATA_ACCOUNT_RUNTIME_CAPABILITY] }, - _meta: { runtimeId: 'test' } - }) - .mockRejectedValueOnce(new Error('capture failed')) - const login = vi.fn(async (_command: string, args: string[]) => { - expect(args).toEqual([ - 'auth', - 'login', - 'github-copilot', - '--method', - ' device ', - '--answer', - 'deploymentType=github.com', - '--answer', - 'note name=a=b', - '--standalone' - ]) - }) - const flags = new Map([ - ['integration', 'github-copilot'], - ['method', ' device '], - ['answer', ['deploymentType=github.com', 'note name=a=b'].join(REPEATED_FLAG_SEPARATOR)] - ]) - await expect(addDataAccount({ ...context, flags }, 'opencode', login)).rejects.toThrow( - 'capture failed' - ) - expect(login).toHaveBeenCalledOnce() - }) - it.each([ ['devin', new Map([['method', 'device']]), 'only supported with --agent opencode'], ['opencode', new Map([['method', ' ']]), '--method requires'], diff --git a/src/cli/handlers/orchestration-windows-ask-cli.test.ts b/src/cli/handlers/orchestration-windows-ask-cli.test.ts deleted file mode 100644 index 70cfc10c35f..00000000000 --- a/src/cli/handlers/orchestration-windows-ask-cli.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const callMock = vi.fn() -const originalCliCommand = process.env.ORCA_CLI_COMMAND -const originalPackagedLauncher = process.env.ORCA_WINDOWS_PACKAGED_CLI_LAUNCHER -const originalTerminalHandle = process.env.ORCA_TERMINAL_HANDLE -const originalExitCode = process.exitCode - -vi.mock('../format', () => ({ printResult: vi.fn() })) -vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() })) - -import { ORCHESTRATION_HANDLERS } from './orchestration' - -describe('packaged Windows legacy ask protocol', () => { - beforeEach(() => { - callMock.mockReset() - process.env.ORCA_WINDOWS_PACKAGED_CLI_LAUNCHER = '1' - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - process.exitCode = undefined - }) - - afterEach(() => { - vi.restoreAllMocks() - process.exitCode = originalExitCode - restoreEnv('ORCA_CLI_COMMAND', originalCliCommand) - restoreEnv('ORCA_WINDOWS_PACKAGED_CLI_LAUNCHER', originalPackagedLauncher) - restoreEnv('ORCA_TERMINAL_HANDLE', originalTerminalHandle) - }) - - it.each(['orca', 'orca-ide'] as const)( - 'commits with the %s launcher and exits 75 before resume', - async (command) => { - process.env.ORCA_CLI_COMMAND = command - callMock.mockResolvedValue({ - result: { - answer: null, - messageId: 'msg_question', - threadId: 'msg_question', - timedOut: false, - legacyCompatibility: { - resumeRequired: true, - resumeCommand: `${command} orchestration ask --resume msg_question` - } - } - }) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await invokeAsk(new Map([['question', 'Proceed?']])) - - expect(callMock).toHaveBeenCalledWith( - 'orchestration.ask', - expect.objectContaining({ - question: 'Proceed?', - resume: undefined, - compatibilityWindowsCommand: command - }), - expect.any(Object) - ) - expect(log.mock.calls.map(([line]) => line)).toEqual([ - `Question msg_question committed.\nNext: Resume with: ${command} orchestration ask --resume msg_question` - ]) - expect(process.exitCode).toBe(75) - } - ) - - it('resumes the committed question without another exit-75 handoff', async () => { - process.env.ORCA_CLI_COMMAND = 'orca' - callMock.mockResolvedValue({ - result: { - answer: 'yes', - messageId: 'msg_question', - threadId: 'msg_question', - timedOut: false - } - }) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await invokeAsk(new Map([['resume', 'msg_question']])) - - expect(callMock).toHaveBeenCalledWith( - 'orchestration.ask', - expect.objectContaining({ - question: undefined, - resume: 'msg_question', - compatibilityWindowsCommand: 'orca' - }), - expect.any(Object) - ) - expect(log).toHaveBeenCalledWith('yes') - expect(process.exitCode).toBeUndefined() - }) -}) - -function invokeAsk(flags: Map): Promise { - return ORCHESTRATION_HANDLERS['orchestration ask']({ - flags, - client: { call: callMock }, - cwd: '/tmp/repo', - json: false - } as never) -} - -function restoreEnv(name: string, value: string | undefined): void { - if (value === undefined) { - delete process.env[name] - } else { - process.env[name] = value - } -} diff --git a/src/cli/index-file-open-headless.test.ts b/src/cli/index-file-open-headless.test.ts index 58bf2e6b061..3c0a9044a47 100644 --- a/src/cli/index-file-open-headless.test.ts +++ b/src/cli/index-file-open-headless.test.ts @@ -38,36 +38,6 @@ describe('file commands on a server with no app window', () => { vi.spyOn(console, 'error').mockImplementation(() => {}) }) - it('explains the refusal instead of printing the raw token', async () => { - mocks.callMock.mockRejectedValueOnce(headlessRefusal()) - - await main(['file', 'open', 'src/App.tsx', '--worktree', 'id:wt-1'], '/tmp/repo') - - const printed = String(vi.mocked(console.error).mock.calls[0]?.[0]) - expect(printed).toContain('This Orca server has no app window') - expect(printed).toContain('Next step: Open the file from the file explorer') - expect(printed.split('\n')[0]).not.toBe('renderer_unavailable') - expect(process.exitCode).toBe(1) - }) - - it('keeps a stable code and recovery in --json output', async () => { - mocks.callMock.mockRejectedValueOnce(headlessRefusal()) - - await main( - ['file', 'diff', 'src/App.tsx', '--worktree', 'id:wt-1', '--focus', '--json'], - '/tmp/repo' - ) - - const output = JSON.parse(String(vi.mocked(console.log).mock.calls[0]?.[0])) - expect(output.ok).toBe(false) - expect(output.error.code).toBe('renderer_unavailable') - expect(output.error.message).toContain('no app window') - expect(output.error.data.nextSteps).toEqual([ - expect.stringContaining('file explorer'), - expect.stringContaining('path in your reply') - ]) - }) - it('stops open-changed at the first refusal with the same explanation', async () => { mocks.callMock .mockResolvedValueOnce( @@ -94,19 +64,4 @@ describe('file commands on a server with no app window', () => { 'This Orca server has no app window' ) }) - - it('leaves other runtime errors untouched', async () => { - mocks.callMock.mockRejectedValueOnce( - new RuntimeRpcFailureError({ - id: 'req_open', - ok: false, - error: { code: 'runtime_error', message: 'chat_scratch_not_openable' }, - _meta: { runtimeId: 'runtime-1' } - }) - ) - - await main(['file', 'open', 'src/App.tsx', '--worktree', 'id:wt-1'], '/tmp/repo') - - expect(String(vi.mocked(console.error).mock.calls[0]?.[0])).toBe('chat_scratch_not_openable') - }) }) diff --git a/src/cli/index-vm-recipe-doctor.test.ts b/src/cli/index-vm-recipe-doctor.test.ts deleted file mode 100644 index f78075805b5..00000000000 --- a/src/cli/index-vm-recipe-doctor.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import path from 'node:path' -import { chmodSync, mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { describe, expect, it, vi } from 'vitest' - -const { - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -} = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), - addEnvironmentFromPairingCodeMock: vi.fn(), - listEnvironmentsMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') - return createRuntimeClientModuleMock({ - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock - }) -}) - -vi.mock('./runtime/environments', () => ({ - addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, - removeEnvironment: vi.fn(), - resolveEnvironment: vi.fn() -})) - -vi.mock('../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - listEnvironments: listEnvironmentsMock -})) - -vi.mock('child_process', async () => { - const { createChildProcessModuleMock } = await import('./index-test-harness.js') - return createChildProcessModuleMock(spawnMock) -}) - -import { main } from './index' -import { useWorktreeAwarenessEnvironment } from './index-test-harness' - -describe('orca cli worktree awareness', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - - it('runs vm recipe doctor locally without contacting the app runtime', async () => { - const repoPath = mkdtempSync(path.join(tmpdir(), 'orca-vm-doctor-')) - try { - mkdirSync(path.join(repoPath, 'scripts', 'orca-vm'), { recursive: true }) - const startScript = path.join(repoPath, 'scripts', 'orca-vm', 'start.sh') - const cleanupScript = path.join(repoPath, 'scripts', 'orca-vm', 'cleanup.sh') - writeFileSync(startScript, '#!/bin/sh\n') - writeFileSync(cleanupScript, '#!/bin/sh\n') - chmodSync(startScript, 0o755) - chmodSync(cleanupScript, 0o755) - writeFileSync( - path.join(repoPath, 'orca.yaml'), - [ - 'environmentRecipes:', - ' - id: cloud-sandbox', - ' name: Cloud Sandbox', - ' create: ./scripts/orca-vm/start.sh', - ' destroy: ./scripts/orca-vm/cleanup.sh' - ].join('\n') - ) - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['vm', 'recipe', 'doctor', 'cloud-sandbox', '--repo-path', repoPath, '--json']) - - const output = JSON.parse(String(logSpy.mock.calls[0][0])) as { - ok: boolean - checks: { id: string; status: string }[] - } - if (!output.ok) { - throw new Error(JSON.stringify(output)) - } - expect(output.ok).toBe(true) - expect(output.checks).toEqual( - expect.arrayContaining([ - expect.objectContaining({ id: 'orca_yaml.parse', status: 'pass' }), - expect.objectContaining({ id: 'recipe.exists', status: 'pass' }), - expect.objectContaining({ id: 'recipe.create', status: 'pass' }), - expect.objectContaining({ id: 'recipe.destroy', status: 'pass' }) - ]) - ) - expect(callMock).not.toHaveBeenCalled() - } finally { - rmSync(repoPath, { recursive: true, force: true }) - } - }) -}) diff --git a/src/cli/orchestration-structured-session-no-identity.test.ts b/src/cli/orchestration-structured-session-no-identity.test.ts index 2a268aeec50..566dd31e6ab 100644 --- a/src/cli/orchestration-structured-session-no-identity.test.ts +++ b/src/cli/orchestration-structured-session-no-identity.test.ts @@ -75,15 +75,4 @@ describe('a structured chat session with no orchestration identity', () => { expect.objectContaining({ terminal: 'structworker_self' }) ) }) - - it('leaves an ordinary shell alone, which has no marker and may still guess', async () => { - delete process.env[ORCA_STRUCTURED_SESSION_ENV] - callMock.mockResolvedValue({ result: { messages: [], count: 0 } }) - await invoke('orchestration check') - expect(getTerminalHandleMock).toHaveBeenCalled() - expect(callMock).toHaveBeenCalledWith( - 'orchestration.check', - expect.objectContaining({ terminal: 'term_sibling' }) - ) - }) }) diff --git a/src/cli/plugin-authoring/plugin-editor-check-loader-rules.test.ts b/src/cli/plugin-authoring/plugin-editor-check-loader-rules.test.ts index 83061a44e06..1cc3b0ae3ac 100644 --- a/src/cli/plugin-authoring/plugin-editor-check-loader-rules.test.ts +++ b/src/cli/plugin-authoring/plugin-editor-check-loader-rules.test.ts @@ -109,12 +109,4 @@ describe('orca plugin check: editors load as the frame protocol serves them', () expect(result.issues).toEqual([]) expect(result.files).toContain('editor/my script.js') }) - - it('lets a dependency reach the 16 MiB the protocol serves, past the 10 MiB entry cap', async () => { - const root = await editorWith({ - 'editor/index.html': page(''), - 'editor/vendor.mjs': `export const x = 1\n//${'x'.repeat(11 * 1024 * 1024)}\n` - }) - expect((await check(root)).issues).toEqual([]) - }) }) diff --git a/src/cli/plugin-authoring/plugin-editor-check.test.ts b/src/cli/plugin-authoring/plugin-editor-check.test.ts index 44e53ba2bdb..f39e207ba25 100644 --- a/src/cli/plugin-authoring/plugin-editor-check.test.ts +++ b/src/cli/plugin-authoring/plugin-editor-check.test.ts @@ -2,7 +2,7 @@ import { appendFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/pro import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { checkPluginEditors, formatPluginEditorCheck } from './plugin-editor-check' +import { checkPluginEditors } from './plugin-editor-check' import { createPluginFromTemplate } from './plugin-create' import { validatePluginTarget } from './plugin-folder-validation' import { checkPluginDevFolder } from '../plugin-dev-watch/plugin-dev-watch-check' @@ -37,14 +37,6 @@ async function editorPlugin(): Promise { } describe('orca plugin check: custom editors', () => { - it('passes the editor template and follows its script and imports', async () => { - const dir = await editorPlugin() - const [check] = await checkPluginEditors(dir) - expect(check.issues).toEqual([]) - expect(check.files).toEqual(['editor/index.html', 'editor/main.ts', 'editor/sync.ts']) - expect(formatPluginEditorCheck(check)[0]).toMatch(/: ok, 3 file\(s\) load$/) - }) - it('fails on a syntax error that validate lets through', async () => { const dir = await editorPlugin() await appendFile(join(dir, 'editor', 'main.ts'), 'this is not valid ts(\n') diff --git a/src/cli/plugin-authoring/plugin-release-entry.test.ts b/src/cli/plugin-authoring/plugin-release-entry.test.ts index 9ee3494257f..99c95095830 100644 --- a/src/cli/plugin-authoring/plugin-release-entry.test.ts +++ b/src/cli/plugin-authoring/plugin-release-entry.test.ts @@ -1,4 +1,4 @@ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { runProcess } from '@orca/process-host' @@ -90,18 +90,4 @@ describe('orca plugin release-entry', () => { expect(result.entry).toBeUndefined() expect(result.note).toContain('themes/dark.json') }) - - it('explains why there is no entry outside Git or before the first commit', async () => { - const outside = join(await tempRoot(), 'loose') - await createPluginFromTemplate({ dir: outside, template: 'theme', publisher: 'acme' }) - expect((await releaseFor(outside)).note).toContain('not in a Git repository') - - const repo = await tempRoot() - await git(repo, ['init', '--quiet']) - await mkdir(join(repo, 'p')) - await createPluginFromTemplate({ dir: join(repo, 'p'), template: 'theme', publisher: 'acme' }) - const uncommitted = await releaseFor(join(repo, 'p')) - expect(uncommitted.entry).toBeUndefined() - expect(uncommitted.note).toContain('commit the plugin first') - }) }) diff --git a/src/cli/runtime/environment-pairing-exchange.test.ts b/src/cli/runtime/environment-pairing-exchange.test.ts index 90b284230a4..874c952a4dd 100644 --- a/src/cli/runtime/environment-pairing-exchange.test.ts +++ b/src/cli/runtime/environment-pairing-exchange.test.ts @@ -11,13 +11,6 @@ const pairingCode = encodePairingOffer({ }) describe('exchangeCliPairingCode', () => { - it('saves the code unchanged when the host is unreachable or the code is invalid', async () => { - const send = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')) - await expect(exchangeCliPairingCode(pairingCode, send)).resolves.toBe(pairingCode) - await expect(exchangeCliPairingCode('not a code', send)).resolves.toBe('not a code') - expect(send).toHaveBeenCalledOnce() - }) - it('refuses to save a code the host rejects, such as one another device already used', async () => { for (const send of [ vi diff --git a/src/cli/runtime/environments.test.ts b/src/cli/runtime/environments.test.ts index 31d1f263593..95b9bce3b7f 100644 --- a/src/cli/runtime/environments.test.ts +++ b/src/cli/runtime/environments.test.ts @@ -3,11 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' -import { - addEnvironmentFromPairingCode, - removeEnvironment, - resolveEnvironmentPairingOffer -} from './environments' +import { addEnvironmentFromPairingCode, resolveEnvironmentPairingOffer } from './environments' import { getEnvironmentStorePath } from '../../shared/remote-runtime/host-store/runtime-environment-store-records' import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store' @@ -37,29 +33,6 @@ function pairingCode(endpoint = 'ws://127.0.0.1:6768', keyFill = 1): string { describe('CLI runtime environments', () => { const posixModeIt = process.platform === 'win32' ? it.skip : it - it('saves, resolves, and removes a paired environment', () => { - const userDataPath = temporaryProfile() - const saved = addEnvironmentFromPairingCode(userDataPath, { - name: 'workstation', - pairingCode: pairingCode(), - now: 100 - }) - - expect(listEnvironments(userDataPath)).toHaveLength(1) - expect(resolveEnvironmentPairingOffer(userDataPath, 'workstation')).toMatchObject({ - endpoint: 'ws://127.0.0.1:6768', - deviceToken: 'device-token' - }) - expect(resolveEnvironmentPairingOffer(userDataPath, saved.id)).toMatchObject({ - endpoint: 'ws://127.0.0.1:6768' - }) - expect(statSync(getEnvironmentStorePath(userDataPath)).isFile()).toBe(true) - - const removed = removeEnvironment(userDataPath, 'workstation') - expect(removed.id).toBe(saved.id) - expect(listEnvironments(userDataPath)).toEqual([]) - }) - posixModeIt('stores paired environments with owner-only POSIX permissions', () => { const userDataPath = temporaryProfile() diff --git a/src/cli/runtime/orchestration-recovery-command.test.ts b/src/cli/runtime/orchestration-recovery-command.test.ts index 7f8873f6831..17919ae2197 100644 --- a/src/cli/runtime/orchestration-recovery-command.test.ts +++ b/src/cli/runtime/orchestration-recovery-command.test.ts @@ -1,77 +1,7 @@ import { describe, expect, it } from 'vitest' -import { - buildOrchestrationRecoveryCommand, - resolveOrchestrationCliExecutable -} from './orchestration-recovery-command' +import { buildOrchestrationRecoveryCommand } from './orchestration-recovery-command' describe('orchestration recovery command identity', () => { - it.each([ - ['configured dev', { ORCA_CLI_COMMAND: 'orca-dev' }, 'darwin', 'orca-dev'], - ['configured WSL', { ORCA_CLI_COMMAND: 'orca-ide' }, 'linux', 'orca-ide'], - ['dev checkout', { ORCA_DEV_REPO_ROOT: '/repo' }, 'darwin', 'orca-dev'], - ['packaged Linux', {}, 'linux', 'orca-ide'], - ['local macOS', {}, 'darwin', 'orca'], - ['local Windows', {}, 'win32', 'orca'] - ] as const)('resolves the %s CLI identity', (_name, env, platform, expected) => { - expect(resolveOrchestrationCliExecutable(env, platform)).toBe(expected) - }) - - it('reconstructs the keyed worker-start command from its RPC params', () => { - expect( - buildOrchestrationRecoveryCommand( - 'orchestration.workerStart', - { - task: 'task_1', - on: 'windows', - worktree: 'new-top-level', - timeoutMs: 90_000, - devMode: false - }, - 'orca' - ) - ).toEqual([ - 'orca', - 'orchestration', - 'worker-start', - '--task', - 'task_1', - '--on', - 'windows', - '--worktree', - 'new-top-level', - '--timeout-ms', - '90000' - ]) - }) - - it('preserves the selected executable and raw command arguments', () => { - expect( - buildOrchestrationRecoveryCommand( - 'orchestration.workerStart', - { task: 'task_1' }, - 'orca-dev', - [ - 'orchestration', - 'worker-start', - '--task', - 'task_1', - '--comment', - 'literal $(do-not-run) "quoted"', - '--json' - ] - ) - ).toEqual([ - 'orca-dev', - 'orchestration', - 'worker-start', - '--task', - 'task_1', - '--comment', - 'literal $(do-not-run) "quoted"', - '--json' - ]) - }) - it.each([ ['split', ['orchestration', 'send', '--pairing-code', 'secret', '--subject', 'status']], ['equals', ['orchestration', 'send', '--pairing-code=secret', '--subject', 'status']], @@ -89,28 +19,6 @@ describe('orchestration recovery command identity', () => { ).toBeUndefined() }) - it('supports the explicit executable-first form', () => { - expect( - buildOrchestrationRecoveryCommand('orca-ide', 'orchestration.workerStop', { - dispatch: 'dispatch_1' - }) - ).toEqual(['orca-ide', 'orchestration', 'worker-stop', '--dispatch', 'dispatch_1']) - }) - - it('reconstructs worker-keep-open when raw argv is unavailable', () => { - expect( - buildOrchestrationRecoveryCommand('orchestration.workerRetain', { - dispatch: 'dispatch_1' - }) - ).toEqual([ - resolveOrchestrationCliExecutable(), - 'orchestration', - 'worker-keep-open', - '--dispatch', - 'dispatch_1' - ]) - }) - it('does not fabricate identity for unsupported mutations or malformed params', () => { expect(buildOrchestrationRecoveryCommand('orchestration.send', {})).toBeUndefined() expect(buildOrchestrationRecoveryCommand('orchestration.workerStart', null)).toBeUndefined() diff --git a/src/cli/runtime/serve-install-hold.test.ts b/src/cli/runtime/serve-install-hold.test.ts index 461bb10c1e6..ad7a85848dc 100644 --- a/src/cli/runtime/serve-install-hold.test.ts +++ b/src/cli/runtime/serve-install-hold.test.ts @@ -3,7 +3,6 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { readServeInstallEvidence } from './serve-install-hold' -import { isShipItRunningForBundle } from '../../shared/shipit-process-listing' describe('readServeInstallEvidence', () => { let root: string @@ -60,11 +59,4 @@ describe('readServeInstallEvidence', () => { }) ).resolves.toEqual({ kind: 'clear' }) }) - - it('matches only the ShipIt binary path', () => { - expect(isShipItRunningForBundle(` ${shipIt('/A.app')}`, '/A.app')).toBe(true) - expect( - isShipItRunningForBundle('/A.app/Contents/Frameworks/Squirrel.framework/Squirrel', '/A.app') - ).toBe(false) - }) }) diff --git a/src/cli/runtime/serve-pairing-redaction.test.ts b/src/cli/runtime/serve-pairing-redaction.test.ts index 72e634f40a3..4dba64bb3b6 100644 --- a/src/cli/runtime/serve-pairing-redaction.test.ts +++ b/src/cli/runtime/serve-pairing-redaction.test.ts @@ -5,8 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { createPairingRedactor, PAIRING_HIDDEN_LINE, - redactingSpawn, - shouldRedactSupervisedStdout + redactingSpawn } from './serve-pairing-redaction' const READY = [ @@ -49,12 +48,6 @@ describe('supervised pairing redaction', () => { }) }) - it('redacts only supervised output that is not a terminal', () => { - expect(shouldRedactSupervisedStdout(true, false)).toBe(true) - expect(shouldRedactSupervisedStdout(true, true)).toBe(false) - expect(shouldRedactSupervisedStdout(false, false)).toBe(false) - }) - it('pipes only stdout through the redactor and keeps the ipc slot', async () => { const stdout = new PassThrough() const child = new ChildProcess() diff --git a/src/cli/runtime/serve-supervisor-policy.test.ts b/src/cli/runtime/serve-supervisor-policy.test.ts index 2c12a9611e0..12ae3333e62 100644 --- a/src/cli/runtime/serve-supervisor-policy.test.ts +++ b/src/cli/runtime/serve-supervisor-policy.test.ts @@ -21,23 +21,6 @@ function exit(overrides: Partial = {}): ServeChildExit { } describe('decideAfterServeChildExit', () => { - it('passes a normal exit code through, and explains an unforwarded signal', () => { - const base = { expectedHandoff: null, handoff: null, hasHandoffPath: true } - expect(decideAfterServeChildExit({ ...base, exit: exit({ code: 3 }) })).toEqual({ - kind: 'exit', - code: 3 - }) - expect( - decideAfterServeChildExit({ - ...base, - exit: exit({ code: null, signal: 'SIGTERM', signalWasForwarded: true }) - }) - ).toEqual({ kind: 'exit', code: 0 }) - expect( - decideAfterServeChildExit({ ...base, exit: exit({ code: null, signal: 'SIGABRT' }) }) - ).toEqual({ kind: 'signal-exit', signal: 'SIGABRT' }) - }) - it('waits for the new bundle only when this very child requested the install', () => { expect( decideAfterServeChildExit({ diff --git a/src/cli/runtime/terminal-prompt-mutation-recovery-plugin-denied.test.ts b/src/cli/runtime/terminal-prompt-mutation-recovery-plugin-denied.test.ts deleted file mode 100644 index bb2b2d78760..00000000000 --- a/src/cli/runtime/terminal-prompt-mutation-recovery-plugin-denied.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { attachDurableMutationRecovery } from './terminal-prompt-mutation-recovery' -import { RuntimeClientError } from './types' - -describe('a plugin hook denial in the CLI', () => { - it('gets no retry advice in the CLI', () => { - const denied = new RuntimeClientError( - 'denied_by_plugin', - 'terminal.send denied by plugin a.b: x' - ) - expect( - attachDurableMutationRecovery(denied, 'req-1', ['terminal', 'send'], 'terminal.send') - ).toBe(denied) - const other = attachDurableMutationRecovery( - new RuntimeClientError('runtime_error', 'boom'), - 'req-1', - ['terminal', 'send'], - 'terminal.send' - ) - expect(String(other)).toMatch(/--retry-request req-1/) - }) -}) diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-policy.test.ts b/src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-policy.test.ts deleted file mode 100644 index 0b7830ca9fe..00000000000 --- a/src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-policy.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { browserPageNeedsPaintRetention } from './browser-guest-paint-retention' -import { hydrateBrowserDrivers } from '../../../lib/pane-manager/browser-mobile-driver-state' -import { hydrateBrowserRemoteViewerPages } from '../../../lib/pane-manager/browser-remote-viewer-state' -import { - acquireBrowserAutomationVisibility, - releaseBrowserAutomationVisibility -} from './browser-automation-visibility' - -// The imperative twin, for retention decisions taken outside a render (the eviction budget). -describe('browserPageNeedsPaintRetention', () => { - afterEach(() => { - hydrateBrowserDrivers([]) - hydrateBrowserRemoteViewerPages([]) - }) - - it('answers for each term on its own', () => { - expect(browserPageNeedsPaintRetention('page-a')).toBe(false) - - hydrateBrowserRemoteViewerPages(['page-a']) - expect(browserPageNeedsPaintRetention('page-a')).toBe(true) - hydrateBrowserRemoteViewerPages([]) - - hydrateBrowserDrivers([ - { browserPageId: 'page-a', driver: { kind: 'mobile', clientId: 'phone-1' } } - ]) - expect(browserPageNeedsPaintRetention('page-a')).toBe(true) - hydrateBrowserDrivers([]) - - const token = acquireBrowserAutomationVisibility('page-a') - expect(browserPageNeedsPaintRetention('page-a')).toBe(true) - releaseBrowserAutomationVisibility(token) - expect(browserPageNeedsPaintRetention('page-a')).toBe(false) - }) - - it('stays scoped to the page asked about', () => { - hydrateBrowserRemoteViewerPages(['page-a']) - expect(browserPageNeedsPaintRetention('page-b')).toBe(false) - }) -}) diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts b/src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts index efff82bd6cf..33989c229ad 100644 --- a/src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts +++ b/src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts @@ -62,36 +62,6 @@ afterEach(() => { }) describe('browser page guest recovery', () => { - it('reloads a lost renderer in place and cancels the failure surface after recovery', () => { - vi.useFakeTimers() - const state = createRecovery() - - state.recovery.recoverRenderer() - - expect(state.reload).toHaveBeenCalledOnce() - expect(state.pending()).toBe(true) - - state.recovery.finish() - vi.advanceTimersByTime(BROWSER_GUEST_RECOVERY_TIMEOUT_MS) - - expect(state.pending()).toBe(false) - expect(state.onRecoveryFailed).not.toHaveBeenCalled() - }) - - it('recreates a guest when in-place reload is unavailable', async () => { - const state = createRecovery({ - reload: () => { - throw new Error('guest destroyed') - } - }) - - state.recovery.recoverRenderer() - await vi.waitFor(() => expect(state.onReplacementReady).toHaveBeenCalledOnce()) - - expect(state.replaceGuest).toHaveBeenCalledOnce() - expect(state.pending()).toBe(true) - }) - it('surfaces guest replacement rejection without marking it ready', async () => { const replacementError = new Error('replacement failed') const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) @@ -139,32 +109,6 @@ describe('browser page guest recovery', () => { expect(state.onReplacementReady).toHaveBeenCalledOnce() }) - it('recreates an active guest missing from the authoritative registry after resume', async () => { - const state = createRecovery({ registered: false }) - - state.recovery.validateAfterResume() - await vi.waitFor(() => expect(state.onReplacementReady).toHaveBeenCalledOnce()) - - expect(state.validateRegistration).toHaveBeenCalledOnce() - expect(state.replaceGuest).toHaveBeenCalledOnce() - }) - - it('waits for an attaching guest instead of replacing it as missing', async () => { - vi.useFakeTimers() - const state = createRecovery() - state.validateRegistration.mockResolvedValueOnce(null).mockResolvedValueOnce(true) - - state.recovery.validateAfterResume() - await vi.advanceTimersByTimeAsync(0) - - expect(state.replaceGuest).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(BROWSER_GUEST_VALIDATION_RETRY_DELAY_MS) - - expect(state.validateRegistration).toHaveBeenCalledTimes(2) - expect(state.onRecoverySucceeded).toHaveBeenCalledOnce() - expect(state.replaceGuest).not.toHaveBeenCalled() - }) - it('surfaces an attaching guest that never becomes identifiable', async () => { vi.useFakeTimers() const state = createRecovery() @@ -251,17 +195,6 @@ describe('browser page guest recovery', () => { expect(state.onRecoveryFailed).not.toHaveBeenCalled() }) - it('surfaces an explicit recovery failure instead of leaving a permanent blank page', () => { - vi.useFakeTimers() - const state = createRecovery() - - state.recovery.recoverRenderer() - vi.advanceTimersByTime(BROWSER_GUEST_RECOVERY_TIMEOUT_MS) - - expect(state.pending()).toBe(false) - expect(state.onRecoveryFailed).toHaveBeenCalledOnce() - }) - it('keeps the original recovery deadline across repeated renderer loss events', () => { vi.useFakeTimers() const state = createRecovery() diff --git a/src/shared/__tests__/process-host/windows-cmd-shim-resolution.test.ts b/src/shared/__tests__/process-host/windows-cmd-shim-resolution.test.ts index 505294d3fcc..ad875e9f8d9 100644 --- a/src/shared/__tests__/process-host/windows-cmd-shim-resolution.test.ts +++ b/src/shared/__tests__/process-host/windows-cmd-shim-resolution.test.ts @@ -190,34 +190,6 @@ describeOnWindows('resolveWindowsCmdShim', () => { expect(resolveWindowsCmdShim(shim, env)?.prefixArgs).toEqual([join(dir, 'ci2.js')]) }) - it('walks PATH once per shim directory, not once per spawn', () => { - // Adding an earlier interpreter after first resolution proves cached PATH walks stay cached; without the cache this returns early. - const early = mkdtempSync(join(tmpdir(), 'orca-shim-path-early-')) - const late = mkdtempSync(join(tmpdir(), 'orca-shim-path-late-')) - const shimDir = mkdtempSync(join(tmpdir(), 'orca-shim-path-')) - try { - writeFileSync(join(late, 'node.exe'), '') - writeFileSync(join(shimDir, 'cli.js'), '') - const shim = join(shimDir, 'walk.cmd') - writeFileSync(shim, npmProgNodeShim('cli.js')) - const pathEnv = { ...env, Path: undefined, PATH: `${early};${late}` } - - expect(resolveWindowsCmdShim(shim, pathEnv)?.program).toBe(join(late, 'node.exe')) - - writeFileSync(join(early, 'node.exe'), '') - expect(resolveWindowsCmdShim(shim, pathEnv)?.program).toBe(join(late, 'node.exe')) - - // A PATH edit must miss: caching the walk must not outlive its input. - expect(resolveWindowsCmdShim(shim, { ...pathEnv, PATH: `${early};${late};` })?.program).toBe( - join(early, 'node.exe') - ) - } finally { - removeTreeSync(early) - removeTreeSync(late) - removeTreeSync(shimDir) - } - }) - it('gives up when cmd would resolve `node` to a non-.exe PATHEXT spelling', () => { // cmd stops at the first PATHEXT match, including .COM before .EXE; skipping it would launch the wrong binary. const first = mkdtempSync(join(tmpdir(), 'orca-shim-ext-first-')) diff --git a/src/shared/abort-signal-reason.test.ts b/src/shared/abort-signal-reason.test.ts index 514ce5233ba..5992a47e2ee 100644 --- a/src/shared/abort-signal-reason.test.ts +++ b/src/shared/abort-signal-reason.test.ts @@ -1,7 +1,5 @@ -import { getEventListeners } from 'node:events' -import { expect, it, vi } from 'vitest' +import { expect, it } from 'vitest' import { waitForPromiseWithSignal } from './abort-signal-reason' -import { sharedPromiseSettlementWaiters } from './promise-settlement-waiters' it('observes work that rejects after its caller has already canceled', async () => { const controller = new AbortController() @@ -15,29 +13,6 @@ it('observes work that rejects after its caller has already canceled', async () await new Promise((resolve) => setImmediate(resolve)) }) -it('detaches cancelled callers from shared stalled work while another caller waits', async () => { - let finish = (_value: number): void => {} - const work = new Promise((resolve) => { - finish = resolve - }) - const observed = vi.spyOn(work, 'then') - const anchorController = new AbortController() - const anchor = waitForPromiseWithSignal(work, anchorController.signal) - for (let index = 0; index < 100; index += 1) { - const controller = new AbortController() - const cancelled = waitForPromiseWithSignal(work, controller.signal) - controller.abort(new Error('cancelled')) - await expect(cancelled).rejects.toThrow('cancelled') - expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0) - } - expect(observed).toHaveBeenCalledOnce() - expect(sharedPromiseSettlementWaiters(work).waiterCount).toBe(1) - finish(42) - await expect(anchor).resolves.toBe(42) - expect(sharedPromiseSettlementWaiters(work).waiterCount).toBe(0) - expect(getEventListeners(anchorController.signal, 'abort')).toHaveLength(0) -}) - it('allows synchronous cancellation before a cached settlement is delivered', async () => { const work = Promise.resolve(42) await expect(waitForPromiseWithSignal(work, new AbortController().signal)).resolves.toBe(42) diff --git a/src/shared/agent-cli-install-dir-fallback.test.ts b/src/shared/agent-cli-install-dir-fallback.test.ts index 127057c14b2..66e97c004f2 100644 --- a/src/shared/agent-cli-install-dir-fallback.test.ts +++ b/src/shared/agent-cli-install-dir-fallback.test.ts @@ -99,28 +99,6 @@ describe('agent CLI install-dir fallback', () => { }) }) - // Match packaged PATH seeding and guest prelude order so all resolvers select the same binary. - it('ranks system install dirs in the same order as the PATH seed', () => { - const home = '/home/tester' - const dirs = [ - '/usr/local/bin', - '/snap/bin', - '/home/linuxbrew/.linuxbrew/bin', - '/nix/var/nix/profiles/default/bin', - join(home, '.nix-profile', 'bin'), - join(home, '.opencode', 'bin'), - join(home, '.vite-plus', 'bin'), - join(home, '.grok', 'bin') - ] - stage(...dirs.map((dir) => join(dir, 'opencode'))) - for (const expected of dirs) { - expect(resolveAll(['opencode'], { platform: 'linux', homePath: home })).toEqual({ - opencode: join(expected, 'opencode') - }) - fsFixture.executables.delete(join(expected, 'opencode')) - } - }) - // Both resolver entrypoints must prefer version-manager binaries over same-named system installs. describe.each([ { platform: 'darwin' as const, home: '/Users/tester', systemDir: '/opt/homebrew/bin' }, diff --git a/src/shared/agent-hook-listener/reverse-file-region-scan.test.ts b/src/shared/agent-hook-listener/reverse-file-region-scan.test.ts index c13eb8d9632..e4f12108195 100644 --- a/src/shared/agent-hook-listener/reverse-file-region-scan.test.ts +++ b/src/shared/agent-hook-listener/reverse-file-region-scan.test.ts @@ -42,21 +42,6 @@ describe('scanFileRegionsBackward', () => { } }) - it('stops at the first defined result without reading the rest of the file', () => { - const file = writeFixture(`${Array.from({ length: 200 }, (_, i) => `line-${i}`).join('\n')}\n`) - let regions = 0 - const found = scanFileRegionsBackward( - file, - { chunkBytes: 32, maxScanBytes: 1024 * 1024 }, - () => { - regions += 1 - return 'first' - } - ) - expect(found).toBe('first') - expect(regions).toBe(1) - }) - it('reports the byte offset each region starts at', () => { const file = writeFixture('😀alpha\nbravo\ncharlie\n') const offsets: { text: string; regionPosition: number }[] = [] diff --git a/src/shared/agent-hook-listener/transcript-reader.test.ts b/src/shared/agent-hook-listener/transcript-reader.test.ts index a4b9acf7a65..d0f482cac54 100644 --- a/src/shared/agent-hook-listener/transcript-reader.test.ts +++ b/src/shared/agent-hook-listener/transcript-reader.test.ts @@ -61,36 +61,7 @@ it('reads the same bounded first-record prefix with N and 10N later records and } }) -function expectedLines(text: string): string[] { - return text - .split('\n') - .toReversed() - .map((line) => line.trim()) - .filter((line) => line.length > 0) -} - describe('backward transcript line extraction', () => { - it('preserves line order and early return across generated delimiters', () => { - let seed = 29 - const fragments = ['a', '\n', '\r\n', ' ', '\t', '😀', '\u2028', '\0'] - for (let sample = 0; sample < 1000; sample++) { - let text = '' - for (let i = 0; i < sample % 100; i++) { - seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0 - text += fragments[seed % fragments.length] - } - const lines = expectedLines(text) - const stop = sample % (lines.length + 1) - const seen: string[] = [] - const result = findLastExtractedTranscriptLineText(text, (line) => { - seen.push(line) - return seen.length === stop + 1 ? line : undefined - }) - expect(seen).toEqual(lines.slice(0, stop + 1)) - expect(result).toBe(lines[stop]) - } - }) - it('returns the newest assistant message behind a long tool line', () => { const message = JSON.stringify({ role: 'assistant', content: 'latest 😀' }) const tool = JSON.stringify({ role: 'tool', content: 'x'.repeat(256 * 1024) }) diff --git a/src/shared/agent-hook-listener/transport/agent-hook-endpoint-file.test.ts b/src/shared/agent-hook-listener/transport/agent-hook-endpoint-file.test.ts deleted file mode 100644 index afaa23fe816..00000000000 --- a/src/shared/agent-hook-listener/transport/agent-hook-endpoint-file.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { parseAgentHookEndpointFile } from './agent-hook-endpoint-file' -import { getEndpointFileName, writeEndpointFile } from './endpoint-publication' -const ENDPOINT = { port: '12345', token: 'token-123', env: 'production', version: '1' } - -describe('agent hook endpoint files', () => { - it('parses the endpoint bytes published by the platform writer', () => { - const directory = mkdtempSync(join(tmpdir(), 'orca-hook-endpoint-parser-')) - try { - const path = join(directory, getEndpointFileName()) - expect( - writeEndpointFile(directory, path, { - port: 12345, - token: 'token-123', - env: 'production', - version: '1' - }) - ).toBe(true) - expect(parseAgentHookEndpointFile(readFileSync(path, 'utf8'))).toEqual(ENDPOINT) - } finally { - rmSync(directory, { recursive: true, force: true }) - } - }) -}) diff --git a/tests/e2e/github-created-issue-start-prefill.spec.ts b/tests/e2e/github-created-issue-start-prefill.spec.ts deleted file mode 100644 index 3badbabde96..00000000000 --- a/tests/e2e/github-created-issue-start-prefill.spec.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { test as base, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { getTerminalContent } from './helpers/terminal' - -const ISSUE_NUMBER = 6613 -const ISSUE_TITLE = 'Start a newly created issue without losing its context' -const ISSUE_URL = `https://github.com/acme/repo/issues/${ISSUE_NUMBER}` -const fakeCliDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-created-issue-prefill-')) - -const fakeGhSource = ` -const args = process.argv.slice(2) -const joined = args.join(' ') -const issue = { - number: ${ISSUE_NUMBER}, - title: ${JSON.stringify(ISSUE_TITLE)}, - state: 'open', - html_url: ${JSON.stringify(ISSUE_URL)}, - labels: [], - assignees: [], - user: { login: 'e2e' }, - updated_at: '2026-07-22T12:00:00.000Z' -} - -if (args[0] === 'auth' && args[1] === 'status') { - console.error('github.com\\n ✓ Logged in to github.com account e2e (GITHUB_TOKEN)') - process.exit(0) -} -if (args[0] === 'api' && args[1] === 'user') { - console.log(JSON.stringify({ login: 'e2e' })) - process.exit(0) -} -if (args[0] === 'api' && args.includes('rate_limit')) { - console.log(JSON.stringify({ resources: { core: { limit: 5000, remaining: 5000, reset: 0 }, graphql: { limit: 5000, remaining: 5000, reset: 0 }, search: { limit: 30, remaining: 30, reset: 0 } } })) - process.exit(0) -} -if (args[0] === 'api' && args.includes('-X') && args.includes('POST') && joined.includes('repos/acme/repo/issues')) { - console.log(JSON.stringify(issue)) - process.exit(0) -} -if (args[0] === 'api' && joined.includes('/labels')) { - process.exit(0) -} -if (args[0] === 'api' && joined.includes('/assignees')) { - process.exit(0) -} -if (args[0] === 'api' && joined.includes('repos/acme/repo/issues/${ISSUE_NUMBER}')) { - console.log(JSON.stringify(issue)) - process.exit(0) -} -if (args[0] === 'api' && joined.includes('search/issues')) { - console.log(JSON.stringify({ total_count: 0, incomplete_results: false, items: [] })) - process.exit(0) -} -if (args[0] === 'issue' && args[1] === 'list') { - console.log('[]') - process.exit(0) -} -if (args[0] === 'pr' && args[1] === 'list') { - console.log('[]') - process.exit(0) -} -if (args[0] === 'api' && args[1] === 'graphql') { - console.log(JSON.stringify({ data: { search: { issueCount: 0, pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] } } })) - process.exit(0) -} -console.error('fake gh: unhandled ' + joined) -process.exit(1) -` - -const fakeClaudeSource = ` -const args = process.argv.slice(2) -process.stdout.write('E2E_CLAUDE_ARGV ' + JSON.stringify(args) + '\\n') -setInterval(() => {}, 60_000) -` - -function installFakeCli(name: 'gh' | 'claude', source: string): void { - if (process.platform === 'win32') { - writeFileSync(path.join(fakeCliDir, `fake-${name}.js`), source) - writeFileSync( - path.join(fakeCliDir, `${name}.cmd`), - `@echo off\r\nnode "%~dp0\\fake-${name}.js" %*\r\n` - ) - return - } - const executable = path.join(fakeCliDir, name) - writeFileSync(executable, `#!/usr/bin/env node\n${source}`) - chmodSync(executable, 0o755) -} - -installFakeCli('gh', fakeGhSource) -installFakeCli('claude', fakeClaudeSource) - -const test = base.extend({ - launchEnv: { - PATH: `${fakeCliDir}${path.delimiter}${process.env.PATH ?? ''}` - } -}) - -test.afterAll(() => { - rmSync(fakeCliDir, { recursive: true, force: true }) -}) - -function configureGitHubRemote(repoPath: string): void { - try { - execFileSync('git', ['remote', 'remove', 'origin'], { cwd: repoPath, stdio: 'ignore' }) - } catch { - // The disposable E2E repo does not have an origin on its first run. - } - execFileSync('git', ['remote', 'add', 'origin', 'https://github.com/acme/repo.git'], { - cwd: repoPath, - stdio: 'pipe' - }) -} - -// Add origin before repos.add caches no-remote for five minutes, which would disable GitHub issue creation. -test.beforeAll(({ testRepoPath }) => { - configureGitHubRemote(testRepoPath) -}) - -test('starting a just-created GitHub issue launches Claude with its URL prefilled', async ({ - orcaPage, - electronApp -}) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - // Why: the gh preflight merges the login-shell PATH ahead of launchEnv, so the fake gh can lose to a real one. - await electronApp.evaluate( - ({ ipcMain }, created) => { - ipcMain.removeHandler('gh:createIssue') - ipcMain.handle('gh:createIssue', () => ({ ok: true, ...created })) - }, - { number: ISSUE_NUMBER, url: ISSUE_URL } - ) - - await orcaPage.evaluate(async () => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - const preparedWorkspace = state - .allWorktrees() - .find((worktree) => worktree.branch?.endsWith('e2e-secondary')) - if (!preparedWorkspace) { - throw new Error('Seeded secondary E2E worktree is not available') - } - // Why: this regression owns renderer-to-PTY command propagation, while the shared fixture already covers Git worktree creation. - store.setState({ - createWorktree: async () => ({ worktree: preparedWorkspace }) - }) - await state.updateSettings({ - defaultTuiAgent: 'claude', - disabledTuiAgents: [], - ...(navigator.userAgent.includes('Windows') ? { terminalWindowsShell: 'git-bash' } : {}) - }) - store.getState().openTaskPage({ taskSource: 'github' }) - }) - - const newIssueButton = orcaPage.getByRole('button', { name: 'New GitHub issue' }) - await expect(newIssueButton).toBeEnabled({ timeout: 15_000 }) - await newIssueButton.click() - - const createDialog = orcaPage.getByRole('dialog', { name: 'New GitHub issue' }) - await expect(createDialog).toBeVisible() - await createDialog.getByPlaceholder('Short summary').fill(ISSUE_TITLE) - await createDialog.getByRole('button', { name: 'Create issue' }).click() - - await expect(createDialog).toBeHidden({ timeout: 10_000 }) - await expect(orcaPage.getByRole('heading', { name: ISSUE_TITLE })).toBeVisible({ - timeout: 10_000 - }) - - await orcaPage.getByRole('button', { name: 'Start workspace from issue' }).click() - - // Issue start opens the quick-create composer, which must carry its URL into the submitted agent command. - const composer = orcaPage.getByRole('dialog', { name: /Create (workspace|worktree)/i }) - await expect(composer).toBeVisible({ timeout: 15_000 }) - const createWorkspaceButton = composer.getByRole('button', { - name: /Create (workspace|worktree)/i - }) - await expect(createWorkspaceButton).toBeEnabled({ timeout: 15_000 }) - await createWorkspaceButton.click() - await expect(composer).toBeHidden({ timeout: 20_000 }) - - let terminalText = '' - await expect - .poll( - async () => { - terminalText = await getTerminalContent(orcaPage, 12_000) - return terminalText - }, - { - timeout: 30_000, - message: 'Claude prefill command did not reach the active terminal buffer' - } - ) - .toContain('--prefill') - expect(terminalText).toContain('--dangerously-skip-permissions') - expect(terminalText).toContain('--prefill') - expect(terminalText).toContain(ISSUE_URL) - expect(terminalText).not.toMatch(/(?:^|\n)claude '--dangerously-skip-permissions'(?:\r?\n|$)/) -}) From c4b54195f10214e9ac8bfcf1d2f8bec27df1df4d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:01:48 -0800 Subject: [PATCH 5/5] Show the setup-script choice instead of greying out Create (#40341) * Show the setup-script choice instead of greying out Create With a project's setup script set to "Ask every time", Create stayed disabled until the user picked Run or Skip, but that choice only renders inside the collapsed Advanced section, so nothing explained the greyed-out button. Keep the choice out of the disabled gate (as the gate's own comment already intends) and have Create open Advanced to show it. * Annotate the partial submit fixture cast * Bring the setup choice into view when Create needs it Create now scrolls the Run/Skip choice into the dialog's view and focuses it on every attempt, including when Advanced is already open, and the late-discovered setup path uses the same reveal. A submit that only jumps to an existing pending creation no longer asks for a setup choice. * Reveal the setup choice once per Create attempt The choice clears the reveal request after scrolling and focusing, so a later remount (for example after switching projects) cannot pull focus without a new Create. * Drop a pending setup reveal once the user has chosen Choosing Skip in the moment before the reveal fired could still move focus onto Run, so a later Enter switched the choice. --- ...wWorkspaceComposerModal.retention.test.tsx | 2 + .../NewWorkspaceComposerAdvancedSection.tsx | 6 ++ .../WorkspaceSetupChoice.test.tsx | 53 +++++++++++++++++ .../new-workspace/WorkspaceSetupChoice.tsx | 30 +++++++++- .../new-workspace/WorkspaceSetupSection.tsx | 6 ++ .../new-workspace-composer-card-props.ts | 2 + .../composer-state/async-composer-state.ts | 14 ++++- .../src/hooks/composer-state/async-model.ts | 3 + .../composer-state/composer-card-contract.ts | 2 + .../composer-state/composer-card-props.ts | 6 +- .../composer-submit-orchestration.ts | 3 +- .../quick-submit-action.test.tsx | 57 +++++++++++++++++++ .../composer-state/quick-submit-action.ts | 10 +++- .../quick-submit-input-contract.ts | 2 +- .../quick-submit-preparation.ts | 6 +- .../src/lib/new-workspace-create-gates.ts | 3 - 16 files changed, 192 insertions(+), 13 deletions(-) create mode 100644 src/renderer/src/components/new-workspace/WorkspaceSetupChoice.test.tsx create mode 100644 src/renderer/src/hooks/composer-state/quick-submit-action.test.tsx diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.retention.test.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.retention.test.tsx index 2dbb0447b44..d01c63cd408 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.retention.test.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.retention.test.tsx @@ -176,6 +176,8 @@ vi.mock('@/hooks/useComposerState', () => ({ onReuseSelectedBranchChange: noOp, forkPushWarning: null, advancedOpen: false, + setupChoiceRevealRequest: 0, + onSetupChoiceRevealed: noOp, onToggleAdvanced: noOp, parentWorktreeId: null, onParentWorktreeIdChange: noOp, diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerAdvancedSection.tsx b/src/renderer/src/components/new-workspace/NewWorkspaceComposerAdvancedSection.tsx index ecbc518222c..d71d3d057e4 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerAdvancedSection.tsx +++ b/src/renderer/src/components/new-workspace/NewWorkspaceComposerAdvancedSection.tsx @@ -22,6 +22,8 @@ import type { NewWorkspaceComposerCardProps } from './new-workspace-composer-car type NewWorkspaceComposerAdvancedSectionProps = Pick< NewWorkspaceComposerCardProps, | 'advancedOpen' + | 'setupChoiceRevealRequest' + | 'onSetupChoiceRevealed' | 'smartNameSelection' | 'name' | 'onNameValueChange' @@ -61,6 +63,8 @@ type NewWorkspaceComposerAdvancedSectionProps = Pick< export function NewWorkspaceComposerAdvancedSection({ advancedOpen, + setupChoiceRevealRequest, + onSetupChoiceRevealed, sparseEditing, onSparseEditingChange, smartNameSelection, @@ -223,6 +227,8 @@ export function NewWorkspaceComposerAdvancedSection({ setupConfig={setupConfig} copy={selectWorkspaceSetupCopy(setupConfig, getComposerWorkspaceSetupLabels(t))} requiresExplicitSetupChoice={requiresExplicitSetupChoice} + revealRequest={setupChoiceRevealRequest} + onRevealed={onSetupChoiceRevealed} resolvedSetupDecision={resolvedSetupDecision} setupDecision={setupDecision} onSetupDecisionChange={onSetupDecisionChange} diff --git a/src/renderer/src/components/new-workspace/WorkspaceSetupChoice.test.tsx b/src/renderer/src/components/new-workspace/WorkspaceSetupChoice.test.tsx new file mode 100644 index 00000000000..d9e83d5d164 --- /dev/null +++ b/src/renderer/src/components/new-workspace/WorkspaceSetupChoice.test.tsx @@ -0,0 +1,53 @@ +// @vitest-environment happy-dom +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { WorkspaceSetupChoice } from './WorkspaceSetupChoice' + +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +describe('WorkspaceSetupChoice', () => { + it('brings the choice into view and focuses it on each reveal request', () => { + vi.useFakeTimers() + const scrollIntoView = vi.fn() + Element.prototype.scrollIntoView = scrollIntoView + const onRevealed = vi.fn() + const props = { + decision: null, + onChange: vi.fn(), + runLabel: 'Run', + skipLabel: 'Skip', + onRevealed + } + const { rerender } = render() + vi.runAllTimers() + expect(scrollIntoView).not.toHaveBeenCalled() + + // A second request matters too: Advanced may already be open from the first. + for (const revealRequest of [1, 2]) { + rerender() + vi.runAllTimers() + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Run' })) + } + expect(scrollIntoView).toHaveBeenCalledTimes(2) + // Each handled request is cleared so a remount after a project switch cannot replay it. + expect(onRevealed).toHaveBeenCalledTimes(2) + }) + + it('does not move focus onto Run when the user chose before the reveal fired', () => { + vi.useFakeTimers() + Element.prototype.scrollIntoView = vi.fn() + const onRevealed = vi.fn() + const props = { onChange: vi.fn(), runLabel: 'Run', skipLabel: 'Skip', onRevealed } + const { rerender } = render( + + ) + rerender() + vi.runAllTimers() + + expect(document.activeElement).not.toBe(screen.getByRole('button', { name: 'Run' })) + expect(onRevealed).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/renderer/src/components/new-workspace/WorkspaceSetupChoice.tsx b/src/renderer/src/components/new-workspace/WorkspaceSetupChoice.tsx index edc754b3e78..70eafc944cd 100644 --- a/src/renderer/src/components/new-workspace/WorkspaceSetupChoice.tsx +++ b/src/renderer/src/components/new-workspace/WorkspaceSetupChoice.tsx @@ -1,21 +1,49 @@ +import { useEffect, useRef } from 'react' import { Button } from '@/components/ui/button' +// Matches the Advanced section's expand transition so the choice is laid out before scrolling. +const REVEAL_AFTER_EXPAND_MS = 220 + export function WorkspaceSetupChoice({ decision, onChange, disabled = false, runLabel, - skipLabel + skipLabel, + revealRequest = 0, + onRevealed }: { decision: 'run' | 'skip' | null onChange: (decision: 'run' | 'skip') => void disabled?: boolean runLabel: string skipLabel: string + revealRequest?: number + onRevealed?: () => void }): React.JSX.Element { + const runButtonRef = useRef(null) + useEffect(() => { + if (revealRequest === 0) { + return + } + if (decision !== null) { + // Chosen before the reveal fired: drop it rather than move focus onto Run. + onRevealed?.() + return + } + // A submit without a choice lands here; scroll the choice into the dialog's view and focus it. + const timer = setTimeout(() => { + runButtonRef.current?.scrollIntoView({ block: 'nearest' }) + runButtonRef.current?.focus() + onRevealed?.() + }, REVEAL_AFTER_EXPAND_MS) + return () => clearTimeout(timer) + }, [revealRequest, onRevealed, decision]) + return (