test: remove 129 low-value cases and 21 whole suites (#41210)

* test: remove 83 low-value cases and ten whole suites

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

---------

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-11 11:03:08 -08:00
committed by GitHub
co-authored by OrcaWin
parent 9a10464bec
commit d5f6fe17bf
53 changed files with 23 additions and 2236 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,
@@ -7237,7 +7236,6 @@
"tests/e2e/structured-chat-tab-lifetime.unit.test.ts": 5616,
"tests/e2e/sustained-agent-typing-load-scripts.unit.test.ts": 2169,
"tests/e2e/task-page-linear-refresh-authority.unit.test.ts": 5548,
"tests/e2e/terminal-binding-crash-hydration.unit.test.ts": 1769,
"tests/e2e/terminal-foreground-confirmation.unit.test.ts": 644,
"tests/e2e/terminal-perf-presentation.unit.test.ts": 60,
"tests/e2e/worktree-status-warning.unit.test.ts": 2331,
@@ -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,11 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createBridgeInitFrame } from './bridge-init-frame'
import {
BRIDGE_PROTOCOL_VERSION,
BRIDGE_RPC_ENVELOPE_GRANT,
readBridgeClientMessage,
readBridgeHostMessage
} from './bridge-envelope'
import { BRIDGE_RPC_ENVELOPE_GRANT, readBridgeClientMessage } from './bridge-envelope'
import {
BridgeRpcEnvelopeInvalidError,
BridgeRpcEnvelopeUngrantedError
@@ -24,10 +18,6 @@ function grantedPage() {
return page
}
function frameKey(json: string): string {
return json.replace(/"id":"[^"]+"/, '"id":"_"')
}
beforeEach(() => {
vi.useFakeTimers()
})
@@ -37,25 +27,6 @@ afterEach(() => {
})
describe('bridge rpc envelope: page side', () => {
it('posts the same bytes as before when there is no envelope or an empty one', () => {
const page = grantedPage()
void page.client.sendRequest('worktree.ps', { a: 1 }, { timeoutMs: 50 })
void page.client.sendRequest('worktree.ps', { a: 1 }, { timeoutMs: 50, envelope: {} })
page.client.subscribe('terminal.subscribe', { terminal: 't' }, () => undefined)
page.client.subscribe('terminal.subscribe', { terminal: 't' }, () => undefined, {
envelope: {}
})
const [, request, emptyRequest, subscribe, emptySubscribe] = page.sent.map(frameKey)
expect(request).toBe(
'{"v":1,"type":"request","id":"_","method":"worktree.ps","params":{"a":1},"options":{"timeoutMs":50}}'
)
expect(emptyRequest).toBe(request)
expect(subscribe).toBe(
'{"v":1,"type":"subscribe","id":"_","method":"terminal.subscribe","params":{"terminal":"t"}}'
)
expect(emptySubscribe).toBe(subscribe)
})
it('posts no options when the only option was the envelope, and keeps an empty bag', () => {
const page = grantedPage()
void page.client.sendRequest('worktree.ps', { a: 1 }, { envelope: {} })
@@ -69,18 +40,6 @@ describe('bridge rpc envelope: page side', () => {
expect(emptyBag).toMatchObject({ options: {} })
})
it('carries a granted envelope beside params, out of options', () => {
const page = grantedPage()
void page.client.sendRequest('worktree.ps', undefined, { timeoutMs: 50, envelope: ENVELOPE })
page.client.subscribe('terminal.subscribe', { terminal: 't' }, () => undefined, {
envelope: ENVELOPE
})
const [, request, subscribe] = page.frames()
expect(request).toMatchObject({ options: { timeoutMs: 50 }, envelope: ENVELOPE })
expect(request).not.toHaveProperty('options.envelope')
expect(subscribe).toMatchObject({ type: 'subscribe', envelope: ENVELOPE })
})
it('refuses an envelope the shell did not grant, and posts nothing', async () => {
const page = createPageClient()
page.start()
@@ -177,46 +136,3 @@ describe('bridge rpc envelope: shell side', () => {
}
})
})
describe('bridge rpc envelope: mixed versions', () => {
it('the current page reader accepts an unknown grant name in init', () => {
const init = createBridgeInitFrame({
sessionId: 's',
buildId: 'b',
connection: INIT.connection,
route: { pathname: '/h/a' },
pageRoutes: [],
granted: [BRIDGE_RPC_ENVELOPE_GRANT, 'someFutureGrant'],
host: { id: 'a', name: 'A', endpoint: 'ws://a', lastConnected: 0 },
storage: {}
})
const read = readBridgeHostMessage(JSON.stringify(init))
expect(read.ok && read.message.type === 'init' && read.message.grants.native).toEqual([
BRIDGE_RPC_ENVELOPE_GRANT,
'someFutureGrant'
])
})
it('a shell drops a frame key it does not declare and still serves the frame', () => {
// The rule an older shell applies to `envelope`: unknown keys are stripped, never refused.
const frame = {
v: BRIDGE_PROTOCOL_VERSION,
type: 'request',
id: 'a'.repeat(22),
method: 'm',
params: {},
laterField: { executionHost: 'runtime:a' }
}
const read = readBridgeClientMessage(JSON.stringify(frame))
expect(read).toEqual({
ok: true,
message: {
v: BRIDGE_PROTOCOL_VERSION,
type: 'request',
id: 'a'.repeat(22),
method: 'm',
params: {}
}
})
})
})
@@ -1,53 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
createOrcaBridgePageTransport,
readOrcaBridgePageChannel,
type OrcaBridgePageChannel
} from './orca-bridge-page-channel'
function installChannel(channel: unknown): void {
Object.defineProperty(globalThis, 'orcaBridge', { value: channel, configurable: true })
}
function createChannel(): OrcaBridgePageChannel {
return { postMessage: vi.fn(), onmessage: null }
}
afterEach(() => {
Reflect.deleteProperty(globalThis, 'orcaBridge')
})
describe('the page channel the shell installs', () => {
it('is absent in a browser, which is a page the bundle still has to open', () => {
expect(readOrcaBridgePageChannel()).toBeNull()
})
it('refuses a global of another shape rather than posting into it', () => {
installChannel({ postMessage: 'not a function', onmessage: null })
expect(readOrcaBridgePageChannel()).toBeNull()
})
it('reads the installed object itself, so the page posts through the real sink', () => {
const channel = createChannel()
installChannel(channel)
expect(readOrcaBridgePageChannel()).toBe(channel)
})
})
describe('the page channel as a client transport', () => {
it('posts what the client sends', () => {
const channel = createChannel()
createOrcaBridgePageTransport(channel).send('{"v":1}')
expect(channel.postMessage).toHaveBeenCalledWith('{"v":1}')
})
it('hands the client the frame off the event, and gives the slot back', () => {
const channel = createChannel()
const handler = vi.fn()
const release = createOrcaBridgePageTransport(channel).onMessage(handler)
channel.onmessage?.({ data: '{"v":1,"type":"init"}' })
expect(handler).toHaveBeenCalledWith('{"v":1,"type":"init"}')
release()
expect(channel.onmessage).toBeNull()
})
})
@@ -10,10 +10,6 @@ function Throws(): ReactElement {
throw FAILURE
}
function Renders(): ReactElement {
return createElement('div', null, 'a worktree list')
}
function boundary(child: () => ReactElement, onFault: (error: unknown) => void): ReactElement {
return createElement(PageFaultBoundary, { onFault }, createElement(child))
}
@@ -30,26 +26,6 @@ afterEach(() => {
})
describe('the page fault boundary', () => {
it('reports a throw from the tree it wraps and leaves nothing on the page', async () => {
const faults: unknown[] = []
const rendered: { tree: ReactTestRenderer | null } = { tree: null }
await act(async () => {
rendered.tree = create(boundary(Throws, (error) => faults.push(error)))
})
expect(faults).toEqual([FAILURE])
expect(rendered.tree?.toJSON()).toBeNull()
})
it('stays out of the way of a tree that renders', async () => {
const faults: unknown[] = []
const rendered: { tree: ReactTestRenderer | null } = { tree: null }
await act(async () => {
rendered.tree = create(boundary(Renders, (error) => faults.push(error)))
})
expect(faults).toEqual([])
expect(rendered.tree?.toJSON()).not.toBeNull()
})
it('reports once, because a faulted page never renders the tree that threw again', async () => {
const faults: unknown[] = []
const render = (): ReactElement => boundary(Throws, (error) => faults.push(error))
@@ -1,36 +0,0 @@
import { describe, expect, it } from 'vitest'
import { cancelledShellNavigationTarget } from './cancelled-navigation-target'
describe('cancelledShellNavigationTarget', () => {
it('opens the three schemes the page may already ask for', () => {
expect(cancelledShellNavigationTarget('https://example.com/a')).toBe('https://example.com/a')
expect(cancelledShellNavigationTarget('http://example.com/a')).toBe('http://example.com/a')
expect(cancelledShellNavigationTarget('mailto:someone@example.com')).toBe(
'mailto:someone@example.com'
)
})
it('opens the normalized href, not the string the artifact spelled', () => {
// The WHATWG parser strips tab, LF and CR from anywhere, so this is not the URL it looks like.
expect(cancelledShellNavigationTarget('ht\ntps://example.com/a')).toBe('https://example.com/a')
expect(cancelledShellNavigationTarget('https://example.com')).toBe('https://example.com/')
})
it('opens nothing for a scheme the grant does not cover', () => {
expect(cancelledShellNavigationTarget('javascript:alert(1)')).toBeNull()
expect(cancelledShellNavigationTarget('data:text/html,<b>x')).toBeNull()
expect(cancelledShellNavigationTarget('file:///etc/passwd')).toBeNull()
expect(cancelledShellNavigationTarget('orca-mobile-web://sess/')).toBeNull()
})
it('opens nothing for a relative target, which is a route rather than a link out', () => {
expect(cancelledShellNavigationTarget('/h/abc')).toBeNull()
expect(cancelledShellNavigationTarget('')).toBeNull()
})
it('opens nothing for a payload that is not a string', () => {
expect(cancelledShellNavigationTarget(undefined)).toBeNull()
expect(cancelledShellNavigationTarget(null)).toBeNull()
expect(cancelledShellNavigationTarget(42)).toBeNull()
})
})
@@ -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())
})
})
@@ -1,45 +0,0 @@
import { describe, expect, it } from 'vitest'
import { bridgeDiagnosticLine, frameWithoutHostLine } from './shell-bridge-log-lines'
describe('shell bridge log lines', () => {
it('skips routine bridge kinds and names the specific failure for the rest', () => {
expect(
bridgeDiagnosticLine({
kind: 'terminal-backlog',
id: 't',
coalescedFrames: 0,
deliveredFrames: 0,
peakPendingBytes: 0,
ended: null
})
).toBeNull()
expect(
bridgeDiagnosticLine({ kind: 'notify-refused', name: 'fault', why: 'ungranted' })
).toEqual({
level: 'warn',
code: 'web-shell-bridge',
message: 'Web shell bridge: notify-refused',
detail: 'ungranted'
})
const gone = new Error('view gone')
gone.name = 'BridgeViewGoneError'
expect(bridgeDiagnosticLine({ kind: 'post-failed', error: gone })?.detail).toBe(
'error=BridgeViewGoneError'
)
expect(bridgeDiagnosticLine({ kind: 'post-failed', error: 'nope' })?.detail).toBe(
'error=string'
)
expect(
bridgeDiagnosticLine({ kind: 'route-refused', issue: 'Invalid path /Users/bob/wt' })?.detail
).toBe('issue=Invalid path [path]')
})
it('says which half a frame with no bridge host was waiting on', () => {
expect(frameWithoutHostLine({ clientReady: false, snapshotReady: true })).toEqual({
level: 'warn',
code: 'web-shell-page',
message: 'Web shell: page frame with no bridge host',
detail: 'client=null snapshot=ok'
})
})
})
@@ -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()
}
@@ -26,21 +26,6 @@ function row(
}
describe('buildAgentRowLineageTree', () => {
it('groups children under their parent and leaves roots flat', () => {
const rows = [row('a'), row('b', 'a'), row('c', 'a'), row('d')]
const { rootRows, childrenByParentPaneKey } = buildAgentRowLineageTree(rows)
expect(rootRows.map((r) => r.paneKey)).toEqual(['a', 'd'])
expect(childrenByParentPaneKey.get('a')?.map((r) => r.paneKey)).toEqual(['b', 'c'])
})
it('treats a dangling parent pointer as a root', () => {
const rows = [row('a', 'missing-parent'), row('b')]
const { rootRows } = buildAgentRowLineageTree(rows)
expect(rootRows.map((r) => r.paneKey).sort()).toEqual(['a', 'b'])
})
it('keeps all rows visible when the parent links form a cycle', () => {
const rows = [row('a', 'b'), row('b', 'a')]
const { rootRows, childrenByParentPaneKey } = buildAgentRowLineageTree(rows)
@@ -48,11 +33,6 @@ describe('buildAgentRowLineageTree', () => {
expect(rootRows.map((r) => r.paneKey).sort()).toEqual(['a', 'b'])
expect(childrenByParentPaneKey.size).toBe(0)
})
it('ignores a self-referential parent', () => {
const { rootRows } = buildAgentRowLineageTree([row('a', 'a')])
expect(rootRows.map((r) => r.paneKey)).toEqual(['a'])
})
})
describe('flattenAgentRowLineage', () => {
@@ -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'
])
})
})
@@ -19,7 +19,6 @@ vi.mock('@react-native-async-storage/async-storage', () => ({
}
}))
import { isLastVisitedWorktreeRow } from './host-list-highlight'
import {
readLastVisitedWorktreeOnHost,
subscribeLastVisitedWorktree,
@@ -34,12 +33,6 @@ import {
const stored = () => storage.values.get(LAST_VISITED_WORKTREE_STORAGE_KEY) ?? null
describe('readLastVisitedWorktreeOnHost', () => {
it('reads nothing for a host this phone never opened a workspace on', () => {
expect(readLastVisitedWorktreeOnHost(null, 'host-1')).toBeNull()
const raw = withLastVisitedWorktree(null, { hostId: 'host-2', worktreeId: 'repo::/w/a' })
expect(readLastVisitedWorktreeOnHost(raw, 'host-1')).toBeNull()
})
it('remembers each host’s own visit, whichever host was visited last', () => {
let raw = withLastVisitedWorktree(null, { hostId: 'host-1', worktreeId: 'repo::/w/a' })
raw = withLastVisitedWorktree(raw, {
@@ -84,28 +77,6 @@ describe('readLastVisitedWorktreeOnHost', () => {
})
})
describe('isLastVisitedWorktreeRow', () => {
it('matches a desktop row (local or SSH) by id, and a server row by its server too', () => {
const visit = { worktreeId: 'repo::/w/a' }
expect(isLastVisitedWorktreeRow({ worktreeId: 'repo::/w/a', hostId: 'local' }, visit)).toBe(
true
)
expect(isLastVisitedWorktreeRow({ worktreeId: 'repo::/w/a', hostId: 'ssh:gpu' }, visit)).toBe(
true
)
expect(
isLastVisitedWorktreeRow({ worktreeId: 'repo::/w/a', hostId: 'runtime:env-1' }, visit)
).toBe(false)
const serverVisit = { worktreeId: 'repo::/w/a', executionHost: 'runtime:env-1' as const }
expect(
isLastVisitedWorktreeRow({ worktreeId: 'repo::/w/a', hostId: 'runtime:env-1' }, serverVisit)
).toBe(true)
expect(isLastVisitedWorktreeRow({ worktreeId: 'repo::/w/a', hostId: 'local' }, null)).toBe(
false
)
})
})
describe('writeLastVisitedWorktree', () => {
it('tells listeners at once and stores the visit beside other hosts’ visits', async () => {
storage.values.clear()
@@ -6,34 +6,14 @@ import {
} from './last-visited-worktree-repo'
describe('last visited worktree repo', () => {
it('extracts the repo id for the current host', () => {
const raw = JSON.stringify({ hostId: 'host-1', worktreeId: 'repo-2::/tmp/worktree' })
expect(readLastVisitedWorktreeRepoId(raw, 'host-1')).toBe('repo-2')
})
it('ignores records for another host', () => {
const raw = JSON.stringify({ hostId: 'host-2', worktreeId: 'repo-2::/tmp/worktree' })
expect(readLastVisitedWorktreeRepoId(raw, 'host-1')).toBeNull()
})
it('ignores malformed stored values', () => {
expect(readLastVisitedWorktreeRepoId('{', 'host-1')).toBeNull()
expect(readLastVisitedWorktreeRepoId(JSON.stringify({ hostId: 'host-1' }), 'host-1')).toBeNull()
})
})
describe('readLastVisitedWorktreeRecord', () => {
it('reads a well-formed record', () => {
const raw = JSON.stringify({ hostId: 'host-1', worktreeId: 'repo-2::/tmp/worktree' })
expect(readLastVisitedWorktreeRecord(raw)).toEqual({
hostId: 'host-1',
worktreeId: 'repo-2::/tmp/worktree'
})
})
it('reads absent, truncated, and wrong-shaped payloads as no history', () => {
expect(readLastVisitedWorktreeRecord(null)).toBeNull()
expect(readLastVisitedWorktreeRecord('')).toBeNull()
@@ -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' })
@@ -21,20 +21,8 @@ describe('areStructurallyEqual', () => {
expect(areStructurallyEqual({ a: 1 }, { b: 1 })).toBe(false)
})
it('compares functions by identity', () => {
const press = () => {}
expect(areStructurallyEqual({ press }, { press })).toBe(true)
expect(areStructurallyEqual({ press }, { press: () => {} })).toBe(false)
})
it('does not equate an array with an object of the same entries', () => {
expect(areStructurallyEqual(['a'], { 0: 'a' })).toBe(false)
expect(areStructurallyEqual([], {})).toBe(false)
})
it('compares primitives with Object.is', () => {
expect(areStructurallyEqual(Number.NaN, Number.NaN)).toBe(true)
expect(areStructurallyEqual(null, undefined)).toBe(false)
expect(areStructurallyEqual(0, '0')).toBe(false)
})
})
@@ -1,10 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { Worktree } from './workspace-list-types'
import {
buildWorkspaceDetailLinks,
buildWorkspaceOrigin,
workspaceNotes
} from './workspace-details-model'
import { buildWorkspaceDetailLinks } from './workspace-details-model'
function row(overrides: Partial<Worktree> = {}): Worktree {
return {
@@ -41,31 +37,6 @@ describe('buildWorkspaceDetailLinks', () => {
expect(links[3]).toMatchObject({ title: 'Bug', url: 'https://x/3' })
})
it('reads the singular fields of a host that predates linkedItems', () => {
const links = buildWorkspaceDetailLinks(
row({ linkedIssue: 4, linkedGitLabMR: 9, linkedGitLabIssue: 2, linkedLinearIssue: 'ENG-1' })
)
expect(links.map((link) => `${link.provider} ${link.label}`)).toEqual([
'gitlab MR !9',
'github Issue #4',
'gitlab Issue #2',
'linear ENG-1'
])
})
it('lists a reference once when the attachments and a singular field both name it', () => {
const links = buildWorkspaceDetailLinks(
row({
linkedItems: [{ provider: 'github', type: 'issue', number: 4, title: 'Bug' }],
linkedIssue: 4
})
)
expect(links).toHaveLength(1)
expect(links[0]).toMatchObject({ label: 'Issue #4', title: 'Bug' })
})
it("carries the row's PR state, title, link and checks onto its entry", () => {
const [pr, other] = buildWorkspaceDetailLinks(
row({
@@ -151,62 +122,4 @@ describe('buildWorkspaceDetailLinks', () => {
)
expect(pr).toMatchObject({ label: 'PR #3', url: undefined })
})
it('names a GitLab review an MR', () => {
expect(buildWorkspaceDetailLinks(row({ linkedGitLabMR: 5 }))[0]).toMatchObject({
label: 'MR !5',
number: 5
})
})
it('drops attachments this build cannot place and never opens a non-web link', () => {
const linkedItems = JSON.parse(
JSON.stringify([
'garbage',
{ provider: 'sourceforge', type: 'issue', number: 1 },
{ provider: 'github', type: 'issue', number: 0 },
{ provider: 'github', type: 'issue', number: 8, url: 'javascript:alert(1)' }
])
)
const links = buildWorkspaceDetailLinks(row({ linkedItems }))
expect(links).toEqual([])
})
it('keeps two same-numbered issues from different repos apart, as the desktop does', () => {
const links = buildWorkspaceDetailLinks(
row({
linkedItems: [
{
provider: 'github',
type: 'issue',
number: 4,
url: 'https://github.com/a/one/issues/4'
},
{ provider: 'github', type: 'issue', number: 4, url: 'https://github.com/a/two/issues/4' }
]
})
)
expect(links.map((link) => link.url)).toEqual([
'https://github.com/a/one/issues/4',
'https://github.com/a/two/issues/4'
])
})
})
describe('workspace origin', () => {
it('names the automation the host names, and says only that one made it on an older host', () => {
expect(
buildWorkspaceOrigin(row({ automationCreated: true, automationName: ' Nightly deps ' }))
).toEqual({ kind: 'automation', name: 'Nightly deps' })
expect(buildWorkspaceOrigin(row({ automationCreated: true }))).toEqual({ kind: 'automation' })
expect(buildWorkspaceOrigin(row({ cliCreated: true }))).toEqual({ kind: 'cli' })
expect(buildWorkspaceOrigin(row())).toBeNull()
})
})
it('treats blank notes as none', () => {
expect(workspaceNotes({ comment: ' \n ' })).toBeNull()
expect(workspaceNotes({ comment: ' Check iPad ' })).toBe('Check iPad')
})
@@ -1,7 +1,6 @@
import { NO_WORKSPACE_ROW_FILTERS } from '../../../src/shared/workspace-view/workspace-row-filters'
import { describe, expect, it } from 'vitest'
import { buildFilterRepos } from './workspace-filter-repos'
import { filterWorktrees, type Worktree } from './workspace-list-sections'
import type { Worktree } from './workspace-list-sections'
function row(worktreeId: string, repoId: string, hostId: Worktree['hostId']): Worktree {
return {
@@ -59,14 +58,4 @@ describe('the repo filter', () => {
expect(repos.map((repo) => repo.id)).toEqual(['local-orca', 'm4-orca'])
})
it('filters by the picked repo id, leaving the same-named repo on another host out', () => {
const rows = [row('a', 'local-orca', 'local'), row('b', 'm4-orca', 'runtime:m4air')]
expect(
filterWorktrees(rows, { ...NO_WORKSPACE_ROW_FILTERS, filterRepoIds: ['m4-orca'] }, '').map(
(w) => w.worktreeId
)
).toEqual(['b'])
})
})
@@ -88,42 +88,9 @@ describe('Project grouping on the phone', () => {
{ key: 'repo:local-assets', label: 'design-assets' }
])
})
it('drops a served setup whose host id this build cannot read, keeping the rest', () => {
const verdict = projectSectionsRead.interpret({
id: 'sections',
ok: true,
result: {
catalog: {
...PROJECT_SECTION_PARITY_SERVED,
setups: [
{ ...PROJECT_SECTION_PARITY_SERVED.setups[0], hostId: 'nonsense' },
...PROJECT_SECTION_PARITY_SERVED.setups.slice(1)
]
}
}
})
expect(verdict.accepted && verdict.value?.setups).toHaveLength(
PROJECT_SECTION_PARITY_SERVED.setups.length - 1
)
})
})
describe('readServedProjectSections', () => {
it('reads a served catalog, and a desktop with no published window as none', () => {
expect(
readServedProjectSections({
id: 'sections',
ok: true,
result: { catalog: PROJECT_SECTION_PARITY_SERVED }
})
).toMatchObject({ kind: 'answered', value: { repos: expect.any(Array) } })
expect(
readServedProjectSections({ id: 'sections', ok: true, result: { catalog: null } })
).toEqual({ kind: 'answered', value: null })
})
it.each(['forbidden', 'method_not_found'])(
'reads an older desktop that answers %s as serving none',
(code) => {
@@ -1,207 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { Repo } from '../../../src/shared/repo-types'
import {
filterWorkspaceRows,
type WorkspaceRowFactReader,
type WorkspaceRowFilters
} from '../../../src/shared/workspace-view/workspace-row-filters'
import {
getWorkspaceRowKindFacts,
isAutomationGeneratedWorkspace,
isCliCreatedWorkspace,
isDefaultBranchWorkspace,
isDetachedHeadWorkspace
} from '../../../src/shared/worktree/workspace-kinds'
import type { Worktree as DesktopWorktree } from '../../../src/shared/worktree/types'
import { filterWorktrees, type Worktree } from './workspace-list-sections'
// Compare all filter combinations with desktop facts mirrored here because mobile cannot resolve renderer aliases.
const repos: Repo[] = [
{ id: 'git', path: '/git', displayName: 'Git', badgeColor: '#000', addedAt: 0 },
{
id: 'folder-repo',
path: '/f',
displayName: 'Folder',
badgeColor: '#000',
addedAt: 0,
kind: 'folder'
}
]
const repoMap = new Map(repos.map((repo) => [repo.id, repo]))
type Fixture = DesktopWorktree & { sleeping: boolean; otherClient: boolean; folderWorkspace?: true }
function fixture(id: string, fields: Partial<Fixture> = {}): Fixture {
return {
id,
repoId: 'git',
path: `/w/${id}`,
head: 'abc1234',
branch: `refs/heads/${id}`,
isBare: false,
isMainWorktree: false,
displayName: id,
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 0,
sleeping: true,
otherClient: false,
...fields
}
}
const FIXTURES: Fixture[] = [
fixture('main', { isMainWorktree: true, branch: 'refs/heads/main' }),
fixture('main-detached', { isMainWorktree: true, branch: '' }),
fixture('provisioned', { isMainWorktree: true, ephemeralVmCheckoutMode: 'provisioned-root' }),
fixture('awake', { sleeping: false }),
fixture('automation', {
sleeping: false,
automationProvenance: {
kind: 'created-by-automation',
automationId: 'a',
automationNameSnapshot: 'Nightly',
automationRunId: 'r',
automationRunTitleSnapshot: 'Run',
createdAt: 0,
executionTargetType: 'local',
executionTargetId: 'local',
projectId: 'p',
hostId: 'local'
}
}),
fixture('cli', { sleeping: false, cliProvenance: { kind: 'created-by-cli', createdAt: 0 } }),
fixture('detached', { branch: '', sleeping: false }),
fixture('other-client', { otherClient: true, sleeping: false }),
fixture('archived', { isArchived: true, sleeping: false }),
fixture('folder-root', { repoId: 'folder-repo', isMainWorktree: true, branch: '', head: '' }),
fixture('folder:lane', {
repoId: 'folder-workspace:group',
branch: '',
head: '',
folderWorkspace: true
})
]
const DESKTOP_FACTS: WorkspaceRowFactReader<Fixture> = {
isArchived: (w) => w.isArchived,
isFolderWorkspace: (w) => w.folderWorkspace === true,
repoId: (w) => w.repoId,
hostId: () => 'local',
isOtherClient: (w) => w.otherClient,
isDefaultBranch: (w) => isDefaultBranchWorkspace(w, repoMap.get(w.repoId)),
isAutomationCreated: isAutomationGeneratedWorkspace,
isCliCreated: isCliCreatedWorkspace,
isDetachedHead: isDetachedHeadWorkspace,
isMainWorktree: (w) => w.isMainWorktree,
isSleeping: (w) => w.sleeping
}
/** The row the phone receives for this workspace from a current host. */
function served(w: Fixture): Worktree {
return {
workspaceKind: w.folderWorkspace ? 'folder-workspace' : 'git',
worktreeId: w.id,
repoId: w.repoId,
hostId: 'local',
repo: repoMap.get(w.repoId)?.displayName ?? w.repoId,
branch: w.branch,
displayName: w.displayName,
path: w.path,
isArchived: w.isArchived,
isMainWorktree: w.isMainWorktree,
hasHostSidebarActivity: !w.sleeping,
...(w.otherClient ? { desktopOtherClient: true } : {}),
...getWorkspaceRowKindFacts(w, repoMap.get(w.repoId)),
liveTerminalCount: 0,
hasAttachedPty: false,
unread: false,
isPinned: false,
linkedPR: null
}
}
function* everyFilterCombination(): Generator<Omit<WorkspaceRowFilters, 'visibleHostIds'>> {
const bools = [false, true]
for (const hideSleepingWorkspaces of bools) {
for (const alwaysShowDefaultBranchWorkspace of [undefined, true, false]) {
for (const hideDefaultBranchWorkspace of bools) {
for (const hideAutomationGeneratedWorkspaces of bools) {
for (const hideCliCreatedWorkspaces of bools) {
for (const hideDetachedHeadWorkspaces of bools) {
for (const hideWorkspacesFromOtherDevices of bools) {
for (const filterRepoIds of [[], ['git'], ['folder-repo']]) {
yield {
hideSleepingWorkspaces,
alwaysShowDefaultBranchWorkspace,
hideDefaultBranchWorkspace,
hideAutomationGeneratedWorkspaces,
hideCliCreatedWorkspaces,
hideDetachedHeadWorkspaces,
hideWorkspacesFromOtherDevices,
filterRepoIds
}
}
}
}
}
}
}
}
}
}
describe('the phone shows what the desktop sidebar shows', () => {
it('under every Workspace options filter combination, folder projects included', () => {
const phoneRows = FIXTURES.map(served)
let combinations = 0
for (const filters of everyFilterCombination()) {
combinations += 1
const desktop = filterWorkspaceRows(
FIXTURES,
{ ...filters, visibleHostIds: null },
DESKTOP_FACTS
)
const phone = filterWorktrees(phoneRows, { ...filters, visibleHostIds: null }, '')
expect(
phone.map((w) => w.worktreeId),
JSON.stringify(filters)
).toEqual(desktop.map((w) => w.id))
}
expect(combinations).toBe(2 * 3 * 2 ** 5 * 3)
})
it('keeps every row an older host sends, whatever kind filter is on', () => {
const legacy: Worktree[] = FIXTURES.filter((w) => !w.isArchived && !w.otherClient).map((w) => ({
worktreeId: w.id,
repoId: w.repoId,
repo: w.repoId,
branch: w.branch,
displayName: w.displayName,
path: w.path,
liveTerminalCount: 1,
hasAttachedPty: false,
unread: false,
isPinned: false,
linkedPR: null
}))
const kindFiltersOn = {
hideSleepingWorkspaces: false,
hideDefaultBranchWorkspace: false,
hideAutomationGeneratedWorkspaces: true,
hideCliCreatedWorkspaces: true,
hideDetachedHeadWorkspaces: true,
hideWorkspacesFromOtherDevices: true,
filterRepoIds: [],
visibleHostIds: null
}
expect(filterWorktrees(legacy, kindFiltersOn, '')).toHaveLength(legacy.length)
})
})
@@ -1,6 +1,5 @@
import { NO_WORKSPACE_ROW_FILTERS } from '../../../src/shared/workspace-view/workspace-row-filters'
import { describe, expect, it } from 'vitest'
import { DEFAULT_WORKSPACE_STATUSES } from '../../../src/shared/workspace-statuses'
import {
applyDesktopViewSettings,
buildWorkspaceViewSettingsUpdate,
@@ -24,10 +23,6 @@ describe('the other-client filter on an older desktop', () => {
expect(rowFiltersForView(base).hideWorkspacesFromOtherDevices).toBe(false)
})
it('does not hide marked rows before the first ui.get says which kind of desktop it is', () => {
expect(rowFiltersForView(INITIAL_MOBILE_VIEW).hideWorkspacesFromOtherDevices).toBe(false)
})
it('learns from each ui.get whether the desktop shares the filter', () => {
expect(applyDesktopViewSettings(base, {}).sharesOtherClientFilter).toBe(false)
expect(
@@ -52,16 +47,6 @@ describe('applyDesktopViewSettings', () => {
})
})
it('keeps current values when the desktop payload is empty', () => {
expect(applyDesktopViewSettings(base, {})).toEqual({ ...base, sharesOtherClientFilter: false })
})
it('keeps renderable workspace statuses when desktop sends an empty catalog', () => {
const next = applyDesktopViewSettings(base, { workspaceStatuses: [] })
expect(next.workspaceStatuses).toBe(DEFAULT_WORKSPACE_STATUSES)
})
it("falls back to the desktop's legacy host scope when no host list is saved", () => {
const scoped = applyDesktopViewSettings(base, {
visibleWorkspaceHostIds: null,
@@ -74,14 +59,6 @@ describe('applyDesktopViewSettings', () => {
).toBeNull()
})
it("reads the desktop's shown hosts into the host filter, and null as every host", () => {
const scoped = applyDesktopViewSettings(base, { visibleWorkspaceHostIds: ['local'] })
expect(scoped.filters.visibleHostIds).toEqual(['local'])
expect(
applyDesktopViewSettings(scoped, { visibleWorkspaceHostIds: null }).filters.visibleHostIds
).toBeNull()
})
it('ignores an unrecognized groupBy rather than blanking the mode', () => {
const newerGroup: WorkspaceViewSettings = JSON.parse('{"groupBy":"mystery"}')
const next = applyDesktopViewSettings(base, newerGroup)
@@ -118,18 +95,6 @@ describe('buildWorkspaceViewSettingsUpdate', () => {
).toEqual({ collapsedGroups: ['g1'] })
})
it('writes each filter under its desktop name, the host scope included', () => {
const filters = {
hideAutomationGeneratedWorkspaces: true,
visibleHostIds: ['local' as const]
}
expect(buildWorkspaceViewSettingsUpdate({ filters }, apply(filters))).toEqual({
hideAutomationGeneratedWorkspaces: true,
visibleWorkspaceHostIds: ['local'],
workspaceHostScope: 'local'
})
})
it('leaves the legacy host scope alone for a several-host list', () => {
const filters = { visibleHostIds: ['local' as const, 'ssh:box' as const] }
expect(buildWorkspaceViewSettingsUpdate({ filters }, apply(filters))).toEqual({
@@ -155,20 +120,6 @@ describe('buildWorkspaceViewSettingsUpdate', () => {
workspaceHostScope: 'all'
})
})
it('never invents alwaysShowDefaultBranchWorkspace for edits that leave it alone (#8873)', () => {
expect(
'alwaysShowDefaultBranchWorkspace' in
buildWorkspaceViewSettingsUpdate(
{ filters: { hideSleepingWorkspaces: true } },
apply({ hideSleepingWorkspaces: true })
)
).toBe(false)
})
it('returns an empty update for an empty patch', () => {
expect(buildWorkspaceViewSettingsUpdate({}, base)).toEqual({})
})
})
describe('card view settings', () => {
@@ -208,12 +159,4 @@ describe('card view settings', () => {
)
).toEqual({ worktreeCardProperties: ['status'], _worktreeCardModeDefaulted: true })
})
it('keeps the card settings a ui.get does not carry', () => {
const current = { ...base, compactWorktreeCards: true, newCardStyle: true }
expect(applyDesktopViewSettings(current, { groupBy: 'none' })).toMatchObject({
compactWorktreeCards: true,
newCardStyle: true
})
})
})
@@ -1,13 +0,0 @@
import { describe, expect, it } from 'vitest'
import { headlessActivationNeedsHostRenderer } from './worktree-activation-result'
describe('headlessActivationNeedsHostRenderer', () => {
it('only reports the explicit sleeping-agent headless outcome', () => {
expect(headlessActivationNeedsHostRenderer({ sleepingAgentWake: 'unsupported-headless' })).toBe(
true
)
expect(headlessActivationNeedsHostRenderer({ sleepingAgentWake: 'not-applicable' })).toBe(false)
expect(headlessActivationNeedsHostRenderer({ sleepingAgentWake: 'requested' })).toBe(false)
expect(headlessActivationNeedsHostRenderer(null)).toBe(false)
})
})
@@ -1,53 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { z } from 'zod'
import { retiredWorktreeNamesSchema, worktreeCatalogSchema } from './worktree-catalog-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 catalog reads both arms of the host union', () => {
it('reads a full snapshot', () => {
const reply = { snapshotId: 'snapshot-1', worktrees: [{ worktreeId: 'w-1' }] }
expect(reads(worktreeCatalogSchema, reply).worktrees).toEqual([{ worktreeId: 'w-1' }])
})
it('reads an unchanged poll, which carries no rows at all', () => {
// Conditional unchanged replies contain no rows; requiring worktrees would reject valid polls.
const unchanged = reads(worktreeCatalogSchema, { unchanged: true, snapshotId: 's-1' })
expect(unchanged.unchanged).toBe(true)
expect(unchanged.worktrees).toBe(undefined)
})
it('leaves the rows opaque for the three screens that each project their own', () => {
const rows = [{ worktreeId: 'w-1', displayName: 'One' }, 'not-a-row']
expect(reads(worktreeCatalogSchema, { worktrees: rows }).worktrees).toEqual(rows)
})
it('names a reply that is not a catalog envelope', () => {
expect(refuses(worktreeCatalogSchema, null)).toBe(true)
expect(refuses(worktreeCatalogSchema, undefined)).toBe(true)
})
it('drops a worktrees that is not an array, as Array.isArray did', () => {
expect(reads(worktreeCatalogSchema, { worktrees: 'all' }).worktrees).toBe(undefined)
})
})
describe('the retired-name registry stays opaque', () => {
it('takes every shape readRetiredNameRegistryForRepo guards', () => {
expect(refuses(retiredWorktreeNamesSchema, null)).toBe(false)
expect(refuses(retiredWorktreeNamesSchema, undefined)).toBe(false)
expect(refuses(retiredWorktreeNamesSchema, { retiredNamesByRepo: { 'repo-1': ['a'] } })).toBe(
false
)
})
})
@@ -1,46 +0,0 @@
import { describe, expect, it } from 'vitest'
import { buildSshHostHealthById, getHostHealthBadgeLabel } from './worktree-host-health'
describe('buildSshHostHealthById', () => {
it('derives each SSH host health from its lifecycle, keyed by canonical host id', () => {
const health = buildSshHostHealthById([
{ id: 'up', connected: true, connectionStatus: 'connected' },
{ id: 'relay', connected: false, connectionStatus: 'deploying-relay' },
{ id: 'retry', connected: false, connectionStatus: 'reconnecting' },
{ id: 'down', connected: false, connectionStatus: 'disconnected' },
{ id: 'auth', connected: false, connectionStatus: 'auth-failed' },
{ id: 'never', connected: false },
{ id: 'ssh:canonical', connected: false, connectionStatus: 'connecting' }
])
expect(Object.fromEntries(health)).toEqual({
'ssh:up': 'available',
'ssh:relay': 'connecting',
'ssh:retry': 'connecting',
'ssh:down': 'disconnected',
'ssh:auth': 'error',
// Same verdict as the desktop sidebar for a target with no lifecycle state yet.
'ssh:never': 'disconnected',
'ssh:canonical': 'connecting'
})
})
it('reports nothing for a desktop that predates lifecycle fields or a status it cannot read', () => {
const health = buildSshHostHealthById([
{ id: 'old-desktop' },
{ id: 'future', connected: false, connectionStatus: 'hibernating' }
])
expect(health.size).toBe(0)
})
})
describe('getHostHealthBadgeLabel', () => {
it('uses the desktop sidebar words for unhealthy hosts only', () => {
expect(getHostHealthBadgeLabel('disconnected')).toBe('Disconnected')
expect(getHostHealthBadgeLabel('connecting')).toBe('Connecting')
expect(getHostHealthBadgeLabel('error')).toBe('Needs attention')
expect(getHostHealthBadgeLabel('blocked')).toBe('Update needed')
expect(getHostHealthBadgeLabel('available')).toBeUndefined()
expect(getHostHealthBadgeLabel('local')).toBeUndefined()
expect(getHostHealthBadgeLabel(undefined)).toBeUndefined()
})
})
@@ -37,18 +37,6 @@ describe('removeWorktreeRow', () => {
expect(removeWorktreeRow([local, remote], local)).toEqual([remote])
})
it('removes the matching row', () => {
const only = row('shared', 'ssh:a')
expect(removeWorktreeRow([only], only)).toEqual([])
})
})
describe('getWorktreeRowIdentity', () => {
it('uses the shared host-qualified identity format', () => {
expect(getWorktreeRowIdentity(row('shared', 'ssh:builder'))).toBe('ssh:builder|shared')
})
})
describe('host-qualified row display state', () => {
@@ -87,31 +75,6 @@ describe('host-qualified row display state', () => {
expect([...retained]).toEqual([])
})
it('indexes confirmed identities once instead of rescanning for every slept row', () => {
const rowCount = 64
let worktreeIdReads = 0
const confirmed = Array.from({ length: rowCount }, (_, index) => {
const worktree = row(`worktree-${index}`, `ssh:host-${index}`, { liveTerminalCount: 1 })
Object.defineProperty(worktree, 'worktreeId', {
configurable: true,
get: () => {
worktreeIdReads += 1
return `worktree-${index}`
}
})
return worktree
})
const previous = new Set(
Array.from({ length: rowCount }, (_, index) => {
const reversed = rowCount - index - 1
return `ssh:host-${reversed}|worktree-${reversed}`
})
)
expect(retainLiveSleptWorktreeIdentities(previous, confirmed)).toBe(previous)
expect(worktreeIdReads).toBe(rowCount)
})
it('applies active and slept overrides to the matching host row only', () => {
const local = row('shared', 'ssh:a')
const remote = row('shared', 'ssh:b')
@@ -1,226 +0,0 @@
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types'
import type { Worktree } from './workspace-list-sections'
import { areWorktreeListsEqual } from './worktree-list-snapshot'
function agent(overrides: Partial<RuntimeWorktreeAgentRow> = {}): RuntimeWorktreeAgentRow {
return {
paneKey: 'agent-1',
parentPaneKey: null,
state: 'working',
agentType: 'codex',
prompt: 'fix mobile lag',
taskTitle: null,
displayName: null,
lastAssistantMessage: null,
toolName: null,
toolInput: null,
interrupted: false,
stateStartedAt: 100,
updatedAt: 200,
...overrides
}
}
function done(
outcome: 'success' | 'failure',
stateStartedAt = 1
): NonNullable<RuntimeWorktreeAgentRow['mainAgent']> {
return { state: 'done', outcome, stateStartedAt }
}
function worktree(overrides: Partial<Worktree> = {}): Worktree {
const worktreePath = join('/tmp', 'orca', 'worktrees', 'manta')
return {
worktreeId: `repo-1::${worktreePath}`,
repoId: 'repo-1',
repo: 'orca',
branch: 'feature/mobile-lag',
displayName: 'manta',
workspaceStatus: 'in-progress',
path: worktreePath,
liveTerminalCount: 1,
hasAttachedPty: true,
unread: false,
lastOutputAt: 1234,
isPinned: false,
isActive: false,
linkedPR: null,
linkedIssue: null,
linkedLinearIssue: null,
linkedGitLabMR: null,
linkedGitLabIssue: null,
comment: '',
status: 'active',
agents: [],
...overrides
}
}
describe('areWorktreeListsEqual', () => {
it('treats cloned snapshots with the same visible fields as equal', () => {
const first = [worktree({ agents: [agent()] })]
const second = [worktree({ agents: [agent()] })]
expect(areWorktreeListsEqual(first, second)).toBe(true)
})
it('detects order and field changes that affect the host list', () => {
const first = [worktree({ worktreeId: 'a' }), worktree({ worktreeId: 'b' })]
const reordered = [worktree({ worktreeId: 'b' }), worktree({ worktreeId: 'a' })]
const renamed = [
worktree({ worktreeId: 'a', displayName: 'renamed' }),
worktree({ worktreeId: 'b' })
]
expect(areWorktreeListsEqual(first, reordered)).toBe(false)
expect(areWorktreeListsEqual(first, renamed)).toBe(false)
})
it('detects host visibility field changes', () => {
expect(areWorktreeListsEqual([worktree()], [worktree({ isArchived: true })])).toBe(false)
expect(areWorktreeListsEqual([worktree()], [worktree({ isMainWorktree: true })])).toBe(false)
expect(areWorktreeListsEqual([worktree()], [worktree({ hasHostSidebarActivity: true })])).toBe(
false
)
})
it('detects workspace status changes', () => {
expect(
areWorktreeListsEqual(
[worktree({ workspaceStatus: 'in-progress' })],
[worktree({ workspaceStatus: 'in-review' })]
)
).toBe(false)
})
it('detects manual order changes', () => {
expect(
areWorktreeListsEqual(
[worktree({ manualOrder: 10, sortOrder: 1 })],
[worktree({ manualOrder: 20, sortOrder: 1 })]
)
).toBe(false)
})
it('detects desktop ordering field changes', () => {
expect(
areWorktreeListsEqual(
[worktree({ lastActivityAt: 10, createdAt: 1 })],
[worktree({ lastActivityAt: 20, createdAt: 1 })]
)
).toBe(false)
expect(
areWorktreeListsEqual(
[worktree({ lastActivityAt: 10, createdAt: 1 })],
[worktree({ lastActivityAt: 10, createdAt: 2 })]
)
).toBe(false)
})
it('detects resume host and terminal platform changes', () => {
expect(areWorktreeListsEqual([worktree()], [worktree({ hostId: 'ssh:box' })])).toBe(false)
expect(
areWorktreeListsEqual(
[worktree({ terminalPlatform: 'win32' })],
[worktree({ terminalPlatform: 'linux' })]
)
).toBe(false)
})
it('detects lineage changes', () => {
const base = worktree({ worktreeId: 'child', parentWorktreeId: 'parent-a' })
const changedParent = worktree({ worktreeId: 'child', parentWorktreeId: 'parent-b' })
const changedChildren = worktree({
worktreeId: 'child',
parentWorktreeId: 'parent-a',
childWorktreeIds: ['grandchild']
})
expect(areWorktreeListsEqual([base], [changedParent])).toBe(false)
expect(areWorktreeListsEqual([base], [changedChildren])).toBe(false)
})
it('detects lineage instance changes', () => {
const base = worktree({
worktreeId: 'child',
parentWorktreeId: 'parent',
worktreeInstanceId: 'child-instance',
lineageWorktreeInstanceId: 'child-instance',
parentWorktreeInstanceId: 'parent-instance'
})
const changedParentInstance = worktree({
worktreeId: 'child',
parentWorktreeId: 'parent',
worktreeInstanceId: 'child-instance',
lineageWorktreeInstanceId: 'child-instance',
parentWorktreeInstanceId: 'new-parent-instance'
})
expect(areWorktreeListsEqual([base], [changedParentInstance])).toBe(false)
})
it('detects agent status changes', () => {
const first = [worktree({ agents: [agent({ state: 'working' })] })]
const second = [worktree({ agents: [agent({ state: 'waiting' })] })]
expect(areWorktreeListsEqual(first, second)).toBe(false)
})
it('detects a verdict change that leaves the interrupted flag as it was', () => {
const first = [worktree({ agents: [agent({ state: 'done', mainAgent: done('success') })] })]
const second = [worktree({ agents: [agent({ state: 'done', mainAgent: done('failure') })] })]
expect(areWorktreeListsEqual(first, second)).toBe(false)
})
it('detects a main agent failing while its subagents keep the row working', () => {
const first = [worktree({ agents: [agent({ state: 'working' })] })]
const second = [worktree({ agents: [agent({ state: 'working', mainAgent: done('failure') })] })]
expect(areWorktreeListsEqual(first, second)).toBe(false)
})
it('detects the main agent clock moving, which dates a failure', () => {
const at = (stateStartedAt: number) => [
worktree({
agents: [agent({ state: 'working', mainAgent: done('failure', stateStartedAt) })]
})
]
expect(areWorktreeListsEqual(at(1), at(2))).toBe(false)
expect(areWorktreeListsEqual(at(1), at(1))).toBe(true)
})
// Stopping may change without advancing any row clock.
it("detects the host's Stopping coming and going with nothing else moved", () => {
const stopping = (value: boolean) => [
worktree({
agents: [
agent({
mainAgent: { state: 'working', stateStartedAt: 1, ...(value ? { stopping: true } : {}) }
})
]
})
]
expect(areWorktreeListsEqual(stopping(false), stopping(true))).toBe(false)
expect(areWorktreeListsEqual(stopping(true), stopping(false))).toBe(false)
expect(areWorktreeListsEqual(stopping(true), stopping(true))).toBe(true)
})
it('detects monitoring mode changes within working', () => {
const first = [worktree({ agents: [agent({ state: 'working' })] })]
const second = [worktree({ agents: [agent({ state: 'working', workingMode: 'monitoring' })] })]
expect(areWorktreeListsEqual(first, second)).toBe(false)
})
it('detects workspace monitoring mode changes within working', () => {
const first = [worktree({ status: 'working' })]
const second = [worktree({ status: 'working', workingMode: 'monitoring' })]
expect(areWorktreeListsEqual(first, second)).toBe(false)
})
})
@@ -1,89 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
DEFAULT_WORKTREE_CARD_PROPERTIES,
getWorktreeCardDetails
} from '../../../src/shared/worktree/card-properties'
import type { Worktree } from './workspace-list-types'
import { getWorktreeMetaGlyphPresence } from './worktree-meta-glyph-presence'
const ALL = getWorktreeCardDetails(DEFAULT_WORKTREE_CARD_PROPERTIES, {
compactWorktreeCards: false,
newCardStyle: false
})
const row: Worktree = {
worktreeId: 'w',
repoId: 'r',
repo: 'orca',
path: '/w',
branch: 'b',
displayName: 'w',
liveTerminalCount: 0,
hasAttachedPty: false,
unread: false,
isPinned: false,
linkedPR: null
}
describe('getWorktreeMetaGlyphPresence', () => {
it('shows each fact the row carries and its property turns on', () => {
expect(
getWorktreeMetaGlyphPresence(
{
...row,
comment: ' note ',
automationCreated: true,
cliCreated: true,
linkedIssue: 3,
linkedLinearIssue: 'ENG-1',
linkedGitLabMR: 4,
linkedItems: [{ provider: 'jira', type: 'issue', number: 1 }]
},
ALL
)
).toEqual({
notes: true,
automation: true,
cli: true,
issue: true,
jira: true,
linear: true,
gitLabMR: true
})
})
it('shows none for a bare row, or when the properties are off', () => {
const none = getWorktreeCardDetails([], { compactWorktreeCards: false, newCardStyle: false })
expect(Object.values(getWorktreeMetaGlyphPresence(row, ALL)).some(Boolean)).toBe(false)
expect(
Object.values(
getWorktreeMetaGlyphPresence(
{
...row,
comment: 'note',
automationCreated: true,
cliCreated: true,
linkedIssue: 3,
linkedLinearIssue: 'ENG-1',
linkedGitLabMR: 4,
linkedItems: [{ provider: 'jira', type: 'issue', number: 1 }]
},
none
)
).some(Boolean)
).toBe(false)
})
it('finds only a linked Jira issue, and reads an unchecked list without throwing', () => {
const jiraFor = (linkedItems: unknown) =>
getWorktreeMetaGlyphPresence(
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: rows reach the phone unchecked; this feeds the malformed shapes a host could send.
{ ...row, linkedItems } as Worktree,
ALL
).jira
expect(jiraFor([{ provider: 'linear', type: 'issue', number: 1 }])).toBe(false)
expect(jiraFor([{ provider: 'jira', type: 'pr', number: 1 }])).toBe(false)
expect(jiraFor('jira')).toBe(false)
expect(jiraFor([null, 3])).toBe(false)
})
})
@@ -1,5 +1,4 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { AGENT_SESSION_MAX_NEW_OPERATION_AGE_MS } from '../../../../../shared/agent-session/agent-session-host-authority'
import { openTestJournalHostDatabase } from '../../../agent-session-journal/store-lifecycle/journal-host-database-test-support'
import {
createQueuedMessageTestRig,
@@ -9,8 +8,6 @@ import {
import { HOST_TEST_NOW as NOW } from './structured-agent-session-host-test-data'
const CALLER_SCOPE = { kind: 'caller', callerKey: CALLER.callerKey } as const
void (NOW - AGENT_SESSION_MAX_NEW_OPERATION_AGE_MS - 60_000)
void (NOW + 6 * 60_000)
let rig: QueuedMessageTestRig
let serial = 0
@@ -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)
})
})
@@ -5,7 +5,6 @@ import { afterEach, describe, expect, it } from 'vitest'
import type { SkillInstallReceiptV1 } from '../transaction-state/skill-install-provenance'
import { nativeSkillInstallFilesystem } from '../filesystem/skill-install-filesystem'
import { reconcileSkillProviderPlacement } from './skill-placement-reconciliation'
import { isRemovableSkillPlacement } from './skill-removable-placement'
const roots: string[] = []
@@ -75,19 +74,4 @@ describe('independent skill placement copy drift', () => {
})
expect(await readFile(join(value.placementPath, 'local.md'), 'utf8')).toBe('local change')
})
it('refuses to remove a locally modified copy', async () => {
const value = await fixture()
await writeFile(join(value.placementPath, 'local.md'), 'local change')
await expect(
isRemovableSkillPlacement({
placement: value.receipt.placements[0]!,
receipt: value.receipt,
allowedProviderRoots: [value.providerRoot],
filesystem: nativeSkillInstallFilesystem
})
).resolves.toBe(false)
expect(await readFile(join(value.placementPath, 'local.md'), 'utf8')).toBe('local change')
})
})
@@ -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,4 +1,3 @@
// Exercise draft preservation, self-write echoes, autosave suspension and baseline settlement through the headless controller.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, requestEditorFileSave } from './editor-autosave'
import { attachEditorAutosaveController } from './editor-autosave-controller'
@@ -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)
})
@@ -76,18 +76,4 @@ describe('buildSourceControlManualReviewUrl', () => {
})
).toBe('https://github.com/stablyai/orca/compare/main...feature/pushed-name?expand=1')
})
it('opens the Azure DevOps PR form for a vs-ssh.visualstudio.com remote', () => {
expect(
buildSourceControlManualReviewUrl({
baseRef: 'refs/remotes/origin/main',
branchName: 'feature',
repoRemoteName: 'origin',
repoRemoteUrl: 'myorg@vs-ssh.visualstudio.com:v3/myorg/Proj/Repo',
upstreamName: 'origin/feature'
})
).toBe(
'https://myorg.visualstudio.com/Proj/_git/Repo/pullrequestcreate?sourceRef=refs%2Fheads%2Ffeature&targetRef=refs%2Fheads%2Fmain'
)
})
})
@@ -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)
})
})
@@ -1,101 +0,0 @@
import '../../src/renderer/src/store/terminals/terminal-hydration-store.test-bootstrap'
import { describe, expect, it, vi } from 'vitest'
import { applyPtyBinding } from '../../src/main/persistence/loading-store/terminal-bindings/pty-binding-session-update'
import { getDefaultWorkspaceSession } from '../../src/shared/constants'
import { folderWorkspaceKey } from '../../src/shared/workspace-scope'
import type { WorkspaceSessionState } from '../../src/shared/workspace-session/workspace-session-state-types'
import { reconcileHydratedWorkspaceTabModels } from '../../src/renderer/src/app-shell/reconcile-hydrated-workspace-tab-models'
import { createTestStore } from '../../src/renderer/src/store/testing/app-store-test-fixture'
import { makeTab } from '../../src/renderer/src/store/terminals/terminal-tab.test-fixture'
import { makeWorktree } from '../../src/renderer/src/store/slices/worktrees/worktree.test-fixture'
import { TEST_REPO } from '../../src/renderer/src/store/repos/repo.test-fixture'
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
vi.mock('@/runtime/sync-runtime-graph/graph-sync-scheduler', () => ({
scheduleRuntimeGraphSync: vi.fn()
}))
vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', () => ({
registerEagerPtyBuffer: vi.fn(),
ensurePtyDispatcher: vi.fn()
}))
const TAB_ID = 'crash-survivor'
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
const INCARNATION_ID = '22222222-2222-4222-8222-222222222222'
const FOLDER_KEY = folderWorkspaceKey('crash-folder')
describe.each(['repo1::/repo1', FOLDER_KEY])('binding crash hydration for %s', (worktreeId) => {
it.each([false, true])(
'restores the acknowledged terminal before a renderer snapshot (existing row: %s)',
async (existingRow) => {
const ptyId = `${worktreeId}@@surviving-pty`
const persisted: WorkspaceSessionState = {
...getDefaultWorkspaceSession(),
activeWorktreeId: worktreeId,
activeTabId: TAB_ID,
activeTabIdByWorktree: { [worktreeId]: TAB_ID },
activeWorktreeIdsOnShutdown: [],
unifiedTabs: {},
tabGroups: {},
tabGroupLayouts: {},
...(existingRow
? { tabsByWorktree: { [worktreeId]: [makeTab({ id: TAB_ID, worktreeId, ptyId: null })] } }
: {})
}
applyPtyBinding(
{ worktreeId, tabId: TAB_ID, leafId: LEAF_ID, ptyId, incarnationId: INCARNATION_ID },
persisted,
worktreeId,
`${TAB_ID}:${LEAF_ID}`
)
// A crash leaves only the binding transaction; no renderer snapshot can fill its gaps.
const restoredSession = structuredClone(persisted)
const store = createTestStore()
store.setState({
repos: [TEST_REPO],
worktreesByRepo: {
repo1: [makeWorktree({ id: 'repo1::/repo1', repoId: 'repo1', path: '/repo1' })]
}
})
const options = { additionalValidWorkspaceKeys: [FOLDER_KEY] }
store.getState().hydrateWorkspaceSession(restoredSession, options)
store.getState().hydrateTabsSession(restoredSession, options)
reconcileHydratedWorkspaceTabModels(
restoredSession,
store.getState().reconcileWorktreeTabModels
)
const beforeReconnect = store.getState()
expect(beforeReconnect.tabsByWorktree[worktreeId]?.map((tab) => tab.id)).toEqual([TAB_ID])
expect(beforeReconnect.pendingReconnectPtyIdByTabId[TAB_ID]).toBe(ptyId)
expect(beforeReconnect.unifiedTabsByWorktree[worktreeId]).toEqual([
expect.objectContaining({ id: TAB_ID, entityId: TAB_ID, contentType: 'terminal' })
])
expect(beforeReconnect.groupsByWorktree[worktreeId]).toEqual([
expect.objectContaining({ activeTabId: TAB_ID, tabOrder: [TAB_ID] })
])
expect(beforeReconnect.layoutByWorktree[worktreeId]).toEqual({
type: 'leaf',
groupId: beforeReconnect.groupsByWorktree[worktreeId][0].id
})
expect(beforeReconnect.terminalLayoutsByTabId[TAB_ID]).toMatchObject({
root: { type: 'leaf', leafId: LEAF_ID },
activeLeafId: LEAF_ID,
ptyIdsByLeafId: { [LEAF_ID]: ptyId }
})
expect(restoredSession.terminalPtyIncarnationsByPaneKey?.[`${TAB_ID}:${LEAF_ID}`]).toBe(
INCARNATION_ID
)
await store.getState().reconnectPersistedTerminals()
expect(store.getState().workspaceSessionReady).toBe(true)
expect(store.getState().activeTabId).toBe(TAB_ID)
expect(store.getState().tabsByWorktree[worktreeId]).toEqual([
expect.objectContaining({ id: TAB_ID, ptyId })
])
expect(store.getState().ptyIdsByTabId[TAB_ID]).toEqual([ptyId])
}
)
})