From deb834db0593f763197adeb1a7d30a8fbd21cbb3 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sat, 7 Nov 2026 06:33:36 -0800 Subject: [PATCH] test: remove 244 low-value tests (#39507) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- config/flaky-test-pattern-baseline.txt | 9 +- .../scripts/ci/sharding/ci-shard-timings.json | 15 - .../AutomationManager.run-history.spec.tsx | 49 --- .../automations/AutomationManager.test.tsx | 2 +- .../environment-pairing-exchange.test.ts | 14 +- .../external-automation-owner-guard.test.ts | 47 +-- ...xternal-automation-probe-scheduler.test.ts | 42 --- .../external-manager-scoped.test.ts | 102 ------ src/main/automations/external-manager.test.ts | 53 --- .../automations/schedule-drift-report.test.ts | 60 ---- .../azure-devops/pull-request-mappers.test.ts | 18 - .../bitbucket/credential-connection.test.ts | 44 --- src/main/bitbucket/credential-store.test.ts | 43 --- .../bitbucket/pull-request-mappers.test.ts | 18 - .../browser-cookie-clear-preserve.test.ts | 148 -------- ...browser-cookie-public-suffix-scope.test.ts | 58 +-- .../browser-cookie-registrable-family.test.ts | 46 --- .../claude-account-folder.test.ts | 31 +- ...laude-command-process-windows-only.test.ts | 8 - .../claude-login-session.test.ts | 14 - .../claude-pasted-code-login.test.ts | 21 -- .../claude-sign-in-browser.test.ts | 13 - src/preload/browser-password-detector.test.ts | 117 ------- .../browser-password-form-parser.test.ts | 33 +- .../native-chat-visual-guest-theme.test.ts | 86 ----- .../annotate/markup-shape-render.test.ts | 125 +------ .../annotate/use-markup-draw-hint.test.ts | 14 - .../annotate/useMarkupEditor.test.ts | 125 ------- .../BrowserPane.webview-preferences.test.ts | 28 -- .../browser-chrome-folded-tools.test.tsx | 105 ------ .../browser-link-status-bubble.test.tsx | 73 ---- .../browser-navigation-control-row.test.tsx | 41 --- .../use-browser-chrome-tool-fold.test.tsx | 44 --- ...er-client-hosted-download-notices.test.tsx | 79 ----- ...ser-client-page-metadata-publisher.test.ts | 47 --- ...ent-page-retained-drag-passthrough.test.ts | 15 - .../browser-external-app-prompt.test.ts | 48 --- .../browser-http-auth-prompt.test.ts | 44 --- .../browser-pane/browser-page-prompts.test.ts | 46 +-- .../browser-reopen-on-server.test.ts | 33 +- .../browser-site-permission-prompt.test.ts | 21 -- .../browser-annotation-geometry.test.ts | 55 --- .../browser-artifact-upload.test.ts | 30 -- .../describe-page/browser-favicon-url.test.ts | 90 ----- .../browser-page-url-display.test.ts | 30 -- .../live-browser-url-registry.test.ts | 20 -- src/shared/github/api-availability.test.ts | 40 +-- src/shared/github/owner-slug.test.ts | 15 +- .../github/pr-comment-diff-hunk.test.ts | 29 -- src/shared/github/pr-reviewer-display.test.ts | 45 --- .../github/project-board-columns.test.ts | 43 --- .../github/project-roadmap-timeline.test.ts | 273 +-------------- .../pull-request-for-branch-outcome.test.ts | 17 +- src/shared/gitlab-projects.test.ts | 50 --- src/shared/grok-model-list-probe.test.ts | 87 ----- src/shared/grok-session-paths.test.ts | 77 ---- src/shared/handled-wire-discriminant.test.ts | 5 - .../harness-injected-user-turns.test.ts | 82 +---- src/shared/hook-command-source-policy.test.ts | 19 - src/shared/host-automatic-work-budget.test.ts | 6 - .../host-balanced-listing-scaling.test.ts | 39 +-- src/shared/host-setting-overrides.test.ts | 144 -------- .../agent-hook-envelope-publication.test.ts | 212 ----------- src/wsl-guest/agent-hook-integration.test.ts | 85 ----- .../agent-hook-opencode-tui-identity.test.ts | 8 - .../agent-hook-provider-normalization.test.ts | 37 +- src/wsl-guest/agent-hook-server.test.ts | 330 +----------------- src/wsl-guest/relay-command-env.test.ts | 24 -- 68 files changed, 21 insertions(+), 3850 deletions(-) delete mode 100644 src/main/automations/schedule-drift-report.test.ts delete mode 100644 src/main/azure-devops/pull-request-mappers.test.ts delete mode 100644 src/main/bitbucket/pull-request-mappers.test.ts delete mode 100644 src/main/browser/cookies/browser-cookie-clear-preserve.test.ts delete mode 100644 src/main/browser/cookies/browser-cookie-registrable-family.test.ts delete mode 100644 src/preload/native-chat-visual-guest-theme.test.ts delete mode 100644 src/renderer/src/components/browser-pane/assemble-chrome/browser-chrome-folded-tools.test.tsx delete mode 100644 src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.test.tsx delete mode 100644 src/renderer/src/components/browser-pane/assemble-chrome/browser-navigation-control-row.test.tsx delete mode 100644 src/renderer/src/components/browser-pane/browser-external-app-prompt.test.ts delete mode 100644 src/renderer/src/components/browser-pane/browser-http-auth-prompt.test.ts delete mode 100644 src/renderer/src/components/browser-pane/describe-page/browser-favicon-url.test.ts delete mode 100644 src/shared/github/pr-comment-diff-hunk.test.ts delete mode 100644 src/shared/gitlab-projects.test.ts delete mode 100644 src/shared/hook-command-source-policy.test.ts delete mode 100644 src/shared/host-setting-overrides.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 7ffe1a3a86d..bd4ae36a3c4 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -358,7 +358,7 @@ 2 test-no-real-time-wait:src/shared/startup-command-staging.node-pty.test.ts 4 test-no-real-time-wait:src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts 1 test-no-real-time-wait:src/wsl-guest/agent-hook-canonical-status.test.ts -6 test-no-real-time-wait:src/wsl-guest/agent-hook-server.test.ts +5 test-no-real-time-wait:src/wsl-guest/agent-hook-server.test.ts 1 test-no-real-time-wait:tests/e2e/accumulated-workspace-status-fixture.ts 1 test-no-real-time-wait:tests/e2e/agent-session-live-force-exit-resume.spec.ts 3 test-no-real-time-wait:tests/e2e/agent-session-log-tail-stability.spec.ts @@ -563,7 +563,6 @@ 2 test-no-wall-clock:src/main/antigravity/posix-hook-invocation.test.ts 2 test-no-wall-clock:src/main/browser/cookies/browser-cookie-import-partition-reland.electron.test.ts 2 test-no-wall-clock:src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts -1 test-no-wall-clock:src/main/claude-accounts/claude-account-folder.test.ts 1 test-no-wall-clock:src/main/claude/claude-background-wake-retention.test.ts 1 test-no-wall-clock:src/main/claude/claude-descendant-escalation-boundary.test.ts 1 test-no-wall-clock:src/main/claude/claude-folder-trust-file.test.ts @@ -810,10 +809,9 @@ 2 test-no-wall-clock:src/shared/startup-command-staging.node-pty.test.ts 1 test-no-wall-clock:src/shared/startup-command-staging.test.ts 2 test-no-wall-clock:src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts -14 test-no-wall-clock:src/wsl-guest/agent-hook-integration.test.ts +10 test-no-wall-clock:src/wsl-guest/agent-hook-integration.test.ts 1 test-no-wall-clock:src/wsl-guest/agent-hook-opencode-tui-identity.test.ts -1 test-no-wall-clock:src/wsl-guest/agent-hook-provider-normalization.test.ts -2 test-no-wall-clock:src/wsl-guest/agent-hook-server.test.ts +1 test-no-wall-clock:src/wsl-guest/agent-hook-server.test.ts 1 test-no-wall-clock:src/wsl-guest/relay-idle-process-owner.test.ts 1 test-no-wall-clock:tests/e2e/cross-version-wire/cross-version-web-device-key.unit.test.ts 2 test-no-wall-clock:tests/e2e/cross-version-wire/legacy-relay-bridge.unit.test.ts @@ -948,7 +946,6 @@ 1 test-timeout-needs-reason:src/shared/source-control/checks/logs/check-job-log-text-performance.test.ts 1 test-timeout-needs-reason:src/shared/workspace-disk-space/workspace-space-entry-traversal.test.ts 1 test-timeout-needs-reason:src/shared/wsl-login-shell-command.test.ts -1 test-timeout-needs-reason:src/wsl-guest/agent-hook-server.test.ts 1 test-timeout-needs-reason:tests/e2e/active-view-restart-restore.spec.ts 1 test-timeout-needs-reason:tests/e2e/agent-send-picker-reveal.spec.ts 1 test-timeout-needs-reason:tests/e2e/agent-session-log-tail-stability.spec.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 2029f26161e..b5c0746f0a8 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -929,14 +929,11 @@ "src/main/automations/runtime-chat-run-observer.test.ts": 6812, "src/main/automations/runtime-terminal-run-observer-evidence.test.ts": 230, "src/main/automations/runtime-terminal-run-observer.test.ts": 4026, - "src/main/automations/schedule-drift-report.test.ts": 83, "src/main/automations/service-precheck.test.ts": 2057, "src/main/automations/service.test.ts": 2970, - "src/main/azure-devops/pull-request-mappers.test.ts": 49, "src/main/azure-devops/repository-ref.test.ts": 392, "src/main/bitbucket/credential-connection.test.ts": 156, "src/main/bitbucket/credential-store.test.ts": 245, - "src/main/bitbucket/pull-request-mappers.test.ts": 44, "src/main/bitbucket/repository-ref.test.ts": 426, "src/main/bitbucket/status-no-decrypt.test.ts": 256, "src/main/updater/browser-sidecar-owner.test.ts": 53, @@ -1074,7 +1071,6 @@ "src/main/browser/cdp/transport/cdp-ws-proxy.test.ts": 2756, "src/main/browser/cookies/chromium/chromium-cookie-snapshot.test.ts": 457, "src/main/browser/cookies/client-route/client-route-cookie-import-source-store.test.ts": 147, - "src/main/browser/cookies/browser-cookie-clear-preserve.test.ts": 133, "src/main/browser/cookies/browser-cookie-clear-store-lifecycle.test.ts": 183, "src/main/browser/cookies/browser-cookie-clear-store.test.ts": 93, "src/main/browser/cookies/browser-cookie-import-clear-atomicity.test.ts": 112, @@ -1091,7 +1087,6 @@ "src/main/browser/cookies/browser-cookie-import.comet.test.ts": 1501, "src/main/browser/cookies/browser-cookie-import.test.ts": 1304, "src/main/browser/cookies/browser-cookie-public-suffix-scope.test.ts": 92, - "src/main/browser/cookies/browser-cookie-registrable-family.test.ts": 79, "src/main/browser/cookies/browser-cookie-samesite.electron.test.ts": 1882, "src/main/browser/cookies/sources/browser-cookie-decryption.test.ts": 74, "src/main/browser/cookies/sources/browser-cookie-import-undecryptable.test.ts": 541, @@ -5651,9 +5646,6 @@ "src/renderer/src/components/browser-pane/annotate/useMarkupEditor.test.ts": 364, "src/renderer/src/components/browser-pane/annotate/useMarkupPointerHandlers.test.ts": 280, "src/renderer/src/components/browser-pane/assemble-chrome/BrowserPane.webview-preferences.test.ts": 1920, - "src/renderer/src/components/browser-pane/assemble-chrome/browser-chrome-folded-tools.test.tsx": 326, - "src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.test.tsx": 1818, - "src/renderer/src/components/browser-pane/assemble-chrome/browser-navigation-control-row.test.tsx": 427, "src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx": 25933, "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, @@ -5664,14 +5656,11 @@ "src/renderer/src/components/browser-pane/browser-client-page-profile-staging.test.ts": 434, "src/renderer/src/components/browser-pane/browser-client-page-retained-drag-passthrough.test.ts": 501, "src/renderer/src/components/browser-pane/browser-client-page-retained-registry.test.ts": 550, - "src/renderer/src/components/browser-pane/browser-external-app-prompt.test.ts": 204, - "src/renderer/src/components/browser-pane/browser-http-auth-prompt.test.ts": 205, "src/renderer/src/components/browser-pane/browser-page-prompts.test.ts": 360, "src/renderer/src/components/browser-pane/browser-reopen-on-server.test.ts": 258, "src/renderer/src/components/browser-pane/browser-site-permission-prompt.test.ts": 206, "src/renderer/src/components/browser-pane/describe-page/browser-annotation-geometry.test.ts": 237, "src/renderer/src/components/browser-pane/describe-page/browser-artifact-upload.test.ts": 1902, - "src/renderer/src/components/browser-pane/describe-page/browser-favicon-url.test.ts": 44, "src/renderer/src/components/browser-pane/describe-page/browser-page-url-display.test.ts": 1937, "src/renderer/src/components/browser-pane/describe-page/live-browser-url-registry.test.ts": 43, "src/renderer/src/components/browser-pane/history/browser-history-view-rows.test.ts": 437, @@ -8739,7 +8728,6 @@ "src/shared/github/account-binding.test.ts": 48, "src/shared/github/api-availability.test.ts": 47, "src/shared/github/owner-slug.test.ts": 45, - "src/shared/github/pr-comment-diff-hunk.test.ts": 47, "src/shared/source-control/review-comments/pr-comments-resolution-prompt.test.ts": 49, "src/shared/github/pr-reviewer-display.test.ts": 56, "src/shared/github/project-board-columns.test.ts": 64, @@ -8751,7 +8739,6 @@ "src/shared/github/pull-request-merge-methods.test.ts": 41, "src/shared/github/repository-identity-key.test.ts": 39, "src/shared/source-control/checks/gitlab/gitlab-job-log-excerpt.test.ts": 95, - "src/shared/gitlab-projects.test.ts": 42, "src/shared/grok-model-list-probe.test.ts": 54, "src/shared/grok-session-paths.test.ts": 104, "src/shared/handled-wire-discriminant.test.ts": 45, @@ -8760,11 +8747,9 @@ "src/shared/headless-serve-ozone-platform.test.ts": 44, "src/shared/agent-launch/startup/hermes-startup-query.windows.test.ts": 43, "src/shared/home-or-filesystem-root.test.ts": 54, - "src/shared/hook-command-source-policy.test.ts": 43, "src/shared/host-authority.test.ts": 47, "src/shared/host-automatic-work-budget.test.ts": 48, "src/shared/host-balanced-listing-scaling.test.ts": 64, - "src/shared/host-setting-overrides.test.ts": 55, "src/shared/host-spawn-admission.test.ts": 183, "src/shared/source-control/hosted-review/hosted-review-refs.test.ts": 57, "src/shared/html-file-url.test.ts": 49, diff --git a/mobile/src/automations/AutomationManager.run-history.spec.tsx b/mobile/src/automations/AutomationManager.run-history.spec.tsx index eb5726c26e5..8c96679fbd5 100644 --- a/mobile/src/automations/AutomationManager.run-history.spec.tsx +++ b/mobile/src/automations/AutomationManager.run-history.spec.tsx @@ -1,65 +1,16 @@ import { createElement } from 'react' import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' import { expect, it, vi } from 'vitest' -import { AutomationEditor } from './AutomationEditor' -import { AutomationRunList } from './AutomationRunList' import { AutomationRunDetails } from './AutomationRunDetails' -import { MobileSegmentedControl } from '../components/MobileSegmentedControl' import { automationClient, savedRun } from './automation-test-fixtures' export function registerAutomationRunHistoryTests({ - mount, root, - press, setTree }: { - mount: () => Promise> root: () => ReactTestInstance - press: (label: string) => Promise setTree: (tree: ReactTestRenderer) => void }): void { - it('observes history only while a history consumer is visible', async () => { - const port = await mount() - const historyReads = () => - port.send.mock.calls.filter(([method]) => method === 'automation.runs') - const refresh = async () => { - await act(async () => { - port.event({ type: 'automationsChanged' }) - }) - } - const tab = async (value: 'automations' | 'runs') => { - await act(async () => { - root().findByType(MobileSegmentedControl).props.onSelect(value) - }) - } - const catalogReads = port.send.mock.calls.filter( - ([method]) => method === 'automation.list' - ).length - expect(historyReads()).toHaveLength(0) - await refresh() - expect( - port.send.mock.calls.filter(([method]) => method === 'automation.list').length - ).toBeGreaterThan(catalogReads) - expect(historyReads()).toHaveLength(0) - await press('New automation') - expect(root().findByType(AutomationEditor)).toBeTruthy() - await refresh() - expect(historyReads()).toHaveLength(0) - - await tab('runs') - expect(historyReads()).toHaveLength(1) - const original = root().findByType(AutomationRunList).props.history.runs[0] - await tab('automations') - await refresh() - expect(historyReads()).toHaveLength(1) - await press('New automation') - await refresh() - expect(historyReads()).toHaveLength(1) - await tab('runs') - expect(historyReads()).toHaveLength(2) - expect(root().findByType(AutomationRunList).props.history.runs[0]).toEqual(original) - }) - it('retries a failed full-row read when history re-reads the row', async () => { const preview = { ...savedRun(), diff --git a/mobile/src/automations/AutomationManager.test.tsx b/mobile/src/automations/AutomationManager.test.tsx index 94762327037..3c82b8048fc 100644 --- a/mobile/src/automations/AutomationManager.test.tsx +++ b/mobile/src/automations/AutomationManager.test.tsx @@ -200,7 +200,7 @@ async function mount( } describe('mobile automation navigation and setup', () => { - registerAutomationRunHistoryTests({ mount, root, press, setTree }) + registerAutomationRunHistoryTests({ root, setTree }) registerAutomationPresentationTests({ inventory, root, press, setTree, mount }) registerAutomationHostReselectionTests({ inventory, diff --git a/src/cli/runtime/environment-pairing-exchange.test.ts b/src/cli/runtime/environment-pairing-exchange.test.ts index bb5625bf2d0..90b284230a4 100644 --- a/src/cli/runtime/environment-pairing-exchange.test.ts +++ b/src/cli/runtime/environment-pairing-exchange.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import { encodePairingOffer, parsePairingCode } from '../../shared/remote-runtime/pairing/pairing' +import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' import { RemoteRuntimeClientError } from '../../shared/remote-runtime/remote-runtime-client-error' -import { PAIRING_TICKET_EXCHANGE_RUNTIME_CAPABILITY } from '../../shared/remote-runtime/pairing/ticket-exchange-capability' import { exchangeCliPairingCode } from './environment-pairing-exchange' const pairingCode = encodePairingOffer({ @@ -12,17 +11,6 @@ const pairingCode = encodePairingOffer({ }) describe('exchangeCliPairingCode', () => { - it('exchanges when the host advertises it', async () => { - const send = vi.fn(async (_connection: unknown, method: string) => - method === 'status.get' - ? { ok: true, result: { capabilities: [PAIRING_TICKET_EXCHANGE_RUNTIME_CAPABILITY] } } - : { ok: true, result: { deviceId: 'd' } } - ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the stub answers the two methods this helper sends with their real result shapes. - const saved = await exchangeCliPairingCode(pairingCode, send as never) - expect(parsePairingCode(saved)?.deviceToken).toMatch(/^[0-9a-f]{48}$/) - }) - 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) diff --git a/src/main/automations/external-automation-owner-guard.test.ts b/src/main/automations/external-automation-owner-guard.test.ts index 50e8e1d9ba9..c7eb96bfece 100644 --- a/src/main/automations/external-automation-owner-guard.test.ts +++ b/src/main/automations/external-automation-owner-guard.test.ts @@ -4,7 +4,7 @@ import { AutomationOwnerConflictError } from '../../shared/automation-owner-conf import type { AutomationOwnerRef } from '../../shared/automation-owner-ref' import { EXTERNAL_AUTOMATION_SCOPE_CODES, - ExternalAutomationScopeError + type ExternalAutomationScopeError } from '../../shared/external-automation-scope' import type { ExternalAutomationProvider } from '../../shared/automations-types' import type { SshTarget } from '../../shared/ssh-types' @@ -35,51 +35,6 @@ function desktopSsh(targetId: string, targetGeneration: number): AutomationOwner } describe('resolveExternalAutomationScope', () => { - it('resolves desktop + self to the local target', () => { - const scope = resolveExternalAutomationScope( - { owner: desktopSelf, provider: 'openclaw' }, - registry([]) - ) - - expect(scope.target).toEqual({ type: 'local' }) - expect(scope.sshTarget).toBeNull() - expect(scope.managerId).toBe('openclaw:local') - }) - - it('resolves a desktop SSH host whose registration generation still matches', () => { - const target = sshTarget() - - const scope = resolveExternalAutomationScope( - { owner: desktopSsh('target-a', 3), provider: 'openclaw' }, - registry([target]) - ) - - expect(scope.target).toEqual({ type: 'ssh', connectionId: 'target-a' }) - expect(scope.sshTarget).toBe(target) - expect(scope.managerId).toBe('openclaw:ssh:target-a') - }) - - it('excludes a runtime-owned target instead of exposing it', () => { - const target = sshTarget({ owner: { type: 'on-demand-runtime', runtimeId: 'rt-1' } }) - - expect(() => - resolveExternalAutomationScope( - { owner: desktopSsh('target-a', 3), provider: 'openclaw' }, - registry([target]) - ) - ).toThrow(ExternalAutomationScopeError) - try { - resolveExternalAutomationScope( - { owner: desktopSsh('target-a', 3), provider: 'openclaw' }, - registry([target]) - ) - } catch (error) { - expect((error as ExternalAutomationScopeError).code).toBe( - EXTERNAL_AUTOMATION_SCOPE_CODES.targetHidden - ) - } - }) - it('hides a runtime-owned target even when the captured generation is wrong', () => { const target = sshTarget({ generation: 9, diff --git a/src/main/automations/external-automation-probe-scheduler.test.ts b/src/main/automations/external-automation-probe-scheduler.test.ts index abdc4da515f..f293bd0cb49 100644 --- a/src/main/automations/external-automation-probe-scheduler.test.ts +++ b/src/main/automations/external-automation-probe-scheduler.test.ts @@ -13,48 +13,6 @@ function deferred(): { promise: Promise; resolve: (value: T) => void } { } describe('ExternalAutomationProbeScheduler', () => { - it('never runs more probes at once than its bound allows', async () => { - const scheduler = new ExternalAutomationProbeScheduler({ concurrency: 2 }) - const gates = [deferred(), deferred(), deferred()] - const started: string[] = [] - - const promises = gates.map((gate, index) => - scheduler.schedule({ - key: `probe-${index}`, - scopeKey: 'owner:desktop:self', - run: () => { - started.push(`probe-${index}`) - return gate.promise - } - }) - ) - - expect(started).toEqual(['probe-0', 'probe-1']) - expect(scheduler.queued).toBe(1) - - gates[0]?.resolve('a') - await promises[0] - expect(started).toEqual(['probe-0', 'probe-1', 'probe-2']) - - gates[1]?.resolve('b') - gates[2]?.resolve('c') - await Promise.all(promises) - }) - - it('shares one probe between concurrent requests for the same key', async () => { - const scheduler = new ExternalAutomationProbeScheduler() - const run = vi.fn(() => Promise.resolve('manager')) - - const [first, second] = await Promise.all([ - scheduler.schedule({ key: 'openclaw@self', scopeKey: 'owner:desktop:self', run }), - scheduler.schedule({ key: 'openclaw@self', scopeKey: 'owner:desktop:self', run }) - ]) - - expect(run).toHaveBeenCalledTimes(1) - expect(first).toBe('manager') - expect(second).toBe('manager') - }) - it('parks queued probes while Orca automation work holds priority', async () => { const scheduler = new ExternalAutomationProbeScheduler({ concurrency: 4 }) const run = vi.fn(() => Promise.resolve('manager')) diff --git a/src/main/automations/external-manager-scoped.test.ts b/src/main/automations/external-manager-scoped.test.ts index 8c4e6159724..0734c1a81a6 100644 --- a/src/main/automations/external-manager-scoped.test.ts +++ b/src/main/automations/external-manager-scoped.test.ts @@ -5,15 +5,9 @@ import { ExternalAutomationProbeScheduler } from './external-automation-probe-sc import { SSH_HOST_NOT_SERVED_MESSAGE } from '../providers/ssh-host-not-served-error' import { AutomationOwnerConflictError } from '../../shared/automation-owner-conflict' import type { AutomationOwnerRef } from '../../shared/automation-owner-ref' -import { - EXTERNAL_AUTOMATION_SCOPE_CODES, - ExternalAutomationScopeError -} from '../../shared/external-automation-scope' -import type { ExternalAutomationProvider } from '../../shared/automations-types' import type { SshTarget } from '../../shared/ssh-types' import type * as Fs from 'node:fs' import type * as Os from 'node:os' -import { join } from 'node:path' const runProcessMock = vi.hoisted(() => vi.fn()) const existsSyncMock = vi.hoisted(() => vi.fn<(file: Fs.PathLike) => boolean>(() => false)) @@ -44,11 +38,6 @@ function sshTarget(overrides: Partial = {}): SshTarget { } } -const desktopSelf: AutomationOwnerRef = { - authority: { kind: 'desktop' }, - selector: { kind: 'self' } -} - function desktopSsh(targetId: string, targetGeneration: number): AutomationOwnerRef { return { authority: { kind: 'desktop' }, selector: { kind: 'ssh', targetId, targetGeneration } } } @@ -80,47 +69,6 @@ afterEach(() => { }) describe('scoped external automations', () => { - it('discovers only OpenClaw and leaves isolated Hermes cron files untouched', async () => { - const files = new Map([ - [join(fixtureHome, '.hermes', 'cron', 'jobs.json'), '[{"id":"hermes-job","enabled":true}]'], - [join(fixtureHome, '.hermes', 'state.db'), 'Hermes session fixture'], - [join(fixtureHome, '.hermes', 'cron', 'executions.db'), 'Hermes execution fixture'], - [join(fixtureHome, '.hermes', 'cron', 'output', 'hermes-job', 'run.md'), '# Output\nDone'], - [join(fixtureHome, '.hermes', 'config.yaml'), 'model: fixture-model'], - [ - join(fixtureHome, '.openclaw', 'cron', 'jobs.json'), - '{"jobs":[{"id":"claw-job","name":"OpenClaw job","enabled":true}]}' - ] - ]) - const before = [...files] - existsSyncMock.mockImplementation((file) => files.has(String(file))) - readFileMock.mockImplementation(async (file) => { - const content = files.get(String(file)) - if (content === undefined) { - throw new Error('Unexpected fixture read') - } - return content - }) - - const entry = await buildEngine([]).listManager({ owner: desktopSelf, provider: 'openclaw' }) - - expect(entry.manager?.jobs.map((job) => job.id)).toEqual(['claw-job']) - expect(readFileMock).toHaveBeenCalledExactlyOnceWith( - join(fixtureHome, '.openclaw', 'cron', 'jobs.json'), - 'utf-8' - ) - expect(existsSyncMock).toHaveBeenCalledExactlyOnceWith( - join(fixtureHome, '.openclaw', 'cron', 'jobs.json') - ) - expect(runProcessMock).toHaveBeenCalledExactlyOnceWith({ - program: process.platform === 'win32' ? 'where' : 'which', - args: ['openclaw'], - timeoutMs: 5_000 - }) - expect(writeFileMock).not.toHaveBeenCalled() - expect([...files]).toEqual(before) - }) - it('reports an SSH host this process does not serve without probing this computer', async () => { const engine = buildEngine([sshTarget(), sshTarget({ id: 'target-b', generation: 1 })]) @@ -133,56 +81,6 @@ describe('scoped external automations', () => { expect(runProcessMock).not.toHaveBeenCalled() }) - it('fails closed on a stale generation without probing', async () => { - const engine = buildEngine([sshTarget({ generation: 4 })]) - - await expect( - engine.listManager({ owner: desktopSsh('target-a', 3), provider: 'openclaw' }) - ).rejects.toBeInstanceOf(AutomationOwnerConflictError) - expect(runProcessMock).not.toHaveBeenCalled() - }) - - it('excludes a runtime-owned target without probing it', async () => { - const engine = buildEngine([ - sshTarget({ owner: { type: 'on-demand-runtime', runtimeId: 'rt-1' } }) - ]) - - await expect( - engine.listManager({ owner: desktopSsh('target-a', 3), provider: 'openclaw' }) - ).rejects.toBeInstanceOf(ExternalAutomationScopeError) - expect(runProcessMock).not.toHaveBeenCalled() - }) - - it('rejects a runtime authority before any probe', async () => { - const engine = buildEngine([]) - - await expect( - engine.listManager({ - owner: { - authority: { kind: 'runtime', environmentId: 'env-1', pairingRevision: 2 }, - selector: { kind: 'self' } - }, - provider: 'openclaw' - }) - ).rejects.toThrow(EXTERNAL_AUTOMATION_SCOPE_CODES.authorityNotSupported) - expect(runProcessMock).not.toHaveBeenCalled() - }) - - it('rejects an unknown provider before launching any command', async () => { - const engine = buildEngine([sshTarget()]) - const unknown = 'cron' as ExternalAutomationProvider - - await expect( - engine.runAction({ - owner: desktopSelf, - provider: unknown, - jobId: 'job-1', - action: 'delete' - }) - ).rejects.toThrow(EXTERNAL_AUTOMATION_SCOPE_CODES.providerNotAllowed) - expect(runProcessMock).not.toHaveBeenCalled() - }) - it('fails a scoped mutation closed when the host changed under the dialog', async () => { const engine = buildEngine([sshTarget({ generation: 5 })]) diff --git a/src/main/automations/external-manager.test.ts b/src/main/automations/external-manager.test.ts index 6b84ea91e9f..88e0a7bed6a 100644 --- a/src/main/automations/external-manager.test.ts +++ b/src/main/automations/external-manager.test.ts @@ -1,6 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { runExternalAutomationAction } from './external-manager' -import { mapOpenClawJobs } from './external-job-mappers' import { SSH_HOST_NOT_SERVED_MESSAGE } from '../providers/ssh-host-not-served-error' import type { ExternalAutomationAction, @@ -51,20 +50,6 @@ describe('runExternalAutomationAction', () => { expect(runProcessMock).not.toHaveBeenCalled() }) - it('rejects an action name that is not in the provider table', async () => { - await expect( - runExternalAutomationAction({ - managerId: 'openclaw:local', - provider: 'openclaw', - target: { type: 'local' }, - jobId: 'job-1', - action: 'purge' as ExternalAutomationAction - }) - ).rejects.toThrow('Unsupported external automation action.') - - expect(runProcessMock).not.toHaveBeenCalled() - }) - it('rejects an action inherited from the prototype chain', async () => { await expect( runExternalAutomationAction({ @@ -106,41 +91,3 @@ describe('runExternalAutomationAction', () => { expect(runProcessMock).not.toHaveBeenCalled() }) }) - -describe('mapOpenClawJobs', () => { - it('normalizes OpenClaw cron jobs into external automation rows', () => { - const jobs = mapOpenClawJobs('openclaw:local', { - version: 1, - jobs: [ - { - id: 'claw-1', - name: 'Morning report', - enabled: true, - schedule: { kind: 'cron', expr: '0 9 * * *', tz: 'America/Phoenix' }, - payload: { kind: 'agentTurn', message: 'Summarize overnight alerts' }, - state: { - nextRunAtMs: Date.parse('2026-05-16T16:00:00Z'), - lastRunAtMs: Date.parse('2026-05-15T16:00:00Z'), - lastRunStatus: 'ok' - } - } - ] - }) - - expect(jobs[0]).toMatchObject({ - id: 'claw-1', - managerId: 'openclaw:local', - provider: 'openclaw', - name: 'Morning report', - schedule: 'cron 0 9 * * * @ America/Phoenix', - rawSchedule: '0 9 * * *', - enabled: true, - state: 'ok', - prompt: 'Summarize overnight alerts', - promptPreview: 'Summarize overnight alerts', - nextRunAt: '2026-05-16T16:00:00.000Z', - lastRunAt: '2026-05-15T16:00:00.000Z', - lastStatus: 'ok' - }) - }) -}) diff --git a/src/main/automations/schedule-drift-report.test.ts b/src/main/automations/schedule-drift-report.test.ts deleted file mode 100644 index a97b00ad104..00000000000 --- a/src/main/automations/schedule-drift-report.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { Automation } from '../../shared/automations-types' -import { reportAutomationScheduleDrift } from './schedule-drift-report' - -const makeAutomation = (name: string, rrule: string): Automation => ({ - id: `id-${name}`, - name, - prompt: 'Check the repo', - precheck: null, - agentId: 'claude', - projectId: 'r1', - executionTargetType: 'local', - executionTargetId: 'local', - schedulerOwner: 'local_host_service', - workspaceMode: 'existing', - workspaceId: 'wt1', - baseBranch: null, - reuseSession: false, - timezone: 'UTC', - rrule, - dtstart: 0, - enabled: true, - nextRunAt: 0, - missedRunPolicy: 'run_once_within_grace', - missedRunGraceMinutes: 720, - createdAt: 0, - updatedAt: 0 -}) - -describe('automation schedule drift report', () => { - afterEach(() => { - vi.restoreAllMocks() - }) - - it('names each affected record and which way it moved', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const count = reportAutomationScheduleDrift([ - makeAutomation('Quarter-hourly sweep', '5/15 * * * *'), - makeAutomation('Odd days and Mondays', '0 9 */2 * 1'), - makeAutomation('Weekday standup', '30 9 * * 1-5') - ]) - - expect(count).toBe(2) - const lines = warn.mock.calls.map((call) => String(call[0])) - expect(lines[0]).toContain('2 saved schedule(s) changed meaning') - expect( - lines.some((l) => l.includes('Quarter-hourly sweep') && l.includes('now runs more')) - ).toBe(true) - expect( - lines.some((l) => l.includes('Odd days and Mondays') && l.includes('now runs fewer')) - ).toBe(true) - expect(lines.some((l) => l.includes('Weekday standup'))).toBe(false) - }) - - it('says nothing when no saved schedule drifted', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - expect(reportAutomationScheduleDrift([makeAutomation('Hourly', '0 * * * *')])).toBe(0) - expect(warn).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/azure-devops/pull-request-mappers.test.ts b/src/main/azure-devops/pull-request-mappers.test.ts deleted file mode 100644 index a5054936f85..00000000000 --- a/src/main/azure-devops/pull-request-mappers.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { deriveAzureDevOpsStatus, mapAzureDevOpsPullRequestState } from './pull-request-mappers' - -describe('Azure DevOps pull request mappers', () => { - it('maps Azure DevOps PR states into the hosted review state set', () => { - expect(mapAzureDevOpsPullRequestState({ status: 'active' })).toBe('open') - expect(mapAzureDevOpsPullRequestState({ status: 'active', isDraft: true })).toBe('draft') - expect(mapAzureDevOpsPullRequestState({ status: 'completed' })).toBe('merged') - expect(mapAzureDevOpsPullRequestState({ status: 'abandoned' })).toBe('closed') - }) - - it('derives check status from Azure DevOps PR and commit status states', () => { - expect(deriveAzureDevOpsStatus([{ state: 'succeeded' }])).toBe('success') - expect(deriveAzureDevOpsStatus([{ state: 'succeeded' }, { state: 'pending' }])).toBe('pending') - expect(deriveAzureDevOpsStatus([{ state: 'succeeded' }, { state: 'failed' }])).toBe('failure') - expect(deriveAzureDevOpsStatus([])).toBe('neutral') - }) -}) diff --git a/src/main/bitbucket/credential-connection.test.ts b/src/main/bitbucket/credential-connection.test.ts index 495a875ec3a..6f212bf419b 100644 --- a/src/main/bitbucket/credential-connection.test.ts +++ b/src/main/bitbucket/credential-connection.test.ts @@ -44,31 +44,6 @@ afterEach(() => { }) describe('Bitbucket credential connection', () => { - it('verifies credentials before saving and reports a stored connection', async () => { - const conn = await loadModule() - globalThis.fetch = vi.fn(async () => - Response.json({ username: 'ada' }) - ) as unknown as typeof fetch - - await expect( - conn.connectBitbucket({ - authMode: 'basic', - email: 'ada@example.com', - apiToken: 'tok' - }) - ).resolves.toEqual({ ok: true, account: 'ada' }) - - expect(conn.getBitbucketConnectionStatus()).toEqual({ - configured: true, - source: 'stored', - credentialProtection: 'sealed', - account: 'ada', - authMode: 'basic', - email: 'ada@example.com', - baseUrl: null - }) - }) - it('sends Basic auth built from the entered email and API token', async () => { const conn = await loadModule() const fetchSpy = vi.fn(async () => Response.json({ username: 'ada' })) @@ -131,23 +106,4 @@ describe('Bitbucket credential connection', () => { expect(result.ok).toBe(false) expect(fetchSpy).not.toHaveBeenCalled() }) - - it('reports environment variables as the source and takes precedence over stored creds', async () => { - const conn = await loadModule() - globalThis.fetch = vi.fn(async () => - Response.json({ username: 'ada' }) - ) as unknown as typeof fetch - await conn.connectBitbucket({ - authMode: 'basic', - email: 'ada@example.com', - apiToken: 'tok' - }) - - process.env.ORCA_BITBUCKET_ACCESS_TOKEN = 'env-token' - expect(conn.getBitbucketConnectionStatus()).toMatchObject({ - configured: true, - source: 'environment', - authMode: 'token' - }) - }) }) diff --git a/src/main/bitbucket/credential-store.test.ts b/src/main/bitbucket/credential-store.test.ts index b30911401fd..03976511452 100644 --- a/src/main/bitbucket/credential-store.test.ts +++ b/src/main/bitbucket/credential-store.test.ts @@ -82,22 +82,6 @@ beforeEach(() => { }) describe('Bitbucket credential store', () => { - it('writes both credential files 0600', async () => { - const store = await loadStore() - store.saveBitbucketCredential({ - authMode: 'token', - email: null, - baseUrl: null, - account: 'dev', - accessToken: 'access-secret', - apiToken: null - }) - - for (const file of ['bitbucket-credential.enc', 'bitbucket-credential.json']) { - expect(statSync(join(tempHome, '.orca', file)).mode & 0o777).toBe(0o600) - } - }) - it('re-tightens permissions when overwriting an existing credential', async () => { const store = await loadStore() const save = (account: string): void => @@ -266,25 +250,6 @@ describe('Bitbucket credential store', () => { }) }) - it('writes the whole credential even when the filesystem short-writes (STA-3941)', async () => { - const store = await loadStore({ shortWrites: true }) - store.saveBitbucketCredential({ - authMode: 'basic', - email: 'ada@example.com', - baseUrl: null, - account: 'ada', - accessToken: null, - apiToken: 'a-token-long-enough-to-need-several-writes' - }) - store._resetBitbucketCredentialCache() - - expect(store.loadStoredBitbucketSecret({ force: true })).toMatchObject({ - apiToken: 'a-token-long-enough-to-need-several-writes', - email: 'ada@example.com' - }) - expect(store.getStoredBitbucketMetadata()?.account).toBe('ada') - }) - it('clears both files and in-memory state on disconnect', async () => { const store = await loadStore() store.saveBitbucketCredential({ @@ -321,12 +286,4 @@ describe('Bitbucket credential store', () => { expect(() => store.clearStoredBitbucketCredential()).toThrow(/permission denied/) expect(existsSync(join(tempHome, '.orca', 'bitbucket-credential.enc'))).toBe(true) }) - - it('ignores a missing file on disconnect', async () => { - const missing: NodeJS.ErrnoException = Object.assign(new Error('no such file'), { - code: 'ENOENT' - }) - const store = await loadStore({ unlinkError: missing }) - expect(() => store.clearStoredBitbucketCredential()).not.toThrow() - }) }) diff --git a/src/main/bitbucket/pull-request-mappers.test.ts b/src/main/bitbucket/pull-request-mappers.test.ts deleted file mode 100644 index dd3d146c2d9..00000000000 --- a/src/main/bitbucket/pull-request-mappers.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { deriveBitbucketBuildStatus, mapBitbucketPullRequestState } from './pull-request-mappers' - -describe('Bitbucket pull request mappers', () => { - it('normalizes Bitbucket pull request states', () => { - expect(mapBitbucketPullRequestState('OPEN')).toBe('open') - expect(mapBitbucketPullRequestState('MERGED')).toBe('merged') - expect(mapBitbucketPullRequestState('DECLINED')).toBe('closed') - expect(mapBitbucketPullRequestState('SUPERSEDED')).toBe('closed') - }) - - it('derives Orca check status from Bitbucket build statuses', () => { - expect(deriveBitbucketBuildStatus([])).toBe('neutral') - expect(deriveBitbucketBuildStatus([{ state: 'SUCCESSFUL' }])).toBe('success') - expect(deriveBitbucketBuildStatus([{ state: 'INPROGRESS' }])).toBe('pending') - expect(deriveBitbucketBuildStatus([{ state: 'FAILED' }])).toBe('failure') - }) -}) diff --git a/src/main/browser/cookies/browser-cookie-clear-preserve.test.ts b/src/main/browser/cookies/browser-cookie-clear-preserve.test.ts deleted file mode 100644 index 860a97df108..00000000000 --- a/src/main/browser/cookies/browser-cookie-clear-preserve.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -import type { Cookie } from 'electron' -import { describe, expect, it, vi } from 'vitest' -import { removeTransplantableCookies, type CookieClearSession } from './browser-cookie-import-clear' -import { importedDomainScope } from './browser-cookie-import-policy' - -/** A populated jar exposes loss from clearing more cookies than the import restores. */ -function jar(initial: Cookie[]) { - let cookies = [...initial] - const removeMock = vi.fn(async (url: string, name: string) => { - const host = new URL(url).hostname - cookies = cookies.filter( - (c) => !(c.name === name && (c.domain ?? '').replace(/^\./, '') === host.replace(/^\./, '')) - ) - }) - const snapshotMock = vi.fn(async (items: readonly { cookie: Cookie; url: string }[]) => - items.map(({ cookie, url }) => ({ - url, - name: cookie.name, - value: cookie.value, - domain: cookie.domain, - path: cookie.path - })) - ) - const session: CookieClearSession = { - cookies: { - get: async () => [...cookies], - remove: removeMock - }, - snapshotClearIdentities: snapshotMock, - restoreClearIdentities: async () => undefined - } as unknown as CookieClearSession - return { - session, - removeMock, - snapshotMock, - names: () => cookies.map((c) => c.name).sort(), - get: (name: string) => cookies.find((c) => c.name === name) - } -} - -const cookie = (domain: string, name: string, value = `${name}-live`): Cookie => - ({ domain, name, value, path: '/', secure: true }) as Cookie - -const coordinatesOf = (calls: readonly [string, string][]): string[] => - calls.map(([url, name]) => `${url}|${name}`) - -describe('removeTransplantableCookies — preserved families on a POPULATED jar', () => { - it('leaves a preserved family untouched while clearing everything else', async () => { - const target = jar([ - cookie('.mixed.example', 'apex-session'), - cookie('sub.mixed.example', 'sub-session'), - cookie('.other.example', 'stale') - ]) - - await removeTransplantableCookies( - target.session, - new Set(['mixed.example']), - importedDomainScope(['mixed.example', 'sub.mixed.example', 'other.example']) - ) - - expect(target.names()).toEqual(['apex-session', 'sub-session']) - expect(target.get('apex-session')?.value).toBe('apex-session-live') - expect(target.get('sub-session')?.value).toBe('sub-session-live') - }) - - it('submits no coordinate to a removal the snapshot cannot restore', async () => { - // Only remove coordinates covered by the frozen rollback snapshot. - const target = jar([ - cookie('.mixed.example', 'live-session'), - cookie('.other.example', 'stale') - ]) - - await removeTransplantableCookies( - target.session, - new Set(['mixed.example']), - importedDomainScope(['mixed.example', 'other.example']) - ) - - const removed = coordinatesOf(target.removeMock.mock.calls) - const snapshotted = target.snapshotMock.mock.calls.flatMap(([items]) => - items.map(({ cookie: c, url }) => `${url}|${c.name}`) - ) - expect(removed).toEqual(['https://other.example/|stale']) - expect(snapshotted).toEqual(removed) - }) - - it('preserves a family named by an IPv4 literal', async () => { - const target = jar([cookie('127.0.0.1', 'loopback-session'), cookie('.other.example', 'stale')]) - - await removeTransplantableCookies( - target.session, - new Set(['127.0.0.1']), - importedDomainScope(['127.0.0.1', 'other.example']) - ) - - expect(target.names()).toEqual(['loopback-session']) - }) - - it('preserves a single-label host family', async () => { - const target = jar([cookie('localhost', 'dev-session'), cookie('.other.example', 'stale')]) - - await removeTransplantableCookies( - target.session, - new Set(['localhost']), - importedDomainScope(['localhost', 'other.example']) - ) - - expect(target.names()).toEqual(['dev-session']) - }) - - it('keeps skip-path removals at concurrency eight', async () => { - let releaseRemovals: (() => void) | undefined - const removalsReleased = new Promise((resolve) => { - releaseRemovals = resolve - }) - let active = 0 - let maxActive = 0 - const remove = vi.fn(async (_url: string, _name: string) => { - active++ - maxActive = Math.max(maxActive, active) - await removalsReleased - active-- - }) - const cookies = [ - cookie('.preserved.example', 'live-session'), - ...Array.from({ length: 12 }, (_, index) => cookie('.other.example', `stale-${index}`)) - ] - const session = { - cookies: { get: async () => cookies, remove }, - snapshotClearIdentities: async (items: { cookie: Cookie; url: string }[]) => - items.map(({ cookie: entry, url }) => ({ url, ...entry })), - restoreClearIdentities: async () => undefined - } as unknown as CookieClearSession - - const clearing = removeTransplantableCookies( - session, - new Set(['preserved.example']), - importedDomainScope(['preserved.example', 'other.example']) - ) - await vi.waitFor(() => expect(remove).toHaveBeenCalledTimes(8)) - expect(maxActive).toBe(8) - releaseRemovals?.() - await clearing - - expect(remove).toHaveBeenCalledTimes(12) - expect(remove.mock.calls.map(([, name]) => name)).not.toContain('live-session') - }) -}) diff --git a/src/main/browser/cookies/browser-cookie-public-suffix-scope.test.ts b/src/main/browser/cookies/browser-cookie-public-suffix-scope.test.ts index e617a78affc..ee8e1d6afde 100644 --- a/src/main/browser/cookies/browser-cookie-public-suffix-scope.test.ts +++ b/src/main/browser/cookies/browser-cookie-public-suffix-scope.test.ts @@ -1,41 +1,8 @@ import { describe, expect, it } from 'vitest' -import { - domainIsInImportedScope, - importedDomainScope, - normalizeCookieImportDomain, - registrableFamily -} from './browser-cookie-import-policy' +import { normalizeCookieImportDomain } from './browser-cookie-import-policy' // Suffix-list changes can widen removal scopes and destroy unrelated sessions. describe('registrable family across public-suffix sections', () => { - it('keeps each PRIVATE-section tenant in its own family', () => { - expect(registrableFamily('foo.github.io')).toBe('foo.github.io') - expect(registrableFamily('bar.github.io')).toBe('bar.github.io') - expect(registrableFamily('bar.s3.amazonaws.com')).toBe('bar.s3.amazonaws.com') - expect(registrableFamily('foo.vercel.app')).toBe('foo.vercel.app') - }) - - it('refuses to name a bare public suffix as a family', () => { - expect(registrableFamily('com')).toBeNull() - expect(registrableFamily('co.uk')).toBeNull() - expect(registrableFamily('github.io')).toBeNull() - expect(registrableFamily('api.br')).toBeNull() - expect(registrableFamily('seg.ar')).toBeNull() - }) - - it('resolves ICANN suffixes to the registrable domain', () => { - expect(registrableFamily('a.b.example.co.uk')).toBe('example.co.uk') - expect(registrableFamily('www.example.com')).toBe('example.com') - expect(registrableFamily('foo.example.api.br')).toBe('example.api.br') - }) - - it('returns the canonicalised address for every IP spelling', () => { - expect(registrableFamily('127.0.0.1')).toBe('127.0.0.1') - expect(registrableFamily('127.1')).toBe('127.0.0.1') - expect(registrableFamily('2130706433')).toBe('127.0.0.1') - expect(registrableFamily('[::1]')).toBe('[::1]') - }) - it('rejects a bare suffix as an import domain but keeps real hosts', () => { expect(normalizeCookieImportDomain('co.uk')).toBeNull() expect(normalizeCookieImportDomain('api.br')).toBeNull() @@ -43,26 +10,3 @@ describe('registrable family across public-suffix sections', () => { expect(normalizeCookieImportDomain('foo.github.io')).toBe('foo.github.io') }) }) - -// Unlisted .local uses a two-label family boundary. -describe('unlisted .local suffix', () => { - it('pulls the shared parent into the removal scope', () => { - const scope = importedDomainScope(['app.orca.local']) - - expect(domainIsInImportedScope(scope, 'orca.local', false)).toBe(true) - expect(domainIsInImportedScope(scope, 'orca.local', true)).toBe(false) - }) -}) - -// Only *.compute.amazonaws.com is a suffix; the bare host belongs to amazonaws.com. -describe('suffix entries that changed shape upstream', () => { - it('reads bare compute.amazonaws.com as a registrable domain', () => { - expect(registrableFamily('compute.amazonaws.com')).toBe('amazonaws.com') - expect(normalizeCookieImportDomain('compute.amazonaws.com')).toBe('compute.amazonaws.com') - }) - - it('still refuses the wildcard child and the sibling private suffix', () => { - expect(registrableFamily('foo.compute.amazonaws.com')).toBeNull() - expect(registrableFamily('s3.amazonaws.com')).toBeNull() - }) -}) diff --git a/src/main/browser/cookies/browser-cookie-registrable-family.test.ts b/src/main/browser/cookies/browser-cookie-registrable-family.test.ts deleted file mode 100644 index c9080b83e6a..00000000000 --- a/src/main/browser/cookies/browser-cookie-registrable-family.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { registrableFamily } from './browser-cookie-import-policy' - -describe('registrableFamily', () => { - it.each([ - ['sub.example.com', 'example.com'], - ['a.b.c.example.co.uk', 'example.co.uk'], - ['example.com', 'example.com'], - ['.example.com', 'example.com'], - ['EXAMPLE.COM', 'example.com'], - ['user.github.io', 'user.github.io'], - ['localhost', 'localhost'] - ])('maps %s to %s', (host, expected) => { - expect(registrableFamily(host)).toBe(expected) - }) - - // Normalize alternate IP spellings before applying public-suffix rules. - it.each([ - ['127.0.0.1', '127.0.0.1'], - ['192.168.1.1', '192.168.1.1'], - ['127.1', '127.0.0.1'], - ['2130706433', '127.0.0.1'], - ['0x7f.1', '127.0.0.1'], - ['127.0.0.1.', '127.0.0.1'], - // The URL parser treats a leading zero as octal. - ['010.0.0.1', '8.0.0.1'] - ])('recognises the IPv4 literal %s as %s', (host, expected) => { - expect(registrableFamily(host)).toBe(expected) - }) - - it.each([ - ['[::1]', '[::1]'], - ['[2001:db8::1]', '[2001:db8::1]'] - ])('recognises the IPv6 literal %s', (host, expected) => { - expect(registrableFamily(host)).toBe(expected) - }) - - it.each([['com'], ['co.uk'], ['github.io']])('returns null for the public suffix %s', (host) => { - expect(registrableFamily(host)).toBeNull() - }) - - it('returns null for a domain that cannot be normalised', () => { - expect(registrableFamily('')).toBeNull() - expect(registrableFamily('http://evil.example/path')).toBeNull() - }) -}) diff --git a/src/main/claude-accounts/claude-account-folder.test.ts b/src/main/claude-accounts/claude-account-folder.test.ts index 703d118f7e7..b14649168c4 100644 --- a/src/main/claude-accounts/claude-account-folder.test.ts +++ b/src/main/claude-accounts/claude-account-folder.test.ts @@ -1,12 +1,4 @@ -import { - existsSync, - mkdirSync, - mkdtempSync, - rmSync, - symlinkSync, - utimesSync, - writeFileSync -} from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -29,7 +21,7 @@ vi.mock('../macos-keychain/generic-password', () => ({ } })) -import { readClaudeFolderLoginAsync, removeClaudeAccountFolder } from './claude-account-folder' +import { removeClaudeAccountFolder } from './claude-account-folder' import { claudeKeychainService } from './keychain' @@ -50,25 +42,6 @@ function fixture() { } describe('claude account folder', () => { - it('rereads a state file over a share only when its mtime or size changes', async () => { - const { home } = fixture() - const stateFile = join(home, '.claude.json') - await expect(readClaudeFolderLoginAsync(stateFile)).resolves.toBeNull() - writeFileSync(stateFile, JSON.stringify({ oauthAccount: { emailAddress: 'a@example.test' } })) - // Whole seconds avoid filesystem timestamp rounding. - const mtime = new Date(Math.floor(Date.now() / 1000) * 1000) - utimesSync(stateFile, mtime, mtime) - expect((await readClaudeFolderLoginAsync(stateFile))?.email).toBe('a@example.test') - // Hold size and mtime constant to prove the cached answer is reused. - writeFileSync(stateFile, JSON.stringify({ oauthAccount: { emailAddress: 'b@example.test' } })) - utimesSync(stateFile, mtime, mtime) - expect((await readClaudeFolderLoginAsync(stateFile))?.email).toBe('a@example.test') - utimesSync(stateFile, mtime, new Date(mtime.getTime() + 2_000)) - expect((await readClaudeFolderLoginAsync(stateFile))?.email).toBe('b@example.test') - rmSync(stateFile) - await expect(readClaudeFolderLoginAsync(stateFile)).resolves.toBeNull() - }) - // A real symlink needs Developer Mode on Windows (EPERM otherwise). it.skipIf(process.platform === 'win32')( 'unlinks shared history before deleting, and leaves the older layout alone', diff --git a/src/main/claude-accounts/claude-command-process-windows-only.test.ts b/src/main/claude-accounts/claude-command-process-windows-only.test.ts index 778e49d99f1..947bea6925c 100644 --- a/src/main/claude-accounts/claude-command-process-windows-only.test.ts +++ b/src/main/claude-accounts/claude-command-process-windows-only.test.ts @@ -44,14 +44,6 @@ afterEach(() => { Object.defineProperty(process, 'platform', { value: originalPlatform }) }) -it('says Claude is installed only on Windows instead of a raw spawn ENOENT', async () => { - Object.defineProperty(process, 'platform', { value: 'linux' }) - state.resolved.push(WINDOWS_ONLY, WINDOWS_ONLY, WINDOWS_ONLY) - await expect(runClaudeCommandProcess(['auth', 'status'], config, 1000)).rejects.toThrow( - 'Claude is installed only on Windows, not in this WSL distro. Install it inside the distro.' - ) -}) - it('never keeps the Windows-only answer, so a Claude installed in WSL since is used', async () => { Object.defineProperty(process, 'platform', { value: 'linux' }) // The first lookup sees only the Windows copy; every later one finds the new WSL install. diff --git a/src/main/claude-accounts/claude-login-session.test.ts b/src/main/claude-accounts/claude-login-session.test.ts index bbb91ad1b5b..dd81f503449 100644 --- a/src/main/claude-accounts/claude-login-session.test.ts +++ b/src/main/claude-accounts/claude-login-session.test.ts @@ -68,20 +68,6 @@ describe('runClaudeLoginSession', () => { expect(openWslSignInLink).not.toHaveBeenCalled() }) - it('never opens a link that is not a Claude sign-in, and keeps the login going', async () => { - const config = folder('wsl') - const openWslSignInLink = vi.fn() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const runCommand = claudeHandsOver(config, 'http://claude.com/oauth', () => - warn.mock.calls.some(([message]) => String(message).includes('unexpected sign-in link')) - ) - await expect( - runClaudeLoginSession(config, { runCommand, setCancel: vi.fn(), openWslSignInLink }) - ).resolves.toBeUndefined() - expect(openWslSignInLink).not.toHaveBeenCalled() - warn.mockRestore() - }) - it('never opens a link for a WSL login the user already cancelled', async () => { const config = folder('wsl') const openWslSignInLink = vi.fn() diff --git a/src/main/claude-accounts/claude-pasted-code-login.test.ts b/src/main/claude-accounts/claude-pasted-code-login.test.ts index 1ff8dae0589..5380c5f7027 100644 --- a/src/main/claude-accounts/claude-pasted-code-login.test.ts +++ b/src/main/claude-accounts/claude-pasted-code-login.test.ts @@ -5,7 +5,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { HostAccountSignInChannel } from '../../shared/host-account-sign-in-types' import type { ClaudeCommandConfig, ClaudeCommandOptions } from './claude-command-process' import { - CLAUDE_PASTED_CODE_REJECTED_MESSAGE, parseClaudePastedCodeSignInLink, runClaudePastedCodeLogin } from './claude-pasted-code-login' @@ -45,10 +44,6 @@ function channel(code = new Promise(() => {})) { } describe('parseClaudePastedCodeSignInLink', () => { - it('reads the pasted-code link from the captured transcript', () => { - expect(parseClaudePastedCodeSignInLink(TRANSCRIPT)).toBe(new URL(PASTE_LINK).toString()) - }) - it('waits for the whole link and ignores a localhost-callback one', () => { expect(parseClaudePastedCodeSignInLink(`visit: ${PASTE_LINK.slice(0, 80)}`)).toBeNull() expect(parseClaudePastedCodeSignInLink(`visit: ${LOCAL_LINK}\n`)).toBeNull() @@ -82,22 +77,6 @@ describe('runClaudePastedCodeLogin', () => { expect(readdirSync(folder.windowsPath)).toEqual([]) }) - it('names a refused code in words a person can act on', async () => { - const { value } = channel(Promise.resolve('wrong')) - const runCommand = vi.fn(async (_args, _config, _timeout, options) => { - let sent = false - options?.onStdin?.(() => { - sent = true - }) - options?.onStdout?.(TRANSCRIPT) - await vi.waitFor(() => expect(sent).toBe(true)) - throw new Error('Claude command failed: Login failed: Request failed with status code 400') - }) - await expect( - runClaudePastedCodeLogin(hostFolder(), runCommand, value, vi.fn()) - ).rejects.toThrow(CLAUDE_PASTED_CODE_REJECTED_MESSAGE) - }) - it('stops the login when the flow is cancelled, and spawns none once already cancelled', async () => { const { value, controller } = channel() let signal: AbortSignal | undefined diff --git a/src/main/claude-accounts/claude-sign-in-browser.test.ts b/src/main/claude-accounts/claude-sign-in-browser.test.ts index 43aaeef8199..09ac9ccd83c 100644 --- a/src/main/claude-accounts/claude-sign-in-browser.test.ts +++ b/src/main/claude-accounts/claude-sign-in-browser.test.ts @@ -40,19 +40,6 @@ describe('prepareClaudeSignInBrowser', () => { expect(readdirSync(home)).toEqual([]) } ) - - it.skipIf(process.platform === 'win32')('stops waiting once the sign-in ends', async () => { - const home = folder() - const browser = await prepareClaudeSignInBrowser({ - windowsPath: home, - linuxPath: null, - wslDistro: null - }) - const stop = new AbortController() - const next = browser!.nextLink(stop.signal) - stop.abort() - await expect(next).resolves.toBeNull() - }) }) describe('isClaudeLocalSignInLink', () => { diff --git a/src/preload/browser-password-detector.test.ts b/src/preload/browser-password-detector.test.ts index 041ef883666..a06fdf168c5 100644 --- a/src/preload/browser-password-detector.test.ts +++ b/src/preload/browser-password-detector.test.ts @@ -9,10 +9,6 @@ import type { BrowserPasswordGuestEnable } from '../shared/browser-passwords-types' import { installBrowserPasswordDetector } from './browser-password-detector' -import { - PRELOAD_BROWSER_PASSWORDS_GUEST_CHANNELS, - PRELOAD_BROWSER_PASSWORDS_TO_GUEST_CHANNELS -} from './browser-password-guest-channels' const CHANNEL = BROWSER_PASSWORDS_GUEST_CHANNELS @@ -166,11 +162,6 @@ afterEach(() => { }) describe('browser password detector', () => { - it('sends and listens on exactly the channels main uses', () => { - expect(PRELOAD_BROWSER_PASSWORDS_GUEST_CHANNELS).toEqual(BROWSER_PASSWORDS_GUEST_CHANNELS) - expect(PRELOAD_BROWSER_PASSWORDS_TO_GUEST_CHANNELS).toEqual(BROWSER_PASSWORDS_TO_GUEST_CHANNELS) - }) - it('installs only its main listeners until main enables the document', async () => { load(LOGIN_FORM) const addEventListener = vi.mocked(document.addEventListener) @@ -240,14 +231,6 @@ describe('browser password detector', () => { }) }) - it('sends nothing on a page without credential fields', async () => { - load('

hello

') - install() - enable() - await vi.advanceTimersByTimeAsync(2000) - expect(sent).toEqual([]) - }) - it('reports trusted typing after the debounce, with only typed values', async () => { load(LOGIN_FORM) el('#email').value = 'prefilled@example.com' @@ -363,34 +346,6 @@ describe('browser password detector', () => { expect(sentOn(CHANNEL.submitted)).toEqual([]) }) - it('reports a focused credential field with its box, and hides on blur and scroll', async () => { - load(LOGIN_FORM) - install() - enable() - window.innerWidth = 1280 - - focusIn(el('#pw')) - const fieldToken = readString(sentOn(CHANNEL.fieldFocused)[0], 'fieldToken') - expect(sentOn(CHANNEL.fieldFocused)[0]).toEqual({ - fieldToken: expect.any(String), - formSignature: expect.any(String), - role: 'password', - rect: { x: 10, y: 50, width: 200, height: 30 }, - viewportWidth: 1280 - }) - - el('#pw').dispatchEvent(new FocusEvent('focusout', { bubbles: true, composed: true })) - expect(sentOn(CHANNEL.fieldBlurred)).toEqual([{ fieldToken, reason: 'focusout' }]) - - focusIn(el('#email')) - expect(sentOn(CHANNEL.fieldFocused).at(-1)).toMatchObject({ role: 'username' }) - await vi.advanceTimersByTimeAsync(300) - window.dispatchEvent(new Event('scroll')) - expect(sentOn(CHANNEL.fieldBlurred)).toHaveLength(3) - window.dispatchEvent(new Event('scroll')) - expect(sentOn(CHANNEL.fieldBlurred)).toHaveLength(3) - }) - it('keeps viewport invalidation alive after a picker focus transfer', async () => { load(LOGIN_FORM) install() @@ -407,35 +362,6 @@ describe('browser password detector', () => { ]) }) - it('keeps a show-password toggle classified as a password', async () => { - load(LOGIN_FORM) - install() - enable() - el('#pw').setAttribute('type', 'text') - await vi.advanceTimersByTimeAsync(600) - - focusIn(el('#pw')) - - expect(sentOn(CHANNEL.fieldFocused)).toEqual([expect.objectContaining({ role: 'password' })]) - }) - - it('reports a field inside an open shadow root', async () => { - load('
') - const shadow = el('#host').attachShadow({ mode: 'open' }) - shadow.innerHTML = '
' - const pw = shadow.querySelector('input[type="password"]') - if (!(pw instanceof HTMLInputElement)) { - throw new Error('missing shadow password') - } - rects.set(pw, new DOMRect(10, 10, 200, 30)) - install() - enable() - - focusIn(pw) - - expect(sentOn(CHANNEL.fieldFocused)).toEqual([expect.objectContaining({ role: 'password' })]) - }) - it('detects and captures credentials when HTTP crypto has no randomUUID', async () => { vi.stubGlobal('crypto', { getRandomValues: crypto.getRandomValues.bind(crypto) }) load(LOGIN_FORM) @@ -448,32 +374,6 @@ describe('browser password detector', () => { expect(sentOn(CHANNEL.typed)).toEqual([expect.objectContaining({ password: 'http-password' })]) }) - it('walks the whole document at most once per interval while a page keeps adding many nodes', async () => { - load('
') - const walker = vi.spyOn(document, 'createTreeWalker') - const wholeDocumentWalks = (): number => - walker.mock.calls.filter(([root]) => root === document).length - install() - enable() - expect(wholeDocumentWalks()).toBe(1) - const feed = el('#feed') - const addBurst = async (): Promise => { - for (let i = 0; i < 250; i++) { - feed.appendChild(document.createElement('span')) - } - await vi.advanceTimersByTimeAsync(500) - } - - for (let i = 0; i < 8; i++) { - await addBurst() - } - expect(wholeDocumentWalks()).toBe(1) - - await addBurst() - await addBurst() - expect(wholeDocumentWalks()).toBe(2) - }) - it('discovers late nested shadow roots on interaction and observes later type changes', async () => { load('
') install() @@ -543,23 +443,6 @@ describe('browser password detector', () => { ]) }) - it('fills from the username field and replaces a placeholder value', () => { - load(LOGIN_FORM) - el('#email').value = 'Email' - install() - enable() - - fill({ - requestId: 'r', - fieldToken: focusedToken(el('#email')), - username: 'bob', - password: 'pw' - }) - - expect(el('#email').value).toBe('bob') - expect(el('#pw').value).toBe('pw') - }) - it('fills the picked account over a different username already in the field', () => { load(LOGIN_FORM) el('#email').value = 'carol@example.com' diff --git a/src/preload/browser-password-form-parser.test.ts b/src/preload/browser-password-form-parser.test.ts index 446cd095d5a..3139ad42165 100644 --- a/src/preload/browser-password-form-parser.test.ts +++ b/src/preload/browser-password-form-parser.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from 'vitest' import type { PasswordFieldDescriptor } from './browser-password-field-rules' -import { isPlaceholderUsernameValue } from './browser-password-field-rules' -import { parsePasswordForm, passwordFieldRoleIn } from './browser-password-form-parser' +import { parsePasswordForm } from './browser-password-form-parser' type TestField = PasswordFieldDescriptor & { key: string } @@ -307,34 +306,4 @@ describe('parsePasswordForm', () => { } }) }) - - it('reports each classified field role', () => { - const user = input('user') - const current = password('old', { value: 'x' }) - const fresh = password('new', { value: 'y' }) - const confirm = password('again', { value: 'y' }) - const other = input('other') - const parsed = parsePasswordForm({ fields: [user, current, fresh, confirm, other], text: '' }) - expect(parsed).not.toBeNull() - if (!parsed) { - return - } - expect( - [user, current, fresh, confirm, other].map((field) => passwordFieldRoleIn(parsed, field)) - ).toEqual(['username', 'password', 'new-password', 'new-password', null]) - }) -}) - -describe('isPlaceholderUsernameValue', () => { - it.each([ - ['', true], - [' Email ', true], - ['username', true], - ['Username or email', true], - ['@example.com', true], - ['alice@example.com', false], - ['alice', false] - ])('%j → %s', (value, expected) => { - expect(isPlaceholderUsernameValue(value)).toBe(expected) - }) }) diff --git a/src/preload/native-chat-visual-guest-theme.test.ts b/src/preload/native-chat-visual-guest-theme.test.ts deleted file mode 100644 index 95ba408925b..00000000000 --- a/src/preload/native-chat-visual-guest-theme.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { buildSync } from 'esbuild' -import { fileURLToPath } from 'node:url' -import { runInNewContext } from 'node:vm' -import { - NATIVE_CHAT_VISUAL_GUEST_THEME_READ as READ, - NATIVE_CHAT_VISUAL_GUEST_THEME_UPDATE as UPDATE -} from '../shared/native-chat/native-chat-visual-shell' - -const preload = buildSync({ - entryPoints: [fileURLToPath(new URL('./native-chat-visual-guest-theme.ts', import.meta.url))], - bundle: true, - platform: 'node', - format: 'cjs', - external: ['electron'], - write: false -}).outputFiles[0].text - -afterEach(() => vi.restoreAllMocks()) -describe('visual guest preload', () => { - it('installs initial CSS synchronously and changes appearance without replacing page state', () => { - const callbacks = new Map void>() - const theme = { css: ':root{--background:#111}', colorScheme: 'dark' } - const ipc = { - sendSync: vi.fn(() => theme), - on: vi.fn((name, callback) => callbacks.set(name, callback)) - } - const frame = { insertCSS: vi.fn(() => 'style-key'), removeInsertedCSS: vi.fn() } - const input = { value: 'keep this' } - const root = { classList: { toggle: vi.fn() } } - const document: { documentElement: typeof root | null; input: typeof input } = { - documentElement: null, - input - } - let onRoot: () => void = () => {} - const disconnect = vi.fn() - const observer = vi.fn() - const module = { - exports: { installNativeChatVisualGuestTheme: vi.fn() } - } - runInNewContext(preload, { - module, - exports: module.exports, - process: { isMainFrame: true }, - location: { href: 'file:///profile/chat-scratch/session/mock.html' }, - document, - MutationObserver: class { - constructor(callback: () => void) { - onRoot = callback - } - observe = observer - disconnect = disconnect - } - }) - module.exports.installNativeChatVisualGuestTheme(ipc, frame) - expect(ipc.sendSync).toHaveBeenCalledExactlyOnceWith(READ) - expect(frame.insertCSS).toHaveBeenCalledExactlyOnceWith(theme.css, { cssOrigin: 'author' }) - document.documentElement = root - onRoot() - expect(root.classList.toggle).toHaveBeenCalledWith('dark', true) - expect(disconnect).toHaveBeenCalledTimes(1) - callbacks.get(UPDATE)!({}, { css: ':root{--background:#fff}', colorScheme: 'light' }) - expect(frame.removeInsertedCSS).toHaveBeenCalledWith('style-key') - expect(root.classList.toggle).toHaveBeenLastCalledWith('dark', false) - expect(document.input).toBe(input) - expect(input.value).toBe('keep this') - }) - - it.each([ - [false, 'file:///mock.html'], - [true, 'https://example.com/'] - ])('does not request appearance for unrelated contexts', (isMainFrame, href) => { - const module = { - exports: { installNativeChatVisualGuestTheme: vi.fn() } - } - runInNewContext(preload, { - module, - exports: module.exports, - process: { isMainFrame }, - location: { href } - }) - const sendSync = vi.fn() - module.exports.installNativeChatVisualGuestTheme({ sendSync }, {}) - expect(sendSync).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/browser-pane/annotate/markup-shape-render.test.ts b/src/renderer/src/components/browser-pane/annotate/markup-shape-render.test.ts index 48026f637d8..f9380f0ae37 100644 --- a/src/renderer/src/components/browser-pane/annotate/markup-shape-render.test.ts +++ b/src/renderer/src/components/browser-pane/annotate/markup-shape-render.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' -import { drawShape, textInkBox } from './markup-shape-render' -import { HIGHLIGHT_ALPHA, type MarkupShape } from './markup-drawing-model' +import { textInkBox } from './markup-shape-render' // Record the context subset drawShape uses without requiring a real canvas. function makeRecordingCtx() { @@ -46,128 +45,6 @@ function makeRecordingCtx() { return { ctx: ctx as unknown as CanvasRenderingContext2D, calls, methods } } -describe('drawShape dispatch', () => { - it('strokes a multi-point pen as a polyline', () => { - const { ctx, methods } = makeRecordingCtx() - const shape: MarkupShape = { - id: 'p', - kind: 'pen', - color: '#ef4444', - width: 4, - points: [ - { x: 0, y: 0 }, - { x: 5, y: 5 }, - { x: 9, y: 1 } - ] - } - drawShape(ctx, shape) - expect(methods('moveTo')).toEqual([{ method: 'moveTo', args: [0, 0] }]) - expect(methods('lineTo')).toEqual([ - { method: 'lineTo', args: [5, 5] }, - { method: 'lineTo', args: [9, 1] } - ]) - expect(methods('stroke')).toHaveLength(1) - }) - - it('draws a dot for a single-point pen', () => { - const { ctx, methods } = makeRecordingCtx() - drawShape(ctx, { id: 'p', kind: 'pen', color: '#fff', width: 4, points: [{ x: 3, y: 3 }] }) - expect(methods('arc')).toHaveLength(1) - expect(methods('fill')).toHaveLength(1) - }) - - it('applies translucent alpha for highlights', () => { - const { ctx } = makeRecordingCtx() - drawShape(ctx, { - id: 'h', - kind: 'highlight', - color: '#eab308', - width: 4, - points: [ - { x: 0, y: 0 }, - { x: 8, y: 0 } - ] - }) - expect(ctx.globalAlpha).toBe(HIGHLIGHT_ALPHA) - }) - - it('draws an arrow as a shaft plus a head', () => { - const { ctx, methods } = makeRecordingCtx() - drawShape(ctx, { - id: 'a', - kind: 'arrow', - color: '#fff', - width: 4, - from: { x: 0, y: 0 }, - to: { x: 20, y: 0 } - }) - // shaft (moveTo+lineTo) + head (moveTo+lineTo+lineTo) - expect(methods('moveTo').length).toBeGreaterThanOrEqual(2) - expect(methods('stroke').length).toBeGreaterThanOrEqual(2) - }) - - it('uses strokeRect for rectangles', () => { - const { ctx, methods } = makeRecordingCtx() - drawShape(ctx, { - id: 'r', - kind: 'rect', - color: '#fff', - width: 2, - from: { x: 10, y: 10 }, - to: { x: 4, y: 30 } - }) - expect(methods('strokeRect')).toHaveLength(1) - expect(methods('strokeRect')[0].args).toEqual([4, 10, 6, 20]) - }) - - it('uses ellipse for ovals', () => { - const { ctx, methods } = makeRecordingCtx() - drawShape(ctx, { - id: 'e', - kind: 'ellipse', - color: '#fff', - width: 2, - from: { x: 0, y: 0 }, - to: { x: 20, y: 10 } - }) - expect(methods('ellipse')).toHaveLength(1) - expect(methods('ellipse')[0].args.slice(0, 4)).toEqual([10, 5, 10, 5]) - }) - - it('renders single-line text with a halo (stroke behind fill)', () => { - const { ctx, calls } = makeRecordingCtx() - drawShape(ctx, { - id: 't', - kind: 'text', - color: '#fff', - at: { x: 5, y: 5 }, - text: 'fix this', - fontSize: 18 - }) - expect(calls.filter((call) => call.method.endsWith('Text'))).toEqual([ - { method: 'strokeText', args: ['fix this', 5, 5] }, - { method: 'fillText', args: ['fix this', 5, 5] } - ]) - }) - - it('brackets rectangle drawing with save and restore calls', () => { - const { ctx, calls } = makeRecordingCtx() - drawShape(ctx, { - id: 'r', - kind: 'rect', - color: '#fff', - width: 2, - from: { x: 0, y: 0 }, - to: { x: 1, y: 1 } - }) - expect(calls).toEqual([ - { method: 'save', args: [] }, - { method: 'strokeRect', args: [0, 0, 1, 1] }, - { method: 'restore', args: [] } - ]) - }) -}) - describe('textInkBox', () => { it('covers the measured glyphs plus the halo, measured in the style text is drawn with', () => { const { ctx, methods } = makeRecordingCtx() diff --git a/src/renderer/src/components/browser-pane/annotate/use-markup-draw-hint.test.ts b/src/renderer/src/components/browser-pane/annotate/use-markup-draw-hint.test.ts index 309a109b03b..338ed138176 100644 --- a/src/renderer/src/components/browser-pane/annotate/use-markup-draw-hint.test.ts +++ b/src/renderer/src/components/browser-pane/annotate/use-markup-draw-hint.test.ts @@ -20,20 +20,6 @@ describe('useMarkupDrawHint', () => { window.localStorage.removeItem(HINT_KEY) }) - it('opens once when eligible and records the seen flag', () => { - const { result } = renderHook(() => useMarkupDrawHint(true)) - - expect(result.current.hintOpen).toBe(true) - expect(window.localStorage.getItem(HINT_KEY)).toBe('true') - }) - - it('does not open when the surface is not eligible', () => { - const { result } = renderHook(() => useMarkupDrawHint(false)) - - expect(result.current.hintOpen).toBe(false) - expect(window.localStorage.getItem(HINT_KEY)).toBeNull() - }) - it('closes when eligibility drops so a hidden pane cannot keep it open', () => { const { result, rerender } = renderHook(({ eligible }) => useMarkupDrawHint(eligible), { initialProps: { eligible: true } 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 4bd09a512ea..a5c73a46513 100644 --- a/src/renderer/src/components/browser-pane/annotate/useMarkupEditor.test.ts +++ b/src/renderer/src/components/browser-pane/annotate/useMarkupEditor.test.ts @@ -18,13 +18,6 @@ function pointerEvent(clientX: number, clientY: number): React.PointerEvent } -function secondPointerEvent( - clientX: number, - clientY: number -): React.PointerEvent { - return { ...pointerEvent(clientX, clientY), pointerId: 2 } -} - describe('useMarkupEditor.commitPendingText in a non-secure browser context', () => { beforeEach(() => { // Simulate a LAN HTTP client: getRandomValues exists but randomUUID does not. @@ -94,122 +87,4 @@ describe('useMarkupEditor gestures', () => { act(() => result.current.undo()) expect(result.current.shapes).toEqual([first, second]) }) - - it('shows a click on overlapping marks taking only the newest, and a drag taking both', () => { - const result = renderEditor({ wrapper: StrictMode }) - drawLine(result, 0) - drawLine(result, 0) - const [older, newer] = result.current.shapes - - act(() => result.current.setTool('eraser')) - act(() => result.current.onPointerDown(pointerEvent(50, 0))) - expect(result.current.shapes).toEqual([older]) - act(() => result.current.onPointerUp(pointerEvent(50, 0))) - expect(result.current.shapes).toEqual([older]) - - act(() => result.current.undo()) - act(() => result.current.onPointerDown(pointerEvent(50, 0))) - act(() => result.current.onPointerMove(pointerEvent(50, 40))) - expect(result.current.shapes).toEqual([]) - act(() => result.current.onPointerUp(pointerEvent(50, 40))) - - act(() => result.current.undo()) - expect(result.current.shapes).toEqual([older, newer]) - }) - - it('adds no undo step for an eraser click on empty space', () => { - const result = renderEditor() - drawLine(result, 0) - - act(() => result.current.setTool('eraser')) - act(() => result.current.onPointerDown(pointerEvent(50, 300))) - act(() => result.current.onPointerUp(pointerEvent(50, 300))) - act(() => result.current.undo()) - - expect(result.current.shapes).toEqual([]) - }) - - it('lets only the finger that started an erase steer and end it', () => { - const result = renderEditor() - drawLine(result, 0) - drawLine(result, 200) - const [first, second] = result.current.shapes - - act(() => result.current.setTool('eraser')) - act(() => result.current.onPointerDown(pointerEvent(50, 0))) - act(() => result.current.onPointerMove(secondPointerEvent(50, 200))) - expect(result.current.shapes).toEqual([second]) - - act(() => result.current.onPointerUp(secondPointerEvent(50, 200))) - act(() => result.current.onPointerMove(pointerEvent(50, 200))) - act(() => result.current.onPointerUp(pointerEvent(50, 200))) - expect(result.current.shapes).toEqual([]) - - // Both marks went in one gesture, so one undo brings both back. - act(() => result.current.undo()) - expect(result.current.shapes).toEqual([first, second]) - }) - - it('takes back only an in-flight erase on undo, and ignores the rest of that drag', () => { - const result = renderEditor({ wrapper: StrictMode }) - drawLine(result, 0) - drawLine(result, 200) - const [first, second] = result.current.shapes - - act(() => result.current.setTool('eraser')) - act(() => result.current.onPointerDown(pointerEvent(50, 0))) - expect(result.current.shapes).toEqual([second]) - act(() => result.current.undo()) - expect(result.current.shapes).toEqual([first, second]) - - // The held pointer sweeps across the second mark, then lifts. - act(() => result.current.onPointerMove(pointerEvent(50, 200))) - act(() => result.current.onPointerUp(pointerEvent(50, 200))) - expect(result.current.shapes).toEqual([first, second]) - - act(() => result.current.undo()) - expect(result.current.shapes).toEqual([first]) - }) - - it('takes back only an in-flight stroke on undo, even the first one', () => { - const result = renderEditor({ wrapper: StrictMode }) - expect(result.current.canUndo).toBe(false) - - act(() => result.current.onPointerDown(pointerEvent(0, 0))) - expect(result.current.canUndo).toBe(true) - act(() => result.current.undo()) - act(() => result.current.onPointerMove(pointerEvent(100, 0))) - act(() => result.current.onPointerUp(pointerEvent(100, 0))) - expect(result.current.shapes).toEqual([]) - expect(result.current.canUndo).toBe(false) - - drawLine(result, 50) - expect(result.current.shapes).toHaveLength(1) - }) - - it('keeps an in-flight erase when redo has nothing to redo', () => { - const result = renderEditor() - drawLine(result, 0) - drawLine(result, 200) - const [, second] = result.current.shapes - - act(() => result.current.setTool('eraser')) - act(() => result.current.onPointerDown(pointerEvent(50, 0))) - act(() => result.current.redo()) - act(() => result.current.onPointerUp(pointerEvent(50, 0))) - - expect(result.current.shapes).toEqual([second]) - }) - - it('drops an in-flight stroke when everything is cleared', () => { - const result = renderEditor() - - act(() => result.current.onPointerDown(pointerEvent(0, 0))) - act(() => result.current.onPointerMove(pointerEvent(100, 0))) - act(() => result.current.clear()) - act(() => result.current.onPointerMove(pointerEvent(150, 0))) - act(() => result.current.onPointerUp(pointerEvent(150, 0))) - - expect(result.current.shapes).toEqual([]) - }) }) diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserPane.webview-preferences.test.ts b/src/renderer/src/components/browser-pane/assemble-chrome/BrowserPane.webview-preferences.test.ts index 4cf2db76c1b..35bfe7c6283 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserPane.webview-preferences.test.ts +++ b/src/renderer/src/components/browser-pane/assemble-chrome/BrowserPane.webview-preferences.test.ts @@ -1,6 +1,5 @@ // @vitest-environment happy-dom import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ORCA_BROWSER_PAGE_GUEST_WEB_PREFERENCES_ATTRIBUTE } from '../../../../../shared/browser-guest-web-preferences' const registryMocks = vi.hoisted(() => ({ destroyPersistentWebview: vi.fn(), @@ -38,33 +37,6 @@ describe('BrowserPane webview preferences', () => { document.body.innerHTML = '' }) - it('creates a webview with the resolved partition and shared guest webpreferences', () => { - const container = createContainer('initial') - - const ensuredWebview = ensureBrowserPageWebview({ - browserTabId: 'browser-page-1', - container, - inputLocked: false, - webviewPartition: 'persist:orca-browser-session-profile-1', - resolveContainer: () => container - }) - - expect(ensuredWebview).not.toBeNull() - expect(ensuredWebview?.created).toBe(true) - expect(ensuredWebview?.container).toBe(container) - expect(ensuredWebview?.webview.getAttribute('partition')).toBe( - 'persist:orca-browser-session-profile-1' - ) - expect(ensuredWebview?.webview.getAttribute('webpreferences')).toBe( - ORCA_BROWSER_PAGE_GUEST_WEB_PREFERENCES_ATTRIBUTE - ) - expect(registryMocks.registerPersistentWebview).toHaveBeenCalledWith( - 'browser-page-1', - ensuredWebview?.webview - ) - expect(container.lastElementChild).toBe(ensuredWebview?.webview as unknown as Element) - }) - it('remounts the webview in a refreshed container when the stored resolved partition changes', () => { const staleContainer = createContainer('stale') const staleWebview = document.createElement('webview') as Electron.WebviewTag diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-chrome-folded-tools.test.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-chrome-folded-tools.test.tsx deleted file mode 100644 index 13bed84cd99..00000000000 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-chrome-folded-tools.test.tsx +++ /dev/null @@ -1,105 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { Share2 } from 'lucide-react' - -vi.mock('@/components/ui/dropdown-menu', () => ({ - DropdownMenuItem: ({ - children, - onSelect, - role, - 'aria-checked': ariaChecked - }: { - children: React.ReactNode - onSelect: () => void - role?: string - 'aria-checked'?: boolean - }) => ( - - ), - DropdownMenuSeparator: () =>
, - DropdownMenuShortcut: ({ children }: { children: React.ReactNode }) => {children} -})) - -import { BrowserChromeFoldedMenuItems } from './browser-chrome-folded-tools' - -afterEach(cleanup) - -describe('BrowserChromeFoldedMenuItems', () => { - it('runs ordinary actions directly', () => { - const onSelect = vi.fn() - render( - - ) - - fireEvent.click(screen.getByRole('button', { name: 'Share' })) - expect(onSelect).toHaveBeenCalledOnce() - }) - - it('defers popover actions until the menu closes', () => { - const onSelect = vi.fn() - const deferUntilClose = vi.fn() - render( - - ) - - fireEvent.click(screen.getByRole('button', { name: 'Share' })) - expect(onSelect).not.toHaveBeenCalled() - expect(deferUntilClose).toHaveBeenCalledWith(onSelect) - }) - - it('preserves active state for folded toggle tools', () => { - render( - - ) - - expect( - screen.getByRole('menuitemcheckbox', { name: 'Draw' }).getAttribute('aria-checked') - ).toBe('true') - }) - - it('gives toggle tools their own section, split from the actions by a divider', () => { - const { container } = render( - - ) - - expect( - Array.from(container.querySelectorAll('button, hr')).map((el) => - el.tagName === 'HR' ? 'divider' : el.textContent - ) - ).toEqual(['Draw', 'divider', 'Share', 'divider']) - }) -}) diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.test.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.test.tsx deleted file mode 100644 index 489e537ac8c..00000000000 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.test.tsx +++ /dev/null @@ -1,73 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, render } from '@testing-library/react' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { BrowserTargetUrlChangedEvent } from '../../../../../shared/browser-guest-events' -import { BrowserLinkStatusBubble } from './browser-link-status-bubble' - -let emit: (event: BrowserTargetUrlChangedEvent) => void - -beforeEach(() => { - vi.useFakeTimers() - Object.defineProperty(window, 'api', { - configurable: true, - value: { - browser: { - onTargetUrlChanged: (callback: (event: BrowserTargetUrlChangedEvent) => void) => { - emit = callback - return () => {} - } - }, - ui: { getZoomLevel: () => 0 } - } - }) -}) - -afterEach(() => { - cleanup() - vi.useRealTimers() -}) - -function hover(url: string, browserPageId = 'page-1'): void { - act(() => emit({ browserPageId, url, screenX: 0, screenY: 0 })) -} - -function advance(ms: number): void { - act(() => vi.advanceTimersByTime(ms)) -} - -it('shows the hovered URL after a short delay and hides it after leaving the link', () => { - const { container } = render() - const bubble = container.querySelector('[data-browser-link-status]')! - - hover('https://example.com/docs', 'page-2') - advance(500) - expect(bubble.classList.contains('opacity-0')).toBe(true) - - hover('https://example.com/docs') - advance(50) - expect(bubble.classList.contains('opacity-0')).toBe(true) - advance(50) - expect(bubble.classList.contains('opacity-100')).toBe(true) - expect(bubble.textContent).toBe('https://example.com/docs') - - hover('') - advance(200) - expect(bubble.classList.contains('opacity-100')).toBe(true) - advance(100) - expect(bubble.classList.contains('opacity-0')).toBe(true) -}) - -it('keeps the host out of the trimmed tail and caps huge URLs', () => { - const { container } = render() - const parts = (): string[] => - [...container.querySelectorAll('[data-browser-link-status] span')].map((s) => s.textContent!) - - hover('https://example.com/a') - expect(parts()).toEqual(['https://example.com', '/a']) - - hover(`data:text/plain,${'x'.repeat(5000)}`) - const [head, tail] = parts() - expect(head.length).toBe(513) - expect(head.endsWith('…')).toBe(true) - expect(tail).toBe('x'.repeat(20)) -}) diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-navigation-control-row.test.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-navigation-control-row.test.tsx deleted file mode 100644 index 9c7ded833bc..00000000000 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-navigation-control-row.test.tsx +++ /dev/null @@ -1,41 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - BrowserNavigationControlRow, - type BrowserNavigationControls -} from './browser-navigation-control-row' - -function renderRow(overrides: Partial = {}): BrowserNavigationControls { - const controls: BrowserNavigationControls = { - canGoBack: true, - canGoForward: true, - goBack: vi.fn(), - goForward: vi.fn(), - reload: vi.fn(), - navigate: vi.fn(), - ...overrides - } - render() - return controls -} - -describe('BrowserNavigationControlRow', () => { - afterEach(cleanup) - - it('drives every history action through the controls seam', () => { - const controls = renderRow() - screen.getByLabelText('Back').click() - screen.getByLabelText('Forward').click() - screen.getByLabelText('Reload').click() - expect(controls.goBack).toHaveBeenCalledTimes(1) - expect(controls.goForward).toHaveBeenCalledTimes(1) - expect(controls.reload).toHaveBeenCalledTimes(1) - }) - - it('disables history buttons from the backend-reported history depth', () => { - renderRow({ canGoBack: false, canGoForward: false }) - expect(screen.getByLabelText('Back').disabled).toBe(true) - expect(screen.getByLabelText('Forward').disabled).toBe(true) - }) -}) 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 6edb0570a8c..d72076ce9f7 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 @@ -77,50 +77,6 @@ function expectedFolded(width: number): number { } describe('useBrowserChromeToolFold', () => { - it('keeps every tool inline when the address has its minimum width', () => { - let folded = -1 - layout.rowWidth = 600 - render( (folded = count)} />) - expect(folded).toBe(0) - }) - - it('folds just enough tools to give the address its minimum width', () => { - let folded = -1 - layout.rowWidth = 300 - render( (folded = count)} />) - expect(folded).toBe(expectedFolded(300)) - expect(folded).toBeGreaterThan(0) - }) - - it('unfolds as the row widens and refolds as it narrows', () => { - let folded = -1 - layout.rowWidth = 600 - render( (folded = count)} />) - - resizeTo(260) - expect(folded).toBe(expectedFolded(260)) - - resizeTo(400) - expect(folded).toBe(expectedFolded(400)) - - resizeTo(700) - expect(folded).toBe(0) - }) - - it('folds everything but lets the address shrink once no tool is left', () => { - let folded = -1 - layout.rowWidth = 150 - render( (folded = count)} />) - expect(folded).toBe(BROWSER_CHROME_FOLD_ORDER.length) - }) - - it('leaves a hidden (zero-width) row alone', () => { - let folded = -1 - layout.rowWidth = 0 - render( (folded = count)} />) - expect(folded).toBe(0) - }) - it('measures when a hidden row becomes visible', () => { let folded = -1 layout.rowWidth = 0 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 index c393a1d8782..7d233d9b7bb 100644 --- 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 @@ -87,54 +87,7 @@ function emitFinished(overrides: Partial = {}): vo act(() => finished.emit(event)) } -function emitProgress(overrides: Partial = {}): void { - const event = { - downloadId: 'download-1', - receivedBytes: 2_202_009, - totalBytes: 8_388_608, - state: 'progressing', - ...overrides - } as BrowserDownloadProgressEvent - act(() => progress.emit(event)) -} - describe('client-hosted browser download notices', () => { - it('names the remote workspace destination when the download lands there', () => { - renderNotices() - - emitRequested() - expect(toastMocks.loading).toHaveBeenCalledWith('Downloading report.pdf…', { - id: 'browser-download:download-1' - }) - - emitFinished({ - remoteDestination: { - workspaceRelativePath: '.orca/browser-downloads/report.pdf', - hostLabel: 'build-box' - } - }) - - expect(toastMocks.success).toHaveBeenCalledWith( - 'Saved to .orca/browser-downloads/report.pdf on build-box', - { id: 'browser-download:download-1' } - ) - }) - - it('surfaces the fail-closed remote error instead of dropping it', () => { - renderNotices() - emitRequested() - - emitFinished({ - status: 'failed', - error: 'Could not save the download to the remote workspace.' - }) - - expect(toastMocks.error).toHaveBeenCalledWith( - 'Could not save the download to the remote workspace.', - { id: 'browser-download:download-1' } - ) - }) - // 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() @@ -147,36 +100,4 @@ describe('client-hosted browser download notices', () => { id: 'browser-download:download-1' }) }) - - it('leaves downloads from pages this desktop does not host to their own shelf', () => { - renderNotices() - - emitRequested({ browserPageId: 'local-page', downloadId: 'download-2' }) - emitFinished({ browserPageId: 'local-page', downloadId: 'download-2' }) - - expect(toastMocks.loading).not.toHaveBeenCalled() - expect(toastMocks.success).not.toHaveBeenCalled() - }) - - // Remote downloads have no local shelf; this toast is their only visible progress. - it('moves the toast forward as bytes arrive', () => { - renderNotices() - emitRequested() - toastMocks.loading.mockClear() - - emitProgress() - - expect(toastMocks.loading).toHaveBeenCalledWith('Downloading report.pdf… 2.1 MB / 8.0 MB', { - id: 'browser-download:download-1' - }) - }) - - it('ignores progress for a download it never claimed', () => { - renderNotices() - toastMocks.loading.mockClear() - - emitProgress() - - expect(toastMocks.loading).not.toHaveBeenCalled() - }) }) diff --git a/src/renderer/src/components/browser-pane/browser-client-page-metadata-publisher.test.ts b/src/renderer/src/components/browser-pane/browser-client-page-metadata-publisher.test.ts index 023b4e4528e..740f12e8417 100644 --- a/src/renderer/src/components/browser-pane/browser-client-page-metadata-publisher.test.ts +++ b/src/renderer/src/components/browser-pane/browser-client-page-metadata-publisher.test.ts @@ -87,53 +87,6 @@ describe('browser client page metadata publisher', () => { expect.objectContaining({ revision: 2, title: 'Later' }) ) }) - - it('reports a publish the runtime refused instead of discarding it', async () => { - const onUnpublished = vi.fn() - const publish = vi - .fn() - .mockResolvedValueOnce({ status: 'published', accepted: false }) - .mockResolvedValueOnce({ status: 'failed', errorCode: 'browser_host_lease_stale' }) - let revision = 0 - const publisher = createBrowserClientPageMetadataPublisher({ - browserPageId: 'page-a', - placement: PLACEMENT, - nextRevision: () => ++revision, - publish, - onUnpublished - }) - - publisher.publish(snapshot('Refused')) - await vi.waitFor(() => expect(onUnpublished).toHaveBeenCalledTimes(1)) - expect(onUnpublished).toHaveBeenNthCalledWith(1, { reason: 'rejected' }) - - publisher.publish(snapshot('Failed')) - await vi.waitFor(() => expect(onUnpublished).toHaveBeenCalledTimes(2)) - expect(onUnpublished).toHaveBeenNthCalledWith(2, { - reason: 'failed', - errorCode: 'browser_host_lease_stale' - }) - }) - - // Transport rejection exercises a separate path from a runtime-declined outcome. - it('reports a publish that threw on its way out', async () => { - const onUnpublished = vi.fn() - let revision = 0 - const publisher = createBrowserClientPageMetadataPublisher({ - browserPageId: 'page-a', - placement: PLACEMENT, - nextRevision: () => ++revision, - publish: () => Promise.reject(new Error('remote_runtime_unavailable')), - onUnpublished - }) - - publisher.publish(snapshot('Thrown')) - await vi.waitFor(() => expect(onUnpublished).toHaveBeenCalledTimes(1)) - expect(onUnpublished).toHaveBeenNthCalledWith(1, { - reason: 'failed', - errorCode: 'remote_runtime_unavailable' - }) - }) }) function snapshot(title: string) { diff --git a/src/renderer/src/components/browser-pane/browser-client-page-retained-drag-passthrough.test.ts b/src/renderer/src/components/browser-pane/browser-client-page-retained-drag-passthrough.test.ts index 271f2985c3b..29933703c8f 100644 --- a/src/renderer/src/components/browser-pane/browser-client-page-retained-drag-passthrough.test.ts +++ b/src/renderer/src/components/browser-pane/browser-client-page-retained-drag-passthrough.test.ts @@ -29,21 +29,6 @@ afterEach(() => { }) describe('client-hosted retained guest drag passthrough', () => { - it('holds a visible retained host click-through for the length of a drag', async () => { - const rig = createRetainedHostFixture() - await rig.mount() - rig.attach() - expect(rig.host().style.pointerEvents).toBe('auto') - - const endDrag = startDrag() - - expect(rig.host().style.pointerEvents).toBe('none') - - endDrag() - - expect(rig.host().style.pointerEvents).toBe('auto') - }) - it('brings a retained page attached mid-drag up click-through', async () => { const rig = createRetainedHostFixture() await rig.mount() diff --git a/src/renderer/src/components/browser-pane/browser-external-app-prompt.test.ts b/src/renderer/src/components/browser-pane/browser-external-app-prompt.test.ts deleted file mode 100644 index 3b5de51841d..00000000000 --- a/src/renderer/src/components/browser-pane/browser-external-app-prompt.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { ConfirmationDialogContextValue } from '@/components/confirmation-dialog-context' - -vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) - -import { externalAppPrompt } from './browser-external-app-prompt' - -const signal = new AbortController().signal - -describe('browser external-app prompt', () => { - it('names the app and the asking site, and answers yes with Open', async () => { - const confirm = vi.fn().mockResolvedValue(true) - - await expect( - externalAppPrompt.ask( - confirm, - { - appName: 'Okta Verify', - scheme: 'com-okta-authenticator', - origin: 'https://acme.okta.com' - }, - signal - ) - ).resolves.toBe(true) - expect(confirm).toHaveBeenCalledWith( - expect.objectContaining({ - title: 'Open Okta Verify?', - description: 'https://acme.okta.com wants to open another application.', - confirmLabel: 'Open Okta Verify' - }) - ) - }) - - it('falls back to the link type when the app is unknown, and declines on Cancel', async () => { - const confirm = vi.fn().mockResolvedValue(false) - - await expect( - externalAppPrompt.ask(confirm, { appName: null, scheme: 'zoommtg', origin: null }, signal) - ).resolves.toBeNull() - expect(confirm).toHaveBeenCalledWith( - expect.objectContaining({ - title: 'Open this zoommtg link?', - description: 'A page in the browser wants to open another application.', - confirmLabel: 'Open link' - }) - ) - }) -}) diff --git a/src/renderer/src/components/browser-pane/browser-http-auth-prompt.test.ts b/src/renderer/src/components/browser-pane/browser-http-auth-prompt.test.ts deleted file mode 100644 index e1d302c1e63..00000000000 --- a/src/renderer/src/components/browser-pane/browser-http-auth-prompt.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { - ConfirmationDialogContextValue, - ConfirmationDialogOptions -} from '@/components/confirmation-dialog-context' - -import { httpAuthPrompt } from './browser-http-auth-prompt' - -const signal = new AbortController().signal - -describe('browser HTTP auth prompt', () => { - it('names the site, warns on plain http, and answers with what the user typed', async () => { - // Stands in for the user typing into the dialog's fields and pressing Sign in. - const confirm = vi.fn(async (options: ConfirmationDialogOptions) => { - options.fields?.onConfirmed({ username: 'qa', password: 'hunter2' }) - return true - }) - - await expect( - httpAuthPrompt.ask(confirm, { origin: 'http://192.168.1.20:8080', retry: true }, signal) - ).resolves.toEqual({ username: 'qa', password: 'hunter2' }) - expect(confirm).toHaveBeenCalledWith( - expect.objectContaining({ - title: 'Sign in', - description: [ - 'http://192.168.1.20:8080 is asking for a username and password.', - "Your connection to this site isn't private.", - "That username or password didn't work." - ].join('\n') - }) - ) - }) - - it('declines when the user cancels', async () => { - const confirm = vi.fn().mockResolvedValue(false) - - await expect( - httpAuthPrompt.ask(confirm, { origin: 'https://staging.acme.com', retry: false }, signal) - ).resolves.toBeNull() - expect(confirm.mock.calls[0][0].description).toBe( - 'https://staging.acme.com is asking for a username and password.' - ) - }) -}) diff --git a/src/renderer/src/components/browser-pane/browser-page-prompts.test.ts b/src/renderer/src/components/browser-pane/browser-page-prompts.test.ts index 54e5d765bc0..1c866d50e09 100644 --- a/src/renderer/src/components/browser-pane/browser-page-prompts.test.ts +++ b/src/renderer/src/components/browser-pane/browser-page-prompts.test.ts @@ -1,9 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { BrowserPagePromptRequest } from '../../../../shared/browser-page-prompt' -import type { - ConfirmationDialogContextValue, - ConfirmationDialogOptions -} from '@/components/confirmation-dialog-context' +import type { ConfirmationDialogContextValue } from '@/components/confirmation-dialog-context' const { toastError } = vi.hoisted(() => ({ toastError: vi.fn() })) vi.mock('sonner', () => ({ toast: { error: toastError } })) @@ -50,28 +47,6 @@ beforeEach(() => { }) describe('browser page prompts', () => { - it("asks with the prompt's own kind and sends back its answer", async () => { - // Stands in for the user typing into the dialog's fields and pressing Sign in. - const confirm = vi.fn(async (options: ConfirmationDialogOptions) => { - options.fields?.onConfirmed({ username: 'qa', password: 'hunter2' }) - return true - }) - const { emit } = installSubscription(confirm) - - emit({ - requestId: 'r1', - kind: 'http-auth', - details: { origin: 'https://staging.acme.com', retry: false } - }) - - await vi.waitFor(() => - expect(respondPagePrompt).toHaveBeenCalledWith({ - requestId: 'r1', - answer: { username: 'qa', password: 'hunter2' } - }) - ) - }) - it('dismisses the prompt without answering when main closes the request', async () => { const confirm = vi.fn( (options) => @@ -90,23 +65,4 @@ describe('browser page prompts', () => { expect(confirm.mock.calls[0][0].signal?.aborted).toBe(true) expect(respondPagePrompt).not.toHaveBeenCalled() }) - - it("says so when the user said yes but Orca couldn't carry it out", async () => { - respondPagePrompt.mockResolvedValue('failed') - const { emit } = installSubscription( - vi.fn().mockResolvedValue(true) - ) - - emit({ - requestId: 'r3', - kind: 'external-app', - details: { appName: null, scheme: 'zoommtg', origin: null } - }) - - await vi.waitFor(() => - expect(toastError).toHaveBeenCalledWith( - "Couldn't open an app for this zoommtg link. It may not be installed." - ) - ) - }) }) diff --git a/src/renderer/src/components/browser-pane/browser-reopen-on-server.test.ts b/src/renderer/src/components/browser-pane/browser-reopen-on-server.test.ts index 23a0fe24fe3..c3d3e9260fc 100644 --- a/src/renderer/src/components/browser-pane/browser-reopen-on-server.test.ts +++ b/src/renderer/src/components/browser-pane/browser-reopen-on-server.test.ts @@ -9,18 +9,9 @@ vi.mock('@/runtime/web-runtime-browser-creation', () => ({ createWebRuntimeSessionBrowserTab: mocks.createWebRuntimeSessionBrowserTab })) -import { - reopenBrowserPageOnServer, - resolveBrowserReopenOnServerUrl -} from './browser-reopen-on-server' +import { resolveBrowserReopenOnServerUrl } from './browser-reopen-on-server' describe('resolveBrowserReopenOnServerUrl', () => { - it('keeps a committed web URL', () => { - expect(resolveBrowserReopenOnServerUrl('https://example.com/app')).toBe( - 'https://example.com/app' - ) - }) - it('reopens blank rather than replaying something the new engine cannot restore', () => { expect(resolveBrowserReopenOnServerUrl(ORCA_BROWSER_BLANK_URL)).toBeUndefined() expect(resolveBrowserReopenOnServerUrl('about:blank')).toBeUndefined() @@ -30,25 +21,3 @@ describe('resolveBrowserReopenOnServerUrl', () => { expect(resolveBrowserReopenOnServerUrl(undefined)).toBeUndefined() }) }) - -describe('reopenBrowserPageOnServer', () => { - it('creates a new server-placed page at the last committed URL', async () => { - mocks.createWebRuntimeSessionBrowserTab.mockClear() - - await expect( - reopenBrowserPageOnServer({ - environmentId: 'env-1', - worktreeId: 'wt-1', - lastCommittedUrl: 'https://example.com/app' - }) - ).resolves.toBe(true) - - expect(mocks.createWebRuntimeSessionBrowserTab).toHaveBeenCalledWith({ - worktreeId: 'wt-1', - environmentId: 'env-1', - url: 'https://example.com/app', - placementPreference: 'server', - focusOnCreate: true - }) - }) -}) diff --git a/src/renderer/src/components/browser-pane/browser-site-permission-prompt.test.ts b/src/renderer/src/components/browser-pane/browser-site-permission-prompt.test.ts index 95623ad1340..af8bde25fbf 100644 --- a/src/renderer/src/components/browser-pane/browser-site-permission-prompt.test.ts +++ b/src/renderer/src/components/browser-pane/browser-site-permission-prompt.test.ts @@ -10,27 +10,6 @@ const details = { } describe('browser site permission prompt', () => { - it('names the site and lists what it wants', async () => { - const confirm = vi.fn(async (_options: ConfirmationDialogOptions) => true) - - await expect(sitePermissionPrompt.ask(confirm, details, signal)).resolves.toBe('allow') - expect(confirm).toHaveBeenCalledWith( - expect.objectContaining({ - title: 'meet.example.com wants to', - description: 'Use your camera\nUse your microphone', - confirmLabel: 'Allow', - cancelLabel: 'Block' - }) - ) - }) - - it('calls a local file "this file"', async () => { - const confirm = vi.fn(async (_options: ConfirmationDialogOptions) => true) - - await sitePermissionPrompt.ask(confirm, { origin: 'file://', permissions: ['camera'] }, signal) - expect(confirm.mock.calls[0][0].title).toBe('This file wants to') - }) - // Stands in for the dialog: Block runs onCancelClicked before resolving false; Esc only resolves. it.each([ ['Block', true, 'block'], 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 0dcd77a4bce..5d793218b7f 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 @@ -43,22 +43,6 @@ function anchorFor( } describe('browser annotation composer placement', () => { - it('sits below a target with room underneath', () => { - expect(anchorFor({ x: 100, y: 40, width: 185, height: 16 }, 900, 900)).toEqual({ - x: 192.5, - y: 56, - side: 'bottom' - }) - }) - - it('sits above a target with room overhead but not underneath', () => { - expect(anchorFor({ x: 100, y: 700, width: 185, height: 16 }, 900, 900)).toEqual({ - x: 192.5, - y: 700, - side: 'top' - }) - }) - // The reported bug: a target too tall to clear vertically used to put the card on top of it. it('moves beside a target that leaves no vertical room', () => { expect(anchorFor({ x: 300, y: 150, width: 300, height: 300 }, 1400, 600)).toEqual({ @@ -71,13 +55,6 @@ describe('browser annotation composer placement', () => { it('falls to the left band when the right one is too narrow', () => { expect(anchorFor({ x: 800, y: 150, width: 300, height: 300 }, 1400, 600).side).toBe('left') }) - - // Only the anchor is asserted: when nothing fits, Radix collision handling controls the final overlap and needs a real browser to measure. - it('anchors to the deeper vertical band when no side can hold the card', () => { - const anchor = anchorFor({ x: 20, y: 20, width: 860, height: 560 }, 900, 600) - expect(anchor.side).toBe('bottom') - expect(anchor.y).toBe(580) - }) }) describe('browser annotation geometry', () => { @@ -138,19 +115,6 @@ describe('browser annotation card follows the live element', () => { }) }) - it('follows the element after a pane resize reflows it', () => { - const viewport = applyBrowserAnnotationViewportReport( - { scrollX: 5, scrollY: 15, version: 1 }, - { scrollX: 5, scrollY: 15, target: { x: 200, y: 20, width: 300, height: 20 } } - ) - const pane = box(0, 0, 600, 900) - expect(getBrowserOverlayAnchor(clicked, pane, pane, viewport)).toEqual({ - x: 350, - y: 40, - side: 'bottom' - }) - }) - it('converts guest pixels to pane pixels when the page is zoomed', () => { // 120% page zoom: the guest lays out 1000 CSS pixels across a 1200-pixel-wide view. const viewport = applyBrowserAnnotationViewportReport( @@ -181,23 +145,4 @@ describe('browser annotation card follows the live element', () => { expect(getBrowserOverlayAnchor(fixed, pane, pane, viewport).side).toBe('right') expect(getBrowserOverlayAnchor(fixed, pane, pane, viewport, 200).side).toBe('bottom') }) - - it('keeps the same viewport state when a report changes nothing', () => { - const target = { x: 1, y: 2, width: 3, height: 4 } - const report = { scrollX: 1, scrollY: 2, viewportWidth: 800, target } - const first = applyBrowserAnnotationViewportReport( - { scrollX: 0, scrollY: 0, version: 0 }, - report - ) - expect(first.version).toBe(1) - expect(applyBrowserAnnotationViewportReport(first, { ...report, target: { ...target } })).toBe( - first - ) - const released = applyBrowserAnnotationViewportReport(first, { - scrollX: 1, - scrollY: 2, - viewportWidth: 800 - }) - expect(released).toEqual({ scrollX: 1, scrollY: 2, viewportWidth: 800, version: 2 }) - }) }) diff --git a/src/renderer/src/components/browser-pane/describe-page/browser-artifact-upload.test.ts b/src/renderer/src/components/browser-pane/describe-page/browser-artifact-upload.test.ts index c525d22a755..557468a08df 100644 --- a/src/renderer/src/components/browser-pane/describe-page/browser-artifact-upload.test.ts +++ b/src/renderer/src/components/browser-pane/describe-page/browser-artifact-upload.test.ts @@ -36,24 +36,6 @@ describe('browser artifact upload', () => { expect(getShareableBrowserArtifactFile('file:///tmp/report.md')).toBeNull() }) - it('reads the backing file through the authorized filesystem API', async () => { - await expect(readBrowserHtmlArtifactRequest('file:///tmp/report.html')).resolves.toEqual({ - sourceKey: '/tmp/report.html', - content: '

Mock

', - contentType: 'text/html', - fileName: 'report.html' - }) - // Why user-file: the user opened this page by URL, so it is shared from where it is. - expect(stat).toHaveBeenCalledWith({ - filePath: '/tmp/report.html', - access: { kind: 'user-file' } - }) - expect(readFile).toHaveBeenCalledWith({ - filePath: '/tmp/report.html', - access: { kind: 'user-file' } - }) - }) - it('rejects oversized and unreadable files before upload', async () => { stat.mockResolvedValueOnce({ size: ARTIFACT_MAX_CONTENT_BYTES + 1, @@ -70,16 +52,4 @@ describe('browser artifact upload', () => { code: 'unreadable' } satisfies Partial) }) - - it('accepts a file whose stat is exactly at the 10 MiB boundary', async () => { - stat.mockResolvedValueOnce({ - size: ARTIFACT_MAX_CONTENT_BYTES, - isDirectory: false, - mtime: 1 - }) - - await expect(readBrowserHtmlArtifactRequest('file:///tmp/exact.html')).resolves.toMatchObject({ - sourceKey: '/tmp/exact.html' - }) - }) }) diff --git a/src/renderer/src/components/browser-pane/describe-page/browser-favicon-url.test.ts b/src/renderer/src/components/browser-pane/describe-page/browser-favicon-url.test.ts deleted file mode 100644 index 4c295309174..00000000000 --- a/src/renderer/src/components/browser-pane/describe-page/browser-favicon-url.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - browserNavigationLeavesFaviconOrigin, - displayableFaviconUrl, - pickDisplayableFaviconUrl -} from './browser-favicon-url' - -describe('displayableFaviconUrl', () => { - it('accepts http, https and image data urls', () => { - expect(displayableFaviconUrl('https://github.com/favicon.ico')).toBe( - 'https://github.com/favicon.ico' - ) - expect(displayableFaviconUrl('http://127.0.0.1:8765/favicon.ico')).toBe( - 'http://127.0.0.1:8765/favicon.ico' - ) - expect(displayableFaviconUrl(' data:image/png;base64,AAAA ')).toBe( - 'data:image/png;base64,AAAA' - ) - }) - - it('rejects the empty-icon sentinel and non-web schemes', () => { - expect(displayableFaviconUrl('data:,')).toBeNull() - expect(displayableFaviconUrl('chrome-extension://abc/icon.png')).toBeNull() - expect(displayableFaviconUrl('file:///tmp/icon.png')).toBeNull() - expect(displayableFaviconUrl('not a url')).toBeNull() - expect(displayableFaviconUrl(null)).toBeNull() - expect(displayableFaviconUrl(' ')).toBeNull() - }) -}) - -describe('pickDisplayableFaviconUrl', () => { - it('skips leading entries that cannot render', () => { - expect(pickDisplayableFaviconUrl(['data:,', 'https://example.com/icon.png'])).toBe( - 'https://example.com/icon.png' - ) - }) - - it('keeps the declaration order among usable entries', () => { - expect( - pickDisplayableFaviconUrl([ - 'https://github.githubassets.com/favicons/favicon.png', - 'https://github.githubassets.com/favicons/favicon.svg' - ]) - ).toBe('https://github.githubassets.com/favicons/favicon.png') - }) - - it('reports nothing for an absent or unusable list', () => { - expect(pickDisplayableFaviconUrl(undefined)).toBeNull() - expect(pickDisplayableFaviconUrl([])).toBeNull() - expect(pickDisplayableFaviconUrl(['data:,'])).toBeNull() - }) -}) - -describe('browserNavigationLeavesFaviconOrigin', () => { - it('keeps the icon across a same-origin navigation', () => { - expect( - browserNavigationLeavesFaviconOrigin( - 'https://github.com/alibaba/jvm-sandbox', - 'https://github.com/btraceio/btrace' - ) - ).toBe(false) - }) - - it('drops the icon when the origin changes', () => { - expect( - browserNavigationLeavesFaviconOrigin('https://github.com/nodejs/node', 'https://x.com/home') - ).toBe(true) - }) - - it('treats scheme and port as part of the origin', () => { - expect( - browserNavigationLeavesFaviconOrigin('http://localhost:3000/', 'http://localhost:4000/') - ).toBe(true) - expect( - browserNavigationLeavesFaviconOrigin('http://example.com/', 'https://example.com/') - ).toBe(true) - }) - - it('drops the icon when the destination cannot carry one', () => { - expect(browserNavigationLeavesFaviconOrigin('https://github.com/', 'about:blank')).toBe(true) - expect( - browserNavigationLeavesFaviconOrigin('https://github.com/', 'file:///tmp/report.html') - ).toBe(true) - }) - - it('keeps the icon when the document being left is unknown', () => { - expect(browserNavigationLeavesFaviconOrigin(null, 'https://github.com/nodejs/node')).toBe(false) - expect(browserNavigationLeavesFaviconOrigin('about:blank', 'https://github.com/')).toBe(false) - }) -}) diff --git a/src/renderer/src/components/browser-pane/describe-page/browser-page-url-display.test.ts b/src/renderer/src/components/browser-pane/describe-page/browser-page-url-display.test.ts index 7662d104ccd..f89de082b8c 100644 --- a/src/renderer/src/components/browser-pane/describe-page/browser-page-url-display.test.ts +++ b/src/renderer/src/components/browser-pane/describe-page/browser-page-url-display.test.ts @@ -1,10 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/constants' import { - getBrowserDisplayTitle, getBrowserPageRuntimeEnvironmentId, - getOpenableExternalUrl, - isChromiumErrorPage, retryBrowserTabLoad, toDisplayUrl } from './browser-page-url-display' @@ -17,18 +14,6 @@ describe('browser page URL display', () => { expect(toDisplayUrl('https://kagi.com/search?q=a&token=secret')).not.toContain('secret') }) - it('titles blank tabs New Tab and otherwise uses the provided title', () => { - expect(getBrowserDisplayTitle('Example', 'https://example.com')).toBe('Example') - expect(getBrowserDisplayTitle(null, 'about:blank')).toBe('New Tab') - expect(getBrowserDisplayTitle('about:blank', 'https://example.com')).toBe('New Tab') - expect(getBrowserDisplayTitle('Example', ORCA_BROWSER_BLANK_URL)).toBe('New Tab') - }) - - it('detects Chromium error pages', () => { - expect(isChromiumErrorPage('chrome-error://chromewebdata/')).toBe(true) - expect(isChromiumErrorPage('https://example.com')).toBe(false) - }) - it('prefers the page-owned runtime environment id when present', () => { expect( getBrowserPageRuntimeEnvironmentId( @@ -50,11 +35,6 @@ describe('browser page URL display', () => { ).toBeNull() }) - it('opens only normalizable external URLs', () => { - expect(getOpenableExternalUrl('https://example.com')).toBe('https://example.com/') - expect(getOpenableExternalUrl(ORCA_BROWSER_BLANK_URL)).toBeNull() - }) - it('retries a failed load by assigning the attempted URL instead of reload()', () => { const webview = { src: 'chrome-error://chromewebdata/' } const onUpdatePageState = vi.fn() @@ -73,14 +53,4 @@ describe('browser page URL display', () => { }) expect(webview.src).toBe('https://example.com/app') }) - - it('does nothing when there is no webview', () => { - const onUpdatePageState = vi.fn() - retryBrowserTabLoad( - null, - { id: 'page-1', url: 'https://example.com' } as BrowserPageState, - onUpdatePageState - ) - expect(onUpdatePageState).not.toHaveBeenCalled() - }) }) diff --git a/src/renderer/src/components/browser-pane/describe-page/live-browser-url-registry.test.ts b/src/renderer/src/components/browser-pane/describe-page/live-browser-url-registry.test.ts index 8381d962ef8..d4e71378ead 100644 --- a/src/renderer/src/components/browser-pane/describe-page/live-browser-url-registry.test.ts +++ b/src/renderer/src/components/browser-pane/describe-page/live-browser-url-registry.test.ts @@ -12,16 +12,6 @@ describe('browser runtime live URL cache', () => { clearLiveBrowserUrl('popup-1') }) - it('remembers and clears the last live URL for a browser page', () => { - rememberLiveBrowserUrl('page-1', 'https://example.com/') - - expect(getLiveBrowserUrl('page-1')).toBe('https://example.com/') - - clearLiveBrowserUrl('page-1') - - expect(getLiveBrowserUrl('page-1')).toBeNull() - }) - it('seeds an initial URL without replacing a committed navigation', () => { seedLiveBrowserUrl('page-1', 'https://initial.example/') rememberLiveBrowserUrl('page-1', 'https://committed.example/') @@ -29,14 +19,4 @@ describe('browser runtime live URL cache', () => { expect(getLiveBrowserUrl('page-1')).toBe('https://committed.example/') }) - - it('keeps popup page URLs independent and clears only the destroyed page', () => { - seedLiveBrowserUrl('page-1', 'https://opener.example/') - seedLiveBrowserUrl('popup-1', 'https://popup.example/') - - clearLiveBrowserUrl('popup-1') - - expect(getLiveBrowserUrl('page-1')).toBe('https://opener.example/') - expect(getLiveBrowserUrl('popup-1')).toBeNull() - }) }) diff --git a/src/shared/github/api-availability.test.ts b/src/shared/github/api-availability.test.ts index aec7abd4422..0a6e9bd4241 100644 --- a/src/shared/github/api-availability.test.ts +++ b/src/shared/github/api-availability.test.ts @@ -1,36 +1,7 @@ import { describe, expect, it } from 'vitest' -import { classifyGitHubUnavailable, isGitHubUnavailableError } from './api-availability' +import { classifyGitHubUnavailable } from './api-availability' describe('classifyGitHubUnavailable', () => { - it('classifies HTTP 5xx outages as server_error', () => { - expect(classifyGitHubUnavailable('HTTP 503: Service Unavailable')).toBe('server_error') - expect(classifyGitHubUnavailable('gh: Command failed: HTTP 502 Bad Gateway')).toBe( - 'server_error' - ) - expect(classifyGitHubUnavailable('GitHub API error: 500 Internal Server Error')).toBe( - 'server_error' - ) - expect(classifyGitHubUnavailable('The service is temporarily unavailable')).toBe('server_error') - }) - - it('classifies transport failures as network', () => { - for (const message of [ - 'request to https://api.github.com failed, reason: getaddrinfo ENOTFOUND api.github.com', - 'error connecting to api.github.com\ncheck your internet connection or GitHub status', - 'dial tcp: lookup api.github.com: no such host', - 'connect ETIMEDOUT 140.82.112.5:443', - 'TimeoutError: request aborted', - 'NetworkError when attempting to fetch resource', - 'network unavailable', - 'fetch failed', - 'socket hang up', - 'could not resolve host: api.github.com', - 'connection refused' - ]) { - expect(classifyGitHubUnavailable(message)).toBe('network') - } - }) - it('classifies rate limiting as rate_limited (even when it carries HTTP 403)', () => { expect(classifyGitHubUnavailable('HTTP 403: API rate limit exceeded')).toBe('rate_limited') expect(classifyGitHubUnavailable('You have exceeded a secondary rate limit')).toBe( @@ -56,12 +27,3 @@ describe('classifyGitHubUnavailable', () => { expect(classifyGitHubUnavailable('found 512 pull requests')).toBeNull() }) }) - -describe('isGitHubUnavailableError', () => { - it('detects reachability failures from Error objects and strings', () => { - expect(isGitHubUnavailableError(new Error('HTTP 503: Service Unavailable'))).toBe(true) - expect(isGitHubUnavailableError('fetch failed')).toBe(true) - expect(isGitHubUnavailableError(new Error('HTTP 404: Not Found'))).toBe(false) - expect(isGitHubUnavailableError(null)).toBe(false) - }) -}) diff --git a/src/shared/github/owner-slug.test.ts b/src/shared/github/owner-slug.test.ts index d3a899d4d23..50bd1d326ff 100644 --- a/src/shared/github/owner-slug.test.ts +++ b/src/shared/github/owner-slug.test.ts @@ -1,10 +1,6 @@ import { describe, expect, it } from 'vitest' -import { - GITHUB_OWNER_NUMBER_SHORTHAND_RE, - GITHUB_OWNER_SLUG_RE, - isGitHubOwnerSlug -} from './owner-slug' +import { GITHUB_OWNER_SLUG_RE, isGitHubOwnerSlug } from './owner-slug' describe('GitHub owner slug alphabet', () => { it('accepts plain logins and Enterprise Managed User logins', () => { @@ -33,13 +29,4 @@ describe('GitHub owner slug alphabet', () => { } expect(isGitHubOwnerSlug(123)).toBe(false) }) - - it('shorthand captures the same owner alphabet plus a number', () => { - expect(GITHUB_OWNER_NUMBER_SHORTHAND_RE.exec('octocat_acme/12')?.slice(1)).toEqual([ - 'octocat_acme', - '12' - ]) - expect(GITHUB_OWNER_NUMBER_SHORTHAND_RE.test('_acme/12')).toBe(false) - expect(GITHUB_OWNER_NUMBER_SHORTHAND_RE.test('acme/x')).toBe(false) - }) }) diff --git a/src/shared/github/pr-comment-diff-hunk.test.ts b/src/shared/github/pr-comment-diff-hunk.test.ts deleted file mode 100644 index 179987c61d0..00000000000 --- a/src/shared/github/pr-comment-diff-hunk.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { tailDiffHunk, threadDiffLines } from './pr-comment-diff-hunk' - -const HUNK = [ - '@@ -20,4 +20,6 @@ export function Banner(props) {', - ' return (', - '- ', - '+ ', - '+ ', - ' {props.title}' -].join('\n') - -describe('pr comment diff hunk', () => { - it('numbers the anchored lines back from the end line, skipping removed lines', () => { - const tail = tailDiffHunk(HUNK) ?? '' - const strip = (lines: ReturnType) => - lines.map(({ number, sign, text }) => ({ number, sign, text })) - expect(strip(threadDiffLines(tail, 23))).toEqual([ - { number: 23, sign: ' ', text: ' {props.title}' } - ]) - // A hunk ending on line 21 with a removal inside 20..21: it shows unnumbered and line 20 still shows. - const toLine21 = tail.split('\n').slice(0, 3).join('\n') - expect(strip(threadDiffLines(toLine21, 21, 20))).toEqual([ - { number: 20, sign: ' ', text: ' return (' }, - { number: null, sign: '-', text: ' ' }, - { number: 21, sign: '+', text: ' ' } - ]) - }) -}) diff --git a/src/shared/github/pr-reviewer-display.test.ts b/src/shared/github/pr-reviewer-display.test.ts index 73fe33cba19..c08153b2d36 100644 --- a/src/shared/github/pr-reviewer-display.test.ts +++ b/src/shared/github/pr-reviewer-display.test.ts @@ -1,60 +1,15 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import type { GitHubWorkItem } from './work-item-types' import { GITHUB_PR_REVIEWER_INPUT_MAX_BYTES, - getGitHubPRReviewerRows, parseGitHubReviewerInputLogins } from './pr-reviewer-display' -function item(patch: Partial): GitHubWorkItem { - return patch as GitHubWorkItem -} - afterEach(() => { vi.restoreAllMocks() }) describe('GitHub PR reviewer display', () => { - it('builds reviewer rows for requested and reviewed users', () => { - expect( - getGitHubPRReviewerRows( - item({ - reviewRequests: [{ login: 'ExampleReviewer', name: null, avatarUrl: 'avatar-1' }], - latestReviews: [ - { login: 'reviewer', state: 'APPROVED', avatarUrl: 'avatar-2' }, - { login: 'ExampleReviewer', state: 'COMMENTED', avatarUrl: 'avatar-1b' } - ] - }) - ) - ).toEqual([ - { - login: 'ExampleReviewer', - name: null, - avatarUrl: 'avatar-1', - stateLabel: 'Requested' - }, - { - login: 'reviewer', - name: null, - avatarUrl: 'avatar-2', - stateLabel: 'Approved' - } - ]) - }) - - it('parses pasted reviewer input without regex splitting', () => { - const split = vi.spyOn(String.prototype, 'split') - const input = ['@ExampleReviewer,', String.fromCharCode(160), '@new-reviewer\nthird'].join('') - - expect(parseGitHubReviewerInputLogins(input)).toEqual([ - '@ExampleReviewer', - '@new-reviewer', - 'third' - ]) - expect(split).not.toHaveBeenCalled() - }) - it('rejects oversized reviewer input before tokenizing pasted text', () => { const split = vi.spyOn(String.prototype, 'split') const oversized = 'secret-reviewer,'.repeat(GITHUB_PR_REVIEWER_INPUT_MAX_BYTES) diff --git a/src/shared/github/project-board-columns.test.ts b/src/shared/github/project-board-columns.test.ts index 6c604cd7399..3fe4697b43d 100644 --- a/src/shared/github/project-board-columns.test.ts +++ b/src/shared/github/project-board-columns.test.ts @@ -86,12 +86,6 @@ describe('resolveBoardColumnField', () => { expect(resolveBoardColumnField(v)).toBe(SPRINT_FIELD) }) - it('falls back to the Status field, then any single-select', () => { - const priority: GitHubProjectField = { ...STATUS_FIELD, id: 'f_prio', name: 'Priority' } - expect(resolveBoardColumnField(view({ fields: [priority, STATUS_FIELD] }))).toBe(STATUS_FIELD) - expect(resolveBoardColumnField(view({ fields: [priority] }))).toBe(priority) - }) - it('ignores a non-select vertical field instead of building clear-only columns', () => { const textField: GitHubProjectField = { kind: 'field', @@ -102,28 +96,9 @@ describe('resolveBoardColumnField', () => { const v = view({ fields: [STATUS_FIELD], verticalGroupByFields: [textField] }) expect(resolveBoardColumnField(v)).toBe(STATUS_FIELD) }) - - it('returns null when nothing can shape columns', () => { - expect( - resolveBoardColumnField( - view({ fields: [{ kind: 'field', id: 'f_t', name: 'Title', dataType: 'TITLE' }] }) - ) - ).toBeNull() - }) }) describe('buildBoardColumns', () => { - it('emits every option as a column in option order, empty ones included', () => { - const columns = buildBoardColumns(STATUS_FIELD, [ - row('a', [statusValue('opt_done', 'Done')]), - row('b', [statusValue('opt_todo', 'Todo')]) - ]) - expect(columns.map((c) => c.label)).toEqual(['Todo', 'In Progress', 'Done', 'No Status']) - expect(columns.map((c) => c.rows.length)).toEqual([1, 0, 1, 0]) - expect(columns[0]?.dropValue).toEqual({ kind: 'single-select', optionId: 'opt_todo' }) - expect(columns[0]?.color).toBe('GREEN') - }) - it('routes no-value rows to the trailing column whose drop clears the field', () => { const columns = buildBoardColumns(STATUS_FIELD, [row('a', [])]) const trailing = columns.at(-1)! @@ -143,24 +118,6 @@ describe('buildBoardColumns', () => { expect(columns.at(-1)?.label).toBe('No Status') }) - it('builds iteration columns with iteration drops', () => { - const columns = buildBoardColumns(SPRINT_FIELD, [ - row('a', [ - { - kind: 'iteration', - fieldId: 'f_sprint', - iterationId: 'it_2', - title: 'Sprint 2', - startDate: '2026-09-07', - duration: 14 - } - ]) - ]) - expect(columns.map((c) => c.label)).toEqual(['Sprint 1', 'Sprint 2', 'No Sprint']) - expect(columns[1]?.dropValue).toEqual({ kind: 'iteration', iterationId: 'it_2' }) - expect(columns[1]?.rows.map((r) => r.id)).toEqual(['a']) - }) - it('buckets non-select fields read-only', () => { const assignees: GitHubProjectField = { kind: 'field', diff --git a/src/shared/github/project-roadmap-timeline.test.ts b/src/shared/github/project-roadmap-timeline.test.ts index ec7bf8b0e77..fdcd05c81a2 100644 --- a/src/shared/github/project-roadmap-timeline.test.ts +++ b/src/shared/github/project-roadmap-timeline.test.ts @@ -1,230 +1,9 @@ import { describe, expect, it } from 'vitest' -import { - buildRoadmapTicks, - getRoadmapSpan, - parseRoadmapDate, - resolveRoadmapDateSource, - roadmapOffsetPx, - ROADMAP_DAY_MS, - type RoadmapSpan -} from './project-roadmap-timeline' -import type { - GitHubProjectField, - GitHubProjectFieldValue, - GitHubProjectRow, - GitHubProjectView -} from './project-types' - -function dateField(id: string, name: string): GitHubProjectField { - return { kind: 'field', id, name, dataType: 'DATE' } -} - -function iterationField(id: string, name: string): GitHubProjectField { - return { kind: 'iteration', id, name, dataType: 'ITERATION', iterations: [] } -} - -function view(fields: GitHubProjectField[]): GitHubProjectView { - return { - id: 'PVTV_1', - number: 1, - name: 'Roadmap', - layout: 'ROADMAP_LAYOUT', - filter: '', - fields, - groupByFields: [], - sortByFields: [] - } -} - -function row(values: GitHubProjectFieldValue[]): GitHubProjectRow { - const fieldValuesByFieldId: Record = {} - for (const value of values) { - fieldValuesByFieldId[value.fieldId] = value - } - return { - id: 'PVTI_1', - itemType: 'ISSUE', - content: { - number: 1, - title: 'Item', - body: null, - url: 'https://github.com/o/r/issues/1', - state: 'OPEN', - stateReason: null, - isDraft: null, - repository: 'o/r', - assignees: [], - labels: [], - parentIssue: null, - issueType: null - }, - fieldValuesByFieldId, - updatedAt: '2026-08-31T00:00:00Z', - position: 0 - } -} +import { buildRoadmapTicks, parseRoadmapDate, type RoadmapSpan } from './project-roadmap-timeline' const utc = (iso: string): number => Date.parse(`${iso}T00:00:00Z`) -describe('resolveRoadmapDateSource', () => { - it('pairs date fields by name regardless of view order', () => { - const target = dateField('f_end', 'Target date') - const start = dateField('f_start', 'Start date') - expect(resolveRoadmapDateSource(view([target, start]))).toEqual({ - kind: 'date-range', - startField: start, - targetField: target - }) - }) - - it('keeps a name-matched field in its role when the other name matches nothing', () => { - const review = dateField('f_review', 'Review date') - const start = dateField('f_start', 'Start date') - expect(resolveRoadmapDateSource(view([review, start]))).toEqual({ - kind: 'date-range', - startField: start, - targetField: review - }) - }) - - it('finds placement fields via sortByFields when the visible list hides them', () => { - const start = dateField('f_start', 'Start date') - const target = dateField('f_end', 'Target date') - const hidden = view([{ kind: 'field', id: 'f_t', name: 'Title', dataType: 'TITLE' }]) - hidden.sortByFields = [ - { direction: 'ASC', field: start }, - { direction: 'ASC', field: target } - ] - expect(resolveRoadmapDateSource(hidden)).toEqual({ - kind: 'date-range', - startField: start, - targetField: target - }) - }) - - it('derives placement fields from row values when no configured field has them', () => { - const bare = view([{ kind: 'field', id: 'f_t', name: 'Title', dataType: 'TITLE' }]) - const rows = [ - row([ - { kind: 'date', fieldId: 'f_start', date: '2026-03-02', fieldName: 'Start date' }, - { kind: 'date', fieldId: 'f_end', date: '2026-03-04', fieldName: 'Target date' } - ]) - ] - expect(resolveRoadmapDateSource(bare, rows)).toEqual({ - kind: 'date-range', - startField: { kind: 'field', id: 'f_start', name: 'Start date', dataType: 'DATE' }, - targetField: { kind: 'field', id: 'f_end', name: 'Target date', dataType: 'DATE' } - }) - }) - - it('falls back to view order when names do not match the patterns', () => { - const first = dateField('f_1', '開始') - const second = dateField('f_2', '完了') - expect(resolveRoadmapDateSource(view([first, second]))).toEqual({ - kind: 'date-range', - startField: first, - targetField: second - }) - }) - - it('prefers an iteration field over a lone date field', () => { - const iteration = iterationField('f_it', 'Sprint') - expect(resolveRoadmapDateSource(view([dateField('f_1', 'Start date'), iteration]))).toEqual({ - kind: 'iteration', - field: iteration - }) - }) - - it('uses a lone date field as a point source', () => { - const only = dateField('f_1', 'Ship date') - expect(resolveRoadmapDateSource(view([only]))).toEqual({ kind: 'date-point', field: only }) - }) - - it('returns null when the view has nothing to place items on', () => { - expect( - resolveRoadmapDateSource( - view([{ kind: 'field', id: 'f_t', name: 'Title', dataType: 'TITLE' }]) - ) - ).toBeNull() - }) -}) - -describe('getRoadmapSpan', () => { - const start = dateField('f_start', 'Start date') - const target = dateField('f_end', 'Target date') - const source = { kind: 'date-range', startField: start, targetField: target } as const - - it('spans an inclusive end date', () => { - const span = getRoadmapSpan( - row([ - { kind: 'date', fieldId: 'f_start', date: '2026-03-02' }, - { kind: 'date', fieldId: 'f_end', date: '2026-03-04' } - ]), - source - ) - expect(span).toEqual({ startMs: utc('2026-03-02'), endMs: utc('2026-03-05'), point: false }) - }) - - it('renders a single known date as a point', () => { - const span = getRoadmapSpan( - row([{ kind: 'date', fieldId: 'f_end', date: '2026-03-04' }]), - source - ) - expect(span).toEqual({ startMs: utc('2026-03-04'), endMs: utc('2026-03-05'), point: true }) - }) - - it('orders an inverted pair instead of dropping the row', () => { - const span = getRoadmapSpan( - row([ - { kind: 'date', fieldId: 'f_start', date: '2026-03-10' }, - { kind: 'date', fieldId: 'f_end', date: '2026-03-01' } - ]), - source - ) - expect(span).toEqual({ startMs: utc('2026-03-01'), endMs: utc('2026-03-11'), point: false }) - }) - - it('returns null when neither date is set', () => { - expect(getRoadmapSpan(row([]), source)).toBeNull() - }) - - it('derives the span from an iteration value', () => { - const span = getRoadmapSpan( - row([ - { - kind: 'iteration', - fieldId: 'f_it', - iterationId: 'it_1', - title: 'Sprint 1', - startDate: '2026-03-02', - duration: 14 - } - ]), - { kind: 'iteration', field: iterationField('f_it', 'Sprint') } - ) - expect(span).toEqual({ - startMs: utc('2026-03-02'), - endMs: utc('2026-03-02') + 14 * ROADMAP_DAY_MS, - point: false - }) - }) - - it('ignores a value whose kind does not match the source', () => { - expect( - getRoadmapSpan(row([{ kind: 'text', fieldId: 'f_start', text: '2026-03-02' }]), source) - ).toBeNull() - }) -}) - describe('parseRoadmapDate', () => { - it('reads the date part of an ISO timestamp', () => { - expect(parseRoadmapDate('2026-03-02T11:22:33Z')).toBe(utc('2026-03-02')) - }) - - it('rejects malformed input', () => { - expect(parseRoadmapDate('March 2')).toBeNull() - }) - it('rejects invalid calendar dates instead of letting Date.UTC normalize them', () => { expect(parseRoadmapDate('2026-02-30')).toBeNull() expect(parseRoadmapDate('2026-13-01')).toBeNull() @@ -240,35 +19,6 @@ describe('buildRoadmapTicks', () => { point: false }) - it('pads one month on each side of the covered range', () => { - const ticks = buildRoadmapTicks([span('2026-03-02', '2026-10-10')], 'month', utc('2026-03-15')) - expect(ticks[0]?.startMs).toBe(utc('2026-02-01')) - expect(ticks.at(-1)?.endMs).toBe(utc('2026-12-01')) - }) - - it('always covers today even when every item sits elsewhere', () => { - const ticks = buildRoadmapTicks([span('2026-03-02', '2026-03-10')], 'month', utc('2026-09-15')) - expect(ticks[0]?.startMs).toBe(utc('2026-02-01')) - expect(ticks.at(-1)?.endMs).toBe(utc('2026-11-01')) - }) - - it('widens an empty roadmap to the minimum readable width', () => { - expect(buildRoadmapTicks([], 'month', utc('2026-03-15'))).toHaveLength(6) - expect(buildRoadmapTicks([], 'quarter', utc('2026-03-15'))).toHaveLength(4) - expect(buildRoadmapTicks([], 'year', utc('2026-03-15'))).toHaveLength(3) - }) - - it('snaps quarter and year grids to their unit boundaries', () => { - const quarters = buildRoadmapTicks( - [span('2026-05-02', '2026-05-10')], - 'quarter', - utc('2026-05-15') - ) - expect(quarters[0]?.startMs).toBe(utc('2026-01-01')) - const years = buildRoadmapTicks([span('2026-05-02', '2026-05-10')], 'year', utc('2026-05-15')) - expect(years[0]?.startMs).toBe(utc('2025-01-01')) - }) - it('caps the grid instead of expanding for a far-future date, keeping today visible', () => { const today = utc('2026-03-15') const ticks = buildRoadmapTicks([span('2026-03-02', '9999-01-01')], 'month', today) @@ -287,24 +37,3 @@ describe('buildRoadmapTicks', () => { expect(ticks.at(-1)!.endMs).toBe(utc('2026-05-01')) }) }) - -describe('roadmapOffsetPx', () => { - const ticks = buildRoadmapTicks([], 'month', utc('2026-03-15')) - - it('interpolates inside the containing tick so column rules stay aligned', () => { - const second = ticks[1] - expect(second).toBeDefined() - expect(roadmapOffsetPx(second!.startMs, ticks, 100)).toBe(100) - const midpoint = second!.startMs + (second!.endMs - second!.startMs) / 2 - expect(roadmapOffsetPx(midpoint, ticks, 100)).toBeCloseTo(150, 5) - }) - - it('clamps out-of-range timestamps to the grid edges', () => { - expect(roadmapOffsetPx(utc('1990-01-01'), ticks, 100)).toBe(0) - expect(roadmapOffsetPx(utc('2090-01-01'), ticks, 100)).toBe(ticks.length * 100) - }) - - it('returns zero for an empty grid', () => { - expect(roadmapOffsetPx(utc('2026-03-15'), [], 100)).toBe(0) - }) -}) diff --git a/src/shared/github/pull-request-for-branch-outcome.test.ts b/src/shared/github/pull-request-for-branch-outcome.test.ts index e607f63cc6a..288d131f46a 100644 --- a/src/shared/github/pull-request-for-branch-outcome.test.ts +++ b/src/shared/github/pull-request-for-branch-outcome.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import type { PRRefreshOutcome } from './pull-request-refresh-types' + import type { PRInfo } from './pull-request-types' import { normalizeGitHubPRForBranchOutcome } from './pull-request-for-branch-outcome' @@ -14,11 +14,6 @@ const PR: PRInfo = { } describe('normalizeGitHubPRForBranchOutcome', () => { - it('preserves current classified outcomes', () => { - const outcome: PRRefreshOutcome = { kind: 'found', pr: PR, fetchedAt: 10 } - expect(normalizeGitHubPRForBranchOutcome(outcome, 20)).toBe(outcome) - }) - it.each([ { kind: 'no-pr' as const, fetchedAt: 10 }, { kind: 'no-pr' as const, fetchedAt: 10, rejectedPRUrls: [PR.url] } @@ -37,14 +32,4 @@ describe('normalizeGitHubPRForBranchOutcome', () => { fetchedAt: 20 }) }) - - it('preserves classified upstream errors', () => { - const outcome: PRRefreshOutcome = { - kind: 'upstream-error', - errorType: 'network', - message: 'network unavailable', - fetchedAt: 10 - } - expect(normalizeGitHubPRForBranchOutcome(outcome, 20)).toBe(outcome) - }) }) diff --git a/src/shared/gitlab-projects.test.ts b/src/shared/gitlab-projects.test.ts deleted file mode 100644 index f5d1a55808b..00000000000 --- a/src/shared/gitlab-projects.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { computeNextGitLabRecents, GITLAB_RECENTS_MAX } from './gitlab-projects' - -describe('computeNextGitLabRecents', () => { - const fixedNow = new Date('2026-05-08T10:00:00.000Z') - - it('prepends a fresh entry to an empty list', () => { - expect(computeNextGitLabRecents([], 'gitlab.com', 'g/p', fixedNow)).toEqual([ - { host: 'gitlab.com', path: 'g/p', lastOpenedAt: fixedNow.toISOString() } - ]) - }) - - it('moves an existing entry to the front (dedupes by host + path)', () => { - const existing = [ - { host: 'gitlab.com', path: 'a/b', lastOpenedAt: '2026-05-07' }, - { host: 'gitlab.com', path: 'g/p', lastOpenedAt: '2026-05-06' }, - { host: 'gitlab.com', path: 'c/d', lastOpenedAt: '2026-05-05' } - ] - const result = computeNextGitLabRecents(existing, 'gitlab.com', 'g/p', fixedNow) - expect(result.map((r) => r.path)).toEqual(['g/p', 'a/b', 'c/d']) - expect(result[0].lastOpenedAt).toBe(fixedNow.toISOString()) - }) - - it('treats different hosts at the same path as distinct entries', () => { - const existing = [{ host: 'gitlab.example.com', path: 'g/p', lastOpenedAt: '2026-05-07' }] - const result = computeNextGitLabRecents(existing, 'gitlab.com', 'g/p', fixedNow) - expect(result).toHaveLength(2) - expect(result[0]).toMatchObject({ host: 'gitlab.com', path: 'g/p' }) - expect(result[1]).toMatchObject({ host: 'gitlab.example.com', path: 'g/p' }) - }) - - it('caps the list at GITLAB_RECENTS_MAX entries', () => { - const existing = Array.from({ length: GITLAB_RECENTS_MAX }, (_, i) => ({ - host: 'gitlab.com', - path: `g/p${i}`, - lastOpenedAt: `2026-05-0${i}` - })) - const result = computeNextGitLabRecents(existing, 'gitlab.com', 'g/new', fixedNow) - expect(result).toHaveLength(GITLAB_RECENTS_MAX) - expect(result[0].path).toBe('g/new') - expect(result.find((r) => r.path === `g/p${GITLAB_RECENTS_MAX - 1}`)).toBeUndefined() - }) - - it('does not mutate the input array', () => { - const existing = [{ host: 'gitlab.com', path: 'a/b', lastOpenedAt: '2026-05-07' }] - const snapshot = JSON.stringify(existing) - computeNextGitLabRecents(existing, 'gitlab.com', 'g/p', fixedNow) - expect(JSON.stringify(existing)).toBe(snapshot) - }) -}) diff --git a/src/shared/grok-model-list-probe.test.ts b/src/shared/grok-model-list-probe.test.ts index 9793b6b540b..43ee3a20855 100644 --- a/src/shared/grok-model-list-probe.test.ts +++ b/src/shared/grok-model-list-probe.test.ts @@ -22,17 +22,6 @@ describe('parseGrokModelList', () => { ]) }) - it('marks only the row the listing itself annotates', () => { - const parsed = parseGrokModelList( - 'Available models:\n * grok-build\n * grok-4.5 (default)\n * grok-mini\n' - ) - expect(parsed.map(({ id, isDefault }) => [id, isDefault])).toEqual([ - ['grok-build', undefined], - ['grok-4.5', true], - ['grok-mini', undefined] - ]) - }) - it('names no default when the listing annotates none', () => { // Without an explicit marker, first-row promotion would misrepresent the CLI’s unflagged default. const parsed = parseGrokModelList('Available models:\n * grok-4.5\n * grok-build\n') @@ -42,67 +31,12 @@ describe('parseGrokModelList', () => { ]) }) - it('does not treat another parenthetical as the default marker', () => { - const parsed = parseGrokModelList('Available models:\n * grok-build (beta)\n') - expect(parsed[0]!.isDefault).toBeUndefined() - }) - - it('reads the default marker off a dashed row too', () => { - // The bullet grok uses is presentational; only the annotation is the claim. - expect( - parseGrokModelList('Available models:\n - grok-build\n - grok-4.5 (default)\n').map( - ({ id, isDefault }) => [id, isDefault] - ) - ).toEqual([ - ['grok-build', undefined], - ['grok-4.5', true] - ]) - }) - - it('strips a trailing parenthetical annotation from the id, spaced or not', () => { - const parsed = parseGrokModelList( - 'Available models:\n * grok-4.5 (default)\n * grok-build(beta)\n' - ) - expect(parsed.map(({ id }) => id)).toEqual(['grok-4.5', 'grok-build']) - }) - - it('keeps hyphens and dots inside an id', () => { - const parsed = parseGrokModelList('Available models:\n * grok-4.5-fast-2026.07.19\n') - expect(parsed).toEqual([{ id: 'grok-4.5-fast-2026.07.19', label: 'Grok 4.5 Fast 2026.07.19' }]) - }) - - it('parses several models in listing order and deduplicates', () => { - const parsed = parseGrokModelList( - 'Available models:\n * grok-4.5 (default)\n * grok-build\n * grok-4.5\n' - ) - expect(parsed.map(({ id }) => id)).toEqual(['grok-4.5', 'grok-build']) - }) - - it('tolerates CRLF line endings', () => { - expect(parseGrokModelList('Available models:\r\n * grok-4.5 (default)\r\n')).toEqual([ - { id: 'grok-4.5', label: 'Grok 4.5', isDefault: true } - ]) - }) - it('returns nothing when the header is missing, whatever follows', () => { // Unrecognized listing headers must not publish partial authoritative model lists. expect(parseGrokModelList('Models:\n * grok-4.5 (default)\n')).toEqual([]) expect(parseGrokModelList('Default model: grok-4.5\n')).toEqual([]) }) - it('returns nothing for a header with no bullets under it', () => { - expect(parseGrokModelList('Available models:\n')).toEqual([]) - expect(parseGrokModelList('Available models:\n\n (none)\n')).toEqual([]) - }) - - it('returns nothing for empty, signed-out, or arbitrary output', () => { - expect(parseGrokModelList('')).toEqual([]) - expect(parseGrokModelList('\n\n \n')).toEqual([]) - // Synthetic: the live signed-out path was never run against a real account. - expect(parseGrokModelList('You are not logged in. Run `grok login` to continue.\n')).toEqual([]) - expect(parseGrokModelList("error: unexpected argument '--json' found\n")).toEqual([]) - }) - it('stops at the blank line that ends the listing section', () => { // Footer bullets must not become selectable IDs that launch e.g. -m Set. expect( @@ -117,25 +51,4 @@ describe('parseGrokModelList', () => { [{ id: 'grok-4.5', label: 'Grok 4.5', isDefault: true }] ) }) - - it('still reads a listing whose bullets start after a blank line', () => { - expect( - parseGrokModelList('Available models:\n\n * grok-4.5 (default)\n').map(({ id }) => id) - ).toEqual(['grok-4.5']) - }) - - it('never emits an entry without both an id and a label', () => { - const stdouts = [ - SIGNED_IN_STDOUT, - 'Available models:\n * \n *\n * grok-4.5\n', - 'Available models:\n * (default)\n' - ] - for (const stdout of stdouts) { - for (const model of parseGrokModelList(stdout)) { - expect(model.id.length).toBeGreaterThan(0) - expect(model.label.length).toBeGreaterThan(0) - expect(model.id).not.toMatch(/[\s(]/) - } - } - }) }) diff --git a/src/shared/grok-session-paths.test.ts b/src/shared/grok-session-paths.test.ts index e29645f9dfd..855d424712c 100644 --- a/src/shared/grok-session-paths.test.ts +++ b/src/shared/grok-session-paths.test.ts @@ -8,7 +8,6 @@ import { buildGrokChatHistoryPathCandidates, clearGrokSessionPathLookupCacheForTests, findGrokChatHistoryBySessionId, - getCachedGrokChatHistoryBySessionId, grokEncodedCwdDirName, isSafeGrokSessionId, resolveGrokChatHistoryPathSync, @@ -48,13 +47,6 @@ function deferred(): { } describe('grok-session-paths', () => { - it('honors GROK_HOME for home and sessions roots', () => { - const root = makeRoot() - expect(resolveGrokHomeDir({ GROK_HOME: root }, '/unused')).toBe(root) - expect(resolveGrokSessionsDir({ GROK_HOME: root }, '/unused')).toBe(join(root, 'sessions')) - expect(resolveGrokHomeDir({}, '/home/ada')).toBe(join('/home/ada', '.grok')) - }) - // Relative GROK_HOME depends on each terminal/main/daemon cwd and can trigger unbounded scans (#13082). // Grok 1.0.30 also treats ~ literally rather than expanding it. it.each(['.', '..', 'rel/path', '~/grok', '~', 'C:foo', 'C:'])( @@ -69,19 +61,6 @@ describe('grok-session-paths', () => { } ) - it('uses the CLI slug and BLAKE3 name for long cwd paths', () => { - const longCwd = `/${'a'.repeat(200)}/${'b'.repeat(200)}` - const group = `${'b'.repeat(40)}-e22e6487078c7674` - expect(grokEncodedCwdDirName(longCwd)).toBe(group) - expect( - buildGrokChatHistoryPathCandidates({ - sessionId: 'sess-1', - cwd: longCwd, - sessionsDir: '/tmp/sessions' - }) - ).toEqual([join('/tmp/sessions', group, 'sess-1', 'chat_history.jsonl')]) - }) - it.each([ [`/Users/test/${'中'.repeat(30)}`, 'workspace-43f12fb9a5ee1037'], [ @@ -122,24 +101,6 @@ describe('grok-session-paths', () => { ).toEqual([]) }) - it('resolves via encodeURIComponent(cwd) when the short path exists', () => { - const root = makeRoot() - const sessionsDir = join(root, 'sessions') - const cwd = '/tmp/work' - const sessionId = 'sess-short' - const history = join(sessionsDir, encodeURIComponent(cwd), sessionId, 'chat_history.jsonl') - mkdirSync(dirname(history), { recursive: true }) - writeFileSync(history, '{"type":"user"}\n') - - expect( - resolveGrokChatHistoryPathSync({ - sessionId, - cwd, - sessionsDir - }) - ).toBe(history) - }) - it('resolves the CLI long-cwd slug group', () => { const root = makeRoot() const sessionsDir = join(root, 'sessions') @@ -160,44 +121,6 @@ describe('grok-session-paths', () => { ).toBe(history) }) - it('finds the documented group/session layout asynchronously', async () => { - const root = makeRoot() - const sessionsDir = join(root, 'sessions') - const history = join(sessionsDir, 'slug-hash', 'sess-async', 'chat_history.jsonl') - mkdirSync(dirname(history), { recursive: true }) - writeFileSync(history, '{}\n') - - await expect(findGrokChatHistoryBySessionId(sessionsDir, 'sess-async')).resolves.toBe(history) - }) - - it('deduplicates concurrent async discovery', async () => { - const root = makeRoot() - const sessionsDir = join(root, 'sessions') - const history = join(sessionsDir, 'slug-hash', 'sess-deduped', 'chat_history.jsonl') - mkdirSync(dirname(history), { recursive: true }) - writeFileSync(history, '{}\n') - - const first = findGrokChatHistoryBySessionId(sessionsDir, 'sess-deduped') - const second = findGrokChatHistoryBySessionId(sessionsDir, 'sess-deduped') - - expect(second).toBe(first) - await expect(first).resolves.toBe(history) - }) - - it('reuses a successful discovery from cache without another scan', async () => { - const root = makeRoot() - const sessionsDir = join(root, 'sessions') - const history = join(sessionsDir, 'slug-hash', 'sess-cached', 'chat_history.jsonl') - mkdirSync(dirname(history), { recursive: true }) - writeFileSync(history, '{}\n') - - await expect(findGrokChatHistoryBySessionId(sessionsDir, 'sess-cached')).resolves.toBe(history) - rmSync(join(sessionsDir, 'slug-hash'), { recursive: true, force: true }) - - expect(getCachedGrokChatHistoryBySessionId(sessionsDir, 'sess-cached')).toBe(history) - await expect(findGrokChatHistoryBySessionId(sessionsDir, 'sess-cached')).resolves.toBe(history) - }) - it('does not descend below the documented group/session layout', async () => { const root = makeRoot() const sessionsDir = join(root, 'sessions') diff --git a/src/shared/handled-wire-discriminant.test.ts b/src/shared/handled-wire-discriminant.test.ts index 26178532839..06af631b12c 100644 --- a/src/shared/handled-wire-discriminant.test.ts +++ b/src/shared/handled-wire-discriminant.test.ts @@ -7,11 +7,6 @@ const HANDLED: Record<'missing' | 'unavailable', true> = { } describe('isHandledWireDiscriminant', () => { - it('admits the handled members', () => { - expect(isHandledWireDiscriminant('missing', HANDLED)).toBe(true) - expect(isHandledWireDiscriminant('unavailable', HANDLED)).toBe(true) - }) - it('rejects a member this build has never heard of', () => { expect(isHandledWireDiscriminant('permission-denied', HANDLED)).toBe(false) }) diff --git a/src/shared/harness-injected-user-turns.test.ts b/src/shared/harness-injected-user-turns.test.ts index d5574da73e4..d4bf68381a7 100644 --- a/src/shared/harness-injected-user-turns.test.ts +++ b/src/shared/harness-injected-user-turns.test.ts @@ -1,82 +1,8 @@ import { describe, expect, it } from 'vitest' -import { - isCompactContinuationUserTurnText, - isKnownHarnessInjectedUserTurnText -} from './harness-injected-user-turns' +import { isKnownHarnessInjectedUserTurnText } from './harness-injected-user-turns' describe('isKnownHarnessInjectedUserTurnText', () => { - it('matches every known harness tag, including attribute-carrying forms', () => { - // Inventory mirrors the tags the harness itself classifies as machinery. - const injected = [ - ' bzthj2b8r toolu_01abc', - '', - 'context', - ' REVIEW the diff', - 'status?', - 'hello', - 'new post', - 'Your directive: ship it', - 'remember this', - '', - 'tick', - '/review', - 'review', - '--fix', - 'ok', - 'boom', - 'Caveat: tool output', - 'ls', - 'file.txt', - 'err', - 'hook context' - ] - for (const text of injected) { - expect(isKnownHarnessInjectedUserTurnText(text), text).toBe(true) - } - }) - - it('matches harness prose wrappers and notices', () => { - expect( - isKnownHarnessInjectedUserTurnText('A message arrived from teammate-b:\nhi') - ).toBe(true) - expect( - isKnownHarnessInjectedUserTurnText( - 'Another Claude session sent a message:\nhi' - ) - ).toBe(true) - expect(isKnownHarnessInjectedUserTurnText('No response requested.')).toBe(true) - expect(isKnownHarnessInjectedUserTurnText('[Request interrupted by user]')).toBe(true) - expect(isKnownHarnessInjectedUserTurnText('[Request interrupted by user for tool use]')).toBe( - true - ) - expect( - isKnownHarnessInjectedUserTurnText( - 'This session is being continued from a previous conversation.' - ) - ).toBe(true) - expect( - isKnownHarnessInjectedUserTurnText( - 'Caveat: the messages below were generated by the user while running local commands.' - ) - ).toBe(true) - }) - - it('distinguishes compact continuation from other harness turns', () => { - expect( - isCompactContinuationUserTurnText( - 'This session is being continued from a previous conversation. Summary follows.' - ) - ).toBe(true) - expect(isCompactContinuationUserTurnText('done')).toBe(false) - expect(isCompactContinuationUserTurnText('/review')).toBe(false) - }) - - it('is case-insensitive and ignores surrounding whitespace', () => { - expect(isKnownHarnessInjectedUserTurnText(' done')).toBe(true) - expect(isKnownHarnessInjectedUserTurnText('\n hi')).toBe(true) - }) - it('keeps real user prompts, including ones that mention the tags', () => { expect(isKnownHarnessInjectedUserTurnText('fix the login bug')).toBe(false) expect( @@ -86,12 +12,6 @@ describe('isKnownHarnessInjectedUserTurnText', () => { expect(isKnownHarnessInjectedUserTurnText(' ')).toBe(false) }) - it('classifies harness and user prefixes in multi-KB pastes', () => { - const largePrompt = `done\n${'x'.repeat(20_000)}` - expect(isKnownHarnessInjectedUserTurnText(largePrompt)).toBe(true) - expect(isKnownHarnessInjectedUserTurnText(`fix login ${'y'.repeat(20_000)}`)).toBe(false) - }) - it('keeps single-word tag pastes, custom elements, and underscore wrappers', () => { // Grok wraps REAL typed prompts in — never classify as noise. expect(isKnownHarnessInjectedUserTurnText('fix the bug')).toBe(false) diff --git a/src/shared/hook-command-source-policy.test.ts b/src/shared/hook-command-source-policy.test.ts deleted file mode 100644 index fd080266b75..00000000000 --- a/src/shared/hook-command-source-policy.test.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { resolveHookCommandSourcePolicy } from './hook-command-source-policy' - -describe('hook command source policy', () => { - it('uses local commands by default when a local script is configured', () => { - expect(resolveHookCommandSourcePolicy(undefined, { hasLocalScript: true })).toBe('local-only') - }) - - it('uses shared commands by default when no local script is configured', () => { - expect(resolveHookCommandSourcePolicy(undefined, { hasLocalScript: false })).toBe('shared-only') - }) - - it('preserves explicit command source choices', () => { - expect(resolveHookCommandSourcePolicy('shared-only', { hasLocalScript: true })).toBe( - 'shared-only' - ) - expect(resolveHookCommandSourcePolicy('run-both', { hasLocalScript: true })).toBe('run-both') - }) -}) diff --git a/src/shared/host-automatic-work-budget.test.ts b/src/shared/host-automatic-work-budget.test.ts index f4aa67c5e24..0266beef144 100644 --- a/src/shared/host-automatic-work-budget.test.ts +++ b/src/shared/host-automatic-work-budget.test.ts @@ -7,7 +7,6 @@ import { } from './host-spawn-admission' import { AUTOMATIC_ADMIT_HISTORY_MS, - NO_OTHER_AUTOMATIC_WORK, withOtherDaemonsAutomaticWork } from './host-automatic-work-budget' @@ -32,11 +31,6 @@ function decide(state: ReturnType, now: number } describe('withOtherDaemonsAutomaticWork', () => { - it('returns the daemon state unchanged when no other daemon has automatic work', () => { - const state = createSpawnAdmissionState(LIMITS, 0) - expect(withOtherDaemonsAutomaticWork(state, NO_OTHER_AUTOMATIC_WORK, [], LIMITS, 0)).toBe(state) - }) - it('counts another daemon live restores against the one live cap', () => { const state = createSpawnAdmissionState(LIMITS, 0) state.liveAutomatic = 3 diff --git a/src/shared/host-balanced-listing-scaling.test.ts b/src/shared/host-balanced-listing-scaling.test.ts index 29c3b5cd8e9..2d353f5226b 100644 --- a/src/shared/host-balanced-listing-scaling.test.ts +++ b/src/shared/host-balanced-listing-scaling.test.ts @@ -1,43 +1,6 @@ -import { expect, it, vi } from 'vitest' +import { expect, it } from 'vitest' import { selectHostBalancedPage } from './host-balanced-listing-page' -it('retires exhausted host buckets from subsequent listing rounds', () => { - const rows = [ - ...Array.from({ length: 1000 }, (_, index) => ({ host: `host-${index}`, id: index })), - ...Array.from({ length: 2000 }, (_, index) => ({ host: 'large-host', id: 1000 + index })) - ] - const original = Map.prototype.values - let reads = 0 - const spy = vi.spyOn(Map.prototype, 'values').mockImplementation(function ( - this: Map - ) { - const iterator = original.call(this) - if (!this.has('large-host')) { - return iterator - } - return iterator.map( - (bucket: number[]) => - new Proxy(bucket, { - get(target, key, receiver) { - if (typeof key === 'string' && /^\d+$/.test(key)) { - reads += 1 - } - // oxlint-disable-next-line anti-slop/no-reflect-get -- Proxy `get` trap: only Reflect.get forwards a raw string|symbol key with the proxy receiver. - return Reflect.get(target, key, receiver) - } - }) - ) - }) - let result: typeof rows - try { - result = selectHostBalancedPage(rows, 2000, (row) => row.host) - } finally { - spy.mockRestore() - } - expect(result!.map((row) => row.id)).toEqual(Array.from({ length: 2000 }, (_, index) => index)) - expect(reads).toBeLessThanOrEqual(2000) -}) - // Retained buckets must outlive their round index or undefined rows enter the page. it('fills every cap exactly, without undefined or duplicate rows', () => { const rows = [ diff --git a/src/shared/host-setting-overrides.test.ts b/src/shared/host-setting-overrides.test.ts deleted file mode 100644 index e1fd5a390f8..00000000000 --- a/src/shared/host-setting-overrides.test.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - clearHostSettingOverride, - getEffectiveHostSetting, - getHostDisplayLabelOverrides, - getHostSettingOverride, - setHostSettingOverride -} from './host-setting-overrides' -import type { GlobalSettings } from './global-settings-types' - -function settingsWith( - overrides: GlobalSettings['hostSettingOverrides'] -): Pick { - return { hostSettingOverrides: overrides } -} - -describe('getEffectiveHostSetting', () => { - it('prefers a host override over the client default', () => { - const settings = settingsWith({ 'ssh:box': { defaultWorktreeLocation: '/remote/work' } }) - expect( - getEffectiveHostSetting(settings, 'ssh:box', 'defaultWorktreeLocation', '/local/work') - ).toBe('/remote/work') - }) - - it('falls back to the client default when no override exists', () => { - const settings = settingsWith({}) - expect( - getEffectiveHostSetting(settings, 'ssh:box', 'defaultWorktreeLocation', '/local/work') - ).toBe('/local/work') - }) - - it('falls back for an unknown host', () => { - const settings = settingsWith({ 'ssh:other': { defaultWorktreeLocation: '/x' } }) - expect( - getEffectiveHostSetting(settings, 'runtime:env', 'defaultWorktreeLocation', '/local/work') - ).toBe('/local/work') - }) - - it('treats a whitespace override as absent and falls back', () => { - const settings = settingsWith({ 'ssh:box': { defaultWorktreeLocation: ' ' } }) - expect( - getEffectiveHostSetting(settings, 'ssh:box', 'defaultWorktreeLocation', '/local/work') - ).toBe('/local/work') - }) - - it('allows local-host overrides', () => { - const settings = settingsWith({ local: { defaultWorktreeLocation: '/local/override' } }) - expect( - getEffectiveHostSetting(settings, 'local', 'defaultWorktreeLocation', '/local/work') - ).toBe('/local/override') - }) - - it('falls back when settings are null/undefined', () => { - expect(getEffectiveHostSetting(null, 'ssh:box', 'displayLabel', 'Default')).toBe('Default') - expect(getEffectiveHostSetting(undefined, 'ssh:box', 'displayLabel', 'Default')).toBe('Default') - }) -}) - -describe('getHostSettingOverride', () => { - it('returns the override when present', () => { - const settings = settingsWith({ 'ssh:box': { displayLabel: 'My Box' } }) - expect(getHostSettingOverride(settings, 'ssh:box', 'displayLabel')).toBe('My Box') - }) - - it('returns undefined when missing', () => { - expect(getHostSettingOverride(settingsWith({}), 'ssh:box', 'displayLabel')).toBeUndefined() - }) -}) - -describe('setHostSettingOverride', () => { - it('adds an override for a new host', () => { - const next = setHostSettingOverride(settingsWith({}), 'ssh:box', 'displayLabel', 'Box') - expect(next).toEqual({ 'ssh:box': { displayLabel: 'Box' } }) - }) - - it('merges into an existing host without clobbering other keys', () => { - const settings = settingsWith({ 'ssh:box': { displayLabel: 'Box' } }) - const next = setHostSettingOverride(settings, 'ssh:box', 'defaultWorktreeLocation', '/w') - expect(next).toEqual({ 'ssh:box': { displayLabel: 'Box', defaultWorktreeLocation: '/w' } }) - }) - - it('does not mutate the input map', () => { - const overrides = { 'ssh:box': { displayLabel: 'Box' } } - const settings = settingsWith(overrides) - setHostSettingOverride(settings, 'ssh:box', 'displayLabel', 'Renamed') - expect(overrides).toEqual({ 'ssh:box': { displayLabel: 'Box' } }) - }) - - it('clears the key when given an empty value', () => { - const settings = settingsWith({ - 'ssh:box': { displayLabel: 'Box', defaultWorktreeLocation: '/w' } - }) - const next = setHostSettingOverride(settings, 'ssh:box', 'displayLabel', ' ') - expect(next).toEqual({ 'ssh:box': { defaultWorktreeLocation: '/w' } }) - }) -}) - -describe('clearHostSettingOverride', () => { - it('removes a single key but keeps remaining overrides', () => { - const settings = settingsWith({ - 'ssh:box': { displayLabel: 'Box', defaultWorktreeLocation: '/w' } - }) - expect(clearHostSettingOverride(settings, 'ssh:box', 'displayLabel')).toEqual({ - 'ssh:box': { defaultWorktreeLocation: '/w' } - }) - }) - - it('drops the host entry when no overrides remain', () => { - const settings = settingsWith({ 'ssh:box': { displayLabel: 'Box' } }) - expect(clearHostSettingOverride(settings, 'ssh:box', 'displayLabel')).toEqual({}) - }) - - it('is a no-op for an unknown host', () => { - const settings = settingsWith({ 'ssh:other': { displayLabel: 'Other' } }) - expect(clearHostSettingOverride(settings, 'ssh:box', 'displayLabel')).toEqual({ - 'ssh:other': { displayLabel: 'Other' } - }) - }) - - it('does not mutate the input map', () => { - const overrides = { 'ssh:box': { displayLabel: 'Box' } } - const settings = settingsWith(overrides) - clearHostSettingOverride(settings, 'ssh:box', 'displayLabel') - expect(overrides).toEqual({ 'ssh:box': { displayLabel: 'Box' } }) - }) -}) - -describe('getHostDisplayLabelOverrides', () => { - it('collects non-empty display labels keyed by host id', () => { - const settings = settingsWith({ - 'ssh:box': { displayLabel: 'Box' }, - 'runtime:env': { defaultWorktreeLocation: '/w' }, - local: { displayLabel: ' ' } - }) - const map = getHostDisplayLabelOverrides(settings) - expect(map.get('ssh:box')).toBe('Box') - expect(map.has('runtime:env')).toBe(false) - expect(map.has('local')).toBe(false) - }) - - it('returns an empty map when no overrides exist', () => { - expect(getHostDisplayLabelOverrides(null).size).toBe(0) - }) -}) diff --git a/src/wsl-guest/agent-hook-envelope-publication.test.ts b/src/wsl-guest/agent-hook-envelope-publication.test.ts index e9f94614ecd..ed1d16aeb0a 100644 --- a/src/wsl-guest/agent-hook-envelope-publication.test.ts +++ b/src/wsl-guest/agent-hook-envelope-publication.test.ts @@ -131,86 +131,6 @@ describe('publishAgentHookEnvelope', () => { vi.useRealTimers() }) - it('publishes an in-capacity envelope untouched', () => { - const primary = makeBoundedClient(65536) - const dispatcher = new RelayDispatcher(primary.write, primary.options) - try { - const envelope = makeEnvelope({ lastAssistantMessage: 128, interactivePrompt: 64 }) - publishAgentHookEnvelope(dispatcher, envelope) - - const published = decodeEnvelopes(primary) - expect(published).toHaveLength(1) - expect(published[0]).toEqual(envelope) - expect(primary.closes).toBe(0) - } finally { - dispatcher.dispose() - } - }) - - it('sheds lastAssistantMessage first and stops as soon as the frame fits', () => { - const primary = makeBoundedClient(16384) - const dispatcher = new RelayDispatcher(primary.write, primary.options) - try { - // Only lastAssistantMessage pushes this past the 12288-byte producer cap. - publishAgentHookEnvelope( - dispatcher, - makeEnvelope({ lastAssistantMessage: 20_000, interactivePrompt: 128, subagents: 2 }) - ) - - const published = decodeEnvelopes(primary) - expect(published).toHaveLength(1) - expect(published[0].payload.lastAssistantMessage).toBeUndefined() - expect(published[0].payload.interactivePrompt).toBe('q'.repeat(128)) - expect(published[0].payload.subagents).toHaveLength(2) - expect(published[0].payload.state).toBe('working') - expect(published[0].paneKey).toBe('tab-1:4f1b0f4e-0000-4000-8000-000000000001') - expect(published[0].connectionId).toBeNull() - expect(primary.closes).toBe(0) - } finally { - dispatcher.dispose() - } - }) - - it('logs only when the final single-sink envelope is actually dropped', () => { - const primary = makeBoundedClient(16384) - const dispatcher = new RelayDispatcher(primary.write, primary.options) - const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) - try { - publishAgentHookEnvelope(dispatcher, makeEnvelope({ lastAssistantMessage: 20_000 })) - expect(decodeEnvelopes(primary)).toHaveLength(1) - expect(stderr).not.toHaveBeenCalled() - - const unsendable = makeEnvelope({}) - unsendable.payload.prompt = 'p'.repeat(40_000) - publishAgentHookEnvelope(dispatcher, unsendable) - expect(stderr).toHaveBeenCalledTimes(1) - expect(String(stderr.mock.calls[0][0])).toContain('Dropped agent.hook') - } finally { - stderr.mockRestore() - dispatcher.dispose() - } - }) - - it('sheds subagents next when dropping the assistant message is not enough', () => { - const primary = makeBoundedClient(16384) - const dispatcher = new RelayDispatcher(primary.write, primary.options) - try { - publishAgentHookEnvelope( - dispatcher, - makeEnvelope({ lastAssistantMessage: 8_000, interactivePrompt: 6_000, subagents: 40 }) - ) - - const published = decodeEnvelopes(primary) - expect(published).toHaveLength(1) - expect(published[0].payload.lastAssistantMessage).toBeUndefined() - expect(published[0].payload.subagents).toBeUndefined() - expect(published[0].payload.interactivePrompt).toBe('q'.repeat(6_000)) - expect(primary.closes).toBe(0) - } finally { - dispatcher.dispose() - } - }) - it('keeps the blocking question card when a waiting envelope has to shed', () => { const primary = makeBoundedClient(16384) const dispatcher = new RelayDispatcher(primary.write, primary.options) @@ -315,60 +235,6 @@ describe('publishAgentHookEnvelope', () => { } }) - it('never probes the budget for a single sink that accepts the frame', () => { - const primary = makeBoundedClient(16384) - const dispatcher = new RelayDispatcher(primary.write, primary.options) - const probe = vi.spyOn(dispatcher, 'producerEnvelopeBudget') - try { - // One sink writes nothing when it rejects, so the publish attempt is itself the measurement. - publishAgentHookEnvelope(dispatcher, makeEnvelope({ lastAssistantMessage: 128 })) - expect(probe).not.toHaveBeenCalled() - - // Two of the three ladder steps are absent here; skipping them must not cost an extra encode. - publishAgentHookEnvelope(dispatcher, makeEnvelope({ interactivePrompt: 20_000 })) - expect(probe).toHaveBeenCalledTimes(1) - expect(decodeEnvelopes(primary)).toHaveLength(2) - } finally { - probe.mockRestore() - dispatcher.dispose() - } - }) - - it('measures a fan-out up front so both sinks get the same payload', () => { - const primary = makeBoundedClient(65536) - const dispatcher = new RelayDispatcher(primary.write, primary.options) - const secondary = makeBoundedClient(16384) - const probe = vi.spyOn(dispatcher, 'producerEnvelopeBudget') - try { - dispatcher.attachClient(secondary.write, secondary.options) - publishAgentHookEnvelope(dispatcher, makeEnvelope({ lastAssistantMessage: 20_000 })) - // Probing first is what keeps the larger sink from being written a frame we then have to shed. - expect(probe).toHaveBeenCalledTimes(2) - for (const client of [primary, secondary]) { - expect(decodeEnvelopes(client)).toHaveLength(1) - } - } finally { - probe.mockRestore() - dispatcher.dispose() - } - }) - - it('skips absent fields instead of consuming a shed step on them', () => { - const primary = makeBoundedClient(16384) - const dispatcher = new RelayDispatcher(primary.write, primary.options) - try { - // No lastAssistantMessage at all: the ladder must move on to interactivePrompt. - publishAgentHookEnvelope(dispatcher, makeEnvelope({ interactivePrompt: 20_000 })) - - const published = decodeEnvelopes(primary) - expect(published).toHaveLength(1) - expect(published[0].payload.interactivePrompt).toBeUndefined() - expect(primary.closes).toBe(0) - } finally { - dispatcher.dispose() - } - }) - it('publishes without closing the client when even the fully shed envelope is oversized', () => { const primary = makeBoundedClient(16384) const dispatcher = new RelayDispatcher(primary.write, primary.options) @@ -388,27 +254,6 @@ describe('publishAgentHookEnvelope', () => { } }) - it('does not mutate the caller envelope, so the hook-server replay cache stays intact', () => { - const primary = makeBoundedClient(16384) - const dispatcher = new RelayDispatcher(primary.write, primary.options) - try { - const envelope = makeEnvelope({ - lastAssistantMessage: 6_000, - interactivePrompt: 6_000, - subagents: 40 - }) - const before = structuredClone(envelope) - - publishAgentHookEnvelope(dispatcher, envelope) - - expect(envelope).toEqual(before) - expect(envelope.payload.lastAssistantMessage).toBe('a'.repeat(6_000)) - expect(envelope.payload.subagents).toHaveLength(40) - } finally { - dispatcher.dispose() - } - }) - it('sheds to the smallest attached sink so a replay reaches every client', () => { const primary = makeBoundedClient(65536) const dispatcher = new RelayDispatcher(primary.write, primary.options) @@ -427,28 +272,6 @@ describe('publishAgentHookEnvelope', () => { dispatcher.dispose() } }) - - it('logs one multi-sink drop when the fully shed envelope remains unsendable', () => { - const primary = makeBoundedClient(65536) - const dispatcher = new RelayDispatcher(primary.write, primary.options) - const secondary = makeBoundedClient(16384) - const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) - try { - dispatcher.attachClient(secondary.write, secondary.options) - const envelope = makeEnvelope({}) - envelope.payload.prompt = 'p'.repeat(40_000) - publishAgentHookEnvelope(dispatcher, envelope) - publishAgentHookEnvelope(dispatcher, envelope) - - expect(decodeEnvelopes(primary)).toHaveLength(0) - expect(decodeEnvelopes(secondary)).toHaveLength(0) - expect(stderr).toHaveBeenCalledTimes(1) - expect(String(stderr.mock.calls[0][0])).toContain('Dropped agent.hook') - } finally { - stderr.mockRestore() - dispatcher.dispose() - } - }) }) describe('publishAgentHookEnvelope shed marker', () => { @@ -577,41 +400,6 @@ describe('publishAgentHookEnvelope redelivery', () => { } }) - it('evicts the longest-idle pane once the pending map is full, keeping the newest', () => { - const primary = makeBoundedClient(16384) - const dispatcher = new RelayDispatcher(primary.write, primary.options) - try { - saturateProducerQueue(dispatcher, primary) - // 65 panes against a 64-pane cap: the first must be evicted, the last must survive. - for (let pane = 0; pane < 65; pane++) { - const envelope = makeEnvelope({}) - envelope.paneKey = `tab-1:4f1b0f4e-0000-4000-8000-${String(pane).padStart(12, '0')}` - publishAgentHookEnvelope(dispatcher, envelope) - } - - const refreshed = makeEnvelope({}) - refreshed.paneKey = 'tab-1:4f1b0f4e-0000-4000-8000-000000000001' - publishAgentHookEnvelope(dispatcher, refreshed) - const newest = makeEnvelope({}) - newest.paneKey = 'tab-1:4f1b0f4e-0000-4000-8000-000000000065' - publishAgentHookEnvelope(dispatcher, newest) - - primary.blocked = false - primary.drain() - vi.advanceTimersByTime(1_000) - - const redelivered = decodeEnvelopes(primary).map((envelope) => envelope.paneKey) - expect(redelivered).toHaveLength(64) - expect(redelivered).toContain('tab-1:4f1b0f4e-0000-4000-8000-000000000064') - expect(redelivered).not.toContain('tab-1:4f1b0f4e-0000-4000-8000-000000000000') - expect(redelivered).toContain('tab-1:4f1b0f4e-0000-4000-8000-000000000001') - expect(redelivered).not.toContain('tab-1:4f1b0f4e-0000-4000-8000-000000000002') - expect(redelivered).toContain('tab-1:4f1b0f4e-0000-4000-8000-000000000065') - } finally { - dispatcher.dispose() - } - }) - it('drops pending redeliveries when the dispatcher is disposed', () => { const primary = makeBoundedClient(16384) const dispatcher = new RelayDispatcher(primary.write, primary.options) diff --git a/src/wsl-guest/agent-hook-integration.test.ts b/src/wsl-guest/agent-hook-integration.test.ts index 5520e8b3b02..cced308168f 100644 --- a/src/wsl-guest/agent-hook-integration.test.ts +++ b/src/wsl-guest/agent-hook-integration.test.ts @@ -14,7 +14,6 @@ import { AGENT_HOOK_NOTIFICATION_METHOD, AGENT_HOOK_REQUEST_REPLAY_METHOD } from '../shared/agent-hook-listener/transport/agent-hook-relay' -import { AGENT_STATUS_ASSISTANT_MESSAGE_MAX_LENGTH } from '../shared/agent-status/contracts/agent-status-types' import { AgentHookServer } from '../main/agent-hooks/server' import { publishAgentHookEnvelope } from './agent-hook-envelope-publication' @@ -142,54 +141,6 @@ describe('Integration: relay hook server → mux → AgentHookServer.ingestRemot .toBe('cancellation') }) - it.each([ - { agent: 'claude', input: { hook_event_name: 'UserPromptSubmit', prompt: 'roundtrip' } }, - { - agent: 'opencode2', - input: { hook_event_name: 'MessagePart', role: 'user', text: 'roundtrip' } - } - ])('forwards a $agent prompt through the relay to ingestRemote', async ({ agent, input }) => { - const events: { paneKey: string; payload: unknown; connectionId: string | null }[] = [] - orcaServer.setListener((event) => { - events.push({ - paneKey: event.paneKey, - payload: event.payload, - connectionId: event.connectionId - }) - }) - - const { port, token } = hookServer.getCoordinates() - const res = await fetch(`http://127.0.0.1:${port}/hook/${agent}`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': token - }, - body: JSON.stringify({ - paneKey: `tab-7:${LEAF_7}`, - tabId: 'tab-7', - worktreeId: 'wt-7', - env: 'remote', - version: '1', - payload: input - }) - }) - expect(res.status).toBe(204) - - // Dispatch, transport and mux delivery span ticks; await the observed event rather than a fixed delay. - const start = Date.now() - while (events.length === 0 && Date.now() - start < 1500) { - await new Promise((r) => setImmediate(r)) - } - expect(events).toHaveLength(1) - expect(events[0].paneKey).toBe(`tab-7:${LEAF_7}`) - expect(events[0].connectionId).toBe('conn-test') - const payload = events[0].payload as { state: string; prompt: string; agentType: string } - expect(payload.state).toBe('working') - expect(payload.prompt).toBe('roundtrip') - expect(payload.agentType).toBe(agent) - }) - it.each([0, 1, 2, 3])( 'delivers Cursor form payloads with %i BOMs to the host-owned status store', async (count) => { @@ -261,42 +212,6 @@ describe('Integration: relay hook server → mux → AgentHookServer.ingestRemot expect(orcaServer.getStatusSnapshot()).toEqual([]) }) - it('sheds an oversized assistant message through the production publication path', async () => { - const events: { payload: { state: string; lastAssistantMessage?: string } }[] = [] - orcaServer.setListener((event) => { - events.push({ payload: event.payload }) - }) - const { port, token } = hookServer.getCoordinates() - const post = (payload: Record): Promise => - fetch(`http://127.0.0.1:${port}/hook/claude`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': token - }, - body: JSON.stringify({ paneKey: `tab-7:${LEAF_7}`, payload }) - }) - - await expect( - post({ hook_event_name: 'UserPromptSubmit', prompt: 'bounded publication' }) - ).resolves.toMatchObject({ status: 204 }) - await expect( - post({ - hook_event_name: 'Stop', - last_assistant_message: 'a'.repeat(AGENT_STATUS_ASSISTANT_MESSAGE_MAX_LENGTH) - }) - ).resolves.toMatchObject({ status: 204 }) - - const start = Date.now() - while (events.length < 2 && Date.now() - start < 1500) { - await new Promise((resolve) => setImmediate(resolve)) - } - expect(events).toHaveLength(2) - expect(events[1].payload.state).toBe('done') - expect(events[1].payload.lastAssistantMessage).toBeUndefined() - expect(dispatcher.activeClientIds()).toHaveLength(1) - }) - it('clears remote Claude permission when the approved tool starts with matching identity', async () => { const { port, token } = hookServer.getCoordinates() const postClaude = async (payload: Record): Promise => diff --git a/src/wsl-guest/agent-hook-opencode-tui-identity.test.ts b/src/wsl-guest/agent-hook-opencode-tui-identity.test.ts index 9b3e834aa40..d18dfe8dbbe 100644 --- a/src/wsl-guest/agent-hook-opencode-tui-identity.test.ts +++ b/src/wsl-guest/agent-hook-opencode-tui-identity.test.ts @@ -88,14 +88,6 @@ describe('legacy TUI identity admitted by the execution-host relay', () => { ]) }) - it('keeps the session creator when another pane views the same session', async () => { - await post(PANE_A, 'ses_a') - forward.mockClear() - await post(PANE_B, 'ses_a') - expect(forward.mock.calls[0][0].paneKey).toBe(PANE_A) - expect(server.replayCachedPayloadsForPanes()).toBe(1) - }) - it.each(['SessionIdle', 'PermissionRequest', 'MessagePart'] as const)( 'rejects a retired physical viewer before attributing its late %s to a live creator', async (hookEventName) => { diff --git a/src/wsl-guest/agent-hook-provider-normalization.test.ts b/src/wsl-guest/agent-hook-provider-normalization.test.ts index 3ea7bdabb39..5b8edac5967 100644 --- a/src/wsl-guest/agent-hook-provider-normalization.test.ts +++ b/src/wsl-guest/agent-hook-provider-normalization.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { RelayAgentHookServer } from './agent-hook-server' @@ -18,41 +18,6 @@ describe('relay provider normalization', () => { }) afterEach(() => rmSync(dir, { recursive: true, force: true })) - it('forwards mixed-provider spool replay without losing the new prompt', async () => { - const spoolDir = join(dir, 'spool') - mkdirSync(spoolDir) - writeFileSync( - join(spoolDir, 'pane.jsonl'), - `${[ - ['codex', { hook_event_name: 'UserPromptSubmit', prompt: 'Old turn' }], - ['claude', { hook_event_name: 'UserPromptSubmit', prompt: 'New turn' }], - ['claude', { hook_event_name: 'PreToolUse', tool_name: 'Read' }] - ] - .map(([source, payload]) => - JSON.stringify({ - paneKey: PANE, - tabId: 'tab-1', - source, - payload, - receivedAt: Date.now() - }) - ) - .join('\n')}\n` - ) - const forward = vi.fn<(event: AgentHookRelayEnvelope) => void>() - const relay = new RelayAgentHookServer({ endpointDir: dir, forward }) - try { - await relay.start() - expect(forward).toHaveBeenCalledTimes(3) - expect(forward.mock.calls[2][0]).toMatchObject({ - isReplay: true, - payload: { agentType: 'claude', prompt: 'New turn', toolName: 'Read' } - }) - } finally { - relay.stop() - } - }) - it('forwards a new provider despite the cached owner and replays its latest prompt', async () => { const forward = vi.fn<(event: AgentHookRelayEnvelope) => void>() const relay = new RelayAgentHookServer({ endpointDir: dir, forward }) diff --git a/src/wsl-guest/agent-hook-server.test.ts b/src/wsl-guest/agent-hook-server.test.ts index 1f0989c34a4..cb432c5db41 100644 --- a/src/wsl-guest/agent-hook-server.test.ts +++ b/src/wsl-guest/agent-hook-server.test.ts @@ -1,10 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { homedir, tmpdir } from 'node:os' +import { tmpdir } from 'node:os' import { join } from 'node:path' import { RelayAgentHookServer } from './agent-hook-server' -import type { AgentHookResultRetryScheduler } from './agent-hook-result-retry-scheduler' -import { endpointDirForRelaySocket } from './agent-hook-endpoint-coordinates' import type { AgentHookRelayEnvelope } from '../shared/agent-hook-listener/transport/agent-hook-relay' import { makePaneKey } from '../shared/workspace-layout/stable-pane-id' import * as agentHookListener from '../shared/agent-hook-listener/grok-result-discovery' @@ -13,11 +11,6 @@ import { HOOK_REQUEST_MAX_BYTES } from '../shared/agent-hook-listener/request-bo const LEAF_ID = '11111111-1111-4111-8111-111111111111' const PANE_KEY = makePaneKey('tab-1', LEAF_ID) -type RelayServerInternals = { - state: { lastStatusByPaneKey: Map } - retryScheduler: AgentHookResultRetryScheduler -} - describe('RelayAgentHookServer', () => { let dir: string beforeEach(() => { @@ -27,13 +20,6 @@ describe('RelayAgentHookServer', () => { rmSync(dir, { recursive: true, force: true }) }) - it('keeps named-pipe endpoint files on a real filesystem path', () => { - const endpointDir = endpointDirForRelaySocket('\\\\.\\pipe\\orca-relay-abc123') - - expect(endpointDir).toBe(join(homedir(), '.orca-relay', 'agent-hooks', 'orca-relay-abc123')) - expect(endpointDir).not.toContain('\\\\.\\pipe') - }) - it('forwards a raw Claude JSON POST with base64 metadata headers', async () => { const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() const server = new RelayAgentHookServer({ endpointDir: dir, forward }) @@ -71,49 +57,6 @@ describe('RelayAgentHookServer', () => { } }) - it('normalizes and forwards raw spooled hooks on startup', async () => { - const spoolDir = join(dir, 'spool') - const spoolFile = join(spoolDir, 'pane-codex.jsonl') - mkdirSync(spoolDir) - writeFileSync( - spoolFile, - `${JSON.stringify({ - paneKey: PANE_KEY, - tabId: 'tab-1', - worktreeId: 'wt-1', - env: 'remote', - version: '1', - launchToken: 'generation-token', - hookEventName: 'SubagentStop', - source: 'codex', - payload: { hook_event_name: 'SubagentStop', agent_id: 'child-spooled' }, - receivedAt: Date.now() - })}\n` - ) - const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() - const server = new RelayAgentHookServer({ endpointDir: dir, forward }) - - await server.start() - try { - expect(forward).toHaveBeenCalledTimes(1) - expect(forward.mock.calls[0][0]).toMatchObject({ - source: 'codex', - paneKey: PANE_KEY, - tabId: 'tab-1', - worktreeId: 'wt-1', - launchToken: 'generation-token', - hookEventName: 'SubagentStop', - isReplay: true, - env: 'remote', - version: '1', - payload: { state: 'working', agentType: 'codex' } - }) - expect(readFileSync(spoolFile)).toHaveLength(0) - } finally { - server.stop() - } - }) - it('keeps the relay listening when spool replay forwarding fails', async () => { const spoolDir = join(dir, 'spool') const spoolFile = join(spoolDir, 'pane-codex.jsonl') @@ -144,44 +87,6 @@ describe('RelayAgentHookServer', () => { } }) - it('fails open after a throwing forward while retaining the already-cached event', async () => { - const server = new RelayAgentHookServer({ - endpointDir: dir, - forward: () => { - throw new Error('forward failed') - } - }) - // Characterization deliberately observes cache/scheduler order without widening production API. - const internals = server as unknown as RelayServerInternals - const retryScheduler = internals.retryScheduler - const assistantRetry = vi.spyOn(retryScheduler, 'scheduleAssistantMessageRetry') - const codexRetry = vi.spyOn(retryScheduler, 'scheduleTranscriptPoll') - await server.start() - try { - const { port, token } = server.getCoordinates() - const res = await fetch(`http://127.0.0.1:${port}/hook/claude`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': token - }, - body: JSON.stringify({ - paneKey: PANE_KEY, - hook_event_name: 'UserPromptSubmit', - payload: { prompt: 'cached before throw' } - }) - }) - expect(res.status).toBe(204) - expect(internals.state.lastStatusByPaneKey.has(PANE_KEY)).toBe(true) - expect(assistantRetry).not.toHaveBeenCalled() - expect(codexRetry).not.toHaveBeenCalled() - } finally { - server.stop() - assistantRetry.mockRestore() - codexRetry.mockRestore() - } - }) - it('forwards Claude background monitoring until its authoritative inventory drains', async () => { const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() const server = new RelayAgentHookServer({ endpointDir: dir, forward }) @@ -287,124 +192,6 @@ describe('RelayAgentHookServer', () => { } }) - it('replays cached payloads on demand', async () => { - const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() - const server = new RelayAgentHookServer({ endpointDir: dir, forward }) - await server.start() - try { - const { port, token } = server.getCoordinates() - await fetch(`http://127.0.0.1:${port}/hook/claude`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': token - }, - body: JSON.stringify({ - paneKey: PANE_KEY, - tabId: 'tab-1', - env: 'remote', - version: '1', - payload: { hook_event_name: 'UserPromptSubmit', prompt: 'cache me' } - }) - }) - forward.mockClear() - const replayed = server.replayCachedPayloadsForPanes() - expect(replayed).toBe(1) - expect(forward).toHaveBeenCalledTimes(1) - expect(forward.mock.calls[0][0].payload.prompt).toBe('cache me') - // Replay must retain env/version/source for protocol diagnostics and remote location. - expect(forward.mock.calls[0][0].source).toBe('claude') - expect(forward.mock.calls[0][0].env).toBe('remote') - expect(forward.mock.calls[0][0].version).toBe('1') - expect(forward.mock.calls[0][0].isReplay).toBe(true) - } finally { - server.stop() - } - }) - - it('forwards and replays Pi session identity as metadata-only', async () => { - const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() - const server = new RelayAgentHookServer({ endpointDir: dir, forward }) - await server.start() - try { - const { port, token } = server.getCoordinates() - const res = await fetch(`http://127.0.0.1:${port}/hook/pi`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': token - }, - body: JSON.stringify({ - paneKey: PANE_KEY, - tabId: 'tab-1', - worktreeId: 'wt-1', - env: 'remote', - version: '1', - payload: { - hook_event_name: 'session_start', - session_id: 'pi-session-1', - session_file: '/tmp/pi-session-1.jsonl' - } - }) - }) - - expect(res.status).toBe(204) - expect(forward).toHaveBeenCalledTimes(1) - expect(forward.mock.calls[0][0]).toMatchObject({ - source: 'pi', - paneKey: PANE_KEY, - providerSessionOnly: true, - providerSession: { - key: 'session_id', - id: 'pi-session-1', - transcriptPath: '/tmp/pi-session-1.jsonl' - } - }) - - forward.mockClear() - expect(server.replayCachedPayloadsForPanes()).toBe(1) - expect(forward).toHaveBeenCalledWith( - expect.objectContaining({ - source: 'pi', - providerSessionOnly: true, - providerSession: expect.objectContaining({ - transcriptPath: '/tmp/pi-session-1.jsonl' - }), - isReplay: true - }) - ) - } finally { - server.stop() - } - }) - - it('does not replay paneKeys after clearPaneState', async () => { - const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() - const server = new RelayAgentHookServer({ endpointDir: dir, forward }) - await server.start() - try { - const { port, token } = server.getCoordinates() - await fetch(`http://127.0.0.1:${port}/hook/claude`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': token - }, - body: JSON.stringify({ - paneKey: PANE_KEY, - payload: { hook_event_name: 'UserPromptSubmit', prompt: 'gone' } - }) - }) - server.clearPaneState(PANE_KEY) - forward.mockClear() - const replayed = server.replayCachedPayloadsForPanes() - expect(replayed).toBe(0) - expect(forward).not.toHaveBeenCalled() - } finally { - server.stop() - } - }) - // Reject malformed HTTP events before the wire even though main revalidates at SSH ingress. it('does not forward when normalizeHookPayload rejects the event', async () => { const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() @@ -433,19 +220,6 @@ describe('RelayAgentHookServer', () => { } }) - it('can defer endpoint file publication until relay socket ownership is proven', async () => { - const forward = vi.fn() - const server = new RelayAgentHookServer({ endpointDir: dir, forward }) - await server.start({ publishEndpoint: false }) - try { - expect(server.buildPtyEnv().ORCA_AGENT_HOOK_ENDPOINT).toBeUndefined() - expect(server.publishEndpointFile()).toBe(true) - expect(server.buildPtyEnv().ORCA_AGENT_HOOK_ENDPOINT).toBeTruthy() - } finally { - server.stop() - } - }) - it('keeps Copilot transcript retry alive across a following SessionEnd event', async () => { const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() const server = new RelayAgentHookServer({ endpointDir: dir, forward }) @@ -547,108 +321,6 @@ describe('RelayAgentHookServer', () => { } }) - it('retries Grok chat history on the relay without blocking the hook POST', async () => { - const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() - const server = new RelayAgentHookServer({ endpointDir: dir, forward }) - const sessionId = '019e37f4-5135-7b63-a4ab-6d13aa6bf528' - const cwd = join(dir, 'workspace') - const sessionDir = join(dir, '.grok', 'sessions', encodeURIComponent(cwd), sessionId) - mkdirSync(sessionDir, { recursive: true }) - writeFileSync(join(sessionDir, 'chat_history.jsonl'), '') - vi.stubEnv('HOME', dir) - vi.stubEnv('USERPROFILE', dir) - await server.start() - try { - const { port, token } = server.getCoordinates() - await fetch(`http://127.0.0.1:${port}/hook/grok`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': token - }, - body: JSON.stringify({ - paneKey: PANE_KEY, - tabId: 'tab-1', - env: 'remote', - version: '1', - payload: { hookEventName: 'user_prompt_submit', prompt: 'hihi' } - }) - }) - const response = await fetch(`http://127.0.0.1:${port}/hook/grok`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': token - }, - body: JSON.stringify({ - paneKey: PANE_KEY, - tabId: 'tab-1', - env: 'remote', - version: '1', - payload: { hookEventName: 'Stop', sessionId, cwd } - }) - }) - - expect(response.status).toBe(204) - expect(forward.mock.calls.at(-1)?.[0].payload.lastAssistantMessage).toBeUndefined() - - writeFileSync( - join(sessionDir, 'chat_history.jsonl'), - `${JSON.stringify({ type: 'assistant', content: 'Relay Grok reply.' })}\n` - ) - await new Promise((resolve) => setTimeout(resolve, 120)) - - expect(forward.mock.calls.at(-1)?.[0].payload.lastAssistantMessage).toBe('Relay Grok reply.') - } finally { - server.stop() - vi.unstubAllEnvs() - } - }) - - it('caps the replay cache at 256 panes, evicting the least-recently-updated', async () => { - // Match private MAX_CACHED_PANES; WSL receives no pane teardown signal and relies on recency eviction. - const CAP = 256 - const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() - const server = new RelayAgentHookServer({ endpointDir: dir, forward }) - await server.start() - try { - const { port, token } = server.getCoordinates() - const paneKeyFor = (i: number): string => makePaneKey(`tab-${i}`, LEAF_ID) - const postPane = (paneKey: string): Promise => - fetch(`http://127.0.0.1:${port}/hook/claude`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': token - }, - body: JSON.stringify({ - paneKey, - payload: { hook_event_name: 'UserPromptSubmit', prompt: 'p' } - }) - }) - - // Await posts sequentially so insertion order tracks update recency. - for (let i = 0; i < CAP; i++) { - await postPane(paneKeyFor(i)) - } - // Refresh the oldest before overflow to distinguish recency eviction from insertion order. - await postPane(paneKeyFor(0)) - await postPane(paneKeyFor(CAP)) - - forward.mockClear() - const replayed = server.replayCachedPayloadsForPanes() - expect(replayed).toBe(CAP) - - const cachedPaneKeys = new Set(forward.mock.calls.map((call) => call[0].paneKey)) - expect(cachedPaneKeys.size).toBe(CAP) - expect(cachedPaneKeys.has(paneKeyFor(0))).toBe(true) - expect(cachedPaneKeys.has(paneKeyFor(CAP))).toBe(true) - expect(cachedPaneKeys.has(paneKeyFor(1))).toBe(false) - } finally { - server.stop() - } - }, 30_000) - it('forwards a Grok result when discovery finishes after the old retry window', async () => { let releaseDiscovery!: () => void const discovery = new Promise((resolve) => { diff --git a/src/wsl-guest/relay-command-env.test.ts b/src/wsl-guest/relay-command-env.test.ts index dbd204fbca8..7cb1a978ca1 100644 --- a/src/wsl-guest/relay-command-env.test.ts +++ b/src/wsl-guest/relay-command-env.test.ts @@ -1,5 +1,4 @@ import { describe, expect, it, vi } from 'vitest' -import { homedir } from 'node:os' import { buildRelayCommandEnv, buildRelayUnattendedGitEnv } from './relay-command-env' // Fix the fallback home so no-resolvable-home behavior is testable and independent of the user’s machine. @@ -22,35 +21,12 @@ describe('buildRelayCommandEnv', () => { expect(env.Path).not.toContain('.npm-global') }) - it('falls back to homedir() for user bins when the relay env carries no HOME', () => { - const env = buildRelayCommandEnv({ PATH: '/usr/bin' }, 'linux') - - expect(env.PATH?.split(':')).toContain('/home/fallback/.local/bin') - expect(env.PATH).not.toContain('undefined') - }) - - it('adds only POSIX fallbacks when no home directory can be resolved', () => { - vi.mocked(homedir).mockReturnValueOnce('') - const env = buildRelayCommandEnv({ PATH: '' }, 'linux') - const segments = env.PATH?.split(':') ?? [] - - expect(segments).toEqual(expect.arrayContaining(['/usr/local/bin', '/usr/bin', '/bin'])) - expect(segments.some((s) => s.includes('.local/bin'))).toBe(false) - }) - it('keeps inherited PATH entries ahead of the appended fallbacks', () => { const env = buildRelayCommandEnv({ HOME: '/home/me', PATH: '/custom/bin' }, 'linux') const segments = env.PATH?.split(':') ?? [] expect(segments.indexOf('/custom/bin')).toBeLessThan(segments.indexOf('/usr/bin')) }) - - it('orders the static POSIX fallbacks ahead of the resolved user bins', () => { - const env = buildRelayCommandEnv({ HOME: '/home/me', PATH: '' }, 'linux') - const segments = env.PATH?.split(':') ?? [] - - expect(segments.indexOf('/usr/bin')).toBeLessThan(segments.indexOf('/home/me/.local/bin')) - }) }) describe('buildRelayUnattendedGitEnv', () => {