test: retire mobile presence and native-chat fixture suites (#41617)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-12 10:02:51 -08:00
committed by GitHub
co-authored by OrcaWin
parent d34c829237
commit a1034d5bd8
11 changed files with 8 additions and 1961 deletions
-1
View File
@@ -530,7 +530,6 @@
3 test-no-wall-clock:src/renderer/src/components/activity/activity-auto-mark-read-loop.react185.test.tsx
2 test-no-wall-clock:src/renderer/src/components/artifacts/ArtifactCollection.test.tsx
1 test-no-wall-clock:src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx
3 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx
2 test-no-wall-clock:src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx
1 test-no-wall-clock:src/renderer/src/components/sidebar/workspace-card/review/use-workspace-reference-details.test.tsx
1 test-no-wall-clock:src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx
File diff suppressed because one or more lines are too long
@@ -1,29 +0,0 @@
export const mobilePresenceStore = {
getRepo: () => ({
id: 'repo-1',
path: '/tmp/repo',
displayName: 'repo',
badgeColor: 'blue',
addedAt: 1
}),
getRepos: () => [mobilePresenceStore.getRepo()],
addRepo: () => {},
updateRepo: () => undefined as never,
getAllWorktreeMeta: () => ({}),
getWorktreeMeta: () => undefined,
getGitHubCache: () => ({ pr: {}, issue: {} }),
setWorktreeMeta: () => undefined as never,
removeWorktreeMeta: () => {},
getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }),
addRetiredWorktreeName: () => {},
mergeRetiredWorktreeNames: () => false,
getSettings: () => ({
workspaceDir: '/tmp/workspaces',
nestWorkspaces: false,
refreshLocalBaseRefOnWorktreeCreate: false,
branchPrefix: 'none',
branchPrefixCustom: '',
// Legacy restore tests need a finite 5s; production defaults to indefinite hold.
mobileAutoRestoreFitMs: 5_000
})
}
@@ -1,199 +0,0 @@
import { mobilePresenceStore as store } from '../../orca-runtime-test-mocks/mobile-presence-store'
import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache'
import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing'
import '../input/terminal-input-admission'
import './mobile-subscribe-integration.spec'
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { listWorktrees } from '../../../git/worktrees/catalog/worktree-scan-cache'
import type * as GitUsernameModule from '../../../git/repositories/git-username'
import { OrcaRuntimeService } from '../../orca-runtime'
import type { RuntimePtyController } from '../lifecycle/runtime-pty-controller-contract'
vi.mock('../../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => {
const facade = getWorktreeListingMocks()
return {
...(await importOriginal<typeof WorktreeScanCacheModule>()),
listWorktrees: facade.listWorktrees
}
})
vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => {
const facade = getWorktreeListingMocks()
return {
...(await importOriginal<typeof WorktreeListingModule>()),
listWorktreesStrict: facade.listWorktreesStrict
}
})
const { getWorktreeListingMocks } = vi.hoisted(() => {
const createWorktreeListingMocks = () => ({
listWorktrees: vi.fn().mockResolvedValue([]),
listWorktreesStrict: vi.fn().mockResolvedValue([])
})
let listings: ReturnType<typeof createWorktreeListingMocks> | undefined
return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) }
})
vi.mock('../../../workspace-hooks/hooks', () => ({
getEffectiveHooks: vi.fn().mockReturnValue(null),
runHook: vi.fn().mockResolvedValue({ success: true, output: '' })
}))
vi.mock('../../../workspace-hooks/worktree-runner-script', () => ({
createSetupRunnerScript: vi.fn()
}))
vi.mock('../../../ipc/worktree-logic', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>
return { ...actual, computeWorktreePath: vi.fn(), ensurePathWithinWorkspace: vi.fn() }
})
vi.mock('../../../ipc/worktrees/removal/registered-worktree-roots-cache', () => ({
invalidateAuthorizedRootsCache: vi.fn(),
invalidateAuthorizedRootsCacheForRepo: vi.fn()
}))
const repoBranchConflictMock = vi.hoisted(() => vi.fn().mockResolvedValue(null))
vi.mock('../../../git/repositories/git-username', async () => {
const actual = await vi.importActual<typeof GitUsernameModule>(
'../../../git/repositories/git-username'
)
return { ...actual, resolveLocalGitUsername: vi.fn(async () => '') }
})
// #7588 held-modal cases need per-test indefinite hold without mutating the shared default.
function createRuntime(mobileAutoRestoreFitMs: number | null = 5_000) {
vi.mocked(listWorktrees).mockResolvedValue([])
const effectiveStore = {
...store,
getSettings: () => ({ ...store.getSettings(), mobileAutoRestoreFitMs })
}
const runtime = new OrcaRuntimeService(effectiveStore)
const ptySizes = new Map<string, { cols: number; rows: number }>([
['pty-1', { cols: 150, rows: 40 }]
])
const resizes: { ptyId: string; cols: number; rows: number }[] = []
const writes: string[] = []
const driverEvents: { ptyId: string; driver: { kind: string; clientId?: string } }[] = []
const fitOverrideEvents: { ptyId: string; mode: string; cols: number; rows: number }[] = []
let resizeSucceeds = true
const controller: RuntimePtyController = {
write: (_ptyId, data) => {
writes.push(data)
return true
},
kill: () => true,
getForegroundProcess: async () => null,
resize: (ptyId, cols, rows) => {
if (!resizeSucceeds) {
return false
}
ptySizes.set(ptyId, { cols, rows })
resizes.push({ ptyId, cols, rows })
return true
},
getSize: (ptyId) => ptySizes.get(ptyId) ?? null
}
runtime.setPtyController(controller)
runtime.setNotifier({
worktreesChanged: vi.fn(),
reposChanged: vi.fn(),
activateWorktree: vi.fn(),
createTerminal: vi.fn(),
splitTerminal: vi.fn(),
renameTerminal: vi.fn(),
focusTerminal: vi.fn(),
closeTerminal: vi.fn(),
terminalFitOverrideChanged: (ptyId, mode, cols, rows) => {
fitOverrideEvents.push({ ptyId, mode, cols, rows })
},
terminalDriverChanged: (ptyId, driver) => {
driverEvents.push({ ptyId, driver: { ...driver } })
}
})
return {
runtime,
controller,
ptySizes,
resizes,
writes,
driverEvents,
fitOverrideEvents,
setResizeSucceeds: (next: boolean) => {
resizeSucceeds = next
}
}
}
describe('mobile presence lock — multi-mobile semantics', () => {
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())
it('updateDesktopViewport resizes the source PTY and records desktop geometry', async () => {
const { runtime, ptySizes, resizes } = createRuntime()
expect(await runtime.updateDesktopViewport('pty-1', { cols: 132, rows: 44 })).toBe(true)
expect(ptySizes.get('pty-1')).toEqual({ cols: 132, rows: 44 })
expect(resizes.at(-1)).toEqual({ ptyId: 'pty-1', cols: 132, rows: 44 })
// Controller drift must not overwrite remembered renderer geometry.
ptySizes.set('pty-1', { cols: 160, rows: 50 })
await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 49, rows: 20 })
expect(await runtime.reclaimTerminalForDesktop('pty-1')).toBe(true)
expect(ptySizes.get('pty-1')).toEqual({ cols: 132, rows: 44 })
})
it('updateDesktopViewport records restore geometry while phone-fit override is held', async () => {
const { runtime, ptySizes, resizes } = createRuntime()
await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 49, rows: 20 })
expect(ptySizes.get('pty-1')).toEqual({ cols: 49, rows: 20 })
resizes.length = 0
expect(await runtime.updateDesktopViewport('pty-1', { cols: 132, rows: 44 })).toBe(true)
expect(ptySizes.get('pty-1')).toEqual({ cols: 49, rows: 20 })
expect(resizes).toEqual([])
expect(await runtime.reclaimTerminalForDesktop('pty-1')).toBe(true)
expect(ptySizes.get('pty-1')).toEqual({ cols: 132, rows: 44 })
})
})
// #7588: null-viewport re-subscribe leaves an active subscriber under the held fit override.
async function reachHeldModalWithNullViewportResubscribe(
runtime: OrcaRuntimeService
): Promise<void> {
await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
runtime.handleMobileUnsubscribe('pty-1', 'phone-A')
await vi.advanceTimersByTimeAsync(300)
await runtime.handleMobileSubscribe('pty-1', 'phone-A', undefined)
}
describe('mobile presence lock — issue #7588 held-modal restore convergence', () => {
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())
it('reclaim after a null-viewport resubscribe restores dims, clears override, notifies both channels', async () => {
const { runtime, ptySizes, fitOverrideEvents } = createRuntime(null)
const listenerEvents: { mode: string; cols: number; rows: number }[] = []
runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e))
await reachHeldModalWithNullViewportResubscribe(runtime)
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'idle' })
expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull()
expect(ptySizes.get('pty-1')).toEqual({ cols: 45, rows: 20 })
const notifierBefore = fitOverrideEvents.length
const listenerBefore = listenerEvents.length
const restored = await runtime.reclaimTerminalForDesktop('pty-1')
expect(restored).toBe(true)
expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 })
expect(runtime.getTerminalFitOverride('pty-1')).toBeNull()
expect(fitOverrideEvents.slice(notifierBefore).some((e) => e.mode === 'desktop-fit')).toBe(true)
expect(listenerEvents.slice(listenerBefore).some((e) => e.mode === 'desktop-fit')).toBe(true)
})
})
vi.mock('../../../git/refs/resolution/repo-branch-conflict', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getBranchConflictKind: repoBranchConflictMock
}))
@@ -1,279 +0,0 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { listWorktrees } from '../../../git/worktrees/catalog/worktree-scan-cache'
import { OrcaRuntimeService } from '../../orca-runtime'
// Legacy restore cases need finite 5s (the clamp floor); production defaults to indefinite hold.
const LEGACY_RESTORE_MS = 5_000
const settingsState = {
mobileAutoRestoreFitMs: LEGACY_RESTORE_MS as number | null
}
const store = {
getRepo: () => ({
id: 'repo-1',
path: '/tmp/repo',
displayName: 'repo',
badgeColor: 'blue',
addedAt: 1
}),
getRepos: () => [store.getRepo()],
addRepo: () => {},
updateRepo: () => undefined as never,
getAllWorktreeMeta: () => ({}),
getWorktreeMeta: () => undefined,
getGitHubCache: () => ({ pr: {}, issue: {} }),
setWorktreeMeta: () => undefined as never,
removeWorktreeMeta: () => {},
getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }),
addRetiredWorktreeName: () => {},
mergeRetiredWorktreeNames: () => false,
getSettings: () => ({
workspaceDir: '/tmp/workspaces',
nestWorkspaces: false,
refreshLocalBaseRefOnWorktreeCreate: false,
branchPrefix: 'none',
branchPrefixCustom: '',
mobileAutoRestoreFitMs: settingsState.mobileAutoRestoreFitMs
}),
updateSettings: (updates: { mobileAutoRestoreFitMs?: number | null }) => {
if ('mobileAutoRestoreFitMs' in updates) {
settingsState.mobileAutoRestoreFitMs = updates.mobileAutoRestoreFitMs ?? null
}
}
}
class ObservableRuntime extends OrcaRuntimeService {
get restoreTimers(): typeof this.pendingRestoreTimers {
return this.pendingRestoreTimers
}
get softLeavers(): typeof this.pendingSoftLeavers {
return this.pendingSoftLeavers
}
get fitOverrides(): typeof this.terminalFitOverrides {
return this.terminalFitOverrides
}
get drivers(): typeof this.terminalDrivers {
return this.terminalDrivers
}
}
function createRuntime() {
vi.mocked(listWorktrees).mockResolvedValue([
{
path: '/tmp/worktree-a',
head: 'abc',
branch: 'feature/foo',
isBare: false,
isMainWorktree: false
}
])
const runtime = new ObservableRuntime(store)
const ptySizes = new Map<string, { cols: number; rows: number }>()
ptySizes.set('pty-1', { cols: 150, rows: 40 })
ptySizes.set('pty-2', { cols: 120, rows: 35 })
ptySizes.set('pty-3', { cols: 100, rows: 30 })
const resizes: { ptyId: string; cols: number; rows: number }[] = []
const notifications: { ptyId: string; mode: string; cols: number; rows: number }[] = []
runtime.setPtyController({
write: () => true,
kill: () => true,
getForegroundProcess: async () => null,
resize: (ptyId, cols, rows) => {
ptySizes.set(ptyId, { cols, rows })
resizes.push({ ptyId, cols, rows })
return true
},
getSize: (ptyId) => ptySizes.get(ptyId) ?? null
})
runtime.setNotifier({
worktreesChanged: vi.fn(),
reposChanged: vi.fn(),
activateWorktree: vi.fn(),
createTerminal: vi.fn(),
splitTerminal: vi.fn(),
renameTerminal: vi.fn(),
focusTerminal: vi.fn(),
closeTerminal: vi.fn(),
terminalFitOverrideChanged: (ptyId, mode, cols, rows) => {
notifications.push({ ptyId, mode, cols, rows })
},
terminalDriverChanged: vi.fn()
})
return { runtime, ptySizes, resizes, notifications }
}
describe('mobile subscribe integration', () => {
beforeEach(() => {
vi.useFakeTimers()
settingsState.mobileAutoRestoreFitMs = LEGACY_RESTORE_MS
})
afterEach(() => {
vi.useRealTimers()
})
it('serializeMainTerminalBuffer reports the seq included in the headless snapshot', async () => {
vi.useRealTimers()
const { runtime } = createRuntime()
const first = 'one\r\n'
const second = 'two\r\n'
const third = 'three\r\n'
runtime.onPtyData('pty-1', first, Date.now())
const initialSnapshot = await runtime.serializeMainTerminalBuffer('pty-1')
expect(initialSnapshot?.seq).toBe(first.length)
expect(initialSnapshot?.source).toBe('headless')
type HeadlessStateForTest = {
emulator: { write: (data: string) => Promise<void> | void }
}
const headless = (
runtime as unknown as { headlessTerminals: Map<string, HeadlessStateForTest> }
).headlessTerminals.get('pty-1')
expect(headless).toBeDefined()
const originalWrite = headless!.emulator.write.bind(headless!.emulator)
const secondWriteGate: { release: (() => void) | null } = { release: null }
const secondWriteStarted = new Promise<void>((resolve) => {
headless!.emulator.write = async (data: string): Promise<void> => {
if (data === second) {
resolve()
await new Promise<void>((release) => {
secondWriteGate.release = release
})
}
await originalWrite(data)
}
})
try {
runtime.onPtyData('pty-1', second, Date.now())
await secondWriteStarted
const racedSnapshot = runtime.serializeMainTerminalBuffer('pty-1')
runtime.onPtyData('pty-1', third, Date.now())
if (!secondWriteGate.release) {
throw new Error('second write did not block')
}
secondWriteGate.release()
const snapshot = await racedSnapshot
expect(snapshot?.seq).toBe(first.length + second.length)
expect(snapshot?.source).toBe('headless')
expect(runtime.getPtyOutputSequence('pty-1')).toBe(
first.length + second.length + third.length
)
const finalSnapshot = await runtime.serializeMainTerminalBuffer('pty-1')
expect(finalSnapshot?.seq).toBe(first.length + second.length + third.length)
expect(finalSnapshot?.source).toBe('headless')
} finally {
headless!.emulator.write = originalWrite
secondWriteGate.release?.()
}
})
it('preserves held-override baseline across resubscribe-after-indefinite-hold', async () => {
// Indefinite-hold re-subscribe must inherit the retained desktop baseline for later Restore.
settingsState.mobileAutoRestoreFitMs = null
const { runtime, ptySizes } = createRuntime()
await runtime.handleMobileSubscribe('pty-1', 'client-a', { cols: 45, rows: 20 })
expect(ptySizes.get('pty-1')).toEqual({ cols: 45, rows: 20 })
runtime.handleMobileUnsubscribe('pty-1', 'client-a')
await vi.advanceTimersByTimeAsync(60_000)
expect(ptySizes.get('pty-1')).toEqual({ cols: 45, rows: 20 })
await runtime.handleMobileSubscribe('pty-1', 'client-a', { cols: 45, rows: 20 })
await runtime.reclaimTerminalForDesktop('pty-1')
expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 })
})
describe('onExternalPtyResize', () => {
it('ignores reports while a mobile-fit override is in place', async () => {
// Phone-fit echoes must not poison the desktop restore baseline; see docs/mobile-fit-hold.md.
const { runtime, ptySizes } = createRuntime()
await runtime.handleMobileSubscribe('pty-1', 'client-a', { cols: 45, rows: 20 })
runtime.onExternalPtyResize('pty-1', 45, 20)
runtime.setMobileDisplayMode('pty-1', 'desktop')
await runtime.applyMobileDisplayMode('pty-1')
expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 })
})
it('updates baseline mid-fit when desktop reports dims that differ from the override', async () => {
// A newly visible desktop tab can report real geometry during phone fit; retain it for restore.
const { runtime, ptySizes } = createRuntime()
ptySizes.set('pty-1', { cols: 80, rows: 24 })
runtime.onExternalPtyResize('pty-1', 80, 24)
await runtime.handleMobileSubscribe('pty-1', 'client-a', { cols: 45, rows: 20 })
runtime.onExternalPtyResize('pty-1', 200, 60)
runtime.setMobileDisplayMode('pty-1', 'desktop')
await runtime.applyMobileDisplayMode('pty-1')
expect(ptySizes.get('pty-1')).toEqual({ cols: 200, rows: 60 })
})
})
describe('recordRendererGeometry (pty:reportGeometry IPC)', () => {
it('bypasses the cascade-suppress window (it is measurement-only)', async () => {
const { runtime, ptySizes, resizes } = createRuntime()
await runtime.handleMobileSubscribe('pty-1', 'client-a', { cols: 45, rows: 20 })
runtime.setMobileDisplayMode('pty-1', 'desktop')
await runtime.applyMobileDisplayMode('pty-1')
expect(runtime.isResizeSuppressed()).toBe(true)
expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 })
resizes.length = 0
runtime.recordRendererGeometry('pty-1', 130, 40)
expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 })
expect(resizes).toEqual([])
runtime.setMobileDisplayMode('pty-1', 'auto')
await runtime.applyMobileDisplayMode('pty-1')
expect(ptySizes.get('pty-1')).toEqual({ cols: 45, rows: 20 })
runtime.setMobileDisplayMode('pty-1', 'desktop')
await runtime.applyMobileDisplayMode('pty-1')
expect(ptySizes.get('pty-1')).toEqual({ cols: 130, rows: 40 })
})
})
// See docs/mobile-fit-hold.md.
describe('mobileAutoRestoreFitMs (fit hold)', () => {
it('reclaim with WS disconnect between cycles — held branch restores correctly each time', async () => {
// Repeated held-override reclaim must restore desktop geometry, never the current phone fit.
settingsState.mobileAutoRestoreFitMs = null
const { runtime, ptySizes } = createRuntime()
for (let i = 0; i < 3; i++) {
await runtime.handleMobileSubscribe('pty-1', 'client-a', { cols: 45, rows: 20 })
await runtime.mobileTookFloor('pty-1', 'client-a')
expect(ptySizes.get('pty-1'), `iter ${i}: phone-fit`).toEqual({ cols: 45, rows: 20 })
runtime.onClientDisconnected('client-a')
await vi.advanceTimersByTimeAsync(0)
await vi.advanceTimersByTimeAsync(60_000)
expect(ptySizes.get('pty-1'), `iter ${i}: held after disconnect`).toEqual({
cols: 45,
rows: 20
})
expect(runtime.isMobileSubscriberActive('pty-1'), `iter ${i}: no subscribers`).toBe(false)
expect(runtime.getTerminalFitOverride('pty-1'), `iter ${i}: override held`).not.toBeNull()
const ok = await runtime.reclaimTerminalForDesktop('pty-1')
expect(ok, `iter ${i}: reclaim ok`).toBe(true)
expect(ptySizes.get('pty-1'), `iter ${i}: PTY restored to desktop`).toEqual({
cols: 150,
rows: 40
})
expect(runtime.getTerminalFitOverride('pty-1'), `iter ${i}: override cleared`).toBeNull()
}
})
})
})
@@ -1,140 +0,0 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, render, screen } from '@testing-library/react'
import type {
AgentStatusEntry,
AgentStatusPayload
} from '../../../../../../shared/agent-status/contracts/agent-status-types'
import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types'
import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract'
// Stub transcript/composer to exercise store status through the view into shared turn and prompt rendering.
const retained = vi.hoisted((): { session: NativeChatLiveSession | null } => ({ session: null }))
vi.mock('../../session/terminal/read/use-native-chat-retained-session', () => ({
useNativeChatRetainedSession: () => retained.session
}))
vi.mock('../../composer/NativeChatComposer', () => ({ NativeChatComposer: () => null }))
const { NativeChatResolvedView } = await import('../../NativeChatResolvedView')
const { TooltipProvider } = await import('@/components/ui/tooltip')
const { useAppStore } = await import('../../../../store/index')
const { installNativeChatMessageListTestViewport } =
await import('../../viewport/virtualization/native-chat-message-list-test-viewport')
const paneKey = 'tab-state:leaf-state'
let restoreViewport = (): void => {}
const userTurn: NativeChatMessage = {
id: 'user-1',
role: 'user',
blocks: [{ type: 'text', text: 'Rename the module' }],
timestamp: 1,
source: 'transcript'
}
const stepCall: NativeChatMessage = {
id: 'step-1',
role: 'assistant',
blocks: [{ type: 'tool-call', name: 'Bash', input: { command: 'pnpm build' } }],
timestamp: 3,
source: 'transcript'
}
// State both reconciled fields so the fixture represents a consistent live session.
function transcript(
status: NativeChatLiveSession['status'],
hookAwaitingInput: boolean,
messages: NativeChatMessage[] = [userTurn]
): NativeChatLiveSession {
return {
messages,
status,
sessionId: 'session-state',
agent: 'claude',
hookAwaitingInput,
hasMore: false,
loadingEarlier: false,
olderHistoryGeneration: 0,
loadEarlier: vi.fn(),
readPhase: 'ready'
}
}
function setStatus(payload: Omit<AgentStatusPayload, 'prompt' | 'agentType'>, age = 0): void {
useAppStore
.getState()
.setAgentStatus(paneKey, { prompt: 'Rename the module', agentType: 'claude', ...payload })
const live = useAppStore.getState().agentStatusByPaneKey[paneKey]
if (!live) {
throw new Error('the store dropped the status row this test depends on')
}
useAppStore.setState((store) => ({
agentStatusByPaneKey: {
...store.agentStatusByPaneKey,
[paneKey]: { ...live, stateStartedAt: Date.now() - age }
}
}))
}
function patchStatus(fields: Partial<AgentStatusEntry>): void {
useAppStore.setState((store) => ({
agentStatusByPaneKey: {
...store.agentStatusByPaneKey,
[paneKey]: { ...store.agentStatusByPaneKey[paneKey]!, ...fields }
}
}))
}
function renderPane(): void {
render(
<TooltipProvider>
<NativeChatResolvedView
paneKey={paneKey}
agent="claude"
sessionId="session-state"
transcriptPath={null}
isVisible
isFocusedGroup={false}
targetPtyId="pty-state"
terminalTabId="tab-state"
ownsTabWideLaunchDraft={false}
/>
</TooltipProvider>
)
}
beforeEach(() => {
restoreViewport = installNativeChatMessageListTestViewport()
useAppStore.setState({ agentStatusByPaneKey: {}, nativeChatLaunchPromptByTabId: {} })
})
afterEach(() => {
cleanup()
restoreViewport()
useAppStore.setState({ agentStatusByPaneKey: {}, nativeChatLaunchPromptByTabId: {} })
})
describe('NativeChatResolvedView turn status', () => {
// Store staleness alone cannot prove an unanswered turn ended.
it('does not settle a turn the host went quiet on', () => {
retained.session = transcript('ready', true, [userTurn, stepCall])
setStatus({ state: 'waiting' }, 60_000)
patchStatus({ turnStartedAt: Date.now() - 60_000 })
renderPane()
expect(screen.getByText('Working for 1m 0s')).toBeInTheDocument()
// The live session reads no hook state once the row is stale, so the wait no longer holds the turn.
retained.session = transcript('ready', false, [userTurn, stepCall])
act(() => {
patchStatus({ updatedAt: Date.now() - 31 * 60_000 })
})
expect(screen.queryByText(/Work(ing|ed) for/)).toBeNull()
expect(screen.queryByRole('button', { name: 'Toggle turn details' })).toBeNull()
expect(screen.getByText('pnpm build')).toBeInTheDocument()
})
})
@@ -1,303 +0,0 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterAll, afterEach, beforeAll, beforeEach, expect, it, vi } from 'vitest'
import type { ReactNode } from 'react'
import { useAppStore } from '@/store'
import { TooltipProvider } from '@/components/ui/tooltip'
import type { AgentSessionStatusEvent } from '../../../../../../shared/agent-session/agent-session-wire'
import type { AgentMessageSource } from '../../../../../../shared/agent-session/agent-session-message-source'
import { testOrcaSessionId } from '../../../../../../shared/orca-session-address-test-fixture'
import type { Tab } from '../../../../../../shared/tab-types'
import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target'
import { AGENT_SESSION_STATUS_FEED_RUNTIME_CAPABILITY } from '../../../../../../shared/agent-session/agent-session-attention-capabilities'
import {
MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION,
RUNTIME_PROTOCOL_VERSION
} from '../../../../../../shared/protocol-version'
const { mocks, moduleFactories, resetStructuredSessionMocks } = await vi.hoisted(async () =>
(
await import('../../surfaces/integration/NativeChatStructuredSession.test-harness')
).createStructuredSessionMocks()
)
const transport = vi.hoisted(() => ({
bridge: vi.fn(),
subscribe: vi.fn(),
focusRenderer: vi.fn(() => false),
subscriptions: new Map<string, (event: AgentSessionStatusEvent) => void>(),
unsupported: false,
olderLookup: false
}))
vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () =>
moduleFactories.structuredAgentSessionCall()
)
vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({
...moduleFactories.structuredAgentSessionSubscriptions(),
subscribeStructuredAgentSessionStatus: transport.subscribe
}))
vi.mock('../../session/structured/use-structured-agent-session', () =>
moduleFactories.useStructuredAgentSession()
)
vi.mock('../../appearance/use-native-chat-font-size', () => moduleFactories.useNativeChatFontSize())
vi.mock('../../links/actions/use-native-chat-file-link-context', () =>
moduleFactories.useNativeChatFileLinkContext()
)
vi.mock('../../links/actions/use-native-chat-file-link-click', () =>
moduleFactories.useNativeChatFileLinkClick()
)
vi.mock('../../media/images/native-chat-image-runtime-context', () => ({
useNativeChatImageRuntimeContext: () => ({
settings: null,
worktreeId: 'shared-workspace',
worktreePath: '/repo'
})
}))
vi.mock('../../composer/NativeChatComposer', () => moduleFactories.nativeChatComposer())
vi.mock('../../host-access/NativeChatEmptyState', () => moduleFactories.nativeChatEmptyState())
vi.mock('../../prompts/NativeChatApprovalCard', () => moduleFactories.nativeChatApprovalCard())
vi.mock('../../prompts/NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard())
vi.mock('../../attachments/intake/NativeChatPaneFileDropSurface', () => ({
NativeChatPaneFileDropSurface: ({ children }: { children: ReactNode }) => children
}))
vi.mock('../../../tab-group/RetainedPaneHost', () => ({
RetainedPaneHost: ({ children }: { children: ReactNode }) => children
}))
vi.mock('@/components/terminal-pane/links/handles/terminal-handle-links', async (original) => ({
...(await original<Record<string, unknown>>()),
focusRendererTerminalHandle: transport.focusRenderer
}))
import StructuredAgentSessionPaneOverlayLayer from '../../pane/routing/StructuredAgentSessionPaneOverlayLayer'
import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '@/runtime/rpc/compatibility/runtime-compatibility-cache'
import {
getStructuredAgentSessionStatusFeed,
resetStructuredAgentSessionStatusFeedsForTests
} from '@/runtime/native-chat/status/structured-agent-session-status-feed'
const WORKSPACE = 'shared-workspace'
const ROOT = testOrcaSessionId('root-chat')
const initial = useAppStore.getInitialState()
const previousApi = Object.getOwnPropertyDescriptor(window, 'api')
import { installNativeChatMessageListTestViewport } from '../../viewport/virtualization/native-chat-message-list-test-viewport'
let restoreViewport = () => {}
beforeAll(() => {
restoreViewport = installNativeChatMessageListTestViewport()
})
afterAll(() => restoreViewport())
function tab(id: string, sessionId: string, name: string, host: 'local' | 'runtime:server-1'): Tab {
return {
id,
entityId: sessionId,
customLabel: name,
executionHostId: host,
worktreeId: WORKSPACE,
groupId: 'group',
contentType: 'agent-session',
label: 'Claude Chat',
color: null,
sortOrder: 0,
createdAt: 0
}
}
function source(terminal = false): AgentMessageSource {
const address = terminal ? 'term-sender' : `orca_session_id:${ROOT}`
return {
kind: 'agent',
senders: [
{
party: {
address,
terminalHandle: terminal ? address : null,
orcaSessionId: terminal ? null : ROOT
},
name: 'Recorded sender'
}
],
orchestration: {
message: 'mail-notice',
mailbox: 'run:r1',
dispatchId: null,
messages: [{ messageId: 'mail-1', runId: 'r1', from: address }]
}
}
}
function seed(duplicate = false, terminal = false): void {
const from = source(terminal)
mocks.messages = [
{
id: 'mail',
role: 'user',
timestamp: 1,
source: 'transcript',
blocks: [{ type: 'text', text: 'Agent mail' }],
from
}
]
mocks.queuedCards = [
{ messageId: 'queued', position: 1, text: 'Agent mail', state: 'waiting', hold: 'turn', from }
]
useAppStore.setState(
{
...initial,
activeWorktreeId: WORKSPACE,
activeWorkspaceExecutionHostId: 'local',
focusGroup: vi.fn(),
activateTab: vi.fn(),
setActiveTabType: vi.fn(),
unifiedTabsByWorktree: {
[WORKSPACE]: [
{
...tab('recipient', 'recipient-chat', 'Recipient', 'runtime:server-1'),
agentSessionAgent: 'claude'
},
tab('remote-sender', ROOT, 'Remote rename', 'runtime:server-1'),
tab('local-sender', duplicate ? ROOT : 'local-chat', 'Wrong local name', 'local')
]
},
groupsByWorktree: {
[WORKSPACE]: [
{ id: 'group', worktreeId: WORKSPACE, activeTabId: 'recipient', tabOrder: ['recipient'] }
]
},
activeGroupIdByWorktree: { [WORKSPACE]: 'group' }
},
true
)
}
async function mount(): Promise<ReturnType<typeof render>> {
let view: ReturnType<typeof render>
await act(async () => {
view = render(
<TooltipProvider>
<StructuredAgentSessionPaneOverlayLayer worktreeId={WORKSPACE} isWorktreeActive />
</TooltipProvider>
)
})
return view!
}
function publish(host: string, sessionId: string = ROOT): void {
transport.subscriptions.get(host)?.({
type: 'snapshot',
sessions: [
{
sessionId,
workspaceId: WORKSPACE,
agent: 'claude',
status: null,
latestPrompt: '',
updatedAt: 1
}
]
})
}
beforeEach(() => {
resetStructuredSessionMocks()
resetStructuredAgentSessionStatusFeedsForTests()
clearRuntimeCompatibilityCacheForTests()
transport.subscriptions.clear()
transport.subscribe.mockReset()
transport.focusRenderer.mockClear()
transport.unsupported = false
transport.olderLookup = false
transport.subscribe.mockImplementation(
async (target: RuntimeClientTarget, emit: (event: AgentSessionStatusEvent) => void) => {
const host = target.kind === 'local' ? 'local' : target.environmentId
transport.subscriptions.set(host, emit)
return { unsubscribe: vi.fn(() => transport.subscriptions.delete(host)) }
}
)
transport.bridge.mockReset()
transport.bridge.mockImplementation(
async ({ method, params }: { method: string; params?: { address?: string } }) => {
if (method.startsWith('orchestration.party') && transport.olderLookup) {
return {
id: 'reply',
ok: false,
error: { code: 'method_not_found', message: 'older host' },
_meta: { runtimeId: 'remote' }
}
}
const result =
method === 'status.get'
? {
runtimeId: 'remote',
graphStatus: 'ready',
runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION,
minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION,
capabilities: transport.unsupported
? []
: [AGENT_SESSION_STATUS_FEED_RUNTIME_CAPABILITY]
}
: method === 'orchestration.partyOpen'
? {
location:
params?.address === 'term-sender'
? { kind: 'terminal', handle: 'term-current' }
: { kind: 'chat', sessionId: ROOT, worktreeId: WORKSPACE }
}
: { ok: true }
return { id: 'reply', ok: true, result, _meta: { runtimeId: 'remote' } }
}
)
Object.defineProperty(window, 'api', {
configurable: true,
value: {
...window.api,
runtime: { call: transport.bridge },
runtimeEnvironments: { call: transport.bridge }
}
})
})
afterEach(() => {
cleanup()
resetStructuredAgentSessionStatusFeedsForTests()
clearRuntimeCompatibilityCacheForTests()
useAppStore.setState(initial, true)
if (previousApi) {
Object.defineProperty(window, 'api', previousApi)
} else {
Reflect.deleteProperty(window, 'api')
}
})
it.each([false, true])(
'uses the stamped recipient host through queue/transcript names, renames and chat clicks (duplicate IDs %s)',
async (duplicate) => {
seed(duplicate)
const stopLocal = getStructuredAgentSessionStatusFeed({ kind: 'local' }).activate()
await mount()
act(() => {
publish('local', duplicate ? ROOT : 'local-chat')
publish('server-1')
})
expect(screen.getAllByRole('button', { name: 'Remote rename' })).toHaveLength(2)
act(() =>
useAppStore.setState({
unifiedTabsByWorktree: {
[WORKSPACE]: useAppStore
.getState()
.unifiedTabsByWorktree[WORKSPACE]!.map((t) =>
t.id === 'remote-sender' ? { ...t, customLabel: 'Updated remote rename' } : t
)
}
})
)
const links = screen.getAllByRole('button', { name: 'Updated remote rename' })
for (const link of links) {
await act(async () => fireEvent.click(link))
expect(transport.bridge).toHaveBeenCalledWith(
expect.objectContaining({ selector: 'server-1', method: 'orchestration.partyOpen' })
)
expect(transport.bridge).toHaveBeenCalledWith(
expect.objectContaining({ selector: 'server-1', method: 'session.tabs.activate' })
)
expect(useAppStore.getState().activateTab).toHaveBeenLastCalledWith('remote-sender', {
worktreeId: WORKSPACE
})
}
stopLocal()
}
)
@@ -1,573 +0,0 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { cleanup, fireEvent, screen, within } from '@testing-library/react'
import { render } from '../actions/native-chat-tooltip-test-harness'
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
import type {
AgentJournalItemBody,
AgentJournalRenderItem,
AgentJournalStatusItem
} from '../../../../../../shared/agent-session/journal/agent-session-journal-types'
import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types'
import { projectStructuredItemToNativeChat } from '../../../../../../shared/agent-session/view/structured-agent-session-projection'
import { NativeChatMessageList } from '../../NativeChatMessageList'
import { installNativeChatMessageListTestViewport } from '../../viewport/virtualization/native-chat-message-list-test-viewport'
import { projectNativeChatTaskListFrames } from '../../../../../../shared/native-chat/input/native-chat-task-list-frames'
import { projectStructuredQuestionMessages } from '../../../../../../shared/structured-agent-question-projection'
import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract'
{
const STARTED = 1_000
const prompt: NativeChatMessage = {
id: 'user-1',
role: 'user',
blocks: [{ type: 'text', text: 'Start the task' }],
timestamp: STARTED - 500,
source: 'transcript'
}
function reasoning(
id: string,
text: string,
state: 'running' | 'completed',
fields: Partial<NativeChatMessage> = {}
): NativeChatMessage {
return {
id,
role: 'reasoning',
blocks: [{ type: 'text', text }],
timestamp: STARTED,
source: 'transcript',
state,
...(state === 'completed' ? { completedAt: STARTED + 12_000 } : {}),
...fields
}
}
function journal(rows: readonly NativeChatMessage[]): AgentJournalRenderItem[] {
return [
{
itemId: prompt.id,
revision: 1,
sequence: 1,
observedAt: 1,
body: { kind: 'message', role: 'user', blocks: prompt.blocks }
},
{
itemId: 'turn-1',
revision: 1,
sequence: 2,
observedAt: 2,
body: { kind: 'turn', turnId: 'turn-1', state: 'running', userItemId: prompt.id }
},
...rows.map((row, index) => ({
itemId: row.id,
revision: 1,
sequence: index + 3,
observedAt: index + 3,
...(row.agentId ? { agentId: row.agentId } : {}),
body: {
kind: 'message' as const,
role: row.role,
blocks: row.blocks,
...(row.state ? { state: row.state } : {})
}
}))
]
}
function sessionOf(messages: NativeChatMessage[]): NativeChatLiveSession {
return {
messages,
status: 'working',
sessionId: 'session-1',
agent: 'claude',
hasMore: false,
loadingEarlier: false,
olderHistoryGeneration: 0,
loadEarlier: vi.fn(),
readPhase: 'ready'
}
}
function list(
rows: readonly NativeChatMessage[],
props: Partial<React.ComponentProps<typeof NativeChatMessageList>> = {}
): React.JSX.Element {
return (
<NativeChatMessageList
session={sessionOf([prompt, ...rows])}
journalItems={journal(rows)}
isWorking
expandSignal={false}
{...props}
/>
)
}
describe('live reasoning, read through the one live line', () => {
let restoreViewport = (): void => {}
beforeAll(() => {
restoreViewport = installNativeChatMessageListTestViewport()
})
afterAll(() => restoreViewport())
afterEach(cleanup)
it('opens to the live text, which follows the block as it grows', () => {
const { rerender } = render(list([reasoning('r-1', 'Weighing two approaches', 'running')]))
fireEvent.click(screen.getByRole('button', { name: 'Thinking' }))
expect(screen.getByRole('button', { name: 'Thinking' })).toHaveAttribute(
'aria-expanded',
'true'
)
expect(screen.getByText('Weighing two approaches')).toBeInTheDocument()
rerender(list([reasoning('r-1', 'Weighing two approaches, then the cheaper one', 'running')]))
expect(screen.getByText('Weighing two approaches, then the cheaper one')).toBeInTheDocument()
})
it('lands the finished row open when the reader opened it live, while the turn works on', () => {
const { rerender } = render(list([reasoning('r-1', 'Weighing two approaches', 'running')]))
fireEvent.click(screen.getByRole('button', { name: 'Thinking' }))
rerender(list([reasoning('r-1', 'Weighing two approaches', 'completed')]))
expect(screen.queryByRole('button', { name: /Thinking|Working/ })).toBeNull()
expect(screen.getByRole('button', { name: 'Reasoning: Thought for 12s' })).toHaveAttribute(
'aria-expanded',
'true'
)
expect(screen.getByText('Weighing two approaches')).toBeInTheDocument()
})
it('starts the next block collapsed', () => {
const { rerender } = render(list([reasoning('r-1', 'First thought', 'running')]))
fireEvent.click(screen.getByRole('button', { name: 'Thinking' }))
rerender(
list([
reasoning('r-1', 'First thought', 'completed'),
reasoning('r-2', 'Second', 'running')
])
)
expect(screen.getByRole('button', { name: 'Thinking' })).toHaveAttribute(
'aria-expanded',
'false'
)
expect(screen.queryByText('Second')).toBeNull()
})
// A live region only announces changes to itself; a replaced one says nothing.
it('keeps one live region while the line turns into the disclosure and back', () => {
const tool: NativeChatMessage = {
id: 'tool-1',
role: 'assistant',
blocks: [
{ type: 'tool-call', name: 'shell', input: { command: 'ls' }, state: 'completed' }
],
timestamp: STARTED,
source: 'transcript'
}
const later = { timestamp: STARTED + 50 }
const region = () => document.querySelector('[data-native-chat-turn-activity][aria-live]')
const { rerender } = render(list([tool]))
const before = region()
expect(before).toHaveTextContent('Working…')
rerender(list([tool, reasoning('r-1', 'Weighing two approaches', 'running', later)]))
expect(region()).toBe(before)
expect(before).toHaveTextContent('Thinking')
rerender(
list([
tool,
reasoning('r-1', 'Weighing two approaches', 'completed', later),
{ ...tool, id: 'tool-2', timestamp: STARTED + 60 }
])
)
expect(region()).toBe(before)
expect(before).toHaveTextContent('Working…')
})
})
}
{
function frame(
id: number,
status: string,
overrides: { kind?: string; truncated?: boolean } = {}
) {
const kind = overrides.kind ?? 'notification:turn/plan/updated'
const head = JSON.stringify({
threadId: 'thread',
turnId: 'turn',
explanation: 'Keep verification visible',
plan: [{ step: 'Verify', status }]
})
const body: AgentJournalStatusItem = {
kind: 'status',
text: `codex · ${kind}`,
providerFrame: {
provider: 'codex',
kind,
payload: {
head,
byteLength: new TextEncoder().encode(head).byteLength,
digest: 'fixture-digest',
truncated: overrides.truncated ?? false
}
}
}
const message = projectStructuredItemToNativeChat({
itemId: `frame-${id}`,
revision: 1,
sequence: id,
observedAt: id,
body
})
if (!message) {
throw new Error('Expected a projected message')
}
return message
}
function transcript(messages: NativeChatMessage[], sessionId = 'live-codex') {
return (
<NativeChatMessageList
session={{
messages,
status: 'ready',
sessionId,
agent: 'codex',
hasMore: false,
loadingEarlier: false,
olderHistoryGeneration: 0,
loadEarlier: vi.fn(),
readPhase: 'ready'
}}
isWorking={false}
expandSignal
/>
)
}
describe('live Codex checklist frames', () => {
let restoreViewport = (): void => {}
beforeAll(() => {
restoreViewport = installNativeChatMessageListTestViewport()
})
afterAll(() => restoreViewport())
afterEach(cleanup)
it('updates one pinned checklist from journal notifications without rewinding on pagination', () => {
const first = frame(1, 'pending')
const active = frame(2, 'inProgress')
const last = frame(3, 'completed')
const { rerender, container } = render(transcript([first]))
const toggle = screen.getByRole('button', { name: 'Tasks 0 of 1 task completed' })
const viewport = container.querySelector('.overflow-y-auto')!
expect(viewport.contains(toggle)).toBe(false)
fireEvent.click(toggle)
rerender(transcript([first, active]))
expect(within(toggle.parentElement!).getByText('Verify').closest('li')).toHaveClass(
'text-chat-foreground-strong'
)
expect(within(viewport as HTMLElement).getByText('Started Verify')).toBeInTheDocument()
rerender(transcript([last]))
expect(
within(
screen.getByRole('button', { name: 'Tasks 1 of 1 task completed' }).parentElement!
).getByText('Verify')
).toHaveClass('line-through')
expect(screen.getAllByText('Keep verification visible')).toHaveLength(2)
rerender(transcript([first, active, last]))
expect(screen.getAllByText('Verify')).toHaveLength(2)
expect(screen.getByRole('button', { name: 'Tasks 1 of 1 task completed' })).toBe(toggle)
expect(screen.getByText('Started Verify')).toBeInTheDocument()
expect(screen.queryByText('notification:turn/plan/updated')).toBeNull()
expect(projectNativeChatTaskListFrames([last])[0]).toBe(
projectNativeChatTaskListFrames([last])[0]
)
})
})
describe('NativeChatMessageList task list history', () => {
let restoreViewport = (): void => {}
beforeAll(() => {
restoreViewport = installNativeChatMessageListTestViewport()
})
afterAll(() => restoreViewport())
afterEach(cleanup)
it('keeps the latest Claude state after pagination and resets disclosure between sessions', () => {
const first = {
id: 'first-list',
role: 'assistant' as const,
timestamp: 1,
source: 'transcript' as const,
blocks: [
{
type: 'tool-call' as const,
name: 'TodoWrite',
input: {
todos: [
{ content: 'Read', status: 'pending' },
{ content: 'Test', status: 'pending' }
]
}
}
]
}
const last = {
...first,
id: 'last-list',
timestamp: 3,
blocks: [
{ type: 'text' as const, text: 'Ready for verification' },
{
type: 'tool-call' as const,
name: 'TodoWrite',
input: {
todos: [
{ content: 'Read', status: 'completed' },
{ content: 'Test', status: 'pending' }
]
}
}
]
}
const { rerender } = render(transcript([last]))
fireEvent.click(screen.getByRole('button', { name: 'Tasks 1 of 2 tasks completed' }))
rerender(transcript([first, last]))
expect(screen.getAllByText('Read')).toHaveLength(2)
expect(screen.getByText('Completed Read')).toBeInTheDocument()
expect(
within(
screen.getByRole('button', { name: 'Tasks 1 of 2 tasks completed' }).parentElement!
).getByText('Read')
).toHaveClass('line-through')
expect(screen.getByText('Ready for verification')).toBeInTheDocument()
rerender(transcript([first], 'two'))
expect(screen.getByRole('button', { name: 'Tasks 0 of 2 tasks completed' })).toHaveAttribute(
'aria-expanded',
'false'
)
expect(screen.getAllByText('Read')).toHaveLength(1)
rerender(transcript([], 'three'))
expect(screen.queryByText('Tasks')).toBeNull()
})
})
}
{
function item(
itemId: string,
body: AgentJournalItemBody,
sequence: number
): AgentJournalRenderItem {
return { itemId, body, sequence, observedAt: sequence * 1000, revision: 1 }
}
const user = item(
'user',
{ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Make the change' }] },
1
)
const prose = item(
'prose',
{ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Updating the files.' }] },
2
)
function diff(patch = '@@ -1 +1 @@\n-before\n+after'): AgentJournalRenderItem {
return item(
'diff',
{
kind: 'diff',
path: 'src/a.ts',
patch: { head: patch, truncated: false, digest: 'fixture', byteLength: patch.length }
},
3
)
}
function session(items: AgentJournalRenderItem[]): NativeChatLiveSession {
return {
messages: projectStructuredQuestionMessages(items),
status: 'ready',
sessionId: 'session',
agent: 'codex',
hasMore: false,
loadingEarlier: false,
olderHistoryGeneration: 0,
loadEarlier: vi.fn(),
readPhase: 'ready'
}
}
function view(items: AgentJournalRenderItem[], structured = true) {
return (
<NativeChatMessageList
session={session(items)}
journalItems={structured ? items : undefined}
isWorking={false}
expandSignal={false}
/>
)
}
describe('turn history presentation', () => {
let restoreViewport = (): void => {}
beforeAll(() => {
restoreViewport = installNativeChatMessageListTestViewport()
})
afterAll(() => restoreViewport())
afterEach(() => {
cleanup()
vi.restoreAllMocks()
})
it('renders canonical pending questions while idle and keeps resolved answers at their row', () => {
const question = item(
'question',
{
kind: 'question',
question: 'Which branch?',
options: [{ id: 'main', label: 'main' }],
resolution: {
state: 'pending',
selectedOptionId: null,
resolvedBy: null,
resolvedAt: null
}
},
3
)
const { rerender } = render(view([user, prose, question]))
expect(screen.getByText('Awaiting user input:')).toBeInTheDocument()
expect(screen.getByText('Which branch?')).toBeInTheDocument()
expect(screen.queryByText(/request_user_input/)).toBeNull()
const settled = item(
'question',
{
...question.body,
kind: 'question',
question: 'Which branch?',
options: [{ id: 'main', label: 'main' }],
resolution: {
state: 'resolved',
selectedOptionId: 'main',
resolvedBy: 'desktop',
resolvedAt: 4000
}
},
3
)
rerender(view([user, prose, settled]))
expect(screen.queryByText('Awaiting user input:')).toBeNull()
expect(screen.getByText('Asked:')).toBeInTheDocument()
expect(screen.getByText('main')).toBeInTheDocument()
})
it('groups pending Codex questions then narrows the awaiting count after one answer', () => {
const first = item(
'q1',
{
kind: 'question',
question: 'Which branch?',
options: [{ id: 'main', label: 'main' }],
resolution: {
state: 'pending',
selectedOptionId: null,
resolvedBy: null,
resolvedAt: null
}
},
3
)
const second = item(
'q2',
{
kind: 'question',
question: 'Proceed?',
options: [],
resolution: {
state: 'pending',
selectedOptionId: null,
resolvedBy: null,
resolvedAt: null
}
},
4
)
const { rerender } = render(view([user, first, second]))
expect(screen.getByText('2 questions')).toBeInTheDocument()
expect(screen.getAllByText('Awaiting user input:')).toHaveLength(1)
const answered = item(
'q1',
{
kind: 'question',
question: 'Which branch?',
options: [{ id: 'main', label: 'main' }],
resolution: {
state: 'resolved',
selectedOptionId: 'main',
resolvedBy: 'phone',
resolvedAt: 5000
}
},
3
)
rerender(view([user, answered, second]))
expect(screen.queryByText('2 questions')).toBeNull()
expect(screen.getByText('Proceed?')).toBeInTheDocument()
expect(screen.getByText('main')).toBeInTheDocument()
expect(screen.getAllByText('Awaiting user input:')).toHaveLength(1)
})
it('opens a recorded patch while completed work stays folded', () => {
render(view([user, prose, diff()]))
expect(screen.queryByText('after')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: /src\/a.ts/ }))
expect(screen.getByText('after')).toBeInTheDocument()
expect(screen.getByText('before')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Edited 1 file/, expanded: false })).toBeVisible()
})
it('updates journal revisions and replaces flat approval text with a passive receipt', () => {
const approval = item(
'approval',
{
kind: 'approval',
title: 'Run tests?',
detail: 'pnpm test',
options: [{ id: 'allow', label: 'Allow once' }],
resolution: {
state: 'pending',
selectedOptionId: null,
resolvedBy: null,
resolvedAt: null
}
},
4
)
const initial = [user, prose, diff(), approval]
const { rerender } = render(view(initial))
expect(screen.queryByText('Run tests?')).toBeNull()
if (approval.body.kind !== 'approval') {
throw new Error('fixture')
}
const resolved = {
...approval,
revision: 2,
body: {
...approval.body,
resolution: {
state: 'resolved' as const,
selectedOptionId: 'allow',
resolvedBy: 'desktop',
resolvedAt: 5000
}
}
}
rerender(view([user, prose, diff('@@ -0,0 +1,2 @@\n+first\n+second'), resolved]))
expect(screen.getByRole('button', { name: /src\/a.ts \+2/ })).toBeInTheDocument()
expect(screen.getByText('Run tests?')).toBeInTheDocument()
expect(screen.getByText('Allow once')).toBeInTheDocument()
expect(screen.getByText('Answered on another device')).toBeInTheDocument()
expect(screen.getByText('Resolved').closest('[data-native-chat-receipt]')).not.toBeNull()
expect(screen.queryByText('resolved')).toBeNull()
})
})
}
@@ -1,140 +0,0 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import type { AgentStatusPayload } from '../../../../../shared/agent-status/contracts/agent-status-types'
import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types'
import type { NativeChatLiveSession } from '../session/terminal/read/native-chat-live-session-contract'
// The composer is a marker that counts its mounts, so the test sees whether the view remounted it.
const retained = vi.hoisted((): { session: NativeChatLiveSession | null } => ({ session: null }))
const composer = vi.hoisted(() => ({ mounts: 0 }))
const ptyInput = vi.hoisted(() => ({ verified: vi.fn<() => Promise<boolean>>() }))
vi.mock('../session/terminal/read/use-native-chat-retained-session', () => ({
useNativeChatRetainedSession: () => retained.session
}))
vi.mock('../composer/NativeChatComposer', async () => {
const { useEffect } = await import('react')
return {
NativeChatComposer: () => {
useEffect(() => {
composer.mounts += 1
}, [])
return <div data-testid="native-chat-composer" />
}
}
})
vi.mock('@/runtime/hosted-terminals/input/runtime-terminal-verified-input', () => ({
sendRuntimePtyInputVerified: ptyInput.verified
}))
const { NativeChatResolvedView } = await import('../NativeChatResolvedView')
const { TooltipProvider } = await import('@/components/ui/tooltip')
const { nativeChatPromptDismissals } = await import('./native-chat-prompt-dismissals')
const { useAppStore } = await import('../../../store/index')
const { installNativeChatMessageListTestViewport } =
await import('../viewport/virtualization/native-chat-message-list-test-viewport')
const paneKey = 'tab-card:leaf-card'
let restoreViewport = (): void => {}
const userTurn: NativeChatMessage = {
id: 'user-1',
role: 'user',
blocks: [{ type: 'text', text: 'Clean the build' }],
timestamp: 1,
source: 'transcript'
}
function transcript(): NativeChatLiveSession {
return {
messages: [userTurn],
status: 'ready',
sessionId: 'session-card',
agent: 'claude',
hookAwaitingInput: true,
hasMore: false,
loadingEarlier: false,
olderHistoryGeneration: 0,
loadEarlier: vi.fn(),
readPhase: 'ready'
}
}
function setStatus(
payload: Omit<AgentStatusPayload, 'prompt' | 'agentType'>,
stateStartedAt?: number
): void {
useAppStore
.getState()
.setAgentStatus(
paneKey,
{ prompt: 'Clean the build', agentType: 'claude', ...payload },
undefined,
stateStartedAt === undefined ? undefined : { stateStartedAt }
)
}
function renderPane(targetPtyId = 'pty-card'): ReturnType<typeof render> {
return render(paneElement(targetPtyId))
}
function paneElement(targetPtyId = 'pty-card'): React.JSX.Element {
return (
<TooltipProvider>
<NativeChatResolvedView
paneKey={paneKey}
agent="claude"
sessionId="session-card"
transcriptPath={null}
isVisible
isFocusedGroup
targetPtyId={targetPtyId}
terminalTabId="tab-card"
ownsTabWideLaunchDraft={false}
/>
</TooltipProvider>
)
}
beforeEach(() => {
restoreViewport = installNativeChatMessageListTestViewport()
composer.mounts = 0
nativeChatPromptDismissals.clearForTests()
ptyInput.verified.mockReset()
useAppStore.setState({ agentStatusByPaneKey: {}, nativeChatLaunchPromptByTabId: {} })
retained.session = transcript()
})
afterEach(() => {
cleanup()
restoreViewport()
useAppStore.setState({ agentStatusByPaneKey: {}, nativeChatLaunchPromptByTabId: {} })
})
// Prompt cards own terminal input because composer sends would otherwise answer the agent’s active selector.
describe('NativeChatResolvedView prompt cards own the input region', () => {
it('keeps an answered approval hidden across a chat view remount and a PTY rebind', async () => {
ptyInput.verified.mockResolvedValue(true)
setStatus({
state: 'waiting',
interactivePrompt: JSON.stringify({ approval: { tool: 'Bash', summary: 'npm test' } })
})
const first = renderPane()
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Allow' }))
})
// The approved tool is still running, so the host status lingers: a chat/terminal toggle.
first.unmount()
const second = renderPane()
expect(document.querySelector('[data-native-chat-approval-card="true"]')).toBeNull()
expect(screen.getByTestId('native-chat-composer').closest('[hidden]')).toBeNull()
second.unmount()
renderPane('pty-card-reconnected')
expect(document.querySelector('[data-native-chat-approval-card="true"]')).toBeNull()
expect(ptyInput.verified).toHaveBeenCalledOnce()
})
})
@@ -1,249 +0,0 @@
import type * as RuntimeTerminalInputSendModule from '@/runtime/hosted-terminals/input/runtime-terminal-input-send'
import { AGENT_TUI_CLEAR_INPUT_MAX } from '../../../../../../shared/agent-launch/startup/agent-tui-input-clear'
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import type { AgentStatusPayload } from '../../../../../../shared/agent-status/contracts/agent-status-types'
import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types'
import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract'
import type {
NativeChatComposerHandle,
NativeChatComposerProps
} from '../../composer/native-chat-composer-types'
import { mergeNativeChatLiveSession } from '../../../../../../shared/native-chat/native-chat-live-status'
import { clearPendingSendCacheForTests } from '../../session/terminal/delivery/native-chat-pending'
const MESSAGE = 'please also run lint'
const retained = vi.hoisted((): { session: NativeChatLiveSession | null } => ({ session: null }))
const composer = vi.hoisted(() => ({ mounts: 0, typed: vi.fn<(text: string) => boolean>() }))
const pty = vi.hoisted(() => ({
verified: vi.fn<(id: string, data: string) => Promise<boolean>>(),
raw: vi.fn<(id: string, data: string) => boolean>()
}))
vi.mock('../../session/terminal/read/use-native-chat-retained-session', () => ({
useNativeChatRetainedSession: () => retained.session
}))
vi.mock('@/runtime/hosted-terminals/input/runtime-terminal-input-send', async (importOriginal) => ({
...(await importOriginal<typeof RuntimeTerminalInputSendModule>()),
sendRuntimePtyInput: pty.raw
}))
vi.mock('@/runtime/hosted-terminals/input/runtime-terminal-verified-input', () => ({
sendRuntimePtyInputVerified: pty.verified
}))
// Stub only the field; retain the production send lifecycle, queue and observed writes.
vi.mock('../../composer/NativeChatComposer', async () => {
const { forwardRef, useEffect, useImperativeHandle, useRef } = await import('react')
const { useNativeChatSendLifecycle } =
await import('../../session/terminal/send/use-native-chat-send-lifecycle')
const { sendNativeChatMessage } =
await import('../../session/terminal/send/native-chat-runtime-send')
return {
NativeChatComposer: forwardRef<NativeChatComposerHandle, NativeChatComposerProps>(
function StandInComposer(props, ref) {
useEffect(() => {
composer.mounts += 1
}, [])
const fieldRef = useRef<HTMLTextAreaElement>(null)
useImperativeHandle(ref, () => ({
focus: () => {
fieldRef.current?.focus()
return true
},
insertAgentReferences: () => false,
insertTypedText: composer.typed,
acceptsText: () => true,
appendText: () => {},
handlePasteEvent: () => {},
pasteFromClipboard: () => {},
contains: () => false
}))
const lifecycle = useNativeChatSendLifecycle(
props.terminalTabId,
props.targetPtyId,
props.onOptimisticSendCanceled,
{
inputOwnedByCard: props.inputOwnedByCard === true,
onPendingSendRetired: props.optimisticSendOutcome?.reject
}
)
const send = (): void => {
let pendingId: string | undefined
const handle = sendNativeChatMessage(props.targetPtyId ?? '', MESSAGE, {
onWriteRejected: () => {
if (pendingId) {
props.optimisticSendOutcome?.reject(pendingId)
}
}
})
pendingId = props.onOptimisticSend?.(MESSAGE)
lifecycle.trackPendingSend(handle, pendingId)
}
return (
<>
<textarea ref={fieldRef} data-testid="composer-field" />
<button type="button" data-testid="composer-send" onClick={send}>
send
</button>
</>
)
}
)
}
})
const { NativeChatResolvedView } = await import('../../NativeChatResolvedView')
const { TooltipProvider } = await import('@/components/ui/tooltip')
const { useAppStore } = await import('../../../../store/index')
const { installNativeChatMessageListTestViewport } =
await import('../../viewport/virtualization/native-chat-message-list-test-viewport')
const { resetNativeChatPtySendQueuesForTests } =
await import('../../session/terminal/send/native-chat-pty-send-queue')
const { nativeChatPromptDismissals } = await import('../../prompts/native-chat-prompt-dismissals')
const paneKey = 'tab-hidden:leaf-hidden'
const approval = JSON.stringify({ approval: { tool: 'Bash', summary: 'npm test' } })
let restoreViewport = (): void => {}
const userTurn: NativeChatMessage = {
id: 'user-1',
role: 'user',
blocks: [{ type: 'text', text: 'Clean the build' }],
timestamp: 1,
source: 'transcript'
}
function setStatus(payload: Omit<AgentStatusPayload, 'prompt' | 'agentType'>): void {
useAppStore
.getState()
.setAgentStatus(paneKey, { prompt: 'Clean the build', agentType: 'claude', ...payload })
}
function renderPane(): void {
render(
<TooltipProvider>
<NativeChatResolvedView
paneKey={paneKey}
agent="claude"
sessionId="session-hidden"
transcriptPath={null}
isVisible
isFocusedGroup
targetPtyId="pty-hidden"
terminalTabId="tab-hidden"
ownsTabWideLaunchDraft={false}
/>
</TooltipProvider>
)
}
beforeEach(() => {
restoreViewport = installNativeChatMessageListTestViewport()
resetNativeChatPtySendQueuesForTests()
nativeChatPromptDismissals.clearForTests()
composer.mounts = 0
composer.typed.mockReset().mockReturnValue(true)
pty.verified.mockReset().mockResolvedValue(true)
pty.raw.mockReset().mockReturnValue(true)
useAppStore.setState({ agentStatusByPaneKey: {}, nativeChatLaunchPromptByTabId: {} })
retained.session = {
messages: [userTurn],
status: 'working',
sessionId: 'session-hidden',
agent: 'claude',
hookAwaitingInput: false,
hasMore: false,
loadingEarlier: false,
olderHistoryGeneration: 0,
loadEarlier: vi.fn(),
readPhase: 'ready'
}
})
afterEach(() => {
try {
cleanup()
resetNativeChatPtySendQueuesForTests()
restoreViewport()
useAppStore.setState({ agentStatusByPaneKey: {}, nativeChatLaunchPromptByTabId: {} })
} finally {
vi.useRealTimers()
}
})
describe('queued follow-ups through transcript recovery', () => {
it.each(['error', 'ready'] as const)(
'keeps a send after the current reply when a read error is presented as %s',
async (status) => {
vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] })
clearPendingSendCacheForTests()
setStatus({ state: 'working', lastAssistantMessage: 'Current reply' })
const input = {
messages: [userTurn],
sessionId: 'session-hidden',
agent: 'claude' as const,
hookState: 'working' as const,
stateStartedAt: Date.now()
}
retained.session = {
...retained.session!,
...mergeNativeChatLiveSession({ ...input, error: 'Read failed' }),
status,
readPhase: 'error'
}
renderPane()
await act(async () => {
fireEvent.click(screen.getByTestId('composer-send'))
})
act(() => {
retained.session = {
...retained.session!,
...mergeNativeChatLiveSession(input),
readPhase: 'ready'
}
setStatus({ state: 'working', lastAssistantMessage: 'Current reply continues' })
})
const text = document.body.textContent!
expect(text).toContain('Current')
expect(text.indexOf(MESSAGE)).toBeGreaterThan(text.indexOf('Current'))
}
)
})
describe('a prompt card hides the composer without unmounting it', () => {
it('keeps an in-flight message visible and never submits it into the approval', async () => {
vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] })
setStatus({ state: 'working' })
renderPane()
await act(async () => {
fireEvent.click(screen.getByTestId('composer-send'))
})
expect(pty.verified.mock.calls.map((call) => call[1]).join('')).toContain(MESSAGE)
// The approval arrives inside the body-to-Enter gap.
await act(async () => {
await vi.advanceTimersByTimeAsync(100)
setStatus({ state: 'waiting', interactivePrompt: approval })
})
await act(async () => {
await vi.advanceTimersByTimeAsync(900)
})
expect(document.querySelector('[data-native-chat-approval-card="true"]')).not.toBeNull()
expect(pty.verified.mock.calls.map((call) => call[1])).not.toContain('\r')
// Only the pre-body clear: retiring the send types nothing under the card.
expect(pty.raw.mock.calls.map((call) => call[1])).toEqual([AGENT_TUI_CLEAR_INPUT_MAX])
expect(screen.getByTestId('composer-send').closest('[hidden]')).not.toBeNull()
expect(screen.getAllByText(MESSAGE).length).toBeGreaterThan(0)
expect(screen.getByText('Message not sent')).toBeInTheDocument()
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Allow' }))
})
expect(screen.getByTestId('composer-send').closest('[hidden]')).toBeNull()
expect(composer.mounts).toBe(1)
})
})
@@ -1,26 +0,0 @@
const TEST_VIEWPORT_HEIGHT_PX = 1_000_000
const TEST_ROW_HEIGHT_PX = 48
/** Give non-windowing component tests a measurable viewport that contains every fixture row. */
export function installNativeChatMessageListTestViewport(): () => void {
const original = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight')
Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
configurable: true,
get(this: HTMLElement): number {
if (this.hasAttribute('data-native-chat-scroll')) {
return TEST_VIEWPORT_HEIGHT_PX
}
if (this.dataset.index !== undefined) {
return TEST_ROW_HEIGHT_PX
}
return original?.get?.call(this) ?? 0
}
})
return () => {
if (original) {
Object.defineProperty(HTMLElement.prototype, 'offsetHeight', original)
} else {
Reflect.deleteProperty(HTMLElement.prototype, 'offsetHeight')
}
}
}