test: remove 46 more low-value cases and eleven suites

This commit is contained in:
OrcaWin
2026-11-11 10:40:39 -08:00
parent 225e98cbb2
commit 5606ccfdd2
28 changed files with 20 additions and 915 deletions
@@ -4528,7 +4528,6 @@
"src/renderer/src/components/editor/ai-vault-session-log-content.test.tsx": 1899,
"src/renderer/src/components/editor/check-details/actions/check-annotation-path.test.ts": 53,
"src/renderer/src/components/editor/model-lifetime/retention/closed-editor-model-lifetime.test.ts": 7921,
"src/renderer/src/components/editor/model-lifetime/retention/closed-editor-model-shell.test.tsx": 4492,
"src/renderer/src/components/editor/model-lifetime/retention/closed-editor-tab-disposal.test.ts": 121,
"src/renderer/src/components/editor/model-lifetime/retention/closed-editor-view-state-retention.test.ts": 9012,
"src/renderer/src/components/editor/closed-unsaved-files-toast.test.ts": 448,
@@ -10,19 +10,16 @@ private const val DOCUMENT = "orca-mobile-web://sess-01JN_aZ9/"
private fun verdict(
url: String? = FOREIGN,
isForMainFrame: Boolean = true,
isFromSubframe: Boolean = false,
isDocumentUrl: Boolean = false,
isShellLoad: Boolean = false,
hasGesture: Boolean = true,
isDownload: Boolean = false
hasGesture: Boolean = true
) = mobileWebShellNavigationVerdict(
url,
isForMainFrame,
isFromSubframe,
false,
isDocumentUrl,
isShellLoad,
false,
hasGesture,
isDownload
false
)
class MobileWebShellDroppedNavigationTest {
@@ -41,62 +38,12 @@ class MobileWebShellDroppedNavigationTest {
)
}
@Test
fun `allows the document only for the load the shell itself started`() {
assertEquals(
MobileWebShellNavigationVerdict.Allow,
verdict(url = DOCUMENT, isDocumentUrl = true, isShellLoad = true, hasGesture = false)
)
// iOS reports the source frame; a subframe cannot borrow the shell-load flag.
assertEquals(
MobileWebShellNavigationVerdict.Cancel,
verdict(
url = DOCUMENT,
isFromSubframe = true,
isDocumentUrl = true,
isShellLoad = true,
hasGesture = false
)
)
}
@Test
fun `cancels a foreign navigation with no gesture and offers nothing`() {
// Meta refresh/redirects must not open a browser without a user action.
assertEquals(MobileWebShellNavigationVerdict.Cancel, verdict(hasGesture = false))
}
@Test
fun `cancels a download rather than allowing it, and offers a gesture-started one`() {
assertEquals(
MobileWebShellNavigationVerdict.Cancel,
verdict(
url = DOCUMENT,
isDocumentUrl = true,
isShellLoad = true,
hasGesture = false,
isDownload = true
)
)
assertEquals(
MobileWebShellNavigationVerdict.CancelAndOffer(FOREIGN),
verdict(isDownload = true)
)
}
@Test
fun `refuses a download that names the document, and offers it to nobody`() {
// A document-URL download is never offered, from either frame or gesture state.
assertEquals(
MobileWebShellNavigationVerdict.Cancel,
verdict(url = DOCUMENT, isDocumentUrl = true, isDownload = true)
)
assertEquals(
MobileWebShellNavigationVerdict.Cancel,
verdict(url = DOCUMENT, isFromSubframe = true, isDocumentUrl = true, isDownload = true)
)
}
@Test
fun `offers nothing for a subframe, which is the sealed preview loading itself`() {
assertEquals(MobileWebShellNavigationVerdict.Cancel, verdict(isForMainFrame = false))
-21
View File
@@ -1,21 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
vi.mock('react-native', () => ({
StyleSheet: { create: <T>(styles: T) => styles },
View: 'View'
}))
import { colors } from '../theme/mobile-theme'
import { statusDotColor } from './StatusDot'
describe('statusDotColor', () => {
it('keeps Relay progress amber when the raw state is disconnected', () => {
expect(
statusDotColor('disconnected', {
kind: 'normal',
label: 'Connecting via Relay…',
dialing: true
})
).toBe(colors.statusAmber)
})
})
@@ -1,9 +1,5 @@
import { describe, expect, it } from 'vitest'
import {
bottomDrawerDismissMotion,
bottomDrawerScrim,
shouldDismissBottomDrawer
} from './bottom-drawer-drag-motion'
import { bottomDrawerDismissMotion, shouldDismissBottomDrawer } from './bottom-drawer-drag-motion'
describe('bottom drawer release', () => {
it('judges where the sheet is heading, not where the finger let go', () => {
@@ -23,10 +19,4 @@ describe('bottom drawer release', () => {
expect(((y1 / x1) * remaining) / (duration / 1000)).toBeCloseTo(velocity)
}
})
it('clears the dim exactly when the sheet has left the screen', () => {
const travel = 777 + 48
expect(bottomDrawerScrim(1, travel, 777)).toBe(1)
expect(bottomDrawerScrim(1 - 777 / travel, travel, 777)).toBeCloseTo(0)
})
})
@@ -1,57 +0,0 @@
import { describe, expect, it } from 'vitest'
import { resolveBottomDrawerKeyboardInset } from './bottom-drawer-keyboard-inset'
describe('resolveBottomDrawerKeyboardInset', () => {
it('uses the full keyboard frame for fill sheets on iOS and Android', () => {
expect(
resolveBottomDrawerKeyboardInset({
keyboardHeight: 336,
bottomInset: 34,
fillAvailable: true,
platform: 'ios'
})
).toBe(336)
expect(
resolveBottomDrawerKeyboardInset({
keyboardHeight: 300,
bottomInset: 48,
fillAvailable: true,
platform: 'android'
})
).toBe(300)
})
it('subtracts the home-indicator inset only for iOS content-sized sheets', () => {
expect(
resolveBottomDrawerKeyboardInset({
keyboardHeight: 336,
bottomInset: 34,
fillAvailable: false,
platform: 'ios'
})
).toBe(302)
})
it('uses the full IME height for Android content-sized sheets', () => {
// Why: Android keyboard height does not include the nav bar (session terminal lift).
expect(
resolveBottomDrawerKeyboardInset({
keyboardHeight: 300,
bottomInset: 48,
fillAvailable: false,
platform: 'android'
})
).toBe(300)
})
it('never returns a negative inset', () => {
expect(
resolveBottomDrawerKeyboardInset({
keyboardHeight: 20,
bottomInset: 34,
fillAvailable: false,
platform: 'ios'
})
).toBe(0)
})
})
@@ -9,16 +9,6 @@ import {
} from './drag-reorder-positions'
describe('drag reorder positions', () => {
it('shifts intermediate rows down when dragging a row later', () => {
const positions = dragReorderPositionsFromKeys(['a', 'b', 'c', 'd'])
expect(orderedKeysFromDragReorderPositions(moveDragReorderKey(positions, 'a', 2))).toEqual([
'b',
'c',
'a',
'd'
])
})
it('shifts intermediate rows up when dragging a row earlier', () => {
const positions = dragReorderPositionsFromKeys(['a', 'b', 'c', 'd'])
expect(orderedKeysFromDragReorderPositions(moveDragReorderKey(positions, 'd', 1))).toEqual([
@@ -1,6 +1,5 @@
import { describe, expect, it } from 'vitest'
import { routeMarkdownHref } from './markdown-href-routing'
import { createNativeChatFileHref } from '../../../src/shared/native-chat/native-chat-href-routing'
describe('routeMarkdownHref', () => {
it('carries a #L fragment as a :line suffix', () => {
@@ -18,13 +17,6 @@ describe('routeMarkdownHref', () => {
})
})
it('preserves the existing wrapped reply-location contract', () => {
expect(routeMarkdownHref(createNativeChatFileHref(' docs/report.md:12:4 '))).toEqual({
kind: 'file',
pathText: 'docs/report.md:12:4'
})
})
it('routes file: URIs to the file opener', () => {
expect(routeMarkdownHref('file:///Users/me/wt/src/app.tsx')).toEqual({
kind: 'file',
@@ -39,12 +31,4 @@ describe('routeMarkdownHref', () => {
pathText: 'C:/repo/src/index.ts'
})
})
it('drops anchors, unknown schemes, and empty hrefs', () => {
expect(routeMarkdownHref('#section')).toEqual({ kind: 'none' })
expect(routeMarkdownHref('')).toEqual({ kind: 'none' })
expect(routeMarkdownHref('editor://file/x.ts')).toEqual({ kind: 'none' })
expect(routeMarkdownHref('javascript:alert(1)')).toEqual({ kind: 'none' })
expect(routeMarkdownHref('data:text/plain,hi')).toEqual({ kind: 'none' })
})
})
@@ -6,13 +6,6 @@ import { richMarkdownEditorStyle } from './document-style'
// Move globals onto host, including theme variables/color/font/box model; unlike terminal, editor owns these page rules rather than delegating to app seam.
const PREFIX = '.orca-rich-markdown-document-host'
/** Every selector in a sheet, one per entry, as the rewrite leaves them. */
function selectorsOf(css: string): string[] {
return [...css.matchAll(/(?:^|\})\s*([^{}]+)\{/g)].flatMap((match) =>
match[1]!.split(',').map((one) => one.trim())
)
}
describe('the editor stylesheet on the page', () => {
it('moves the document’s own rules onto the host rather than dropping them', () => {
const scoped = scopeDocumentStyleToHost(richMarkdownEditorStyle(), PREFIX)
@@ -27,17 +20,6 @@ describe('the editor stylesheet on the page', () => {
}
})
it('keeps the universal rule as the host and everything in it', () => {
const scoped = scopeDocumentStyleToHost('* { box-sizing: border-box; }', PREFIX)
expect(selectorsOf(scoped)).toEqual([PREFIX, `${PREFIX} *`])
})
it('collapses the document’s three names to one host selector', () => {
expect(
selectorsOf(scopeDocumentStyleToHost(':root, html, body { color: red; }', PREFIX))
).toEqual([PREFIX])
})
it('refuses a document-level selector it cannot move, rather than scoping it wrongly', () => {
// Refuse compound host-global selector rather than silently rewriting body p into mismatching .host body p or changed .host p.
expect(() => scopeDocumentStyleToHost('body p { color: red; }', PREFIX)).toThrow(
@@ -45,15 +45,6 @@ it('updates the task name after editing its text', () => {
expect(editor.names()).toEqual(['First task updated'])
})
it('keeps an emptied task control named', () => {
const editor = mount('- [ ] Remove text')
editor.root.querySelector('p')!.replaceChildren()
editor.surface.dispatchEvent(
new InputEvent('input', { bubbles: true, inputType: 'deleteContentBackward' })
)
expect(editor.names()).toEqual(['Task'])
})
it('names a task from its own line rather than its code block', () => {
const editor = mount('- [ ] Install:\n ```sh\n pnpm install\n ```')
expect(editor.surface.querySelector('li pre')).not.toBeNull()
@@ -1,50 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { SUPPORTED_UI_LOCALES } from '../../../src/shared/ui-locale'
import { activateMobileUiLocale, translate } from '../i18n/mobile-i18n'
import { troubleshootCommonIssues } from './troubleshoot-common-issues'
vi.mock('lucide-react-native', () => ({
WifiOff: () => null,
Shield: () => null,
Monitor: () => null,
Clock: () => null,
Globe: () => null,
Bell: () => null
}))
afterEach(() => activateMobileUiLocale('en'))
describe('troubleshooting firewall advice', () => {
it.each([
{ endpoints: ['ws://192.168.1.10:6769'], ports: ['6769'] },
{ endpoints: ['ws://[fd7a:115c:a1e0::1]:7777'], ports: ['7777'] },
{ endpoints: ['wss://desktop.example', 'ws://desktop.local'], ports: ['443', '80'] },
{ endpoints: [], ports: ['6768'] },
{ endpoints: ['invalid endpoint'], ports: ['6768'] },
{
endpoints: ['ws://first.local:6769', 'ws://second.local:7777', 'ws://third.local:6769'],
ports: ['6769', '7777']
}
])('uses paired ports for $endpoints', ({ endpoints, ports }) => {
const sections = troubleshootCommonIssues(translate, endpoints).filter((section) =>
section.id.startsWith('firewall')
)
expect(sections.map((section) => section.title)).toEqual(
ports.map((port) => `Firewall Blocking Port ${port}`)
)
expect(sections.map((section) => section.steps.find((step) => step.includes('ufw')))).toEqual(
ports.map((port) => `Linux: sudo ufw allow ${port}`)
)
expect(new Set(sections.map((section) => section.id)).size).toBe(ports.length)
})
it.each(SUPPORTED_UI_LOCALES)('interpolates the paired port in %s', async (locale) => {
await activateMobileUiLocale(locale)
const section = troubleshootCommonIssues(translate, ['ws://desktop.local:6769']).find((entry) =>
entry.id.startsWith('firewall')
)
expect(section?.title).toContain('6769')
expect(section?.title).not.toContain('6768')
expect(section?.steps.some((step) => step.includes('sudo ufw allow 6769'))).toBe(true)
})
})
@@ -4,19 +4,6 @@ import { insertDictationText } from './mobile-dictation-text-insertion'
const at = (text: string, start: number, end = start) => ({ text, start, end })
describe('insertDictationText', () => {
it('spaces dictation away from the words around the caret at the start, middle and end', () => {
const draft = 'update the tests'
expect(insertDictationText(draft, 'Please', at(draft, 0))).toEqual({
text: 'Please update the tests',
caret: 6
})
expect(insertDictationText(draft, 'all', at(draft, 11)).text).toBe('update the all tests')
expect(insertDictationText(draft, 'now', at(draft, draft.length)).text).toBe(
'update the tests now'
)
expect(insertDictationText('Done.', 'Next', at('Done.', 5)).text).toBe('Done. Next')
})
it('replaces the selected words and keeps the caret after them', () => {
const draft = 'Rename the prop and update the tests'
expect(insertDictationText(draft, 'fetchTimeout', at(draft, 7, 15))).toEqual({
@@ -25,41 +12,6 @@ describe('insertDictationText', () => {
})
})
it('adds no space inside quotes, before punctuation or around CJK', () => {
const command = "git commit -m ''"
expect(insertDictationText(command, 'log retry', at(command, 15)).text).toBe(
"git commit -m 'log retry'"
)
expect(insertDictationText('git commit -m "', 'fix it', null).text).toBe(
'git commit -m "fix it'
)
expect(insertDictationText('He said “”', 'hello', at('He said “”', 9)).text).toBe(
'He said “hello”'
)
expect(insertDictationText('hello', ', world', at('hello', 5)).text).toBe('hello, world')
expect(insertDictationText('你好', '世界', at('你好', 2)).text).toBe('你好世界')
})
it('spaces dictation after closing quotes, brackets and symbols', () => {
for (const draft of [
'echo "hi"',
'see (this)',
'Look at `foo`',
'ls -la |',
'done 🎉',
"fix James'"
]) {
expect(insertDictationText(draft, 'and more', null).text).toBe(`${draft} and more`)
}
})
it('tells apostrophes from quote marks', () => {
const quoted = "it's 'quoted'"
expect(insertDictationText(quoted, 'really', at(quoted, 5)).text).toBe("it's really 'quoted'")
const inner = "don't touch 'x'"
expect(insertDictationText(inner, 'y', at(inner, 14)).text).toBe("don't touch 'x y'")
})
it('appends when the field was never focused or changed since the selection was read', () => {
expect(insertDictationText('ls -la', 'in src', null).text).toBe('ls -la in src')
expect(insertDictationText('', 'spoken', null).text).toBe('spoken')
@@ -1,8 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
import {
canPreviewMobileFileRow,
navigateToMobileFilePreview
} from './mobile-file-preview-navigation'
import { navigateToMobileFilePreview } from './mobile-file-preview-navigation'
describe('mobile-file-preview-navigation', () => {
it('pushes the file route before closing the embedded explorer on scheduler delivery', () => {
@@ -34,30 +31,4 @@ describe('mobile-file-preview-navigation', () => {
scheduleClose.mock.calls[0]?.[0]()
expect(events).toEqual(['push', 'schedule', 'close'])
})
it.each([
'mp4',
'MOV',
'm4v',
'webm',
'mp3',
'wav',
'm4a',
'aac',
'ogg',
'oga',
'flac',
'opus',
'pdf'
])('opens %s files from the explorer', (extension) => {
expect(
canPreviewMobileFileRow({ kind: 'binary', relativePath: `media/demo.${extension}` })
).toBe(true)
})
it('keeps non-image binary rows disabled while previewing text and raster images', () => {
expect(canPreviewMobileFileRow({ kind: 'text', relativePath: 'src/app.ts' })).toBe(true)
expect(canPreviewMobileFileRow({ kind: 'binary', relativePath: 'assets/logo.webp' })).toBe(true)
expect(canPreviewMobileFileRow({ kind: 'binary', relativePath: 'archive.zip' })).toBe(false)
})
})
@@ -1,30 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { describe, expect, it, vi } from 'vitest'
const viewport = vi.hoisted(() => ({ width: 669, height: 951, ownsHostArea: true }))
vi.mock('react-native', () => ({ useWindowDimensions: () => viewport }))
vi.mock('./page-owns-host-area', () => ({ usePageOwnsHostArea: () => viewport.ownsHostArea }))
vi.mock('../host-screen/HostScreen', () => ({ HostScreen: () => createElement('WorkspacePicker') }))
vi.mock('../components/WorkspaceDetailPlaceholder', () => ({
WorkspaceDetailPlaceholder: () => createElement('WorkspacePlaceholder')
}))
import HostWorktreeRoute from '../../app/h/[hostId]/index.web'
describe('host root content across layouts', () => {
it.each([
{ width: 390, height: 844, ownsHostArea: true, expected: 'WorkspacePicker' },
{ width: 669, height: 951, ownsHostArea: true, expected: 'WorkspacePicker' },
{ width: 951, height: 669, ownsHostArea: true, expected: 'WorkspacePlaceholder' },
{ width: 951, height: 669, ownsHostArea: false, expected: 'WorkspacePicker' }
])('renders $expected at $width with ownership $ownsHostArea', (state) => {
Object.assign(viewport, state)
let tree: ReactTestRenderer | undefined
act(() => {
tree = create(createElement(HostWorktreeRoute))
})
expect(tree?.toJSON()).toMatchObject({ type: state.expected })
act(() => tree?.unmount())
})
})
@@ -80,32 +80,22 @@ describe('a keyboard the phone closes', () => {
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],
['focused by the tap', true]
] as const)(
'keeps focus and reopens the keyboard when Chromium hides it for a tapped autocorrected word in a field %s',
(_case, tapFocuses) => {
const field = focusedField(ANDROID)
if (tapFocuses) {
field.blur()
}
startBlurringOnKeyboardClose()
it('keeps focus and reopens the keyboard when Chromium hides it for a tapped autocorrected word', () => {
const field = focusedField(ANDROID)
startBlurringOnKeyboardClose()
field.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))
TextInputState.focusTextInput(field)
shellReports(300)
const focusSessions = vi.fn()
field.addEventListener('focus', focusSessions)
vi.advanceTimersByTime(400)
shellReports(0)
vi.advanceTimersByTime(100)
field.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))
TextInputState.focusTextInput(field)
shellReports(300)
const focusSessions = vi.fn()
field.addEventListener('focus', focusSessions)
vi.advanceTimersByTime(400)
shellReports(0)
vi.advanceTimersByTime(100)
expect(document.activeElement).toBe(field)
expect(focusSessions).toHaveBeenCalledOnce()
}
)
expect(document.activeElement).toBe(field)
expect(focusSessions).toHaveBeenCalledOnce()
})
it.each([
['a touch elsewhere', 'body', 400],
@@ -123,14 +113,4 @@ describe('a keyboard the phone closes', () => {
expect(document.activeElement).not.toBe(field)
})
it('leaves focus alone on iOS, where only a blur closes the keyboard', () => {
const field = focusedField('Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X)')
startBlurringOnKeyboardClose()
shellReports(300)
shellReports(0)
expect(document.activeElement).toBe(field)
})
})
@@ -1,46 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useMobileNativeChatSessionOptionController } from './use-mobile-native-chat-session-option-controller'
describe('useMobileNativeChatSessionOptionController on a structured chat', () => {
let renderer: ReactTestRenderer | null = null
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
})
it("keeps the chat's /clear and /compact when its agent lists no models", () => {
const seen: { current: ReturnType<typeof useMobileNativeChatSessionOptionController> | null } =
{ current: null }
function Harness(): null {
seen.current = useMobileNativeChatSessionOptionController({
activeChatStructured: true,
activeSessionTabId: 'omp-tab',
agent: 'omp',
dispatchCommand: vi.fn(),
hostId: 'host',
isTabChatView: () => true,
isWorking: false,
reportedModel: null,
structured: {
conversationCommands: ['clear', 'compact'],
snapshot: [],
pendingId: null,
setOption: vi.fn(),
invokeAction: vi.fn()
},
toggleTabChatView: vi.fn(),
worktreeId: 'worktree'
})
return null
}
act(() => {
renderer = create(createElement(Harness))
})
expect(seen.current?.nativeChatSessionOptions?.controller.conversationCommands).toEqual([
'clear',
'compact'
])
})
})
@@ -1,60 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it } from 'vitest'
import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types'
import { Harness, Result, userMessage } from './use-mobile-native-chat-turn-disclosure.test-fixture'
function assistantMessage(id: string): NativeChatMessage {
return {
id,
role: 'assistant',
blocks: [{ type: 'text', text: id }],
timestamp: null,
source: 'transcript'
}
}
describe('useMobileNativeChatTurnDisclosure growing row', () => {
let renderer: ReactTestRenderer | null = null
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
})
it('marks no row while a prompt is open', () => {
const messages = [userMessage('u1'), assistantMessage('a1')]
act(() => {
renderer = create(createElement(Harness, { messages, enabled: true, lineYields: true }))
})
const { disclosure } = renderer!.root.findByType(Result).props
expect(disclosure.resolveRow(1, messages[1]).mayStillGrow).toBe(false)
})
it('marks only the newest assistant row, even when a user row follows it', () => {
const messages = [
userMessage('u1'),
assistantMessage('a1'),
assistantMessage('a2'),
userMessage('u2')
]
act(() => {
renderer = create(createElement(Harness, { messages, enabled: true }))
})
const { disclosure } = renderer!.root.findByType(Result).props
expect(
messages.map((message, index) => disclosure.resolveRow(index, message).mayStillGrow)
).toEqual([false, false, true, false])
})
it('puts only the terminal-backed streaming row in the live turn', () => {
const messages = [userMessage('u1'), assistantMessage('a1'), assistantMessage('streaming')]
act(() => {
renderer = create(createElement(Harness, { messages, enabled: false }))
})
const { disclosure } = renderer!.root.findByType(Result).props
expect(
messages.map((message, index) => disclosure.resolveRow(index, message).activeTurnIsWorking)
).toEqual([false, false, true])
})
})
@@ -22,14 +22,4 @@ describe('encodeTerminalKeyForModes', () => {
expect(encodeTerminalKeyForModes('\x1b[A', MODES)).toBe('\x1b[A')
expect(encodeTerminalKeyForModes('\x1b[A', { ...decckm, kittyKeyboardFlags: 1 })).toBe('\x1b[A')
})
it('encodes Shift+Enter for the negotiated keyboard protocol', () => {
expect(encodeTerminalKeyForModes('\x1b[13;2u', { ...MODES, kittyKeyboardFlags: 1 })).toBe(
'\x1b[13;2u'
)
expect(encodeTerminalKeyForModes('\x1b[13;2u', { ...MODES, modifyOtherKeys: 2 })).toBe(
'\x1b[27;2;13~'
)
expect(encodeTerminalKeyForModes('\x1b[13;2u', MODES)).toBe('\x1b\r')
})
})
@@ -1,54 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { z } from 'zod'
import { terminalSendAcceptedSchema, terminalViewportUpdatedSchema } from './terminal-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
}
describe('a terminal send is delivered only on an exact true', () => {
it('reads the accepted envelope', () => {
expect(reads(terminalSendAcceptedSchema, { send: { accepted: true } })).toBe(true)
expect(reads(terminalSendAcceptedSchema, { send: { accepted: false } })).toBe(false)
})
it('reads every other shape as not delivered rather than as an error', () => {
expect(reads(terminalSendAcceptedSchema, {})).toBe(false)
expect(reads(terminalSendAcceptedSchema, { send: null })).toBe(false)
expect(reads(terminalSendAcceptedSchema, { send: 'accepted' })).toBe(false)
expect(reads(terminalSendAcceptedSchema, { send: { accepted: 'yes' } })).toBe(false)
expect(reads(terminalSendAcceptedSchema, { error: 'refused' })).toBe(false)
})
})
describe('a viewport update projects both flags through an exact true', () => {
it('reads what the runtime recorded and whether it re-fitted', () => {
expect(reads(terminalViewportUpdatedSchema, { updated: true, applied: true })).toEqual({
updated: true,
applied: true
})
expect(reads(terminalViewportUpdatedSchema, { updated: true, applied: false })).toEqual({
updated: true,
applied: false
})
})
it('falls through to the legacy resubscribe for anything that is not exactly true', () => {
expect(reads(terminalViewportUpdatedSchema, {})).toEqual({ updated: false, applied: false })
expect(reads(terminalViewportUpdatedSchema, { updated: 1, applied: 1 })).toEqual({
updated: false,
applied: false
})
})
it('passes the seq the host also sends through without declaring it', () => {
expect(reads(terminalViewportUpdatedSchema, { updated: true, applied: true, seq: 9 })).toEqual({
updated: true,
applied: true
})
})
})
@@ -1,20 +0,0 @@
import { describe, expect, it } from 'vitest'
import { collapsedChildrenSignalState, partitionIdleChildren } from './agent-child-disclosure'
import type { AgentDotState } from './agent-row-display'
const children = (...states: AgentDotState[]) => states.map((dotState) => ({ dotState }))
describe('agent child disclosure', () => {
it('keeps a lone idle child inline and groups two or more', () => {
expect(partitionIdleChildren(children('working', 'idle')).idleChildren).toEqual([])
expect(partitionIdleChildren(children('idle', 'done', 'idle'))).toEqual({
activeChildren: children('done'),
idleChildren: children('idle', 'idle')
})
})
it('signals the most urgent hidden state and stays quiet for settled children', () => {
expect(collapsedChildrenSignalState(children('working', 'waiting', 'idle'))).toBe('waiting')
expect(collapsedChildrenSignalState(children('idle', 'done', 'unverifiable'))).toBeUndefined()
})
})
@@ -54,7 +54,3 @@ export function toggleDisclosure(key: string): void {
}
}
}
export function clearDisclosuresForTests(): void {
openDisclosureKeys.clear()
}
@@ -1,40 +0,0 @@
import { describe, expect, it } from 'vitest'
import { withFolderWorkspacesLast } from './folder-workspace-lane-order'
import type { Worktree } from './workspace-list-types'
function row(worktreeId: string, overrides: Partial<Worktree> = {}): Worktree {
return {
workspaceKind: 'git',
worktreeId,
repoId: 'repo-1',
repo: 'orca',
branch: '',
displayName: worktreeId,
path: `/tmp/${worktreeId}`,
liveTerminalCount: 0,
hasAttachedPty: false,
unread: false,
isPinned: false,
linkedPR: null,
agents: [],
...overrides
}
}
describe('withFolderWorkspacesLast', () => {
it('lists folder workspaces after the worktrees, by user rank then name, like desktop', () => {
const folder = { workspaceKind: 'folder-workspace' as const }
const rows = [
row('folder:low', { ...folder, displayName: 'b', sortOrder: 1 }),
row('git'),
row('folder:tie', { ...folder, displayName: 'a', sortOrder: 1 }),
row('folder:high', { ...folder, displayName: 'c', sortOrder: 5 })
]
expect(withFolderWorkspacesLast(rows).map((w) => w.worktreeId)).toEqual([
'git',
'folder:high',
'folder:tie',
'folder:low'
])
})
})
@@ -17,21 +17,6 @@ function makeRepo(id: string, overrides: Partial<Repo> = {}): Repo {
}
describe('mobile new workspace dialog repo selection', () => {
it('refreshes the selected repo from the fresh repo list', () => {
const staleSelectedRepo = makeRepo('repo', { path: '/cached/repo' })
const freshRepo = makeRepo('repo', { path: '/fresh/repo' })
expect(refreshMobileNewWorkspaceDialogSelectedRepo([freshRepo], staleSelectedRepo)).toBe(
freshRepo
)
})
it('clears a cached selected repo that is missing from the fresh repo list', () => {
expect(
refreshMobileNewWorkspaceDialogSelectedRepo([makeRepo('fresh')], makeRepo('stale'))
).toBe(null)
})
it('keeps a repo picked on a server when the desktop lists one with the same id', () => {
const onDesktop = makeRepo('repo', { path: '/mac/repo' })
const onServer = makeRepo('repo', { path: '/srv/repo', executionHostId: 'runtime:env-1' })
@@ -80,29 +80,4 @@ describe("a client's tab move in a workspace main owns", () => {
expect(groups().map((entry) => entry.tabOrder)).toEqual([[TAB_ID], ['a', 'b']])
})
it("refuses with today's codes and moves nothing", async () => {
const { runtime, groups, group } = await setup()
const before = groups()
await expect(
runtime.moveMobileSessionTab(WT, {
kind: 'move-to-group',
tabId: 'gone',
targetGroupId: group
})
).rejects.toThrow('tab_not_found')
await expect(
runtime.moveMobileSessionTab(WT, { kind: 'move-to-group', tabId: 'a', targetGroupId: 'gone' })
).rejects.toThrow('target_group_not_found')
await expect(
runtime.moveMobileSessionTab(WT, {
kind: 'reorder',
tabId: 'a',
targetGroupId: group,
tabOrder: ['a', 'b']
})
).rejects.toThrow('invalid_tab_order')
expect(groups()).toEqual(before)
})
})
@@ -96,12 +96,4 @@ describe('wslHolderKeepPolicy', () => {
addHost('Ubuntu', 42000)
expect(isWanted('ubuntu')).toBe(true)
})
it('keeps an add in flight, and nothing while hosts are off', () => {
expect(
wslHolderKeepPolicy({ userDataPath, keepHostHolders: true, isAdding: () => true })('Alpine')
).toBe(true)
addHost('Ubuntu', 42000)
expect(wslHolderKeepPolicy({ userDataPath, keepHostHolders: false })('Ubuntu')).toBe(false)
})
})
@@ -1,104 +0,0 @@
// @vitest-environment happy-dom
import React from 'react'
import { useStore, type StoreApi } from 'zustand'
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'
import { act, cleanup, render, waitFor } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import type { AppState } from '@/store/types'
import type { TerminalController } from '../../../use-terminal-controller'
import { TerminalLegacyEditorSurface } from '../../../TerminalLegacyEditorSurface'
import { editorModelRegistry } from '@/lib/editor/monaco/editor-model-registry'
import { useClosedEditorTabCleanup } from './useClosedEditorTabCleanup'
import {
createModelLifetimeFixture,
resetModelLifetimeFixtures
} from './editor-model-lifetime-fixture'
const fixture = vi.hoisted((): { store: StoreApi<AppState> | null } => ({ store: null }))
vi.mock('@/store/index', () => ({
useAppStore: {
getState: () => {
if (!fixture.store) {
throw new Error('Missing fixture store')
}
return fixture.store.getState()
},
subscribe: (...args: Parameters<StoreApi<AppState>['subscribe']>) => {
if (!fixture.store) {
throw new Error('Missing fixture store')
}
return fixture.store.subscribe(...args)
}
}
}))
vi.mock('sonner', () => ({ toast: { info: vi.fn(), error: vi.fn(), success: vi.fn() } }))
vi.mock('../../EditorPanel', () => ({ default: () => <div data-testid="editor-panel" /> }))
let unregister: (() => void) | null = null
function Surface({ visible }: { visible: boolean }): React.JSX.Element | null {
if (!fixture.store) {
throw new Error('Missing fixture store')
}
const files = useStore(fixture.store, (state) => state.openFiles)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The actual legacy surface reads only these three controller fields.
const controller = {
activeTabType: visible ? 'editor' : 'terminal',
renderedActiveWorktreeId: 'model-fixture::/fixture/workspace',
worktreeFiles: files
} as TerminalController
return <TerminalLegacyEditorSurface controller={controller} />
}
function Shell({ visible = true, generation = 0 }): React.JSX.Element {
useClosedEditorTabCleanup()
return <Surface key={generation} visible={visible} />
}
function setup(): ReturnType<typeof createModelLifetimeFixture> {
const context = createModelLifetimeFixture()
fixture.store = context.store
unregister = editorModelRegistry.register(monaco)
return context
}
afterEach(() => {
cleanup()
unregister?.()
unregister = null
fixture.store = null
resetModelLifetimeFixtures()
})
it('keeps the actual cleanup hook alive when closing the final editor unmounts its surface', async () => {
const { store, add } = setup()
const view = render(<Shell />)
for (let index = 0; index < 8; index += 1) {
const added: { model?: monaco.editor.ITextModel } = {}
act(() => {
added.model = add(`shell-last-${index}`).model
})
await waitFor(() => expect(view.queryByTestId('editor-panel')).not.toBeNull())
act(() => store.getState().closeFile(`shell-last-${index}`))
expect(view.queryByTestId('editor-panel')).toBeNull()
await Promise.resolve()
expect(added.model?.isDisposed()).toBe(true)
}
})
it('observes a close while the terminal subtree is absent and survives its remount', async () => {
const { store, add } = setup()
const old = add('shell-hidden')
const view = render(<Shell />)
await waitFor(() => expect(view.queryByTestId('editor-panel')).not.toBeNull())
view.rerender(<Shell visible={false} generation={1} />)
expect(old.model.isDisposed()).toBe(false)
act(() => store.getState().closeFile(old.file.id))
await Promise.resolve()
expect(old.model.isDisposed()).toBe(true)
act(() => {
add('shell-successor')
})
view.rerender(<Shell generation={2} />)
await waitFor(() => expect(view.queryByTestId('editor-panel')).not.toBeNull())
expect(store.getState().openFiles).toHaveLength(1)
})
@@ -1,107 +0,0 @@
import { bindPtyConnectionTestMocks } from '../test-fixtures/pty-connection-mocks.spec'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { sendTerminalInputThroughPane } from '../test-fixtures/pty-connection-test-dom'
import {
LEAF_2,
createMockTransport,
createPane,
createManager,
type MockTransport
} from '../test-fixtures/pty-connection-test-pane-fixtures'
import {
buildPaneConnectionDeps,
type PtyConnectionAgentTitleMocks,
bindPaneAgentTitleMocks
} from '../test-fixtures/pty-connection-test-deps'
import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures'
import type { StoreState } from '../test-fixtures/pty-connection-test-store-state'
import {
installTerminalTestGlobals,
restoreTerminalTestGlobals
} from '../test-fixtures/pty-connection-test-environment'
import { mockPanePtyArgs } from '../test-fixtures/pty-connection-test-connect-mock-pane'
export function registerPtyConnectionTerminalInputSessionListingTests(): void {
let mockStoreState: StoreState
let transportFactoryQueue: MockTransport[] = []
let createdTransportOptions: Record<string, unknown>[] = []
let storeSubscribers: ((state: StoreState) => void)[] = []
function createDeps(overrides: Record<string, unknown> = {}) {
return buildPaneConnectionDeps(() => mockStoreState, overrides)
}
describe('connectPanePty', () => {
beforeEach(async () => {
vi.clearAllMocks()
transportFactoryQueue = []
createdTransportOptions = []
storeSubscribers = []
mockStoreState = createInitialStoreState(() => mockStoreState)
bindPtyConnectionTestMocks({
getState: () => mockStoreState,
getTransportQueue: () => transportFactoryQueue,
getTransportOptions: () => createdTransportOptions,
getStoreSubscribers: () => storeSubscribers,
setStoreSubscribers: (subscribers) => {
storeSubscribers = subscribers
}
})
await installTerminalTestGlobals()
})
afterEach(async () => {
await restoreTerminalTestGlobals()
})
describe('terminal input liveness IPC gating (perf)', () => {
// Why (perf regression guard): listSessions() is a renderer→main→daemon round-trip; terminal input must never trigger it.
async function connectActivePaneWithInput(): Promise<{
binding: { noteVisibilityResume: () => void }
transport: MockTransport
typeKeystroke: (data?: string) => void
}> {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks16 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-pane-2')
transportFactoryQueue.push(transport)
const manager = createManager(2)
const deps = createDeps({
restoredLeafId: LEAF_2,
paneTransportsRef: { current: new Map([[1, createMockTransport('pty-pane-1')]]) }
})
const pane = createPane(2)
const binding = connectPanePty(
...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks16))
)
return {
binding,
transport,
// Drives the real xterm onData (terminal input) handler.
typeKeystroke: (data = 'a') => sendTerminalInputThroughPane(pane, data)
}
}
it('sends the first post-resume input without starting the liveness re-check', async () => {
const listSessions = vi.mocked(window.api.pty.listSessions)
listSessions.mockClear()
const calls: string[] = []
listSessions.mockImplementation(() => {
calls.push('listSessions')
return Promise.resolve([])
})
const { binding, transport, typeKeystroke } = await connectActivePaneWithInput()
transport.sendInput.mockImplementation(() => {
calls.push('sendInput')
return true
})
binding.noteVisibilityResume()
typeKeystroke('a')
expect(calls).toEqual(['sendInput'])
})
})
})
}
@@ -11,7 +11,6 @@ import { registerPtyConnectionHibernationActivityTests } from '../input/pty-conn
import { registerPtyConnectionHiddenSleepingResumeTests } from '../lifecycle/pty-connection-hidden-sleeping-resume.spec'
import { registerPtyConnectionSessionLivenessTests } from '../lifecycle/pty-connection-session-liveness.spec'
import { registerPtyConnectionOwnerErrorRetryTests } from '../reattach/pty-connection-owner-error-retry.spec'
import { registerPtyConnectionTerminalInputSessionListingTests } from '../input/pty-connection-terminal-input-session-listing.spec'
import { registerPtyConnectionSleepingResumeBannerTests } from '../spawn/pty-connection-sleeping-resume-banner.spec'
// Main's answer to the window's layout commands, as a switch-on build sends them.
@@ -42,6 +41,5 @@ describe('pty-connection-hidden-sleeping-resume', registerPtyConnectionHiddenSle
describe('pty-connection-session-liveness', () => {
registerPtyConnectionSessionLivenessTests()
registerPtyConnectionOwnerErrorRetryTests()
registerPtyConnectionTerminalInputSessionListingTests()
})
describe('pty-connection-sleeping-resume-banner', registerPtyConnectionSleepingResumeBannerTests)
@@ -6,7 +6,6 @@ import { resumeSleepingAgentSessionsForWorktree } from './resume-sleeping-agent-
const initialAppStoreState = useAppStore.getState()
const LEAF_ID = '33333333-3333-4333-8333-333333333333'
const OTHER_LEAF_ID = '44444444-4444-4444-8444-444444444444'
afterEach(() => {
vi.unstubAllGlobals()
@@ -73,31 +72,4 @@ describe('waking panes slept by a manual workspace sleep', () => {
expect(state.tabsByWorktree['wt-1']).toHaveLength(1)
expect(state.sleepingAgentSessionsByPaneKey[record.paneKey]).toBe(record)
})
// Inactive slept tabs are unowned; classifying their records active would spawn duplicates and strand originals as bare shells.
it('keeps a slept done record on a non-active tab for in-place cold restore', () => {
const record = makeRecord({ state: 'done' })
useAppStore.setState({
activeWorktreeId: 'wt-1',
activeTabType: 'terminal',
activeTabId: 'tab-2',
activeTabIdByWorktree: { 'wt-1': 'tab-2' },
tabsByWorktree: {
'wt-1': [makeTerminalTab('tab-1', 'wt-1'), makeTerminalTab('tab-2', 'wt-1')]
},
terminalLayoutsByTabId: {
'tab-1': makeLayout(LEAF_ID),
'tab-2': makeLayout(OTHER_LEAF_ID, 'pty-2')
},
ptyIdsByTabId: {},
sleepingAgentSessionsByPaneKey: { [record.paneKey]: record }
} as never)
const launched = resumeSleepingAgentSessionsForWorktree('wt-1')
const state = useAppStore.getState()
expect(launched).toBe(0)
expect(state.tabsByWorktree['wt-1']).toHaveLength(2)
expect(state.sleepingAgentSessionsByPaneKey[record.paneKey]).toBe(record)
})
})