Merge main into native chat SQLite host

This commit is contained in:
Brennan Benson
2026-11-11 11:19:40 -08:00
162 changed files with 3609 additions and 4793 deletions
@@ -110,7 +110,6 @@
1 src/renderer/src/components/editor/editor-header-file-rename.ts
1 src/renderer/src/components/editor/external-changes/ExternalFileChangeCompareDialog.tsx
1 src/renderer/src/components/editor/git-graph/git-graph-filter.tsx
1 src/renderer/src/components/editor/git-graph/git-graph-tab.tsx
1 src/renderer/src/components/editor/markdown-preview/render-tree/use-markdown-preview-components.tsx
1 src/renderer/src/components/editor/markdown-preview/review/MarkdownPreviewAnnotationComposer.tsx
1 src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.tsx
-1
View File
@@ -72,7 +72,6 @@
1 src/renderer/src/app-shell/use-app-session-persistence.ts
1 src/renderer/src/components/browser-pane/browser-client-page-position-driver.ts
1 src/renderer/src/components/contextual-tours/use-contextual-tour.ts
1 src/renderer/src/components/editor/setup-contextual-copy.ts
1 src/renderer/src/components/right-sidebar/plugin-panels/health/plugin-panel-watchdog.ts
1 src/renderer/src/components/sidebar/SeveredTerminalDaemonBanner.tsx
1 src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.tsx
+2 -1
View File
@@ -38,7 +38,8 @@
"../src/types/**/*"
],
"exclude": [
"../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts"
"../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts",
"../src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts"
],
"compilerOptions": {
"composite": true,
+1
View File
@@ -2,6 +2,7 @@
"extends": "./tsconfig.web.json",
"include": [
"../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts",
"../src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts",
"../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx",
"../src/renderer/src/runtime/observed-provider-accounts.test.tsx",
"../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.observation.test.tsx",
+2 -1
View File
@@ -15,7 +15,8 @@ const contracts = [
'src/main/usage/source-input/jsonl/jsonl-file-reader.test.ts',
'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs',
'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs',
'src/main/claude-usage/scanner-incremental-append.test.ts'
'src/main/claude-usage/scanner-incremental-append.test.ts',
'src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts'
]
for (const contract of contracts) {
if (!existsSync(resolve(contract))) {
@@ -71,7 +71,7 @@ export function screenModuleMocks(dependencies: ScreenDependencies) {
View: 'View',
useWindowDimensions: () => ({ width: 390, height: 844 })
}),
// Stub Expo-dependent native handlers; native-clipboard.test.ts covers their behavior.
// Stub Expo-dependent native handlers.
'expo-clipboard': () => ({
setStringAsync: () => Promise.resolve(true),
getStringAsync: () => Promise.resolve('')
@@ -84,9 +84,4 @@ describe('a workspace screen’s router', () => {
['back']
])
})
it('is the plain router in the desktop’s own workspaces', async () => {
const router = await workspaceRouterFor({})
expect(router).toBe(route.router)
})
})
@@ -1,23 +0,0 @@
import { beforeEach, expect, it, vi } from 'vitest'
const requireNativeModule = vi.hoisted(() => vi.fn())
vi.mock('expo-modules-core', () => ({ requireNativeModule }))
beforeEach(() => {
vi.resetModules()
requireNativeModule.mockReset()
})
it('requires the iOS ledger and surfaces a missing native module as a build defect', async () => {
requireNativeModule.mockImplementation(() => {
throw new Error('Cannot find native module OrcaNotificationDismissal')
})
await expect(import('./native-push-dismissal.ios')).rejects.toThrow(
'Cannot find native module OrcaNotificationDismissal'
)
})
it('does not load an iOS module on the default Android/web path', async () => {
expect((await import('./native-push-dismissal')).nativePushDismissal).toBeNull()
expect(requireNativeModule).not.toHaveBeenCalled()
})
@@ -2,7 +2,7 @@ import { createElement, type ReactNode } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { MobileOnboardingPage } from './MobileOnboardingPage'
import { findAllByHostType, findByHostType } from '../test-support/react-test-renderer-host-nodes'
import { findByHostType } from '../test-support/react-test-renderer-host-nodes'
vi.mock('react-native', async () => {
const React = await import('react')
@@ -87,12 +87,6 @@ describe('MobileOnboardingPage', () => {
)
}
function collectText(): string {
return findAllByHostType(renderer!.root, 'Text')
.flatMap((node) => node.props.children)
.join(' ')
}
it('renders the session choices and sends exactly one selected view', async () => {
const callbacks = await renderPage('session-view')
@@ -109,19 +103,6 @@ describe('MobileOnboardingPage', () => {
expect(callbacks.onSessionChoice).not.toHaveBeenCalled()
})
it('explains that alerts cover finished work and waiting agents, even if the app is closed', async () => {
await renderPage('notifications')
const copy = collectText()
expect(copy).toContain('Don’t miss when an agent needs you')
expect(copy).toContain('finishes or is waiting')
expect(copy).toContain('using the app')
expect(copy).toContain('Enable notifications')
expect(copy).toContain('Codex finished')
expect(copy).toContain('Claude needs input')
expect(renderer!.root.findByProps({ testID: 'notification-onboarding-preview' })).toBeTruthy()
})
it('disables both notification choices while permission is pending', async () => {
await renderPage('notifications', { busyChoice: 'enable' })
const enable = button('Enable agent notifications')
-14
View File
@@ -26,28 +26,14 @@ afterEach(() => {
})
describe('opening a URL from a phone screen', () => {
it('hands it straight to the app, unchanged', () => {
openExternalLink('https://github.com/stablyai/orca/pull/1')
expect(linking.openURL.mock.calls).toEqual([['https://github.com/stablyai/orca/pull/1']])
})
it('does not throw out of a tap handler when nothing can open the URL', async () => {
linking.openURL.mockImplementation(() => Promise.reject(new Error('no activity found')))
expect(() => openExternalLink('mailto:someone@example.com')).not.toThrow()
await Promise.resolve()
})
it('checks no scheme of its own, because on a phone this is what every call site already did', () => {
openExternalLink('orca://x')
expect(linking.openURL.mock.calls).toEqual([['orca://x']])
})
})
describe('a URL the platform refuses before it returns a promise', () => {
it('does not throw out of a tap handler for an empty string', () => {
expect(() => openExternalLink('')).not.toThrow()
})
it('names the refusal rather than failing silently', () => {
const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
openExternalLink('')
-77
View File
@@ -1,77 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { BRIDGE_HAPTICS_KINDS } from '../mobile-web-shell/bridge/bridge-haptics-notify'
import {
publishHapticsNotifier,
triggerEdgeBump,
triggerError,
triggerMediumImpact,
triggerSelection,
triggerSuccess
} from './haptics.web'
const asked: string[] = []
beforeEach(() => {
asked.length = 0
publishHapticsNotifier((kind) => {
asked.push(kind)
return true
})
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('the haptic each page function asks the shell for', () => {
it.each([
['mediumImpact', triggerMediumImpact],
['selection', triggerSelection],
['success', triggerSuccess],
['error', triggerError],
['edgeBump', triggerEdgeBump]
] as const)('posts exactly one notify, carrying %s', (kind, trigger) => {
trigger()
expect(asked).toEqual([kind])
})
it('covers every kind the notify accepts, so no name is left on a no-op', () => {
// Check export/kind parity so adding a native haptic cannot silently leave page taps inert.
for (const trigger of [
triggerMediumImpact,
triggerSelection,
triggerSuccess,
triggerError,
triggerEdgeBump
]) {
trigger()
}
expect([...asked].sort()).toEqual([...BRIDGE_HAPTICS_KINDS].sort())
})
it('posts one frame per call, because a scrolling list calls once per row', () => {
for (let row = 0; row < 12; row += 1) {
triggerSelection()
}
expect(asked).toHaveLength(12)
})
})
describe('a shell that will not play it', () => {
it('says nothing, because nobody reads the answer and every row tap would say it again', () => {
const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
publishHapticsNotifier(() => false)
expect(() => triggerSelection()).not.toThrow()
expect(warned).not.toHaveBeenCalled()
})
it('asks nothing at all in a document that published no notifier', async () => {
// Reload the module to clear notifiers published by earlier cases.
vi.resetModules()
const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
const fresh: typeof import('./haptics.web') = await import('./haptics.web')
expect(() => fresh.triggerError()).not.toThrow()
expect(asked).toEqual([])
expect(warned).not.toHaveBeenCalled()
})
})
@@ -37,7 +37,7 @@ function focusedField(userAgent: string): HTMLInputElement {
describe('a keyboard the phone closes', () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ['setTimeout', 'performance'] })
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] })
publishShellKeyboardSource({
read: () => shellHeight,
subscribe: (listener) => {
@@ -62,10 +62,24 @@ describe('a keyboard the phone closes', () => {
expect(document.activeElement).toBe(field)
shellReports(0)
vi.advanceTimersByTime(1000)
expect(document.activeElement).not.toBe(field)
})
it('keeps the field focused when the keyboard closes and reopens for a switch to a voice IME', () => {
const field = focusedField(ANDROID)
startBlurringOnKeyboardClose()
shellReports(300)
shellReports(0)
vi.advanceTimersByTime(250)
shellReports(200)
vi.advanceTimersByTime(5000)
expect(document.activeElement).toBe(field)
})
// The second case is tapping the underlined word after Back: that tap both focuses the field and opens the menu.
it.each([
['already focused', false],
@@ -105,7 +119,7 @@ describe('a keyboard the phone closes', () => {
target.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))
vi.advanceTimersByTime(waitMs)
shellReports(0)
vi.advanceTimersByTime(100)
vi.advanceTimersByTime(1000)
expect(document.activeElement).not.toBe(field)
})
+11 -3
View File
@@ -5,6 +5,8 @@ import { subscribeSoftKeyboard } from './keyboard-occlusion.web'
// Chromium hides the IME itself to show a tapped autocorrected word's menu; Back comes with no touch.
const FIELD_TAP_HIDE_WINDOW_MS = 1000
const KEYBOARD_REOPEN_DELAY_MS = 50
// A keyboard's mic switches to a voice IME, which closes the keyboard and opens again ~250 ms later; Back opens none.
const IME_SWITCH_WINDOW_MS = 1000
// Android raises the IME only for a new focus session, as for the terminal live input.
function reopenKeyboard(field: HTMLElement): void {
@@ -14,12 +16,13 @@ function reopenKeyboard(field: HTMLElement): void {
}
}
// Android Back hides the IME without blurring; blur now so the next terminal touch cannot reopen it.
// Android Back hides the IME without blurring; blur once it stays closed so the next terminal touch cannot reopen it.
export function startBlurringOnKeyboardClose(): void {
if (hostOs() !== 'android') {
return
}
let lastTouch: { target: Node; at: number } | null = null
let pendingBlur: ReturnType<typeof setTimeout> | undefined
document.addEventListener(
'pointerdown',
(event) => {
@@ -29,7 +32,7 @@ export function startBlurringOnKeyboardClose(): void {
{ capture: true }
)
subscribeSoftKeyboard(
() => {},
() => clearTimeout(pendingBlur),
() => {
const field = document.activeElement
const touch = lastTouch
@@ -42,7 +45,12 @@ export function startBlurringOnKeyboardClose(): void {
) {
setTimeout(() => reopenKeyboard(field), KEYBOARD_REOPEN_DELAY_MS)
} else {
Keyboard.dismiss()
// Leave alone a field focus moved to meanwhile.
pendingBlur = setTimeout(() => {
if (document.activeElement === field) {
Keyboard.dismiss()
}
}, IME_SWITCH_WINDOW_MS)
}
}
)
@@ -26,9 +26,4 @@ describe('the composing range a live input reports', () => {
undefined
])
})
it('passes the range through where there is no navigator', () => {
vi.stubGlobal('navigator', undefined)
expect(reportedLiveInputComposing(true)).toBe(true)
})
})
@@ -37,15 +37,6 @@ async function flush(): Promise<void> {
}
describe('the lock a microphone holds', () => {
it('takes the tag once and gives it back once', async () => {
const { device, calls } = createTestDevice()
const lock = createMicrophoneScreenLock(device, 'orca-mic')
lock.hold()
lock.release()
await flush()
expect(calls).toEqual(['+orca-mic', '-orca-mic'])
})
it('asks the device nothing for a hold it already has', async () => {
const { device, calls } = createTestDevice()
const lock = createMicrophoneScreenLock(device, 'orca-mic')
@@ -1,59 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ZodError } from 'zod'
const clipboard = vi.hoisted(() => ({
setStringAsync: vi.fn(() => Promise.resolve(true)),
getStringAsync: vi.fn(() => Promise.resolve(''))
}))
vi.mock('expo-clipboard', () => clipboard)
import { serveNativeClipboardVerb } from './native-clipboard'
beforeEach(() => {
clipboard.setStringAsync.mockReset()
clipboard.setStringAsync.mockImplementation(() => Promise.resolve(true))
clipboard.getStringAsync.mockReset()
clipboard.getStringAsync.mockImplementation(() => Promise.resolve('on the pasteboard'))
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('serving a clipboard verb', () => {
it('writes text and answers whether the pasteboard took it', async () => {
await expect(
serveNativeClipboardVerb('native.clipboard.write', { mime: 'text', value: 'copied' })
).resolves.toEqual({ written: true })
expect(clipboard.setStringAsync.mock.calls).toEqual([['copied']])
})
it('carries a pasteboard refusal through rather than reporting success', async () => {
clipboard.setStringAsync.mockImplementation(() => Promise.resolve(false))
await expect(
serveNativeClipboardVerb('native.clipboard.write', { mime: 'text', value: 'copied' })
).resolves.toEqual({ written: false })
})
it('reads text off the pasteboard', async () => {
await expect(
serveNativeClipboardVerb('native.clipboard.read', { mime: 'text' })
).resolves.toEqual({ value: 'on the pasteboard' })
})
it('does not take an image at all, because the media verbs stage one instead', async () => {
// Images use staged media handles; clipboard.read rejects their MIME before reaching the device.
for (const verb of ['native.clipboard.write', 'native.clipboard.read'] as const) {
const params =
verb === 'native.clipboard.write' ? { mime: 'image', value: 'x' } : { mime: 'image' }
// Require the params refusal code so a pasteboard error cannot satisfy this assertion.
await expect(serveNativeClipboardVerb(verb, params)).rejects.toSatisfy(
(error: unknown) =>
error instanceof ZodError && error.issues.some((issue) => issue.path[0] === 'mime')
)
}
expect(clipboard.setStringAsync).not.toHaveBeenCalled()
expect(clipboard.getStringAsync).not.toHaveBeenCalled()
})
})
@@ -117,16 +117,6 @@ function heldBytes(): number {
return [...storage.files.values()].reduce((total, bytes) => total + bytes.byteLength, 0)
}
it('preserves the successful staged URI, base64 options and bytes without deleting it', () => {
const uri = device().stageBase64('AQID')
expect(uri).toBe('file:///cache/orca-media-1234-0.25.png')
expect(storage.events).toEqual([
{ operation: 'create', uri, options: { overwrite: true } },
{ operation: 'write', uri, content: 'AQID', options: { encoding: 'base64' } }
])
expect(storage.files.get(uri)).toEqual(Uint8Array.from([1, 2, 3]))
})
it.each([0, 4096])('releases an unreturned file after a write fails with %i bytes', (bytes) => {
const original = new Error('partial native write')
storage.writeFailure = original
@@ -150,13 +140,6 @@ it('preserves the write failure when best-effort deletion also fails', () => {
expect(heldBytes()).toBe(4096)
})
it('preserves creation failure and its original operation order', () => {
const original = new Error('native create failed')
storage.createFailure = original
expect(thrownBy(() => device().stageBase64('AQID'))).toBe(original)
expect(storage.events.map((event) => event.operation)).toEqual(['create'])
})
it('deletes only the failed file while a prior successful file remains readable', () => {
vi.spyOn(Math, 'random').mockReturnValueOnce(0.1).mockReturnValueOnce(0.2)
const successfulUri = device().stageBase64('AQID')
@@ -13,13 +13,6 @@ afterEach(() => {
})
describe('randomV4Uuid', () => {
it('uses crypto.randomUUID where the platform has it', () => {
const randomUUID = vi.fn(() => '11111111-1111-4111-8111-111111111111')
vi.stubGlobal('crypto', { randomUUID })
expect(randomV4Uuid()).toBe('11111111-1111-4111-8111-111111111111')
expect(secure.getRandomBytes).not.toHaveBeenCalled()
})
it('falls back to the secure byte source, never Math.random, and stamps v4', () => {
vi.stubGlobal('crypto', {})
const insecure = vi.spyOn(Math, 'random')
@@ -1,136 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
canDockSessionPanel,
nextActivePanel,
resolvePanelAction,
panelRouteDescriptor,
shouldShowSessionHeaderChecksAction,
type ActivePanel
} from './session-panel-host'
const PANELS = ['sourceControl', 'files', 'pr'] as const
describe('nextActivePanel', () => {
it('opens a panel from the closed state', () => {
for (const panel of PANELS) {
expect(nextActivePanel(null, panel)).toBe(panel)
}
})
it('closes the panel when tapping the active one', () => {
for (const panel of PANELS) {
expect(nextActivePanel(panel, panel)).toBeNull()
}
})
it('swaps to a different panel', () => {
expect(nextActivePanel('sourceControl', 'files')).toBe('files')
expect(nextActivePanel('files', 'pr')).toBe('pr')
expect(nextActivePanel('pr', 'sourceControl')).toBe('sourceControl')
})
})
describe('resolvePanelAction', () => {
it('docks with the opened panel on wide layouts (open)', () => {
expect(resolvePanelAction({ canDock: true, tapped: 'files', current: null })).toEqual({
kind: 'dock',
next: 'files'
})
})
it('docks with null on wide layouts when tapping the active panel (close)', () => {
expect(resolvePanelAction({ canDock: true, tapped: 'pr', current: 'pr' })).toEqual({
kind: 'dock',
next: null
})
})
it('docks with the new panel on wide layouts (swap)', () => {
expect(
resolvePanelAction({ canDock: true, tapped: 'sourceControl', current: 'files' })
).toEqual({ kind: 'dock', next: 'sourceControl' })
})
it('pushes the tapped panel when docking is unavailable regardless of current', () => {
const currents: ActivePanel[] = [null, 'sourceControl', 'files', 'pr']
for (const panel of PANELS) {
for (const current of currents) {
expect(resolvePanelAction({ canDock: false, tapped: panel, current })).toEqual({
kind: 'push',
panel
})
}
}
})
})
describe('canDockSessionPanel', () => {
it('requires a wide layout and enough measured content-row width', () => {
expect(canDockSessionPanel({ isWideLayout: true, availableWidth: 700, dockWidth: 340 })).toBe(
true
)
expect(canDockSessionPanel({ isWideLayout: true, availableWidth: 699, dockWidth: 340 })).toBe(
false
)
expect(canDockSessionPanel({ isWideLayout: false, availableWidth: 900, dockWidth: 340 })).toBe(
false
)
})
})
describe('shouldShowSessionHeaderChecksAction', () => {
it('shows Checks on git worktree routes once a checks-capable provider is confirmed', () => {
expect(
shouldShowSessionHeaderChecksAction({
isFolderWorkspaceRoute: false,
repoContextLoaded: true,
hostedChecksSupported: true
})
).toBe(true)
})
it('hides Checks for providers without hosted checks (pr-panel guard would no-op it)', () => {
expect(
shouldShowSessionHeaderChecksAction({
isFolderWorkspaceRoute: false,
repoContextLoaded: true,
hostedChecksSupported: false
})
).toBe(false)
})
it('hides Checks until the provider probe resolves', () => {
expect(
shouldShowSessionHeaderChecksAction({
isFolderWorkspaceRoute: false,
repoContextLoaded: false,
hostedChecksSupported: true
})
).toBe(false)
})
it('hides Checks on folder workspace session routes', () => {
expect(
shouldShowSessionHeaderChecksAction({
isFolderWorkspaceRoute: true,
repoContextLoaded: true,
hostedChecksSupported: true
})
).toBe(false)
})
})
describe('panelRouteDescriptor', () => {
it('maps each panel to its expo-router pathname', () => {
expect(panelRouteDescriptor('sourceControl')).toEqual({
pathname: '/h/[hostId]/source-control/[worktreeId]'
})
expect(panelRouteDescriptor('files')).toEqual({
pathname: '/h/[hostId]/files/[worktreeId]'
})
expect(panelRouteDescriptor('pr')).toEqual({
pathname: '/h/[hostId]/source-control/[worktreeId]',
params: { tab: 'pr' }
})
})
})
@@ -1,49 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { readDefaultSessionViewPreference } from '../storage/session-view-preferences'
import { shouldPresentSessionViewOptIn } from './session-view-opt-in-gate'
vi.mock('../storage/session-view-preferences', () => ({
readDefaultSessionViewPreference: vi.fn()
}))
describe('session view opt-in gate', () => {
beforeEach(() => {
vi.mocked(readDefaultSessionViewPreference).mockReset()
})
it('presents when no default has ever been saved', async () => {
vi.mocked(readDefaultSessionViewPreference).mockResolvedValue({
value: null,
loaded: true,
hasStoredValue: false
})
await expect(shouldPresentSessionViewOptIn()).resolves.toBe(true)
})
it.each(['terminal', 'chat'] as const)('preserves an existing %s choice', async (value) => {
vi.mocked(readDefaultSessionViewPreference).mockResolvedValue({
value,
loaded: true,
hasStoredValue: true
})
await expect(shouldPresentSessionViewOptIn()).resolves.toBe(false)
})
it('does not overwrite an unknown stored value', async () => {
vi.mocked(readDefaultSessionViewPreference).mockResolvedValue({
value: null,
loaded: true,
hasStoredValue: true
})
await expect(shouldPresentSessionViewOptIn()).resolves.toBe(false)
})
it('does not block startup when storage is unreadable', async () => {
vi.mocked(readDefaultSessionViewPreference).mockResolvedValue({
value: null,
loaded: false,
hasStoredValue: false
})
await expect(shouldPresentSessionViewOptIn()).resolves.toBe(false)
})
})
@@ -1,46 +0,0 @@
import { describe, expect, it } from 'vitest'
import { resolveMobileHistoryScreenView } from './mobile-history-screen-state'
import type { MobileCommitRow } from './mobile-git-history'
const row: MobileCommitRow = {
id: 'abc123',
shortId: 'abc123',
subject: 'commit',
author: 'author',
parentId: null,
relativeTime: '1m'
}
describe('resolveMobileHistoryScreenView', () => {
it('shows waiting (not an endless spinner) when disconnected with nothing loaded', () => {
// Offline cold loads cannot run; show Retry instead of an endless spinner.
expect(resolveMobileHistoryScreenView({ connected: false, rows: null, error: null })).toEqual({
kind: 'waiting'
})
})
it('spins only while connected and loading', () => {
expect(resolveMobileHistoryScreenView({ connected: true, rows: null, error: null })).toEqual({
kind: 'loading'
})
})
it('keeps already-loaded rows visible across a connection drop', () => {
expect(resolveMobileHistoryScreenView({ connected: false, rows: [row], error: null })).toEqual({
kind: 'rows',
rows: [row]
})
})
it('prefers the error state over waiting so failures stay actionable', () => {
expect(resolveMobileHistoryScreenView({ connected: false, rows: null, error: 'boom' })).toEqual(
{ kind: 'error', message: 'boom' }
)
})
it('distinguishes an empty history from a pending load', () => {
expect(resolveMobileHistoryScreenView({ connected: true, rows: [], error: null })).toEqual({
kind: 'empty'
})
})
})
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
import { getMobilePrEligibilityReadiness, readFreshGitStatus } from './mobile-open-pr-prefill'
import { readFreshGitStatus } from './mobile-open-pr-prefill'
import type { MobileGitStatusResult } from './mobile-git-status'
const fallback = { branch: 'old', entries: [] } as unknown as MobileGitStatusResult
@@ -33,23 +33,3 @@ describe('readFreshGitStatus', () => {
expect(out).toBe(fallback)
})
})
describe('getMobilePrEligibilityReadiness', () => {
it('keeps readiness fields absent when git status is unknown', () => {
expect(getMobilePrEligibilityReadiness(null)).toEqual({})
})
it('derives dirty and upstream readiness from git status', () => {
const status = {
entries: [{ path: 'a.ts' }],
upstreamStatus: { hasUpstream: true, ahead: 2, behind: 1 }
} as unknown as MobileGitStatusResult
expect(getMobilePrEligibilityReadiness(status)).toEqual({
hasUncommittedChanges: true,
hasUpstream: true,
ahead: 2,
behind: 1
})
})
})
@@ -1,28 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
isMobileConflictAborting,
mobileConflictAbortLabel
} from './mobile-source-control-conflict-abort'
describe('isMobileConflictAborting', () => {
it('is true only for the matching abort action', () => {
expect(isMobileConflictAborting('abort-merge', 'merge')).toBe(true)
expect(isMobileConflictAborting('abort-rebase', 'rebase')).toBe(true)
})
it('is false for other busy actions (stage/commit must not look like abort)', () => {
expect(isMobileConflictAborting('stage-all', 'merge')).toBe(false)
expect(isMobileConflictAborting('commit', 'rebase')).toBe(false)
expect(isMobileConflictAborting(null, 'merge')).toBe(false)
expect(isMobileConflictAborting('abort-merge', 'rebase')).toBe(false)
expect(isMobileConflictAborting('abort-merge', 'unknown')).toBe(false)
})
})
describe('mobileConflictAbortLabel', () => {
it('shows Aborting only while abort is in flight', () => {
expect(mobileConflictAbortLabel('merge', true)).toBe('Aborting…')
expect(mobileConflictAbortLabel('merge', false)).toBe('Abort merge')
expect(mobileConflictAbortLabel('rebase', false)).toBe('Abort rebase')
})
})
@@ -1,22 +0,0 @@
import { describe, it, expect } from 'vitest'
import { parseSourceControlHubTab } from './mobile-source-control-hub-tab'
describe('parseSourceControlHubTab', () => {
it('accepts each known tab', () => {
for (const tab of ['changes', 'pr', 'history']) {
expect(parseSourceControlHubTab(tab)).toBe(tab)
}
})
it('reads the first element of an array param', () => {
expect(parseSourceControlHubTab(['pr', 'history'])).toBe('pr')
})
it('falls back to changes for unknown, empty, or missing values', () => {
expect(parseSourceControlHubTab('nope')).toBe('changes')
expect(parseSourceControlHubTab('')).toBe('changes')
expect(parseSourceControlHubTab(undefined)).toBe('changes')
expect(parseSourceControlHubTab(null)).toBe('changes')
expect(parseSourceControlHubTab([])).toBe('changes')
})
})
@@ -28,7 +28,6 @@ vi.mock('../platform/haptics', () => ({
triggerImpact: () => undefined
}))
import { BRIDGE_MAX_MESSAGE_BYTES } from '../mobile-web-shell/bridge/bridge-caps'
import { useRouteHandoff } from '../navigation/route-handoff'
import { useMobileGitRequests } from './use-mobile-git-requests'
import { useMobileSourceControlRunners } from './use-mobile-source-control-runners'
@@ -68,33 +67,6 @@ function idleRunnerParams() {
}
describe('stage-all over the outbound frame cap', () => {
it('refuses the frame at the page rather than posting one the shell drops', async () => {
const pair = createFakeBridgePortPair()
await pair.flush()
const postedBefore = pair.toShell.length
const rejection = await pair.client
.sendRequest('git.bulkStage', { worktree: 'id:wt-1', filePaths: STAGEABLE_PATHS })
.then(
() => null,
(error: unknown) => error
)
await pair.flush()
expect(rejection).toBeInstanceOf(Error)
expect(rejection instanceof Error ? rejection.name : String(rejection)).toBe(
'BridgeRequestOversizedError'
)
// The frame never left, so this is definite failure and a smaller retry cannot duplicate host work.
expect(pair.toShell.length).toBe(postedBefore)
expect(pair.hostDiagnostics).toEqual([])
expect(pair.diagnostics.map((entry) => entry.kind)).toEqual(['send-oversized'])
const [diagnostic] = pair.diagnostics
expect(diagnostic.kind === 'send-oversized' ? diagnostic.bytes : 0).toBeGreaterThan(
BRIDGE_MAX_MESSAGE_BYTES
)
})
it('reports the oversized action and suggests fewer files, then stops being busy', async () => {
const pair = createFakeBridgePortPair()
await pair.flush()
@@ -61,46 +61,6 @@ describe('mobile hosted review eligibility loader core', () => {
})
).toBe(false)
})
it('builds distinct keys for different branches', () => {
const first = buildMobileHostedReviewEligibilityLoadKey({
hostId: 'host-1',
worktreeId: 'wt-1',
branch: 'feature-a',
hasUpstream: true,
ahead: 0,
behind: 0,
hasUncommittedChanges: false
})
const second = buildMobileHostedReviewEligibilityLoadKey({
hostId: 'host-1',
worktreeId: 'wt-1',
branch: 'feature-b',
hasUpstream: true,
ahead: 0,
behind: 0,
hasUncommittedChanges: false
})
expect(first.identity).not.toBe(second.identity)
expect(first.fetch).not.toBe(second.fetch)
})
it('scopes load identity to the paired host', () => {
const input = {
worktreeId: 'repo-1::/workspace',
branch: 'feature',
hasUpstream: true,
ahead: 0,
behind: 0,
hasUncommittedChanges: false
}
const local = buildMobileHostedReviewEligibilityLoadKey({ ...input, hostId: 'local' })
const ssh = buildMobileHostedReviewEligibilityLoadKey({ ...input, hostId: 'ssh-builder' })
expect(local.identity).not.toBe(ssh.identity)
expect(local.fetch).not.toBe(ssh.fetch)
})
})
// Fetch-imminent must render loading immediately; an idle frame would shift the list when Create PR appears.
@@ -124,31 +84,6 @@ describe('rendered eligibility state', () => {
).toEqual({ kind: 'loading', eligibility: null })
})
it('passes resolved and refetch states through untouched', () => {
const key = buildMobileHostedReviewEligibilityLoadKey({
hostId: 'host-1',
worktreeId: 'wt-1',
branch: 'feature',
hasUpstream: true,
ahead: 0,
behind: 0,
hasUncommittedChanges: false
})
const ready = { kind: 'ready', eligibility: eligibility() } as const
const refetch = { kind: 'loading', eligibility: eligibility() } as const
const error = { kind: 'error' } as const
for (const state of [ready, refetch, error]) {
expect(
renderedMobileHostedReviewEligibilityState({
snapshot: loadSnapshot(key, state),
key,
shouldFetch: true
})
).toBe(state)
}
})
it('renders idle when a fetch is not possible, hiding stale snapshots in the same render', () => {
const key = buildMobileHostedReviewEligibilityLoadKey({
hostId: 'host-1',
@@ -271,55 +206,4 @@ describe('eligibility request ordering', () => {
})
expect(renderedState).toMatchObject({ kind: 'loading', eligibility: ready })
})
it('keeps remounted hook state separate from a prior instance’s pending request', async () => {
type Response = { ok: true; result: MobileHostedReviewEligibilityReply }
const requests: ReturnType<typeof deferred<Response>>[] = []
const client = {
sendRequest: vi.fn(() => {
const request = deferred<Response>()
requests.push(request)
return request.promise
})
}
const newest = eligibility({ canCreate: false, blockedReason: 'existing_review' })
function Harness(): null {
renderedState = useMobileHostedReviewEligibility({
client: client as never,
connState: 'connected',
hostId: 'host-1',
worktreeId: 'wt-1',
branch: 'feature',
hasUpstream: true,
ahead: 0,
behind: 0,
hasUncommittedChanges: false
})
return null
}
await act(async () => {
renderer = create(createElement(Harness))
await Promise.resolve()
})
act(() => renderer?.unmount())
renderer = null
await act(async () => {
renderer = create(createElement(Harness))
await Promise.resolve()
})
expect(requests).toHaveLength(2)
await act(async () => {
requests[1]!.resolve({ ok: true, result: newest })
await Promise.resolve()
})
await act(async () => {
requests[0]!.resolve({ ok: true, result: eligibility() })
await Promise.resolve()
})
expect(renderedState).toMatchObject({ kind: 'ready', eligibility: newest })
})
})
@@ -1,95 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
extractGitHubIssueSourceError,
extractGitHubIssueSourceFallback
} from './github-work-item-source-errors'
describe('extractGitHubIssueSourceError', () => {
it('keeps the failing issue source slug with the repo that produced it', () => {
expect(
extractGitHubIssueSourceError(
{ id: 'repo-1', path: '/work/orca' },
{
sources: { issues: { owner: 'upstream', repo: 'orca' } },
errors: { issues: { message: 'HTTP 403: resource not accessible' } }
}
)
).toEqual({
repoId: 'repo-1',
repoPath: '/work/orca',
source: { owner: 'upstream', repo: 'orca' },
message: 'HTTP 403: resource not accessible'
})
})
it('drops issue errors when the source slug is unavailable', () => {
expect(
extractGitHubIssueSourceError(
{ id: 'repo-1', path: '/work/orca' },
{
sources: { issues: null },
errors: { issues: { message: 'failed' } }
}
)
).toBeNull()
})
it('returns null when the envelope has no issue-side error', () => {
expect(
extractGitHubIssueSourceError(
{ id: 'repo-1', path: '/work/orca' },
{
sources: { issues: { owner: 'stablyai', repo: 'orca' } }
}
)
).toBeNull()
})
})
describe('extractGitHubIssueSourceFallback', () => {
it('reports the repo whose upstream issue source fell back to origin', () => {
expect(
extractGitHubIssueSourceFallback(
{ id: 'repo-1', path: '/work/orca', displayName: 'orca' },
{
issueSourceFellBack: true,
sources: {
issues: { owner: 'stablyai', repo: 'orca-fork' },
prs: { owner: 'stablyai', repo: 'orca' }
}
}
)
).toEqual({
repoId: 'repo-1',
repoPath: '/work/orca',
repoLabel: 'stablyai/orca'
})
})
it('uses the Orca repo display name when the PR source is unavailable', () => {
expect(
extractGitHubIssueSourceFallback(
{ id: 'repo-1', path: '/work/orca', displayName: 'orca' },
{
issueSourceFellBack: true,
sources: { issues: null, prs: null }
}
)
).toEqual({
repoId: 'repo-1',
repoPath: '/work/orca',
repoLabel: 'orca'
})
})
it('returns null when the source resolver did not fall back', () => {
expect(
extractGitHubIssueSourceFallback(
{ id: 'repo-1', path: '/work/orca', displayName: 'orca' },
{
sources: { issues: { owner: 'stablyai', repo: 'orca' } }
}
)
).toBeNull()
})
})
-6
View File
@@ -41,12 +41,6 @@ describe('hostRepoListReducer', () => {
const loaded = reduce(idle, { type: 'resolved', repos: [{ id: 'a' }] })
expect(reduce(loaded, { type: 'reset' })).toEqual(idle)
})
it('returns the identical state when a reset or repeat request changes nothing', () => {
expect(hostRepoListReducer<Repo>(idle, { type: 'reset' })).toBe(idle)
const loading = reduce(idle, { type: 'requested' })
expect(hostRepoListReducer<Repo>(loading, { type: 'requested' })).toBe(loading)
})
})
describe('host repo list readiness', () => {
+1 -17
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { isHostedTaskRepo, reconcileRepoSelection } from './hosted-repo-selection'
import { reconcileRepoSelection } from './hosted-repo-selection'
const repos = [
{ id: 'a', kind: 'worktree' },
@@ -7,27 +7,11 @@ const repos = [
{ id: 'folder', kind: 'folder' }
]
describe('isHostedTaskRepo', () => {
it('excludes folder workspaces and keeps everything else', () => {
expect(repos.filter(isHostedTaskRepo).map((repo) => repo.id)).toEqual(['a', 'b'])
expect(isHostedTaskRepo({ id: 'no-kind' })).toBe(true)
})
})
describe('reconcileRepoSelection', () => {
it('treats an absent or empty persisted selection as "all repos"', () => {
expect(reconcileRepoSelection(repos, null)).toEqual(new Set())
expect(reconcileRepoSelection(repos, [])).toEqual(new Set())
})
it('drops ids this host no longer has', () => {
expect(reconcileRepoSelection(repos, ['a', 'gone'])).toEqual(new Set(['a']))
})
it('widens back to all repos when nothing in the selection survives', () => {
expect(reconcileRepoSelection(repos, ['gone'])).toEqual(new Set())
})
it('never selects a folder workspace', () => {
expect(reconcileRepoSelection(repos, ['folder'])).toEqual(new Set())
})
@@ -1,28 +0,0 @@
import { describe, expect, it } from 'vitest'
import { shouldResolveHostedReviewStartPoint } from './hosted-review-start-point'
describe('shouldResolveHostedReviewStartPoint', () => {
it('resolves PR and MR start points when no explicit base branch was selected', () => {
expect(shouldResolveHostedReviewStartPoint({ type: 'pr' })).toBe(true)
expect(shouldResolveHostedReviewStartPoint({ type: 'mr', baseBranchOverride: '' })).toBe(true)
})
it('does not resolve a hosted review start point when the user selected a base branch', () => {
expect(
shouldResolveHostedReviewStartPoint({
type: 'pr',
baseBranchOverride: 'origin/feature/manual'
})
).toBe(false)
expect(
shouldResolveHostedReviewStartPoint({
type: 'mr',
baseBranchOverride: 'origin/release'
})
).toBe(false)
})
it('never resolves start points for issues', () => {
expect(shouldResolveHostedReviewStartPoint({ type: 'issue' })).toBe(false)
})
})
@@ -1,38 +0,0 @@
import { describe, expect, it } from 'vitest'
import { toJiraDetailComments } from './jira-mobile-issue-read'
describe('toJiraDetailComments', () => {
it('maps the author and avatar off the nested user', () => {
expect(
toJiraDetailComments([
{
id: '10',
body: 'hi',
createdAt: '2026-01-01T00:00:00Z',
user: { accountId: 'a', displayName: 'Dana', avatarUrl: 'https://x/y.png' }
}
])
).toEqual([
{
id: '10',
author: 'Dana',
authorAvatarUrl: 'https://x/y.png',
body: 'hi',
createdAt: '2026-01-01T00:00:00Z'
}
])
})
it('degrades to an empty list instead of breaking the detail sheet', () => {
expect(toJiraDetailComments(null)).toEqual([])
expect(toJiraDetailComments({ error: 'nope' })).toEqual([])
})
it('drops entries without a usable id', () => {
expect(
toJiraDetailComments([{ id: 5, body: 'x' }, { body: 'y' }, { id: '7', body: 'z' }])
).toEqual([
{ id: '7', author: undefined, authorAvatarUrl: undefined, body: 'z', createdAt: undefined }
])
})
})
@@ -1,51 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { LinearIssue } from './mobile-tasks-provider-detail-types'
import {
sortLinearIssues,
groupLinearIssues,
groupSortedLinearIssues
} from './mobile-tasks-reviewer-linear'
vi.mock('./mobile-tasks-dependencies', () => import('../theme/mobile-theme'))
afterEach(() => vi.restoreAllMocks())
const issues: LinearIssue[] = Array.from({ length: 60 }, (_, i) => ({
id: `${i}`,
identifier: ['ENG-10', 'ENG-2', 'Ä-1', 'Å-1', 'é-2', 'e\u0301-2', 'İ-3'][i % 7],
title: 'Task',
url: '',
labels: [],
priority: i % 5,
updatedAt: ['2026-02-01', 'invalid', '1970-01-01', '2026-02-01', '2025-01-01'][
Math.floor(i / 5) % 5
],
state: { name: i % 2 ? 'Todo' : 'Done', type: 'started', color: '' },
team: { id: `${i % 3}`, name: `Team ${i % 3}`, key: 'ENG' }
}))
describe('mobile Linear grouping of sorted issues', () => {
it('does no date parsing or collation after ordering has been established', () => {
const sorted = sortLinearIssues(issues, 'updated')
const parse = vi.spyOn(Date, 'parse')
const compare = vi.spyOn(String.prototype, 'localeCompare')
groupSortedLinearIssues(sorted, 'none')
groupSortedLinearIssues(sorted, 'status')
expect(parse).not.toHaveBeenCalled()
expect(compare).not.toHaveBeenCalled()
groupLinearIssues(sorted, 'status', 'updated')
expect(parse).toHaveBeenCalled()
})
it('returns independent issue arrays for empty, singleton and ungrouped inputs', () => {
for (const input of [[], [issues[0]], issues]) {
const sorted = Object.freeze([...input])
const first = groupSortedLinearIssues(sorted, 'none')
const second = groupSortedLinearIssues(sorted, 'none')
expect(first).toEqual(second)
expect(first[0].issues).not.toBe(second[0].issues)
first[0].issues.pop()
expect(second[0].issues).toEqual(sorted)
}
expect(groupSortedLinearIssues([], 'status')).toEqual([])
})
})
@@ -1,62 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { LinearIssue } from './mobile-tasks-provider-detail-types'
import { sortLinearIssues } from './mobile-tasks-reviewer-linear'
vi.mock('./mobile-tasks-dependencies', () => import('../theme/mobile-theme'))
afterEach(() => vi.restoreAllMocks())
const issues: LinearIssue[] = Array.from({ length: 60 }, (_, i) => ({
id: `${i}`,
identifier: ['ENG-10', 'ENG-2', 'Ä-1', 'Å-1', 'é-2', 'e\u0301-2', 'İ-3'][i % 7],
title: 'Task',
url: '',
labels: [],
priority: i % 5,
updatedAt: ['2026-02-01', 'invalid', '1970-01-01', '2026-02-01', '2025-01-01'][
Math.floor(i / 5) % 5
],
state: { name: i % 2 ? 'Todo' : 'Done', type: 'started', color: '' },
team: { id: `${i % 3}`, name: `Team ${i % 3}`, key: 'ENG' }
}))
describe('mobile Linear sorting', () => {
it.each(['updated', 'identifier', 'priority'] as const)('bounds %s setup to one pass', (mode) => {
const parse = vi.spyOn(Date, 'parse')
const NativeCollator = Intl.Collator
const collator = vi.spyOn(Intl, 'Collator').mockImplementation(function (locales, options) {
return new NativeCollator(locales, options)
})
const compare = vi.spyOn(String.prototype, 'localeCompare')
const before = [...issues]
const actual = sortLinearIssues(issues, mode)
const expectedFirstIds = {
updated: ['0', '1', '2'],
priority: ['1', '16', '26'],
identifier: ['1', '8', '15']
}
const ordered =
mode === 'identifier' ? actual.filter((issue) => issue.identifier.startsWith('ENG-')) : actual
expect(ordered.slice(0, 3).map((issue) => issue.id)).toEqual(expectedFirstIds[mode])
expect(actual).toHaveLength(issues.length)
expect(issues).toEqual(before)
expect(parse).toHaveBeenCalledTimes(mode === 'identifier' ? 0 : issues.length)
expect(collator).toHaveBeenCalledTimes(mode === 'identifier' ? 1 : 0)
expect(compare).not.toHaveBeenCalled()
})
it('skips setup for empty and singleton inputs and returns fresh arrays', () => {
const parse = vi.spyOn(Date, 'parse')
const NativeCollator = Intl.Collator
const collator = vi.spyOn(Intl, 'Collator').mockImplementation(function (locales, options) {
return new NativeCollator(locales, options)
})
for (const mode of ['updated', 'identifier', 'priority'] as const) {
for (const input of [[], [issues[0]]]) {
const actual = sortLinearIssues(input, mode)
expect(actual).toEqual(input)
expect(actual).not.toBe(input)
}
}
expect(parse).not.toHaveBeenCalled()
expect(collator).not.toHaveBeenCalled()
})
})
@@ -1,87 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
normalizeSmartMode,
resolveAvailableSmartModes,
resolveDefaultSmartMode
} from './mobile-smart-source-modes'
const fullyAvailable = {
textOnly: false,
tasksSupported: true,
hasRepo: true,
githubAvailable: true,
gitlabAvailable: true,
linearAvailable: true,
jiraAvailable: true
}
describe('resolveAvailableSmartModes', () => {
it('lists every mode in desktop order when all are available', () => {
expect(resolveAvailableSmartModes(fullyAvailable)).toEqual([
'smart',
'github',
'linear',
'jira',
'gitlab',
'branches',
'text'
])
})
it('collapses to Name for a non-git (text-only) repo', () => {
expect(resolveAvailableSmartModes({ ...fullyAvailable, textOnly: true })).toEqual(['text'])
})
it('drops provider + smart modes when the tasks RPC surface is missing', () => {
expect(resolveAvailableSmartModes({ ...fullyAvailable, tasksSupported: false })).toEqual([
'branches',
'text'
])
})
it('gates provider tabs on their availability and a selected repo', () => {
expect(
resolveAvailableSmartModes({
...fullyAvailable,
githubAvailable: false,
gitlabAvailable: false
})
).toEqual(['smart', 'linear', 'jira', 'branches', 'text'])
expect(resolveAvailableSmartModes({ ...fullyAvailable, hasRepo: false })).toEqual([
'smart',
'linear',
'jira',
'text'
])
})
it('keeps the Jira tab repo-independent but hides it when Jira is disconnected', () => {
expect(resolveAvailableSmartModes({ ...fullyAvailable, hasRepo: false })).toContain('jira')
expect(resolveAvailableSmartModes({ ...fullyAvailable, jiraAvailable: false })).not.toContain(
'jira'
)
})
})
describe('resolveDefaultSmartMode', () => {
it('defaults to smart for a git repo with search', () => {
expect(resolveDefaultSmartMode(fullyAvailable)).toBe('smart')
})
it('defaults to text for a non-git repo', () => {
expect(resolveDefaultSmartMode({ ...fullyAvailable, textOnly: true })).toBe('text')
})
it('defaults to branches for a git repo without the tasks surface', () => {
expect(resolveDefaultSmartMode({ ...fullyAvailable, tasksSupported: false })).toBe('branches')
})
})
describe('normalizeSmartMode', () => {
it('keeps a valid mode and snaps an unavailable one back to default', () => {
expect(normalizeSmartMode('gitlab', fullyAvailable)).toBe('gitlab')
expect(normalizeSmartMode('gitlab', { ...fullyAvailable, gitlabAvailable: false })).toBe(
'smart'
)
})
})
@@ -39,20 +39,6 @@ describe('mobile task copy feedback timer', () => {
expect(timerRef.current).toBeNull()
})
it('replaces stale copy feedback timers', () => {
vi.useFakeTimers()
const timerRef = createTimerRef()
const copied = createCopiedKeyState('task:one')
scheduleMobileTaskCopyFeedbackReset(timerRef, 'task:one', copied.setCopiedKey)
copied.setCopiedKey(() => 'task:two')
scheduleMobileTaskCopyFeedbackReset(timerRef, 'task:two', copied.setCopiedKey)
vi.runOnlyPendingTimers()
expect(copied.value).toBeNull()
expect(timerRef.current).toBeNull()
})
it('cancels pending copy feedback work', () => {
vi.useFakeTimers()
const timerRef = createTimerRef()
-69
View File
@@ -1,69 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import type { TaskItem } from './mobile-tasks-project-workspace-types'
import type { RepoSummary } from './mobile-tasks-provider-detail-types'
import { sortMobileTaskItems } from './mobile-tasks-repository-presentation'
vi.mock('./mobile-tasks-dependencies', () => import('../theme/mobile-theme'))
function task(
provider: TaskItem['provider'],
label: string,
updatedAt: string,
key: string
): TaskItem {
const source =
provider === 'linear'
? { team: { id: label, name: label }, state: { color: '' } }
: provider === 'gitlabTodo'
? { projectPath: label }
: { repoId: label, repoName: label }
return { provider, source, updatedAt, key, title: key, subtitle: '', status: '' } as TaskItem
}
const repos = new Map<string, RepoSummary>([
['alias', { id: 'alias', displayName: 'Álpha', path: '/repo' }]
])
const items = [
task('github', 'alias', '2026-01-01', 'a'),
task('gitlab', 'alpha', '2026-02-01', 'b'),
task('gitlabTodo', 'Zeta', 'invalid', 'c'),
task('linear', 'Älpha', '2026-02-01', 'd'),
task('github', 'alpha', '2026-02-01', 'e'),
task('linear', 'Zeta', '1970-01-01', 'f')
]
describe('mobile task sorting', () => {
it.each(['repository', 'updated'] as const)('computes %s keys only once per item', (sort) => {
const parse = vi.spyOn(Date, 'parse')
const getRepo = vi.spyOn(repos, 'get')
const localeCompare = vi.spyOn(String.prototype, 'localeCompare')
try {
const before = [...items]
const actual = sortMobileTaskItems(items, sort, repos)
expect(actual.map((item) => item.key)).toEqual(['b', 'd', 'e', 'a', 'c', 'f'])
expect(items).toEqual(before)
expect(parse).toHaveBeenCalledTimes(items.length)
expect(getRepo).toHaveBeenCalledTimes(sort === 'repository' ? 3 : 0)
expect(localeCompare).not.toHaveBeenCalled()
} finally {
parse.mockRestore()
getRepo.mockRestore()
localeCompare.mockRestore()
}
})
it('skips setup for empty/singleton arrays while returning a fresh array', () => {
const parse = vi.spyOn(Date, 'parse')
const collator = vi.spyOn(Intl, 'Collator')
try {
expect(sortMobileTaskItems([], 'repository', repos)).toEqual([])
const one = [items[0]]
expect(sortMobileTaskItems(one, 'repository', repos)).toEqual(one)
expect(sortMobileTaskItems(one, 'updated', repos)).not.toBe(one)
expect(parse).not.toHaveBeenCalled()
expect(collator).not.toHaveBeenCalled()
} finally {
parse.mockRestore()
collator.mockRestore()
}
})
})
@@ -1,25 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
vi.mock('./mobile-tasks-dependencies', () => import('../theme/mobile-theme'))
import { reconcileTeamSelection } from './mobile-tasks-reviewer-linear'
import type { LinearTeam } from './mobile-tasks-provider-detail-types'
function team(id: string): LinearTeam {
return { id, name: id, key: id.toUpperCase() }
}
describe('reconcileTeamSelection', () => {
it('selects every team for sticky-all', () => {
expect([...reconcileTeamSelection([team('a'), team('b')], null)]).toEqual(['a', 'b'])
})
it('keeps saved teams that still exist', () => {
expect([...reconcileTeamSelection([team('a'), team('b')], ['b'])]).toEqual(['b'])
})
// Older hosts may publish persisted selection as a string; keep that compatible.
it('reads a saved value of the wrong shape as sticky-all instead of throwing', () => {
expect([...reconcileTeamSelection([team('a'), team('b')], 'a')]).toEqual(['a', 'b'])
expect([...reconcileTeamSelection([team('a'), team('b')], { 0: 'a' })]).toEqual(['a', 'b'])
})
})
@@ -15,13 +15,6 @@ describe('parseSparsePresetDirectories', () => {
})
})
it('requires at least one directory', () => {
expect(parseSparsePresetDirectories(' \n ')).toEqual({
directories: [],
error: 'Add at least one directory.'
})
})
it('rejects root and parent path entries', () => {
expect(parseSparsePresetDirectories('.')).toEqual({
directories: [],
@@ -1,66 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { z } from 'zod'
import {
linearCommentWrittenSchema,
reviewThreadResolvedSchema,
taskCommentWrittenSchema
} from './task-item-comment-reply-schema'
function reads<T>(schema: z.ZodType<T, unknown>, value: unknown): T {
const parsed = schema.safeParse(value)
if (!parsed.success) {
throw new Error(`expected a readable reply: ${parsed.error.message}`)
}
return parsed.data
}
function refuses(schema: z.ZodType<unknown, unknown>, value: unknown): boolean {
return !schema.safeParse(value).success
}
describe('the five writes that answer with a comment', () => {
it('reads the representative GitHub, GitLab and review-reply envelopes unchanged', () => {
for (const comment of [
{ id: 902, author: 'You', body: 'a comment', createdAt: '2020-01-01T00:00:00.000Z' },
{
id: 903,
author: 'You',
body: 'a reply',
createdAt: '2020-01-01T00:00:00.000Z',
path: 'src/index.ts',
line: 12,
threadId: 'thread-1'
}
]) {
expect(reads(taskCommentWrittenSchema, { ok: true, comment }).comment).toMatchObject(comment)
}
})
it('keeps ok tri-state and leaves the refusal wording to the call site', () => {
expect(reads(taskCommentWrittenSchema, { ok: false }).error).toBeUndefined()
expect(reads(taskCommentWrittenSchema, { ok: false, error: 'no' }).error).toBe('no')
expect(reads(taskCommentWrittenSchema, {}).ok).toBeUndefined()
})
it('names a reply that is not the envelope, which main read members off', () => {
expect(refuses(taskCommentWrittenSchema, null)).toBe(true)
expect(refuses(taskCommentWrittenSchema, 'posted')).toBe(true)
})
})
describe('the Linear comment write', () => {
it('reads the representative reply and leaves a missing id to the local echo', () => {
expect(reads(linearCommentWrittenSchema, { ok: true, id: 'comment-9' }).id).toBe('comment-9')
expect(reads(linearCommentWrittenSchema, { ok: true }).id).toBeUndefined()
expect(refuses(linearCommentWrittenSchema, null)).toBe(true)
})
})
describe('resolving a review thread', () => {
it('keeps a real false, and names a reply that is not a boolean', () => {
expect(reads(reviewThreadResolvedSchema, true)).toBe(true)
expect(reads(reviewThreadResolvedSchema, false)).toBe(false)
expect(refuses(reviewThreadResolvedSchema, 'true')).toBe(true)
expect(refuses(reviewThreadResolvedSchema, undefined)).toBe(true)
})
})
@@ -1,103 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { z } from 'zod'
import {
githubPullRequestChecksSchema,
githubPullRequestFileContentsSchema,
hostedIssueCreatedSchema,
linearIssueCreatedSchema,
linearIssueUpdatedSchema,
taskMutationConfirmationSchema
} from './task-item-state-reply-schema'
function reads<T>(schema: z.ZodType<T, unknown>, value: unknown): T {
const parsed = schema.safeParse(value)
if (!parsed.success) {
throw new Error(`expected a readable reply: ${parsed.error.message}`)
}
return parsed.data
}
function refuses(schema: z.ZodType<unknown, unknown>, value: unknown): boolean {
return !schema.safeParse(value).success
}
describe('creating an item', () => {
it('reads a GitHub issue create reply', () => {
const created = reads(hostedIssueCreatedSchema, {
ok: true,
number: 11,
url: 'https://github.com/owner/repo/issues/11'
})
expect(created).toMatchObject({ ok: true, number: 11 })
})
it('reads a number the composer would not have accepted as absent', () => {
expect(reads(hostedIssueCreatedSchema, { ok: true, number: '11' }).number).toBeUndefined()
})
it('leaves id and identifier to the Linear call site, which words that refusal itself', () => {
expect(reads(linearIssueCreatedSchema, { ok: true }).id).toBeUndefined()
expect(
reads(linearIssueCreatedSchema, { ok: true, id: 'issue-3', identifier: 'ENG-3' }).identifier
).toBe('ENG-3')
expect(refuses(linearIssueCreatedSchema, null)).toBe(true)
})
})
describe('the checks read', () => {
it('reads the representative reply and refuses a payload that is not a list', () => {
expect(
reads(githubPullRequestChecksSchema, [
{ name: 'build', status: 'COMPLETED', conclusion: 'SUCCESS', url: '' }
])
).toHaveLength(1)
expect(refuses(githubPullRequestChecksSchema, { checks: [] })).toBe(true)
expect(refuses(githubPullRequestChecksSchema, null)).toBe(true)
})
})
describe('the file-contents read', () => {
it('reads the representative reply, which is now the shape getPRFileContents returns', () => {
const recorded = {
original: 'a',
modified: 'b',
originalIsBinary: false,
modifiedIsBinary: false
}
expect(reads(githubPullRequestFileContentsSchema, recorded)).toEqual(recorded)
})
it('keeps the too-large flags a skipped side carries', () => {
const skipped = { original: '', modified: '', originalTooLarge: true, modifiedTooLarge: true }
expect(reads(githubPullRequestFileContentsSchema, skipped)).toMatchObject(skipped)
})
it('still names a payload that is not the container', () => {
expect(refuses(githubPullRequestFileContentsSchema, null)).toBe(true)
expect(refuses(githubPullRequestFileContentsSchema, 'a\nb')).toBe(true)
})
it('reads a payload carrying none of the six, because no member is required', () => {
expect(reads(githubPullRequestFileContentsSchema, {})).toEqual({})
})
})
describe('the two unread replies', () => {
it('reads anything for the Linear state write, whose body no call site looks at', () => {
expect(refuses(linearIssueUpdatedSchema, null)).toBe(false)
expect(refuses(linearIssueUpdatedSchema, 'accepted')).toBe(false)
})
})
describe('the viewed-state confirmation', () => {
it('keeps a real false, which is the refusal the call site words', () => {
expect(reads(taskMutationConfirmationSchema, true)).toBe(true)
expect(reads(taskMutationConfirmationSchema, false)).toBe(false)
})
it('names a non-boolean instead of reading it as "not confirmed"', () => {
expect(refuses(taskMutationConfirmationSchema, 'true')).toBe(true)
expect(refuses(taskMutationConfirmationSchema, { ok: true })).toBe(true)
expect(refuses(taskMutationConfirmationSchema, null)).toBe(true)
})
})
@@ -1,145 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { z } from 'zod'
import {
githubWorkItemCountSchema,
gitlabTodoListSchema,
linearAccountConnectedSchema,
linearAccountStatusSchema,
taskRepoPreferenceWrittenSchema
} from './task-list-reply-schema'
function reads<T>(schema: z.ZodType<T, unknown>, value: unknown): T {
const parsed = schema.safeParse(value)
if (!parsed.success) {
throw new Error(`expected a readable reply: ${parsed.error.message}`)
}
return parsed.data
}
function refuses(schema: z.ZodType<unknown, unknown>, value: unknown): boolean {
return !schema.safeParse(value).success
}
describe('Linear account status', () => {
it('reads the representative reply, workspace row included', () => {
const status = reads(linearAccountStatusSchema, {
connected: true,
workspaces: [{ id: 'linear-workspace', name: 'Workspace' }],
selectedWorkspaceId: 'linear-workspace'
})
expect(status.connected).toBe(true)
expect(status.workspaces?.[0]).toMatchObject({ id: 'linear-workspace', name: 'Workspace' })
})
it('reads a disconnected host the same way every settings family records it', () => {
expect(reads(linearAccountStatusSchema, { connected: false }).connected).toBe(false)
})
it('names the null main read `connected` off, which the screen showed as its load error', () => {
expect(refuses(linearAccountStatusSchema, null)).toBe(true)
expect(refuses(linearAccountStatusSchema, 'connected')).toBe(true)
})
it('keeps an explicit selectedWorkspaceId null, which the ?? ladder is what interprets', () => {
const status = reads(linearAccountStatusSchema, {
connected: true,
selectedWorkspaceId: null,
activeWorkspaceId: null
})
expect(status.selectedWorkspaceId).toBeNull()
expect(status.activeWorkspaceId).toBeNull()
})
it('drops only the workspace row with no id, which can be neither selected nor matched', () => {
expect(reads(linearAccountStatusSchema, { workspaces: [{ name: 'W' }] }).workspaces).toEqual([])
expect(
reads(linearAccountStatusSchema, { workspaces: [{ id: 'w-1' }, { name: 'W' }] }).workspaces
).toEqual([{ id: 'w-1' }])
expect(reads(linearAccountStatusSchema, { workspaces: 'none' }).workspaces).toBeUndefined()
})
})
describe('the GitHub item count', () => {
it('reads the representative number and names anything else', () => {
expect(reads(githubWorkItemCountSchema, 4)).toBe(4)
expect(refuses(githubWorkItemCountSchema, '4')).toBe(true)
expect(refuses(githubWorkItemCountSchema, { count: 4 })).toBe(true)
expect(refuses(githubWorkItemCountSchema, null)).toBe(true)
})
})
describe('the GitLab to-do inbox', () => {
const RECORDED_TODO = {
id: 1,
actionName: 'review_requested',
targetType: 'Issue',
targetIid: 4,
targetTitle: 'A GitLab todo',
targetUrl: 'https://gitlab.example.com/group/project/-/issues/4',
projectPath: 'group/project',
authorUsername: 'octocat',
authorAvatarUrl: '',
updatedAt: '2020-01-01T00:00:00.000Z',
state: 'pending'
}
it('reads the representative row through untouched, unread members included', () => {
expect(reads(gitlabTodoListSchema, [RECORDED_TODO])).toEqual([RECORDED_TODO])
})
it('reads nullish as the empty inbox the call site already read', () => {
expect(reads(gitlabTodoListSchema, null)).toBeNull()
expect(reads(gitlabTodoListSchema, undefined)).toBeUndefined()
})
it('names a reply that is neither, which the screen showed as ".map is not a function"', () => {
expect(refuses(gitlabTodoListSchema, { todos: [] })).toBe(true)
expect(refuses(gitlabTodoListSchema, 'none')).toBe(true)
})
it('drops a row missing a member the screen reads with no guard', () => {
for (const key of ['id', 'actionName', 'targetUrl', 'projectPath', 'updatedAt']) {
const partial: Record<string, unknown> = { ...RECORDED_TODO }
delete partial[key]
expect(reads(gitlabTodoListSchema, [partial, RECORDED_TODO])).toEqual([RECORDED_TODO])
}
})
it('keeps a row whose guarded members are absent, because each has a fallback', () => {
const guarded: Record<string, unknown> = { ...RECORDED_TODO }
for (const key of ['targetTitle', 'targetType', 'targetIid', 'authorUsername', 'state']) {
delete guarded[key]
}
expect(reads(gitlabTodoListSchema, [guarded])).toEqual([guarded])
})
it('drops a malformed guarded member to absent rather than the whole row', () => {
const row = reads(gitlabTodoListSchema, [
{ ...RECORDED_TODO, targetIid: 'four', state: 'archived' }
])?.[0]
expect(row).toMatchObject({ id: 1, actionName: 'review_requested' })
expect(row?.targetIid).toBeUndefined()
expect(row?.state).toBeUndefined()
})
it('keeps an explicit targetIid null, which gitLabTodoTargetRef reads as no ref', () => {
expect(
reads(gitlabTodoListSchema, [{ ...RECORDED_TODO, targetIid: null }])?.[0]?.targetIid
).toBe(null)
})
})
describe('the two writes on this surface', () => {
it('reads the connect envelope and names a reply that is not one', () => {
expect(reads(linearAccountConnectedSchema, { ok: true }).ok).toBe(true)
expect(reads(linearAccountConnectedSchema, { ok: false, error: 'bad key' }).error).toBe(
'bad key'
)
expect(refuses(linearAccountConnectedSchema, null)).toBe(true)
})
it('reads anything for the repo preference write, whose body the screen never looks at', () => {
expect(refuses(taskRepoPreferenceWrittenSchema, null)).toBe(false)
expect(refuses(taskRepoPreferenceWrittenSchema, 'written')).toBe(false)
})
})
@@ -1,182 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { z } from 'zod'
import {
assignableUserListSchema,
detailCheckListSchema,
detailCommentListSchema,
detailFileListSchema,
reviewSummaryListSchema,
taskCommentWriteEnvelopeSchema,
taskMutationEnvelopeSchema
} from './task-provider-entity-reply-schema'
function reads<T>(schema: z.ZodType<T, unknown>, value: unknown): T {
const parsed = schema.safeParse(value)
if (!parsed.success) {
throw new Error(`expected a readable reply: ${parsed.error.message}`)
}
return parsed.data
}
function refuses(schema: z.ZodType<unknown, unknown>, value: unknown): boolean {
return !schema.safeParse(value).success
}
const COMMENT = { id: 902, author: 'You', body: 'a comment', createdAt: '2020-01-01T00:00:00.000Z' }
describe('the mutation envelope', () => {
it('keeps ok tri-state, so absent is the success main read and false is a refusal', () => {
expect(reads(taskMutationEnvelopeSchema, {}).ok).toBeUndefined()
expect(reads(taskMutationEnvelopeSchema, { ok: true }).ok).toBe(true)
expect(reads(taskMutationEnvelopeSchema, { ok: false }).ok).toBe(false)
})
it('reads a non-boolean ok as absent, which is the success main read for it', () => {
expect(reads(taskMutationEnvelopeSchema, { ok: 'false' }).ok).toBeUndefined()
})
it('requires the container, which is the property read main died on', () => {
expect(refuses(taskMutationEnvelopeSchema, null)).toBe(true)
expect(refuses(taskMutationEnvelopeSchema, 'accepted')).toBe(true)
expect(refuses(taskMutationEnvelopeSchema, 7)).toBe(true)
})
it('drops an error that is not text, so the call site shows its own copy', () => {
expect(reads(taskMutationEnvelopeSchema, { ok: false, error: 'boom' }).error).toBe('boom')
expect(
reads(taskMutationEnvelopeSchema, { ok: false, error: { message: 'boom' } }).error
).toBeUndefined()
})
it('passes members it does not declare straight through', () => {
expect(reads(taskMutationEnvelopeSchema, { ok: true, number: 11 })).toMatchObject({
number: 11
})
})
})
describe('a comment row', () => {
it('requires the id it is keyed by and the body it renders', () => {
expect(reads(detailCommentListSchema, [COMMENT])).toHaveLength(1)
expect(reads(detailCommentListSchema, [{ ...COMMENT, id: 'c-1' }])[0]?.id).toBe('c-1')
expect(reads(detailCommentListSchema, [{ ...COMMENT, id: undefined }])).toEqual([])
expect(reads(detailCommentListSchema, [{ ...COMMENT, body: undefined }])).toEqual([])
})
it('drops the unreadable row rather than the whole list', () => {
expect(reads(detailCommentListSchema, [COMMENT, { id: 1 }])).toHaveLength(1)
})
it('refuses a list that is not one', () => {
expect(refuses(detailCommentListSchema, { comments: [] })).toBe(true)
expect(refuses(detailCommentListSchema, 'none')).toBe(true)
})
it('forwards every provider reaction, including the two vocabularies mobile never declared', () => {
const github = [
{ content: '+1', count: 3 },
{ content: '-1', count: 1 },
{ content: 'heart', count: 1 }
]
expect(
reads(detailCommentListSchema, [{ ...COMMENT, reactions: github }])[0]?.reactions
).toEqual(github)
const gitlab = [{ name: 'thumbsup', count: 2 }]
expect(
reads(detailCommentListSchema, [{ ...COMMENT, reactions: gitlab }])[0]?.reactions
).toMatchObject([{ count: 2 }])
})
it('keeps the count the chip filters on and lets a malformed content read as absent', () => {
const row = reads(detailCommentListSchema, [
{ ...COMMENT, reactions: [{ content: 7, count: 2 }] }
])[0]
expect(row?.reactions).toEqual([{ count: 2 }])
expect(
reads(detailCommentListSchema, [{ ...COMMENT, reactions: [{ content: '+1' }] }])[0]?.reactions
).toEqual([])
})
it('leaves every guarded member exactly as the host sent it', () => {
const row = reads(detailCommentListSchema, [
{ ...COMMENT, path: 'src/a.ts', line: 12, threadId: 't-1', isResolved: false }
])[0]
expect(row).toMatchObject({ path: 'src/a.ts', line: 12, threadId: 't-1', isResolved: false })
})
})
describe('the comment write envelope', () => {
it('drops a comment the timeline could not key, leaving the local echo in place', () => {
expect(
reads(taskCommentWriteEnvelopeSchema, { ok: true, comment: COMMENT }).comment
).toMatchObject({ id: 902 })
expect(
reads(taskCommentWriteEnvelopeSchema, { ok: true, comment: { id: 902 } }).comment
).toBeUndefined()
expect(reads(taskCommentWriteEnvelopeSchema, { ok: true }).comment).toBeUndefined()
})
})
describe('a user row', () => {
it('requires the login every reader trims, and keeps an explicit null beside it', () => {
const rows = reads(assignableUserListSchema, [
{ login: 'octocat', name: 'Octo', avatarUrl: null }
])
expect(rows[0]).toMatchObject({ login: 'octocat', name: 'Octo', avatarUrl: null })
expect(reads(assignableUserListSchema, [{ name: 'Octo' }])).toEqual([])
})
it('keeps a review row own null state rather than defaulting it', () => {
expect(reads(reviewSummaryListSchema, [{ login: 'octocat', state: null }])[0]?.state).toBeNull()
expect(reads(reviewSummaryListSchema, [{ state: 'APPROVED' }])).toEqual([])
})
})
describe('a check row and a file row', () => {
it('keeps the host casing the tasks surface actually sends', () => {
const checks = reads(detailCheckListSchema, [
{ name: 'build', status: 'COMPLETED', conclusion: 'SUCCESS', url: '' }
])
expect(checks[0]).toMatchObject({ name: 'build', status: 'COMPLETED', conclusion: 'SUCCESS' })
})
it('drops a check with no name or no status', () => {
expect(reads(detailCheckListSchema, [{ status: 'completed' }])).toEqual([])
expect(reads(detailCheckListSchema, [{ name: 'build' }])).toEqual([])
})
it('requires the path a file row is matched by', () => {
expect(reads(detailFileListSchema, [{ path: 'src/a.ts' }])).toHaveLength(1)
expect(reads(detailFileListSchema, [{ oldPath: 'src/a.ts' }])).toEqual([])
})
it('carries every file status the host will accept back and drops one it would refuse', () => {
for (const status of [
'added',
'modified',
'removed',
'renamed',
'copied',
'changed',
'unchanged'
]) {
expect(reads(detailFileListSchema, [{ path: 'a', status }])[0]?.status).toBe(status)
}
// Absent status uses modified; forwarding an unknown arm would fail the host’s params validation.
expect(reads(detailFileListSchema, [{ path: 'a', status: 'ADDED' }])[0]?.status).toBeUndefined()
})
it('forwards a viewed state the host has and one this build predates', () => {
for (const viewerViewedState of ['DISMISSED', 'VIEWED', 'UNVIEWED', 'PENDING']) {
expect(
reads(detailFileListSchema, [{ path: 'a', viewerViewedState }])[0]?.viewerViewedState
).toBe(viewerViewedState)
}
})
it('salvages a malformed viewed state to absent and keeps the row', () => {
const row = reads(detailFileListSchema, [{ path: 'a', viewerViewedState: { v: 'VIEWED' } }])[0]
expect(row?.path).toBe('a')
expect(row?.viewerViewedState).toBeUndefined()
})
})
@@ -1,63 +1,11 @@
import { describe, expect, it } from 'vitest'
import {
taskLinearStatusSchema,
taskPreferenceWriteSchema,
taskPreflightSchema,
taskRuntimeStatusSchema,
taskUiStateSchema
} from './task-runtime-reply-schema'
describe('the runtime status', () => {
it('reads the representative capability lists', () => {
for (const capabilities of [['mobile.tasks.v1'], ['files.mutation-ownership.v1']]) {
const parsed = taskRuntimeStatusSchema.safeParse({ capabilities })
expect(parsed.success && parsed.data).toMatchObject({ capabilities })
}
})
it('requires the container main read `.capabilities` off', () => {
expect(taskRuntimeStatusSchema.safeParse(null).success).toBe(false)
expect(taskRuntimeStatusSchema.safeParse('ok').success).toBe(false)
expect(taskRuntimeStatusSchema.safeParse({}).success).toBe(true)
})
it('drops a non-string capability, which `includes` could never have matched', () => {
const parsed = taskRuntimeStatusSchema.safeParse({ capabilities: ['push.v1', 7] })
expect(parsed.success && parsed.data).toMatchObject({ capabilities: ['push.v1'] })
})
it('leaves worktreeCreateIdempotency untouched in all four states the probe triages', () => {
for (const advertised of [undefined, null, 'nonsense', { dedupeTtlMs: 45_000 }]) {
const parsed = taskRuntimeStatusSchema.safeParse({ worktreeCreateIdempotency: advertised })
expect(parsed.success).toBe(true)
expect(parsed.success ? parsed.data.worktreeCreateIdempotency : 'unparsed').toEqual(
advertised
)
}
})
})
describe('the persisted UI state', () => {
it('answers the `ui` member, which is what the member reader it replaces did', () => {
const parsed = taskUiStateSchema.safeParse({
ui: { sortBy: 'name', trustedOrcaHooks: { 'repo-1': { all: { approvedAt: 1 } } } }
})
expect(parsed.success && parsed.data).toMatchObject({
sortBy: 'name',
trustedOrcaHooks: { 'repo-1': { all: { approvedAt: 1 } } }
})
})
it('reads the representative empty ui as an empty record, not as absent', () => {
const parsed = taskUiStateSchema.safeParse({ ui: {} })
expect(parsed.success && parsed.data).toEqual({})
})
it('answers undefined for a payload with no ui, where main read undefined off the object', () => {
const parsed = taskUiStateSchema.safeParse({})
expect(parsed.success && parsed.data).toBeUndefined()
})
it.each([null, undefined, 'ok', 7, [], true])(
'answers undefined for %j, so the other hydration legs survive an unreadable ui reply',
(payload) => {
@@ -69,28 +17,6 @@ describe('the persisted UI state', () => {
})
describe('the two advisory probes', () => {
it('reads the representative preflight and linear replies', () => {
expect(taskPreflightSchema.safeParse({ glab: { installed: false } }).success).toBe(true)
expect(taskLinearStatusSchema.safeParse({ connected: false }).success).toBe(true)
})
it('requires nothing, because every consumer compares the leaf to `true`', () => {
expect(taskPreflightSchema.safeParse({}).success).toBe(true)
expect(taskLinearStatusSchema.safeParse({}).success).toBe(true)
})
it('drops a malformed glab rather than reading it as installed', () => {
const parsed = taskPreflightSchema.safeParse({ glab: 'yes' })
expect(parsed.success ? parsed.data.glab : 'unparsed').toBeUndefined()
})
it('passes a host member no mobile consumer reads straight through', () => {
const parsed = taskPreflightSchema.safeParse({ gh: { installed: true, authenticated: true } })
expect(parsed.success && parsed.data).toMatchObject({
gh: { installed: true, authenticated: true }
})
})
// Advisory acceptance still decodes absent/null results; total readers must retain hydration defaults instead of throwing.
it.each([
['absent', undefined],
@@ -106,11 +32,3 @@ describe('the two advisory probes', () => {
expect(linear.success && linear.data.connected).toBeUndefined()
})
})
describe('the three preference writes', () => {
it('accept every payload, because no call site reads their body', () => {
for (const reply of [null, undefined, 0, 'written', { ok: true }, []]) {
expect(taskPreferenceWriteSchema.safeParse(reply).success).toBe(true)
}
})
})
@@ -203,26 +203,6 @@ describe('useHostRepoList', () => {
expect(probe.resource.state.status).toBe('idle')
})
// Keep resource/callback identities stable so consumer effects cannot form a render loop.
it('keeps a stable identity across renders that change nothing', async () => {
const probe = mountResource()
const first = probe.resource
probe.rerender()
expect(probe.resource).toBe(first)
expect(probe.resource.ensureLoaded).toBe(first.ensureLoaded)
expect(probe.resource.reload).toBe(first.reload)
await act(async () => {
void probe.resource.ensureLoaded()
})
await probe.settle(0, [{ id: 'a' }])
expect(probe.resource.ensureLoaded).toBe(first.ensureLoaded)
expect(probe.resource.reload).toBe(first.reload)
const loaded = probe.resource
probe.rerender()
expect(probe.resource).toBe(loaded)
})
it('re-reads the host on an explicit reload', async () => {
const probe = mountResource()
await act(async () => {
@@ -1,18 +0,0 @@
import { describe, expect, it } from 'vitest'
import { isWorkItemLookupText } from './work-item-lookup-text'
describe('isWorkItemLookupText', () => {
it('treats references as lookup text, not names', () => {
expect(isWorkItemLookupText('#42')).toBe(true)
expect(isWorkItemLookupText('https://github.com/o/r/issues/1')).toBe(true)
expect(isWorkItemLookupText('https://gitlab.com/g/p/-/merge_requests/2')).toBe(true)
expect(isWorkItemLookupText('https://linear.app/acme/issue/ENG-9')).toBe(true)
expect(isWorkItemLookupText('ENG-9')).toBe(false)
})
it('treats plain names as non-lookup text', () => {
expect(isWorkItemLookupText('')).toBe(false)
expect(isWorkItemLookupText('fix the login bug')).toBe(false)
expect(isWorkItemLookupText('https://linear.app/acme/project/mobile')).toBe(false)
})
})
@@ -1,61 +1,8 @@
import { describe, expect, it } from 'vitest'
import {
normalizeWorkspaceAgent,
pickWorkspaceAgent,
resolveWorkspaceAgentSelection,
workspaceAgentLabel
} from './workspace-agent-selection'
import { resolveWorkspaceAgentSelection } from './workspace-agent-selection'
describe('workspace agent selection', () => {
it('uses an installed explicit default agent', () => {
expect(pickWorkspaceAgent({ defaultTuiAgent: 'codex' }, new Set(['claude', 'codex']))).toBe(
'codex'
)
})
it('falls back by desktop auto-pick order when the default is unavailable on the target host', () => {
expect(pickWorkspaceAgent({ defaultTuiAgent: 'codex' }, new Set(['claude']))).toBe('claude')
})
it('skips disabled preferred and fallback agents', () => {
expect(
pickWorkspaceAgent(
{ defaultTuiAgent: 'codex', disabledTuiAgents: ['codex'] },
new Set(['claude', 'codex'])
)
).toBe('claude')
expect(
pickWorkspaceAgent(
{ defaultTuiAgent: null, disabledTuiAgents: ['claude', 'codex', 'not-real'] },
new Set(['claude', 'codex'])
)
).toBe('blank')
})
it('honors blank terminal as an explicit no-agent preference', () => {
expect(pickWorkspaceAgent({ defaultTuiAgent: 'blank' }, new Set(['claude', 'codex']))).toBe(
'blank'
)
})
it('returns blank when detection completed and no known agent exists', () => {
expect(pickWorkspaceAgent({ defaultTuiAgent: null }, new Set(['unknown-agent']))).toBe('blank')
})
it('uses the preferred/default display value while detection is still pending', () => {
expect(pickWorkspaceAgent({ defaultTuiAgent: 'codex' }, null)).toBe('codex')
expect(pickWorkspaceAgent({ defaultTuiAgent: null }, null)).toBe('claude')
expect(
pickWorkspaceAgent({ defaultTuiAgent: 'codex', disabledTuiAgents: ['codex'] }, null)
).toBe('claude')
})
it('normalizes legacy blank sentinel and labels known choices', () => {
expect(normalizeWorkspaceAgent('__blank__')).toBe('blank')
expect(workspaceAgentLabel('codex')).toBe('Codex')
})
it('keeps automatic selection current while create selection is active', () => {
expect(
resolveWorkspaceAgentSelection({
@@ -1,18 +1,5 @@
import { describe, expect, it } from 'vitest'
import { startupAgentCreateFields, buildTaskWorkspaceCreateParams } from './workspace-create-params'
describe('startupAgentCreateFields', () => {
it('sends startupAgent + createdWithAgent so the host resolves launch args', () => {
expect(startupAgentCreateFields('claude')).toEqual({
startupAgent: 'claude',
createdWithAgent: 'claude'
})
})
it('launches no agent when none was picked', () => {
expect(startupAgentCreateFields(undefined)).toEqual({})
})
})
import { buildTaskWorkspaceCreateParams } from './workspace-create-params'
describe('task workspace create params', () => {
it('passes a GitHub PR URL as an agent draft and links the PR', () => {
@@ -226,23 +213,4 @@ describe('task workspace create params', () => {
// A stray linkedLinearIssue would relink the workspace to the wrong provider.
expect(params).not.toHaveProperty('linkedLinearIssue')
})
it('keeps a user-edited workspace name over the derived Jira name', () => {
expect(
buildTaskWorkspaceCreateParams({
item: {
provider: 'jira',
source: {
key: 'ORCA-9',
title: 'Rename me',
url: 'https://acme.atlassian.net/browse/ORCA-9'
}
},
targetRepoId: 'repo-jira',
setupDecision: 'inherit',
workspaceName: 'my-branch',
nameIsAutoManaged: false
})
).toMatchObject({ name: 'my-branch' })
})
})
@@ -1,112 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
agentLaunchCreateReceiptSchema,
worktreeCreateReceiptSchema,
worktreeHostedBaseSchema
} from './workspace-create-reply-schema'
// Preserve receipt fields and keep empty ids and soft-error messages reachable.
describe('the worktree create receipt', () => {
it('reads every representative create', () => {
for (const result of [
{ worktree: { id: 'wt-1', displayName: 'ORC-1 Recorded issue' } },
{ worktree: { id: 'wt-2' }, warning: 'shallow clone' },
{ worktree: { id: 'repo-1::/w' }, warning: ' startup terminal failed ' }
]) {
expect(worktreeCreateReceiptSchema.safeParse(result)).toMatchObject({ success: true })
}
})
it('keeps the warning untrimmed, because both readers trim it themselves', () => {
const parsed = worktreeCreateReceiptSchema.safeParse({
worktree: { id: 'w' },
warning: ' startup terminal failed '
})
expect(parsed.success && parsed.data).toMatchObject({ warning: ' startup terminal failed ' })
})
it('leaves the empty-id arm reachable rather than making it a decode failure', () => {
const parsed = worktreeCreateReceiptSchema.safeParse({ worktree: { id: '' } })
expect(parsed.success && parsed.data).toMatchObject({ worktree: { id: '' } })
})
it('names a receipt with no worktree record, which routed the phone to /session/undefined', () => {
expect(worktreeCreateReceiptSchema.safeParse({ warning: 'x' }).success).toBe(false)
expect(worktreeCreateReceiptSchema.safeParse({ worktree: {} }).success).toBe(false)
expect(worktreeCreateReceiptSchema.safeParse(null).success).toBe(false)
})
})
describe('the agent.launch receipt', () => {
it('reads the representative structured receipt whole', () => {
const result = {
outcome: { kind: 'structured', sessionId: 'sess-1', handle: 't-1' },
worktreeId: 'repo-1::/w',
warning: ' startup terminal failed ',
receipt: {
mode: 'structured',
preferred: 'structured',
reason: 'user_default',
detail: 'Structured session created.'
}
}
expect(agentLaunchCreateReceiptSchema.safeParse(result)).toMatchObject({
success: true,
data: result
})
})
it('requires nothing under the container, because the reader guards every member', () => {
expect(agentLaunchCreateReceiptSchema.safeParse({}).success).toBe(true)
})
it('names a receipt that is not an object at all', () => {
for (const result of [null, 'launched', 7, true]) {
expect(agentLaunchCreateReceiptSchema.safeParse(result).success).toBe(false)
}
})
})
describe('the hosted base resolvers', () => {
it('reads both representative successes', () => {
expect(worktreeHostedBaseSchema.safeParse({ baseBranch: 'main' }).success).toBe(true)
expect(
worktreeHostedBaseSchema.safeParse({ baseBranch: 'main', compareBaseRef: 'origin/main' })
.success
).toBe(true)
})
it('preserves a soft error beside a base branch', () => {
const parsed = worktreeHostedBaseSchema.safeParse({
error: 'pull request not found',
baseBranch: 'main'
})
expect(parsed.success && parsed.data).toMatchObject({ error: 'pull request not found' })
})
it('keeps an empty soft-error message, which the create replaces with its own copy', () => {
const parsed = worktreeHostedBaseSchema.safeParse({ error: '' })
expect(parsed.success && parsed.data).toMatchObject({ error: '' })
})
it('forwards the rest of a start point the create spreads into its params', () => {
const parsed = worktreeHostedBaseSchema.safeParse({
baseBranch: 'main',
pushTarget: { remoteName: 'origin', branchName: 'feature' },
branchNameOverride: 'pr-12',
maintainerCanModify: false
})
expect(parsed.success && parsed.data).toMatchObject({
pushTarget: { remoteName: 'origin', branchName: 'feature' },
branchNameOverride: 'pr-12',
maintainerCanModify: false
})
})
it('names a reply that is neither arm, where `in` was a TypeError', () => {
expect(worktreeHostedBaseSchema.safeParse({}).success).toBe(false)
expect(worktreeHostedBaseSchema.safeParse('main').success).toBe(false)
expect(worktreeHostedBaseSchema.safeParse(null).success).toBe(false)
})
})
+1 -60
View File
@@ -1,27 +1,7 @@
import { describe, expect, it } from 'vitest'
import {
deriveWorkspaceSshGate,
workspaceSshStatusLabel,
type WorkspaceSshRecord
} from './workspace-ssh-gate'
import { deriveWorkspaceSshGate, type WorkspaceSshRecord } from './workspace-ssh-gate'
describe('workspace SSH gate', () => {
it('does not gate local repositories', () => {
expect(
deriveWorkspaceSshGate({
connectionId: null,
state: null,
connecting: false
})
).toEqual({
status: null,
requiresConnection: false,
connectInProgress: false,
error: null,
needsDesktopServerRecovery: false
})
})
it('requires connection for remote repos until the matching target is connected', () => {
expect(
deriveWorkspaceSshGate({
@@ -56,38 +36,6 @@ describe('workspace SSH gate', () => {
})
})
it('marks connecting, relay deploy, and reconnect states as in progress', () => {
for (const status of ['connecting', 'deploying-relay', 'reconnecting'] as const) {
expect(
deriveWorkspaceSshGate({
connectionId: 'ssh-1',
state: { targetId: 'ssh-1', status, error: null, reconnectAttempt: 0 },
connecting: false
})
).toMatchObject({ requiresConnection: true, connectInProgress: true })
}
})
it('keeps auth and relay errors visible in the drawer', () => {
expect(
deriveWorkspaceSshGate({
connectionId: 'ssh-1',
state: {
targetId: 'ssh-1',
status: 'auth-failed',
error: 'Permission denied',
reconnectAttempt: 0
},
connecting: false
})
).toMatchObject({
status: 'auth-failed',
requiresConnection: true,
connectInProgress: false,
error: 'Permission denied'
})
})
it('asks for the desktop recovery only for the refusal the desktop offers it on', () => {
const named = 'run `orcad --reclaim-stale-lock --data-root /home/dev/.orca` there'
const gate = (managedServer: WorkspaceSshRecord['managedServer']) =>
@@ -104,11 +52,4 @@ describe('workspace SSH gate', () => {
expect(gate({ ...refused, kind: 'relay' })).toBe(false)
expect(gate({ ...refused, serving: { detail: named } })).toBe(false)
})
it('labels user-visible SSH states', () => {
expect(workspaceSshStatusLabel(null)).toBe('Disconnected')
expect(workspaceSshStatusLabel('deploying-relay')).toBe('Deploying relay')
expect(workspaceSshStatusLabel('auth-failed')).toBe('Authentication failed')
expect(workspaceSshStatusLabel('connected')).toBe('Connected')
})
})
@@ -1,63 +0,0 @@
// @vitest-environment happy-dom
import { describe, expect, it, vi } from 'vitest'
import { createTerminalDocumentScope } from './document-scope'
import { cancelDocumentFrames, scheduleDocumentFrame } from './document-frame-registry'
// Disposal can call back into document modules; cancellation must remove pending frames and refuse new ones.
describe('the document frame registry', () => {
it('holds a frame until it runs, then forgets it', () => {
const scope = createTerminalDocumentScope()
const frames: FrameRequestCallback[] = []
vi.spyOn(globalThis, 'requestAnimationFrame').mockImplementation((callback) => {
frames.push(callback)
return frames.length
})
const callback = vi.fn()
const id = scheduleDocumentFrame(scope, callback)
expect(callback).not.toHaveBeenCalled()
expect(scope.scheduledFrames).toEqual([id])
frames[0]!(123)
expect(callback).toHaveBeenCalledExactlyOnceWith(123)
expect(scope.scheduledFrames).toEqual([])
vi.restoreAllMocks()
})
it('takes back every pending frame and then refuses to schedule', () => {
const scope = createTerminalDocumentScope()
const cancelled: number[] = []
let next = 0
vi.spyOn(globalThis, 'requestAnimationFrame').mockImplementation(() => {
next += 1
return next
})
vi.spyOn(globalThis, 'cancelAnimationFrame').mockImplementation((id) => cancelled.push(id))
const first = scheduleDocumentFrame(scope, () => {})
const second = scheduleDocumentFrame(scope, () => {})
cancelDocumentFrames(scope)
expect(cancelled).toEqual([first, second])
expect(scope.scheduledFrames).toEqual([])
const requests = vi.mocked(globalThis.requestAnimationFrame).mock.calls.length
expect(scheduleDocumentFrame(scope, () => {})).toBe(-1)
expect(vi.mocked(globalThis.requestAnimationFrame).mock.calls.length).toBe(requests)
expect(scope.scheduledFrames).toEqual([])
vi.restoreAllMocks()
})
it('refuses for good, and the next document starts from a scope that does not know', () => {
const scope = createTerminalDocumentScope()
vi.spyOn(globalThis, 'requestAnimationFrame').mockImplementation(() => 7)
vi.spyOn(globalThis, 'cancelAnimationFrame').mockImplementation(() => {})
cancelDocumentFrames(scope)
expect(scope.framesStopped).toBe(true)
// Stopped scopes never restart; a new document gets a fresh scope.
const next = createTerminalDocumentScope()
expect(next.framesStopped).toBe(false)
expect(scheduleDocumentFrame(next, () => {})).toBe(7)
expect(next.scheduledFrames).toEqual([7])
vi.restoreAllMocks()
})
})
@@ -122,23 +122,6 @@ describe('two terminal documents on one page', () => {
two.started.stop()
})
// The same event inside this host must still reach it, ruling out an inert dispatcher.
it('cancels its own selection when the two fingers land in its own host', () => {
const first = plantHost('first-host')
const second = plantHost('second-host')
const one = startDocumentIn(first)
const two = startDocumentIn(second)
selectAllInBoth(one, two)
fireTwoFingerTouchStart(surfaceOf(first))
expect(pinchCancels(one.posted)).toHaveLength(1)
expect(pinchCancels(two.posted)).toHaveLength(0)
one.started.stop()
two.started.stop()
})
// Event ownership is not enough: page-wide touches must also exclude fingers in the other terminal.
it("does not read another host's finger as its own second one", () => {
const first = plantHost('first-host')
@@ -278,20 +261,6 @@ describe('keyboard-avoidance metrics across a pinch', () => {
doc.started.stop()
})
it('reports a release that changes the preset once, through the refit', async () => {
const doc = startMeasuredDocument()
await settle()
const before = metricsOf(doc.posted).length
pinchTo(doc, 30)
const afterWrite = metricsOf(doc.posted).length
await settle()
expect(afterWrite).toBe(before + 1)
expect(metricsOf(doc.posted).length).toBe(afterWrite + 1)
doc.started.stop()
})
it('never reports the pre-refit pitch when a release lands while a refit is pending', async () => {
const doc = startMeasuredDocument()
await settle()
@@ -1,70 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
documentModuleNames,
documentModuleSource,
exportedLifecycleFunctions,
parseTimeEffects,
sequenceCalls,
topLevelDeclarationsReachAnElement
} from '../../test-support/webview-document-census'
// Module-level effects would bind mounts before lifecycle startup and evade stop; require declarations with inert initializers.
// Factory-local state declarations remain safe because each document call gets fresh bindings.
const DIRECTORY = import.meta.dirname
const ENTRY = 'native-document-entry'
const THE_SEQUENCE = 'create-terminal-document'
const MODULES = documentModuleNames(DIRECTORY, [ENTRY])
const moduleSource = (name: string) => documentModuleSource(DIRECTORY, name)
const sequenceCallsTo = (functionName: string) =>
sequenceCalls(moduleSource(THE_SEQUENCE), functionName, [
'startTerminalDocument',
'stopTerminalDocument'
])
describe('the document modules at parse time', () => {
it('do no work: every effect is in a start function the hosts call', () => {
expect(MODULES.length).toBeGreaterThan(30)
expect(MODULES.flatMap((name) => parseTimeEffects(name, moduleSource(name)))).toEqual([])
})
it('declare nothing that reaches an element', () => {
// Element reads in declaration initializers are still effects; check every module.
for (const name of MODULES) {
expect({
name,
reaches: topLevelDeclarationsReachAnElement(name, moduleSource(name))
}).toEqual({ name, reaches: false })
}
})
it('start and stop: the sequence calls every one there is, and undoes them in reverse', () => {
// Compare start/stop names, not counts, so exported-but-unused lifecycle hooks cannot pass.
// stopEdgeScroll is owned by stopSelectionOverlay rather than the top-level sequence.
const exported = (keyword: 'start' | 'stop') =>
MODULES.filter((name) => name !== THE_SEQUENCE).flatMap((name) =>
exportedLifecycleFunctions(moduleSource(name), keyword, 'TerminalDocumentScope')
)
const started = sequenceCallsTo('startTerminalDocument')
const stopped = sequenceCallsTo('stopTerminalDocument').filter(
(name) => name !== 'cancelDocumentFrames'
)
expect([...started].sort()).toEqual(exported('start').sort())
expect([...stopped].sort()).toEqual(
exported('stop')
.filter((name) => name !== 'stopEdgeScroll')
.sort()
)
const paired = started.filter((name) => stopped.includes(name.replace(/^start/, 'stop')))
expect(paired.map((name) => name.replace(/^start/, 'stop'))).toEqual(
stopped.filter((name) => paired.includes(name.replace(/^stop/, 'start'))).toReversed()
)
expect(sequenceCallsTo('stopTerminalDocument').at(-1)).toBe('cancelDocumentFrames')
})
})
@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { laidOutCellBox, reportLaidOutCellBox } from './laid-out-cell-box'
import { reportLaidOutCellBox } from './laid-out-cell-box'
import { createTerminalDocumentScope, type TerminalDocumentScope } from './document-scope'
import { startTerminalDocument, stopTerminalDocument } from './create-terminal-document'
import type { TerminalDocumentHost } from './document-host-seams'
@@ -31,15 +31,6 @@ describe('laidOutCellBox', () => {
return scope
}
it('reads the box xterm laid out at the current text scale, with its grid', () => {
const scope = scopeWithCell({ width: 29 / 3, height: 21 }, 16)
expect(laidOutCellBox(scope)).toEqual({
cellBox: { fontScale: 1.25, cellWidth: 29 / 3, cellHeight: 21 },
cols: 55,
rows: 47
})
})
it('tells the host each new box once, and refits only a box that changed at a kept grid', () => {
const posted: Record<string, unknown>[] = []
const cell = { width: 29 / 3, height: 21 }
@@ -125,41 +116,6 @@ describe('a started document', () => {
const reflowTo = (scope: TerminalDocumentScope, cols: number) =>
handleMsg(scope, { type: 'reflow', cols, rows: 47 })
it('takes the frame the app laid out from init, resize and reflow', () => {
const { scope } = started()
try {
handleMsg(scope, {
type: 'init',
cols: 55,
rows: 47,
initialData: '',
preserveScroll: false,
frame: { width: 427.5, height: 710 }
})
expect(scope.hostFrame).toEqual({ width: 427.5, height: 710 })
handleMsg(scope, { type: 'resize', cols: 54, rows: 47, frame: { width: 420, height: 700 } })
expect(scope.hostFrame).toEqual({ width: 420, height: 700 })
handleMsg(scope, { type: 'reflow', cols: 53, rows: 46, frame: { width: 410, height: 690 } })
expect(scope.hostFrame).toEqual({ width: 410, height: 690 })
} finally {
stopTerminalDocument(scope)
}
})
it('reports ready with the box its own terminal laid out, at the app text scale', () => {
const { scope, posted, built } = started({ start: () => ({ textScale: 1.25, shown: true }) })
try {
expect(built).toHaveLength(1)
expect(built[0].options.fontSize).toBe(16)
expect(posted[0]).toEqual({
type: 'web-ready',
cellBox: { fontScale: 1.25, cellWidth: (23 / 3) * (16 / 13), cellHeight: 15 * (16 / 13) }
})
} finally {
stopTerminalDocument(scope)
}
})
it('leaves no live terminal when opening the one it builds before ready throws', () => {
const double = terminalDocumentDouble()
double.terminal.open = () => {
@@ -185,21 +141,6 @@ describe('a started document', () => {
}
})
it('reuses that terminal for the first init, so an open builds one xterm', async () => {
const { scope, posted, built, init } = started()
try {
const prepared = scope.term
init()
await untilReady(posted)
expect(built).toHaveLength(1)
expect(scope.term).toBe(prepared)
expect(scope.term?.cols).toBe(55)
expect(scope.term?.rows).toBe(47)
} finally {
stopTerminalDocument(scope)
}
})
it('keeps the terminal built before ready out of sight until the first init has replayed', async () => {
const { scope, posted, init } = started()
try {
@@ -254,19 +195,6 @@ describe('a started document', () => {
}
})
it('reports a changed cell width on the next render', async () => {
const { scope, cell, posted, render, init } = started()
try {
init()
await untilReady(posted)
cell.width = 7.8
render()
expect(boxes(posted).at(-1)).toEqual({ fontScale: 1, cellWidth: 7.8, cellHeight: 15 })
} finally {
stopTerminalDocument(scope)
}
})
it("refits a DOM first init once, and not again on the refit's own report", async () => {
const { scope, cell, posted, render, init } = started()
try {
@@ -283,42 +211,6 @@ describe('a started document', () => {
}
})
it('never refits a box that came with a new grid, so the DOM renderer cannot loop', async () => {
const { scope, cell, posted, render, init } = started()
try {
init()
await untilReady(posted)
for (const [cols, width] of [
[50, 7.9],
[55, 7.8],
[54, 8]
]) {
cell.width = width
reflowTo(scope, cols)
render()
}
expect(refits(posted)).toEqual([false, false, false])
} finally {
stopTerminalDocument(scope)
}
})
it('refits a renderer swap at a grid applied in place', async () => {
const { scope, cell, posted, render, init } = started()
try {
init()
await untilReady(posted)
reflowTo(scope, 50)
render()
expect(refits(posted)).toEqual([])
cell.width = 7.8
render()
expect(refits(posted)).toEqual([true])
} finally {
stopTerminalDocument(scope)
}
})
it('refits a re-init at the same grid with a different renderer', async () => {
const { scope, cell, posted, init } = started()
try {
@@ -154,15 +154,6 @@ describe('the terminal waits for its bundled glyphs', () => {
stopMessageBridge(fonts.scope)
})
it('still starts the terminal if font decoding fails', async () => {
const fonts = pendingFonts()
startMessageBridge(fonts.scope)
fonts.fail()
await fonts.loaded.catch(() => {})
expect(fonts.postToHost).toHaveBeenCalledWith({ type: 'web-ready', cellBox: null })
stopMessageBridge(fonts.scope)
})
it('unwinds the document and reports an error if deferred startup fails', async () => {
const fonts = pendingFonts()
document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP
@@ -186,13 +177,4 @@ describe('the terminal waits for its bundled glyphs', () => {
message: expect.stringContaining('readiness transport failed')
})
})
it('does not revive a document stopped during the font load', async () => {
const fonts = pendingFonts()
startMessageBridge(fonts.scope)
stopMessageBridge(fonts.scope)
fonts.finish()
await fonts.loaded
expect(fonts.postToHost).not.toHaveBeenCalled()
})
})
@@ -152,25 +152,6 @@ describe('the bundled native document', () => {
expect(document.getElementById('terminal-surface')?.contains(opened[0]!)).toBe(true)
})
it('answers a ping through the bridge, which is what native readiness reads', () => {
document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP
const posted: Record<string, unknown>[] = []
const { Terminal } = engineDouble()
Object.assign(globalThis, {
ReactNativeWebView: {
postMessage: (message: string) => posted.push(JSON.parse(message))
},
Terminal,
__engineErrors: []
})
evaluateBundle()
window.dispatchEvent(
new MessageEvent('message', { data: JSON.stringify({ type: 'ping', id: 9 }) })
)
expect(posted).toContainEqual({ type: 'pong', pingId: 9 })
})
it('takes a theme and a write before init, and init is what decides they are stale', async () => {
// Early writes must be superseded by init’s snapshot and theme, not replayed underneath it.
document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP
@@ -1,28 +1,11 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { WebSocket } from 'ws'
import { handleMockTerminalRequest } from '../../scripts/mock-server-terminal-stream'
import {
handleRequest,
type RpcRequest,
type RpcRespond,
type RpcResponse
} from '../../scripts/mock-server-rpc-handlers'
type DeferredResponse = {
response: RpcResponse
shouldSend?: () => boolean
}
function success(id: string, result: unknown, streaming?: boolean): RpcResponse {
return {
id,
ok: true,
result,
...(streaming ? { streaming: true as const } : {}),
_meta: { runtimeId: 'test' }
}
}
function request(id: string, method: string): RpcRequest {
return { id, method, params: { terminal: 'term-1', viewport: { cols: 80, rows: 24 } } }
}
@@ -33,31 +16,6 @@ describe('mock terminal stream cancellation', () => {
vi.unstubAllEnvs()
})
it('invalidates delayed frames after resubscribe and unsubscribe', () => {
vi.useFakeTimers()
const ws = { OPEN: 1, readyState: 1 } as unknown as WebSocket
const deferred: DeferredResponse[] = []
const respond: RpcRespond = (response, shouldSend) => {
deferred.push({ response, shouldSend })
}
const handle = (rpcRequest: RpcRequest) =>
handleMockTerminalRequest(rpcRequest, respond, success, ws, () => 'wt')
expect(handle(request('old', 'terminal.subscribe'))).toBe(true)
vi.advanceTimersByTime(500)
expect(deferred.filter(({ response }) => response.id === 'old')).toHaveLength(2)
expect(handle(request('new', 'terminal.subscribe'))).toBe(true)
const oldResponses = deferred.filter(({ response }) => response.id === 'old')
const newResponses = deferred.filter(({ response }) => response.id === 'new')
expect(newResponses).toHaveLength(1)
expect(oldResponses.every(({ shouldSend }) => shouldSend?.() === false)).toBe(true)
expect(newResponses.every(({ shouldSend }) => shouldSend?.() === true)).toBe(true)
expect(handle(request('stop', 'terminal.unsubscribe'))).toBe(true)
expect(newResponses.every(({ shouldSend }) => shouldSend?.() === false)).toBe(true)
})
it('drops queued delayed frames after stream cancellation', () => {
vi.useFakeTimers()
vi.stubEnv('MOCK_RPC_DELAY_TERMINAL_SUBSCRIBE_MS', '1000')
@@ -1,8 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import {
readTerminalAutoRestoreFitMs,
saveTerminalAutoRestoreFitMs,
setTerminalAutoRestoreFitMsForHost
saveTerminalAutoRestoreFitMs
} from './terminal-auto-restore-fit-state'
describe('terminal auto restore fit state', () => {
@@ -35,19 +34,4 @@ describe('terminal auto restore fit state', () => {
await expect(readTerminalAutoRestoreFitMs({ sendRequest })).resolves.toBeNull()
await expect(saveTerminalAutoRestoreFitMs({ sendRequest }, 60_000)).resolves.toBeNull()
})
it('returns the existing state object when a host value is unchanged', () => {
const current = { hostA: 60_000, hostB: null }
expect(setTerminalAutoRestoreFitMsForHost(current, 'hostA', 60_000)).toBe(current)
expect(setTerminalAutoRestoreFitMsForHost(current, 'hostB', null)).toBe(current)
})
it('updates one host while preserving other host values', () => {
const current = { hostA: 60_000, hostB: null }
const next = setTerminalAutoRestoreFitMsForHost(current, 'hostA', 300_000)
expect(next).not.toBe(current)
expect(next).toEqual({ hostA: 300_000, hostB: null })
})
})
@@ -1,177 +0,0 @@
// @vitest-environment happy-dom
import { Terminal, type ITerminalInitOnlyOptions, type ITerminalOptions } from '@xterm/xterm'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { MOBILE_TERMINAL_CARET_OPTIONS } from './terminal-webview-html'
type CursorCoreService = {
isCursorHidden: boolean
isCursorInitialized: boolean
}
type ListenerOwner = Pick<EventTarget, 'addEventListener' | 'removeEventListener'>
function cursorCoreService(terminal: Terminal): CursorCoreService {
const core = (terminal as unknown as { _core?: { coreService?: CursorCoreService } })._core
expect(core, 'xterm private _core compatibility').toBeDefined()
expect(core?.coreService, 'xterm private coreService compatibility').toBeDefined()
expect(typeof core?.coreService?.isCursorHidden).toBe('boolean')
expect(typeof core?.coreService?.isCursorInitialized).toBe('boolean')
return core!.coreService!
}
function listenerOwner(target: EventTarget): ListenerOwner {
let owner = target as ListenerOwner | null
while (owner) {
if (Object.hasOwn(owner, 'addEventListener') && Object.hasOwn(owner, 'removeEventListener')) {
return owner
}
owner = Object.getPrototypeOf(owner) as ListenerOwner | null
}
throw new Error(`No event-listener owner for ${target.constructor.name}`)
}
function eventListenerOwners(): ListenerOwner[] {
const targets: EventTarget[] = [
document,
document.defaultView!,
document.documentElement,
document.body,
document.createElement('div'),
document.createElement('textarea'),
document.createElement('canvas')
]
return [...new Set(targets.map(listenerOwner))]
}
function trackEventListenerCleanup(): () => {
added: number
removed: number
unreleased: string[]
} {
const registrations: Array<{
capture: boolean
listener: EventListenerOrEventListenerObject
removed: boolean
target: EventTarget
type: string
}> = []
const capture = (options?: boolean | AddEventListenerOptions | EventListenerOptions): boolean =>
typeof options === 'boolean' ? options : (options?.capture ?? false)
const activeRegistration = (
target: EventTarget,
type: string,
listener: EventListenerOrEventListenerObject | null,
options?: boolean | AddEventListenerOptions | EventListenerOptions
) =>
registrations.find(
(entry) =>
!entry.removed &&
entry.target === target &&
entry.type === type &&
entry.listener === listener &&
entry.capture === capture(options)
)
for (const owner of eventListenerOwners()) {
const addEventListener = owner.addEventListener
const removeEventListener = owner.removeEventListener
vi.spyOn(owner, 'addEventListener').mockImplementation(function (
this: EventTarget,
type: string,
listener: EventListenerOrEventListenerObject | null,
options?: boolean | AddEventListenerOptions
) {
addEventListener.call(this, type, listener, options)
if (listener && !activeRegistration(this, type, listener, options)) {
registrations.push({
capture: capture(options),
listener,
removed: false,
target: this,
type
})
}
})
vi.spyOn(owner, 'removeEventListener').mockImplementation(function (
this: EventTarget,
type: string,
listener: EventListenerOrEventListenerObject | null,
options?: boolean | EventListenerOptions
) {
removeEventListener.call(this, type, listener, options)
const registration = listener && activeRegistration(this, type, listener, options)
if (registration) {
registration.removed = true
}
})
}
return () => ({
added: registrations.length,
removed: registrations.filter((registration) => registration.removed).length,
unreleased: registrations
.filter((registration) => !registration.removed)
.map((registration) => registration.type)
})
}
function write(terminal: Terminal, data: string): Promise<void> {
return new Promise((resolve) => terminal.write(data, resolve))
}
describe('xterm caret rendering oracle', () => {
beforeEach(() => {
vi.stubGlobal(
'OffscreenCanvas',
class {
getContext(): Pick<CanvasRenderingContext2D, 'font' | 'measureText'> {
return { font: '', measureText: () => ({ width: 8 }) as TextMetrics }
}
}
)
})
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
it('renders and hides an unfocused main-buffer caret', async () => {
const listenerCleanup = trackEventListenerCleanup()
const options: ITerminalOptions & ITerminalInitOnlyOptions = MOBILE_TERMINAL_CARET_OPTIONS
const terminal = new Terminal(options)
const container = document.createElement('div')
document.body.append(container)
try {
terminal.open(container)
await vi.waitFor(() => expect(cursorCoreService(terminal).isCursorInitialized).toBe(true))
await write(terminal, '\x1b[?25h\x1b[2K\x1b[1G> hello\x1b[?2004h\x1b[1;3H')
terminal.refresh(0, terminal.rows - 1)
await vi.waitFor(() => expect(container.textContent).toContain('hello'))
const coreService = cursorCoreService(terminal)
expect({
initialized: coreService.isCursorInitialized,
rendered: container.querySelector('.xterm-cursor') !== null
}).toEqual({ initialized: true, rendered: true })
await write(terminal, '\x1b[?25l')
terminal.refresh(0, terminal.rows - 1)
await vi.waitFor(() => expect(container.querySelector('.xterm-cursor')).toBeNull())
expect({
hidden: coreService.isCursorHidden,
rendered: container.querySelector('.xterm-cursor') !== null
}).toEqual({ hidden: true, rendered: false })
} finally {
// Teardown only: assertions here could mask the body failure and strand the container.
terminal.dispose()
container.remove()
}
expect(container.querySelector('.xterm')).toBeNull()
const cleanup = listenerCleanup()
expect(cleanup.added).toBeGreaterThan(0)
expect(cleanup.removed).toBe(cleanup.added)
expect(cleanup.unreleased).toEqual([])
})
})
@@ -4,10 +4,6 @@ import { readTerminalCellBox } from './terminal-cell-box'
const CELL_1X = { fontScale: 1, cellWidth: 23 / 3, cellHeight: 15 }
describe('readTerminalCellBox', () => {
it('reads nothing from a notify without a cell box', () => {
expect(readTerminalCellBox({ type: 'web-ready' })).toBeNull()
})
it('reads a well-formed box and rejects a malformed one', () => {
expect(readTerminalCellBox({ cellBox: CELL_1X })).toEqual(CELL_1X)
expect(readTerminalCellBox({ cellBox: { ...CELL_1X, cellWidth: 0 } })).toBeNull()
@@ -1,17 +1,7 @@
import { describe, expect, it } from 'vitest'
import { fitDimensionsFromCell } from './terminal-grid-fit'
const CELL_1X = { cellWidth: 23 / 3, cellHeight: 15 }
describe('fitDimensionsFromCell', () => {
it('fits the frame React Native laid out', () => {
expect(fitDimensionsFromCell(CELL_1X, 427, 710)).toEqual({ cols: 55, rows: 47 })
})
it('answers null for a frame too narrow to fit', () => {
expect(fitDimensionsFromCell(CELL_1X, 100, 710)).toBeNull()
})
it('keeps an exact fit at a fractional pixel ratio whole', () => {
// An exact device-pixel fit can divide to 49.999… after pixel-ratio conversion.
const cell = { cellWidth: 18 / 2.75, cellHeight: 40 / 2.75 }
@@ -1,77 +0,0 @@
import { describe, expect, it } from 'vitest'
import { resolveMobileTerminalInputGate } from './terminal-input-connection-gate'
import { buildTerminalSendParams, TERMINAL_INPUT_SEND_OPTIONS } from './terminal-send-request'
describe('terminal input connection gate', () => {
it('Given a live connection on a terminal tab Then composing and sending are both allowed', () => {
expect(
resolveMobileTerminalInputGate({
connState: 'connected',
activeHandle: 'terminal-a',
activeSessionTabType: 'terminal'
})
).toEqual({ canCompose: true, canSend: true })
})
it('Given a cut connection Then composing stays available while sending is blocked', () => {
for (const connState of [
'connecting',
'handshaking',
'disconnected',
'reconnecting',
'auth-failed'
] as const) {
expect(
resolveMobileTerminalInputGate({
connState,
activeHandle: 'terminal-a',
activeSessionTabType: 'terminal'
})
).toEqual({ canCompose: true, canSend: false })
}
})
it('Given a non-terminal tab or no handle Then neither composing nor sending is allowed', () => {
for (const activeSessionTabType of ['markdown', 'file', 'browser']) {
expect(
resolveMobileTerminalInputGate({
connState: 'connected',
activeHandle: 'terminal-a',
activeSessionTabType
})
).toEqual({ canCompose: false, canSend: false })
}
expect(
resolveMobileTerminalInputGate({
connState: 'connected',
activeHandle: null,
activeSessionTabType: 'terminal'
})
).toEqual({ canCompose: false, canSend: false })
})
it('Given a lagging tab list yielding no tab Then the gate treats the type as unknown, not non-terminal', () => {
expect(
resolveMobileTerminalInputGate({
connState: 'disconnected',
activeHandle: 'terminal-a',
activeSessionTabType: undefined
})
).toEqual({ canCompose: true, canSend: false })
})
})
describe('terminal send request shape', () => {
it('keeps every keystroke-grade terminal send now-or-never so nothing replays after reconnect', () => {
expect(TERMINAL_INPUT_SEND_OPTIONS).toEqual({ failWhenDisconnected: true })
})
it('tags terminal sends with the device presence lock only when a token exists', () => {
expect(
buildTerminalSendParams({ terminal: 't1', text: 'ls', enter: true, deviceToken: 'tok' })
).toEqual({ terminal: 't1', text: 'ls', enter: true, client: { id: 'tok', type: 'mobile' } })
expect(
buildTerminalSendParams({ terminal: 't1', text: 'ls', enter: false, deviceToken: null })
).toEqual({ terminal: 't1', text: 'ls', enter: false })
})
})
@@ -10,26 +10,8 @@ const chord = (key: string, modifiers: { ctrl?: boolean; alt?: boolean; shift?:
})
describe('createTerminalKeyChordInput', () => {
it('encodes keyboard chords as the bytes a terminal expects', () => {
expect(chord('c', { ctrl: true })).toEqual({ bytes: '\x03' })
expect(chord('[', { ctrl: true })).toEqual({ bytes: '\x1b' })
expect(chord('space', { ctrl: true })).toEqual({ bytes: '\x00' })
expect(chord('b', { alt: true })).toEqual({ bytes: '\x1bb' })
expect(chord('B', { alt: true })).toEqual({ bytes: '\x1bB' })
expect(chord('C', { ctrl: true })).toEqual({ bytes: '\x03' })
expect(chord('/', { ctrl: true })).toEqual({ bytes: '\x1f' })
expect(chord('enter', { alt: true })).toEqual({ bytes: '\x1b\r' })
expect(chord('tab', { shift: true })).toEqual({ bytes: '\x1b[Z' })
expect(chord('arrowUp', { ctrl: true })).toEqual({ bytes: '\x1b[1;5A' })
expect(chord('escape')).toEqual({ bytes: '\x1b' })
})
it('keeps the accessory Del local-edit rule for a bare forward delete only', () => {
expect(chord('delete')).toEqual({ bytes: '\x1b[3~', localEdit: 'delete' })
expect(chord('delete', { ctrl: true })).toEqual({ bytes: '\x1b[3;5~' })
})
it('drops chords with no terminal encoding', () => {
expect(chord('1', { ctrl: true })).toBeNull()
})
})
@@ -15,53 +15,6 @@ function metrics(
}
describe('computeActiveTerminalKeyboardLift', () => {
it('returns 0 when the keyboard is closed', () => {
expect(
computeActiveTerminalKeyboardLift({
keyboardLift: 0,
metrics: metrics({ cursorY: 30, contentBottomRow: 34 }),
terminalFrameHeight: FRAME_HEIGHT
})
).toBe(0)
})
it('falls back to the full lift when metrics are missing', () => {
expect(
computeActiveTerminalKeyboardLift({
keyboardLift: KEYBOARD_LIFT,
metrics: undefined,
terminalFrameHeight: FRAME_HEIGHT
})
).toBe(KEYBOARD_LIFT)
})
it('falls back to the full lift when rows or frame height are unmeasured', () => {
expect(
computeActiveTerminalKeyboardLift({
keyboardLift: KEYBOARD_LIFT,
metrics: metrics({ rows: 0 }),
terminalFrameHeight: FRAME_HEIGHT
})
).toBe(KEYBOARD_LIFT)
expect(
computeActiveTerminalKeyboardLift({
keyboardLift: KEYBOARD_LIFT,
metrics: metrics(),
terminalFrameHeight: 0
})
).toBe(KEYBOARD_LIFT)
})
it('lifts fully for alt-screen TUIs', () => {
expect(
computeActiveTerminalKeyboardLift({
keyboardLift: KEYBOARD_LIFT,
metrics: metrics({ cursorY: 10, contentBottomRow: 10, altScreen: true }),
terminalFrameHeight: FRAME_HEIGHT
})
).toBe(KEYBOARD_LIFT)
})
it('clears a main-buffer footer while an old payload retains cursor-only behavior', () => {
const candidate = computeActiveTerminalKeyboardLift({
keyboardLift: KEYBOARD_LIFT,
@@ -77,40 +30,6 @@ describe('computeActiveTerminalKeyboardLift', () => {
expect({ candidate, cursorOnly }).toEqual({ candidate: 220, cursorOnly: 140 })
})
it('keeps short output near the top put (no lift)', () => {
expect(
computeActiveTerminalKeyboardLift({
keyboardLift: KEYBOARD_LIFT,
metrics: metrics({ cursorY: 2, contentBottomRow: 5 }),
terminalFrameHeight: FRAME_HEIGHT
})
).toBe(0)
})
it('matches cursor-clearing behavior for a scrolled shell (prompt at the bottom)', () => {
const lift = computeActiveTerminalKeyboardLift({
keyboardLift: KEYBOARD_LIFT,
metrics: metrics({ cursorY: 38, contentBottomRow: 38 }),
terminalFrameHeight: FRAME_HEIGHT
})
expect(lift).toBe(KEYBOARD_LIFT)
})
it('never exceeds the keyboard lift', () => {
const lift = computeActiveTerminalKeyboardLift({
keyboardLift: KEYBOARD_LIFT,
metrics: metrics({ cursorY: 39, contentBottomRow: 39 }),
terminalFrameHeight: FRAME_HEIGHT
})
expect(lift).toBeLessThanOrEqual(KEYBOARD_LIFT)
const taller = computeActiveTerminalKeyboardLift({
keyboardLift: KEYBOARD_LIFT,
metrics: metrics({ rows: 60, rowPitch: 18, cursorY: 59, contentBottomRow: 59 }),
terminalFrameHeight: FRAME_HEIGHT
})
expect(taller).toBe(KEYBOARD_LIFT)
})
it('applies the supplied keyboard coverage to the lift', () => {
const tuiMetrics = metrics({ cursorY: 30, contentBottomRow: 34 })
const android = computeActiveTerminalKeyboardLift({
@@ -150,12 +69,6 @@ describe('computeActiveTerminalKeyboardLift', () => {
expect(lift(312, { ...drawn425, cursorY: 45, contentBottomRow: 45 })).toBe(0)
})
it('lifts nothing for a keyboard that is open and covers nothing', () => {
expect(lift(0, metrics({ rows: 50, rowPitch: 17, cursorY: 49, contentBottomRow: 49 }))).toBe(
0
)
})
it('stays under the strip while stale rows outlast a rotation or a text-size change', () => {
const rotated = metrics({ rows: 47, rowPitch: 15, cursorY: 46, contentBottomRow: 46 })
expect(lift(150, rotated, 300)).toBe(150)
@@ -1,10 +1,9 @@
// @vitest-environment happy-dom
import { Terminal } from '@xterm/xterm'
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import { createTerminalDocumentScope } from './document/document-scope'
import { emitKeyboardAvoidanceMetrics } from './document/keyboard-avoidance-metrics'
import { commitFitScale } from './document/fit-scale'
import { parseTerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract'
function runMetricsOver(term: unknown, fitScale = 1): Record<string, unknown>[] {
const notifications: Record<string, unknown>[] = []
@@ -17,8 +16,6 @@ function runMetricsOver(term: unknown, fitScale = 1): Record<string, unknown>[]
emitKeyboardAvoidanceMetrics(scope)
return notifications
}
type Cell = { isBgDefault: () => boolean; isInverse: () => number }
type MetricsNotification = {
type: string
cursorY: number
@@ -47,31 +44,6 @@ function checkedMetrics(value: Record<string, unknown> | undefined): MetricsNoti
}
}
function makeLine(text = '', styledColumns: number[] = []) {
const styled = new Set(styledColumns)
return {
isWrapped: false,
length: 10,
translateToString: vi.fn(() => text),
getCell: (column: number): Cell => ({
isBgDefault: () => !styled.has(column),
isInverse: () => 0
})
}
}
function runMetrics(lines: (ReturnType<typeof makeLine> | undefined)[], altScreen = false) {
const buffer = {
cursorY: 2,
viewportY: 3,
type: altScreen ? 'alternate' : 'normal',
getLine: (index: number) => lines[index - 3],
getNullCell: () => ({})
}
const notified = runMetricsOver({ buffer: { active: buffer }, cols: 10, rows: lines.length })
return checkedMetrics(notified[0])
}
function runTerminalMetrics(term: Terminal) {
return checkedMetrics(runMetricsOver(term)[0])
}
@@ -81,21 +53,6 @@ function write(term: Terminal, data: string): Promise<void> {
}
describe('terminal keyboard-avoidance WebView metrics', () => {
it('finds text on wrapped rows using the visible viewport offset', () => {
const lines = [makeLine('header'), makeLine(''), makeLine('wrapped footer')]
lines[2]!.isWrapped = true
expect(runMetrics(lines)).toMatchObject({ contentBottomRow: 2 })
})
it('keeps background-only ANSI chrome visible', () => {
expect(runMetrics([makeLine('header'), makeLine(''), makeLine('')])).toMatchObject({
contentBottomRow: 0
})
expect(runMetrics([makeLine('header'), makeLine(''), makeLine('', [4])])).toMatchObject({
contentBottomRow: 2
})
})
it('classifies real xterm text and styled whitespace by rendered visibility', async () => {
const cases = [
{ name: 'default spaces', data: ' ', expected: 0 },
@@ -148,38 +105,6 @@ describe('terminal keyboard-avoidance WebView metrics', () => {
}
})
it('keeps real xterm metrics compatible with old payloads', async () => {
const term = new Terminal({ cols: 10, rows: 8 })
try {
await write(term, '\x1b[8;1Hfooter\x1b[2;1H')
const { cursorY, rows, altScreen } = runTerminalMetrics(term)
expect(parseTerminalKeyboardAvoidanceMetrics({ cursorY, rows, altScreen })).toEqual({
cursorY: 1,
contentBottomRow: 1,
rows: 8,
altScreen: false
})
} finally {
term.dispose()
}
})
it('stops at the first bottom-up match and skips scans on alternate screen', () => {
const footer = makeLine('footer')
const header = makeLine('header')
expect(runMetrics([header, makeLine(''), footer])).toMatchObject({ contentBottomRow: 2 })
expect(footer.translateToString).toHaveBeenCalledTimes(1)
expect(header.translateToString).not.toHaveBeenCalled()
footer.translateToString.mockImplementation(() => {
throw new Error('alternate screen must not scan')
})
expect(runMetrics([header, makeLine(''), footer], true)).toMatchObject({
altScreen: true,
contentBottomRow: 0
})
})
it('reports the row pitch as drawn, fit scale included, and none before a cell is measured', () => {
const buffer = { cursorY: 0, viewportY: 0, type: 'normal', getLine: () => undefined }
const measuredTerm = {
@@ -1,40 +0,0 @@
import { describe, expect, it } from 'vitest'
import { getTerminalLiveAccessoryRawSendTarget } from './terminal-live-accessory-raw-send-target'
describe('terminal live accessory raw send target', () => {
it('Given the original terminal is still active When raw fallback resumes Then returns that handle', () => {
const targetHandle = 'terminal-a'
const sendTarget = getTerminalLiveAccessoryRawSendTarget({
targetHandle,
activeHandle: targetHandle,
activeSessionTabType: 'terminal'
})
expect(sendTarget).toBe(targetHandle)
})
it('Given the active terminal changed while waiting When raw fallback resumes Then suppresses the send', () => {
const targetHandle = 'terminal-a'
const sendTarget = getTerminalLiveAccessoryRawSendTarget({
targetHandle,
activeHandle: 'terminal-b',
activeSessionTabType: 'terminal'
})
expect(sendTarget).toBeNull()
})
it('Given the target is not an active terminal tab When raw fallback resumes Then suppresses the send', () => {
const targetHandle = 'terminal-a'
const inactiveTabTarget = getTerminalLiveAccessoryRawSendTarget({
targetHandle,
activeHandle: targetHandle,
activeSessionTabType: 'browser'
})
expect(inactiveTabTarget).toBeNull()
})
})
@@ -1,17 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
const host = vi.hoisted(() => ({ os: 'android' }))
vi.mock('react-native', () => ({ Platform: { OS: 'web' } }))
vi.mock('../platform/host-os', () => ({ hostOs: () => host.os }))
const { reopensFocusedInputWhenKeyboardHidden } =
await import('./terminal-live-input-keyboard-reopen')
describe('reopening a focused live input whose keyboard is hidden', () => {
it("follows the phone's OS on the page, which runs as web", () => {
host.os = 'android'
expect(reopensFocusedInputWhenKeyboardHidden()).toBe(true)
host.os = 'ios'
expect(reopensFocusedInputWhenKeyboardHidden()).toBe(false)
})
})
@@ -4,7 +4,6 @@ import { act, createElement, createRef, type ComponentType, type RefObject } fro
import { createRoot } from 'react-dom/client'
import { describe, expect, it } from 'vitest'
import type { TextInput } from 'react-native'
import { writeTerminalLiveInputText } from './terminal-live-input-text-write'
import { writeTerminalLiveInputText as writeTerminalLiveInputTextOnWeb } from './terminal-live-input-text-write.web'
const refTo = (node: unknown): RefObject<TextInput | null> => ({
@@ -12,29 +11,7 @@ const refTo = (node: unknown): RefObject<TextInput | null> => ({
current: node as TextInput | null
})
function mountInput(): HTMLInputElement {
const input = document.createElement('input')
document.body.append(input)
return input
}
describe('the native live-input write with an unmounted ref', () => {
// The no-terminal route never reaches this write, so its render check alone could miss the native-method defect.
it('writes nothing at all when the field has not mounted', () => {
expect(() => writeTerminalLiveInputText(refTo(null), '')).not.toThrow()
})
})
describe('the web sibling', () => {
it('puts the text on the node the field is', () => {
const input = mountInput()
input.value = 'ime-preedit'
writeTerminalLiveInputTextOnWeb(refTo(input), '')
expect(input.value).toBe('')
})
it('writes a multiline field too, which RN Web renders as a textarea', () => {
const area = document.createElement('textarea')
document.body.append(area)
@@ -43,19 +20,6 @@ describe('the web sibling', () => {
expect(area.value).toBe('edited')
})
it('tolerates a field that has unmounted between the edit and the write', () => {
expect(() => writeTerminalLiveInputTextOnWeb(refTo(null), '')).not.toThrow()
})
// Do not add value to unknown wrappers; future RN Web changes must not silently pretend to update the field.
it('leaves a node that is not a field alone', () => {
const div = document.createElement('div')
writeTerminalLiveInputTextOnWeb(refTo(div), 'edited')
expect(Object.hasOwn(div, 'value')).toBe(false)
})
})
// Check the actual RN Web TextInput ref too; a hand-built input would miss component shape changes.
@@ -1,107 +0,0 @@
// @vitest-environment happy-dom
import { createRequire } from 'node:module'
import { act, createElement, createRef, type ComponentType, type RefObject } from 'react'
import { createRoot } from 'react-dom/client'
import { describe, expect, it } from 'vitest'
import type { ScrollView } from 'react-native'
import { setTerminalSettingsScrollEnabled } from './terminal-settings-scroll-lock'
import { setTerminalSettingsScrollEnabled as setTerminalSettingsScrollEnabledOnWeb } from './terminal-settings-scroll-lock.web'
const refTo = (node: unknown): RefObject<ScrollView | null> => ({
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the point of these cases is that a DOM node is what the native signature receives on RN Web, which is the mismatch this sibling exists for.
current: node as ScrollView | null
})
describe('the native scroll-lock write against an RN Web ref', () => {
it('throws, because a DOM node has no setNativeProps', () => {
expect(() =>
setTerminalSettingsScrollEnabled(refTo(document.createElement('div')), false)
).toThrow(/setNativeProps is not a function/)
})
it('writes nothing at all when the view has not mounted', () => {
expect(() => setTerminalSettingsScrollEnabled(refTo(null), false)).not.toThrow()
})
})
describe('the web sibling', () => {
it('locks the scroll with overflow, which stops a wheel as well as a touch drag', () => {
const node = document.createElement('div')
setTerminalSettingsScrollEnabledOnWeb(refTo(node), false)
expect(node.style.overflowY).toBe('hidden')
})
it('tolerates a view that has unmounted between the gesture and the write', () => {
expect(() => setTerminalSettingsScrollEnabledOnWeb(refTo(null), true)).not.toThrow()
})
it('leaves a node that is not an element alone', () => {
expect(() => setTerminalSettingsScrollEnabledOnWeb(refTo({}), false)).not.toThrow()
})
})
// Test RN Web’s real class-driven overflow: a bare div cannot prove clearing inline overflow restores scrolling.
describe('against a real react-native-web ScrollView', () => {
// Require RN Web because its missing type declarations would make a direct import escape the tests-typecheck ratchet.
const {
ScrollView: ReactNativeWebScrollView
}: {
ScrollView: ComponentType<{
ref: RefObject<unknown>
}>
} = createRequire(import.meta.url)('react-native-web')
async function renderScroller(): Promise<{
node: HTMLElement
unmount: () => void
}> {
Reflect.set(globalThis, 'IS_REACT_ACT_ENVIRONMENT', true)
const container = document.createElement('div')
document.body.append(container)
const root = createRoot(container)
const ref: RefObject<unknown> = createRef()
await act(async () => {
root.render(createElement(ReactNativeWebScrollView, { ref }))
})
const node = ref.current
if (!(node instanceof HTMLElement)) {
throw new Error('react-native-web put no element in the ScrollView ref')
}
return {
node,
unmount: () => {
root.unmount()
container.remove()
}
}
}
it('is handed the DOM node itself, which is why the native write cannot land', async () => {
const { node, unmount } = await renderScroller()
try {
expect(node.tagName).toBe('DIV')
expect('setNativeProps' in node).toBe(false)
} finally {
unmount()
}
})
it('locks and then hands the scroller back to the class RN Web styles it with', async () => {
const { node, unmount } = await renderScroller()
try {
expect(node.getAttribute('style')).toBeNull()
expect(node.className).toContain('overflowY')
setTerminalSettingsScrollEnabledOnWeb(refTo(node), false)
expect(node.style.overflowY).toBe('hidden')
setTerminalSettingsScrollEnabledOnWeb(refTo(node), true)
expect(node.style.overflowY).toBe('')
expect(node.className).toContain('overflowY')
} finally {
unmount()
}
})
})
@@ -7,8 +7,4 @@ describe('normalizeTerminalTextInput', () => {
expect(normalizeTerminalTextInput('git checkout – file')).toBe('git checkout -- file')
expect(normalizeTerminalTextInput('git checkout — file')).toBe('git checkout -- file')
})
it('keeps ASCII hyphens unchanged', () => {
expect(normalizeTerminalTextInput('git checkout -- file')).toBe('git checkout -- file')
})
})
@@ -81,14 +81,6 @@ const cellBoxNotify = (cellWidth: number, refit: boolean) => ({
})
describe('the cell box xterm laid out', () => {
it('sizes a fit from web-ready, which the document sends once its terminal is built', () => {
const { handle, notify } = mount()
expect(handle().fitDimensions(FRAME)).toBeNull()
notify({ type: 'web-ready', cellBox: cellAt(scale) })
expect(handle().fitDimensions(FRAME)).toEqual({ cols: 55, rows: 47 })
expect(postedTypes()).not.toContain('measure')
})
it('fits each box the document reports, and refits only when the document says so', () => {
const { handle, notify, onCellBoxChange } = mount()
notify({ type: 'web-ready', cellBox: cellAt(scale) })
@@ -142,14 +134,6 @@ describe('the cell box xterm laid out', () => {
expect(postedTypes()).not.toContain('init')
})
it('reloads the same view when its content process ends', () => {
const { webView } = mount()
const view = webView()
act(() => view.props.onContentProcessDidTerminate({ nativeEvent: {} }))
expect(nativeWebViewMethods.reload).toHaveBeenCalledTimes(1)
expect(webView()).toBe(view)
})
it('drops queued and coalesced commands on a reload or a lost content process', () => {
vi.useFakeTimers()
const { handle, notify, webView } = mount()
@@ -169,30 +153,4 @@ describe('the cell box xterm laid out', () => {
})
expect(postedTypes()).toContain('write')
})
it('tells the document the app text scale before it builds its terminal', () => {
const { webView } = mount(1.25)
const html: string = webView().props.source.html
const start = html.indexOf('window.__orcaTerminalTextScale = 1.25;')
expect(start).toBeGreaterThan(-1)
// Put initial settings in page source so no platform can inject them after document startup.
expect(start).toBeLessThan(html.indexOf('startTerminalDocument'))
})
it('keeps the source it mounted with across renders, so a new text scale does not reload', () => {
const { webView } = mount(1)
const source = webView().props.source
act(() => renderers[0]!.update(createElement(TerminalWebView, { textScale: 1.5 })))
expect(webView().props.source).toBe(source)
})
it('tells a document whose view was hidden at mount not to build before ready', () => {
let renderer: ReactTestRenderer | undefined
act(() => {
renderer = create(createElement(TerminalWebView, { shownAtMount: false }))
})
renderers.push(renderer!)
const webView = renderer!.root.find((node) => typeof node.props.onMessage === 'function')
expect(webView.props.source.html).toContain('window.__orcaTerminalShown = false;')
})
})
@@ -1,23 +1,8 @@
import { describe, expect, it } from 'vitest'
import {
parseTerminalKeyboardAvoidanceMetrics,
sameTerminalKeyboardAvoidanceMetrics,
type TerminalKeyboardAvoidanceMetrics
} from './terminal-webview-contract'
import { parseTerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract'
describe('parseTerminalKeyboardAvoidanceMetrics', () => {
it('parses a full payload', () => {
expect(
parseTerminalKeyboardAvoidanceMetrics({
cursorY: 30,
contentBottomRow: 34,
rows: 40,
altScreen: true
})
).toEqual({ cursorY: 30, contentBottomRow: 34, rows: 40, altScreen: true })
})
it('defaults contentBottomRow to cursorY when absent (older WebView bundles)', () => {
expect(parseTerminalKeyboardAvoidanceMetrics({ cursorY: 12, rows: 40 })).toEqual({
cursorY: 12,
@@ -27,15 +12,6 @@ describe('parseTerminalKeyboardAvoidanceMetrics', () => {
})
})
it('defaults non-numeric fields to zero', () => {
expect(parseTerminalKeyboardAvoidanceMetrics({})).toEqual({
cursorY: 0,
contentBottomRow: 0,
rows: 0,
altScreen: false
})
})
it('bounds untrusted numeric fields to the reported viewport', () => {
expect(
parseTerminalKeyboardAvoidanceMetrics({
@@ -65,30 +41,3 @@ describe('parseTerminalKeyboardAvoidanceMetrics', () => {
}
})
})
describe('sameTerminalKeyboardAvoidanceMetrics', () => {
const metrics: Required<TerminalKeyboardAvoidanceMetrics> = {
cursorY: 38,
contentBottomRow: 38,
rows: 40,
altScreen: false,
rowPitch: 15
}
const variants: [keyof typeof metrics, TerminalKeyboardAvoidanceMetrics][] = [
['cursorY', { ...metrics, cursorY: 39 }],
['contentBottomRow', { ...metrics, contentBottomRow: 39 }],
['rows', { ...metrics, rows: 41 }],
['altScreen', { ...metrics, altScreen: true }],
['rowPitch', { ...metrics, rowPitch: 6.96 }]
]
it('tells apart metrics that differ in any one field', () => {
expect(sameTerminalKeyboardAvoidanceMetrics(metrics, { ...metrics })).toBe(true)
expect(variants.map(([key]) => key).sort()).toEqual(Object.keys(metrics).sort())
for (const [key, variant] of variants) {
expect(sameTerminalKeyboardAvoidanceMetrics(metrics, variant), key).toBe(false)
}
const { rowPitch: _rowPitch, ...older } = metrics
expect(sameTerminalKeyboardAvoidanceMetrics(metrics, older)).toBe(false)
})
})
@@ -1,15 +1,12 @@
// @vitest-environment happy-dom
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { Script } from 'node:vm'
import { parse } from 'acorn'
import { describe, expect, it, vi } from 'vitest'
import { TERMINAL_NERD_FONT_CSS, XTERM_ENGINE_CSS } from './terminal-webview-engine-css.generated'
import { XTERM_ENGINE_CSS } from './terminal-webview-engine-css.generated'
import { XTERM_ENGINE_JS } from './terminal-webview-engine.generated'
import { createTerminalDocumentScope } from './document/document-scope'
import { attachWebglAddon, startWebglRecovery } from './document/webgl-recovery'
import { attachWebglAddon } from './document/webgl-recovery'
import { XTERM_HTML } from './terminal-webview-html'
import { applyTerminalTheme } from './document/terminal-theme'
function createWebglRecoveryHarness(failSecondAttach = false) {
const timers: Array<() => void> = []
@@ -43,7 +40,6 @@ function createWebglRecoveryHarness(failSecondAttach = false) {
})
}
const logged: Record<string, unknown>[] = []
const terminalThemeInput = { mode: 'dark' }
vi.spyOn(globalThis, 'setTimeout').mockImplementation((callback: TimerHandler) => {
if (typeof callback === 'function') {
timers.push(() => {
@@ -60,20 +56,11 @@ function createWebglRecoveryHarness(failSecondAttach = false) {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the double implements the members the recovery path reaches, which is what each case asserts about.
scope.term = term as unknown as typeof scope.term
scope.terminalGeneration = 1
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the recovery only re-applies this value through the theme path; its shape is that path's own input.
scope.terminalThemeInput = terminalThemeInput as unknown as typeof scope.terminalThemeInput
startWebglRecovery(scope)
attachWebglAddon(scope, true)
return {
addons,
appliedThemes: () => term.options.theme,
fireVisibilityChange: () => {
document.dispatchEvent(new Event('visibilitychange'))
},
logged,
scope,
term,
terminalThemeInput,
timers
}
}
@@ -86,33 +73,6 @@ describe('terminal WebView bundled engine', () => {
expect(XTERM_HTML).not.toContain('rel="stylesheet" href=')
})
it('ships the licensed desktop symbol font offline without covering normal text', () => {
const encoded = TERMINAL_NERD_FONT_CSS.match(/base64,([^']+)'/)?.[1]
expect(encoded).toBeTruthy()
const bundled = readFileSync(
path.resolve(import.meta.dirname, '../../assets/fonts/SymbolsNerdFontMono-Regular.woff2')
)
expect(Buffer.from(encoded ?? '', 'base64').equals(bundled)).toBe(true)
expect(
bundled.equals(
readFileSync(
path.resolve(
import.meta.dirname,
'../../../src/renderer/src/assets/fonts/SymbolsNerdFontMono-Regular.woff2'
)
)
)
).toBe(true)
expect(TERMINAL_NERD_FONT_CSS).toContain(
'unicode-range:U+E000-F8FF,U+F0000-FFFFD,U+100000-10FFFD'
)
expect(XTERM_HTML).toContain(`<style>${TERMINAL_NERD_FONT_CSS}</style>`)
expect(XTERM_HTML).toContain(
'"Liberation Mono", "Orca Nerd Font Symbols", "Symbols Nerd Font Mono"'
)
expect(TERMINAL_NERD_FONT_CSS).not.toMatch(/<\/style/i)
})
it('parses the bundled engine at the Chrome 74 syntax floor', () => {
expect(() => parse(XTERM_ENGINE_JS, { ecmaVersion: 2019 })).not.toThrow()
})
@@ -226,21 +186,4 @@ describe('terminal WebView bundled engine', () => {
expect(addons[1]?.dispose).toHaveBeenCalledTimes(1)
expect(term.refresh).toHaveBeenCalledTimes(2)
})
it('reapplies theme, clears the active atlas, and refreshes when visible', () => {
const harness = createWebglRecoveryHarness()
applyTerminalTheme(harness.scope, harness.scope.terminalThemeInput)
const firstTheme = harness.term.options.theme
// Stub only hidden state; Happy DOM’s visible default exercises real recovery.
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
harness.fireVisibilityChange()
expect(harness.term.options.theme).toBe(firstTheme)
vi.restoreAllMocks()
harness.fireVisibilityChange()
expect(harness.term.options.theme).not.toBe(firstTheme)
expect(harness.addons[0]?.clearTextureAtlas).toHaveBeenCalledTimes(1)
expect(harness.term.refresh).toHaveBeenCalledTimes(1)
})
})
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import { documentLevelRules, scopeStyleToHost } from '../../style-scoping/document-style-scoping'
import { scopeStyleToHost } from '../../style-scoping/document-style-scoping'
import { XTERM_ENGINE_CSS } from '../terminal-webview-engine-css.generated'
import { TERMINAL_DOCUMENT_ELEMENT_STYLE, TERMINAL_DOCUMENT_ROOT_STYLE } from './document-style'
import { TERMINAL_DOCUMENT_ELEMENT_STYLE } from './document-style'
// Verify native root rules remain separate while page-injected rules can reach only terminal-owned elements.
const PREFIX = '.orca-terminal-document-host'
@@ -13,11 +13,6 @@ function selectorsOf(css: string): string[] {
}
describe('the terminal document stylesheet', () => {
it('keeps every document-level rule out of the half the page takes', () => {
expect(documentLevelRules(TERMINAL_DOCUMENT_ROOT_STYLE)).toEqual(['*', 'html, body'])
expect(documentLevelRules(TERMINAL_DOCUMENT_ELEMENT_STYLE)).toEqual([])
})
it('holds every selector of both injected sheets under the host', () => {
for (const sheet of [TERMINAL_DOCUMENT_ELEMENT_STYLE, XTERM_ENGINE_CSS]) {
const scoped = scopeStyleToHost(sheet, PREFIX)
@@ -26,9 +21,4 @@ describe('the terminal document stylesheet', () => {
expect(selectors.filter((one) => !one.startsWith(`${PREFIX} `))).toEqual([])
}
})
it('drops a document-level rule rather than prefixing it', () => {
const scoped = scopeStyleToHost(TERMINAL_DOCUMENT_ROOT_STYLE, PREFIX)
expect(scoped.trim()).toBe('')
})
})
@@ -47,41 +47,6 @@ describe('terminal WebView external mouse click', () => {
expect(document.getElementById('selection-overlay')?.classList.contains('active')).toBe(false)
})
it('routes a plain mouse click to the tap pipeline for keyboard focus', () => {
mouse.boot()
mouse.mouseClick(40, 60)
const messages = mouse.postedMessages()
expect(messages.filter((message) => message.type === 'terminal-tap')).toHaveLength(1)
expect(mouse.terminalInputBytes()).toBe('')
})
it('ignores non-mouse pointers and non-left buttons', () => {
mouse.boot()
mouse.activeTerminal().modes.mouseTrackingMode = 'vt200'
mouse.dispatchPointer('pointerdown', {
pointerType: 'touch',
x: 40,
y: 60,
button: 0,
buttons: 1
})
mouse.dispatchPointer('pointerup', {
pointerType: 'touch',
x: 40,
y: 60,
button: 0,
buttons: 0
})
mouse.dispatchPointer('pointerdown', { x: 40, y: 60, button: 2, buttons: 2 })
mouse.dispatchPointer('pointerup', { x: 40, y: 60, button: 2, buttons: 0 })
expect(mouse.terminalInputBytes()).toBe('')
expect(mouse.postedMessages().filter((message) => message.type === 'terminal-tap')).toEqual([])
})
it('lets the touch dispatcher own a gesture when touch events follow pointerdown', () => {
mouse.boot()
mouse.writeLegacyMouseEncoding()
@@ -39,20 +39,6 @@ describe('terminal WebView external mouse drag', () => {
expect(bytes).toHaveLength(6)
})
it('selects character-anchored text on a mouse drag outside tracking mode', () => {
mouse.boot()
// Discard init’s selection reset so assertions observe only the drag.
mouse.clearPostedMessages()
mouse.mouseDrag(40, 60, 160, 90)
expect(mouse.terminalInputBytes()).toBe('')
expect(mouse.selectionSpy()).toHaveBeenCalled()
expect(document.getElementById('selection-overlay')?.classList.contains('active')).toBe(true)
const modes = mouse.postedMessages().filter((message) => message.type === 'set-select-mode')
expect(modes).toEqual([{ type: 'set-select-mode', enabled: true }])
})
it('selects text instead of reporting a drag while the encoding is unproven', () => {
mouse.boot(`${ESC}[?1002h`)
mouse.activeTerminal().modes.mouseTrackingMode = 'drag'
@@ -81,17 +67,4 @@ describe('terminal WebView external mouse drag', () => {
expect(mouse.terminalInputBytes()).toBe('')
})
it('releases a tracked drag when the pointer is cancelled mid-gesture', () => {
mouse.boot()
mouse.writeLegacyMouseEncoding()
mouse.activeTerminal().modes.mouseTrackingMode = 'drag'
mouse.dispatchPointer('pointerdown', { x: 40, y: 60, button: 0, buttons: 1 })
mouse.dispatchPointer('pointermove', { x: 160, y: 60, button: 0, buttons: 1 })
mouse.dispatchPointer('pointercancel', { x: 160, y: 60 })
const reports = mouse.terminalInputBytes().match(DEFAULT_MOUSE_REPORT_RE) ?? []
expect(reports.at(-1)?.charCodeAt(3)).toBe(35)
})
})
@@ -1,52 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { dispatchTerminalWebViewNotification } from './terminal-webview-notification-dispatch'
describe('dispatchTerminalWebViewNotification', () => {
it('preserves bounded keyboard metrics through the dispatcher', () => {
const onKeyboardAvoidanceMetrics = vi.fn()
dispatchTerminalWebViewNotification(
{
type: 'keyboard-avoidance-metrics',
cursorY: 30,
contentBottomRow: 99,
rows: 40,
altScreen: true
},
{ onKeyboardAvoidanceMetrics, reportEngineError: vi.fn() }
)
expect(onKeyboardAvoidanceMetrics).toHaveBeenCalledWith({
cursorY: 30,
contentBottomRow: 39,
rows: 40,
altScreen: true
})
})
it('keeps old WebView payloads cursor-compatible', () => {
const onKeyboardAvoidanceMetrics = vi.fn()
dispatchTerminalWebViewNotification(
{ type: 'keyboard-avoidance-metrics', cursorY: 12, rows: 40 },
{ onKeyboardAvoidanceMetrics, reportEngineError: vi.fn() }
)
expect(onKeyboardAvoidanceMetrics).toHaveBeenCalledWith({
cursorY: 12,
contentBottomRow: 12,
rows: 40,
altScreen: false
})
})
it('passes a tap click on and keeps other terminal input bytes-only', () => {
const onTerminalInput = vi.fn()
const handlers = { onTerminalInput, reportEngineError: vi.fn() }
const click = '\x1b[<0;9;31M\x1b[<0;9;31m'
const wheel = '\x1b[<64;9;31M'
dispatchTerminalWebViewNotification(
{ type: 'terminal-input', bytes: click, click: true },
handlers
)
dispatchTerminalWebViewNotification({ type: 'terminal-input', bytes: wheel }, handlers)
expect(onTerminalInput.mock.calls).toEqual([[click, { click: true }], [wheel]])
})
})
@@ -225,19 +225,6 @@ describe('snapshot replacement ends the previous terminal scroll', () => {
expect(scrolls).toEqual([])
})
it('cancels a pending long press when its terminal is replaced', () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
boot(false)
touch('touchstart', 400)
init()
settle()
messages.length = 0
vi.advanceTimersByTime(500)
expect(
messages.filter((message) => message.type === 'set-select-mode' && message.enabled)
).toEqual([])
})
it('does not launch an old finger’s velocity after snapshot replacement', () => {
boot(false)
touch('touchstart', 400)
@@ -2,7 +2,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { terminalDocumentDouble } from './document/document-terminal-double.test-support'
import type { TerminalDocumentTerminal } from './document/document-terminal-shape'
import { createTerminalDocument } from './document/create-terminal-document'
import { TERMINAL_DOCUMENT_SCRIPT } from './terminal-webview-document-script.generated'
import { TERMINAL_DOCUMENT_MARKUP } from './terminal-webview-html'
@@ -62,16 +61,10 @@ describe('terminal WebView touch scrolling', () => {
let now: number
let postMessage: ReturnType<typeof vi.fn<(data: string) => void>>
let scrollLines: ReturnType<typeof vi.fn<(lines: number) => void>>
let stopDocument: (() => void) | undefined
function boot(importedDocument = false): void {
function boot(): void {
document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP
if (importedDocument) {
const terminalDocument = createTerminalDocument()
stopDocument = () => terminalDocument.stop()
} else {
new Function(TERMINAL_DOCUMENT_SCRIPT)()
}
new Function(TERMINAL_DOCUMENT_SCRIPT)()
window.dispatchEvent(
new MessageEvent('message', {
data: JSON.stringify({ type: 'init', cols: 40, rows: 24, initialData: '' })
@@ -166,8 +159,6 @@ describe('terminal WebView touch scrolling', () => {
})
afterEach(() => {
stopDocument?.()
stopDocument = undefined
for (const [type, listener, options] of vi.mocked(window.addEventListener).mock.calls) {
window.removeEventListener(type, listener, options)
}
@@ -179,15 +170,6 @@ describe('terminal WebView touch scrolling', () => {
vi.useRealTimers()
})
it('scrolls scrollback for a drag slower than one pixel per frame', () => {
boot()
fireTouch('touchstart', { x: 40, y: 400 })
dragUp(400, 0.5, 200)
expect(scrolledRows()).toBe(6)
})
it('carries the sub-row remainder of a fast drag into the next move', () => {
boot()
@@ -199,18 +181,6 @@ describe('terminal WebView touch scrolling', () => {
expect(scrolledRows()).toBe(7)
})
it('coasts when the finger lifts mid-drag', () => {
boot()
fireTouch('touchstart', { x: 40, y: 400 })
dragUp(400, 20, 5)
const rowsWhileTouching = scrolledRows()
fireTouch('touchend', null)
runFrames(30)
expect(scrolledRows()).toBeGreaterThan(rowsWhileTouching)
})
it('does not coast when the finger rested before lifting', () => {
boot()
@@ -288,19 +258,6 @@ describe('terminal WebView touch scrolling', () => {
expect(terminalInputBytes()).toBe(bytesBeforeCancel)
})
it('retires queued scroll and momentum when the document is disposed', () => {
boot(true)
fireTouch('touchstart', { x: 40, y: 400 })
now += FRAME_MS
fireTouch('touchmove', { x: 40, y: 320 })
fireTouch('touchend', null)
stopDocument?.()
runFrames(30)
expect(scrolledRows()).toBe(0)
expect(terminalInputBytes()).toBe('')
})
it('retires subthreshold scroll velocity when a long press enters selection', () => {
boot()
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
@@ -260,15 +260,6 @@ describe('terminal WebView external pointer wheel scrolling', () => {
expect(event.defaultPrevented).toBe(true)
})
it('claims the wheel so xterm does not double-apply it', () => {
buffer = { baseY: 20, type: 'normal', viewportY: 20 }
boot()
const event = dispatchWheel(-CELL_HEIGHT)
expect(event.defaultPrevented).toBe(true)
})
it('clears fractional wheel state when the terminal is recreated', () => {
buffer = { baseY: 0, type: 'alternate', viewportY: 0 }
boot()
@@ -22,31 +22,6 @@ describe('terminal write coalescer', () => {
vi.useRealTimers()
})
it('delivers the first write after construction synchronously (leading edge)', () => {
vi.useFakeTimers()
const sink = createDeliverySink()
const coalescer = createTerminalWriteCoalescer(sink.deliver)
coalescer.write('a')
// Idle keystroke echo must never wait for a batching timer.
expect(sink.delivered).toEqual(['a'])
expect(vi.getTimerCount()).toBe(0)
})
it('takes the leading edge again after clear()', () => {
vi.useFakeTimers()
const sink = createDeliverySink()
const coalescer = createTerminalWriteCoalescer(sink.deliver)
coalescer.write('a')
coalescer.write('b')
coalescer.clear()
coalescer.write('c')
expect(sink.delivered).toEqual(['a', 'c'])
})
it('batches writes inside the trailing window preserving byte order', () => {
vi.useFakeTimers()
const sink = createDeliverySink()
@@ -61,40 +36,6 @@ describe('terminal write coalescer', () => {
expect(sink.delivered).toEqual(['a', 'bc'])
})
it('buffers a write landing inside the window even when the buffer is empty', () => {
vi.useFakeTimers()
const sink = createDeliverySink()
const coalescer = createTerminalWriteCoalescer(sink.deliver)
coalescer.write('a')
vi.advanceTimersByTime(40)
coalescer.write('b')
expect(sink.delivered).toEqual(['a'])
vi.advanceTimersByTime(TERMINAL_WRITE_FLUSH_WINDOW_MS - 40 - 1)
expect(sink.delivered).toEqual(['a'])
vi.advanceTimersByTime(1)
expect(sink.delivered).toEqual(['a', 'b'])
})
it('flushes at most once per window for a sustained stream', () => {
vi.useFakeTimers()
const sink = createDeliverySink()
const coalescer = createTerminalWriteCoalescer(sink.deliver)
for (let i = 0; i < 200; i += 1) {
coalescer.write(`c${i};`)
// Check live timer count too; one timer per chunk could preserve flush counts while wasting work.
expect(vi.getTimerCount()).toBeLessThanOrEqual(1)
vi.advanceTimersByTime(5)
}
vi.runOnlyPendingTimers()
const maxFlushes = Math.ceil((200 * 5) / TERMINAL_WRITE_FLUSH_WINDOW_MS) + 1
expect(sink.delivered.length).toBeLessThanOrEqual(maxFlushes)
expect(sink.delivered.join('')).toBe(Array.from({ length: 200 }, (_, i) => `c${i};`).join(''))
})
it('flushes within one window even when the wall clock jumps backwards mid-stream', () => {
vi.useFakeTimers()
vi.setSystemTime(100_000)
@@ -125,22 +66,6 @@ describe('terminal write coalescer', () => {
expect(sink.delivered).toHaveLength(2)
})
it('treats write("") as a no-op: no delivery, no buffer append, no timer', () => {
vi.useFakeTimers()
const sink = createDeliverySink()
const coalescer = createTerminalWriteCoalescer(sink.deliver)
coalescer.write('')
expect(sink.delivered).toEqual([])
expect(vi.getTimerCount()).toBe(0)
coalescer.write('a')
coalescer.write('')
coalescer.write('b')
vi.runOnlyPendingTimers()
expect(sink.delivered).toEqual(['a', 'b'])
})
it('flushNow() delivers the joined pending buffer synchronously and cancels the timer', () => {
vi.useFakeTimers()
const sink = createDeliverySink()
@@ -157,44 +82,6 @@ describe('terminal write coalescer', () => {
expect(sink.delivered).toEqual(['a', 'bc'])
})
it('flushNow() with an empty buffer delivers nothing', () => {
vi.useFakeTimers()
const sink = createDeliverySink()
const coalescer = createTerminalWriteCoalescer(sink.deliver)
coalescer.flushNow()
expect(sink.delivered).toEqual([])
})
it('clear() drops pending data without delivering and cancels the timer', () => {
vi.useFakeTimers()
const sink = createDeliverySink()
const coalescer = createTerminalWriteCoalescer(sink.deliver)
coalescer.write('a')
coalescer.write('stale')
coalescer.clear()
expect(vi.getTimerCount()).toBe(0)
vi.runOnlyPendingTimers()
expect(sink.delivered).toEqual(['a'])
})
it('delivers nothing further after a flush is followed by clear()', () => {
vi.useFakeTimers()
const sink = createDeliverySink()
const coalescer = createTerminalWriteCoalescer(sink.deliver)
coalescer.write('a')
coalescer.write('b')
vi.advanceTimersByTime(TERMINAL_WRITE_FLUSH_WINDOW_MS)
expect(sink.delivered).toEqual(['a', 'b'])
coalescer.clear()
vi.advanceTimersByTime(TERMINAL_WRITE_FLUSH_WINDOW_MS * 4)
expect(sink.delivered).toEqual(['a', 'b'])
})
it('shortens an existing output wait when a scroll gesture arrives', () => {
vi.useFakeTimers()
const sink = createDeliverySink()
@@ -225,21 +112,6 @@ describe('terminal write coalescer', () => {
expect(vi.getTimerCount()).toBe(0)
})
it('returns sustained unattended output to the original batching window', () => {
vi.useFakeTimers()
const sink = createDeliverySink()
const coalescer = createTerminalWriteCoalescer(sink.deliver)
coalescer.markInteractive()
coalescer.write('gesture')
vi.advanceTimersByTime(TERMINAL_INTERACTIVE_WRITE_DURATION_MS)
coalescer.write('idle-leading')
coalescer.write('idle-trailing')
vi.advanceTimersByTime(TERMINAL_INTERACTIVE_WRITE_WINDOW_MS)
expect(sink.delivered).toEqual(['gesture', 'idle-leading'])
vi.advanceTimersByTime(TERMINAL_WRITE_FLUSH_WINDOW_MS - TERMINAL_INTERACTIVE_WRITE_WINDOW_MS)
expect(sink.delivered).toEqual(['gesture', 'idle-leading', 'idle-trailing'])
})
it('clears interactive state and pending output when a document is replaced', () => {
vi.useFakeTimers()
const sink = createDeliverySink()
@@ -1,68 +0,0 @@
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, relative } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { censusSourceFiles, isGeneratedSource } from './census-source-files'
const mobileRoot = fileURLToPath(new URL('../..', import.meta.url))
let scratch = ''
beforeEach(() => {
scratch = mkdtempSync(join(tmpdir(), 'orca-census-source-files-'))
})
afterEach(() => {
rmSync(scratch, { recursive: true, force: true })
})
function plant(relativePath: string, source: string): void {
const absolute = join(scratch, relativePath)
mkdirSync(join(absolute, '..'), { recursive: true })
writeFileSync(absolute, source, 'utf8')
}
describe('the source files a census reads', () => {
it('leaves out build output that would be read as a violating import', () => {
// Generated vendor text can match source rules without any editable repository call site.
const violating = "import { requiredString } from '../../src/shared/rpc-contract/params'\n"
plant('src/components/engine.generated.ts', violating)
plant('src/components/Diagram.tsx', violating)
const walked = censusSourceFiles(join(scratch, 'src')).map((path) => relative(scratch, path))
expect(walked).toEqual([join('src', 'components', 'Diagram.tsx')])
})
it('leaves out node_modules, and keeps everything else', () => {
plant('src/a.ts', '')
plant('src/node_modules/dep/index.ts', '')
plant('src/deep/b.tsx', '')
plant('src/notes.md', '')
expect(
censusSourceFiles(join(scratch, 'src'))
.map((path) => relative(scratch, path))
.sort()
).toEqual([join('src', 'a.ts'), join('src', 'deep', 'b.tsx'), join('src', 'notes.md')].sort())
})
it('names build output by the suffix the generators write, and nothing else', () => {
expect(isGeneratedSource('mermaid-page-engine.generated.ts')).toBe(true)
expect(isGeneratedSource('route-manifest.generated.tsx')).toBe(true)
expect(isGeneratedSource('generated.ts')).toBe(false)
expect(isGeneratedSource('rpc-client.ts')).toBe(false)
expect(isGeneratedSource('generated-goldens.ts')).toBe(false)
})
it('covers every artifact the tree generates, read from the ignore file that lists them', () => {
// Use gitignore as the generated-artifact authority; new names must not silently reintroduce megabytes into source censuses.
const ignored = readFileSync(join(mobileRoot, '.gitignore'), 'utf8')
.split('\n')
.map((line) => line.trim())
.filter((line) => line.endsWith('.generated.ts'))
expect(ignored.length).toBeGreaterThan(0)
for (const entry of ignored) {
expect(isGeneratedSource(entry), entry).toBe(true)
}
})
})
@@ -42,8 +42,6 @@ inert. It renders its children and keeps its props where a projection can read t
nothing else: no callback it is handed is ever invoked, nothing is measured and no navigation
happens. `renderedElementProps` is the consequence — an inert list never calls `renderItem`, so the
data it was handed is the only record of what the screen would have drawn.
`screen-native-substitutes.test.ts` is the census; it renders every element with a callback prop and
a render callback as children and fails if either is called.
Nothing is listed ahead of a reader, and that is a rule rather than an oversight. A member
provisioned before any recording reads it converts a refusal that would have forced a decision into
@@ -315,8 +313,7 @@ only the uncommitted ones.
Recording is deterministic and carries no header, so an unchanged behaviour re-records to the same
bytes on any machine: recording everything is always safe, and `git diff` shows only what moved.
Without `--prune`, a golden the manifest stopped deriving is listed and the census test
(`derived-goldens.test.ts`) keeps failing on it; deleting coverage is always explicit.
Without `--prune`, a golden the manifest stopped deriving is listed and remains on disk.
Mutants are the defect evidence. `mutants/operation-mutations.ts` holds one anchored source edit
per adapter family, and every family's recording must change visible state when its mutant is
@@ -1,27 +0,0 @@
import { describe, expect, it } from 'vitest'
import { MOUNTED_OPERATION_MODULES } from './adapters/mounted-operation-modules'
import type { operationModuleLoader } from './operation-module-loader'
// Defer product loads until hook mount; registration-time loads apply shared-file mutants repeatedly and obscure adapter failures.
function refusingLoader(): ReturnType<typeof operationModuleLoader> {
return {
load: (path: string) => {
throw new Error(`loaded ${path} before a mount ran`)
},
mutationsApplied: () => 0
}
}
describe('adapter mount tables', () => {
it('reads no product source until a mount runs', () => {
const eager = MOUNTED_OPERATION_MODULES.flatMap(({ source, mounts }) => {
try {
mounts(refusingLoader(), {})
return []
} catch (error) {
return [`${source} ${error instanceof Error ? error.message : String(error)}`]
}
})
expect(eager).toEqual([])
})
})
@@ -1,27 +0,0 @@
import { readdirSync } from 'node:fs'
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
import { derivedGoldens } from './derived-goldens'
import { readScenarios } from './scenario-input'
const root = resolve(import.meta.dirname, '../../../..')
const input = readScenarios(
process.env.RPC_FOUNDATION_SCENARIOS ??
resolve(root, 'mobile/rpc-foundation/pilot-scenarios.json')
)
const directory =
process.env.RPC_FOUNDATION_GOLDENS ?? resolve(root, 'mobile/rpc-foundation/goldens')
describe('derived goldens', () => {
// Check both directions: missing derivations leave orphan files, and missing files leave unrecorded scenarios.
it('derives exactly the goldens on disk', () => {
const derived = derivedGoldens(input.scenarios).map((golden) => golden.id)
const onDisk = readdirSync(directory)
.filter((file) => file.endsWith('.json'))
.map((file) => file.replace(/\.json$/, ''))
expect(
derived.sort(),
'Record new goldens with `pnpm --dir mobile rpc:record`; delete ones the manifest no longer derives with `pnpm --dir mobile rpc:record --prune`'
).toEqual(onDisk.sort())
})
})
@@ -1,35 +0,0 @@
import { describe, expect, it } from 'vitest'
import { nativeMountingSubstitutes } from './native-mounting-substitutes'
/** TypeScript's emitted interop helper, verbatim: what every `import X from` in a mounted module runs. */
function importDefault(module: unknown): { default?: unknown } {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: mirrors the emit, which reads the marker off an untyped module record.
const record = module as { __esModule?: unknown; default?: unknown }
return record?.__esModule ? record : { default: module }
}
function substitute(name: string): unknown {
const found = nativeMountingSubstitutes().get(name)
if (found === undefined) {
throw new Error(`no substitute for ${name}`)
}
return found
}
describe('nativeMountingSubstitutes', () => {
it('names the module and member a recording reached instead of failing on a missing function', () => {
const store = importDefault(substitute('@react-native-async-storage/async-storage')).default
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the member is a function by construction; the test asserts what calling it throws.
const getItem = (store as { getItem: () => unknown }).getItem
expect(() => getItem()).toThrow(
'Native store reached during recording: @react-native-async-storage/async-storage.getItem'
)
})
it('throws on a member nobody substituted rather than recording an undefined native API', () => {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the read itself is the assertion; the proxy has no declared shape.
expect(() => (substitute('expo-crypto') as { randomUUID?: unknown }).randomUUID).toThrow(
'Unsubstituted native member: expo-crypto.randomUUID'
)
})
})
@@ -1,52 +0,0 @@
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
import { nativeMountingSubstitutes } from './native-mounting-substitutes'
import type * as NativeSubstitutesModule from './native-mounting-substitutes'
import { operationModuleLoader } from './operation-module-loader'
vi.mock('./native-mounting-substitutes', async (original) => {
const module = await original<typeof NativeSubstitutesModule>()
return { ...module, nativeMountingSubstitutes: vi.fn(module.nativeMountingSubstitutes) }
})
const roots: string[] = []
function sourceTree(files: Record<string, string>): string {
const root = mkdtempSync(join(tmpdir(), 'rpc-loader-work-budget-'))
roots.push(root)
mkdirSync(join(root, 'mobile', 'src'), { recursive: true })
for (const [name, source] of Object.entries(files)) {
writeFileSync(join(root, 'mobile', 'src', name), source)
}
return root
}
afterEach(() => {
for (const root of roots.splice(0)) {
rmSync(root, { recursive: true, force: true })
}
vi.clearAllMocks()
})
it('builds device substitutes only for a used loader and keeps their state per loader', async () => {
const root = sourceTree({
'operation.ts': `
import * as clipboard from 'expo-clipboard'
export const read = () => clipboard.getStringAsync()
export const write = () => clipboard.setStringAsync('first recording')
`
})
const loaders = Array.from({ length: 64 }, () => operationModuleLoader(root))
expect(nativeMountingSubstitutes).not.toHaveBeenCalled()
type ClipboardOperation = { read: () => Promise<string>; write: () => Promise<void> }
const first = loaders[0].load<ClipboardOperation>('mobile/src/operation.ts')
await first.write()
expect(await first.read()).toBe('first recording')
expect(nativeMountingSubstitutes).toHaveBeenCalledTimes(1)
const second = loaders[1].load<ClipboardOperation>('mobile/src/operation.ts')
expect(await second.read()).toBe('')
expect(await first.read()).toBe('first recording')
expect(nativeMountingSubstitutes).toHaveBeenCalledTimes(2)
})
@@ -29,19 +29,6 @@ afterAll(() => {
})
describe('the mounted module loader', () => {
it('preserves constants through a star reexport in an evaluated module', () => {
const modules = loaderOver({
'constants.ts': `export const CAPABILITY = 'files.mutation-ownership.v1'`,
'protocol.ts': `export * from './constants'`,
'operation.ts': `
import { CAPABILITY } from './protocol'
export const read = () => CAPABILITY
`
})
const { read } = modules.load<{ read: () => string }>('mobile/src/operation.ts')
expect(read()).toBe('files.mutation-ownership.v1')
})
it('follows named reexports reached through the task foundation barrel', () => {
const modules = loaderOver({
'mobile-tasks-legacy-foundation.tsx': `export * from './mapping'`,
@@ -152,19 +139,6 @@ describe('the mounted module loader', () => {
)
})
it('refuses a named import of an unlisted package on the read', () => {
const modules = loaderOver({
'uses-named.ts': `
import { thing } from 'expo-not-substituted'
export const read = () => thing
`
})
const { read } = modules.load<{ read: () => unknown }>('mobile/src/uses-named.ts')
expect(() => read()).toThrow(
'Unspecified native mounting dependency: expo-not-substituted.thing'
)
})
// Default dependencies may reference native members before an adapter overrides them; import alone must remain possible.
it('lets a namespace import of an unlisted package load, and refuses the member it reads', () => {
const modules = loaderOver({
@@ -1,70 +0,0 @@
import { createElement, type ElementType } from 'react'
import { act, create } from 'react-test-renderer'
import { describe, expect, it } from 'vitest'
import { nativeMountingSubstitutes } from './native-mounting-substitutes'
import { reactNativeScreenMembers } from './screen-native-substitutes'
function member(module: string, name: string): unknown {
const substitute = nativeMountingSubstitutes().get(module)
if (substitute === undefined) {
throw new Error(`no substitute for ${module}`)
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the read is the assertion; a substitute proxy has no declared shape.
return (substitute as Record<string, unknown>)[name]
}
const INERT_ELEMENTS: readonly (readonly [string, string])[] = [
...Object.entries(reactNativeScreenMembers())
.filter(([, value]) => typeof value === 'function')
.map(([name]): readonly [string, string] => ['react-native', name]),
['react-native-safe-area-context', 'SafeAreaView']
]
describe('the inert screen substitutes', () => {
// Preserve children/props while never invoking device callbacks, including render-callback children.
it.each(INERT_ELEMENTS)('renders %s.%s inertly', (module, name) => {
let invoked = 0
const element = member(module, name)
let rendered: ReturnType<typeof create> | undefined
act(() => {
rendered = create(
createElement(
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: every entry above is an inert element component by construction.
element as ElementType,
{ testID: name, onPress: () => invoked++, renderItem: () => invoked++ },
'child'
)
)
})
const tree = rendered?.toJSON()
expect(invoked).toBe(0)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a rendered host node carries exactly these fields.
const node = tree as { type: string; props: Record<string, unknown>; children: unknown }
expect(node.props.testID).toBe(name)
expect(typeof node.props.onPress).toBe('function')
expect(node.children).toEqual(['child'])
})
it('drops a render callback passed as children rather than calling it', () => {
let invoked = 0
let rendered: ReturnType<typeof create> | undefined
act(() => {
rendered = create(
createElement(
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the substitute is an inert element component by construction.
member('react-native', 'Pressable') as ElementType,
{},
// @ts-expect-error -- deliberately invalid function children; asserts the substitute drops them
() => {
invoked++
return null
}
)
)
})
expect(invoked).toBe(0)
const tree = rendered?.toJSON()
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a rendered host node carries exactly these fields.
expect((tree as { children: unknown }).children).toBeNull()
})
})
@@ -50,10 +50,4 @@ describe('recording scheduler randomness', () => {
const expected = [{ name: 'draw', ordinal: 1, value: SEEDED_FIRST_DRAW }]
expect([first, later]).toEqual([expected, expected])
})
it('draws the same seeded value before the first drain as after it', async () => {
expect(await record('draw-before-drain', false)).toEqual([
{ name: 'draw', ordinal: 1, value: SEEDED_FIRST_DRAW }
])
})
})
@@ -1,289 +0,0 @@
import { readdirSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { parseSync } from 'oxc-parser'
// Census every WebView document with AST readers: module evaluation can retain the first mount’s nodes across remounts.
// Declarations can run work too, while literal shape alone implies no effect.
const DECLARATION_KINDS = new Set([
'ImportDeclaration',
'ExportNamedDeclaration',
'ExportDefaultDeclaration',
'ExportAllDeclaration',
'FunctionDeclaration',
'ClassDeclaration',
'VariableDeclaration',
'TSTypeAliasDeclaration',
'TSInterfaceDeclaration',
'TSEnumDeclaration',
'TSModuleDeclaration',
'TSDeclareFunction',
'TSImportEqualsDeclaration',
'EmptyStatement'
])
const RUNS_NOW = new Set([
'CallExpression',
'NewExpression',
'AwaitExpression',
'TaggedTemplateExpression'
])
/** What an initialiser *is* rather than what it does: its body runs later, not now. */
const RUNS_LATER = new Set(['FunctionExpression', 'ArrowFunctionExpression', 'ClassExpression'])
function fieldsOf(node: unknown): [string, unknown][] {
return node !== null && typeof node === 'object' && !Array.isArray(node)
? Object.entries(node)
: []
}
function stringField(node: unknown, key: string): string {
const found = fieldsOf(node).find(([name]) => name === key)?.[1]
return typeof found === 'string' ? found : ''
}
function field(node: unknown, key: string): unknown {
return fieldsOf(node).find(([name]) => name === key)?.[1]
}
function isElementGlobal(node: unknown): boolean {
const name = stringField(node, 'name')
return stringField(node, 'type') === 'Identifier' && (name === 'document' || name === 'window')
}
function initialiserRuns(node: unknown): boolean {
if (Array.isArray(node)) {
return node.some(initialiserRuns)
}
const type = stringField(node, 'type')
if (RUNS_NOW.has(type)) {
return true
}
if (RUNS_LATER.has(type)) {
return false
}
if (type === 'MemberExpression' && isElementGlobal(field(node, 'object'))) {
return true
}
return fieldsOf(node).some(([key, value]) => key !== 'type' && initialiserRuns(value))
}
function readsTheDocument(node: unknown): boolean {
if (Array.isArray(node)) {
return node.some(readsTheDocument)
}
if (isElementGlobal(node)) {
return true
}
return fieldsOf(node).some(([key, value]) => key !== 'type' && readsTheDocument(value))
}
function parseModule(name: string, source: string) {
const { program, errors } = parseSync(`${name}.ts`, source, { lang: 'ts' })
if (errors.length > 0) {
throw new Error(`[webview-document-census] ${name}.ts did not parse: ${errors[0]?.message}`)
}
return program
}
// Do not descend into default-exported function bodies; declaration alone does not execute their calls.
const DECLARES_WITHOUT_RUNNING = new Set(['FunctionDeclaration', 'TSDeclareFunction'])
// Detect evaluated declaration initializers, static class members and default-export expressions as module work.
export function parseTimeEffects(name: string, source: string): string[] {
const effects: string[] = []
const report = (node: unknown) => {
effects.push(`${name}: ${source.slice(numberField(node, 'start'), numberField(node, 'end'))}`)
}
for (const statement of parseModule(name, source).body) {
if (!DECLARATION_KINDS.has(statement.type)) {
effects.push(`${name}: ${statement.type}`)
continue
}
const exported =
statement.type === 'ExportNamedDeclaration' || statement.type === 'ExportDefaultDeclaration'
const declared = exported ? (field(statement, 'declaration') ?? statement) : statement
const declaredType = stringField(declared, 'type')
if (declaredType === 'VariableDeclaration') {
for (const declarator of arrayField(declared, 'declarations')) {
const init = field(declarator, 'init')
if (init && initialiserRuns(init)) {
report(declarator)
}
}
continue
}
if (declaredType === 'ClassDeclaration' || declaredType === 'ClassExpression') {
for (const member of arrayField(field(declared, 'body'), 'body')) {
// Static blocks/fields run with class evaluation; instance fields run later at construction.
if (stringField(member, 'type') === 'StaticBlock') {
report(member)
} else if (field(member, 'static') === true && initialiserRuns(field(member, 'value'))) {
report(member)
}
}
continue
}
if (
statement.type === 'ExportDefaultDeclaration' &&
!DECLARES_WITHOUT_RUNNING.has(declaredType) &&
initialiserRuns(declared)
) {
report(declared)
}
}
return effects
}
export function topLevelDeclarationsReachAnElement(name: string, source: string): boolean {
return parseModule(name, source)
.body.filter(
(statement) =>
statement.type === 'VariableDeclaration' ||
(statement.type === 'ExportNamedDeclaration' &&
statement.declaration?.type === 'VariableDeclaration')
)
.some(readsTheDocument)
}
// Read ordered lifecycle calls from the AST so unwind mentions cannot count as starts.
export function sequenceCalls(source: string, functionName: string, ignore: string[]): string[] {
const declaration = parseModule('sequence', source)
.body.map((statement) =>
statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement
)
.find(
(node) =>
node?.type === 'FunctionDeclaration' &&
stringField(field(node, 'id'), 'name') === functionName
)
const called: string[] = []
const walk = (node: unknown): void => {
if (Array.isArray(node)) {
node.forEach(walk)
return
}
if (stringField(node, 'type') === 'CallExpression') {
const name = stringField(field(node, 'callee'), 'name')
if (name !== '' && !ignore.includes(name)) {
called.push(name)
}
}
fieldsOf(node).forEach(([key, value]) => {
if (key !== 'type') {
walk(value)
}
})
}
walk(declaration)
return called
}
// Stop at function-owned bindings, which belong to calls; blocks still belong to the module.
const OWNS_ITS_BINDINGS = new Set([
'FunctionDeclaration',
'FunctionExpression',
'ArrowFunctionExpression',
'ClassDeclaration',
'ClassExpression',
'TSDeclareFunction'
])
function arrayField(node: unknown, key: string): unknown[] {
const found = field(node, key)
return Array.isArray(found) ? found : []
}
function numberField(node: unknown, key: string): number {
const found = field(node, key)
return typeof found === 'number' ? found : -1
}
// Walk top-level mutable bindings through exports, blocks and loops; stop at function scopes.
export function moduleLevelMutableBindings(name: string, source: string): string[] {
const found: string[] = []
const walk = (node: unknown): void => {
if (Array.isArray(node)) {
node.forEach(walk)
return
}
const type = stringField(node, 'type')
if (OWNS_ITS_BINDINGS.has(type)) {
return
}
if (type === 'VariableDeclaration') {
const kind = stringField(node, 'kind')
if (kind === 'let' || kind === 'var') {
const declarations = field(node, 'declarations')
for (const declarator of Array.isArray(declarations) ? declarations : []) {
const id = field(declarator, 'id')
found.push(
`${name}: ${kind} ${source.slice(numberField(id, 'start'), numberField(id, 'end'))}`
)
}
}
return
}
fieldsOf(node).forEach(([key, value]) => {
if (key !== 'type') {
walk(value)
}
})
}
walk(parseModule(name, source).body)
return found
}
// Find lifecycle exports by name and scope parameter, including async/wrapped declarations; textual matching can silently miss both sides of a set comparison.
export function exportedLifecycleFunctions(
source: string,
keyword: 'start' | 'stop',
scopeType: string
): string[] {
const names: string[] = []
for (const statement of parseModule('lifecycle', source).body) {
if (statement.type !== 'ExportNamedDeclaration') {
continue
}
const declared = field(statement, 'declaration')
if (stringField(declared, 'type') !== 'FunctionDeclaration') {
continue
}
const name = stringField(field(declared, 'id'), 'name')
if (!name.startsWith(keyword)) {
continue
}
// Lifecycle starts take only scope; startEdgeScroll(scope, dir) is an action, not module startup.
const params = arrayField(declared, 'params')
const [first] = params
if (params.length !== 1 || stringField(first, 'name') !== 'scope') {
continue
}
const annotation = field(first, 'typeAnnotation')
const written = source
.slice(numberField(annotation, 'start'), numberField(annotation, 'end'))
.replace(/^:\s*/, '')
if (written === scopeType) {
names.push(name)
}
}
return names
}
// Discover modules from the directory so unlisted files cannot evade lifecycle rules.
export function documentModuleNames(directory: string, except: string[]): string[] {
return readdirSync(directory)
.filter((name) => name.endsWith('.ts') && !name.includes('.test'))
.map((name) => name.replace(/\.ts$/, ''))
.filter((name) => !except.includes(name))
.sort()
}
export function documentModuleSource(directory: string, name: string): string {
return readFileSync(join(directory, `${name}.ts`), 'utf8')
}
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types'
import { flattenAgentRowLineage, type AgentRowNode } from './agent-row-lineage'
import { flattenAgentRowLineage } from './agent-row-lineage'
function row(paneKey: string, parentPaneKey: string | null): RuntimeWorktreeAgentRow {
return {
@@ -42,34 +42,4 @@ describe('agent lineage traversal', () => {
[3, 2]
])
})
it('copies no ancestor members while traversing a long lineage', () => {
const rows = Array.from({ length: 512 }, (_, index) =>
row(`pane-${index}`, index === 0 ? null : `pane-${index - 1}`)
)
const NativeSet = globalThis.Set
let copiedMembers = 0
class ObservedSet<T> extends NativeSet<T> {
constructor(values?: Iterable<T> | null) {
super()
if (values) {
for (const value of values) {
copiedMembers += 1
this.add(value)
}
}
}
}
vi.stubGlobal('Set', ObservedSet)
let actual: AgentRowNode[]
try {
actual = flattenAgentRowLineage(rows)
} finally {
vi.unstubAllGlobals()
}
expect(copiedMembers).toBe(0)
expect(actual.map((node) => [node.row.paneKey, node.depth])).toEqual(
rows.map((agent, index) => [agent.paneKey, index])
)
})
})
+49 -11
View File
@@ -2,6 +2,7 @@ import type {
AgentSessionHistoryPage,
AgentSessionHistoryResult
} from '../shared/agent-session/agent-session-wire'
import type { AgentSessionWorkState } from '../shared/agent-session/agent-session-work-state'
import { AGENT_SESSION_HISTORY_MAX_LIMIT } from '../shared/agent-session/agent-session-wire'
import {
AGENT_SESSION_UNATTACHED_REFUSAL_CODE,
@@ -56,8 +57,45 @@ export async function readTranscript(
return { ...response, result: { session, entries, cursor: page.window.newest, truncated } }
}
export function requireWorkingFlag(page: AgentSessionHistoryPage): void {
if (page.working === undefined) {
/** Older hosts' history pages may omit `working`. */
export type ChatWorkState = Omit<AgentSessionWorkState, 'working'> & { working?: boolean }
/** One command's reads of the facts a send or wait decides from. Hosts without
* `agentSession.workState` answer from a history page for the rest of the command. */
export function chatWorkStateReader(
client: RuntimeClient,
session: string
): () => Promise<ChatWorkState> {
let historyOnly = false
return async () => {
if (!historyOnly) {
try {
const response = await client.call<AgentSessionWorkState>('agentSession.workState', {
sessionId: session
})
return response.result
} catch (error) {
if (!(error instanceof RuntimeClientError && error.code === 'method_not_found')) {
throw explainChatRefusal(error, session, 'read')
}
historyOnly = true
}
}
const { page } = (await readHistory(client, session, 1)).result
return {
...(page.working !== undefined ? { working: page.working } : {}),
actionablePrompt: (page.actionablePromptIds?.length ?? 0) > 0,
...(page.queuedMessages !== undefined
? { queuedMessageIds: (page.queuedMessages ?? []).map((m) => m.messageId) }
: {}),
nextQueuedMessageId: page.nextQueuedMessageId ?? null,
...(page.fence !== undefined ? { fence: page.fence } : {})
}
}
}
export function requireWorkingFlag(state: { working?: boolean }): void {
if (state.working === undefined) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host does not report when a chat is working, so it cannot wait. Update Orca on the host.'
@@ -67,26 +105,26 @@ export function requireWorkingFlag(page: AgentSessionHistoryPage): void {
// Settled means no running turn or unanswered send, or a question/approval waiting for the user.
export async function waitForChat(
client: RuntimeClient,
session: string,
readWorkState: () => Promise<ChatWorkState>,
timeoutMs: number | undefined,
queuedMessageId?: string
): Promise<ChatSettled> {
const deadline = timeoutMs === undefined ? Infinity : Date.now() + timeoutMs
for (;;) {
const { page } = (await readHistory(client, session, 1)).result
requireWorkingFlag(page)
if ((page.actionablePromptIds?.length ?? 0) > 0) {
const state = await readWorkState()
requireWorkingFlag(state)
if (state.actionablePrompt) {
return 'blocked'
}
// Between turns the host names its next automatic send while working is briefly false.
const sendsNext = structuredAgentSessionQueueSendsNext(
page.nextQueuedMessageId,
page.working === true
state.nextQueuedMessageId,
state.working === true
)
if (!page.working && !sendsNext) {
if (!state.working && !sendsNext) {
// Still queued with nothing running or about to send: stopped, failed or held across a reopen.
const held = page.queuedMessages?.some((m) => m.messageId === queuedMessageId) === true
const held =
queuedMessageId !== undefined && state.queuedMessageIds?.includes(queuedMessageId) === true
return held ? 'held' : 'done'
}
if (Date.now() >= deadline) {
+10 -10
View File
@@ -35,6 +35,10 @@ function historyPage(
})
}
function workState(fields: Record<string, unknown>) {
return ok({ working: false, actionablePrompt: false, ...fields })
}
function item(body: unknown) {
return { itemId: 'i', revision: 1, sequence: 1, observedAt: 1, body }
}
@@ -90,7 +94,7 @@ afterEach(() => {
describe('chat send', () => {
it('sends a host-valid message fenced to the chat it read, queued while the agent works', async () => {
const client = fakeClient([
historyPage([], 7),
workState({ fence: 7 }),
ok({
ok: true,
replayed: false,
@@ -122,7 +126,7 @@ describe('chat send', () => {
it('reports a host refusal as an error instead of a sent message', async () => {
const client = fakeClient([
historyPage([], 2),
workState({ fence: 2 }),
ok({
ok: false,
refusal: { code: 'agent_session_fence_mismatch', message: 'The chat restarted.' }
@@ -136,7 +140,7 @@ describe('chat send', () => {
it('with --wait, waits for its queued message to run and returns that turn', async () => {
vi.useFakeTimers()
const client = fakeClient([
historyPage([], 7, { working: true }),
workState({ fence: 7, working: true }),
ok({
ok: true,
replayed: false,
@@ -148,13 +152,9 @@ describe('chat send', () => {
}
}),
// The earlier turn ended, but the queued message has not been handed to the agent yet.
historyPage([], 7, {
working: false,
queuedMessages: [{ messageId: 'q-1' }],
nextQueuedMessageId: 'q-1'
}),
historyPage([], 7, { working: true, queuedMessages: [] }),
historyPage([], 7, { working: false, queuedMessages: [], actionablePromptIds: [] }),
workState({ fence: 7, queuedMessageIds: ['q-1'], nextQueuedMessageId: 'q-1' }),
workState({ fence: 7, working: true, queuedMessageIds: [] }),
workState({ fence: 7, queuedMessageIds: [] }),
historyPage([
item({ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Earlier' }] }),
item({ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Old reply' }] }),
+7 -6
View File
@@ -17,9 +17,9 @@ import { AGENT_STATUS_STATES } from '../../shared/agent-status/contracts/agent-s
import { readInjectedAgentSessionId } from '../../shared/agent-session/lifecycle/agent-session-caller-env'
import {
DEFAULT_READ_LIMIT,
chatWorkStateReader,
explainChatRefusal,
formatSettled,
readHistory,
readSettledTurn,
readTranscript,
requireWorkingFlag,
@@ -122,7 +122,7 @@ export const CHAT_HANDLERS: Record<string, CommandHandler> = {
'chat wait': async ({ flags, client, json }) => {
const session = readSession(flags, client)
const timeoutMs = getOptionalPositiveIntegerFlag(flags, 'timeout-ms')
const settled = await waitForChat(client, session, timeoutMs)
const settled = await waitForChat(chatWorkStateReader(client, session), timeoutMs)
printResult(await readSettledTurn(client, session, settled), json, formatSettled)
},
'chat send': async ({ flags, client, cwd, json }) => {
@@ -146,11 +146,12 @@ export const CHAT_HANDLERS: Record<string, CommandHandler> = {
AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY
) === true
// The send is fenced to the session's current runtime, so a restarted chat refuses it.
const { page } = (await readHistory(client, session, 1)).result
const readWorkState = chatWorkStateReader(client, session)
const state = await readWorkState()
if (wait) {
requireWorkingFlag(page)
requireWorkingFlag(state)
}
const { fence } = page
const { fence } = state
if (fence === undefined) {
throw new RuntimeClientError(
'agent_session_not_running',
@@ -188,7 +189,7 @@ export const CHAT_HANDLERS: Record<string, CommandHandler> = {
return
}
const queuedId = 'queued' in value ? value.queued.messageId : undefined
const settled = await waitForChat(client, session, timeoutMs, queuedId)
const settled = await waitForChat(readWorkState, timeoutMs, queuedId)
const turn = await readSettledTurn(client, session, settled)
printResult({ ...turn, result: { ...sent, ...turn.result } }, json, formatSettled)
}
@@ -0,0 +1,150 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it, onTestFinished, vi } from 'vitest'
import { closeProviderTimelineRigs } from '../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support'
import { createStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger'
import { collectBundle } from '../../observability/bundle'
import { createLocalFileSink } from '../../observability/local-file-sink'
import { setActiveSink } from '../../observability/tracer'
import { acpLaunchSpecFor } from '../launch/acp-launch-registry'
import { GROK, openAcpAdapterRig } from './testing/acp-structured-adapter.test-support'
afterEach(async () => {
setActiveSink(null)
vi.restoreAllMocks()
await closeProviderTimelineRigs()
})
it.each(['initialize', 'session/new', 'authenticate'])(
'keeps a live %s rejection and stderr in the startup failure',
async (method) => {
const rig = await openAcpAdapterRig({
spec: acpLaunchSpecFor('antigravity')!,
initialize: { authMethods: [{ id: 'oauth-personal', name: 'Google' }] },
script: (agent) => {
if (method === 'authenticate') {
agent.on('session/new', (frame) => agent.fail(frame, -32000, 'Sign in'))
}
agent.on(method, (frame) => {
rig.child().stderr = 'harness: Permission denied {"token":"stderr-private"}'
agent.fail(frame, -32603, 'Internal error', {
details: '{"error":"Cannot execute localharness","authorization":"Bearer rpc-private"}'
})
})
}
})
await rig.acquire()
expect(rig.openVerdict()).toMatchObject({
retry: 'never',
cause: {
name: 'AcpAgentError',
code: -32603,
data: {
details: '{"error":"Cannot execute localharness","authorization":"Bearer rpc-private"}'
}
},
fact: {
kind: 'startFailed',
detail: {
audience: 'log',
text: '{"error":"Cannot execute localharness",[redacted:labeled-kv]}\nharness: Permission denied {[redacted:labeled-kv]}'
}
}
})
}
)
it('reserves space for long RPC details and the newest redacted stderr', async () => {
const rig = await openAcpAdapterRig({
script: (agent) =>
agent.on('session/new', (frame) => {
rig.child().stderr = `${'old stderr\n'.repeat(100)}recent harness failure token=private`
agent.fail(frame, -32603, 'Internal error', { details: `RPC evidence ${'x'.repeat(700)}` })
})
})
await rig.acquire()
const detail = rig.openVerdict()?.fact.detail?.text
expect(detail).toHaveLength(512)
expect(detail).toContain('RPC evidence')
expect(detail).toContain('recent harness failure [redacted:labeled-kv]')
expect(detail).not.toContain('private')
})
it('keeps existing sign-in failure wording free of preceding stderr', async () => {
const rig = await openAcpAdapterRig({
script: (agent) =>
agent.on('session/new', (frame) => {
rig.child().stderr = 'unrelated preceding stderr'
agent.fail(frame, -32000, 'Please sign in')
})
})
await rig.acquire()
expect(rig.openVerdict()?.fact.kind).toBe('notSignedIn')
expect(rig.openVerdict()?.fact.detail?.text).not.toContain('preceding stderr')
})
it.each(['load', 'resume'] as const)(
'retains a rejected %s in the trace and exported bundle after fallback succeeds',
async (method) => {
const directory = await mkdtemp(join(tmpdir(), 'acp-start-diagnostic-'))
const traceFile = join(directory, 'main.trace.ndjson')
const sink = createLocalFileSink({ filePath: traceFile })
onTestFinished(async () => {
setActiveSink(null)
sink.close()
await rm(directory, { recursive: true, force: true })
})
setActiveSink(sink)
vi.spyOn(console, 'warn').mockImplementation(() => {})
const rig = await openAcpAdapterRig({
spec: { ...GROK, resumePreference: method === 'resume' ? 'resume' : undefined },
initialize: {
agentCapabilities: { loadSession: true, sessionCapabilities: { resume: {} } }
},
launch: {
resume: {
sessionId: 'saved-session',
key: 'acp:grok:saved',
mayBeUnsaved: async () => false,
lossKeys: []
}
},
deps: { logger: createStructuredAgentSessionLogger() },
script: (agent) =>
agent.on(`session/${method}`, (frame) => {
rig.child().stderr =
'saved database unavailable "authorization":"Bearer stderr-private" refresh_token="opaque-oauth-proof" harness evidence'
agent.fail(
frame,
-32603,
'Internal error',
method === 'load'
? { reason: 'database open failed', token: 'rpc-private' }
: { details: '{"error":"database open failed","token":"rpc-private"}' }
)
})
})
await rig.acquire()
expect(rig.openVerdict()).toBeUndefined()
expect(rig.started().link?.origin).toBe('created')
await sink.flushAsync()
const bundle = collectBundle({
traceFilePath: traceFile,
maxFiles: 1,
appVersion: '1',
platform: 'darwin',
arch: 'arm64',
osRelease: '24',
orcaChannel: 'dev'
})
expect(bundle.payload).toContain('agentSession.acp-restore-failed')
expect(bundle.payload).toContain('providerDetail')
expect(bundle.payload).toContain('database open failed')
expect(bundle.payload).toContain('saved database unavailable [redacted:labeled-kv]')
expect(bundle.payload).not.toContain('rpc-private')
expect(bundle.payload).not.toContain('stderr-private')
expect(bundle.payload).toContain('harness evidence')
expect(bundle.payload).not.toContain('opaque-oauth-proof')
}
)
@@ -0,0 +1,41 @@
import {
MAX_PROVIDER_DIAGNOSTIC_CHARS,
providerDiagnostic,
providerDiagnosticOf,
withProviderDiagnostic
} from '../../../../shared/agent-session/failures/agent-session-failure'
import { redactString, redactValue } from '../../../observability/redactor'
import { providerStderrForDisplay } from '../../../provider-process/provider-spawn-failure-report'
import type { AcpDialect } from '../../acp-dialects/acp-dialect'
import type { AcpStructuredConnection } from '../../process/acp-structured-connection'
import { AcpAgentError, acpErrorDataWords } from '../../transport/acp-errors'
import { acpAuthenticationRequired, acpPromptErrorDetail } from '../../turns/acp-prompt-failure'
/** Keep the rejection's type and retry meaning; diagnostics belong to the existing Details. */
export function withAcpStartupDiagnostic(
error: unknown,
connection: AcpStructuredConnection,
dialect: AcpDialect
): void {
if (
!(error instanceof AcpAgentError) ||
acpAuthenticationRequired(dialect, error) ||
providerDiagnosticOf(error)
) {
return
}
let words = acpPromptErrorDetail(dialect, error)
if (error.data != null && acpErrorDataWords(error.data) === undefined) {
try {
words = dialect.promptErrorDetail?.(error) ?? JSON.stringify(redactValue(error.data)) ?? words
} catch {
// Diagnostic formatting must never replace the agent's rejection.
}
}
const rpc = redactString(words).trim()
const stderr = redactString(providerStderrForDisplay(connection.stderrTail())).trim()
const limit = MAX_PROVIDER_DIAGNOSTIC_CHARS
const reply = rpc.slice(0, stderr ? Math.floor(limit / 2) : limit)
const tail = stderr.slice(-(limit - (reply ? reply.length + 1 : 0)))
withProviderDiagnostic(error, providerDiagnostic([reply, tail].filter(Boolean).join('\n'), 'log'))
}
@@ -1,5 +1,6 @@
import { withStructuredHistoryInvocation } from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-history-invocation'
import { observeAcpForkSupport } from '../../capabilities/acp-fork-support'
import { withAcpStartupDiagnostic } from './acp-startup-diagnostic'
// An ACP child's handshake, run after the host has published it: initialize, reopen the chat's
// session or start a new one, then return its protocol facts to the host. A saved session the
// agent cannot reopen is replaced by a new one, with a warning row that any later start writes if
@@ -109,6 +110,7 @@ export async function initializeAcpStructuredSession(
replayed = input.lanes.finishLoad()
attaching.translator.finishLoad()
} catch (error) {
withAcpStartupDiagnostic(error, connection, spec.dialect)
takeover = await acpReopenTakeover(error, resume, {
// An agent already exited, its output still draining, has no session to take over in.
over: connection.closed || connection.exited || input.abandoned(),
@@ -7,6 +7,7 @@ import { acpAgentName } from '../acp-structured-agent-definitions'
import { acpStartupFailure } from '../children/acp-structured-child'
import type { AcpStructuredChildren } from '../children/acp-structured-child-lifecycle'
import { acpStartFailure } from './acp-startup-outcome'
import { withAcpStartupDiagnostic } from './acp-startup-diagnostic'
/** A start's open answers with the agent's verdict; a child that already ended answers with how
* it ended, and an answer its own exit followed is still worded as that exit. */
@@ -40,6 +41,9 @@ export async function openAcpStart(
throw failure.detail ? withProviderDiagnostic(refusal, failure.detail) : refusal
})
} catch (error) {
if (child) {
withAcpStartupDiagnostic(error, child.connection, child.spec.dialect)
}
throw acpStartFailure(error, child?.connection.exited === true && !child.closeRequested)
}
}
@@ -2,7 +2,7 @@ import type {
AgentJournalRenderItem,
AgentJournalSubmission
} from '../../../shared/agent-session/journal/agent-session-journal-types'
import { runningStructuredAgentSessionTurnItemBySequence } from '../../../shared/agent-session/view/structured-agent-session-live-turn'
import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record'
import type { JournalLatestStop } from './context-epochs/journal-stop-turn-end'
import { journalContextEpoch } from './context-epochs/journal-context-epoch'
import type { JournalSqlScope } from './journal-sql-scope'
@@ -173,8 +173,9 @@ export class JournalSqlStatusContext {
itemFence = (id: string) => this.current(id)?.fence
runningTurn = () => {
const boundary = this.select({ kind: 'boundary', raw: true })[Symbol.iterator]().next().value
return boundary ? runningStructuredAgentSessionTurnItemBySequence([boundary.item]) : null
const item = this.select({ kind: 'boundary', raw: true })[Symbol.iterator]().next().value?.item
const turn = item ? readAgentJournalTurn(item.body) : null
return item && turn?.state === 'running' ? { item, turnId: turn.turnId } : null
}
recoverableSubmissions = (): AgentJournalSubmission[] => {
@@ -59,7 +59,8 @@ export class StructuredAgentSessionHost {
private readonly lifetime: HostTypes.StructuredAgentSessionConversationLifetime
private readonly conversationDelivery: conversation.StructuredAgentSessionConversationDelivery
private readonly eventRecovery: EventRecovery
private readonly backgroundTasks: BackgroundTasks
/** History and work-state reads, which open a chat at rest without starting its agent. */
readonly backgroundTasks: BackgroundTasks
readonly restartResume: StructuredAgentSessionRestartResume
readonly usageLimitContinue: ReturnType<typeof usageLimit.start>

Some files were not shown because too many files have changed in this diff Show More