test: remove low-value browser CLI and attention cases (#42461)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-14 11:10:21 -08:00
committed by GitHub
co-authored by OrcaWin
parent 9c7be3d42a
commit 85f8ff358e
11 changed files with 4 additions and 576 deletions
+2 -13
View File
@@ -15,12 +15,9 @@ function chatClient(isRemote: boolean): { client: RuntimeClient; call: ReturnTyp
return { client, call }
}
function rename(client: RuntimeClient, session?: string): Promise<void> {
function rename(client: RuntimeClient): Promise<void> {
return CHAT_HANDLERS['chat rename']({
flags: new Map([
['name', 'Release notes'],
...(session === undefined ? [] : [['session', session] as const])
]),
flags: new Map([['name', 'Release notes']]),
client,
cwd: '/tmp/worktree',
json: true
@@ -40,12 +37,4 @@ describe('chat rename CLI', () => {
await expect(rename(client)).rejects.toThrow('Missing required --session: on a paired host')
expect(call).not.toHaveBeenCalled()
})
it('refuses an empty --session instead of renaming the chat it runs in', async () => {
vi.stubEnv('ORCA_AGENT_SESSION_ID', 'chat-7')
const { client, call } = chatClient(false)
await expect(rename(client, '')).rejects.toThrow('Missing value for --session')
expect(call).not.toHaveBeenCalled()
})
})
@@ -1,102 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const callMock = vi.fn()
vi.mock('../runtime/client', () => {
class RuntimeClient {
call = callMock
getCliStatus = vi.fn()
openOrca = vi.fn()
}
return { RuntimeClient }
})
import { main } from '../index'
describe('orca cli storage set preserves an empty value', () => {
beforeEach(() => {
callMock.mockReset()
process.exitCode = undefined
})
afterEach(() => {
vi.restoreAllMocks()
})
// PowerShell 5.1 drops empty native arguments; equals form preserves them.
it('still rejects an empty --key before RPC dispatch', async () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const priorExitCode = process.exitCode
await main(
['storage', 'local', 'set', '--key', '', '--value', 'x', '--worktree', 'all'],
'/tmp/not-an-orca-worktree'
)
expect(callMock).not.toHaveBeenCalled()
expect(errorSpy.mock.calls.flat().join('\n')).toContain('Missing required --key')
expect(process.exitCode).toBe(1)
process.exitCode = priorExitCode
})
it('still rejects a missing --value before RPC dispatch', async () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const priorExitCode = process.exitCode
await main(
['storage', 'local', 'set', '--key', 'flag', '--worktree', 'all'],
'/tmp/not-an-orca-worktree'
)
expect(callMock).not.toHaveBeenCalled()
expect(errorSpy.mock.calls.flat().join('\n')).toContain('Missing required --value')
expect(process.exitCode).toBe(1)
process.exitCode = priorExitCode
})
})
describe('orca cli cookie set and set credentials preserve an empty value', () => {
beforeEach(() => {
callMock.mockReset()
process.exitCode = undefined
})
afterEach(() => {
vi.restoreAllMocks()
})
it('still rejects an empty --name before RPC dispatch', async () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const priorExitCode = process.exitCode
await main(
['cookie', 'set', '--name', '', '--value', 'x', '--worktree', 'all'],
'/tmp/not-an-orca-worktree'
)
expect(callMock).not.toHaveBeenCalled()
expect(errorSpy.mock.calls.flat().join('\n')).toContain('Missing required --name')
expect(process.exitCode).toBe(1)
process.exitCode = priorExitCode
})
it('still rejects a missing --pass before RPC dispatch', async () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const priorExitCode = process.exitCode
await main(
['set', 'credentials', '--user', 'token', '--worktree', 'all'],
'/tmp/not-an-orca-worktree'
)
expect(callMock).not.toHaveBeenCalled()
expect(errorSpy.mock.calls.flat().join('\n')).toContain('Missing required --pass')
expect(process.exitCode).toBe(1)
process.exitCode = priorExitCode
})
})
@@ -28,8 +28,6 @@ vi.mock('../runtime/profile/metadata', async (importOriginal) => ({
getDefaultUserDataPath: getDefaultUserDataPathMock
}))
import { BROWSER_EXPECT_URL_RUNTIME_CAPABILITY } from '../../shared/browser/runtime/browser-runtime-capabilities'
import { main } from '../index'
import { okFixture } from '../runtime/fixtures/runtime-rpc-fixtures'
@@ -69,28 +67,4 @@ describe('--expect-url', () => {
expect(callMock.mock.calls.map(([method]) => method)).toEqual(['status.get'])
expect(process.exitCode).toBe(1)
})
it.each([[''], [undefined]])(
'refuses an empty value (%s) rather than run unguarded',
async (value) => {
answerRuntime([BROWSER_EXPECT_URL_RUNTIME_CAPABILITY])
await main(
[
'click',
'--element',
'@e1',
'--page',
'page-1',
'--json',
'--expect-url',
...(value === undefined ? [] : [value])
],
'/tmp/not-an-orca-worktree'
)
expect(callMock).not.toHaveBeenCalled()
expect(process.exitCode).toBe(1)
}
)
})
@@ -1,28 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { suggestCommands, unknownFlagData } from './command-suggestion'
import type { CommandSpec } from './command-spec'
const specs: CommandSpec[] = [
{ path: ['list'], summary: '', usage: '', allowedFlags: [] },
{ path: ['remove'], summary: '', usage: '', allowedFlags: [], destructive: true }
]
afterEach(() => vi.restoreAllMocks())
describe('suggestion distance work', () => {
it('keeps the inclusive three-edit suggestion boundary', () => {
expect(suggestCommands(specs, ['listxxx'])).toEqual(['list'])
expect(unknownFlagData('jsonxxx', ['json']).suggestions).toEqual(['json'])
})
it('keeps the inclusive one-edit destructive intent boundary', () => {
expect(suggestCommands(specs, ['remov'])).toEqual(['remove'])
expect(suggestCommands(specs, ['remo'])).toEqual([])
})
it('retains UTF-16 distance semantics at the length boundary', () => {
expect(unknownFlagData('json😀x', ['json']).suggestions).toEqual(['json'])
expect(unknownFlagData('json😀😀', ['json']).suggestions).toEqual([])
})
})
@@ -30,7 +30,6 @@ describe('CdpWsProxy', () => {
function expectPdfStreamHandle(response: Record<string, unknown>): string {
const result = response.result as Record<string, unknown>
expect(result.data).toBe('')
expect(result.stream).toEqual(expect.stringMatching(/^orca-pdf-[\da-f-]{36}-\d+$/))
return result.stream as string
}
@@ -66,7 +65,6 @@ describe('CdpWsProxy', () => {
params: { handle }
})
expect(printResponse.id).toBe(21)
expect(firstRead).toEqual({
id: 22,
result: { base64Encoded: true, data: Buffer.from('ab').toString('base64'), eof: false }
@@ -45,38 +45,6 @@ describe('BrowserClientHostCommandDispatcher', () => {
await vi.runAllTimersAsync()
await dispatcher.dispatch(command(1, 'create-b', 'createPage', 'page-a', 2))
})
it('bounds close while canceling queued and non-cooperative handlers', async () => {
vi.useFakeTimers()
const stuck = deferred<BrowserClientHostCommandResult>()
const handler = vi.fn().mockReturnValue(stuck.promise)
const dispatcher = new BrowserClientHostCommandDispatcher({
authority,
handler,
maxConcurrentHandlers: 1,
joinTimeoutMs: 50
})
const running = dispatcher.dispatch(command(1, 'create-a'))
const queued = dispatcher.dispatch(command(1, 'create-b', 'createPage', 'page-b'))
const closing = dispatcher.close()
await vi.advanceTimersByTimeAsync(50)
await expect(running).resolves.toMatchObject({ errorCode: 'browser_host_command_cancelled' })
await expect(queued).resolves.toMatchObject({ errorCode: 'browser_host_command_cancelled' })
await expect(closing).resolves.toBe(false)
expect(() => dispatcher.dispatch(command(1, 'create-c', 'createPage', 'page-c'))).toThrow(
'browser_host_command_dispatcher_closed'
)
let handlersSettled = false
void dispatcher.whenClosed().then(() => {
handlersSettled = true
})
await Promise.resolve()
expect(handlersSettled).toBe(false)
stuck.resolve({ status: 'completed' })
await vi.runAllTimersAsync()
await expect(dispatcher.whenClosed()).resolves.toBeUndefined()
})
})
function command(
@@ -134,30 +134,4 @@ describe('BrowserClientDownloadRelay', () => {
expect(aborts).toHaveLength(1)
expect(removed).toContain(path.dirname(route.stagingPath))
})
it('aborts the remote transfer and removes the staged copy when a chunk is rejected', async () => {
const aborted: unknown[] = []
const transport = negotiatedTransport((method, params) => {
if (method.endsWith('abort')) {
aborted.push(params)
return { released: true }
}
return { accepted: false }
})
const { filesystem, removed } = memoryFilesystem(Buffer.from('abc'))
const relay = new BrowserClientDownloadRelay({
stagingRoot: '/tmp/staging',
hostLabel: 'build-box',
transport,
resolvePage: () => page,
filesystem
})
const route = remoteRoute(relay.route({ guestWebContentsId: 7 }))
await expect(route.complete('report.pdf')).rejects.toThrow(
'browser_client_download_chunk_rejected'
)
expect(aborted).toHaveLength(1)
expect(removed.length).toBeGreaterThan(0)
})
})
@@ -35,14 +35,12 @@ type EnvironmentHarness = {
function environment(input: {
environmentId: string
guestWebContentsId: number
availability?: 'negotiated' | 'unsupported' | 'unavailable'
}): EnvironmentHarness {
const availability = input.availability ?? 'negotiated'
const writes: { browserPageId: string; hostLabel: string }[] = []
const transport = new BrowserClientFileChannelTransport()
transport.bind({
fileChannelNegotiated: availability === 'negotiated',
fileChannelAvailability: availability,
fileChannelNegotiated: true,
fileChannelAvailability: 'negotiated',
sendFileChannelRequest: async (_method, params) => {
writes.push({
browserPageId: (params as { browserPageId: string }).browserPageId,
@@ -102,43 +100,4 @@ describe('client-hosted download routing', () => {
expect(envA.writes).toEqual([{ browserPageId: 'page-env-a', hostLabel: 'env-a' }])
expect(envB.writes).toEqual([])
})
it('cancels rather than saving locally when the owning page has no usable channel', () => {
environment({
environmentId: 'env-a',
guestWebContentsId: ENV_A_GUEST_ID,
availability: 'unavailable'
})
setBrowserClientRouteWebContentsProbe(() => true)
expect(routeBrowserClientDownload({ guestWebContentsId: ENV_A_GUEST_ID })).toEqual({
kind: 'blocked'
})
})
it('keeps the desktop fallback for a lease that never negotiated the file channel', () => {
environment({
environmentId: 'env-a',
guestWebContentsId: ENV_A_GUEST_ID,
availability: 'unsupported'
})
setBrowserClientRouteWebContentsProbe(() => true)
expect(routeBrowserClientDownload({ guestWebContentsId: ENV_A_GUEST_ID })).toEqual({
kind: 'local'
})
})
it('does not read a throwing router as permission to save locally', () => {
registerBrowserClientDownloadRouter('env-a', {
route: () => {
throw new Error('router exploded')
}
})
setBrowserClientRouteWebContentsProbe(() => true)
expect(routeBrowserClientDownload({ guestWebContentsId: ENV_A_GUEST_ID })).toEqual({
kind: 'blocked'
})
})
})
@@ -1,174 +0,0 @@
// @vitest-environment happy-dom
import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
import { useEffect } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useAppStore } from '@/store'
import {
drawTabsFromMain,
type TabsDrawnFromMain
} from '@/store/slices/tabs/tabs-drawn-from-main.test-fixture'
import { runBackgroundWorktreeCreation } from '@/lib/workspace/creation/worktree-creation-flow'
import {
makeCreatedAgentWorktree,
seedEmptyActivatableWorktree
} from '@/lib/workspace/activation/worktree-activation-created-agent.test-fixture'
import { TooltipProvider } from '@/components/ui/tooltip'
import { registerNativeChatPane } from '@/components/native-chat/composer/focus/native-chat-composer-mount'
import { AppWorkspaceShell } from './AppWorkspaceShell'
import { useAppChromeLayout } from './use-app-chrome-layout'
import { useFloatingWorkspacePanel } from './use-floating-workspace-panel'
const host = vi.hoisted(() => ({ createSupport: vi.fn() }))
vi.mock('../runtime/native-chat/requests/structured-agent-session-call', () => ({
callStructuredAgentSession: vi.fn((_target: unknown, method: string) =>
method === 'agentSession.createSupport' ? host.createSupport() : new Promise(() => undefined)
)
}))
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) =>
(
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
).runtimeRpcClientWithLayoutApply(await importOriginal())
)
vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) =>
(
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
).runtimeLayoutClientWithTestFrames(await importOriginal())
)
// Keep the actual shell, pending chat and creation flow; unrelated chrome and heavy pane contents are boundaries.
vi.mock('../components/Sidebar', () => ({ default: () => null }))
vi.mock('../components/right-sidebar/RightSidebar', () => ({
default: () => <aside aria-label="Workspace tools" />
}))
vi.mock('./TitlebarLeftControls', () => ({ TitlebarLeftControls: () => null }))
vi.mock('./TitlebarMainStrip', () => ({
TitlebarMainStrip: () => null,
RightSidebarToggle: () => null
}))
vi.mock('@/components/native-chat/composer/NativeChatComposer', () => ({
NativeChatComposer: () => <textarea aria-label="Pending chat message" />
}))
vi.mock('../components/Terminal', () => ({
default: function CreatedChatPane() {
const chatTabId = useAppStore((s) =>
Object.values(s.unifiedTabsByWorktree)
.flat()
.find((tab) => tab.contentType === 'agent-session')
)?.id
// Like the real chat pane, report actionable so handoff need not wait out its fallback.
useEffect(
() => (chatTabId ? registerNativeChatPane(chatTabId, () => true) : undefined),
[chatTabId]
)
const hasChat = useAppStore((s) =>
(s.unifiedTabsByWorktree[s.activeWorktreeId ?? ''] ?? []).some(
(tab) => tab.contentType === 'agent-session'
)
)
const activeWorktreeId = useAppStore((s) => s.activeWorktreeId)
const hasTerminal = useAppStore(
(s) => (s.tabsByWorktree[s.activeWorktreeId ?? ''] ?? []).length > 0
)
return hasChat ? (
<div role="log" aria-label="Created chat" />
) : hasTerminal ? (
<div role="log" aria-label="Workspace terminal">
{activeWorktreeId}
</div>
) : null
}
}))
function WorkspaceShell(): React.JSX.Element {
return (
<AppWorkspaceShell
layout={useAppChromeLayout()}
floatingWorkspace={useFloatingWorkspacePanel()}
/>
)
}
const expectedFolderWorkspaceId =
process.platform === 'win32' ? 'repo-1::\\workspace\\feature' : 'repo-1::/workspace/feature'
const initialApiDescriptor = Object.getOwnPropertyDescriptor(window, 'api')
const initialState = useAppStore.getState()
let main: TabsDrawnFromMain | undefined
afterEach(() => {
cleanup()
main?.close()
main = undefined
useAppStore.setState(initialState, true)
vi.restoreAllMocks()
if (initialApiDescriptor) {
Object.defineProperty(window, 'api', initialApiDescriptor)
} else {
Reflect.deleteProperty(window, 'api')
}
})
describe('worktree creation chat handoff', () => {
it('retains the visible workspace until ordinary local folder creation completes', async () => {
const worktree = { ...makeCreatedAgentWorktree(), hostId: 'local' as const }
const previous = { ...worktree, id: 'previous-workspace', path: '/workspace/previous' }
seedEmptyActivatableWorktree(worktree, { extraWorktrees: [previous] })
useAppStore.getState().createTab(previous.id)
Object.defineProperty(window, 'api', {
configurable: true,
value: {
runtime: { call: vi.fn() },
pty: { listSessions: () => new Promise(() => {}) }
}
})
const checkout = Promise.withResolvers<{
worktree: typeof worktree
startupTerminal: { spawned: boolean }
}>()
useAppStore.setState((state) => ({
repos: state.repos.map((repo) => ({ ...repo, kind: 'folder' as const })),
activeWorktreeId: previous.id,
activeView: 'terminal',
pendingWorktreeCreations: {},
createWorktree: vi.fn(() => checkout.promise)
}))
main = await drawTabsFromMain(useAppStore)
render(
<TooltipProvider>
<WorkspaceShell />
</TooltipProvider>
)
const terminal = await screen.findByRole('log', { name: 'Workspace terminal' })
expect(terminal.textContent).toBe('previous-workspace')
act(() => {
runBackgroundWorktreeCreation({
repoId: worktree.repoId,
executionHostId: 'local',
worktreeCreateProgressMode: 'stepped',
name: 'feature',
setupDecision: 'skip',
agent: null,
pendingFirstAgentMessageRename: false,
note: '',
startupPlan: null,
quickPrompt: '',
quickTelemetry: null
})
})
expect(screen.getByRole('log', { name: 'Workspace terminal' })).toBe(terminal)
expect(terminal.textContent).toBe('previous-workspace')
await act(async () => {
checkout.resolve({ worktree, startupTerminal: { spawned: false } })
})
await waitFor(() =>
expect(screen.getByRole('log', { name: 'Workspace terminal' }).textContent).toBe(
expectedFolderWorkspaceId
)
)
})
})
@@ -1,78 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import type { AgentAttentionSurface } from './agent-attention-contract'
import {
applyAgentAttention,
resolveAgentAttention,
type AgentAttentionRequest,
type AgentAttentionSink
} from './agent-attention-policy'
const WORKSPACE = 'wt-1'
const SUBJECT = 'tab-1:leaf-1'
const GROUP = 'tab-1'
function makeSurface(overrides: Partial<AgentAttentionSurface> = {}): AgentAttentionSurface {
return {
hasLiveSession: () => true,
admitSurface: () => ({ admitted: true, groupId: GROUP }),
isSurfaceViewed: () => false,
isWorkspaceViewed: () => false,
isWorkspaceActive: () => false,
isWorkspaceMuted: () => false,
resolveViewedSubjectKey: () => null,
...overrides
}
}
function completion(overrides: Partial<AgentAttentionRequest> = {}): AgentAttentionRequest {
return {
subject: { workspaceId: WORKSPACE, surfaceKey: SUBJECT },
reason: 'agent-completion',
settlesTurn: true,
hasFreshActivityEvidence: false,
...overrides
}
}
function makeSink(): AgentAttentionSink & { calls: string[] } {
const calls: string[] = []
return {
calls,
unread: (write) =>
calls.push(
`unread:${write.workspaceId}:${write.subjectKey}:${write.groupId}:${write.reason}`
),
requestDelivery: (request) => calls.push(`deliver:${request.workspaceId}:${request.subjectKey}`)
}
}
describe('resolveAgentAttention', () => {
it('rejects a muted workspace before any other gate, so it earns no unread or delivery', () => {
const hasLiveSession = vi.fn(() => true)
const decision = resolveAgentAttention(
completion(),
makeSurface({ isWorkspaceMuted: () => true, hasLiveSession })
)
expect(decision).toEqual({ admitted: false, cause: 'muted-workspace' })
expect(hasLiveSession).not.toHaveBeenCalled()
const sink = makeSink()
applyAgentAttention(decision, sink)
expect(sink.calls).toEqual([])
})
it('delivers a bell without validating the surface address or writing unread', () => {
const admitSurface = vi.fn()
const isSurfaceViewed = vi.fn()
const decision = resolveAgentAttention(
completion({ reason: 'terminal-bell', settlesTurn: false }),
makeSurface({ admitSurface, isSurfaceViewed })
)
expect(decision).toMatchObject({ admitted: true, unread: null })
expect(admitSurface).not.toHaveBeenCalled()
expect(isSurfaceViewed).not.toHaveBeenCalled()
const sink = makeSink()
applyAgentAttention(decision, sink)
expect(sink.calls).toEqual([`deliver:${WORKSPACE}:${SUBJECT}`])
})
})
@@ -1,52 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
emitAgentSubjectReads,
registerAgentSubjectReadCapture,
subscribeAgentSubjectReads,
type StructuredSubjectRead
} from './agent-subject-read-actions'
const stops: (() => void)[] = []
afterEach(() => {
for (const stop of stops.splice(0).toReversed()) {
stop()
}
vi.restoreAllMocks()
})
const structured: StructuredSubjectRead = {
sessionId: 'session',
target: { kind: 'environment', environmentId: 'host' },
observedCursor: { epoch: 'epoch', sequence: 1 },
observationKey: 'observed'
}
describe('agent subject read batch index', () => {
it('captures explicit reads, isolates listener errors, and retires subscriptions', () => {
const capture = vi.fn(() => structured)
stops.push(registerAgentSubjectReadCapture('one', capture))
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
const stopFailure = subscribeAgentSubjectReads(() => {
throw new Error('listener failed')
})
const observed: StructuredSubjectRead[] = []
const stopSurvivor = subscribeAgentSubjectReads((_reads, index) => {
const read = index.get('one')?.structured
if (read) {
observed.push(read)
}
})
stops.push(stopFailure, stopSurvivor)
emitAgentSubjectReads(['one'], undefined, 'explicit')
expect(capture).toHaveBeenCalledWith('explicit')
expect(observed).toEqual([structured])
expect(warning).toHaveBeenCalledOnce()
stopFailure()
emitAgentSubjectReads(['one'], undefined, 'explicit')
expect(observed).toEqual([structured, structured])
expect(warning).toHaveBeenCalledOnce()
stopSurvivor()
emitAgentSubjectReads(['one'], undefined, 'explicit')
expect(observed).toHaveLength(2)
})
})