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/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 396968458f5..afd1ef5bf40 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, @@ -346,14 +345,12 @@ "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, "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, @@ -382,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, @@ -443,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, @@ -4735,7 +4730,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 +4747,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,9 +4762,7 @@ "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, "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, @@ -7107,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, @@ -8267,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/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/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/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-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/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/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/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/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 +} 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/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/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/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 (