test: remove low-value renderer and budget suites

This commit is contained in:
OrcaWin
2026-11-09 01:09:39 -08:00
parent c3910146ee
commit bbac4a2859
21 changed files with 9 additions and 1121 deletions
File diff suppressed because one or more lines are too long
@@ -1,82 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type {
TerminalLayoutSnapshot,
TerminalTab
} from '../../../shared/workspace-layout/terminal-tab-types'
import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types'
import { normalizeWorkspaceSessionPaneIdentities } from './workspace-pane-normalization'
const { registerPaneKeyAliasMock } = vi.hoisted(() => ({
registerPaneKeyAliasMock: vi.fn()
}))
vi.mock('../../agent-hooks/server/agent-hook-server', () => ({
agentHookServer: {
registerPaneKeyAlias: registerPaneKeyAliasMock
}
}))
function terminalTab(id: string, worktreeId: string, ptyId: string | null): TerminalTab {
return {
id,
worktreeId,
ptyId,
title: 'Terminal',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
}
function workspaceSession(
tabsByWorktree: Record<string, TerminalTab[]>,
terminalLayoutsByTabId: Record<string, TerminalLayoutSnapshot>
): WorkspaceSessionState {
return {
activeRepoId: null,
activeWorktreeId: null,
activeTabId: null,
tabsByWorktree,
terminalLayoutsByTabId
}
}
function legacyLayout(): TerminalLayoutSnapshot {
return {
root: { type: 'leaf', leafId: 'pane:1' },
activeLeafId: 'pane:1',
expandedLeafId: null
}
}
describe('workspace pane normalization tab index', () => {
beforeEach(() => {
registerPaneKeyAliasMock.mockReset()
})
it('keeps the first tab when duplicate ids occur across worktrees', () => {
const result = normalizeWorkspaceSessionPaneIdentities(
workspaceSession(
{
first: [terminalTab('duplicate-tab', 'first', 'first-pty')],
second: [terminalTab('duplicate-tab', 'second', 'second-pty')]
},
{ 'duplicate-tab': legacyLayout() }
)
)
expect(result.legacyPaneKeyAliasEntries).not.toHaveLength(0)
expect(result.legacyPaneKeyAliasEntries.every((entry) => entry.ptyId === 'first-pty')).toBe(
true
)
})
it('keeps missing tab ids without inventing persisted aliases', () => {
const result = normalizeWorkspaceSessionPaneIdentities(
workspaceSession({}, { 'missing-tab': legacyLayout() })
)
expect(result.legacyPaneKeyAliasEntries).toEqual([])
})
})
@@ -59,20 +59,6 @@ describe('RuntimeFileReads', () => {
).rejects.toThrow('file_too_large')
})
it('keeps local previews above the remote cap available without a request budget', async () => {
const size = RUNTIME_PREVIEWABLE_BINARY_MAX_BYTES + 1
const dir = await previewFixture(size)
const { commands } = createFileReads({ path: dir })
resolveAuthorizedPathMock.mockImplementation(async (p: string) => p)
await expect(commands.readFileExplorerPreview('id:wt-1', 'logo.png')).resolves.toEqual({
content: Buffer.alloc(size, 0x61).toString('base64'),
isBinary: true,
isImage: true,
mimeType: 'image/png'
})
})
// Phones read images a chat names by host path; only image files on this machine qualify.
it('reads a chat image outside every project root but never another file type', async () => {
const dir = await previewFixture()
@@ -1,27 +0,0 @@
import { afterEach, expect, it, vi } from 'vitest'
import { CrewReadModel } from './crew-read-model'
import { fixture } from './crew-read-model.test-fixture'
afterEach(() => vi.useRealTimers())
it.each([
['x'.repeat(1024), 'x'.repeat(1024)],
['x'.repeat(1025), `${'x'.repeat(1021)}…`],
[`${'x'.repeat(1020)}🙂tail`, `${'x'.repeat(1020)}…`],
[`${'x'.repeat(1017)}🙂tail`, `${'x'.repeat(1017)}🙂…`]
])('preserves the existing UTF-8 preview boundary for %#', (body, expected) => {
const { db, deps, run, assign } = fixture()
const dispatch = assign('term_worker')
db.createQuestion({
runId: run.id,
dispatchId: dispatch.id,
askerHandle: 'term_worker',
question: body
})
const row = new CrewReadModel(() => deps, db.crewChanges.subscribe).read('term_coord').sections
.managing[0]
expect(row.latest?.preview).toBe(expected)
expect(row.pendingQuestion?.preview).toBe(expected)
})
@@ -1,103 +0,0 @@
import { join } from 'node:path'
import { afterEach, beforeEach, expect, it } from 'vitest'
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../../shared/agent-session/journal/agent-session-journal-types'
import type { AgentSessionSubscribeEvent } from '../../../../../../shared/agent-session/agent-session-wire'
import { codexProviderHandle } from '../../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
import { MOBILE_BRIDGE_MAX_FRAME_BYTES } from '../../../../../../shared/mobile-bridge-frame-bytes'
import { AgentSessionSubscribers } from '../../../../../native-chat/agent-session-wire/publication/subscribers/structured-agent-session-subscribers'
import type { AgentSessionSubscribeInput } from '../../../../../native-chat/agent-session-wire/publication/subscribers/agent-session-subscribe-input'
import {
fixture,
journals
} from '../../../../../native-chat/agent-session-wire/publication/subscribers/testing/structured-agent-session-subscriber-contract-test-fixture'
import {
clearStructuredHostStub,
hostCalls,
installStructuredHostStub,
openStream
} from '../protocol/structured-agent-session-rpc.test-fixture'
import {
SESSION,
STRUCTURED_MOBILE_CLIENT
} from '../protocol/structured-agent-session-rpc-client.test-fixture'
beforeEach(installStructuredHostStub)
afterEach(clearStructuredHostStub)
it.each(['snapshot', 'reset', 'batch'] as const)(
'keeps near-limit %s delivery readable when receipt names do not fit',
async (type) => {
const journal = await journals.open({
identity: {
sessionId: SESSION,
workspaceId: 'workspace-1',
hostId: 'local',
agent: 'codex',
providerHandle: codexProviderHandle('thread-1')
},
stateDirectory: join(fixture.root, 'receipts')
})
const start = journal.cursor()
for (let ordinal = 1; ordinal <= 200; ordinal++) {
await journal.appendItem(
{ provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal },
{
kind: 'approval',
title: `Approval ${ordinal}`,
detail: 'x'.repeat(2500),
options: [{ id: 'yes', label: 'Allow' }],
resolution: {
state: 'resolved',
selectedOptionId: 'yes',
resolvedBy: 'desktop-renderer',
resolvedAt: 10
}
},
{ fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
)
}
const base: AgentSessionSubscribeEvent[] = []
const subscribers = new AgentSessionSubscribers()
hostCalls.subscribe.mockImplementation((input: AgentSessionSubscribeInput) =>
subscribers.open({
...input,
journal,
fence: 7,
emit: (event) => {
base.push(event)
input.emit(event)
}
})
)
const cursor = type === 'reset' ? { epoch: 'old', sequence: 0 } : start
const responses = await openStream(
'agentSession.subscribe',
{ sessionId: SESSION, ...(type === 'snapshot' ? {} : { cursor }) },
{ ...STRUCTURED_MOBILE_CLIENT, clientId: 'reader-phone' },
{ readMachineName: () => '界'.repeat(255) }
)
expect(base[0]?.type).toBe(type)
expect(Buffer.byteLength(JSON.stringify(base[0]), 'utf8')).toBeGreaterThan(540 * 1024)
expect(responses).toHaveLength(base.length)
for (const [index, response] of responses.entries()) {
expect(response).toMatchObject({ ok: true, result: base[index] })
if (!response.ok) {
throw new Error('expected receipt delivery')
}
const frame = {
v: 1,
type: 'event',
id: 'receipt-stream',
seq: 2 ** 31,
payload: response.result
}
expect(Buffer.byteLength(JSON.stringify(frame), 'utf8')).toBeLessThanOrEqual(
MOBILE_BRIDGE_MAX_FRAME_BYTES
)
}
expect(journal.snapshot().items).toHaveLength(200)
expect(JSON.stringify(journal.snapshot().items)).not.toContain('resolvedByDevice')
}
)
@@ -1,59 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload'
import type { DashboardCard, DashboardSnapshot } from '../../../../shared/dashboard-snapshot'
import { patchDashboardSnapshotFromAgentStatus } from './dashboard-agent-status-patch'
function card(overrides: Partial<DashboardCard> = {}): DashboardCard {
return {
paneKey: 'tab-1:leaf-1',
ptyId: 'pty-1',
agentType: 'codex',
bucket: 'working',
dotState: 'working',
task: 'old task',
repoId: 'repo-1',
worktreeId: 'worktree-1',
tabId: 'tab-1',
leafId: 'leaf-1',
repoName: 'Repo',
worktreeName: 'Worktree',
startedAt: 100,
finishedAt: null,
stateChangedAt: 100,
statusUpdatedAt: 150,
unseen: false,
...overrides
}
}
function event(overrides: Partial<AgentStatusIpcPayload> = {}): AgentStatusIpcPayload {
return {
paneKey: 'tab-1:leaf-1',
state: 'blocked',
prompt: 'Need a decision',
connectionId: null,
receivedAt: 300,
stateStartedAt: 250,
interactivePrompt: '{"question":"Continue?"}',
...overrides
}
}
function snapshot(cards: DashboardCard[] = [card()]): DashboardSnapshot {
return { generatedAt: 200, cards }
}
describe('patchDashboardSnapshotFromAgentStatus', () => {
it('ignores stale, wrong-workspace, and session-only events', () => {
const original = snapshot()
expect(
patchDashboardSnapshotFromAgentStatus(original, event({ receivedAt: 150 })).snapshot
).toBe(original)
expect(
patchDashboardSnapshotFromAgentStatus(original, event({ worktreeId: 'other' })).snapshot
).toBe(original)
expect(
patchDashboardSnapshotFromAgentStatus(original, event({ providerSessionOnly: true })).snapshot
).toBe(original)
})
})
@@ -1,17 +0,0 @@
import { describe, expect, it } from 'vitest'
import { dictationStartFailureKind } from './dictation-toasts'
const startError = (detail: string): string =>
`Error: Error invoking remote method 'speech:startDictation': Error: ${detail}`
describe('dictationStartFailureKind', () => {
it.each([
[startError('Model not ready: not-downloaded'), 'settings'],
[startError('The speech engine stopped unexpectedly. Try again.'), 'settings'],
['NotAllowedError: Permission denied', null],
[startError('Microphone access not granted. Open System Settings.'), null],
['Error: dictation_model_busy', null]
])('%s → %s', (message, kind) => {
expect(dictationStartFailureKind(message)).toBe(kind)
})
})
@@ -1,61 +0,0 @@
// Clean tabs must not retain disk-text drafts that could later overwrite a shared model.
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { __clearSelfWriteRegistryForTests } from './editor-self-write-registry'
import { createEditorStore } from '../autosave/editor-autosave-controller-test-fixture'
import { stampCleanTabDiskBaseline } from './editor-clean-tab-disk-baseline'
import { getDiskBaselineSignature } from '../../../../../shared/file-write/disk-baseline-signature'
import { GUARDED_PATH, stubGuardedDisk } from '../save/queue/editor-save-guarded-disk-fixture'
const storeRef = vi.hoisted((): { current: ReturnType<typeof createEditorStore> | null } => ({
current: null
}))
vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { error: vi.fn() }) }))
vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined }))
vi.mock('@/store/index', () => ({ useAppStore: { getState: () => storeRef.current?.getState() } }))
function openCleanTab(disk: string, language = 'typescript') {
const store = createEditorStore()
storeRef.current = store
store.getState().openFile({
filePath: GUARDED_PATH,
relativePath: 'file.ts',
worktreeId: 'wt-1',
language,
mode: 'edit'
})
const id = store.getState().openFiles[0].id
store.getState().setLastKnownDiskSignature(id, getDiskBaselineSignature(disk))
return { store, id }
}
beforeEach(() => {
vi.useFakeTimers()
stubGuardedDisk({ [GUARDED_PATH]: 'disk' })
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
__clearSelfWriteRegistryForTests()
})
it("a reload keeps a clean Markdown tab's trailing-whitespace draft, but not one over older text", () => {
const { store, id } = openCleanTab('# notes', 'markdown')
store.getState().setEditorDraft(id, '# notes\n\n')
stampCleanTabDiskBaseline(id, { content: '# notes', isBinary: false })
expect(store.getState().editorDrafts[id]).toBe('# notes\n\n')
stampCleanTabDiskBaseline(id, { content: '# newer notes', isBinary: false })
expect(store.getState().editorDrafts[id]).toBeUndefined()
})
it('a reload drops a whitespace-only Markdown draft when disk moved, even by whitespace alone', () => {
const { store, id } = openCleanTab('# notes', 'markdown')
store.getState().setEditorDraft(id, '# notes\n\n')
// An outside write added a trailing newline; keeping the draft would undo it.
stampCleanTabDiskBaseline(id, { content: '# notes\n', isBinary: false })
expect(store.getState().editorDrafts[id]).toBeUndefined()
})
@@ -1,58 +0,0 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { imageClipboardPngDataUrl, imagePngLayout } from './image-png-export'
const PNG_BASE64 =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII='
describe('imagePngLayout', () => {
it('doubles small images for crisp text', () => {
expect(imagePngLayout({ width: 300, height: 100 })).toEqual({
width: 600,
height: 200,
pixelRatio: 2
})
})
it('scales down to stay inside the clipboard pixel budget and canvas side limit', () => {
const budget = imagePngLayout({ width: 4000, height: 4000 }, 1_000_000)
expect(budget!.width * budget!.height).toBeLessThanOrEqual(1_000_000)
const wide = imagePngLayout({ width: 40_000, height: 10 })
expect(wide!.width).toBeLessThanOrEqual(16384)
})
it('refuses an image with no size', () => {
expect(imagePngLayout({ width: 0, height: 10 })).toBeNull()
})
})
describe('imageClipboardPngDataUrl', () => {
afterEach(() => {
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
it('copies a raster PNG as its own bytes instead of a 2x render', async () => {
const bytes = Uint8Array.from(atob(PNG_BASE64), (character) => character.charCodeAt(0))
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response(new Blob([bytes], { type: 'image/png' })))
)
vi.stubGlobal(
'Image',
class {
src = ''
naturalWidth = 1
naturalHeight = 1
decode = async (): Promise<void> => undefined
}
)
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:decode')
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined)
await expect(
imageClipboardPngDataUrl('blob:image', { width: 1, height: 1 }, null)
).resolves.toBe(`data:image/png;base64,${PNG_BASE64}`)
})
})
@@ -1,57 +0,0 @@
// @vitest-environment happy-dom
import { act, renderHook } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import type { GitLabWorkItem } from '../../../../shared/gitlab-types'
import type { GitLabItemDialogState } from './use-gitlab-item-dialog-state'
import { useGitLabPrimaryActions } from './use-gitlab-primary-actions'
const mocks = vi.hoisted(() => ({
mergeMR: vi.fn(),
toastError: vi.fn()
}))
vi.mock('@/runtime/repository-gitlab/gitlab-owner-api', () => ({
gitLabApiFor: () => ({ mergeMR: mocks.mergeMR })
}))
vi.mock('sonner', () => ({ toast: { error: mocks.toastError, success: vi.fn() } }))
const item: GitLabWorkItem = {
id: 'mr:7',
type: 'mr',
number: 7,
title: 'MR 7',
state: 'opened',
url: 'https://gitlab.example.test/g/p/-/merge_requests/7',
labels: [],
updatedAt: '2026-11-01T00:00:00Z',
author: null,
repoId: 'repo-1'
}
describe('useGitLabPrimaryActions', () => {
it('rereads after a returned merge failure and keeps the error toast', async () => {
mocks.mergeMR.mockResolvedValue({ ok: false, error: 'Connection lost' })
const events: string[] = []
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: handleMerge reads only these dialog-state fields; the rest of the dialog state is unused here.
const state = {
claimDetailsOwner: () => () => true,
commentDraft: '',
mountedRef: { current: true },
setActionInFlight: (value: string | null) => events.push(`inFlight:${value}`),
setCommentDraftState: vi.fn(),
setCommentSubmitting: vi.fn()
} as unknown as GitLabItemDialogState
const { result } = renderHook(() =>
useGitLabPrimaryActions(item, 'mr:7', { repoPath: '/repo' }, state, () =>
events.push('reread')
)
)
await act(async () => result.current.handleMerge())
expect(mocks.toastError).toHaveBeenCalledWith('Connection lost')
expect(events).toEqual(['inFlight:merge', 'inFlight:null', 'reread'])
})
})
@@ -1,61 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { NativeChatMessage } from '../../../../../../../shared/native-chat/native-chat-types'
import { prepareNativeChatLiveMessages } from './native-chat-live-message-preparation'
import { createNativeChatMessageListProjection } from '../../../conversation/projection/native-chat-message-list-projection'
const row = (id: string, text: string, source: NativeChatMessage['source'] = 'transcript') => ({
id,
role: 'user' as const,
blocks: [{ type: 'text' as const, text }],
timestamp: 100,
source
})
const CONTEXT_ROWS: NativeChatMessage[] = [
row('b-envelope', '<command-name>/context</command-name>\n<command-args></command-args>'),
{
...row(
'a-stdout',
'<local-command-stdout> \u001b[1mContext Usage\u001b[22m</local-command-stdout>'
),
parentId: 'b-envelope'
}
]
function visibleText(agent: 'openclaude' | 'claude', messages: NativeChatMessage[]): string[] {
return createNativeChatMessageListProjection()(
prepareNativeChatLiveMessages(messages, agent)
).conversation.flatMap((message) =>
message.blocks.map((block) => (block.type === 'text' ? block.text : ''))
)
}
describe('prepareNativeChatLiveMessages command output', () => {
it("lists OpenClaude's /context report in the chat", () => {
expect(visibleText('openclaude', CONTEXT_ROWS)).toEqual(['Context Usage'])
// A live hook preview alongside the transcript takes the reassembly path.
expect(
visibleText('openclaude', [...CONTEXT_ROWS, row('hook', 'next prompt', 'hook')])
).toEqual(['Context Usage', 'next prompt'])
})
it('keeps a later /model reply hidden after a /context report', () => {
const modelRows = [
{ ...row('d-envelope', '<command-name>/model</command-name>'), timestamp: 300 },
{
...row('c-stdout', '<local-command-stdout>Set model to gpt-4o</local-command-stdout>'),
timestamp: 300,
parentId: 'd-envelope'
}
]
// Unsupported command envelopes surface as typed turns while their linked replies stay hidden.
expect(visibleText('openclaude', [...CONTEXT_ROWS, ...modelRows])).toEqual([
'Context Usage',
'/model'
])
})
it('keeps the reply row hidden for Claude', () => {
expect(visibleText('claude', CONTEXT_ROWS)).toEqual(['/context'])
})
})
@@ -1,58 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { JiraIssue, JiraSite } from '../../../../shared/jira/jira-types'
import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context'
import { bindJiraIssueSourceContext } from './use-jira-url-source'
import { resolveWorkItemSourceRow } from './work-item-source-selection'
const source: TaskSourceContext = {
kind: 'task-source',
provider: 'jira',
projectId: 'project',
hostId: 'ssh:box',
repoId: null,
providerIdentity: null,
accountLabel: null
}
const site: JiraSite = {
id: 'site',
siteUrl: 'https://company.atlassian.net',
email: 'account@example.com',
displayName: 'Account',
accountId: 'account'
}
const issue: JiraIssue = {
id: 'issue',
key: 'ENG-1',
title: 'Issue',
url: `${site.siteUrl}/browse/ENG-1`,
siteId: site.id,
project: { id: 'project', key: 'ENG', name: 'Engineering' },
issueType: { id: 'bug', name: 'Bug' },
status: { id: 'open', name: 'Open', categoryKey: 'new', categoryName: 'To do' },
labels: [],
updatedAt: '',
createdAt: ''
}
const contexts = { github: null, gitlab: null, linear: null, jira: source }
describe('shared work-item source resolution', () => {
it.each([{ siteId: 'another-account' }, { url: 'https://other.atlassian.net/browse/ENG-1' }])(
'rejects a pre-bound account that does not match the result: %j',
(overrides) => {
const bound = bindJiraIssueSourceContext(source, site, issue)
expect(
resolveWorkItemSourceRow(
{ kind: 'jira', value: 'jira', issue: { ...issue, ...overrides } },
{ ...contexts, jira: bound }
)
).toBeNull()
}
)
it('accepts the callback-bound account when no connection list is available', () => {
const bound = bindJiraIssueSourceContext(source, site, issue)
expect(
resolveWorkItemSourceRow({ kind: 'jira', value: 'jira', issue }, { ...contexts, jira: bound })
?.taskSourceContext
).toEqual(bound)
})
})
@@ -1,61 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { PtyListedSession as DaemonSession } from '../../../../shared/terminal/pty/lifecycle/pty-listed-session'
import { ResourceSessionInventoryCache } from './resource-session-inventory-cache'
function session(id: string, incarnationId?: string): DaemonSession {
return { id, incarnationId, cwd: '/workspace', title: id, agentOwnership: 'absent' as const }
}
function deferredListing() {
let resolve!: (sessions: DaemonSession[]) => void
let reject!: (error: Error) => void
const promise = new Promise<DaemonSession[]>((done, fail) => {
resolve = done
reject = fail
})
return { promise, resolve, reject }
}
describe('resource session inventory request-scoped exits', () => {
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())
it('associates loading notifications with the request they can invalidate', async () => {
const original = session('one', 'A')
const list = vi.fn().mockResolvedValue([original])
const cache = new ResourceSessionInventoryCache(list, true)
let exited = false
cache.subscribe(() => {
if (!exited && cache.getSnapshot().loading) {
exited = true
cache.exited({ code: 0, ...original, hostId: 'local' })
}
})
cache.setActive(true)
await vi.advanceTimersByTimeAsync(0)
expect(list).toHaveBeenCalledTimes(1)
expect(cache.getSnapshot().sessionInventory.count).toBe(0)
})
it('absorbs pending exit publications into an in-flight listing without resurrecting its incarnation', async () => {
const original = session('one', 'A')
const replacement = session('one', 'B')
const slow = deferredListing()
const list = vi.fn().mockResolvedValueOnce([original]).mockReturnValueOnce(slow.promise)
const cache = new ResourceSessionInventoryCache(list, true)
cache.setActive(true)
await vi.advanceTimersByTimeAsync(100)
void cache.refresh()
await vi.advanceTimersByTimeAsync(0)
cache.exited({ code: 0, ...original, hostId: 'local' })
slow.resolve([original, replacement])
await vi.advanceTimersByTimeAsync(0)
const settled = cache.getSnapshot().sessionInventory
expect(settled.sessions).toEqual([replacement])
await vi.advanceTimersByTimeAsync(50)
expect(cache.getSnapshot().sessionInventory).toBe(settled)
expect(vi.getTimerCount()).toBe(0)
})
})
@@ -1,58 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
bufferPreHandlerPtyData,
clearPreHandlerPtyState,
drainPreHandlerPtyData
} from '@/components/terminal-pane/pty-transport/delivery/pty-pre-handler-buffer'
import { waitForAgentDraftInputReady } from './agent-draft-readiness'
import type * as RemoteRuntimePtyIdModule from '../../../shared/remote-runtime/remote-runtime-pty-id'
const testState = vi.hoisted(() => ({
observer: null as ((data: string) => void) | null,
unsubscribe: vi.fn()
}))
vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-data-sidecar-subscriptions', () => ({
subscribeToPtyData: (_ptyId: string, observer: (data: string) => void) => {
testState.observer = observer
return testState.unsubscribe
}
}))
vi.mock('../../../shared/remote-runtime/remote-runtime-pty-id', async (importOriginal) => ({
...(await importOriginal<typeof RemoteRuntimePtyIdModule>()),
isRemoteRuntimePtyId: () => false
}))
const PTY_ID = 'pty-buffered-codex'
const CODEX_COMPOSER = '\x1b[?1049h\x1b[1m›\x1b[0m Implement {feature}'
const DECSET_BRACKETED_PASTE = '\x1b[?2004h'
describe('waitForAgentDraftInputReady', () => {
afterEach(() => {
clearPreHandlerPtyState(PTY_ID)
testState.observer = null
testState.unsubscribe.mockReset()
vi.unstubAllGlobals()
vi.useRealTimers()
})
it('observes buffered startup bytes without consuming the primary drain', async () => {
vi.useFakeTimers()
bufferPreHandlerPtyData(PTY_ID, CODEX_COMPOSER)
bufferPreHandlerPtyData(PTY_ID, DECSET_BRACKETED_PASTE)
const primary = vi.fn()
await expect(
waitForAgentDraftInputReady(PTY_ID, 20_000, 'codex-composer-prompt')
).resolves.toBe(true)
drainPreHandlerPtyData(PTY_ID, primary)
expect(testState.unsubscribe).toHaveBeenCalledOnce()
expect(primary.mock.calls).toEqual([
[CODEX_COMPOSER, undefined],
[DECSET_BRACKETED_PASTE, undefined]
])
expect(vi.getTimerCount()).toBe(0)
})
})
@@ -1,58 +0,0 @@
import { expect, it, vi } from 'vitest'
import { terminalOutputPrefersRenderRefresh } from './terminal-complex-script'
it.each(['\x1b[32mx\x1b[0m', '\x1b[38m'])(
'keeps parameter scanning linear for repeated simple SGR %j',
(sequence) => {
for (const repetitions of [1_000, 10_000]) {
const data = sequence.repeat(repetitions)
let examinedCharacters = 0
const indexOf = String.prototype.indexOf
const charCodeAt = String.prototype.charCodeAt
const indexOfSpy = vi.spyOn(String.prototype, 'indexOf').mockImplementation(function (
this: string,
search,
position = 0
) {
const result = indexOf.call(this, search, position)
if (String(this) === data) {
examinedCharacters +=
result < 0 ? this.length - position : result - position + search.length
}
return result
})
const charCodeAtSpy = vi.spyOn(String.prototype, 'charCodeAt').mockImplementation(function (
this: string,
position
) {
if (String(this) === data) {
examinedCharacters += 1
}
return charCodeAt.call(this, position)
})
let prefersRefresh: boolean
try {
prefersRefresh = terminalOutputPrefersRenderRefresh(data)
} finally {
indexOfSpy.mockRestore()
charCodeAtSpy.mockRestore()
}
expect(prefersRefresh).toBe(false)
expect(examinedCharacters).toBeLessThan(data.length * 12)
}
}
)
it.each([
['\x1b[38;2;1;2;44m', false],
['\x1b[38;2;1;2;3;41m', true],
['\x1b[38:5:1;44m', true],
['\x1b[38;5;41m', false],
['\x1b[38;41m', false],
['\x1b[0041m', true],
['\x1b[4:41m', false],
['\x1b[48m', true],
['\x1b[\x1b[41m', true]
])('classifies background SGR parameters in %j as %s', (data, expected) => {
expect(terminalOutputPrefersRenderRefresh(data)).toBe(expected)
})
@@ -1,23 +1,7 @@
import { describe, expect, it } from 'vitest'
import {
isNonFastForwardRemoteError,
resolveRemoteOperationErrorMessage
} from './source-control-remote-error'
import { resolveRemoteOperationErrorMessage } from './source-control-remote-error'
describe('source-control remote error formatting', () => {
it.each(['fatal', 'remote'])(
'redacts ANSI-bearing credentials in %s details from older remote hosts',
(prefix) => {
const error = new Error(
`git.push failed:\n${prefix}: Access denied to https://user:sec\x1b[1 qret@example.com/repo.git`
)
expect(resolveRemoteOperationErrorMessage(error, { isPush: true })).toBe(
'Push failed. Access denied to https://example.com/repo.git. Check your remote access and try again.'
)
}
)
it.each([
[{ isFetch: true }, 'Fetch failed. '],
[{ isFastForward: true }, 'Fast-forward failed. '],
@@ -31,29 +15,4 @@ describe('source-control remote error formatting', () => {
)
expect(error.message).toContain('user:sec\x1b[1 qret@')
})
it.each([
[{ publish: true }, 'Publish Branch'],
[{ isSync: true }, 'Sync'],
[{ isForcePush: true }, 'Force Push'],
[{ isPush: true }, 'Push']
])('sanitizes and classifies older-host submodule errors for %j', (options, operation) => {
const error = new Error(
"Unable to push sub\x1b[1 qmodule 'https://user:sec\x1b[1 qret@example.com/repo.git'\n" +
' ! [rejected] main -> main (fetch\x1b[1 q first)'
)
expect(resolveRemoteOperationErrorMessage(error, options)).toBe(
`${operation} failed. Submodule 'https://example.com/repo.git' has remote changes. Pull inside the submodule, then try again.`
)
expect(isNonFastForwardRemoteError(error)).toBe(true)
expect(
resolveRemoteOperationErrorMessage(
new Error("Unable to push submodule 'https://user:sec\x1b[1 qret@example.com/repo.git'"),
options
)
).toBe(
`${operation} failed. Submodule 'https://example.com/repo.git' could not be pushed. Resolve the submodule push error, then try again.`
)
})
})
@@ -1,61 +0,0 @@
import { expect, it } from 'vitest'
import type { Tab } from '../../../../shared/tab-types'
import { buildMobileSessionTabSnapshots } from './mobile-session-snapshots'
import { makeState } from './testing/sync-runtime-graph-test-harness'
function makeTab(overrides: Pick<Tab, 'id' | 'entityId' | 'contentType'>): Tab {
return {
groupId: 'group-1',
worktreeId: 'wt-1',
label: overrides.id,
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1,
...overrides
}
}
it('invalidates the production snapshot cache when the selected host chat lifetime changes', async () => {
const { setHostSessionTabIdMapping, clearHostSessionTabIdMappings } =
await import('../web-session-tabs-sync/tracking-mappings')
const chat = makeTab({ id: 'window-chat', entityId: 'chat-0001', contentType: 'agent-session' })
const state = makeState({
unifiedTabsByWorktree: { 'wt-1': [chat] },
groupsByWorktree: {
'wt-1': [
{
id: 'group-1',
worktreeId: 'wt-1',
activeTabId: chat.id,
tabOrder: [chat.id],
recentTabIds: [chat.id]
}
]
}
})
try {
const legacy = buildMobileSessionTabSnapshots(state)[0]
setHostSessionTabIdMapping(
{ environmentId: 'local', worktreeId: 'wt-1', tabId: chat.id },
'agent-chat-tab-v1-a'
)
const issued = buildMobileSessionTabSnapshots(state)[0]
expect(issued).not.toBe(legacy)
expect(issued?.tabGroups?.[0]).toMatchObject({
tabOrder: ['agent-chat-tab-v1-a'],
activeTabId: 'agent-chat-tab-v1-a',
recentTabIds: ['agent-chat-tab-v1-a']
})
expect(buildMobileSessionTabSnapshots(state)[0]).toBe(issued)
setHostSessionTabIdMapping(
{ environmentId: 'local', worktreeId: 'wt-1', tabId: chat.id },
'agent-chat-tab-v1-b'
)
expect(buildMobileSessionTabSnapshots(state)[0]?.tabGroups?.[0]?.tabOrder).toEqual([
'agent-chat-tab-v1-b'
])
} finally {
clearHostSessionTabIdMappings('local', 'wt-1')
}
})
@@ -1,60 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import type { RuntimeMobileSessionTabsResult } from '../../../../../shared/runtime-session-contracts'
import {
listRemoteRuntimeSessionTabsAfterCurrentInFlight,
listRemoteRuntimeSessionTabsDeduped
} from './remote-runtime-session-tabs-inflight'
const SNAPSHOT = {
worktree: 'wt-1',
publicationEpoch: 'epoch-1',
snapshotVersion: 1,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: []
} satisfies RuntimeMobileSessionTabsResult
describe('remote runtime session-tabs in-flight requests', () => {
it('waits out an older request before sharing a post-operation inventory', async () => {
let resolveCurrent: (answer: { snapshot: RuntimeMobileSessionTabsResult }) => void = () => {}
const currentLoad = vi.fn(
() =>
new Promise<{ snapshot: RuntimeMobileSessionTabsResult }>((resolve) => {
resolveCurrent = resolve
})
)
let resolveFresh: (answer: { snapshot: RuntimeMobileSessionTabsResult }) => void = () => {}
const freshLoad = vi.fn(
() =>
new Promise<{ snapshot: RuntimeMobileSessionTabsResult }>((resolve) => {
resolveFresh = resolve
})
)
const ownership = { environmentId: 'env-1', worktreeId: 'wt-1' }
const current = listRemoteRuntimeSessionTabsDeduped({ ...ownership, load: currentLoad })
const firstFresh = listRemoteRuntimeSessionTabsAfterCurrentInFlight({
...ownership,
load: freshLoad
})
const secondFresh = listRemoteRuntimeSessionTabsAfterCurrentInFlight({
...ownership,
load: freshLoad
})
expect(freshLoad).not.toHaveBeenCalled()
resolveCurrent({ snapshot: SNAPSHOT })
await expect(current.then((answer) => answer.snapshot)).resolves.toBe(SNAPSHOT)
await vi.waitFor(() => expect(freshLoad).toHaveBeenCalledOnce())
resolveFresh({ snapshot: { ...SNAPSHOT, snapshotVersion: 2 } })
await expect(
Promise.all([firstFresh, secondFresh]).then((answers) =>
answers.map((answer) => answer.snapshot)
)
).resolves.toEqual([
{ ...SNAPSHOT, snapshotVersion: 2 },
{ ...SNAPSHOT, snapshotVersion: 2 }
])
})
})
@@ -1,59 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { PRCheckDetail } from '../../../../../shared/github/check-types'
import { createTestStore, mockApi, resetRemoteRuntimeMocks } from '../github-slice-test-harness'
// What main's gate rejects with, as IPC delivers it to the renderer.
const refusal = new Error(
"Error invoking remote method 'gh:issue': WslDistroStoppedError: WSL distro 'Ubuntu' is not running. Retry, or open a terminal in it, to start it."
)
const issue = { number: 7, title: 'Linked', state: 'open', url: 'https://example.test/7' }
const checks: PRCheckDetail[] = [{ name: 'Build', status: 'queued', conclusion: null, url: null }]
let consoleError: ReturnType<typeof vi.spyOn>
beforeEach(() => {
vi.clearAllMocks()
resetRemoteRuntimeMocks()
consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined)
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})
describe('GitHub polls refused for a stopped WSL distro', () => {
it('keeps the linked issue a card already shows, without logging a failure', async () => {
vi.useFakeTimers()
const store = createTestStore()
mockApi.gh.issue.mockResolvedValueOnce(issue)
await store.getState().fetchIssue('/repo', 7)
// Past the issue cache's freshness window, so the next card poll asks main again.
vi.advanceTimersByTime(24 * 60 * 60 * 1000)
mockApi.gh.issue.mockRejectedValueOnce(refusal)
await expect(store.getState().fetchIssue('/repo', 7)).resolves.toEqual(issue)
expect(Object.values(store.getState().issueCache).map((entry) => entry.data)).toEqual([issue])
expect(consoleError).not.toHaveBeenCalled()
})
it('sends Refresh as a user act and does not join a poll already in flight', async () => {
const store = createTestStore()
const poll = Promise.withResolvers<PRCheckDetail[]>()
mockApi.gh.prChecks.mockReturnValueOnce(poll.promise).mockResolvedValueOnce(checks)
const polled = store.getState().fetchPRChecks('/repo', 1, 'main', 'sha', undefined, {
force: true
})
const refreshed = store.getState().fetchPRChecks('/repo', 1, 'main', 'sha', undefined, {
force: true,
wakeWslDistro: true
})
poll.reject(refusal)
await expect(refreshed).resolves.toEqual(checks)
await polled
expect(mockApi.gh.prChecks.mock.calls[0][0]).not.toHaveProperty('wakeWslDistro')
expect(mockApi.gh.prChecks.mock.calls[1][0]).toMatchObject({ wakeWslDistro: true })
})
})
@@ -1,58 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createTestStore } from '../../testing/app-store-test-fixture'
// Directly test paneKey reuse: minted IDs make ordinary collisions rare, but stale closed-pane acks must never suppress a future unvisited signal.
describe('acknowledgedAgentsByPaneKey cleanup on teardown', () => {
afterEach(() => {
vi.useRealTimers()
})
it('removeAgentStatusByTabPrefix drops every ack entry whose paneKey starts with the tab prefix', () => {
vi.useFakeTimers()
const store = createTestStore()
store
.getState()
.setAgentStatus('tab-1:0', { state: 'working', prompt: 'p', agentType: 'claude' })
store
.getState()
.setAgentStatus('tab-1:1', { state: 'working', prompt: 'p', agentType: 'claude' })
store
.getState()
.setAgentStatus('tab-10:0', { state: 'working', prompt: 'p', agentType: 'claude' })
store.getState().acknowledgeAgents(['tab-1:0', 'tab-1:1', 'tab-10:0'])
store.setState({
activityClearedAtByPaneKey: { 'tab-1:0': 100, 'tab-10:0': 300 },
manuallyUnreadTurnsByPaneKey: { 'tab-1:1': 200, 'tab-10:0': 400 }
})
store.getState().removeAgentStatusByTabPrefix('tab-1')
const ack = store.getState().acknowledgedAgentsByPaneKey
expect(ack['tab-1:0']).toBeUndefined()
expect(ack['tab-1:1']).toBeUndefined()
// Delimiter prevents tab-1 prefixes matching tab-10.
expect(ack['tab-10:0']).toBeGreaterThan(0)
expect(store.getState().activityClearedAtByPaneKey).toEqual({ 'tab-10:0': 300 })
expect(store.getState().manuallyUnreadTurnsByPaneKey).toEqual({ 'tab-10:0': 400 })
})
it('removeAgentStatus leaves read state alone for a retained-only pane (unverified SSH exit)', () => {
vi.useFakeTimers()
const store = createTestStore()
// Unconditional PTY exit may be unverified SSH loss; preserve retained read state so reconnect does not rebold acked rows or replay cleared history.
store.getState().acknowledgeAgents(['tab-6:0'])
store.setState({
activityClearedAtByPaneKey: { 'tab-6:0': 100 },
manuallyUnreadTurnsByPaneKey: { 'tab-6:0': 200 }
})
const epochBefore = store.getState().agentStatusEpoch
store.getState().removeAgentStatus('tab-6:0')
expect(store.getState().acknowledgedAgentsByPaneKey['tab-6:0']).toBeGreaterThan(0)
expect(store.getState().activityClearedAtByPaneKey['tab-6:0']).toBe(100)
expect(store.getState().manuallyUnreadTurnsByPaneKey['tab-6:0']).toBe(200)
expect(store.getState().agentStatusEpoch).toBe(epochBefore)
})
})
@@ -1,59 +0,0 @@
import { beforeEach, expect, it } from 'vitest'
import { useAppStore } from '@/store'
import { assertEditorBufferInvariant } from './editor-buffer-record-lifecycle'
import { makeWorktree } from '../../worktrees/worktree.test-fixture'
import type { OpenFile } from '../types/open-file'
function tab(id: string, patch: Partial<OpenFile> = {}): OpenFile {
return {
id,
filePath: '/repo/a.ts',
relativePath: 'a.ts',
worktreeId: 'wt-1',
language: 'typescript',
isDirty: false,
mode: 'edit',
lastKnownDiskSignature: 'sig',
...patch
}
}
const view = (id: string) => useAppStore.getState().openFiles.find((file) => file.id === id)
beforeEach(() => {
useAppStore.setState(useAppStore.getInitialState(), true)
useAppStore.setState({
worktreesByRepo: {
'repo-1': [makeWorktree({ id: 'wt-1', repoId: 'repo-1', path: '/repo', hostId: 'local' })]
}
})
})
it('a view with an identical draft merges and mirrors the record as dirty', () => {
useAppStore.setState({
openFiles: [tab('a', { isDirty: true })],
editorDrafts: { a: 'same edits' }
})
// The joining view holds the same draft but its own flag reads clean.
useAppStore.setState((s) => ({
openFiles: [...s.openFiles, tab('b')],
editorDrafts: { ...s.editorDrafts, b: 'same edits' }
}))
const state = useAppStore.getState()
expect(state.editorBufferIdOf.b).toBe(state.editorBufferIdOf.a)
expect(view('b')?.isDirty).toBe(true)
expect(() => assertEditorBufferInvariant(state)).not.toThrow()
})
it('a clean view that saw the file deleted keeps the deleted banner on every view when it joins', () => {
useAppStore.setState({ openFiles: [tab('a')] })
useAppStore.setState((s) => ({
openFiles: [...s.openFiles, tab('b', { externalMutation: 'deleted' })]
}))
const state = useAppStore.getState()
expect(state.editorBufferIdOf.b).toBe(state.editorBufferIdOf.a)
expect(view('a')?.externalMutation).toBe('deleted')
expect(view('b')?.externalMutation).toBe('deleted')
})