mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 19:07:41 +00:00
test: remove 11 low-value suites and trim 17 others (#42989)
Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
@@ -3172,15 +3172,10 @@
|
||||
"src/packages/process-host/src/windows-command-line.test.ts": 73,
|
||||
"src/packages/process-host/src/windows-tree-kill.test.ts": 81,
|
||||
"src/packages/process-host/src/wsl-distro-allowlist.test.ts": 55,
|
||||
"src/preload/api/notifications/notification-sound-playback.test.ts": 64,
|
||||
"src/preload/renderer/restart/app-restart-checkpoint-routing.test.ts": 2028,
|
||||
"src/preload/renderer/browser-pages/browser-client-page-renderer-requests.test.ts": 154,
|
||||
"src/preload/browser/extensions/messaging/browser-extension-content-script-relay.test.ts": 65,
|
||||
"src/preload/browser/extensions/documents/browser-extension-document-targets.test.ts": 75,
|
||||
"src/preload/browser/extensions/api/browser-extension-main-world.test.ts": 81,
|
||||
"src/preload/browser/extensions/storage/browser-extension-storage-relay.test.ts": 104,
|
||||
"src/preload/browser/extensions/storage/browser-extension-storage-sync.test.ts": 108,
|
||||
"src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.test.ts": 166,
|
||||
"src/preload/renderer/browser-pages/browser-find-subscriptions.test.ts": 66,
|
||||
"src/preload/browser-window-close.test.ts": 98,
|
||||
"src/preload/doc-preview-link-interception.test.ts": 234,
|
||||
@@ -4703,7 +4698,6 @@
|
||||
"src/wsl-guest/transport/connection/dispatcher-structured-error.test.ts": 203,
|
||||
"src/wsl-guest/transport/writer/dispatcher-writer-admission.test.ts": 109,
|
||||
"src/wsl-guest/transport/publication/dispatcher.test.ts": 348,
|
||||
"src/wsl-guest/plugins/overlays/omp-config-root.test.ts": 254,
|
||||
"src/wsl-guest/plugins/installation/opencode-startup-prompt-install.test.ts": 290,
|
||||
"src/wsl-guest/plugins/overlays/plugin-overlay-env.test.ts": 130,
|
||||
"src/wsl-guest/plugins/overlays/plugin-overlay.test.ts": 263,
|
||||
@@ -5112,7 +5106,6 @@
|
||||
"tests/e2e/worktree-active-delete-scroll-position.spec.ts": 59200,
|
||||
"tests/e2e/worktree-card-downward-drag.spec.ts": 60000,
|
||||
"tests/e2e/worktree-delete-shortcut.spec.ts": 20600,
|
||||
"tests/e2e/worktree-jump-palette-filter.spec.ts": 96200,
|
||||
"tests/e2e/worktree-lifecycle.spec.ts": 44000,
|
||||
"tests/e2e/worktree-lineage-agent-expansion.spec.ts": 21800,
|
||||
"tests/e2e/worktree-lineage.spec.ts": 96700,
|
||||
|
||||
@@ -30,35 +30,6 @@ describe('GrowingByteBuffer', () => {
|
||||
expect(taken).toEqual(bytes)
|
||||
})
|
||||
|
||||
it('preserves 100,000 one-byte fragments across buffer growth', () => {
|
||||
const buffer = new GrowingByteBuffer()
|
||||
const expected = Buffer.alloc(100_000)
|
||||
|
||||
for (let index = 0; index < expected.byteLength; index += 1) {
|
||||
const value = index % 251
|
||||
expected[index] = value
|
||||
buffer.append(Uint8Array.of(value))
|
||||
}
|
||||
|
||||
expect(buffer.byteLength).toBe(expected.byteLength)
|
||||
expect(buffer.takeString('latin1')).toBe(expected.toString('latin1'))
|
||||
expect(buffer.byteLength).toBe(0)
|
||||
})
|
||||
|
||||
it('consumes delimited prefixes and retains a bounded suffix', () => {
|
||||
const buffer = new GrowingByteBuffer()
|
||||
for (const byte of Buffer.from('first\nsecond-tail')) {
|
||||
buffer.append(Uint8Array.of(byte))
|
||||
}
|
||||
|
||||
const newline = buffer.indexOfByte(0x0a)
|
||||
expect(buffer.takePrefixString(newline)).toBe('first')
|
||||
buffer.discardPrefix(1)
|
||||
buffer.retainSuffix(4)
|
||||
|
||||
expect(buffer.toString()).toBe('tail')
|
||||
})
|
||||
|
||||
it('appends only a bounded copy from an oversized source chunk', () => {
|
||||
const buffer = new GrowingByteBuffer()
|
||||
buffer.append(Buffer.from('old'))
|
||||
@@ -70,40 +41,4 @@ describe('GrowingByteBuffer', () => {
|
||||
expect(buffer.byteLength).toBe(4)
|
||||
expect(buffer.toString()).toBe('tail')
|
||||
})
|
||||
|
||||
it('keeps the newest bytes across bounded suffix appends', () => {
|
||||
const buffer = new GrowingByteBuffer()
|
||||
|
||||
buffer.appendRetainedSuffix(Buffer.from('1234'), 6)
|
||||
buffer.appendRetainedSuffix(Buffer.from('5678'), 6)
|
||||
|
||||
expect(buffer.toString()).toBe('345678')
|
||||
})
|
||||
|
||||
it('reads and writes correctly after the head offset has advanced', () => {
|
||||
const buffer = new GrowingByteBuffer()
|
||||
buffer.append(Buffer.from('aaa\nbbb\nccc'))
|
||||
|
||||
expect(buffer.takePrefixString(buffer.indexOfByte(0x0a))).toBe('aaa')
|
||||
buffer.discardPrefix(1)
|
||||
expect(buffer.indexOfByte(0x0a)).toBe(3)
|
||||
expect(buffer.byteLength).toBe(7)
|
||||
buffer.append(Buffer.from('!'))
|
||||
expect(buffer.toString()).toBe('bbb\nccc!')
|
||||
expect(buffer.takeBuffer()).toEqual(Buffer.from('bbb\nccc!'))
|
||||
expect(buffer.byteLength).toBe(0)
|
||||
})
|
||||
|
||||
it('retains the newest 64 bytes across many small appends', () => {
|
||||
const buffer = new GrowingByteBuffer()
|
||||
let expected = ''
|
||||
for (let index = 0; index < 5_000; index += 1) {
|
||||
const chunk = String(index % 10).repeat(3)
|
||||
buffer.appendRetainedSuffix(Buffer.from(chunk), 64)
|
||||
expected = (expected + chunk).slice(-64)
|
||||
}
|
||||
|
||||
expect(buffer.byteLength).toBe(64)
|
||||
expect(buffer.takeString()).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,7 +5,6 @@ const { spawnProcess } = vi.hoisted(() => ({ spawnProcess: vi.fn() }))
|
||||
vi.mock('./run-process', () => ({ spawnProcess }))
|
||||
|
||||
import {
|
||||
buildWindowsEnvironmentBlock,
|
||||
quoteWindowsArgumentLikeLibuv,
|
||||
setIsolatedSpawner,
|
||||
spawnDetachedWithoutInheritance,
|
||||
@@ -36,27 +35,6 @@ describe('quoteWindowsArgumentLikeLibuv', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildWindowsEnvironmentBlock', () => {
|
||||
it('sorts case-insensitively, keeps the first of a duplicate, and ends with two NULs', () => {
|
||||
const block = buildWindowsEnvironmentBlock(
|
||||
{ b: '2', A: '1', B: 'dup', SYSTEMROOT: 'C:\\Windows', skip: undefined },
|
||||
{}
|
||||
)
|
||||
|
||||
expect(block).toBe('A=1\0b=2\0SYSTEMROOT=C:\\Windows\0\0')
|
||||
})
|
||||
|
||||
it('fills required variables from the parent the way libuv does', () => {
|
||||
const block = buildWindowsEnvironmentBlock({ X: '1' }, { SystemRoot: 'C:\\W', Other: 'no' })
|
||||
|
||||
expect(block).toBe('SystemRoot=C:\\W\0X=1\0\0')
|
||||
})
|
||||
|
||||
it('keeps an empty environment a valid block', () => {
|
||||
expect(buildWindowsEnvironmentBlock({}, {})).toBe('\0')
|
||||
})
|
||||
})
|
||||
|
||||
describe('spawnDetachedWithoutInheritance', () => {
|
||||
afterEach(() => {
|
||||
setIsolatedSpawner(null)
|
||||
|
||||
@@ -28,27 +28,6 @@ async function executable(file: string, text: string) {
|
||||
}
|
||||
|
||||
describe.skipIf(process.platform === 'win32')('native executable candidates', () => {
|
||||
it('rediscovers removed files, PATH changes and earlier installations after a fixed expiry', async () => {
|
||||
const { first, second, env } = await fixture()
|
||||
let now = 0
|
||||
const resolver = new NativeExecutableResolver('darwin', () => now)
|
||||
const late = join(second, 'probe')
|
||||
const early = join(first, 'probe')
|
||||
await executable(late, '#!/bin/sh\necho late\n')
|
||||
expect(resolver.resolve('probe', env).file).toBe(late)
|
||||
await executable(early, '#!/bin/sh\necho early\n')
|
||||
now = 29_000
|
||||
expect((await resolver.resolveAsync('probe', env)).file).toBe(late)
|
||||
now = 30_001
|
||||
expect(resolver.resolve('probe', env).file).toBe(early)
|
||||
await rm(early)
|
||||
expect((await resolver.resolveAsync('probe', env)).file).toBe(late)
|
||||
await executable(early, '#!/bin/sh\necho new\n')
|
||||
expect(resolver.resolve('probe', { PATH: first }).file).toBe(early)
|
||||
await chmod(late, 0o644)
|
||||
expect(resolver.resolve('probe', env).file).toBe(early)
|
||||
})
|
||||
|
||||
it('leaves native lookup in charge of absent, empty and relative PATH, explicit paths and other hosts', async () => {
|
||||
const { first, second, env } = await fixture()
|
||||
await executable(join(second, 'probe'), '#!/bin/sh\nexit 0\n')
|
||||
|
||||
@@ -133,12 +133,6 @@ describe.skipIf(process.platform === 'win32')('lsof supervisor lifecycle', () =>
|
||||
}
|
||||
)
|
||||
|
||||
it('accepts zombie-only group evidence after the direct child closes', async () => {
|
||||
const result = await runProbe({ census: 'printf "%s Z\\n" "$(cat "$PROBE_PID")"\n' })
|
||||
expect(result.stdout).toBe('unavailable\n123\n')
|
||||
expect(result.timedOut).toBe(false)
|
||||
})
|
||||
|
||||
it('requires census cleanup even when the lsof group disappears', async () => {
|
||||
const result = await runProbe({
|
||||
census: 'sleep 60 </dev/null >/dev/null 2>&1 &\nexit 0\n',
|
||||
@@ -192,31 +186,5 @@ linuxOnly('lsof blindness to another uid', () => {
|
||||
expect(result.stdout).toBe('unavailable\n\n')
|
||||
})
|
||||
|
||||
it('still reports lsof for an empty answer about a path nothing has bound', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'orca-lsof-stale-'))
|
||||
try {
|
||||
const result = await runProbe({ lsof: BLIND_LSOF, sockPath: join(dir, 'never-bound.sock') })
|
||||
expect(result.stdout).toBe('lsof\n\n')
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps a reported pid even while the path is still bound', async () => {
|
||||
const result = await withBoundSocket((sockPath) =>
|
||||
runProbe({ lsof: '#!/bin/sh\necho 123\nexit 0\n', sockPath })
|
||||
)
|
||||
expect(result.stdout).toBe('lsof\n123\n')
|
||||
})
|
||||
|
||||
// Test both prefix directions to reject substring-based socket matches.
|
||||
it.each([
|
||||
['a prefix of the bound path', (sockPath: string) => sockPath.slice(0, -1)],
|
||||
['a path the bound one prefixes', (sockPath: string) => `${sockPath}.other`]
|
||||
])('does not treat %s as bound', async (_name, derive) => {
|
||||
const result = await withBoundSocket((sockPath) =>
|
||||
runProbe({ lsof: BLIND_LSOF, sockPath: derive(sockPath) })
|
||||
)
|
||||
expect(result.stdout).toBe('lsof\n\n')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -209,35 +209,6 @@ describe('process-tree-kill breadcrumb seam', () => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('reports the Windows taskkill tree it just spawned', async () => {
|
||||
await withWindows(async () => {
|
||||
const child = mockProcess(1234)
|
||||
const taskkill = mockProcess(5678)
|
||||
spawnMock.mockReturnValue(taskkill)
|
||||
|
||||
const pending = signalProcessTree(child, 'SIGKILL')
|
||||
taskkill.emit('close', 0)
|
||||
await pending
|
||||
|
||||
expect(observed).toEqual([
|
||||
{ pid: 1234, site: 'run-process-tree', scope: 'win-taskkill-tree' }
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'reports the POSIX process group it signalled',
|
||||
async () => {
|
||||
vi.spyOn(process, 'kill').mockImplementation(() => true)
|
||||
|
||||
await expect(signalProcessTree(mockProcess(1234), 'SIGKILL')).resolves.toBe(true)
|
||||
|
||||
expect(observed).toEqual([
|
||||
{ pid: 1234, site: 'run-process-tree', scope: 'posix-process-group' }
|
||||
])
|
||||
}
|
||||
)
|
||||
|
||||
it('never taskkills a pid the child already gave back to Windows', async () => {
|
||||
await withWindows(async () => {
|
||||
const child = mockProcess(1234)
|
||||
|
||||
@@ -46,32 +46,4 @@ describe('process byte capture', () => {
|
||||
expect(result.stdoutBytes).toEqual(Buffer.alloc(50))
|
||||
expect(result.code === 0 && result.signal === null).toBe(false)
|
||||
})
|
||||
|
||||
it('lets diagnostic streams exceed the cap while retaining their binary tails', async () => {
|
||||
const result = await runProcess(
|
||||
{
|
||||
program: process.execPath,
|
||||
args: [
|
||||
'-e',
|
||||
'process.stdout.write(Buffer.alloc(12*1024*1024));process.stdout.write(Buffer.from([0,255,254,128]));process.stderr.write(Buffer.alloc(12*1024*1024));process.stderr.write(Buffer.from([128,254,255,0]))'
|
||||
],
|
||||
maxOutputBytes: 4,
|
||||
captureStdoutAsBytes: true,
|
||||
captureStderrAsBytes: true,
|
||||
terminationBarrier: true,
|
||||
timeoutMs: 10_000
|
||||
},
|
||||
'tail'
|
||||
)
|
||||
expect(result).toMatchObject({
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
outputTruncated: true,
|
||||
stdout: '',
|
||||
stderr: ''
|
||||
})
|
||||
expect(result.stdoutBytes).toEqual(Buffer.from([0, 255, 254, 128]))
|
||||
expect(result.stderrBytes).toEqual(Buffer.from([128, 254, 255, 0]))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -6,8 +6,6 @@ import { runProcess, runProcessSync } from './run-process'
|
||||
import { resolveSpawn } from './spawn-resolution'
|
||||
import { WINDOWS_ARGUMENT_CORPUS } from './__fixtures__/windows-argument-corpus'
|
||||
|
||||
const SPEC = { program: 'C:\\bin\\agent.cmd', args: ['--prompt', 'hi'] }
|
||||
|
||||
describe('resolveSpawn', () => {
|
||||
it('always hides the console and never uses a shell', () => {
|
||||
for (const platform of ['win32', 'darwin', 'linux'] as const) {
|
||||
@@ -17,46 +15,6 @@ describe('resolveSpawn', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves IPC serialization while hiding the worker on every platform', () => {
|
||||
for (const platform of ['win32', 'darwin', 'linux'] as const) {
|
||||
for (const serialization of ['json', 'advanced'] as const) {
|
||||
const resolved = resolveSpawn(
|
||||
{ program: process.execPath, stdio: ['pipe', 'pipe', 'pipe', 'ipc'], serialization },
|
||||
platform
|
||||
)
|
||||
expect(resolved.options.serialization).toBe(serialization)
|
||||
expect(resolved.options.stdio).toEqual(['pipe', 'pipe', 'pipe', 'ipc'])
|
||||
expect(resolved.options.windowsHide).toBe(true)
|
||||
expect(resolved.options.shell).toBe(false)
|
||||
}
|
||||
}
|
||||
expect(
|
||||
resolveSpawn({ program: process.execPath }, 'linux').options.serialization
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it('spawns a non-cmd program directly, letting Node do the argv quoting', () => {
|
||||
const resolved = resolveSpawn({ program: 'C:\\bin\\agent.exe', args: ['a b'] }, 'win32')
|
||||
expect(resolved.file).toBe('C:\\bin\\agent.exe')
|
||||
expect(resolved.args).toEqual(['a b'])
|
||||
expect(resolved.options.windowsVerbatimArguments).toBeUndefined()
|
||||
})
|
||||
|
||||
it('routes a .cmd target through cmd.exe with a verbatim line', () => {
|
||||
const resolved = resolveSpawn({ ...SPEC, env: { ComSpec: 'C:\\W\\cmd.exe' } }, 'win32')
|
||||
expect(resolved.file).toBe('C:\\W\\cmd.exe')
|
||||
expect(resolved.args).toHaveLength(1)
|
||||
expect(resolved.args[0]).toContain('/d /v:off /s /c')
|
||||
expect(resolved.options.windowsVerbatimArguments).toBe(true)
|
||||
expect(resolved.options.windowsHide).toBe(true)
|
||||
})
|
||||
|
||||
it('treats a .cmd path as an ordinary program off Windows', () => {
|
||||
const resolved = resolveSpawn(SPEC, 'linux')
|
||||
expect(resolved.file).toBe(SPEC.program)
|
||||
expect(resolved.args).toEqual(SPEC.args)
|
||||
})
|
||||
|
||||
it('never lets a corpus argument reach cmd as an operator', () => {
|
||||
for (const { name, value } of WINDOWS_ARGUMENT_CORPUS) {
|
||||
const line = resolveSpawn({ program: 'C:\\a.cmd', args: [value] }, 'win32').args[0]!
|
||||
@@ -100,35 +58,6 @@ describe('runProcessSync', () => {
|
||||
captureStdoutAsBytes ? Buffer.concat([Buffer.from(input), Buffer.from([0, 255])]) : undefined
|
||||
)
|
||||
})
|
||||
|
||||
it('reports a timeout as timedOut', () => {
|
||||
const result = runProcessSync({
|
||||
program: process.execPath,
|
||||
args: ['-e', 'setTimeout(() => {}, 5000)'],
|
||||
timeoutMs: 300
|
||||
})
|
||||
expect(result.timedOut).toBe(true)
|
||||
})
|
||||
|
||||
it('does not report a deliberately terminated child as timedOut', () => {
|
||||
const result = runProcessSync({
|
||||
program: process.execPath,
|
||||
args: ['-e', 'process.kill(process.pid, "SIGTERM")'],
|
||||
timeoutMs: 30_000
|
||||
})
|
||||
// Windows reports an exit code for deliberate termination; POSIX reports a signal.
|
||||
expect(result.timedOut).toBe(false)
|
||||
expect(result.code === 0 && result.signal === null).toBe(false)
|
||||
})
|
||||
|
||||
it('captures stdout and the exit code without throwing on failure', () => {
|
||||
const result = runProcessSync({
|
||||
program: process.execPath,
|
||||
args: ['-e', 'process.stdout.write("hi"); process.exit(3)']
|
||||
})
|
||||
expect(result.stdout).toBe('hi')
|
||||
expect(result.code).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('bounded output', () => {
|
||||
@@ -154,20 +83,6 @@ describe('bounded output', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('stderr streaming', () => {
|
||||
it('forwards stderr as it arrives without changing the captured result', async () => {
|
||||
const chunks: string[] = []
|
||||
const result = await runProcess({
|
||||
program: process.execPath,
|
||||
args: ['-e', 'process.stderr.write("x".repeat(64))'],
|
||||
maxOutputBytes: 8,
|
||||
onStderr: (chunk) => chunks.push(chunk.toString())
|
||||
})
|
||||
expect(chunks.join('')).toBe('x'.repeat(64))
|
||||
expect(result.stderr).toBe('xxxxxxxx')
|
||||
})
|
||||
})
|
||||
|
||||
describe('unkillable children', () => {
|
||||
it('settles a timeout after the child reports ready', async () => {
|
||||
const result = await runProcess({
|
||||
@@ -277,18 +192,3 @@ describe('a signal that is already aborted', () => {
|
||||
expect(onChildTerminated).toHaveBeenCalledOnce()
|
||||
}, 20_000)
|
||||
})
|
||||
|
||||
describe('output truncation', () => {
|
||||
const emit = (bytes: number): string =>
|
||||
`for (let i = 0; i < ${bytes}; i += 1) process.stderr.write('n'); process.stderr.write('FAILED')`
|
||||
|
||||
it('keeps the head by default', async () => {
|
||||
const result = await runProcess({
|
||||
program: process.execPath,
|
||||
args: ['-e', emit(200)],
|
||||
maxOutputBytes: 64
|
||||
})
|
||||
expect(result.stderr).not.toContain('FAILED')
|
||||
expect(result.stderr).toBe('n'.repeat(64))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildWindowsCmdShimCommandLine,
|
||||
isCmdInterpretedProgram,
|
||||
parseWindowsCommandLine,
|
||||
quoteWindowsArgument
|
||||
} from './windows-command-line'
|
||||
import { buildWindowsCmdShimCommandLine, quoteWindowsArgument } from './windows-command-line'
|
||||
import { WINDOWS_ARGUMENT_CORPUS } from './__fixtures__/windows-argument-corpus'
|
||||
|
||||
/** cmd tracks quote state by counting `"`; an odd count leaks operators. */
|
||||
@@ -13,19 +8,6 @@ function quoteParity(line: string): number {
|
||||
}
|
||||
|
||||
describe('quoteWindowsArgument', () => {
|
||||
it.each(WINDOWS_ARGUMENT_CORPUS)(
|
||||
'round-trips $name through the command-line parser',
|
||||
({ value }) => {
|
||||
expect(parseWindowsCommandLine(quoteWindowsArgument(value))).toEqual([value])
|
||||
}
|
||||
)
|
||||
|
||||
it('round-trips the whole corpus as a single multi-argument line', () => {
|
||||
const values = WINDOWS_ARGUMENT_CORPUS.map((entry) => entry.value)
|
||||
const line = values.map(quoteWindowsArgument).join(' ')
|
||||
expect(parseWindowsCommandLine(line)).toEqual(values)
|
||||
})
|
||||
|
||||
it('writes an embedded quote as "" so cmd quote parity stays even', () => {
|
||||
expect(quoteWindowsArgument('c"d')).toBe('"c""d"')
|
||||
expect(quoteParity(quoteWindowsArgument('c"d'))).toBe(0)
|
||||
@@ -62,19 +44,6 @@ describe('buildWindowsCmdShimCommandLine', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('isCmdInterpretedProgram', () => {
|
||||
it.each([
|
||||
['C:\\bin\\agent.cmd', true],
|
||||
['C:\\bin\\agent.CMD', true],
|
||||
['C:\\bin\\agent.bat', true],
|
||||
['C:\\bin\\agent.exe', false],
|
||||
['C:\\bin\\agent', false],
|
||||
['C:\\bin\\agent.ps1', false]
|
||||
])('%s -> %s', (program, expected) => {
|
||||
expect(isCmdInterpretedProgram(program)).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('line breaks', () => {
|
||||
it.each([
|
||||
['newline in an argument', 'agent', ['fix\nthis']],
|
||||
|
||||
@@ -1,17 +1,6 @@
|
||||
import { ChildProcess } from 'node:child_process'
|
||||
import type * as Os from 'node:os'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { getPriorityMock, setPriorityMock } = vi.hoisted(() => ({
|
||||
getPriorityMock: vi.fn(),
|
||||
setPriorityMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('node:os', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof Os>()),
|
||||
getPriority: getPriorityMock,
|
||||
setPriority: setPriorityMock
|
||||
}))
|
||||
import {
|
||||
_setWindowsTaskkillLauncherForTests,
|
||||
inFlightWindowsTreeKill,
|
||||
@@ -164,75 +153,4 @@ describe('windows tree kill tracker', () => {
|
||||
|
||||
expect(launch).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
describe('termination helper scheduling', () => {
|
||||
const originalPlatform = process.platform
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
|
||||
getPriorityMock.mockReset().mockReturnValue(10)
|
||||
setPriorityMock.mockReset()
|
||||
launch.mockImplementationOnce(() => {
|
||||
const killer = new FakeProcess()
|
||||
Object.defineProperty(killer, 'pid', { value: 5678 })
|
||||
launched.push(killer)
|
||||
return killer
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(process, 'platform', {
|
||||
configurable: true,
|
||||
value: originalPlatform
|
||||
})
|
||||
})
|
||||
|
||||
it.each([10, 19])('restores normal priority for a background helper at %i', (priority) => {
|
||||
getPriorityMock.mockReturnValue(priority)
|
||||
const killRoot = vi.fn()
|
||||
const kill = startWindowsTreeKill(new FakeProcess(), 1234, killRoot)
|
||||
|
||||
expect(setPriorityMock).toHaveBeenCalledWith(5678, 0)
|
||||
expect(kill.verdict()).toBe('live')
|
||||
expect(killRoot).not.toHaveBeenCalled()
|
||||
launched[0].emit('close', 0)
|
||||
expect(kill.verdict()).toBe('exited')
|
||||
})
|
||||
|
||||
it.each([0, -7, -14])('preserves a helper already at priority %i', (priority) => {
|
||||
getPriorityMock.mockReturnValue(priority)
|
||||
startWindowsTreeKill(new FakeProcess(), 1234, vi.fn())
|
||||
|
||||
expect(setPriorityMock).not.toHaveBeenCalled()
|
||||
launched[0].emit('close', 0)
|
||||
})
|
||||
|
||||
it.each(['read', 'write'])('keeps tracking when the priority %s fails', async (operation) => {
|
||||
const fail = (): never => {
|
||||
throw new Error('priority access denied or helper already exited')
|
||||
}
|
||||
if (operation === 'read') {
|
||||
getPriorityMock.mockImplementation(fail)
|
||||
} else {
|
||||
setPriorityMock.mockImplementation(fail)
|
||||
}
|
||||
const killRoot = vi.fn()
|
||||
const kill = startWindowsTreeKill(new FakeProcess(), 1234, killRoot)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(WINDOWS_TASKKILL_WAIT_MS)
|
||||
expect(kill.verdict()).toBe('live')
|
||||
expect(killRoot).not.toHaveBeenCalled()
|
||||
launched[0].emit('close', 0)
|
||||
await expect(kill.settled).resolves.toBe('exited')
|
||||
})
|
||||
|
||||
it('leaves POSIX scheduling unchanged', () => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' })
|
||||
startWindowsTreeKill(new FakeProcess(), 1234, vi.fn())
|
||||
|
||||
expect(getPriorityMock).not.toHaveBeenCalled()
|
||||
expect(setPriorityMock).not.toHaveBeenCalled()
|
||||
launched[0].emit('close', 0)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import type { notificationsApi } from './notifications-bridge'
|
||||
|
||||
const SOUND_PATH = join(tmpdir(), 'notification.mp3')
|
||||
|
||||
const { invoke, play } = vi.hoisted(() => ({
|
||||
invoke: vi.fn(),
|
||||
play: vi.fn(() => Promise.resolve())
|
||||
}))
|
||||
|
||||
vi.mock('electron', () => ({ ipcRenderer: { invoke } }))
|
||||
|
||||
async function loadNotificationsApi(): Promise<typeof notificationsApi> {
|
||||
vi.resetModules()
|
||||
return (await import('./notifications-bridge')).notificationsApi
|
||||
}
|
||||
|
||||
describe('notificationsApi.playSound', () => {
|
||||
beforeEach(() => {
|
||||
play.mockClear()
|
||||
vi.stubGlobal(
|
||||
'Audio',
|
||||
class extends EventTarget {
|
||||
currentTime = 0
|
||||
volume = 1
|
||||
src = ''
|
||||
pause = vi.fn()
|
||||
play = play
|
||||
}
|
||||
)
|
||||
invoke.mockReset()
|
||||
invoke.mockImplementation((channel: string) => {
|
||||
if (channel === 'notifications:resolveSoundPath') {
|
||||
return Promise.resolve({ ok: true, path: SOUND_PATH })
|
||||
}
|
||||
if (channel === 'notifications:loadSound') {
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
data: new Uint8Array([1]),
|
||||
mimeType: 'audio/mpeg',
|
||||
path: SOUND_PATH
|
||||
})
|
||||
}
|
||||
return Promise.resolve(undefined)
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('retries after a rejected play without leaving future notifications silent', async () => {
|
||||
const notificationsApi = await loadNotificationsApi()
|
||||
play.mockRejectedValueOnce(new Error('audio device unavailable'))
|
||||
await expect(notificationsApi.playSound()).resolves.toEqual({
|
||||
played: false,
|
||||
reason: 'playback-failed'
|
||||
})
|
||||
await expect(notificationsApi.playSound()).resolves.toEqual({
|
||||
played: true
|
||||
})
|
||||
})
|
||||
|
||||
it('skips playback under macOS Focus but keeps the cached sound for previews', async () => {
|
||||
const notificationsApi = await loadNotificationsApi()
|
||||
await expect(notificationsApi.playSound()).resolves.toEqual({
|
||||
played: true
|
||||
})
|
||||
invoke.mockImplementation((channel: string, options?: { force?: boolean }) =>
|
||||
channel === 'notifications:resolveSoundPath'
|
||||
? Promise.resolve(
|
||||
options?.force ? { ok: true, path: SOUND_PATH } : { ok: false, reason: 'focus-active' }
|
||||
)
|
||||
: Promise.reject(new Error(`unexpected ${channel}`))
|
||||
)
|
||||
play.mockClear()
|
||||
await expect(notificationsApi.playSound()).resolves.toEqual({
|
||||
played: false,
|
||||
reason: 'focus-active'
|
||||
})
|
||||
expect(play).not.toHaveBeenCalled()
|
||||
await expect(notificationsApi.playSound({ force: true })).resolves.toEqual({
|
||||
played: true
|
||||
})
|
||||
expect(play).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -1,243 +0,0 @@
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { BROWSER_EXTENSION_API_SURFACE } from './browser-extension-api-surface'
|
||||
import { passesBrowserExtensionEventFilter } from './browser-extension-event-filters'
|
||||
import {
|
||||
installBrowserExtensionApis,
|
||||
type BrowserExtensionInvokeReply
|
||||
} from './browser-extension-main-world'
|
||||
|
||||
type Api = Record<string, unknown>
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object'
|
||||
}
|
||||
|
||||
function isCallable(value: unknown): value is (...args: unknown[]) => unknown {
|
||||
return typeof value === 'function'
|
||||
}
|
||||
|
||||
function member(root: unknown, path: string): unknown {
|
||||
return path
|
||||
.split('.')
|
||||
.reduce<unknown>((value, key) => (isRecord(value) ? value[key] : undefined), root)
|
||||
}
|
||||
|
||||
function call(root: unknown, path: string, ...args: unknown[]): unknown {
|
||||
const fn = member(root, path)
|
||||
if (!isCallable(fn)) {
|
||||
throw new Error(`${path} is not a function`)
|
||||
}
|
||||
return fn.call(member(root, path.split('.').slice(0, -1).join('.')), ...args)
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the installer the way contextBridge.executeInMainWorld does: from its source text, in a
|
||||
* realm that shares nothing with this module.
|
||||
*/
|
||||
class FakeImageData {
|
||||
readonly data: Uint8ClampedArray
|
||||
constructor(
|
||||
readonly width: number,
|
||||
readonly height: number
|
||||
) {
|
||||
this.data = new Uint8ClampedArray(width * height * 4).fill(7)
|
||||
}
|
||||
}
|
||||
|
||||
function installInFreshRealm(
|
||||
permissions: string[],
|
||||
replies: (namespace: string, method: string, args: unknown[]) => BrowserExtensionInvokeReply,
|
||||
manifestKeys: Record<string, unknown> = {}
|
||||
) {
|
||||
let dispatch: ((namespace: string, event: string, args: unknown[]) => void) | null = null
|
||||
const calls: unknown[][] = []
|
||||
const listens: unknown[][] = []
|
||||
const nativeQuery = vi.fn((_info: unknown, callback: (tabs: unknown[]) => void) =>
|
||||
callback([{ id: 5, url: 'https://example.com/', title: 'Example' }])
|
||||
)
|
||||
const nativeOnInstalled = { addListener: vi.fn() }
|
||||
const realm: {
|
||||
chrome: Api
|
||||
browser: Api
|
||||
console: Console
|
||||
URL: typeof URL
|
||||
ImageData: typeof FakeImageData
|
||||
} = {
|
||||
chrome: {
|
||||
runtime: {
|
||||
getManifest: () => ({ permissions, ...manifestKeys }),
|
||||
onInstalled: nativeOnInstalled
|
||||
},
|
||||
tabs: { query: nativeQuery, sendMessage: () => {} }
|
||||
},
|
||||
browser: { runtime: { onInstalled: nativeOnInstalled }, tabs: {} },
|
||||
console,
|
||||
URL,
|
||||
ImageData: FakeImageData
|
||||
}
|
||||
const bridge = {
|
||||
call: async (namespace: string, method: string, args: unknown[]) => {
|
||||
calls.push([namespace, method, args])
|
||||
return replies(namespace, method, args)
|
||||
},
|
||||
listen: (namespace: string, event: string, active: boolean, filters?: unknown[]) =>
|
||||
listens.push(filters ? [namespace, event, active, filters] : [namespace, event, active]),
|
||||
onEvent: (handler: typeof dispatch) => {
|
||||
dispatch = handler
|
||||
},
|
||||
passesFilter: passesBrowserExtensionEventFilter
|
||||
}
|
||||
runInNewContext(`(${installBrowserExtensionApis.toString()})(bridge, surface)`, {
|
||||
...realm,
|
||||
globalThis: realm,
|
||||
bridge,
|
||||
surface: BROWSER_EXTENSION_API_SURFACE
|
||||
})
|
||||
return {
|
||||
chrome: realm.chrome,
|
||||
browser: realm.browser,
|
||||
calls,
|
||||
listens,
|
||||
nativeQuery,
|
||||
nativeOnInstalled,
|
||||
emit: (ns: string, ev: string, args: unknown[]) => dispatch?.(ns, ev, args)
|
||||
}
|
||||
}
|
||||
|
||||
const ok = (value: unknown): BrowserExtensionInvokeReply => ({ ok: true, value })
|
||||
|
||||
describe('installBrowserExtensionApis', () => {
|
||||
it('flattens ImageData so its pixels survive the bridge', async () => {
|
||||
const { chrome, calls } = installInFreshRealm([], () => ok(undefined), { action: {} })
|
||||
await call(chrome, 'action.setIcon', { imageData: { 16: new FakeImageData(1, 1) }, tabId: 3 })
|
||||
expect(calls.at(-1)).toEqual([
|
||||
'action',
|
||||
'setIcon',
|
||||
[{ imageData: { 16: { width: 1, height: 1, data: [7, 7, 7, 7] } }, tabId: 3 }]
|
||||
])
|
||||
})
|
||||
|
||||
it('drops trailing undefined arguments, as Chrome does, before finding the callback', async () => {
|
||||
const { chrome, calls } = installInFreshRealm([], () => ok(undefined), { action: {} })
|
||||
await call(chrome, 'action.setIcon', { path: 'icon.png' }, undefined)
|
||||
const called = await new Promise((resolve) =>
|
||||
call(chrome, 'action.setTitle', { title: 'T' }, () => resolve(true), undefined)
|
||||
)
|
||||
expect(called).toBe(true)
|
||||
expect(calls).toEqual([
|
||||
['action', 'setIcon', [{ path: 'icon.png' }]],
|
||||
['action', 'setTitle', [{ title: 'T' }]]
|
||||
])
|
||||
})
|
||||
|
||||
it('answers promise and callback calls, and sets lastError only during a failed callback', async () => {
|
||||
const { chrome } = installInFreshRealm([], (_ns, method) =>
|
||||
method === 'get' ? { ok: false, error: 'No window with id: 9.' } : ok({ id: 1 })
|
||||
)
|
||||
await expect(call(chrome, 'windows.getCurrent')).resolves.toEqual({ id: 1 })
|
||||
|
||||
const fromCallback = await new Promise((resolve) => call(chrome, 'windows.getCurrent', resolve))
|
||||
expect(fromCallback).toEqual({ id: 1 })
|
||||
|
||||
const lastError = await new Promise((resolve) =>
|
||||
call(chrome, 'windows.get', 9, () => resolve(member(chrome, 'runtime.lastError.message')))
|
||||
)
|
||||
expect(lastError).toBe('No window with id: 9.')
|
||||
expect(member(chrome, 'runtime.lastError')).toBeUndefined()
|
||||
await expect(call(chrome, 'windows.get', 9)).rejects.toThrow('No window with id: 9.')
|
||||
})
|
||||
|
||||
it('runs the native query without Orca-owned keys and sends its result to main', async () => {
|
||||
const { chrome, calls, nativeQuery } = installInFreshRealm([], () => ok([]))
|
||||
await call(chrome, 'tabs.query', { active: true, currentWindow: true, url: 'https://*/*' })
|
||||
expect(nativeQuery.mock.calls[0][0]).toEqual({ url: 'https://*/*' })
|
||||
expect(calls.at(-1)).toEqual([
|
||||
'tabs',
|
||||
'query',
|
||||
[
|
||||
{ active: true, currentWindow: true, url: 'https://*/*' },
|
||||
[{ id: 5, url: 'https://example.com/', title: 'Example' }]
|
||||
]
|
||||
])
|
||||
})
|
||||
|
||||
it('tells main when the first listener arrives and the last leaves, and applies url filters', () => {
|
||||
const { chrome, listens, emit } = installInFreshRealm(['webNavigation'], () => ok(null))
|
||||
const all = vi.fn()
|
||||
const filtered = vi.fn()
|
||||
const onCommitted = 'webNavigation.onCommitted'
|
||||
call(chrome, `${onCommitted}.addListener`, all)
|
||||
call(chrome, `${onCommitted}.addListener`, filtered, { url: [{ hostSuffix: 'example.com' }] })
|
||||
emit('webNavigation', 'onCommitted', [{ url: 'https://other.test/' }])
|
||||
emit('webNavigation', 'onCommitted', [{ url: 'https://app.example.com/' }])
|
||||
call(chrome, `${onCommitted}.removeListener`, all)
|
||||
call(chrome, `${onCommitted}.removeListener`, filtered)
|
||||
|
||||
expect(all).toHaveBeenCalledTimes(2)
|
||||
expect(filtered).toHaveBeenCalledTimes(1)
|
||||
expect(listens).toEqual([
|
||||
['webNavigation', 'onCommitted', true],
|
||||
['webNavigation', 'onCommitted', false]
|
||||
])
|
||||
})
|
||||
|
||||
it('replaces the native runtime.onInstalled on chrome and browser so only Orca fires it', () => {
|
||||
const { chrome, browser, listens, emit, nativeOnInstalled } = installInFreshRealm([], () =>
|
||||
ok(null)
|
||||
)
|
||||
const onInstalled = vi.fn()
|
||||
call(chrome, 'runtime.onInstalled.addListener', onInstalled)
|
||||
emit('runtime', 'onInstalled', [{ reason: 'install' }])
|
||||
|
||||
expect(member(browser, 'runtime.onInstalled')).toBe(member(chrome, 'runtime.onInstalled'))
|
||||
expect(typeof member(chrome, 'runtime.onStartup.addListener')).toBe('function')
|
||||
expect(nativeOnInstalled.addListener).not.toHaveBeenCalled()
|
||||
expect(onInstalled).toHaveBeenCalledWith({ reason: 'install' })
|
||||
expect(listens).toEqual([['runtime', 'onInstalled', true]])
|
||||
})
|
||||
})
|
||||
|
||||
describe('Wave 2 API shapes', () => {
|
||||
it('returns a contextMenus.create id synchronously and sends it to main', async () => {
|
||||
const { chrome, calls } = installInFreshRealm(['contextMenus'], () => ok('fill'))
|
||||
expect(
|
||||
call(chrome, 'contextMenus.create', { id: 'fill', title: 'Fill', onclick: () => {} })
|
||||
).toBe('fill')
|
||||
const generated = call(chrome, 'contextMenus.create', { title: 'No id' }, () => {})
|
||||
expect(typeof generated).toBe('number')
|
||||
await Promise.resolve()
|
||||
expect(calls).toEqual([
|
||||
['contextMenus', 'create', [{ id: 'fill', title: 'Fill' }]],
|
||||
['contextMenus', 'create', [{ id: generated, title: 'No id' }]]
|
||||
])
|
||||
})
|
||||
|
||||
it('sends webRequest listener filters to main and filters each listener on delivery', () => {
|
||||
const { chrome, listens, emit } = installInFreshRealm(['webRequest'], () => ok(undefined))
|
||||
const pages: unknown[] = []
|
||||
const images: unknown[] = []
|
||||
const pageFilter = { urls: ['https://*.bank.test/*'], types: ['main_frame'] }
|
||||
call(
|
||||
chrome,
|
||||
'webRequest.onCompleted.addListener',
|
||||
(details: unknown) => pages.push(details),
|
||||
pageFilter
|
||||
)
|
||||
call(chrome, 'webRequest.onCompleted.addListener', (details: unknown) => images.push(details), {
|
||||
urls: ['<all_urls>'],
|
||||
types: ['image']
|
||||
})
|
||||
expect(listens.at(-1)).toEqual([
|
||||
'webRequest',
|
||||
'onCompleted',
|
||||
true,
|
||||
[pageFilter, { urls: ['<all_urls>'], types: ['image'] }]
|
||||
])
|
||||
emit('webRequest', 'onCompleted', [{ url: 'https://www.bank.test/login', type: 'main_frame' }])
|
||||
emit('webRequest', 'onCompleted', [{ url: 'https://www.bank.test/logo.png', type: 'image' }])
|
||||
emit('webRequest', 'onCompleted', [{ url: 'https://evil.test/', type: 'main_frame' }])
|
||||
expect(pages).toEqual([{ url: 'https://www.bank.test/login', type: 'main_frame' }])
|
||||
expect(images).toEqual([{ url: 'https://www.bank.test/logo.png', type: 'image' }])
|
||||
})
|
||||
})
|
||||
@@ -3,17 +3,9 @@ import { webcrypto } from 'node:crypto'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
installBrowserExtensionDocumentTargets,
|
||||
PRELOAD_DOCUMENT_TARGETS_NAMESPACE,
|
||||
PRELOAD_FIRST_DISCARDED_TAB_ID
|
||||
} from './browser-extension-document-targets'
|
||||
|
||||
const DISCARDED_TAB = PRELOAD_FIRST_DISCARDED_TAB_ID + 3
|
||||
|
||||
const ORCA_TOP = 'A'.repeat(32)
|
||||
const ORCA_AD = 'B'.repeat(32)
|
||||
const CHROMIUM_TOP = 'C'.repeat(32)
|
||||
const CHROMIUM_AD = 'D'.repeat(32)
|
||||
|
||||
type NativeListener = (message: unknown, sender: unknown, respond: (value: unknown) => void) => void
|
||||
|
||||
function navigatingDocumentTarget(navigateOnLookup = 1) {
|
||||
@@ -96,128 +88,6 @@ function navigatingDocumentTarget(navigateOnLookup = 1) {
|
||||
return { chrome, delivered, listeners }
|
||||
}
|
||||
|
||||
/** Runs the installer from its source text, as contextBridge.executeInMainWorld does. */
|
||||
function install(permissions: string[], nativeScripting = true) {
|
||||
const nativeListeners = new Set<NativeListener>()
|
||||
const executeScript = vi.fn(
|
||||
async (injection: { target: Record<string, unknown>; func?: () => unknown }) => {
|
||||
const frameIds = Array.isArray(injection.target.frameIds)
|
||||
? injection.target.frameIds
|
||||
: Array.isArray(injection.target.documentIds)
|
||||
? injection.target.documentIds.map((id) => (id === CHROMIUM_AD ? 42 : 0))
|
||||
: [0]
|
||||
return frameIds.map((frameId: number) => ({
|
||||
frameId,
|
||||
documentId: frameId === 42 ? CHROMIUM_AD : CHROMIUM_TOP,
|
||||
result: frameId
|
||||
}))
|
||||
}
|
||||
)
|
||||
const insertCSS = vi.fn((_injection: unknown, callback?: () => void) => {
|
||||
callback?.()
|
||||
return callback ? undefined : Promise.resolve()
|
||||
})
|
||||
const sendMessage = vi.fn(
|
||||
async (
|
||||
tabId: number,
|
||||
message: unknown,
|
||||
options?: { frameId?: number; documentId?: string },
|
||||
_callback?: () => void
|
||||
): Promise<string | boolean> => {
|
||||
if (message && typeof message === 'object' && 'orcaDocumentTargetProbe' in message) {
|
||||
const frameId = options?.frameId ?? 0
|
||||
const probe = message.orcaDocumentTargetProbe
|
||||
for (const listener of nativeListeners) {
|
||||
listener(
|
||||
{
|
||||
orcaDocumentTargetProbe: {
|
||||
...(typeof probe === 'object' ? probe : {}),
|
||||
response: true
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'extension',
|
||||
tab: { id: tabId },
|
||||
frameId,
|
||||
documentId: frameId === 42 ? CHROMIUM_AD : CHROMIUM_TOP
|
||||
},
|
||||
() => {}
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
return 'pong'
|
||||
}
|
||||
)
|
||||
const scripting = { executeScript, insertCSS, removeCSS: vi.fn(async () => {}) }
|
||||
const tabs = { sendMessage }
|
||||
const calls: unknown[][] = []
|
||||
const bridge = {
|
||||
call: async (namespace: string, method: string, args: unknown[]) => {
|
||||
// Main's tabs.get: a discarded tab, or (once replaced by its loaded guest) no tab.
|
||||
if (namespace === 'tabs' && method === 'get') {
|
||||
return args[0] === DISCARDED_TAB
|
||||
? { ok: true as const, value: { id: DISCARDED_TAB, discarded: true } }
|
||||
: { ok: false as const, error: `No tab with id: ${String(args[0])}.` }
|
||||
}
|
||||
expect([namespace, method]).toEqual([PRELOAD_DOCUMENT_TARGETS_NAMESPACE, 'frames'])
|
||||
calls.push(args)
|
||||
return {
|
||||
ok: true as const,
|
||||
value: [
|
||||
{ frameId: 0, documentId: ORCA_TOP },
|
||||
{ frameId: 42, documentId: ORCA_AD }
|
||||
]
|
||||
}
|
||||
},
|
||||
listen: () => {},
|
||||
onEvent: () => {},
|
||||
passesFilter: () => true
|
||||
}
|
||||
const runtime: {
|
||||
id: string
|
||||
getManifest: () => unknown
|
||||
lastError?: unknown
|
||||
onMessage: {
|
||||
addListener: (listener: NativeListener) => void
|
||||
removeListener: (listener: NativeListener) => void
|
||||
}
|
||||
} = {
|
||||
id: 'extension',
|
||||
getManifest: () => ({ permissions }),
|
||||
onMessage: {
|
||||
addListener: (listener) => {
|
||||
nativeListeners.add(listener)
|
||||
},
|
||||
removeListener: (listener) => {
|
||||
nativeListeners.delete(listener)
|
||||
}
|
||||
}
|
||||
}
|
||||
const chrome = { runtime, scripting, tabs }
|
||||
// `browser` shares chrome's namespace objects, as Orca's installer mirrors them.
|
||||
const realm = {
|
||||
chrome: nativeScripting ? chrome : { runtime, tabs },
|
||||
browser: nativeScripting ? { scripting, tabs } : { tabs },
|
||||
crypto: webcrypto,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
Promise,
|
||||
Map,
|
||||
Set,
|
||||
Object,
|
||||
Array
|
||||
}
|
||||
runInNewContext(`(${installBrowserExtensionDocumentTargets.toString()})(bridge, first)`, {
|
||||
...realm,
|
||||
globalThis: realm,
|
||||
bridge,
|
||||
first: PRELOAD_FIRST_DISCARDED_TAB_ID,
|
||||
Error
|
||||
})
|
||||
return { chrome, executeScript, insertCSS, sendMessage, calls, nativeListeners }
|
||||
}
|
||||
|
||||
describe('Orca documentIds in native scripting targets', () => {
|
||||
it.each([1, 2])(
|
||||
'rejects script navigation at discovery snapshot %i before executing user code',
|
||||
@@ -252,24 +122,3 @@ describe('Orca documentIds in native scripting targets', () => {
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
describe('calls to a discarded tab', () => {
|
||||
it("fail with Chrome's errors instead of reaching Electron", async () => {
|
||||
const { chrome, executeScript, sendMessage } = install(['scripting'])
|
||||
await expect(
|
||||
chrome.scripting.executeScript({ target: { tabId: DISCARDED_TAB }, func: () => 1 })
|
||||
).rejects.toThrow('Cannot access contents of url ""')
|
||||
await expect(chrome.tabs.sendMessage(DISCARDED_TAB, 'ping')).rejects.toThrow(
|
||||
'Could not establish connection. Receiving end does not exist.'
|
||||
)
|
||||
const lastError = await new Promise((resolve) =>
|
||||
chrome.scripting.insertCSS({ target: { tabId: DISCARDED_TAB }, css: 'a{}' }, () =>
|
||||
resolve(chrome.runtime.lastError)
|
||||
)
|
||||
)
|
||||
expect(lastError).toEqual({ message: expect.stringContaining('Cannot access contents') })
|
||||
expect(chrome.runtime.lastError).toBeUndefined()
|
||||
expect(executeScript).not.toHaveBeenCalled()
|
||||
expect(sendMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -200,13 +200,4 @@ describe('installBrowserExtensionStorageRelay in a worker', () => {
|
||||
'Error in invocation of storage.set'
|
||||
)
|
||||
})
|
||||
|
||||
it('replaces native onChanged and delivers changes main relays from extension pages', async () => {
|
||||
const worker = install('worker')
|
||||
expect(worker.chrome.storage.onChanged).not.toEqual({ native: true })
|
||||
worker.listen()
|
||||
worker.emit([{ token: { newValue: 'abc' } }, 'session'])
|
||||
expect(worker.all).toEqual([['session', { token: { newValue: 'abc' } }]])
|
||||
expect(worker.perArea).toEqual([['session', { token: { newValue: 'abc' } }]])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { BrowserExtensionInvokeReply } from '../api/browser-extension-main-world'
|
||||
import {
|
||||
installBrowserExtensionStorageSync,
|
||||
PRELOAD_STORAGE_SYNC_CONSTANTS,
|
||||
PRELOAD_STORAGE_SYNC_NAMESPACE
|
||||
} from './browser-extension-storage-sync'
|
||||
|
||||
type Runtime = { lastError?: { message: string } }
|
||||
|
||||
function nativeEvent() {
|
||||
const listeners = new Set<unknown>()
|
||||
return {
|
||||
listeners,
|
||||
addListener: vi.fn((callback: unknown) => listeners.add(callback)),
|
||||
removeListener: vi.fn((callback: unknown) => listeners.delete(callback))
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the installer from its source text, as contextBridge.executeInMainWorld does. */
|
||||
function install(
|
||||
reply: (method: string, args: unknown[]) => BrowserExtensionInvokeReply,
|
||||
forward?: (changes: unknown, from?: string) => void
|
||||
) {
|
||||
const runtime: Runtime = {}
|
||||
const native = nativeEvent()
|
||||
const nativeSync = { get: vi.fn(), set: vi.fn() }
|
||||
const chrome = { runtime, storage: { local: {}, sync: nativeSync, onChanged: native } }
|
||||
let dispatch: ((namespace: string, event: string, args: unknown[]) => void) | null = null
|
||||
const calls: unknown[][] = []
|
||||
const listens: unknown[][] = []
|
||||
const bridge = {
|
||||
call: async (namespace: string, method: string, args: unknown[]) => {
|
||||
calls.push([namespace, method, args])
|
||||
return reply(method, args)
|
||||
},
|
||||
listen: (namespace: string, event: string, active: boolean) =>
|
||||
listens.push([namespace, event, active]),
|
||||
onEvent: (handler: typeof dispatch) => {
|
||||
dispatch = handler
|
||||
},
|
||||
passesFilter: () => true
|
||||
}
|
||||
const realm = { chrome, console, JSON, Promise }
|
||||
const relay: unknown = runInNewContext(
|
||||
`(${installBrowserExtensionStorageSync.toString()})(bridge, constants, forward)`,
|
||||
{
|
||||
...realm,
|
||||
globalThis: realm,
|
||||
bridge,
|
||||
constants: PRELOAD_STORAGE_SYNC_CONSTANTS,
|
||||
forward
|
||||
}
|
||||
)
|
||||
return {
|
||||
relay: (method: string, args: unknown[], from?: string): unknown =>
|
||||
typeof relay === 'function' ? relay(method, args, from) : undefined,
|
||||
chrome,
|
||||
native,
|
||||
nativeSync,
|
||||
calls,
|
||||
listens,
|
||||
emit: (changes: unknown) => dispatch?.(PRELOAD_STORAGE_SYNC_NAMESPACE, 'onChanged', [changes])
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object'
|
||||
}
|
||||
|
||||
function call(root: unknown, path: string, ...args: unknown[]): unknown {
|
||||
const keys = path.split('.')
|
||||
const name = keys.pop() ?? ''
|
||||
const owner = keys.reduce<unknown>(
|
||||
(value, key) => (isRecord(value) ? value[key] : undefined),
|
||||
root
|
||||
)
|
||||
const fn = isRecord(owner) ? owner[name] : null
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`${path} is not a function`)
|
||||
}
|
||||
return fn.call(owner, ...args)
|
||||
}
|
||||
|
||||
describe('installBrowserExtensionStorageSync', () => {
|
||||
it('sets lastError only inside a failed callback and rejects a failed promise', async () => {
|
||||
const page = install(() => ({ ok: false, error: 'QUOTA_BYTES quota exceeded' }))
|
||||
const lastError = await new Promise((resolve) =>
|
||||
call(page.chrome, 'storage.sync.set', { big: 1 }, () =>
|
||||
resolve(page.chrome.runtime.lastError?.message)
|
||||
)
|
||||
)
|
||||
expect(lastError).toBe('QUOTA_BYTES quota exceeded')
|
||||
expect(page.chrome.runtime.lastError).toBeUndefined()
|
||||
await expect(call(page.chrome, 'storage.sync.set', { big: 1 })).rejects.toThrow(
|
||||
'QUOTA_BYTES quota exceeded'
|
||||
)
|
||||
})
|
||||
})
|
||||
-130
@@ -1,130 +0,0 @@
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
installChromeWebStoreApis,
|
||||
type ChromeWebStoreBridgeReply
|
||||
} from './browser-extension-web-store-main-world'
|
||||
|
||||
type Callable = (...args: unknown[]) => unknown
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object'
|
||||
}
|
||||
|
||||
function member(root: unknown, path: string): unknown {
|
||||
return path
|
||||
.split('.')
|
||||
.reduce<unknown>((value, key) => (isRecord(value) ? value[key] : undefined), root)
|
||||
}
|
||||
|
||||
function isCallable(value: unknown): value is Callable {
|
||||
return typeof value === 'function'
|
||||
}
|
||||
|
||||
function fn(root: unknown, path: string): Callable {
|
||||
const value = member(root, path)
|
||||
if (!isCallable(value)) {
|
||||
throw new Error(`${path} is not a function`)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/** Runs the installer from its source text in a fresh realm, as executeInMainWorld does. */
|
||||
function installInFreshRealm(
|
||||
reply: (method: string, args: unknown[]) => ChromeWebStoreBridgeReply,
|
||||
realmChrome?: Record<string, unknown>
|
||||
) {
|
||||
let dispatch: ((event: string, args: unknown[]) => void) | null = null
|
||||
const calls: [string, unknown[]][] = []
|
||||
const realm: Record<string, unknown> = { console }
|
||||
if (realmChrome) {
|
||||
realm.chrome = realmChrome
|
||||
}
|
||||
const bridge = {
|
||||
call: async (method: string, args: unknown[]) => {
|
||||
calls.push([method, args])
|
||||
return reply(method, args)
|
||||
},
|
||||
onEvent: (handler: typeof dispatch) => {
|
||||
dispatch = handler
|
||||
}
|
||||
}
|
||||
runInNewContext(`(${installChromeWebStoreApis.toString()})(bridge, '146.0.7680.0')`, {
|
||||
...realm,
|
||||
globalThis: realm,
|
||||
bridge
|
||||
})
|
||||
return { realm, calls, emit: (event: string, args: unknown[]) => dispatch?.(event, args) }
|
||||
}
|
||||
|
||||
function lastErrors(realm: unknown): [unknown, unknown] {
|
||||
return [member(realm, 'chrome.runtime.lastError'), member(realm, 'chrome.extension.lastError')]
|
||||
}
|
||||
|
||||
describe('installChromeWebStoreApis', () => {
|
||||
it('sets lastError on runtime and extension only while the callback runs', async () => {
|
||||
const { realm, calls } = installInFreshRealm(() => ({
|
||||
value: 'user_cancelled',
|
||||
error: 'User cancelled install'
|
||||
}))
|
||||
const seen: unknown[] = []
|
||||
fn(realm, 'chrome.webstorePrivate.beginInstallWithManifest3')(
|
||||
{ id: 'x' },
|
||||
(result: unknown) => {
|
||||
seen.push(result, ...lastErrors(realm))
|
||||
}
|
||||
)
|
||||
await vi.waitFor(() => expect(seen).toHaveLength(3))
|
||||
|
||||
expect(calls).toEqual([['beginInstallWithManifest3', [{ id: 'x' }]]])
|
||||
expect(seen).toEqual([
|
||||
'user_cancelled',
|
||||
{ message: 'User cancelled install' },
|
||||
{ message: 'User cancelled install' }
|
||||
])
|
||||
expect(lastErrors(realm)).toEqual([undefined, undefined])
|
||||
})
|
||||
|
||||
it('calls back with no arguments and no lastError on success', async () => {
|
||||
const { realm } = installInFreshRealm(() => ({}))
|
||||
const callback = vi.fn((...args: unknown[]) => args.concat(lastErrors(realm)))
|
||||
fn(realm, 'chrome.webstorePrivate.completeInstall')('id', callback)
|
||||
await vi.waitFor(() => expect(callback).toHaveBeenCalled())
|
||||
expect(callback.mock.results[0].value).toEqual([undefined, undefined])
|
||||
})
|
||||
|
||||
it('strips the callback, keeps optional arguments, and supports promises', async () => {
|
||||
const { realm, calls } = installInFreshRealm((method) =>
|
||||
method === 'management.getAll' ? { value: [{ id: 'a' }] } : { value: 'installable' }
|
||||
)
|
||||
const status = vi.fn()
|
||||
fn(realm, 'chrome.webstorePrivate.getExtensionStatus')('id', status)
|
||||
await expect(fn(realm, 'chrome.management.getAll')()).resolves.toEqual([{ id: 'a' }])
|
||||
await vi.waitFor(() => expect(status).toHaveBeenCalledWith('installable'))
|
||||
expect(calls).toEqual([
|
||||
['getExtensionStatus', ['id']],
|
||||
['management.getAll', []]
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects the promise form with the error', async () => {
|
||||
const { realm } = installInFreshRealm(() => ({
|
||||
error: 'Extension x uninstall canceled by user.'
|
||||
}))
|
||||
await expect(
|
||||
fn(realm, 'chrome.management.uninstall')('x', { showConfirmDialog: true })
|
||||
).rejects.toThrow('uninstall canceled by user')
|
||||
})
|
||||
|
||||
it('delivers management events to registered listeners', () => {
|
||||
const { realm, emit } = installInFreshRealm(() => ({}))
|
||||
const listener = vi.fn()
|
||||
fn(realm, 'chrome.management.onInstalled.addListener')(listener)
|
||||
emit('onInstalled', [{ id: 'a' }])
|
||||
emit('onUninstalled', ['a'])
|
||||
fn(realm, 'chrome.management.onInstalled.removeListener')(listener)
|
||||
emit('onInstalled', [{ id: 'b' }])
|
||||
expect(listener.mock.calls).toEqual([[{ id: 'a' }]])
|
||||
})
|
||||
})
|
||||
@@ -288,22 +288,6 @@ describe('browser password detector', () => {
|
||||
expect(sentOn(CHANNEL.submitted)).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps viewport invalidation alive after a picker focus transfer', async () => {
|
||||
load(LOGIN_FORM)
|
||||
install()
|
||||
enable()
|
||||
focusIn(el('#pw'))
|
||||
const fieldToken = readString(sentOn(CHANNEL.fieldFocused).at(-1), 'fieldToken')
|
||||
el('#pw').dispatchEvent(new FocusEvent('focusout', { bubbles: true, composed: true }))
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
expect(sentOn(CHANNEL.fieldFocused)).toHaveLength(1)
|
||||
expect(sentOn(CHANNEL.fieldBlurred)).toEqual([
|
||||
{ fieldToken, reason: 'focusout' },
|
||||
{ fieldToken }
|
||||
])
|
||||
})
|
||||
|
||||
it('detects and captures credentials when HTTP crypto has no randomUUID', async () => {
|
||||
vi.stubGlobal('crypto', { getRandomValues: crypto.getRandomValues.bind(crypto) })
|
||||
load(LOGIN_FORM)
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { PreloadApi } from '../../api-types'
|
||||
|
||||
const { exposeInMainWorld, invoke, on, removeListener, send, sendSync, getPathForFile } =
|
||||
vi.hoisted(() => ({
|
||||
exposeInMainWorld: vi.fn(),
|
||||
invoke: vi.fn(),
|
||||
on: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
send: vi.fn(),
|
||||
sendSync: vi.fn(),
|
||||
getPathForFile: vi.fn(() => '/files/notes.txt')
|
||||
}))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
contextBridge: { exposeInMainWorld },
|
||||
ipcRenderer: { invoke, on, removeListener, send, sendSync },
|
||||
webFrame: {
|
||||
getZoomFactor: vi.fn(() => 1),
|
||||
setZoomFactor: vi.fn(),
|
||||
setVisualZoomLevelLimits: vi.fn()
|
||||
},
|
||||
webUtils: { getPathForFile }
|
||||
}))
|
||||
|
||||
describe('native preload destructive app actions', () => {
|
||||
const originalContextIsolated = Object.getOwnPropertyDescriptor(process, 'contextIsolated')
|
||||
let eventTarget: EventTarget
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
exposeInMainWorld.mockReset()
|
||||
invoke.mockReset()
|
||||
on.mockReset()
|
||||
removeListener.mockReset()
|
||||
send.mockReset()
|
||||
sendSync.mockReset()
|
||||
Object.defineProperty(process, 'contextIsolated', { configurable: true, value: true })
|
||||
eventTarget = new EventTarget()
|
||||
vi.stubGlobal('window', eventTarget)
|
||||
vi.stubGlobal('document', { addEventListener: vi.fn() })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
if (originalContextIsolated) {
|
||||
Object.defineProperty(process, 'contextIsolated', originalContextIsolated)
|
||||
} else {
|
||||
Reflect.deleteProperty(process, 'contextIsolated')
|
||||
}
|
||||
})
|
||||
|
||||
const loadApi = async (): Promise<PreloadApi> => {
|
||||
await import('../../index')
|
||||
return exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi
|
||||
}
|
||||
|
||||
it('exposes the durable checkpoint join the lazy-chunk recovery reload depends on', async () => {
|
||||
const api = await loadApi()
|
||||
invoke.mockResolvedValue({ ok: true })
|
||||
|
||||
await expect(api.app.awaitBeforeUnloadCheckpoint()).resolves.toBeUndefined()
|
||||
expect(invoke).toHaveBeenCalledWith('app:await-before-unload-checkpoint')
|
||||
|
||||
invoke.mockResolvedValue({ ok: false })
|
||||
|
||||
await expect(api.app.awaitBeforeUnloadCheckpoint()).rejects.toThrow(
|
||||
'Failed to persist renderer state before unload.'
|
||||
)
|
||||
})
|
||||
})
|
||||
-20
@@ -216,26 +216,6 @@ describe('Markdown document navigation', () => {
|
||||
}
|
||||
)
|
||||
|
||||
it.each(['superseded', 'unmounted'])('ignores a %s listing failure', async (reason) => {
|
||||
let rejectListing: (error: unknown) => void = () => {}
|
||||
runtime.list.mockReturnValueOnce(
|
||||
new Promise((_resolve, reject) => {
|
||||
rejectListing = reject
|
||||
})
|
||||
)
|
||||
await render(sourceFile('edit'), 'source')
|
||||
await (reason === 'superseded'
|
||||
? render(sourceFile('edit', 'next-owner'), 'source')
|
||||
: act(async () => root.render(null)))
|
||||
await act(async () => rejectListing(null))
|
||||
|
||||
expect(runtime.toastError).not.toHaveBeenCalled()
|
||||
expect(runtime.translate).not.toHaveBeenCalled()
|
||||
if (reason === 'superseded') {
|
||||
expect(controller.markdownDocuments).toEqual([target])
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['directory', 'missing'])('does not navigate to a %s destination', async (kind) => {
|
||||
await render(sourceFile('markdown-preview'), 'source')
|
||||
if (kind === 'directory') {
|
||||
|
||||
+1
-111
@@ -3,17 +3,12 @@ import { describe, expect, it } from 'vitest'
|
||||
import { createTestStore } from '@/store/testing/app-store-test-fixture'
|
||||
import type { AiVaultSession } from '../../../../../../shared/ai-vault/contracts/ai-vault-types'
|
||||
import type { AgentStatusEntry } from '../../../../../../shared/agent-status/contracts/agent-status-types'
|
||||
import type { SleepingAgentSessionRecord } from '../../../../../../shared/agent-session/lifecycle/agent-session-resume'
|
||||
import {
|
||||
buildAiVaultOriginalPaneIndex,
|
||||
findOriginalAiVaultSessionPaneInIndex
|
||||
} from './ai-vault-original-pane-index'
|
||||
import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id'
|
||||
import {
|
||||
type OriginalPaneState,
|
||||
findAiVaultSessionLiveState,
|
||||
findOriginalAiVaultSessionPane
|
||||
} from './ai-vault-original-pane'
|
||||
import { type OriginalPaneState, findOriginalAiVaultSessionPane } from './ai-vault-original-pane'
|
||||
|
||||
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const OTHER_LEAF_ID = '22222222-2222-4222-8222-222222222222'
|
||||
@@ -91,24 +86,6 @@ function makeEntry(overrides: Partial<AgentStatusEntry> = {}): AgentStatusEntry
|
||||
}
|
||||
}
|
||||
|
||||
function makeSleepingRecord(
|
||||
overrides: Partial<SleepingAgentSessionRecord> = {}
|
||||
): SleepingAgentSessionRecord {
|
||||
return {
|
||||
paneKey: makePaneKey('tab-1', LEAF_ID),
|
||||
tabId: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
agent: 'codex',
|
||||
providerSession: { key: 'session_id', id: 'session-1' },
|
||||
prompt: 'continue',
|
||||
state: 'working',
|
||||
capturedAt: 1,
|
||||
updatedAt: 1,
|
||||
origin: 'live',
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('findOriginalAiVaultSessionPane', () => {
|
||||
it('does not return a target when the original leaf is gone', () => {
|
||||
const entry = makeEntry()
|
||||
@@ -123,95 +100,8 @@ describe('findOriginalAiVaultSessionPane', () => {
|
||||
|
||||
expect(target).toBeNull()
|
||||
})
|
||||
|
||||
it('resolves legacy numeric pane keys through the current tab layout', () => {
|
||||
const record = makeSleepingRecord({ paneKey: 'tab-1:1' })
|
||||
|
||||
const target = findOriginalAiVaultSessionPane(
|
||||
makeState({ sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } }),
|
||||
baseSession
|
||||
)
|
||||
|
||||
expect(target?.leafId).toBe(LEAF_ID)
|
||||
})
|
||||
})
|
||||
|
||||
describe('findAiVaultSessionLiveState', () => {
|
||||
it('falls back to a prompt match only when it is unambiguous', () => {
|
||||
const matching = makeEntry({
|
||||
providerSession: undefined,
|
||||
prompt: baseSession.title,
|
||||
state: 'working'
|
||||
})
|
||||
expect(
|
||||
findAiVaultSessionLiveState(
|
||||
makeState({
|
||||
agentStatusByPaneKey: acceptedAgentStatuses(
|
||||
Object.entries({ [matching.paneKey]: matching })
|
||||
)
|
||||
}),
|
||||
baseSession
|
||||
)
|
||||
).toBe('working')
|
||||
|
||||
const otherPaneKey = makePaneKey('tab-1', OTHER_LEAF_ID)
|
||||
const ambiguous = makeState({
|
||||
agentStatusByPaneKey: acceptedAgentStatuses(
|
||||
Object.entries({
|
||||
[matching.paneKey]: matching,
|
||||
[otherPaneKey]: makeEntry({
|
||||
providerSession: undefined,
|
||||
prompt: baseSession.title,
|
||||
paneKey: otherPaneKey,
|
||||
state: 'waiting'
|
||||
})
|
||||
})
|
||||
)
|
||||
})
|
||||
expect(findAiVaultSessionLiveState(ambiguous, baseSession)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when no live pane matches the session', () => {
|
||||
const state = makeState({
|
||||
agentStatusByPaneKey: acceptedAgentStatuses(
|
||||
Object.entries({
|
||||
[makeEntry().paneKey]: makeEntry({
|
||||
providerSession: { key: 'session_id', id: 'other-session' }
|
||||
})
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
expect(findAiVaultSessionLiveState(state, baseSession)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
it.each([true, false])(
|
||||
'finds the original pane after live removal (provider known: %s)',
|
||||
(known) => {
|
||||
const paneKey = makePaneKey('tab-1', LEAF_ID)
|
||||
const state = makeState({
|
||||
agentConversationsByPaneKey: {
|
||||
[paneKey]: {
|
||||
paneKey,
|
||||
worktreeId: 'wt-1',
|
||||
executionHostId: 'local',
|
||||
connectionId: null,
|
||||
agent: 'codex',
|
||||
...(known
|
||||
? { providerSession: { key: 'session_id', id: 'session-1' } }
|
||||
: { promptCandidates: ['fix the pane focus'] })
|
||||
}
|
||||
}
|
||||
})
|
||||
expect(findOriginalAiVaultSessionPane(state, baseSession)?.paneKey).toBe(paneKey)
|
||||
expect(
|
||||
findOriginalAiVaultSessionPaneInIndex(buildAiVaultOriginalPaneIndex(state), baseSession)
|
||||
?.paneKey
|
||||
).toBe(paneKey)
|
||||
}
|
||||
)
|
||||
|
||||
it.each([true, false])(
|
||||
'forgets the preceding original-pane target after an unidentified successor (provider known: %s)',
|
||||
(known) => {
|
||||
|
||||
+1
-109
@@ -8,9 +8,7 @@ import type { Repo } from '../../../../../../shared/repository/repo-types'
|
||||
import {
|
||||
getRootProjectHeaderCountByOccurrenceKey,
|
||||
getRootProjectHeaderDragKeys,
|
||||
getSidebarRootProjectHeaderKeys,
|
||||
getRootProjectOrderForSidebarDrop,
|
||||
getRootProjectOrderUpdatesForSidebarDrop
|
||||
getSidebarRootProjectHeaderKeys
|
||||
} from './root-project-header-drop'
|
||||
|
||||
function group(id: string, overrides: Partial<ProjectGroup> = {}): ProjectGroup {
|
||||
@@ -34,45 +32,6 @@ function repo(id: string, overrides: Partial<Repo> = {}): Repo {
|
||||
}
|
||||
|
||||
describe('root project header drops', () => {
|
||||
it('moves a project between groups while retaining filtered roots and excluding nested members', () => {
|
||||
const order = getRootProjectOrderForSidebarDrop({
|
||||
projectGroups: [
|
||||
group('a'),
|
||||
group('hidden', { tabOrder: 1 }),
|
||||
group('b', { tabOrder: 2, executionHostId: 'runtime:remote' }),
|
||||
group('nested', { parentGroupId: 'a' })
|
||||
],
|
||||
repos: [repo('x'), repo('member', { projectGroupId: 'a' }), repo('y')],
|
||||
visibleKeys: ['group:a', 'group:b', 'repo:x', 'repo:y'],
|
||||
draggedKey: 'repo:y',
|
||||
dropIndex: 1
|
||||
})
|
||||
|
||||
expect(order).toMatchObject([
|
||||
{ kind: 'group', group: { id: 'a' } },
|
||||
{ kind: 'group', group: { id: 'hidden' } },
|
||||
{ kind: 'repo', repo: { id: 'y' } },
|
||||
{ kind: 'group', group: { id: 'b', executionHostId: 'runtime:remote' } },
|
||||
{ kind: 'repo', repo: { id: 'x' } }
|
||||
])
|
||||
})
|
||||
|
||||
it('moves a group below projects without duplicating a project registered on multiple hosts', () => {
|
||||
const order = getRootProjectOrderForSidebarDrop({
|
||||
projectGroups: [group('a'), group('b', { tabOrder: 1 })],
|
||||
repos: [repo('x'), repo('x', { executionHostId: 'runtime:remote' }), repo('hidden')],
|
||||
visibleKeys: ['group:a', 'group:b', 'repo:x'],
|
||||
draggedKey: 'group:a',
|
||||
dropIndex: 3
|
||||
})
|
||||
|
||||
expect(order).toMatchObject([
|
||||
{ kind: 'group', group: { id: 'b' } },
|
||||
{ kind: 'repo', repo: { id: 'x' } },
|
||||
{ kind: 'group', group: { id: 'a' } },
|
||||
{ kind: 'repo', repo: { id: 'hidden' } }
|
||||
])
|
||||
})
|
||||
it('limits root moves to the source host section', () => {
|
||||
expect(
|
||||
getRootProjectHeaderDragKeys(
|
||||
@@ -96,73 +55,6 @@ describe('root project header drops', () => {
|
||||
).toEqual(['group:a'])
|
||||
})
|
||||
|
||||
it('changes only the moved rank when neighbors already have space', () => {
|
||||
const updates = getRootProjectOrderUpdatesForSidebarDrop({
|
||||
projectGroups: [
|
||||
group('a', { rootProjectOrder: 0 }),
|
||||
group('b', { rootProjectOrder: 1000, tabOrder: 1 })
|
||||
],
|
||||
repos: [repo('x', { projectGroupOrder: 2000 }), repo('y', { projectGroupOrder: 3000 })],
|
||||
visibleKeys: ['group:a', 'group:b', 'repo:x', 'repo:y'],
|
||||
draggedKey: 'repo:y',
|
||||
dropIndex: 1
|
||||
})
|
||||
expect(updates).toMatchObject([
|
||||
{ entry: { kind: 'repo', repo: { id: 'y' } }, rootProjectOrder: 500 }
|
||||
])
|
||||
})
|
||||
|
||||
it('reindexes roots when there is no representable rank between adjacent neighbors', () => {
|
||||
const updates = getRootProjectOrderUpdatesForSidebarDrop({
|
||||
projectGroups: [
|
||||
group('a', { rootProjectOrder: 9007199254740992 }),
|
||||
group('b', { rootProjectOrder: 9007199254740994, tabOrder: 1 })
|
||||
],
|
||||
repos: [
|
||||
repo('x', { projectGroupOrder: 9007199254740996 }),
|
||||
repo('y', { projectGroupOrder: 9007199254740998 })
|
||||
],
|
||||
visibleKeys: ['group:a', 'group:b', 'repo:x', 'repo:y'],
|
||||
draggedKey: 'repo:y',
|
||||
dropIndex: 1
|
||||
})
|
||||
expect(updates).toMatchObject([
|
||||
{ entry: { kind: 'group', group: { id: 'a' } }, rootProjectOrder: 0 },
|
||||
{ entry: { kind: 'repo', repo: { id: 'y' } }, rootProjectOrder: 1000 },
|
||||
{ entry: { kind: 'group', group: { id: 'b' } }, rootProjectOrder: 2000 },
|
||||
{ entry: { kind: 'repo', repo: { id: 'x' } }, rootProjectOrder: 3000 }
|
||||
])
|
||||
})
|
||||
|
||||
it('materializes only the legacy suffix needed to place a project before a group', () => {
|
||||
const updates = getRootProjectOrderUpdatesForSidebarDrop({
|
||||
projectGroups: [group('a'), group('b', { tabOrder: 1 })],
|
||||
repos: [repo('x'), repo('y')],
|
||||
visibleKeys: ['group:a', 'group:b', 'repo:x', 'repo:y'],
|
||||
draggedKey: 'repo:y',
|
||||
dropIndex: 1
|
||||
})
|
||||
expect(updates).toMatchObject([
|
||||
{ entry: { kind: 'repo', repo: { id: 'y' } }, rootProjectOrder: -2000 },
|
||||
{ entry: { kind: 'group', group: { id: 'b' } }, rootProjectOrder: -1000 }
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps group order synchronized when the recent view exposes only group headers', () => {
|
||||
const updates = getRootProjectOrderUpdatesForSidebarDrop({
|
||||
projectGroups: [
|
||||
group('a', { rootProjectOrder: 0 }),
|
||||
group('b', { rootProjectOrder: 2000, tabOrder: 1 })
|
||||
],
|
||||
repos: [repo('x', { projectGroupOrder: 1000 })],
|
||||
visibleKeys: ['group:a', 'group:b'],
|
||||
draggedKey: 'group:b',
|
||||
dropIndex: 0
|
||||
})
|
||||
expect(updates).toMatchObject([
|
||||
{ entry: { kind: 'group', group: { id: 'b' } }, rootProjectOrder: -1000, tabOrder: -1000 }
|
||||
])
|
||||
})
|
||||
it('uses the actual host occurrence when repeated logical headers span sections', () => {
|
||||
const host = (hostId: HostHeaderRow['hostId']): HostHeaderRow => ({
|
||||
type: 'host-header',
|
||||
|
||||
-291
@@ -1,291 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, useMemo } from 'react'
|
||||
import { cleanup, renderHook } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { createProgrammaticScrollMarks } from '@/hooks/programmatic-scroll-marks'
|
||||
import { requestVirtualizedScrollAnchorRecord } from '@/hooks/requestVirtualizedScrollAnchorRecord'
|
||||
import type { VirtualizedScrollAnchor } from '@/hooks/useVirtualizedScrollAnchor'
|
||||
import { buildLineageRowProjection } from '../listing/lineage-row-projection'
|
||||
import type { RenderRow } from '../listing/render-row'
|
||||
import { repo, worktree } from '../grouping/worktree-list-groups-test-fixtures'
|
||||
import { revealElementInScrollContainer } from '../navigation/worktree-sidebar-reveal'
|
||||
import { useVirtualRowMeasurementSync } from './use-row-measurement'
|
||||
import { useWorktreeSidebarScrollSuppression } from './use-scroll-suppression'
|
||||
import { preserveDeleteSiblingPosition } from '../../workspace-actions/context-menu/worktree-context-menu-policy'
|
||||
import type { WorktreeListVirtualizer } from './use-virtualizer'
|
||||
|
||||
const caches = vi.hoisted(() => ({ prCache: {}, issueCache: {} }))
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: (selector: (state: typeof caches) => unknown) => selector(caches)
|
||||
}))
|
||||
|
||||
const frames = new Map<number, FrameRequestCallback>()
|
||||
let nextFrame = 0
|
||||
beforeEach(() => {
|
||||
vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
|
||||
frames.set(++nextFrame, callback)
|
||||
return nextFrame
|
||||
})
|
||||
vi.spyOn(window, 'cancelAnimationFrame').mockImplementation((id) => frames.delete(id))
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
frames.clear()
|
||||
document.body.replaceChildren()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function row(id: string): RenderRow {
|
||||
return {
|
||||
type: 'item',
|
||||
rowKey: id,
|
||||
sectionKey: 'all',
|
||||
repo,
|
||||
worktree: { ...worktree, id },
|
||||
depth: 0,
|
||||
groupDepth: 0,
|
||||
isLastLineageChild: false,
|
||||
lineageChildCount: 0
|
||||
}
|
||||
}
|
||||
|
||||
function setup(interior = false) {
|
||||
const scroller = document.createElement('div')
|
||||
scroller.setAttribute('data-worktree-sidebar', '')
|
||||
document.body.append(scroller)
|
||||
Object.defineProperties(scroller, {
|
||||
clientHeight: { value: 400 },
|
||||
scrollHeight: { value: 4000 }
|
||||
})
|
||||
scroller.getBoundingClientRect = () => new DOMRect(0, 0, 300, 400)
|
||||
scroller.scrollTop = 1000
|
||||
scroller.scrollTo = (options?: ScrollToOptions | number) => {
|
||||
if (typeof options === 'object') {
|
||||
scroller.scrollTop = options.top ?? 0
|
||||
}
|
||||
}
|
||||
const model = {
|
||||
sizes: new Map<string, number>(),
|
||||
starts: new Map([
|
||||
['a', 0],
|
||||
['b', 1000],
|
||||
['c', 2000],
|
||||
['d', 3000]
|
||||
]),
|
||||
items: interior ? ['a', 'b', 'c', 'd'] : ['a', 'b', 'c'],
|
||||
totalSize: 4000
|
||||
}
|
||||
const mount = (id: string) => {
|
||||
const element = document.createElement('div')
|
||||
element.setAttribute('data-worktree-virtual-row', '')
|
||||
element.setAttribute('data-worktree-virtual-row-key', `wt:${id}`)
|
||||
element.getBoundingClientRect = () =>
|
||||
new DOMRect(
|
||||
0,
|
||||
(model.starts.get(id) ?? 0) - scroller.scrollTop,
|
||||
300,
|
||||
model.sizes.get(id) ?? 1000
|
||||
)
|
||||
scroller.append(element)
|
||||
return element
|
||||
}
|
||||
const mounted = mount('b')
|
||||
const virtualizer = {
|
||||
elementsCache: new Map(),
|
||||
getTotalSize: () => model.totalSize,
|
||||
getVirtualItems: () =>
|
||||
model.items.map((id, index) => ({
|
||||
index,
|
||||
key: `wt:${id}`,
|
||||
start: model.starts.get(id) ?? 0,
|
||||
end: (model.starts.get(id) ?? 0) + (model.sizes.get(id) ?? 1000),
|
||||
size: model.sizes.get(id) ?? 1000,
|
||||
lane: 0
|
||||
})),
|
||||
measureElement: () => {},
|
||||
isScrolling: false,
|
||||
scrollOffset: null,
|
||||
scrollToIndex: () => {
|
||||
scroller.scrollTop = 500
|
||||
}
|
||||
}
|
||||
const scrollRef = { current: scroller }
|
||||
const scrollOffsetRef = { current: 1000 }
|
||||
const scrollAnchorRef: { current: VirtualizedScrollAnchor } = { current: null }
|
||||
const marks = createProgrammaticScrollMarks()
|
||||
const view = renderHook(
|
||||
({ rows }: { rows: RenderRow[] }) => {
|
||||
const projection = useMemo(() => buildLineageRowProjection(rows, 'none', false), [rows])
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The fixture supplies the geometry and virtualizer methods consumed by the production measurement/anchor integration.
|
||||
const virtualization = {
|
||||
virtualizer,
|
||||
isCurrentVirtualRowElement: () => true,
|
||||
stickyHeaderIndexes: [],
|
||||
activeStickyHeaderIndexRef: { current: null },
|
||||
activeStickyHostIndexRef: { current: null },
|
||||
stickyRangeStartIndexRef: { current: 0 },
|
||||
rowIndexByKey: projection.rowIndexByKey,
|
||||
restoreSignal: projection.restoreSignal,
|
||||
programmaticScrollMarks: marks
|
||||
} as unknown as WorktreeListVirtualizer
|
||||
const input = useWorktreeSidebarScrollSuppression(scrollRef)
|
||||
useVirtualRowMeasurementSync({
|
||||
renderRows: rows,
|
||||
virtualization,
|
||||
scrollRef,
|
||||
scrollOffsetRef,
|
||||
scrollAnchorRef,
|
||||
shouldSkipScrollAnchorRestore: input.shouldSkipScrollAnchorRestore
|
||||
})
|
||||
return input
|
||||
},
|
||||
{
|
||||
initialProps: {
|
||||
rows: interior
|
||||
? [row('a'), { ...row('b'), depth: 1 }, { ...row('c'), depth: 1 }, row('d')]
|
||||
: [row('a'), row('b'), row('c')]
|
||||
}
|
||||
}
|
||||
)
|
||||
act(() => requestVirtualizedScrollAnchorRecord(scroller))
|
||||
return { scroller, model, mount, mounted, view }
|
||||
}
|
||||
|
||||
it('leaves height-only scroll correction to the virtualizer instead of restoring an older DOM position', () => {
|
||||
const { scroller, model, view } = setup()
|
||||
act(() => {
|
||||
scroller.scrollTop = 1200
|
||||
scroller.dispatchEvent(new Event('scroll'))
|
||||
})
|
||||
model.starts.set('b', 950)
|
||||
model.totalSize = 3950
|
||||
view.rerender({ rows: [row('a'), row('b'), row('c')] })
|
||||
expect(scroller.scrollTop).toBe(1200)
|
||||
})
|
||||
|
||||
it('preserves the visible occurrence when rows before it disappear', () => {
|
||||
const { scroller, model, mounted, view } = setup()
|
||||
act(() => {
|
||||
scroller.scrollTop = 1020
|
||||
scroller.dispatchEvent(new Event('scroll'))
|
||||
})
|
||||
model.starts.set('b', 0)
|
||||
model.starts.set('c', 1000)
|
||||
model.items = ['b', 'c']
|
||||
model.totalSize = 3000
|
||||
view.rerender({ rows: [row('b'), row('c')] })
|
||||
expect(scroller.scrollTop).toBe(20)
|
||||
expect(mounted.getBoundingClientRect().top).toBe(-20)
|
||||
})
|
||||
|
||||
it('lets an already-visible explicit reveal supersede a pending offscreen restore', () => {
|
||||
const { scroller, model, mounted, mount, view } = setup()
|
||||
mounted.remove()
|
||||
model.items = []
|
||||
view.rerender({ rows: [row('b'), row('c')] })
|
||||
expect(scroller.scrollTop).toBe(500)
|
||||
model.starts.set('c', 550)
|
||||
const destination = mount('c')
|
||||
destination.getBoundingClientRect = () => new DOMRect(0, 550 - scroller.scrollTop, 300, 100)
|
||||
model.starts.set('b', 400)
|
||||
model.sizes.set('b', 100)
|
||||
const oldTarget = mount('b')
|
||||
oldTarget.getBoundingClientRect = () => new DOMRect(0, 400 - scroller.scrollTop, 300, 100)
|
||||
model.items = ['b', 'c']
|
||||
act(() => {
|
||||
expect(revealElementInScrollContainer(scroller, destination, 'auto')).toBe(true)
|
||||
const pendingFrames = [...frames]
|
||||
for (const [id, callback] of pendingFrames) {
|
||||
frames.delete(id)
|
||||
callback(0)
|
||||
}
|
||||
})
|
||||
expect(scroller.scrollTop).toBe(500)
|
||||
expect(destination.getBoundingClientRect().top).toBe(50)
|
||||
})
|
||||
|
||||
function finishPositioning() {
|
||||
act(() => {
|
||||
for (let turn = 0; turn < 12 && frames.size; turn++) {
|
||||
const pendingFrames = [...frames]
|
||||
for (const [id, callback] of pendingFrames) {
|
||||
frames.delete(id)
|
||||
callback(0)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
it('lets no-op direct input retire an old target and preserve position on a later insertion', () => {
|
||||
const { scroller, model, mounted, mount, view } = setup()
|
||||
mounted.remove()
|
||||
model.items = []
|
||||
view.rerender({ rows: [row('b'), row('c')] })
|
||||
model.starts.set('b', 400)
|
||||
model.sizes.set('b', 100)
|
||||
const oldTarget = mount('b')
|
||||
oldTarget.getBoundingClientRect = () => new DOMRect(0, 400 - scroller.scrollTop, 300, 100)
|
||||
model.starts.set('c', 480)
|
||||
const destination = mount('c')
|
||||
model.items = ['b', 'c']
|
||||
act(() => view.result.current.markDirectScrollInput())
|
||||
finishPositioning()
|
||||
expect(scroller.scrollTop).toBe(500)
|
||||
expect(destination.getBoundingClientRect().top).toBe(-20)
|
||||
model.starts.set('c', 680)
|
||||
model.items = ['b', 'new', 'c']
|
||||
view.rerender({ rows: [row('b'), row('new'), row('c')] })
|
||||
expect(scroller.scrollTop).toBe(700)
|
||||
expect(destination.getBoundingClientRect().top).toBe(-20)
|
||||
})
|
||||
|
||||
it('keeps an interior descendant successor at the removed card position after action takeover', () => {
|
||||
const { scroller, model, mounted, mount, view } = setup(true)
|
||||
model.sizes.set('b', 200)
|
||||
model.starts.set('c', 1200)
|
||||
model.starts.set('d', 2200)
|
||||
model.totalSize = 3200
|
||||
const successor = mount('c')
|
||||
act(() => {
|
||||
scroller.scrollTop = 1020
|
||||
scroller.dispatchEvent(new Event('scroll'))
|
||||
})
|
||||
const position = preserveDeleteSiblingPosition(mounted)
|
||||
// The real teardown boundary records the live viewport immediately before its row mutation.
|
||||
act(() => requestVirtualizedScrollAnchorRecord(scroller))
|
||||
mounted.remove()
|
||||
model.starts.set('c', 1000)
|
||||
model.starts.set('d', 2000)
|
||||
model.items = ['a', 'c', 'd']
|
||||
model.totalSize = 3000
|
||||
view.rerender({ rows: [row('a'), { ...row('c'), depth: 1 }, row('d')] })
|
||||
expect(scroller.scrollTop).toBe(1000)
|
||||
act(position)
|
||||
view.rerender({ rows: [row('a'), { ...row('c'), depth: 1 }, row('d')] })
|
||||
expect(scroller.scrollTop).toBe(1020)
|
||||
finishPositioning()
|
||||
expect(scroller.scrollTop).toBe(1020)
|
||||
expect(successor.getBoundingClientRect().top).toBe(-20)
|
||||
})
|
||||
|
||||
it('preserves the live viewport when delayed removal follows completed positioning and user scrolling', () => {
|
||||
const { scroller, model, mounted, mount, view } = setup(true)
|
||||
const successor = mount('c')
|
||||
const position = preserveDeleteSiblingPosition(mounted)
|
||||
act(position)
|
||||
finishPositioning()
|
||||
act(() => {
|
||||
scroller.scrollTop = 2100
|
||||
scroller.dispatchEvent(new Event('scroll'))
|
||||
requestVirtualizedScrollAnchorRecord(scroller)
|
||||
})
|
||||
mounted.remove()
|
||||
model.starts.set('c', 1000)
|
||||
model.starts.set('d', 2000)
|
||||
model.items = ['a', 'c', 'd']
|
||||
model.totalSize = 3000
|
||||
view.rerender({ rows: [row('a'), { ...row('c'), depth: 1 }, row('d')] })
|
||||
finishPositioning()
|
||||
expect(scroller.scrollTop).toBe(1100)
|
||||
expect(successor.getBoundingClientRect().top).toBe(-100)
|
||||
})
|
||||
@@ -1,394 +0,0 @@
|
||||
/**
|
||||
* @vitest-environment happy-dom
|
||||
*
|
||||
* Two splits side by side whose tab strips overflow and scroll. dnd-kit measures each tab with
|
||||
* getBoundingClientRect, which ignores the strip's overflow clip, so scrolled-off tabs keep rects
|
||||
* over the other split or the strip's own buttons. Drops must follow what the user sees.
|
||||
*/
|
||||
import { act, createElement } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import type {
|
||||
Active,
|
||||
ClientRect,
|
||||
DragMoveEvent,
|
||||
DroppableContainer,
|
||||
Over,
|
||||
UniqueIdentifier
|
||||
} from '@dnd-kit/core'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Tab } from '../../../../shared/workspace-layout/tab-groups/tab-types'
|
||||
import { useAppStore } from '../../store'
|
||||
import { recordTabDragPointer } from './tab-drag-pointer'
|
||||
import { getTabPaneBodyDroppableId, useTabDragSplit, type TabDragItemData } from './useTabDragSplit'
|
||||
|
||||
vi.mock('../../runtime/web-session-tabs-sync/identity/web-runtime-session-environment', () => ({
|
||||
isWebRuntimeSessionActive: vi.fn(() => false)
|
||||
}))
|
||||
vi.mock('../../runtime/web-session-tabs-sync/actions/web-runtime-session-tab-move', () => ({
|
||||
moveWebRuntimeSessionTab: vi.fn()
|
||||
}))
|
||||
|
||||
const WT = 'folder:owner-layout'
|
||||
const LEFT = 'left-group'
|
||||
const RIGHT = 'right-group'
|
||||
const STRIP_HEIGHT = 32
|
||||
const PANEL_HEIGHT = 900
|
||||
const STRIP_Y = STRIP_HEIGHT / 2
|
||||
|
||||
type SplitSpec = {
|
||||
groupId: string
|
||||
panelLeft: number
|
||||
panelWidth: number
|
||||
/** The scroller ends before the strip's own buttons. */
|
||||
scrollerWidth: number
|
||||
tabWidth: number
|
||||
tabIds: string[]
|
||||
scrollLeft: number
|
||||
}
|
||||
|
||||
type Layout = {
|
||||
containers: DroppableContainer[]
|
||||
rects: Map<UniqueIdentifier, ClientRect>
|
||||
}
|
||||
|
||||
const mounted: { container: HTMLDivElement; root: Root }[] = []
|
||||
|
||||
function rect(left: number, top: number, width: number, height: number): ClientRect {
|
||||
return { left, top, width, height, right: left + width, bottom: top + height }
|
||||
}
|
||||
|
||||
function stubRect(element: HTMLElement, box: ClientRect): void {
|
||||
element.getBoundingClientRect = () => new DOMRect(box.left, box.top, box.width, box.height)
|
||||
}
|
||||
|
||||
function ids(prefix: string, count: number): string[] {
|
||||
return Array.from({ length: count }, (_, index) => `${prefix}-${index}`)
|
||||
}
|
||||
|
||||
function isChat(id: string): boolean {
|
||||
return id.startsWith('structured-agent-session')
|
||||
}
|
||||
|
||||
function tabData(groupId: string, id: string): TabDragItemData {
|
||||
return {
|
||||
kind: 'tab',
|
||||
worktreeId: WT,
|
||||
groupId,
|
||||
unifiedTabId: id,
|
||||
visibleTabId: id,
|
||||
tabType: isChat(id) ? 'agent-session' : 'browser',
|
||||
label: id
|
||||
}
|
||||
}
|
||||
|
||||
function unifiedTab(groupId: string, id: string, sortOrder: number): Tab {
|
||||
return {
|
||||
id,
|
||||
groupId,
|
||||
worktreeId: WT,
|
||||
contentType: isChat(id) ? 'agent-session' : 'browser',
|
||||
entityId: id,
|
||||
label: id,
|
||||
customLabel: null,
|
||||
color: null,
|
||||
sortOrder,
|
||||
createdAt: 0
|
||||
}
|
||||
}
|
||||
|
||||
function droppable(
|
||||
id: UniqueIdentifier,
|
||||
data: Record<string, unknown>,
|
||||
node: HTMLElement
|
||||
): DroppableContainer {
|
||||
return {
|
||||
id,
|
||||
key: String(id),
|
||||
data: { current: data },
|
||||
disabled: false,
|
||||
node: { current: node },
|
||||
rect: { current: null }
|
||||
}
|
||||
}
|
||||
|
||||
/** Mounts each split as TabGroupPanel renders it and returns the rects dnd-kit would measure. */
|
||||
function mountSplits(splits: [SplitSpec, SplitSpec]): Layout {
|
||||
const containers: DroppableContainer[] = []
|
||||
const rects = new Map<UniqueIdentifier, ClientRect>()
|
||||
for (const split of splits) {
|
||||
const panel = document.createElement('div')
|
||||
const scroller = document.createElement('div')
|
||||
scroller.setAttribute('data-tab-strip-scroller', '')
|
||||
stubRect(scroller, rect(split.panelLeft, 0, split.scrollerWidth, STRIP_HEIGHT))
|
||||
panel.appendChild(scroller)
|
||||
split.tabIds.forEach((id, index) => {
|
||||
const node = document.createElement('div')
|
||||
scroller.appendChild(node)
|
||||
containers.push(droppable(id, tabData(split.groupId, id), node))
|
||||
rects.set(
|
||||
id,
|
||||
rect(
|
||||
split.panelLeft + index * split.tabWidth - split.scrollLeft,
|
||||
0,
|
||||
split.tabWidth,
|
||||
STRIP_HEIGHT
|
||||
)
|
||||
)
|
||||
})
|
||||
const body = document.createElement('div')
|
||||
body.dataset.tabGroupBodyId = split.groupId
|
||||
body.dataset.worktreeId = WT
|
||||
const bodyRect = rect(
|
||||
split.panelLeft,
|
||||
STRIP_HEIGHT,
|
||||
split.panelWidth,
|
||||
PANEL_HEIGHT - STRIP_HEIGHT
|
||||
)
|
||||
stubRect(body, bodyRect)
|
||||
stubRect(panel, rect(split.panelLeft, 0, split.panelWidth, PANEL_HEIGHT))
|
||||
panel.appendChild(body)
|
||||
document.body.appendChild(panel)
|
||||
const bodyId = getTabPaneBodyDroppableId(split.groupId)
|
||||
containers.push(
|
||||
droppable(bodyId, { kind: 'pane-body', worktreeId: WT, groupId: split.groupId }, body)
|
||||
)
|
||||
rects.set(bodyId, bodyRect)
|
||||
}
|
||||
|
||||
useAppStore.setState({
|
||||
activeWorktreeId: WT,
|
||||
activeGroupIdByWorktree: { [WT]: splits[0].groupId },
|
||||
groupsByWorktree: {
|
||||
[WT]: splits.map((split) => ({
|
||||
id: split.groupId,
|
||||
worktreeId: WT,
|
||||
activeTabId: split.tabIds.at(-1)!,
|
||||
tabOrder: [...split.tabIds]
|
||||
}))
|
||||
},
|
||||
layoutByWorktree: {
|
||||
[WT]: {
|
||||
type: 'split',
|
||||
direction: 'horizontal',
|
||||
first: { type: 'leaf', groupId: splits[0].groupId },
|
||||
second: { type: 'leaf', groupId: splits[1].groupId },
|
||||
ratio: 0.48
|
||||
}
|
||||
},
|
||||
unifiedTabsByWorktree: {
|
||||
[WT]: splits.flatMap((split) =>
|
||||
split.tabIds.map((id, index) => unifiedTab(split.groupId, id, index))
|
||||
)
|
||||
}
|
||||
})
|
||||
return { containers, rects }
|
||||
}
|
||||
|
||||
function renderDragHook(): () => ReturnType<typeof useTabDragSplit> {
|
||||
let latest: ReturnType<typeof useTabDragSplit> | null = null
|
||||
function Probe(): null {
|
||||
latest = useTabDragSplit({ worktreeId: WT })
|
||||
return null
|
||||
}
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const root = createRoot(host)
|
||||
act(() => root.render(createElement(Probe)))
|
||||
mounted.push({ container: host, root })
|
||||
return () => {
|
||||
if (!latest) {
|
||||
throw new Error('useTabDragSplit did not render')
|
||||
}
|
||||
return latest
|
||||
}
|
||||
}
|
||||
|
||||
/** Drag a tab to a point the way dnd-kit does: resolve collisions, report a move, then drop. */
|
||||
function dragTab(args: {
|
||||
layout: Layout
|
||||
groupId: string
|
||||
tabId: string
|
||||
pointer: { x: number; y: number }
|
||||
/** Where the dragged ghost's centre sits relative to the pointer. */
|
||||
grabOffsetX?: number
|
||||
}): { insertionTabId: string | null } {
|
||||
const drag = renderDragHook()
|
||||
const activeRect = args.layout.rects.get(args.tabId)!
|
||||
const active: Active = {
|
||||
id: args.tabId,
|
||||
data: { current: tabData(args.groupId, args.tabId) },
|
||||
rect: { current: { initial: activeRect, translated: activeRect } }
|
||||
}
|
||||
const activatorEvent = new Event('pointerdown')
|
||||
act(() => drag().onDragStart({ active, activatorEvent }))
|
||||
const centerX = args.pointer.x + (args.grabOffsetX ?? 0)
|
||||
const collisions = drag().collisionDetection({
|
||||
active,
|
||||
collisionRect: rect(centerX - activeRect.width / 2, 0, activeRect.width, STRIP_HEIGHT),
|
||||
droppableRects: args.layout.rects,
|
||||
droppableContainers: args.layout.containers,
|
||||
pointerCoordinates: args.pointer
|
||||
})
|
||||
const overId = collisions[0]?.id
|
||||
const overDroppable = args.layout.containers.find((candidate) => candidate.id === overId)
|
||||
// dnd-kit reports `over` with the rect it measured, not a clipped one.
|
||||
const over: Over | null =
|
||||
overId !== undefined && overDroppable
|
||||
? {
|
||||
id: overId,
|
||||
rect: args.layout.rects.get(overId)!,
|
||||
data: overDroppable.data,
|
||||
disabled: false
|
||||
}
|
||||
: null
|
||||
const event: DragMoveEvent = { active, over, delta: { x: 0, y: 0 }, activatorEvent, collisions }
|
||||
recordTabDragPointer(args.pointer)
|
||||
act(() => drag().onDragMove(event))
|
||||
const insertionTabId = drag().hoveredTabInsertion?.visibleTabId ?? null
|
||||
act(() => drag().onDragEnd(event))
|
||||
return { insertionTabId }
|
||||
}
|
||||
|
||||
function tabOrder(groupId: string): string[] | undefined {
|
||||
return useAppStore.getState().groupsByWorktree[WT]?.find((group) => group.id === groupId)
|
||||
?.tabOrder
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
recordTabDragPointer(null)
|
||||
for (const { container: host, root } of mounted.splice(0)) {
|
||||
act(() => root.unmount())
|
||||
host.remove()
|
||||
}
|
||||
document.body.replaceChildren()
|
||||
})
|
||||
|
||||
const CHAT_IDS = ['a', 'b', 'c', 'd', 'e'].map((id) => `structured-agent-session-${id}`)
|
||||
const OWNER_RIGHT_IDS = ids('right-tab', 26)
|
||||
// The owner's layout: five chats on the left; 26 tabs on the right, scrolled to the last one.
|
||||
const OWNER_LEFT: SplitSpec = {
|
||||
groupId: LEFT,
|
||||
panelLeft: 0,
|
||||
panelWidth: 760,
|
||||
scrollerWidth: 700,
|
||||
tabWidth: 140,
|
||||
tabIds: CHAT_IDS,
|
||||
scrollLeft: 0
|
||||
}
|
||||
const OWNER_RIGHT: SplitSpec = {
|
||||
groupId: RIGHT,
|
||||
panelLeft: 764,
|
||||
panelWidth: 836,
|
||||
scrollerWidth: 760,
|
||||
tabWidth: 120,
|
||||
tabIds: OWNER_RIGHT_IDS,
|
||||
scrollLeft: 26 * 120 - 760
|
||||
}
|
||||
|
||||
describe('tab drops beside a scrolled tab strip', () => {
|
||||
it('reorders a chat within its split when a scrolled-off tab of the other split lies under the pointer', () => {
|
||||
const layout = mountSplits([OWNER_LEFT, OWNER_RIGHT])
|
||||
// Right half of the third chat: "move the first chat after the third".
|
||||
const { insertionTabId } = dragTab({
|
||||
layout,
|
||||
groupId: LEFT,
|
||||
tabId: CHAT_IDS[0]!,
|
||||
pointer: { x: 2 * 140 + 100, y: STRIP_Y }
|
||||
})
|
||||
|
||||
expect(insertionTabId).toBe('structured-agent-session-c')
|
||||
expect(tabOrder(LEFT)).toEqual([
|
||||
'structured-agent-session-b',
|
||||
'structured-agent-session-c',
|
||||
'structured-agent-session-a',
|
||||
'structured-agent-session-d',
|
||||
'structured-agent-session-e'
|
||||
])
|
||||
expect(tabOrder(RIGHT)).toEqual(OWNER_RIGHT_IDS)
|
||||
})
|
||||
|
||||
it('never marks a hidden tab of the same split, even over that strip’s own buttons', () => {
|
||||
const leftIds = ids('left-tab', 8)
|
||||
// The scroller spans 0..640 and the strip's buttons follow; tab 5 (700..840) is out of view.
|
||||
const layout = mountSplits([
|
||||
{ ...OWNER_LEFT, scrollerWidth: 640, tabIds: leftIds },
|
||||
{ ...OWNER_RIGHT, tabIds: ids('right-tab', 3), scrollLeft: 0 }
|
||||
])
|
||||
const { insertionTabId } = dragTab({
|
||||
layout,
|
||||
groupId: LEFT,
|
||||
tabId: leftIds[0]!,
|
||||
pointer: { x: 720, y: STRIP_Y }
|
||||
})
|
||||
|
||||
expect(insertionTabId).toBe('left-tab-4')
|
||||
expect(tabOrder(LEFT)).toEqual([
|
||||
'left-tab-1',
|
||||
'left-tab-2',
|
||||
'left-tab-3',
|
||||
'left-tab-4',
|
||||
'left-tab-0',
|
||||
'left-tab-5',
|
||||
'left-tab-6',
|
||||
'left-tab-7'
|
||||
])
|
||||
})
|
||||
|
||||
it('drops into the strip gap after the last tab of the split under the pointer', () => {
|
||||
const rightIds = ids('right-tab', 3)
|
||||
const layout = mountSplits([
|
||||
{ ...OWNER_LEFT, tabIds: CHAT_IDS.slice(0, 3) },
|
||||
{ ...OWNER_RIGHT, tabIds: rightIds, scrollLeft: 0 }
|
||||
])
|
||||
// Grabbed near its left edge, the ghost's centre sits right of the pointer, nearer the other split.
|
||||
dragTab({
|
||||
layout,
|
||||
groupId: LEFT,
|
||||
tabId: CHAT_IDS[0]!,
|
||||
pointer: { x: 600, y: STRIP_Y },
|
||||
grabOffsetX: 60
|
||||
})
|
||||
|
||||
expect(tabOrder(LEFT)).toEqual([
|
||||
'structured-agent-session-b',
|
||||
'structured-agent-session-c',
|
||||
'structured-agent-session-a'
|
||||
])
|
||||
expect(tabOrder(RIGHT)).toEqual(rightIds)
|
||||
})
|
||||
|
||||
it('reorders within the right split when the left strip overflows over it', () => {
|
||||
const leftIds = ids('left-tab', 12)
|
||||
const rightIds = ids('right-tab', 4)
|
||||
// The left strip is unscrolled, so its overflowing tabs (hidden tab 10 is 1000..1100) lie over the right strip.
|
||||
const layout = mountSplits([
|
||||
{ ...OWNER_LEFT, tabWidth: 100, tabIds: leftIds },
|
||||
{ ...OWNER_RIGHT, tabIds: rightIds, scrollLeft: 0 }
|
||||
])
|
||||
// Right half of right tab 2 (1004..1124): "move right tab 0 after right tab 2".
|
||||
dragTab({
|
||||
layout,
|
||||
groupId: RIGHT,
|
||||
tabId: rightIds[0]!,
|
||||
pointer: { x: 1070, y: STRIP_Y }
|
||||
})
|
||||
|
||||
expect(tabOrder(RIGHT)).toEqual(['right-tab-1', 'right-tab-2', 'right-tab-0', 'right-tab-3'])
|
||||
expect(tabOrder(LEFT)).toEqual(leftIds)
|
||||
})
|
||||
|
||||
it('still moves a tab into the other split when dropped on that split’s tab', () => {
|
||||
const rightIds = ids('right-tab', 3)
|
||||
const layout = mountSplits([OWNER_LEFT, { ...OWNER_RIGHT, tabIds: rightIds, scrollLeft: 0 }])
|
||||
// Left half of right tab 1 (884..1004).
|
||||
dragTab({
|
||||
layout,
|
||||
groupId: LEFT,
|
||||
tabId: CHAT_IDS[0]!,
|
||||
pointer: { x: 884 + 20, y: STRIP_Y }
|
||||
})
|
||||
|
||||
expect(tabOrder(LEFT)).toEqual(CHAT_IDS.slice(1))
|
||||
expect(tabOrder(RIGHT)).toEqual(['right-tab-0', CHAT_IDS[0], 'right-tab-1', 'right-tab-2'])
|
||||
})
|
||||
})
|
||||
@@ -183,19 +183,6 @@ describe('terminal search inside one very long wrapped line', () => {
|
||||
expect(performance.now() - startedAt).toBeLessThan(FULL_SCAN_BUDGET_MS)
|
||||
})
|
||||
|
||||
it('finds a whole-word match that only matches from a later wrapped row', async () => {
|
||||
const { terminal, search } = openTerminalWithSearch()
|
||||
const filler = 'x'.repeat(COLS - NEEDLE.length - 2)
|
||||
await write(terminal, `a${NEEDLE}a${filler} ${NEEDLE} ${filler}`)
|
||||
|
||||
const found = safeFind((term, options) => search.findNext(term, options), NEEDLE, {
|
||||
wholeWord: true,
|
||||
decorations: SEARCH_DECORATIONS
|
||||
})
|
||||
|
||||
expect(found).toBe(true)
|
||||
})
|
||||
|
||||
it('steps past a zero-length regex match instead of abandoning the line', async () => {
|
||||
const { terminal, search } = openTerminalWithSearch()
|
||||
await write(terminal, `abc ${NEEDLE} def\r\n`)
|
||||
@@ -208,17 +195,4 @@ describe('terminal search inside one very long wrapped line', () => {
|
||||
expect(found).toBe(true)
|
||||
expect(terminal.getSelectionPosition()?.start).toEqual({ x: 4, y: 0 })
|
||||
})
|
||||
|
||||
it('anchors a regex to the logical line, not to every wrapped row', async () => {
|
||||
const { terminal, search } = openTerminalWithSearch()
|
||||
// A visual wrap is not a logical line start, so ^ must not match there.
|
||||
await write(terminal, 'x'.repeat(COLS) + NEEDLE + 'x'.repeat(COLS - NEEDLE.length))
|
||||
|
||||
const found = safeFind((term, options) => search.findNext(term, options), `^${NEEDLE}`, {
|
||||
regex: true,
|
||||
decorations: SEARCH_DECORATIONS
|
||||
})
|
||||
|
||||
expect(found).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
-274
@@ -1,274 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as ReactI18Next from 'react-i18next'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import type { AppState } from '@/store/types'
|
||||
|
||||
import WorktreeJumpPalette from '../WorktreeJumpPalette'
|
||||
import { encodePaletteIdentity } from '../../../../../shared/palette-match/palette-ranking'
|
||||
import {
|
||||
makeGroup,
|
||||
makeRecentTabState,
|
||||
makeRepo,
|
||||
makeUnifiedTab
|
||||
} from '../worktree-jump-palette-test-fixtures'
|
||||
|
||||
vi.mock('react-i18next', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof ReactI18Next>()
|
||||
return {
|
||||
...actual,
|
||||
useTranslation: () => ({
|
||||
t: (_key: string, fallback?: string) => fallback ?? _key
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
message: vi.fn()
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSettingsNavigationMetadata', () => ({
|
||||
useSettingsNavigationMetadata: () => []
|
||||
}))
|
||||
|
||||
vi.mock('@/components/sidebar/workspace-card/surface/StatusIndicator', () => ({
|
||||
default: () => <span data-status-indicator="true" />
|
||||
}))
|
||||
|
||||
vi.mock('@/components/repo/RepoBadgeLabel', () => ({
|
||||
RepoBadgeMark: () => <span data-repo-badge-mark="true" />
|
||||
}))
|
||||
|
||||
vi.mock('@/components/cmd-j/palette-host-badge', () => ({
|
||||
getPaletteHostBadge: () => null
|
||||
}))
|
||||
|
||||
// Stub activation at its boundary; the palette contract is which result it hands over.
|
||||
const { activateWorkspaceTabPaletteResult } = vi.hoisted(() => ({
|
||||
activateWorkspaceTabPaletteResult: vi.fn((_result: unknown) => ({ status: 'activated' }) as const)
|
||||
}))
|
||||
vi.mock('@/lib/workspace/search/tabs/workspace-tab-palette-activation', () => ({
|
||||
activateWorkspaceTabPaletteResult: (result: unknown) => activateWorkspaceTabPaletteResult(result)
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/command', async () => {
|
||||
const React = await import('react')
|
||||
return {
|
||||
Command: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
CommandGroup: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
// Pass controlled cmdk value through so Enter-target assertions reflect actual selection.
|
||||
CommandDialog: ({
|
||||
children,
|
||||
open,
|
||||
commandProps
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
open?: boolean
|
||||
commandProps?: { value?: string; onValueChange?: (next: string) => void }
|
||||
}) => {
|
||||
return open ? (
|
||||
<div data-command-dialog="true" data-command-value={commandProps?.value ?? ''}>
|
||||
{children}
|
||||
</div>
|
||||
) : null
|
||||
},
|
||||
CommandInput: ({
|
||||
value,
|
||||
onValueChange,
|
||||
placeholder
|
||||
}: {
|
||||
value?: string
|
||||
onValueChange?: (next: string) => void
|
||||
placeholder?: string
|
||||
}) => {
|
||||
setCommandQuery = onValueChange ?? null
|
||||
return (
|
||||
<input
|
||||
data-command-input="true"
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(event) => onValueChange?.(event.currentTarget.value)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
CommandList: React.forwardRef(function CommandList(
|
||||
{ children }: { children: React.ReactNode },
|
||||
ref: React.ForwardedRef<HTMLDivElement>
|
||||
) {
|
||||
return (
|
||||
<div ref={ref} data-command-list="true">
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
CommandEmpty: ({ children }: { children: React.ReactNode }) => (
|
||||
<div data-command-empty="true">{children}</div>
|
||||
),
|
||||
CommandItem: ({
|
||||
children,
|
||||
onSelect,
|
||||
value
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
onSelect?: (value: string) => void
|
||||
value?: string
|
||||
}) => (
|
||||
<button data-command-item={value ?? ''} onClick={() => onSelect?.(value ?? '')} type="button">
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
const initialAppState = useAppStore.getInitialState()
|
||||
let testRoot: Root
|
||||
let testContainer: HTMLDivElement
|
||||
let setCommandQuery: ((next: string) => void) | null = null
|
||||
|
||||
async function flushEffects(): Promise<void> {
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
})
|
||||
}
|
||||
|
||||
async function renderPalette(overrides: Partial<AppState>): Promise<void> {
|
||||
useAppStore.setState({
|
||||
activeModal: 'worktree-palette',
|
||||
activeWorktreeId: null,
|
||||
repos: [makeRepo()],
|
||||
tabsByWorktree: {},
|
||||
browserTabsByWorktree: {},
|
||||
browserPagesByWorkspace: {},
|
||||
unifiedTabsByWorktree: {},
|
||||
hideDefaultBranchWorkspace: false,
|
||||
hideAutomationGeneratedWorkspaces: false,
|
||||
// Why explicit: the sweep exemption is what these cases probe, so it must
|
||||
// not ride on whatever the store default happens to be.
|
||||
alwaysShowDefaultBranchWorkspace: true,
|
||||
lastVisitedAtByWorktreeId: {},
|
||||
...overrides
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
testRoot.render(<WorktreeJumpPalette />)
|
||||
})
|
||||
await flushEffects()
|
||||
}
|
||||
|
||||
function getTabRowIds(): string[] {
|
||||
return [
|
||||
...testContainer.querySelectorAll<HTMLElement>(
|
||||
`[data-command-item^="${encodePaletteIdentity(['workspace-tab'])}"]`
|
||||
)
|
||||
]
|
||||
.map((node) => node.dataset.commandItem ?? '')
|
||||
.map(
|
||||
(id) =>
|
||||
Object.values(useAppStore.getState().unifiedTabsByWorktree)
|
||||
.flat()
|
||||
.find(
|
||||
(tab) => encodePaletteIdentity(['workspace-tab', '', tab.worktreeId, tab.id]) === id
|
||||
)?.id ?? ''
|
||||
)
|
||||
}
|
||||
|
||||
describe('WorktreeJumpPalette recent chats & terminals', () => {
|
||||
beforeEach(() => {
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
setCommandQuery = null
|
||||
activateWorkspaceTabPaletteResult.mockClear()
|
||||
useAppStore.setState(initialAppState, true)
|
||||
testContainer = document.createElement('div')
|
||||
document.body.appendChild(testContainer)
|
||||
testRoot = createRoot(testContainer)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
testRoot.unmount()
|
||||
})
|
||||
document.body.replaceChildren()
|
||||
useAppStore.setState(initialAppState, true)
|
||||
})
|
||||
|
||||
it('excludes the current editor tab — no agent ladder can lift it out of "you are here"', async () => {
|
||||
const fileId = '/repo/wt-alpha/notes.ts'
|
||||
const state = makeRecentTabState({
|
||||
activeWorktreeId: 'wt-alpha',
|
||||
activeTabType: 'editor',
|
||||
activeTabTypeByWorktree: { 'wt-alpha': 'editor' },
|
||||
activeFileId: fileId,
|
||||
activeFileIdByWorktree: { 'wt-alpha': fileId },
|
||||
openFiles: [
|
||||
{
|
||||
id: fileId,
|
||||
filePath: fileId,
|
||||
relativePath: 'notes.ts',
|
||||
worktreeId: 'wt-alpha',
|
||||
language: 'typescript',
|
||||
isDirty: false,
|
||||
mode: 'edit'
|
||||
}
|
||||
]
|
||||
})
|
||||
await renderPalette({
|
||||
...state,
|
||||
unifiedTabsByWorktree: {
|
||||
...state.unifiedTabsByWorktree,
|
||||
'wt-alpha': [
|
||||
{
|
||||
...makeUnifiedTab('tab-alpha-file', 'wt-alpha', fileId, 'notes.ts'),
|
||||
contentType: 'editor'
|
||||
},
|
||||
...(state.unifiedTabsByWorktree?.['wt-alpha'] ?? [])
|
||||
]
|
||||
},
|
||||
groupsByWorktree: {
|
||||
...state.groupsByWorktree,
|
||||
'wt-alpha': [makeGroup('wt-alpha', ['tab-alpha-file', 'tab-alpha'])]
|
||||
}
|
||||
})
|
||||
|
||||
expect(getTabRowIds()).not.toContain('tab-alpha-file')
|
||||
expect(getTabRowIds()).toContain('tab-alpha')
|
||||
|
||||
// Proves the exclusion is the current-tab rule, not a missing index entry: search still finds it.
|
||||
await act(async () => {
|
||||
setCommandQuery?.('notes')
|
||||
})
|
||||
await flushEffects()
|
||||
expect(getTabRowIds()).toContain('tab-alpha-file')
|
||||
})
|
||||
|
||||
it('does not admit the current tab mid-open when it goes unread', async () => {
|
||||
await renderPalette(
|
||||
makeRecentTabState({
|
||||
activeWorktreeId: 'wt-alpha',
|
||||
activeTabType: 'terminal',
|
||||
activeTabId: 'term-alpha',
|
||||
activeTabIdByWorktree: { 'wt-alpha': 'term-alpha' },
|
||||
activeTabTypeByWorktree: { 'wt-alpha': 'terminal' }
|
||||
})
|
||||
)
|
||||
|
||||
expect(getTabRowIds()).toEqual(['tab-beta'])
|
||||
|
||||
await act(async () => {
|
||||
useAppStore.setState({ unreadTerminalTabs: { 'term-alpha': true } })
|
||||
})
|
||||
await flushEffects()
|
||||
|
||||
// Freeze membership/order per open so late arrivals cannot move rows or digit shortcuts under the cursor.
|
||||
expect(getTabRowIds()).toEqual(['tab-beta'])
|
||||
})
|
||||
})
|
||||
@@ -1,9 +1,6 @@
|
||||
import { EVERY_AGENT_CHAT } from '../../../../../../shared/native-chat/every-agent-chat.test-fixture'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY,
|
||||
STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY
|
||||
} from '../../../../../../shared/agent-session/agent-session-runtime-capabilities'
|
||||
import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../../../shared/agent-session/agent-session-runtime-capabilities'
|
||||
import { folderWorkspaceKey } from '../../../../../../shared/workspace/identity/workspace-scope'
|
||||
import { buildAgentLaunchRouteInput } from './agent-launch-route-input'
|
||||
import type { AgentLaunchRouteArgs, AgentLaunchRouteStore } from './agent-launch-route-input'
|
||||
@@ -68,10 +65,6 @@ describe('buildAgentLaunchRouteInput', () => {
|
||||
beforeEach(stageLocalStructuredHost)
|
||||
|
||||
describe('a workspace on a paired server', () => {
|
||||
const CURRENT_SERVER = [
|
||||
STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY,
|
||||
STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY
|
||||
]
|
||||
const args: AgentLaunchRouteArgs = {
|
||||
agent: 'claude',
|
||||
workspace: { kind: 'git-worktree', worktreeId: 'wt-1' }
|
||||
@@ -102,15 +95,6 @@ describe('buildAgentLaunchRouteInput', () => {
|
||||
'terminal-tui'
|
||||
)
|
||||
})
|
||||
|
||||
it('opens a chat for a browser client too', () => {
|
||||
mocks.isWebClientLocation.mockReturnValue(true)
|
||||
try {
|
||||
expect(routeFor(pairedStore(CURRENT_SERVER), args)).toBe('structured-native-chat')
|
||||
} finally {
|
||||
mocks.isWebClientLocation.mockReturnValue(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('does not name a host for a workspace id two hosts publish', () => {
|
||||
@@ -151,19 +135,6 @@ describe('a cwd that names the workspace root', () => {
|
||||
folderWorkspaces: [{ id: 'folder-1', folderPath: '/srv/notes' }]
|
||||
}) as unknown as AgentLaunchRouteStore
|
||||
|
||||
it.each(['/repo/app', '/repo/app/', '.'])(
|
||||
'routes structured under the chat default for cwd %s',
|
||||
(cwd) => {
|
||||
const args = {
|
||||
agent: 'codex' as const,
|
||||
workspace: { kind: 'git-worktree' as const, worktreeId: 'wt-1' },
|
||||
tuiCustomization: { cwd }
|
||||
}
|
||||
expect(buildAgentLaunchRouteInput(withRoot(), args).startsOutsideWorkspaceRoot).toBe(false)
|
||||
expect(routeFor(withRoot(), args)).toBe('structured-native-chat')
|
||||
}
|
||||
)
|
||||
|
||||
it('still requires a terminal for a subdirectory, which a structured session cannot start in', () => {
|
||||
const args = {
|
||||
agent: 'codex' as const,
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { PluginOverlayManager } from './plugin-overlay'
|
||||
import { resolveOmpConfigDirName, resolvePiSourceAgentDir } from './plugin-overlay-env'
|
||||
import { __resetShellStartupEnvCache } from '../../../main/pty/shell-startup/shell-startup-env'
|
||||
import { resetLoginShellEnvironmentCacheForTests } from '../../../main/startup/shell-environment/login-shell-environment'
|
||||
|
||||
describe('relay OMP config root', () => {
|
||||
let home: string
|
||||
let manager: PluginOverlayManager
|
||||
|
||||
beforeEach(() => {
|
||||
home = mkdtempSync(join(tmpdir(), 'orca-relay-omp-config-'))
|
||||
manager = new PluginOverlayManager({ homeDir: home })
|
||||
manager.setSources({ ompExtensionSource: 'export default function() {}' })
|
||||
__resetShellStartupEnvCache()
|
||||
resetLoginShellEnvironmentCacheForTests()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
__resetShellStartupEnvCache()
|
||||
resetLoginShellEnvironmentCacheForTests()
|
||||
rmSync(home, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it.each(['.company-omp', '.config/omp', ''])(
|
||||
'installs into the guest config root %j',
|
||||
async (config) => {
|
||||
const env = { HOME: home, PI_CONFIG_DIR: config }
|
||||
const result = manager.materializePi(
|
||||
'pane',
|
||||
resolvePiSourceAgentDir(env, '/bin/bash', 'omp'),
|
||||
'omp',
|
||||
{
|
||||
materializeDefaultHome: true,
|
||||
configDirName: await resolveOmpConfigDirName(env, '/bin/bash')
|
||||
}
|
||||
)
|
||||
const expected = join(home, config || '.omp', 'agent')
|
||||
expect(result?.sourceAgentDir).toBe(expected)
|
||||
expect(readFileSync(join(expected, 'extensions', 'orca-agent-status.ts'), 'utf8')).toContain(
|
||||
'@orca-managed-pi-extension'
|
||||
)
|
||||
if (config) {
|
||||
expect(existsSync(join(home, '.omp'))).toBe(false)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it('keeps an explicit source directory ahead of the config root', () => {
|
||||
const source = join(home, 'explicit-agent')
|
||||
mkdirSync(source)
|
||||
const result = manager.materializePi('pane', source, 'omp', { configDirName: '.company-omp' })
|
||||
expect(result?.sourceAgentDir).toBe(source)
|
||||
expect(existsSync(join(home, '.company-omp'))).toBe(false)
|
||||
})
|
||||
|
||||
it('does not create a missing config root for a bare shell', () => {
|
||||
const result = manager.materializePi('pane', undefined, 'omp', {
|
||||
materializeDefaultHome: false,
|
||||
configDirName: '.company-omp'
|
||||
})
|
||||
expect(result?.sourceAgentDir).toBeUndefined()
|
||||
expect(result?.statusExtensionPath).toBeTruthy()
|
||||
expect(existsSync(join(home, '.company-omp'))).toBe(false)
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'uses the guest profile only when no pane override exists',
|
||||
async () => {
|
||||
writeFileSync(join(home, '.bash_profile'), 'export PI_CONFIG_DIR=".profile-omp"\n')
|
||||
expect(await resolveOmpConfigDirName({ HOME: home }, '/bin/bash')).toBe('.profile-omp')
|
||||
expect(await resolveOmpConfigDirName({ HOME: home, PI_CONFIG_DIR: '' }, '/bin/bash')).toBe(
|
||||
'.omp'
|
||||
)
|
||||
expect(
|
||||
await resolveOmpConfigDirName({ HOME: home, PI_CONFIG_DIR: '.pane-omp' }, '/bin/bash')
|
||||
).toBe('.pane-omp')
|
||||
}
|
||||
)
|
||||
})
|
||||
@@ -1,241 +0,0 @@
|
||||
import type { Locator, Page } from '@stablyai/playwright-test'
|
||||
import type { ExecutionHostId } from '../../src/shared/execution-host'
|
||||
import { getPaletteWorktreeIdentity } from '../../src/renderer/src/lib/workspace/search/palette-repo-resolution'
|
||||
import { encodePaletteIdentity } from '../../src/shared/palette-match/palette-ranking'
|
||||
import { expect, test } from './helpers/orca-app'
|
||||
import { waitForActiveWorktree, waitForSessionReady } from './helpers/store'
|
||||
|
||||
const LOCAL_PROJECT = 'E2E Palette Local Project'
|
||||
const REMOTE_PROJECT = 'E2E Palette Remote Project'
|
||||
const REMOTE_WORKSPACE = 'E2E Palette Remote Workspace'
|
||||
const REMOTE_HOST = 'E2E Palette Builder'
|
||||
const SEARCH_PLACEHOLDER = 'Search chats, terminals, workspaces, tasks, settings, and actions...'
|
||||
|
||||
type PaletteFilterFixture = {
|
||||
localRepoId: string
|
||||
localWorktreeId: string
|
||||
remoteWorktreeId: string
|
||||
remoteHostId: ExecutionHostId
|
||||
}
|
||||
|
||||
async function seedPaletteFilterFixture(page: Page): Promise<PaletteFilterFixture> {
|
||||
return page.evaluate(
|
||||
async ({ localProject, remoteHost, remoteProject, remoteWorkspace }) => {
|
||||
const store = window.__store
|
||||
if (!store) {
|
||||
throw new Error('window.__store is unavailable')
|
||||
}
|
||||
|
||||
const sourceRepo = store.getState().repos[0]
|
||||
if (
|
||||
!sourceRepo ||
|
||||
!(await store.getState().updateRepo(sourceRepo.id, { displayName: localProject }))
|
||||
) {
|
||||
throw new Error('Failed to persist the local palette fixture name')
|
||||
}
|
||||
const state = store.getState()
|
||||
const sourceWorktree = Object.values(state.worktreesByRepo)
|
||||
.flat()
|
||||
.find((worktree) => worktree.repoId === sourceRepo?.id && !worktree.isArchived)
|
||||
if (!sourceRepo || !sourceWorktree) {
|
||||
throw new Error('Palette filter E2E needs the seeded local repository')
|
||||
}
|
||||
|
||||
const token = crypto.randomUUID()
|
||||
const remoteConnectionId = `e2e-palette-host-${token}`
|
||||
const remoteRepoId = `e2e-palette-remote-repo-${token}`
|
||||
const remoteWorktreeId = `e2e-palette-remote-worktree-${token}`
|
||||
const remoteHostId = `ssh:${remoteConnectionId}` as const
|
||||
const remoteRepo = {
|
||||
...sourceRepo,
|
||||
id: remoteRepoId,
|
||||
path: `${sourceRepo.path}-e2e-palette-remote-${token}`,
|
||||
displayName: remoteProject,
|
||||
connectionId: remoteConnectionId,
|
||||
executionHostId: remoteHostId
|
||||
}
|
||||
const remoteWorktree = {
|
||||
...sourceWorktree,
|
||||
id: remoteWorktreeId,
|
||||
repoId: remoteRepoId,
|
||||
path: `${sourceWorktree.path}-e2e-palette-remote-${token}`,
|
||||
displayName: remoteWorkspace,
|
||||
title: remoteWorkspace,
|
||||
branch: 'refs/heads/e2e-palette-remote',
|
||||
isMainWorktree: false,
|
||||
isArchived: false,
|
||||
hostId: remoteHostId
|
||||
}
|
||||
|
||||
const sshTargetLabels = new Map(state.sshTargetLabels)
|
||||
sshTargetLabels.set(remoteConnectionId, remoteHost)
|
||||
store.setState({
|
||||
repos: [...state.repos, remoteRepo],
|
||||
sshTargetLabels,
|
||||
worktreesByRepo: {
|
||||
...state.worktreesByRepo,
|
||||
[sourceRepo.id]: (state.worktreesByRepo[sourceRepo.id] ?? []).map((worktree) =>
|
||||
worktree.id === sourceWorktree.id ? { ...worktree, hostId: 'local' } : worktree
|
||||
),
|
||||
[remoteRepoId]: [remoteWorktree]
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
localRepoId: sourceRepo.id,
|
||||
localWorktreeId: sourceWorktree.id,
|
||||
remoteWorktreeId,
|
||||
remoteHostId
|
||||
}
|
||||
},
|
||||
{
|
||||
localProject: LOCAL_PROJECT,
|
||||
remoteHost: REMOTE_HOST,
|
||||
remoteProject: REMOTE_PROJECT,
|
||||
remoteWorkspace: REMOTE_WORKSPACE
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
function worktreeRow(page: Page, worktreeId: string, hostId: ExecutionHostId = 'local') {
|
||||
const rowId = encodePaletteIdentity([
|
||||
'worktree',
|
||||
getPaletteWorktreeIdentity({ id: worktreeId, hostId })
|
||||
])
|
||||
return palette(page).locator(`[cmdk-item][data-value=${JSON.stringify(rowId)}]`)
|
||||
}
|
||||
|
||||
function palette(page: Page) {
|
||||
return page.getByRole('dialog', { name: 'Jump to...' })
|
||||
}
|
||||
|
||||
function filterTrigger(page: Page) {
|
||||
return page.getByRole('button', { name: 'Filter results' })
|
||||
}
|
||||
|
||||
async function openPalette(page: Page): Promise<void> {
|
||||
await page.evaluate(() => window.__store?.getState().openModal('worktree-palette'))
|
||||
await expect(palette(page)).toBeVisible()
|
||||
}
|
||||
|
||||
async function searchFixtureWorkspaces(page: Page, fixture: PaletteFilterFixture): Promise<void> {
|
||||
const input = palette(page).getByPlaceholder(SEARCH_PLACEHOLDER)
|
||||
await input.fill('E2E Palette')
|
||||
await expect(worktreeRow(page, fixture.localWorktreeId)).toBeVisible()
|
||||
await expect(worktreeRow(page, fixture.remoteWorktreeId, fixture.remoteHostId)).toBeVisible()
|
||||
}
|
||||
|
||||
async function selectRemoteHost(page: Page, useKeyboard = false): Promise<void> {
|
||||
if (useKeyboard) {
|
||||
const input = palette(page).getByPlaceholder(SEARCH_PLACEHOLDER)
|
||||
await input.press('Tab')
|
||||
await expect(filterTrigger(page)).toBeFocused()
|
||||
await filterTrigger(page).click()
|
||||
} else {
|
||||
await filterTrigger(page).click()
|
||||
}
|
||||
|
||||
await expect(palette(page).getByText('Hosts', { exact: true })).toBeVisible()
|
||||
await palette(page).getByText('Hosts', { exact: true }).click()
|
||||
const hosts = palette(page).getByRole('listbox', { name: 'Hosts' })
|
||||
await expect(hosts.getByRole('option', { name: REMOTE_HOST })).toBeVisible()
|
||||
await hosts.getByRole('option', { name: REMOTE_HOST }).click()
|
||||
await filterTrigger(page).click()
|
||||
}
|
||||
|
||||
async function openComposerFromTypedName(page: Page): Promise<Locator> {
|
||||
await openPalette(page)
|
||||
const input = palette(page).getByPlaceholder(SEARCH_PLACEHOLDER)
|
||||
await input.fill(`cmd-j-enter-${Date.now()}`)
|
||||
await expect(palette(page).locator('[cmdk-item][data-value="__create_worktree__"]')).toBeVisible()
|
||||
|
||||
await input.press('Enter')
|
||||
|
||||
const createDialog = page.getByRole('dialog', { name: /Create (Workspace|Worktree)/i })
|
||||
await expect(createDialog).toBeVisible()
|
||||
// Require autofocus: Escape must dismiss in one press even when the user never chose the name input.
|
||||
await expect(createDialog.locator('[data-workspace-name-input="true"]')).toBeFocused()
|
||||
return createDialog
|
||||
}
|
||||
|
||||
test.describe('Worktree jump-palette filters', () => {
|
||||
test.beforeEach(async ({ orcaPage }) => {
|
||||
await waitForSessionReady(orcaPage)
|
||||
await waitForActiveWorktree(orcaPage)
|
||||
})
|
||||
test.afterEach(async ({ orcaPage }) => {
|
||||
await orcaPage.evaluate(() => {
|
||||
const store = window.__store?.getState()
|
||||
store?.setFilterRepoIds([])
|
||||
store?.closeModal()
|
||||
})
|
||||
})
|
||||
|
||||
test('filters results, intersects fields, and reseeds from the sidebar on reopen', async ({
|
||||
orcaPage
|
||||
}) => {
|
||||
const fixture = await seedPaletteFilterFixture(orcaPage)
|
||||
await openPalette(orcaPage)
|
||||
await searchFixtureWorkspaces(orcaPage, fixture)
|
||||
|
||||
// P1: keyboard focus reaches the control; its rendered selection narrows rows.
|
||||
await selectRemoteHost(orcaPage, true)
|
||||
await expect(filterTrigger(orcaPage)).toContainText('1')
|
||||
await expect(palette(orcaPage).getByLabel(`Remove filter ${REMOTE_HOST}`)).toBeVisible()
|
||||
await expect(
|
||||
worktreeRow(orcaPage, fixture.remoteWorktreeId, fixture.remoteHostId)
|
||||
).toBeVisible()
|
||||
await expect(worktreeRow(orcaPage, fixture.localWorktreeId)).toHaveCount(0)
|
||||
|
||||
// P2: host and repository fields intersect, with the filter-specific empty state.
|
||||
await palette(orcaPage).getByPlaceholder(SEARCH_PLACEHOLDER).fill('')
|
||||
await filterTrigger(orcaPage).click()
|
||||
await palette(orcaPage).getByText('Projects', { exact: true }).click()
|
||||
const projects = palette(orcaPage).getByRole('listbox', { name: 'Projects' })
|
||||
const localProject = projects.getByRole('option', { name: LOCAL_PROJECT })
|
||||
await expect(localProject).toBeVisible()
|
||||
await localProject.click()
|
||||
await filterTrigger(orcaPage).click()
|
||||
await expect(palette(orcaPage).getByText('No results match the active filter')).toBeVisible()
|
||||
await expect(
|
||||
palette(orcaPage).getByText('Clear the filter above, or widen it to more hosts and projects.')
|
||||
).toBeVisible()
|
||||
|
||||
// P3: clear restores both rows; reopening replaces ephemeral state with the sidebar scope.
|
||||
await filterTrigger(orcaPage).click()
|
||||
await palette(orcaPage).getByRole('button', { name: 'Clear all' }).last().click()
|
||||
await filterTrigger(orcaPage).click()
|
||||
await expect(filterTrigger(orcaPage)).not.toContainText('1')
|
||||
await searchFixtureWorkspaces(orcaPage, fixture)
|
||||
|
||||
await selectRemoteHost(orcaPage)
|
||||
await orcaPage.evaluate((repoId) => {
|
||||
const store = window.__store?.getState()
|
||||
store?.closeModal()
|
||||
store?.setFilterRepoIds([repoId])
|
||||
}, fixture.localRepoId)
|
||||
await expect(palette(orcaPage)).toBeHidden()
|
||||
await openPalette(orcaPage)
|
||||
await palette(orcaPage).getByPlaceholder(SEARCH_PLACEHOLDER).fill('E2E Palette')
|
||||
await expect(filterTrigger(orcaPage)).toContainText('1')
|
||||
await expect(worktreeRow(orcaPage, fixture.localWorktreeId)).toBeVisible()
|
||||
await expect(worktreeRow(orcaPage, fixture.remoteWorktreeId, fixture.remoteHostId)).toHaveCount(
|
||||
0
|
||||
)
|
||||
})
|
||||
|
||||
test('Escape closes the composer opened over the Automations page', async ({ orcaPage }) => {
|
||||
// Keep an underlying page capture listener: it runs before Radix document capture, and preventDefault there can veto Cmd+J palette dismissal.
|
||||
await orcaPage.evaluate(() => window.__store?.getState().openAutomationsPage())
|
||||
const automationsHeading = orcaPage.getByRole('heading', { name: 'Automations', level: 1 })
|
||||
await expect(automationsHeading).toBeVisible()
|
||||
|
||||
const createDialog = await openComposerFromTypedName(orcaPage)
|
||||
|
||||
await orcaPage.keyboard.press('Escape')
|
||||
|
||||
await expect(createDialog).toBeHidden()
|
||||
// The page declined the press rather than consuming it, so it is still open.
|
||||
await expect(automationsHeading).toBeVisible()
|
||||
})
|
||||
})
|
||||
@@ -1,80 +0,0 @@
|
||||
import { expect, test } from './helpers/orca-app'
|
||||
import { waitForActiveWorktree, waitForSessionReady } from './helpers/store'
|
||||
import { startBrowserLinkServer } from './helpers/browser-link-server'
|
||||
|
||||
for (const theme of ['light', 'dark'] as const) {
|
||||
test(`Cmd+J offers a website first and opens it with Enter (${theme})`, async ({
|
||||
orcaPage,
|
||||
electronApp
|
||||
}, testInfo) => {
|
||||
await waitForSessionReady(orcaPage)
|
||||
await waitForActiveWorktree(orcaPage)
|
||||
await orcaPage.evaluate(async (theme) => {
|
||||
const state = window.__store!.getState()
|
||||
await state.updateSettingsOrThrow({ theme })
|
||||
state.openModal('worktree-palette')
|
||||
}, theme)
|
||||
const palette = orcaPage.getByRole('dialog', { name: 'Jump to...' })
|
||||
const input = palette.locator('[cmdk-input]')
|
||||
const website = palette.locator('[cmdk-item][data-value="quick-action:navigate-to-url"]')
|
||||
await input.fill('brex.com')
|
||||
await expect(website).toContainText('Go to brex.com')
|
||||
await expect(website).toContainText('Open in a new browser tab')
|
||||
await expect(website).toHaveAttribute('data-selected', 'true')
|
||||
await expect(palette.locator('[cmdk-item]').first()).toContainText('Go to brex.com')
|
||||
const screenshot = testInfo.outputPath(`website-palette-${theme}.png`)
|
||||
await palette.screenshot({ path: screenshot, animations: 'disabled' })
|
||||
await testInfo.attach(`website-palette-${theme}`, {
|
||||
path: screenshot,
|
||||
contentType: 'image/png'
|
||||
})
|
||||
|
||||
await input.fill('brex login')
|
||||
await expect(website).toHaveCount(0)
|
||||
|
||||
await input.fill('readthedocs.io')
|
||||
await expect(website).toContainText('Go to readthedocs.io')
|
||||
await expect(website).toHaveAttribute('data-selected', 'true')
|
||||
|
||||
await orcaPage.evaluate(() => {
|
||||
window.__store!.setState((state) => ({
|
||||
worktreesByRepo: Object.fromEntries(
|
||||
Object.entries(state.worktreesByRepo).map(([repoId, worktrees]) => [
|
||||
repoId,
|
||||
worktrees.map((worktree) =>
|
||||
worktree.id === state.activeWorktreeId
|
||||
? { ...worktree, displayName: 'project.dev server' }
|
||||
: worktree
|
||||
)
|
||||
])
|
||||
)
|
||||
}))
|
||||
})
|
||||
await input.fill('project.dev')
|
||||
await expect(palette.locator('[cmdk-item]').first()).toContainText('Go to project.dev')
|
||||
await expect(website).toHaveAttribute('data-selected', 'true')
|
||||
|
||||
const server = await startBrowserLinkServer()
|
||||
try {
|
||||
const address = server.sourceUrl.replace('http://', '')
|
||||
await input.fill(address)
|
||||
await expect(website).toContainText(`Go to ${address}`)
|
||||
await expect(website).toHaveAttribute('data-selected', 'true')
|
||||
await input.press('Enter')
|
||||
await expect(palette).toHaveCount(0)
|
||||
await expect(
|
||||
orcaPage.locator('[data-orca-browser-address-bar="true"]').filter({ visible: true })
|
||||
).toHaveValue(server.sourceUrl)
|
||||
await expect(
|
||||
orcaPage.locator('[data-tab-id]').filter({ hasText: 'Source page' }).first()
|
||||
).toBeVisible()
|
||||
expect(
|
||||
await electronApp.evaluate(({ BrowserWindow }) =>
|
||||
BrowserWindow.getAllWindows().every((window) => !window.isVisible())
|
||||
)
|
||||
).toBe(true)
|
||||
} finally {
|
||||
await server.close()
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user