test: retire low-value browser CLI and UI suites (#42462)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-14 11:18:32 -08:00
committed by GitHub
co-authored by OrcaWin
parent 85f8ff358e
commit aee2f8abe9
15 changed files with 2 additions and 820 deletions
@@ -4094,10 +4094,8 @@
"src/renderer/src/components/JiraIssueWorkspace.optimistic-edit.test.tsx": 2340,
"src/renderer/src/components/JiraIssueWorkspace.status-queue.test.tsx": 1852,
"src/renderer/src/components/JiraIssueWorkspace.transition-source.test.tsx": 1843,
"src/renderer/src/components/NewWorkspaceComposerCard.quick-file-drop.test.tsx": 4557,
"src/renderer/src/components/NewWorkspaceComposerCard.set-location.test.tsx": 1301,
"src/renderer/src/components/SelectedTextCopyMenu.test.tsx": 329,
"src/renderer/src/components/TerminalSearch.test.tsx": 458,
"src/renderer/src/components/UpdateCard.error-card.test.tsx": 2851,
"src/renderer/src/components/UpdateCard.test.ts": 694,
"src/renderer/src/components/WorktreeBaseFallbackDialog.test.tsx": 2104,
@@ -1,69 +1,6 @@
import { describe, expect, it } from 'vitest'
import { normalizeCommandPositionals, parseArgs, validateCommandAndFlags } from '../arguments/args'
import type { CommandSpec } from './command-spec'
import { suggestCommands, unknownCommandData } from './command-suggestion'
import { COMMAND_SPECS } from '../specs/index'
const blocked = [
['orchestration resume', 'orchestration reset'],
['orchestration rerun', 'orchestration reset'],
['orchestration repl', 'orchestration reset'],
['artifacts deset', 'artifacts delete'],
['emulator ball', 'emulator kill'],
['emulator showdown', 'emulator shutdown'],
['orchestration worker-showw', 'orchestration worker-stop'],
['orchestration worker-state', 'orchestration worker-stop'],
['orchestration worker-relay', 'orchestration worker-release'],
['orchestration worker-reuse', 'orchestration worker-release'],
['tab clues', 'tab close'],
['linear relation move', 'linear relation remove'],
['environment rollbook', 'environment rollback']
]
const recovery = [
['orchestration rese', 'orchestration reset'],
['orchestration rest', 'orchestration reset'],
['emulator kil', 'emulator kill'],
['emulator shutdow', 'emulator shutdown'],
['orchestration worker-stp', 'orchestration worker-stop'],
['orchestration worker-releasee', 'orchestration worker-release'],
['tab clos', 'tab close'],
['tab clone', 'tab close'],
['environment rollbac', 'environment rollback'],
['environment remov', 'environment rm'],
['artifacts delet', 'artifacts delete'],
['worktree remov', 'worktree remove'],
['worktree delet', 'worktree delete'],
['orchestration chek', 'orchestration check'],
['linear relation remov', 'linear relation remove'],
['linear label remov', 'linear label remove'],
['capture stp', 'capture stop'],
['clea', 'clear']
]
describe('live destructive command recovery', () => {
it.each(blocked)('does not turn %s into %s', (input, destructive) => {
const path = input.split(' ')
const data = unknownCommandData(COMMAND_SPECS, path)
expect(data.suggestions).not.toContain(destructive)
expect(data.nextSteps.join(' ')).not.toContain(`orca ${destructive}`)
const parsed = normalizeCommandPositionals(COMMAND_SPECS, parseArgs(path))
expect(() => validateCommandAndFlags(COMMAND_SPECS, parsed)).toThrow('Unknown command')
})
it.each(recovery)('still recovers %s as %s', (input, expected) => {
const data = unknownCommandData(COMMAND_SPECS, input.split(' '))
expect(data.suggestions).toContain(expected)
expect(data.nextSteps.join(' ')).toContain(`orca ${expected}`)
})
it('retains the complete legitimate environment removal ranking', () => {
expect(suggestCommands(COMMAND_SPECS, ['environment', 'remov'])).toEqual([
'environment recover',
'environment rm'
])
})
})
import { suggestCommands } from './command-suggestion'
function destructiveSpec(path: string[], aliases?: string[][]): CommandSpec {
return { path, aliases, destructive: true, summary: '', usage: '', allowedFlags: [] }
@@ -1,58 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { CommandSpec } from './command-spec'
import { suggestCommands } from './command-suggestion'
const specs: CommandSpec[] = [
{
path: ['worktree', 'rm'],
aliases: [
['worktree', 'remove'],
['worktree', 'delete']
],
destructive: true,
summary: 'Remove a worktree',
usage: 'orca worktree rm',
allowedFlags: []
},
{
path: ['worktree', 'list'],
summary: 'List worktrees',
usage: 'orca worktree list',
allowedFlags: []
},
{
path: ['terminal', 'send'],
summary: 'Send input',
usage: 'orca terminal send',
allowedFlags: []
},
{
path: ['emulator', 'kill'],
destructive: true,
summary: 'Kill the emulator',
usage: 'orca emulator kill',
allowedFlags: []
},
{
path: ['terminal', 'stop'],
hidden: true,
summary: 'Deprecated terminal stop',
usage: 'orca terminal stop',
allowedFlags: []
}
]
describe('suggestCommands', () => {
it('never suggests a destructive command for a benign non-destructive typo', () => {
const result = suggestCommands(specs, ['worktree', 'move'])
expect(result).not.toContain('worktree remove')
expect(result).not.toContain('worktree rm')
expect(result).not.toContain('worktree delete')
})
it('guards destructive commands outside the delete-family via the spec flag', () => {
expect(suggestCommands(specs, ['emulator', 'ball'])).not.toContain('emulator kill')
expect(suggestCommands(specs, ['emulator', 'kil'])).toContain('emulator kill')
})
})
-57
View File
@@ -1,57 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
vi.mock('../runtime/client', () => {
class RuntimeClient {
readonly isRemote = false
call = callMock
getCliStatus = vi.fn()
openOrca = vi.fn()
}
return { RuntimeClient }
})
import { main } from '../index'
import { buildWorktree, okFixture, queueFixtures } from '../runtime/fixtures/runtime-rpc-fixtures'
describe('absolute file CLI paths', () => {
beforeEach(() => {
vi.restoreAllMocks()
callMock.mockReset()
process.exitCode = undefined
// Prevent a real WSL_DISTRO_NAME from enabling the rewrite in unrelated cases.
vi.stubEnv('WSL_DISTRO_NAME', '')
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
vi.unstubAllEnvs()
})
describe('WSL UNC worktree roots', () => {
const uncRoot = '//wsl.localhost/Ubuntu/root/orca/workspaces/xxx'
async function openPath(path: string, cwd = '/tmp'): Promise<void> {
await main(['file', 'open', '--path', path, '--worktree', 'id:wt-1'], cwd)
}
it('rejects the UNC worktree root itself typed as a Linux path', async () => {
vi.stubEnv('WSL_DISTRO_NAME', 'Ubuntu')
queueFixtures(
callMock,
okFixture('req_show', { worktree: buildWorktree(uncRoot, 'feature') })
)
await openPath('/root/orca/workspaces/xxx')
expect(process.exitCode).toBe(1)
expect(console.error).toHaveBeenCalledWith(
'The selected worktree root is a directory, not a file-open target.'
)
expect(callMock).toHaveBeenCalledTimes(1)
})
})
})
-24
View File
@@ -88,28 +88,4 @@ describe('command aliases dispatch to the canonical handler', () => {
process.exitCode = priorExitCode
}
})
it('rejects the archive-hook waiver without --run-hooks instead of ignoring it', async () => {
queueFixtures(callMock, okFixture('req_show', { worktree: { hostId: 'local' } }))
const priorExitCode = process.exitCode
try {
await main(
['worktree', 'rm', '--worktree', 'id:wt-1', '--allow-failed-archive-hook', '--json'],
'/tmp/repo'
)
expect(process.exitCode).toBe(1)
expect(callMock).not.toHaveBeenCalledWith('worktree.rm', expect.anything())
expect(JSON.parse(String(logSpy.mock.calls.at(-1)?.[0]))).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message: expect.stringContaining('without --run-hooks no hook runs at all')
}
})
} finally {
process.exitCode = priorExitCode
}
})
})
-98
View File
@@ -64,26 +64,6 @@ describe('orchestration agent views', () => {
vi.restoreAllMocks()
})
it('makes a failed worker-start impossible to miss on stdout, stderr, and the exit code', async () => {
const { stdout, stderr } = await run('worker-start', [['task', 'task_1']], {
...OLDER_RUNTIME_START,
state: 'failed',
failedStage: 'agent_ready',
lastError: 'Agent did not reach a ready prompt within 60000ms.',
residualResources: [{ kind: 'terminal', id: 'term_agent', ownership: 'owned' }],
recovery: 'Close it with: orca orchestration worker-release --dispatch ctx_1'
})
expect(stdout).toBe(
'dispatchId=ctx_1 taskId=task_1 runId=run_1 state=failed terminal=term_agent workspace=wt_1::/repo failedStage=agent_ready lastError="Agent did not reach a ready prompt within 60000ms." residualResources="terminal term_agent"\n' +
'Next: Close it with: orca-dev orchestration worker-release --dispatch ctx_1'
)
expect(stderr).toBe(
'error: start_failed: agent_ready: Agent did not reach a ready prompt within 60000ms.'
)
expect(process.exitCode).toBe(1)
})
it('escapes terminal control bytes in worker-written fields', async () => {
const { stdout } = await run('worker-start', [['task', 'task_1']], {
...OLDER_RUNTIME_START,
@@ -135,68 +115,6 @@ describe('orchestration agent views', () => {
expect(process.exitCode).toBeUndefined()
})
it('asks an older host to release only reclaimable finished workers', async () => {
const worker = { taskId: 'task_1', runId: 'run_1', workerState: 'succeeded' }
const { stdout } = await run(
'worker-list',
[['run', 'run_1']],
{
workers: [
{ ...worker, dispatchId: 'ctx_done', terminalState: 'reclaimable', resource: null },
{ ...worker, dispatchId: 'ctx_kept', terminalState: 'retained', resource: null }
],
counts: {}
},
true
)
const [done, kept] = JSON.parse(stdout).result.workers
expect(done.next).toContain('orchestration worker-release --dispatch ctx_done')
expect(kept.next).toBeUndefined()
})
it('keeps --full ask output and exit exactly as before', async () => {
callMock.mockImplementation(async (method: string) =>
method === 'status.get'
? { result: { capabilities: [] } }
: {
result: {
answer: null,
messageId: 'msg_q',
threadId: 'msg_q',
timedOut: true,
timeoutMs: 1000
}
}
)
const log = vi
.spyOn(console, 'log')
.mockClear()
.mockImplementation(() => {})
const error = vi
.spyOn(console, 'error')
.mockClear()
.mockImplementation(() => {})
await ORCHESTRATION_HANDLERS['orchestration ask'](
orchestrationTestContext(
callMock,
new Map<string, string | boolean>([
['question', 'Proceed?'],
['from', 'term_worker'],
['full', true]
]),
false
)
)
expect(log).not.toHaveBeenCalled()
expect(error.mock.calls).toEqual([
[
'ask timeout after 1000ms; question is still pending (messageId: msg_q). Resume waiting; do not ask again:\norca-dev orchestration ask --from term_worker --resume msg_q --timeout-ms 1000'
]
])
expect(process.exitCode).toBe(1)
})
it('frames an unobserved turn start as a slow worker, not a failure to retry', async () => {
const { stdout, stderr } = await run('worker-start', [['task', 'task_1']], {
...OLDER_RUNTIME_START,
@@ -277,22 +195,6 @@ describe('orchestration agent views', () => {
expect(result.formatted).toBeUndefined()
})
it('marks a failed concise JSON receipt ok:false and keeps its fields', async () => {
const { stdout } = await run(
'worker-list',
[['run', 'run_1']],
{
workers: [],
counts: {},
partialHostErrors: [
{ environmentId: 'env_1', name: 'linux', code: 'unreachable', dispatchIds: [] }
]
},
true
)
expect(JSON.parse(stdout)).toMatchObject({ ok: false, result: { workers: [] } })
})
it('never lets a payload stand in for Orca-computed message fields', async () => {
const { stdout } = await run('check', [['run', 'run_1']], {
messages: [
@@ -80,40 +80,8 @@ describe('browser file channel reconnect degradation', () => {
expect(attempts[1]!.sendRequest).toHaveBeenCalledOnce()
await lease.close()
})
it('ignores a superseded connection failure and reports no channel once closed', async () => {
const attempts = mockAttempts()
const onError = vi.fn()
const lease = createLease({ onError })
const starting = lease.start()
await vi.waitFor(() => expect(attempts).toHaveLength(1))
attempts[0]!.callbacks.onResponse(readyResponse({ fileChannel: true }))
await starting
attempts[0]!.callbacks.onError(recoverableError())
await vi.waitFor(() => expect(attempts).toHaveLength(2))
attempts[1]!.callbacks.onResponse(readyResponse({ fileChannel: true }))
await vi.waitFor(() => expect(lease.fileChannelNegotiated).toBe(true))
attempts[0]!.callbacks.onError(new RemoteRuntimeClientError('bad_request', 'superseded'))
await flushMicrotasks()
expect(onError).not.toHaveBeenCalled()
expect(lease.fileChannelNegotiated).toBe(true)
await lease.close()
expect(lease.fileChannelNegotiated).toBe(false)
expect(() =>
lease.sendFileChannelRequest('browser.clientHost.fileChannel.read', {}, 10)
).toThrow('Remote runtime browser file channel is unavailable.')
})
})
async function flushMicrotasks(): Promise<void> {
for (let index = 0; index < 10; index += 1) {
await Promise.resolve()
}
}
function createLease(overrides: {
onError?: (error: Error) => void
onReconnected?: (authority: unknown) => void
@@ -95,7 +95,7 @@ function fileServices(root: string) {
}
}
})
return { buffers, staging, transport, requests: () => requests }
return { buffers, staging, transport }
}
async function startUpload(root: string) {
@@ -148,7 +148,6 @@ it.each(['resolve', 'reject', 'page-release'] as const)(
await collect()
const pendingBuffers = upload.buffers.filter((buffer) => buffer.deref()).length
expect(upload.buffers).toHaveLength(2)
expect(upload.requests()).toBe(8)
expect(upload.params).toEqual({ element: '#upload', files: remotePaths })
expect(upload.staging.activeStagingCount()).toBe(1)
await expectStagedBytes(upload.localPaths)
@@ -1,29 +0,0 @@
import { existsSync } from 'node:fs'
import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { BrowserClientUploadStaging } from './browser-client-upload-staging'
let stagingRoot = ''
beforeEach(async () => {
// Resolve macOS /var aliases so path assertions use the real root.
stagingRoot = await realpath(await mkdtemp(path.join(tmpdir(), 'orca-upload-staging-')))
})
afterEach(async () => {
await rm(stagingRoot, { recursive: true, force: true })
})
describe('BrowserClientUploadStaging', () => {
it('sweeps staged bytes an abnormal exit left in the root', async () => {
const orphan = path.join(stagingRoot, 'abandoned', '0')
await mkdir(orphan, { recursive: true })
await writeFile(path.join(orphan, 'report.pdf'), 'remote-bytes')
new BrowserClientUploadStaging(stagingRoot)
expect(existsSync(path.join(stagingRoot, 'abandoned'))).toBe(false)
})
})
@@ -22,29 +22,4 @@ describe('fetchBrowserClientUploadFiles', () => {
})
).rejects.toThrow('browser_client_upload_transfer_stalled')
})
it('rejects a chunk whose declared length does not match its bytes', async () => {
await expect(
fetchBrowserClientUploadFiles({
request: async () => ({
contentBase64: Buffer.from('abc').toString('base64'),
bytesRead: 99,
totalBytes: 99,
eof: true
}),
event,
remotePaths: ['a.txt']
})
).rejects.toThrow('browser_client_upload_chunk_invalid')
})
it('rejects a request naming more files than the command budget allows', async () => {
await expect(
fetchBrowserClientUploadFiles({
request: async () => ({ contentBase64: '', bytesRead: 0, totalBytes: 0, eof: true }),
event,
remotePaths: Array.from({ length: 17 }, (_unused, index) => `${index}.txt`)
})
).rejects.toThrow('browser_client_upload_file_count_exceeded')
})
})
@@ -1,59 +0,0 @@
import { mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import {
browserHostClientIdentityPath,
readOrCreateBrowserHostClientId
} from './browser-host-client-identity'
function profileDirectory(): string {
return mkdtempSync(join(tmpdir(), 'orca-host-identity-'))
}
describe('browser host client identity', () => {
it('keeps one hosting identity across relaunches of the same profile', () => {
const directory = profileDirectory()
const first = readOrCreateBrowserHostClientId(directory)
const second = readOrCreateBrowserHostClientId(directory)
expect(second).toBe(first)
expect(first).toMatch(/^[0-9a-f-]{36}$/)
})
it('gives each Orca profile its own hosting identity', () => {
expect(readOrCreateBrowserHostClientId(profileDirectory())).not.toBe(
readOrCreateBrowserHostClientId(profileDirectory())
)
})
it.each([
['unparseable content', 'not json at all'],
['a future store version', JSON.stringify({ version: 2, browserHostClientId: 'kept' })],
['a missing identity', JSON.stringify({ version: 1 })],
['a non-string identity', JSON.stringify({ version: 1, browserHostClientId: 7 })],
['an empty identity', JSON.stringify({ version: 1, browserHostClientId: '' })],
[
'an identity past the wire limit',
JSON.stringify({ version: 1, browserHostClientId: 'x'.repeat(257) })
]
])('mints a fresh identity rather than trusting %s', (_label, contents) => {
const directory = profileDirectory()
writeFileSync(browserHostClientIdentityPath(directory), contents)
const identity = readOrCreateBrowserHostClientId(directory)
expect(identity).toMatch(/^[0-9a-f-]{36}$/)
expect(readOrCreateBrowserHostClientId(directory)).toBe(identity)
})
it('still names the host when the profile cannot be written', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const file = join(profileDirectory(), 'occupied')
writeFileSync(file, 'not a directory')
expect(readOrCreateBrowserHostClientId(join(file, 'nested'))).toMatch(/^[0-9a-f-]{36}$/)
expect(warn).toHaveBeenCalled()
})
})
@@ -1,74 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { BrowserClientHostAuthorityReplacementWait } from './browser-client-host-authority-replacement-wait'
describe('BrowserClientHostAuthorityReplacementWait', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('expires exactly once, at the grace deadline', () => {
const wait = new BrowserClientHostAuthorityReplacementWait(1_000)
const expire = vi.fn()
wait.arm(expire)
expect(wait.armed).toBe(true)
vi.advanceTimersByTime(999)
expect(expire).not.toHaveBeenCalled()
vi.advanceTimersByTime(1)
expect(expire).toHaveBeenCalledOnce()
expect(wait.armed).toBe(false)
vi.advanceTimersByTime(10_000)
expect(expire).toHaveBeenCalledOnce()
})
// Bursts of mismatch errors must not postpone retirement indefinitely.
it('keeps the first deadline when armed again while already armed', () => {
const wait = new BrowserClientHostAuthorityReplacementWait(1_000)
const first = vi.fn()
const second = vi.fn()
wait.arm(first)
vi.advanceTimersByTime(900)
wait.arm(second)
vi.advanceTimersByTime(100)
expect(first).toHaveBeenCalledOnce()
expect(second).not.toHaveBeenCalled()
})
it('never expires after a cancel', () => {
const wait = new BrowserClientHostAuthorityReplacementWait(1_000)
const expire = vi.fn()
wait.arm(expire)
wait.cancel()
expect(wait.armed).toBe(false)
vi.advanceTimersByTime(10_000)
expect(expire).not.toHaveBeenCalled()
})
it('is re-armable after a cancel and after an expiry', () => {
const wait = new BrowserClientHostAuthorityReplacementWait(1_000)
const cancelled = vi.fn()
const rearmed = vi.fn()
wait.arm(cancelled)
wait.cancel()
wait.arm(rearmed)
vi.advanceTimersByTime(1_000)
expect(cancelled).not.toHaveBeenCalled()
expect(rearmed).toHaveBeenCalledOnce()
const afterExpiry = vi.fn()
wait.arm(afterExpiry)
vi.advanceTimersByTime(1_000)
expect(afterExpiry).toHaveBeenCalledOnce()
})
})
@@ -1,113 +0,0 @@
// @vitest-environment happy-dom
import { act, cleanup, render, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useAppStore } from '@/store'
import { useComposerState } from '@/hooks/useComposerState'
import NewWorkspaceComposerCard from './NewWorkspaceComposerCard'
import { TooltipProvider } from '@/components/ui/tooltip'
import type * as I18nModule from '@/i18n/i18n'
import type * as ReactI18nextModule from 'react-i18next'
vi.mock('@/components/contextual-tours/use-contextual-tour', () => ({
useContextualTour: () => {}
}))
vi.mock('@/i18n/i18n', async (importOriginal) => ({
...(await importOriginal<typeof I18nModule>()),
translate: (_key: string, fallback: string) => fallback
}))
vi.mock('react-i18next', async (importOriginal) => ({
...(await importOriginal<typeof ReactI18nextModule>()),
useTranslation: () => ({})
}))
const prepare = vi.fn(async ({ paths }: { paths: string[] }) => ({ paths, failures: [] }))
const stat = vi.fn(async () => ({ isDirectory: false }))
beforeEach(() => {
vi.clearAllMocks()
vi.stubGlobal('api', {
fs: {
getPathForFile: (file: File) => `/drop/${file.name}`,
prepareDroppedPaths: prepare,
stat
},
gh: {
repoSlug: vi.fn(async () => null),
listWorkItems: vi.fn(async () => ({ items: [], hasMore: false }))
},
sparsePresets: { list: vi.fn(async () => []) },
worktrees: { listRetiredNames: vi.fn(async () => ({ names: [], exhaustedTiers: 0 })) },
preflight: { detectAgents: vi.fn(async () => []) }
})
useAppStore.setState({
repos: [
{
id: 'local-project',
path: '/project',
displayName: 'Project',
badgeColor: 'var(--muted-foreground)',
addedAt: 0
}
],
activeRepoId: 'local-project',
activeModal: 'new-workspace-composer',
projects: [],
projectGroups: [],
projectHostSetups: [],
newWorkspaceDraft: null,
worktreesByRepo: {},
sparsePresetsByRepo: {}
})
})
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
})
type FileDragTransfer = { types: string[]; files: File[]; dropEffect: string }
function gesture(target: Element, type: string, transfer: FileDragTransfer) {
const event = new Event(type, { bubbles: true, cancelable: true, composed: true })
Object.defineProperty(event, 'isTrusted', { value: true })
Object.defineProperty(event, 'dataTransfer', { value: transfer })
target.dispatchEvent(event)
}
describe('quick-create modal card without an attachment destination', () => {
it('refuses an OS drop with the selected local project and does not show an accepting ring', async () => {
const hook = renderHook(() =>
useComposerState({
initialRepoId: 'local-project',
persistDraft: false
})
)
expect(hook.result.current.cardProps.selectedRepoPath).toBe('/project')
expect(hook.result.current.cardProps.selectedRepoExecutionHostId).toBe('local')
const { container } = render(
<TooltipProvider>
<NewWorkspaceComposerCard
{...hook.result.current.cardProps}
composerRef={hook.result.current.composerRef}
onComposerNodeChange={hook.result.current.onComposerNodeChange}
onCreate={() => {}}
primaryActionLabel="Create workspace"
quickAgent={null}
onQuickAgentChange={() => {}}
/>
</TooltipProvider>
)
const card = container.querySelector('[data-workspace-composer-root]')!
expect(container.querySelector('textarea')?.getAttribute('placeholder')).toBe('Write a note')
expect(container.querySelector('[data-attachment-path]')).toBeNull()
const transfer = { types: ['Files'], files: [new File(['x'], 'notes.txt')], dropEffect: 'link' }
await act(async () => {
gesture(card, 'dragenter', transfer)
gesture(card, 'dragover', transfer)
})
expect(transfer.dropEffect).toBe('none')
expect(card.className).not.toContain('ring-2')
await act(async () => gesture(card, 'drop', transfer))
expect(prepare).not.toHaveBeenCalled()
expect(stat).not.toHaveBeenCalled()
expect(hook.result.current.cardProps.attachmentPaths).toEqual([])
})
})
@@ -1,103 +0,0 @@
// @vitest-environment happy-dom
import { act, cleanup, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { NotificationCardStack } from './NotificationCardStack'
/** A ResizeObserver that reports only what it observes, when the test resizes an element. */
class FakeResizeObserver implements ResizeObserver {
static all: FakeResizeObserver[] = []
private readonly targets = new Set<Element>()
constructor(private readonly callback: ResizeObserverCallback) {
FakeResizeObserver.all.push(this)
}
observe(target: Element): void {
this.targets.add(target)
}
unobserve(target: Element): void {
this.targets.delete(target)
}
disconnect(): void {
this.targets.clear()
}
static resize(target: Element): void {
for (const observer of FakeResizeObserver.all) {
if (observer.targets.has(target)) {
observer.callback([], observer)
}
}
}
}
function stackOf(card: HTMLElement): HTMLElement {
const stack = card.parentElement
if (!stack) {
throw new Error('card is not in a stack')
}
return stack
}
/** Pins the stack's scroll metrics; its box stays capped at 220px while content grows. */
function capStack(stack: HTMLElement, content: { height: number }): void {
Object.defineProperty(stack, 'clientHeight', { configurable: true, get: () => 220 })
Object.defineProperty(stack, 'scrollHeight', { configurable: true, get: () => content.height })
}
describe('NotificationCardStack', () => {
beforeEach(() => {
FakeResizeObserver.all = []
vi.stubGlobal('ResizeObserver', FakeResizeObserver)
})
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
})
it('starts scrolling when a card grows inside a stack already at its max height', () => {
render(
<NotificationCardStack>
<div data-testid="card" />
</NotificationCardStack>
)
const card = screen.getByTestId('card')
const stack = stackOf(card)
const content = { height: 220 }
capStack(stack, content)
act(() => FakeResizeObserver.resize(stack))
expect(stack.hasAttribute('data-overflowing')).toBe(false)
content.height = 240
act(() => FakeResizeObserver.resize(card))
expect(stack.hasAttribute('data-overflowing')).toBe(true)
})
it('watches a card that mounts after the stack', async () => {
const { rerender } = render(
<NotificationCardStack>
<div data-testid="first" />
</NotificationCardStack>
)
const stack = stackOf(screen.getByTestId('first'))
const content = { height: 200 }
capStack(stack, content)
rerender(
<NotificationCardStack>
<div data-testid="first" />
<div data-testid="second" />
</NotificationCardStack>
)
// MutationObserver delivers on a microtask.
await act(async () => {})
content.height = 260
act(() => FakeResizeObserver.resize(screen.getByTestId('second')))
expect(stack.hasAttribute('data-overflowing')).toBe(true)
})
})
@@ -1,80 +0,0 @@
// @vitest-environment happy-dom
import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react'
import type { SearchAddon } from '@xterm/addon-search'
import { afterEach, describe, expect, it, vi } from 'vitest'
import TerminalSearch from './TerminalSearch'
vi.mock('@/i18n/i18n', () => ({
translate: (_key: string, fallback: string) => fallback
}))
afterEach(cleanup)
type ResultsEvent = { resultIndex: number; resultCount: number }
function createSearchAddon() {
let listener: ((payload: ResultsEvent) => void) | null = null
const dispose = vi.fn(() => {
listener = null
})
const stub = {
findNext: vi.fn(() => true),
findPrevious: vi.fn(() => true),
clearDecorations: vi.fn(),
onDidChangeResults: (handler: (payload: ResultsEvent) => void) => {
listener = handler
return { dispose }
}
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The stub implements every addon member used by TerminalSearch.
const addon = stub as unknown as SearchAddon
return {
addon,
dispose,
emit: (payload: ResultsEvent) => act(() => listener?.(payload))
}
}
function renderSearch(searchAddon: SearchAddon, query = ''): ReturnType<typeof render> {
const view = render(
<TerminalSearch
isOpen
onClose={vi.fn()}
searchAddon={searchAddon}
searchStateRef={{ current: { query: '', caseSensitive: false, regex: false } }}
/>
)
if (query) {
fireEvent.change(view.getByPlaceholderText('Search...'), { target: { value: query } })
}
return view
}
describe('TerminalSearch cleanup', () => {
it('clears and unsubscribes the previous addon when search moves to another pane', async () => {
const previous = createSearchAddon()
const next = createSearchAddon()
const view = renderSearch(previous.addon, 'needle')
previous.emit({ resultIndex: 1, resultCount: 3 })
await waitFor(() => expect(previous.addon.findNext).toHaveBeenCalled())
vi.mocked(previous.addon.clearDecorations).mockClear()
vi.mocked(previous.addon.findNext).mockClear()
view.rerender(
<TerminalSearch
isOpen
onClose={vi.fn()}
searchAddon={next.addon}
searchStateRef={{ current: { query: '', caseSensitive: false, regex: false } }}
/>
)
expect(previous.addon.clearDecorations).toHaveBeenCalledTimes(1)
expect(previous.addon.findNext).toHaveBeenCalledWith('')
expect(previous.dispose).toHaveBeenCalledTimes(1)
next.emit({ resultIndex: 0, resultCount: 7 })
previous.emit({ resultIndex: 2, resultCount: 3 })
expect(view.getByText('1/7')).toBeTruthy()
})
})